1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
9 import org.bouncycastle.util.encoders.Base64;
10 import org.bouncycastle.crypto.digests.*;
13 * This object encapsulates a *single* HTTP connection. Multiple requests may be pipelined over a connection (thread-safe),
14 * although any IOException encountered in a request will invalidate all later requests.
18 /** the URL as passed to the original constructor; this is never changed */
19 final String originalUrl;
21 /** the URL to connect to; this is munged when the url is parsed */
24 /** the host to connect to */
27 /** the port to connect on */
30 /** true if SSL (HTTPS) should be used */
33 /** the path (URI) to retrieve on the server */
39 /** the socket's inputstream */
40 InputStream in = null;
42 /** the username and password portions of the URL */
43 String userInfo = null;
45 /** cache of userInfo strings, keyed on originalUrl */
46 private static Hashtable authCache = new Hashtable();
48 /** this is null if the current request is the first request on
49 * this HTTP connection; otherwise it is a Semaphore which will be
50 * released once the request ahead of us has recieved its response
52 Semaphore okToRecieve = null;
54 /** cache for resolveAndCheckIfFirewalled() */
55 static Hashtable resolvedHosts = new Hashtable();
57 /** if any request encounters an IOException, the entire HTTP connection is invalidated */
58 boolean invalid = false;
60 /** true iff we are allowed to skip the resolve check (only allowed when we're downloading the PAC script) */
61 boolean skipResolveCheck = false;
63 /** true iff we're using a proxy */
64 boolean proxied = false;
67 // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
69 public HTTP(String url) { this(url, false); }
70 public HTTP(String url, boolean skipResolveCheck) {
72 this.skipResolveCheck = skipResolveCheck;
75 /** Performs an HTTP GET request */
76 public HTTPInputStream GET() throws IOException { return makeRequest(null, null); }
78 /** Performs an HTTP POST request; content is appended to the headers (so it should include a blank line to delimit the beginning of the body) */
79 public HTTPInputStream POST(String contentType, String content) throws IOException { return makeRequest(contentType, content); }
82 * This method isn't synchronized; however, only one thread can be in the inner synchronized block at a time, and the rest of
83 * the method is protected by in-order one-at-a-time semaphore lock-steps
85 private HTTPInputStream makeRequest(String contentType, String content) throws IOException {
87 // Step 1: send the request and establish a semaphore to stop any requests that pipeline after us
88 Semaphore blockOn = null;
89 Semaphore releaseMe = null;
91 if (invalid) throw new HTTPException("connection failed on a previous pipelined call");
94 sendRequest(contentType, content);
95 } catch (IOException e) {
99 blockOn = okToRecieve;
100 releaseMe = okToRecieve = new Semaphore();
103 // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
104 boolean doRelease = true;
106 if (blockOn != null) blockOn.block();
107 if (invalid) throw new HTTPException("connection failed on a previous pipelined call");
109 Hashtable h = in == null ? null : parseHeaders(in);
111 // sometimes the server chooses to close the stream between requests
112 in = null; sock = null;
114 return makeRequest(contentType, content);
117 String reply = h.get("STATUSLINE").toString();
119 if (reply.startsWith("407") || reply.startsWith("401")) {
121 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
122 else doWebAuth(h, content == null ? "GET" : "POST");
124 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
125 if (Log.on) Log.log(this, "proxy returned an HTTP/1.0 reply with no content-length...");
126 in = null; sock = null;
128 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
129 new HTTPInputStream(in, cl, releaseMe).close();
132 return makeRequest(contentType, content);
134 } else if (reply.startsWith("2")) {
135 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
136 throw new HTTPException("XWT does not support HTTP/1.0 servers which fail to return the Content-Length header");
137 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
138 HTTPInputStream ret = new HTTPInputStream(in, cl, releaseMe);
143 throw new HTTPException("HTTP Error: " + reply);
147 } catch (IOException e) { invalid = true; throw e;
148 } finally { if (doRelease) releaseMe.release();
153 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
156 * resolves the hostname and returns it as a string in the form "x.y.z.w"
157 * @throws HTTPException if the host falls within a firewalled netblock
159 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
162 if (resolvedHosts.get(host) != null) return;
164 // if all scripts are trustworthy (local FS), continue
165 if (Main.originAddr == null) return;
169 InetAddress addr = InetAddress.getByName(host);
170 byte[] quadbyte = addr.getAddress();
171 if ((quadbyte[0] == 10 ||
172 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
173 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
174 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
176 } catch (UnknownHostException uhe) { }
178 if (Platform.detectProxy() == null) throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
182 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
184 /** Attempts a direct connection */
185 public Socket attemptDirect() {
187 if (Log.verbose) Log.log(this, "attempting to create unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
188 return Platform.getSocket(host, port, ssl, true);
189 } catch (IOException e) {
190 if (Log.on) Log.log(this, "exception in attemptDirect(): " + e);
195 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
196 public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
198 if (Log.verbose) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
200 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
202 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
204 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
205 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
206 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
208 String s = br.readLine();
209 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
210 while (br.readLine().length() > 0) { };
211 ((TinySSL)sock).negotiate();
215 } catch (IOException e) {
216 if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
222 * Implements SOCKSv4 with v4a DNS extension
223 * @see http://www.socks.nec.com/protocol/socks4.protocol
224 * @see http://www.socks.nec.com/protocol/socks4a.protocol
226 public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
228 // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
229 InetAddress addr = null;
230 try { addr = InetAddress.getByName(host); } catch (Exception e) { }
232 if (Log.verbose) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
233 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
236 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
238 DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
239 dos.writeByte(0x04); // SOCKSv4(a)
240 dos.writeByte(0x01); // CONNECT
241 dos.writeShort(port & 0xffff); // port
242 if (addr == null) dos.writeInt(0x00000001); // bogus IP
243 else dos.write(addr.getAddress()); // actual IP
244 dos.writeByte(0x00); // no userid
246 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
249 dos.writeByte(0x00); // hostname null terminator
253 DataInputStream dis = new DataInputStream(sock.getInputStream());
254 dis.readByte(); // reply version
255 byte success = dis.readByte(); // success/fail
256 dis.skip(6); // ip/port
258 if ((int)(success & 0xff) == 90) {
259 if (ssl) ((TinySSL)sock).negotiate();
262 if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
265 } catch (IOException e) {
266 if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
271 /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
272 public Socket attemptPAC(org.xwt.js.JS.Callable pacFunc) {
273 if (Log.verbose) Log.log(this, "evaluating PAC script");
276 org.xwt.js.JS.Array args = new org.xwt.js.JS.Array();
277 args.addElement(url.toString());
278 args.addElement(url.getHost());
279 Object obj = pacFunc.call(args);
280 if (Log.verbose) Log.log(this, " PAC script returned \"" + obj + "\"");
281 pac = obj.toString();
282 } catch (Throwable e) {
283 if (Log.on) Log.log(this, "PAC script threw exception " + e);
287 StringTokenizer st = new StringTokenizer(pac, ";", false);
288 while (st.hasMoreTokens()) {
289 String token = st.nextToken().trim();
290 if (Log.verbose) Log.log(this, " trying \"" + token + "\"...");
293 if (token.startsWith("DIRECT"))
294 ret = attemptDirect();
295 else if (token.startsWith("PROXY"))
296 ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
297 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
298 else if (token.startsWith("SOCKS"))
299 ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
300 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
301 if (ret != null) return ret;
302 } catch (Throwable e) {
303 if (Log.on) Log.log(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
306 if (Log.on) Log.log(this, "all PAC results exhausted");
311 // Everything Else ////////////////////////////////////////////////////////////////////////////
313 private synchronized void connect() throws IOException {
315 if (in == null) in = new BufferedInputStream(sock.getInputStream());
318 // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
319 String url = originalUrl;
320 userInfo = url.substring(url.indexOf("://") + 3);
321 userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
322 if (userInfo.indexOf('@') != -1) {
323 userInfo = userInfo.substring(0, userInfo.indexOf('@'));
324 url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
329 if (url.startsWith("https:")) {
330 this.url = new URL("http" + url.substring(5));
332 } else if (!url.startsWith("http:")) {
333 throw new MalformedURLException("HTTP only supports http/https urls");
335 this.url = new URL(url);
337 if (!skipResolveCheck) resolveAndCheckIfFirewalled(this.url.getHost());
338 port = this.url.getPort();
339 path = this.url.getFile();
340 if (port == -1) port = ssl ? 443 : 80;
341 host = this.url.getHost();
342 if (Log.verbose) Log.log(this, "creating HTTP object for connection to " + host + ":" + port);
344 Proxy pi = Platform.detectProxy();
345 if (sock == null && pi != null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
346 if (sock == null && pi != null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost, pi.httpsProxyPort);
347 if (sock == null && pi != null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
348 if (sock == null && pi != null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
349 proxied = sock != null;
350 if (sock == null) sock = attemptDirect();
351 if (sock == null) throw new HTTPException("unable to contact host " + host);
352 if (in == null) in = new BufferedInputStream(sock.getInputStream());
355 public void sendRequest(String contentType, String content) throws IOException {
357 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
358 if (content != null) {
359 pw.print("POST " + path + " HTTP/1.1\r\n");
360 int contentLength = content.substring(0, 2).equals("\r\n") ?
361 content.length() - 2 :
362 (content.length() - content.indexOf("\r\n\r\n") - 4);
363 pw.print("Content-Length: " + contentLength + "\r\n");
364 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
366 pw.print("GET " + path + " HTTP/1.1\r\n");
369 pw.print("User-Agent: XWT\r\n");
370 pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
371 if (proxied) pw.print("X-RequestOrigin: " + Main.originHost + "\r\n");
373 if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: " + Proxy.Authorization.authorization2 + "\r\n");
374 if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
376 pw.print(content == null ? "\r\n" : content);
381 private void doWebAuth(Hashtable h0, String method) throws IOException {
382 if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
383 Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
385 if (h.get("AUTHTYPE").equals("Basic")) {
386 if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
387 authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("US-ASCII"))));
389 } else if (h.get("AUTHTYPE").equals("Digest")) {
390 if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale"))) throw new HTTPException("username/password rejected");
392 if (path2.startsWith("http://") || path2.startsWith("https://")) {
393 path2 = path2.substring(path2.indexOf("://") + 3);
394 path2 = path2.substring(path2.indexOf('/'));
396 String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" + userInfo.substring(userInfo.indexOf(':') + 1);
397 String A2 = method + ":" + path2;
398 authCache.put(originalUrl,
400 "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
401 "realm=\"" + h.get("realm") + "\", " +
402 "nonce=\"" + h.get("nonce") + "\", " +
403 "uri=\"" + path2 + "\", " +
404 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
405 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
410 throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
414 private void doProxyAuth(Hashtable h0, String method) throws IOException {
415 if (Log.on) Log.log(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
416 Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
417 String style = h.get("AUTHTYPE").toString();
418 String realm = h.get("realm").toString();
420 if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
421 Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), Proxy.Authorization.authorization);
423 if (style.equals("Basic")) {
424 Proxy.Authorization.authorization2 =
425 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("US-ASCII")));
427 } else if (style.equals("Digest")) {
428 String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
429 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
430 String A2 = method + ":" + path;
431 Proxy.Authorization.authorization2 =
433 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) + "\", " +
434 "realm=\"" + h.get("realm") + "\", " +
435 "nonce=\"" + h.get("nonce") + "\", " +
436 "uri=\"" + path + "\", " +
437 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
438 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
444 // HTTPException ///////////////////////////////////////////////////////////////////////////////////
446 static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
449 // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
451 /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
452 public class HTTPInputStream extends FilterInputStream {
454 /** if chunking, the number of bytes remaining in this subset; otherwise the remainder of the chunk */
455 private int length = 0;
457 /** this semaphore will be released when the stream is closed */
458 private Semaphore releaseMe = null;
460 /** indicates that we have encountered the zero-length terminator chunk */
461 boolean chunkedDone = false;
463 /** if we're on the first chunk, we don't pre-read a CRLF */
464 boolean firstChunk = true;
466 /** the length of the entire content body; -1 if chunked */
467 private int contentLength = 0;
468 public int getContentLength() { return contentLength; }
470 HTTPInputStream(InputStream in, int length, Semaphore releaseMe) {
472 this.releaseMe = releaseMe;
473 this.contentLength = length;
474 this.length = length == -1 ? 0 : length;
477 public boolean markSupported() { return false; }
478 public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
479 public long skip(long n) throws IOException { return read(null, -1, (int)n); }
480 public int available() throws IOException {
481 if (contentLength == -1) return java.lang.Math.min(super.available(), length);
482 return super.available();
485 public int read() throws IOException {
486 byte[] b = new byte[1];
487 int ret = read(b, 0, 1);
488 return ret == -1 ? -1 : b[0] & 0xff;
491 private void readChunk() throws IOException {
492 if (chunkedDone) return;
493 if (!firstChunk) super.skip(2); // CRLF
495 String chunkLen = "";
497 int i = super.read();
498 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
500 // FIXME: handle chunking extensions
508 length = Integer.parseInt(chunkLen.trim(), 16);
509 if (length == 0) chunkedDone = true;
512 public int read(byte[] b, int off, int len) throws IOException {
513 boolean good = false;
515 if (length == 0 && contentLength == -1) {
517 if (chunkedDone) { good = true; return -1; }
519 if (length == 0) { good = true; return -1; }
521 if (len > length) len = length;
522 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
529 if (!good) invalid = true;
533 public void close() throws IOException {
534 if (contentLength == -1) {
535 while(!chunkedDone) {
536 if (length != 0) skip(length);
541 if (length != 0) skip(length);
543 if (releaseMe != null) releaseMe.release();
548 // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
550 /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
551 private Hashtable parseHeaders(InputStream in) throws IOException {
552 Hashtable ret = new Hashtable();
554 // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
555 byte[] buf = new byte[4096];
558 int read = in.read();
559 if (read == -1 && buflen == 0) return null;
560 if (read == -1) throw new HTTPException("stream closed while reading headers");
561 buf[buflen++] = (byte)read;
562 if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
563 if (buflen == buf.length) {
564 byte[] newbuf = new byte[buf.length * 2];
565 System.arraycopy(buf, 0, newbuf, 0, buflen);
570 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
571 String s = br.readLine();
572 if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
573 ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
574 ret.put("HTTP", s.substring(5, s.indexOf(' ')));
576 while((s = br.readLine()) != null && s.length() > 0) {
577 String front = s.substring(0, s.indexOf(':')).toLowerCase();
578 String back = s.substring(s.indexOf(':') + 1).trim();
579 // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
580 if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
581 ret.put(front, back);
586 private Hashtable parseAuthenticationChallenge(String s) {
587 Hashtable ret = new Hashtable();
590 ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
591 s = s.substring(s.indexOf(' ')).trim();
593 while (s.length() > 0) {
595 String key = s.substring(0, s.indexOf('='));
596 s = s.substring(s.indexOf('=') + 1);
597 if (s.charAt(0) == '\"') {
599 val = s.substring(0, s.indexOf('\"'));
600 s = s.substring(s.indexOf('\"') + 1);
602 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
603 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
605 if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
612 private String H(String s) throws IOException {
613 byte[] b = s.getBytes("US-ASCII");
614 MD5Digest md5 = new MD5Digest();
615 md5.update(b, 0, b.length);
616 byte[] out = new byte[md5.getDigestSize()];
619 for(int i=0; i<out.length; i++) {
620 ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
621 ret += "0123456789abcdef".charAt(out[i] & 0x0f);
627 // Proxy ///////////////////////////////////////////////////////////
629 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
630 public static class Proxy {
634 /** the HTTP Proxy host to use */
635 public String httpProxyHost = null;
637 /** the HTTP Proxy port to use */
638 public int httpProxyPort = -1;
640 /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
641 public String httpsProxyHost = null;
643 /** if a seperate proxy should be used for HTTPS, this is the port */
644 public int httpsProxyPort = -1;
646 /** the SOCKS Proxy Host to use */
647 public String socksProxyHost = null;
649 /** the SOCKS Proxy Port to use */
650 public int socksProxyPort = -1;
652 /** hosts to be excluded from proxy use; wildcards permitted */
653 public String[] excluded = null;
655 /** the PAC script */
656 public JS.Callable proxyAutoConfigFunction = null;
658 public static Proxy detectProxyViaManual() {
659 Proxy ret = new Proxy();
661 ret.httpProxyHost = Platform.getEnv("http_proxy");
662 if (ret.httpProxyHost != null) {
663 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
664 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
665 if (ret.httpProxyHost.indexOf(':') != -1) {
666 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
667 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
669 ret.httpProxyPort = 80;
673 ret.httpsProxyHost = Platform.getEnv("https_proxy");
674 if (ret.httpsProxyHost != null) {
675 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
676 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
677 if (ret.httpsProxyHost.indexOf(':') != -1) {
678 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
679 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
681 ret.httpsProxyPort = 80;
685 ret.socksProxyHost = Platform.getEnv("socks_proxy");
686 if (ret.socksProxyHost != null) {
687 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
688 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
689 if (ret.socksProxyHost.indexOf(':') != -1) {
690 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
691 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
693 ret.socksProxyPort = 80;
697 String noproxy = Platform.getEnv("no_proxy");
698 if (noproxy != null) {
699 StringTokenizer st = new StringTokenizer(noproxy, ",");
700 ret.excluded = new String[st.countTokens()];
701 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
704 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
708 public static JS.Scope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
709 public static JS.Callable getProxyAutoConfigFunction(String url) {
711 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
714 while((s = br.readLine()) != null) script += s + "\n";
715 if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
716 if (Log.on) Log.log(Proxy.class, script);
719 Vector carpHosts = new Vector();
720 for(int i=0; i<script.length(); i++)
721 if (script.regionMatches(i, "new Node(", 0, 9)) {
722 String host = script.substring(i + 10, script.indexOf('\"', i + 11));
723 if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
724 carpHosts.addElement(host);
726 if (carpHosts.size() > 0) {
727 script = "function FindProxyForURL(url, host) {\nreturn \"";
728 for(int i=0; i<carpHosts.size(); i++)
729 script += "PROXY " + carpHosts.elementAt(i) + "; ";
731 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
732 if (Log.on) Log.log(Proxy.class, script);
735 JS.CompiledFunction scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
736 scr.call(new JS.Array(), proxyAutoConfigRootScope);
737 return (JS.Callable)proxyAutoConfigRootScope.get("FindProxyForURL");
738 } catch (Exception e) {
740 Log.log(Platform.class, "WPAD detection failed due to:");
741 if (e instanceof JS.Exn) {
743 org.xwt.js.JS.Array arr = new org.xwt.js.JS.Array();
744 arr.addElement(((JS.Exn)e).getObject());
746 //XWT.recursivePrintObject.call();
747 } catch (Exception e2) {
748 Log.log(Platform.class, e);
751 else Log.log(Platform.class, e);
758 // Authorization ///////////////////////////////////////////////////////////////////////////////////
760 public static class Authorization {
762 static public String authorization = null;
763 static public String authorization2 = null;
764 static public Semaphore waitingForUser = new Semaphore();
766 public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
768 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
769 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
770 // a password, so we should reattempt authorization.
772 if (authorization != oldAuth) return;
773 if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
774 MessageQueue.add(new Message() {
775 public void perform() {
777 Template.getTemplate("org.xwt.builtin.proxy_authorization", null).apply(b, null, null, null, 0, 0);
778 b.put("realm", realm);
779 b.put("proxyIP", proxyIP);
783 waitingForUser.block();
784 if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
790 // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
792 public static class ProxyAutoConfigRootScope extends JS.Scope {
794 public ProxyAutoConfigRootScope() { super(null); }
796 // FIXME: needs "standard objects"
798 public Object get(Object name) {
799 if (name.equals("isPlainHostName")) return isPlainHostName;
800 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
801 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
802 else if (name.equals("isResolvable")) return isResolvable;
803 else if (name.equals("isInNet")) return isInNet;
804 else if (name.equals("dnsResolve")) return dnsResolve;
805 else if (name.equals("myIpAddress")) return myIpAddress;
806 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
807 else if (name.equals("shExpMatch")) return shExpMatch;
808 else if (name.equals("weekdayRange")) return weekdayRange;
809 else if (name.equals("dateRange")) return dateRange;
810 else if (name.equals("timeRange")) return timeRange;
811 else if (name.equals("ProxyConfig")) return ProxyConfig;
812 else return super.get(name);
815 private static final JS.Obj proxyConfigBindings = new JS.Obj();
816 private static final JS.Obj ProxyConfig = new JS.Obj() {
817 public Object get(Object name) {
818 if (name.equals("bindings")) return proxyConfigBindings;
823 private static final JS.Callable isPlainHostName = new JS.Callable() {
824 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
825 return (args.elementAt(0).toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
829 private static final JS.Callable dnsDomainIs = new JS.Callable() {
830 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
831 return (args.elementAt(0).toString().endsWith(args.elementAt(1).toString())) ? Boolean.TRUE : Boolean.FALSE;
835 private static final JS.Callable localHostOrDomainIs = new JS.Callable() {
836 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
837 return (args.elementAt(0).toString().equals(args.elementAt(1).toString()) ||
838 (args.elementAt(0).toString().indexOf('.') == -1 && args.elementAt(1).toString().startsWith(args.elementAt(0).toString()))) ?
839 Boolean.TRUE : Boolean.FALSE;
843 private static final JS.Callable isResolvable = new JS.Callable() {
844 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
846 return (InetAddress.getByName(args.elementAt(0).toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
847 } catch (UnknownHostException e) {
848 return Boolean.FALSE;
853 private static final JS.Callable isInNet = new JS.Callable() {
854 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
855 if (args.length() != 3) return Boolean.FALSE;
857 byte[] host = InetAddress.getByName(args.elementAt(0).toString()).getAddress();
858 byte[] net = InetAddress.getByName(args.elementAt(1).toString()).getAddress();
859 byte[] mask = InetAddress.getByName(args.elementAt(2).toString()).getAddress();
860 return ((host[0] & mask[0]) == net[0] &&
861 (host[1] & mask[1]) == net[1] &&
862 (host[2] & mask[2]) == net[2] &&
863 (host[3] & mask[3]) == net[3]) ?
864 Boolean.TRUE : Boolean.FALSE;
865 } catch (Exception e) {
866 throw new JS.Exn("exception in isInNet(): " + e);
871 private static final JS.Callable dnsResolve = new JS.Callable() {
872 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
874 return InetAddress.getByName(args.elementAt(0).toString()).getHostAddress();
875 } catch (UnknownHostException e) {
881 private static final JS.Callable myIpAddress = new JS.Callable() {
882 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
884 return InetAddress.getLocalHost().getHostAddress();
885 } catch (UnknownHostException e) {
886 if (Log.on) Log.log(this, "strange... host does not know its own address");
892 private static final JS.Callable dnsDomainLevels = new JS.Callable() {
893 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
894 String s = args.elementAt(0).toString();
896 while((i = s.indexOf('.', i)) != -1) i++;
897 return new Integer(i);
901 private static boolean match(String[] arr, String s, int index) {
902 if (index >= arr.length) return true;
903 for(int i=0; i<s.length(); i++) {
904 String s2 = s.substring(i);
905 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
910 private static final JS.Callable shExpMatch = new JS.Callable() {
911 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
912 StringTokenizer st = new StringTokenizer(args.elementAt(1).toString(), "*", false);
913 String[] arr = new String[st.countTokens()];
914 String s = args.elementAt(0).toString();
915 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
916 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
920 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
922 private static final JS.Callable weekdayRange = new JS.Callable() {
923 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
924 TimeZone tz = (args.length() < 3 || args.elementAt(2) == null || !args.elementAt(2).equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
925 Calendar c = new GregorianCalendar();
927 c.setTime(new java.util.Date());
928 java.util.Date d = c.getTime();
929 int day = d.getDay();
931 String d1s = args.elementAt(0).toString().toUpperCase();
933 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
935 if (args.length() == 1)
936 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
938 String d2s = args.elementAt(1).toString().toUpperCase();
939 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
942 ((d1 <= d2 && day >= d1 && day <= d2) ||
943 (d1 > d2 && (day >= d1 || day <= d2))) ?
944 Boolean.TRUE : Boolean.FALSE;
948 private static final JS.Callable dateRange = new JS.Callable() {
949 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
950 throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
954 private static final JS.Callable timeRange = new JS.Callable() {
955 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
956 throw new JS.Exn("XWT does not support timeRange() in PAC scripts");