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