1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
8 import org.mozilla.javascript.*;
11 * A crude HTTP[S] connection implementation with support for proxies, since not all Java libraries
12 * (particularly GCJ's) support proxies.
14 * FEATURE: implement pipelining
18 /** the URL to connect to */
21 /** the host to connect to */
24 /** the port to connect on */
27 /** true if SSL (HTTPS) should be used */
30 /** the path (URI) to retrieve on the server */
33 /** the socket; created lazily */
36 /** the socket's inputstream */
37 InputStream in = null;
39 /** the socket's outputstream */
40 OutputStream out = null;
42 /** the content-type of the data being received */
43 String contentType = null;
45 /** the content-length of the data being recieved */
46 int contentLength = 0;
48 /** true iff a proxy should be used */
49 boolean proxy = false;
51 /** additional headers to be transmitted */
54 public HTTP(String url) throws MalformedURLException, IOException {
55 if (url.startsWith("https:")) {
56 url = "http" + url.substring(5);
59 if (!url.startsWith("http:")) throw new IOException("HTTP only supports http/https urls");
60 this.url = new URL(url);
61 host = this.url.getHost();
62 port = this.url.getPort();
63 path = this.url.getFile();
64 if (port == -1) port = ssl ? 443 : 80;
66 InetAddress addr = InetAddress.getByName(host);
67 byte[] quadbyte = addr.getAddress();
68 if (quadbyte[0] == 10 || (quadbyte[0] == 192 && quadbyte[1] == 168) ||
69 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16) && !addr.equals(Main.originAddr))
70 throw new IOException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
71 } catch (UnknownHostException uhe) {
72 if (Platform.detectProxy() == null) throw new IOException("could not resolve hostname \"" + host + "\" and no proxy configured");
73 else if (Log.on) Log.log("could not resolve host " + host + "; assuming that the proxy can resolve it for us");
77 public String getContentType() throws IOException {
82 public int getContentLength() throws IOException {
87 public void addHeader(String header, String value) throws IOException {
88 if (in != null) throw new IOException("attempt to add header after connection has been made");
89 headers += header + ": " + value + "\r\n";
92 private void getSock() throws IOException {
93 ProxyInfo pi = Platform.detectProxy();
96 if (pi == null || (pi.proxyAutoConfigFunction == null && pi.socksProxyHost == null && pi.httpProxyHost == null)) {
97 if (Log.on) Log.log(this, "creating unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
98 sock = Platform.getSocket(host, port, ssl);
102 // no PAC; simple config
103 if (pi.proxyAutoConfigFunction == null) {
104 String proxyHost = ssl && pi.httpsProxyHost != null ? pi.httpsProxyHost : pi.httpProxyHost;
105 int proxyPort = ssl && pi.httpsProxyHost != null ? pi.httpsProxyPort : pi.httpProxyPort;
106 if (Log.on) Log.log(this, "no proxyAutoConfigFunction; using proxy " + proxyHost + ":" + proxyPort);
107 sock = Platform.getSocket(proxyHost, proxyPort, ssl);
115 Context cx = Context.enter();
116 Object obj = pi.proxyAutoConfigFunction.call(cx, ProxyInfo.base, null, new Object[] { url.toString(), host });
117 if (Log.on) Log.log(this, "PAC script returned \"" + obj + "\"");
118 pac = obj.toString();
119 } catch (Throwable e) {
120 if (Log.on) Log.log(this, "PAC script threw an exception:");
121 if (Log.on) Log.log(this, e);
122 throw new IOException("PAC script threw exception " + e);
125 StringTokenizer st = new StringTokenizer(pac, ";", false);
126 while (st.hasMoreTokens()) {
127 String token = st.nextToken().trim();
128 if (Log.on) Log.log(this, " trying \"" + token + "\"...");
130 if (token.startsWith("DIRECT")) {
132 sock = Platform.getSocket(host, port, ssl);
134 } else if (token.startsWith("PROXY")) {
136 sock = Platform.getSocket(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
137 Integer.parseInt(token.substring(token.indexOf(':') + 1)), ssl);
139 } else if (token.startsWith("SOCKS")) {
142 } catch (Throwable e) {
143 if (Log.on) Log.log(this, "attempt at \"" + proxy + "\" failed due to " + e + "; trying next one");
146 throw new IOException("all proxy options exhausted");
149 public OutputStream getOutputStream(int contentLength, String contentType) throws IOException {
150 if (out != null) return out;
151 if (in != null) throw new IOException("attempt to getOutputStream() after getInputStream()");
153 sock.setTcpNoDelay(true);
154 out = sock.getOutputStream();
155 PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
156 pw.print("POST " + (proxy ? url.toString() : path) + " HTTP/1.0\r\n");
157 pw.print("Host: " + host + "\r\n");
158 pw.print("User-Agent: XWT\r\n");
159 pw.print("Content-length: " + contentLength + "\r\n");
161 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
167 public InputStream getInputStream() throws IOException {
168 if (in != null) return in;
173 sock.setTcpNoDelay(true);
174 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
175 pw.print("GET " + (proxy ? url.toString() : path) + " HTTP/1.0\r\n");
176 pw.print("Host: " + host + "\r\n");
177 pw.print("User-Agent: XWT\r\n");
183 in = new BufferedInputStream(sock.getInputStream());
185 // we can't use a BufferedReader directly on the input stream,
186 // since it will buffer beyond the end of the headers
187 byte[] buf = new byte[4096];
190 int read = in.read();
191 if (read == -1) throw new IOException("stream closed while reading headers");
192 buf[buflen++] = (byte)read;
193 if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
194 if (buflen == buf.length) {
195 byte[] newbuf = new byte[buf.length * 2];
196 System.arraycopy(buf, 0, newbuf, 0, buflen);
201 BufferedReader headerReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
202 String s = headerReader.readLine();
203 if (!s.startsWith("HTTP/")) throw new IOException("Expected reply to start with \"HTTP/\"");
204 String reply = s.substring(s.indexOf(' ') + 1);
205 if (!reply.startsWith("2")) throw new IOException("HTTP Error: " + reply);
206 while((s = headerReader.readLine()) != null) {
207 if (s.length() > 15 && s.substring(0, 15).equalsIgnoreCase("content-length: "))
208 contentLength = Integer.parseInt(s.substring(15));
214 public static class ProxyInfo {
216 public ProxyInfo() { }
218 /** the HTTP Proxy host to use */
219 public String httpProxyHost = null;
221 /** the HTTP Proxy port to use */
222 public int httpProxyPort = -1;
224 /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
225 public String httpsProxyHost = null;
227 /** if a seperate proxy should be used for HTTPS, this is the port */
228 public int httpsProxyPort = -1;
230 /** the SOCKS Proxy Host to use */
231 public String socksProxyHost = null;
233 /** the SOCKS Proxy Port to use */
234 public int socksProxyPort = -1;
236 /** hosts to be excluded from proxy use; wildcards permitted */
237 public String[] excluded = null;
239 /** the PAC script */
240 public Function proxyAutoConfigFunction = null;
242 public static ProxyInfo detectProxyViaManual() {
244 try { InetAddress.getByName("xwt-proxy-httpHost");
245 } catch (UnkownHostException unhe) { InetAddress.getByName("xwt-proxy-socksHost"); }
247 if (Log.on) Log.log(Platform.class, "using xwt-proxy-* configuration");
248 ProxyInfo ret = new ProxyInfo();
250 ret.httpProxyHost = InetAddress.getByName("xwt-proxy-httpHost").getHostAddress();
251 byte[] quadbyte = InetAddress.getByName("xwt-proxy-httpPort").getAddress();
252 ret.httpProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
253 } catch (UnknownHostException e) { }
255 ret.httpsProxyHost = InetAddress.getByName("xwt-proxy-httpsHost").getHostAddress();
256 byte[] quadbyte = InetAddress.getByName("xwt-proxy-httpsPort").getAddress();
257 ret.httpsProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
258 } catch (UnknownHostException e) { }
260 ret.socksProxyHost = InetAddress.getByName("xwt-proxy-socksHost").getHostAddress();
261 byte[] quadbyte = InetAddress.getByName("xwt-proxy-socksPort").getAddress();
262 ret.socksProxyPort = ((quadbyte[1] & 0xff) * 10000) + ((quadbyte[2] & 0xff) * 100) + (quadbyte[3] & 0xff);
263 } catch (UnknownHostException e) { }
265 } catch (UnknownHostException e) {
266 if (Log.on) Log.log(Platform.class, "xwt-proxy-* detection failed due to:");
271 // FIXME: search up from default domain
272 public static ProxyInfo detectProxyViaWPAD() {
274 InetAddress wpad = InetAddress.getByName("wpad");
275 if (Log.on) Log.log(Platform.class, "using Web Proxy Auto Detection to detect proxy settings");
276 ProxyInfo ret = new ProxyInfo();
277 ret.proxyAutoConfigFunction = getProxyAutoConfigFunction("http://wpad/wpad.dat");
278 if (ret.proxyAutoConfigFunction != null) return ret;
279 } catch (UnknownHostException e) {
280 if (Log.on) Log.log(HTTP.class, "couldn't find WPAD server: " + e);
285 public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
287 public static Function getProxyAutoConfigFunction(String url) {
289 Context cx = Context.enter();
290 cx.setOptimizationLevel(-1);
291 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url).getInputStream()));
294 while((s = br.readLine()) != null) script += s + "\n";
295 if (Log.on) Log.log(HTTP.ProxyInfo.class, "successfully retrieved WPAD PAC:");
296 if (Log.on) Log.log(HTTP.ProxyInfo.class, script);
297 Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
298 scr.exec(cx, proxyAutoConfigRootScope);
299 return (Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
300 } catch (Exception e) {
302 Log.log(Platform.class, "WPAD detection failed due to:");
303 if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
304 ((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
305 else Log.log(Platform.class, e);
311 public static class ProxyAutoConfigRootScope extends ScriptableObject {
313 public String getClassName() { return "ProxyAutoConfigRootScope"; }
314 ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
316 public Object get(String name, Scriptable start) {
317 if (name.equals("isPlainHostName")) return isPlainHostName;
318 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
319 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
320 else if (name.equals("isResolvable")) return isResolvable;
321 else if (name.equals("dnsResolve")) return dnsResolve;
322 else if (name.equals("myIpAddress")) return myIpAddress;
323 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
324 else if (name.equals("shExpMatch")) return shExpMatch;
325 else if (name.equals("weekdayRange")) return weekdayRange;
326 else if (name.equals("dateRange")) return dateRange;
327 else if (name.equals("timeRange")) return timeRange;
328 else if (name.equals("ProxyConfig")) return ProxyConfig;
329 else return super.get(name, start);
332 private static final JSObject proxyConfigBindings = new JSObject();
333 private static final JSObject ProxyConfig = new JSObject() {
334 public Object get(String name, Scriptable start) {
335 if (name.equals("bindings")) return proxyConfigBindings;
340 private static abstract class JSFunction extends JSObject implements Function {
341 JSFunction() { setSeal(true); }
342 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
345 private static final JSFunction isPlainHostName = new JSFunction() {
346 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
347 return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
351 private static final JSFunction dnsDomainIs = new JSFunction() {
352 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
353 return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
357 private static final JSFunction localHostOrDomainIs = new JSFunction() {
358 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
359 return (args[0].toString().equals(args[1].toString()) ||
360 (args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
361 Boolean.TRUE : Boolean.FALSE;
365 private static final JSFunction isResolvable = new JSFunction() {
366 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
368 return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
369 } catch (UnknownHostException e) {
370 return Boolean.FALSE;
375 private static final JSFunction isInNet = new JSFunction() {
376 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
382 private static final JSFunction dnsResolve = new JSFunction() {
383 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
385 return InetAddress.getByName(args[0].toString()).getHostAddress();
386 } catch (UnknownHostException e) {
392 private static final JSFunction myIpAddress = new JSFunction() {
393 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
395 return InetAddress.getLocalHost().getHostAddress();
396 } catch (UnknownHostException e) {
397 if (Log.on) Log.log(this, "strange... host does not know its own address");
403 private static final JSFunction dnsDomainLevels = new JSFunction() {
404 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
405 String s = args[0].toString();
407 while((i = s.indexOf('.', i)) != -1) i++;
408 return new Integer(i);
413 private static boolean match(String[] arr, String s, int index) {
414 if (index == arr.length) return true;
415 for(int i=0; i<s.length(); i++) {
416 String s2 = s.substring(i);
417 if (s2.startsWith(arr[index]) && match(arr, s.substring(arr[index].length()), index + 1)) return true;
422 private static final JSFunction shExpMatch = new JSFunction() {
423 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
424 StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
425 String[] arr = new String[st.countTokens()];
426 String s = args[0].toString();
427 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
428 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
432 private static final JSFunction weekdayRange = new JSFunction() {
433 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
434 throw new JavaScriptException("XWT does not support weekdayRange() in PAC scripts");
436 TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
437 Calendar c = new Calendar();
439 c.setTime(new Date());
440 Date d = c.getTime();
441 if (args.length == 1) return
446 private static final JSFunction dateRange = new JSFunction() {
447 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
448 throw new JavaScriptException("XWT does not support dateRange() in PAC scripts");
452 private static final JSFunction timeRange = new JSFunction() {
453 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
454 throw new JavaScriptException("XWT does not support timeRange() in PAC scripts");