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