2002/05/04 07:25:32
[org.ibex.core.git] / src / org / xwt / HTTP.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.net.*;
5 import java.io.*;
6 import java.util.*;
7 import org.xwt.util.*;
8 import org.mozilla.javascript.*;
9
10 /**
11  *  A crude HTTP[S] connection implementation with support for proxies, since not all Java libraries
12  *  (particularly GCJ's) support proxies.
13  *
14  *  FEATURE: implement pipelining
15  */
16 public class HTTP {
17
18     /** the URL to connect to */
19     URL url = null;
20
21     /** the host to connect to */
22     String host = null;
23
24     /** the port to connect on */
25     int port = -1;
26
27     /** true if SSL (HTTPS) should be used */
28     boolean ssl = false;
29
30     /** the path (URI) to retrieve on the server */
31     String path = null;
32
33     /** the socket; created lazily */
34     Socket sock = null;
35
36     /** the socket's inputstream */
37     InputStream in = null;
38
39     /** the socket's outputstream */
40     OutputStream out = null;
41
42     /** the content-type of the data being received */
43     String contentType = null;
44
45     /** the content-length of the data being recieved */
46     int contentLength = 0;
47
48     /** true iff a proxy should be used */
49     boolean proxy = false;
50
51     /** additional headers to be transmitted */
52     String headers = "";
53
54     public HTTP(String url) throws MalformedURLException, IOException {
55         if (url.startsWith("https:")) {
56             url = "http" + url.substring(5);
57             ssl = true;
58         }
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;
65         try {
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");
74         }
75     }
76
77     public String getContentType() throws IOException {
78         getInputStream();
79         return contentType;
80     }
81
82     public int getContentLength() throws IOException {
83         getInputStream();
84         return contentLength;
85     }
86
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";
90     }
91
92     private void getSock() throws IOException {
93         ProxyInfo pi = Platform.detectProxy();
94
95         // unproxied
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);
99             return;
100         }
101
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);
108             proxy = true;
109             return;
110         }
111         
112         // PAC
113         String pac = null;
114         try {
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);
123         }
124
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 + "\"...");
129             try {
130                 if (token.startsWith("DIRECT")) {
131                     proxy = false;
132                     sock = Platform.getSocket(host, port, ssl);
133                     return;
134                 } else if (token.startsWith("PROXY")) { 
135                     proxy = true;
136                     sock = Platform.getSocket(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
137                                               Integer.parseInt(token.substring(token.indexOf(':') + 1)), ssl);
138                     return;
139                 } else if (token.startsWith("SOCKS")) {
140                     // FIXME
141                 }
142             } catch (Throwable e) {
143                 if (Log.on) Log.log(this, "attempt at \"" + proxy + "\" failed due to " + e + "; trying next one");
144             }
145         }
146         throw new IOException("all proxy options exhausted");
147     }
148
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()");
152         getSock();
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");
160         pw.print(headers);
161         if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
162         pw.print("\r\n");
163         pw.flush();
164         return out;
165     }
166
167     public InputStream getInputStream() throws IOException {
168         if (in != null) return in;
169         if (out != null) {
170             out.flush();
171         } else {
172             getSock();
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");
178             pw.print(headers);
179             pw.print("\r\n");
180             pw.flush();
181         }
182
183         in = new BufferedInputStream(sock.getInputStream());
184
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];
188         int buflen = 0;
189         while(true) {
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);
197                 buf = newbuf;
198             }
199         }
200         
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));
209         }
210
211         return in;
212     }
213
214     public static class ProxyInfo {
215
216         public ProxyInfo() { }
217
218         /** the HTTP Proxy host to use */
219         public String httpProxyHost = null;
220
221         /** the HTTP Proxy port to use */
222         public int httpProxyPort = -1;
223
224         /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
225         public String httpsProxyHost = null;
226
227         /** if a seperate proxy should be used for HTTPS, this is the port */
228         public int httpsProxyPort = -1;
229
230         /** the SOCKS Proxy Host to use */
231         public String socksProxyHost = null;
232
233         /** the SOCKS Proxy Port to use */
234         public int socksProxyPort = -1;
235
236         /** hosts to be excluded from proxy use; wildcards permitted */
237         public String[] excluded = null;
238
239         /** the PAC script */
240         public Function proxyAutoConfigFunction = null;
241
242         public static ProxyInfo detectProxyViaManual() {
243             try {
244                 try { InetAddress.getByName("xwt-proxy-httpHost");
245                 } catch (UnkownHostException unhe) { InetAddress.getByName("xwt-proxy-socksHost"); }
246
247                 if (Log.on) Log.log(Platform.class, "using xwt-proxy-* configuration");
248                 ProxyInfo ret = new ProxyInfo();
249                 try {
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) { }
254                 try {
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) { }
259                 try {
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) { }
264                 return ret;
265             } catch (UnknownHostException e) {
266                 if (Log.on) Log.log(Platform.class, "xwt-proxy-* detection failed due to:");
267                 return null;
268             }
269         }
270
271         // FIXME: search up from default domain
272         public static ProxyInfo detectProxyViaWPAD() {
273             try {
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);
281             }
282             return null;
283         }
284
285         public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
286
287         public static Function getProxyAutoConfigFunction(String url) {
288             try { 
289                 Context cx = Context.enter();
290                 cx.setOptimizationLevel(-1);
291                 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url).getInputStream()));
292                 String s = null;
293                 String script = "";
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) {
301                 if (Log.on) {
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);
306                 }
307                 return null;
308             }
309         }
310
311         public static class ProxyAutoConfigRootScope extends ScriptableObject {
312
313             public String getClassName() { return "ProxyAutoConfigRootScope"; }
314             ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
315
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);
330             }
331
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;
336                         return null;
337                     }
338                 };
339             
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; }
343             }
344
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;
348                     }
349                 };
350
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;
354                     }
355                 };
356             
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;
362                     }
363                 };
364             
365             private static final JSFunction isResolvable = new JSFunction() {
366                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
367                         try {
368                             return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
369                         } catch (UnknownHostException e) {
370                             return Boolean.FALSE;
371                         }
372                     }
373                 };
374
375             private static final JSFunction isInNet = new JSFunction() {
376                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
377                         // FIXME
378                         return null;
379                     }
380                 };
381
382             private static final JSFunction dnsResolve = new JSFunction() {
383                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
384                         try {
385                             return InetAddress.getByName(args[0].toString()).getHostAddress();
386                         } catch (UnknownHostException e) {
387                             return null;
388                         }
389                     }
390                 };
391
392             private static final JSFunction myIpAddress = new JSFunction() {
393                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
394                         try {
395                             return InetAddress.getLocalHost().getHostAddress();
396                         } catch (UnknownHostException e) {
397                             if (Log.on) Log.log(this, "strange... host does not know its own address");
398                             return null;
399                         }
400                     }
401                 };
402
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();
406                         int i = 0;
407                         while((i = s.indexOf('.', i)) != -1) i++;
408                         return new Integer(i);
409                     }
410                 };
411         
412             // FIXME: test this!
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;
418                 }
419                 return false;
420             }
421
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;
429                     }
430                 };
431
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");
435                         /*
436                         TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
437                         Calendar c = new Calendar();
438                         c.setTimeZone(tz);
439                         c.setTime(new Date());
440                         Date d = c.getTime();
441                         if (args.length == 1) return 
442                         */
443                     }
444                 };
445
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");
449                     }
450                 };
451
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");
455                     }
456                 };
457
458         }
459
460     }
461
462 }