Debian Codegraph @

src/main/java/com/github/markusbernhardt/proxy/search/desktop/osx/OsxProxySearchStrategy.java

raw symbols SCIP
1 package com.github.markusbernhardt.proxy.search.desktop.osx;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.net.NetworkInterface;
6 import java.net.ProxySelector;
7 import java.net.SocketException;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.Enumeration;
11 import java.util.List;
12
13 import com.github.markusbernhardt.proxy.ProxySearchStrategy;
14 import com.github.markusbernhardt.proxy.search.browser.ie.IELocalByPassFilter;
15 import com.github.markusbernhardt.proxy.search.wpad.WpadProxySearchStrategy;
16 import com.github.markusbernhardt.proxy.selector.direct.NoProxySelector;
17 import com.github.markusbernhardt.proxy.selector.fixed.FixedProxySelector;
18 import com.github.markusbernhardt.proxy.selector.fixed.FixedSocksSelector;
19 import com.github.markusbernhardt.proxy.selector.misc.ProtocolDispatchSelector;
20 import com.github.markusbernhardt.proxy.selector.whitelist.ProxyBypassListSelector;
21 import com.github.markusbernhardt.proxy.util.Logger;
22 import com.github.markusbernhardt.proxy.util.Logger.LogLevel;
23 import com.github.markusbernhardt.proxy.util.PListParser;
24 import com.github.markusbernhardt.proxy.util.PListParser.Dict;
25 import com.github.markusbernhardt.proxy.util.PListParser.XmlParseException;
26 import com.github.markusbernhardt.proxy.util.ProxyException;
27 import com.github.markusbernhardt.proxy.util.ProxyUtil;
28 import com.github.markusbernhardt.proxy.util.UriFilter;
29
30 /*****************************************************************************
31 * Loads the OSX system proxy settings from the settings file.
32 * <p>
33 * All settings are stored in OSX in a special XML file format. These settings
34 * file are named plist files and contain nested dictionaries, arrays and
35 * values.
36 * </p>
37 * <p>
38 * To parse this file we use a parser that is derived from a plist parser that
39 * comes with the xmlwise XML parser package:
40 * </p>
41 * <p>
42 * http://code.google.com/p/xmlwise/
43 * </p>
44 * <p>
45 * I modified that parser to work with the default Java XML parsing library.
46 * </p>
47 * <p>
48 * The plist file is located on OSX at:
49 * </p>
50 * <p>
51 * /Library/Preferences/SystemConfiguration/preferences.plist
52 * </p>
53 *
54 * @author Markus Bernhardt, Copyright 2016
55 * @author Bernd Rosstauscher, Copyright 2009
56 ****************************************************************************/
57
58 public class OsxProxySearchStrategy implements ProxySearchStrategy {
59
60 public static final String OVERRIDE_SETTINGS_FILE = "com.github.markusbernhardt.proxy.osx.settingsFile";
61 public static final String OVERRIDE_ACCEPTED_DEVICES = "com.github.markusbernhardt.proxy.osx.acceptedDevices";
62
63 private static final String SETTINGS_FILE = "/Library/Preferences/SystemConfiguration/preferences.plist";
64
65 /*************************************************************************
66 * ProxySelector
67 *
68 * @see java.net.ProxySelector#ProxySelector()
69 ************************************************************************/
70
71 public OsxProxySearchStrategy() {
72 super();
73 }
74
75 /*************************************************************************
76 * Loads the proxy settings and initializes a proxy selector for the OSX
77 * proxy settings.
78 *
79 * @return a configured ProxySelector, null if none is found.
80 * @throws ProxyException
81 * on file reading error.
82 ************************************************************************/
83
84 @Override
85 public ProxySelector getProxySelector() throws ProxyException {
86
87 Logger.log(getClass(), LogLevel.TRACE, "Detecting OSX proxy settings");
88
89 try {
90 List<String> acceptedInterfaces = getNetworkInterfaces();
91
92 Dict settings = PListParser.load(getSettingsFile());
93 Object currentSet = settings.getAtPath("/CurrentSet");
94 if (currentSet == null) {
95 throw new ProxyException("CurrentSet not defined");
96 }
97
98 Dict networkSet = (Dict) settings.getAtPath(String.valueOf(currentSet));
99
100 // TODO 30.03.2015 bros Test for IP6 compatibility
101 List<?> serviceOrder = (List<?>) networkSet.getAtPath("/Network/Global/IPv4/ServiceOrder");
102 if (serviceOrder == null || serviceOrder.size() == 0) {
103 throw new ProxyException("ServiceOrder not defined");
104 }
105
106 // Look at the Services in priority order and pick the first one
107 // that was
108 // also accepted above
109 Dict proxySettings = null;
110 for (int i = 0; i < serviceOrder.size() && proxySettings == null; i++) {
111 Object candidateService = serviceOrder.get(i);
112 Object networkService = networkSet.getAtPath("/Network/Service/" + candidateService + "/__LINK__");
113 if (networkService == null) {
114 throw new ProxyException("NetworkService not defined.");
115 }
116 Dict selectedServiceSettings = (Dict) settings.getAtPath("" + networkService);
117 String interfaceName = (String) selectedServiceSettings.getAtPath("/Interface/DeviceName");
118 if (acceptedInterfaces.contains(interfaceName)) {
119 Logger.log(getClass(), LogLevel.TRACE, "Looking up proxies for device " + interfaceName);
120 proxySettings = (Dict) selectedServiceSettings.getAtPath("/Proxies");
121 }
122 }
123 if (proxySettings == null) {
124 return NoProxySelector.getInstance();
125 }
126
127 return buildSelector(proxySettings);
128 } catch (XmlParseException e) {
129 throw new ProxyException(e);
130 } catch (IOException e) {
131 throw new ProxyException(e);
132 }
133 }
134
135 /*************************************************************************
136 * Gets the printable name of the search strategy.
137 *
138 * @return the printable name of the search strategy
139 ************************************************************************/
140
141 @Override
142 public String getName() {
143 return "osx";
144 }
145
146 /*************************************************************************
147 * Build a selector from the given settings.
148 *
149 * @param proxySettings
150 * to parse
151 * @return the configured selector
152 * @throws ProxyException
153 * on error
154 ************************************************************************/
155
156 private ProxySelector buildSelector(Dict proxySettings) throws ProxyException {
157 ProtocolDispatchSelector ps = new ProtocolDispatchSelector();
158 installSelectorForProtocol(proxySettings, ps, "HTTP");
159 installSelectorForProtocol(proxySettings, ps, "HTTPS");
160 installSelectorForProtocol(proxySettings, ps, "FTP");
161 installSelectorForProtocol(proxySettings, ps, "Gopher");
162 installSelectorForProtocol(proxySettings, ps, "RTSP");
163 installSocksProxy(proxySettings, ps);
164
165 ProxySelector result = ps;
166 result = installPacProxyIfAvailable(proxySettings, result);
167 result = autodetectProxyIfAvailable(proxySettings, result);
168
169 if (result != null) {
170 result = installExceptionList(proxySettings, result);
171 result = installSimpleHostFilter(proxySettings, result);
172 }
173 return result;
174 }
175
176 /*************************************************************************
177 * Create a list of Ethernet interfaces that are connected
178 *
179 * @return a list of available interface names
180 * @throws SocketException
181 ************************************************************************/
182
183 private List<String> getNetworkInterfaces() throws SocketException {
184 String override = System.getProperty(OVERRIDE_ACCEPTED_DEVICES);
185 if (override != null && override.length() > 0) {
186 return Arrays.asList(override.split(";"));
187 }
188
189 List<String> acceptedInterfaces = new ArrayList<String>();
190 Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
191 while (interfaces.hasMoreElements()) {
192 NetworkInterface ni = interfaces.nextElement();
193 if (isInterfaceAllowed(ni)) {
194 acceptedInterfaces.add(ni.getName());
195 }
196 }
197 return acceptedInterfaces;
198 }
199
200 /*************************************************************************
201 * Check if a given network interface is interesting for us.
202 *
203 * @param ni
204 * the interface to check
205 * @return true if accepted else false.
206 * @throws SocketException
207 * on error.
208 ************************************************************************/
209
210 private boolean isInterfaceAllowed(NetworkInterface ni) throws SocketException {
211 return !ni.isLoopback() && !ni.isPointToPoint() && // Not sure if we
212 // should filter the
213 // point to point
214 // interfaces?
215 !ni.isVirtual() && ni.isUp();
216 }
217
218 /*************************************************************************
219 * Gets the settings file to parse the settings from.
220 *
221 * @return the settings file.
222 ************************************************************************/
223
224 private File getSettingsFile() {
225 File result = new File(SETTINGS_FILE);
226 String overrideFile = System.getProperty(OVERRIDE_SETTINGS_FILE);
227 if (overrideFile != null) {
228 return new File(overrideFile);
229 }
230 return result;
231 }
232
233 /*************************************************************************
234 * Install a filter to ignore simple host names without domain name.
235 *
236 * @param proxySettings
237 * the dictionary containing all settings
238 * @param result
239 * the proxy selector that needs to be adapted.
240 * @return a wrapped proxy selector that will ignore simple names.
241 ************************************************************************/
242
243 private ProxySelector installSimpleHostFilter(Dict proxySettings, ProxySelector result) {
244 if (isActive(proxySettings.get("ExcludeSimpleHostnames"))) {
245 List<UriFilter> localBypassFilter = new ArrayList<UriFilter>();
246 localBypassFilter.add(new IELocalByPassFilter());
247 result = new ProxyBypassListSelector(localBypassFilter, result);
248 }
249 return result;
250 }
251
252 /*************************************************************************
253 * Install a host name base filter to handle the proxy exclude list.
254 *
255 * @param proxySettings
256 * the dictionary containing all settings
257 * @param result
258 * the proxy selector that needs to be adapted.
259 * @return a wrapped proxy selector that will handle the exclude list.
260 ************************************************************************/
261
262 private ProxySelector installExceptionList(Dict proxySettings, ProxySelector result) {
263 List<?> proxyExceptions = (List<?>) proxySettings.get("ExceptionsList");
264 if (proxyExceptions != null && proxyExceptions.size() > 0) {
265 Logger.log(getClass(), LogLevel.TRACE, "OSX uses proxy bypass list: {0}", proxyExceptions);
266 String noProxyList = toCommaSeparatedString(proxyExceptions);
267 result = new ProxyBypassListSelector(noProxyList, result);
268 }
269 return result;
270 }
271
272 /*************************************************************************
273 * Convert a list to a comma separated list.
274 *
275 * @param proxyExceptions
276 * list of elements.
277 * @return a comma separated string of the list's content.
278 ************************************************************************/
279
280 private String toCommaSeparatedString(List<?> proxyExceptions) {
281 StringBuilder result = new StringBuilder();
282 for (Object object : proxyExceptions) {
283 if (result.length() > 0) {
284 result.append(",");
285 }
286 result.append(object);
287 }
288 return result.toString();
289 }
290
291 /*************************************************************************
292 * Invoke WPAD proxy detection if configured.
293 *
294 * @param proxySettings
295 * the settings to analyse.
296 * @param result
297 * the current proxy selector.
298 * @return a WPAD proxy selector or the passed in proxy selector.
299 * @throws ProxyException
300 * on automatic detection errors.
301 ************************************************************************/
302
303 private ProxySelector autodetectProxyIfAvailable(Dict proxySettings, ProxySelector result) throws ProxyException {
304 if (isActive(proxySettings.get("ProxyAutoDiscoveryEnable"))) {
305 ProxySelector wp = new WpadProxySearchStrategy().getProxySelector();
306 if (wp != null) {
307 result = wp;
308 }
309 }
310 return result;
311 }
312
313 /*************************************************************************
314 * Use a PAC based proxy selector if configured.
315 *
316 * @param proxySettings
317 * the settings to analyse.
318 * @param result
319 * the current proxy selector.
320 * @return a PAC proxy selector or the passed in proxy selector.
321 ************************************************************************/
322
323 private ProxySelector installPacProxyIfAvailable(Dict proxySettings, ProxySelector result) {
324 if (isActive(proxySettings.get("ProxyAutoConfigEnable"))) {
325 String url = (String) proxySettings.get("ProxyAutoConfigURLString");
326 result = ProxyUtil.buildPacSelectorForUrl(url);
327 }
328 return result;
329 }
330
331 /*************************************************************************
332 * Build a socks proxy and set it for the socks protocol.
333 *
334 * @param proxySettings
335 * to read the config values from.
336 * @param ps
337 * the ProtocolDispatchSelector to install the new proxy on.
338 ************************************************************************/
339
340 private void installSocksProxy(Dict proxySettings, ProtocolDispatchSelector ps) {
341 if (isActive(proxySettings.get("SOCKSEnable"))) {
342 String proxyHost = (String) proxySettings.get("SOCKSProxy");
343 int proxyPort = (Integer) proxySettings.get("SOCKSPort");
344 ps.setSelector("socks", new FixedSocksSelector(proxyHost, proxyPort));
345 Logger.log(getClass(), LogLevel.TRACE, "OSX socks proxy is {0}:{1}", proxyHost, proxyPort);
346 }
347 }
348
349 /*************************************************************************
350 * Installs a proxy selector for the given protocoll on the
351 * ProtocolDispatchSelector
352 *
353 * @param proxySettings
354 * to read the config for the procotol from.
355 * @param ps
356 * the ProtocolDispatchSelector to install the new selector on.
357 * @param protocol
358 * to use.
359 ************************************************************************/
360
361 private void installSelectorForProtocol(Dict proxySettings, ProtocolDispatchSelector ps, String protocol) {
362 String prefix = protocol.trim();
363 if (isActive(proxySettings.get(prefix + "Enable"))) {
364 String proxyHost = (String) proxySettings.get(prefix + "Proxy");
365 int proxyPort = (Integer) proxySettings.get(prefix + "Port");
366 FixedProxySelector fp = new FixedProxySelector(proxyHost, proxyPort);
367 ps.setSelector(protocol.toLowerCase(), fp);
368 Logger.log(getClass(), LogLevel.TRACE, "OSX uses for {0} the proxy {1}:{2}", protocol, proxyHost,
369 proxyPort);
370 }
371 }
372
373 /*************************************************************************
374 * Checks if the given value is set to "on".
375 *
376 * @param value
377 * the value to test.
378 * @return true if it is set else false.
379 ************************************************************************/
380
381 private boolean isActive(Object value) {
382 return Integer.valueOf(1).equals(value);
383 }
384
385 }