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