1 /*
2  * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License").
5  * You may not use this file except in compliance with the License.
6  * A copy of the License is located at
7  *
8  *  http://aws.amazon.com/apache2.0
9  *
10  * or in the "license" file accompanying this file. This file is distributed
11  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
12  * express or implied. See the License for the specific language governing
13  * permissions and limitations under the License.
14  */
15 
16 package software.amazon.awssdk.http.apache.internal;
17 
18 import static software.amazon.awssdk.utils.StringUtils.lowerCase;
19 
20 import java.util.Set;
21 import org.apache.http.HttpException;
22 import org.apache.http.HttpHost;
23 import org.apache.http.HttpRequest;
24 import org.apache.http.impl.conn.DefaultRoutePlanner;
25 import org.apache.http.impl.conn.DefaultSchemePortResolver;
26 import org.apache.http.protocol.HttpContext;
27 import software.amazon.awssdk.annotations.SdkInternalApi;
28 
29 /**
30  * SdkProxyRoutePlanner delegates a Proxy Route Planner from the settings instead of the
31  * system properties. It will use the proxy created from proxyHost and proxyPort and
32  * filter the hosts who matches nonProxyHosts pattern.
33  */
34 @SdkInternalApi
35 public class SdkProxyRoutePlanner extends DefaultRoutePlanner {
36 
37     private HttpHost proxy;
38     private Set<String> hostPatterns;
39 
SdkProxyRoutePlanner(String proxyHost, int proxyPort, String proxyProtocol, Set<String> nonProxyHosts)40     public SdkProxyRoutePlanner(String proxyHost, int proxyPort, String proxyProtocol, Set<String> nonProxyHosts) {
41         super(DefaultSchemePortResolver.INSTANCE);
42         proxy = new HttpHost(proxyHost, proxyPort, proxyProtocol);
43         this.hostPatterns = nonProxyHosts;
44     }
45 
doesTargetMatchNonProxyHosts(HttpHost target)46     private boolean doesTargetMatchNonProxyHosts(HttpHost target) {
47         if (hostPatterns == null) {
48             return false;
49         }
50         String targetHost = lowerCase(target.getHostName());
51         for (String pattern : hostPatterns) {
52             if (targetHost.matches(pattern)) {
53                 return true;
54             }
55         }
56         return false;
57     }
58 
59     @Override
determineProxy( final HttpHost target, final HttpRequest request, final HttpContext context)60     protected HttpHost determineProxy(
61             final HttpHost target,
62             final HttpRequest request,
63             final HttpContext context) throws HttpException {
64 
65         return doesTargetMatchNonProxyHosts(target) ? null : proxy;
66     }
67 }
68