summaryrefslogtreecommitdiffstats
path: root/src/main/java/com/btr/proxy/search/desktop/gnome/GnomeProxySearchStrategy.java
blob: 10d237a09f9fb3a4fa5028af9c2ad394e09bbe87 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
package com.btr.proxy.search.desktop.gnome;

import java.io.File;
import java.io.IOException;
import java.net.Proxy;
import java.net.ProxySelector;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import com.btr.proxy.search.ProxySearchStrategy;
import com.btr.proxy.selector.direct.NoProxySelector;
import com.btr.proxy.selector.misc.ProtocolDispatchSelector;
import com.btr.proxy.selector.whitelist.ProxyBypassListSelector;
import com.btr.proxy.util.EmptyXMLResolver;
import com.btr.proxy.util.Logger;
import com.btr.proxy.util.Logger.LogLevel;
import com.btr.proxy.util.ProxyException;
import com.btr.proxy.util.ProxyUtil;

/*****************************************************************************
 * Loads the Gnome proxy settings from the Gnome GConf settings.
 * <p>
 * The following settings are extracted from the configuration that is stored 
 * in <i>.gconf</i> folder found in the user's home directory: 
 * </p>
 * <ul>
 * <li><i>/system/http_proxy/use_http_proxy</i>          ->   bool     used only by gnome-vfs </li>
 * <li><i>/system/http_proxy/host</i>                    ->   string   "my-proxy.example.com" without "http://"</li>
 * <li><i>/system/http_proxy/port</i>                    ->   int</li>
 * <li><i>/system/http_proxy/use_authentication</i>      ->   bool</li>
 * <li><i>/system/http_proxy/authentication_user</i>     ->   string</li>
 * <li><i>/system/http_proxy/authentication_password</i> ->   string</li>
 * <li><i>/system/http_proxy/ignore_hosts</i>            ->   list-of-string</li>
 * <li><i>/system/proxy/mode</i>                         ->   string   THIS IS THE CANONICAL KEY; SEE BELOW</li>
 * <li><i>/system/proxy/secure_host</i>                  ->   string   "proxy-for-https.example.com"</li>
 * <li><i>/system/proxy/secure_port</i>                  ->   int</li>
 * <li><i>/system/proxy/ftp_host</i>                     ->   string   "proxy-for-ftp.example.com"</li>
 * <li><i>/system/proxy/ftp_port</i>                     ->   int</li>
 * <li><i>/system/proxy/socks_host</i>                   ->   string   "proxy-for-socks.example.com"</li>
 * <li><i>/system/proxy/socks_port</i>                   ->   int</li>
 * <li><i>/system/proxy/autoconfig_url</i>               ->   string   "http://proxy-autoconfig.example.com"</li>
 * </ul>
 * <i>/system/proxy/mode</i> can be either:<br/>
 * "none" -> No proxy is used<br/>
 * "manual" -> The user's configuration values are used (/system/http_proxy/{host,port,etc.})<br/>
 * "auto" -> The "/system/proxy/autoconfig_url" key is used  <br/>
 * <p>
 * GNOME Proxy_configuration settings are explained 
 * <a href="http://en.opensuse.org/GNOME/Proxy_configuration">here</a> in detail
 * </p>
 * @author Bernd Rosstauscher (proxyvole@rosstauscher.de) Copyright 2009
 ****************************************************************************/

public class GnomeProxySearchStrategy implements ProxySearchStrategy {
	
	/*************************************************************************
	 * ProxySelector
	 * @see java.net.ProxySelector#ProxySelector()
	 ************************************************************************/
	
	public GnomeProxySearchStrategy() {
		super();
	}
	
	/*************************************************************************
	 * Loads the proxy settings and initializes a proxy selector for the Gnome
	 * proxy settings.
	 * @return a configured ProxySelector, null if none is found.
	 * @throws ProxyException on file reading error. 
	 ************************************************************************/

	public ProxySelector getProxySelector() throws ProxyException {

		Logger.log(getClass(), LogLevel.TRACE, "Detecting Gnome proxy settings");

		Properties settings = readSettings();
		
		String type = settings.getProperty("/system/proxy/mode");
		ProxySelector result = null; 
		if (type == null) {
			String useProxy = settings.getProperty("/system/http_proxy/use_http_proxy");
			if (useProxy == null) {
				return null;
			}
			type = Boolean.parseBoolean(useProxy)?"manual":"none";
		} 
		
		if ("none".equals(type)) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome uses no proxy");
			result = NoProxySelector.getInstance();
		}
		if ("manual".equals(type)) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome uses manual proxy settings");
			result = setupFixedProxySelector(settings);
		}
		if ("auto".equals(type)) {
			String pacScriptUrl = settings.getProperty("/system/proxy/autoconfig_url", "");
			Logger.log(getClass(), LogLevel.TRACE, "Gnome uses autodetect script {0}", pacScriptUrl);
			result = ProxyUtil.buildPacSelectorForUrl(pacScriptUrl);
		}

		// Wrap into white-list filter?
		String noProxyList = settings.getProperty("/system/http_proxy/ignore_hosts", null);
		if (result != null && noProxyList != null && noProxyList.trim().length() > 0) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome uses proxy bypass list: {0}", noProxyList);
			result = new ProxyBypassListSelector(noProxyList, result);
		}				
		
		return result;
	}

	/*************************************************************************
	 * Load the proxy settings from the  gconf settings XML file.  
	 * @return the loaded settings stored in a properties object.
	 * @throws ProxyException on processing error.
	 ************************************************************************/
	
	public Properties readSettings() throws ProxyException {
		Properties settings = new Properties();
		try {
			parseSettings("/system/proxy/", settings);
			parseSettings("/system/http_proxy/", settings);
		} catch (IOException e) {
			Logger.log(getClass(), LogLevel.ERROR, "Gnome settings file error.", e);
			throw new ProxyException(e);
		}
		return settings;
	}

	/*************************************************************************
	 * Finds the Gnome GConf settings file.
	 * @param context the gconf context to parse. 
	 * @return a file or null if does not exist. 
	 ************************************************************************/
	
	private File findSettingsFile(String context) {
		// Normally we should inspect /etc/gconf/<version>/path to find out where the actual file is.
		// But for normal systems this is always stored in .gconf folder in the user's home directory.
		File userDir = new File(System.getProperty("user.home"));
		
		// Build directory path for context
		StringBuilder path = new StringBuilder();
		String[] parts = context.split("/");
		for (String part : parts) {
			path.append(part);
			path.append(File.separator);
		}
		
		File settingsFile = new File(userDir, ".gconf"+File.separator+path.toString()+"%gconf.xml");
		if (!settingsFile.exists()) {
			Logger.log(getClass(), LogLevel.WARNING, "Gnome settings: {0} not found.", settingsFile);
			return null;
		}
		return settingsFile;
	}

	/*************************************************************************
	 * Parse the fixed proxy settings and build an ProxySelector for this a 
	 * chained configuration.
	 * @param settings the proxy settings to evaluate.
	 ************************************************************************/
	
	private ProxySelector setupFixedProxySelector(Properties settings) {
		if (!hasProxySettings(settings)) {
			return null;
		}
		ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
		installHttpSelector(settings, ps);

		if (useForAllProtocols(settings)) {
			ps.setFallbackSelector(ps.getSelector("http"));
		} else {
			installSecureSelector(settings, ps);
			installFtpSelector(settings, ps);
			installSocksSelector(settings, ps);
		}
		return ps;
	}

	/*************************************************************************
	 * Check if the http proxy should also be used for all other protocols.
	 * @param settings to inspect.
	 * @return true if only one proxy is configured else false.
	 ************************************************************************/
	
	private boolean useForAllProtocols(Properties settings) {
		return Boolean.parseBoolean(
				settings.getProperty("/system/http_proxy/use_same_proxy", "false"));
	}

	/*************************************************************************
	 * Checks if we have Proxy configuration settings in the properties.
	 * @param settings to inspect.
	 * @return true if we have found Proxy settings.
	 ************************************************************************/
	
	private boolean hasProxySettings(Properties settings) {
		String proxyHost = settings.getProperty("/system/http_proxy/host", null);
		return proxyHost != null && proxyHost.length() > 0;
	}
	
	/*************************************************************************
	 * Install a http proxy from the given settings.
	 * @param settings to inspect
	 * @param ps the dispatch selector to configure.
	 * @throws NumberFormatException
	 ************************************************************************/
	
	private void installHttpSelector(Properties settings,
			ProtocolDispatchSelector ps) throws NumberFormatException {
		String proxyHost = settings.getProperty("/system/http_proxy/host", null);
		int proxyPort = Integer.parseInt(settings.getProperty("/system/http_proxy/port", "0").trim());
		if (proxyHost != null && proxyHost.length() > 0) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome http proxy is {0}:{1}", proxyHost, proxyPort);
			ps.setSelector("http", ProxyUtil.parseProxySettings(proxyHost.trim(), Proxy.Type.HTTP, proxyPort));
		}
	}

	/*************************************************************************
	 * Install a socks proxy from the given settings.
	 * @param settings to inspect
	 * @param ps the dispatch selector to configure.
	 * @throws NumberFormatException
	 ************************************************************************/
	
	private void installSocksSelector(Properties settings,
			ProtocolDispatchSelector ps) throws NumberFormatException {
		String proxyHost = settings.getProperty("/system/proxy/socks_host", null);
		int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/socks_port", "0").trim());
		if (proxyHost != null && proxyHost.length() > 0) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome socks proxy is {0}:{1}", proxyHost, proxyPort);
			ps.setSelector("socks", ProxyUtil.parseProxySettings(proxyHost.trim(), Proxy.Type.SOCKS, proxyPort));
		}
	}

	/*************************************************************************
	 * @param settings
	 * @param ps
	 * @throws NumberFormatException
	 ************************************************************************/
	
	private void installFtpSelector(Properties settings,
			ProtocolDispatchSelector ps) throws NumberFormatException {
		String proxyHost = settings.getProperty("/system/proxy/ftp_host", null);
		int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/ftp_port", "0").trim());
		if (proxyHost != null && proxyHost.length() > 0) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome ftp proxy is {0}:{1}", proxyHost, proxyPort);
			ps.setSelector("ftp", ProxyUtil.parseProxySettings(proxyHost.trim(), Proxy.Type.HTTP, proxyPort));
		}
	}

	/*************************************************************************
	 * @param settings
	 * @param ps
	 * @throws NumberFormatException
	 ************************************************************************/
	
	
	private void installSecureSelector(Properties settings,
			ProtocolDispatchSelector ps) throws NumberFormatException {
		String proxyHost = settings.getProperty("/system/proxy/secure_host", null);
		int proxyPort = Integer.parseInt(settings.getProperty("/system/proxy/secure_port", "0").trim());
		if (proxyHost != null && proxyHost.length() > 0) {
			Logger.log(getClass(), LogLevel.TRACE, "Gnome secure proxy is {0}:{1}", proxyHost, proxyPort);
			ProxySelector ps2 = ProxyUtil.parseProxySettings(proxyHost.trim(), Proxy.Type.HTTP, proxyPort);
			ps.setSelector("https", ps2);
			ps.setSelector("sftp", ps2);
		}
	}
	
	/*************************************************************************
	 * Parse the settings file and extract all network.proxy.* settings from it.
	 * @param context the gconf context to parse.
	 * @param settings the settings object to fill.
	 * @return the parsed properties.
	 * @throws IOException on read error.
	 ************************************************************************/
	
	private Properties parseSettings(String context, Properties settings) throws IOException {
		
		// Read settings from file
		File settingsFile = findSettingsFile(context);
		if (settingsFile == null) {
			return settings;
		}
		
		try {
			DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			documentBuilder.setEntityResolver(new EmptyXMLResolver());
			Document doc = documentBuilder.parse(settingsFile);
			Element root = doc.getDocumentElement();
			Node entry = root.getFirstChild();
			while (entry != null) {
				if ("entry".equals(entry.getNodeName()) && entry instanceof Element) {
					String entryName = ((Element)entry).getAttribute("name");
					settings.setProperty(context+entryName, getEntryValue((Element) entry));
				}
				entry = entry.getNextSibling();
			}
		} catch (SAXException e) {
			Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
			throw new IOException(e.getMessage());
		} catch (ParserConfigurationException e) {
			Logger.log(getClass(), LogLevel.ERROR, "Gnome settings parse error", e);
			throw new IOException(e.getMessage());
		}
		
		return settings;
	}

	/*************************************************************************
	 * Parse an entry value from a given entry node.
	 * @param entry the XML node to inspect.
	 * @return the value, null if it has no value.
	 ************************************************************************/
	
	private String getEntryValue(Element entry) {
		String type = entry.getAttribute("type");
	
		if ("int".equals(type) || "bool".equals(type)) {
			return entry.getAttribute("value"); 
		}
		if ("string".equals(type)) {
			NodeList list = entry.getElementsByTagName("stringvalue");
			if (list.getLength() > 0) {
				return list.item(0).getTextContent();
			}
		}
		if ("list".equals(type)) {
			StringBuilder result = new StringBuilder();
			NodeList list = entry.getElementsByTagName("li");

			// Build comma separated list of items
			for (int i = 0; i < list.getLength(); i++) {
				if (result.length() > 0) {
					result.append(",");
				}
				result.append(getEntryValue((Element) list.item(i)));
			}
			return result.toString();
		}
		return null;
	}

}