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  import java.io.IOException;
31  import java.net.ConnectException;
32  import java.net.InetSocketAddress;
33  import java.net.Socket;
34  import java.net.InetAddress;
35  import java.net.UnknownHostException;
36  
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
39  import org.apache.http.annotation.ThreadSafe;
40  
41  import org.apache.http.HttpHost;
42  import org.apache.http.params.HttpParams;
43  import org.apache.http.params.HttpConnectionParams;
44  import org.apache.http.protocol.HttpContext;
45  
46  import org.apache.http.conn.ConnectTimeoutException;
47  import org.apache.http.conn.HttpHostConnectException;
48  import org.apache.http.conn.HttpInetSocketAddress;
49  import org.apache.http.conn.OperatedClientConnection;
50  import org.apache.http.conn.ClientConnectionOperator;
51  import org.apache.http.conn.scheme.SchemeLayeredSocketFactory;
52  import org.apache.http.conn.scheme.Scheme;
53  import org.apache.http.conn.scheme.SchemeRegistry;
54  import org.apache.http.conn.scheme.SchemeSocketFactory;
55  
56  import org.apache.http.conn.DnsResolver;
57  
58  /**
59   * Default implementation of a {@link ClientConnectionOperator}. It uses a {@link SchemeRegistry}
60   * to look up {@link SchemeSocketFactory} objects.
61   * <p>
62   * This connection operator is multihome network aware and will attempt to retry failed connects
63   * against all known IP addresses sequentially until the connect is successful or all known
64   * addresses fail to respond. Please note the same
65   * {@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT} value will be used
66   * for each connection attempt, so in the worst case the total elapsed time before timeout
67   * can be <code>CONNECTION_TIMEOUT * n</code> where <code>n</code> is the number of IP addresses
68   * of the given host. One can disable multihome support by overriding
69   * the {@link #resolveHostname(String)} method and returning only one IP address for the given
70   * host name.
71   * <p>
72   * The following parameters can be used to customize the behavior of this
73   * class:
74   * <ul>
75   *  <li>{@link org.apache.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
76   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
77   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_LINGER}</li>
78   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SO_REUSEADDR}</li>
79   *  <li>{@link org.apache.http.params.CoreConnectionPNames#TCP_NODELAY}</li>
80   *  <li>{@link org.apache.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
81   *  <li>{@link org.apache.http.params.CoreConnectionPNames#CONNECTION_TIMEOUT}</li>
82   *  <li>{@link org.apache.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
83   * </ul>
84   *
85   * @since 4.0
86   */
87  @ThreadSafe
88  public class DefaultClientConnectionOperator implements ClientConnectionOperator {
89  
90      private final Log log = LogFactory.getLog(getClass());
91  
92      /** The scheme registry for looking up socket factories. */
93      protected final SchemeRegistry schemeRegistry; // @ThreadSafe
94  
95      /** the custom-configured DNS lookup mechanism. */
96      protected final DnsResolver dnsResolver;
97  
98      /**
99       * Creates a new client connection operator for the given scheme registry.
100      *
101      * @param schemes   the scheme registry
102      *
103      * @since 4.2
104      */
105     public DefaultClientConnectionOperator(final SchemeRegistry schemes) {
106         if (schemes == null) {
107             throw new IllegalArgumentException("Scheme registry amy not be null");
108         }
109         this.schemeRegistry = schemes;
110         this.dnsResolver = new SystemDefaultDnsResolver();
111     }
112 
113     /**
114     * Creates a new client connection operator for the given scheme registry
115     * and the given custom DNS lookup mechanism.
116     *
117     * @param schemes
118     *            the scheme registry
119     * @param dnsResolver
120     *            the custom DNS lookup mechanism
121     */
122     public DefaultClientConnectionOperator(final SchemeRegistry schemes,final DnsResolver dnsResolver) {
123         if (schemes == null) {
124             throw new IllegalArgumentException(
125                      "Scheme registry may not be null");
126         }
127 
128         if(dnsResolver == null){
129             throw new IllegalArgumentException("DNS resolver may not be null");
130         }
131 
132         this.schemeRegistry = schemes;
133         this.dnsResolver = dnsResolver;
134     }
135 
136     public OperatedClientConnection createConnection() {
137         return new DefaultClientConnection();
138     }
139 
140     public void openConnection(
141             final OperatedClientConnection conn,
142             final HttpHost target,
143             final InetAddress local,
144             final HttpContext context,
145             final HttpParams params) throws IOException {
146         if (conn == null) {
147             throw new IllegalArgumentException("Connection may not be null");
148         }
149         if (target == null) {
150             throw new IllegalArgumentException("Target host may not be null");
151         }
152         if (params == null) {
153             throw new IllegalArgumentException("Parameters may not be null");
154         }
155         if (conn.isOpen()) {
156             throw new IllegalStateException("Connection must not be open");
157         }
158 
159         Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
160         SchemeSocketFactory sf = schm.getSchemeSocketFactory();
161 
162         InetAddress[] addresses = resolveHostname(target.getHostName());
163         int port = schm.resolvePort(target.getPort());
164         for (int i = 0; i < addresses.length; i++) {
165             InetAddress address = addresses[i];
166             boolean last = i == addresses.length - 1;
167 
168             Socket sock = sf.createSocket(params);
169             conn.opening(sock, target);
170 
171             InetSocketAddress remoteAddress = new HttpInetSocketAddress(target, address, port);
172             InetSocketAddress localAddress = null;
173             if (local != null) {
174                 localAddress = new InetSocketAddress(local, 0);
175             }
176             if (this.log.isDebugEnabled()) {
177                 this.log.debug("Connecting to " + remoteAddress);
178             }
179             try {
180                 Socket connsock = sf.connectSocket(sock, remoteAddress, localAddress, params);
181                 if (sock != connsock) {
182                     sock = connsock;
183                     conn.opening(sock, target);
184                 }
185                 prepareSocket(sock, context, params);
186                 conn.openCompleted(sf.isSecure(sock), params);
187                 return;
188             } catch (ConnectException ex) {
189                 if (last) {
190                     throw new HttpHostConnectException(target, ex);
191                 }
192             } catch (ConnectTimeoutException ex) {
193                 if (last) {
194                     throw ex;
195                 }
196             }
197             if (this.log.isDebugEnabled()) {
198                 this.log.debug("Connect to " + remoteAddress + " timed out. " +
199                         "Connection will be retried using another IP address");
200             }
201         }
202     }
203 
204     public void updateSecureConnection(
205             final OperatedClientConnection conn,
206             final HttpHost target,
207             final HttpContext context,
208             final HttpParams params) throws IOException {
209         if (conn == null) {
210             throw new IllegalArgumentException("Connection may not be null");
211         }
212         if (target == null) {
213             throw new IllegalArgumentException("Target host may not be null");
214         }
215         if (params == null) {
216             throw new IllegalArgumentException("Parameters may not be null");
217         }
218         if (!conn.isOpen()) {
219             throw new IllegalStateException("Connection must be open");
220         }
221 
222         final Scheme schm = schemeRegistry.getScheme(target.getSchemeName());
223         if (!(schm.getSchemeSocketFactory() instanceof SchemeLayeredSocketFactory)) {
224             throw new IllegalArgumentException
225                 ("Target scheme (" + schm.getName() +
226                  ") must have layered socket factory.");
227         }
228 
229         SchemeLayeredSocketFactory lsf = (SchemeLayeredSocketFactory) schm.getSchemeSocketFactory();
230         Socket sock;
231         try {
232             sock = lsf.createLayeredSocket(
233                     conn.getSocket(), target.getHostName(), target.getPort(), params);
234         } catch (ConnectException ex) {
235             throw new HttpHostConnectException(target, ex);
236         }
237         prepareSocket(sock, context, params);
238         conn.update(sock, target, lsf.isSecure(sock), params);
239     }
240 
241     /**
242      * Performs standard initializations on a newly created socket.
243      *
244      * @param sock      the socket to prepare
245      * @param context   the context for the connection
246      * @param params    the parameters from which to prepare the socket
247      *
248      * @throws IOException      in case of an IO problem
249      */
250     protected void prepareSocket(
251             final Socket sock,
252             final HttpContext context,
253             final HttpParams params) throws IOException {
254         sock.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
255         sock.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
256 
257         int linger = HttpConnectionParams.getLinger(params);
258         if (linger >= 0) {
259             sock.setSoLinger(linger > 0, linger);
260         }
261     }
262 
263     /**
264      * Resolves the given host name to an array of corresponding IP addresses, based on the
265      * configured name service on the provided DNS resolver. If one wasn't provided, the system
266      * configuration is used.
267      *
268      * @param host host name to resolve
269      * @return array of IP addresses
270      * @exception  UnknownHostException  if no IP address for the host could be determined.
271      *
272      * @see DnsResolver
273      * @see SystemDefaultDnsResolver
274      *
275      * @since 4.1
276      */
277     protected InetAddress[] resolveHostname(final String host) throws UnknownHostException {
278             return dnsResolver.resolve(host);
279     }
280 
281 }
282