81318a09b598e1161bc9141d763c86f8caa5deaf
[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.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 JS proxyAutoConfigRootScope = new ProxyAutoConfigRootScope();
91     public static JS.Function getProxyAutoConfigFunction(String url) {
92         throw new Error("not implemented");
93         // FIXME
94         /*
95         try { 
96             Context cx = Context.enter();
97             cx.setOptimizationLevel(-1);
98             BufferedReader br = new BufferedReader(new InputStreamReader(new HTTP(url, true).GET()));
99             String s = null;
100             String script = "";
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);
104             
105             // MS CARP hack
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);
112                 }
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) + "; ";
117                 script += "\";\n}";
118                 if (Log.on) Log.log(Proxy.class, "DeCARPed PAC script:");
119                 if (Log.on) Log.log(Proxy.class, script);
120             }
121             
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) {
126             if (Log.on) {
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) {
131             try {
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);
136             }
137         }
138                 else Log.log(Platform.class, e);
139             }
140             return null;
141         }
142         */
143     }
144
145
146     // Authorization ///////////////////////////////////////////////////////////////////////////////////
147
148     public static class Authorization {
149
150         static public String authorization = null;
151         static public String authorization2 = null;
152         static public Semaphore waitingForUser = new Semaphore();
153
154         public static synchronized void getPassword(final String realm, final String style, final String proxyIP, String oldAuth) {
155
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.
159
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);
167                     }
168                 });
169
170             waitingForUser.block();
171             if (Log.on) Log.log(Authorization.class, "got proxy authorization info; re-attempting connection");
172             
173         }
174     }
175
176
177     // ProxyAutoConfigRootScope ////////////////////////////////////////////////////////////////////
178     /*    
179     public static class ProxyAutoConfigRootScope extends JSObject {
180         
181         public String getClassName() { return "ProxyAutoConfigRootScope"; }
182         ProxyAutoConfigRootScope() { Context.enter().initStandardObjects(this); }
183         
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);
199         }
200         
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;
205                     return null;
206                 }
207             };
208         
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;
212                 }
213             };
214         
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;
218                 }
219             };
220         
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;
226                 }
227             };
228         
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 {
231                     try {
232                         return (InetAddress.getByName(args[0].toString()) != null) ? Boolean.TRUE : Boolean.FALSE;
233                     } catch (UnknownHostException e) {
234                         return Boolean.FALSE;
235                     }
236                 }
237             };
238         
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;
242                     try {
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);
253                     }
254                 }
255             };
256         
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 {
259                     try {
260                         return InetAddress.getByName(args[0].toString()).getHostAddress();
261                     } catch (UnknownHostException e) {
262                         return null;
263                     }
264                 }
265             };
266         
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 {
269                     try {
270                         return InetAddress.getLocalHost().getHostAddress();
271                     } catch (UnknownHostException e) {
272                         if (Log.on) Log.log(this, "strange... host does not know its own address");
273                         return null;
274                     }
275                 }
276             };
277         
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();
281                     int i = 0;
282                     while((i = s.indexOf('.', i)) != -1) i++;
283                     return new Integer(i);
284                 }
285             };
286         
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;
292             }
293             return false;
294         }
295         
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;
303                 }
304             };
305         
306         public static String[] days = { "SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT" };
307         
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();
312                     c.setTimeZone(tz);
313                     c.setTime(new Date());
314                     Date d = c.getTime();
315                     int day = d.getDay();
316                     
317                     String d1s = args[0].toString().toUpperCase();
318                     int d1 = 0, d2 = 0;
319                     for(int i=0; i<days.length; i++) if (days[i].equals(d1s)) d1 = i;
320                     
321                     if (args.length == 1)
322                         return d1 == day ? Boolean.TRUE : Boolean.FALSE;
323                     
324                     String d2s = args[1].toString().toUpperCase();
325                     for(int i=0; i<days.length; i++) if (days[i].equals(d2s)) d2 = i;
326                     
327                     return
328                         ((d1 <= d2 && day >= d1 && day <= d2) ||
329                          (d1 > d2 && (day >= d1 || day <= d2))) ?
330                         Boolean.TRUE : Boolean.FALSE;
331                 }
332             };
333         
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");
337                 }
338             };
339         
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");
343                 }
344             };
345         
346     }
347     */    
348 }