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  package org.apache.hc.client5.http.impl.async;
28  
29  import java.io.IOException;
30  import java.net.URI;
31  
32  import org.apache.hc.client5.http.CircularRedirectException;
33  import org.apache.hc.client5.http.HttpRoute;
34  import org.apache.hc.client5.http.RedirectException;
35  import org.apache.hc.client5.http.async.AsyncExecCallback;
36  import org.apache.hc.client5.http.async.AsyncExecChain;
37  import org.apache.hc.client5.http.async.AsyncExecChainHandler;
38  import org.apache.hc.client5.http.auth.AuthExchange;
39  import org.apache.hc.client5.http.config.RequestConfig;
40  import org.apache.hc.client5.http.protocol.HttpClientContext;
41  import org.apache.hc.client5.http.protocol.RedirectLocations;
42  import org.apache.hc.client5.http.protocol.RedirectStrategy;
43  import org.apache.hc.client5.http.routing.HttpRoutePlanner;
44  import org.apache.hc.client5.http.utils.URIUtils;
45  import org.apache.hc.core5.annotation.Contract;
46  import org.apache.hc.core5.annotation.Internal;
47  import org.apache.hc.core5.annotation.ThreadingBehavior;
48  import org.apache.hc.core5.http.EntityDetails;
49  import org.apache.hc.core5.http.HttpException;
50  import org.apache.hc.core5.http.HttpHost;
51  import org.apache.hc.core5.http.HttpRequest;
52  import org.apache.hc.core5.http.HttpResponse;
53  import org.apache.hc.core5.http.HttpStatus;
54  import org.apache.hc.core5.http.Method;
55  import org.apache.hc.core5.http.ProtocolException;
56  import org.apache.hc.core5.http.nio.AsyncDataConsumer;
57  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
58  import org.apache.hc.core5.http.support.BasicRequestBuilder;
59  import org.apache.hc.core5.util.LangUtils;
60  import org.slf4j.Logger;
61  import org.slf4j.LoggerFactory;
62  
63  /**
64   * Request execution handler in the asynchronous request execution chain
65   * responsible for handling of request redirects.
66   * <p>
67   * Further responsibilities such as communication with the opposite
68   * endpoint is delegated to the next executor in the request execution
69   * chain.
70   * </p>
71   *
72   * @since 5.0
73   */
74  @Contract(threading = ThreadingBehavior.STATELESS)
75  @Internal
76  public final class AsyncRedirectExec implements AsyncExecChainHandler {
77  
78      private static final Logger LOG = LoggerFactory.getLogger(AsyncRedirectExec.class);
79  
80      private final HttpRoutePlanner routePlanner;
81      private final RedirectStrategy redirectStrategy;
82  
83      AsyncRedirectExec(final HttpRoutePlanner routePlanner, final RedirectStrategy redirectStrategy) {
84          this.routePlanner = routePlanner;
85          this.redirectStrategy = redirectStrategy;
86      }
87  
88      private static class State {
89  
90          volatile URI redirectURI;
91          volatile int maxRedirects;
92          volatile int redirectCount;
93          volatile HttpRequest currentRequest;
94          volatile AsyncEntityProducer currentEntityProducer;
95          volatile RedirectLocations redirectLocations;
96          volatile AsyncExecChain.Scope currentScope;
97          volatile boolean reroute;
98  
99      }
100 
101     private void internalExecute(
102             final State state,
103             final AsyncExecChain chain,
104             final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
105 
106         final HttpRequest request = state.currentRequest;
107         final AsyncEntityProducer entityProducer = state.currentEntityProducer;
108         final AsyncExecChain.Scope scope = state.currentScope;
109         final HttpClientContext clientContext = scope.clientContext;
110         final String exchangeId = scope.exchangeId;
111         final HttpRoute currentRoute = scope.route;
112         chain.proceed(request, entityProducer, scope, new AsyncExecCallback() {
113 
114             @Override
115             public AsyncDataConsumer handleResponse(
116                     final HttpResponse response,
117                     final EntityDetails entityDetails) throws HttpException, IOException {
118 
119                 state.redirectURI = null;
120                 final RequestConfig config = clientContext.getRequestConfig();
121                 if (config.isRedirectsEnabled() && redirectStrategy.isRedirected(request, response, clientContext)) {
122                     if (state.redirectCount >= state.maxRedirects) {
123                         throw new RedirectException("Maximum redirects (" + state.maxRedirects + ") exceeded");
124                     }
125 
126                     state.redirectCount++;
127 
128                     final URI redirectUri = redirectStrategy.getLocationURI(request, response, clientContext);
129                     if (LOG.isDebugEnabled()) {
130                         LOG.debug("{} redirect requested to location '{}'", exchangeId, redirectUri);
131                     }
132                     if (!config.isCircularRedirectsAllowed()) {
133                         if (state.redirectLocations.contains(redirectUri)) {
134                             throw new CircularRedirectException("Circular redirect to '" + redirectUri + "'");
135                         }
136                     }
137                     state.redirectLocations.add(redirectUri);
138 
139                     final HttpHost newTarget = URIUtils.extractHost(redirectUri);
140                     if (newTarget == null) {
141                         throw new ProtocolException("Redirect URI does not specify a valid host name: " + redirectUri);
142                     }
143 
144                     final int statusCode = response.getCode();
145                     final BasicRequestBuilder redirectBuilder;
146                     switch (statusCode) {
147                         case HttpStatus.SC_MOVED_PERMANENTLY:
148                         case HttpStatus.SC_MOVED_TEMPORARILY:
149                             if (Method.POST.isSame(request.getMethod())) {
150                                 redirectBuilder = BasicRequestBuilder.get();
151                                 state.currentEntityProducer = null;
152                             } else {
153                                 redirectBuilder = BasicRequestBuilder.copy(scope.originalRequest);
154                             }
155                             break;
156                         case HttpStatus.SC_SEE_OTHER:
157                             if (!Method.GET.isSame(request.getMethod()) && !Method.HEAD.isSame(request.getMethod())) {
158                                 redirectBuilder = BasicRequestBuilder.get();
159                                 state.currentEntityProducer = null;
160                             } else {
161                                 redirectBuilder = BasicRequestBuilder.copy(scope.originalRequest);
162                             }
163                             break;
164                         default:
165                             redirectBuilder = BasicRequestBuilder.copy(scope.originalRequest);
166                     }
167                     redirectBuilder.setUri(redirectUri);
168                     state.reroute = false;
169                     state.redirectURI = redirectUri;
170                     state.currentRequest = redirectBuilder.build();
171 
172                     if (!LangUtils.equals(currentRoute.getTargetHost(), newTarget)) {
173                         final HttpRoute newRoute = routePlanner.determineRoute(newTarget, clientContext);
174                         if (!LangUtils.equals(currentRoute, newRoute)) {
175                             state.reroute = true;
176                             final AuthExchange targetAuthExchange = clientContext.getAuthExchange(currentRoute.getTargetHost());
177                             if (LOG.isDebugEnabled()) {
178                                 LOG.debug("{} resetting target auth state", exchangeId);
179                             }
180                             targetAuthExchange.reset();
181                             if (currentRoute.getProxyHost() != null) {
182                                 final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(currentRoute.getProxyHost());
183                                 if (proxyAuthExchange.isConnectionBased()) {
184                                     if (LOG.isDebugEnabled()) {
185                                         LOG.debug("{} resetting proxy auth state", exchangeId);
186                                     }
187                                     proxyAuthExchange.reset();
188                                 }
189                             }
190                             state.currentScope = new AsyncExecChain.Scope(
191                                     scope.exchangeId,
192                                     newRoute,
193                                     scope.originalRequest,
194                                     scope.cancellableDependency,
195                                     scope.clientContext,
196                                     scope.execRuntime,
197                                     scope.scheduler,
198                                     scope.execCount);
199                         }
200                     }
201                 }
202                 if (state.redirectURI != null) {
203                     if (LOG.isDebugEnabled()) {
204                         LOG.debug("{} redirecting to '{}' via {}", exchangeId, state.redirectURI, currentRoute);
205                     }
206                     return null;
207                 }
208                 return asyncExecCallback.handleResponse(response, entityDetails);
209             }
210 
211             @Override
212             public void handleInformationResponse(
213                     final HttpResponse response) throws HttpException, IOException {
214                 asyncExecCallback.handleInformationResponse(response);
215             }
216 
217             @Override
218             public void completed() {
219                 if (state.redirectURI == null) {
220                     asyncExecCallback.completed();
221                 } else {
222                     final AsyncEntityProducer entityProducer = state.currentEntityProducer;
223                     if (entityProducer != null) {
224                         entityProducer.releaseResources();
225                     }
226                     if (entityProducer != null && !entityProducer.isRepeatable()) {
227                         if (LOG.isDebugEnabled()) {
228                             LOG.debug("{} cannot redirect non-repeatable request", exchangeId);
229                         }
230                         asyncExecCallback.completed();
231                     } else {
232                         try {
233                             if (state.reroute) {
234                                 scope.execRuntime.releaseEndpoint();
235                             }
236                             internalExecute(state, chain, asyncExecCallback);
237                         } catch (final IOException | HttpException ex) {
238                             asyncExecCallback.failed(ex);
239                         }
240                     }
241                 }
242             }
243 
244             @Override
245             public void failed(final Exception cause) {
246                 asyncExecCallback.failed(cause);
247             }
248 
249         });
250 
251     }
252 
253     @Override
254     public void execute(
255             final HttpRequest request,
256             final AsyncEntityProducer entityProducer,
257             final AsyncExecChain.Scope scope,
258             final AsyncExecChain chain,
259             final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
260         final HttpClientContext clientContext = scope.clientContext;
261         RedirectLocations redirectLocations = clientContext.getRedirectLocations();
262         if (redirectLocations == null) {
263             redirectLocations = new RedirectLocations();
264             clientContext.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
265         }
266         redirectLocations.clear();
267 
268         final RequestConfig config = clientContext.getRequestConfig();
269 
270         final State state = new State();
271         state.maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
272         state.redirectCount = 0;
273         state.currentRequest = request;
274         state.currentEntityProducer = entityProducer;
275         state.redirectLocations = redirectLocations;
276         state.currentScope = scope;
277 
278         internalExecute(state, chain, asyncExecCallback);
279     }
280 
281 }