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