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;
19 // FIXME: HACK: these shouldn't be set globally
20 public static String userAgent = "Ibex";
21 public static boolean allowRedirects = true;
23 // Cookies //////////////////////////////////////////////////////////////////////////////
25 public static class Cookie {
26 public final String name;
27 public final String value;
28 public final String domain;
29 public final String path;
30 public final Date expires;
31 public final boolean secure;
32 public Cookie(String name, String value, String domain, String path, Date expires, boolean secure) {
37 this.expires = expires;
41 // FIXME: this could be much more efficient
42 // FIXME currently only implements http://wp.netscape.com/newsref/std/cookie_spec.html
43 public static class Jar {
44 private Hash h = new Hash();
45 public String getCookieHeader(String domain, String path, boolean secure) {
46 StringBuffer ret = new StringBuffer("Cookie: ");
47 Enumeration e = h.keys();
48 while (e.hasMoreElements()) {
49 Vec v = (Vec)h.get(e.nextElement());
51 for(int i=0; i<v.size(); i++) {
52 Cookie c = (Cookie)v.elementAt(i);
53 if (domain.endsWith(c.domain) &&
54 (c.path == null || path.startsWith(c.path)) &&
55 (cookie == null || c.domain.length() > cookie.domain.length()))
59 ret.append(cookie.name);
61 ret.append(cookie.value);
65 //ret.setLength(ret.length() - 2);
66 return ret.toString();
68 public void setCookie(String header, String defaultDomain) {
71 String domain = defaultDomain;
74 boolean secure = false;
75 StringTokenizer st = new StringTokenizer(header, ";");
76 while(st.hasMoreTokens()) {
77 String s = st.nextToken();
78 if (s.indexOf('=') == -1) {
79 if (s.equals("secure")) secure = true;
82 String start = s.substring(0, s.indexOf('='));
83 String end = s.substring(s.indexOf('=')+1);
89 //#switch(start.toLowerCase())
90 case "domain": domain = end;
91 case "path": path = end;
92 case "expires": expires = new Date(end);
95 if (h.get(name) == null) h.put(name, new Vec());
96 ((Vec)h.get(name)).addElement(new Cookie(name, value, domain, path, expires, secure));
101 // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
103 public HTTP(String url) { this(url, false); }
104 public HTTP(String url, boolean skipResolveCheck) { originalUrl = url; this.skipResolveCheck = skipResolveCheck; }
106 /** Performs an HTTP GET request */
107 public InputStream GET(String referer, Cookie.Jar cookies) throws IOException {
108 return makeRequest(null, null, referer, cookies); }
110 /** Performs an HTTP POST request; content is additional headers, blank line, and body */
111 public InputStream POST(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
112 return makeRequest(contentType, content, referer, cookies); }
114 public static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
116 public static HTTP stdio = new HTTP("stdio:");
119 // Statics ///////////////////////////////////////////////////////////////////////////////////////////////
121 static Hash resolvedHosts = new Hash(); ///< cache for resolveAndCheckIfFirewalled()
122 private static Hash authCache = new Hash(); ///< cache of userInfo strings, keyed on originalUrl
125 // Instance Data ///////////////////////////////////////////////////////////////////////////////////////////////
127 final String originalUrl; ///< the URL as passed to the original constructor; this is never changed
128 String url = null; ///< the URL to connect to; this is munged when the url is parsed */
129 String host = null; ///< the host to connect to
130 int port = -1; ///< the port to connect on
131 boolean ssl = false; ///< true if SSL (HTTPS) should be used
132 String path = null; ///< the path (URI) to retrieve on the server
133 Socket sock = null; ///< the socket
134 InputStream in = null; ///< the socket's inputstream
135 String userInfo = null; ///< the username and password portions of the URL
136 boolean firstRequest = true; ///< true iff this is the first request to be made on this socket
137 boolean skipResolveCheck = false; ///< allowed to skip the resolve check when downloading PAC script
138 boolean proxied = false; ///< true iff we're using a proxy
140 /** this is null if the current request is the first request on
141 * this HTTP connection; otherwise it is a Semaphore which will be
142 * released once the request ahead of us has recieved its response
144 Semaphore okToRecieve = null;
147 * This method isn't synchronized; however, only one thread can be in the inner synchronized block at a time, and the rest of
148 * the method is protected by in-order one-at-a-time semaphore lock-steps
150 private InputStream makeRequest(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
152 // Step 1: send the request and establish a semaphore to stop any requests that pipeline after us
153 Semaphore blockOn = null;
154 Semaphore releaseMe = null;
158 sendRequest(contentType, content, referer, cookies);
159 } catch (IOException e) {
163 blockOn = okToRecieve;
164 releaseMe = okToRecieve = new Semaphore();
167 // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
168 boolean doRelease = true;
170 if (blockOn != null) blockOn.block();
172 // previous call wrecked the socket connection, but we already sent our request, so we can't just retry --
173 // this could cause the server to receive the request twice, which could be bad (think of the case where the
174 // server call causes Amazon.com to ship you an item with one-click purchasing).
176 throw new HTTPException("a previous pipelined call messed up the socket");
178 Hashtable h = in == null ? null : parseHeaders(in, cookies);
180 if (firstRequest) throw new HTTPException("server closed the socket with no response");
181 // sometimes the server chooses to close the stream between requests
184 return makeRequest(contentType, content, referer, cookies);
187 String reply = h.get("STATUSLINE").toString();
189 if (reply.startsWith("407") || reply.startsWith("401")) {
191 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
192 else doWebAuth(h, content == null ? "GET" : "POST");
194 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
195 if (Log.on) Log.info(this, "proxy returned an HTTP/1.0 reply with no content-length...");
198 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
199 new HTTPInputStream(in, cl, releaseMe).close();
202 return makeRequest(contentType, content, referer, cookies);
204 } else if (reply.startsWith("3") && allowRedirects) {
205 String location = (String)h.get("location");
206 if (location == null) throw new HTTPException("Got HTTP " + reply.substring(0, 3) + " but no Location header");
207 Log.info(HTTP.class, "redirecting to " + location);
209 return new HTTP(location).POST(contentType, content, url, cookies);
211 return new HTTP(location).GET(url, cookies);
213 } else if (reply.startsWith("2")) {
214 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
215 throw new HTTPException("Ibex does not support HTTP/1.0 servers which fail to return the Content-Length header");
216 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
217 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
218 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
223 throw new HTTPException("HTTP Error: " + reply);
227 } catch (IOException e) { reset(); throw e;
228 } finally { if (doRelease) releaseMe.release();
233 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
236 * resolves the hostname and returns it as a string in the form "x.y.z.w"
237 * @throws HTTPException if the host falls within a firewalled netblock
239 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
242 if (resolvedHosts.get(host) != null) return;
244 // if all scripts are trustworthy (local FS), continue
245 if (originAddr == null) return;
249 InetAddress addr = InetAddress.getByName(host);
250 byte[] quadbyte = addr.getAddress();
251 if ((quadbyte[0] == 10 ||
252 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
253 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(originAddr))
254 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() +
255 "] is in a firewalled netblock");
257 } catch (UnknownHostException uhe) { }
260 if (Platform.detectProxy() == null)
261 throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
266 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
268 private Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
269 Socket ret = ssl ? new SSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
270 ret.setTcpNoDelay(true);
274 /** Attempts a direct connection */
275 private Socket attemptDirect() {
277 Log.info(this, "attempting to create unproxied socket to " +
278 host + ":" + port + (ssl ? " [ssl]" : ""));
279 return getSocket(host, port, ssl, true);
280 } catch (IOException e) {
281 if (Log.on) Log.info(this, "exception in attemptDirect(): " + e);
286 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
287 private Socket attemptHttpProxy(String proxyHost, int proxyPort) {
289 if (Log.verbose) Log.info(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
290 Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
293 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
297 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
298 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
299 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
301 String s = br.readLine();
302 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
303 while (br.readLine().length() > 0) { };
304 ((SSL)sock).negotiate();
307 } catch (IOException e) {
308 if (Log.on) Log.info(this, "exception in attemptHttpProxy(): " + e);
314 * Implements SOCKSv4 with v4a DNS extension
315 * @see http://www.socks.nec.com/protocol/socks4.protocol
316 * @see http://www.socks.nec.com/protocol/socks4a.protocol
318 private Socket attemptSocksProxy(String proxyHost, int proxyPort) {
320 // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
321 InetAddress addr = null;
322 try { addr = InetAddress.getByName(host); } catch (Exception e) { }
324 if (Log.verbose) Log.info(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
325 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
328 Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
330 DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
331 dos.writeByte(0x04); // SOCKSv4(a)
332 dos.writeByte(0x01); // CONNECT
333 dos.writeShort(port & 0xffff); // port
334 if (addr == null) dos.writeInt(0x00000001); // bogus IP
335 else dos.write(addr.getAddress()); // actual IP
336 dos.writeByte(0x00); // no userid
338 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
341 dos.writeByte(0x00); // hostname null terminator
345 DataInputStream dis = new DataInputStream(sock.getInputStream());
346 dis.readByte(); // reply version
347 byte success = dis.readByte(); // success/fail
348 dis.skip(6); // ip/port
350 if ((int)(success & 0xff) == 90) {
351 if (ssl) ((SSL)sock).negotiate();
354 if (Log.on) Log.info(this, "SOCKS server denied access, code " + (success & 0xff));
357 } catch (IOException e) {
358 if (Log.on) Log.info(this, "exception in attemptSocksProxy(): " + e);
363 /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
365 private Socket attemptPAC(org.ibex.js.JS pacFunc) {
366 if (Log.verbose) Log.info(this, "evaluating PAC script");
369 Object obj = pacFunc.call(url, host, null, null, 2);
370 if (Log.verbose) Log.info(this, " PAC script returned \"" + obj + "\"");
371 pac = obj.toString();
372 } catch (Throwable e) {
373 if (Log.on) Log.info(this, "PAC script threw exception " + e);
377 StringTokenizer st = new StringTokenizer(pac, ";", false);
378 while (st.hasMoreTokens()) {
379 String token = st.nextToken().trim();
380 if (Log.verbose) Log.info(this, " trying \"" + token + "\"...");
383 if (token.startsWith("DIRECT"))
384 ret = attemptDirect();
385 else if (token.startsWith("PROXY"))
386 ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
387 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
388 else if (token.startsWith("SOCKS"))
389 ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
390 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
391 if (ret != null) return ret;
392 } catch (Throwable e) {
393 if (Log.on) Log.info(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
396 if (Log.on) Log.info(this, "all PAC results exhausted");
401 // Everything Else ////////////////////////////////////////////////////////////////////////////
403 private synchronized void connect() throws IOException {
404 if (originalUrl.equals("stdio:")) { in = new BufferedInputStream(System.in); return; }
406 if (in == null) in = new BufferedInputStream(sock.getInputStream());
409 // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
410 String url = originalUrl;
411 userInfo = url.substring(url.indexOf("://") + 3);
412 userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
413 if (userInfo.indexOf('@') != -1) {
414 userInfo = userInfo.substring(0, userInfo.indexOf('@'));
415 url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
420 if (url.startsWith("https:")) {
422 } else if (!url.startsWith("http:")) {
423 throw new IOException("HTTP only supports http/https urls");
425 if (url.indexOf("://") == -1) throw new IOException("URLs must contain a ://");
426 String temphost = url.substring(url.indexOf("://") + 3);
427 path = temphost.substring(temphost.indexOf('/'));
428 temphost = temphost.substring(0, temphost.indexOf('/'));
429 if (temphost.indexOf(':') != -1) {
430 port = Integer.parseInt(temphost.substring(temphost.indexOf(':')+1));
431 temphost = temphost.substring(0, temphost.indexOf(':'));
433 port = ssl ? 443 : 80;
435 if (!skipResolveCheck) resolveAndCheckIfFirewalled(temphost);
437 if (Log.verbose) Log.info(this, "creating HTTP object for connection to " + host + ":" + port);
440 Proxy pi = Platform.detectProxy();
443 for(int i=0; i<pi.excluded.length; i++) if (host.equals(pi.excluded[i])) break OUTER;
444 if (sock == null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
445 if (sock == null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost,pi.httpsProxyPort);
446 if (sock == null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
447 if (sock == null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
451 proxied = sock != null;
452 if (sock == null) sock = attemptDirect();
453 if (sock == null) throw new HTTPException("unable to contact host " + host);
454 if (in == null) in = new BufferedInputStream(sock.getInputStream());
457 private void sendRequest(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
458 PrintWriter pw = new PrintWriter(new OutputStreamWriter(originalUrl.equals("stdio:") ?
459 System.out : sock.getOutputStream()));
460 if (content != null) {
461 pw.print("POST " + path + " HTTP/1.0\r\n"); // FIXME chunked encoding
462 int contentLength = content.substring(0, 2).equals("\r\n") ?
463 content.length() - 2 :
464 (content.length() - content.indexOf("\r\n\r\n") - 4);
465 pw.print("Content-Length: " + contentLength + "\r\n");
466 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
468 pw.print("GET " + path + " HTTP/1.1\r\n");
471 if (cookies != null) pw.print(cookies.getCookieHeader(host, path, ssl));
472 pw.print("User-Agent: " + userAgent + "\r\n");
473 pw.print("Accept-encoding: gzip\r\n");
474 pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
475 if (proxied) pw.print("X-RequestOrigin: " + originHost + "\r\n");
477 if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: "+Proxy.Authorization.authorization2+"\r\n");
478 if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
480 pw.print(content == null ? "\r\n" : content);
485 private void doWebAuth(Hashtable h0, String method) throws IOException {
486 if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
487 Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
489 if (h.get("AUTHTYPE").equals("Basic")) {
490 if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
491 authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("UTF8"))));
493 } else if (h.get("AUTHTYPE").equals("Digest")) {
494 if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale")))
495 throw new HTTPException("username/password rejected");
497 if (path2.startsWith("http://") || path2.startsWith("https://")) {
498 path2 = path2.substring(path2.indexOf("://") + 3);
499 path2 = path2.substring(path2.indexOf('/'));
501 String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
502 userInfo.substring(userInfo.indexOf(':') + 1);
503 String A2 = method + ":" + path2;
504 authCache.put(originalUrl,
506 "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
507 "realm=\"" + h.get("realm") + "\", " +
508 "nonce=\"" + h.get("nonce") + "\", " +
509 "uri=\"" + path2 + "\", " +
510 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
511 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
516 throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
520 private void doProxyAuth(Hashtable h0, String method) throws IOException {
521 if (Log.on) Log.info(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
522 Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
523 String style = h.get("AUTHTYPE").toString();
524 String realm = (String)h.get("realm");
526 if (style.equals("NTLM") && Proxy.Authorization.authorization2 == null) {
527 Log.info(this, "Proxy identified itself as NTLM, sending Type 1 packet");
528 Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(Proxy.NTLM.type1);
532 if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
533 Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(),
534 Proxy.Authorization.authorization);
536 if (style.equals("Basic")) {
537 Proxy.Authorization.authorization2 =
538 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("UTF8")));
540 } else if (style.equals("Digest")) {
541 String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
542 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
543 String A2 = method + ":" + path;
544 Proxy.Authorization.authorization2 =
546 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) +
548 "realm=\"" + h.get("realm") + "\", " +
549 "nonce=\"" + h.get("nonce") + "\", " +
550 "uri=\"" + path + "\", " +
551 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
552 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
555 } else if (style.equals("NTLM")) {
556 Log.info(this, "Proxy identified itself as NTLM, got Type 2 packet");
557 byte[] type2 = Base64.decode(((String)h0.get("proxy-authenticate")).substring(5).trim());
558 for(int i=0; i<type2.length; i += 4) {
560 if (i<type2.length) log += Integer.toString(type2[i] & 0xff, 16) + " ";
561 if (i+1<type2.length) log += Integer.toString(type2[i+1] & 0xff, 16) + " ";
562 if (i+2<type2.length) log += Integer.toString(type2[i+2] & 0xff, 16) + " ";
563 if (i+3<type2.length) log += Integer.toString(type2[i+3] & 0xff, 16) + " ";
566 // FEATURE: need to keep the connection open between type1 and type3
567 // FEATURE: finish this
568 //byte[] type3 = Proxy.NTLM.getResponse(
569 //Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(type3));
574 // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
576 /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
577 public class HTTPInputStream extends FilterInputStream implements KnownLength {
579 private int length = 0; ///< if chunking, numbytes left in this subset; else the remainder of the chunk
580 private Semaphore releaseMe = null; ///< this semaphore will be released when the stream is closed
581 boolean chunkedDone = false; ///< indicates that we have encountered the zero-length terminator chunk
582 boolean firstChunk = true; ///< if we're on the first chunk, we don't pre-read a CRLF
583 private int contentLength = 0; ///< the length of the entire content body; -1 if chunked
585 HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
587 this.releaseMe = releaseMe;
588 this.contentLength = length;
589 this.length = length == -1 ? 0 : length;
592 public int getLength() { return contentLength; }
593 public boolean markSupported() { return false; }
594 public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
595 public long skip(long n) throws IOException { return read(null, -1, (int)n); }
596 public int available() throws IOException {
597 if (contentLength == -1) return java.lang.Math.min(super.available(), length);
598 return super.available();
601 public int read() throws IOException {
602 byte[] b = new byte[1];
603 int ret = read(b, 0, 1);
604 return ret == -1 ? -1 : b[0] & 0xff;
607 private void readChunk() throws IOException {
608 if (chunkedDone) return;
609 if (!firstChunk) super.skip(2); // CRLF
611 String chunkLen = "";
613 int i = super.read();
614 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
616 // FEATURE: handle chunking extensions
624 length = Integer.parseInt(chunkLen.trim(), 16);
625 if (length == 0) chunkedDone = true;
628 public int read(byte[] b, int off, int len) throws IOException {
629 boolean good = false;
631 if (length == 0 && contentLength == -1) {
633 if (chunkedDone) { good = true; return -1; }
635 if (length == 0) { good = true; return -1; }
637 if (len > length) len = length;
638 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
649 public void close() throws IOException {
650 if (contentLength == -1) {
651 while(!chunkedDone) {
652 if (length != 0) skip(length);
657 if (length != 0) skip(length);
659 if (releaseMe != null) releaseMe.release();
670 // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
672 /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
673 private Hashtable parseHeaders(InputStream in, Cookie.Jar cookies) throws IOException {
674 Hashtable ret = new Hashtable();
676 // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
677 byte[] buf = new byte[4096];
680 int read = in.read();
681 if (read == -1 && buflen == 0) return null;
682 if (read == -1) throw new HTTPException("stream closed while reading headers");
683 buf[buflen++] = (byte)read;
684 if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' &&
685 buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n')
687 if (buflen >=2 && buf[buflen - 1] == '\n' && buf[buflen - 2] == '\n')
688 break; // nice for people using stdio
689 if (buflen == buf.length) {
690 byte[] newbuf = new byte[buf.length * 2];
691 System.arraycopy(buf, 0, newbuf, 0, buflen);
696 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
697 String s = br.readLine();
698 if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
699 ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
700 ret.put("HTTP", s.substring(5, s.indexOf(' ')));
702 while((s = br.readLine()) != null && s.length() > 0) {
703 String front = s.substring(0, s.indexOf(':')).toLowerCase();
704 String back = s.substring(s.indexOf(':') + 1).trim();
705 // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
706 if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
707 if (front.equals("set-cookie")) cookies.setCookie(back, host);
708 ret.put(front, back);
713 private Hashtable parseAuthenticationChallenge(String s) {
714 Hashtable ret = new Hashtable();
717 ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
718 s = s.substring(s.indexOf(' ')).trim();
720 while (s.length() > 0) {
722 String key = s.substring(0, s.indexOf('='));
723 s = s.substring(s.indexOf('=') + 1);
724 if (s.charAt(0) == '\"') {
726 val = s.substring(0, s.indexOf('\"'));
727 s = s.substring(s.indexOf('\"') + 1);
729 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
730 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
732 if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
739 private String H(String s) throws IOException {
740 byte[] b = s.getBytes("UTF8");
742 md5.update(b, 0, b.length);
743 byte[] out = new byte[md5.getDigestSize()];
746 for(int i=0; i<out.length; i++) {
747 ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
748 ret += "0123456789abcdef".charAt(out[i] & 0x0f);
754 // Proxy ///////////////////////////////////////////////////////////
756 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
757 public static class Proxy {
759 public String httpProxyHost = null; ///< the HTTP Proxy host to use
760 public int httpProxyPort = -1; ///< the HTTP Proxy port to use
761 public String httpsProxyHost = null; ///< seperate proxy for HTTPS
762 public int httpsProxyPort = -1;
763 public String socksProxyHost = null; ///< the SOCKS Proxy Host to use
764 public int socksProxyPort = -1; ///< the SOCKS Proxy Port to use
765 public String[] excluded = new String[] { }; ///< hosts to be excluded from proxy use; wildcards permitted
767 // ** temporarily disabled so HTTP does not depend on org.ibex.js **
768 //public JS proxyAutoConfigFunction = null; ///< the PAC script
769 public Object proxyAutoConfigFunction = null; ///< the PAC script
771 public static Proxy detectProxyViaManual() {
772 Proxy ret = new Proxy();
774 ret.httpProxyHost = Platform.getEnv("http_proxy");
775 if (ret.httpProxyHost != null) {
776 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
777 if (ret.httpProxyHost.endsWith("/"))
778 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
779 if (ret.httpProxyHost.indexOf(':') != -1) {
780 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
781 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
783 ret.httpProxyPort = 80;
787 ret.httpsProxyHost = Platform.getEnv("https_proxy");
788 if (ret.httpsProxyHost != null) {
789 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
790 if (ret.httpsProxyHost.endsWith("/"))
791 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
792 if (ret.httpsProxyHost.indexOf(':') != -1) {
793 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
794 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
796 ret.httpsProxyPort = 80;
800 ret.socksProxyHost = Platform.getEnv("socks_proxy");
801 if (ret.socksProxyHost != null) {
802 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
803 if (ret.socksProxyHost.endsWith("/"))
804 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
805 if (ret.socksProxyHost.indexOf(':') != -1) {
806 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
807 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
809 ret.socksProxyPort = 80;
813 String noproxy = Platform.getEnv("no_proxy");
814 if (noproxy != null) {
815 StringTokenizer st = new StringTokenizer(noproxy, ",");
816 ret.excluded = new String[st.countTokens()];
817 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
820 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
826 public static JSScope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
827 public static JS getProxyAutoConfigFunction(String url) {
829 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
832 while((s = br.readLine()) != null) script += s + "\n";
833 if (Log.on) Log.info(Proxy.class, "successfully retrieved WPAD PAC:");
834 if (Log.on) Log.info(Proxy.class, script);
837 Vector carpHosts = new Vector();
838 for(int i=0; i<script.length(); i++)
839 if (script.regionMatches(i, "new Node(", 0, 9)) {
840 String host = script.substring(i + 10, script.indexOf('\"', i + 11));
841 if (Log.on) Log.info(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
842 carpHosts.addElement(host);
844 if (carpHosts.size() > 0) {
845 script = "function FindProxyForURL(url, host) {\nreturn \"";
846 for(int i=0; i<carpHosts.size(); i++)
847 script += "PROXY " + carpHosts.elementAt(i) + "; ";
849 if (Log.on) Log.info(Proxy.class, "DeCARPed PAC script:");
850 if (Log.on) Log.info(Proxy.class, script);
853 JS scr = JS.fromReader("PAC script at " + url, 0, new StringReader(script));
854 JS.cloneWithNewParentScope(scr, proxyAutoConfigRootScope).call(null, null, null, null, 0);
855 return (JS)proxyAutoConfigRootScope.get("FindProxyForURL");
856 } catch (Exception e) {
858 Log.info(Platform.class, "WPAD detection failed due to:");
859 if (e instanceof JSExn) {
861 org.ibex.js.JSArray arr = new org.ibex.js.JSArray();
862 arr.addElement(((JSExn)e).getObject());
863 } catch (Exception e2) {
864 Log.info(Platform.class, e);
867 else Log.info(Platform.class, e);
874 // Authorization ///////////////////////////////////////////////////////////////////////////////////
876 public static class Authorization {
878 static public String authorization = null;
879 static public String authorization2 = null;
880 static public Semaphore waitingForUser = new Semaphore();
882 // FIXME: temporarily disabled so we can use HTTP outside the core
884 public static synchronized void getPassword(final String realm, final String style,
885 final String proxyIP, String oldAuth) throws IOException {
887 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
888 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
889 // a password, so we should reattempt authorization.
891 if (authorization != oldAuth) return;
892 if (Log.on) Log.info(Authorization.class, "displaying proxy authorization dialog");
893 Scheduler.add(new Task() {
894 public void perform() throws IOException, JSExn {
898 //Template.buildTemplate("org/ibex/builtin/proxy_authorization.ibex", Stream.getInputStream((JS)Main.builtin.get("org/ibex/builtin/proxy_authorization.ibex")), new Ibex(null));
900 b.put("realm", realm);
901 b.put("proxyIP", proxyIP);
905 waitingForUser.block();
906 if (Log.on) Log.info(Authorization.class, "got proxy authorization info; re-attempting connection");
912 // ProxyAutoConfigRootJSScope ////////////////////////////////////////////////////////////////////
914 public static class ProxyAutoConfigRootScope extends JSScope.Global {
916 public ProxyAutoConfigRootScope() { super(); }
918 public Object get(Object name) throws JSExn {
920 case "isPlainHostName": return METHOD;
921 case "dnsDomainIs": return METHOD;
922 case "localHostOrDomainIs": return METHOD;
923 case "isResolvable": return METHOD;
924 case "isInNet": return METHOD;
925 case "dnsResolve": return METHOD;
926 case "myIpAddress": return METHOD;
927 case "dnsDomainLevels": return METHOD;
928 case "shExpMatch": return METHOD;
929 case "weekdayRange": return METHOD;
930 case "dateRange": return METHOD;
931 case "timeRange": return METHOD;
932 case "ProxyConfig": return ProxyConfig;
934 return super.get(name);
937 private static final JS proxyConfigBindings = new JS();
938 private static final JS ProxyConfig = new JS() {
939 public Object get(Object name) {
940 if (name.equals("bindings")) return proxyConfigBindings;
945 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
947 case "isPlainHostName": return (a0.toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
948 case "dnsDomainIs": return (a0.toString().endsWith(a1.toString())) ? Boolean.TRUE : Boolean.FALSE;
949 case "localHostOrDomainIs":
950 return (a0.equals(a1) || (a0.toString().indexOf('.') == -1 && a1.toString().startsWith(a0.toString()))) ? T:F;
951 case "isResolvable": try {
952 return (InetAddress.getByName(a0.toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
953 } catch (UnknownHostException e) { return F; }
955 if (nargs != 3) return Boolean.FALSE;
957 byte[] host = InetAddress.getByName(a0.toString()).getAddress();
958 byte[] net = InetAddress.getByName(a1.toString()).getAddress();
959 byte[] mask = InetAddress.getByName(a2.toString()).getAddress();
960 return ((host[0] & mask[0]) == net[0] &&
961 (host[1] & mask[1]) == net[1] &&
962 (host[2] & mask[2]) == net[2] &&
963 (host[3] & mask[3]) == net[3]) ?
964 Boolean.TRUE : Boolean.FALSE;
965 } catch (Exception e) {
966 throw new JSExn("exception in isInNet(): " + e);
970 return InetAddress.getByName(a0.toString()).getHostAddress();
971 } catch (UnknownHostException e) {
976 return InetAddress.getLocalHost().getHostAddress();
977 } catch (UnknownHostException e) {
978 if (Log.on) Log.info(this, "strange... host does not know its own address");
981 case "dnsDomainLevels":
982 String s = a0.toString();
984 while((i = s.indexOf('.', i)) != -1) i++;
985 return new Integer(i);
987 StringTokenizer st = new StringTokenizer(a1.toString(), "*", false);
988 String[] arr = new String[st.countTokens()];
989 String s = a0.toString();
990 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
991 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
993 TimeZone tz = (nargs < 3 || a2 == null || !a2.equals("GMT")) ?
994 TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
995 Calendar c = new GregorianCalendar();
997 c.setTime(new java.util.Date());
998 java.util.Date d = c.getTime();
999 int day = d.getDay();
1000 String d1s = a0.toString().toUpperCase();
1002 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
1005 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
1007 String d2s = a1.toString().toUpperCase();
1008 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
1010 return ((d1 <= d2 && day >= d1 && day <= d2) || (d1 > d2 && (day >= d1 || day <= d2))) ? T : F;
1012 case "dateRange": throw new JSExn("Ibex does not support dateRange() in PAC scripts");
1013 case "timeRange": throw new JSExn("Ibex does not support timeRange() in PAC scripts");
1015 return super.callMethod(method, a0, a1, a2, rest, nargs);
1017 private static boolean match(String[] arr, String s, int index) {
1018 if (index >= arr.length) return true;
1019 for(int i=0; i<s.length(); i++) {
1020 String s2 = s.substring(i);
1021 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
1025 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
1030 * An implementation of Microsoft's proprietary NTLM authentication protocol. This code was derived from Eric
1031 * Glass's work, and is copyright as follows:
1033 * Copyright (c) 2003 Eric Glass (eglass1 at comcast.net).
1035 * Permission to use, copy, modify, and distribute this document for any purpose and without any fee is hereby
1036 * granted, provided that the above copyright notice and this list of conditions appear in all copies.
1037 * The most current version of this document may be obtained from http://davenport.sourceforge.net/ntlm.html .
1039 public static class NTLM {
1041 public static final byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01,
1042 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00 };
1045 * Calculates the NTLM Response for the given challenge, using the
1046 * specified password.
1048 * @param password The user's password.
1049 * @param challenge The Type 2 challenge from the server.
1051 * @return The NTLM Response.
1053 public static byte[] getNTLMResponse(String password, byte[] challenge)
1054 throws UnsupportedEncodingException {
1055 byte[] ntlmHash = ntlmHash(password);
1056 return lmResponse(ntlmHash, challenge);
1060 * Calculates the LM Response for the given challenge, using the specified
1063 * @param password The user's password.
1064 * @param challenge The Type 2 challenge from the server.
1066 * @return The LM Response.
1068 public static byte[] getLMResponse(String password, byte[] challenge)
1070 byte[] lmHash = lmHash(password);
1071 return lmResponse(lmHash, challenge);
1075 * Calculates the NTLMv2 Response for the given challenge, using the
1076 * specified authentication target, username, password, target information
1077 * block, and client challenge.
1079 * @param target The authentication target (i.e., domain).
1080 * @param user The username.
1081 * @param password The user's password.
1082 * @param targetInformation The target information block from the Type 2
1084 * @param challenge The Type 2 challenge from the server.
1085 * @param clientChallenge The random 8-byte client challenge.
1087 * @return The NTLMv2 Response.
1089 public static byte[] getNTLMv2Response(String target, String user,
1090 String password, byte[] targetInformation, byte[] challenge,
1091 byte[] clientChallenge) throws UnsupportedEncodingException {
1092 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1093 byte[] blob = createBlob(targetInformation, clientChallenge);
1094 return lmv2Response(ntlmv2Hash, blob, challenge);
1098 * Calculates the LMv2 Response for the given challenge, using the
1099 * specified authentication target, username, password, and client
1102 * @param target The authentication target (i.e., domain).
1103 * @param user The username.
1104 * @param password The user's password.
1105 * @param challenge The Type 2 challenge from the server.
1106 * @param clientChallenge The random 8-byte client challenge.
1108 * @return The LMv2 Response.
1110 public static byte[] getLMv2Response(String target, String user,
1111 String password, byte[] challenge, byte[] clientChallenge)
1112 throws UnsupportedEncodingException {
1113 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1114 return lmv2Response(ntlmv2Hash, clientChallenge, challenge);
1118 * Calculates the NTLM2 Session Response for the given challenge, using the
1119 * specified password and client challenge.
1121 * @param password The user's password.
1122 * @param challenge The Type 2 challenge from the server.
1123 * @param clientChallenge The random 8-byte client challenge.
1125 * @return The NTLM2 Session Response. This is placed in the NTLM
1126 * response field of the Type 3 message; the LM response field contains
1127 * the client challenge, null-padded to 24 bytes.
1129 public static byte[] getNTLM2SessionResponse(String password,
1130 byte[] challenge, byte[] clientChallenge) throws UnsupportedEncodingException {
1131 byte[] ntlmHash = ntlmHash(password);
1132 MD5 md5 = new MD5();
1133 md5.update(challenge, 0, challenge.length);
1134 md5.update(clientChallenge, 0, clientChallenge.length);
1135 byte[] sessionHash = new byte[8];
1136 byte[] md5_out = new byte[md5.getDigestSize()];
1137 md5.doFinal(md5_out, 0);
1138 System.arraycopy(md5_out, 0, sessionHash, 0, 8);
1139 return lmResponse(ntlmHash, sessionHash);
1143 * Creates the LM Hash of the user's password.
1145 * @param password The password.
1147 * @return The LM Hash of the given password, used in the calculation
1148 * of the LM Response.
1150 private static byte[] lmHash(String password) {
1152 byte[] oemPassword = password.toUpperCase().getBytes("UTF8");
1153 int length = java.lang.Math.min(oemPassword.length, 14);
1154 byte[] keyBytes = new byte[14];
1155 System.arraycopy(oemPassword, 0, keyBytes, 0, length);
1156 Key lowKey = createDESKey(keyBytes, 0);
1157 Key highKey = createDESKey(keyBytes, 7);
1158 byte[] magicConstant = "KGS!@#$%".getBytes("UTF8");
1159 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1160 des.init(Cipher.ENCRYPT_MODE, lowKey);
1161 byte[] lowHash = des.doFinal(magicConstant);
1162 des.init(Cipher.ENCRYPT_MODE, highKey);
1163 byte[] highHash = des.doFinal(magicConstant);
1164 byte[] lmHash = new byte[16];
1165 System.arraycopy(lowHash, 0, lmHash, 0, 8);
1166 System.arraycopy(highHash, 0, lmHash, 8, 8);
1173 * Creates the NTLM Hash of the user's password.
1175 * @param password The password.
1177 * @return The NTLM Hash of the given password, used in the calculation
1178 * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1180 private static byte[] ntlmHash(String password) throws UnsupportedEncodingException {
1183 byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
1184 MD4 md4 = new MD4();
1185 md4.update(unicodePassword, 0, unicodePassword.length);
1186 byte[] ret = new byte[md4.getDigestSize()];
1193 * Creates the NTLMv2 Hash of the user's password.
1195 * @param target The authentication target (i.e., domain).
1196 * @param user The username.
1197 * @param password The password.
1199 * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1200 * and LMv2 Responses.
1202 private static byte[] ntlmv2Hash(String target, String user,
1203 String password) throws UnsupportedEncodingException {
1204 byte[] ntlmHash = ntlmHash(password);
1205 String identity = user.toUpperCase() + target.toUpperCase();
1206 return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
1210 * Creates the LM Response from the given hash and Type 2 challenge.
1212 * @param hash The LM or NTLM Hash.
1213 * @param challenge The server challenge from the Type 2 message.
1215 * @return The response (either LM or NTLM, depending on the provided
1218 private static byte[] lmResponse(byte[] hash, byte[] challenge)
1221 byte[] keyBytes = new byte[21];
1222 System.arraycopy(hash, 0, keyBytes, 0, 16);
1223 Key lowKey = createDESKey(keyBytes, 0);
1224 Key middleKey = createDESKey(keyBytes, 7);
1225 Key highKey = createDESKey(keyBytes, 14);
1226 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1227 des.init(Cipher.ENCRYPT_MODE, lowKey);
1228 byte[] lowResponse = des.doFinal(challenge);
1229 des.init(Cipher.ENCRYPT_MODE, middleKey);
1230 byte[] middleResponse = des.doFinal(challenge);
1231 des.init(Cipher.ENCRYPT_MODE, highKey);
1232 byte[] highResponse = des.doFinal(challenge);
1233 byte[] lmResponse = new byte[24];
1234 System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
1235 System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
1236 System.arraycopy(highResponse, 0, lmResponse, 16, 8);
1243 * Creates the LMv2 Response from the given hash, client data, and
1246 * @param hash The NTLMv2 Hash.
1247 * @param clientData The client data (blob or client challenge).
1248 * @param challenge The server challenge from the Type 2 message.
1250 * @return The response (either NTLMv2 or LMv2, depending on the
1253 private static byte[] lmv2Response(byte[] hash, byte[] clientData,
1255 byte[] data = new byte[challenge.length + clientData.length];
1256 System.arraycopy(challenge, 0, data, 0, challenge.length);
1257 System.arraycopy(clientData, 0, data, challenge.length,
1259 byte[] mac = hmacMD5(data, hash);
1260 byte[] lmv2Response = new byte[mac.length + clientData.length];
1261 System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
1262 System.arraycopy(clientData, 0, lmv2Response, mac.length,
1264 return lmv2Response;
1268 * Creates the NTLMv2 blob from the given target information block and
1271 * @param targetInformation The target information block from the Type 2
1273 * @param clientChallenge The random 8-byte client challenge.
1275 * @return The blob, used in the calculation of the NTLMv2 Response.
1277 private static byte[] createBlob(byte[] targetInformation,
1278 byte[] clientChallenge) {
1279 byte[] blobSignature = new byte[] {
1280 (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1282 byte[] reserved = new byte[] {
1283 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1285 byte[] unknown1 = new byte[] {
1286 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1288 byte[] unknown2 = new byte[] {
1289 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1291 long time = System.currentTimeMillis();
1292 time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
1293 time *= 10000; // tenths of a microsecond.
1294 // convert to little-endian byte array.
1295 byte[] timestamp = new byte[8];
1296 for (int i = 0; i < 8; i++) {
1297 timestamp[i] = (byte) time;
1300 byte[] blob = new byte[blobSignature.length + reserved.length +
1301 timestamp.length + clientChallenge.length +
1302 unknown1.length + targetInformation.length +
1305 System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
1306 offset += blobSignature.length;
1307 System.arraycopy(reserved, 0, blob, offset, reserved.length);
1308 offset += reserved.length;
1309 System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
1310 offset += timestamp.length;
1311 System.arraycopy(clientChallenge, 0, blob, offset,
1312 clientChallenge.length);
1313 offset += clientChallenge.length;
1314 System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
1315 offset += unknown1.length;
1316 System.arraycopy(targetInformation, 0, blob, offset,
1317 targetInformation.length);
1318 offset += targetInformation.length;
1319 System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
1324 * Calculates the HMAC-MD5 hash of the given data using the specified
1327 * @param data The data for which the hash will be calculated.
1328 * @param key The hashing key.
1330 * @return The HMAC-MD5 hash of the given data.
1332 private static byte[] hmacMD5(byte[] data, byte[] key) {
1333 byte[] ipad = new byte[64];
1334 byte[] opad = new byte[64];
1335 for (int i = 0; i < 64; i++) {
1336 ipad[i] = (byte) 0x36;
1337 opad[i] = (byte) 0x5c;
1339 for (int i = key.length - 1; i >= 0; i--) {
1343 byte[] content = new byte[data.length + 64];
1344 System.arraycopy(ipad, 0, content, 0, 64);
1345 System.arraycopy(data, 0, content, 64, data.length);
1346 MD5 md5 = new MD5();
1347 md5.update(content, 0, content.length);
1348 data = new byte[md5.getDigestSize()];
1349 md5.doFinal(data, 0);
1350 content = new byte[data.length + 64];
1351 System.arraycopy(opad, 0, content, 0, 64);
1352 System.arraycopy(data, 0, content, 64, data.length);
1354 md5.update(content, 0, content.length);
1355 byte[] ret = new byte[md5.getDigestSize()];
1356 md5.doFinal(ret, 0);
1361 * Creates a DES encryption key from the given key material.
1363 * @param bytes A byte array containing the DES key material.
1364 * @param offset The offset in the given byte array at which
1365 * the 7-byte key material starts.
1367 * @return A DES encryption key created from the key material
1368 * starting at the specified offset in the given byte array.
1371 private static Key createDESKey(byte[] bytes, int offset) {
1372 byte[] keyBytes = new byte[7];
1373 System.arraycopy(bytes, offset, keyBytes, 0, 7);
1374 byte[] material = new byte[8];
1375 material[0] = keyBytes[0];
1376 material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
1377 material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
1378 material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
1379 material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
1380 material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
1381 material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
1382 material[7] = (byte) (keyBytes[6] << 1);
1383 oddParity(material);
1384 return new SecretKeySpec(material, "DES");
1389 * Applies odd parity to the given byte array.
1391 * @param bytes The data whose parity bits are to be adjusted for
1394 private static void oddParity(byte[] bytes) {
1395 for (int i = 0; i < bytes.length; i++) {
1397 boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1398 (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1399 (b >>> 1)) & 0x01) == 0;
1401 bytes[i] |= (byte) 0x01;
1403 bytes[i] &= (byte) 0xfe;