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