1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
9 import org.bouncycastle.util.encoders.Base64;
10 import org.bouncycastle.crypto.digests.*;
13 * This object encapsulates a *single* HTTP connection. Multiple requests may be pipelined over a connection (thread-safe),
14 * although any IOException encountered in a request will invalidate all later requests.
18 /** the URL as passed to the original constructor; this is never changed */
19 final String originalUrl;
21 /** the URL to connect to; this is munged when the url is parsed */
24 /** the host to connect to */
27 /** the port to connect on */
30 /** true if SSL (HTTPS) should be used */
33 /** the path (URI) to retrieve on the server */
39 /** the socket's inputstream */
40 InputStream in = null;
42 /** the username and password portions of the URL */
43 String userInfo = null;
45 /** cache of userInfo strings, keyed on originalUrl */
46 private static Hashtable authCache = new Hashtable();
48 /** this is null if the current request is the first request on
49 * this HTTP connection; otherwise it is a Semaphore which will be
50 * released once the request ahead of us has recieved its response
52 Semaphore okToRecieve = null;
54 /** true iff this is the first request to be made on this socket */
55 boolean firstRequest = true;
57 /** cache for resolveAndCheckIfFirewalled() */
58 static Hashtable resolvedHosts = new Hashtable();
60 /** true iff we are allowed to skip the resolve check (only allowed when we're downloading the PAC script) */
61 boolean skipResolveCheck = false;
63 /** true iff we're using a proxy */
64 boolean proxied = false;
67 // Public Methods ////////////////////////////////////////////////////////////////////////////////////////
69 public HTTP(String url) { this(url, false); }
70 public HTTP(String url, boolean skipResolveCheck) {
72 this.skipResolveCheck = skipResolveCheck;
75 /** Performs an HTTP GET request */
76 public InputStream GET() throws IOException { return makeRequest(null, null); }
78 /** Performs an HTTP POST request; content is appended to the headers (so it should include a blank line to delimit the beginning of the body) */
79 public InputStream POST(String contentType, String content) throws IOException { return makeRequest(contentType, content); }
82 * This method isn't synchronized; however, only one thread can be in the inner synchronized block at a time, and the rest of
83 * the method is protected by in-order one-at-a-time semaphore lock-steps
85 private InputStream makeRequest(String contentType, String content) throws IOException {
87 // Step 1: send the request and establish a semaphore to stop any requests that pipeline after us
88 Semaphore blockOn = null;
89 Semaphore releaseMe = null;
93 sendRequest(contentType, content);
94 } catch (IOException e) {
98 blockOn = okToRecieve;
99 releaseMe = okToRecieve = new Semaphore();
102 // Step 2: wait for requests ahead of us to complete, then read the reply off the stream
103 boolean doRelease = true;
105 if (blockOn != null) blockOn.block();
107 // previous call wrecked the socket connection, but we already sent our request, so we can't just retry --
108 // this could cause the server to receive the request twice, which could be bad (think of the case where the
109 // server call causes Amazon.com to ship you an item with one-click purchasing).
111 throw new HTTPException("a previous pipelined call messed up the socket");
113 Hashtable h = in == null ? null : parseHeaders(in);
115 if (firstRequest) throw new HTTPException("server closed the socket with no response");
116 // sometimes the server chooses to close the stream between requests
119 return makeRequest(contentType, content);
122 String reply = h.get("STATUSLINE").toString();
124 if (reply.startsWith("407") || reply.startsWith("401")) {
126 if (reply.startsWith("407")) doProxyAuth(h, content == null ? "GET" : "POST");
127 else doWebAuth(h, content == null ? "GET" : "POST");
129 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null) {
130 if (Log.on) Log.log(this, "proxy returned an HTTP/1.0 reply with no content-length...");
133 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
134 new HTTPInputStream(in, cl, releaseMe).close();
137 return makeRequest(contentType, content);
139 } else if (reply.startsWith("2")) {
140 if (h.get("HTTP").equals("1.0") && h.get("content-length") == null)
141 throw new HTTPException("XWT does not support HTTP/1.0 servers which fail to return the Content-Length header");
142 int cl = h.get("content-length") == null ? -1 : Integer.parseInt(h.get("content-length").toString());
143 InputStream ret = new HTTPInputStream(in, cl, releaseMe);
144 if ("gzip".equals(h.get("content-encoding"))) ret = new java.util.zip.GZIPInputStream(ret);
149 throw new HTTPException("HTTP Error: " + reply);
153 } catch (IOException e) { reset(); throw e;
154 } finally { if (doRelease) releaseMe.release();
159 // Safeguarded DNS Resolver ///////////////////////////////////////////////////////////////////////////
162 * resolves the hostname and returns it as a string in the form "x.y.z.w"
163 * @throws HTTPException if the host falls within a firewalled netblock
165 private void resolveAndCheckIfFirewalled(String host) throws HTTPException {
168 if (resolvedHosts.get(host) != null) return;
170 // if all scripts are trustworthy (local FS), continue
171 if (Main.originAddr == null) return;
175 InetAddress addr = InetAddress.getByName(host);
176 byte[] quadbyte = addr.getAddress();
177 if ((quadbyte[0] == 10 ||
178 (quadbyte[0] == 192 && quadbyte[1] == 168) ||
179 (quadbyte[0] == 172 && (quadbyte[1] & 0xF0) == 16)) && !addr.equals(Main.originAddr))
180 throw new HTTPException("security violation: " + host + " [" + addr.getHostAddress() + "] is in a firewalled netblock");
182 } catch (UnknownHostException uhe) { }
184 if (Platform.detectProxy() == null)
185 throw new HTTPException("could not resolve hostname \"" + host + "\" and no proxy configured");
189 // Methods to attempt socket creation /////////////////////////////////////////////////////////////////
191 /** Attempts a direct connection */
192 public Socket attemptDirect() {
194 if (Log.verbose) Log.log(this, "attempting to create unproxied socket to " + host + ":" + port + (ssl ? " [ssl]" : ""));
195 return Platform.getSocket(host, port, ssl, true);
196 } catch (IOException e) {
197 if (Log.on) Log.log(this, "exception in attemptDirect(): " + e);
202 /** Attempts to use an HTTP proxy, employing the CONNECT method if HTTPS is requested */
203 public Socket attemptHttpProxy(String proxyHost, int proxyPort) {
205 if (Log.verbose) Log.log(this, "attempting to create HTTP proxied socket using proxy " + proxyHost + ":" + proxyPort);
207 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
209 if (!path.startsWith("http://")) path = "http://" + host + ":" + port + path;
211 PrintWriter pw = new PrintWriter(new OutputStreamWriter(sock.getOutputStream()));
212 BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
213 pw.print("CONNECT " + host + ":" + port + " HTTP/1.1\r\n\r\n");
215 String s = br.readLine();
216 if (s.charAt(9) != '2') throw new HTTPException("proxy refused CONNECT method: \"" + s + "\"");
217 while (br.readLine().length() > 0) { };
218 ((TinySSL)sock).negotiate();
222 } catch (IOException e) {
223 if (Log.on) Log.log(this, "exception in attemptHttpProxy(): " + e);
229 * Implements SOCKSv4 with v4a DNS extension
230 * @see http://www.socks.nec.com/protocol/socks4.protocol
231 * @see http://www.socks.nec.com/protocol/socks4a.protocol
233 public Socket attemptSocksProxy(String proxyHost, int proxyPort) {
235 // even if host is already a "x.y.z.w" string, we use this to parse it into bytes
236 InetAddress addr = null;
237 try { addr = InetAddress.getByName(host); } catch (Exception e) { }
239 if (Log.verbose) Log.log(this, "attempting to create SOCKSv4" + (addr == null ? "" : "a") +
240 " proxied socket using proxy " + proxyHost + ":" + proxyPort);
243 Socket sock = Platform.getSocket(proxyHost, proxyPort, ssl, false);
245 DataOutputStream dos = new DataOutputStream(sock.getOutputStream());
246 dos.writeByte(0x04); // SOCKSv4(a)
247 dos.writeByte(0x01); // CONNECT
248 dos.writeShort(port & 0xffff); // port
249 if (addr == null) dos.writeInt(0x00000001); // bogus IP
250 else dos.write(addr.getAddress()); // actual IP
251 dos.writeByte(0x00); // no userid
253 PrintWriter pw = new PrintWriter(new OutputStreamWriter(dos));
256 dos.writeByte(0x00); // hostname null terminator
260 DataInputStream dis = new DataInputStream(sock.getInputStream());
261 dis.readByte(); // reply version
262 byte success = dis.readByte(); // success/fail
263 dis.skip(6); // ip/port
265 if ((int)(success & 0xff) == 90) {
266 if (ssl) ((TinySSL)sock).negotiate();
269 if (Log.on) Log.log(this, "SOCKS server denied access, code " + (success & 0xff));
272 } catch (IOException e) {
273 if (Log.on) Log.log(this, "exception in attemptSocksProxy(): " + e);
278 /** executes the PAC script and dispatches a call to one of the other attempt methods based on the result */
279 public Socket attemptPAC(org.xwt.js.JS.Callable pacFunc) {
280 if (Log.verbose) Log.log(this, "evaluating PAC script");
283 org.xwt.js.JS.Array args = new org.xwt.js.JS.Array();
284 args.addElement(url.toString());
285 args.addElement(url.getHost());
287 Object obj = pacFunc.call(args);
288 if (Log.verbose) Log.log(this, " PAC script returned \"" + obj + "\"");
289 pac = obj.toString();
291 } catch (Throwable e) {
292 if (Log.on) Log.log(this, "PAC script threw exception " + e);
296 StringTokenizer st = new StringTokenizer(pac, ";", false);
297 while (st.hasMoreTokens()) {
298 String token = st.nextToken().trim();
299 if (Log.verbose) Log.log(this, " trying \"" + token + "\"...");
302 if (token.startsWith("DIRECT"))
303 ret = attemptDirect();
304 else if (token.startsWith("PROXY"))
305 ret = attemptHttpProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
306 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
307 else if (token.startsWith("SOCKS"))
308 ret = attemptSocksProxy(token.substring(token.indexOf(' ') + 1, token.indexOf(':')),
309 Integer.parseInt(token.substring(token.indexOf(':') + 1)));
310 if (ret != null) return ret;
311 } catch (Throwable e) {
312 if (Log.on) Log.log(this, "attempt at \"" + token + "\" failed due to " + e + "; trying next token");
315 if (Log.on) Log.log(this, "all PAC results exhausted");
320 // Everything Else ////////////////////////////////////////////////////////////////////////////
322 private synchronized void connect() throws IOException {
323 if (originalUrl.equals("stdio:")) {
324 in = new BufferedInputStream(System.in);
328 if (in == null) in = new BufferedInputStream(sock.getInputStream());
331 // grab the userinfo; gcj doesn't have java.net.URL.getUserInfo()
332 String url = originalUrl;
333 userInfo = url.substring(url.indexOf("://") + 3);
334 userInfo = userInfo.indexOf('/') == -1 ? userInfo : userInfo.substring(0, userInfo.indexOf('/'));
335 if (userInfo.indexOf('@') != -1) {
336 userInfo = userInfo.substring(0, userInfo.indexOf('@'));
337 url = url.substring(0, url.indexOf("://") + 3) + url.substring(url.indexOf('@') + 1);
342 if (url.startsWith("https:")) {
343 this.url = new URL("http" + url.substring(5));
345 } else if (!url.startsWith("http:")) {
346 throw new MalformedURLException("HTTP only supports http/https urls");
348 this.url = new URL(url);
350 if (!skipResolveCheck) resolveAndCheckIfFirewalled(this.url.getHost());
351 port = this.url.getPort();
352 path = this.url.getFile();
353 if (port == -1) port = ssl ? 443 : 80;
354 host = this.url.getHost();
355 if (Log.verbose) Log.log(this, "creating HTTP object for connection to " + host + ":" + port);
357 Proxy pi = Platform.detectProxy();
360 for(int i=0; i<pi.excluded.length; i++) if (host.equals(pi.excluded[i])) break OUTER;
361 if (sock == null && pi.proxyAutoConfigFunction != null) sock = attemptPAC(pi.proxyAutoConfigFunction);
362 if (sock == null && ssl && pi.httpsProxyHost != null) sock = attemptHttpProxy(pi.httpsProxyHost, pi.httpsProxyPort);
363 if (sock == null && pi.httpProxyHost != null) sock = attemptHttpProxy(pi.httpProxyHost, pi.httpProxyPort);
364 if (sock == null && pi.socksProxyHost != null) sock = attemptSocksProxy(pi.socksProxyHost, pi.socksProxyPort);
367 proxied = sock != null;
368 if (sock == null) sock = attemptDirect();
369 if (sock == null) throw new HTTPException("unable to contact host " + host);
370 if (in == null) in = new BufferedInputStream(sock.getInputStream());
373 public void sendRequest(String contentType, String content) throws IOException {
375 PrintWriter pw = new PrintWriter(new OutputStreamWriter(originalUrl.equals("stdio:") ? System.out : sock.getOutputStream()));
376 if (content != null) {
377 pw.print("POST " + path + " HTTP/1.1\r\n");
378 int contentLength = content.substring(0, 2).equals("\r\n") ?
379 content.length() - 2 :
380 (content.length() - content.indexOf("\r\n\r\n") - 4);
381 pw.print("Content-Length: " + contentLength + "\r\n");
382 if (contentType != null) pw.print("Content-Type: " + contentType + "\r\n");
384 pw.print("GET " + path + " HTTP/1.1\r\n");
387 pw.print("User-Agent: XWT\r\n");
388 pw.print("Accept-encoding: gzip\r\n");
389 pw.print("Host: " + (host + (port == 80 ? "" : (":" + port))) + "\r\n");
390 if (proxied) pw.print("X-RequestOrigin: " + Main.originHost + "\r\n");
392 if (Proxy.Authorization.authorization != null) pw.print("Proxy-Authorization: " + Proxy.Authorization.authorization2 + "\r\n");
393 if (authCache.get(originalUrl) != null) pw.print("Authorization: " + authCache.get(originalUrl) + "\r\n");
395 pw.print(content == null ? "\r\n" : content);
400 private void doWebAuth(Hashtable h0, String method) throws IOException {
401 if (userInfo == null) throw new HTTPException("web server demanded username/password, but none were supplied");
402 Hashtable h = parseAuthenticationChallenge(h0.get("www-authenticate").toString());
404 if (h.get("AUTHTYPE").equals("Basic")) {
405 if (authCache.get(originalUrl) != null) throw new HTTPException("username/password rejected");
406 authCache.put(originalUrl, "Basic " + new String(Base64.encode(userInfo.getBytes("US-ASCII"))));
408 } else if (h.get("AUTHTYPE").equals("Digest")) {
409 if (authCache.get(originalUrl) != null && !"true".equals(h.get("stale"))) throw new HTTPException("username/password rejected");
411 if (path2.startsWith("http://") || path2.startsWith("https://")) {
412 path2 = path2.substring(path2.indexOf("://") + 3);
413 path2 = path2.substring(path2.indexOf('/'));
415 String A1 = userInfo.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" + userInfo.substring(userInfo.indexOf(':') + 1);
416 String A2 = method + ":" + path2;
417 authCache.put(originalUrl,
419 "username=\"" + userInfo.substring(0, userInfo.indexOf(':')) + "\", " +
420 "realm=\"" + h.get("realm") + "\", " +
421 "nonce=\"" + h.get("nonce") + "\", " +
422 "uri=\"" + path2 + "\", " +
423 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
424 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
429 throw new HTTPException("unknown authentication type: " + h.get("AUTHTYPE"));
433 private void doProxyAuth(Hashtable h0, String method) throws IOException {
434 if (Log.on) Log.log(this, "Proxy AuthChallenge: " + h0.get("proxy-authenticate"));
435 Hashtable h = parseAuthenticationChallenge(h0.get("proxy-authenticate").toString());
436 String style = h.get("AUTHTYPE").toString();
437 String realm = (String)h.get("realm");
439 if (style.equals("NTLM") && Proxy.Authorization.authorization2 == null) {
440 Log.log(this, "Proxy identified itself as NTLM, sending Type 1 packet");
441 Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(Proxy.NTLM.type1);
445 if (!realm.equals("Digest") || Proxy.Authorization.authorization2 == null || !"true".equals(h.get("stale")))
446 Proxy.Authorization.getPassword(realm, style, sock.getInetAddress().getHostAddress(), Proxy.Authorization.authorization);
448 if (style.equals("Basic")) {
449 Proxy.Authorization.authorization2 =
450 "Basic " + new String(Base64.encode(Proxy.Authorization.authorization.getBytes("US-ASCII")));
452 } else if (style.equals("Digest")) {
453 String A1 = Proxy.Authorization.authorization.substring(0, userInfo.indexOf(':')) + ":" + h.get("realm") + ":" +
454 Proxy.Authorization.authorization.substring(Proxy.Authorization.authorization.indexOf(':') + 1);
455 String A2 = method + ":" + path;
456 Proxy.Authorization.authorization2 =
458 "username=\"" + Proxy.Authorization.authorization.substring(0, Proxy.Authorization.authorization.indexOf(':')) + "\", " +
459 "realm=\"" + h.get("realm") + "\", " +
460 "nonce=\"" + h.get("nonce") + "\", " +
461 "uri=\"" + path + "\", " +
462 (h.get("opaque") == null ? "" : ("opaque=\"" + h.get("opaque") + "\", ")) +
463 "response=\"" + H(H(A1) + ":" + h.get("nonce") + ":" + H(A2)) + "\", " +
466 } else if (style.equals("NTLM")) {
467 Log.log(this, "Proxy identified itself as NTLM, got Type 2 packet");
468 byte[] type2 = Base64.decode(((String)h0.get("proxy-authenticate")).substring(5).trim());
469 for(int i=0; i<type2.length; i += 4) {
471 if (i<type2.length) log += Integer.toString(type2[i] & 0xff, 16) + " ";
472 if (i+1<type2.length) log += Integer.toString(type2[i+1] & 0xff, 16) + " ";
473 if (i+2<type2.length) log += Integer.toString(type2[i+2] & 0xff, 16) + " ";
474 if (i+3<type2.length) log += Integer.toString(type2[i+3] & 0xff, 16) + " ";
477 // FIXME: need to keep the connection open between type1 and type3
478 // FIXME: finish this
479 //byte[] type3 = Proxy.NTLM.getResponse(
480 //Proxy.Authorization.authorization2 = "NTLM " + Base64.encode(type3));
485 // HTTPException ///////////////////////////////////////////////////////////////////////////////////
487 static class HTTPException extends IOException { public HTTPException(String s) { super(s); } }
490 // HTTPInputStream ///////////////////////////////////////////////////////////////////////////////////
492 /** An input stream that represents a subset of a longer input stream. Supports HTTP chunking as well */
493 public class HTTPInputStream extends FilterInputStream implements KnownLength {
495 /** if chunking, the number of bytes remaining in this subset; otherwise the remainder of the chunk */
496 private int length = 0;
498 /** this semaphore will be released when the stream is closed */
499 private Semaphore releaseMe = null;
501 /** indicates that we have encountered the zero-length terminator chunk */
502 boolean chunkedDone = false;
504 /** if we're on the first chunk, we don't pre-read a CRLF */
505 boolean firstChunk = true;
507 /** the length of the entire content body; -1 if chunked */
508 private int contentLength = 0;
509 public int getContentLength() { return contentLength; }
511 HTTPInputStream(InputStream in, int length, Semaphore releaseMe) throws IOException {
513 this.releaseMe = releaseMe;
514 this.contentLength = length;
515 this.length = length == -1 ? 0 : length;
518 public int getLength() { return contentLength; }
519 public boolean markSupported() { return false; }
520 public int read(byte[] b) throws IOException { return read(b, 0, b.length); }
521 public long skip(long n) throws IOException { return read(null, -1, (int)n); }
522 public int available() throws IOException {
523 if (contentLength == -1) return java.lang.Math.min(super.available(), length);
524 return super.available();
527 public int read() throws IOException {
528 byte[] b = new byte[1];
529 int ret = read(b, 0, 1);
530 return ret == -1 ? -1 : b[0] & 0xff;
533 private void readChunk() throws IOException {
534 if (chunkedDone) return;
535 if (!firstChunk) super.skip(2); // CRLF
537 String chunkLen = "";
539 int i = super.read();
540 if (i == -1) throw new HTTPException("encountered end of stream while reading chunk length");
542 // FEATURE: handle chunking extensions
550 length = Integer.parseInt(chunkLen.trim(), 16);
551 if (length == 0) chunkedDone = true;
554 public int read(byte[] b, int off, int len) throws IOException {
555 boolean good = false;
557 if (length == 0 && contentLength == -1) {
559 if (chunkedDone) { good = true; return -1; }
561 if (length == 0) { good = true; return -1; }
563 if (len > length) len = length;
564 int ret = b == null ? (int)super.skip(len) : super.read(b, off, len);
575 public void close() throws IOException {
576 if (contentLength == -1) {
577 while(!chunkedDone) {
578 if (length != 0) skip(length);
583 if (length != 0) skip(length);
585 if (releaseMe != null) releaseMe.release();
596 // Misc Helpers ///////////////////////////////////////////////////////////////////////////////////
598 /** reads a set of HTTP headers off of the input stream, returning null if the stream is already at its end */
599 private Hashtable parseHeaders(InputStream in) throws IOException {
600 Hashtable ret = new Hashtable();
602 // we can't use a BufferedReader directly on the input stream, since it will buffer past the end of the headers
603 byte[] buf = new byte[4096];
606 int read = in.read();
607 if (read == -1 && buflen == 0) return null;
608 if (read == -1) throw new HTTPException("stream closed while reading headers");
609 buf[buflen++] = (byte)read;
610 if (buflen >= 4 && buf[buflen - 4] == '\r' && buf[buflen - 3] == '\n' && buf[buflen - 2] == '\r' && buf[buflen - 1] == '\n') break;
611 if (buflen == buf.length) {
612 byte[] newbuf = new byte[buf.length * 2];
613 System.arraycopy(buf, 0, newbuf, 0, buflen);
618 BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(buf, 0, buflen)));
619 String s = br.readLine();
620 if (!s.startsWith("HTTP/")) throw new HTTPException("Expected reply to start with \"HTTP/\", got: " + s);
621 ret.put("STATUSLINE", s.substring(s.indexOf(' ') + 1));
622 ret.put("HTTP", s.substring(5, s.indexOf(' ')));
624 while((s = br.readLine()) != null && s.length() > 0) {
625 String front = s.substring(0, s.indexOf(':')).toLowerCase();
626 String back = s.substring(s.indexOf(':') + 1).trim();
627 // ugly hack: we never replace a Digest-auth with a Basic-auth (proxy + www)
628 if (front.endsWith("-authenticate") && ret.get(front) != null && !back.equals("Digest")) continue;
629 ret.put(front, back);
634 private Hashtable parseAuthenticationChallenge(String s) {
635 Hashtable ret = new Hashtable();
638 ret.put("AUTHTYPE", s.substring(0, s.indexOf(' ')));
639 s = s.substring(s.indexOf(' ')).trim();
641 while (s.length() > 0) {
643 String key = s.substring(0, s.indexOf('='));
644 s = s.substring(s.indexOf('=') + 1);
645 if (s.charAt(0) == '\"') {
647 val = s.substring(0, s.indexOf('\"'));
648 s = s.substring(s.indexOf('\"') + 1);
650 val = s.indexOf(',') == -1 ? s : s.substring(0, s.indexOf(','));
651 s = s.indexOf(',') == -1 ? "" : s.substring(s.indexOf(',') + 1);
653 if (s.length() > 0 && s.charAt(0) == ',') s = s.substring(1);
660 private String H(String s) throws IOException {
661 byte[] b = s.getBytes("US-ASCII");
662 MD5Digest md5 = new MD5Digest();
663 md5.update(b, 0, b.length);
664 byte[] out = new byte[md5.getDigestSize()];
667 for(int i=0; i<out.length; i++) {
668 ret += "0123456789abcdef".charAt((out[i] & 0xf0) >> 4);
669 ret += "0123456789abcdef".charAt(out[i] & 0x0f);
675 // Proxy ///////////////////////////////////////////////////////////
677 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
678 public static class Proxy {
682 /** the HTTP Proxy host to use */
683 public String httpProxyHost = null;
685 /** the HTTP Proxy port to use */
686 public int httpProxyPort = -1;
688 /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
689 public String httpsProxyHost = null;
691 /** if a seperate proxy should be used for HTTPS, this is the port */
692 public int httpsProxyPort = -1;
694 /** the SOCKS Proxy Host to use */
695 public String socksProxyHost = null;
697 /** the SOCKS Proxy Port to use */
698 public int socksProxyPort = -1;
700 /** hosts to be excluded from proxy use; wildcards permitted */
701 public String[] excluded = null;
703 /** the PAC script */
704 public JS.Callable proxyAutoConfigFunction = null;
706 public static Proxy detectProxyViaManual() {
707 Proxy ret = new Proxy();
709 ret.httpProxyHost = Platform.getEnv("http_proxy");
710 if (ret.httpProxyHost != null) {
711 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
712 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
713 if (ret.httpProxyHost.indexOf(':') != -1) {
714 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
715 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
717 ret.httpProxyPort = 80;
721 ret.httpsProxyHost = Platform.getEnv("https_proxy");
722 if (ret.httpsProxyHost != null) {
723 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
724 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
725 if (ret.httpsProxyHost.indexOf(':') != -1) {
726 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
727 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
729 ret.httpsProxyPort = 80;
733 ret.socksProxyHost = Platform.getEnv("socks_proxy");
734 if (ret.socksProxyHost != null) {
735 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
736 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
737 if (ret.socksProxyHost.indexOf(':') != -1) {
738 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
739 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
741 ret.socksProxyPort = 80;
745 String noproxy = Platform.getEnv("no_proxy");
746 if (noproxy != null) {
747 StringTokenizer st = new StringTokenizer(noproxy, ",");
748 ret.excluded = new String[st.countTokens()];
749 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
752 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
756 public static JS.Scope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
757 public static JS.Callable getProxyAutoConfigFunction(String url) {
759 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
762 while((s = br.readLine()) != null) script += s + "\n";
763 if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
764 if (Log.on) Log.log(Proxy.class, script);
767 Vector carpHosts = new Vector();
768 for(int i=0; i<script.length(); i++)
769 if (script.regionMatches(i, "new Node(", 0, 9)) {
770 String host = script.substring(i + 10, script.indexOf('\"', i + 11));
771 if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
772 carpHosts.addElement(host);
774 if (carpHosts.size() > 0) {
775 script = "function FindProxyForURL(url, host) {\nreturn \"";
776 for(int i=0; i<carpHosts.size(); i++)
777 script += "PROXY " + carpHosts.elementAt(i) + "; ";
779 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
780 if (Log.on) Log.log(Proxy.class, script);
783 Function scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
786 scr.call(new JS.Array(), proxyAutoConfigRootScope);
788 return (JS.Callable)proxyAutoConfigRootScope.get("FindProxyForURL");
789 } catch (Exception e) {
791 Log.log(Platform.class, "WPAD detection failed due to:");
792 if (e instanceof JS.Exn) {
794 org.xwt.js.JS.Array arr = new org.xwt.js.JS.Array();
795 arr.addElement(((JS.Exn)e).getObject());
796 } catch (Exception e2) {
797 Log.log(Platform.class, e);
800 else Log.log(Platform.class, e);
807 // Authorization ///////////////////////////////////////////////////////////////////////////////////
809 public static class Authorization {
811 static public String authorization = null;
812 static public String authorization2 = null;
813 static public Semaphore waitingForUser = new Semaphore();
815 public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
817 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
818 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
819 // a password, so we should reattempt authorization.
821 if (authorization != oldAuth) return;
822 if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
825 Message.Q.add(new Message() {
826 public void perform() {
828 Template t = Template.getTemplate((Res)Main.builtin.get("org/xwt/builtin/proxy_authorization.xwt"));
829 t.apply(b, null, null);
830 b.put("realm", realm);
831 b.put("proxyIP", proxyIP);
835 waitingForUser.block();
836 if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
842 // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
844 public static class ProxyAutoConfigRootScope extends JS.GlobalScope {
846 public ProxyAutoConfigRootScope() { super(null); }
848 public Object get(Object name) {
849 if (name.equals("isPlainHostName")) return isPlainHostName;
850 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
851 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
852 else if (name.equals("isResolvable")) return isResolvable;
853 else if (name.equals("isInNet")) return isInNet;
854 else if (name.equals("dnsResolve")) return dnsResolve;
855 else if (name.equals("myIpAddress")) return myIpAddress;
856 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
857 else if (name.equals("shExpMatch")) return shExpMatch;
858 else if (name.equals("weekdayRange")) return weekdayRange;
859 else if (name.equals("dateRange")) return dateRange;
860 else if (name.equals("timeRange")) return timeRange;
861 else if (name.equals("ProxyConfig")) return ProxyConfig;
862 else return super.get(name);
865 private static final JS.Obj proxyConfigBindings = new JS.Obj();
866 private static final JS.Obj ProxyConfig = new JS.Obj() {
867 public Object get(Object name) {
868 if (name.equals("bindings")) return proxyConfigBindings;
873 private static final JS.Callable isPlainHostName = new JS.Callable() {
874 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
875 return (args.elementAt(0).toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
879 private static final JS.Callable dnsDomainIs = new JS.Callable() {
880 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
881 return (args.elementAt(0).toString().endsWith(args.elementAt(1).toString())) ? Boolean.TRUE : Boolean.FALSE;
885 private static final JS.Callable localHostOrDomainIs = new JS.Callable() {
886 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
887 return (args.elementAt(0).toString().equals(args.elementAt(1).toString()) ||
888 (args.elementAt(0).toString().indexOf('.') == -1 && args.elementAt(1).toString().startsWith(args.elementAt(0).toString()))) ?
889 Boolean.TRUE : Boolean.FALSE;
893 private static final JS.Callable isResolvable = new JS.Callable() {
894 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
896 return (InetAddress.getByName(args.elementAt(0).toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
897 } catch (UnknownHostException e) {
898 return Boolean.FALSE;
903 private static final JS.Callable isInNet = new JS.Callable() {
904 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
905 if (args.length() != 3) return Boolean.FALSE;
907 byte[] host = InetAddress.getByName(args.elementAt(0).toString()).getAddress();
908 byte[] net = InetAddress.getByName(args.elementAt(1).toString()).getAddress();
909 byte[] mask = InetAddress.getByName(args.elementAt(2).toString()).getAddress();
910 return ((host[0] & mask[0]) == net[0] &&
911 (host[1] & mask[1]) == net[1] &&
912 (host[2] & mask[2]) == net[2] &&
913 (host[3] & mask[3]) == net[3]) ?
914 Boolean.TRUE : Boolean.FALSE;
915 } catch (Exception e) {
916 throw new JS.Exn("exception in isInNet(): " + e);
921 private static final JS.Callable dnsResolve = new JS.Callable() {
922 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
924 return InetAddress.getByName(args.elementAt(0).toString()).getHostAddress();
925 } catch (UnknownHostException e) {
931 private static final JS.Callable myIpAddress = new JS.Callable() {
932 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
934 return InetAddress.getLocalHost().getHostAddress();
935 } catch (UnknownHostException e) {
936 if (Log.on) Log.log(this, "strange... host does not know its own address");
942 private static final JS.Callable dnsDomainLevels = new JS.Callable() {
943 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
944 String s = args.elementAt(0).toString();
946 while((i = s.indexOf('.', i)) != -1) i++;
947 return new Integer(i);
951 private static boolean match(String[] arr, String s, int index) {
952 if (index >= arr.length) return true;
953 for(int i=0; i<s.length(); i++) {
954 String s2 = s.substring(i);
955 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
960 private static final JS.Callable shExpMatch = new JS.Callable() {
961 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
962 StringTokenizer st = new StringTokenizer(args.elementAt(1).toString(), "*", false);
963 String[] arr = new String[st.countTokens()];
964 String s = args.elementAt(0).toString();
965 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
966 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
970 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
972 private static final JS.Callable weekdayRange = new JS.Callable() {
973 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
974 TimeZone tz = (args.length() < 3 || args.elementAt(2) == null || !args.elementAt(2).equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
975 Calendar c = new GregorianCalendar();
977 c.setTime(new java.util.Date());
978 java.util.Date d = c.getTime();
979 int day = d.getDay();
981 String d1s = args.elementAt(0).toString().toUpperCase();
983 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
985 if (args.length() == 1)
986 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
988 String d2s = args.elementAt(1).toString().toUpperCase();
989 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
992 ((d1 <= d2 && day >= d1 && day <= d2) ||
993 (d1 > d2 && (day >= d1 || day <= d2))) ?
994 Boolean.TRUE : Boolean.FALSE;
998 private static final JS.Callable dateRange = new JS.Callable() {
999 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
1000 throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
1004 private static final JS.Callable timeRange = new JS.Callable() {
1005 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
1006 throw new JS.Exn("XWT does not support timeRange() in PAC scripts");
1013 * An implementation of Microsoft's proprietary NTLM authentication protocol. This code was derived from Eric
1014 * Glass's work, and is copyright as follows:
1016 * Copyright (c) 2003 Eric Glass (eglass1 at comcast.net).
1018 * Permission to use, copy, modify, and distribute this document for any purpose and without any fee is hereby
1019 * granted, provided that the above copyright notice and this list of conditions appear in all copies.
1020 * The most current version of this document may be obtained from http://davenport.sourceforge.net/ntlm.html .
1022 public static class NTLM {
1024 public static final byte[] type1 = new byte[] { 0x4e, 0x54, 0x4c, 0x4d, 0x53, 0x53, 0x50, 0x00, 0x01,
1025 0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x00 };
1028 * Calculates the NTLM Response for the given challenge, using the
1029 * specified password.
1031 * @param password The user's password.
1032 * @param challenge The Type 2 challenge from the server.
1034 * @return The NTLM Response.
1036 public static byte[] getNTLMResponse(String password, byte[] challenge)
1038 byte[] ntlmHash = ntlmHash(password);
1039 return lmResponse(ntlmHash, challenge);
1043 * Calculates the LM Response for the given challenge, using the specified
1046 * @param password The user's password.
1047 * @param challenge The Type 2 challenge from the server.
1049 * @return The LM Response.
1051 public static byte[] getLMResponse(String password, byte[] challenge)
1053 byte[] lmHash = lmHash(password);
1054 return lmResponse(lmHash, challenge);
1058 * Calculates the NTLMv2 Response for the given challenge, using the
1059 * specified authentication target, username, password, target information
1060 * block, and client challenge.
1062 * @param target The authentication target (i.e., domain).
1063 * @param user The username.
1064 * @param password The user's password.
1065 * @param targetInformation The target information block from the Type 2
1067 * @param challenge The Type 2 challenge from the server.
1068 * @param clientChallenge The random 8-byte client challenge.
1070 * @return The NTLMv2 Response.
1072 public static byte[] getNTLMv2Response(String target, String user,
1073 String password, byte[] targetInformation, byte[] challenge,
1074 byte[] clientChallenge) throws Exception {
1075 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1076 byte[] blob = createBlob(targetInformation, clientChallenge);
1077 return lmv2Response(ntlmv2Hash, blob, challenge);
1081 * Calculates the LMv2 Response for the given challenge, using the
1082 * specified authentication target, username, password, and client
1085 * @param target The authentication target (i.e., domain).
1086 * @param user The username.
1087 * @param password The user's password.
1088 * @param challenge The Type 2 challenge from the server.
1089 * @param clientChallenge The random 8-byte client challenge.
1091 * @return The LMv2 Response.
1093 public static byte[] getLMv2Response(String target, String user,
1094 String password, byte[] challenge, byte[] clientChallenge)
1096 byte[] ntlmv2Hash = ntlmv2Hash(target, user, password);
1097 return lmv2Response(ntlmv2Hash, clientChallenge, challenge);
1101 * Calculates the NTLM2 Session Response for the given challenge, using the
1102 * specified password and client challenge.
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 NTLM2 Session Response. This is placed in the NTLM
1109 * response field of the Type 3 message; the LM response field contains
1110 * the client challenge, null-padded to 24 bytes.
1112 public static byte[] getNTLM2SessionResponse(String password,
1113 byte[] challenge, byte[] clientChallenge) throws Exception {
1114 byte[] ntlmHash = ntlmHash(password);
1115 MD5Digest md5 = new MD5Digest();
1116 md5.update(challenge, 0, challenge.length);
1117 md5.update(clientChallenge, 0, clientChallenge.length);
1118 byte[] sessionHash = new byte[8];
1119 byte[] md5_out = new byte[md5.getDigestSize()];
1120 md5.doFinal(md5_out, 0);
1121 System.arraycopy(md5_out, 0, sessionHash, 0, 8);
1122 return lmResponse(ntlmHash, sessionHash);
1126 * Creates the LM Hash of the user's password.
1128 * @param password The password.
1130 * @return The LM Hash of the given password, used in the calculation
1131 * of the LM Response.
1133 private static byte[] lmHash(String password) throws Exception {
1135 byte[] oemPassword = password.toUpperCase().getBytes("US-ASCII");
1136 int length = java.lang.Math.min(oemPassword.length, 14);
1137 byte[] keyBytes = new byte[14];
1138 System.arraycopy(oemPassword, 0, keyBytes, 0, length);
1139 Key lowKey = createDESKey(keyBytes, 0);
1140 Key highKey = createDESKey(keyBytes, 7);
1141 byte[] magicConstant = "KGS!@#$%".getBytes("US-ASCII");
1142 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1143 des.init(Cipher.ENCRYPT_MODE, lowKey);
1144 byte[] lowHash = des.doFinal(magicConstant);
1145 des.init(Cipher.ENCRYPT_MODE, highKey);
1146 byte[] highHash = des.doFinal(magicConstant);
1147 byte[] lmHash = new byte[16];
1148 System.arraycopy(lowHash, 0, lmHash, 0, 8);
1149 System.arraycopy(highHash, 0, lmHash, 8, 8);
1152 return null; // FIXME
1156 * Creates the NTLM Hash of the user's password.
1158 * @param password The password.
1160 * @return The NTLM Hash of the given password, used in the calculation
1161 * of the NTLM Response and the NTLMv2 and LMv2 Hashes.
1163 private static byte[] ntlmHash(String password) throws Exception {
1164 byte[] unicodePassword = password.getBytes("UnicodeLittleUnmarked");
1165 MD4Digest md4 = new MD4Digest();
1166 md4.update(unicodePassword, 0, unicodePassword.length);
1167 byte[] ret = new byte[md4.getDigestSize()];
1172 * Creates the NTLMv2 Hash of the user's password.
1174 * @param target The authentication target (i.e., domain).
1175 * @param user The username.
1176 * @param password The password.
1178 * @return The NTLMv2 Hash, used in the calculation of the NTLMv2
1179 * and LMv2 Responses.
1181 private static byte[] ntlmv2Hash(String target, String user,
1182 String password) throws Exception {
1183 byte[] ntlmHash = ntlmHash(password);
1184 String identity = user.toUpperCase() + target.toUpperCase();
1185 return hmacMD5(identity.getBytes("UnicodeLittleUnmarked"), ntlmHash);
1189 * Creates the LM Response from the given hash and Type 2 challenge.
1191 * @param hash The LM or NTLM Hash.
1192 * @param challenge The server challenge from the Type 2 message.
1194 * @return The response (either LM or NTLM, depending on the provided
1197 private static byte[] lmResponse(byte[] hash, byte[] challenge)
1200 byte[] keyBytes = new byte[21];
1201 System.arraycopy(hash, 0, keyBytes, 0, 16);
1202 Key lowKey = createDESKey(keyBytes, 0);
1203 Key middleKey = createDESKey(keyBytes, 7);
1204 Key highKey = createDESKey(keyBytes, 14);
1205 Cipher des = Cipher.getInstance("DES/ECB/NoPadding");
1206 des.init(Cipher.ENCRYPT_MODE, lowKey);
1207 byte[] lowResponse = des.doFinal(challenge);
1208 des.init(Cipher.ENCRYPT_MODE, middleKey);
1209 byte[] middleResponse = des.doFinal(challenge);
1210 des.init(Cipher.ENCRYPT_MODE, highKey);
1211 byte[] highResponse = des.doFinal(challenge);
1212 byte[] lmResponse = new byte[24];
1213 System.arraycopy(lowResponse, 0, lmResponse, 0, 8);
1214 System.arraycopy(middleResponse, 0, lmResponse, 8, 8);
1215 System.arraycopy(highResponse, 0, lmResponse, 16, 8);
1218 return null; // FIXME
1222 * Creates the LMv2 Response from the given hash, client data, and
1225 * @param hash The NTLMv2 Hash.
1226 * @param clientData The client data (blob or client challenge).
1227 * @param challenge The server challenge from the Type 2 message.
1229 * @return The response (either NTLMv2 or LMv2, depending on the
1232 private static byte[] lmv2Response(byte[] hash, byte[] clientData,
1233 byte[] challenge) throws Exception {
1234 byte[] data = new byte[challenge.length + clientData.length];
1235 System.arraycopy(challenge, 0, data, 0, challenge.length);
1236 System.arraycopy(clientData, 0, data, challenge.length,
1238 byte[] mac = hmacMD5(data, hash);
1239 byte[] lmv2Response = new byte[mac.length + clientData.length];
1240 System.arraycopy(mac, 0, lmv2Response, 0, mac.length);
1241 System.arraycopy(clientData, 0, lmv2Response, mac.length,
1243 return lmv2Response;
1247 * Creates the NTLMv2 blob from the given target information block and
1250 * @param targetInformation The target information block from the Type 2
1252 * @param clientChallenge The random 8-byte client challenge.
1254 * @return The blob, used in the calculation of the NTLMv2 Response.
1256 private static byte[] createBlob(byte[] targetInformation,
1257 byte[] clientChallenge) {
1258 byte[] blobSignature = new byte[] {
1259 (byte) 0x01, (byte) 0x01, (byte) 0x00, (byte) 0x00
1261 byte[] reserved = new byte[] {
1262 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1264 byte[] unknown1 = new byte[] {
1265 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1267 byte[] unknown2 = new byte[] {
1268 (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00
1270 long time = System.currentTimeMillis();
1271 time += 11644473600000l; // milliseconds from January 1, 1601 -> epoch.
1272 time *= 10000; // tenths of a microsecond.
1273 // convert to little-endian byte array.
1274 byte[] timestamp = new byte[8];
1275 for (int i = 0; i < 8; i++) {
1276 timestamp[i] = (byte) time;
1279 byte[] blob = new byte[blobSignature.length + reserved.length +
1280 timestamp.length + clientChallenge.length +
1281 unknown1.length + targetInformation.length +
1284 System.arraycopy(blobSignature, 0, blob, offset, blobSignature.length);
1285 offset += blobSignature.length;
1286 System.arraycopy(reserved, 0, blob, offset, reserved.length);
1287 offset += reserved.length;
1288 System.arraycopy(timestamp, 0, blob, offset, timestamp.length);
1289 offset += timestamp.length;
1290 System.arraycopy(clientChallenge, 0, blob, offset,
1291 clientChallenge.length);
1292 offset += clientChallenge.length;
1293 System.arraycopy(unknown1, 0, blob, offset, unknown1.length);
1294 offset += unknown1.length;
1295 System.arraycopy(targetInformation, 0, blob, offset,
1296 targetInformation.length);
1297 offset += targetInformation.length;
1298 System.arraycopy(unknown2, 0, blob, offset, unknown2.length);
1303 * Calculates the HMAC-MD5 hash of the given data using the specified
1306 * @param data The data for which the hash will be calculated.
1307 * @param key The hashing key.
1309 * @return The HMAC-MD5 hash of the given data.
1311 private static byte[] hmacMD5(byte[] data, byte[] key) throws Exception {
1312 byte[] ipad = new byte[64];
1313 byte[] opad = new byte[64];
1314 for (int i = 0; i < 64; i++) {
1315 ipad[i] = (byte) 0x36;
1316 opad[i] = (byte) 0x5c;
1318 for (int i = key.length - 1; i >= 0; i--) {
1322 byte[] content = new byte[data.length + 64];
1323 System.arraycopy(ipad, 0, content, 0, 64);
1324 System.arraycopy(data, 0, content, 64, data.length);
1325 MD5Digest md5 = new MD5Digest();
1326 md5.update(content, 0, content.length);
1327 data = new byte[md5.getDigestSize()];
1328 md5.doFinal(data, 0);
1329 content = new byte[data.length + 64];
1330 System.arraycopy(opad, 0, content, 0, 64);
1331 System.arraycopy(data, 0, content, 64, data.length);
1332 md5 = new MD5Digest();
1333 md5.update(content, 0, content.length);
1334 byte[] ret = new byte[md5.getDigestSize()];
1335 md5.doFinal(ret, 0);
1340 * Creates a DES encryption key from the given key material.
1342 * @param bytes A byte array containing the DES key material.
1343 * @param offset The offset in the given byte array at which
1344 * the 7-byte key material starts.
1346 * @return A DES encryption key created from the key material
1347 * starting at the specified offset in the given byte array.
1350 private static Key createDESKey(byte[] bytes, int offset) {
1351 byte[] keyBytes = new byte[7];
1352 System.arraycopy(bytes, offset, keyBytes, 0, 7);
1353 byte[] material = new byte[8];
1354 material[0] = keyBytes[0];
1355 material[1] = (byte) (keyBytes[0] << 7 | (keyBytes[1] & 0xff) >>> 1);
1356 material[2] = (byte) (keyBytes[1] << 6 | (keyBytes[2] & 0xff) >>> 2);
1357 material[3] = (byte) (keyBytes[2] << 5 | (keyBytes[3] & 0xff) >>> 3);
1358 material[4] = (byte) (keyBytes[3] << 4 | (keyBytes[4] & 0xff) >>> 4);
1359 material[5] = (byte) (keyBytes[4] << 3 | (keyBytes[5] & 0xff) >>> 5);
1360 material[6] = (byte) (keyBytes[5] << 2 | (keyBytes[6] & 0xff) >>> 6);
1361 material[7] = (byte) (keyBytes[6] << 1);
1362 oddParity(material);
1363 return new SecretKeySpec(material, "DES");
1368 * Applies odd parity to the given byte array.
1370 * @param bytes The data whose parity bits are to be adjusted for
1373 private static void oddParity(byte[] bytes) {
1374 for (int i = 0; i < bytes.length; i++) {
1376 boolean needsParity = (((b >>> 7) ^ (b >>> 6) ^ (b >>> 5) ^
1377 (b >>> 4) ^ (b >>> 3) ^ (b >>> 2) ^
1378 (b >>> 1)) & 0x01) == 0;
1380 bytes[i] |= (byte) 0x01;
1382 bytes[i] &= (byte) 0xfe;