Skip to content

Commit 2777d03

Browse files
committed
better organization
1 parent 36a85c5 commit 2777d03

8 files changed

Lines changed: 342 additions & 281 deletions

File tree

httpclient5/src/main/java/org/apache/hc/client5/http/async/AsyncExecRuntime.java

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,18 @@ Cancellable execute(
175175
*/
176176
void markConnectionNonReusable();
177177

178+
/**
179+
* Returns the route that has already been established by the connection pool,
180+
* or {@code null} if route completion is not handled at the pool level.
181+
*
182+
* @return the established route, or {@code null}.
183+
*
184+
* @since 5.7
185+
*/
186+
default HttpRoute getEstablishedRoute() {
187+
return null;
188+
}
189+
178190
/**
179191
* Forks this runtime for parallel execution.
180192
*

httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java

Lines changed: 4 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,6 @@
4646
import org.apache.hc.client5.http.auth.AuthenticationException;
4747
import org.apache.hc.client5.http.auth.ChallengeType;
4848
import org.apache.hc.client5.http.auth.MalformedChallengeException;
49-
import org.apache.hc.client5.http.config.RequestConfig;
5049
import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;
5150
import org.apache.hc.client5.http.impl.auth.AuthenticationHandler;
5251
import org.apache.hc.client5.http.impl.routing.BasicRouteDirector;
@@ -250,13 +249,9 @@ public void cancelled() {
250249
public void completed(final AsyncExecRuntime execRuntime) {
251250
final HttpHost proxy = route.getProxyHost();
252251
tracker.connectProxy(proxy, route.isSecure() && !route.isTunnelled());
253-
if (route.isTunnelled() && execRuntime instanceof InternalH2AsyncExecRuntime) {
254-
if (route.getHopCount() > 2) {
255-
asyncExecCallback.failed(new HttpException("Proxy chains are not supported"));
256-
return;
257-
}
252+
if (route.isTunnelled() && execRuntime.getEstablishedRoute() != null) {
258253
if (LOG.isDebugEnabled()) {
259-
LOG.debug("{} H2 tunnel to target already established by connection pool", exchangeId);
254+
LOG.debug("{} tunnel to target already established by connection pool", exchangeId);
260255
}
261256
tracker.tunnelTarget(false);
262257
if (route.isLayered()) {
@@ -532,31 +527,8 @@ private boolean needAuthentication(
532527
final HttpHost proxy,
533528
final HttpResponse response,
534529
final HttpClientContext context) throws AuthenticationException, MalformedChallengeException {
535-
final RequestConfig config = context.getRequestConfigOrDefault();
536-
if (config.isAuthenticationEnabled()) {
537-
final boolean proxyAuthRequested = authenticator.isChallenged(proxy, ChallengeType.PROXY, response, proxyAuthExchange, context);
538-
final boolean proxyMutualAuthRequired = authenticator.isChallengeExpected(proxyAuthExchange);
539-
540-
if (authCacheKeeper != null) {
541-
if (proxyAuthRequested) {
542-
authCacheKeeper.updateOnChallenge(proxy, null, proxyAuthExchange, context);
543-
} else {
544-
authCacheKeeper.updateOnNoChallenge(proxy, null, proxyAuthExchange, context);
545-
}
546-
}
547-
548-
if (proxyAuthRequested || proxyMutualAuthRequired) {
549-
final boolean updated = authenticator.handleResponse(proxy, ChallengeType.PROXY, response,
550-
proxyAuthStrategy, proxyAuthExchange, context);
551-
552-
if (authCacheKeeper != null) {
553-
authCacheKeeper.updateOnResponse(proxy, null, proxyAuthExchange, context);
554-
}
555-
556-
return updated;
557-
}
558-
}
559-
return false;
530+
return authenticator.needProxyAuthentication(
531+
proxyAuthExchange, proxy, response, proxyAuthStrategy, authCacheKeeper, context);
560532
}
561533

562534
private void proceedConnected(

httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -974,21 +974,21 @@ public CloseableHttpAsyncClient build() {
974974
}
975975

976976
final MultihomeConnectionInitiator connectionInitiator = new MultihomeConnectionInitiator(ioReactor, dnsResolver);
977-
final IOEventHandlerFactory tunnelProtocolStarter = new H2TunnelProtocolStarter(
978-
h2Config,
979-
charCodingConfig);
980-
final InternalH2ConnPool connPool = new InternalH2ConnPool(
981-
connectionInitiator,
982-
host -> null,
977+
final H2RouteOperator routeOperator = new H2RouteOperator(
983978
tlsStrategyCopy,
984-
tunnelProtocolStarter,
979+
new H2TunnelProtocolStarter(h2Config, charCodingConfig),
985980
proxyConnectHttpProcessor,
986981
proxyAuthStrategyCopy,
987982
schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE,
988983
authCachingDisabled,
989984
authSchemeRegistryCopy,
990985
credentialsProviderCopy,
991986
defaultRequestConfig);
987+
final InternalH2ConnPool connPool = new InternalH2ConnPool(
988+
connectionInitiator,
989+
host -> null,
990+
tlsStrategyCopy,
991+
routeOperator);
992992
connPool.setConnectionConfigResolver(connectionConfigResolver);
993993

994994
List<Closeable> closeablesCopy = closeables != null ? new ArrayList<>(closeables) : null;
Lines changed: 257 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,257 @@
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 org.apache.hc.client5.http.AuthenticationStrategy;
30+
import org.apache.hc.client5.http.HttpRoute;
31+
import org.apache.hc.client5.http.SchemePortResolver;
32+
import org.apache.hc.client5.http.auth.AuthExchange;
33+
import org.apache.hc.client5.http.auth.AuthSchemeFactory;
34+
import org.apache.hc.client5.http.auth.AuthenticationException;
35+
import org.apache.hc.client5.http.auth.ChallengeType;
36+
import org.apache.hc.client5.http.auth.CredentialsProvider;
37+
import org.apache.hc.client5.http.auth.MalformedChallengeException;
38+
import org.apache.hc.client5.http.config.RequestConfig;
39+
import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;
40+
import org.apache.hc.client5.http.impl.auth.AuthenticationHandler;
41+
import org.apache.hc.client5.http.protocol.HttpClientContext;
42+
import org.apache.hc.core5.annotation.Internal;
43+
import org.apache.hc.core5.concurrent.FutureCallback;
44+
import org.apache.hc.core5.http.HttpException;
45+
import org.apache.hc.core5.http.HttpHost;
46+
import org.apache.hc.core5.http.HttpResponse;
47+
import org.apache.hc.core5.http.HttpStatus;
48+
import org.apache.hc.core5.http.config.Lookup;
49+
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
50+
import org.apache.hc.core5.http.protocol.HttpProcessor;
51+
import org.apache.hc.core5.http2.nio.support.H2OverH2TunnelSupport;
52+
import org.apache.hc.core5.http2.nio.support.TunnelRefusedException;
53+
import org.apache.hc.core5.net.NamedEndpoint;
54+
import org.apache.hc.core5.reactor.IOEventHandlerFactory;
55+
import org.apache.hc.core5.reactor.IOSession;
56+
import org.apache.hc.core5.util.Timeout;
57+
import org.slf4j.Logger;
58+
import org.slf4j.LoggerFactory;
59+
60+
/**
61+
* Completes an HTTP/2 route by establishing a CONNECT tunnel through the proxy
62+
* and optionally upgrading to TLS. Handles proxy authentication with bounded retry.
63+
*
64+
* @since 5.7
65+
*/
66+
@Internal
67+
final class H2RouteOperator {
68+
69+
private static final Logger LOG = LoggerFactory.getLogger(H2RouteOperator.class);
70+
private static final int MAX_TUNNEL_AUTH_ATTEMPTS = 3;
71+
72+
private final TlsStrategy tlsStrategy;
73+
private final IOEventHandlerFactory tunnelProtocolStarter;
74+
private final HttpProcessor proxyHttpProcessor;
75+
private final AuthenticationStrategy proxyAuthStrategy;
76+
private final AuthenticationHandler authenticator;
77+
private final AuthCacheKeeper authCacheKeeper;
78+
private final Lookup<AuthSchemeFactory> authSchemeRegistry;
79+
private final CredentialsProvider credentialsProvider;
80+
private final RequestConfig defaultRequestConfig;
81+
82+
H2RouteOperator(
83+
final TlsStrategy tlsStrategy,
84+
final IOEventHandlerFactory tunnelProtocolStarter) {
85+
this(tlsStrategy, tunnelProtocolStarter, null, null, null, true, null, null, null);
86+
}
87+
88+
H2RouteOperator(
89+
final TlsStrategy tlsStrategy,
90+
final IOEventHandlerFactory tunnelProtocolStarter,
91+
final HttpProcessor proxyHttpProcessor,
92+
final AuthenticationStrategy proxyAuthStrategy,
93+
final SchemePortResolver schemePortResolver,
94+
final boolean authCachingDisabled,
95+
final Lookup<AuthSchemeFactory> authSchemeRegistry,
96+
final CredentialsProvider credentialsProvider,
97+
final RequestConfig defaultRequestConfig) {
98+
this.tlsStrategy = tlsStrategy;
99+
this.tunnelProtocolStarter = tunnelProtocolStarter;
100+
this.proxyHttpProcessor = proxyHttpProcessor;
101+
this.proxyAuthStrategy = proxyAuthStrategy;
102+
this.authenticator = proxyHttpProcessor != null && proxyAuthStrategy != null
103+
? new AuthenticationHandler() : null;
104+
this.authCacheKeeper = proxyHttpProcessor != null && proxyAuthStrategy != null
105+
&& !authCachingDisabled && schemePortResolver != null
106+
? new AuthCacheKeeper(schemePortResolver)
107+
: null;
108+
this.authSchemeRegistry = authSchemeRegistry;
109+
this.credentialsProvider = credentialsProvider;
110+
this.defaultRequestConfig = defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT;
111+
}
112+
113+
void completeRoute(
114+
final HttpRoute route,
115+
final Timeout connectTimeout,
116+
final IOSession ioSession,
117+
final FutureCallback<IOSession> callback) {
118+
if (!route.isTunnelled()) {
119+
callback.completed(ioSession);
120+
return;
121+
}
122+
if (route.getHopCount() > 2) {
123+
callback.failed(new HttpException("Proxy chains are not supported for HTTP/2 CONNECT tunneling"));
124+
return;
125+
}
126+
if (tunnelProtocolStarter == null) {
127+
callback.failed(new IllegalStateException("HTTP/2 tunnel protocol starter not configured"));
128+
return;
129+
}
130+
if (route.isLayered() && tlsStrategy == null) {
131+
callback.failed(new IllegalStateException("TLS strategy not configured"));
132+
return;
133+
}
134+
final NamedEndpoint targetEndpoint = route.getTargetName() != null
135+
? route.getTargetName() : route.getTargetHost();
136+
final HttpHost proxy = route.getProxyHost();
137+
if (LOG.isDebugEnabled()) {
138+
LOG.debug("{} establishing H2 tunnel to {} via {}", ioSession.getId(), targetEndpoint, proxy);
139+
}
140+
if (proxy != null && proxyHttpProcessor != null && proxyAuthStrategy != null && authenticator != null) {
141+
establishTunnelWithAuth(route, ioSession, targetEndpoint, proxy, connectTimeout, callback);
142+
} else {
143+
H2OverH2TunnelSupport.establish(
144+
ioSession,
145+
targetEndpoint,
146+
connectTimeout,
147+
route.isLayered(),
148+
tlsStrategy,
149+
tunnelProtocolStarter,
150+
callback);
151+
}
152+
}
153+
154+
private void establishTunnelWithAuth(
155+
final HttpRoute route,
156+
final IOSession ioSession,
157+
final NamedEndpoint targetEndpoint,
158+
final HttpHost proxy,
159+
final Timeout connectTimeout,
160+
final FutureCallback<IOSession> callback) {
161+
final HttpClientContext tunnelContext = HttpClientContext.create();
162+
if (authSchemeRegistry != null) {
163+
tunnelContext.setAuthSchemeRegistry(authSchemeRegistry);
164+
}
165+
if (credentialsProvider != null) {
166+
tunnelContext.setCredentialsProvider(credentialsProvider);
167+
}
168+
tunnelContext.setRequestConfig(defaultRequestConfig);
169+
170+
final AuthExchange proxyAuthExchange = tunnelContext.getAuthExchange(proxy);
171+
if (authCacheKeeper != null) {
172+
authCacheKeeper.loadPreemptively(proxy, null, proxyAuthExchange, tunnelContext);
173+
}
174+
establishTunnelWithAuthAttempt(
175+
route, ioSession, targetEndpoint, proxy, connectTimeout,
176+
callback, tunnelContext, proxyAuthExchange, 1);
177+
}
178+
179+
private void establishTunnelWithAuthAttempt(
180+
final HttpRoute route,
181+
final IOSession ioSession,
182+
final NamedEndpoint targetEndpoint,
183+
final HttpHost proxy,
184+
final Timeout connectTimeout,
185+
final FutureCallback<IOSession> callback,
186+
final HttpClientContext tunnelContext,
187+
final AuthExchange proxyAuthExchange,
188+
final int attemptCount) {
189+
H2OverH2TunnelSupport.establish(
190+
ioSession,
191+
targetEndpoint,
192+
connectTimeout,
193+
route.isLayered(),
194+
tlsStrategy,
195+
(request, entityDetails, context) -> {
196+
proxyHttpProcessor.process(request, null, tunnelContext);
197+
authenticator.addAuthResponse(proxy, ChallengeType.PROXY, request, proxyAuthExchange, tunnelContext);
198+
},
199+
tunnelProtocolStarter,
200+
new FutureCallback<IOSession>() {
201+
202+
@Override
203+
public void completed(final IOSession result) {
204+
callback.completed(result);
205+
}
206+
207+
@Override
208+
public void failed(final Exception ex) {
209+
if (!(ex instanceof TunnelRefusedException)) {
210+
callback.failed(ex);
211+
return;
212+
}
213+
final TunnelRefusedException tunnelRefusedException = (TunnelRefusedException) ex;
214+
final HttpResponse response = tunnelRefusedException.getResponse();
215+
if (response.getCode() != HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
216+
|| attemptCount >= MAX_TUNNEL_AUTH_ATTEMPTS) {
217+
callback.failed(ex);
218+
return;
219+
}
220+
try {
221+
proxyHttpProcessor.process(response, null, tunnelContext);
222+
final boolean retry = needAuthentication(
223+
proxyAuthExchange, proxy, response, tunnelContext);
224+
if (retry) {
225+
if (LOG.isDebugEnabled()) {
226+
LOG.debug("{} tunnel auth challenge from {}; attempt {}/{}",
227+
ioSession.getId(), proxy, attemptCount, MAX_TUNNEL_AUTH_ATTEMPTS);
228+
}
229+
establishTunnelWithAuthAttempt(
230+
route, ioSession, targetEndpoint, proxy, connectTimeout,
231+
callback, tunnelContext, proxyAuthExchange, attemptCount + 1);
232+
} else {
233+
callback.failed(ex);
234+
}
235+
} catch (final Exception ioEx) {
236+
callback.failed(ioEx);
237+
}
238+
}
239+
240+
@Override
241+
public void cancelled() {
242+
callback.cancelled();
243+
}
244+
245+
});
246+
}
247+
248+
private boolean needAuthentication(
249+
final AuthExchange proxyAuthExchange,
250+
final HttpHost proxy,
251+
final HttpResponse response,
252+
final HttpClientContext context) throws AuthenticationException, MalformedChallengeException {
253+
return authenticator.needProxyAuthentication(
254+
proxyAuthExchange, proxy, response, proxyAuthStrategy, authCacheKeeper, context);
255+
}
256+
257+
}

httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -188,6 +188,12 @@ Endpoint ensureValid() {
188188
return endpoint;
189189
}
190190

191+
@Override
192+
public HttpRoute getEstablishedRoute() {
193+
final Endpoint endpoint = sessionRef.get();
194+
return endpoint != null ? endpoint.route : null;
195+
}
196+
191197
@Override
192198
public Cancellable connectEndpoint(
193199
final HttpClientContext context,

0 commit comments

Comments
 (0)