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.execchain;
29  
30  import java.io.IOException;
31  import java.net.URI;
32  import java.util.List;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.http.HttpEntityEnclosingRequest;
37  import org.apache.http.HttpException;
38  import org.apache.http.HttpHost;
39  import org.apache.http.HttpRequest;
40  import org.apache.http.ProtocolException;
41  import org.apache.http.annotation.Contract;
42  import org.apache.http.annotation.ThreadingBehavior;
43  import org.apache.http.auth.AuthState;
44  import org.apache.http.client.RedirectException;
45  import org.apache.http.client.RedirectStrategy;
46  import org.apache.http.client.config.RequestConfig;
47  import org.apache.http.client.methods.CloseableHttpResponse;
48  import org.apache.http.client.methods.HttpExecutionAware;
49  import org.apache.http.client.methods.HttpRequestWrapper;
50  import org.apache.http.client.protocol.HttpClientContext;
51  import org.apache.http.client.utils.URIUtils;
52  import org.apache.http.conn.routing.HttpRoute;
53  import org.apache.http.conn.routing.HttpRoutePlanner;
54  import org.apache.http.util.Args;
55  import org.apache.http.util.EntityUtils;
56  
57  /**
58   * Request executor in the request execution chain that is responsible
59   * for handling of request redirects.
60   * <p>
61   * Further responsibilities such as communication with the opposite
62   * endpoint is delegated to the next executor in the request execution
63   * chain.
64   * </p>
65   *
66   * @since 4.3
67   */
68  @Contract(threading = ThreadingBehavior.IMMUTABLE_CONDITIONAL)
69  public class RedirectExec implements ClientExecChain {
70  
71      private final Log log = LogFactory.getLog(getClass());
72  
73      private final ClientExecChain requestExecutor;
74      private final RedirectStrategy redirectStrategy;
75      private final HttpRoutePlanner routePlanner;
76  
77      public RedirectExec(
78              final ClientExecChain requestExecutor,
79              final HttpRoutePlanner routePlanner,
80              final RedirectStrategy redirectStrategy) {
81          super();
82          Args.notNull(requestExecutor, "HTTP client request executor");
83          Args.notNull(routePlanner, "HTTP route planner");
84          Args.notNull(redirectStrategy, "HTTP redirect strategy");
85          this.requestExecutor = requestExecutor;
86          this.routePlanner = routePlanner;
87          this.redirectStrategy = redirectStrategy;
88      }
89  
90      @Override
91      public CloseableHttpResponse execute(
92              final HttpRoute route,
93              final HttpRequestWrapper request,
94              final HttpClientContext context,
95              final HttpExecutionAware execAware) throws IOException, HttpException {
96          Args.notNull(route, "HTTP route");
97          Args.notNull(request, "HTTP request");
98          Args.notNull(context, "HTTP context");
99  
100         final List<URI> redirectLocations = context.getRedirectLocations();
101         if (redirectLocations != null) {
102             redirectLocations.clear();
103         }
104 
105         final RequestConfig config = context.getRequestConfig();
106         final int maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
107         HttpRoute currentRoute = route;
108         HttpRequestWrapper currentRequest = request;
109         for (int redirectCount = 0;;) {
110             final CloseableHttpResponse response = requestExecutor.execute(
111                     currentRoute, currentRequest, context, execAware);
112             try {
113                 if (config.isRedirectsEnabled() &&
114                         this.redirectStrategy.isRedirected(currentRequest.getOriginal(), response, context)) {
115                     if (!RequestEntityProxy.isRepeatable(currentRequest)) {
116                         if (log.isDebugEnabled()) {
117                             log.debug("Cannot redirect non-repeatable request");
118                         }
119                         return response;
120                     }
121                     if (redirectCount >= maxRedirects) {
122                         throw new RedirectException("Maximum redirects ("+ maxRedirects + ") exceeded");
123                     }
124                     redirectCount++;
125 
126                     final HttpRequest redirect = this.redirectStrategy.getRedirect(
127                             currentRequest.getOriginal(), response, context);
128                     if (!redirect.headerIterator().hasNext()) {
129                         final HttpRequest original = request.getOriginal();
130                         redirect.setHeaders(original.getAllHeaders());
131                     }
132                     currentRequest = HttpRequestWrapper.wrap(redirect);
133 
134                     if (currentRequest instanceof HttpEntityEnclosingRequest) {
135                         RequestEntityProxy.enhance((HttpEntityEnclosingRequest) currentRequest);
136                     }
137 
138                     final URI uri = currentRequest.getURI();
139                     final HttpHost newTarget = URIUtils.extractHost(uri);
140                     if (newTarget == null) {
141                         throw new ProtocolException("Redirect URI does not specify a valid host name: " +
142                                 uri);
143                     }
144 
145                     // Reset virtual host and auth states if redirecting to another host
146                     if (!currentRoute.getTargetHost().equals(newTarget)) {
147                         final AuthState targetAuthState = context.getTargetAuthState();
148                         if (targetAuthState != null) {
149                             this.log.debug("Resetting target auth state");
150                             targetAuthState.reset();
151                         }
152                         final AuthState proxyAuthState = context.getProxyAuthState();
153                         if (proxyAuthState != null && proxyAuthState.isConnectionBased()) {
154                             this.log.debug("Resetting proxy auth state");
155                             proxyAuthState.reset();
156                         }
157                     }
158 
159                     currentRoute = this.routePlanner.determineRoute(newTarget, currentRequest, context);
160                     if (this.log.isDebugEnabled()) {
161                         this.log.debug("Redirecting to '" + uri + "' via " + currentRoute);
162                     }
163                     EntityUtils.consume(response.getEntity());
164                     response.close();
165                 } else {
166                     return response;
167                 }
168             } catch (final RuntimeException ex) {
169                 response.close();
170                 throw ex;
171             } catch (final IOException ex) {
172                 response.close();
173                 throw ex;
174             } catch (final HttpException ex) {
175                 // Protocol exception related to a direct.
176                 // The underlying connection may still be salvaged.
177                 try {
178                     EntityUtils.consume(response.getEntity());
179                 } catch (final IOException ioex) {
180                     this.log.debug("I/O error while releasing connection", ioex);
181                 } finally {
182                     response.close();
183                 }
184                 throw ex;
185             }
186         }
187     }
188 
189 }