1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]package org.xwt;
8 import org.mozilla.javascript.*;
11 * A crude HTTP[S] connection implementation with support for proxies, since not all Java libraries
12 * (particularly GCJ's) support proxies.
14 * FEATURE: implement pipelining
18 /** the URL to connect to */
21 /** the host to connect to */
24 /** the port to connect on */
27 /** true if SSL (HTTPS) should be used */
30 /** the path (URI) to retrieve on the server */
36 /** the socket's inputstream */
37 InputStream in = null;
39 /** the socket's outputstream */
40 OutputStream out = null;
42 /** the content-type of the data being received */
43 String contentType = null;
45 /** the content-length of the data being recieved */
46 int contentLength = 0;
48 /** additional headers to be transmitted */
51 /** cache for resolveAndCheckIfFirewalled() */
52 static Hashtable resolvedHosts = new Hashtable();
55 // Constructor ////////////////////////////////////////////////////////////////////////////////////////
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));
62 } else if (!url.startsWith("http:")) {
63 throw new HTTPException("HTTP only supports http/https urls");
65 this.url = new URL(url);
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);
76 /** this method initializes the HTTP object, resetting if needed (in case of a reconnect) */
77 public void init() throws IOException {
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);
92 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
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
98 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
101 if (host.equals("xmlrpc.xwt.org")) return;
104 if (resolvedHosts.get(host) != null) return;
106 if (Log.on) Log.log(this, " resolveAndCheckIfFirewalled: resolving " + host);
108 // if all scripts are trustworthy (local FS), continue
109 if (Main.originAddr == null) return;
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");
120 } catch (UnknownHostException uhe) { }
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");
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);
130 } catch (Throwable e) {
131 throw new HTTPException("exception while attempting to use xmlrpc.xwt.org to resolve " + host + ": " + e);
136 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
138 /** Attempts a direct connection */
139 public Socket attemptDirect() {
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);
149 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
150 public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
152 if (Log.on) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
154 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
156 path = "http://" + host + ":" + port + path;
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");
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();
169 } catch (IOException e) {
170 if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
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
180 public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
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) { }
186 if (Log.on) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
187 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
190 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
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
200 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
203 dos.writeByte(0x00); // hostname null terminator
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
212 if ((int)(success & 0xff) == 90) {
213 if (ssl) ((TinySSL)sock).negotiate();
216 if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
219 } catch (IOException e) {
220 if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
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");
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);
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 + "\"...");
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");
257 if (Log.on) Log.log(this, "all PAC results exhausted");
262 // Everything Else ////////////////////////////////////////////////////////////////////////////
264 /** returns the content-type of the reply */
265 public String getContentType() throws IOException {
270 /** returns the content-length of the reply */
271 public int getContentLength() throws IOException {
273 return contentLength;
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";
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");
291 if (ProxyAuthorization.authorization != null) pw.print("Proxy-Authorization: " + ProxyAuthorization.authorization + "\r\n");
292 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
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
302 public InputStream getInputStream() throws IOException {
304 if (in != null) return in;
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");
312 System.out.print(headers);
313 if (ProxyAuthorization.authorization != null) pw.print("Proxy-Authorization: " + ProxyAuthorization.authorization + "\r\n");
318 in = new BufferedInputStream(sock.getInputStream());
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];
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);
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);
341 if (reply.startsWith("407")) {
342 if (Log.on) Log.log(this, "Proxy Auth Required: HTTP " + reply);
344 String style = "Basic";
346 while((s = headerReader.readLine()) != null)
347 if (s.startsWith("Proxy-Authenticate:")) {
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('\"'));
358 ProxyAuthorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), ProxyAuthorization.authorization);
362 return getInputStream();
364 } else if (!reply.startsWith("2")) {
365 throw new HTTPException("HTTP Error: " + reply);
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));
377 // HTTPException ///////////////////////////////////////////////////////////////////////////////////
379 static class HTTPException extends IOException {
380 public HTTPException(String s) { super(s); }
384 // ProxyInfo ///////////////////////////////////////////////////////////////////////////////////
386 public static class ProxyInfo {
388 public ProxyInfo() { }
390 /** the HTTP Proxy host to use */
391 public String httpProxyHost = null;
393 /** the HTTP Proxy port to use */
394 public int httpProxyPort = -1;
396 /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
397 public String httpsProxyHost = null;
399 /** if a seperate proxy should be used for HTTPS, this is the port */
400 public int httpsProxyPort = -1;
402 /** the SOCKS Proxy Host to use */
403 public String socksProxyHost = null;
405 /** the SOCKS Proxy Port to use */
406 public int socksProxyPort = -1;
408 /** hosts to be excluded from proxy use; wildcards permitted */
409 public String[] excluded = null;
411 /** the PAC script */
412 public Function proxyAutoConfigFunction = null;
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();
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(':'));
427 ret.httpProxyPort = 80;
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(':'));
439 ret.httpsProxyPort = 80;
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(':'));
451 ret.socksProxyPort = 80;
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();
462 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
466 // FIXME: search up from default domain
467 public static ProxyInfo detectProxyViaWPAD() {
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);
480 public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
482 public static Function getProxyAutoConfigFunction(String url) {
484 Context cx = Context.enter();
485 cx.setOptimizationLevel(-1);
486 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).getInputStream()));
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);
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);
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) + "; ";
506 if (Log.on) Log.log(ProxyInfo.class, "DeCARPed PAC script:");
507 if (Log.on) Log.log(ProxyInfo.class, script);
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) {
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);
524 public static class ProxyAutoConfigRootScope extends ScriptableObject {
526 public String getClassName() { return "ProxyAutoConfigRootScope"; }
527 ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
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);
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;
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; }
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;
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;
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;
579 private static final JSFunction isResolvable = new JSFunction() {
580 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
582 return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
583 } catch (UnknownHostException e) {
584 return Boolean.FALSE;
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;
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);
607 private static final JSFunction dnsResolve = new JSFunction() {
608 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
610 return InetAddress.getByName(args[0].toString()).getHostAddress();
611 } catch (UnknownHostException e) {
617 private static final JSFunction myIpAddress = new JSFunction() {
618 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
620 return InetAddress.getLocalHost().getHostAddress();
621 } catch (UnknownHostException e) {
622 if (Log.on) Log.log(this, "strange... host does not know its own address");
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();
632 while((i = s.indexOf('.', i)) != -1) i++;
633 return new Integer(i);
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;
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;
656 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
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();
663 c.setTime(new Date());
664 Date d = c.getTime();
665 int day = d.getDay();
667 String d1s = args[0].toString().toUpperCase();
669 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
671 if (args.length == 1)
672 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
674 String d2s = args[1].toString().toUpperCase();
675 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
678 ((d1 <= d2 && day >= d1 && day <= d2) ||
679 (d1 > d2 && (day >= d1 || day <= d2))) ?
680 Boolean.TRUE : Boolean.FALSE;
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");
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");
700 // ProxyAuthorization ///////////////////////////////////////////////////////////////////////////////////
702 public static class ProxyAuthorization {
704 static public String authorization = null;
705 static public Semaphore waitingForUser = new Semaphore();
707 // FIXME: Digest and NTLM
708 public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
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.
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);
724 waitingForUser.block();
725 if (Log.on) Log.log(ProxyAuthorization.class, "got proxy authorization info; re-attempting connection");