2003/06/16 07:58:57
[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.js.*;
8 import org.xwt.util.*;
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 JS.Callable 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 JS.Scope proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
91     public static JS.Callable getProxyAutoConfigFunction(String url) {
92         try { 
93             BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
94             String s = null;
95             String script = "";
96             while((s = br.readLine()) != null) script += s + "\n";
97             if (Log.on) Log.log(Proxy.class, "successfully retrieved WPAD PAC:");
98             if (Log.on) Log.log(Proxy.class, script);
99             
100             // MS CARP hack
101             Vector carpHosts = new Vector();
102             for(int i=0; i<script.length(); i++)
103                 if (script.regionMatches(i, "new Node(", 0, 9)) {
104                     String host = script.substring(i + 10, script.indexOf('\"', i + 11));
105                     if (Log.on) Log.log(Proxy.class, "Detected MS Proxy Server CARP Script, Host=" + host);
106                     carpHosts.addElement(host);
107                 }
108             if (carpHosts.size() > 0) {
109                 script = "function FindProxyForURL(url, host) {\nreturn \"";
110                 for(int i=0; i<carpHosts.size(); i++)
111                     script += "PROXY " + carpHosts.elementAt(i) + "; ";
112                 script += "\";\n}";
113                 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
114                 if (Log.on) Log.log(Proxy.class, script);
115             }
116
117             JS.CompiledFunction scr = JS.parse("PAC script at " + url, 0, new StringReader(script));
118             scr.call(new JS.Array(), proxyAutoConfigRootScope);
119             return (JS.Callable)proxyAutoConfigRootScope.get("FindProxyForURL");
120         } catch (Exception e) {
121             if (Log.on) {
122                 Log.log(Platform.class, "WPAD detection failed due to:");
123                 if (e instanceof JS.Exn) {
124                     try {
125                         org.xwt.js.JS.Array arr = new org.xwt.js.JS.Array();
126                         arr.addElement(((JS.Exn)e).getObject());
127                         // FIXME
128                         //XWT.recursivePrintObject.call();
129                     } catch (Exception e2) {
130                         Log.log(Platform.class, e);
131                     }
132                 }
133                 else Log.log(Platform.class, e);
134             }
135             return null;
136         }
137     }
138
139
140     // Authorization ///////////////////////////////////////////////////////////////////////////////////
141
142     public static class Authorization {
143
144         static public String authorization = null;
145         static public String authorization2 = null;
146         static public Semaphore waitingForUser = new Semaphore();
147
148         public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
149
150             // this handles cases where multiple threads hit the proxy auth at the same time -- all but one will block on the
151             // synchronized keyword. If 'authorization' changed while the thread was blocked, it means that the user entered
152             // a password, so we should reattempt authorization.
153
154             if (authorization != oldAuth) return;
155             if (Log.on) Log.log(Authorization.class, "displaying proxy authorization dialog");
156             MessageQueue.add(new Message() {
157                     public void perform() {
158                         Box b = new Box("org.xwt.builtin.proxy_authorization", null);
159                         b.put("realm", realm);
160                         b.put("proxyIP", proxyIP);
161                     }
162                 });
163
164             waitingForUser.block();
165             if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
166             
167         }
168     }
169
170
171     // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
172
173     public static class ProxyAutoConfigRootScope extends JS.Scope {
174
175         public ProxyAutoConfigRootScope() { super(null); }
176         
177         // FIXME: needs "standard objects"
178
179         public Object get(Object name) {
180             if (name.equals("isPlainHostName")) return isPlainHostName;
181             else if (name.equals("dnsDomainIs")) return dnsDomainIs;
182             else if (name.equals("localHostOrDomainIs")) return localHostOrDomainIs;
183             else if (name.equals("isResolvable")) return isResolvable;
184             else if (name.equals("isInNet")) return isInNet;
185             else if (name.equals("dnsResolve")) return dnsResolve;
186             else if (name.equals("myIpAddress")) return myIpAddress;
187             else if (name.equals("dnsDomainLevels")) return dnsDomainLevels;
188             else if (name.equals("shExpMatch")) return shExpMatch;
189             else if (name.equals("weekdayRange")) return weekdayRange;
190             else if (name.equals("dateRange")) return dateRange;
191             else if (name.equals("timeRange")) return timeRange;
192             else if (name.equals("ProxyConfig")) return ProxyConfig;
193             else return super.get(name);
194         }
195         
196         private static final JS.Obj proxyConfigBindings = new JS.Obj();
197         private static final JS.Obj ProxyConfig = new JS.Obj() {
198                 public Object get(Object name) {
199                     if (name.equals("bindings")) return proxyConfigBindings;
200                     return null;
201                 }
202             };
203         
204         private static final JS.Callable isPlainHostName = new JS.Callable() {
205                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
206                     return (args.elementAt(0).toString().indexOf('.') == -1) ? Boolean.TRUE : Boolean.FALSE;
207                 }
208             };
209         
210         private static final JS.Callable dnsDomainIs = new JS.Callable() {
211                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
212                     return (args.elementAt(0).toString().endsWith(args.elementAt(1).toString())) ? Boolean.TRUE : Boolean.FALSE;
213                 }
214             };
215         
216         private static final JS.Callable localHostOrDomainIs = new JS.Callable() {
217                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
218                     return (args.elementAt(0).toString().equals(args.elementAt(1).toString()) || 
219                             (args.elementAt(0).toString().indexOf('.') == -1 && args.elementAt(1).toString().startsWith(args.elementAt(0).toString()))) ?
220                         Boolean.TRUE : Boolean.FALSE;
221                 }
222             };
223         
224         private static final JS.Callable isResolvable = new JS.Callable() {
225                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
226                     try {
227                         return (InetAddress.getByName(args.elementAt(0).toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
228                     } catch (UnknownHostException e) {
229                         return Boolean.FALSE;
230                     }
231                 }
232             };
233         
234         private static final JS.Callable isInNet = new JS.Callable() {
235                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
236                     if (args.length() != 3) return Boolean.FALSE;
237                     try {
238                         byte[] host = InetAddress.getByName(args.elementAt(0).toString()).getAddress();
239                         byte[] net = InetAddress.getByName(args.elementAt(1).toString()).getAddress();
240                         byte[] mask = InetAddress.getByName(args.elementAt(2).toString()).getAddress();
241                         return ((host[0] & mask[0]) == net[0] &&
242                                 (host[1] & mask[1]) == net[1] &&
243                                 (host[2] & mask[2]) == net[2] &&
244                                 (host[3] & mask[3]) == net[3]) ?
245                             Boolean.TRUE : Boolean.FALSE;
246                     } catch (Exception e) {
247                         throw new JS.Exn("exception in isInNet(): " + e);
248                     }
249                 }
250             };
251         
252         private static final JS.Callable dnsResolve = new JS.Callable() {
253                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
254                     try {
255                         return InetAddress.getByName(args.elementAt(0).toString()).getHostAddress();
256                     } catch (UnknownHostException e) {
257                         return null;
258                     }
259                 }
260             };
261         
262         private static final JS.Callable myIpAddress = new JS.Callable() {
263                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
264                     try {
265                         return InetAddress.getLocalHost().getHostAddress();
266                     } catch (UnknownHostException e) {
267                         if (Log.on) Log.log(this, "strange... host does not know its own address");
268                         return null;
269                     }
270                 }
271             };
272         
273         private static final JS.Callable dnsDomainLevels = new JS.Callable() {
274                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
275                     String s = args.elementAt(0).toString();
276                     int i = 0;
277                     while((i = s.indexOf('.', i)) != -1) i++;
278                     return new Integer(i);
279                 }
280             };
281         
282         private static boolean match(String[] arr, String s, int index) {
283             if (index >= arr.length) return true;
284             for(int i=0; i<s.length(); i++) {
285                 String s2 = s.substring(i);
286                 if (s2.startsWith(arr[index]) && match(arr, s2.substring(arr[index].length()), index + 1)) return true;
287             }
288             return false;
289         }
290         
291         private static final JS.Callable shExpMatch = new JS.Callable() {
292                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
293                     StringTokenizer st = new StringTokenizer(args.elementAt(1).toString(), "*", false);
294                     String[] arr = new String[st.countTokens()];
295                     String s = args.elementAt(0).toString();
296                     for (int i=0; st.hasMoreTokens(); i++) arr[i] = st.nextToken();
297                     return match(arr, s, 0) ? Boolean.TRUE : Boolean.FALSE;
298                 }
299             };
300         
301         public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
302         
303         private static final JS.Callable weekdayRange = new JS.Callable() {
304                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
305                     TimeZone tz = (args.length() < 3 || args.elementAt(2) == null || !args.elementAt(2).equals("GMT")) ? TimeZone.getTimeZone("UTC") : TimeZone.getDefault();
306                     Calendar c = new GregorianCalendar();
307                     c.setTimeZone(tz);
308                     c.setTime(new java.util.Date());
309                     java.util.Date d = c.getTime();
310                     int day = d.getDay();
311                     
312                     String d1s = args.elementAt(0).toString().toUpperCase();
313                     int d1 = 0, d2 = 0;
314                     for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
315                     
316                     if (args.length() == 1)
317                         return d1 == day ? Boolean.TRUE : Boolean.FALSE;
318                     
319                     String d2s = args.elementAt(1).toString().toUpperCase();
320                     for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
321                     
322                     return
323                         ((d1 <= d2 && day >= d1 && day <= d2) ||
324                          (d1 > d2 && (day >= d1 || day <= d2))) ?
325                         Boolean.TRUE : Boolean.FALSE;
326                 }
327             };
328         
329         private static final JS.Callable dateRange = new JS.Callable() {
330                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
331                     throw new JS.Exn("XWT does not support dateRange() in PAC scripts");
332                 }
333             };
334         
335         private static final JS.Callable timeRange = new JS.Callable() {
336                 public Object call(org.xwt.js.JS.Array args) throws JS.Exn {
337                     throw new JS.Exn("XWT does not support timeRange() in PAC scripts");
338                 }
339             };
340         
341     }
342
343 }