View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.impl.conn;
29  
30  
31  import java.net.InetAddress;
32  import java.net.InetSocketAddress;
33  import java.net.Proxy;
34  import java.net.ProxySelector;
35  import java.net.URI;
36  import java.net.URISyntaxException;
37  import java.util.List;
38  
39  import org.apache.http.HttpException;
40  import org.apache.http.HttpHost;
41  import org.apache.http.HttpRequest;
42  import org.apache.http.annotation.NotThreadSafe;
43  import org.apache.http.conn.params.ConnRouteParams;
44  import org.apache.http.conn.routing.HttpRoute;
45  import org.apache.http.conn.routing.HttpRoutePlanner;
46  import org.apache.http.conn.scheme.Scheme;
47  import org.apache.http.conn.scheme.SchemeRegistry;
48  import org.apache.http.protocol.HttpContext;
49  import org.apache.http.util.Args;
50  import org.apache.http.util.Asserts;
51  
52  
53  /**
54   * Default implementation of an {@link HttpRoutePlanner}.
55   * This implementation is based on {@link java.net.ProxySelector}.
56   * By default, it will pick up the proxy settings of the JVM, either
57   * from system properties or from the browser running the application.
58   * Additionally, it interprets some
59   * {@link org.apache.http.conn.params.ConnRoutePNames parameters},
60   * though not the {@link
61   * org.apache.http.conn.params.ConnRoutePNames#DEFAULT_PROXY DEFAULT_PROXY}.
62   * <p>
63   * The following parameters can be used to customize the behavior of this
64   * class:
65   * <ul>
66   *  <li>{@link org.apache.http.conn.params.ConnRoutePNames#LOCAL_ADDRESS}</li>
67   *  <li>{@link org.apache.http.conn.params.ConnRoutePNames#FORCED_ROUTE}</li>
68   * </ul>
69   *
70   * @since 4.0
71   *
72   * @deprecated (4.3) use {@link SystemDefaultRoutePlanner}
73   */
74  @NotThreadSafe // e.g [gs]etProxySelector()
75  @Deprecated
76  public class ProxySelectorRoutePlanner implements HttpRoutePlanner {
77  
78      /** The scheme registry. */
79      protected final SchemeRegistry schemeRegistry; // @ThreadSafe
80  
81      /** The proxy selector to use, or {@code null} for system default. */
82      protected ProxySelector proxySelector;
83  
84      /**
85       * Creates a new proxy selector route planner.
86       *
87       * @param schreg    the scheme registry
88       * @param prosel    the proxy selector, or
89       *                  {@code null} for the system default
90       */
91      public ProxySelectorRoutePlanner(final SchemeRegistry schreg,
92                                       final ProxySelector prosel) {
93          Args.notNull(schreg, "SchemeRegistry");
94          schemeRegistry = schreg;
95          proxySelector  = prosel;
96      }
97  
98      /**
99       * Obtains the proxy selector to use.
100      *
101      * @return the proxy selector, or {@code null} for the system default
102      */
103     public ProxySelector getProxySelector() {
104         return this.proxySelector;
105     }
106 
107     /**
108      * Sets the proxy selector to use.
109      *
110      * @param prosel    the proxy selector, or
111      *                  {@code null} to use the system default
112      */
113     public void setProxySelector(final ProxySelector prosel) {
114         this.proxySelector = prosel;
115     }
116 
117     @Override
118     public HttpRoute determineRoute(final HttpHost target,
119                                     final HttpRequest request,
120                                     final HttpContext context)
121         throws HttpException {
122 
123         Args.notNull(request, "HTTP request");
124 
125         // If we have a forced route, we can do without a target.
126         HttpRoute route =
127             ConnRouteParams.getForcedRoute(request.getParams());
128         if (route != null) {
129             return route;
130         }
131 
132         // If we get here, there is no forced route.
133         // So we need a target to compute a route.
134 
135         Asserts.notNull(target, "Target host");
136 
137         final InetAddress local =
138             ConnRouteParams.getLocalAddress(request.getParams());
139         final HttpHost proxy = determineProxy(target, request, context);
140 
141         final Scheme schm =
142             this.schemeRegistry.getScheme(target.getSchemeName());
143         // as it is typically used for TLS/SSL, we assume that
144         // a layered scheme implies a secure connection
145         final boolean secure = schm.isLayered();
146 
147         if (proxy == null) {
148             route = new HttpRoute(target, local, secure);
149         } else {
150             route = new HttpRoute(target, local, proxy, secure);
151         }
152         return route;
153     }
154 
155     /**
156      * Determines a proxy for the given target.
157      *
158      * @param target    the planned target, never {@code null}
159      * @param request   the request to be sent, never {@code null}
160      * @param context   the context, or {@code null}
161      *
162      * @return  the proxy to use, or {@code null} for a direct route
163      *
164      * @throws HttpException
165      *         in case of system proxy settings that cannot be handled
166      */
167     protected HttpHost determineProxy(final HttpHost    target,
168                                       final HttpRequest request,
169                                       final HttpContext context)
170         throws HttpException {
171 
172         // the proxy selector can be 'unset', so we better deal with null here
173         ProxySelector psel = this.proxySelector;
174         if (psel == null) {
175             psel = ProxySelector.getDefault();
176         }
177         if (psel == null) {
178             return null;
179         }
180 
181         URI targetURI = null;
182         try {
183             targetURI = new URI(target.toURI());
184         } catch (final URISyntaxException usx) {
185             throw new HttpException
186                 ("Cannot convert host to URI: " + target, usx);
187         }
188         final List<Proxy> proxies = psel.select(targetURI);
189 
190         final Proxy p = chooseProxy(proxies, target, request, context);
191 
192         HttpHost result = null;
193         if (p.type() == Proxy.Type.HTTP) {
194             // convert the socket address to an HttpHost
195             if (!(p.address() instanceof InetSocketAddress)) {
196                 throw new HttpException
197                     ("Unable to handle non-Inet proxy address: "+p.address());
198             }
199             final InetSocketAddress isa = (InetSocketAddress) p.address();
200             // assume default scheme (http)
201             result = new HttpHost(getHost(isa), isa.getPort());
202         }
203 
204         return result;
205     }
206 
207     /**
208      * Obtains a host from an {@link InetSocketAddress}.
209      *
210      * @param isa       the socket address
211      *
212      * @return  a host string, either as a symbolic name or
213      *          as a literal IP address string
214      * <p>
215      * (TODO: determine format for IPv6 addresses, with or without [brackets])
216      * </p>
217      */
218     protected String getHost(final InetSocketAddress isa) {
219 
220         //@@@ Will this work with literal IPv6 addresses, or do we
221         //@@@ need to wrap these in [] for the string representation?
222         //@@@ Having it in this method at least allows for easy workarounds.
223        return isa.isUnresolved() ?
224             isa.getHostName() : isa.getAddress().getHostAddress();
225 
226     }
227 
228     /**
229      * Chooses a proxy from a list of available proxies.
230      * The default implementation just picks the first non-SOCKS proxy
231      * from the list. If there are only SOCKS proxies,
232      * {@link Proxy#NO_PROXY Proxy.NO_PROXY} is returned.
233      * Derived classes may implement more advanced strategies,
234      * such as proxy rotation if there are multiple options.
235      *
236      * @param proxies   the list of proxies to choose from,
237      *                  never {@code null} or empty
238      * @param target    the planned target, never {@code null}
239      * @param request   the request to be sent, never {@code null}
240      * @param context   the context, or {@code null}
241      *
242      * @return  a proxy type
243      */
244     protected Proxy chooseProxy(final List<Proxy> proxies,
245                                 final HttpHost    target,
246                                 final HttpRequest request,
247                                 final HttpContext context) {
248         Args.notEmpty(proxies, "List of proxies");
249 
250         Proxy result = null;
251 
252         // check the list for one we can use
253         for (int i=0; (result == null) && (i < proxies.size()); i++) {
254 
255             final Proxy p = proxies.get(i);
256             switch (p.type()) {
257 
258             case DIRECT:
259             case HTTP:
260                 result = p;
261                 break;
262 
263             case SOCKS:
264                 // SOCKS hosts are not handled on the route level.
265                 // The socket may make use of the SOCKS host though.
266                 break;
267             }
268         }
269 
270         if (result == null) {
271             //@@@ log as warning or info that only a socks proxy is available?
272             // result can only be null if all proxies are socks proxies
273             // socks proxies are not handled on the route planning level
274             result = Proxy.NO_PROXY;
275         }
276 
277         return result;
278     }
279 
280 }
281