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