2002/10/04 02:09:25
[org.ibex.core.git] / src / org / xwt / Proxy.java
1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.net.*;
5 import java.io.*;
6 import java.util.*;
7 import org.xwt.util.*;
8 import org.mozilla.javascript.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11 /** encapsulates most of the proxy logic; some is shared in HTTP.java */
12 public class Proxy {
13     
14     public Proxy() { }
15     
16     /** the HTTP Proxy host to use */
17     public String httpProxyHost = null;
18     
19     /** the HTTP Proxy port to use */
20     public int httpProxyPort = -1;
21     
22     /** if a seperate proxy should be used for HTTPS, this is the hostname; otherwise, httpProxyHost is used */
23     public String httpsProxyHost = null;
24     
25     /** if a seperate proxy should be used for HTTPS, this is the port */
26     public int httpsProxyPort = -1;
27     
28     /** the SOCKS Proxy Host to use */
29     public String socksProxyHost = null;
30     
31     /** the SOCKS Proxy Port to use */
32     public int socksProxyPort = -1;
33     
34     /** hosts to be excluded from proxy use; wildcards permitted */
35     public String[] excluded = null;
36     
37     /** the PAC script */
38     public Function proxyAutoConfigFunction = null;
39     
40     public static Proxy detectProxyViaManual() {
41         Proxy ret = new Proxy();
42         
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(':'));
50             } else {
51                 ret.httpProxyPort = 80;
52             }
53         }
54         
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(':'));
62             } else {
63                 ret.httpsProxyPort = 80;
64             }
65         }
66         
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(':'));
74             } else {
75                 ret.socksProxyPort = 80;
76             }
77         }
78         
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();
84         }
85         
86         if (ret.httpProxyHost == null && ret.socksProxyHost == null) return null;
87         return ret;
88     }
89     
90     public static Scriptable proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
91     
92     public static Function getProxyAutoConfigFunction(String url) {
93         try { 
94             Context cx = Context.enter();
95             cx.setOptimizationLevel(-1);
96             BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
97             String s = null;
98             String script = "";
99             while((s = br.readLine()) != null) script += s + "\n";
100             if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
101             if (Log.on) Log.log(Proxy.class, script);
102             
103             // MS CARP hack
104             Vector carpHosts = new Vector();
105             for(int i=0; i<script.length(); i++)
106                 if (script.regionMatches(i, "new Node(", 0, 9)) {
107                     String host = script.substring(i + 10, script.indexOf('\"', i + 11));
108                     if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
109                     carpHosts.addElement(host);
110                 }
111             if (carpHosts.size() > 0) {
112                 script = "function FindProxyForURL(url, host) {\nreturn \"";
113                 for(int i=0; i<carpHosts.size(); i++)
114                     script += "PROXY " + carpHosts.elementAt(i) + "; ";
115                 script += "\";\n}";
116                 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
117                 if (Log.on) Log.log(Proxy.class, script);
118             }
119             
120             Script scr = cx.compileReader(proxyAutoConfigRootScope, new StringReader(script), "PAC script at " + url, 0, null);
121             scr.exec(cx, proxyAutoConfigRootScope);
122             return (Function)proxyAutoConfigRootScope.get("FindProxyForURL", null);
123         } catch (Exception e) {
124             if (Log.on) {
125                 Log.log(Platform.class, "WPAD detection failed due to:");
126                 if (e instanceof EcmaError) Log.log(HTTP.class, ((EcmaError)e).getMessage() + " at " +
127                                                     ((EcmaError)e).getSourceName() + ":" + ((EcmaError)e).getLineNumber());
128                 else if (e instanceof JavaScriptException) {
129             try {
130             XWT.recursivePrintObject.call(Context.enter(), null, null, new Object[] {
131                 ((JavaScriptException)e).getValue() });
132             } catch (Exception e2) {
133             Log.log(Platform.class, e);
134             }
135         }
136                 else Log.log(Platform.class, e);
137             }
138             return null;
139         }
140     }
141
142
143     // Authorization ///////////////////////////////////////////////////////////////////////////////////
144
145     public static class Authorization {
146
147         static public String authorization = null;
148         static public String authorization2 = null;
149         static public Semaphore waitingForUser = new Semaphore();
150
151         public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
152
153             // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
154             // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
155             // a password, so we should reattempt authorization.
156
157             if (authorization != oldAuth) return;
158             if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
159             MessageQueue.add(new Message() {
160                     public void perform() {
161                         Box b = new Box("org.xwt.builtin.proxy_authorization", null);
162                         b.put("realm", realm);
163                         b.put("proxyIP", proxyIP);
164                     }
165                 });
166
167             waitingForUser.block();
168             if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
169             
170         }
171     }
172
173
174     // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
175     
176     public static class ProxyAutoConfigRootScope extends ScriptableObject {
177         
178         public String getClassName() { return "ProxyAutoConfigRootScope"; }
179         ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
180         
181         public Object get(String name, Scriptable start) {
182             if (name.equals("isPlainHostName")) return isPlainHostName;
183             else if (name.equals("dnsDomainIs")) return dnsDomainIs;
184             else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
185             else if (name.equals("isResolvable")) return isResolvable;
186             else if (name.equals("isInNet")) return isInNet;
187             else if (name.equals("dnsResolve")) return dnsResolve;
188             else if (name.equals("myIpAddress")) return myIpAddress;
189             else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
190             else if (name.equals("shExpMatch")) return shExpMatch;
191             else if (name.equals("weekdayRange")) return weekdayRange;
192             else if (name.equals("dateRange")) return dateRange;
193             else if (name.equals("timeRange")) return timeRange;
194             else if (name.equals("ProxyConfig")) return ProxyConfig;
195             else return super.get(name, start);
196         }
197         
198         private static final JSObject proxyConfigBindings = new JSObject();
199         private static final JSObject ProxyConfig = new JSObject() {
200                 public Object get(String name, Scriptable start) {
201                     if (name.equals("bindings")) return proxyConfigBindings;
202                     return null;
203                 }
204             };
205         
206         private static abstract class JSFunction extends JSObject implements Function {
207             JSFunction() { setSeal(true); }
208             public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
209         }
210         
211         private static final JSFunction isPlainHostName = new JSFunction() {
212                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
213                     return (args[0].toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
214                 }
215             };
216         
217         private static final JSFunction dnsDomainIs = new JSFunction() {
218                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
219                     return (args[0].toString().endsWith(args[1].toString())) ? Boolean.TRUE : Boolean.FALSE;
220                 }
221             };
222         
223         private static final JSFunction localHostOrDomainIs = new JSFunction() {
224                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
225                     return (args[0].toString().equals(args[1].toString()) || 
226                             (args[0].toString().indexOf('.') == -1 && args[1].toString().startsWith(args[0].toString()))) ?
227                         Boolean.TRUE : Boolean.FALSE;
228                 }
229             };
230         
231         private static final JSFunction isResolvable = new JSFunction() {
232                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
233                     try {
234                         return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
235                     } catch (UnknownHostException e) {
236                         return Boolean.FALSE;
237                     }
238                 }
239             };
240         
241         private static final JSFunction isInNet = new JSFunction() {
242                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
243                     if (args.length != 3) return Boolean.FALSE;
244                     try {
245                         byte[] host = InetAddress.getByName(args[0].toString()).getAddress();
246                         byte[] net = InetAddress.getByName(args[1].toString()).getAddress();
247                         byte[] mask = InetAddress.getByName(args[2].toString()).getAddress();
248                         return ((host[0] & mask[0]) == net[0] &&
249                                 (host[1] & mask[1]) == net[1] &&
250                                 (host[2] & mask[2]) == net[2] &&
251                                 (host[3] & mask[3]) == net[3]) ?
252                             Boolean.TRUE : Boolean.FALSE;
253                     } catch (Exception e) {
254                         throw new JavaScriptException("exception in isInNet(): " + e);
255                     }
256                 }
257             };
258         
259         private static final JSFunction dnsResolve = new JSFunction() {
260                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
261                     try {
262                         return InetAddress.getByName(args[0].toString()).getHostAddress();
263                     } catch (UnknownHostException e) {
264                         return null;
265                     }
266                 }
267             };
268         
269         private static final JSFunction myIpAddress = new JSFunction() {
270                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
271                     try {
272                         return InetAddress.getLocalHost().getHostAddress();
273                     } catch (UnknownHostException e) {
274                         if (Log.on) Log.log(this, "strange... host does not know its own address");
275                         return null;
276                     }
277                 }
278             };
279         
280         private static final JSFunction dnsDomainLevels = new JSFunction() {
281                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
282                     String s = args[0].toString();
283                     int i = 0;
284                     while((i = s.indexOf('.', i)) != -1) i++;
285                     return new Integer(i);
286                 }
287             };
288         
289         private static boolean match(String[] arr, String s, int index) {
290             if (index >= arr.length) return true;
291             for(int i=0; i<s.length(); i++) {
292                 String s2 = s.substring(i);
293                 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
294             }
295             return false;
296         }
297         
298         private static final JSFunction shExpMatch = new JSFunction() {
299                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
300                     StringTokenizer st = new StringTokenizer(args[1].toString(), "*", false);
301                     String[] arr = new String[st.countTokens()];
302                     String s = args[0].toString();
303                     for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
304                     return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
305                 }
306             };
307         
308         public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
309         
310         private static final JSFunction weekdayRange = new JSFunction() {
311                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
312                     TimeZone tz = (args.length < 3 || args[2] == null || !args[2].equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
313                     Calendar c = new GregorianCalendar();
314                     c.setTimeZone(tz);
315                     c.setTime(new Date());
316                     Date d = c.getTime();
317                     int day = d.getDay();
318                     
319                     String d1s = args[0].toString().toUpperCase();
320                     int d1 = 0, d2 = 0;
321                     for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
322                     
323                     if (args.length == 1)
324                         return d1 == day ? Boolean.TRUE : Boolean.FALSE;
325                     
326                     String d2s = args[1].toString().toUpperCase();
327                     for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
328                     
329                     return
330                         ((d1 <= d2 && day >= d1 && day <= d2) ||
331                          (d1 > d2 && (day >= d1 || day <= d2))) ?
332                         Boolean.TRUE : Boolean.FALSE;
333                 }
334             };
335         
336         private static final JSFunction dateRange = new JSFunction() {
337                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
338                     throw new JavaScriptException("XWT does not support dateRange() in PAC scripts");
339                 }
340             };
341         
342         private static final JSFunction timeRange = new JSFunction() {
343                 public Object call(Context cx, Scriptable thisObj, Scriptable ctorObj, Object[] args) throws JavaScriptException {
344                     throw new JavaScriptException("XWT does not support timeRange() in PAC scripts");
345                 }
346             };
347         
348     }
349     
350 }