2003/09/27 09:08:26
[org.ibex.core.git] / src / org / xwt / HTTP.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.net.*;
5 import java.io.*;
6 import java.util.*;
7 import org.xwt.js.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10 import org.bouncycastle.crypto.digests.*;
11
12 /**
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.
15  */
16 public class HTTP {
17
18     /** the URL as passed to the original constructor; this is never changed */
19     final String originalUrl;
20
21     /** the URL to connect to; this is munged when the url is parsed */
22     URL url = null;
23
24     /** the host to connect to */
25     String host = null;
26
27     /** the port to connect on */
28     int port = -1;
29
30     /** true if SSL (HTTPS) should be used */
31     boolean ssl = false;
32
33     /** the path (URI) to retrieve on the server */
34     String path = null;
35
36     /** the socket */
37     Socket sock = null;
38
39     /** the socket's inputstream */
40     InputStream in = null;
41
42     /** the username and password portions of the URL */
43     String userInfo = null;
44
45     /** cache of userInfo strings, keyed on originalUrl */
46     private static Hashtable authCache = new Hashtable();
47
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
51      */
52     Semaphore okToRecieve = null;
53
54     /** cache for resolveAndCheckIfFirewalled() */
55     static Hashtable resolvedHosts = new Hashtable();
56
57     /** if any request encounters an IOException, the entire HTTP connection is invalidated */
58     boolean invalid = false;
59
60     /** true iff we are allowed to skip the resolve check (only allowed when we're downloading the PAC script) */
61     boolean skipResolveCheck = false;
62
63     /** true iff we're using a proxy */
64     boolean proxied = false;
65
66
67     // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
68
69     public HTTP(String url) { this(url, false); }
70     public HTTP(String url, boolean skipResolveCheck) {
71         originalUrl = url;
72         this.skipResolveCheck = skipResolveCheck;
73     }
74
75     /** Performs an HTTP GET request */
76     public InputStream GET() throws IOException { return makeRequest(null, null); }
77
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 InputStream POST(String contentType, String content) throws IOException { return makeRequest(contentType, content); }
80
81     /**
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
84      */
85     private InputStream makeRequest(String contentType, String content) throws IOException {
86
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;
90         synchronized(this) {
91             if (invalid) throw new HTTPException("connection failed on a previous pipelined call");
92             try {
93                 connect();
94                 sendRequest(contentType, content);
95             } catch (IOException e) {
96                 invalid = true;
97                 throw e;
98             }
99             blockOn = okToRecieve;
100             releaseMe = okToRecieve = new Semaphore();
101         }
102         
103         // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
104         boolean doRelease = true;
105         try {
106             if (blockOn != null) blockOn.block();
107             if (invalid) throw new HTTPException("connection failed on a previous pipelined call");
108             
109             Hashtable h = in == null ? null : parseHeaders(in);
110             if (h == null) {
111                 // sometimes the server chooses to close the stream between requests
112                 in = null; sock = null;
113                 releaseMe.release();
114                 return makeRequest(contentType, content);
115             }
116
117             String reply = h.get("STATUSLINE").toString();
118             
119             if (reply.startsWith("407") || reply.startsWith("401")) {
120                 
121                 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
122                 else doWebAuth(h, content == null ? "GET" : "POST");
123                 
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;
127                 } else {
128                     int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
129                     new HTTPInputStream(in, cl, releaseMe).close();
130                 }
131                 releaseMe.release();
132                 return makeRequest(contentType, content);
133                 
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                 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
139                 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
140                 doRelease = false;
141                 return ret;
142                 
143             } else {
144                 throw new HTTPException("HTTP Error: " + reply);
145                 
146             }
147             
148         } catch (IOException e) { invalid = true; throw e;
149         } finally { if (doRelease) releaseMe.release();
150         }
151     }
152
153
154     // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
155
156     /**
157      *  resolves the hostname and returns it as a string in the form "x.y.z.w"
158      *  @throws HTTPException if the host falls within a firewalled netblock
159      */
160     private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
161
162         // cached
163         if (resolvedHosts.get(host) != null) return;
164
165         // if all scripts are trustworthy (local FS), continue
166         if (Main.originAddr == null) return;
167
168         // resolve using DNS
169         try {
170             InetAddress addr = InetAddress.getByName(host);
171             byte[] quadbyte = addr.getAddress();
172             if ((quadbyte[0] == 10 ||
173                  (quadbyte[0] == 192 && quadbyte[1] == 168) ||
174                  (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
175                 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
176             return;
177         } catch (UnknownHostException uhe) { }
178
179         if (Platform.detectProxy() == null) throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
180         if (Log.on) Log.log(this, "  could not resolve host " + host + "; using xmlrpc.xwt.org to ensure security");
181         try {
182             JS.Array args = new JS.Array();
183             args.addElement(host);
184             Object ret = new XMLRPC("http://xmlrpc.xwt.org/RPC2/", "dns.resolve").call(args);
185             if (ret == null || !(ret instanceof String)) throw new Exception("    xmlrpc.xwt.org returned non-String: " + ret);
186             resolvedHosts.put(host, ret);
187             return;
188         } catch (Throwable e) {
189             throw new HTTPException("exception while attempting to use xmlrpc.xwt.org to resolve " + host + ": " + e);
190         }
191     }
192
193
194     // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
195
196     /** Attempts a direct connection */
197     public Socket attemptDirect() {
198         try {
199             if (Log.verbose) Log.log(this, "attempting to create unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
200             return Platform.getSocket(host, port, ssl, true);
201         } catch (IOException e) {
202             if (Log.on) Log.log(this, "exception in attemptDirect(): " + e);
203             return null;
204         }
205     }
206
207     /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
208     public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
209         try {
210             if (Log.verbose) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
211
212             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
213             if (!ssl) {
214                 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
215             } else {
216                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
217                 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
218                 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
219                 pw.flush();
220                 String s = br.readLine();
221                 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
222                 while (br.readLine().length() > 0) { };
223                 ((TinySSL)sock).negotiate();
224             }
225             return sock;
226
227         } catch (IOException e) {
228             if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
229             return null;
230         }
231     }
232
233     /**
234      *  Implements SOCKSv4 with v4a DNS extension
235      *  @see http://www.socks.nec.com/protocol/socks4.protocol
236      *  @see http://www.socks.nec.com/protocol/socks4a.protocol
237      */
238     public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
239
240         // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
241         InetAddress addr = null;
242         try { addr = InetAddress.getByName(host); } catch (Exception e) { }
243
244         if (Log.verbose) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
245                                  " proxied socket using proxy " + proxyHost + ":" + proxyPort);
246
247         try {
248             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
249             
250             DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
251             dos.writeByte(0x04);                         // SOCKSv4(a)
252             dos.writeByte(0x01);                         // CONNECT
253             dos.writeShort(port & 0xffff);               // port
254             if (addr == null) dos.writeInt(0x00000001);  // bogus IP
255             else dos.write(addr.getAddress());           // actual IP
256             dos.writeByte(0x00);                         // no userid
257             if (addr == null) {
258                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
259                 pw.print(host);
260                 pw.flush();
261                 dos.writeByte(0x00);                     // hostname null terminator
262             }
263             dos.flush();
264
265             DataInputStream dis = new DataInputStream(sock.getInputStream());
266             dis.readByte();                              // reply version
267             byte success = dis.readByte();               // success/fail
268             dis.skip(6);                                 // ip/port
269             
270             if ((int)(success & 0xff) == 90) {
271                 if (ssl) ((TinySSL)sock).negotiate();
272                 return sock;
273             }
274             if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
275             return null;
276
277         } catch (IOException e) {
278             if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
279             return null;
280         }
281     }
282
283     /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
284     public Socket attemptPAC(org.xwt.js.JS.Callable pacFunc) {
285         if (Log.verbose) Log.log(this, "evaluating PAC script");
286         String pac = null;
287         try {
288             org.xwt.js.JS.Array args = new org.xwt.js.JS.Array();
289             args.addElement(url.toString());
290             args.addElement(url.getHost());
291             Object obj = pacFunc.call(args);
292             if (Log.verbose) Log.log(this, "  PAC script returned \"" + obj + "\"");
293             pac = obj.toString();
294         } catch (Throwable e) {
295             if (Log.on) Log.log(this, "PAC script threw exception " + e);
296             return null;
297         }
298
299         StringTokenizer st = new StringTokenizer(pac, ";", false);
300         while (st.hasMoreTokens()) {
301             String token = st.nextToken().trim();
302             if (Log.verbose) Log.log(this, "  trying \"" + token + "\"...");
303             try {
304                 Socket ret = null;
305                 if (token.startsWith("DIRECT"))
306                     ret = attemptDirect();
307                 else if (token.startsWith("PROXY"))
308                     ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
309                                            Integer.parseInt(token.substring(token.indexOf(':') + 1)));
310                 else if (token.startsWith("SOCKS"))
311                     ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
312                                             Integer.parseInt(token.substring(token.indexOf(':') + 1)));
313                 if (ret != null) return ret;
314             } catch (Throwable e) {
315                 if (Log.on) Log.log(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
316             }
317         }
318         if (Log.on) Log.log(this, "all PAC results exhausted");
319         return null;
320     }
321
322
323     // Everything Else ////////////////////////////////////////////////////////////////////////////
324
325     private synchronized void connect() throws IOException {
326         if (originalUrl.equals("stdio:")) {
327             in = new BufferedInputStream(System.in);
328             return;
329         }
330         if (sock != null) {
331             if (in == null) in = new BufferedInputStream(sock.getInputStream());
332             return;
333         }
334         // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
335         String url = originalUrl;
336         userInfo = url.substring(url.indexOf("://") + 3);
337         userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
338         if (userInfo.indexOf('@') != -1) {
339             userInfo = userInfo.substring(0, userInfo.indexOf('@'));
340             url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
341         } else {
342             userInfo = null;
343         }
344
345         if (url.startsWith("https:")) {
346             this.url = new URL("http" + url.substring(5));
347             ssl = true;
348         } else if (!url.startsWith("http:")) {
349             throw new MalformedURLException("HTTP only supports http/https urls");
350         } else {
351             this.url = new URL(url);
352         }
353         if (!skipResolveCheck) resolveAndCheckIfFirewalled(this.url.getHost());
354         port = this.url.getPort();
355         path = this.url.getFile();
356         if (port == -1) port = ssl ? 443 : 80;
357         host = this.url.getHost();
358         if (Log.verbose) Log.log(this, "creating HTTP object for connection to " + host + ":" + port);
359
360         Proxy pi = Platform.detectProxy();
361         if (sock == null && pi != null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
362         if (sock == null && pi != null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost, pi.httpsProxyPort);
363         if (sock == null && pi != null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
364         if (sock == null && pi != null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
365         proxied = sock != null;
366         if (sock == null) sock = attemptDirect();
367         if (sock == null) throw new HTTPException("unable to contact host " + host);
368         if (in == null) in = new BufferedInputStream(sock.getInputStream());
369     }
370
371     public void sendRequest(String contentType, String content) throws IOException {
372
373         PrintWriter pw = new PrintWriter(new OutputStreamWriter(originalUrl.equals("stdio:") ? System.out : sock.getOutputStream()));
374         if (content != null) {
375             pw.print("POST " + path + " HTTP/1.1\r\n");
376             int contentLength = content.substring(0, 2).equals("\r\n") ?
377                 content.length() - 2 :
378                 (content.length() - content.indexOf("\r\n\r\n") - 4);
379             pw.print("Content-Length: " + contentLength + "\r\n");
380             if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
381         } else {
382             pw.print("GET " + path + " HTTP/1.1\r\n");
383         }
384         
385         pw.print("User-Agent: XWT\r\n");
386         pw.print("Accept-encoding: gzip\r\n");
387         pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
388         if (proxied) pw.print("X-RequestOrigin: " + Main.originHost + "\r\n");
389
390         if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: " + Proxy.Authorization.authorization2 + "\r\n");
391         if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
392
393         pw.print(content == null ? "\r\n" : content);
394         pw.print("\r\n");
395         pw.flush();
396     }
397
398     private void doWebAuth(Hashtable h0, String method) throws IOException {
399         if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
400         Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
401         
402         if (h.get("AUTHTYPE").equals("Basic")) {
403             if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
404             authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("US-ASCII"))));
405             
406         } else if (h.get("AUTHTYPE").equals("Digest")) {
407             if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale"))) throw new HTTPException("username/password rejected");
408             String path2 = path;
409             if (path2.startsWith("http://") || path2.startsWith("https://")) {
410                 path2 = path2.substring(path2.indexOf("://") + 3);
411                 path2 = path2.substring(path2.indexOf('/'));
412             }
413             String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" + userInfo.substring(userInfo.indexOf(':') + 1);
414             String A2 = method + ":" + path2;
415             authCache.put(originalUrl,
416                           "Digest " +
417                           "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
418                           "realm=\"" + h.get("realm") + "\", " +
419                           "nonce=\"" + h.get("nonce") + "\", " +
420                           "uri=\"" + path2 + "\", " +
421                           (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) + 
422                           "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
423                           "algorithm=MD5"
424                           );
425             
426         } else {
427             throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
428         }
429     }
430
431     private void doProxyAuth(Hashtable h0, String method) throws IOException {
432         if (Log.on) Log.log(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
433         Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
434         String style = h.get("AUTHTYPE").toString();
435         String realm = h.get("realm").toString();
436
437         if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
438             Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), Proxy.Authorization.authorization);
439
440         if (style.equals("Basic")) {
441             Proxy.Authorization.authorization2 =
442                 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("US-ASCII")));
443             
444         } else if (style.equals("Digest")) {
445             String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
446                 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
447             String A2 = method + ":" + path;
448             Proxy.Authorization.authorization2 = 
449                 "Digest " +
450                 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) + "\", " +
451                 "realm=\"" + h.get("realm") + "\", " +
452                 "nonce=\"" + h.get("nonce") + "\", " +
453                 "uri=\"" + path + "\", " +
454                 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) + 
455                 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
456                 "algorithm=MD5";
457         }            
458     }
459
460
461     // HTTPException ///////////////////////////////////////////////////////////////////////////////////
462
463     static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
464
465
466     // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
467
468     /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
469     public class HTTPInputStream extends FilterInputStream {
470
471         /** if chunking, the number of bytes remaining in this subset; otherwise the remainder of the chunk */
472         private int length = 0;
473
474         /** this semaphore will be released when the stream is closed */
475         private Semaphore releaseMe = null;
476
477         /** indicates that we have encountered the zero-length terminator chunk */
478         boolean chunkedDone = false;
479
480         /** if we're on the first chunk, we don't pre-read a CRLF */
481         boolean firstChunk = true;
482
483         /** the length of the entire content body; -1 if chunked */
484         private int contentLength = 0;
485         public int getContentLength() { return contentLength; }
486
487         HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
488             super(in);
489             this.releaseMe = releaseMe;
490             this.contentLength = length;
491             this.length = length == -1 ? 0 : length;
492         }
493
494         public boolean markSupported() { return false; }
495         public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
496         public long skip(long n) throws IOException { return read(null, -1, (int)n); }
497         public int available() throws IOException {
498             if (contentLength == -1) return java.lang.Math.min(super.available(), length);
499             return super.available();
500         }
501
502         public int read() throws IOException {
503             byte[] b = new byte[1];
504             int ret = read(b, 0, 1);
505             return ret == -1 ? -1 : b[0] & 0xff;
506         }
507
508         private void readChunk() throws IOException {
509             if (chunkedDone) return;
510             if (!firstChunk) super.skip(2); // CRLF
511             firstChunk = false;
512             String chunkLen = "";
513             while(true) {
514                 int i = super.read();
515                 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
516
517                 // FEATURE: handle chunking extensions
518                 if (i == '\r') {
519                     super.read();    // LF
520                     break;
521                 } else {
522                     chunkLen += (char)i;
523                 }
524             }
525             length = Integer.parseInt(chunkLen.trim(), 16);
526             if (length == 0) chunkedDone = true;
527         }
528
529         public int read(byte[] b, int off, int len) throws IOException {
530             boolean good = false;
531             try {
532                 if (length == 0 && contentLength == -1) {
533                     readChunk();
534                     if (chunkedDone) { good = true; return -1; }
535                 } else {
536                     if (length == 0) { good = true; return -1; }
537                 }
538                 if (len > length) len = length;
539                 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
540                 if (ret >= 0) {
541                     length -= ret;
542                     good = true;
543                 }
544                 return ret;
545             } finally {
546                 if (!good) invalid = true;
547             }
548         }
549
550         public void close() throws IOException {
551             if (contentLength == -1) {
552                 while(!chunkedDone) {
553                     if (length != 0) skip(length);
554                     readChunk();
555                 }
556                 skip(2);
557             } else {
558                 if (length != 0) skip(length);
559             }
560             if (releaseMe != null) releaseMe.release();
561         }
562     }
563
564
565     // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
566
567     /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
568     private Hashtable parseHeaders(InputStream in) throws IOException {
569         Hashtable ret = new Hashtable();
570
571         // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
572         byte[] buf = new byte[4096];
573         int buflen = 0;
574         while(true) {
575             int read = in.read();
576             if (read == -1 && buflen == 0) return null;
577             if (read == -1) throw new HTTPException("stream closed while reading headers");
578             buf[buflen++] = (byte)read;
579             if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
580             if (buflen == buf.length) {
581                 byte[] newbuf = new byte[buf.length * 2];
582                 System.arraycopy(buf, 0, newbuf, 0, buflen);
583                 buf = newbuf;
584             }
585         }
586
587         BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
588         String s = br.readLine();
589         if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
590         ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
591         ret.put("HTTP", s.substring(5, s.indexOf(' ')));
592
593         while((s = br.readLine()) != null && s.length() > 0) {
594             String front = s.substring(0, s.indexOf(':')).toLowerCase();
595             String back = s.substring(s.indexOf(':') + 1).trim();
596             // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
597             if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
598             ret.put(front, back);
599         }
600         return ret;
601     }
602
603     private Hashtable parseAuthenticationChallenge(String s) {
604         Hashtable ret = new Hashtable();
605
606         s = s.trim();
607         ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
608         s = s.substring(s.indexOf(' ')).trim();
609
610         while (s.length() > 0) {
611             String val = null;
612             String key = s.substring(0, s.indexOf('='));
613             s = s.substring(s.indexOf('=') + 1);
614             if (s.charAt(0) == '\"') {
615                 s = s.substring(1);
616                 val = s.substring(0, s.indexOf('\"'));
617                 s = s.substring(s.indexOf('\"') + 1);
618             } else {
619                 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
620                 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
621             }
622             if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
623             s = s.trim();
624             ret.put(key, val);
625         }
626         return ret;
627     }
628
629     private String H(String s) throws IOException {
630         byte[] b = s.getBytes("US-ASCII");
631         MD5Digest md5 = new MD5Digest();
632         md5.update(b, 0, b.length);
633         byte[] out = new byte[md5.getDigestSize()];
634         md5.doFinal(out, 0);
635         String ret = "";
636         for(int i=0; i<out.length; i++) {
637             ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
638             ret += "0123456789abcdef".charAt(out[i] & 0x0f);
639         }
640         return ret;
641     }
642
643
644     // Proxy ///////////////////////////////////////////////////////////
645
646     /** encapsulates most of the proxy logic; some is shared in HTTP.java */
647     public static class Proxy {
648         
649         public Proxy() { }
650         
651         /** the HTTP Proxy host to use */
652         public String httpProxyHost = null;
653         
654         /** the HTTP Proxy port to use */
655         public int httpProxyPort = -1;
656         
657         /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
658         public String httpsProxyHost = null;
659     
660         /** if a seperate proxy should be used for HTTPS, this is the port */
661         public int httpsProxyPort = -1;
662     
663         /** the SOCKS Proxy Host to use */
664         public String socksProxyHost = null;
665     
666         /** the SOCKS Proxy Port to use */
667         public int socksProxyPort = -1;
668     
669         /** hosts to be excluded from proxy use; wildcards permitted */
670         public String[] excluded = null;
671     
672         /** the PAC script */
673         public JS.Callable proxyAutoConfigFunction = null;
674     
675         public static Proxy detectProxyViaManual() {
676             Proxy ret = new Proxy();
677         
678             ret.httpProxyHost = Platform.getEnv("http_proxy");
679             if (ret.httpProxyHost != null) {
680                 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
681                 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
682                 if (ret.httpProxyHost.indexOf(':') != -1) {
683                     ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
684                     ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
685                 } else {
686                     ret.httpProxyPort = 80;
687                 }
688             }
689         
690             ret.httpsProxyHost = Platform.getEnv("https_proxy");
691             if (ret.httpsProxyHost != null) {
692                 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
693                 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
694                 if (ret.httpsProxyHost.indexOf(':') != -1) {
695                     ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
696                     ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
697                 } else {
698                     ret.httpsProxyPort = 80;
699                 }
700             }
701         
702             ret.socksProxyHost = Platform.getEnv("socks_proxy");
703             if (ret.socksProxyHost != null) {
704                 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
705                 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
706                 if (ret.socksProxyHost.indexOf(':') != -1) {
707                     ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
708                     ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
709                 } else {
710                     ret.socksProxyPort = 80;
711                 }
712             }
713         
714             String noproxy = Platform.getEnv("no_proxy");
715             if (noproxy != null) {
716                 StringTokenizer st = new StringTokenizer(noproxy, ",");
717                 ret.excluded = new String[st.countTokens()];
718                 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
719             }
720         
721             if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
722             return ret;
723         }
724     
725         public static JS.Scope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
726         public static JS.Callable getProxyAutoConfigFunction(String url) {
727             try { 
728                 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
729                 String s = null;
730                 String script = "";
731                 while((s = br.readLine()) != null) script += s + "\n";
732                 if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
733                 if (Log.on) Log.log(Proxy.class, script);
734             
735                 // MS CARP hack
736                 Vector carpHosts = new Vector();
737                 for(int i=0; i<script.length(); i++)
738                     if (script.regionMatches(i, "new Node(", 0, 9)) {
739                         String host = script.substring(i + 10, script.indexOf('\"', i + 11));
740                         if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
741                         carpHosts.addElement(host);
742                     }
743                 if (carpHosts.size() > 0) {
744                     script = "function FindProxyForURL(url, host) {\nreturn \"";
745                     for(int i=0; i<carpHosts.size(); i++)
746                         script += "PROXY " + carpHosts.elementAt(i) + "; ";
747                     script += "\";\n}";
748                     if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
749                     if (Log.on) Log.log(Proxy.class, script);
750                 }
751
752                 JS.CompiledFunction scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
753                 scr.call(new JS.Array(), proxyAutoConfigRootScope);
754                 return (JS.Callable)proxyAutoConfigRootScope.get("FindProxyForURL");
755             } catch (Exception e) {
756                 if (Log.on) {
757                     Log.log(Platform.class, "WPAD detection failed due to:");
758                     if (e instanceof JS.Exn) {
759                         try {
760                             org.xwt.js.JS.Array arr = new org.xwt.js.JS.Array();
761                             arr.addElement(((JS.Exn)e).getObject());
762                         } catch (Exception e2) {
763                             Log.log(Platform.class, e);
764                         }
765                     }
766                     else Log.log(Platform.class, e);
767                 }
768                 return null;
769             }
770         }
771
772
773         // Authorization ///////////////////////////////////////////////////////////////////////////////////
774
775         public static class Authorization {
776
777             static public String authorization = null;
778             static public String authorization2 = null;
779             static public Semaphore waitingForUser = new Semaphore();
780
781             public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
782
783                 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
784                 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
785                 // a password, so we should reattempt authorization.
786
787                 if (authorization != oldAuth) return;
788                 if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
789                 Message.Q.add(new Message() {
790                         public void perform() {
791                             Box b = new Box();
792                             Template t = Template.getTemplate((Res)Main.builtin.get("org/xwt/builtin/proxy_authorization.xwt"));
793                             t.apply(b, null, null);
794                             b.put("realm", realm);
795                             b.put("proxyIP", proxyIP);
796                         }
797                     });
798
799                 waitingForUser.block();
800                 if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
801             
802             }
803         }
804
805
806         // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
807
808         public static class ProxyAutoConfigRootScope extends JS.GlobalScope {
809
810             public ProxyAutoConfigRootScope() { super(null); }
811         
812             public Object get(Object name) {
813                 if (name.equals("isPlainHostName")) return isPlainHostName;
814                 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
815                 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
816                 else if (name.equals("isResolvable")) return isResolvable;
817                 else if (name.equals("isInNet")) return isInNet;
818                 else if (name.equals("dnsResolve")) return dnsResolve;
819                 else if (name.equals("myIpAddress")) return myIpAddress;
820                 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
821                 else if (name.equals("shExpMatch")) return shExpMatch;
822                 else if (name.equals("weekdayRange")) return weekdayRange;
823                 else if (name.equals("dateRange")) return dateRange;
824                 else if (name.equals("timeRange")) return timeRange;
825                 else if (name.equals("ProxyConfig")) return ProxyConfig;
826                 else return super.get(name);
827             }
828         
829             private static final JS.Obj proxyConfigBindings = new JS.Obj();
830             private static final JS.Obj ProxyConfig = new JS.Obj() {
831                     public Object get(Object name) {
832                         if (name.equals("bindings")) return proxyConfigBindings;
833                         return null;
834                     }
835                 };
836         
837             private static final JS.Callable isPlainHostName = new JS.Callable() {
838                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
839                         return (args.elementAt(0).toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
840                     }
841                 };
842         
843             private static final JS.Callable dnsDomainIs = new JS.Callable() {
844                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
845                         return (args.elementAt(0).toString().endsWith(args.elementAt(1).toString())) ? Boolean.TRUE : Boolean.FALSE;
846                     }
847                 };
848         
849             private static final JS.Callable localHostOrDomainIs = new JS.Callable() {
850                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
851                         return (args.elementAt(0).toString().equals(args.elementAt(1).toString()) || 
852                                 (args.elementAt(0).toString().indexOf('.') == -1 && args.elementAt(1).toString().startsWith(args.elementAt(0).toString()))) ?
853                             Boolean.TRUE : Boolean.FALSE;
854                     }
855                 };
856         
857             private static final JS.Callable isResolvable = new JS.Callable() {
858                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
859                         try {
860                             return (InetAddress.getByName(args.elementAt(0).toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
861                         } catch (UnknownHostException e) {
862                             return Boolean.FALSE;
863                         }
864                     }
865                 };
866         
867             private static final JS.Callable isInNet = new JS.Callable() {
868                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
869                         if (args.length() != 3) return Boolean.FALSE;
870                         try {
871                             byte[] host = InetAddress.getByName(args.elementAt(0).toString()).getAddress();
872                             byte[] net = InetAddress.getByName(args.elementAt(1).toString()).getAddress();
873                             byte[] mask = InetAddress.getByName(args.elementAt(2).toString()).getAddress();
874                             return ((host[0] & mask[0]) == net[0] &&
875                                     (host[1] & mask[1]) == net[1] &&
876                                     (host[2] & mask[2]) == net[2] &&
877                                     (host[3] & mask[3]) == net[3]) ?
878                                 Boolean.TRUE : Boolean.FALSE;
879                         } catch (Exception e) {
880                             throw new JS.Exn("exception in isInNet(): " + e);
881                         }
882                     }
883                 };
884         
885             private static final JS.Callable dnsResolve = new JS.Callable() {
886                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
887                         try {
888                             return InetAddress.getByName(args.elementAt(0).toString()).getHostAddress();
889                         } catch (UnknownHostException e) {
890                             return null;
891                         }
892                     }
893                 };
894         
895             private static final JS.Callable myIpAddress = new JS.Callable() {
896                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
897                         try {
898                             return InetAddress.getLocalHost().getHostAddress();
899                         } catch (UnknownHostException e) {
900                             if (Log.on) Log.log(this, "strange... host does not know its own address");
901                             return null;
902                         }
903                     }
904                 };
905         
906             private static final JS.Callable dnsDomainLevels = new JS.Callable() {
907                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
908                         String s = args.elementAt(0).toString();
909                         int i = 0;
910                         while((i = s.indexOf('.', i)) != -1) i++;
911                         return new Integer(i);
912                     }
913                 };
914         
915             private static boolean match(String[] arr, String s, int index) {
916                 if (index >= arr.length) return true;
917                 for(int i=0; i<s.length(); i++) {
918                     String s2 = s.substring(i);
919                     if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
920                 }
921                 return false;
922             }
923         
924             private static final JS.Callable shExpMatch = new JS.Callable() {
925                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
926                         StringTokenizer st = new StringTokenizer(args.elementAt(1).toString(), "*", false);
927                         String[] arr = new String[st.countTokens()];
928                         String s = args.elementAt(0).toString();
929                         for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
930                         return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
931                     }
932                 };
933         
934             public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
935         
936             private static final JS.Callable weekdayRange = new JS.Callable() {
937                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
938                         TimeZone tz = (args.length() < 3 || args.elementAt(2) == null || !args.elementAt(2).equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
939                         Calendar c = new GregorianCalendar();
940                         c.setTimeZone(tz);
941                         c.setTime(new java.util.Date());
942                         java.util.Date d = c.getTime();
943                         int day = d.getDay();
944                     
945                         String d1s = args.elementAt(0).toString().toUpperCase();
946                         int d1 = 0, d2 = 0;
947                         for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
948                     
949                         if (args.length() == 1)
950                             return d1 == day ? Boolean.TRUE : Boolean.FALSE;
951                     
952                         String d2s = args.elementAt(1).toString().toUpperCase();
953                         for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
954                     
955                         return
956                             ((d1 <= d2 && day >= d1 && day <= d2) ||
957                              (d1 > d2 && (day >= d1 || day <= d2))) ?
958                             Boolean.TRUE : Boolean.FALSE;
959                     }
960                 };
961         
962             private static final JS.Callable dateRange = new JS.Callable() {
963                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
964                         throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
965                     }
966                 };
967         
968             private static final JS.Callable timeRange = new JS.Callable() {
969                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
970                         throw new JS.Exn("XWT does not support timeRange() in PAC scripts");
971                     }
972                 };
973         
974         }
975
976     }
977
978 }