This project has retired. For details please refer to its Attic page.
ProxyDetector xref
View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.chemistry.opencmis.workbench;
20  
21  import java.io.BufferedReader;
22  import java.io.IOException;
23  import java.io.InputStreamReader;
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.Locale;
27  import java.util.Map;
28  import java.util.regex.Matcher;
29  import java.util.regex.Pattern;
30  
31  import org.apache.chemistry.opencmis.commons.impl.IOUtils;
32  
33  /**
34   * Tries to detect the OS proxy configuration.
35   */
36  public class ProxyDetector {
37  
38      public static final String HTTP_PROXY_HOST = "http.proxyHost";
39      public static final String HTTP_PROXY_PORT = "http.proxyPort";
40      public static final String HTTP_PROXY_USER = "http.proxyUser";
41      public static final String HTTP_PROXY_PASSWORD = "http.proxyPassword";
42      public static final String HTTPS_PROXY_HOST = "https.proxyHost";
43      public static final String HTTPS_PROXY_PORT = "https.proxyPort";
44      public static final String HTTPS_PROXY_USER = "https.proxyUser";
45      public static final String HTTPS_PROXY_PASSWORD = "https.proxyPassword";
46      public static final String HTTP_NON_PROXY_HOSTS = "http.nonProxyHosts";
47  
48      public static final Pattern PROXY_ENV_VAR1 = Pattern.compile("http.?:\\/\\/(.+):(\\d+).*");
49      public static final Pattern PROXY_ENV_VAR2 = Pattern.compile("(.+):(\\d+)");
50      public static final Pattern PROXY_WIN_REG = Pattern.compile("\\s+Proxy(.+)\\s+REG.+\\s+(.+)");
51  
52      private static boolean debug = false;
53  
54      /**
55       * Gets proxy settings from system properties.
56       */
57      public static ProxySettings getJavaProxySettings() {
58          ProxySettings settings = new ProxySettings();
59  
60          settings.setHttpProxyHost(System.getProperty(HTTP_PROXY_HOST));
61          settings.setHttpProxyPort(parsePort(System.getProperty(HTTP_PROXY_PORT)));
62          settings.setHttpProxyUser(System.getProperty(HTTP_PROXY_USER));
63          settings.setHttpProxyPassword(System.getProperty(HTTP_PROXY_PASSWORD));
64          settings.setHttpsProxyHost(System.getProperty(HTTPS_PROXY_HOST));
65          settings.setHttpsProxyPort(parsePort(System.getProperty(HTTPS_PROXY_PORT)));
66          settings.setHttpsProxyUser(System.getProperty(HTTPS_PROXY_USER));
67          settings.setHttpsProxyPassword(System.getProperty(HTTPS_PROXY_PASSWORD));
68  
69          String nonProxyHosts = System.getProperty(HTTP_NON_PROXY_HOSTS);
70          if (nonProxyHosts != null) {
71              List<String> noHosts = new ArrayList<String>();
72  
73              String nph = nonProxyHosts;
74              int pp = nph.indexOf('|');
75              while (pp > -1) {
76                  String noHost = nph.substring(0, pp).trim();
77                  if (noHost.length() > 0) {
78                      noHosts.add(noHost);
79                  }
80  
81                  nph = nph.substring(pp + 1);
82                  pp = nph.indexOf('|');
83              }
84  
85              nph = nph.trim();
86              if (nph.length() > 0) {
87                  noHosts.add(nph);
88              }
89  
90              settings.setNonProxyHosts(noHosts);
91          }
92  
93          if (settings.getHttpProxyHost() != null || settings.getHttpsProxyHost() != null) {
94              return settings;
95          }
96  
97          return null;
98      }
99  
100     /**
101      * Gets proxy settings from environment variables.
102      */
103     public static ProxySettings getEnvProxySettings() {
104         ProxySettings settings = new ProxySettings();
105 
106         Map<String, String> env = System.getenv();
107 
108         for (Map.Entry<String, String> e : env.entrySet()) {
109             String key = e.getKey().trim().toLowerCase(Locale.ENGLISH);
110 
111             if ("http_proxy".equals(key)) {
112                 Matcher m = PROXY_ENV_VAR1.matcher(e.getValue());
113                 if (m.matches()) {
114                     settings.setHttpProxyHost(parseHost(m.group(1)));
115                     settings.setHttpProxyPort(parsePort(m.group(2)));
116                     settings.setHttpProxyUser(parseProxyUser(m.group(1)));
117                     settings.setHttpProxyPassword(parseProxyPassword(m.group(1)));
118                 } else {
119                     m = PROXY_ENV_VAR2.matcher(e.getValue());
120                     if (m.matches()) {
121                         settings.setHttpProxyHost(parseHost(m.group(1)));
122                         settings.setHttpProxyPort(parsePort(m.group(2)));
123                         settings.setHttpProxyUser(parseProxyUser(m.group(1)));
124                         settings.setHttpProxyPassword(parseProxyPassword(m.group(1)));
125                     }
126                 }
127             } else if ("https_proxy".equals(key)) {
128                 Matcher m = PROXY_ENV_VAR1.matcher(e.getValue());
129                 if (m.matches()) {
130                     settings.setHttpsProxyHost(parseHost(m.group(1)));
131                     settings.setHttpsProxyPort(parsePort(m.group(2)));
132                     settings.setHttpsProxyUser(parseProxyUser(m.group(1)));
133                     settings.setHttpsProxyPassword(parseProxyPassword(m.group(1)));
134                 } else {
135                     m = PROXY_ENV_VAR2.matcher(e.getValue());
136                     if (m.matches()) {
137                         settings.setHttpProxyHost(parseHost(m.group(1)));
138                         settings.setHttpProxyPort(parsePort(m.group(2)));
139                         settings.setHttpsProxyUser(parseProxyUser(m.group(1)));
140                         settings.setHttpsProxyPassword(parseProxyPassword(m.group(1)));
141                     }
142                 }
143             } else if ("no_proxy".equals(key)) {
144                 List<String> noHosts = new ArrayList<String>();
145                 for (String noHost : e.getValue().split(",")) {
146                     noHost = noHost.trim();
147                     if (noHost.length() == 0) {
148                         continue;
149                     }
150 
151                     if (noHost.charAt(0) == '.') {
152                         noHost = "*" + noHost;
153                     }
154 
155                     if (noHost.charAt(noHost.length() - 1) == '.') {
156                         noHost = noHost + "*";
157                     }
158 
159                     noHosts.add(noHost);
160                 }
161 
162                 settings.setNonProxyHosts(noHosts);
163             }
164         }
165 
166         if (settings.getHttpProxyHost() != null || settings.getHttpsProxyHost() != null) {
167             return settings;
168         }
169 
170         return null;
171     }
172 
173     /**
174      * Gets proxy settings from the Windows registry.
175      */
176     public static ProxySettings getRegistryProxySettings() {
177         if (!isWindows()) {
178             return null;
179         }
180 
181         BufferedReader reader = null;
182         try {
183             ProxySettings settings = new ProxySettings();
184 
185             Process process = Runtime
186                     .getRuntime()
187                     .exec("reg query \"HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings\" /v Proxy*");
188 
189             reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
190 
191             String line;
192             while ((line = reader.readLine()) != null) {
193                 Matcher m = PROXY_WIN_REG.matcher(line);
194                 if (!m.matches()) {
195                     continue;
196                 }
197 
198                 String key = m.group(1).trim().toLowerCase(Locale.ENGLISH);
199                 String value = m.group(2).trim();
200 
201                 if ("enable".equals(key)) {
202                     if (!value.equals("0x1")) {
203                         // proxies disabled
204                         return null;
205                     }
206                 } else if ("server".equals(key)) {
207                     // server
208                     String host = value;
209                     int port = 80;
210 
211                     int x = value.indexOf(':');
212                     if (x > 0) {
213                         host = value.substring(0, x);
214                         port = parsePort(value.substring(x + 1));
215                     }
216 
217                     settings.setHttpProxyHost(host);
218                     settings.setHttpProxyPort(port);
219                     settings.setHttpsProxyHost(host);
220                     settings.setHttpsProxyPort(port);
221                 } else if ("override".equals(key)) {
222                     // no proxy
223                     List<String> noHosts = new ArrayList<String>();
224                     for (String noHost : value.split(";")) {
225                         noHost = noHost.trim();
226                         if (noHost.length() == 0) {
227                             continue;
228                         }
229                         noHosts.add(noHost);
230                     }
231 
232                     settings.setNonProxyHosts(noHosts);
233                 }
234             }
235 
236             if (settings.getHttpProxyHost() != null || settings.getHttpsProxyHost() != null) {
237                 return settings;
238             }
239         } catch (IOException e) {
240             // ignore
241             if (debug) {
242                 e.printStackTrace();
243             }
244         } finally {
245             IOUtils.closeQuietly(reader);
246         }
247 
248         return null;
249     }
250 
251     private static String parseHost(String host) {
252         if (host == null) {
253             return null;
254         }
255 
256         int at = host.lastIndexOf('@');
257         if (at > -1) {
258             return host.substring(at + 1);
259         }
260 
261         return host;
262     }
263 
264     private static int parsePort(String port) {
265         if (port == null) {
266             return 80;
267         }
268 
269         try {
270             return Integer.parseInt(port);
271         } catch (NumberFormatException e) {
272             throw new RuntimeException("Invalid port: " + port);
273         }
274     }
275 
276     private static String parseProxyUser(String host) {
277         if (host == null) {
278             return null;
279         }
280 
281         int at = host.lastIndexOf('@');
282         if (at == -1) {
283             return null;
284         }
285 
286         int colon = host.indexOf(':');
287         if (colon == -1 || colon > at) {
288             return host.substring(0, at);
289         }
290 
291         return host.substring(0, colon);
292     }
293 
294     private static String parseProxyPassword(String host) {
295         if (host == null) {
296             return null;
297         }
298 
299         int at = host.lastIndexOf('@');
300         if (at == -1) {
301             return null;
302         }
303 
304         int colon = host.indexOf(':');
305         if (colon == -1 || colon > at) {
306             return null;
307         }
308 
309         return host.substring(colon + 1, at);
310     }
311 
312     private static boolean isWindows() {
313         return System.getProperty("os.name").startsWith("Windows");
314     }
315 
316     /**
317      * Main.
318      */
319     public static void main(String[] args) {
320         boolean javaParams = false;
321         boolean useSystemProxy = false;
322 
323         for (String arg : args) {
324             if (arg.equalsIgnoreCase("-j")) {
325                 javaParams = true;
326             } else if (arg.equalsIgnoreCase("-s")) {
327                 useSystemProxy = true;
328             } else if (arg.equalsIgnoreCase("-d")) {
329                 debug = true;
330             } else if (arg.equalsIgnoreCase("-h") || arg.equalsIgnoreCase("-?")) {
331                 System.out.println("Parameters:");
332                 System.out.println("-j  print Java system properties");
333                 System.out.println("-s  add java.net.useSystemProxies property");
334                 return;
335             }
336         }
337 
338         ProxySettings settings = null;
339 
340         settings = getJavaProxySettings();
341 
342         if (settings == null) {
343             // try environment variables
344             settings = getEnvProxySettings();
345         }
346 
347         if (settings == null) {
348             // try the Windows registry
349             settings = getRegistryProxySettings();
350         }
351 
352         // print proxy settings
353         if (javaParams) {
354             String proxyStr = "";
355 
356             if (settings != null) {
357                 proxyStr = settings.toJavaConfigString();
358             }
359 
360             if (useSystemProxy) {
361                 if (proxyStr.length() > 0) {
362                     proxyStr = proxyStr + " ";
363                 }
364                 proxyStr = proxyStr + "-Djava.net.useSystemProxies=true";
365             }
366 
367             System.out.println(proxyStr);
368         } else {
369             if (settings != null) {
370                 System.out.println(settings.toString());
371             } else {
372                 System.out.println("DIRECT");
373             }
374         }
375     }
376 
377     /**
378      * Proxy settings holder.
379      */
380     public static class ProxySettings {
381         private String httpProxyHost;
382         private int httpProxyPort;
383         private String httpProxyUser;
384         private String httpProxyPassword;
385 
386         private String httpsProxyHost;
387         private int httpsProxyPort;
388         private String httpsProxyUser;
389         private String httpsProxyPassword;
390 
391         private List<String> nonProxyHosts;
392 
393         public ProxySettings() {
394         }
395 
396         public String getHttpProxyHost() {
397             return httpProxyHost;
398         }
399 
400         public void setHttpProxyHost(String httpProxyHost) {
401             this.httpProxyHost = httpProxyHost;
402         }
403 
404         public int getHttpProxyPort() {
405             return httpProxyPort;
406         }
407 
408         public void setHttpProxyPort(int httpProxyPort) {
409             this.httpProxyPort = httpProxyPort;
410         }
411 
412         public String getHttpProxyUser() {
413             return httpProxyUser;
414         }
415 
416         public void setHttpProxyUser(String httpProxyUser) {
417             this.httpProxyUser = httpProxyUser;
418         }
419 
420         public String getHttpProxyPassword() {
421             return httpProxyPassword;
422         }
423 
424         public void setHttpProxyPassword(String httpProxyPassword) {
425             this.httpProxyPassword = httpProxyPassword;
426         }
427 
428         public String getHttpsProxyHost() {
429             return httpsProxyHost;
430         }
431 
432         public void setHttpsProxyHost(String httpsProxyHost) {
433             this.httpsProxyHost = httpsProxyHost;
434         }
435 
436         public int getHttpsProxyPort() {
437             return httpsProxyPort;
438         }
439 
440         public void setHttpsProxyPort(int httpsProxyPort) {
441             this.httpsProxyPort = httpsProxyPort;
442         }
443 
444         public String getHttpsProxyUser() {
445             return httpsProxyUser;
446         }
447 
448         public void setHttpsProxyUser(String httpsProxyUser) {
449             this.httpsProxyUser = httpsProxyUser;
450         }
451 
452         public String getHttpsProxyPassword() {
453             return httpsProxyPassword;
454         }
455 
456         public void setHttpsProxyPassword(String httpsProxyPassword) {
457             this.httpsProxyPassword = httpsProxyPassword;
458         }
459 
460         public List<String> getNonProxyHosts() {
461             return nonProxyHosts;
462         }
463 
464         public void setNonProxyHosts(List<String> nonProxyHosts) {
465             this.nonProxyHosts = nonProxyHosts;
466         }
467 
468         public String toJavaConfigString() {
469             StringBuilder sb = new StringBuilder();
470 
471             if (httpProxyHost != null) {
472                 sb.append("-D" + HTTP_PROXY_HOST + "=" + httpProxyHost + " -D" + HTTP_PROXY_PORT + "=" + httpProxyPort);
473             }
474 
475             if (httpProxyUser != null) {
476                 if (sb.length() > 0) {
477                     sb.append(' ');
478                 }
479 
480                 sb.append("-D" + HTTP_PROXY_USER + "=" + httpProxyUser);
481             }
482 
483             if (httpProxyPassword != null) {
484                 if (sb.length() > 0) {
485                     sb.append(' ');
486                 }
487 
488                 sb.append("-D" + HTTP_PROXY_PASSWORD + "=" + httpProxyPassword);
489             }
490 
491             if (httpsProxyHost != null) {
492                 if (sb.length() > 0) {
493                     sb.append(' ');
494                 }
495 
496                 sb.append("-D" + HTTPS_PROXY_HOST + "=" + httpsProxyHost + " -D" + HTTPS_PROXY_PORT + "="
497                         + httpsProxyPort);
498             }
499 
500             if (httpsProxyUser != null) {
501                 if (sb.length() > 0) {
502                     sb.append(' ');
503                 }
504 
505                 sb.append("-D" + HTTPS_PROXY_USER + "=" + httpsProxyUser);
506             }
507 
508             if (httpsProxyPassword != null) {
509                 if (sb.length() > 0) {
510                     sb.append(' ');
511                 }
512 
513                 sb.append("-D" + HTTPS_PROXY_PASSWORD + "=" + httpsProxyPassword);
514             }
515 
516             if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
517                 if (sb.length() > 0) {
518                     sb.append(' ');
519                 }
520 
521                 if (isWindows()) {
522                     sb.append('\"');
523                 }
524 
525                 sb.append("-D" + HTTP_NON_PROXY_HOSTS + "=");
526 
527                 boolean first = true;
528                 for (String host : nonProxyHosts) {
529                     if (!first) {
530                         sb.append('|');
531                     } else {
532                         first = false;
533                     }
534 
535                     sb.append(host);
536                 }
537 
538                 if (isWindows()) {
539                     sb.append('\"');
540                 }
541             }
542 
543             return sb.toString();
544         }
545 
546         @Override
547         public String toString() {
548             StringBuilder sb = new StringBuilder();
549 
550             if (httpProxyHost != null) {
551                 sb.append("HTTP proxy: " + httpProxyHost + ":" + httpProxyPort);
552             }
553 
554             if (httpProxyUser != null) {
555                 if (sb.length() > 0) {
556                     sb.append('\n');
557                 }
558 
559                 sb.append("HTTP proxy user: " + httpProxyUser);
560             }
561 
562             if (httpProxyPassword != null) {
563                 if (sb.length() > 0) {
564                     sb.append('\n');
565                 }
566 
567                 sb.append("HTTP proxy password: " + httpProxyPassword);
568             }
569 
570             if (httpsProxyHost != null) {
571                 if (sb.length() > 0) {
572                     sb.append('\n');
573                 }
574 
575                 sb.append("HTTPS proxy: " + httpsProxyHost + ":" + httpsProxyPort);
576             }
577 
578             if (httpsProxyUser != null) {
579                 if (sb.length() > 0) {
580                     sb.append('\n');
581                 }
582 
583                 sb.append("HTTPS proxy user: " + httpsProxyUser);
584             }
585 
586             if (httpsProxyPassword != null) {
587                 if (sb.length() > 0) {
588                     sb.append('\n');
589                 }
590 
591                 sb.append("HTTPS proxy password: " + httpsProxyPassword);
592             }
593 
594             if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
595                 if (sb.length() > 0) {
596                     sb.append('\n');
597                 }
598 
599                 sb.append("Non proxy hosts: ");
600 
601                 boolean first = true;
602                 for (String host : nonProxyHosts) {
603                     if (!first) {
604                         sb.append(",");
605                     } else {
606                         first = false;
607                     }
608 
609                     sb.append(host);
610                 }
611             }
612 
613             return sb.toString();
614         }
615     }
616 }