KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sslexplorer > agent > client > ProxyUtil


1 /*
2  * SSL-Explorer
3  *
4  * Copyright (C) 2003-2006 3SP LTD. All Rights Reserved
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2 of
9  * the License, or (at your option) any later version.
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public
16  * License along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */

19             
20 package com.sslexplorer.agent.client;
21
22 import java.io.BufferedReader JavaDoc;
23 import java.io.File JavaDoc;
24 import java.io.FileInputStream JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.io.InputStreamReader JavaDoc;
27 import java.text.MessageFormat JavaDoc;
28 import java.util.Enumeration JavaDoc;
29 import java.util.Hashtable JavaDoc;
30 import java.util.Properties JavaDoc;
31 import java.util.StringTokenizer JavaDoc;
32 import java.util.Vector JavaDoc;
33
34 import ca.beq.util.win32.registry.RegistryKey;
35 import ca.beq.util.win32.registry.RootKey;
36
37 import com.sslexplorer.agent.client.util.Utils;
38
39 /**
40  * Utilities to detect proxy server settings from the browser.
41  *
42  * @author Lee David Painter <a HREF="mailto: lee@3sp.com">&lt;lee@3sp.com&gt;</a>
43  */

44 public class ProxyUtil {
45
46     // #ifdef DEBUG
47
static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(ProxyUtil.class);
48     // #endif
49

50     /**
51      * Attempt to proxy settings from Firefox.
52      *
53      * @return firefox proxy settings
54      * @throws IOException if firefox settings could not be obtained for some
55      * reason
56      */

57     public static BrowserProxySettings lookupFirefoxProxySettings() throws IOException JavaDoc {
58
59         try {
60
61             Vector JavaDoc proxies = new Vector JavaDoc();
62             Vector JavaDoc bypassAddr = new Vector JavaDoc();
63
64             File JavaDoc home = new File JavaDoc(Utils.getHomeDirectory());
65             File JavaDoc firefoxAppData;
66
67             if (System.getProperty("os.name") != null && System.getProperty("os.name").startsWith("Windows")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
68
firefoxAppData = new File JavaDoc(home, "Application Data\\Mozilla\\Firefox\\profiles.ini"); //$NON-NLS-1$
69
} else {
70                 firefoxAppData = new File JavaDoc(home, ".mozilla/firefox/profiles.ini"); //$NON-NLS-1$
71
}
72
73             // Look for Path elements in the profiles.ini
74
BufferedReader JavaDoc reader = null;
75             Hashtable JavaDoc profiles = new Hashtable JavaDoc();
76             String JavaDoc line;
77             try {
78                 reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new FileInputStream JavaDoc(firefoxAppData)));
79                 String JavaDoc currentProfileName = ""; //$NON-NLS-1$
80

81                 while ((line = reader.readLine()) != null) {
82                     line = line.trim();
83                     if (line.startsWith("[") && line.endsWith("]")) { //$NON-NLS-1$ //$NON-NLS-2$
84
currentProfileName = line.substring(1, line.length() - 1);
85                         continue;
86                     }
87
88                     if (line.startsWith("Path=")) { //$NON-NLS-1$
89
profiles.put(currentProfileName, new File JavaDoc(firefoxAppData.getParent(), line.substring(5)));
90                     }
91                 }
92             } finally {
93                 if (reader != null) {
94                     reader.close();
95                 }
96             }
97
98             // Iterate through all the profiles and load the proxy infos from
99
// the prefs.js file
100

101             File JavaDoc prefsJS;
102             String JavaDoc profileName;
103             for (Enumeration JavaDoc e = profiles.keys(); e.hasMoreElements();) {
104                 profileName = (String JavaDoc) e.nextElement();
105                 prefsJS = new File JavaDoc((File JavaDoc) profiles.get(profileName), "prefs.js"); //$NON-NLS-1$
106
Properties JavaDoc props = new Properties JavaDoc();
107                 reader = null;
108                 try {
109                     reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(new FileInputStream JavaDoc(prefsJS)));
110                     while ((line = reader.readLine()) != null) {
111                         line = line.trim();
112                         if (line.startsWith("user_pref(\"")) { //$NON-NLS-1$
113
int idx = line.indexOf("\"", 11); //$NON-NLS-1$
114
if (idx == -1)
115                                 continue;
116                             String JavaDoc pref = line.substring(11, idx);
117
118                             // Save this position
119
int pos = idx + 1;
120
121                             // Look for another quote
122
idx = line.indexOf("\"", idx + 1); //$NON-NLS-1$
123

124                             String JavaDoc value;
125                             if (idx == -1) {
126                                 // No more quotes
127
idx = line.indexOf(" ", pos); //$NON-NLS-1$
128

129                                 if (idx == -1)
130                                     continue;
131
132                                 int idx2 = line.indexOf(")", pos); //$NON-NLS-1$
133

134                                 if (idx2 == -1)
135                                     continue;
136
137                                 value = line.substring(idx + 1, idx2);
138
139                             } else {
140
141                                 // String value
142
int idx2 = line.indexOf("\"", idx + 1); //$NON-NLS-1$
143

144                                 if (idx2 == -1)
145                                     continue;
146
147                                 value = line.substring(idx + 1, idx2);
148                             }
149
150                             props.put(pref, value);
151
152                         }
153                     }
154                 } finally {
155                     if (reader != null) {
156                         reader.close();
157                     }
158                 }
159                 ProxyInfo p;
160                 /**
161                  * Extract some proxies from the properites, if the proxy is
162                  * enabled
163                  */

164                 if ("1".equals(props.get("network.proxy.type"))) { //$NON-NLS-1$ //$NON-NLS-2$
165
if (props.containsKey("network.proxy.ftp")) { //$NON-NLS-1$
166
p = createProxyInfo("ftp=" + props.get("network.proxy.ftp") + ":" + props.get("network.proxy.ftp_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
167
"Firefox Profile [" + profileName + "]" ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
168
proxies.addElement(p);
169                     }
170
171                     if (props.containsKey("network.proxy.http")) { //$NON-NLS-1$
172
p = createProxyInfo("http=" + props.get("network.proxy.http") + ":" + props.get("network.proxy.http_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
173
"Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
174
proxies.addElement(p);
175                     }
176
177                     if (props.containsKey("network.proxy.ssl")) { //$NON-NLS-1$
178
p = createProxyInfo("ssl=" + props.get("network.proxy.ssl") + ":" + props.get("network.proxy.ssl_port"), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
179
"Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$
180
proxies.addElement(p);
181                     }
182
183                     if (props.containsKey("network.proxy.socks")) { //$NON-NLS-1$
184
p = createProxyInfo("socks=" + props.get("network.proxy.socks") + ":" //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
185
+ props.get("network.proxy.socks_port"), "Firefox Profile [" + profileName + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
186
proxies.addElement(p);
187                     }
188
189                     if (props.containsKey("network.proxy.no_proxies_on")) { //$NON-NLS-1$
190

191                         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(props.getProperty("network.proxy.no_proxies_on"), ","); //$NON-NLS-1$ //$NON-NLS-2$
192

193                         while (tokens.hasMoreTokens()) {
194                             bypassAddr.addElement(((String JavaDoc) tokens.nextToken()).trim());
195                         }
196
197                     }
198                 }
199             }
200
201             BrowserProxySettings bps = new BrowserProxySettings();
202             bps.setBrowser("Mozilla Firefox"); //$NON-NLS-1$
203
bps.setProxies(new ProxyInfo[proxies.size()]);
204             proxies.copyInto(bps.getProxies());
205             bps.setBypassAddr(new String JavaDoc[bypassAddr.size()]);
206             bypassAddr.copyInto(bps.getBypassAddr());
207             return bps;
208
209         } catch (Throwable JavaDoc t) {
210             throw new IOException JavaDoc("Failed to get proxy information from Firefox profiles: " + t.getMessage()); //$NON-NLS-1$
211
}
212     }
213
214     /**
215      * Attempt to proxy settings from Internet Explorer.
216      *
217      * @return internet explorer proxy settings
218      * @throws IOException if IE settings could not be obtained for some reason
219      */

220     public static BrowserProxySettings lookupIEProxySettings() throws IOException JavaDoc {
221
222         try {
223             Vector JavaDoc addresses = new Vector JavaDoc();
224             Vector JavaDoc proxies = new Vector JavaDoc();
225             String JavaDoc proxyServerValue = null;
226             String JavaDoc proxyOveride = null;
227
228             /* Only use jRegistry if on Windows, running 1.3 or up Java
229              * and NOT Windows Vista with JDK6.0 (because of jvm crash)
230              */

231             
232             if (Utils.isSupportedJRE("+1.3") && Utils.isSupportedPlatform("Windows") &&
233                     !(Utils.isSupportedOSVersion("+6.0") && Utils.isSupportedJRE("+1.6"))) {
234                     
235                 /*
236                  * We can use jRegistryKey API to lookup IE settings in the
237                  * registry
238                  */

239                 RegistryKey key = new RegistryKey(RootKey.HKEY_CURRENT_USER,
240                                 "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"); //$NON-NLS-1$
241

242                 if (key != null && key.hasValue("ProxyEnable")) { //$NON-NLS-1$
243
/*
244                      * We have ProxyEnable so check to see if we are using a
245                      * proxy
246                      */

247                     if (key.getValue("ProxyEnable").getStringValue().equals("1")) { //$NON-NLS-1$ //$NON-NLS-2$
248

249                         if (key.hasValue("ProxyServer")) { //$NON-NLS-1$
250
/**
251                              * We have some proxy settings. The values will be
252                              * in the format "server.proxy.net:8888" or
253                              */

254                             proxyServerValue = key.getValue("ProxyServer").getStringValue(); //$NON-NLS-1$
255

256                             if (key.hasValue("ProxyOverride")) { //$NON-NLS-1$
257
/**
258                                  * There is a list of local address which do not
259                                  * require a proxy. The values will be in the
260                                  * format "localhost;3sp.co.uk;shabby.net"
261                                  */

262                                 proxyOveride = key.getValue("ProxyOverride").getStringValue(); //$NON-NLS-1$
263
}
264                         }
265                     } else {
266
267                     }
268                 }
269             } else {
270                 if (System.getProperty("java.vendor").startsWith("Microsoft")) { //$NON-NLS-1$ //$NON-NLS-2$
271
try {
272                         Class JavaDoc clazz = Class.forName("com.ms.lang.RegKey"); //$NON-NLS-1$
273
int userRoot = clazz.getField("USER_ROOT").getInt(null); //$NON-NLS-1$
274
int keyOpenAll = clazz.getField("KEYOPEN_ALL").getInt(null); //$NON-NLS-1$
275
// #ifdef DEBUG
276
log.info(Messages.getString("ProxyUtil.lookingForRoot")); //$NON-NLS-1$
277
// #endif
278
Object JavaDoc rootKey = clazz.getMethod("getRootKey", new Class JavaDoc[] { int.class }).invoke(null, //$NON-NLS-1$
279
new Object JavaDoc[] { new Integer JavaDoc(userRoot) });
280                         // #ifdef DEBUG
281
log.info(Messages.getString("ProxyUtil.getIERegistryKey")); //$NON-NLS-1$
282
// #endif
283
Object JavaDoc key = clazz.getConstructor(new Class JavaDoc[] { clazz, String JavaDoc.class, int.class }).newInstance(
284                             new Object JavaDoc[] { rootKey, "Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", //$NON-NLS-1$
285
new Integer JavaDoc(keyOpenAll) });
286                         // #ifdef DEBUG
287
log.info(Messages.getString("ProxyUtil.checkingIfProxyEnabled")); //$NON-NLS-1$
288
// #endif
289
if (((Integer JavaDoc) (clazz.getMethod("getIntValue", new Class JavaDoc[] { String JavaDoc.class }).invoke(key, //$NON-NLS-1$
290
new Object JavaDoc[] { "ProxyEnable" }))).intValue() == 1) { //$NON-NLS-1$
291
// #ifdef DEBUG
292
log.info(Messages.getString("ProxyUtil.gettingProxyServerList")); //$NON-NLS-1$
293
// #endif
294
proxyServerValue = (String JavaDoc) (clazz.getMethod("getStringValue", //$NON-NLS-1$
295
new Class JavaDoc[] { String JavaDoc.class, String JavaDoc.class }).invoke(key, new Object JavaDoc[] { "ProxyServer", "" })); //$NON-NLS-1$ //$NON-NLS-2$
296
// #ifdef DEBUG
297
log.info(Messages.getString("ProxyUtil.gettingProxyOverides")); //$NON-NLS-1$
298
// #endif
299
proxyOveride = (String JavaDoc) (clazz.getMethod("getStringValue", new Class JavaDoc[] { String JavaDoc.class, String JavaDoc.class }) //$NON-NLS-1$
300
.invoke(key, new Object JavaDoc[] { "ProxyOverride", "" })); //$NON-NLS-1$ //$NON-NLS-2$
301
}
302                     } catch (Throwable JavaDoc t) {
303                         t.printStackTrace();
304                     }
305
306                 } else {
307                     // #ifdef DEBUG
308
log.info(MessageFormat.format(Messages.getString("ProxyUtil.unsupportedJavaRuntime"), new Object JavaDoc[] { System.getProperty("java.version"), System.getProperty("java.vendor") } ) ); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
309
// #endif
310
}
311
312             }
313
314             ProxyInfo p;
315
316             if (proxyServerValue != null && proxyServerValue.indexOf(';') > -1) {
317                 /**
318                  * Format is multiple
319                  * "ftp=ftp.com:4444;gopher=gopher.com:3333;http=198.162.1.119:8888;https=https.com:2222;socks=socks.com:1111"
320                  */

321                 StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(proxyServerValue, ";"); //$NON-NLS-1$
322

323                 while (tokens.hasMoreTokens()) {
324                     p = createProxyInfo(tokens.nextToken(), "IE Proxy Settings"); //$NON-NLS-1$
325
proxies.addElement(p);
326                 }
327
328             } else if (proxyServerValue != null) {
329                 /**
330                  * Format is single "http=server.proxy.net:8888" or
331                  * "server.proxy.net:8888"
332                  */

333                 p = createProxyInfo(proxyServerValue, "IE Proxy Settings"); //$NON-NLS-1$
334
proxies.addElement(p);
335             }
336
337             BrowserProxySettings bps = new BrowserProxySettings();
338             bps.setBrowser("Internet Explorer"); //$NON-NLS-1$
339
bps.setProxies(new ProxyInfo[proxies.size()]);
340             proxies.copyInto(bps.getProxies());
341             if (proxyOveride != null) {
342
343                 StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(proxyOveride, ";"); //$NON-NLS-1$
344

345                 while (tokens.hasMoreTokens()) {
346                     addresses.addElement(tokens.nextToken());
347                 }
348             }
349
350             bps.setBypassAddr(new String JavaDoc[addresses.size()]);
351             addresses.copyInto(bps.getBypassAddr());
352             return bps;
353
354         } catch (Throwable JavaDoc t) {
355             t.printStackTrace();
356             throw new IOException JavaDoc(MessageFormat.format(
357                 Messages.getString("ProxyUtil.failedToLookupIEProxies"), new Object JavaDoc[] { t.getMessage() } ) ); //$NON-NLS-1$
358
}
359     }
360
361     private static ProxyInfo createProxyInfo(String JavaDoc proxyInfo, String JavaDoc sourceIdent) {
362         int idx = proxyInfo.indexOf('=');
363         int idx2 = proxyInfo.indexOf(':');
364         ProxyInfo proxy = new ProxyInfo(idx > -1 ? proxyInfo.substring(0, idx) : "all", "", "", proxyInfo.substring( //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
365
(idx > -1 ? idx + 1 : 0), idx2), Integer.parseInt(proxyInfo.substring(idx2 + 1)), sourceIdent);
366         return proxy;
367     }
368
369     /**
370      * Test entry point.
371      *
372      * @param args arguments
373      * @throws Exception
374      */

375     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
376         BrowserProxySettings settings = lookupFirefoxProxySettings();
377         // #ifdef DEBUG
378
log.info("Browser = " + settings.getBrowser()); //$NON-NLS-1$
379
// #endif
380
ProxyInfo[] info = settings.getProxies();
381         for (int i = 0; i < info.length; i++) {
382             // #ifdef DEBUG
383
log.info(" " + info[i].toUri() + " [" + info[i].getSourceIdent() + "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
384
// #endif
385
}
386     }
387
388 }
389
Popular Tags