2002/07/19 05:45:00
[org.ibex.core.git] / src / org / xwt / HTTP.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]package org.xwt;
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 */
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     /** additional headers to be transmitted */
49     String headers = "";
50
51     /** cache for resolveAndCheckIfFirewalled() */
52     static Hashtable resolvedHosts = new Hashtable();
53
54
55     // Constructor ////////////////////////////////////////////////////////////////////////////////////////
56
57     public HTTP(String url) throws MalformedURLException, IOException { this(url, false); }
58     public HTTP(String url, boolean skipResolveCheck) throws MalformedURLException, IOException {
59         if (url.startsWith("https:")) {
60             this.url = new URL("http" + url.substring(5));
61             ssl = true;
62         } else if (!url.startsWith("http:")) {
63             throw new HTTPException("HTTP only supports http/https urls");
64         } else {
65             this.url = new URL(url);
66         }
67         if (!skipResolveCheck) resolveAndCheckIfFirewalled(this.url.getHost());
68         port = this.url.getPort();
69         path = this.url.getFile();
70         if (port == -1) port = ssl ? 443 : 80;
71         host = this.url.getHost();
72         if (Log.on) Log.log(this, "creating HTTP object for connection to " + host + ":" + port);
73         init();
74     }
75
76     /** this method initializes the HTTP object, resetting if needed (in case of a reconnect) */
77     public void init() throws IOException {
78         headers = "";
79         sock = null;
80         in = null;
81         out = null;
82         addHeader("Host", host);
83         ProxyInfo pi = Platform.detectProxy();
84         if (sock == null && pi != null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
85         if (sock == null && pi != null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost, pi.httpsProxyPort);
86         if (sock == null && pi != null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
87         if (sock == null && pi != null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
88         if (sock == null) sock = attemptDirect();
89         if (sock == null) throw new HTTPException("unable to contact host " + host);
90     }
91
92     // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
93
94     /**
95      *  resolves the hostname and returns it as a string in the form "x.y.z.w", except for the special case "xmlrpc.xwt.org".
96      *  @throws HTTPException if the host falls within a firewalled netblock
97      */
98     private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
99
100         // special case
101         if (host.equals("xmlrpc.xwt.org")) return;
102
103         // cached
104         if (resolvedHosts.get(host) != null) return;
105
106         if (Log.on) Log.log(this, "  resolveAndCheckIfFirewalled: resolving " + host);
107
108         // if all scripts are trustworthy (local FS), continue
109         if (Main.originAddr == null) return;
110
111         // resolve using DNS
112         try {
113             InetAddress addr = InetAddress.getByName(host);
114             byte[] quadbyte = addr.getAddress();
115             if ((quadbyte[0] == 10 ||
116                  (quadbyte[0] == 192 && quadbyte[1] == 168) ||
117                  (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
118                 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
119             return;
120         } catch (UnknownHostException uhe) { }
121
122         // resolve using xmlrpc.xwt.org
123         if (Platform.detectProxy() == null) throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
124         if (Log.on) Log.log(this, "  could not resolve host " + host + "; using xmlrpc.xwt.org to ensure security");
125         try {
126             Object ret = new XMLRPC("http://xmlrpc.xwt.org/RPC2/", "dns.resolve").call(new Object[] { host });
127             if (ret == null || !(ret instanceof String)) throw new Exception("    xmlrpc.xwt.org returned non-String: " + ret);
128             resolvedHosts.put(host, ret);
129             return;
130         } catch (Throwable e) {
131             throw new HTTPException("exception while attempting to use xmlrpc.xwt.org to resolve " + host + ": " + e);
132         }
133     }
134
135
136     // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
137
138     /** Attempts a direct connection */
139     public Socket attemptDirect() {
140         try {
141             if (Log.on) Log.log(this, "attempting to create unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
142             return Platform.getSocket(host, port, ssl, true);
143         } catch (IOException e) {
144             if (Log.on) Log.log(this, "exception in attemptDirect(): " + e);
145             return null;
146         }
147     }
148
149     /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
150     public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
151         try {
152             if (Log.on) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
153
154             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
155             if (!ssl) {
156                 path = "http://" + host + ":" + port + path;
157             } else {
158                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
159                 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
160                 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
161                 pw.flush();
162                 String s = br.readLine();
163                 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
164                 while (br.readLine().length() > 0) { };
165                 ((TinySSL)sock).negotiate();
166             }
167             return sock;
168
169         } catch (IOException e) {
170             if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
171             return null;
172         }
173     }
174
175     /**
176      *  Implements SOCKSv4 with v4a DNS extension
177      *  @see http://www.socks.nec.com/protocol/socks4.protocol
178      *  @see http://www.socks.nec.com/protocol/socks4a.protocol
179      */
180     public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
181
182         // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
183         InetAddress addr = null;
184         try { addr = InetAddress.getByName(host); } catch (Exception e) { }
185
186         if (Log.on) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
187                             " proxied socket using proxy " + proxyHost + ":" + proxyPort);
188
189         try {
190             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
191             
192             DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
193             dos.writeByte(0x04);                         // SOCKSv4(a)
194             dos.writeByte(0x01);                         // CONNECT
195             dos.writeShort(port & 0xffff);               // port
196             if (addr == null) dos.writeInt(0x00000001);  // bogus IP
197             else dos.write(addr.getAddress());           // actual IP
198             dos.writeByte(0x00);                         // no userid
199             if (addr == null) {
200                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
201                 pw.print(host);
202                 pw.flush();
203                 dos.writeByte(0x00);                     // hostname null terminator
204             }
205             dos.flush();
206
207             DataInputStream dis = new DataInputStream(sock.getInputStream());
208             dis.readByte();                              // reply version
209             byte success = dis.readByte();               // success/fail
210             dis.skip(6);                                 // ip/port
211             
212             if ((int)(success & 0xff) == 90) {
213                 if (ssl) ((TinySSL)sock).negotiate();
214                 return sock;
215             }
216             if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
217             return null;
218
219         } catch (IOException e) {
220             if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
221             return null;
222         }
223     }
224
225     /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
226     public Socket attemptPAC(Function pacFunc) {
227         if (Log.on) Log.log(this, "evaluating PAC script");
228         String pac = null;
229         try {
230             Object obj = pacFunc.call(Context.enter(), ProxyInfo.proxyAutoConfigRootScope, null, new Object[] { url.toString(), url.getHost() });
231             if (Log.on) Log.log(this, "  PAC script returned \"" + obj + "\"");
232             pac = obj.toString();
233         } catch (Throwable e) {
234             if (Log.on) Log.log(this, "PAC script threw exception " + e);
235             return null;
236         }
237
238         StringTokenizer st = new StringTokenizer(pac, ";", false);
239         while (st.hasMoreTokens()) {
240             String token = st.nextToken().trim();
241             if (Log.on) Log.log(this, "  trying \"" + token + "\"...");
242             try {
243                 Socket ret = null;
244                 if (token.startsWith("DIRECT"))
245                     ret = attemptDirect();
246                 else if (token.startsWith("PROXY"))
247                     ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
248                                            Integer.parseInt(token.substring(token.indexOf(':') + 1)));
249                 else if (token.startsWith("SOCKS"))
250                     ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
251                                             Integer.parseInt(token.substring(token.indexOf(':') + 1)));
252                 if (ret != null) return ret;
253             } catch (Throwable e) {
254                 if (Log.on) Log.log(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
255             }
256         }
257         if (Log.on) Log.log(this, "all PAC results exhausted");
258         return null;
259     }
260
261
262     // Everything Else ////////////////////////////////////////////////////////////////////////////
263
264     /** returns the content-type of the reply */
265     public String getContentType() throws IOException {
266         getInputStream();
267         return contentType;
268     }
269
270     /** returns the content-length of the reply */
271     public int getContentLength() throws IOException {
272         getInputStream();
273         return contentLength;
274     }
275
276     /** adds a header to the outbound transmission */
277     public void addHeader(String header, String value) throws HTTPException {
278         if (in != null) throw new HTTPException("attempt to add header after connection has been made");
279         headers += header + ": " + value + "\r\n";
280     }
281
282     public OutputStream getOutputStream(int contentLength, String contentType) throws IOException {
283         if (out != null) return out;
284         if (in != null) throw new HTTPException("attempt to getOutputStream() after getInputStream()");
285         out = sock.getOutputStream();
286         PrintWriter pw = new PrintWriter(new OutputStreamWriter(out));
287         pw.print("POST " + path + " HTTP/1.0\r\n");
288         pw.print("User-Agent: XWT\r\n");
289         pw.print("Content-length: " + contentLength + "\r\n");
290         pw.print(headers);
291         if (ProxyAuthorization.authorization != null) pw.print("Proxy-Authorization: " + ProxyAuthorization.authorization + "\r\n");
292         if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
293         pw.print("\r\n");
294
295         // FIXME: check for HTTP "ok, go ahead" here, in case we need proxy authorization this can happen if the xwar is
296         //        on the local disk and the first HTTP request is through an auth-requiring proxy
297
298         pw.flush();
299         return out;
300     }
301
302     public InputStream getInputStream() throws IOException {
303
304         if (in != null) return in;
305         if (out != null) {
306             out.flush();
307         } else {
308             PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
309             pw.print("GET " + path + " HTTP/1.0\r\n");
310             pw.print("User-Agent: XWT\r\n");
311             pw.print(headers);
312             System.out.print(headers);
313             if (ProxyAuthorization.authorization != null) pw.print("Proxy-Authorization: " + ProxyAuthorization.authorization + "\r\n");
314             pw.print("\r\n");
315             pw.flush();
316         }
317
318         in = new BufferedInputStream(sock.getInputStream());
319
320         // we can't use a BufferedReader directly on the input stream,
321         // since it will buffer past the end of the headers
322         byte[] buf = new byte[4096];
323         int buflen = 0;
324         while(true) {
325             int read = in.read();
326             if (read == -1) throw new HTTPException("stream closed while reading headers");
327             buf[buflen++] = (byte)read;
328             if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
329             if (buflen == buf.length) {
330                 byte[] newbuf = new byte[buf.length * 2];
331                 System.arraycopy(buf, 0, newbuf, 0, buflen);
332                 buf = newbuf;
333             }
334         }
335         
336         BufferedReader headerReader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
337         String s = headerReader.readLine();
338         if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\"");
339         String reply = s.substring(s.indexOf(' ') + 1);
340
341         if (reply.startsWith("407")) {
342             if (Log.on) Log.log(this, "Proxy Auth Required: HTTP " + reply);
343             String realm = "";
344             String style = "Basic";
345
346             while((s = headerReader.readLine()) != null)
347                 if (s.startsWith("Proxy-Authenticate:")) {
348                     s = s.substring(19);
349                     while(s.charAt(0) == ' ') s = s.substring(1);
350                     style = s.substring(0, s.indexOf(' '));
351                     s = s.substring(s.indexOf(' '));
352                     s = s.substring(s.indexOf("realm"));
353                     s = s.substring(s.indexOf('\"') + 1);
354                     s = s.substring(0, s.indexOf('\"'));
355                     realm = s;
356                 }
357
358             ProxyAuthorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), ProxyAuthorization.authorization);
359
360             // reset and re-try
361             init();
362             return getInputStream();
363
364         } else if (!reply.startsWith("2")) {
365             throw new HTTPException("HTTP Error: " + reply);
366         }
367
368         while((s = headerReader.readLine()) != null)
369             if (s.length() > 15 && s.substring(0, 16).equalsIgnoreCase("content-length: "))
370                 contentLength = Integer.parseInt(s.substring(16));
371
372         return in;
373     }
374
375
376
377     // HTTPException ///////////////////////////////////////////////////////////////////////////////////
378
379     static class HTTPException extends IOException {
380         public HTTPException(String s) { super(s); }
381     }
382
383
384     // ProxyInfo ///////////////////////////////////////////////////////////////////////////////////
385
386     public static class ProxyInfo {
387
388         public ProxyInfo() { }
389
390         /** the HTTP Proxy host to use */
391         public String httpProxyHost = null;
392
393         /** the HTTP Proxy port to use */
394         public int httpProxyPort = -1;
395
396         /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
397         public String httpsProxyHost = null;
398
399         /** if a seperate proxy should be used for HTTPS, this is the port */
400         public int httpsProxyPort = -1;
401
402         /** the SOCKS Proxy Host to use */
403         public String socksProxyHost = null;
404
405         /** the SOCKS Proxy Port to use */
406         public int socksProxyPort = -1;
407
408         /** hosts to be excluded from proxy use; wildcards permitted */
409         public String[] excluded = null;
410
411         /** the PAC script */
412         public Function proxyAutoConfigFunction = null;
413
414         // this method has been disabled because it was causing problems -- some domains are set up so that *.foo.com resolves
415         // to a single IP, for any value of *. If the client's home domain is foo.com, then xwt-proxy-httpHost will resolve erroneously.
416         public static ProxyInfo detectProxyViaManual() {
417             ProxyInfo ret = new ProxyInfo();
418             
419             ret.httpProxyHost = Platform.getEnv("http_proxy");
420             if (ret.httpProxyHost != null) {
421                 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
422                 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
423                 if (ret.httpProxyHost.indexOf(':') != -1) {
424                     ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
425                     ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
426                 } else {
427                     ret.httpProxyPort = 80;
428                 }
429             }
430             
431             ret.httpsProxyHost = Platform.getEnv("https_proxy");
432             if (ret.httpsProxyHost != null) {
433                 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
434                 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
435                 if (ret.httpsProxyHost.indexOf(':') != -1) {
436                     ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
437                     ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
438                 } else {
439                     ret.httpsProxyPort = 80;
440                 }
441             }
442             
443             ret.socksProxyHost = Platform.getEnv("socks_proxy");
444             if (ret.socksProxyHost != null) {
445                 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
446                 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
447                 if (ret.socksProxyHost.indexOf(':') != -1) {
448                     ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
449                     ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
450                 } else {
451                     ret.socksProxyPort = 80;
452                 }
453             }
454             
455             String noproxy = Platform.getEnv("no_proxy");
456             if (noproxy != null) {
457                 StringTokenizer st = new StringTokenizer(noproxy, ",");
458                 ret.excluded = new String[st.countTokens()];
459                 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
460             }
461             
462             if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
463             return ret;
464         }
465
466         // FIXME: search up from default domain
467         public static ProxyInfo detectProxyViaWPAD() {
468             try {
469                 InetAddress wpad = InetAddress.getByName("wpad");
470                 if (Log.on) Log.log(Platform.class, "using Web Proxy Auto Detection to detect proxy settings");
471                 ProxyInfo ret = new ProxyInfo();
472                 ret.proxyAutoConfigFunction = getProxyAutoConfigFunction("http://wpad/wpad.dat");
473                 if (ret.proxyAutoConfigFunction != null) return ret;
474             } catch (UnknownHostException e) {
475                 if (Log.on) Log.log(HTTP.class, "couldn't find WPAD server: " + e);
476             }
477             return null;
478         }
479
480         public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
481
482         public static Function getProxyAutoConfigFunction(String url) {
483             try { 
484                 Context cx = Context.enter();
485                 cx.setOptimizationLevel(-1);
486                 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).getInputStream()));
487                 String s = null;
488                 String script = "";
489                 while((s = br.readLine()) != null) script += s + "\n";
490                 if (Log.on) Log.log(ProxyInfo.class, "successfully retrieved WPAD PAC:");
491                 if (Log.on) Log.log(ProxyInfo.class, script);
492                 
493                 // MS CARP hack
494                 Vector carpHosts = new Vector();
495                 for(int i=0; i<script.length(); i++)
496                     if (script.regionMatches(i, "new Node(", 0, 9)) {
497                         String host = script.substring(i + 10, script.indexOf('\"', i + 11));
498                         if (Log.on) Log.log(ProxyInfo.class, "Detected MS Proxy Server CARP Script, Host=" + host);
499                         carpHosts.addElement(host);
500                     }
501                 if (carpHosts.size() > 0) {
502                     script = "function FindProxyForURL(url, host) {\nreturn \"";
503                     for(int i=0; i<carpHosts.size(); i++)
504                         script += "PROXY " + carpHosts.elementAt(i) + "; ";
505                     script += "\";\n}";
506                     if (Log.on) Log.log(ProxyInfo.class, "DeCARPed PAC script:");
507                     if (Log.on) Log.log(ProxyInfo.class, script);
508                 }
509
510                 Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
511                 scr.exec(cx, proxyAutoConfigRootScope);
512                 return (Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
513             } catch (Exception e) {
514                 if (Log.on) {
515                     Log.log(Platform.class, "WPAD detection failed due to:");
516                     if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
517                                                         ((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
518                     else Log.log(Platform.class, e);
519                 }
520                 return null;
521             }
522         }
523
524         public static class ProxyAutoConfigRootScope extends ScriptableObject {
525
526             public String getClassName() { return "ProxyAutoConfigRootScope"; }
527             ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
528
529             public Object get(String name, Scriptable start) {
530                 if (name.equals("isPlainHostName")) return isPlainHostName;
531                 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
532                 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
533                 else if (name.equals("isResolvable")) return isResolvable;
534                 else if (name.equals("isInNet")) return isInNet;
535                 else if (name.equals("dnsResolve")) return dnsResolve;
536                 else if (name.equals("myIpAddress")) return myIpAddress;
537                 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
538                 else if (name.equals("shExpMatch")) return shExpMatch;
539                 else if (name.equals("weekdayRange")) return weekdayRange;
540                 else if (name.equals("dateRange")) return dateRange;
541                 else if (name.equals("timeRange")) return timeRange;
542                 else if (name.equals("ProxyConfig")) return ProxyConfig;
543                 else return super.get(name, start);
544             }
545
546             private static final JSObject proxyConfigBindings = new JSObject();
547             private static final JSObject ProxyConfig = new JSObject() {
548                     public Object get(String name, Scriptable start) {
549                         if (name.equals("bindings")) return proxyConfigBindings;
550                         return null;
551                     }
552                 };
553             
554             private static abstract class JSFunction extends JSObject implements Function {
555                 JSFunction() { setSeal(true); }
556                 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
557             }
558
559             private static final JSFunction isPlainHostName = new JSFunction() {
560                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
561                         return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
562                     }
563                 };
564
565             private static final JSFunction dnsDomainIs = new JSFunction() {
566                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
567                         return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
568                     }
569                 };
570             
571             private static final JSFunction localHostOrDomainIs = new JSFunction() {
572                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
573                         return (args[0].toString().equals(args[1].toString()) || 
574                                 (args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
575                             Boolean.TRUE : Boolean.FALSE;
576                     }
577                 };
578             
579             private static final JSFunction isResolvable = new JSFunction() {
580                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
581                         try {
582                             return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
583                         } catch (UnknownHostException e) {
584                             return Boolean.FALSE;
585                         }
586                     }
587                 };
588
589             private static final JSFunction isInNet = new JSFunction() {
590                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
591                         if (args.length != 3) return Boolean.FALSE;
592                         try {
593                             byte[] host = InetAddress.getByName(args[0].toString()).getAddress();
594                             byte[] net = InetAddress.getByName(args[1].toString()).getAddress();
595                             byte[] mask = InetAddress.getByName(args[2].toString()).getAddress();
596                             return ((host[0] & mask[0]) == net[0] &&
597                                     (host[1] & mask[1]) == net[1] &&
598                                     (host[2] & mask[2]) == net[2] &&
599                                     (host[3] & mask[3]) == net[3]) ?
600                                 Boolean.TRUE : Boolean.FALSE;
601                         } catch (Exception e) {
602                             throw new JavaScriptException("exception in isInNet(): " + e);
603                         }
604                     }
605                 };
606
607             private static final JSFunction dnsResolve = new JSFunction() {
608                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
609                         try {
610                             return InetAddress.getByName(args[0].toString()).getHostAddress();
611                         } catch (UnknownHostException e) {
612                             return null;
613                         }
614                     }
615                 };
616
617             private static final JSFunction myIpAddress = new JSFunction() {
618                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
619                         try {
620                             return InetAddress.getLocalHost().getHostAddress();
621                         } catch (UnknownHostException e) {
622                             if (Log.on) Log.log(this, "strange... host does not know its own address");
623                             return null;
624                         }
625                     }
626                 };
627
628             private static final JSFunction dnsDomainLevels = new JSFunction() {
629                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
630                         String s = args[0].toString();
631                         int i = 0;
632                         while((i = s.indexOf('.', i)) != -1) i++;
633                         return new Integer(i);
634                     }
635                 };
636         
637             private static boolean match(String[] arr, String s, int index) {
638                 if (index == arr.length) return true;
639                 for(int i=0; i<s.length(); i++) {
640                     String s2 = s.substring(i);
641                     if (s2.startsWith(arr[index]) && match(arr, s.substring(arr[index].length()), index + 1)) return true;
642                 }
643                 return false;
644             }
645
646             private static final JSFunction shExpMatch = new JSFunction() {
647                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
648                         StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
649                         String[] arr = new String[st.countTokens()];
650                         String s = args[0].toString();
651                         for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
652                         return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
653                     }
654                 };
655
656             public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
657
658             private static final JSFunction weekdayRange = new JSFunction() {
659                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
660                         TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
661                         Calendar c = new GregorianCalendar();
662                         c.setTimeZone(tz);
663                         c.setTime(new Date());
664                         Date d = c.getTime();
665                         int day = d.getDay();
666
667                         String d1s = args[0].toString().toUpperCase();
668                         int d1 = 0, d2 = 0;
669                         for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
670
671                         if (args.length == 1)
672                             return d1 == day ? Boolean.TRUE : Boolean.FALSE;
673
674                         String d2s = args[1].toString().toUpperCase();
675                         for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
676
677                         return
678                             ((d1 <= d2 && day >= d1 && day <= d2) ||
679                              (d1 > d2 && (day >= d1 || day <= d2))) ?
680                             Boolean.TRUE : Boolean.FALSE;
681                     }
682                 };
683
684             private static final JSFunction dateRange = new JSFunction() {
685                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
686                         throw new JavaScriptException("XWT does not support dateRange() in PAC scripts");
687                     }
688                 };
689
690             private static final JSFunction timeRange = new JSFunction() {
691                     public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
692                         throw new JavaScriptException("XWT does not support timeRange() in PAC scripts");
693                     }
694                 };
695
696         }
697
698     }
699
700     // ProxyAuthorization ///////////////////////////////////////////////////////////////////////////////////
701
702     public static class ProxyAuthorization {
703
704         static public String authorization = null;
705         static public Semaphore waitingForUser = new Semaphore();
706
707         // FIXME: Digest and NTLM
708         public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
709
710             // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
711             // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
712             // a password, so we should reattempt authorization.
713
714             if (authorization != oldAuth) return;
715             if (Log.on) Log.log(ProxyAuthorization.class, "displaying proxy authorization dialog");
716             MessageQueue.add(new Message() {
717                     public void perform() {
718                         Box b = new Box("org.xwt.builtin.proxy_authorization", null);
719                         b.put("realm", realm);
720                         b.put("proxyIP", proxyIP);
721                     }
722                 });
723
724             waitingForUser.block();
725             if (Log.on) Log.log(ProxyAuthorization.class, "got proxy authorization info; re-attempting connection");
726             
727         }
728     }
729
730 }