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