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