1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
9 import org.bouncycastle.util.encoders.Base64;
11 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
16 /** the HTTP Proxy host to use */
17 public String httpProxyHost = null;
19 /** the HTTP Proxy port to use */
20 public int httpProxyPort = -1;
22 /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
23 public String httpsProxyHost = null;
25 /** if a seperate proxy should be used for HTTPS, this is the port */
26 public int httpsProxyPort = -1;
28 /** the SOCKS Proxy Host to use */
29 public String socksProxyHost = null;
31 /** the SOCKS Proxy Port to use */
32 public int socksProxyPort = -1;
34 /** hosts to be excluded from proxy use; wildcards permitted */
35 public String[] excluded = null;
38 public JS.Function proxyAutoConfigFunction = null;
40 public static Proxy detectProxyViaManual() {
41 Proxy ret = new Proxy();
43 ret.httpProxyHost = Platform.getEnv("http_proxy");
44 if (ret.httpProxyHost != null) {
45 if (ret.httpProxyHost.startsWith("http://")) ret.httpProxyHost = ret.httpProxyHost.substring(7);
46 if (ret.httpProxyHost.endsWith("/")) ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.length() - 1);
47 if (ret.httpProxyHost.indexOf(':') != -1) {
48 ret.httpProxyPort = Integer.parseInt(ret.httpProxyHost.substring(ret.httpProxyHost.indexOf(':') + 1));
49 ret.httpProxyHost = ret.httpProxyHost.substring(0, ret.httpProxyHost.indexOf(':'));
51 ret.httpProxyPort = 80;
55 ret.httpsProxyHost = Platform.getEnv("https_proxy");
56 if (ret.httpsProxyHost != null) {
57 if (ret.httpsProxyHost.startsWith("https://")) ret.httpsProxyHost = ret.httpsProxyHost.substring(7);
58 if (ret.httpsProxyHost.endsWith("/")) ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.length() - 1);
59 if (ret.httpsProxyHost.indexOf(':') != -1) {
60 ret.httpsProxyPort = Integer.parseInt(ret.httpsProxyHost.substring(ret.httpsProxyHost.indexOf(':') + 1));
61 ret.httpsProxyHost = ret.httpsProxyHost.substring(0, ret.httpsProxyHost.indexOf(':'));
63 ret.httpsProxyPort = 80;
67 ret.socksProxyHost = Platform.getEnv("socks_proxy");
68 if (ret.socksProxyHost != null) {
69 if (ret.socksProxyHost.startsWith("socks://")) ret.socksProxyHost = ret.socksProxyHost.substring(7);
70 if (ret.socksProxyHost.endsWith("/")) ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.length() - 1);
71 if (ret.socksProxyHost.indexOf(':') != -1) {
72 ret.socksProxyPort = Integer.parseInt(ret.socksProxyHost.substring(ret.socksProxyHost.indexOf(':') + 1));
73 ret.socksProxyHost = ret.socksProxyHost.substring(0, ret.socksProxyHost.indexOf(':'));
75 ret.socksProxyPort = 80;
79 String noproxy = Platform.getEnv("no_proxy");
80 if (noproxy != null) {
81 StringTokenizer st = new StringTokenizer(noproxy, ",");
82 ret.excluded = new String[st.countTokens()];
83 for(int i=0; st.hasMoreTokens(); i++) ret.excluded[i] = st.nextToken();
86 if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
90 //public static JS proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
91 public static JS.Function getProxyAutoConfigFunction(String url) {
92 throw new Error("not implemented");
96 Context cx = Context.enter();
97 cx.setOptimizationLevel(-1);
98 BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
101 while((s = br.readLine()) != null) script += s + "\n";
102 if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
103 if (Log.on) Log.log(Proxy.class, script);
106 Vector carpHosts = new Vector();
107 for(int i=0; i<script.length(); i++)
108 if (script.regionMatches(i, "new Node(", 0, 9)) {
109 String host = script.substring(i + 10, script.indexOf('\"', i + 11));
110 if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
111 carpHosts.addElement(host);
113 if (carpHosts.size() > 0) {
114 script = "function FindProxyForURL(url, host) {\nreturn \"";
115 for(int i=0; i<carpHosts.size(); i++)
116 script += "PROXY " + carpHosts.elementAt(i) + "; ";
118 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
119 if (Log.on) Log.log(Proxy.class, script);
122 Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
123 scr.exec(cx, proxyAutoConfigRootScope);
124 return (JS.Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
125 } catch (Exception e) {
127 Log.log(Platform.class, "WPAD detection failed due to:");
128 if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
129 ((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
130 else if (e instanceof JS.Exn) {
132 XWT.recursivePrintObject.call(Context.enter(), null, null, new Object[] {
133 ((JS.Exn)e).getValue() });
134 } catch (Exception e2) {
135 Log.log(Platform.class, e);
138 else Log.log(Platform.class, e);
146 // Authorization ///////////////////////////////////////////////////////////////////////////////////
148 public static class Authorization {
150 static public String authorization = null;
151 static public String authorization2 = null;
152 static public Semaphore waitingForUser = new Semaphore();
154 public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
156 // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
157 // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
158 // a password, so we should reattempt authorization.
160 if (authorization != oldAuth) return;
161 if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
162 MessageQueue.add(new Message() {
163 public void perform() {
164 Box b = new Box("org.xwt.builtin.proxy_authorization", null);
165 b.put("realm", realm);
166 b.put("proxyIP", proxyIP);
170 waitingForUser.block();
171 if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
177 // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
179 public static class ProxyAutoConfigRootScope extends JSObject {
181 public String getClassName() { return "ProxyAutoConfigRootScope"; }
182 ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
184 public Object get(String name, JS start) {
185 if (name.equals("isPlainHostName")) return isPlainHostName;
186 else if (name.equals("dnsDomainIs")) return dnsDomainIs;
187 else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
188 else if (name.equals("isResolvable")) return isResolvable;
189 else if (name.equals("isInNet")) return isInNet;
190 else if (name.equals("dnsResolve")) return dnsResolve;
191 else if (name.equals("myIpAddress")) return myIpAddress;
192 else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
193 else if (name.equals("shExpMatch")) return shExpMatch;
194 else if (name.equals("weekdayRange")) return weekdayRange;
195 else if (name.equals("dateRange")) return dateRange;
196 else if (name.equals("timeRange")) return timeRange;
197 else if (name.equals("ProxyConfig")) return ProxyConfig;
198 else return super.get(name, start);
201 private static final JS.Object proxyConfigBindings = new JS.Object();
202 private static final JS.Object ProxyConfig = new JS.Object() {
203 public Object get(String name, JS start) {
204 if (name.equals("bindings")) return proxyConfigBindings;
209 private static final JS.Function isPlainHostName = new JS.Function() {
210 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
211 return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
215 private static final JS.Function dnsDomainIs = new JS.Function() {
216 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
217 return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
221 private static final JS.Function localHostOrDomainIs = new JS.Function() {
222 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
223 return (args[0].toString().equals(args[1].toString()) ||
224 (args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
225 Boolean.TRUE : Boolean.FALSE;
229 private static final JS.Function isResolvable = new JS.Function() {
230 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
232 return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
233 } catch (UnknownHostException e) {
234 return Boolean.FALSE;
239 private static final JS.Function isInNet = new JS.Function() {
240 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
241 if (args.length != 3) return Boolean.FALSE;
243 byte[] host = InetAddress.getByName(args[0].toString()).getAddress();
244 byte[] net = InetAddress.getByName(args[1].toString()).getAddress();
245 byte[] mask = InetAddress.getByName(args[2].toString()).getAddress();
246 return ((host[0] & mask[0]) == net[0] &&
247 (host[1] & mask[1]) == net[1] &&
248 (host[2] & mask[2]) == net[2] &&
249 (host[3] & mask[3]) == net[3]) ?
250 Boolean.TRUE : Boolean.FALSE;
251 } catch (Exception e) {
252 throw new JS.Exn("exception in isInNet(): " + e);
257 private static final JS.Function dnsResolve = new JS.Function() {
258 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
260 return InetAddress.getByName(args[0].toString()).getHostAddress();
261 } catch (UnknownHostException e) {
267 private static final JS.Function myIpAddress = new JS.Function() {
268 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
270 return InetAddress.getLocalHost().getHostAddress();
271 } catch (UnknownHostException e) {
272 if (Log.on) Log.log(this, "strange... host does not know its own address");
278 private static final JS.Function dnsDomainLevels = new JS.Function() {
279 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
280 String s = args[0].toString();
282 while((i = s.indexOf('.', i)) != -1) i++;
283 return new Integer(i);
287 private static boolean match(String[] arr, String s, int index) {
288 if (index >= arr.length) return true;
289 for(int i=0; i<s.length(); i++) {
290 String s2 = s.substring(i);
291 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
296 private static final JS.Function shExpMatch = new JS.Function() {
297 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
298 StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
299 String[] arr = new String[st.countTokens()];
300 String s = args[0].toString();
301 for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
302 return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
306 public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
308 private static final JS.Function weekdayRange = new JS.Function() {
309 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
310 TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
311 Calendar c = new GregorianCalendar();
313 c.setTime(new Date());
314 Date d = c.getTime();
315 int day = d.getDay();
317 String d1s = args[0].toString().toUpperCase();
319 for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
321 if (args.length == 1)
322 return d1 == day ? Boolean.TRUE : Boolean.FALSE;
324 String d2s = args[1].toString().toUpperCase();
325 for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
328 ((d1 <= d2 && day >= d1 && day <= d2) ||
329 (d1 > d2 && (day >= d1 || day <= d2))) ?
330 Boolean.TRUE : Boolean.FALSE;
334 private static final JS.Function dateRange = new JS.Function() {
335 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
336 throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
340 private static final JS.Function timeRange = new JS.Function() {
341 public Object call(Context cx, JS thisObj, JS ctorObj, Object[] args) throws JS.Exn {
342 throw new JS.Exn("XWT does not support timeRange() in PAC scripts");