2003/10/01 04:29:10
[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     /** true iff this is the first request to be made on this socket */
55     boolean firstRequest = true;
56
57     /** cache for resolveAndCheckIfFirewalled() */
58     static Hashtable resolvedHosts = new Hashtable();
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             try {
92                 connect();
93                 sendRequest(contentType, content);
94             } catch (IOException e) {
95                 reset();
96                 throw e;
97             }
98             blockOn = okToRecieve;
99             releaseMe = okToRecieve = new Semaphore();
100         }
101         
102         // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
103         boolean doRelease = true;
104         try {
105             if (blockOn != null) blockOn.block();
106             
107             // previous call wrecked the socket connection, but we already sent our request, so we can't just retry --
108             // this could cause the server to receive the request twice, which could be bad (think of the case where the
109             // server call causes Amazon.com to ship you an item with one-click purchasing).
110             if (sock == null)
111                 throw new HTTPException("a previous pipelined call messed up the socket");
112             
113             Hashtable h = in == null ? null : parseHeaders(in);
114             if (h == null) {
115                 if (firstRequest) throw new HTTPException("server closed the socket with no response");
116                 // sometimes the server chooses to close the stream between requests
117                 reset();
118                 releaseMe.release();
119                 return makeRequest(contentType, content);
120             }
121
122             String reply = h.get("STATUSLINE").toString();
123             
124             if (reply.startsWith("407") || reply.startsWith("401")) {
125                 
126                 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
127                 else doWebAuth(h, content == null ? "GET" : "POST");
128                 
129                 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
130                     if (Log.on) Log.log(this, "proxy returned an HTTP/1.0 reply with no content-length...");
131                     reset();
132                 } else {
133                     int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
134                     new HTTPInputStream(in, cl, releaseMe).close();
135                 }
136                 releaseMe.release();
137                 return makeRequest(contentType, content);
138                 
139             } else if (reply.startsWith("2")) {
140                 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
141                     throw new HTTPException("XWT does not support HTTP/1.0 servers which fail to return the Content-Length header");
142                 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
143                 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
144                 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
145                 doRelease = false;
146                 return ret;
147                 
148             } else {
149                 throw new HTTPException("HTTP Error: " + reply);
150                 
151             }
152             
153         } catch (IOException e) { reset(); throw e;
154         } finally { if (doRelease) releaseMe.release();
155         }
156     }
157
158
159     // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
160
161     /**
162      *  resolves the hostname and returns it as a string in the form "x.y.z.w"
163      *  @throws HTTPException if the host falls within a firewalled netblock
164      */
165     private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
166
167         // cached
168         if (resolvedHosts.get(host) != null) return;
169
170         // if all scripts are trustworthy (local FS), continue
171         if (Main.originAddr == null) return;
172
173         // resolve using DNS
174         try {
175             InetAddress addr = InetAddress.getByName(host);
176             byte[] quadbyte = addr.getAddress();
177             if ((quadbyte[0] == 10 ||
178                  (quadbyte[0] == 192 && quadbyte[1] == 168) ||
179                  (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
180                 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
181             return;
182         } catch (UnknownHostException uhe) { }
183
184         if (Platform.detectProxy() == null) throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
185         if (Log.on) Log.log(this, "  could not resolve host " + host + "; using xmlrpc.xwt.org to ensure security");
186         try {
187             JS.Array args = new JS.Array();
188             args.addElement(host);
189             Object ret = new XMLRPC("http://xmlrpc.xwt.org/RPC2/", "dns.resolve").call(args);
190             if (ret == null || !(ret instanceof String)) throw new Exception("    xmlrpc.xwt.org returned non-String: " + ret);
191             resolvedHosts.put(host, ret);
192             return;
193         } catch (Throwable e) {
194             throw new HTTPException("exception while attempting to use xmlrpc.xwt.org to resolve " + host + ": " + e);
195         }
196     }
197
198
199     // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
200
201     /** Attempts a direct connection */
202     public Socket attemptDirect() {
203         try {
204             if (Log.verbose) Log.log(this, "attempting to create unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
205             return Platform.getSocket(host, port, ssl, true);
206         } catch (IOException e) {
207             if (Log.on) Log.log(this, "exception in attemptDirect(): " + e);
208             return null;
209         }
210     }
211
212     /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
213     public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
214         try {
215             if (Log.verbose) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
216
217             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
218             if (!ssl) {
219                 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
220             } else {
221                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
222                 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
223                 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
224                 pw.flush();
225                 String s = br.readLine();
226                 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
227                 while (br.readLine().length() > 0) { };
228                 ((TinySSL)sock).negotiate();
229             }
230             return sock;
231
232         } catch (IOException e) {
233             if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
234             return null;
235         }
236     }
237
238     /**
239      *  Implements SOCKSv4 with v4a DNS extension
240      *  @see http://www.socks.nec.com/protocol/socks4.protocol
241      *  @see http://www.socks.nec.com/protocol/socks4a.protocol
242      */
243     public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
244
245         // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
246         InetAddress addr = null;
247         try { addr = InetAddress.getByName(host); } catch (Exception e) { }
248
249         if (Log.verbose) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
250                                  " proxied socket using proxy " + proxyHost + ":" + proxyPort);
251
252         try {
253             Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
254             
255             DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
256             dos.writeByte(0x04);                         // SOCKSv4(a)
257             dos.writeByte(0x01);                         // CONNECT
258             dos.writeShort(port & 0xffff);               // port
259             if (addr == null) dos.writeInt(0x00000001);  // bogus IP
260             else dos.write(addr.getAddress());           // actual IP
261             dos.writeByte(0x00);                         // no userid
262             if (addr == null) {
263                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
264                 pw.print(host);
265                 pw.flush();
266                 dos.writeByte(0x00);                     // hostname null terminator
267             }
268             dos.flush();
269
270             DataInputStream dis = new DataInputStream(sock.getInputStream());
271             dis.readByte();                              // reply version
272             byte success = dis.readByte();               // success/fail
273             dis.skip(6);                                 // ip/port
274             
275             if ((int)(success & 0xff) == 90) {
276                 if (ssl) ((TinySSL)sock).negotiate();
277                 return sock;
278             }
279             if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
280             return null;
281
282         } catch (IOException e) {
283             if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
284             return null;
285         }
286     }
287
288     /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
289     public Socket attemptPAC(org.xwt.js.JS.Callable pacFunc) {
290         if (Log.verbose) Log.log(this, "evaluating PAC script");
291         String pac = null;
292         try {
293             org.xwt.js.JS.Array args = new org.xwt.js.JS.Array();
294             args.addElement(url.toString());
295             args.addElement(url.getHost());
296             Object obj = pacFunc.call(args);
297             if (Log.verbose) Log.log(this, "  PAC script returned \"" + obj + "\"");
298             pac = obj.toString();
299         } catch (Throwable e) {
300             if (Log.on) Log.log(this, "PAC script threw exception " + e);
301             return null;
302         }
303
304         StringTokenizer st = new StringTokenizer(pac, ";", false);
305         while (st.hasMoreTokens()) {
306             String token = st.nextToken().trim();
307             if (Log.verbose) Log.log(this, "  trying \"" + token + "\"...");
308             try {
309                 Socket ret = null;
310                 if (token.startsWith("DIRECT"))
311                     ret = attemptDirect();
312                 else if (token.startsWith("PROXY"))
313                     ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
314                                            Integer.parseInt(token.substring(token.indexOf(':') + 1)));
315                 else if (token.startsWith("SOCKS"))
316                     ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
317                                             Integer.parseInt(token.substring(token.indexOf(':') + 1)));
318                 if (ret != null) return ret;
319             } catch (Throwable e) {
320                 if (Log.on) Log.log(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
321             }
322         }
323         if (Log.on) Log.log(this, "all PAC results exhausted");
324         return null;
325     }
326
327
328     // Everything Else ////////////////////////////////////////////////////////////////////////////
329
330     private synchronized void connect() throws IOException {
331         if (originalUrl.equals("stdio:")) {
332             in = new BufferedInputStream(System.in);
333             return;
334         }
335         if (sock != null) {
336             if (in == null) in = new BufferedInputStream(sock.getInputStream());
337             return;
338         }
339         // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
340         String url = originalUrl;
341         userInfo = url.substring(url.indexOf("://") + 3);
342         userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
343         if (userInfo.indexOf('@') != -1) {
344             userInfo = userInfo.substring(0, userInfo.indexOf('@'));
345             url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
346         } else {
347             userInfo = null;
348         }
349
350         if (url.startsWith("https:")) {
351             this.url = new URL("http" + url.substring(5));
352             ssl = true;
353         } else if (!url.startsWith("http:")) {
354             throw new MalformedURLException("HTTP only supports http/https urls");
355         } else {
356             this.url = new URL(url);
357         }
358         if (!skipResolveCheck) resolveAndCheckIfFirewalled(this.url.getHost());
359         port = this.url.getPort();
360         path = this.url.getFile();
361         if (port == -1) port = ssl ? 443 : 80;
362         host = this.url.getHost();
363         if (Log.verbose) Log.log(this, "creating HTTP object for connection to " + host + ":" + port);
364
365         Proxy pi = Platform.detectProxy();
366         OUTER: do {
367             if (pi != null) {
368                 for(int i=0; i<pi.excluded.length; i++) if (host.equals(pi.excluded[i])) break OUTER;
369                 if (sock == null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
370                 if (sock == null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost, pi.httpsProxyPort);
371                 if (sock == null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
372                 if (sock == null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
373             }
374         } while (false);
375         proxied = sock != null;
376         if (sock == null) sock = attemptDirect();
377         if (sock == null) throw new HTTPException("unable to contact host " + host);
378         if (in == null) in = new BufferedInputStream(sock.getInputStream());
379     }
380
381     public void sendRequest(String contentType, String content) throws IOException {
382
383         PrintWriter pw = new PrintWriter(new OutputStreamWriter(originalUrl.equals("stdio:") ? System.out : sock.getOutputStream()));
384         if (content != null) {
385             pw.print("POST " + path + " HTTP/1.1\r\n");
386             int contentLength = content.substring(0, 2).equals("\r\n") ?
387                 content.length() - 2 :
388                 (content.length() - content.indexOf("\r\n\r\n") - 4);
389             pw.print("Content-Length: " + contentLength + "\r\n");
390             if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
391         } else {
392             pw.print("GET " + path + " HTTP/1.1\r\n");
393         }
394         
395         pw.print("User-Agent: XWT\r\n");
396         pw.print("Accept-encoding: gzip\r\n");
397         pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
398         if (proxied) pw.print("X-RequestOrigin: " + Main.originHost + "\r\n");
399
400         if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: " + Proxy.Authorization.authorization2 + "\r\n");
401         if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
402
403         pw.print(content == null ? "\r\n" : content);
404         pw.print("\r\n");
405         pw.flush();
406     }
407
408     private void doWebAuth(Hashtable h0, String method) throws IOException {
409         if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
410         Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
411         
412         if (h.get("AUTHTYPE").equals("Basic")) {
413             if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
414             authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("US-ASCII"))));
415             
416         } else if (h.get("AUTHTYPE").equals("Digest")) {
417             if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale"))) throw new HTTPException("username/password rejected");
418             String path2 = path;
419             if (path2.startsWith("http://") || path2.startsWith("https://")) {
420                 path2 = path2.substring(path2.indexOf("://") + 3);
421                 path2 = path2.substring(path2.indexOf('/'));
422             }
423             String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" + userInfo.substring(userInfo.indexOf(':') + 1);
424             String A2 = method + ":" + path2;
425             authCache.put(originalUrl,
426                           "Digest " +
427                           "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
428                           "realm=\"" + h.get("realm") + "\", " +
429                           "nonce=\"" + h.get("nonce") + "\", " +
430                           "uri=\"" + path2 + "\", " +
431                           (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) + 
432                           "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
433                           "algorithm=MD5"
434                           );
435             
436         } else {
437             throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
438         }
439     }
440
441     private void doProxyAuth(Hashtable h0, String method) throws IOException {
442         if (Log.on) Log.log(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
443         Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
444         String style = h.get("AUTHTYPE").toString();
445         String realm = (String)h.get("realm");
446
447         if (style.equals("NTLM") && Proxy.Authorization.authorization2 == null) {
448             Log.log(this, "Proxy identified itself as NTLM, sending Type 1 packet");
449             Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(Proxy.NTLM.type1);
450             return;
451         }
452
453         if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
454             Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), Proxy.Authorization.authorization);
455
456         if (style.equals("Basic")) {
457             Proxy.Authorization.authorization2 =
458                 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("US-ASCII")));
459             
460         } else if (style.equals("Digest")) {
461             String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
462                 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
463             String A2 = method + ":" + path;
464             Proxy.Authorization.authorization2 = 
465                 "Digest " +
466                 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) + "\", " +
467                 "realm=\"" + h.get("realm") + "\", " +
468                 "nonce=\"" + h.get("nonce") + "\", " +
469                 "uri=\"" + path + "\", " +
470                 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) + 
471                 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
472                 "algorithm=MD5";
473
474         } else if (style.equals("NTLM")) {
475             Log.log(this, "Proxy identified itself as NTLM, got Type 2 packet");
476             byte[] type2 = Base64.decode(((String)h0.get("proxy-authenticate")).substring(5).trim());
477             for(int i=0; i<type2.length; i += 4) {
478                 String log = "";
479                 if (i<type2.length) log += Integer.toString(type2[i] & 0xff, 16) + " ";
480                 if (i+1<type2.length) log += Integer.toString(type2[i+1] & 0xff, 16) + " ";
481                 if (i+2<type2.length) log += Integer.toString(type2[i+2] & 0xff, 16) + " ";
482                 if (i+3<type2.length) log += Integer.toString(type2[i+3] & 0xff, 16) + " ";
483                 Log.log(this, log);
484             }
485             // FIXME: need to keep the connection open between type1 and type3
486             // FIXME: finish this
487             //byte[] type3 = Proxy.NTLM.getResponse(
488             //Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(type3));
489         }            
490     }
491
492
493     // HTTPException ///////////////////////////////////////////////////////////////////////////////////
494
495     static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
496
497
498     // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
499
500     /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
501     public class HTTPInputStream extends FilterInputStream {
502
503         /** if chunking, the number of bytes remaining in this subset; otherwise the remainder of the chunk */
504         private int length = 0;
505
506         /** this semaphore will be released when the stream is closed */
507         private Semaphore releaseMe = null;
508
509         /** indicates that we have encountered the zero-length terminator chunk */
510         boolean chunkedDone = false;
511
512         /** if we're on the first chunk, we don't pre-read a CRLF */
513         boolean firstChunk = true;
514
515         /** the length of the entire content body; -1 if chunked */
516         private int contentLength = 0;
517         public int getContentLength() { return contentLength; }
518
519         HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
520             super(in);
521             this.releaseMe = releaseMe;
522             this.contentLength = length;
523             this.length = length == -1 ? 0 : length;
524         }
525
526         public boolean markSupported() { return false; }
527         public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
528         public long skip(long n) throws IOException { return read(null, -1, (int)n); }
529         public int available() throws IOException {
530             if (contentLength == -1) return java.lang.Math.min(super.available(), length);
531             return super.available();
532         }
533
534         public int read() throws IOException {
535             byte[] b = new byte[1];
536             int ret = read(b, 0, 1);
537             return ret == -1 ? -1 : b[0] & 0xff;
538         }
539
540         private void readChunk() throws IOException {
541             if (chunkedDone) return;
542             if (!firstChunk) super.skip(2); // CRLF
543             firstChunk = false;
544             String chunkLen = "";
545             while(true) {
546                 int i = super.read();
547                 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
548
549                 // FEATURE: handle chunking extensions
550                 if (i == '\r') {
551                     super.read();    // LF
552                     break;
553                 } else {
554                     chunkLen += (char)i;
555                 }
556             }
557             length = Integer.parseInt(chunkLen.trim(), 16);
558             if (length == 0) chunkedDone = true;
559         }
560
561         public int read(byte[] b, int off, int len) throws IOException {
562             boolean good = false;
563             try {
564                 if (length == 0 && contentLength == -1) {
565                     readChunk();
566                     if (chunkedDone) { good = true; return -1; }
567                 } else {
568                     if (length == 0) { good = true; return -1; }
569                 }
570                 if (len > length) len = length;
571                 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
572                 if (ret >= 0) {
573                     length -= ret;
574                     good = true;
575                 }
576                 return ret;
577             } finally {
578                 if (!good) reset();
579             }
580         }
581
582         public void close() throws IOException {
583             if (contentLength == -1) {
584                 while(!chunkedDone) {
585                     if (length != 0) skip(length);
586                     readChunk();
587                 }
588                 skip(2);
589             } else {
590                 if (length != 0) skip(length);
591             }
592             if (releaseMe != null) releaseMe.release();
593         }
594     }
595
596     void reset() {
597         firstRequest = true;
598         in = null;
599         sock = null;
600     }
601
602
603     // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
604
605     /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
606     private Hashtable parseHeaders(InputStream in) throws IOException {
607         Hashtable ret = new Hashtable();
608
609         // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
610         byte[] buf = new byte[4096];
611         int buflen = 0;
612         while(true) {
613             int read = in.read();
614             if (read == -1 && buflen == 0) return null;
615             if (read == -1) throw new HTTPException("stream closed while reading headers");
616             buf[buflen++] = (byte)read;
617             if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
618             if (buflen == buf.length) {
619                 byte[] newbuf = new byte[buf.length * 2];
620                 System.arraycopy(buf, 0, newbuf, 0, buflen);
621                 buf = newbuf;
622             }
623         }
624
625         BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
626         String s = br.readLine();
627         if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
628         ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
629         ret.put("HTTP", s.substring(5, s.indexOf(' ')));
630
631         while((s = br.readLine()) != null && s.length() > 0) {
632             String front = s.substring(0, s.indexOf(':')).toLowerCase();
633             String back = s.substring(s.indexOf(':') + 1).trim();
634             // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
635             if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
636             ret.put(front, back);
637         }
638         return ret;
639     }
640
641     private Hashtable parseAuthenticationChallenge(String s) {
642         Hashtable ret = new Hashtable();
643
644         s = s.trim();
645         ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
646         s = s.substring(s.indexOf(' ')).trim();
647
648         while (s.length() > 0) {
649             String val = null;
650             String key = s.substring(0, s.indexOf('='));
651             s = s.substring(s.indexOf('=') + 1);
652             if (s.charAt(0) == '\"') {
653                 s = s.substring(1);
654                 val = s.substring(0, s.indexOf('\"'));
655                 s = s.substring(s.indexOf('\"') + 1);
656             } else {
657                 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
658                 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
659             }
660             if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
661             s = s.trim();
662             ret.put(key, val);
663         }
664         return ret;
665     }
666
667     private String H(String s) throws IOException {
668         byte[] b = s.getBytes("US-ASCII");
669         MD5Digest md5 = new MD5Digest();
670         md5.update(b, 0, b.length);
671         byte[] out = new byte[md5.getDigestSize()];
672         md5.doFinal(out, 0);
673         String ret = "";
674         for(int i=0; i<out.length; i++) {
675             ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
676             ret += "0123456789abcdef".charAt(out[i] & 0x0f);
677         }
678         return ret;
679     }
680
681
682     // Proxy ///////////////////////////////////////////////////////////
683
684     /** encapsulates most of the proxy logic; some is shared in HTTP.java */
685     public static class Proxy {
686         
687         public Proxy() { }
688         
689         /** the HTTP Proxy host to use */
690         public String httpProxyHost = null;
691         
692         /** the HTTP Proxy port to use */
693         public int httpProxyPort = -1;
694         
695         /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
696         public String httpsProxyHost = null;
697     
698         /** if a seperate proxy should be used for HTTPS, this is the port */
699         public int httpsProxyPort = -1;
700     
701         /** the SOCKS Proxy Host to use */
702         public String socksProxyHost = null;
703     
704         /** the SOCKS Proxy Port to use */
705         public int socksProxyPort = -1;
706     
707         /** hosts to be excluded from proxy use; wildcards permitted */
708         public String[] excluded = null;
709     
710         /** the PAC script */
711         public JS.Callable proxyAutoConfigFunction = null;
712     
713         public static Proxy detectProxyViaManual() {
714             Proxy ret = new Proxy();
715         
716             ret.httpProxyHost = Platform.getEnv("http_proxy");
717             if (ret.httpProxyHost != null) {
718                 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
719                 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
720                 if (ret.httpProxyHost.indexOf(':') != -1) {
721                     ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
722                     ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
723                 } else {
724                     ret.httpProxyPort = 80;
725                 }
726             }
727         
728             ret.httpsProxyHost = Platform.getEnv("https_proxy");
729             if (ret.httpsProxyHost != null) {
730                 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
731                 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
732                 if (ret.httpsProxyHost.indexOf(':') != -1) {
733                     ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
734                     ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
735                 } else {
736                     ret.httpsProxyPort = 80;
737                 }
738             }
739         
740             ret.socksProxyHost = Platform.getEnv("socks_proxy");
741             if (ret.socksProxyHost != null) {
742                 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
743                 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
744                 if (ret.socksProxyHost.indexOf(':') != -1) {
745                     ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
746                     ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
747                 } else {
748                     ret.socksProxyPort = 80;
749                 }
750             }
751         
752             String noproxy = Platform.getEnv("no_proxy");
753             if (noproxy != null) {
754                 StringTokenizer st = new StringTokenizer(noproxy, ",");
755                 ret.excluded = new String[st.countTokens()];
756                 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
757             }
758         
759             if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
760             return ret;
761         }
762     
763         public static JS.Scope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
764         public static JS.Callable getProxyAutoConfigFunction(String url) {
765             try { 
766                 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
767                 String s = null;
768                 String script = "";
769                 while((s = br.readLine()) != null) script += s + "\n";
770                 if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
771                 if (Log.on) Log.log(Proxy.class, script);
772             
773                 // MS CARP hack
774                 Vector carpHosts = new Vector();
775                 for(int i=0; i<script.length(); i++)
776                     if (script.regionMatches(i, "new Node(", 0, 9)) {
777                         String host = script.substring(i + 10, script.indexOf('\"', i + 11));
778                         if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
779                         carpHosts.addElement(host);
780                     }
781                 if (carpHosts.size() > 0) {
782                     script = "function FindProxyForURL(url, host) {\nreturn \"";
783                     for(int i=0; i<carpHosts.size(); i++)
784                         script += "PROXY " + carpHosts.elementAt(i) + "; ";
785                     script += "\";\n}";
786                     if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
787                     if (Log.on) Log.log(Proxy.class, script);
788                 }
789
790                 JS.CompiledFunction scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
791                 scr.call(new JS.Array(), proxyAutoConfigRootScope);
792                 return (JS.Callable)proxyAutoConfigRootScope.get("FindProxyForURL");
793             } catch (Exception e) {
794                 if (Log.on) {
795                     Log.log(Platform.class, "WPAD detection failed due to:");
796                     if (e instanceof JS.Exn) {
797                         try {
798                             org.xwt.js.JS.Array arr = new org.xwt.js.JS.Array();
799                             arr.addElement(((JS.Exn)e).getObject());
800                         } catch (Exception e2) {
801                             Log.log(Platform.class, e);
802                         }
803                     }
804                     else Log.log(Platform.class, e);
805                 }
806                 return null;
807             }
808         }
809
810
811         // Authorization ///////////////////////////////////////////////////////////////////////////////////
812
813         public static class Authorization {
814
815             static public String authorization = null;
816             static public String authorization2 = null;
817             static public Semaphore waitingForUser = new Semaphore();
818
819             public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
820
821                 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
822                 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
823                 // a password, so we should reattempt authorization.
824
825                 if (authorization != oldAuth) return;
826                 if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
827                 Message.Q.add(new Message() {
828                         public void perform() {
829                             Box b = new Box();
830                             Template t = Template.getTemplate((Res)Main.builtin.get("org/xwt/builtin/proxy_authorization.xwt"));
831                             t.apply(b, null, null);
832                             b.put("realm", realm);
833                             b.put("proxyIP", proxyIP);
834                         }
835                     });
836
837                 waitingForUser.block();
838                 if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
839             
840             }
841         }
842
843
844         // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
845
846         public static class ProxyAutoConfigRootScope extends JS.GlobalScope {
847
848             public ProxyAutoConfigRootScope() { super(null); }
849         
850             public Object get(Object name) {
851                 if (name.equals("isPlainHostName")) return isPlainHostName;
852                 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
853                 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
854                 else if (name.equals("isResolvable")) return isResolvable;
855                 else if (name.equals("isInNet")) return isInNet;
856                 else if (name.equals("dnsResolve")) return dnsResolve;
857                 else if (name.equals("myIpAddress")) return myIpAddress;
858                 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
859                 else if (name.equals("shExpMatch")) return shExpMatch;
860                 else if (name.equals("weekdayRange")) return weekdayRange;
861                 else if (name.equals("dateRange")) return dateRange;
862                 else if (name.equals("timeRange")) return timeRange;
863                 else if (name.equals("ProxyConfig")) return ProxyConfig;
864                 else return super.get(name);
865             }
866         
867             private static final JS.Obj proxyConfigBindings = new JS.Obj();
868             private static final JS.Obj ProxyConfig = new JS.Obj() {
869                     public Object get(Object name) {
870                         if (name.equals("bindings")) return proxyConfigBindings;
871                         return null;
872                     }
873                 };
874         
875             private static final JS.Callable isPlainHostName = new JS.Callable() {
876                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
877                         return (args.elementAt(0).toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
878                     }
879                 };
880         
881             private static final JS.Callable dnsDomainIs = new JS.Callable() {
882                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
883                         return (args.elementAt(0).toString().endsWith(args.elementAt(1).toString())) ? Boolean.TRUE : Boolean.FALSE;
884                     }
885                 };
886         
887             private static final JS.Callable localHostOrDomainIs = new JS.Callable() {
888                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
889                         return (args.elementAt(0).toString().equals(args.elementAt(1).toString()) || 
890                                 (args.elementAt(0).toString().indexOf('.') == -1 && args.elementAt(1).toString().startsWith(args.elementAt(0).toString()))) ?
891                             Boolean.TRUE : Boolean.FALSE;
892                     }
893                 };
894         
895             private static final JS.Callable isResolvable = new JS.Callable() {
896                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
897                         try {
898                             return (InetAddress.getByName(args.elementAt(0).toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
899                         } catch (UnknownHostException e) {
900                             return Boolean.FALSE;
901                         }
902                     }
903                 };
904         
905             private static final JS.Callable isInNet = new JS.Callable() {
906                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
907                         if (args.length() != 3) return Boolean.FALSE;
908                         try {
909                             byte[] host = InetAddress.getByName(args.elementAt(0).toString()).getAddress();
910                             byte[] net = InetAddress.getByName(args.elementAt(1).toString()).getAddress();
911                             byte[] mask = InetAddress.getByName(args.elementAt(2).toString()).getAddress();
912                             return ((host[0] & mask[0]) == net[0] &&
913                                     (host[1] & mask[1]) == net[1] &&
914                                     (host[2] & mask[2]) == net[2] &&
915                                     (host[3] & mask[3]) == net[3]) ?
916                                 Boolean.TRUE : Boolean.FALSE;
917                         } catch (Exception e) {
918                             throw new JS.Exn("exception in isInNet(): " + e);
919                         }
920                     }
921                 };
922         
923             private static final JS.Callable dnsResolve = new JS.Callable() {
924                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
925                         try {
926                             return InetAddress.getByName(args.elementAt(0).toString()).getHostAddress();
927                         } catch (UnknownHostException e) {
928                             return null;
929                         }
930                     }
931                 };
932         
933             private static final JS.Callable myIpAddress = new JS.Callable() {
934                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
935                         try {
936                             return InetAddress.getLocalHost().getHostAddress();
937                         } catch (UnknownHostException e) {
938                             if (Log.on) Log.log(this, "strange... host does not know its own address");
939                             return null;
940                         }
941                     }
942                 };
943         
944             private static final JS.Callable dnsDomainLevels = new JS.Callable() {
945                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
946                         String s = args.elementAt(0).toString();
947                         int i = 0;
948                         while((i = s.indexOf('.', i)) != -1) i++;
949                         return new Integer(i);
950                     }
951                 };
952         
953             private static boolean match(String[] arr, String s, int index) {
954                 if (index >= arr.length) return true;
955                 for(int i=0; i<s.length(); i++) {
956                     String s2 = s.substring(i);
957                     if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
958                 }
959                 return false;
960             }
961         
962             private static final JS.Callable shExpMatch = new JS.Callable() {
963                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
964                         StringTokenizer st = new StringTokenizer(args.elementAt(1).toString(), "*", false);
965                         String[] arr = new String[st.countTokens()];
966                         String s = args.elementAt(0).toString();
967                         for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
968                         return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
969                     }
970                 };
971         
972             public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
973         
974             private static final JS.Callable weekdayRange = new JS.Callable() {
975                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
976                         TimeZone tz = (args.length() < 3 || args.elementAt(2) == null || !args.elementAt(2).equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
977                         Calendar c = new GregorianCalendar();
978                         c.setTimeZone(tz);
979                         c.setTime(new java.util.Date());
980                         java.util.Date d = c.getTime();
981                         int day = d.getDay();
982                     
983                         String d1s = args.elementAt(0).toString().toUpperCase();
984                         int d1 = 0, d2 = 0;
985                         for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
986                     
987                         if (args.length() == 1)
988                             return d1 == day ? Boolean.TRUE : Boolean.FALSE;
989                     
990                         String d2s = args.elementAt(1).toString().toUpperCase();
991                         for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
992                     
993                         return
994                             ((d1 <= d2 && day >= d1 && day <= d2) ||
995                              (d1 > d2 && (day >= d1 || day <= d2))) ?
996                             Boolean.TRUE : Boolean.FALSE;
997                     }
998                 };
999         
1000             private static final JS.Callable dateRange = new JS.Callable() {
1001                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
1002                         throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
1003                     }
1004                 };
1005         
1006             private static final JS.Callable timeRange = new JS.Callable() {
1007                     public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
1008                         throw new JS.Exn("XWT does not support timeRange() in PAC scripts");
1009                     }
1010                 };
1011         
1012         }
1013
1014         /**
1015          *  An implementation of Microsoft's proprietary NTLM authentication protocol.  This code was derived from Eric
1016          *  Glass's work, and is copyright as follows:
1017          *
1018          *  Copyright (c) 2003 Eric Glass     (eglass1 at comcast.net). 
1019          *
1020          *  Permission to use, copy, modify, and distribute this document for any purpose and without any fee is hereby
1021          *  granted, provided that the above copyright notice and this list of conditions appear in all copies.
1022          *  The most current version of this document may be obtained from http://davenport.sourceforge.net/ntlm.html .
1023          */ 
1024         public static class NTLM {
1025             
1026             public static final byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01,
1027                                                             0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00 };
1028             
1029             /**
1030              * Calculates the NTLM Response for the given challenge, using the
1031              * specified password.
1032              *
1033              * @param password The user's password.
1034              * @param challenge The Type 2 challenge from the server.
1035              *
1036              * @return The NTLM Response.
1037              */
1038             public static byte[] getNTLMResponse(String password, byte[] challenge)
1039                 throws Exception {
1040                 byte[] ntlmHash = ntlmHash(password);
1041                 return lmResponse(ntlmHash, challenge);
1042             }
1043
1044             /**
1045              * Calculates the LM Response for the given challenge, using the specified
1046              * password.
1047              *
1048              * @param password The user's password.
1049              * @param challenge The Type 2 challenge from the server.
1050              *
1051              * @return The LM Response.
1052              */
1053             public static byte[] getLMResponse(String password, byte[] challenge)
1054                 throws Exception {
1055                 byte[] lmHash = lmHash(password);
1056                 return lmResponse(lmHash, challenge);
1057             }
1058
1059             /**
1060              * Calculates the NTLMv2 Response for the given challenge, using the
1061              * specified authentication target, username, password, target information
1062              * block, and client challenge.
1063              *
1064              * @param target The authentication target (i.e., domain).
1065              * @param user The username. 
1066              * @param password The user's password.
1067              * @param targetInformation The target information block from the Type 2
1068              * message.
1069              * @param challenge The Type 2 challenge from the server.
1070              * @param clientChallenge The random 8-byte client challenge. 
1071              *
1072              * @return The NTLMv2 Response.
1073              */
1074             public static byte[] getNTLMv2Response(String target, String user,
1075                                                    String password, byte[] targetInformation, byte[] challenge,
1076                                                    byte[] clientChallenge) throws Exception {
1077                 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1078                 byte[] blob = createBlob(targetInformation, clientChallenge);
1079                 return lmv2Response(ntlmv2Hash, blob, challenge);
1080             }
1081
1082             /**
1083              * Calculates the LMv2 Response for the given challenge, using the
1084              * specified authentication target, username, password, and client
1085              * challenge.
1086              *
1087              * @param target The authentication target (i.e., domain).
1088              * @param user The username.
1089              * @param password The user's password.
1090              * @param challenge The Type 2 challenge from the server.
1091              * @param clientChallenge The random 8-byte client challenge.
1092              *
1093              * @return The LMv2 Response. 
1094              */
1095             public static byte[] getLMv2Response(String target, String user,
1096                                                  String password, byte[] challenge, byte[] clientChallenge)
1097                 throws Exception {
1098                 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1099                 return lmv2Response(ntlmv2Hash, clientChallenge, challenge);
1100             }
1101
1102             /**
1103              * Calculates the NTLM2 Session Response for the given challenge, using the
1104              * specified password and client challenge.
1105              *
1106              * @param password The user's password.
1107              * @param challenge The Type 2 challenge from the server.
1108              * @param clientChallenge The random 8-byte client challenge.
1109              *
1110              * @return The NTLM2 Session Response.  This is placed in the NTLM
1111              * response field of the Type 3 message; the LM response field contains
1112              * the client challenge, null-padded to 24 bytes.
1113              */
1114             public static byte[] getNTLM2SessionResponse(String password,
1115                                                          byte[] challenge, byte[] clientChallenge) throws Exception {
1116                 byte[] ntlmHash = ntlmHash(password);
1117                 MD5Digest md5 = new MD5Digest();
1118                 md5.update(challenge, 0, challenge.length);
1119                 md5.update(clientChallenge, 0, clientChallenge.length);
1120                 byte[] sessionHash = new byte[8];
1121                 byte[] md5_out = new byte[md5.getDigestSize()];
1122                 md5.doFinal(md5_out, 0);
1123                 System.arraycopy(md5_out, 0, sessionHash, 0, 8);
1124                 return lmResponse(ntlmHash, sessionHash);
1125             }
1126
1127             /**
1128              * Creates the LM Hash of the user's password.
1129              *
1130              * @param password The password.
1131              *
1132              * @return The LM Hash of the given password, used in the calculation
1133              * of the LM Response.
1134              */
1135             private static byte[] lmHash(String password) throws Exception {
1136                 /*
1137                 byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
1138                 int length = java.lang.Math.min(oemPassword.length, 14);
1139                 byte[] keyBytes = new byte[14];
1140                 System.arraycopy(oemPassword, 0, keyBytes, 0, length);
1141                 Key lowKey = createDESKey(keyBytes, 0);
1142                 Key highKey = createDESKey(keyBytes, 7);
1143                 byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
1144                 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1145                 des.init(Cipher.ENCRYPT_MODE, lowKey);
1146                 byte[] lowHash = des.doFinal(magicConstant);
1147                 des.init(Cipher.ENCRYPT_MODE, highKey);
1148                 byte[] highHash = des.doFinal(magicConstant);
1149                 byte[] lmHash = new byte[16];
1150                 System.arraycopy(lowHash, 0, lmHash, 0, 8);
1151                 System.arraycopy(highHash, 0, lmHash, 8, 8);
1152                 return lmHash;
1153                 */
1154                 return null; // FIXME
1155             }
1156
1157             /**
1158              * Creates the NTLM Hash of the user's password.
1159              *
1160              * @param password The password.
1161              *
1162              * @return The NTLM Hash of the given password, used in the calculation
1163              * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1164              */
1165             private static byte[] ntlmHash(String password) throws Exception {
1166                 byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
1167                 MD4Digest md4 = new MD4Digest();
1168                 md4.update(unicodePassword, 0, unicodePassword.length);
1169                 byte[] ret = new byte[md4.getDigestSize()];
1170                 return ret;
1171             }
1172
1173             /**
1174              * Creates the NTLMv2 Hash of the user's password.
1175              *
1176              * @param target The authentication target (i.e., domain).
1177              * @param user The username.
1178              * @param password The password.
1179              *
1180              * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1181              * and LMv2 Responses. 
1182              */
1183             private static byte[] ntlmv2Hash(String target, String user,
1184                                              String password) throws Exception {
1185                 byte[] ntlmHash = ntlmHash(password);
1186                 String identity = user.toUpperCase() + target.toUpperCase();
1187                 return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
1188             }
1189
1190             /**
1191              * Creates the LM Response from the given hash and Type 2 challenge.
1192              *
1193              * @param hash The LM or NTLM Hash.
1194              * @param challenge The server challenge from the Type 2 message.
1195              *
1196              * @return The response (either LM or NTLM, depending on the provided
1197              * hash).
1198              */
1199             private static byte[] lmResponse(byte[] hash, byte[] challenge)
1200                 throws Exception {
1201                 /*
1202                 byte[] keyBytes = new byte[21];
1203                 System.arraycopy(hash, 0, keyBytes, 0, 16);
1204                 Key lowKey = createDESKey(keyBytes, 0);
1205                 Key middleKey = createDESKey(keyBytes, 7);
1206                 Key highKey = createDESKey(keyBytes, 14);
1207                 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1208                 des.init(Cipher.ENCRYPT_MODE, lowKey);
1209                 byte[] lowResponse = des.doFinal(challenge);
1210                 des.init(Cipher.ENCRYPT_MODE, middleKey);
1211                 byte[] middleResponse = des.doFinal(challenge);
1212                 des.init(Cipher.ENCRYPT_MODE, highKey);
1213                 byte[] highResponse = des.doFinal(challenge);
1214                 byte[] lmResponse = new byte[24];
1215                 System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
1216                 System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
1217                 System.arraycopy(highResponse, 0, lmResponse, 16, 8);
1218                 return lmResponse;
1219                 */
1220                 return null; // FIXME
1221             }
1222
1223             /**
1224              * Creates the LMv2 Response from the given hash, client data, and
1225              * Type 2 challenge.
1226              *
1227              * @param hash The NTLMv2 Hash.
1228              * @param clientData The client data (blob or client challenge).
1229              * @param challenge The server challenge from the Type 2 message.
1230              *
1231              * @return The response (either NTLMv2 or LMv2, depending on the
1232              * client data).
1233              */
1234             private static byte[] lmv2Response(byte[] hash, byte[] clientData,
1235                                                byte[] challenge) throws Exception {
1236                 byte[] data = new byte[challenge.length + clientData.length];
1237                 System.arraycopy(challenge, 0, data, 0, challenge.length);
1238                 System.arraycopy(clientData, 0, data, challenge.length,
1239                                  clientData.length);
1240                 byte[] mac = hmacMD5(data, hash);
1241                 byte[] lmv2Response = new byte[mac.length + clientData.length];
1242                 System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
1243                 System.arraycopy(clientData, 0, lmv2Response, mac.length,
1244                                  clientData.length);
1245                 return lmv2Response;
1246             }
1247
1248             /**
1249              * Creates the NTLMv2 blob from the given target information block and
1250              * client challenge.
1251              *
1252              * @param targetInformation The target information block from the Type 2
1253              * message.
1254              * @param clientChallenge The random 8-byte client challenge.
1255              *
1256              * @return The blob, used in the calculation of the NTLMv2 Response.
1257              */
1258             private static byte[] createBlob(byte[] targetInformation,
1259                                              byte[] clientChallenge) {
1260                 byte[] blobSignature = new byte[] {
1261                     (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1262                 };
1263                 byte[] reserved = new byte[] {
1264                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1265                 };
1266                 byte[] unknown1 = new byte[] {
1267                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1268                 };
1269                 byte[] unknown2 = new byte[] {
1270                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1271                 };
1272                 long time = System.currentTimeMillis();
1273                 time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
1274                 time *= 10000; // tenths of a microsecond.
1275                 // convert to little-endian byte array.
1276                 byte[] timestamp = new byte[8];
1277                 for (int i = 0; i < 8; i++) {
1278                     timestamp[i] = (byte) time;
1279                     time >>>= 8;
1280                 }
1281                 byte[] blob = new byte[blobSignature.length + reserved.length +
1282                                        timestamp.length + clientChallenge.length +
1283                                        unknown1.length + targetInformation.length +
1284                                        unknown2.length];
1285                 int offset = 0;
1286                 System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
1287                 offset += blobSignature.length;
1288                 System.arraycopy(reserved, 0, blob, offset, reserved.length);
1289                 offset += reserved.length;
1290                 System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
1291                 offset += timestamp.length;
1292                 System.arraycopy(clientChallenge, 0, blob, offset,
1293                                  clientChallenge.length);
1294                 offset += clientChallenge.length;
1295                 System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
1296                 offset += unknown1.length;
1297                 System.arraycopy(targetInformation, 0, blob, offset,
1298                                  targetInformation.length);
1299                 offset += targetInformation.length;
1300                 System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
1301                 return blob;
1302             }
1303
1304             /**
1305              * Calculates the HMAC-MD5 hash of the given data using the specified
1306              * hashing key.
1307              *
1308              * @param data The data for which the hash will be calculated. 
1309              * @param key The hashing key.
1310              *
1311              * @return The HMAC-MD5 hash of the given data.
1312              */
1313             private static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
1314                 byte[] ipad = new byte[64];
1315                 byte[] opad = new byte[64];
1316                 for (int i = 0; i < 64; i++) {
1317                     ipad[i] = (byte) 0x36;
1318                     opad[i] = (byte) 0x5c;
1319                 }
1320                 for (int i = key.length - 1; i >= 0; i--) {
1321                     ipad[i] ^= key[i];
1322                     opad[i] ^= key[i];
1323                 }
1324                 byte[] content = new byte[data.length + 64];
1325                 System.arraycopy(ipad, 0, content, 0, 64);
1326                 System.arraycopy(data, 0, content, 64, data.length);
1327                 MD5Digest md5 = new MD5Digest();
1328                 md5.update(content, 0, content.length);
1329                 data = new byte[md5.getDigestSize()];
1330                 md5.doFinal(data, 0);
1331                 content = new byte[data.length + 64];
1332                 System.arraycopy(opad, 0, content, 0, 64);
1333                 System.arraycopy(data, 0, content, 64, data.length);
1334                 md5 = new MD5Digest();
1335                 md5.update(content, 0, content.length);
1336                 byte[] ret = new byte[md5.getDigestSize()];
1337                 md5.doFinal(ret, 0);
1338                 return ret;
1339             }
1340
1341             /**
1342              * Creates a DES encryption key from the given key material.
1343              *
1344              * @param bytes A byte array containing the DES key material.
1345              * @param offset The offset in the given byte array at which
1346              * the 7-byte key material starts.
1347              *
1348              * @return A DES encryption key created from the key material
1349              * starting at the specified offset in the given byte array.
1350              */
1351                 /*
1352             private static Key createDESKey(byte[] bytes, int offset) {
1353                 byte[] keyBytes = new byte[7];
1354                 System.arraycopy(bytes, offset, keyBytes, 0, 7);
1355                 byte[] material = new byte[8];
1356                 material[0] = keyBytes[0];
1357                 material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
1358                 material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
1359                 material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
1360                 material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
1361                 material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
1362                 material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
1363                 material[7] = (byte) (keyBytes[6] << 1);
1364                 oddParity(material);
1365                 return new SecretKeySpec(material, "DES");
1366             }
1367                 */
1368
1369             /**
1370              * Applies odd parity to the given byte array.
1371              *
1372              * @param bytes The data whose parity bits are to be adjusted for
1373              * odd parity.
1374              */
1375             private static void oddParity(byte[] bytes) {
1376                 for (int i = 0; i < bytes.length; i++) {
1377                     byte b = bytes[i];
1378                     boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1379                                             (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1380                                             (b >>> 1)) & 0x01) == 0;
1381                     if (needsParity) {
1382                         bytes[i] |= (byte) 0x01;
1383                     } else {
1384                         bytes[i] &= (byte) 0xfe;
1385                     }
1386                 }
1387             }
1388
1389         }
1390     }
1391 }