View Javadoc
1   package com.atlassian.sal.core.net;
2   
3   import org.apache.commons.lang3.StringUtils;
4   import org.slf4j.Logger;
5   import org.slf4j.LoggerFactory;
6   
7   import javax.annotation.Nonnull;
8   import javax.annotation.Nullable;
9   import java.net.URI;
10  import java.net.URISyntaxException;
11  import java.util.Arrays;
12  
13  public class ProxyUtil {
14      private static final Logger log = LoggerFactory.getLogger(ProxyUtil.class);
15  
16      /**
17       * Check if proxy configuration requires authentication before sending request to requestUrl
18       * @param proxyConfig proxy configuration
19       * @param requestUrl url
20       * @return true if proxy authentication should be requested before fetching requestUrl
21       */
22      static boolean requiresAuthentication(final ProxyConfig proxyConfig, final String requestUrl) {
23          if (proxyConfig.getNonProxyHosts().length != 0
24                  && proxyConfig.requiresAuthentication()) {
25              try {
26                  final String host = new URI(requestUrl).getHost();
27                  if (!shouldBeProxied(host, proxyConfig.getNonProxyHosts())) {
28                      return false;
29                  }
30              }
31              catch (URISyntaxException e) {
32                  log.debug("Can't get host value from {}", requestUrl);
33              }
34          }
35          return proxyConfig.requiresAuthentication();
36      }
37  
38      /**
39       * Check if host should be proxied.
40       * @param host to be checked
41       * @param nonProxyHosts array of nonProxyHosts, wildcards supported
42       * @return true if proxy server should be used to access host
43       */
44      static boolean shouldBeProxied(@Nullable String host, @Nonnull String[] nonProxyHosts) {
45          if (StringUtils.isBlank(host)) {
46              return false;
47          }
48          try {
49              for (String nonProxyHost : nonProxyHosts) {
50                  String pattern = nonProxyHost.replace(".", "\\.")
51                          .replace("*", ".*")
52                          .replace("[", "\\[")
53                          .replace("]", "\\]");
54                  if (host.matches(pattern)) {
55                      return false;
56                  }
57              }
58          } catch (Exception e) {
59              log.debug("Failed to match host {} against non proxy hosts {}, will assume host should be proxied: {}",
60                      host, Arrays.toString(nonProxyHosts), e.getMessage());
61          }
62          return true;
63      }
64  }