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