1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
10 import org.ibex.util.*;
11 import org.ibex.crypto.*;
14 * This object encapsulates a *single* HTTP connection. Multiple requests may be pipelined over a connection (thread-safe),
15 * although any IOException encountered in a request will invalidate all later requests.
19 public static InetAddress originAddr = null;
20 public static String originHost = null;
22 // FIXME: HACK: these shouldn't be set globally
23 public static String userAgent = "Ibex";
24 public static boolean allowRedirects = true;
26 // Cookies //////////////////////////////////////////////////////////////////////////////
28 public static class Cookie {
29 public final String name;
30 public final String value;
31 public final String domain;
32 public final String path;
33 public final Date expires;
34 public final boolean secure;
35 public Cookie(String name, String value, String domain, String path, Date expires, boolean secure) {
40 this.expires = expires;
44 // FIXME: this could be much more efficient
45 // FIXME currently only implements http://wp.netscape.com/newsref/std/cookie_spec.html
46 public static class Jar {
47 private Hash h = new Hash();
48 public String getCookieHeader(String domain, String path, boolean secure) {
49 StringBuffer ret = new StringBuffer("Cookie: ");
50 Enumeration e = h.keys();
51 while (e.hasMoreElements()) {
52 Vec v = (Vec)h.get(e.nextElement());
54 for(int i=0; i<v.size(); i++) {
55 Cookie c = (Cookie)v.elementAt(i);
56 if (domain.endsWith(c.domain) &&
57 (c.path == null || path.startsWith(c.path)) &&
58 (cookie == null || c.domain.length() > cookie.domain.length()))
62 ret.append(cookie.name);
64 ret.append(cookie.value);
68 //ret.setLength(ret.length() - 2);
69 return ret.toString();
71 public void setCookie(String header, String defaultDomain) {
74 String domain = defaultDomain;
77 boolean secure = false;
78 StringTokenizer st = new StringTokenizer(header, ";");
79 while(st.hasMoreTokens()) {
80 String s = st.nextToken();
81 if (s.indexOf('=') == -1) {
82 if (s.equals("secure")) secure = true;
85 String start = s.substring(0, s.indexOf('='));
86 String end = s.substring(s.indexOf('=')+1);
92 //#switch(start.toLowerCase())
93 case "domain": domain = end;
94 case "path": path = end;
95 case "expires": expires = new Date(end);
98 if (h.get(name) == null) h.put(name, new Vec());
99 ((Vec)h.get(name)).addElement(new Cookie(name, value, domain, path, expires, secure));
104 // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
106 public HTTP(String url) { this(url, false); }
107 public HTTP(String url, boolean skipResolveCheck) { originalUrl = url; this.skipResolveCheck = skipResolveCheck; }
109 /** Performs an HTTP GET request */
110 public InputStream GET(String referer, Cookie.Jar cookies) throws IOException {
111 return makeRequest(null, null, referer, cookies); }
113 /** Performs an HTTP POST request; content is additional headers, blank line, and body */
114 public InputStream POST(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
115 return makeRequest(contentType, content, referer, cookies); }
117 public static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
119 public static HTTP stdio = new HTTP("stdio:");
122 // Statics ///////////////////////////////////////////////////////////////////////////////////////////////
124 static Hash resolvedHosts = new Hash(); ///< cache for resolveAndCheckIfFirewalled()
125 private static Hash authCache = new Hash(); ///< cache of userInfo strings, keyed on originalUrl
128 // Instance Data ///////////////////////////////////////////////////////////////////////////////////////////////
130 final String originalUrl; ///< the URL as passed to the original constructor; this is never changed
131 String url = null; ///< the URL to connect to; this is munged when the url is parsed */
132 String host = null; ///< the host to connect to
133 int port = -1; ///< the port to connect on
134 boolean ssl = false; ///< true if SSL (HTTPS) should be used
135 String path = null; ///< the path (URI) to retrieve on the server
136 Socket sock = null; ///< the socket
137 InputStream in = null; ///< the socket's inputstream
138 String userInfo = null; ///< the username and password portions of the URL
139 boolean firstRequest = true; ///< true iff this is the first request to be made on this socket
140 boolean skipResolveCheck = false; ///< allowed to skip the resolve check when downloading PAC script
141 boolean proxied = false; ///< true iff we're using a proxy
143 /** this is null if the current request is the first request on
144 * this HTTP connection; otherwise it is a Semaphore which will be
145 * released once the request ahead of us has recieved its response
147 Semaphore okToRecieve = null;
150 * This method isn't synchronized; however, only one thread can be in the inner synchronized block at a time, and the rest of
151 * the method is protected by in-order one-at-a-time semaphore lock-steps
153 private InputStream makeRequest(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
155 // Step 1: send the request and establish a semaphore to stop any requests that pipeline after us
156 Semaphore blockOn = null;
157 Semaphore releaseMe = null;
161 sendRequest(contentType, content, referer, cookies);
162 } catch (IOException e) {
166 blockOn = okToRecieve;
167 releaseMe = okToRecieve = new Semaphore();
170 // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
171 boolean doRelease = true;
173 if (blockOn != null) blockOn.block();
175 // previous call wrecked the socket connection, but we already sent our request, so we can't just retry --
176 // this could cause the server to receive the request twice, which could be bad (think of the case where the
177 // server call causes Amazon.com to ship you an item with one-click purchasing).
179 throw new HTTPException("a previous pipelined call messed up the socket");
181 Hashtable h = in == null ? null : parseHeaders(in, cookies);
183 if (firstRequest) throw new HTTPException("server closed the socket with no response");
184 // sometimes the server chooses to close the stream between requests
187 return makeRequest(contentType, content, referer, cookies);
190 String reply = h.get("STATUSLINE").toString();
192 if (reply.startsWith("407") || reply.startsWith("401")) {
194 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
195 else doWebAuth(h, content == null ? "GET" : "POST");
197 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
198 if (Log.on) Log.info(this, "proxy returned an HTTP/1.0 reply with no content-length...");
201 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
202 new HTTPInputStream(in, cl, releaseMe).close();
205 return makeRequest(contentType, content, referer, cookies);
207 } else if (reply.startsWith("3") && allowRedirects) {
208 String location = (String)h.get("location");
209 if (location == null) throw new HTTPException("Got HTTP " + reply.substring(0, 3) + " but no Location header");
210 Log.info(HTTP.class, "redirecting to " + location);
212 return new HTTP(location).POST(contentType, content, url, cookies);
214 return new HTTP(location).GET(url, cookies);
216 } else if (reply.startsWith("2")) {
217 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
218 throw new HTTPException("Ibex does not support HTTP/1.0 servers which fail to return the Content-Length header");
219 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
220 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
221 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
226 throw new HTTPException("HTTP Error: " + reply);
230 } catch (IOException e) { reset(); throw e;
231 } finally { if (doRelease) releaseMe.release();
236 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
239 * resolves the hostname and returns it as a string in the form "x.y.z.w"
240 * @throws HTTPException if the host falls within a firewalled netblock
242 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
245 if (resolvedHosts.get(host) != null) return;
247 // if all scripts are trustworthy (local FS), continue
248 if (originAddr == null) return;
252 InetAddress addr = InetAddress.getByName(host);
253 byte[] quadbyte = addr.getAddress();
254 if ((quadbyte[0] == 10 ||
255 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
256 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(originAddr))
257 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() +
258 "] is in a firewalled netblock");
260 } catch (UnknownHostException uhe) { }
263 if (Platform.detectProxy() == null)
264 throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
269 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
271 private Socket getSocket(String host, int port, boolean ssl, boolean negotiate) throws IOException {
272 Socket ret = ssl ? new SSL(host, port, negotiate) : new Socket(java.net.InetAddress.getByName(host), port);
273 ret.setTcpNoDelay(true);
277 /** Attempts a direct connection */
278 private Socket attemptDirect() {
280 Log.info(this, "attempting to create unproxied socket to " +
281 host + ":" + port + (ssl ? " [ssl]" : ""));
282 return getSocket(host, port, ssl, true);
283 } catch (IOException e) {
284 if (Log.on) Log.info(this, "exception in attemptDirect(): " + e);
289 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
290 private Socket attemptHttpProxy(String proxyHost, int proxyPort) {
292 if (Log.verbose) Log.info(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
293 Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
296 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
300 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
301 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
302 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
304 String s = br.readLine();
305 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
306 while (br.readLine().length() > 0) { };
307 ((SSL)sock).negotiate();
310 } catch (IOException e) {
311 if (Log.on) Log.info(this, "exception in attemptHttpProxy(): " + e);
317 * Implements SOCKSv4 with v4a DNS extension
318 * @see http://www.socks.nec.com/protocol/socks4.protocol
319 * @see http://www.socks.nec.com/protocol/socks4a.protocol
321 private Socket attemptSocksProxy(String proxyHost, int proxyPort) {
323 // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
324 InetAddress addr = null;
325 try { addr = InetAddress.getByName(host); } catch (Exception e) { }
327 if (Log.verbose) Log.info(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
328 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
331 Socket sock = getSocket(proxyHost, proxyPort, ssl, false);
333 DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
334 dos.writeByte(0x04); // SOCKSv4(a)
335 dos.writeByte(0x01); // CONNECT
336 dos.writeShort(port & 0xffff); // port
337 if (addr == null) dos.writeInt(0x00000001); // bogus IP
338 else dos.write(addr.getAddress()); // actual IP
339 dos.writeByte(0x00); // no userid
341 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
344 dos.writeByte(0x00); // hostname null terminator
348 DataInputStream dis = new DataInputStream(sock.getInputStream());
349 dis.readByte(); // reply version
350 byte success = dis.readByte(); // success/fail
351 dis.skip(6); // ip/port
353 if ((int)(success & 0xff) == 90) {
354 if (ssl) ((SSL)sock).negotiate();
357 if (Log.on) Log.info(this, "SOCKS server denied access, code " + (success & 0xff));
360 } catch (IOException e) {
361 if (Log.on) Log.info(this, "exception in attemptSocksProxy(): " + e);
366 /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
368 private Socket attemptPAC(org.ibex.js.JS pacFunc) {
369 if (Log.verbose) Log.info(this, "evaluating PAC script");
372 Object obj = pacFunc.call(url, host, null, null, 2);
373 if (Log.verbose) Log.info(this, " PAC script returned \"" + obj + "\"");
374 pac = obj.toString();
375 } catch (Throwable e) {
376 if (Log.on) Log.info(this, "PAC script threw exception " + e);
380 StringTokenizer st = new StringTokenizer(pac, ";", false);
381 while (st.hasMoreTokens()) {
382 String token = st.nextToken().trim();
383 if (Log.verbose) Log.info(this, " trying \"" + token + "\"...");
386 if (token.startsWith("DIRECT"))
387 ret = attemptDirect();
388 else if (token.startsWith("PROXY"))
389 ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
390 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
391 else if (token.startsWith("SOCKS"))
392 ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
393 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
394 if (ret != null) return ret;
395 } catch (Throwable e) {
396 if (Log.on) Log.info(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
399 if (Log.on) Log.info(this, "all PAC results exhausted");
404 // Everything Else ////////////////////////////////////////////////////////////////////////////
406 private synchronized void connect() throws IOException {
407 if (originalUrl.equals("stdio:")) { in = new BufferedInputStream(System.in); return; }
409 if (in == null) in = new BufferedInputStream(sock.getInputStream());
412 // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
413 String url = originalUrl;
414 userInfo = url.substring(url.indexOf("://") + 3);
415 userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
416 if (userInfo.indexOf('@') != -1) {
417 userInfo = userInfo.substring(0, userInfo.indexOf('@'));
418 url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
423 if (url.startsWith("https:")) {
425 } else if (!url.startsWith("http:")) {
426 throw new IOException("HTTP only supports http/https urls");
428 if (url.indexOf("://") == -1) throw new IOException("URLs must contain a ://");
429 String temphost = url.substring(url.indexOf("://") + 3);
430 path = temphost.substring(temphost.indexOf('/'));
431 temphost = temphost.substring(0, temphost.indexOf('/'));
432 if (temphost.indexOf(':') != -1) {
433 port = Integer.parseInt(temphost.substring(temphost.indexOf(':')+1));
434 temphost = temphost.substring(0, temphost.indexOf(':'));
436 port = ssl ? 443 : 80;
438 if (!skipResolveCheck) resolveAndCheckIfFirewalled(temphost);
440 if (Log.verbose) Log.info(this, "creating HTTP object for connection to " + host + ":" + port);
443 Proxy pi = Platform.detectProxy();
446 for(int i=0; i<pi.excluded.length; i++) if (host.equals(pi.excluded[i])) break OUTER;
447 if (sock == null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
448 if (sock == null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost,pi.httpsProxyPort);
449 if (sock == null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
450 if (sock == null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
454 proxied = sock != null;
455 if (sock == null) sock = attemptDirect();
456 if (sock == null) throw new HTTPException("unable to contact host " + host);
457 if (in == null) in = new BufferedInputStream(sock.getInputStream());
460 private void sendRequest(String contentType, String content, String referer, Cookie.Jar cookies) throws IOException {
461 PrintWriter pw = new PrintWriter(new OutputStreamWriter(originalUrl.equals("stdio:") ?
462 System.out : sock.getOutputStream()));
463 if (content != null) {
464 pw.print("POST " + path + " HTTP/1.0\r\n"); // FIXME chunked encoding
465 int contentLength = content.substring(0, 2).equals("\r\n") ?
466 content.length() - 2 :
467 (content.length() - content.indexOf("\r\n\r\n") - 4);
468 pw.print("Content-Length: " + contentLength + "\r\n");
469 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
471 pw.print("GET " + path + " HTTP/1.1\r\n");
474 if (cookies != null) pw.print(cookies.getCookieHeader(host, path, ssl));
475 pw.print("User-Agent: " + userAgent + "\r\n");
476 pw.print("Accept-encoding: gzip\r\n");
477 pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
478 if (proxied) pw.print("X-RequestOrigin: " + originHost + "\r\n");
480 if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: "+Proxy.Authorization.authorization2+"\r\n");
481 if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
483 pw.print(content == null ? "\r\n" : content);
488 private void doWebAuth(Hashtable h0, String method) throws IOException {
489 if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
490 Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
492 if (h.get("AUTHTYPE").equals("Basic")) {
493 if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
494 authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("UTF8"))));
496 } else if (h.get("AUTHTYPE").equals("Digest")) {
497 if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale")))
498 throw new HTTPException("username/password rejected");
500 if (path2.startsWith("http://") || path2.startsWith("https://")) {
501 path2 = path2.substring(path2.indexOf("://") + 3);
502 path2 = path2.substring(path2.indexOf('/'));
504 String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
505 userInfo.substring(userInfo.indexOf(':') + 1);
506 String A2 = method + ":" + path2;
507 authCache.put(originalUrl,
509 "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
510 "realm=\"" + h.get("realm") + "\", " +
511 "nonce=\"" + h.get("nonce") + "\", " +
512 "uri=\"" + path2 + "\", " +
513 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
514 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
519 throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
523 private void doProxyAuth(Hashtable h0, String method) throws IOException {
524 if (Log.on) Log.info(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
525 Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
526 String style = h.get("AUTHTYPE").toString();
527 String realm = (String)h.get("realm");
529 if (style.equals("NTLM") && Proxy.Authorization.authorization2 == null) {
530 Log.info(this, "Proxy identified itself as NTLM, sending Type 1 packet");
531 Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(Proxy.NTLM.type1);
535 if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
536 Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(),
537 Proxy.Authorization.authorization);
539 if (style.equals("Basic")) {
540 Proxy.Authorization.authorization2 =
541 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("UTF8")));
543 } else if (style.equals("Digest")) {
544 String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
545 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
546 String A2 = method + ":" + path;
547 Proxy.Authorization.authorization2 =
549 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) +
551 "realm=\"" + h.get("realm") + "\", " +
552 "nonce=\"" + h.get("nonce") + "\", " +
553 "uri=\"" + path + "\", " +
554 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
555 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
558 } else if (style.equals("NTLM")) {
559 Log.info(this, "Proxy identified itself as NTLM, got Type 2 packet");
560 byte[] type2 = Base64.decode(((String)h0.get("proxy-authenticate")).substring(5).trim());
561 for(int i=0; i<type2.length; i += 4) {
563 if (i<type2.length) log += Integer.toString(type2[i] & 0xff, 16) + " ";
564 if (i+1<type2.length) log += Integer.toString(type2[i+1] & 0xff, 16) + " ";
565 if (i+2<type2.length) log += Integer.toString(type2[i+2] & 0xff, 16) + " ";
566 if (i+3<type2.length) log += Integer.toString(type2[i+3] & 0xff, 16) + " ";
569 // FEATURE: need to keep the connection open between type1 and type3
570 // FEATURE: finish this
571 //byte[] type3 = Proxy.NTLM.getResponse(
572 //Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(type3));
577 // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
579 /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
580 public class HTTPInputStream extends FilterInputStream implements KnownLength {
582 private int length = 0; ///< if chunking, numbytes left in this subset; else the remainder of the chunk
583 private Semaphore releaseMe = null; ///< this semaphore will be released when the stream is closed
584 boolean chunkedDone = false; ///< indicates that we have encountered the zero-length terminator chunk
585 boolean firstChunk = true; ///< if we're on the first chunk, we don't pre-read a CRLF
586 private int contentLength = 0; ///< the length of the entire content body; -1 if chunked
588 HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
590 this.releaseMe = releaseMe;
591 this.contentLength = length;
592 this.length = length == -1 ? 0 : length;
595 public int getLength() { return contentLength; }
596 public boolean markSupported() { return false; }
597 public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
598 public long skip(long n) throws IOException { return read(null, -1, (int)n); }
599 public int available() throws IOException {
600 if (contentLength == -1) return java.lang.Math.min(super.available(), length);
601 return super.available();
604 public int read() throws IOException {
605 byte[] b = new byte[1];
606 int ret = read(b, 0, 1);
607 return ret == -1 ? -1 : b[0] & 0xff;
610 private void readChunk() throws IOException {
611 if (chunkedDone) return;
612 if (!firstChunk) super.skip(2); // CRLF
614 String chunkLen = "";
616 int i = super.read();
617 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
619 // FEATURE: handle chunking extensions
627 length = Integer.parseInt(chunkLen.trim(), 16);
628 if (length == 0) chunkedDone = true;
631 public int read(byte[] b, int off, int len) throws IOException {
632 boolean good = false;
634 if (length == 0 && contentLength == -1) {
636 if (chunkedDone) { good = true; return -1; }
638 if (length == 0) { good = true; return -1; }
640 if (len > length) len = length;
641 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
652 public void close() throws IOException {
653 if (contentLength == -1) {
654 while(!chunkedDone) {
655 if (length != 0) skip(length);
660 if (length != 0) skip(length);
662 if (releaseMe != null) releaseMe.release();
673 // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
675 /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
676 private Hashtable parseHeaders(InputStream in, Cookie.Jar cookies) throws IOException {
677 Hashtable ret = new Hashtable();
679 // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
680 byte[] buf = new byte[4096];
683 int read = in.read();
684 if (read == -1 && buflen == 0) return null;
685 if (read == -1) throw new HTTPException("stream closed while reading headers");
686 buf[buflen++] = (byte)read;
687 if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' &&
688 buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n')
690 if (buflen >=2 && buf[buflen - 1] == '\n' && buf[buflen - 2] == '\n')
691 break; // nice for people using stdio
692 if (buflen == buf.length) {
693 byte[] newbuf = new byte[buf.length * 2];
694 System.arraycopy(buf, 0, newbuf, 0, buflen);
699 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
700 String s = br.readLine();
701 if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
702 ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
703 ret.put("HTTP", s.substring(5, s.indexOf(' ')));
705 while((s = br.readLine()) != null && s.length() > 0) {
706 String front = s.substring(0, s.indexOf(':')).toLowerCase();
707 String back = s.substring(s.indexOf(':') + 1).trim();
708 // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
709 if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
710 if (front.equals("set-cookie")) cookies.setCookie(back, host);
711 ret.put(front, back);
716 private Hashtable parseAuthenticationChallenge(String s) {
717 Hashtable ret = new Hashtable();
720 ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
721 s = s.substring(s.indexOf(' ')).trim();
723 while (s.length() > 0) {
725 String key = s.substring(0, s.indexOf('='));
726 s = s.substring(s.indexOf('=') + 1);
727 if (s.charAt(0) == '\"') {
729 val = s.substring(0, s.indexOf('\"'));
730 s = s.substring(s.indexOf('\"') + 1);
732 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
733 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
735 if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
742 private String H(String s) throws IOException {
743 byte[] b = s.getBytes("UTF8");
745 md5.update(b, 0, b.length);
746 byte[] out = new byte[md5.getDigestSize()];
749 for(int i=0; i<out.length; i++) {
750 ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
751 ret += "0123456789abcdef".charAt(out[i] & 0x0f);
757 // Proxy ///////////////////////////////////////////////////////////
759 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
760 public static class Proxy {
762 public String httpProxyHost = null; ///< the HTTP Proxy host to use
763 public int httpProxyPort = -1; ///< the HTTP Proxy port to use
764 public String httpsProxyHost = null; ///< seperate proxy for HTTPS
765 public int httpsProxyPort = -1;
766 public String socksProxyHost = null; ///< the SOCKS Proxy Host to use
767 public int socksProxyPort = -1; ///< the SOCKS Proxy Port to use
768 public String[] excluded = new String[] { }; ///< hosts to be excluded from proxy use; wildcards permitted
770 // ** temporarily disabled so HTTP does not depend on org.ibex.js **
771 //public JS proxyAutoConfigFunction = null; ///< the PAC script
772 public Object proxyAutoConfigFunction = null; ///< the PAC script
774 public static Proxy detectProxyViaManual() {
775 Proxy ret = new Proxy();
777 ret.httpProxyHost = Platform.getEnv("http_proxy");
778 if (ret.httpProxyHost != null) {
779 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
780 if (ret.httpProxyHost.endsWith("/"))
781 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
782 if (ret.httpProxyHost.indexOf(':') != -1) {
783 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
784 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
786 ret.httpProxyPort = 80;
790 ret.httpsProxyHost = Platform.getEnv("https_proxy");
791 if (ret.httpsProxyHost != null) {
792 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
793 if (ret.httpsProxyHost.endsWith("/"))
794 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
795 if (ret.httpsProxyHost.indexOf(':') != -1) {
796 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
797 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
799 ret.httpsProxyPort = 80;
803 ret.socksProxyHost = Platform.getEnv("socks_proxy");
804 if (ret.socksProxyHost != null) {
805 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
806 if (ret.socksProxyHost.endsWith("/"))
807 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
808 if (ret.socksProxyHost.indexOf(':') != -1) {
809 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
810 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
812 ret.socksProxyPort = 80;
816 String noproxy = Platform.getEnv("no_proxy");
817 if (noproxy != null) {
818 StringTokenizer st = new StringTokenizer(noproxy, ",");
819 ret.excluded = new String[st.countTokens()];
820 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
823 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
829 public static JSScope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
830 public static JS getProxyAutoConfigFunction(String url) {
832 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
835 while((s = br.readLine()) != null) script += s + "\n";
836 if (Log.on) Log.info(Proxy.class, "successfully retrieved WPAD PAC:");
837 if (Log.on) Log.info(Proxy.class, script);
840 Vector carpHosts = new Vector();
841 for(int i=0; i<script.length(); i++)
842 if (script.regionMatches(i, "new Node(", 0, 9)) {
843 String host = script.substring(i + 10, script.indexOf('\"', i + 11));
844 if (Log.on) Log.info(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
845 carpHosts.addElement(host);
847 if (carpHosts.size() > 0) {
848 script = "function FindProxyForURL(url, host) {\nreturn \"";
849 for(int i=0; i<carpHosts.size(); i++)
850 script += "PROXY " + carpHosts.elementAt(i) + "; ";
852 if (Log.on) Log.info(Proxy.class, "DeCARPed PAC script:");
853 if (Log.on) Log.info(Proxy.class, script);
856 JS scr = JS.fromReader("PAC script at " + url, 0, new StringReader(script));
857 JS.cloneWithNewParentScope(scr, proxyAutoConfigRootScope).call(null, null, null, null, 0);
858 return (JS)proxyAutoConfigRootScope.get("FindProxyForURL");
859 } catch (Exception e) {
861 Log.info(Platform.class, "WPAD detection failed due to:");
862 if (e instanceof JSExn) {
864 org.ibex.js.JSArray arr = new org.ibex.js.JSArray();
865 arr.addElement(((JSExn)e).getObject());
866 } catch (Exception e2) {
867 Log.info(Platform.class, e);
870 else Log.info(Platform.class, e);
877 // Authorization ///////////////////////////////////////////////////////////////////////////////////
879 public static class Authorization {
881 static public String authorization = null;
882 static public String authorization2 = null;
883 static public Semaphore waitingForUser = new Semaphore();
885 // FIXME: temporarily disabled so we can use HTTP outside the core
887 public static synchronized void getPassword(final String realm, final String style,
888 final String proxyIP, String oldAuth) throws IOException {
890 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
891 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
892 // a password, so we should reattempt authorization.
894 if (authorization != oldAuth) return;
895 if (Log.on) Log.info(Authorization.class, "displaying proxy authorization dialog");
896 Scheduler.add(new Task() {
897 public void perform() throws IOException, JSExn {
901 //Template.buildTemplate("org/ibex/builtin/proxy_authorization.ibex", Stream.getInputStream((JS)Main.builtin.get("org/ibex/builtin/proxy_authorization.ibex")), new Ibex(null));
903 b.put("realm", realm);
904 b.put("proxyIP", proxyIP);
908 waitingForUser.block();
909 if (Log.on) Log.info(Authorization.class, "got proxy authorization info; re-attempting connection");
915 // ProxyAutoConfigRootJSScope ////////////////////////////////////////////////////////////////////
917 public static class ProxyAutoConfigRootScope extends JSScope.Global {
919 public ProxyAutoConfigRootScope() { super(); }
921 public Object get(Object name) throws JSExn {
923 case "isPlainHostName": return METHOD;
924 case "dnsDomainIs": return METHOD;
925 case "localHostOrDomainIs": return METHOD;
926 case "isResolvable": return METHOD;
927 case "isInNet": return METHOD;
928 case "dnsResolve": return METHOD;
929 case "myIpAddress": return METHOD;
930 case "dnsDomainLevels": return METHOD;
931 case "shExpMatch": return METHOD;
932 case "weekdayRange": return METHOD;
933 case "dateRange": return METHOD;
934 case "timeRange": return METHOD;
935 case "ProxyConfig": return ProxyConfig;
937 return super.get(name);
940 private static final JS proxyConfigBindings = new JS();
941 private static final JS ProxyConfig = new JS() {
942 public Object get(Object name) {
943 if (name.equals("bindings")) return proxyConfigBindings;
948 public Object callMethod(Object method, Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
950 case "isPlainHostName": return (a0.toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
951 case "dnsDomainIs": return (a0.toString().endsWith(a1.toString())) ? Boolean.TRUE : Boolean.FALSE;
952 case "localHostOrDomainIs":
953 return (a0.equals(a1) || (a0.toString().indexOf('.') == -1 && a1.toString().startsWith(a0.toString()))) ? T:F;
954 case "isResolvable": try {
955 return (InetAddress.getByName(a0.toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
956 } catch (UnknownHostException e) { return F; }
958 if (nargs != 3) return Boolean.FALSE;
960 byte[] host = InetAddress.getByName(a0.toString()).getAddress();
961 byte[] net = InetAddress.getByName(a1.toString()).getAddress();
962 byte[] mask = InetAddress.getByName(a2.toString()).getAddress();
963 return ((host[0] & mask[0]) == net[0] &&
964 (host[1] & mask[1]) == net[1] &&
965 (host[2] & mask[2]) == net[2] &&
966 (host[3] & mask[3]) == net[3]) ?
967 Boolean.TRUE : Boolean.FALSE;
968 } catch (Exception e) {
969 throw new JSExn("exception in isInNet(): " + e);
973 return InetAddress.getByName(a0.toString()).getHostAddress();
974 } catch (UnknownHostException e) {
979 return InetAddress.getLocalHost().getHostAddress();
980 } catch (UnknownHostException e) {
981 if (Log.on) Log.info(this, "strange... host does not know its own address");
984 case "dnsDomainLevels":
985 String s = a0.toString();
987 while((i = s.indexOf('.', i)) != -1) i++;
988 return new Integer(i);
990 StringTokenizer st = new StringTokenizer(a1.toString(), "*", false);
991 String[] arr = new String[st.countTokens()];
992 String s = a0.toString();
993 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
994 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
996 TimeZone tz = (nargs < 3 || a2 == null || !a2.equals("GMT")) ?
997 TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
998 Calendar c = new GregorianCalendar();
1000 c.setTime(new java.util.Date());
1001 java.util.Date d = c.getTime();
1002 int day = d.getDay();
1003 String d1s = a0.toString().toUpperCase();
1005 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
1008 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
1010 String d2s = a1.toString().toUpperCase();
1011 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
1013 return ((d1 <= d2 && day >= d1 && day <= d2) || (d1 > d2 && (day >= d1 || day <= d2))) ? T : F;
1015 case "dateRange": throw new JSExn("Ibex does not support dateRange() in PAC scripts");
1016 case "timeRange": throw new JSExn("Ibex does not support timeRange() in PAC scripts");
1018 return super.callMethod(method, a0, a1, a2, rest, nargs);
1020 private static boolean match(String[] arr, String s, int index) {
1021 if (index >= arr.length) return true;
1022 for(int i=0; i<s.length(); i++) {
1023 String s2 = s.substring(i);
1024 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
1028 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
1033 * An implementation of Microsoft's proprietary NTLM authentication protocol. This code was derived from Eric
1034 * Glass's work, and is copyright as follows:
1036 * Copyright (c) 2003 Eric Glass (eglass1 at comcast.net).
1038 * Permission to use, copy, modify, and distribute this document for any purpose and without any fee is hereby
1039 * granted, provided that the above copyright notice and this list of conditions appear in all copies.
1040 * The most current version of this document may be obtained from http://davenport.sourceforge.net/ntlm.html .
1042 public static class NTLM {
1044 public static final byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01,
1045 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00 };
1048 * Calculates the NTLM Response for the given challenge, using the
1049 * specified password.
1051 * @param password The user's password.
1052 * @param challenge The Type 2 challenge from the server.
1054 * @return The NTLM Response.
1056 public static byte[] getNTLMResponse(String password, byte[] challenge)
1057 throws UnsupportedEncodingException {
1058 byte[] ntlmHash = ntlmHash(password);
1059 return lmResponse(ntlmHash, challenge);
1063 * Calculates the LM Response for the given challenge, using the specified
1066 * @param password The user's password.
1067 * @param challenge The Type 2 challenge from the server.
1069 * @return The LM Response.
1071 public static byte[] getLMResponse(String password, byte[] challenge)
1073 byte[] lmHash = lmHash(password);
1074 return lmResponse(lmHash, challenge);
1078 * Calculates the NTLMv2 Response for the given challenge, using the
1079 * specified authentication target, username, password, target information
1080 * block, and client challenge.
1082 * @param target The authentication target (i.e., domain).
1083 * @param user The username.
1084 * @param password The user's password.
1085 * @param targetInformation The target information block from the Type 2
1087 * @param challenge The Type 2 challenge from the server.
1088 * @param clientChallenge The random 8-byte client challenge.
1090 * @return The NTLMv2 Response.
1092 public static byte[] getNTLMv2Response(String target, String user,
1093 String password, byte[] targetInformation, byte[] challenge,
1094 byte[] clientChallenge) throws UnsupportedEncodingException {
1095 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1096 byte[] blob = createBlob(targetInformation, clientChallenge);
1097 return lmv2Response(ntlmv2Hash, blob, challenge);
1101 * Calculates the LMv2 Response for the given challenge, using the
1102 * specified authentication target, username, password, and client
1105 * @param target The authentication target (i.e., domain).
1106 * @param user The username.
1107 * @param password The user's password.
1108 * @param challenge The Type 2 challenge from the server.
1109 * @param clientChallenge The random 8-byte client challenge.
1111 * @return The LMv2 Response.
1113 public static byte[] getLMv2Response(String target, String user,
1114 String password, byte[] challenge, byte[] clientChallenge)
1115 throws UnsupportedEncodingException {
1116 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1117 return lmv2Response(ntlmv2Hash, clientChallenge, challenge);
1121 * Calculates the NTLM2 Session Response for the given challenge, using the
1122 * specified password and client challenge.
1124 * @param password The user's password.
1125 * @param challenge The Type 2 challenge from the server.
1126 * @param clientChallenge The random 8-byte client challenge.
1128 * @return The NTLM2 Session Response. This is placed in the NTLM
1129 * response field of the Type 3 message; the LM response field contains
1130 * the client challenge, null-padded to 24 bytes.
1132 public static byte[] getNTLM2SessionResponse(String password,
1133 byte[] challenge, byte[] clientChallenge) throws UnsupportedEncodingException {
1134 byte[] ntlmHash = ntlmHash(password);
1135 MD5 md5 = new MD5();
1136 md5.update(challenge, 0, challenge.length);
1137 md5.update(clientChallenge, 0, clientChallenge.length);
1138 byte[] sessionHash = new byte[8];
1139 byte[] md5_out = new byte[md5.getDigestSize()];
1140 md5.doFinal(md5_out, 0);
1141 System.arraycopy(md5_out, 0, sessionHash, 0, 8);
1142 return lmResponse(ntlmHash, sessionHash);
1146 * Creates the LM Hash of the user's password.
1148 * @param password The password.
1150 * @return The LM Hash of the given password, used in the calculation
1151 * of the LM Response.
1153 private static byte[] lmHash(String password) {
1155 byte[] oemPassword = password.toUpperCase().getBytes("UTF8");
1156 int length = java.lang.Math.min(oemPassword.length, 14);
1157 byte[] keyBytes = new byte[14];
1158 System.arraycopy(oemPassword, 0, keyBytes, 0, length);
1159 Key lowKey = createDESKey(keyBytes, 0);
1160 Key highKey = createDESKey(keyBytes, 7);
1161 byte[] magicConstant = "KGS!@#$%".getBytes("UTF8");
1162 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1163 des.init(Cipher.ENCRYPT_MODE, lowKey);
1164 byte[] lowHash = des.doFinal(magicConstant);
1165 des.init(Cipher.ENCRYPT_MODE, highKey);
1166 byte[] highHash = des.doFinal(magicConstant);
1167 byte[] lmHash = new byte[16];
1168 System.arraycopy(lowHash, 0, lmHash, 0, 8);
1169 System.arraycopy(highHash, 0, lmHash, 8, 8);
1176 * Creates the NTLM Hash of the user's password.
1178 * @param password The password.
1180 * @return The NTLM Hash of the given password, used in the calculation
1181 * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1183 private static byte[] ntlmHash(String password) throws UnsupportedEncodingException {
1186 byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
1187 MD4 md4 = new MD4();
1188 md4.update(unicodePassword, 0, unicodePassword.length);
1189 byte[] ret = new byte[md4.getDigestSize()];
1196 * Creates the NTLMv2 Hash of the user's password.
1198 * @param target The authentication target (i.e., domain).
1199 * @param user The username.
1200 * @param password The password.
1202 * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1203 * and LMv2 Responses.
1205 private static byte[] ntlmv2Hash(String target, String user,
1206 String password) throws UnsupportedEncodingException {
1207 byte[] ntlmHash = ntlmHash(password);
1208 String identity = user.toUpperCase() + target.toUpperCase();
1209 return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
1213 * Creates the LM Response from the given hash and Type 2 challenge.
1215 * @param hash The LM or NTLM Hash.
1216 * @param challenge The server challenge from the Type 2 message.
1218 * @return The response (either LM or NTLM, depending on the provided
1221 private static byte[] lmResponse(byte[] hash, byte[] challenge)
1224 byte[] keyBytes = new byte[21];
1225 System.arraycopy(hash, 0, keyBytes, 0, 16);
1226 Key lowKey = createDESKey(keyBytes, 0);
1227 Key middleKey = createDESKey(keyBytes, 7);
1228 Key highKey = createDESKey(keyBytes, 14);
1229 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1230 des.init(Cipher.ENCRYPT_MODE, lowKey);
1231 byte[] lowResponse = des.doFinal(challenge);
1232 des.init(Cipher.ENCRYPT_MODE, middleKey);
1233 byte[] middleResponse = des.doFinal(challenge);
1234 des.init(Cipher.ENCRYPT_MODE, highKey);
1235 byte[] highResponse = des.doFinal(challenge);
1236 byte[] lmResponse = new byte[24];
1237 System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
1238 System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
1239 System.arraycopy(highResponse, 0, lmResponse, 16, 8);
1246 * Creates the LMv2 Response from the given hash, client data, and
1249 * @param hash The NTLMv2 Hash.
1250 * @param clientData The client data (blob or client challenge).
1251 * @param challenge The server challenge from the Type 2 message.
1253 * @return The response (either NTLMv2 or LMv2, depending on the
1256 private static byte[] lmv2Response(byte[] hash, byte[] clientData,
1258 byte[] data = new byte[challenge.length + clientData.length];
1259 System.arraycopy(challenge, 0, data, 0, challenge.length);
1260 System.arraycopy(clientData, 0, data, challenge.length,
1262 byte[] mac = hmacMD5(data, hash);
1263 byte[] lmv2Response = new byte[mac.length + clientData.length];
1264 System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
1265 System.arraycopy(clientData, 0, lmv2Response, mac.length,
1267 return lmv2Response;
1271 * Creates the NTLMv2 blob from the given target information block and
1274 * @param targetInformation The target information block from the Type 2
1276 * @param clientChallenge The random 8-byte client challenge.
1278 * @return The blob, used in the calculation of the NTLMv2 Response.
1280 private static byte[] createBlob(byte[] targetInformation,
1281 byte[] clientChallenge) {
1282 byte[] blobSignature = new byte[] {
1283 (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1285 byte[] reserved = new byte[] {
1286 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1288 byte[] unknown1 = new byte[] {
1289 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1291 byte[] unknown2 = new byte[] {
1292 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1294 long time = System.currentTimeMillis();
1295 time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
1296 time *= 10000; // tenths of a microsecond.
1297 // convert to little-endian byte array.
1298 byte[] timestamp = new byte[8];
1299 for (int i = 0; i < 8; i++) {
1300 timestamp[i] = (byte) time;
1303 byte[] blob = new byte[blobSignature.length + reserved.length +
1304 timestamp.length + clientChallenge.length +
1305 unknown1.length + targetInformation.length +
1308 System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
1309 offset += blobSignature.length;
1310 System.arraycopy(reserved, 0, blob, offset, reserved.length);
1311 offset += reserved.length;
1312 System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
1313 offset += timestamp.length;
1314 System.arraycopy(clientChallenge, 0, blob, offset,
1315 clientChallenge.length);
1316 offset += clientChallenge.length;
1317 System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
1318 offset += unknown1.length;
1319 System.arraycopy(targetInformation, 0, blob, offset,
1320 targetInformation.length);
1321 offset += targetInformation.length;
1322 System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
1327 * Calculates the HMAC-MD5 hash of the given data using the specified
1330 * @param data The data for which the hash will be calculated.
1331 * @param key The hashing key.
1333 * @return The HMAC-MD5 hash of the given data.
1335 private static byte[] hmacMD5(byte[] data, byte[] key) {
1336 byte[] ipad = new byte[64];
1337 byte[] opad = new byte[64];
1338 for (int i = 0; i < 64; i++) {
1339 ipad[i] = (byte) 0x36;
1340 opad[i] = (byte) 0x5c;
1342 for (int i = key.length - 1; i >= 0; i--) {
1346 byte[] content = new byte[data.length + 64];
1347 System.arraycopy(ipad, 0, content, 0, 64);
1348 System.arraycopy(data, 0, content, 64, data.length);
1349 MD5 md5 = new MD5();
1350 md5.update(content, 0, content.length);
1351 data = new byte[md5.getDigestSize()];
1352 md5.doFinal(data, 0);
1353 content = new byte[data.length + 64];
1354 System.arraycopy(opad, 0, content, 0, 64);
1355 System.arraycopy(data, 0, content, 64, data.length);
1357 md5.update(content, 0, content.length);
1358 byte[] ret = new byte[md5.getDigestSize()];
1359 md5.doFinal(ret, 0);
1364 * Creates a DES encryption key from the given key material.
1366 * @param bytes A byte array containing the DES key material.
1367 * @param offset The offset in the given byte array at which
1368 * the 7-byte key material starts.
1370 * @return A DES encryption key created from the key material
1371 * starting at the specified offset in the given byte array.
1374 private static Key createDESKey(byte[] bytes, int offset) {
1375 byte[] keyBytes = new byte[7];
1376 System.arraycopy(bytes, offset, keyBytes, 0, 7);
1377 byte[] material = new byte[8];
1378 material[0] = keyBytes[0];
1379 material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
1380 material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
1381 material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
1382 material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
1383 material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
1384 material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
1385 material[7] = (byte) (keyBytes[6] << 1);
1386 oddParity(material);
1387 return new SecretKeySpec(material, "DES");
1392 * Applies odd parity to the given byte array.
1394 * @param bytes The data whose parity bits are to be adjusted for
1397 private static void oddParity(byte[] bytes) {
1398 for (int i = 0; i < bytes.length; i++) {
1400 boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1401 (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1402 (b >>> 1)) & 0x01) == 0;
1404 bytes[i] |= (byte) 0x01;
1406 bytes[i] &= (byte) 0xfe;