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.message.BasicHttpRequest;
57  import org.apache.hc.core5.http.nio.AsyncDataConsumer;
58  import org.apache.hc.core5.http.nio.AsyncEntityProducer;
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   * responsbile 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 int statusCode = response.getCode();
140 
141                     state.currentRequest = null;
142                     switch (statusCode) {
143                         case HttpStatus.SC_MOVED_PERMANENTLY:
144                         case HttpStatus.SC_MOVED_TEMPORARILY:
145                             if (Method.POST.isSame(request.getMethod())) {
146                                 state.currentRequest = new BasicHttpRequest(Method.GET, redirectUri);
147                                 state.currentEntityProducer = null;
148                             }
149                             break;
150                         case HttpStatus.SC_SEE_OTHER:
151                             if (!Method.GET.isSame(request.getMethod()) && !Method.HEAD.isSame(request.getMethod())) {
152                                 state.currentRequest = new BasicHttpRequest(Method.GET, redirectUri);
153                                 state.currentEntityProducer = null;
154                             }
155                     }
156                     if (state.currentRequest == null) {
157                         state.currentRequest = new BasicHttpRequest(request.getMethod(), redirectUri);
158                     }
159                     state.currentRequest.setHeaders(scope.originalRequest.getHeaders());
160                     final HttpHost newTarget = URIUtils.extractHost(redirectUri);
161                     if (newTarget == null) {
162                         throw new ProtocolException("Redirect URI does not specify a valid host name: " + redirectUri);
163                     }
164 
165                     state.reroute = false;
166                     state.redirectURI = redirectUri;
167 
168                     if (!LangUtils.equals(currentRoute.getTargetHost(), newTarget)) {
169                         final HttpRoute newRoute = routePlanner.determineRoute(newTarget, clientContext);
170                         if (!LangUtils.equals(currentRoute, newRoute)) {
171                             state.reroute = true;
172                             final AuthExchange targetAuthExchange = clientContext.getAuthExchange(currentRoute.getTargetHost());
173                             if (LOG.isDebugEnabled()) {
174                                 LOG.debug("{}: resetting target auth state", exchangeId);
175                             }
176                             targetAuthExchange.reset();
177                             if (currentRoute.getProxyHost() != null) {
178                                 final AuthExchange proxyAuthExchange = clientContext.getAuthExchange(currentRoute.getProxyHost());
179                                 if (proxyAuthExchange.isConnectionBased()) {
180                                     if (LOG.isDebugEnabled()) {
181                                         LOG.debug("{}: resetting proxy auth state", exchangeId);
182                                     }
183                                     proxyAuthExchange.reset();
184                                 }
185                             }
186                             state.currentScope = new AsyncExecChain.Scope(scope.exchangeId, newRoute,
187                                     scope.originalRequest, scope.cancellableDependency, clientContext, scope.execRuntime);
188                         }
189                     }
190                 }
191                 if (state.redirectURI != null) {
192                     if (LOG.isDebugEnabled()) {
193                         LOG.debug("{}: redirecting to '{}' via {}", exchangeId, state.redirectURI, currentRoute);
194                     }
195                     return null;
196                 }
197                 return asyncExecCallback.handleResponse(response, entityDetails);
198             }
199 
200             @Override
201             public void handleInformationResponse(
202                     final HttpResponse response) throws HttpException, IOException {
203                 asyncExecCallback.handleInformationResponse(response);
204             }
205 
206             @Override
207             public void completed() {
208                 if (state.redirectURI == null) {
209                     asyncExecCallback.completed();
210                 } else {
211                     final AsyncEntityProducer entityProducer = state.currentEntityProducer;
212                     if (entityProducer != null) {
213                         entityProducer.releaseResources();
214                     }
215                     if (entityProducer != null && !entityProducer.isRepeatable()) {
216                         if (LOG.isDebugEnabled()) {
217                             LOG.debug("{}: cannot redirect non-repeatable request", exchangeId);
218                         }
219                         asyncExecCallback.completed();
220                     } else {
221                         try {
222                             if (state.reroute) {
223                                 scope.execRuntime.releaseEndpoint();
224                             }
225                             internalExecute(state, chain, asyncExecCallback);
226                         } catch (final IOException | HttpException ex) {
227                             asyncExecCallback.failed(ex);
228                         }
229                     }
230                 }
231             }
232 
233             @Override
234             public void failed(final Exception cause) {
235                 asyncExecCallback.failed(cause);
236             }
237 
238         });
239 
240     }
241 
242     @Override
243     public void execute(
244             final HttpRequest request,
245             final AsyncEntityProducer entityProducer,
246             final AsyncExecChain.Scope scope,
247             final AsyncExecChain chain,
248             final AsyncExecCallback asyncExecCallback) throws HttpException, IOException {
249         final HttpClientContext clientContext = scope.clientContext;
250         RedirectLocations redirectLocations = clientContext.getRedirectLocations();
251         if (redirectLocations == null) {
252             redirectLocations = new RedirectLocations();
253             clientContext.setAttribute(HttpClientContext.REDIRECT_LOCATIONS, redirectLocations);
254         }
255         redirectLocations.clear();
256 
257         final RequestConfig config = clientContext.getRequestConfig();
258 
259         final State state = new State();
260         state.maxRedirects = config.getMaxRedirects() > 0 ? config.getMaxRedirects() : 50;
261         state.redirectCount = 0;
262         state.currentRequest = request;
263         state.currentEntityProducer = entityProducer;
264         state.redirectLocations = redirectLocations;
265         state.currentScope = scope;
266 
267         internalExecute(state, chain, asyncExecCallback);
268     }
269 
270 }