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