1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.ibex.util.*;
8 import org.ibex.crypto.*;
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.
16 public static InetAddress originAddr = null;
17 public static String originHost = null;
20 public static String userAgent = "Ibex";
22 // Cookies //////////////////////////////////////////////////////////////////////////////
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) {
36 this.expires = expires;
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());
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()))
58 ret.append(cookie.name);
60 ret.append(cookie.value);
64 //ret.setLength(ret.length() - 2);
65 return ret.toString();
67 public void setCookie(String header, String defaultDomain) {
70 String domain = defaultDomain;
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;
81 String start = s.substring(0, s.indexOf('='));
82 String end = s.substring(s.indexOf('=')+1);
88 //#switch(start.toLowerCase())
89 case "domain": domain = end;
90 case "path": path = end;
91 case "expires": expires = new Date(end);
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));
100 // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
102 public HTTP(String url) { this(url, false); }
103 public HTTP(String url, boolean skipResolveCheck) { originalUrl = url; this.skipResolveCheck = skipResolveCheck; }
105 /** Performs an HTTP GET request */
106 public InputStream GET(String referer, Cookie.Jar cookies) throws IOException {
107 return makeRequest(null, null, referer, cookies); }
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); }
113 public static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
115 public static HTTP stdio = new HTTP("stdio:");
118 // Statics ///////////////////////////////////////////////////////////////////////////////////////////////
120 static Hash resolvedHosts = new Hash(); ///< cache for resolveAndCheckIfFirewalled()
121 private static Hash authCache = new Hash(); ///< cache of userInfo strings, keyed on originalUrl
124 // Instance Data ///////////////////////////////////////////////////////////////////////////////////////////////
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
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
143 Semaphore okToRecieve = null;
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
149 private InputStream makeRequest(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
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;
157 sendRequest(contentType, content, referer, cookies);
158 } catch (IOException e) {
162 blockOn = okToRecieve;
163 releaseMe = okToRecieve = new Semaphore();
166 // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
167 boolean doRelease = true;
169 if (blockOn != null) blockOn.block();
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).
175 throw new HTTPException("a previous pipelined call messed up the socket");
177 Hashtable h = in == null ? null : parseHeaders(in, cookies);
179 if (firstRequest) throw new HTTPException("server closed the socket with no response");
180 // sometimes the server chooses to close the stream between requests
183 return makeRequest(contentType, content, referer, cookies);
186 String reply = h.get("STATUSLINE").toString();
188 if (reply.startsWith("407") || reply.startsWith("401")) {
190 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
191 else doWebAuth(h, content == null ? "GET" : "POST");
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...");
197 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
198 new HTTPInputStream(in, cl, releaseMe).close();
201 return makeRequest(contentType, content, referer, cookies);
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);
213 throw new HTTPException("HTTP Error: " + reply);
217 } catch (IOException e) { reset(); throw e;
218 } finally { if (doRelease) releaseMe.release();
223 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
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
229 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
232 if (resolvedHosts.get(host) != null) return;
234 // if all scripts are trustworthy (local FS), continue
235 if (originAddr == null) return;
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");
247 } catch (UnknownHostException uhe) { }
250 if (Platform.detectProxy() == null)
251 throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
256 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
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);
264 /** Attempts a direct connection */
265 private Socket attemptDirect() {
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);
276 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
277 private Socket attemptHttpProxy(String proxyHost, int proxyPort) {
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);
283 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
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");
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();
297 } catch (IOException e) {
298 if (Log.on) Log.info(this, "exception in attemptHttpProxy(): " + e);
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
308 private Socket attemptSocksProxy(String proxyHost, int proxyPort) {
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) { }
314 if (Log.verbose) Log.info(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
315 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
318 Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
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
328 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
331 dos.writeByte(0x00); // hostname null terminator
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
340 if ((int)(success & 0xff) == 90) {
341 if (ssl) ((SSL)sock).negotiate();
344 if (Log.on) Log.info(this, "SOCKS server denied access, code " + (success & 0xff));
347 } catch (IOException e) {
348 if (Log.on) Log.info(this, "exception in attemptSocksProxy(): " + e);
353 /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
355 private Socket attemptPAC(org.ibex.js.JS pacFunc) {
356 if (Log.verbose) Log.info(this, "evaluating PAC script");
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);
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 + "\"...");
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");
386 if (Log.on) Log.info(this, "all PAC results exhausted");
391 // Everything Else ////////////////////////////////////////////////////////////////////////////
393 private synchronized void connect() throws IOException {
394 if (originalUrl.equals("stdio:")) { in = new BufferedInputStream(System.in); return; }
396 if (in == null) in = new BufferedInputStream(sock.getInputStream());
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);
410 if (url.startsWith("https:")) {
412 } else if (!url.startsWith("http:")) {
413 throw new IOException("HTTP only supports http/https urls");
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(':'));
423 port = ssl ? 443 : 80;
425 if (!skipResolveCheck) resolveAndCheckIfFirewalled(temphost);
427 if (Log.verbose) Log.info(this, "creating HTTP object for connection to " + host + ":" + port);
430 Proxy pi = Platform.detectProxy();
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);
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());
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");
458 pw.print("GET " + path + " HTTP/1.1\r\n");
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");
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");
470 pw.print(content == null ? "\r\n" : content);
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());
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"))));
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");
487 if (path2.startsWith("http://") || path2.startsWith("https://")) {
488 path2 = path2.substring(path2.indexOf("://") + 3);
489 path2 = path2.substring(path2.indexOf('/'));
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,
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)) + "\", " +
506 throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
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");
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);
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);
526 if (style.equals("Basic")) {
527 Proxy.Authorization.authorization2 =
528 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("UTF8")));
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 =
536 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) +
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)) + "\", " +
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) {
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) + " ";
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));
564 // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
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 {
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
575 HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
577 this.releaseMe = releaseMe;
578 this.contentLength = length;
579 this.length = length == -1 ? 0 : length;
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();
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;
597 private void readChunk() throws IOException {
598 if (chunkedDone) return;
599 if (!firstChunk) super.skip(2); // CRLF
601 String chunkLen = "";
603 int i = super.read();
604 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
606 // FEATURE: handle chunking extensions
614 length = Integer.parseInt(chunkLen.trim(), 16);
615 if (length == 0) chunkedDone = true;
618 public int read(byte[] b, int off, int len) throws IOException {
619 boolean good = false;
621 if (length == 0 && contentLength == -1) {
623 if (chunkedDone) { good = true; return -1; }
625 if (length == 0) { good = true; return -1; }
627 if (len > length) len = length;
628 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
639 public void close() throws IOException {
640 if (contentLength == -1) {
641 while(!chunkedDone) {
642 if (length != 0) skip(length);
647 if (length != 0) skip(length);
649 if (releaseMe != null) releaseMe.release();
660 // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
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();
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];
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')
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);
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(' ')));
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);
703 private Hashtable parseAuthenticationChallenge(String s) {
704 Hashtable ret = new Hashtable();
707 ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
708 s = s.substring(s.indexOf(' ')).trim();
710 while (s.length() > 0) {
712 String key = s.substring(0, s.indexOf('='));
713 s = s.substring(s.indexOf('=') + 1);
714 if (s.charAt(0) == '\"') {
716 val = s.substring(0, s.indexOf('\"'));
717 s = s.substring(s.indexOf('\"') + 1);
719 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
720 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
722 if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
729 private String H(String s) throws IOException {
730 byte[] b = s.getBytes("UTF8");
732 md5.update(b, 0, b.length);
733 byte[] out = new byte[md5.getDigestSize()];
736 for(int i=0; i<out.length; i++) {
737 ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
738 ret += "0123456789abcdef".charAt(out[i] & 0x0f);
744 // Proxy ///////////////////////////////////////////////////////////
746 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
747 public static class Proxy {
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
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
761 public static Proxy detectProxyViaManual() {
762 Proxy ret = new Proxy();
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(':'));
773 ret.httpProxyPort = 80;
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(':'));
786 ret.httpsProxyPort = 80;
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(':'));
799 ret.socksProxyPort = 80;
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();
810 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
816 public static JSScope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
817 public static JS getProxyAutoConfigFunction(String url) {
819 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
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);
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);
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) + "; ";
839 if (Log.on) Log.info(Proxy.class, "DeCARPed PAC script:");
840 if (Log.on) Log.info(Proxy.class, script);
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) {
848 Log.info(Platform.class, "WPAD detection failed due to:");
849 if (e instanceof JSExn) {
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);
857 else Log.info(Platform.class, e);
864 // Authorization ///////////////////////////////////////////////////////////////////////////////////
866 public static class Authorization {
868 static public String authorization = null;
869 static public String authorization2 = null;
870 static public Semaphore waitingForUser = new Semaphore();
872 // FIXME: temporarily disabled so we can use HTTP outside the core
874 public static synchronized void getPassword(final String realm, final String style,
875 final String proxyIP, String oldAuth) throws IOException {
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.
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 {
888 //Template.buildTemplate("org/ibex/builtin/proxy_authorization.ibex", Stream.getInputStream((JS)Main.builtin.get("org/ibex/builtin/proxy_authorization.ibex")), new Ibex(null));
890 b.put("realm", realm);
891 b.put("proxyIP", proxyIP);
895 waitingForUser.block();
896 if (Log.on) Log.info(Authorization.class, "got proxy authorization info; re-attempting connection");
902 // ProxyAutoConfigRootJSScope ////////////////////////////////////////////////////////////////////
904 public static class ProxyAutoConfigRootScope extends JSScope.Global {
906 public ProxyAutoConfigRootScope() { super(); }
908 public Object get(Object name) throws JSExn {
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;
924 return super.get(name);
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;
935 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
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; }
945 if (nargs != 3) return Boolean.FALSE;
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);
960 return InetAddress.getByName(a0.toString()).getHostAddress();
961 } catch (UnknownHostException e) {
966 return InetAddress.getLocalHost().getHostAddress();
967 } catch (UnknownHostException e) {
968 if (Log.on) Log.info(this, "strange... host does not know its own address");
971 case "dnsDomainLevels":
972 String s = a0.toString();
974 while((i = s.indexOf('.', i)) != -1) i++;
975 return new Integer(i);
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;
983 TimeZone tz = (nargs < 3 || a2 == null || !a2.equals("GMT")) ?
984 TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
985 Calendar c = new GregorianCalendar();
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();
992 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
995 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
997 String d2s = a1.toString().toUpperCase();
998 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
1000 return ((d1 <= d2 && day >= d1 && day <= d2) || (d1 > d2 && (day >= d1 || day <= d2))) ? T : F;
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");
1005 return super.callMethod(method, a0, a1, a2, rest, nargs);
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;
1015 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
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:
1023 * Copyright (c) 2003 Eric Glass (eglass1 at comcast.net).
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 .
1029 public static class NTLM {
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 };
1035 * Calculates the NTLM Response for the given challenge, using the
1036 * specified password.
1038 * @param password The user's password.
1039 * @param challenge The Type 2 challenge from the server.
1041 * @return The NTLM Response.
1043 public static byte[] getNTLMResponse(String password, byte[] challenge)
1044 throws UnsupportedEncodingException {
1045 byte[] ntlmHash = ntlmHash(password);
1046 return lmResponse(ntlmHash, challenge);
1050 * Calculates the LM Response for the given challenge, using the specified
1053 * @param password The user's password.
1054 * @param challenge The Type 2 challenge from the server.
1056 * @return The LM Response.
1058 public static byte[] getLMResponse(String password, byte[] challenge)
1060 byte[] lmHash = lmHash(password);
1061 return lmResponse(lmHash, challenge);
1065 * Calculates the NTLMv2 Response for the given challenge, using the
1066 * specified authentication target, username, password, target information
1067 * block, and client challenge.
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
1074 * @param challenge The Type 2 challenge from the server.
1075 * @param clientChallenge The random 8-byte client challenge.
1077 * @return The NTLMv2 Response.
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);
1088 * Calculates the LMv2 Response for the given challenge, using the
1089 * specified authentication target, username, password, and client
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.
1098 * @return The LMv2 Response.
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);
1108 * Calculates the NTLM2 Session Response for the given challenge, using the
1109 * specified password and client challenge.
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.
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.
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);
1133 * Creates the LM Hash of the user's password.
1135 * @param password The password.
1137 * @return The LM Hash of the given password, used in the calculation
1138 * of the LM Response.
1140 private static byte[] lmHash(String password) {
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);
1163 * Creates the NTLM Hash of the user's password.
1165 * @param password The password.
1167 * @return The NTLM Hash of the given password, used in the calculation
1168 * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1170 private static byte[] ntlmHash(String password) throws UnsupportedEncodingException {
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()];
1183 * Creates the NTLMv2 Hash of the user's password.
1185 * @param target The authentication target (i.e., domain).
1186 * @param user The username.
1187 * @param password The password.
1189 * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1190 * and LMv2 Responses.
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);
1200 * Creates the LM Response from the given hash and Type 2 challenge.
1202 * @param hash The LM or NTLM Hash.
1203 * @param challenge The server challenge from the Type 2 message.
1205 * @return The response (either LM or NTLM, depending on the provided
1208 private static byte[] lmResponse(byte[] hash, byte[] challenge)
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);
1233 * Creates the LMv2 Response from the given hash, client data, and
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.
1240 * @return The response (either NTLMv2 or LMv2, depending on the
1243 private static byte[] lmv2Response(byte[] hash, byte[] clientData,
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,
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,
1254 return lmv2Response;
1258 * Creates the NTLMv2 blob from the given target information block and
1261 * @param targetInformation The target information block from the Type 2
1263 * @param clientChallenge The random 8-byte client challenge.
1265 * @return The blob, used in the calculation of the NTLMv2 Response.
1267 private static byte[] createBlob(byte[] targetInformation,
1268 byte[] clientChallenge) {
1269 byte[] blobSignature = new byte[] {
1270 (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1272 byte[] reserved = new byte[] {
1273 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1275 byte[] unknown1 = new byte[] {
1276 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1278 byte[] unknown2 = new byte[] {
1279 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
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;
1290 byte[] blob = new byte[blobSignature.length + reserved.length +
1291 timestamp.length + clientChallenge.length +
1292 unknown1.length + targetInformation.length +
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);
1314 * Calculates the HMAC-MD5 hash of the given data using the specified
1317 * @param data The data for which the hash will be calculated.
1318 * @param key The hashing key.
1320 * @return The HMAC-MD5 hash of the given data.
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;
1329 for (int i = key.length - 1; i >= 0; i--) {
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);
1344 md5.update(content, 0, content.length);
1345 byte[] ret = new byte[md5.getDigestSize()];
1346 md5.doFinal(ret, 0);
1351 * Creates a DES encryption key from the given key material.
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.
1357 * @return A DES encryption key created from the key material
1358 * starting at the specified offset in the given byte array.
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");
1379 * Applies odd parity to the given byte array.
1381 * @param bytes The data whose parity bits are to be adjusted for
1384 private static void oddParity(byte[] bytes) {
1385 for (int i = 0; i < bytes.length; i++) {
1387 boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1388 (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1389 (b >>> 1)) & 0x01) == 0;
1391 bytes[i] |= (byte) 0x01;
1393 bytes[i] &= (byte) 0xfe;