changes made after tupshins reconstruction
[org.ibex.core.git] / src / org / xwt / HTTP.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.net.*;
5 import java.io.*;
6 import java.util.*;
7 import org.xwt.js.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10 import org.bouncycastle.crypto.digests.*;
11
12 /**
13  *  This object encapsulates a *single* HTTP connection. Multiple requests may be pipelined over a connection (thread-safe),
14  *  although any IOException encountered in a request will invalidate all later requests.
15  */
16 public class HTTP {
17
18
19     // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
20
21     public HTTP(String url) { this(url, false); }
22     public HTTP(String url, boolean skipResolveCheck) { originalUrl = url; this.skipResolveCheck = skipResolveCheck; }
23
24     /** Performs an HTTP GET request */
25     public InputStream GET() throws IOException { return makeRequest(null, null); }
26
27     /** Performs an HTTP POST request; content is additional headers, blank line, and body */
28     public InputStream POST(String contentType, String content) throws IOException { return makeRequest(contentType, content); }
29
30     public static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
31
32
33     // Statics ///////////////////////////////////////////////////////////////////////////////////////////////
34
35     static Hash resolvedHosts = new Hash();            ///< cache for resolveAndCheckIfFirewalled()
36     private static Hash authCache = new Hash();        ///< cache of userInfo strings, keyed on originalUrl
37
38
39     // Instance Data ///////////////////////////////////////////////////////////////////////////////////////////////
40
41     final String originalUrl;              ///< the URL as passed to the original constructor; this is never changed
42     URL url = null;                        ///< the URL to connect to; this is munged when the url is parsed */
43     String host = null;                    ///< the host to connect to
44     int port = -1;                         ///< the port to connect on
45     boolean ssl = false;                   ///< true if SSL (HTTPS) should be used
46     String path = null;                    ///< the path (URI) to retrieve on the server
47     Socket sock = null;                    ///< the socket
48     InputStream in = null;                 ///< the socket's inputstream
49     String userInfo = null;                ///< the username and password portions of the URL
50     boolean firstRequest = true;           ///< true iff this is the first request to be made on this socket
51     boolean skipResolveCheck = false;      ///< allowed to skip the resolve check when downloading PAC script
52     boolean proxied = false;               ///< true iff we're using a proxy
53
54     /** this is null if the current request is the first request on
55      *  this HTTP connection; otherwise it is a Semaphore which will be
56      *  released once the request ahead of us has recieved its response
57      */
58     Semaphore okToRecieve = null;
59
60     /**
61      *  This method isn't synchronized; however, only one thread can be in the inner synchronized block at a time, and the rest of
62      *  the method is protected by in-order one-at-a-time semaphore lock-steps
63      */
64     private InputStream makeRequest(String contentType, String content) throws IOException {
65
66         // Step 1: send the request and establish a semaphore to stop any requests that pipeline after us
67         Semaphore blockOn = null;
68         Semaphore releaseMe = null;
69         synchronized(this) {
70             try {
71                 connect();
72                 sendRequest(contentType, content);
73             } catch (IOException e) {
74                 reset();
75                 throw e;
76             }
77             blockOn = okToRecieve;
78             releaseMe = okToRecieve = new Semaphore();
79         }
80         
81         // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
82         boolean doRelease = true;
83         try {
84             if (blockOn != null) blockOn.block();
85             
86             // previous call wrecked the socket connection, but we already sent our request, so we can't just retry --
87             // this could cause the server to receive the request twice, which could be bad (think of the case where the
88             // server call causes Amazon.com to ship you an item with one-click purchasing).
89             if (sock == null)
90                 throw new HTTPException("a previous pipelined call messed up the socket");
91             
92             Hashtable h = in == null ? null : parseHeaders(in);
93             if (h == null) {
94                 if (firstRequest) throw new HTTPException("server closed the socket with no response");
95                 // sometimes the server chooses to close the stream between requests
96                 reset();
97                 releaseMe.release();
98                 return makeRequest(contentType, content);
99             }
100
101             String reply = h.get("STATUSLINE").toString();
102             
103             if (reply.startsWith("407") || reply.startsWith("401")) {
104                 
105                 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
106                 else doWebAuth(h, content == null ? "GET" : "POST");
107                 
108                 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
109                     if (Log.on) Log.info(this, "proxy returned an HTTP/1.0 reply with no content-length...");
110                     reset();
111                 } else {
112                     int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
113                     new HTTPInputStream(in, cl, releaseMe).close();
114                 }
115                 releaseMe.release();
116                 return makeRequest(contentType, content);
117                 
118             } else if (reply.startsWith("2")) {
119                 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
120                     throw new HTTPException("XWT does not support HTTP/1.0 servers which fail to return the Content-Length header");
121                 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
122                 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
123                 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
124                 doRelease = false;
125                 return ret;
126                 
127             } else {
128                 throw new HTTPException("HTTP Error: " + reply);
129                 
130             }
131             
132         } catch (IOException e) { reset(); throw e;
133         } finally { if (doRelease) releaseMe.release();
134         }
135     }
136
137
138     // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
139
140     /**
141      *  resolves the hostname and returns it as a string in the form "x.y.z.w"
142      *  @throws HTTPException if the host falls within a firewalled netblock
143      */
144     private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
145
146         // cached
147         if (resolvedHosts.get(host) != null) return;
148
149         // if all scripts are trustworthy (local FS), continue
150         if (Main.originAddr == null) return;
151
152         // resolve using DNS
153         try {
154             InetAddress addr = InetAddress.getByName(host);
155             byte[] quadbyte = addr.getAddress();
156             if ((quadbyte[0] == 10 ||
157                  (quadbyte[0] == 192 && quadbyte[1] == 168) ||
158                  (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
159                 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() +
160                                         "] is in a firewalled netblock");
161             return;
162         } catch (UnknownHostException uhe) { }
163
164         if (Platform.detectProxy() == null)
165             throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
166     }
167
168
169     // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
170
171     private Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
172         Socket ret = ssl ? new SSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
173         ret.setTcpNoDelay(true);
174         return ret;
175     }
176
177     /** Attempts a direct connection */
178     private Socket attemptDirect() {
179         try {
180             if (Log.verbose) Log.info(this, "attempting to create unproxied socket to " +
181                                      host + ":" + port + (ssl ? " [ssl]" : ""));
182             return getSocket(host, port, ssl, true);
183         } catch (IOException e) {
184             if (Log.on) Log.info(this, "exception in attemptDirect(): " + e);
185             return null;
186         }
187     }
188
189     /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
190     private Socket attemptHttpProxy(String proxyHost, int proxyPort) {
191         try {
192             if (Log.verbose) Log.info(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
193             Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
194
195             if (!ssl) {
196                 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
197                 return sock;
198             }
199
200             PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
201             BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
202             pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
203             pw.flush();
204             String s = br.readLine();
205             if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
206             while (br.readLine().length() > 0) { };
207             ((SSL)sock).negotiate();
208             return sock;
209
210         } catch (IOException e) {
211             if (Log.on) Log.info(this, "exception in attemptHttpProxy(): " + e);
212             return null;
213         }
214     }
215
216     /**
217      *  Implements SOCKSv4 with v4a DNS extension
218      *  @see http://www.socks.nec.com/protocol/socks4.protocol
219      *  @see http://www.socks.nec.com/protocol/socks4a.protocol
220      */
221     private Socket attemptSocksProxy(String proxyHost, int proxyPort) {
222
223         // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
224         InetAddress addr = null;
225         try { addr = InetAddress.getByName(host); } catch (Exception e) { }
226
227         if (Log.verbose) Log.info(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
228                                  " proxied socket using proxy " + proxyHost + ":" + proxyPort);
229
230         try {
231             Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
232             
233             DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
234             dos.writeByte(0x04);                         // SOCKSv4(a)
235             dos.writeByte(0x01);                         // CONNECT
236             dos.writeShort(port & 0xffff);               // port
237             if (addr == null) dos.writeInt(0x00000001);  // bogus IP
238             else dos.write(addr.getAddress());           // actual IP
239             dos.writeByte(0x00);                         // no userid
240             if (addr == null) {
241                 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
242                 pw.print(host);
243                 pw.flush();
244                 dos.writeByte(0x00);                     // hostname null terminator
245             }
246             dos.flush();
247
248             DataInputStream dis = new DataInputStream(sock.getInputStream());
249             dis.readByte();                              // reply version
250             byte success = dis.readByte();               // success/fail
251             dis.skip(6);                                 // ip/port
252             
253             if ((int)(success & 0xff) == 90) {
254                 if (ssl) ((SSL)sock).negotiate();
255                 return sock;
256             }
257             if (Log.on) Log.info(this, "SOCKS server denied access, code " + (success & 0xff));
258             return null;
259
260         } catch (IOException e) {
261             if (Log.on) Log.info(this, "exception in attemptSocksProxy(): " + e);
262             return null;
263         }
264     }
265
266     /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
267     private Socket attemptPAC(org.xwt.js.JS pacFunc) {
268         if (Log.verbose) Log.info(this, "evaluating PAC script");
269         String pac = null;
270         try {
271             org.xwt.js.JSArray args = new org.xwt.js.JSArray();
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: XWT\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 Proxy() { }
653         
654         public String httpProxyHost = null;                  ///< the HTTP Proxy host to use
655         public int httpProxyPort = -1;                       ///< the HTTP Proxy port to use
656         public String httpsProxyHost = null;                 ///< seperate proxy for HTTPS
657         public int httpsProxyPort = -1;
658         public String socksProxyHost = null;                 ///< the SOCKS Proxy Host to use
659         public int socksProxyPort = -1;                      ///< the SOCKS Proxy Port to use
660         public String[] excluded = null;                     ///< hosts to be excluded from proxy use; wildcards permitted
661         public JS proxyAutoConfigFunction = null;  ///< the PAC script
662     
663         public static Proxy detectProxyViaManual() {
664             Proxy ret = new Proxy();
665         
666             ret.httpProxyHost = Platform.getEnv("http_proxy");
667             if (ret.httpProxyHost != null) {
668                 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
669                 if (ret.httpProxyHost.endsWith("/"))
670                     ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
671                 if (ret.httpProxyHost.indexOf(':') != -1) {
672                     ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
673                     ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
674                 } else {
675                     ret.httpProxyPort = 80;
676                 }
677             }
678         
679             ret.httpsProxyHost = Platform.getEnv("https_proxy");
680             if (ret.httpsProxyHost != null) {
681                 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
682                 if (ret.httpsProxyHost.endsWith("/"))
683                     ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
684                 if (ret.httpsProxyHost.indexOf(':') != -1) {
685                     ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
686                     ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
687                 } else {
688                     ret.httpsProxyPort = 80;
689                 }
690             }
691         
692             ret.socksProxyHost = Platform.getEnv("socks_proxy");
693             if (ret.socksProxyHost != null) {
694                 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
695                 if (ret.socksProxyHost.endsWith("/"))
696                     ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
697                 if (ret.socksProxyHost.indexOf(':') != -1) {
698                     ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
699                     ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
700                 } else {
701                     ret.socksProxyPort = 80;
702                 }
703             }
704         
705             String noproxy = Platform.getEnv("no_proxy");
706             if (noproxy != null) {
707                 StringTokenizer st = new StringTokenizer(noproxy, ",");
708                 ret.excluded = new String[st.countTokens()];
709                 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
710             }
711         
712             if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
713             return ret;
714         }
715     
716         public static JSScope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
717         public static JS getProxyAutoConfigFunction(String url) {
718             try { 
719                 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
720                 String s = null;
721                 String script = "";
722                 while((s = br.readLine()) != null) script += s + "\n";
723                 if (Log.on) Log.info(Proxy.class, "successfully retrieved WPAD PAC:");
724                 if (Log.on) Log.info(Proxy.class, script);
725             
726                 // MS CARP hack
727                 Vector carpHosts = new Vector();
728                 for(int i=0; i<script.length(); i++)
729                     if (script.regionMatches(i, "new Node(", 0, 9)) {
730                         String host = script.substring(i + 10, script.indexOf('\"', i + 11));
731                         if (Log.on) Log.info(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
732                         carpHosts.addElement(host);
733                     }
734                 if (carpHosts.size() > 0) {
735                     script = "function FindProxyForURL(url, host) {\nreturn \"";
736                     for(int i=0; i<carpHosts.size(); i++)
737                         script += "PROXY " + carpHosts.elementAt(i) + "; ";
738                     script += "\";\n}";
739                     if (Log.on) Log.info(Proxy.class, "DeCARPed PAC script:");
740                     if (Log.on) Log.info(Proxy.class, script);
741                 }
742
743                 JS scr = JS.fromReader("PAC script at " + url, 0, new StringReader(script));
744                 JS.cloneWithNewParentScope(scr, proxyAutoConfigRootScope).call(null, null, null, null, 0);
745                 return (JS)proxyAutoConfigRootScope.get("FindProxyForURL");
746             } catch (Exception e) {
747                 if (Log.on) {
748                     Log.info(Platform.class, "WPAD detection failed due to:");
749                     if (e instanceof JSExn) {
750                         try {
751                             org.xwt.js.JSArray arr = new org.xwt.js.JSArray();
752                             arr.addElement(((JSExn)e).getObject());
753                         } catch (Exception e2) {
754                             Log.info(Platform.class, e);
755                         }
756                     }
757                     else Log.info(Platform.class, e);
758                 }
759                 return null;
760             }
761         }
762
763
764         // Authorization ///////////////////////////////////////////////////////////////////////////////////
765
766         public static class Authorization {
767
768             static public String authorization = null;
769             static public String authorization2 = null;
770             static public Semaphore waitingForUser = new Semaphore();
771
772             public static synchronized void getPassword(final String realm, final String style,
773                                                         final String proxyIP, String oldAuth) {
774
775                 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
776                 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
777                 // a password, so we should reattempt authorization.
778
779                 if (authorization != oldAuth) return;
780                 if (Log.on) Log.info(Authorization.class, "displaying proxy authorization dialog");
781                 Scheduler.add(new Scheduler.Task() {
782                         public void perform() throws Exception {
783                             Box b = new Box();
784                             Template t = Template.buildTemplate(Stream.getInputStream((JS)Main.builtin.get("org/xwt/builtin/proxy_authorization.xwt")), new XWT(null));
785                             t.apply(b);
786                             b.put("realm", realm);
787                             b.put("proxyIP", proxyIP);
788                         }
789                     });
790
791                 waitingForUser.block();
792                 if (Log.on) Log.info(Authorization.class, "got proxy authorization info; re-attempting connection");
793             }
794         }
795
796
797         // ProxyAutoConfigRootJSScope ////////////////////////////////////////////////////////////////////
798
799         public static class ProxyAutoConfigRootScope extends JSScope.Global {
800
801             public ProxyAutoConfigRootScope() { super(); }
802         
803             public Object get(Object name) throws JSExn {
804                 //#switch(name)
805                 case "isPlainHostName": return METHOD;
806                 case "dnsDomainIs": return METHOD;
807                 case "localHostOrDomainIs": return METHOD;
808                 case "isResolvable": return METHOD;
809                 case "isInNet": return METHOD;
810                 case "dnsResolve": return METHOD;
811                 case "myIpAddress": return METHOD;
812                 case "dnsDomainLevels": return METHOD;
813                 case "shExpMatch": return METHOD;
814                 case "weekdayRange": return METHOD;
815                 case "dateRange": return METHOD;
816                 case "timeRange": return METHOD;
817                 case "ProxyConfig": return ProxyConfig;
818                 //#end
819                 return super.get(name);
820             }
821         
822             private static final JS proxyConfigBindings = new JS();
823             private static final JS ProxyConfig = new JS() {
824                     public Object get(Object name) {
825                         if (name.equals("bindings")) return proxyConfigBindings;
826                         return null;
827                     }
828                 };
829
830             public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
831                 //#switch(method)
832                 case "isPlainHostName": return (a0.toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
833                 case "dnsDomainIs": return (a0.toString().endsWith(a1.toString())) ? Boolean.TRUE : Boolean.FALSE;
834                 case "localHostOrDomainIs":
835                     return (a0.equals(a1) || (a0.toString().indexOf('.') == -1 && a1.toString().startsWith(a0.toString()))) ? T:F;
836                 case "isResolvable": try {
837                     return (InetAddress.getByName(a0.toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
838                 } catch (UnknownHostException e) { return F; }
839                 case "isInNet":
840                     if (nargs != 3) return Boolean.FALSE;
841                     try {
842                         byte[] host = InetAddress.getByName(a0.toString()).getAddress();
843                         byte[] net = InetAddress.getByName(a1.toString()).getAddress();
844                         byte[] mask = InetAddress.getByName(a2.toString()).getAddress();
845                         return ((host[0] & mask[0]) == net[0] &&
846                                 (host[1] & mask[1]) == net[1] &&
847                                 (host[2] & mask[2]) == net[2] &&
848                                 (host[3] & mask[3]) == net[3]) ?
849                             Boolean.TRUE : Boolean.FALSE;
850                     } catch (Exception e) {
851                         throw new JSExn("exception in isInNet(): " + e);
852                     }
853                 case "dnsResolve":
854                     try {
855                         return InetAddress.getByName(a0.toString()).getHostAddress();
856                     } catch (UnknownHostException e) {
857                         return null;
858                     }
859                 case "myIpAddress":
860                     try {
861                         return InetAddress.getLocalHost().getHostAddress();
862                     } catch (UnknownHostException e) {
863                         if (Log.on) Log.info(this, "strange... host does not know its own address");
864                         return null;
865                     }
866                 case "dnsDomainLevels":
867                     String s = a0.toString();
868                     int i = 0;
869                     while((i = s.indexOf('.', i)) != -1) i++;
870                     return new Integer(i);
871                 case "shExpMatch":
872                     StringTokenizer st = new StringTokenizer(a1.toString(), "*", false);
873                     String[] arr = new String[st.countTokens()];
874                     String s = a0.toString();
875                     for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
876                     return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
877                 case "weekdayRange":
878                     TimeZone tz = (nargs < 3 || a2 == null || !a2.equals("GMT")) ?
879                         TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
880                     Calendar c = new GregorianCalendar();
881                     c.setTimeZone(tz);
882                     c.setTime(new java.util.Date());
883                     java.util.Date d = c.getTime();
884                     int day = d.getDay();
885                     String d1s = a0.toString().toUpperCase();
886                     int d1 = 0, d2 = 0;
887                     for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
888                     
889                     if (nargs == 1)
890                         return d1 == day ? Boolean.TRUE : Boolean.FALSE;
891                     
892                     String d2s = a1.toString().toUpperCase();
893                     for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
894                     
895                     return ((d1 <= d2 && day >= d1 && day <= d2) || (d1 > d2 && (day >= d1 || day <= d2))) ? T : F;
896                     
897                 case "dateRange": throw new JSExn("XWT does not support dateRange() in PAC scripts");
898                 case "timeRange": throw new JSExn("XWT does not support timeRange() in PAC scripts");
899                 //#end
900                 return super.callMethod(method, a0, a1, a2, rest, nargs);
901             }       
902             private static boolean match(String[] arr, String s, int index) {
903                 if (index >= arr.length) return true;
904                 for(int i=0; i<s.length(); i++) {
905                     String s2 = s.substring(i);
906                     if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
907                 }
908                 return false;
909             }
910             public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
911         }
912
913
914         /**
915          *  An implementation of Microsoft's proprietary NTLM authentication protocol.  This code was derived from Eric
916          *  Glass's work, and is copyright as follows:
917          *
918          *  Copyright (c) 2003 Eric Glass     (eglass1 at comcast.net). 
919          *
920          *  Permission to use, copy, modify, and distribute this document for any purpose and without any fee is hereby
921          *  granted, provided that the above copyright notice and this list of conditions appear in all copies.
922          *  The most current version of this document may be obtained from http://davenport.sourceforge.net/ntlm.html .
923          */ 
924         public static class NTLM {
925             
926             public static final byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01,
927                                                             0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00 };
928             
929             /**
930              * Calculates the NTLM Response for the given challenge, using the
931              * specified password.
932              *
933              * @param password The user's password.
934              * @param challenge The Type 2 challenge from the server.
935              *
936              * @return The NTLM Response.
937              */
938             public static byte[] getNTLMResponse(String password, byte[] challenge)
939                 throws Exception {
940                 byte[] ntlmHash = ntlmHash(password);
941                 return lmResponse(ntlmHash, challenge);
942             }
943
944             /**
945              * Calculates the LM Response for the given challenge, using the specified
946              * password.
947              *
948              * @param password The user's password.
949              * @param challenge The Type 2 challenge from the server.
950              *
951              * @return The LM Response.
952              */
953             public static byte[] getLMResponse(String password, byte[] challenge)
954                 throws Exception {
955                 byte[] lmHash = lmHash(password);
956                 return lmResponse(lmHash, challenge);
957             }
958
959             /**
960              * Calculates the NTLMv2 Response for the given challenge, using the
961              * specified authentication target, username, password, target information
962              * block, and client challenge.
963              *
964              * @param target The authentication target (i.e., domain).
965              * @param user The username. 
966              * @param password The user's password.
967              * @param targetInformation The target information block from the Type 2
968              * message.
969              * @param challenge The Type 2 challenge from the server.
970              * @param clientChallenge The random 8-byte client challenge. 
971              *
972              * @return The NTLMv2 Response.
973              */
974             public static byte[] getNTLMv2Response(String target, String user,
975                                                    String password, byte[] targetInformation, byte[] challenge,
976                                                    byte[] clientChallenge) throws Exception {
977                 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
978                 byte[] blob = createBlob(targetInformation, clientChallenge);
979                 return lmv2Response(ntlmv2Hash, blob, challenge);
980             }
981
982             /**
983              * Calculates the LMv2 Response for the given challenge, using the
984              * specified authentication target, username, password, and client
985              * challenge.
986              *
987              * @param target The authentication target (i.e., domain).
988              * @param user The username.
989              * @param password The user's password.
990              * @param challenge The Type 2 challenge from the server.
991              * @param clientChallenge The random 8-byte client challenge.
992              *
993              * @return The LMv2 Response. 
994              */
995             public static byte[] getLMv2Response(String target, String user,
996                                                  String password, byte[] challenge, byte[] clientChallenge)
997                 throws Exception {
998                 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
999                 return lmv2Response(ntlmv2Hash, clientChallenge, challenge);
1000             }
1001
1002             /**
1003              * Calculates the NTLM2 Session Response for the given challenge, using the
1004              * specified password and client challenge.
1005              *
1006              * @param password The user's password.
1007              * @param challenge The Type 2 challenge from the server.
1008              * @param clientChallenge The random 8-byte client challenge.
1009              *
1010              * @return The NTLM2 Session Response.  This is placed in the NTLM
1011              * response field of the Type 3 message; the LM response field contains
1012              * the client challenge, null-padded to 24 bytes.
1013              */
1014             public static byte[] getNTLM2SessionResponse(String password,
1015                                                          byte[] challenge, byte[] clientChallenge) throws Exception {
1016                 byte[] ntlmHash = ntlmHash(password);
1017                 MD5Digest md5 = new MD5Digest();
1018                 md5.update(challenge, 0, challenge.length);
1019                 md5.update(clientChallenge, 0, clientChallenge.length);
1020                 byte[] sessionHash = new byte[8];
1021                 byte[] md5_out = new byte[md5.getDigestSize()];
1022                 md5.doFinal(md5_out, 0);
1023                 System.arraycopy(md5_out, 0, sessionHash, 0, 8);
1024                 return lmResponse(ntlmHash, sessionHash);
1025             }
1026
1027             /**
1028              * Creates the LM Hash of the user's password.
1029              *
1030              * @param password The password.
1031              *
1032              * @return The LM Hash of the given password, used in the calculation
1033              * of the LM Response.
1034              */
1035             private static byte[] lmHash(String password) throws Exception {
1036                 /*
1037                 byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
1038                 int length = java.lang.Math.min(oemPassword.length, 14);
1039                 byte[] keyBytes = new byte[14];
1040                 System.arraycopy(oemPassword, 0, keyBytes, 0, length);
1041                 Key lowKey = createDESKey(keyBytes, 0);
1042                 Key highKey = createDESKey(keyBytes, 7);
1043                 byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
1044                 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1045                 des.init(Cipher.ENCRYPT_MODE, lowKey);
1046                 byte[] lowHash = des.doFinal(magicConstant);
1047                 des.init(Cipher.ENCRYPT_MODE, highKey);
1048                 byte[] highHash = des.doFinal(magicConstant);
1049                 byte[] lmHash = new byte[16];
1050                 System.arraycopy(lowHash, 0, lmHash, 0, 8);
1051                 System.arraycopy(highHash, 0, lmHash, 8, 8);
1052                 return lmHash;
1053                 */
1054                 return null;
1055             }
1056
1057             /**
1058              * Creates the NTLM Hash of the user's password.
1059              *
1060              * @param password The password.
1061              *
1062              * @return The NTLM Hash of the given password, used in the calculation
1063              * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1064              */
1065             private static byte[] ntlmHash(String password) throws Exception {
1066                 byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
1067                 MD4Digest md4 = new MD4Digest();
1068                 md4.update(unicodePassword, 0, unicodePassword.length);
1069                 byte[] ret = new byte[md4.getDigestSize()];
1070                 return ret;
1071             }
1072
1073             /**
1074              * Creates the NTLMv2 Hash of the user's password.
1075              *
1076              * @param target The authentication target (i.e., domain).
1077              * @param user The username.
1078              * @param password The password.
1079              *
1080              * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1081              * and LMv2 Responses. 
1082              */
1083             private static byte[] ntlmv2Hash(String target, String user,
1084                                              String password) throws Exception {
1085                 byte[] ntlmHash = ntlmHash(password);
1086                 String identity = user.toUpperCase() + target.toUpperCase();
1087                 return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
1088             }
1089
1090             /**
1091              * Creates the LM Response from the given hash and Type 2 challenge.
1092              *
1093              * @param hash The LM or NTLM Hash.
1094              * @param challenge The server challenge from the Type 2 message.
1095              *
1096              * @return The response (either LM or NTLM, depending on the provided
1097              * hash).
1098              */
1099             private static byte[] lmResponse(byte[] hash, byte[] challenge)
1100                 throws Exception {
1101                 /*
1102                 byte[] keyBytes = new byte[21];
1103                 System.arraycopy(hash, 0, keyBytes, 0, 16);
1104                 Key lowKey = createDESKey(keyBytes, 0);
1105                 Key middleKey = createDESKey(keyBytes, 7);
1106                 Key highKey = createDESKey(keyBytes, 14);
1107                 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1108                 des.init(Cipher.ENCRYPT_MODE, lowKey);
1109                 byte[] lowResponse = des.doFinal(challenge);
1110                 des.init(Cipher.ENCRYPT_MODE, middleKey);
1111                 byte[] middleResponse = des.doFinal(challenge);
1112                 des.init(Cipher.ENCRYPT_MODE, highKey);
1113                 byte[] highResponse = des.doFinal(challenge);
1114                 byte[] lmResponse = new byte[24];
1115                 System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
1116                 System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
1117                 System.arraycopy(highResponse, 0, lmResponse, 16, 8);
1118                 return lmResponse;
1119                 */
1120                 return null;
1121             }
1122
1123             /**
1124              * Creates the LMv2 Response from the given hash, client data, and
1125              * Type 2 challenge.
1126              *
1127              * @param hash The NTLMv2 Hash.
1128              * @param clientData The client data (blob or client challenge).
1129              * @param challenge The server challenge from the Type 2 message.
1130              *
1131              * @return The response (either NTLMv2 or LMv2, depending on the
1132              * client data).
1133              */
1134             private static byte[] lmv2Response(byte[] hash, byte[] clientData,
1135                                                byte[] challenge) throws Exception {
1136                 byte[] data = new byte[challenge.length + clientData.length];
1137                 System.arraycopy(challenge, 0, data, 0, challenge.length);
1138                 System.arraycopy(clientData, 0, data, challenge.length,
1139                                  clientData.length);
1140                 byte[] mac = hmacMD5(data, hash);
1141                 byte[] lmv2Response = new byte[mac.length + clientData.length];
1142                 System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
1143                 System.arraycopy(clientData, 0, lmv2Response, mac.length,
1144                                  clientData.length);
1145                 return lmv2Response;
1146             }
1147
1148             /**
1149              * Creates the NTLMv2 blob from the given target information block and
1150              * client challenge.
1151              *
1152              * @param targetInformation The target information block from the Type 2
1153              * message.
1154              * @param clientChallenge The random 8-byte client challenge.
1155              *
1156              * @return The blob, used in the calculation of the NTLMv2 Response.
1157              */
1158             private static byte[] createBlob(byte[] targetInformation,
1159                                              byte[] clientChallenge) {
1160                 byte[] blobSignature = new byte[] {
1161                     (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1162                 };
1163                 byte[] reserved = new byte[] {
1164                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1165                 };
1166                 byte[] unknown1 = new byte[] {
1167                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1168                 };
1169                 byte[] unknown2 = new byte[] {
1170                     (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1171                 };
1172                 long time = System.currentTimeMillis();
1173                 time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
1174                 time *= 10000; // tenths of a microsecond.
1175                 // convert to little-endian byte array.
1176                 byte[] timestamp = new byte[8];
1177                 for (int i = 0; i < 8; i++) {
1178                     timestamp[i] = (byte) time;
1179                     time >>>= 8;
1180                 }
1181                 byte[] blob = new byte[blobSignature.length + reserved.length +
1182                                        timestamp.length + clientChallenge.length +
1183                                        unknown1.length + targetInformation.length +
1184                                        unknown2.length];
1185                 int offset = 0;
1186                 System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
1187                 offset += blobSignature.length;
1188                 System.arraycopy(reserved, 0, blob, offset, reserved.length);
1189                 offset += reserved.length;
1190                 System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
1191                 offset += timestamp.length;
1192                 System.arraycopy(clientChallenge, 0, blob, offset,
1193                                  clientChallenge.length);
1194                 offset += clientChallenge.length;
1195                 System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
1196                 offset += unknown1.length;
1197                 System.arraycopy(targetInformation, 0, blob, offset,
1198                                  targetInformation.length);
1199                 offset += targetInformation.length;
1200                 System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
1201                 return blob;
1202             }
1203
1204             /**
1205              * Calculates the HMAC-MD5 hash of the given data using the specified
1206              * hashing key.
1207              *
1208              * @param data The data for which the hash will be calculated. 
1209              * @param key The hashing key.
1210              *
1211              * @return The HMAC-MD5 hash of the given data.
1212              */
1213             private static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
1214                 byte[] ipad = new byte[64];
1215                 byte[] opad = new byte[64];
1216                 for (int i = 0; i < 64; i++) {
1217                     ipad[i] = (byte) 0x36;
1218                     opad[i] = (byte) 0x5c;
1219                 }
1220                 for (int i = key.length - 1; i >= 0; i--) {
1221                     ipad[i] ^= key[i];
1222                     opad[i] ^= key[i];
1223                 }
1224                 byte[] content = new byte[data.length + 64];
1225                 System.arraycopy(ipad, 0, content, 0, 64);
1226                 System.arraycopy(data, 0, content, 64, data.length);
1227                 MD5Digest md5 = new MD5Digest();
1228                 md5.update(content, 0, content.length);
1229                 data = new byte[md5.getDigestSize()];
1230                 md5.doFinal(data, 0);
1231                 content = new byte[data.length + 64];
1232                 System.arraycopy(opad, 0, content, 0, 64);
1233                 System.arraycopy(data, 0, content, 64, data.length);
1234                 md5 = new MD5Digest();
1235                 md5.update(content, 0, content.length);
1236                 byte[] ret = new byte[md5.getDigestSize()];
1237                 md5.doFinal(ret, 0);
1238                 return ret;
1239             }
1240
1241             /**
1242              * Creates a DES encryption key from the given key material.
1243              *
1244              * @param bytes A byte array containing the DES key material.
1245              * @param offset The offset in the given byte array at which
1246              * the 7-byte key material starts.
1247              *
1248              * @return A DES encryption key created from the key material
1249              * starting at the specified offset in the given byte array.
1250              */
1251                 /*
1252             private static Key createDESKey(byte[] bytes, int offset) {
1253                 byte[] keyBytes = new byte[7];
1254                 System.arraycopy(bytes, offset, keyBytes, 0, 7);
1255                 byte[] material = new byte[8];
1256                 material[0] = keyBytes[0];
1257                 material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
1258                 material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
1259                 material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
1260                 material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
1261                 material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
1262                 material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
1263                 material[7] = (byte) (keyBytes[6] << 1);
1264                 oddParity(material);
1265                 return new SecretKeySpec(material, "DES");
1266             }
1267                 */
1268
1269             /**
1270              * Applies odd parity to the given byte array.
1271              *
1272              * @param bytes The data whose parity bits are to be adjusted for
1273              * odd parity.
1274              */
1275             private static void oddParity(byte[] bytes) {
1276                 for (int i = 0; i < bytes.length; i++) {
1277                     byte b = bytes[i];
1278                     boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1279                                             (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1280                                             (b >>> 1)) & 0x01) == 0;
1281                     if (needsParity) {
1282                         bytes[i] |= (byte) 0x01;
1283                     } else {
1284                         bytes[i] &= (byte) 0xfe;
1285                     }
1286                 }
1287             }
1288
1289         }
1290     }
1291 }