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