+// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+package org.xwt;
+
+import java.net.*;
+import java.io.*;
+import java.util.*;
+import org.xwt.util.*;
+import org.mozilla.javascript.*;
+
+/**
+ * A crude HTTP[S] connection implementation with support for proxies, since not all Java libraries
+ * (particularly GCJ's) support proxies.
+ *
+ * FEATURE: implement pipelining
+ */
+public class HTTP {
+
+ /** the URL to connect to */
+ URL url = null;
+
+ /** the host to connect to */
+ String host = null;
+
+ /** the port to connect on */
+ int port = -1;
+
+ /** true if SSL (HTTPS) should be used */
+ boolean ssl = false;
+
+ /** the path (URI) to retrieve on the server */
+ String path = null;
+
+ /** the socket; created lazily */
+ Socket sock = null;
+
+ /** the socket's inputstream */
+ InputStream in = null;
+
+ /** the socket's outputstream */
+ OutputStream out = null;
+
+ /** the content-type of the data being received */
+ String contentType = null;
+
+ /** the content-length of the data being recieved */
+ int contentLength = 0;
+
+ /** true iff a proxy should be used */
+ boolean proxy = false;
+
+ /** additional headers to be transmitted */
+ String headers = "";
+
+ public HTTP(String url) throws MalformedURLException, IOException {
+ if (url.startsWith("https:")) {
+ url = "http" + url.substring(5);
+ ssl = true;
+ }
+ if (!url.startsWith("http:")) throw new IOException("HTTP only supports http/https urls");
+ this.url = new URL(url);
+ host = this.url.getHost();
+ port = this.url.getPort();
+ path = this.url.getFile();
+ if (port == -1) port = ssl ? 443 : 80;
+ try {
+ InetAddress addr = InetAddress.getByName(host);
+ byte[] quadbyte = addr.getAddress();
+ if (quadbyte[0] == 10 || (quadbyte[0] == 192 && quadbyte[1] == 168) ||
+ (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16) && !addr.equals(Main.originAddr))
+ throw new IOException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
+ } catch (UnknownHostException uhe) {
+ if (Platform.detectProxy() == null) throw new IOException("could not resolve hostname \"" + host + "\" and no proxy configured");
+ else if (Log.on) Log.log("could not resolve host " + host + "; assuming that the proxy can resolve it for us");
+ }
+ }
+
+ public String getContentType() throws IOException {
+ getInputStream();
+ return contentType;
+ }
+
+ public int getContentLength() throws IOException {
+ getInputStream();
+ return contentLength;
+ }
+
+ public void addHeader(String header, String value) throws IOException {
+ if (in != null) throw new IOException("attempt to add header after connection has been made");
+ headers += header + ": " + value + "\r\n";
+ }
+
+ private void getSock() throws IOException {
+ ProxyInfo pi = Platform.detectProxy();
+
+ // unproxied
+ if (pi == null || (pi.proxyAutoConfigFunction == null && pi.socksProxyHost == null && pi.httpProxyHost == null)) {
+ if (Log.on) Log.log(this, "creating unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
+ sock = Platform.getSocket(host, port, ssl);
+ return;
+ }
+
+ // no PAC; simple config
+ if (pi.proxyAutoConfigFunction == null) {
+ String proxyHost = ssl && pi.httpsProxyHost != null ? pi.httpsProxyHost : pi.httpProxyHost;
+ int proxyPort = ssl && pi.httpsProxyHost != null ? pi.httpsProxyPort : pi.httpProxyPort;
+ if (Log.on) Log.log(this, "no proxyAutoConfigFunction; using proxy " + proxyHost + ":" + proxyPort);
+ sock = Platform.getSocket(proxyHost, proxyPort, ssl);
+ proxy = true;
+ return;
+ }
+
+ // PAC
+ String pac = null;
+ try {
+ Context cx = Context.enter();
+ Object obj = pi.proxyAutoConfigFunction.call(cx, ProxyInfo.base, null, new Object[] { url.toString(), host });
+ if (Log.on) Log.log(this, "PAC script returned \"" + obj + "\"");
+ pac = obj.toString();
+ } catch (Throwable e) {
+ if (Log.on) Log.log(this, "PAC script threw an exception:");
+ if (Log.on) Log.log(this, e);
+ throw new IOException("PAC script threw exception " + e);
+ }
+
+ StringTokenizer st = new StringTokenizer(pac, ";", false);
+ while (st.hasMoreTokens()) {
+ String token = st.nextToken().trim();
+ if (Log.on) Log.log(this, " trying \"" + token + "\"...");
+ try {
+ if (token.startsWith("DIRECT")) {
+ proxy = false;
+ sock = Platform.getSocket(host, port, ssl);
+ return;
+ } else if (token.startsWith("PROXY")) {
+ proxy = true;
+ sock = Platform.getSocket(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
+ Integer.parseInt(token.substring(token.indexOf(':') + 1)), ssl);
+ return;
+ } else if (token.startsWith("SOCKS")) {
+ // FIXME
+ }
+ } catch (Throwable e) {
+ if (Log.on) Log.log(this, "attempt at \"" + proxy + "\" failed due to " + e + "; trying next one");
+ }
+ }
+ throw new IOException("all proxy options exhausted");
+ }
+
+ public OutputStream getOutputStream(int contentLength, String contentType) throws IOException {
+ if (out != null) return out;
+ if (in != null) throw new IOException("attempt to getOutputStream() after getInputStream()");
+ getSock();
+ sock.setTcpNoDelay(true);
+ out = sock.getOutputStream();
+ PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
+ pw.print("POST " + (proxy ? url.toString() : path) + " HTTP/1.0\r\n");
+ pw.print("Host: " + host + "\r\n");
+ pw.print("User-Agent: XWT\r\n");
+ pw.print("Content-length: " + contentLength + "\r\n");
+ pw.print(headers);
+ if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
+ pw.print("\r\n");
+ pw.flush();
+ return out;
+ }
+
+ public InputStream getInputStream() throws IOException {
+ if (in != null) return in;
+ if (out != null) {
+ out.flush();
+ } else {
+ getSock();
+ sock.setTcpNoDelay(true);
+ PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
+ pw.print("GET " + (proxy ? url.toString() : path) + " HTTP/1.0\r\n");
+ pw.print("Host: " + host + "\r\n");
+ pw.print("User-Agent: XWT\r\n");
+ pw.print(headers);
+ pw.print("\r\n");
+ pw.flush();
+ }
+
+ in = new BufferedInputStream(sock.getInputStream());
+
+ // we can't use a BufferedReader directly on the input stream,
+ // since it will buffer beyond the end of the headers
+ byte[] buf = new byte[4096];
+ int buflen = 0;
+ while(true) {
+ int read = in.read();
+ if (read == -1) throw new IOException("stream closed while reading headers");
+ buf[buflen++] = (byte)read;
+ if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
+ if (buflen == buf.length) {
+ byte[] newbuf = new byte[buf.length * 2];
+ System.arraycopy(buf, 0, newbuf, 0, buflen);
+ buf = newbuf;
+ }
+ }
+
+ BufferedReader headerReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
+ String s = headerReader.readLine();
+ if (!s.startsWith("HTTP/")) throw new IOException("Expected reply to start with \"HTTP/\"");
+ String reply = s.substring(s.indexOf(' ') + 1);
+ if (!reply.startsWith("2")) throw new IOException("HTTP Error: " + reply);
+ while((s = headerReader.readLine()) != null) {
+ if (s.length() > 15 && s.substring(0, 15).equalsIgnoreCase("content-length: "))
+ contentLength = Integer.parseInt(s.substring(15));
+ }
+
+ return in;
+ }
+
+ public static class ProxyInfo {
+
+ public ProxyInfo() { }
+
+ /** the HTTP Proxy host to use */
+ public String httpProxyHost = null;
+
+ /** the HTTP Proxy port to use */
+ public int httpProxyPort = -1;
+
+ /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
+ public String httpsProxyHost = null;
+
+ /** if a seperate proxy should be used for HTTPS, this is the port */
+ public int httpsProxyPort = -1;
+
+ /** the SOCKS Proxy Host to use */
+ public String socksProxyHost = null;
+
+ /** the SOCKS Proxy Port to use */
+ public int socksProxyPort = -1;
+
+ /** hosts to be excluded from proxy use; wildcards permitted */
+ public String[] excluded = null;
+
+ /** the PAC script */
+ public Function proxyAutoConfigFunction = null;
+
+ public static ProxyInfo detectProxyViaManual() {
+ try {
+ try { InetAddress.getByName("xwt-proxy-httpHost");
+ } catch (UnkownHostException unhe) { InetAddress.getByName("xwt-proxy-socksHost"); }
+
+ if (Log.on) Log.log(Platform.class, "using xwt-proxy-* configuration");
+ ProxyInfo ret = new ProxyInfo();
+ try {
+ ret.httpProxyHost = InetAddress.getByName("xwt-proxy-httpHost").getHostAddress();
+ byte[] quadbyte = InetAddress.getByName("xwt-proxy-httpPort").getAddress();
+ ret.httpProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
+ } catch (UnknownHostException e) { }
+ try {
+ ret.httpsProxyHost = InetAddress.getByName("xwt-proxy-httpsHost").getHostAddress();
+ byte[] quadbyte = InetAddress.getByName("xwt-proxy-httpsPort").getAddress();
+ ret.httpsProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
+ } catch (UnknownHostException e) { }
+ try {
+ ret.socksProxyHost = InetAddress.getByName("xwt-proxy-socksHost").getHostAddress();
+ byte[] quadbyte = InetAddress.getByName("xwt-proxy-socksPort").getAddress();
+ ret.socksProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
+ } catch (UnknownHostException e) { }
+ return ret;
+ } catch (UnknownHostException e) {
+ if (Log.on) Log.log(Platform.class, "xwt-proxy-* detection failed due to:");
+ return null;
+ }
+ }
+
+ // FIXME: search up from default domain
+ public static ProxyInfo detectProxyViaWPAD() {
+ try {
+ InetAddress wpad = InetAddress.getByName("wpad");
+ if (Log.on) Log.log(Platform.class, "using Web Proxy Auto Detection to detect proxy settings");
+ ProxyInfo ret = new ProxyInfo();
+ ret.proxyAutoConfigFunction = getProxyAutoConfigFunction("http://wpad/wpad.dat");
+ if (ret.proxyAutoConfigFunction != null) return ret;
+ } catch (UnknownHostException e) {
+ if (Log.on) Log.log(HTTP.class, "couldn't find WPAD server: " + e);
+ }
+ return null;
+ }
+
+ public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
+
+ public static Function getProxyAutoConfigFunction(String url) {
+ try {
+ Context cx = Context.enter();
+ cx.setOptimizationLevel(-1);
+ BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url).getInputStream()));
+ String s = null;
+ String script = "";
+ while((s = br.readLine()) != null) script += s + "\n";
+ if (Log.on) Log.log(HTTP.ProxyInfo.class, "successfully retrieved WPAD PAC:");
+ if (Log.on) Log.log(HTTP.ProxyInfo.class, script);
+ Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
+ scr.exec(cx, proxyAutoConfigRootScope);
+ return (Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
+ } catch (Exception e) {
+ if (Log.on) {
+ Log.log(Platform.class, "WPAD detection failed due to:");
+ if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
+ ((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
+ else Log.log(Platform.class, e);
+ }
+ return null;
+ }
+ }
+
+ public static class ProxyAutoConfigRootScope extends ScriptableObject {
+
+ public String getClassName() { return "ProxyAutoConfigRootScope"; }
+ ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
+
+ public Object get(String name, Scriptable start) {
+ if (name.equals("isPlainHostName")) return isPlainHostName;
+ else if (name.equals("dnsDomainIs")) return dnsDomainIs;
+ else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
+ else if (name.equals("isResolvable")) return isResolvable;
+ else if (name.equals("dnsResolve")) return dnsResolve;
+ else if (name.equals("myIpAddress")) return myIpAddress;
+ else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
+ else if (name.equals("shExpMatch")) return shExpMatch;
+ else if (name.equals("weekdayRange")) return weekdayRange;
+ else if (name.equals("dateRange")) return dateRange;
+ else if (name.equals("timeRange")) return timeRange;
+ else if (name.equals("ProxyConfig")) return ProxyConfig;
+ else return super.get(name, start);
+ }
+
+ private static final JSObject proxyConfigBindings = new JSObject();
+ private static final JSObject ProxyConfig = new JSObject() {
+ public Object get(String name, Scriptable start) {
+ if (name.equals("bindings")) return proxyConfigBindings;
+ return null;
+ }
+ };
+
+ private static abstract class JSFunction extends JSObject implements Function {
+ JSFunction() { setSeal(true); }
+ public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
+ }
+
+ private static final JSFunction isPlainHostName = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
+ }
+ };
+
+ private static final JSFunction dnsDomainIs = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
+ }
+ };
+
+ private static final JSFunction localHostOrDomainIs = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ return (args[0].toString().equals(args[1].toString()) ||
+ (args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
+ Boolean.TRUE : Boolean.FALSE;
+ }
+ };
+
+ private static final JSFunction isResolvable = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ try {
+ return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
+ } catch (UnknownHostException e) {
+ return Boolean.FALSE;
+ }
+ }
+ };
+
+ private static final JSFunction isInNet = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ // FIXME
+ return null;
+ }
+ };
+
+ private static final JSFunction dnsResolve = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ try {
+ return InetAddress.getByName(args[0].toString()).getHostAddress();
+ } catch (UnknownHostException e) {
+ return null;
+ }
+ }
+ };
+
+ private static final JSFunction myIpAddress = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ try {
+ return InetAddress.getLocalHost().getHostAddress();
+ } catch (UnknownHostException e) {
+ if (Log.on) Log.log(this, "strange... host does not know its own address");
+ return null;
+ }
+ }
+ };
+
+ private static final JSFunction dnsDomainLevels = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ String s = args[0].toString();
+ int i = 0;
+ while((i = s.indexOf('.', i)) != -1) i++;
+ return new Integer(i);
+ }
+ };
+
+ // FIXME: test this!
+ private static boolean match(String[] arr, String s, int index) {
+ if (index == arr.length) return true;
+ for(int i=0; i<s.length(); i++) {
+ String s2 = s.substring(i);
+ if (s2.startsWith(arr[index]) && match(arr, s.substring(arr[index].length()), index + 1)) return true;
+ }
+ return false;
+ }
+
+ private static final JSFunction shExpMatch = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
+ String[] arr = new String[st.countTokens()];
+ String s = args[0].toString();
+ for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
+ return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
+ }
+ };
+
+ private static final JSFunction weekdayRange = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ throw new JavaScriptException("XWT does not support weekdayRange() in PAC scripts");
+ /*
+ TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
+ Calendar c = new Calendar();
+ c.setTimeZone(tz);
+ c.setTime(new Date());
+ Date d = c.getTime();
+ if (args.length == 1) return
+ */
+ }
+ };
+
+ private static final JSFunction dateRange = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ throw new JavaScriptException("XWT does not support dateRange() in PAC scripts");
+ }
+ };
+
+ private static final JSFunction timeRange = new JSFunction() {
+ public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
+ throw new JavaScriptException("XWT does not support timeRange() in PAC scripts");
+ }
+ };
+
+ }
+
+ }
+
+}