Thursday, June 15, 2017

Interpreting wpad.dat using jrunscript from JDK 8 to work out the right proxy.

In many environments you find that the correct proxy can only be fetched by parsing http://wpad/wpad.dat, which is a pain because it is actually a JavaScript file. Working out the right proxy to call for say a unix environment is a bit of a fiddle particularly if you company is huge and requires different proxies for different countries. JDK 8 to the rescue, as you can run a simple script in the Nashorn environment to get the suggested proxy for one host and use that for everything:

jrunscript -e "`curl -o - -s http://wpad/wpad.dat` function isPlainHostName(hostname) { return hostname.indexOf('.')==-1;}; var proxyList = FindProxyForURL('http://github.com','github.com'); var firstProxy = proxyList.split(';')[0].trim(); print('DIRECT'.equals(firstProxy) ?  '' : 'http://' + firstProxy.split(' ')[1]);"

Depending on your local environment you might have to implement one or more functions from the list that your wpad.dat expects, in our case I needed to implement isPlainHost.

The last part of the script just picks the first proxy name, as the function returns a list of PROXY is suggested order. The raw output looks like this:

PROXY london.example.com:80; PROXY sf.example.com:80; DIRECT;

So we just pick the first one with http as the prefix, as some tools such as docker are fussy about this, or returns an empty string if DIRECT is recommended.

http://london.example.com:80