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