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
18
19
20
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
40
41
42
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 }