arr) {
+ return arr.stream()
+ .map(AddressSelectingDnsResolver::addr)
+ .collect(Collectors.toList());
+ }
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/async/AsyncExecRuntime.java b/httpclient5/src/main/java/org/apache/hc/client5/http/async/AsyncExecRuntime.java
index 4fd510b8c3..d1757e4cc0 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/async/AsyncExecRuntime.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/async/AsyncExecRuntime.java
@@ -175,6 +175,18 @@ Cancellable execute(
*/
void markConnectionNonReusable();
+ /**
+ * Returns the route that has already been established by the connection pool,
+ * or {@code null} if route completion is not handled at the pool level.
+ *
+ * @return the established route, or {@code null}.
+ *
+ * @since 5.7
+ */
+ default HttpRoute getEstablishedRoute() {
+ return null;
+ }
+
/**
* Forks this runtime for parallel execution.
*
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java b/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java
new file mode 100644
index 0000000000..7ad272e3f6
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java
@@ -0,0 +1,72 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.config;
+
+/**
+ * Protocol family preference for outbound connections.
+ *
+ * Used by connection initiation code to filter or order destination
+ * addresses and, when enabled, to interleave families during staggered attempts.
+ *
+ * @since 5.7
+ */
+public enum ProtocolFamilyPreference {
+
+ /**
+ * No family bias. Preserve RFC 6724 order.
+ */
+ DEFAULT,
+
+ /**
+ * Prefer IPv4 addresses (stable: preserves RFC order within each family).
+ */
+ PREFER_IPV4,
+
+ /**
+ * Prefer IPv6 addresses (stable: preserves RFC order within each family).
+ */
+ PREFER_IPV6,
+
+ /**
+ * Filter out all non-IPv4 addresses.
+ */
+ IPV4_ONLY,
+
+ /**
+ * Filter out all non-IPv6 addresses.
+ */
+ IPV6_ONLY,
+
+ /**
+ * Interleave address families (v6, then v4, then v6, …) when multiple
+ * addresses are available, preserving the relative order within each family
+ * as produced by RFC 6724 sorting.
+ */
+ INTERLEAVE
+
+}
+
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java
index a2c816c4aa..e6df2937fe 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/AsyncConnectExec.java
@@ -47,7 +47,6 @@
import org.apache.hc.client5.http.auth.AuthenticationException;
import org.apache.hc.client5.http.auth.ChallengeType;
import org.apache.hc.client5.http.auth.MalformedChallengeException;
-import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.AlpnHeaderSupport;
import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;
import org.apache.hc.client5.http.impl.auth.AuthenticationHandler;
@@ -261,6 +260,15 @@ public void cancelled() {
public void completed(final AsyncExecRuntime execRuntime) {
final HttpHost proxy = route.getProxyHost();
tracker.connectProxy(proxy, route.isSecure() && !route.isTunnelled());
+ if (route.isTunnelled() && execRuntime.getEstablishedRoute() != null) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} tunnel to target already established by connection pool", exchangeId);
+ }
+ tracker.tunnelTarget(false);
+ if (route.isLayered()) {
+ tracker.layerProtocol(route.isSecure());
+ }
+ }
if (LOG.isDebugEnabled()) {
LOG.debug("{} connected to proxy", exchangeId);
}
@@ -542,31 +550,8 @@ private boolean needAuthentication(
final HttpHost proxy,
final HttpResponse response,
final HttpClientContext context) throws AuthenticationException, MalformedChallengeException {
- final RequestConfig config = context.getRequestConfigOrDefault();
- if (config.isAuthenticationEnabled()) {
- final boolean proxyAuthRequested = authenticator.isChallenged(proxy, ChallengeType.PROXY, response, proxyAuthExchange, context);
- final boolean proxyMutualAuthRequired = authenticator.isChallengeExpected(proxyAuthExchange);
-
- if (authCacheKeeper != null) {
- if (proxyAuthRequested) {
- authCacheKeeper.updateCacheOnChallenge(proxy, null, proxyAuthExchange, context);
- } else {
- authCacheKeeper.updateCacheOnNoChallenge(proxy, null, proxyAuthExchange, context);
- }
- }
-
- if (proxyAuthRequested || proxyMutualAuthRequired) {
- final boolean updated = authenticator.handleResponse(proxy, ChallengeType.PROXY, response,
- proxyAuthStrategy, proxyAuthExchange, context);
-
- if (authCacheKeeper != null) {
- authCacheKeeper.updateCacheOnResponse(proxy, null, proxyAuthExchange, context);
- }
-
- return updated;
- }
- }
- return false;
+ return authenticator.needProxyAuthentication(
+ proxyAuthExchange, proxy, response, proxyAuthStrategy, authCacheKeeper, context);
}
private void proceedConnected(
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java
index 6965a05873..c451706377 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2AsyncClientBuilder.java
@@ -866,9 +866,12 @@ public CloseableHttpAsyncClient build() {
new H2AsyncMainClientExec(httpProcessor),
ChainElement.MAIN_TRANSPORT.name());
+ final HttpProcessor proxyConnectHttpProcessor =
+ new DefaultHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy));
+
execChainDefinition.addFirst(
new AsyncConnectExec(
- new DefaultHttpProcessor(new RequestTargetHost(), new RequestUserAgent(userAgentCopy)),
+ proxyConnectHttpProcessor,
proxyAuthStrategyCopy,
schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE,
authCachingDisabled),
@@ -998,11 +1001,22 @@ public CloseableHttpAsyncClient build() {
}
final MultihomeConnectionInitiator connectionInitiator = new MultihomeConnectionInitiator(ioReactor, dnsResolver);
+ final H2RouteOperator routeOperator = new H2RouteOperator(
+ tlsStrategyCopy,
+ new H2TunnelProtocolStarter(h2Config, charCodingConfig),
+ proxyConnectHttpProcessor,
+ proxyAuthStrategyCopy,
+ schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE,
+ authCachingDisabled,
+ authSchemeRegistryCopy,
+ credentialsProviderCopy,
+ defaultRequestConfig);
final InternalH2ConnPool connPool = new InternalH2ConnPool(
Clock.systemUTC(),
connectionInitiator,
host -> null,
- tlsStrategyCopy);
+ tlsStrategyCopy,
+ routeOperator);
connPool.setConnectionConfigResolver(connectionConfigResolver);
List closeablesCopy = closeables != null ? new ArrayList<>(closeables) : null;
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelExchangeHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelExchangeHandler.java
new file mode 100644
index 0000000000..2e72231437
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelExchangeHandler.java
@@ -0,0 +1,323 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.ConnectionClosedException;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpRequestInterceptor;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.Method;
+import org.apache.hc.core5.http.StreamControl;
+import org.apache.hc.core5.http.impl.BasicEntityDetails;
+import org.apache.hc.core5.http.message.BasicHttpRequest;
+import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.http.nio.RequestChannel;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.net.URIAuthority;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOEventHandlerFactory;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
+import org.apache.hc.core5.util.Timeout;
+
+/**
+ * Exchange handler that establishes an HTTP/2 CONNECT tunnel and exposes
+ * the resulting data stream as a {@link ProtocolIOSession}.
+ *
+ * @since 5.7
+ */
+final class H2OverH2TunnelExchangeHandler implements AsyncClientExchangeHandler {
+
+ private final IOSession physicalSession;
+ private final NamedEndpoint targetEndpoint;
+ private final Timeout connectTimeout;
+ private final boolean secure;
+ private final TlsStrategy tlsStrategy;
+ private final HttpRequestInterceptor connectRequestInterceptor;
+ private final IOEventHandlerFactory protocolStarter;
+ private final FutureCallback callback;
+
+ private final AtomicBoolean done;
+ private final AtomicBoolean requestEndStreamSent;
+
+ private volatile DataStreamChannel dataChannel;
+ private volatile CapacityChannel capacityChannel;
+ private volatile StreamControl streamControl;
+ private volatile H2TunnelProtocolIOSession tunnelSession;
+ private volatile TunnelRefusedException tunnelRefusedException;
+
+ H2OverH2TunnelExchangeHandler(
+ final IOSession physicalSession,
+ final NamedEndpoint targetEndpoint,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final HttpRequestInterceptor connectRequestInterceptor,
+ final IOEventHandlerFactory protocolStarter,
+ final FutureCallback callback) {
+ this.physicalSession = physicalSession;
+ this.targetEndpoint = targetEndpoint;
+ this.connectTimeout = connectTimeout;
+ this.secure = secure;
+ this.tlsStrategy = tlsStrategy;
+ this.connectRequestInterceptor = connectRequestInterceptor;
+ this.protocolStarter = protocolStarter;
+ this.callback = callback;
+ this.done = new AtomicBoolean(false);
+ this.requestEndStreamSent = new AtomicBoolean(false);
+ }
+
+ void initiated(final StreamControl streamControl) {
+ this.streamControl = streamControl;
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null) {
+ tunnel.bindStreamControl(streamControl);
+ }
+ }
+
+ @Override
+ public void releaseResources() {
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ fail(cause);
+ }
+
+ @Override
+ public void cancel() {
+ fail(new ConnectionClosedException("Tunnel setup cancelled"));
+ }
+
+ @Override
+ public void produceRequest(final RequestChannel requestChannel, final HttpContext context) throws HttpException, IOException {
+ final HttpRequest connectRequest = new BasicHttpRequest(Method.CONNECT.name(), (String) null);
+ connectRequest.setAuthority(new URIAuthority(targetEndpoint));
+ if (connectRequestInterceptor != null) {
+ connectRequestInterceptor.process(connectRequest, null, context);
+ }
+ requestChannel.sendRequest(connectRequest, new BasicEntityDetails(-1, null), context);
+ }
+
+ @Override
+ public int available() {
+ final TunnelRefusedException tunnelRefusedException = this.tunnelRefusedException;
+ if (tunnelRefusedException != null && !requestEndStreamSent.get()) {
+ return 1;
+ }
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ return tunnel != null ? tunnel.available() : 0;
+ }
+
+ @Override
+ public void produce(final DataStreamChannel channel) throws IOException {
+ this.dataChannel = channel;
+ final TunnelRefusedException tunnelRefusedException = this.tunnelRefusedException;
+ if (tunnelRefusedException != null) {
+ endRequestStream();
+ return;
+ }
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null) {
+ tunnel.attachChannel(channel);
+ tunnel.onOutputReady();
+ }
+ }
+
+ @Override
+ public void consumeInformation(final HttpResponse response, final HttpContext context) {
+ }
+
+ @Override
+ public void consumeResponse(
+ final HttpResponse response,
+ final EntityDetails entityDetails,
+ final HttpContext context) throws HttpException, IOException {
+
+ final int status = response.getCode();
+ if (status < 200 || status >= 300) {
+ final TunnelRefusedException tunnelRefusedException = new TunnelRefusedException(response);
+ this.tunnelRefusedException = tunnelRefusedException;
+ endRequestStream();
+ if (entityDetails == null) {
+ failTunnelRefused(tunnelRefusedException);
+ }
+ return;
+ }
+
+ if (entityDetails == null) {
+ throw new HttpException("CONNECT response does not provide a tunneled data stream");
+ }
+
+ if (this.tunnelSession != null) {
+ return;
+ }
+
+ final H2TunnelProtocolIOSession tunnel =
+ new H2TunnelProtocolIOSession(physicalSession, targetEndpoint, connectTimeout, streamControl);
+
+ final DataStreamChannel currentChannel = this.dataChannel;
+ if (currentChannel != null) {
+ tunnel.attachChannel(currentChannel);
+ }
+ final CapacityChannel currentCapacity = this.capacityChannel;
+ if (currentCapacity != null) {
+ tunnel.updateCapacityChannel(currentCapacity);
+ }
+ this.tunnelSession = tunnel;
+
+ if (secure) {
+ tlsStrategy.upgrade(
+ tunnel,
+ targetEndpoint,
+ null,
+ connectTimeout,
+ new FutureCallback() {
+
+ @Override
+ public void completed(final TransportSecurityLayer transportSecurityLayer) {
+ try {
+ startProtocol(tunnel);
+ complete(tunnel);
+ } catch (final Exception ex) {
+ fail(ex);
+ }
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ fail(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ fail(new ConnectionClosedException("Tunnel TLS upgrade cancelled"));
+ }
+ });
+ } else {
+ startProtocol(tunnel);
+ complete(tunnel);
+ }
+ }
+
+ private void startProtocol(final H2TunnelProtocolIOSession tunnel) throws IOException {
+ if (protocolStarter == null) {
+ return;
+ }
+ final IOEventHandler protocolHandler = protocolStarter.createHandler(tunnel, null);
+ tunnel.upgrade(protocolHandler);
+ protocolHandler.connected(tunnel);
+ }
+
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ this.capacityChannel = capacityChannel;
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null) {
+ tunnel.updateCapacityChannel(capacityChannel);
+ }
+ }
+
+ @Override
+ public void consume(final ByteBuffer src) throws IOException {
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null && src != null && src.hasRemaining()) {
+ tunnel.onInput(src);
+ }
+ }
+
+ @Override
+ public void streamEnd(final List extends Header> trailers) throws IOException {
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null) {
+ tunnel.onRemoteStreamEnd();
+ return;
+ }
+ final TunnelRefusedException tunnelRefusedException = this.tunnelRefusedException;
+ if (tunnelRefusedException != null) {
+ failTunnelRefused(tunnelRefusedException);
+ return;
+ }
+ closeTransport(CloseMode.GRACEFUL);
+ if (done.compareAndSet(false, true) && callback != null) {
+ callback.failed(new ConnectionClosedException("Tunnel stream closed before establishment"));
+ }
+ }
+
+ private void endRequestStream() throws IOException {
+ final DataStreamChannel currentDataChannel = this.dataChannel;
+ if (currentDataChannel != null && requestEndStreamSent.compareAndSet(false, true)) {
+ currentDataChannel.endStream(null);
+ }
+ }
+
+ private void failTunnelRefused(final TunnelRefusedException tunnelRefusedException) {
+ if (done.compareAndSet(false, true) && callback != null) {
+ callback.failed(tunnelRefusedException);
+ }
+ }
+
+ private void closeTransport(final CloseMode closeMode) {
+ final H2TunnelProtocolIOSession tunnel = this.tunnelSession;
+ if (tunnel != null) {
+ tunnel.close(closeMode);
+ return;
+ }
+ final StreamControl currentStreamControl = this.streamControl;
+ if (currentStreamControl != null) {
+ currentStreamControl.cancel();
+ }
+ }
+
+ private void fail(final Exception cause) {
+ closeTransport(CloseMode.IMMEDIATE);
+ if (done.compareAndSet(false, true) && callback != null) {
+ callback.failed(cause);
+ }
+ }
+
+ private void complete(final H2TunnelProtocolIOSession tunnel) {
+ if (done.compareAndSet(false, true) && callback != null) {
+ callback.completed(tunnel);
+ }
+ }
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelSupport.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelSupport.java
new file mode 100644
index 0000000000..5d27eab216
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2OverH2TunnelSupport.java
@@ -0,0 +1,223 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import org.apache.hc.core5.annotation.Contract;
+import org.apache.hc.core5.annotation.ThreadingBehavior;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.HttpRequestInterceptor;
+import org.apache.hc.core5.http.nio.command.RequestExecutionCommand;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http.protocol.HttpCoreContext;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOEventHandlerFactory;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.Timeout;
+
+/**
+ * Helper for establishing HTTP/2 CONNECT tunnels through HTTP/2 proxies.
+ *
+ * Multiplexing-safe: tunnel close affects only the CONNECT stream,
+ * not the underlying physical HTTP/2 connection.
+ *
+ *
+ * This helper does not handle proxy authentication (407 retries).
+ * That responsibility belongs to client implementations that maintain
+ * authentication state.
+ *
+ *
+ * @since 5.7
+ */
+@Contract(threading = ThreadingBehavior.STATELESS)
+public final class H2OverH2TunnelSupport {
+
+ private H2OverH2TunnelSupport() {
+ }
+
+ /**
+ * Establishes a CONNECT tunnel and returns the resulting {@link ProtocolIOSession}
+ * via the callback. The tunnel session supports optional TLS upgrade.
+ *
+ * @param proxySession the HTTP/2 session to the proxy
+ * @param target the target endpoint for the CONNECT request authority
+ * @param connectTimeout timeout for the CONNECT handshake
+ * @param secure whether to upgrade the tunnel to TLS after establishment
+ * @param tlsStrategy TLS strategy for the upgrade (required when {@code secure} is true)
+ * @param callback completion callback receiving the tunnel session
+ * @since 5.7
+ */
+ public static void establish(
+ final IOSession proxySession,
+ final NamedEndpoint target,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final FutureCallback callback) {
+ establishInternal(proxySession, target, connectTimeout, secure, tlsStrategy, null, null, callback);
+ }
+
+ /**
+ * Establishes a CONNECT tunnel with a request interceptor for injecting
+ * headers (e.g. proxy authentication) into the CONNECT request.
+ *
+ * @param proxySession the HTTP/2 session to the proxy
+ * @param target the target endpoint for the CONNECT request authority
+ * @param connectTimeout timeout for the CONNECT handshake
+ * @param secure whether to upgrade the tunnel to TLS after establishment
+ * @param tlsStrategy TLS strategy for the upgrade (required when {@code secure} is true)
+ * @param connectRequestInterceptor interceptor applied to the CONNECT request before sending
+ * @param callback completion callback receiving the tunnel session
+ * @since 5.7
+ */
+ public static void establish(
+ final IOSession proxySession,
+ final NamedEndpoint target,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final HttpRequestInterceptor connectRequestInterceptor,
+ final FutureCallback callback) {
+ establishInternal(proxySession, target, connectTimeout, secure, tlsStrategy, connectRequestInterceptor, null, callback);
+ }
+
+ /**
+ * Establishes a CONNECT tunnel and starts a protocol handler inside it.
+ * The protocol starter factory creates an {@link org.apache.hc.core5.reactor.IOEventHandler}
+ * that is connected to the tunnel session immediately after establishment.
+ *
+ * @param proxySession the HTTP/2 session to the proxy
+ * @param target the target endpoint for the CONNECT request authority
+ * @param connectTimeout timeout for the CONNECT handshake
+ * @param secure whether to upgrade the tunnel to TLS after establishment
+ * @param tlsStrategy TLS strategy for the upgrade (required when {@code secure} is true)
+ * @param protocolStarter factory for the protocol handler to run inside the tunnel
+ * @param callback completion callback receiving the tunnel session
+ * @since 5.7
+ */
+ public static void establish(
+ final IOSession proxySession,
+ final NamedEndpoint target,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final IOEventHandlerFactory protocolStarter,
+ final FutureCallback callback) {
+ establish(proxySession, target, connectTimeout, secure, tlsStrategy, null, protocolStarter, callback);
+ }
+
+ /**
+ * Establishes a CONNECT tunnel with both a request interceptor and a protocol starter.
+ * This is the most general overload combining proxy authentication support with
+ * automatic protocol initialization inside the tunnel.
+ *
+ * @param proxySession the HTTP/2 session to the proxy
+ * @param target the target endpoint for the CONNECT request authority
+ * @param connectTimeout timeout for the CONNECT handshake
+ * @param secure whether to upgrade the tunnel to TLS after establishment
+ * @param tlsStrategy TLS strategy for the upgrade (required when {@code secure} is true)
+ * @param connectRequestInterceptor interceptor applied to the CONNECT request before sending
+ * @param protocolStarter factory for the protocol handler to run inside the tunnel
+ * @param callback completion callback receiving the tunnel session
+ * @since 5.7
+ */
+ public static void establish(
+ final IOSession proxySession,
+ final NamedEndpoint target,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final HttpRequestInterceptor connectRequestInterceptor,
+ final IOEventHandlerFactory protocolStarter,
+ final FutureCallback callback) {
+
+ final FutureCallback adapter = callback != null ? new FutureCallback() {
+
+ @Override
+ public void completed(final ProtocolIOSession result) {
+ callback.completed(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ callback.failed(ex);
+ }
+
+ @Override
+ public void cancelled() {
+ callback.cancelled();
+ }
+
+ } : null;
+
+ establishInternal(proxySession, target, connectTimeout, secure, tlsStrategy, connectRequestInterceptor, protocolStarter, adapter);
+ }
+
+ private static void establishInternal(
+ final IOSession proxySession,
+ final NamedEndpoint target,
+ final Timeout connectTimeout,
+ final boolean secure,
+ final TlsStrategy tlsStrategy,
+ final HttpRequestInterceptor connectRequestInterceptor,
+ final IOEventHandlerFactory protocolStarter,
+ final FutureCallback callback) {
+
+ Args.notNull(proxySession, "Proxy I/O session");
+ Args.notNull(target, "Tunnel target endpoint");
+ if (secure) {
+ Args.notNull(tlsStrategy, "TLS strategy");
+ }
+
+ final H2OverH2TunnelExchangeHandler exchangeHandler = new H2OverH2TunnelExchangeHandler(
+ proxySession,
+ target,
+ connectTimeout,
+ secure,
+ tlsStrategy,
+ connectRequestInterceptor,
+ protocolStarter,
+ callback);
+
+ proxySession.enqueue(
+ new RequestExecutionCommand(
+ exchangeHandler,
+ null,
+ HttpCoreContext.create(),
+ exchangeHandler::initiated),
+ Command.Priority.NORMAL);
+ }
+
+ static void closeQuietly(final ProtocolIOSession session) {
+ if (session != null) {
+ session.close(CloseMode.IMMEDIATE);
+ }
+ }
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2RouteOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2RouteOperator.java
new file mode 100644
index 0000000000..6eaa38048f
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2RouteOperator.java
@@ -0,0 +1,255 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import org.apache.hc.client5.http.AuthenticationStrategy;
+import org.apache.hc.client5.http.HttpRoute;
+import org.apache.hc.client5.http.SchemePortResolver;
+import org.apache.hc.client5.http.auth.AuthExchange;
+import org.apache.hc.client5.http.auth.AuthSchemeFactory;
+import org.apache.hc.client5.http.auth.AuthenticationException;
+import org.apache.hc.client5.http.auth.ChallengeType;
+import org.apache.hc.client5.http.auth.CredentialsProvider;
+import org.apache.hc.client5.http.auth.MalformedChallengeException;
+import org.apache.hc.client5.http.config.RequestConfig;
+import org.apache.hc.client5.http.impl.auth.AuthCacheKeeper;
+import org.apache.hc.client5.http.impl.auth.AuthenticationHandler;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.core5.annotation.Internal;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http.protocol.HttpProcessor;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.reactor.IOEventHandlerFactory;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.Timeout;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Completes an HTTP/2 route by establishing a CONNECT tunnel through the proxy
+ * and optionally upgrading to TLS. Handles proxy authentication with bounded retry.
+ *
+ * @since 5.7
+ */
+@Internal
+final class H2RouteOperator {
+
+ private static final Logger LOG = LoggerFactory.getLogger(H2RouteOperator.class);
+ private static final int MAX_TUNNEL_AUTH_ATTEMPTS = 3;
+
+ private final TlsStrategy tlsStrategy;
+ private final IOEventHandlerFactory tunnelProtocolStarter;
+ private final HttpProcessor proxyHttpProcessor;
+ private final AuthenticationStrategy proxyAuthStrategy;
+ private final AuthenticationHandler authenticator;
+ private final AuthCacheKeeper authCacheKeeper;
+ private final Lookup authSchemeRegistry;
+ private final CredentialsProvider credentialsProvider;
+ private final RequestConfig defaultRequestConfig;
+
+ H2RouteOperator(
+ final TlsStrategy tlsStrategy,
+ final IOEventHandlerFactory tunnelProtocolStarter) {
+ this(tlsStrategy, tunnelProtocolStarter, null, null, null, true, null, null, null);
+ }
+
+ H2RouteOperator(
+ final TlsStrategy tlsStrategy,
+ final IOEventHandlerFactory tunnelProtocolStarter,
+ final HttpProcessor proxyHttpProcessor,
+ final AuthenticationStrategy proxyAuthStrategy,
+ final SchemePortResolver schemePortResolver,
+ final boolean authCachingDisabled,
+ final Lookup authSchemeRegistry,
+ final CredentialsProvider credentialsProvider,
+ final RequestConfig defaultRequestConfig) {
+ this.tlsStrategy = tlsStrategy;
+ this.tunnelProtocolStarter = tunnelProtocolStarter;
+ this.proxyHttpProcessor = proxyHttpProcessor;
+ this.proxyAuthStrategy = proxyAuthStrategy;
+ this.authenticator = proxyHttpProcessor != null && proxyAuthStrategy != null
+ ? new AuthenticationHandler() : null;
+ this.authCacheKeeper = proxyHttpProcessor != null && proxyAuthStrategy != null
+ && !authCachingDisabled && schemePortResolver != null
+ ? new AuthCacheKeeper(schemePortResolver)
+ : null;
+ this.authSchemeRegistry = authSchemeRegistry;
+ this.credentialsProvider = credentialsProvider;
+ this.defaultRequestConfig = defaultRequestConfig != null ? defaultRequestConfig : RequestConfig.DEFAULT;
+ }
+
+ void completeRoute(
+ final HttpRoute route,
+ final Timeout connectTimeout,
+ final IOSession ioSession,
+ final FutureCallback callback) {
+ if (!route.isTunnelled()) {
+ callback.completed(ioSession);
+ return;
+ }
+ if (route.getHopCount() > 2) {
+ callback.failed(new HttpException("Proxy chains are not supported for HTTP/2 CONNECT tunneling"));
+ return;
+ }
+ if (tunnelProtocolStarter == null) {
+ callback.failed(new IllegalStateException("HTTP/2 tunnel protocol starter not configured"));
+ return;
+ }
+ if (route.isLayered() && tlsStrategy == null) {
+ callback.failed(new IllegalStateException("TLS strategy not configured"));
+ return;
+ }
+ final NamedEndpoint targetEndpoint = route.getTargetName() != null
+ ? route.getTargetName() : route.getTargetHost();
+ final HttpHost proxy = route.getProxyHost();
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} establishing H2 tunnel to {} via {}", ioSession.getId(), targetEndpoint, proxy);
+ }
+ if (proxy != null && proxyHttpProcessor != null && proxyAuthStrategy != null && authenticator != null) {
+ establishTunnelWithAuth(route, ioSession, targetEndpoint, proxy, connectTimeout, callback);
+ } else {
+ H2OverH2TunnelSupport.establish(
+ ioSession,
+ targetEndpoint,
+ connectTimeout,
+ route.isLayered(),
+ tlsStrategy,
+ tunnelProtocolStarter,
+ callback);
+ }
+ }
+
+ private void establishTunnelWithAuth(
+ final HttpRoute route,
+ final IOSession ioSession,
+ final NamedEndpoint targetEndpoint,
+ final HttpHost proxy,
+ final Timeout connectTimeout,
+ final FutureCallback callback) {
+ final HttpClientContext tunnelContext = HttpClientContext.create();
+ if (authSchemeRegistry != null) {
+ tunnelContext.setAuthSchemeRegistry(authSchemeRegistry);
+ }
+ if (credentialsProvider != null) {
+ tunnelContext.setCredentialsProvider(credentialsProvider);
+ }
+ tunnelContext.setRequestConfig(defaultRequestConfig);
+
+ final AuthExchange proxyAuthExchange = tunnelContext.getAuthExchange(proxy);
+ if (authCacheKeeper != null) {
+ authCacheKeeper.loadPreemptively(proxy, null, proxyAuthExchange, tunnelContext);
+ }
+ establishTunnelWithAuthAttempt(
+ route, ioSession, targetEndpoint, proxy, connectTimeout,
+ callback, tunnelContext, proxyAuthExchange, 1);
+ }
+
+ private void establishTunnelWithAuthAttempt(
+ final HttpRoute route,
+ final IOSession ioSession,
+ final NamedEndpoint targetEndpoint,
+ final HttpHost proxy,
+ final Timeout connectTimeout,
+ final FutureCallback callback,
+ final HttpClientContext tunnelContext,
+ final AuthExchange proxyAuthExchange,
+ final int attemptCount) {
+ H2OverH2TunnelSupport.establish(
+ ioSession,
+ targetEndpoint,
+ connectTimeout,
+ route.isLayered(),
+ tlsStrategy,
+ (request, entityDetails, context) -> {
+ proxyHttpProcessor.process(request, null, tunnelContext);
+ authenticator.addAuthResponse(proxy, ChallengeType.PROXY, request, proxyAuthExchange, tunnelContext);
+ },
+ tunnelProtocolStarter,
+ new FutureCallback() {
+
+ @Override
+ public void completed(final IOSession result) {
+ callback.completed(result);
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ if (!(ex instanceof TunnelRefusedException)) {
+ callback.failed(ex);
+ return;
+ }
+ final TunnelRefusedException tunnelRefusedException = (TunnelRefusedException) ex;
+ final HttpResponse response = tunnelRefusedException.getResponse();
+ if (response.getCode() != HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED
+ || attemptCount >= MAX_TUNNEL_AUTH_ATTEMPTS) {
+ callback.failed(ex);
+ return;
+ }
+ try {
+ proxyHttpProcessor.process(response, null, tunnelContext);
+ final boolean retry = needAuthentication(
+ proxyAuthExchange, proxy, response, tunnelContext);
+ if (retry) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} tunnel auth challenge from {}; attempt {}/{}",
+ ioSession.getId(), proxy, attemptCount, MAX_TUNNEL_AUTH_ATTEMPTS);
+ }
+ establishTunnelWithAuthAttempt(
+ route, ioSession, targetEndpoint, proxy, connectTimeout,
+ callback, tunnelContext, proxyAuthExchange, attemptCount + 1);
+ } else {
+ callback.failed(ex);
+ }
+ } catch (final Exception ioEx) {
+ callback.failed(ioEx);
+ }
+ }
+
+ @Override
+ public void cancelled() {
+ callback.cancelled();
+ }
+
+ });
+ }
+
+ private boolean needAuthentication(
+ final AuthExchange proxyAuthExchange,
+ final HttpHost proxy,
+ final HttpResponse response,
+ final HttpClientContext context) throws AuthenticationException, MalformedChallengeException {
+ return authenticator.needProxyAuthentication(
+ proxyAuthExchange, proxy, response, proxyAuthStrategy, authCacheKeeper, context);
+ }
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolIOSession.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolIOSession.java
new file mode 100644
index 0000000000..a48a4d2a18
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolIOSession.java
@@ -0,0 +1,401 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ByteChannel;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Lock;
+
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.SSLSession;
+
+import org.apache.hc.core5.concurrent.CallbackContribution;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.StreamControl;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+import org.apache.hc.core5.reactor.ssl.SSLBufferMode;
+import org.apache.hc.core5.reactor.ssl.SSLIOSession;
+import org.apache.hc.core5.reactor.ssl.SSLMode;
+import org.apache.hc.core5.reactor.ssl.SSLSessionInitializer;
+import org.apache.hc.core5.reactor.ssl.SSLSessionVerifier;
+import org.apache.hc.core5.reactor.ssl.TlsDetails;
+import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
+import org.apache.hc.core5.util.Timeout;
+
+/**
+ * {@link ProtocolIOSession} backed by a single HTTP/2 CONNECT stream.
+ *
+ * Supports optional TLS upgrade via {@link #startTls} for establishing
+ * secure tunnels to the target endpoint.
+ *
+ *
+ * @since 5.7
+ */
+final class H2TunnelProtocolIOSession implements ProtocolIOSession {
+
+ private static final IOEventHandler NOOP_HANDLER = new IOEventHandler() {
+
+ @Override
+ public void connected(final IOSession session) {
+ }
+
+ @Override
+ public void inputReady(final IOSession session, final ByteBuffer src) {
+ }
+
+ @Override
+ public void outputReady(final IOSession session) {
+ }
+
+ @Override
+ public void timeout(final IOSession session, final Timeout timeout) {
+ }
+
+ @Override
+ public void exception(final IOSession session, final Exception cause) {
+ }
+
+ @Override
+ public void disconnected(final IOSession session) {
+ }
+ };
+
+ private final NamedEndpoint initialEndpoint;
+ private final H2TunnelRawIOSession ioSession;
+ private final AtomicReference tlsSessionRef;
+ private final AtomicReference currentSessionRef;
+
+ H2TunnelProtocolIOSession(
+ final IOSession physicalSession,
+ final NamedEndpoint initialEndpoint,
+ final Timeout socketTimeout,
+ final StreamControl streamControl) {
+ this.initialEndpoint = initialEndpoint;
+ this.ioSession = new H2TunnelRawIOSession(physicalSession, socketTimeout, streamControl);
+ this.tlsSessionRef = new AtomicReference<>();
+ this.currentSessionRef = new AtomicReference<>(ioSession);
+ this.ioSession.upgrade(NOOP_HANDLER);
+ }
+
+ void bindStreamControl(final StreamControl streamControl) {
+ ioSession.bindStreamControl(streamControl);
+ }
+
+ void attachChannel(final DataStreamChannel channel) {
+ ioSession.attachChannel(channel);
+ }
+
+ void updateCapacityChannel(final CapacityChannel capacityChannel) throws IOException {
+ ioSession.updateCapacityChannel(capacityChannel);
+ }
+
+ int available() {
+ return ioSession.available();
+ }
+
+ void onInput(final ByteBuffer src) throws IOException {
+ final ByteBuffer handlerSrc = src != null ? src.asReadOnlyBuffer() : null;
+
+ ioSession.appendInput(src);
+
+ final IOSession currentSession = currentSessionRef.get();
+ final IOEventHandler handler = currentSession.getHandler();
+ if (handler != null) {
+ if (currentSession == ioSession) {
+ handler.inputReady(currentSession, handlerSrc);
+ if (handlerSrc != null) {
+ final int consumed = handlerSrc.position();
+ if (consumed > 0) {
+ ioSession.discardInbound(consumed);
+ }
+ }
+ } else {
+ driveWrappedInput(currentSession, handler);
+ }
+ }
+
+ if (ioSession.available() > 0) {
+ ioSession.requestOutput();
+ }
+ }
+
+ private void driveWrappedInput(final IOSession currentSession, final IOEventHandler handler) throws IOException {
+ for (;;) {
+ final int pendingInput = ioSession.pendingInput();
+ handler.inputReady(currentSession, null);
+ final int remainingInput = ioSession.pendingInput();
+ if (remainingInput == 0 || remainingInput >= pendingInput) {
+ break;
+ }
+ }
+ }
+
+ void onOutputReady() throws IOException {
+ final IOSession currentSession = currentSessionRef.get();
+ final IOEventHandler handler = currentSession.getHandler();
+ if (handler != null) {
+ handler.outputReady(currentSession);
+ }
+ ioSession.flushOutput();
+ if (ioSession.available() > 0) {
+ ioSession.requestOutput();
+ }
+ }
+
+ void onRemoteStreamEnd() throws IOException {
+ ioSession.onRemoteStreamEnd();
+ final IOSession currentSession = currentSessionRef.get();
+ final IOEventHandler handler = currentSession.getHandler();
+ if (handler != null) {
+ handler.inputReady(currentSession, null);
+ }
+ }
+
+ @Override
+ public NamedEndpoint getInitialEndpoint() {
+ return initialEndpoint;
+ }
+
+ @Override
+ public IOEventHandler getHandler() {
+ return currentSessionRef.get().getHandler();
+ }
+
+ @Override
+ public void upgrade(final IOEventHandler handler) {
+ currentSessionRef.get().upgrade(handler);
+ }
+
+ @Override
+ public Lock getLock() {
+ return ioSession.getLock();
+ }
+
+ @Override
+ public void enqueue(final Command command, final Command.Priority priority) {
+ currentSessionRef.get().enqueue(command, priority);
+ }
+
+ @Override
+ public boolean hasCommands() {
+ return currentSessionRef.get().hasCommands();
+ }
+
+ @Override
+ public Command poll() {
+ return currentSessionRef.get().poll();
+ }
+
+ @Override
+ public ByteChannel channel() {
+ return currentSessionRef.get().channel();
+ }
+
+ @Override
+ public SocketAddress getRemoteAddress() {
+ return ioSession.getRemoteAddress();
+ }
+
+ @Override
+ public SocketAddress getLocalAddress() {
+ return ioSession.getLocalAddress();
+ }
+
+ @Override
+ public int getEventMask() {
+ return currentSessionRef.get().getEventMask();
+ }
+
+ @Override
+ public void setEventMask(final int ops) {
+ currentSessionRef.get().setEventMask(ops);
+ }
+
+ @Override
+ public void setEvent(final int op) {
+ currentSessionRef.get().setEvent(op);
+ }
+
+ @Override
+ public void clearEvent(final int op) {
+ currentSessionRef.get().clearEvent(op);
+ }
+
+ @Override
+ public void close() {
+ close(CloseMode.GRACEFUL);
+ }
+
+ @Override
+ public void close(final CloseMode closeMode) {
+ if (closeMode == CloseMode.IMMEDIATE) {
+ ioSession.close(closeMode);
+ } else {
+ currentSessionRef.get().close(closeMode);
+ }
+ }
+
+ @Override
+ public Status getStatus() {
+ return currentSessionRef.get().getStatus();
+ }
+
+ @Override
+ public Timeout getSocketTimeout() {
+ return ioSession.getSocketTimeout();
+ }
+
+ @Override
+ public void setSocketTimeout(final Timeout timeout) {
+ ioSession.setSocketTimeout(timeout);
+ }
+
+ @Override
+ public long getLastReadTime() {
+ return ioSession.getLastReadTime();
+ }
+
+ @Override
+ public long getLastWriteTime() {
+ return ioSession.getLastWriteTime();
+ }
+
+ @Override
+ public long getLastEventTime() {
+ return ioSession.getLastEventTime();
+ }
+
+ @Override
+ public void updateReadTime() {
+ ioSession.updateReadTime();
+ }
+
+ @Override
+ public void updateWriteTime() {
+ ioSession.updateWriteTime();
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) throws IOException {
+ return currentSessionRef.get().read(dst);
+ }
+
+ @Override
+ public int write(final ByteBuffer src) throws IOException {
+ return currentSessionRef.get().write(src);
+ }
+
+ @Override
+ public boolean isOpen() {
+ return currentSessionRef.get().isOpen();
+ }
+
+ @Override
+ public String getId() {
+ return ioSession.getId();
+ }
+
+ @Override
+ public void startTls(
+ final SSLContext sslContext,
+ final NamedEndpoint endpoint,
+ final SSLBufferMode sslBufferMode,
+ final SSLSessionInitializer initializer,
+ final SSLSessionVerifier verifier,
+ final Timeout handshakeTimeout) {
+ startTls(sslContext, endpoint, sslBufferMode, initializer, verifier, handshakeTimeout, null);
+ }
+
+ @Override
+ public void startTls(
+ final SSLContext sslContext,
+ final NamedEndpoint endpoint,
+ final SSLBufferMode sslBufferMode,
+ final SSLSessionInitializer initializer,
+ final SSLSessionVerifier verifier,
+ final Timeout handshakeTimeout,
+ final FutureCallback callback) {
+
+ final SSLIOSession sslioSession = new SSLIOSession(
+ endpoint != null ? endpoint : initialEndpoint,
+ ioSession,
+ SSLMode.CLIENT,
+ sslContext,
+ sslBufferMode,
+ initializer,
+ verifier,
+ handshakeTimeout,
+ null,
+ null,
+ new CallbackContribution(callback) {
+
+ @Override
+ public void completed(final SSLSession sslSession) {
+ if (callback != null) {
+ callback.completed(H2TunnelProtocolIOSession.this);
+ }
+ }
+
+ });
+
+ if (tlsSessionRef.compareAndSet(null, sslioSession)) {
+ currentSessionRef.set(sslioSession);
+ } else {
+ throw new IllegalStateException("TLS already activated");
+ }
+
+ try {
+ sslioSession.beginHandshake(this);
+ } catch (final Exception ex) {
+ if (callback != null) {
+ callback.failed(ex);
+ }
+ close(CloseMode.IMMEDIATE);
+ }
+ }
+
+ @Override
+ public TlsDetails getTlsDetails() {
+ final SSLIOSession sslIoSession = tlsSessionRef.get();
+ return sslIoSession != null ? sslIoSession.getTlsDetails() : null;
+ }
+
+ @Override
+ public int getPendingCommandCount() {
+ return currentSessionRef.get().getPendingCommandCount();
+ }
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolStarter.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolStarter.java
new file mode 100644
index 0000000000..cbad416933
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelProtocolStarter.java
@@ -0,0 +1,74 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package org.apache.hc.client5.http.impl.async;
+
+import org.apache.hc.core5.http.config.CharCodingConfig;
+import org.apache.hc.core5.http.protocol.HttpProcessorBuilder;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler;
+import org.apache.hc.core5.http2.impl.nio.ClientH2StreamMultiplexerFactory;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOEventHandlerFactory;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+
+/**
+ * Minimal {@link IOEventHandlerFactory} for starting HTTP/2 client protocol
+ * inside a CONNECT tunnel session.
+ *
+ * Unlike {@link H2AsyncClientProtocolStarter}, this factory does not
+ * install push consumer handling, frame/header logging listeners, or
+ * exception callbacks. Those concerns belong to the outer proxy
+ * connection, not the tunneled target connection.
+ *
+ *
+ * @since 5.7
+ */
+final class H2TunnelProtocolStarter implements IOEventHandlerFactory {
+
+ private final H2Config h2Config;
+ private final CharCodingConfig charCodingConfig;
+
+ H2TunnelProtocolStarter(
+ final H2Config h2Config,
+ final CharCodingConfig charCodingConfig) {
+ this.h2Config = h2Config != null ? h2Config : H2Config.DEFAULT;
+ this.charCodingConfig = charCodingConfig != null ? charCodingConfig : CharCodingConfig.DEFAULT;
+ }
+
+ @Override
+ public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
+ final ClientH2StreamMultiplexerFactory multiplexerFactory = new ClientH2StreamMultiplexerFactory(
+ HttpProcessorBuilder.create().build(),
+ null,
+ h2Config,
+ charCodingConfig,
+ null);
+ return new ClientH2PrefaceHandler(ioSession, multiplexerFactory, false, null);
+ }
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelRawIOSession.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelRawIOSession.java
new file mode 100644
index 0000000000..4470002fe5
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/H2TunnelRawIOSession.java
@@ -0,0 +1,733 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import java.io.IOException;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ByteChannel;
+import java.nio.channels.CancelledKeyException;
+import java.nio.channels.SelectionKey;
+import java.util.ArrayDeque;
+import java.util.Deque;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.hc.core5.http.StreamControl;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.Timeout;
+
+/**
+ * Raw tunnel {@link IOSession} implementation with bounded buffering,
+ * capacity flow control and stream-scoped close semantics.
+ *
+ * Closing this session cancels only the CONNECT stream,
+ * not the underlying physical HTTP/2 connection.
+ *
+ *
+ * @since 5.7
+ */
+final class H2TunnelRawIOSession implements IOSession {
+
+ private static final int INBOUND_BUFFER_LIMIT = 64 * 1024;
+ private static final int OUTBOUND_BUFFER_LIMIT = 64 * 1024;
+
+ private final IOSession physicalSession;
+ private final String id;
+ private final Lock lock;
+
+ private final Deque commandQueue;
+ private final Deque inboundQueue;
+ private final Deque outboundQueue;
+
+ private final AtomicReference handlerRef;
+ private final AtomicReference dataChannelRef;
+ private final AtomicReference streamControlRef;
+
+ private CapacityChannel capacityChannel;
+ private Timeout socketTimeout;
+ private int eventMask;
+ private Status status;
+
+ private int inboundBytes;
+ private int outboundBytes;
+ private int consumedBytesSinceUpdate;
+
+ private boolean capacityInitialized;
+ private boolean localEndStreamSent;
+ private boolean remoteEndStream;
+
+ private long lastReadTime;
+ private long lastWriteTime;
+ private long lastEventTime;
+
+ H2TunnelRawIOSession(
+ final IOSession physicalSession,
+ final Timeout socketTimeout,
+ final StreamControl streamControl) {
+ this.physicalSession = physicalSession;
+ this.id = physicalSession.getId() + "-h2-tunnel";
+ this.lock = new ReentrantLock();
+ this.commandQueue = new ArrayDeque<>();
+ this.inboundQueue = new ArrayDeque<>();
+ this.outboundQueue = new ArrayDeque<>();
+ this.handlerRef = new AtomicReference<>();
+ this.dataChannelRef = new AtomicReference<>();
+ this.streamControlRef = new AtomicReference<>(streamControl);
+
+ this.capacityChannel = null;
+ this.socketTimeout = socketTimeout;
+ this.eventMask = SelectionKey.OP_READ;
+ this.status = Status.ACTIVE;
+
+ this.capacityInitialized = false;
+ this.localEndStreamSent = false;
+ this.remoteEndStream = false;
+
+ final long now = System.currentTimeMillis();
+ this.lastReadTime = now;
+ this.lastWriteTime = now;
+ this.lastEventTime = now;
+ }
+
+ void bindStreamControl(final StreamControl streamControl) {
+ streamControlRef.compareAndSet(null, streamControl);
+ }
+
+ void attachChannel(final DataStreamChannel channel) {
+ dataChannelRef.set(channel);
+ }
+
+ void updateCapacityChannel(final CapacityChannel capacityChannel) throws IOException {
+ int update = 0;
+ lock.lock();
+ try {
+ this.capacityChannel = capacityChannel;
+ if (!capacityInitialized) {
+ update += Math.max(0, INBOUND_BUFFER_LIMIT - inboundBytes);
+ capacityInitialized = true;
+ }
+ if (consumedBytesSinceUpdate > 0) {
+ update += consumedBytesSinceUpdate;
+ consumedBytesSinceUpdate = 0;
+ }
+ } finally {
+ lock.unlock();
+ }
+ if (update > 0) {
+ capacityChannel.update(update);
+ }
+ }
+
+ void onRemoteStreamEnd() {
+ lock.lock();
+ try {
+ remoteEndStream = true;
+ if (status == Status.ACTIVE) {
+ status = Status.CLOSING;
+ }
+ if (localEndStreamSent) {
+ status = Status.CLOSED;
+ }
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ void requestOutput() {
+ final DataStreamChannel dataChannel = dataChannelRef.get();
+ if (dataChannel == null) {
+ return;
+ }
+ try {
+ dataChannel.requestOutput();
+ } catch (final CancelledKeyException ex) {
+ discard();
+ }
+ }
+
+ int available() {
+ lock.lock();
+ try {
+ if (outboundBytes > 0) {
+ return outboundBytes;
+ }
+ if (!localEndStreamSent && status == Status.CLOSING) {
+ return 1;
+ }
+ if (!commandQueue.isEmpty() || (eventMask & SelectionKey.OP_WRITE) != 0) {
+ return 1;
+ }
+ return 0;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ void appendInput(final ByteBuffer src) throws IOException {
+ if (src == null || !src.hasRemaining()) {
+ return;
+ }
+ lock.lock();
+ try {
+ if (status == Status.CLOSED) {
+ return;
+ }
+ final int remaining = src.remaining();
+ final int freeSpace = INBOUND_BUFFER_LIMIT - inboundBytes;
+ if (remaining > freeSpace) {
+ throw new IOException("Tunnel inbound buffer overflow");
+ }
+ final byte[] data = new byte[remaining];
+ src.get(data);
+ inboundQueue.addLast(ByteBuffer.wrap(data));
+ inboundBytes += data.length;
+ final long now = System.currentTimeMillis();
+ lastReadTime = now;
+ lastEventTime = now;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ int pendingInput() {
+ lock.lock();
+ try {
+ return inboundBytes;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ void discardInbound(final int bytes) throws IOException {
+ if (bytes <= 0) {
+ return;
+ }
+ int remaining = bytes;
+ int update = 0;
+ CapacityChannel currentCapacityChannel = null;
+
+ lock.lock();
+ try {
+ while (remaining > 0) {
+ final ByteBuffer buffer = inboundQueue.peekFirst();
+ if (buffer == null) {
+ break;
+ }
+ final int chunk = Math.min(remaining, buffer.remaining());
+ if (chunk <= 0) {
+ break;
+ }
+ buffer.position(buffer.position() + chunk);
+ remaining -= chunk;
+ inboundBytes -= chunk;
+ if (!buffer.hasRemaining()) {
+ inboundQueue.pollFirst();
+ }
+ consumedBytesSinceUpdate += chunk;
+ }
+ if (capacityChannel != null && consumedBytesSinceUpdate > 0) {
+ currentCapacityChannel = capacityChannel;
+ update = consumedBytesSinceUpdate;
+ consumedBytesSinceUpdate = 0;
+ }
+ } finally {
+ lock.unlock();
+ }
+
+ if (currentCapacityChannel != null && update > 0) {
+ currentCapacityChannel.update(update);
+ }
+ }
+
+ void flushOutput() throws IOException {
+ final DataStreamChannel dataChannel = dataChannelRef.get();
+ if (dataChannel == null) {
+ return;
+ }
+
+ boolean sendEndStream = false;
+
+ lock.lock();
+ try {
+ for (; ; ) {
+ final ByteBuffer buffer = outboundQueue.peekFirst();
+ if (buffer == null) {
+ break;
+ }
+ final int bytesWritten = dataChannel.write(buffer);
+ if (bytesWritten <= 0) {
+ break;
+ }
+ outboundBytes -= bytesWritten;
+ if (!buffer.hasRemaining()) {
+ outboundQueue.pollFirst();
+ }
+ final long now = System.currentTimeMillis();
+ lastWriteTime = now;
+ lastEventTime = now;
+ }
+ if (!localEndStreamSent && status == Status.CLOSING && outboundQueue.isEmpty()) {
+ localEndStreamSent = true;
+ sendEndStream = true;
+ }
+ } finally {
+ lock.unlock();
+ }
+
+ if (sendEndStream) {
+ try {
+ dataChannel.endStream(null);
+ } finally {
+ lock.lock();
+ try {
+ if (remoteEndStream) {
+ status = Status.CLOSED;
+ }
+ } finally {
+ lock.unlock();
+ }
+ }
+ }
+ }
+
+ private void cancelPendingCommands() {
+ for (final Command command : commandQueue) {
+ command.cancel();
+ }
+ commandQueue.clear();
+ }
+
+ private void discard() {
+ lock.lock();
+ try {
+ if (status == Status.CLOSED) {
+ return;
+ }
+ status = Status.CLOSED;
+ localEndStreamSent = true;
+ cancelPendingCommands();
+ inboundQueue.clear();
+ inboundBytes = 0;
+ outboundQueue.clear();
+ outboundBytes = 0;
+ consumedBytesSinceUpdate = 0;
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ private void cancelStream() {
+ final StreamControl streamControl = streamControlRef.get();
+ if (streamControl != null) {
+ streamControl.cancel();
+ }
+ }
+
+ @Override
+ public IOEventHandler getHandler() {
+ return handlerRef.get();
+ }
+
+ @Override
+ public void upgrade(final IOEventHandler handler) {
+ handlerRef.set(handler);
+ }
+
+ @Override
+ public Lock getLock() {
+ return lock;
+ }
+
+ @Override
+ public void enqueue(final Command command, final Command.Priority priority) {
+ if (command == null) {
+ return;
+ }
+ lock.lock();
+ try {
+ if (status != Status.ACTIVE) {
+ command.cancel();
+ return;
+ }
+ if (priority == Command.Priority.IMMEDIATE) {
+ commandQueue.addFirst(command);
+ } else {
+ commandQueue.addLast(command);
+ }
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ requestOutput();
+ }
+
+ @Override
+ public boolean hasCommands() {
+ lock.lock();
+ try {
+ return !commandQueue.isEmpty();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public Command poll() {
+ lock.lock();
+ try {
+ return commandQueue.pollFirst();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public ByteChannel channel() {
+ return this;
+ }
+
+ @Override
+ public SocketAddress getRemoteAddress() {
+ return physicalSession.getRemoteAddress();
+ }
+
+ @Override
+ public SocketAddress getLocalAddress() {
+ return physicalSession.getLocalAddress();
+ }
+
+ @Override
+ public int getEventMask() {
+ lock.lock();
+ try {
+ return eventMask;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void setEventMask(final int ops) {
+ final boolean wantOutput = (ops & SelectionKey.OP_WRITE) != 0;
+ lock.lock();
+ try {
+ eventMask = ops;
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ if (wantOutput) {
+ requestOutput();
+ }
+ }
+
+ @Override
+ public void setEvent(final int op) {
+ final boolean wantOutput = (op & SelectionKey.OP_WRITE) != 0;
+ lock.lock();
+ try {
+ eventMask |= op;
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ if (wantOutput) {
+ requestOutput();
+ }
+ }
+
+ @Override
+ public void clearEvent(final int op) {
+ lock.lock();
+ try {
+ eventMask &= ~op;
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void close() {
+ close(CloseMode.GRACEFUL);
+ }
+
+ @Override
+ public void close(final CloseMode closeMode) {
+ boolean cancel = false;
+
+ lock.lock();
+ try {
+ if (status == Status.CLOSED) {
+ return;
+ }
+ if (closeMode == CloseMode.IMMEDIATE) {
+ status = Status.CLOSED;
+ localEndStreamSent = true;
+ cancelPendingCommands();
+ inboundQueue.clear();
+ inboundBytes = 0;
+ outboundQueue.clear();
+ outboundBytes = 0;
+ consumedBytesSinceUpdate = 0;
+ cancel = true;
+ } else {
+ status = Status.CLOSING;
+ if (dataChannelRef.get() == null && outboundBytes == 0) {
+ status = Status.CLOSED;
+ localEndStreamSent = true;
+ cancel = true;
+ }
+ }
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+
+ if (cancel) {
+ cancelStream();
+ } else {
+ requestOutput();
+ }
+ }
+
+ @Override
+ public Status getStatus() {
+ lock.lock();
+ try {
+ return status;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public Timeout getSocketTimeout() {
+ lock.lock();
+ try {
+ return socketTimeout;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void setSocketTimeout(final Timeout timeout) {
+ lock.lock();
+ try {
+ socketTimeout = timeout;
+ lastEventTime = System.currentTimeMillis();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public long getLastReadTime() {
+ lock.lock();
+ try {
+ return lastReadTime;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public long getLastWriteTime() {
+ lock.lock();
+ try {
+ return lastWriteTime;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public long getLastEventTime() {
+ lock.lock();
+ try {
+ return lastEventTime;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void updateReadTime() {
+ final long now = System.currentTimeMillis();
+ lock.lock();
+ try {
+ lastReadTime = now;
+ lastEventTime = now;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void updateWriteTime() {
+ final long now = System.currentTimeMillis();
+ lock.lock();
+ try {
+ lastWriteTime = now;
+ lastEventTime = now;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) throws IOException {
+ int total = 0;
+ int update = 0;
+ CapacityChannel currentCapacityChannel = null;
+
+ lock.lock();
+ try {
+ if (inboundQueue.isEmpty()) {
+ return remoteEndStream || status == Status.CLOSED ? -1 : 0;
+ }
+ while (dst.hasRemaining()) {
+ final ByteBuffer buffer = inboundQueue.peekFirst();
+ if (buffer == null) {
+ break;
+ }
+ final int chunk = Math.min(dst.remaining(), buffer.remaining());
+ if (chunk <= 0) {
+ break;
+ }
+
+ if (buffer.hasArray()) {
+ final int pos = buffer.position();
+ dst.put(buffer.array(), buffer.arrayOffset() + pos, chunk);
+ buffer.position(pos + chunk);
+ } else {
+ for (int i = 0; i < chunk; i++) {
+ dst.put(buffer.get());
+ }
+ }
+
+ total += chunk;
+ inboundBytes -= chunk;
+ if (!buffer.hasRemaining()) {
+ inboundQueue.pollFirst();
+ }
+ }
+
+ if (total > 0) {
+ consumedBytesSinceUpdate += total;
+ final long now = System.currentTimeMillis();
+ lastReadTime = now;
+ lastEventTime = now;
+ if (capacityChannel != null && consumedBytesSinceUpdate > 0) {
+ currentCapacityChannel = capacityChannel;
+ update = consumedBytesSinceUpdate;
+ consumedBytesSinceUpdate = 0;
+ }
+ }
+ } finally {
+ lock.unlock();
+ }
+
+ if (currentCapacityChannel != null && update > 0) {
+ currentCapacityChannel.update(update);
+ }
+ return total;
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ if (src == null || !src.hasRemaining()) {
+ return 0;
+ }
+ int bytesAccepted = 0;
+
+ lock.lock();
+ try {
+ if (status != Status.ACTIVE) {
+ return 0;
+ }
+ final int freeSpace = OUTBOUND_BUFFER_LIMIT - outboundBytes;
+ if (freeSpace <= 0) {
+ return 0;
+ }
+ bytesAccepted = Math.min(src.remaining(), freeSpace);
+ if (bytesAccepted <= 0) {
+ return 0;
+ }
+
+ final byte[] data = new byte[bytesAccepted];
+ src.get(data);
+
+ outboundQueue.addLast(ByteBuffer.wrap(data));
+ outboundBytes += bytesAccepted;
+
+ final long now = System.currentTimeMillis();
+ lastWriteTime = now;
+ lastEventTime = now;
+ } finally {
+ lock.unlock();
+ }
+
+ requestOutput();
+ return bytesAccepted;
+ }
+
+ @Override
+ public boolean isOpen() {
+ lock.lock();
+ try {
+ return status != Status.CLOSED && physicalSession.isOpen();
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public String getId() {
+ return id;
+ }
+
+ @Override
+ public int getPendingCommandCount() {
+ lock.lock();
+ try {
+ return commandQueue.size();
+ } finally {
+ lock.unlock();
+ }
+ }
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClients.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClients.java
index 7afd03ccf0..a419c6360b 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClients.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/HttpAsyncClients.java
@@ -276,12 +276,16 @@ public static MinimalHttpAsyncClient createMinimal(final AsyncClientConnectionMa
private static MinimalH2AsyncClient createMinimalHttp2AsyncClientImpl(
final IOEventHandlerFactory eventHandlerFactory,
final AsyncPushConsumerRegistry pushConsumerRegistry,
+ final H2Config h2Config,
+ final CharCodingConfig charCodingConfig,
final IOReactorConfig ioReactorConfig,
final DnsResolver dnsResolver,
final TlsStrategy tlsStrategy) {
return new MinimalH2AsyncClient(
eventHandlerFactory,
pushConsumerRegistry,
+ h2Config,
+ charCodingConfig,
ioReactorConfig,
new DefaultThreadFactory("httpclient-main", true),
new DefaultThreadFactory("httpclient-dispatch", true),
@@ -307,6 +311,8 @@ public static MinimalH2AsyncClient createHttp2Minimal(
CharCodingConfig.DEFAULT,
LoggingExceptionCallback.INSTANCE),
pushConsumerRegistry,
+ h2Config,
+ CharCodingConfig.DEFAULT,
ioReactorConfig,
dnsResolver,
tlsStrategy);
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncClient.java
index e4321994cf..242ada3c1c 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncClient.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncClient.java
@@ -102,12 +102,11 @@ AsyncExecRuntime createAsyncExecRuntime(final HandlerFactory
}
@Override
- HttpRoute determineRoute(final HttpHost httpHost, final HttpRequest request, final HttpClientContext clientContext) throws HttpException {
- final HttpRoute route = routePlanner.determineRoute(httpHost, request, clientContext);
- if (route.isTunnelled()) {
- throw new HttpException("HTTP/2 tunneling not supported");
- }
- return route;
+ HttpRoute determineRoute(
+ final HttpHost httpHost,
+ final HttpRequest request,
+ final HttpClientContext clientContext) throws HttpException {
+ return routePlanner.determineRoute(httpHost, request, clientContext);
}
@Override
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java
index 734cec0d09..5c11c9bbaf 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2AsyncExecRuntime.java
@@ -182,6 +182,12 @@ Endpoint ensureValid() {
return endpoint;
}
+ @Override
+ public HttpRoute getEstablishedRoute() {
+ final Endpoint endpoint = sessionRef.get();
+ return endpoint != null ? endpoint.route : null;
+ }
+
@Override
public Cancellable connectEndpoint(
final HttpClientContext context,
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2ConnPool.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2ConnPool.java
index 125f4482ff..528ee2d2be 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2ConnPool.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/InternalH2ConnPool.java
@@ -45,6 +45,7 @@
import org.apache.hc.core5.http2.nio.support.BasicPingHandler;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.io.ModalCloseable;
+import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.reactor.AbstractIOSessionPool;
import org.apache.hc.core5.reactor.Command;
import org.apache.hc.core5.reactor.ConnectionInitiator;
@@ -63,7 +64,16 @@ class InternalH2ConnPool implements ModalCloseable {
final ConnectionInitiator connectionInitiator,
final Resolver addressResolver,
final TlsStrategy tlsStrategy) {
- this.sessionPool = new SessionPool(clock, connectionInitiator, addressResolver, tlsStrategy);
+ this(clock, connectionInitiator, addressResolver, tlsStrategy, null);
+ }
+
+ InternalH2ConnPool(
+ final Clock clock,
+ final ConnectionInitiator connectionInitiator,
+ final Resolver addressResolver,
+ final TlsStrategy tlsStrategy,
+ final H2RouteOperator routeOperator) {
+ this.sessionPool = new SessionPool(clock, connectionInitiator, addressResolver, tlsStrategy, routeOperator);
}
@Override
@@ -96,17 +106,20 @@ static class SessionPool extends AbstractIOSessionPool {
private final ConnectionInitiator connectionInitiator;
private final Resolver addressResolver;
private final TlsStrategy tlsStrategy;
+ private final H2RouteOperator routeOperator;
private volatile Resolver connectionConfigResolver;
SessionPool(final Clock clock,
final ConnectionInitiator connectionInitiator,
final Resolver addressResolver,
- final TlsStrategy tlsStrategy) {
+ final TlsStrategy tlsStrategy,
+ final H2RouteOperator routeOperator) {
super(clock);
this.connectionInitiator = connectionInitiator;
this.addressResolver = addressResolver;
this.tlsStrategy = tlsStrategy;
+ this.routeOperator = routeOperator;
}
public void setConnectionConfigResolver(final Resolver connectionConfigResolver) {
@@ -117,13 +130,16 @@ public void setConnectionConfigResolver(final Resolver connectSession(final HttpRoute route,
final Timeout timeout,
final FutureCallback callback) {
+ final HttpHost proxy = route.getProxyHost();
final HttpHost target = route.getTargetHost();
+ final HttpHost firstHop = proxy != null ? proxy : target;
+ final NamedEndpoint firstHopName = proxy == null && route.getTargetName() != null ? route.getTargetName() : firstHop;
final InetSocketAddress localAddress = route.getLocalSocketAddress();
- final InetSocketAddress remoteAddress = addressResolver.resolve(target);
+ final InetSocketAddress remoteAddress = addressResolver.resolve(firstHop);
final ConnectionConfig connectionConfig = resolveConnectionConfig(route);
final Timeout connectTimeout = timeout != null ? timeout : connectionConfig.getConnectTimeout();
return connectionInitiator.connect(
- target,
+ firstHopName,
remoteAddress,
localAddress,
connectTimeout,
@@ -134,12 +150,12 @@ protected Future connectSession(final HttpRoute route,
public void completed(final IOSession ioSession) {
final Timeout socketTimeout = connectionConfig.getSocketTimeout();
if (tlsStrategy != null
- && URIScheme.HTTPS.same(target.getSchemeName())
+ && URIScheme.HTTPS.same(firstHop.getSchemeName())
&& ioSession instanceof TransportSecurityLayer) {
ioSession.setSocketTimeout(connectTimeout);
tlsStrategy.upgrade(
(TransportSecurityLayer) ioSession,
- target,
+ firstHopName,
null,
connectTimeout,
new CallbackContribution(callback) {
@@ -149,7 +165,7 @@ public void completed(final TransportSecurityLayer transportSecurityLayer) {
if (socketTimeout != null) {
ioSession.setSocketTimeout(socketTimeout);
}
- callback.completed(ioSession);
+ completeRoute(route, connectTimeout, ioSession, callback);
}
});
@@ -157,13 +173,25 @@ public void completed(final TransportSecurityLayer transportSecurityLayer) {
if (socketTimeout != null) {
ioSession.setSocketTimeout(socketTimeout);
}
- callback.completed(ioSession);
+ completeRoute(route, connectTimeout, ioSession, callback);
}
}
});
}
+ private void completeRoute(
+ final HttpRoute route,
+ final Timeout connectTimeout,
+ final IOSession ioSession,
+ final FutureCallback callback) {
+ if (routeOperator != null) {
+ routeOperator.completeRoute(route, connectTimeout, ioSession, callback);
+ } else {
+ callback.completed(ioSession);
+ }
+ }
+
@Override
protected void validateSession(final HttpRoute route,
final IOSession ioSession,
@@ -195,9 +223,10 @@ protected void closeSession(final IOSession ioSession,
}
ConnectionConfig resolveConnectionConfig(final HttpRoute route) {
- final HttpHost target = route.getTargetHost();
+ final HttpHost proxy = route.getProxyHost();
+ final HttpHost firstHop = proxy != null ? proxy : route.getTargetHost();
final Resolver localResolver = connectionConfigResolver;
- final ConnectionConfig connectionConfig = localResolver != null ? localResolver.resolve(target) : null;
+ final ConnectionConfig connectionConfig = localResolver != null ? localResolver.resolve(firstHop) : null;
return connectionConfig != null ? connectionConfig : ConnectionConfig.DEFAULT;
}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/MinimalH2AsyncClient.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/MinimalH2AsyncClient.java
index d3a3ca0e43..43375a9082 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/MinimalH2AsyncClient.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/MinimalH2AsyncClient.java
@@ -55,6 +55,7 @@
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.URIScheme;
import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
import org.apache.hc.core5.http.nio.AsyncPushConsumer;
import org.apache.hc.core5.http.nio.CapacityChannel;
@@ -62,9 +63,11 @@
import org.apache.hc.core5.http.nio.HandlerFactory;
import org.apache.hc.core5.http.nio.RequestChannel;
import org.apache.hc.core5.http.nio.command.RequestExecutionCommand;
+import org.apache.hc.core5.http.config.CharCodingConfig;
import org.apache.hc.core5.http.nio.command.ShutdownCommand;
import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
import org.apache.hc.core5.http.protocol.HttpContext;
+import org.apache.hc.core5.http2.config.H2Config;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.reactor.Command;
import org.apache.hc.core5.reactor.ConnectionInitiator;
@@ -80,8 +83,7 @@
/**
* Minimal implementation of HTTP/2 only {@link CloseableHttpAsyncClient}. This client
* is optimized for HTTP/2 multiplexing message transport and does not support advanced
- * HTTP protocol functionality such as request execution via a proxy, state management,
- * authentication and request redirects.
+ * HTTP protocol functionality such as state management, authentication and request redirects.
*
* Concurrent message exchanges with the same connection route executed by
* this client will get automatically multiplexed over a single physical HTTP/2
@@ -100,6 +102,8 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
MinimalH2AsyncClient(
final IOEventHandlerFactory eventHandlerFactory,
final AsyncPushConsumerRegistry pushConsumerRegistry,
+ final H2Config h2Config,
+ final CharCodingConfig charCodingConfig,
final IOReactorConfig reactorConfig,
final ThreadFactory threadFactory,
final ThreadFactory workerThreadFactory,
@@ -116,7 +120,14 @@ public final class MinimalH2AsyncClient extends AbstractMinimalHttpAsyncClientBa
pushConsumerRegistry,
threadFactory);
this.connectionInitiator = new MultihomeConnectionInitiator(getConnectionInitiator(), dnsResolver);
- this.connPool = new InternalH2ConnPool(Clock.systemUTC(), this.connectionInitiator, object -> null, tlsStrategy);
+ this.connPool = new InternalH2ConnPool(
+ Clock.systemUTC(),
+ this.connectionInitiator,
+ object -> null,
+ tlsStrategy,
+ new H2RouteOperator(
+ tlsStrategy,
+ new H2TunnelProtocolStarter(h2Config, charCodingConfig)));
}
@Override
@@ -145,8 +156,14 @@ public Cancellable execute(
final Timeout connectTimeout = requestConfig.getConnectTimeout();
final Timeout responseTimeout = requestConfig.getResponseTimeout();
final HttpHost target = new HttpHost(request.getScheme(), request.getAuthority());
+ final HttpHost proxy = requestConfig.getProxy();
+ final HttpRoute route = proxy != null ? new HttpRoute(
+ target,
+ null,
+ proxy,
+ URIScheme.HTTPS.same(target.getSchemeName())) : new HttpRoute(target);
- final Future sessionFuture = connPool.getSession(new HttpRoute(target), connectTimeout,
+ final Future sessionFuture = connPool.getSession(route, connectTimeout,
new FutureCallback() {
@Override
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/TunnelRefusedException.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/TunnelRefusedException.java
new file mode 100644
index 0000000000..3852b2b97b
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/async/TunnelRefusedException.java
@@ -0,0 +1,86 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import org.apache.hc.core5.http.Header;
+import org.apache.hc.core5.http.HttpException;
+import org.apache.hc.core5.http.HttpResponse;
+import org.apache.hc.core5.http.message.BasicHttpResponse;
+import org.apache.hc.core5.http.message.StatusLine;
+import org.apache.hc.core5.util.Args;
+
+/**
+ * Exception indicating CONNECT tunnel refusal by the proxy.
+ *
+ * @since 5.7
+ */
+public final class TunnelRefusedException extends HttpException {
+
+ private static final long serialVersionUID = 1L;
+
+ private final HttpResponse response;
+
+ /**
+ * Creates a new exception from the proxy response that refused the tunnel.
+ *
+ * @param response the non-2xx CONNECT response from the proxy
+ * @since 5.7
+ */
+ public TunnelRefusedException(final HttpResponse response) {
+ super("Tunnel refused: " + new StatusLine(Args.notNull(response, "Response")));
+ this.response = copy(response);
+ }
+
+ /**
+ * Returns a defensive copy of the proxy response that refused the tunnel.
+ *
+ * @return the proxy response
+ * @since 5.7
+ */
+ public HttpResponse getResponse() {
+ return response;
+ }
+
+ /**
+ * Returns the HTTP status code of the proxy response.
+ *
+ * @return the status code (e.g. 407 for proxy authentication required)
+ * @since 5.7
+ */
+ public int getStatusCode() {
+ return response.getCode();
+ }
+
+ private static HttpResponse copy(final HttpResponse response) {
+ final BasicHttpResponse copy = new BasicHttpResponse(response.getCode(), response.getReasonPhrase());
+ copy.setVersion(response.getVersion());
+ for (final Header header : response.getHeaders()) {
+ copy.addHeader(header);
+ }
+ return copy;
+ }
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
index 04e34466e8..cb7c613920 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/auth/AuthenticationHandler.java
@@ -28,13 +28,13 @@
package org.apache.hc.client5.http.impl.auth;
import java.util.ArrayList;
-import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Queue;
-import java.util.stream.Collectors;
import org.apache.hc.client5.http.AuthenticationStrategy;
import org.apache.hc.client5.http.auth.AuthChallenge;
@@ -44,6 +44,7 @@
import org.apache.hc.client5.http.auth.ChallengeType;
import org.apache.hc.client5.http.auth.CredentialsProvider;
import org.apache.hc.client5.http.auth.MalformedChallengeException;
+import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.protocol.HttpClientContext;
import org.apache.hc.core5.annotation.Contract;
import org.apache.hc.core5.annotation.Internal;
@@ -164,37 +165,30 @@ public boolean isChallengeExpected(final AuthExchange authExchange) {
return authScheme != null && authScheme.isChallengeExpected();
}
- private Map extractChallengeMap(
- final ChallengeType challengeType,
- final HttpResponse response) throws ParseException {
- final List authChallenges = new ArrayList<>(10);
- MessageSupport.parseHeadersStrict(
- response,
- challengeType == ChallengeType.PROXY ? HttpHeaders.PROXY_AUTHENTICATE : HttpHeaders.WWW_AUTHENTICATE,
- (buffer, cursor) ->
- parser.parse(challengeType, authChallenges, buffer, cursor));
-
- return authChallenges.stream()
- .collect(Collectors.toMap(
- c -> c.getSchemeName().toLowerCase(Locale.ROOT),
- c -> c,
- (c1, c2) -> c1));
- }
-
public Map extractChallengeMap(
final ChallengeType challengeType,
final HttpResponse response,
final HttpClientContext context) {
- try {
- return extractChallengeMap(challengeType, response);
- } catch (final ParseException ex) {
- if (LOG.isWarnEnabled()) {
- final HttpClientContext clientContext = HttpClientContext.cast(context);
- final String exchangeId = clientContext.getExchangeId();
- LOG.warn("{} Malformed challenge", exchangeId);
+ final Map challengeMap = new HashMap<>();
+ final Iterator it = response.headerIterator(
+ challengeType == ChallengeType.PROXY ? HttpHeaders.PROXY_AUTHENTICATE : HttpHeaders.WWW_AUTHENTICATE);
+ while (it.hasNext()) {
+ try {
+ final List authChallenges = new ArrayList<>();
+ MessageSupport.parseHeaderStrict(it.next(), (buffer, cursor) ->
+ parser.parse(challengeType, authChallenges, buffer, cursor));
+ for (final AuthChallenge authChallenge : authChallenges) {
+ challengeMap.putIfAbsent(authChallenge.getSchemeName().toLowerCase(Locale.ROOT), authChallenge);
+ }
+ } catch (final ParseException ex) {
+ if (LOG.isWarnEnabled()) {
+ final HttpClientContext clientContext = HttpClientContext.cast(context);
+ final String exchangeId = clientContext.getExchangeId();
+ LOG.warn("{} Malformed challenge", exchangeId);
+ }
}
- return Collections.emptyMap();
}
+ return challengeMap;
}
/**
@@ -373,6 +367,47 @@ public boolean handleResponse(
return false;
}
+ /**
+ * Determines whether proxy authentication is needed for the given response,
+ * updating the {@link AuthExchange} and auth cache state as appropriate.
+ *
+ * @since 5.7
+ */
+ public boolean needProxyAuthentication(
+ final AuthExchange proxyAuthExchange,
+ final HttpHost proxy,
+ final HttpResponse response,
+ final AuthenticationStrategy proxyAuthStrategy,
+ final AuthCacheKeeper authCacheKeeper,
+ final HttpClientContext context) throws AuthenticationException, MalformedChallengeException {
+ final RequestConfig config = context.getRequestConfigOrDefault();
+ if (config.isAuthenticationEnabled()) {
+ final boolean proxyAuthRequested = isChallenged(
+ proxy, ChallengeType.PROXY, response, proxyAuthExchange, context);
+ final boolean proxyMutualAuthRequired = isChallengeExpected(proxyAuthExchange);
+
+ if (authCacheKeeper != null) {
+ if (proxyAuthRequested) {
+ authCacheKeeper.updateOnChallenge(proxy, null, proxyAuthExchange, context);
+ } else {
+ authCacheKeeper.updateOnNoChallenge(proxy, null, proxyAuthExchange, context);
+ }
+ }
+
+ if (proxyAuthRequested || proxyMutualAuthRequired) {
+ final boolean updated = handleResponse(
+ proxy, ChallengeType.PROXY, response, proxyAuthStrategy, proxyAuthExchange, context);
+
+ if (authCacheKeeper != null) {
+ authCacheKeeper.updateOnResponse(proxy, null, proxyAuthExchange, context);
+ }
+
+ return updated;
+ }
+ }
+ return false;
+ }
+
/**
* Generates a response to the authentication challenge based on the actual {@link AuthExchange} state
* and adds it to the given {@link HttpRequest} message .
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
index a5f616865f..062d861d93 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperator.java
@@ -32,6 +32,7 @@
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.file.Path;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -89,11 +90,24 @@ public class DefaultHttpClientConnectionOperator implements HttpClientConnection
static final DetachedSocketFactory PLAIN_SOCKET_FACTORY = socksProxy -> socksProxy == null ? new Socket() : new Socket(socksProxy);
+ /**
+ * RFC 8305, Section 8: "When a reasonable value is unknown, implementations SHOULD use a
+ * Connection Attempt Delay of 250 milliseconds".
+ */
+ static final TimeValue DEFAULT_CONNECTION_ATTEMPT_DELAY = TimeValue.ofMilliseconds(250);
+
+ /**
+ * RFC 8305, Section 8: "this value SHOULD NOT be below 10 ms".
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
private final DetachedSocketFactory detachedSocketFactory;
private final UnixDomainSocketFactory unixDomainSocketFactory = UnixDomainSocketFactory.getSocketFactory();
private final Lookup tlsSocketStrategyLookup;
private final SchemePortResolver schemePortResolver;
private final DnsResolver dnsResolver;
+ private final boolean happyEyeballsEnabled;
+ private final TimeValue connectionAttemptDelay;
/**
* @deprecated Provided for backward compatibility
@@ -115,6 +129,19 @@ public DefaultHttpClientConnectionOperator(
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver,
final Lookup tlsSocketStrategyLookup) {
+ this(detachedSocketFactory, schemePortResolver, dnsResolver, tlsSocketStrategyLookup, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ public DefaultHttpClientConnectionOperator(
+ final DetachedSocketFactory detachedSocketFactory,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final Lookup tlsSocketStrategyLookup,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
super();
this.detachedSocketFactory = Args.notNull(detachedSocketFactory, "Plain socket factory");
this.tlsSocketStrategyLookup = Args.notNull(tlsSocketStrategyLookup, "Socket factory registry");
@@ -122,6 +149,13 @@ public DefaultHttpClientConnectionOperator(
DefaultSchemePortResolver.INSTANCE;
this.dnsResolver = dnsResolver != null ? dnsResolver :
SystemDefaultDnsResolver.INSTANCE;
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ final TimeValue delay = connectionAttemptDelay != null ? connectionAttemptDelay : DEFAULT_CONNECTION_ATTEMPT_DELAY;
+ if (happyEyeballsEnabled) {
+ Args.check(delay.toMilliseconds() >= MIN_CONNECTION_ATTEMPT_DELAY_MS,
+ "Connection attempt delay must be at least %s ms (RFC 8305, Section 8)", MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ }
+ this.connectionAttemptDelay = delay;
}
/**
@@ -200,6 +234,105 @@ public void connect(
final int port = this.schemePortResolver.resolve(endpointHost.getSchemeName(), endpointHost);
remoteAddresses = this.dnsResolver.resolve(endpointHost.getHostName(), port);
}
+
+ // A specific, non-ephemeral local port can only ever be bound by one socket at a
+ // time; racing would bind several attempts to it concurrently, and the OS would
+ // reject all but one with a bind conflict instead of a real connect failure. Fall
+ // back to the existing sequential path in that case, exactly as before this feature,
+ // since only one attempt is ever in flight there.
+ final boolean canRace = localAddress == null || localAddress.getPort() == 0;
+ if (happyEyeballsEnabled && canRace && remoteAddresses.size() > 1) {
+ onBeforeSocketConnect(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} racing connection attempts across {} ({})", endpointHost, remoteAddresses, connectTimeout);
+ }
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(connectionAttemptDelay);
+ final Socket socket = connector.connect(endpointHost, remoteAddresses, (remoteAddress, socketConsumer) -> {
+ final Socket attemptSocket = detachedSocketFactory.create(endpointHost.getSchemeName(), socksProxy);
+ socketConsumer.accept(attemptSocket);
+ try {
+ if (localAddress != null) {
+ attemptSocket.bind(localAddress);
+ }
+ configureSocket(attemptSocket, socketConfig, true);
+ attemptSocket.connect(remoteAddress, TimeValue.isPositive(connectTimeout) ? connectTimeout.toMillisecondsIntBound() : 0);
+ return attemptSocket;
+ } catch (final IOException | RuntimeException ex) {
+ Closer.closeQuietly(attemptSocket);
+ throw ex;
+ }
+ });
+ // The winner is already TCP-connected; identify its address so a TLS failure
+ // below can fall back to whichever addresses the race did not settle on,
+ // without retrying this one.
+ final InetSocketAddress winnerAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
+ try {
+ conn.bind(socket);
+ onAfterSocketConnect(context, endpointHost);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(conn), endpointHost, conn.getLocalAddress(), conn.getRemoteAddress());
+ }
+ final TlsSocketStrategy tlsSocketStrategy = tlsSocketStrategyLookup != null ? tlsSocketStrategyLookup.lookup(endpointHost.getSchemeName()) : null;
+ if (tlsSocketStrategy != null) {
+ upgradeToTls(conn, endpointHost, endpointName, connectTimeout, attachment, context, tlsSocketStrategy, socket);
+ }
+ } catch (final RuntimeException ex) {
+ Closer.closeQuietly(socket);
+ throw ex;
+ } catch (final IOException ex) {
+ Closer.closeQuietly(socket);
+ final List remaining = withoutAddress(remoteAddresses, winnerAddress);
+ if (remaining.isEmpty()) {
+ throw ConnectExceptionSupport.enhance(ex, endpointHost);
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{} connection to {} failed after racing ({}); retrying connection to the remaining address(es)", endpointHost, winnerAddress, ex.getClass());
+ }
+ connectSequentially(conn, endpointHost, endpointName, localAddress, remaining, connectTimeout, socketConfig, attachment, context, socksProxy);
+ return;
+ }
+ return;
+ }
+
+ connectSequentially(conn, endpointHost, endpointName, localAddress, remoteAddresses, connectTimeout, socketConfig, attachment, context, socksProxy);
+ }
+
+ /**
+ * Removes the first occurrence of {@code excluded} from {@code addresses}, preserving the
+ * order of the rest.
+ */
+ private static List withoutAddress(
+ final List addresses, final InetSocketAddress excluded) {
+ final List remaining = new ArrayList<>(addresses.size());
+ boolean removedOne = false;
+ for (final InetSocketAddress address : addresses) {
+ if (!removedOne && address.equals(excluded)) {
+ removedOne = true;
+ continue;
+ }
+ remaining.add(address);
+ }
+ return remaining;
+ }
+
+ /**
+ * Connects to each of {@code remoteAddresses} in turn, stopping at the first one that
+ * completes both the TCP connection and, where configured, the TLS handshake. An
+ * {@link IOException} from either step moves on to the next address; the last address's
+ * failure is rethrown, enhanced via {@link ConnectExceptionSupport}. A {@link
+ * RuntimeException} is never retried, exactly as on the address it was thrown for.
+ */
+ private void connectSequentially(
+ final ManagedHttpClientConnection conn,
+ final HttpHost endpointHost,
+ final NamedEndpoint endpointName,
+ final InetSocketAddress localAddress,
+ final List remoteAddresses,
+ final Timeout connectTimeout,
+ final SocketConfig socketConfig,
+ final Object attachment,
+ final HttpContext context,
+ final Proxy socksProxy) throws IOException {
for (int i = 0; i < remoteAddresses.size(); i++) {
final InetSocketAddress remoteAddress = remoteAddresses.get(i);
final boolean last = i == remoteAddresses.size() - 1;
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java
new file mode 100644
index 0000000000..ffbc0cf640
--- /dev/null
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java
@@ -0,0 +1,293 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.io;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorCompletionService;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.Consumer;
+
+import org.apache.hc.client5.http.ConnectExceptionSupport;
+import org.apache.hc.core5.concurrent.DefaultThreadFactory;
+import org.apache.hc.core5.io.Closer;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.util.TimeValue;
+
+/**
+ * Races a blocking connect attempt against each of a host's resolved addresses (RFC 8305,
+ * Happy Eyeballs v2) for the Classic (blocking) client. A single dispatcher, running on the
+ * calling thread, starts the first address immediately and each subsequent one on its own
+ * worker thread, bounded to the number of resolved addresses: it waits up to
+ * {@link #connectionAttemptDelay} for an outstanding attempt to finish before starting the
+ * next one, but starts the next one immediately, at the RFC 8305 Section 5 minimum spacing
+ * (10ms), as soon as an attempt fails. No thread ever sleeps out a delay itself.
+ *
+ * The first attempt to connect successfully wins the race. Because closing a socket is
+ * the only reliable way to abort a blocking {@link Socket#connect}, every other socket, be it
+ * already connecting, about to be registered, or not yet created, must end up closed; a
+ * worker thread registers its socket through a shared, atomic registry rather than a bare
+ * reference, so a socket created in the brief window around the race being decided is always
+ * either excluded from cleanup because it does not exist yet, or closed by the registry the
+ * instant it is registered. {@code ExecutorService#shutdownNow()} only interrupts threads; it
+ * does not itself abort a blocking connect, so it is never relied on for that.
+ *
+ * @since 5.7
+ */
+final class HappyEyeballsSocketConnector {
+
+ /**
+ * RFC 8305, Section 5: the minimum spacing between the start of successive connection
+ * attempts, including one started promptly after an earlier attempt's failure.
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
+ /**
+ * Connects a single socket to {@code remoteAddress}, registering the socket via
+ * {@code socketConsumer} as soon as it is created and before the (blocking) connect
+ * call, so that a concurrent winner can close it even while still connecting.
+ */
+ @FunctionalInterface
+ interface ConnectAttempt {
+ Socket connect(InetSocketAddress remoteAddress, Consumer socketConsumer) throws IOException;
+ }
+
+ /**
+ * Registers each attempt's socket so it can be closed by whichever happens first: this
+ * race deciding a winner, or the socket being registered. {@link #decide} and
+ * {@link #register} coordinate purely through {@link #decided} and the per-slot
+ * {@link AtomicReference}, so neither a socket registered just before {@link #decide}
+ * runs nor one registered just after is ever left open: {@link #decide} closes whatever
+ * it finds already registered, and {@link #register} closes its own socket immediately
+ * if it finds the registry already decided, including re-checking right after
+ * registering to catch a {@link #decide} that ran in between.
+ */
+ private static final class SocketRegistry {
+
+ private final AtomicReference[] slots;
+ private final AtomicBoolean decided = new AtomicBoolean(false);
+
+ @SuppressWarnings("unchecked")
+ SocketRegistry(final int n) {
+ slots = new AtomicReference[n];
+ for (int i = 0; i < n; i++) {
+ slots[i] = new AtomicReference<>();
+ }
+ }
+
+ void register(final int index, final Socket socket) {
+ if (decided.get()) {
+ Closer.closeQuietly(socket);
+ return;
+ }
+ slots[index].set(socket);
+ if (decided.get() && slots[index].compareAndSet(socket, null)) {
+ Closer.closeQuietly(socket);
+ }
+ }
+
+ /** Closes every registered socket except {@code winner} (may be {@code null}). */
+ void decide(final Socket winner) {
+ decided.set(true);
+ for (final AtomicReference slot : slots) {
+ final Socket socket = slot.getAndSet(null);
+ if (socket != null && socket != winner) {
+ Closer.closeQuietly(socket);
+ }
+ }
+ }
+ }
+
+ private final TimeValue connectionAttemptDelay;
+
+ HappyEyeballsSocketConnector(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ }
+
+ Socket connect(
+ final NamedEndpoint remoteEndpoint,
+ final List remoteAddresses,
+ final ConnectAttempt connectAttempt) throws IOException {
+ final int n = remoteAddresses.size();
+ final ExecutorService executor = Executors.newFixedThreadPool(
+ n, new DefaultThreadFactory("Happy-eyeballs-classic-connect", true));
+ final SocketRegistry registry = new SocketRegistry(n);
+ final List> futures = new ArrayList<>(n);
+ Socket winner = null;
+ try {
+ final ExecutorCompletionService completionService = new ExecutorCompletionService<>(executor);
+ futures.add(submit(completionService, 0, remoteAddresses, connectAttempt, registry));
+ int started = 1;
+ long lastStartNanos = System.nanoTime();
+ IOException lastFailure = null;
+
+ for (int received = 0; received < n && winner == null; ) {
+ final Future completed;
+ if (started < n) {
+ final long waitMs = pendingDelayMs(lastStartNanos, connectionAttemptDelay.toMilliseconds());
+ completed = poll(completionService, waitMs);
+ if (completed == null) {
+ // Nothing finished within the delay: start the next address now.
+ futures.add(submit(completionService, started, remoteAddresses, connectAttempt, registry));
+ started++;
+ lastStartNanos = System.nanoTime();
+ continue;
+ }
+ } else {
+ completed = take(completionService);
+ }
+ received++;
+
+ final Outcome outcome;
+ try {
+ outcome = completed.get();
+ } catch (final ExecutionException ex) {
+ final Throwable cause = ex.getCause();
+ lastFailure = cause instanceof IOException ? (IOException) cause : new IOException(cause);
+ continue;
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ if (outcome.socket != null) {
+ winner = outcome.socket;
+ for (final Future future : futures) {
+ future.cancel(true);
+ }
+ break;
+ }
+ if (outcome.failure != null) {
+ lastFailure = outcome.failure;
+ }
+ if (started < n) {
+ // Advance as promptly as RFC 8305 allows, but never closer than the
+ // minimum spacing to the most recently started attempt.
+ final long waitMs = pendingDelayMs(lastStartNanos, MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ if (waitMs > 0) {
+ sleepOrAbort(waitMs);
+ }
+ futures.add(submit(completionService, started, remoteAddresses, connectAttempt, registry));
+ started++;
+ lastStartNanos = System.nanoTime();
+ }
+ }
+ if (winner != null) {
+ return winner;
+ }
+ throw lastFailure != null ?
+ ConnectExceptionSupport.enhance(lastFailure, remoteEndpoint) :
+ new IOException("Connection to " + remoteEndpoint + " failed for an unknown reason");
+ } finally {
+ // The single point of truth for cleanup, covering every exit path (winner found,
+ // every address failed, or this method itself was interrupted): closes every
+ // socket except the winner (if any), including ones registered concurrently with
+ // this call. shutdownNow() only interrupts worker threads; it cannot itself abort
+ // a blocking Socket#connect, so the registry above is what actually does that.
+ registry.decide(winner);
+ executor.shutdownNow();
+ }
+ }
+
+ private static long pendingDelayMs(final long lastStartNanos, final long targetDelayMs) {
+ final long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastStartNanos);
+ return Math.max(0, targetDelayMs - elapsedMs);
+ }
+
+ /**
+ * Blocks the dispatcher thread itself for a bounded, short minimum-spacing gap (at most
+ * {@link #MIN_CONNECTION_ATTEMPT_DELAY_MS}). Unlike the per-address stagger this replaces,
+ * this never delays a worker thread's connect attempt and never exceeds a few
+ * milliseconds, so it does not amount to the blocking the rest of this class avoids. An
+ * interruption here must abort racing immediately, exactly like one during {@link #poll}
+ * or {@link #take}: it is propagated rather than swallowed, so the caller's {@code finally}
+ * block runs cleanup and no further attempt is started.
+ */
+ private static void sleepOrAbort(final long millis) throws InterruptedIOException {
+ try {
+ Thread.sleep(millis);
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future poll(final ExecutorCompletionService completionService, final long timeoutMs) throws InterruptedIOException {
+ try {
+ return completionService.poll(timeoutMs, TimeUnit.MILLISECONDS);
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future take(final ExecutorCompletionService completionService) throws InterruptedIOException {
+ try {
+ return completionService.take();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ throw new InterruptedIOException("Interrupted while racing connection attempts");
+ }
+ }
+
+ private static Future submit(
+ final ExecutorCompletionService completionService,
+ final int index,
+ final List remoteAddresses,
+ final ConnectAttempt connectAttempt,
+ final SocketRegistry registry) {
+ final InetSocketAddress remoteAddress = remoteAddresses.get(index);
+ return completionService.submit(() -> {
+ try {
+ final Socket socket = connectAttempt.connect(remoteAddress, socket1 -> registry.register(index, socket1));
+ return new Outcome(socket, null);
+ } catch (final IOException ex) {
+ return new Outcome(null, ex);
+ }
+ });
+ }
+
+ private static final class Outcome {
+ final Socket socket;
+ final IOException failure;
+
+ Outcome(final Socket socket, final IOException failure) {
+ this.socket = socket;
+ this.failure = failure;
+ }
+ }
+
+}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
index 5256d32033..4fe6a21ca4 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/PoolingHttpClientConnectionManagerBuilder.java
@@ -65,6 +65,8 @@ public class PoolingHttpClientConnectionManagerBuilder {
private TlsSocketStrategy tlsSocketStrategy;
private SchemePortResolver schemePortResolver;
private DnsResolver dnsResolver;
+ private boolean happyEyeballsEnabled;
+ private TimeValue connectionAttemptDelay;
private PoolConcurrencyPolicy poolConcurrencyPolicy;
private PoolReusePolicy poolReusePolicy;
private Resolver socketConfigResolver;
@@ -145,6 +147,41 @@ public final PoolingHttpClientConnectionManagerBuilder setDnsResolver(final DnsR
return this;
}
+ /**
+ * Enables RFC 8305 (Happy Eyeballs v2) connection racing for hosts that resolve to more
+ * than one address: the first address is tried immediately, on its own thread, and each
+ * subsequent one on its own thread after {@link #setConnectionAttemptDelay(TimeValue)}
+ * unless an outstanding attempt fails first. The first successful connection wins; every
+ * other attempt's socket is closed. Disabled ({@code false}) by default, in which case
+ * addresses continue to be tried sequentially on the calling thread.
+ * This feature is considered experimental and may be discontinued in the future.
+ *
+ * @param happyEyeballsEnabled whether to race connection attempts.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingHttpClientConnectionManagerBuilder setHappyEyeballsEnabled(final boolean happyEyeballsEnabled) {
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ return this;
+ }
+
+ /**
+ * Sets the delay between the start of successive connection attempts when
+ * {@link #setHappyEyeballsEnabled(boolean)} is enabled. RFC 8305 Section 8 recommends
+ * 250ms and requires at least 10ms. Has no effect unless Happy Eyeballs racing is enabled.
+ *
+ * @param connectionAttemptDelay the delay, or {@code null} to use the RFC 8305
+ * recommended default of 250ms.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingHttpClientConnectionManagerBuilder setConnectionAttemptDelay(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ return this;
+ }
+
/**
* Sets {@link SchemePortResolver} instance.
*
@@ -346,7 +383,9 @@ protected HttpClientConnectionOperator createConnectionOperator(
dnsResolver,
RegistryBuilder.create()
.register(URIScheme.HTTPS.id, tlsSocketStrategy)
- .build());
+ .build(),
+ happyEyeballsEnabled,
+ connectionAttemptDelay);
}
public PoolingHttpClientConnectionManager build() {
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
index 64b7dbe9bb..6bf559f4d6 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperator.java
@@ -60,6 +60,7 @@
import org.apache.hc.core5.reactor.IOSession;
import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,9 +86,21 @@ protected DefaultAsyncClientConnectionOperator(
final Lookup tlsStrategyLookup,
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver) {
+ this(tlsStrategyLookup, schemePortResolver, dnsResolver, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ protected DefaultAsyncClientConnectionOperator(
+ final Lookup tlsStrategyLookup,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
this.tlsStrategyLookup = Args.notNull(tlsStrategyLookup, "TLS strategy lookup");
this.schemePortResolver = schemePortResolver != null ? schemePortResolver : DefaultSchemePortResolver.INSTANCE;
- this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver);
+ this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay);
}
@Override
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
index 2e8e00bbf0..04ff6e09e1 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeConnectionInitiator.java
@@ -38,6 +38,7 @@
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
/**
@@ -58,6 +59,36 @@ public MultihomeConnectionInitiator(
this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver);
}
+ /**
+ * Creates a multi-home connection initiator that, for hosts resolving to more than one
+ * address, optionally races connection attempts per RFC 8305 (Happy Eyeballs v2) instead
+ * of trying each address sequentially: the first address is tried immediately, and each
+ * subsequent one after {@code connectionAttemptDelay} unless an outstanding attempt fails
+ * first. The first successful connection wins; every other attempt is cancelled, and a
+ * connection that completes after a winner was already decided is closed rather than kept
+ * open. When {@code happyEyeballsEnabled} is {@code false}, behavior is identical to
+ * {@link #MultihomeConnectionInitiator(ConnectionInitiator, DnsResolver)}.
+ *
+ * @param connectionInitiator the connection initiator.
+ * @param dnsResolver the DNS resolver to use.
+ * @param happyEyeballsEnabled whether to race connection attempts instead of trying them
+ * sequentially.
+ * @param connectionAttemptDelay delay between the start of successive connection attempts
+ * (RFC 8305 Section 8 recommends 250ms; must be at least
+ * 10ms). Ignored when {@code happyEyeballsEnabled} is
+ * {@code false}. May be {@code null} to use the RFC 8305
+ * recommended default.
+ * @since 5.7
+ */
+ public MultihomeConnectionInitiator(
+ final ConnectionInitiator connectionInitiator,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
+ this.connectionInitiator = Args.notNull(connectionInitiator, "Connection initiator");
+ this.sessionRequester = new MultihomeIOSessionRequester(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay);
+ }
+
@Override
public Future connect(
final NamedEndpoint remoteEndpoint,
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
index 4b8172c4ce..58c80cb13a 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequester.java
@@ -32,18 +32,29 @@
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
+import java.util.ArrayList;
import java.util.List;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.Executors;
import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.hc.client5.http.ConnectExceptionSupport;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.apache.hc.core5.concurrent.Cancellable;
import org.apache.hc.core5.concurrent.ComplexFuture;
+import org.apache.hc.core5.concurrent.DefaultThreadFactory;
import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.Args;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -51,10 +62,65 @@
final class MultihomeIOSessionRequester {
private static final Logger LOG = LoggerFactory.getLogger(MultihomeIOSessionRequester.class);
+
+ /**
+ * RFC 8305, Section 8: "When a reasonable value is unknown, implementations SHOULD use a
+ * Connection Attempt Delay of 250 milliseconds".
+ */
+ static final TimeValue DEFAULT_CONNECTION_ATTEMPT_DELAY = TimeValue.ofMilliseconds(250);
+
+ /**
+ * RFC 8305, Section 8: "this value SHOULD NOT be below 10 ms".
+ */
+ private static final long MIN_CONNECTION_ATTEMPT_DELAY_MS = 10;
+
+ /**
+ * Lazily initialized, process-wide, single daemon-thread scheduler used solely to pace
+ * staggered connection attempts (RFC 8305 connection racing). Shared across all instances
+ * so that enabling this feature never adds a thread per connection manager, let alone per
+ * connection or per request.
+ */
+ private static final class LazyStaggerScheduler {
+ static final ScheduledExecutorService INSTANCE = Executors.newSingleThreadScheduledExecutor(
+ new DefaultThreadFactory("Connection-attempt-stagger", true));
+ }
+
private final DnsResolver dnsResolver;
+ private final boolean happyEyeballsEnabled;
+ private final TimeValue connectionAttemptDelay;
+ private final ScheduledExecutorService staggerScheduler;
MultihomeIOSessionRequester(final DnsResolver dnsResolver) {
+ this(dnsResolver, false, DEFAULT_CONNECTION_ATTEMPT_DELAY);
+ }
+
+ MultihomeIOSessionRequester(
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
+ this(dnsResolver, happyEyeballsEnabled, connectionAttemptDelay, null);
+ }
+
+ // Package-private: allows unit tests to supply a deterministic, synchronous scheduler
+ // instead of the real, time-based one.
+ MultihomeIOSessionRequester(
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay,
+ final ScheduledExecutorService staggerScheduler) {
this.dnsResolver = dnsResolver != null ? dnsResolver : SystemDefaultDnsResolver.INSTANCE;
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ final TimeValue delay = connectionAttemptDelay != null ? connectionAttemptDelay : DEFAULT_CONNECTION_ATTEMPT_DELAY;
+ if (happyEyeballsEnabled) {
+ Args.check(delay.toMilliseconds() >= MIN_CONNECTION_ATTEMPT_DELAY_MS,
+ "Connection attempt delay must be at least %s ms (RFC 8305, Section 8)", MIN_CONNECTION_ATTEMPT_DELAY_MS);
+ }
+ this.connectionAttemptDelay = delay;
+ this.staggerScheduler = staggerScheduler;
+ }
+
+ private ScheduledExecutorService staggerScheduler() {
+ return staggerScheduler != null ? staggerScheduler : LazyStaggerScheduler.INSTANCE;
}
public Future connect(
@@ -123,6 +189,13 @@ public void cancelled() {
LOG.debug("{} resolved to {}", remoteEndpoint.getHostName(), remoteAddresses);
}
+ if (happyEyeballsEnabled && remoteAddresses.size() > 1) {
+ final Race race = new Race(connectionInitiator, remoteEndpoint, remoteAddresses, localAddress,
+ connectTimeout, attachment, future);
+ race.start();
+ return future;
+ }
+
final Runnable runnable = new Runnable() {
private final AtomicInteger attempt = new AtomicInteger(0);
@@ -207,4 +280,293 @@ public Future connect(
return connect(connectionInitiator, remoteEndpoint, null, localAddress, connectTimeout, attachment, callback);
}
+ /**
+ * RFC 8305 connection racing: the first address is tried immediately; each subsequent
+ * address is tried after {@link #connectionAttemptDelay} unless an outstanding attempt
+ * fails first, in which case the next address is tried immediately. The first successful
+ * connection wins: all other outstanding attempts are cancelled, and any connection that
+ * completes successfully after a winner has already been decided is closed rather than
+ * leaked. Exactly one terminal callback (success or aggregated failure) ever reaches
+ * {@code future}.
+ */
+ private final class Race implements Cancellable {
+
+ private final ConnectionInitiator connectionInitiator;
+ private final NamedEndpoint remoteEndpoint;
+ private final List remoteAddresses;
+ private final SocketAddress localAddress;
+ private final Timeout connectTimeout;
+ private final Object attachment;
+ private final ComplexFuture future;
+
+ private final Object lock = new Object();
+ private final List> inFlight = new ArrayList<>();
+ private int nextIndex;
+ private int outstanding;
+ private boolean decided;
+ private boolean cancelled;
+ private ScheduledFuture> pendingStagger;
+ private long lastAttemptStartNanos = -1L;
+
+ Race(
+ final ConnectionInitiator connectionInitiator,
+ final NamedEndpoint remoteEndpoint,
+ final List remoteAddresses,
+ final SocketAddress localAddress,
+ final Timeout connectTimeout,
+ final Object attachment,
+ final ComplexFuture future) {
+ this.connectionInitiator = connectionInitiator;
+ this.remoteEndpoint = remoteEndpoint;
+ this.remoteAddresses = remoteAddresses;
+ this.localAddress = localAddress;
+ this.connectTimeout = connectTimeout;
+ this.attachment = attachment;
+ this.future = future;
+ // A single Cancellable dependency covers every attempt this race ever starts,
+ // including ones not yet started when the caller cancels (see #cancel()).
+ this.future.setDependency(this);
+ }
+
+ void start() {
+ synchronized (lock) {
+ scheduleNextPromptlyLocked();
+ }
+ }
+
+ /**
+ * Starts the next address now if at least the RFC 8305 Section 5 minimum
+ * inter-attempt spacing (10ms) has passed since the last attempt was started,
+ * including one that just failed or was unexpectedly cancelled; otherwise schedules
+ * it for exactly the remaining part of that minimum. Used whenever an attempt should
+ * advance as promptly as RFC 8305 allows, rather than waiting out the full
+ * {@link #connectionAttemptDelay}.
+ *
+ * Must be called while holding {@code lock}.
+ */
+ private void scheduleNextPromptlyLocked() {
+ if (decided || cancelled || nextIndex >= remoteAddresses.size()) {
+ return;
+ }
+ if (lastAttemptStartNanos < 0) {
+ startNextLocked();
+ return;
+ }
+ final long elapsedMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - lastAttemptStartNanos);
+ if (elapsedMs >= MIN_CONNECTION_ATTEMPT_DELAY_MS) {
+ startNextLocked();
+ } else {
+ pendingStagger = staggerScheduler().schedule(
+ this::onStaggerElapsed, MIN_CONNECTION_ATTEMPT_DELAY_MS - elapsedMs, TimeUnit.MILLISECONDS);
+ }
+ }
+
+ // Must be called while holding `lock`.
+ private void startNextLocked() {
+ if (decided || cancelled || nextIndex >= remoteAddresses.size()) {
+ return;
+ }
+ final int index = nextIndex++;
+ final InetSocketAddress remoteAddress = remoteAddresses.get(index);
+ outstanding++;
+ lastAttemptStartNanos = System.nanoTime();
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} racing attempt {} {}->{} ({})",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), index, localAddress, remoteAddress, connectTimeout);
+ }
+
+ final Future attemptFuture = connectionInitiator.connect(
+ remoteEndpoint,
+ remoteAddress,
+ localAddress,
+ connectTimeout,
+ attachment,
+ new FutureCallback() {
+
+ @Override
+ public void completed(final IOSession session) {
+ onAttemptCompleted(remoteAddress, session);
+ }
+
+ @Override
+ public void failed(final Exception cause) {
+ onAttemptFailed(remoteAddress, cause);
+ }
+
+ @Override
+ public void cancelled() {
+ onAttemptCancelled(remoteAddress);
+ }
+
+ });
+ inFlight.add(attemptFuture);
+
+ // pendingStagger != null here means the attempt above already completed
+ // synchronously and its own failure/cancellation handler already scheduled the
+ // next advance (possibly at the shorter minimum spacing): don't overwrite it.
+ if (!decided && !cancelled && pendingStagger == null && nextIndex < remoteAddresses.size()) {
+ pendingStagger = staggerScheduler().schedule(
+ this::onStaggerElapsed, connectionAttemptDelay.getDuration(), connectionAttemptDelay.getTimeUnit());
+ }
+ }
+
+ private void onStaggerElapsed() {
+ synchronized (lock) {
+ pendingStagger = null;
+ startNextLocked();
+ }
+ }
+
+ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOSession session) {
+ final boolean won;
+ final List> losers;
+ synchronized (lock) {
+ outstanding--;
+ won = !decided && !cancelled;
+ if (won) {
+ decided = true;
+ cancelPendingStaggerLocked();
+ losers = new ArrayList<>(inFlight);
+ } else {
+ losers = null;
+ }
+ }
+ if (won) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} race won by {}->{} as {}",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
+ }
+ for (final Future loser : losers) {
+ loser.cancel(true);
+ }
+ // future may already have been cancelled directly by the caller (not through
+ // this Race's own #cancel()) in the brief window between the checks above and
+ // here: ComplexFuture#completed() returns false in that case, and the session
+ // must still be closed rather than silently leaked.
+ if (!future.completed(session)) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} race won by {}->{} as {} but the future was already done; closing",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
+ }
+ session.close(CloseMode.IMMEDIATE);
+ }
+ } else {
+ // A duplicate winner (concurrent success) or a late completion after the
+ // race was already decided/cancelled: never leak the socket.
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} discarding late successful connection {}->{} ({})",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId());
+ }
+ session.close(CloseMode.IMMEDIATE);
+ }
+ }
+
+ private void onAttemptFailed(final InetSocketAddress remoteAddress, final Exception cause) {
+ boolean advance = false;
+ boolean last = false;
+ synchronized (lock) {
+ outstanding--;
+ if (decided || cancelled) {
+ return;
+ }
+ cancelPendingStaggerLocked();
+ if (nextIndex < remoteAddresses.size()) {
+ advance = true;
+ } else if (outstanding == 0) {
+ decided = true;
+ last = true;
+ }
+ if (advance) {
+ // RFC 8305 Section 5: advance to the next address as promptly as possible
+ // after a failure, never waiting out the full connection attempt delay,
+ // but still respecting the minimum inter-attempt spacing.
+ scheduleNextPromptlyLocked();
+ }
+ }
+ if (last) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection to {} failed ({}); all addresses exhausted",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass());
+ }
+ finish(cause);
+ }
+ }
+
+ /**
+ * An attempt may be cancelled by something other than this race itself deciding a
+ * winner or being cancelled as a whole, for example an external close of the
+ * connection manager. Treat it exactly like a failure so the overall future never
+ * stays pending forever: advance to the next address if one remains, or finish with a
+ * failure if none does.
+ */
+ private void onAttemptCancelled(final InetSocketAddress remoteAddress) {
+ boolean advance = false;
+ boolean last = false;
+ synchronized (lock) {
+ outstanding--;
+ if (decided || cancelled) {
+ // Expected: either this race decided a winner and cancelled every other
+ // attempt itself, or the whole race was cancelled from the outside.
+ return;
+ }
+ cancelPendingStaggerLocked();
+ if (nextIndex < remoteAddresses.size()) {
+ advance = true;
+ } else if (outstanding == 0) {
+ decided = true;
+ last = true;
+ }
+ if (advance) {
+ scheduleNextPromptlyLocked();
+ }
+ }
+ if (last) {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("{}:{} connection attempt to {} was unexpectedly cancelled; all addresses exhausted",
+ remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress);
+ }
+ finish(new CancellationException(
+ "Connection attempt to " + remoteAddress + " was cancelled"));
+ }
+ }
+
+ private void finish(final Exception cause) {
+ if (cause instanceof IOException) {
+ final InetAddress[] addresses = remoteAddresses.stream()
+ .map(InetSocketAddress::getAddress)
+ .toArray(InetAddress[]::new);
+ future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses));
+ } else {
+ future.failed(cause);
+ }
+ }
+
+ @Override
+ public boolean cancel() {
+ final List> toCancel;
+ synchronized (lock) {
+ if (decided || cancelled) {
+ return false;
+ }
+ cancelled = true;
+ cancelPendingStaggerLocked();
+ toCancel = new ArrayList<>(inFlight);
+ }
+ for (final Future attemptFuture : toCancel) {
+ attemptFuture.cancel(true);
+ }
+ return true;
+ }
+
+ // Must be called while holding `lock`.
+ private void cancelPendingStaggerLocked() {
+ if (pendingStagger != null) {
+ pendingStagger.cancel(false);
+ pendingStagger = null;
+ }
+ }
+
+ }
+
}
diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
index a4e1b8fe48..17900c9017 100644
--- a/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
+++ b/httpclient5/src/main/java/org/apache/hc/client5/http/impl/nio/PoolingAsyncClientConnectionManagerBuilder.java
@@ -35,6 +35,7 @@
import org.apache.hc.client5.http.nio.AsyncClientConnectionOperator;
import org.apache.hc.client5.http.ssl.ConscryptClientTlsStrategy;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
+import org.apache.hc.core5.annotation.Experimental;
import org.apache.hc.core5.annotation.Internal;
import org.apache.hc.core5.function.Resolver;
import org.apache.hc.core5.http.HttpHost;
@@ -57,6 +58,8 @@ public class PoolingAsyncClientConnectionManagerBuilder {
private TlsStrategy tlsStrategy;
private SchemePortResolver schemePortResolver;
private DnsResolver dnsResolver;
+ private boolean happyEyeballsEnabled;
+ private TimeValue connectionAttemptDelay;
private PoolConcurrencyPolicy poolConcurrencyPolicy;
private PoolReusePolicy poolReusePolicy;
@@ -99,6 +102,40 @@ public final PoolingAsyncClientConnectionManagerBuilder setDnsResolver(final Dns
return this;
}
+ /**
+ * Enables RFC 8305 (Happy Eyeballs v2) connection racing for hosts that resolve to more
+ * than one address: the first address is tried immediately, and each subsequent one after
+ * {@link #setConnectionAttemptDelay(TimeValue)} unless an outstanding attempt fails first.
+ * The first successful connection wins; every other attempt is cancelled. Disabled
+ * ({@code false}) by default, in which case addresses continue to be tried sequentially.
+ * This feature is considered experimental and may be discontinued in the future.
+ *
+ * @param happyEyeballsEnabled whether to race connection attempts.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingAsyncClientConnectionManagerBuilder setHappyEyeballsEnabled(final boolean happyEyeballsEnabled) {
+ this.happyEyeballsEnabled = happyEyeballsEnabled;
+ return this;
+ }
+
+ /**
+ * Sets the delay between the start of successive connection attempts when
+ * {@link #setHappyEyeballsEnabled(boolean)} is enabled. RFC 8305 Section 8 recommends
+ * 250ms and requires at least 10ms. Has no effect unless Happy Eyeballs racing is enabled.
+ *
+ * @param connectionAttemptDelay the delay, or {@code null} to use the RFC 8305
+ * recommended default of 250ms.
+ * @return this instance.
+ * @since 5.7
+ */
+ @Experimental
+ public final PoolingAsyncClientConnectionManagerBuilder setConnectionAttemptDelay(final TimeValue connectionAttemptDelay) {
+ this.connectionAttemptDelay = connectionAttemptDelay;
+ return this;
+ }
+
/**
* Sets {@link SchemePortResolver} instance.
*
@@ -267,12 +304,27 @@ protected AsyncClientConnectionOperator createConnectionOperator(
final TlsStrategy tlsStrategy,
final SchemePortResolver schemePortResolver,
final DnsResolver dnsResolver) {
+ return createConnectionOperator(tlsStrategy, schemePortResolver, dnsResolver, false, null);
+ }
+
+ /**
+ * @since 5.7
+ */
+ @Internal
+ protected AsyncClientConnectionOperator createConnectionOperator(
+ final TlsStrategy tlsStrategy,
+ final SchemePortResolver schemePortResolver,
+ final DnsResolver dnsResolver,
+ final boolean happyEyeballsEnabled,
+ final TimeValue connectionAttemptDelay) {
return new DefaultAsyncClientConnectionOperator(
RegistryBuilder.create()
.register(URIScheme.HTTPS.getId(), tlsStrategy)
.build(),
schemePortResolver,
- dnsResolver);
+ dnsResolver,
+ happyEyeballsEnabled,
+ connectionAttemptDelay);
}
public PoolingAsyncClientConnectionManager build() {
@@ -287,7 +339,8 @@ public PoolingAsyncClientConnectionManager build() {
}
}
final PoolingAsyncClientConnectionManager poolingmgr = new PoolingAsyncClientConnectionManager(
- createConnectionOperator(tlsStrategyCopy, schemePortResolver, dnsResolver),
+ createConnectionOperator(tlsStrategyCopy, schemePortResolver, dnsResolver,
+ happyEyeballsEnabled, connectionAttemptDelay),
poolConcurrencyPolicy,
poolReusePolicy,
null,
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java
new file mode 100644
index 0000000000..ee42db20f5
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java
@@ -0,0 +1,657 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package org.apache.hc.client5.http;
+
+import static org.junit.jupiter.api.Assertions.assertArrayEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.hc.client5.http.config.ProtocolFamilyPreference;
+import org.apache.hc.client5.http.impl.InMemoryDnsResolver;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class AddressSelectingDnsResolverTest {
+
+ private static final AddressSelectingDnsResolver.SourceAddressResolver NO_SOURCE_ADDR =
+ (final InetSocketAddress dest) -> null;
+
+ private InMemoryDnsResolver delegate;
+
+ @BeforeEach
+ void setUp() {
+ delegate = new InMemoryDnsResolver();
+ }
+
+ @Test
+ void ipv4Only_filtersOutIPv6() throws Exception {
+ final InetAddress v4 = inet("203.0.113.10"); // TEST-NET-3
+ final InetAddress v6 = inet("2001:db8::10"); // documentation prefix
+
+ delegate.add("dual.example", v6, v4);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("dual.example");
+ assertEquals(1, ordered.length);
+ assertInstanceOf(Inet4Address.class, ordered[0]);
+ assertEquals(v4, ordered[0]);
+ }
+
+ @Test
+ void ipv6Only_filtersOutIPv4() throws Exception {
+ final InetAddress v4 = inet("192.0.2.1"); // TEST-NET-1
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("dual.example", v4, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV6_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("dual.example");
+ assertEquals(1, ordered.length);
+ assertInstanceOf(Inet6Address.class, ordered[0]);
+ assertEquals(v6, ordered[0]);
+ }
+
+ @Test
+ void ipv4Only_emptyWhenNoIPv4Candidates() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("v6only.example", v6a, v6b);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final InetAddress[] ordered = r.resolve("v6only.example");
+ assertNull(ordered);
+ }
+
+ @Test
+ void default_hasNoFamilyBias() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v4b = inet("203.0.113.10");
+
+ delegate.add("dual.example", v6a, v6b, v4a, v4b);
+
+ final AddressSelectingDnsResolver r1 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+ final AddressSelectingDnsResolver r2 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out1 = r1.resolve("dual.example");
+ final InetAddress[] out2 = r2.resolve("dual.example");
+
+ assertArrayEquals(out1, out2);
+ assertEquals(4, out1.length);
+ }
+
+ @Test
+ void interleave_alternatesFamilies_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v6b = inet("2001:db8::2");
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v4b = inet("203.0.113.10");
+
+ // With NO_SOURCE_ADDR, RFC sort becomes a stable no-op; deterministic interleave.
+ delegate.add("dual.example", v6a, v6b, v4a, v4b);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("dual.example");
+ assertEquals(Arrays.asList(v6a, v4a, v6b, v4b), Arrays.asList(out));
+ }
+
+ @Test
+ void preferIpv6_groupsAllV6First_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v4b = inet("203.0.113.10");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("dual.example", v4a, v6a, v4b, v6b);
+
+ final AddressSelectingDnsResolver preferV6 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV6, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = preferV6.resolve("dual.example");
+ assertEquals(Arrays.asList(v6a, v6b, v4a, v4b), Arrays.asList(out));
+ assertInstanceOf(Inet6Address.class, out[0]);
+ }
+
+ @Test
+ void filtersOutMulticastDestinations() throws Exception {
+ final InetAddress multicastV6 = inet("ff02::1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("mcast.example", multicastV6, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("mcast.example");
+ assertEquals(1, out.length);
+ assertEquals(v6, out[0]);
+ }
+
+ // -------------------------------------------------------------------------
+ // Direct tests for classifyScope(..) and Scope.fromValue(..)
+ // -------------------------------------------------------------------------
+
+ @Test
+ void classifyScope_ipv6Loopback_isLinkLocal() throws Exception {
+ // ::1 maps to link-local scope; interface-local (0x1) is multicast-only (RFC 4291 §2.7).
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("::1")));
+ }
+
+ @Test
+ void classifyScope_ipv4Loopback_isLinkLocal() throws Exception {
+ // IPv4 127/8 maps to link-local, NOT interface-local (RFC 6724 §3.1).
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("127.0.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("127.255.255.255")));
+ }
+
+ @Test
+ void classifyScope_linkLocal() throws Exception {
+ // IPv4 169.254/16 → link-local.
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("169.254.0.1")));
+ // IPv6 fe80::/10 → link-local.
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("fe80::1")));
+ }
+
+ @Test
+ void classifyScope_ipv4Private_isGlobal() throws Exception {
+ // RFC 6724: all IPv4 except 127/8 and 169.254/16 are global,
+ // including RFC1918 (10/8, 172.16/12, 192.168/16) and 100.64/10.
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("10.0.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("172.16.0.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("192.168.1.1")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("100.64.0.1")));
+ }
+
+ @Test
+ void classifyScope_ipv6SiteLocal() throws Exception {
+ // IPv6 deprecated site-local (fec0::/10) still classified as site-local per RFC 6724.
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("fec0::1")));
+ }
+
+ @Test
+ void classifyScope_global() throws Exception {
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("8.8.8.8")));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("2003::1")));
+ }
+
+ @Test
+ void classifyScope_ipv6Multicast_usesLowNibbleScope() throws Exception {
+ // ff01::1 -> scope 0x1 -> INTERFACE_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.INTERFACE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff01::1")));
+ // ff02::1 -> scope 0x2 -> LINK_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff02::1")));
+ // ff04::1 -> scope 0x4 -> ADMIN_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.ADMIN_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff04::1")));
+ // ff05::1 -> scope 0x5 -> SITE_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff05::1")));
+ // ff08::1 -> scope 0x8 -> ORG_LOCAL
+ assertEquals(AddressSelectingDnsResolver.Scope.ORG_LOCAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff08::1")));
+ // ff0e::1 -> scope 0xe -> GLOBAL
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff0e::1")));
+ }
+
+ @Test
+ void scopeFromValue_mapsKnownConstants() {
+ assertEquals(AddressSelectingDnsResolver.Scope.INTERFACE_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x1));
+ assertEquals(AddressSelectingDnsResolver.Scope.LINK_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x2));
+ assertEquals(AddressSelectingDnsResolver.Scope.ADMIN_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x4));
+ assertEquals(AddressSelectingDnsResolver.Scope.SITE_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x5));
+ assertEquals(AddressSelectingDnsResolver.Scope.ORG_LOCAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0x8));
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.Scope.fromValue(0xe));
+ }
+
+ @Test
+ void scopeFromValue_throwsOnUnknownValue() {
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0x0));
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0x3));
+ assertThrows(IllegalArgumentException.class,
+ () -> AddressSelectingDnsResolver.Scope.fromValue(0xf));
+ }
+
+ @Test
+ void rfcRule2_prefersMatchingScope() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1");
+ final InetAddress bDst = inet("2001:db8::2");
+
+ // A matches scope (GLOBAL == GLOBAL); B mismatches (GLOBAL != LINK_LOCAL)
+ final InetAddress aSrc = inet("2001:db8::abcd");
+ final InetAddress bSrc = inet("fe80::1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule5_prefersMatchingLabel() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1"); // label 5 (2001::/32)
+ final InetAddress bDst = inet("2001:db8::2"); // label 5
+
+ final InetAddress aSrc = inet("2001:db8::abcd"); // label 5 -> matches A
+ final InetAddress bSrc = inet("::ffff:192.0.2.1"); // label 4 -> does not match B
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule6_prefersHigherPrecedence() throws Exception {
+ final InetAddress aDst = inet("::1"); // precedence 50 (policy ::1)
+ final InetAddress bDst = inet("2001:db8::1"); // precedence 5 (policy 2001::/32)
+
+ final InetAddress aSrc = inet("::1");
+ final InetAddress bSrc = inet("2001:db8::abcd");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule8_prefersSmallerScope_whenPrecedenceAndLabelTie() throws Exception {
+ // Both fall to ::/0 policy -> precedence 40, label 1, but different scopes.
+ final InetAddress aDst = inet("fe80::1"); // LINK_LOCAL scope (0x2)
+ final InetAddress bDst = inet("2003::1"); // GLOBAL scope (0xe)
+
+ final InetAddress aSrc = inet("fe80::2"); // LINK_LOCAL, label 1
+ final InetAddress bSrc = inet("2003::2"); // GLOBAL, label 1
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule9_prefersLongestMatchingPrefix_ipv6Only() throws Exception {
+ // Both in same policy (::/0 -> prec 40, label 1), same scope (GLOBAL).
+ // A's source shares a longer prefix with its destination than B's.
+ final InetAddress aDst = inet("2003::1");
+ final InetAddress bDst = inet("2003::1:0:0:1");
+
+ // aSrc shares a full /64 with aDst; bSrc only shares /48.
+ final InetAddress aSrc = inet("2003::2");
+ final InetAddress bSrc = inet("2003::2:0:0:1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ // A has longer common prefix (src=2003::2, dst=2003::1 share 127 bits)
+ // B has shorter common prefix (src=2003::2:0:0:1, dst=2003::1:0:0:1 share 79 bits)
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void classifyScope_unknownMulticastNibble_fallsBackToGlobal() throws Exception {
+ // ff03::1 -> scope nibble 0x3, which is not a known Scope constant.
+ assertEquals(AddressSelectingDnsResolver.Scope.GLOBAL,
+ AddressSelectingDnsResolver.classifyScope(inet("ff03::1")));
+ }
+
+ @Test
+ void addr_fmt_simpleName() throws Exception {
+ assertEquals("null", AddressSelectingDnsResolver.addr(null));
+
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ assertEquals("IPv4(" + v4.getHostAddress() + ")", AddressSelectingDnsResolver.addr(v4));
+ assertEquals("IPv6(" + v6.getHostAddress() + ")", AddressSelectingDnsResolver.addr(v6));
+
+ assertEquals(Arrays.asList("IPv6(" + v6.getHostAddress() + ")", "IPv4(" + v4.getHostAddress() + ")"),
+ AddressSelectingDnsResolver.fmt(new InetAddress[]{v6, v4}));
+
+ assertEquals(Arrays.asList("IPv4(" + v4.getHostAddress() + ")", "IPv6(" + v6.getHostAddress() + ")"),
+ AddressSelectingDnsResolver.fmt(Arrays.asList(v4, v6)));
+
+ }
+
+ private static InetAddress inet(final String s) {
+ try {
+ return InetAddress.getByName(s);
+ } catch (final UnknownHostException ex) {
+ throw new AssertionError(ex);
+ }
+ }
+
+ private static AddressSelectingDnsResolver.SourceAddressResolver sourceMap(
+ final InetAddress aDst, final InetAddress aSrc,
+ final InetAddress bDst, final InetAddress bSrc) {
+ return (final InetSocketAddress dest) -> {
+ final InetAddress d = dest.getAddress();
+ if (aDst.equals(d)) {
+ return aSrc;
+ }
+ if (bDst.equals(d)) {
+ return bSrc;
+ }
+ return null;
+ };
+ }
+
+
+ @Test
+ void ipv4Only_filtersSingleV6Address() throws Exception {
+ // Regression: a single IPv6 address must still be filtered when IPV4_ONLY is set.
+ final InetAddress v6 = inet("2001:db8::1");
+ delegate.add("v6.example", v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ assertNull(r.resolve("v6.example"));
+ }
+
+ @Test
+ void resolveHostPort_appliesRfc6724Ordering() throws Exception {
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress v6 = inet("2001:db8::1");
+
+ delegate.add("dual.example", v4, v6);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ final List out = r.resolve("dual.example", 443);
+ assertEquals(1, out.size());
+ assertEquals(new InetSocketAddress(v4, 443), out.get(0));
+ }
+
+ @Test
+ void resolveHostPort_throwsWhenAllFilteredOut() throws Exception {
+ // Only IPv6 addresses, but IPV4_ONLY is requested.
+ // Must throw rather than returning an unresolved address that bypasses filtering.
+ delegate.add("v6.example", inet("2001:db8::1"));
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR);
+
+ assertThrows(UnknownHostException.class, () -> r.resolve("v6.example", 443));
+ }
+
+ @Test
+ void rfcRule9_appliesToIpv4Pairs() throws Exception {
+ // Both IPv4, same policy (::ffff:0:0/96 → prec 35, label 4), same scope (GLOBAL).
+ // Rule 9 should prefer the address whose source shares a longer prefix.
+ final InetAddress aDst = inet("192.0.2.1");
+ final InetAddress bDst = inet("203.0.113.1");
+
+ // aSrc shares 24 bits with aDst (192.0.2.x); bSrc shares only 8 bits with bDst (203 vs 203).
+ final InetAddress aSrc = inet("192.0.2.100");
+ final InetAddress bSrc = inet("203.0.114.1");
+
+ delegate.add("t.example", bDst, aDst);
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(aDst, aSrc, bDst, bSrc));
+
+ final InetAddress[] out = r.resolve("t.example");
+ // aSrc-aDst share more prefix bits than bSrc-bDst, so aDst should come first.
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void ipAttrOf_ipv4_usesMappedPolicyPrecedenceAndLabel() throws Exception {
+ // RFC 6724 §2.1 Table 2: ::ffff:0:0/96 -> precedence 35, label 4.
+ //
+ // Regression: InetAddress.getByName("::ffff:0:0") collapses to a 4-byte
+ // Inet4Address on the JDK. Network#contains() always compares IPv4
+ // destinations against their 16-byte mapped form, so a policy entry built
+ // from that collapsed 4-byte address never matched any IPv4 destination;
+ // every IPv4 address silently fell through to the ::/0 default
+ // (precedence 40, label 1) instead.
+ final AddressSelectingDnsResolver.Attr attr =
+ AddressSelectingDnsResolver.ipAttrOf(inet("192.0.2.1"));
+ assertEquals(35, attr.precedence);
+ assertEquals(4, attr.label);
+ }
+
+ @Test
+ void networkContains_ipv6Prefix32() throws Exception {
+ final AddressSelectingDnsResolver.Network p32 =
+ new AddressSelectingDnsResolver.Network(inet("2001:db8::").getAddress(), 32);
+
+ assertTrue(p32.contains(inet("2001:db8::1")));
+ assertTrue(p32.contains(inet("2001:db8:ffff::1")));
+
+ assertFalse(p32.contains(inet("2001:db9::1")));
+ assertFalse(p32.contains(inet("2000:db8::1")));
+ }
+
+ @Test
+ void networkContains_ipv4IsMatchedViaV4MappedWhenPrefixIsV6Mapped96() throws Exception {
+ // Build ::ffff:0:0 as raw 16 bytes. Do NOT use InetAddress.getByName(..) here:
+ // the JDK may normalize it to an Inet4Address, yielding a 4-byte array.
+ final byte[] v6mapped = new byte[16];
+ v6mapped[10] = (byte) 0xff;
+ v6mapped[11] = (byte) 0xff;
+
+ final AddressSelectingDnsResolver.Network p96 =
+ new AddressSelectingDnsResolver.Network(v6mapped, 96);
+
+ assertTrue(p96.contains(inet("192.0.2.1")));
+ assertTrue(p96.contains(inet("203.0.113.10")));
+
+ // A pure IPv6 address must not match that v4-mapped prefix.
+ assertFalse(p96.contains(inet("2001:db8::1")));
+ }
+
+ @Test
+ void networkContains_nonByteAlignedPrefix7Boundary() throws Exception {
+ // fc00::/7 (ULA) is in the policy table.
+ final AddressSelectingDnsResolver.Network p7 =
+ new AddressSelectingDnsResolver.Network(inet("fc00::").getAddress(), 7);
+
+ // Inside /7: fc00:: and fd00:: (since /7 covers fc00..fdff)
+ assertTrue(p7.contains(inet("fc00::1")));
+ assertTrue(p7.contains(inet("fd00::1")));
+
+ // Just outside /7: fe00:: (top bits 11111110 vs 1111110x)
+ assertFalse(p7.contains(inet("fe00::1")));
+ assertFalse(p7.contains(inet("2001:db8::1")));
+ }
+
+ @Test
+ void sortByRfc6724_globalIpv6IsPreferredOverGlobalIpv4() throws Exception {
+ // End-to-end regression for the ::ffff:0:0/96 construction bug: a plain global
+ // IPv4 destination (precedence 35) must rank behind a plain global IPv6
+ // destination (precedence 40, the ::/0 default), not ahead of it as it would
+ // when the broken policy entry silently fell through to precedence 40 too.
+ final InetAddress v4Dst = inet("192.0.2.1");
+ final InetAddress v6Dst = inet("2003::1");
+
+ final InetAddress v4Src = inet("192.0.2.100");
+ final InetAddress v6Src = inet("2003::2");
+
+ delegate.add("t.example", v4Dst, v6Dst);
+
+ final AddressSelectingDnsResolver r = new AddressSelectingDnsResolver(
+ delegate, ProtocolFamilyPreference.DEFAULT, sourceMap(v6Dst, v6Src, v4Dst, v4Src));
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(v6Dst, v4Dst), Arrays.asList(out));
+ }
+
+ @Test
+ void preferIpv4_groupsAllV4First_preservingRelativeOrder_whenRfcSortIsNoop() throws Exception {
+ final InetAddress v4a = inet("192.0.2.1");
+ final InetAddress v6a = inet("2001:db8::1");
+ final InetAddress v4b = inet("203.0.113.10");
+ final InetAddress v6b = inet("2001:db8::2");
+
+ delegate.add("dual.example", v6a, v4a, v6b, v4b);
+
+ final AddressSelectingDnsResolver preferV4 =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV4, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = preferV4.resolve("dual.example");
+ assertEquals(Arrays.asList(v4a, v4b, v6a, v6b), Arrays.asList(out));
+ assertInstanceOf(Inet4Address.class, out[0]);
+ }
+
+ @Test
+ void rfcRule1_bothSourcesUnusable_orderIsPreserved() throws Exception {
+ final InetAddress aDst = inet("2001:db8::1");
+ final InetAddress bDst = inet("2001:db8::2");
+
+ delegate.add("t.example", aDst, bDst);
+
+ // Every destination resolves to no usable source address.
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR);
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(aDst, bDst), Arrays.asList(out));
+ }
+
+ @Test
+ void rfcRule1_onlyOneSourceUsable_usableDestinationIsPreferred() throws Exception {
+ final InetAddress usableDst = inet("2001:db8::1");
+ final InetAddress unusableDst = inet("2001:db8::2");
+
+ delegate.add("t.example", unusableDst, usableDst);
+
+ final AddressSelectingDnsResolver.SourceAddressResolver onlyOneUsable = dest -> {
+ if (usableDst.equals(dest.getAddress())) {
+ return inet("2001:db8::abcd");
+ }
+ return null;
+ };
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, onlyOneUsable);
+
+ final InetAddress[] out = r.resolve("t.example");
+ assertEquals(Arrays.asList(usableDst, unusableDst), Arrays.asList(out));
+ }
+
+ @Test
+ void resolve_singleCandidateOfRequestedFamily_returnedWithoutRfcSort() throws Exception {
+ // The RFC6724 sort (and therefore source-address inference) must be skipped
+ // entirely when only one candidate is left after filtering.
+ final InetAddress v4 = inet("192.0.2.1");
+ delegate.add("single.example", v4);
+
+ final AddressSelectingDnsResolver.SourceAddressResolver failing = dest -> {
+ throw new AssertionError("source inference must not run for a single candidate");
+ };
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, failing);
+
+ final InetAddress[] out = r.resolve("single.example");
+ assertEquals(1, out.length);
+ assertEquals(v4, out[0]);
+ }
+
+ @Test
+ void resolve_doesNotMutateDelegateReturnedArray() throws Exception {
+ final InetAddress v6 = inet("2001:db8::1");
+ final InetAddress v4 = inet("192.0.2.1");
+ final InetAddress[] delegateArray = {v6, v4};
+ delegate.add("dual.example", delegateArray);
+
+ final InetAddress[] before = delegateArray.clone();
+
+ final AddressSelectingDnsResolver r =
+ new AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE, NO_SOURCE_ADDR);
+ r.resolve("dual.example");
+
+ assertArrayEquals(before, delegateArray, "resolve() must not mutate the delegate's array in place");
+ }
+
+}
\ No newline at end of file
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java
new file mode 100644
index 0000000000..a7c6656da7
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java
@@ -0,0 +1,79 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+
+package org.apache.hc.client5.http.examples;
+
+import java.net.InetAddress;
+
+import org.apache.hc.client5.http.DnsResolver;
+import org.apache.hc.client5.http.AddressSelectingDnsResolver;
+import org.apache.hc.client5.http.SystemDefaultDnsResolver;
+import org.apache.hc.client5.http.config.ProtocolFamilyPreference;
+
+public final class AddressSelectingDnsResolverExample {
+
+ public static void main(final String[] args) throws Exception {
+ final String host = args.length > 0 ? args[0] : "localhost";
+ final ProtocolFamilyPreference pref = args.length > 1
+ ? ProtocolFamilyPreference.valueOf(args[1])
+ : ProtocolFamilyPreference.DEFAULT;
+
+ System.out.println("Host: " + host);
+ System.out.println("Preference: " + pref);
+ System.out.println();
+
+ // Before: raw system resolver output (no RFC 6724 ordering).
+ final InetAddress[] raw = SystemDefaultDnsResolver.INSTANCE.resolve(host);
+ System.out.println("Before (system resolver):");
+ printAddresses(raw);
+
+ // After: RFC 6724 ordered + family preference applied.
+ final DnsResolver resolver = new AddressSelectingDnsResolver(SystemDefaultDnsResolver.INSTANCE, pref);
+ final InetAddress[] out = resolver.resolve(host);
+ System.out.println("After (AddressSelectingDnsResolver, " + pref + "):");
+ printAddresses(out);
+ }
+
+ private static void printAddresses(final InetAddress[] addresses) {
+ if (addresses == null) {
+ System.out.println(" null");
+ return;
+ }
+ if (addresses.length == 0) {
+ System.out.println(" []");
+ return;
+ }
+ for (final InetAddress a : addresses) {
+ final String family = a instanceof java.net.Inet6Address ? "IPv6" : "IPv4";
+ System.out.println(" " + family + " " + a.getHostAddress());
+ }
+ System.out.println();
+ }
+
+ private AddressSelectingDnsResolverExample() {
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientH2ViaH2ProxyTunnel.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientH2ViaH2ProxyTunnel.java
new file mode 100644
index 0000000000..e32b599728
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AsyncClientH2ViaH2ProxyTunnel.java
@@ -0,0 +1,150 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.examples;
+
+import java.io.File;
+import java.util.concurrent.CountDownLatch;
+
+import javax.net.ssl.SSLContext;
+
+import org.apache.hc.client5.http.HttpRoute;
+import org.apache.hc.client5.http.async.methods.SimpleHttpRequest;
+import org.apache.hc.client5.http.async.methods.SimpleHttpResponse;
+import org.apache.hc.client5.http.async.methods.SimpleRequestBuilder;
+import org.apache.hc.client5.http.async.methods.SimpleRequestProducer;
+import org.apache.hc.client5.http.async.methods.SimpleResponseConsumer;
+import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient;
+import org.apache.hc.client5.http.impl.async.H2AsyncClientBuilder;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.http.routing.HttpRoutePlanner;
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.URIScheme;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.http2.ssl.H2ClientTlsStrategy;
+import org.apache.hc.core5.http.message.StatusLine;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.ssl.SSLContexts;
+
+/**
+ * Full example of pure HTTP/2 client execution through an HTTP/2 proxy tunnel.
+ *
+ *
+ * Requirements:
+ *
+ *
+ * - Proxy endpoint speaks HTTP/2.
+ * - Proxy supports CONNECT for the requested target.
+ * - Target endpoint supports HTTP/2.
+ *
+ *
+ *
+ * This example configures a tunneled and layered route:
+ * {@code client -> (h2) proxy -> CONNECT tunnel -> TLS -> (h2) target}.
+ *
+ */
+public class AsyncClientH2ViaH2ProxyTunnel {
+
+ private static TlsStrategy createTlsStrategy() throws Exception {
+ final String trustStore = System.getProperty("h2.truststore");
+ if (trustStore == null || trustStore.isEmpty()) {
+ return new H2ClientTlsStrategy();
+ }
+ final String trustStorePassword = System.getProperty("h2.truststore.password", "changeit");
+ final SSLContext sslContext = SSLContexts.custom()
+ .loadTrustMaterial(new File(trustStore), trustStorePassword.toCharArray())
+ .build();
+ return new H2ClientTlsStrategy(sslContext);
+ }
+
+ public static void main(final String[] args) throws Exception {
+ final String proxyScheme = System.getProperty("h2.proxy.scheme", "http");
+ final String proxyHost = System.getProperty("h2.proxy.host", "localhost");
+ final int proxyPort = Integer.parseInt(System.getProperty("h2.proxy.port", "8080"));
+ final String targetScheme = System.getProperty("h2.target.scheme", "https");
+ final String targetHost = System.getProperty("h2.target.host", "origin");
+ final int targetPort = Integer.parseInt(System.getProperty("h2.target.port", "9443"));
+ final String[] requestUris = System.getProperty("h2.paths", "/").split(",");
+
+ final HttpHost proxy = new HttpHost(proxyScheme, proxyHost, proxyPort);
+ final HttpHost target = new HttpHost(targetScheme, targetHost, targetPort);
+
+ final HttpRoutePlanner routePlanner = (final HttpHost routeTarget, final org.apache.hc.core5.http.protocol.HttpContext context) ->
+ new HttpRoute(routeTarget, null, proxy, URIScheme.HTTPS.same(routeTarget.getSchemeName()));
+ final TlsStrategy tlsStrategy = createTlsStrategy();
+
+ try (CloseableHttpAsyncClient client = H2AsyncClientBuilder.create()
+ .setRoutePlanner(routePlanner)
+ .setTlsStrategy(tlsStrategy)
+ .build()) {
+
+ client.start();
+
+ final CountDownLatch latch = new CountDownLatch(requestUris.length);
+
+ for (final String requestUri : requestUris) {
+ final String normalizedRequestUri = requestUri.trim();
+ final SimpleHttpRequest request = SimpleRequestBuilder.get()
+ .setHttpHost(target)
+ .setPath(normalizedRequestUri)
+ .build();
+ final HttpClientContext clientContext = HttpClientContext.create();
+
+ client.execute(
+ SimpleRequestProducer.create(request),
+ SimpleResponseConsumer.create(),
+ clientContext,
+ new FutureCallback() {
+
+ @Override
+ public void completed(final SimpleHttpResponse response) {
+ latch.countDown();
+ System.out.println(request + " -> " + new StatusLine(response));
+ System.out.println("Protocol: " + clientContext.getProtocolVersion());
+ System.out.println(response.getBodyText());
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ latch.countDown();
+ System.out.println(request + " -> " + ex);
+ }
+
+ @Override
+ public void cancelled() {
+ latch.countDown();
+ System.out.println(request + " cancelled");
+ }
+
+ });
+ }
+
+ latch.await();
+ client.close(CloseMode.GRACEFUL);
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2OverH2TunnelSupport.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2OverH2TunnelSupport.java
new file mode 100644
index 0000000000..3d80b9c0b9
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2OverH2TunnelSupport.java
@@ -0,0 +1,718 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Proxy;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ByteChannel;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.http.EntityDetails;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.HttpRequest;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.StreamControl;
+import org.apache.hc.core5.http.message.BasicHttpResponse;
+import org.apache.hc.core5.http.nio.AsyncClientExchangeHandler;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.http.nio.RequestChannel;
+import org.apache.hc.core5.http.nio.command.RequestExecutionCommand;
+import org.apache.hc.core5.http.nio.ssl.TlsStrategy;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.net.NamedEndpoint;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOEventHandlerFactory;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer;
+import org.apache.hc.core5.util.Timeout;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestH2OverH2TunnelSupport {
+
+ @Test
+ void testEstablishBuildsH2ConnectForAuthorityAndCompletes() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final HttpHost target = new HttpHost("https", "example.org", 443);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(session, target, Timeout.ofSeconds(1), false, null, callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNull(callback.failed);
+ Assertions.assertFalse(callback.cancelled);
+ Assertions.assertNotNull(session.capturedRequest);
+ Assertions.assertEquals("CONNECT", session.capturedRequest.getMethod());
+ Assertions.assertEquals("example.org", session.capturedRequest.getAuthority().getHostName());
+ Assertions.assertEquals(443, session.capturedRequest.getAuthority().getPort());
+ Assertions.assertNull(session.capturedRequest.getScheme());
+ Assertions.assertNull(session.capturedRequest.getPath());
+ }
+
+ @Test
+ void testEstablishAppliesConnectRequestInterceptor() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("https", "example.org", 443),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ (request, entityDetails, context) -> request.addHeader("Proxy-Authorization", "Basic dGVzdDp0ZXN0"),
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNotNull(session.capturedRequest);
+ Assertions.assertEquals("Basic dGVzdDp0ZXN0", session.capturedRequest.getFirstHeader("Proxy-Authorization").getValue());
+ }
+
+ @Test
+ void testEstablishFailsOnRefusedTunnel() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED, false);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("https", "example.org", 443),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertFalse(callback.completed);
+ Assertions.assertNotNull(callback.failed);
+ Assertions.assertInstanceOf(TunnelRefusedException.class, callback.failed);
+ Assertions.assertEquals(
+ HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,
+ ((TunnelRefusedException) callback.failed).getStatusCode());
+ }
+
+ @Test
+ void testEstablishFailsWhenConnectResponseHasNoTunnelStream() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, false);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("https", "example.org", 443),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertFalse(callback.completed);
+ Assertions.assertNotNull(callback.failed);
+ }
+
+ @Test
+ void testEstablishWithProtocolStarterInvokesConnectedAndSeesInputBuffer() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true, false, true, false);
+ final RecordingProtocolStarter protocolStarter = new RecordingProtocolStarter();
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ protocolStarter,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNull(callback.failed);
+ Assertions.assertTrue(protocolStarter.connectedCalled);
+ Assertions.assertTrue(protocolStarter.inputBufferSeen);
+ }
+
+ @Test
+ void testEstablishSecureTunnelUsesTlsStrategy() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final RecordingTlsStrategy tlsStrategy = new RecordingTlsStrategy();
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("https", "example.org", 443),
+ Timeout.ofSeconds(1),
+ true,
+ tlsStrategy,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNull(callback.failed);
+ Assertions.assertTrue(tlsStrategy.invoked);
+ }
+
+ @Test
+ void testClosingTunnelDoesNotClosePhysicalSession() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNotNull(callback.result);
+ callback.result.close(CloseMode.IMMEDIATE);
+ Assertions.assertTrue(session.isOpen(), "Closing tunnel session must not close physical HTTP/2 connection");
+ }
+
+ @Test
+ void testTunnelImmediateCloseCancelsStreamControlWhenPresent() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true, false, false, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNotNull(callback.result);
+ callback.result.close(CloseMode.IMMEDIATE);
+
+ Assertions.assertTrue(session.streamCancelCalled.get(), "IMMEDIATE close must cancel the CONNECT stream");
+ Assertions.assertTrue(session.isOpen(), "Cancelling tunnel stream must not close physical HTTP/2 connection");
+ }
+
+ @Test
+ void testTunnelWriteBufferIsBounded() throws Exception {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNotNull(callback.result);
+ final int payloadSize = 1024 * 1024;
+ final ByteBuffer src = ByteBuffer.allocate(payloadSize);
+ final int written = callback.result.write(src);
+ Assertions.assertTrue(written > 0);
+ Assertions.assertTrue(written < payloadSize, "Outbound writes must be bounded by tunnel buffer capacity");
+ }
+
+ @Test
+ void testCapacityUpdateIsNotUnbounded() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true, true, false, false);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertTrue(session.lastCapacityUpdate > 0, "Tunnel setup should publish initial bounded capacity");
+ Assertions.assertTrue(session.lastCapacityUpdate < Integer.MAX_VALUE, "Capacity must not be unbounded");
+ }
+
+ @Test
+ void testGracefulCloseEndsStreamAfterDrain() throws Exception {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed);
+ Assertions.assertNotNull(callback.result);
+
+ final ByteBuffer src = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5});
+ final int written = callback.result.write(src);
+ Assertions.assertEquals(5, written);
+
+ callback.result.close(CloseMode.GRACEFUL);
+
+ // Drive output flush: test runs in same package -> can call package-private method.
+ ((H2TunnelProtocolIOSession) callback.result).onOutputReady();
+
+ Assertions.assertTrue(session.endStreamCalled.get(), "GRACEFUL close must end the CONNECT stream after draining");
+ Assertions.assertTrue(session.isOpen(), "Ending tunnel stream must not close physical HTTP/2 connection");
+ }
+
+ @Test
+ void testStreamEndAfterEstablishedTunnelDoesNotFireFailure() {
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, true, false, false, false, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertTrue(callback.completed, "Tunnel should complete successfully");
+ Assertions.assertNull(callback.failed, "streamEnd after established tunnel must not overwrite with failure");
+ }
+
+ @Test
+ void testStreamEndBeforeTunnelEstablishedFiresFailure() {
+ // 200 but no entity details -> consumeResponse throws -> fail() fires
+ // then streamEnd arrives on the already-failed handler
+ final ScriptedProxySession session = new ScriptedProxySession(HttpStatus.SC_OK, false, false, false, false, true);
+ final RecordingCallback callback = new RecordingCallback<>();
+
+ H2OverH2TunnelSupport.establish(
+ session,
+ new HttpHost("http", "example.org", 80),
+ Timeout.ofSeconds(1),
+ false,
+ null,
+ callback);
+
+ Assertions.assertFalse(callback.completed);
+ Assertions.assertNotNull(callback.failed, "streamEnd with no tunnel must report failure");
+ }
+
+ static class RecordingCallback implements FutureCallback {
+
+ volatile boolean completed;
+ volatile boolean cancelled;
+ volatile Exception failed;
+ volatile T result;
+
+ @Override
+ public void completed(final T result) {
+ this.completed = true;
+ this.result = result;
+ }
+
+ @Override
+ public void failed(final Exception ex) {
+ this.failed = ex;
+ }
+
+ @Override
+ public void cancelled() {
+ this.cancelled = true;
+ }
+ }
+
+ static class RecordingProtocolStarter implements IOEventHandlerFactory {
+
+ volatile boolean connectedCalled;
+ volatile boolean inputBufferSeen;
+
+ @Override
+ public IOEventHandler createHandler(final ProtocolIOSession ioSession, final Object attachment) {
+ return new IOEventHandler() {
+
+ @Override
+ public void connected(final IOSession session) {
+ connectedCalled = true;
+ }
+
+ @Override
+ public void inputReady(final IOSession session, final ByteBuffer src) {
+ if (src != null && src.hasRemaining()) {
+ inputBufferSeen = true;
+ }
+ }
+
+ @Override
+ public void outputReady(final IOSession session) {
+ }
+
+ @Override
+ public void timeout(final IOSession session, final Timeout timeout) {
+ }
+
+ @Override
+ public void exception(final IOSession session, final Exception cause) {
+ }
+
+ @Override
+ public void disconnected(final IOSession session) {
+ }
+ };
+ }
+ }
+
+ static class RecordingTlsStrategy implements TlsStrategy {
+
+ volatile boolean invoked;
+
+ @Override
+ public boolean upgrade(
+ final TransportSecurityLayer sessionLayer,
+ final HttpHost host,
+ final SocketAddress localAddress,
+ final SocketAddress remoteAddress,
+ final Object attachment,
+ final Timeout handshakeTimeout) {
+ invoked = true;
+ return true;
+ }
+
+ @Override
+ public void upgrade(
+ final TransportSecurityLayer sessionLayer,
+ final NamedEndpoint endpoint,
+ final Object attachment,
+ final Timeout handshakeTimeout,
+ final FutureCallback callback) {
+ invoked = true;
+ if (callback != null) {
+ callback.completed(sessionLayer);
+ }
+ }
+ }
+
+ static class ScriptedProxySession implements IOSession {
+
+ private final int responseCode;
+ private final boolean withTunnelStream;
+ private final boolean signalCapacity;
+ private final boolean emitInputData;
+ private final boolean provideStreamControl;
+ private final boolean sendStreamEnd;
+
+ private final Lock lock;
+ private Timeout socketTimeout;
+
+ HttpRequest capturedRequest;
+ volatile int lastCapacityUpdate;
+
+ private final AtomicBoolean open;
+ final AtomicBoolean streamCancelCalled;
+ final AtomicBoolean endStreamCalled;
+
+ ScriptedProxySession(final int responseCode, final boolean withTunnelStream) {
+ this(responseCode, withTunnelStream, false, false, false, false);
+ }
+
+ ScriptedProxySession(final int responseCode, final boolean withTunnelStream, final boolean signalCapacity) {
+ this(responseCode, withTunnelStream, signalCapacity, false, false, false);
+ }
+
+ ScriptedProxySession(
+ final int responseCode,
+ final boolean withTunnelStream,
+ final boolean signalCapacity,
+ final boolean emitInputData,
+ final boolean provideStreamControl) {
+ this(responseCode, withTunnelStream, signalCapacity, emitInputData, provideStreamControl, false);
+ }
+
+ ScriptedProxySession(
+ final int responseCode,
+ final boolean withTunnelStream,
+ final boolean signalCapacity,
+ final boolean emitInputData,
+ final boolean provideStreamControl,
+ final boolean sendStreamEnd) {
+ this.responseCode = responseCode;
+ this.withTunnelStream = withTunnelStream;
+ this.signalCapacity = signalCapacity;
+ this.emitInputData = emitInputData;
+ this.provideStreamControl = provideStreamControl;
+ this.sendStreamEnd = sendStreamEnd;
+
+ this.lock = new ReentrantLock();
+ this.socketTimeout = Timeout.ofSeconds(30);
+ this.lastCapacityUpdate = -1;
+ this.open = new AtomicBoolean(true);
+ this.streamCancelCalled = new AtomicBoolean(false);
+ this.endStreamCalled = new AtomicBoolean(false);
+ }
+
+ @Override
+ public IOEventHandler getHandler() {
+ return null;
+ }
+
+ @Override
+ public void upgrade(final IOEventHandler handler) {
+ }
+
+ @Override
+ public Lock getLock() {
+ return lock;
+ }
+
+ @Override
+ public void enqueue(final Command command, final Command.Priority priority) {
+ if (!(command instanceof RequestExecutionCommand)) {
+ return;
+ }
+
+ final RequestExecutionCommand requestExecutionCommand = (RequestExecutionCommand) command;
+ final AsyncClientExchangeHandler exchangeHandler = requestExecutionCommand.getExchangeHandler();
+ final org.apache.hc.core5.http.protocol.HttpContext context = requestExecutionCommand.getContext();
+
+ try {
+ if (provideStreamControl && exchangeHandler instanceof H2OverH2TunnelExchangeHandler) {
+ final StreamControl streamControl = (StreamControl) Proxy.newProxyInstance(
+ StreamControl.class.getClassLoader(),
+ new Class>[]{StreamControl.class},
+ (proxy, method, args) -> {
+ if ("cancel".equals(method.getName())) {
+ streamCancelCalled.set(true);
+ return method.getReturnType() == Boolean.TYPE ? Boolean.TRUE : null;
+ }
+ return defaultValue(method);
+ });
+
+ ((H2OverH2TunnelExchangeHandler) exchangeHandler).initiated(streamControl);
+ }
+
+ exchangeHandler.produceRequest((RequestChannel) (request, entityDetails, requestContext) -> capturedRequest = request, context);
+
+ if (signalCapacity) {
+ exchangeHandler.updateCapacity((CapacityChannel) increment -> lastCapacityUpdate = increment);
+ }
+
+ final EntityDetails responseEntityDetails =
+ withTunnelStream ? new org.apache.hc.core5.http.impl.BasicEntityDetails(-1, null) : null;
+ exchangeHandler.consumeResponse(new BasicHttpResponse(responseCode), responseEntityDetails, context);
+
+ if (withTunnelStream && responseCode == HttpStatus.SC_OK) {
+ exchangeHandler.produce(new DataStreamChannel() {
+
+ @Override
+ public void requestOutput() {
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ final int remaining = src != null ? src.remaining() : 0;
+ if (remaining > 0 && src != null) {
+ final byte[] tmp = new byte[remaining];
+ src.get(tmp);
+ }
+ return remaining;
+ }
+
+ @Override
+ public void endStream() throws IOException {
+
+ }
+
+ @Override
+ public void endStream(final java.util.List extends org.apache.hc.core5.http.Header> trailers) {
+ endStreamCalled.set(true);
+ }
+
+ });
+
+ if (emitInputData) {
+ exchangeHandler.consume(ByteBuffer.wrap(new byte[]{1, 2, 3}));
+ }
+ }
+
+ if (sendStreamEnd) {
+ exchangeHandler.streamEnd(null);
+ }
+ } catch (final Exception ex) {
+ exchangeHandler.failed(ex);
+ }
+ }
+
+ private static Object defaultValue(final Method method) {
+ final Class> rt = method.getReturnType();
+ if (rt == Void.TYPE) {
+ return null;
+ }
+ if (rt == Boolean.TYPE) {
+ return false;
+ }
+ if (rt == Integer.TYPE) {
+ return 0;
+ }
+ if (rt == Long.TYPE) {
+ return 0L;
+ }
+ if (rt == Short.TYPE) {
+ return (short) 0;
+ }
+ if (rt == Byte.TYPE) {
+ return (byte) 0;
+ }
+ if (rt == Character.TYPE) {
+ return (char) 0;
+ }
+ if (rt == Float.TYPE) {
+ return 0f;
+ }
+ if (rt == Double.TYPE) {
+ return 0d;
+ }
+ return null;
+ }
+
+ @Override
+ public boolean hasCommands() {
+ return false;
+ }
+
+ @Override
+ public Command poll() {
+ return null;
+ }
+
+ @Override
+ public ByteChannel channel() {
+ return this;
+ }
+
+ @Override
+ public SocketAddress getRemoteAddress() {
+ return null;
+ }
+
+ @Override
+ public SocketAddress getLocalAddress() {
+ return null;
+ }
+
+ @Override
+ public int getEventMask() {
+ return 0;
+ }
+
+ @Override
+ public void setEventMask(final int ops) {
+ }
+
+ @Override
+ public void setEvent(final int op) {
+ }
+
+ @Override
+ public void clearEvent(final int op) {
+ }
+
+ @Override
+ public void close() {
+ open.set(false);
+ }
+
+ @Override
+ public void close(final CloseMode closeMode) {
+ open.set(false);
+ }
+
+ @Override
+ public Status getStatus() {
+ return open.get() ? Status.ACTIVE : Status.CLOSED;
+ }
+
+ @Override
+ public Timeout getSocketTimeout() {
+ return socketTimeout;
+ }
+
+ @Override
+ public void setSocketTimeout(final Timeout timeout) {
+ this.socketTimeout = timeout;
+ }
+
+ @Override
+ public long getLastReadTime() {
+ return 0;
+ }
+
+ @Override
+ public long getLastWriteTime() {
+ return 0;
+ }
+
+ @Override
+ public long getLastEventTime() {
+ return 0;
+ }
+
+ @Override
+ public void updateReadTime() {
+ }
+
+ @Override
+ public void updateWriteTime() {
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) {
+ return 0;
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ final int remaining = src != null ? src.remaining() : 0;
+ if (remaining > 0) {
+ final byte[] tmp = new byte[remaining];
+ src.get(tmp);
+ }
+ return remaining;
+ }
+
+ @Override
+ public boolean isOpen() {
+ return open.get();
+ }
+
+ @Override
+ public String getId() {
+ return "proxy-session";
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelProtocolStarter.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelProtocolStarter.java
new file mode 100644
index 0000000000..c73a54da0b
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelProtocolStarter.java
@@ -0,0 +1,83 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import org.apache.hc.core5.http.config.CharCodingConfig;
+import org.apache.hc.core5.http2.config.H2Config;
+import org.apache.hc.core5.http2.impl.nio.ClientH2PrefaceHandler;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.ProtocolIOSession;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+class TestH2TunnelProtocolStarter {
+
+ @Test
+ void testCreatesMinimalH2HandlerWithoutPushOrLogging() {
+ final H2TunnelProtocolStarter starter = new H2TunnelProtocolStarter(
+ H2Config.DEFAULT, CharCodingConfig.DEFAULT);
+ final ProtocolIOSession ioSession = Mockito.mock(ProtocolIOSession.class);
+ Mockito.when(ioSession.getId()).thenReturn("test-tunnel");
+
+ final IOEventHandler handler = starter.createHandler(ioSession, null);
+
+ Assertions.assertNotNull(handler);
+ Assertions.assertInstanceOf(ClientH2PrefaceHandler.class, handler);
+ }
+
+ @Test
+ void testDefaultsWhenNullConfig() {
+ final H2TunnelProtocolStarter starter = new H2TunnelProtocolStarter(null, null);
+ final ProtocolIOSession ioSession = Mockito.mock(ProtocolIOSession.class);
+ Mockito.when(ioSession.getId()).thenReturn("test-tunnel-null");
+
+ final IOEventHandler handler = starter.createHandler(ioSession, null);
+
+ Assertions.assertNotNull(handler);
+ Assertions.assertInstanceOf(ClientH2PrefaceHandler.class, handler);
+ }
+
+ @Test
+ void testCustomH2ConfigIsRespected() {
+ final H2Config customConfig = H2Config.custom()
+ .setMaxFrameSize(32768)
+ .setInitialWindowSize(128 * 1024)
+ .setPushEnabled(false)
+ .build();
+ final H2TunnelProtocolStarter starter = new H2TunnelProtocolStarter(
+ customConfig, CharCodingConfig.DEFAULT);
+ final ProtocolIOSession ioSession = Mockito.mock(ProtocolIOSession.class);
+ Mockito.when(ioSession.getId()).thenReturn("test-tunnel-custom");
+
+ final IOEventHandler handler = starter.createHandler(ioSession, null);
+
+ Assertions.assertNotNull(handler);
+ Assertions.assertInstanceOf(ClientH2PrefaceHandler.class, handler);
+ }
+
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelRawIOSession.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelRawIOSession.java
new file mode 100644
index 0000000000..7775711d98
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/async/TestH2TunnelRawIOSession.java
@@ -0,0 +1,391 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.async;
+
+import java.io.IOException;
+import java.lang.reflect.Proxy;
+import java.net.SocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.ByteChannel;
+import java.nio.channels.CancelledKeyException;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.hc.core5.http.StreamControl;
+import org.apache.hc.core5.http.nio.CapacityChannel;
+import org.apache.hc.core5.http.nio.DataStreamChannel;
+import org.apache.hc.core5.http.nio.command.ShutdownCommand;
+import org.apache.hc.core5.io.CloseMode;
+import org.apache.hc.core5.reactor.Command;
+import org.apache.hc.core5.reactor.IOEventHandler;
+import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.Timeout;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestH2TunnelRawIOSession {
+
+ @Test
+ void testCapacityInitialUpdateIsBounded() throws Exception {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+
+ final AtomicInteger last = new AtomicInteger(0);
+ raw.updateCapacityChannel(new CapacityChannel() {
+ @Override
+ public void update(final int increment) {
+ last.set(increment);
+ }
+ });
+
+ Assertions.assertTrue(last.get() > 0);
+ Assertions.assertTrue(last.get() < Integer.MAX_VALUE);
+ }
+
+ @Test
+ void testAppendInputOverflowFails() throws Exception {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+
+ // INBOUND_BUFFER_LIMIT is 64k in the implementation; overflow by 1.
+ final ByteBuffer tooBig = ByteBuffer.allocate(64 * 1024 + 1);
+ Assertions.assertThrows(IOException.class, () -> raw.appendInput(tooBig));
+ }
+
+ @Test
+ void testReadTriggersCapacityUpdateOnConsumption() throws Exception {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+
+ final AtomicInteger last = new AtomicInteger(-1);
+ raw.updateCapacityChannel(new CapacityChannel() {
+ @Override
+ public void update(final int increment) {
+ last.set(increment);
+ }
+ });
+
+ raw.appendInput(ByteBuffer.wrap(new byte[]{1, 2, 3, 4}));
+
+ final ByteBuffer dst = ByteBuffer.allocate(4);
+ final int n = raw.read(dst);
+ Assertions.assertEquals(4, n);
+ // Capacity update should publish the consumed bytes (4), not unbounded.
+ Assertions.assertEquals(4, last.get());
+ }
+
+ @Test
+ void testWriteIsBounded() {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+
+ final ByteBuffer src = ByteBuffer.allocate(1024 * 1024);
+ final int n = raw.write(src);
+ Assertions.assertTrue(n > 0);
+ Assertions.assertTrue(n < 1024 * 1024);
+ Assertions.assertEquals(64 * 1024, n, "Expected OUTBOUND_BUFFER_LIMIT (64k) write bound");
+ }
+
+ @Test
+ void testImmediateCloseCancelsStreamControlButNotPhysicalSession() {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+
+ final AtomicBoolean cancelled = new AtomicBoolean(false);
+ final StreamControl streamControl = (StreamControl) Proxy.newProxyInstance(
+ StreamControl.class.getClassLoader(),
+ new Class>[]{StreamControl.class},
+ (proxy, method, args) -> {
+ final String name = method.getName();
+ final Class> rt = method.getReturnType();
+
+ if ("cancel".equals(name)) {
+ cancelled.set(true);
+ // IMPORTANT: cancel() may return boolean (Cancellable)
+ return rt == Boolean.TYPE ? Boolean.TRUE : null;
+ }
+
+ if (rt == Void.TYPE) {
+ return null;
+ }
+ if (rt == Boolean.TYPE) {
+ return false;
+ }
+ if (rt == Integer.TYPE) {
+ return 0;
+ }
+ if (rt == Long.TYPE) {
+ return 0L;
+ }
+ if (rt == Short.TYPE) {
+ return (short) 0;
+ }
+ if (rt == Byte.TYPE) {
+ return (byte) 0;
+ }
+ if (rt == Character.TYPE) {
+ return (char) 0;
+ }
+ if (rt == Float.TYPE) {
+ return 0f;
+ }
+ if (rt == Double.TYPE) {
+ return 0d;
+ }
+ return null;
+ });
+
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), streamControl);
+ raw.close(CloseMode.IMMEDIATE);
+
+ Assertions.assertTrue(cancelled.get(), "IMMEDIATE close must cancel stream");
+ Assertions.assertTrue(physical.isOpen(), "Tunnel close must not close physical HTTP/2 connection");
+ }
+
+ @Test
+ void testGracefulCloseEndsStreamAfterDrain() throws Exception {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+
+ final AtomicBoolean endStreamCalled = new AtomicBoolean(false);
+ rawAttachChannel(physical, endStreamCalled);
+
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+ raw.attachChannel(physical.dataChannel);
+
+ // Put some outbound bytes
+ final ByteBuffer src = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5});
+ final int written = raw.write(src);
+ Assertions.assertEquals(5, written);
+
+ raw.close(CloseMode.GRACEFUL);
+ raw.flushOutput();
+
+ Assertions.assertTrue(endStreamCalled.get(), "GRACEFUL close must endStream once outbound drained");
+ }
+
+ @Test
+ void testRequestOutputOnCancelledKeyClosesTunnel() {
+ final DummyPhysicalSession physical = new DummyPhysicalSession();
+ final H2TunnelRawIOSession raw = new H2TunnelRawIOSession(physical, Timeout.ofSeconds(5), null);
+ raw.attachChannel(new DataStreamChannel() {
+
+ @Override
+ public void requestOutput() {
+ throw new CancelledKeyException();
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ return 0;
+ }
+
+ @Override
+ public void endStream() {
+ }
+
+ @Override
+ public void endStream(final java.util.List extends org.apache.hc.core5.http.Header> trailers) {
+ }
+ });
+
+ raw.enqueue(ShutdownCommand.GRACEFUL, Command.Priority.NORMAL);
+
+ Assertions.assertEquals(IOSession.Status.CLOSED, raw.getStatus());
+ }
+
+ private static void rawAttachChannel(final DummyPhysicalSession physical, final AtomicBoolean endStreamCalled) {
+ physical.dataChannel = new DataStreamChannel() {
+
+ @Override
+ public void requestOutput() {
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ final int remaining = src != null ? src.remaining() : 0;
+ if (remaining > 0 && src != null) {
+ final byte[] tmp = new byte[remaining];
+ src.get(tmp);
+ }
+ return remaining;
+ }
+
+ @Override
+ public void endStream() throws IOException {
+
+ }
+
+ @Override
+ public void endStream(final java.util.List extends org.apache.hc.core5.http.Header> trailers) {
+ endStreamCalled.set(true);
+ }
+ };
+ }
+
+ static final class DummyPhysicalSession implements IOSession {
+
+ private final Lock lock = new ReentrantLock();
+ private volatile boolean open = true;
+ private volatile Timeout socketTimeout = Timeout.ofSeconds(30);
+
+ volatile DataStreamChannel dataChannel;
+
+ @Override
+ public IOEventHandler getHandler() {
+ return null;
+ }
+
+ @Override
+ public void upgrade(final IOEventHandler handler) {
+ }
+
+ @Override
+ public Lock getLock() {
+ return lock;
+ }
+
+ @Override
+ public void enqueue(final Command command, final Command.Priority priority) {
+ }
+
+ @Override
+ public boolean hasCommands() {
+ return false;
+ }
+
+ @Override
+ public Command poll() {
+ return null;
+ }
+
+ @Override
+ public ByteChannel channel() {
+ return this;
+ }
+
+ @Override
+ public SocketAddress getRemoteAddress() {
+ return null;
+ }
+
+ @Override
+ public SocketAddress getLocalAddress() {
+ return null;
+ }
+
+ @Override
+ public int getEventMask() {
+ return 0;
+ }
+
+ @Override
+ public void setEventMask(final int ops) {
+ }
+
+ @Override
+ public void setEvent(final int op) {
+ }
+
+ @Override
+ public void clearEvent(final int op) {
+ }
+
+ @Override
+ public void close() {
+ open = false;
+ }
+
+ @Override
+ public void close(final CloseMode closeMode) {
+ open = false;
+ }
+
+ @Override
+ public Status getStatus() {
+ return open ? Status.ACTIVE : Status.CLOSED;
+ }
+
+ @Override
+ public Timeout getSocketTimeout() {
+ return socketTimeout;
+ }
+
+ @Override
+ public void setSocketTimeout(final Timeout timeout) {
+ socketTimeout = timeout;
+ }
+
+ @Override
+ public long getLastReadTime() {
+ return 0;
+ }
+
+ @Override
+ public long getLastWriteTime() {
+ return 0;
+ }
+
+ @Override
+ public long getLastEventTime() {
+ return 0;
+ }
+
+ @Override
+ public void updateReadTime() {
+ }
+
+ @Override
+ public void updateWriteTime() {
+ }
+
+ @Override
+ public int read(final ByteBuffer dst) {
+ return 0;
+ }
+
+ @Override
+ public int write(final ByteBuffer src) {
+ final int remaining = src != null ? src.remaining() : 0;
+ if (remaining > 0 && src != null) {
+ final byte[] tmp = new byte[remaining];
+ src.get(tmp);
+ }
+ return remaining;
+ }
+
+ @Override
+ public boolean isOpen() {
+ return open;
+ }
+
+ @Override
+ public String getId() {
+ return "dummy-physical";
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
index db2a0015f1..d809336a1e 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/auth/TestAuthenticationHandler.java
@@ -208,6 +208,30 @@ void testAuthenticationCredentialsForBasic() throws AuthenticationException, Mal
Assertions.assertNull(options.poll());
}
+ @Test
+ void testAuthenticationMalformedChallengeIgnored() throws AuthenticationException, MalformedChallengeException {
+ final HttpHost host = new HttpHost("somehost", 80);
+ final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_UNAUTHORIZED, "UNAUTHORIZED");
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, StandardAuthScheme.BASIC + " realm=\"test\""));
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, ""));
+
+ final Credentials credentials = new UsernamePasswordCredentials("user", "pass".toCharArray());
+ Mockito.when(this.credentialsProvider.getCredentials(Mockito.any(), Mockito.any())).thenReturn(credentials);
+
+ final DefaultAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy();
+
+ Assertions.assertTrue(this.httpAuthenticator.handleResponse(host, ChallengeType.TARGET, response, authStrategy,
+ this.authExchange, this.context));
+ Assertions.assertEquals(AuthExchange.State.CHALLENGED, this.authExchange.getState());
+
+ final Queue options = this.authExchange.getAuthOptions();
+ Assertions.assertNotNull(options);
+ final AuthScheme authScheme1 = options.poll();
+ Assertions.assertNotNull(authScheme1);
+ Assertions.assertEquals(StandardAuthScheme.BASIC, authScheme1.getName());
+ Assertions.assertNull(options.poll());
+ }
+
@Test
void testAuthenticationNoChallenges() throws AuthenticationException, MalformedChallengeException {
final HttpHost host = new HttpHost("somehost", 80);
@@ -529,6 +553,35 @@ void testAuthenticationInfoProcessedOnSuccessResponse() throws Exception {
Assertions.assertEquals("dj1hYmM", getParam(challenge, "data"));
}
+ @Test
+ void testAuthenticationInfoProcessedWithMalformedChallenge() throws Exception {
+ final HttpHost host = new HttpHost("somehost", 80);
+ final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK, "OK");
+ response.addHeader(new BasicHeader(HttpHeaders.WWW_AUTHENTICATE, ""));
+ response.addHeader(new BasicHeader("Authentication-Info", "rspauth=\"abc\""));
+
+ final AuthScheme authScheme = Mockito.mock(AuthScheme.class);
+ Mockito.when(authScheme.getName()).thenReturn(StandardAuthScheme.DIGEST);
+ Mockito.when(authScheme.isChallengeExpected()).thenReturn(Boolean.TRUE);
+ Mockito.when(authScheme.isChallengeComplete()).thenReturn(Boolean.FALSE);
+
+ this.authExchange.select(authScheme);
+ this.authExchange.setState(AuthExchange.State.HANDSHAKE);
+
+ final DefaultAuthenticationStrategy authStrategy = new DefaultAuthenticationStrategy();
+
+ this.httpAuthenticator.handleResponse(
+ host, ChallengeType.TARGET, response, authStrategy, this.authExchange, this.context);
+
+ final ArgumentCaptor challengeCaptor = ArgumentCaptor.forClass(AuthChallenge.class);
+ Mockito.verify(authScheme).processChallenge(
+ Mockito.eq(host),
+ Mockito.eq(false),
+ challengeCaptor.capture(),
+ Mockito.same(this.context));
+ Assertions.assertEquals("abc", getParam(challengeCaptor.getValue(), "rspauth"));
+ }
+
@Test
void testAuthenticationInfoCombinesMultipleFieldLines() throws Exception {
final HttpHost host = new HttpHost("somehost", 80);
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java
new file mode 100644
index 0000000000..f2d1a33a28
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java
@@ -0,0 +1,277 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.io;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.time.Duration;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import javax.net.ssl.SSLSocket;
+
+import org.apache.hc.client5.http.DnsResolver;
+import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
+import org.apache.hc.client5.http.io.DetachedSocketFactory;
+import org.apache.hc.client5.http.protocol.HttpClientContext;
+import org.apache.hc.client5.http.ssl.TlsSocketStrategy;
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.http.config.Lookup;
+import org.apache.hc.core5.http.io.SocketConfig;
+import org.apache.hc.core5.util.TimeValue;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.mockito.Mockito;
+
+class DefaultHttpClientConnectionOperatorTest {
+
+ /**
+ * Regression test: when {@code localAddress} specifies a non-zero (explicit) local port,
+ * Happy Eyeballs racing must not bind more than one socket to it concurrently, which the
+ * OS would reject for all but one attempt as a bind conflict rather than a real connect
+ * failure. The operator falls back to the existing sequential path in that case, so a
+ * dead first address followed by a real, reachable second address must still succeed,
+ * exactly as it would against master without this feature.
+ */
+ @Test
+ void happyEyeballsWithExplicitLocalPort_fallsBackToSequential_stillSucceeds() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close(); // nothing listens here once closed: instant refusal
+
+ final int explicitLocalPort;
+ try (ServerSocket localPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ explicitLocalPort = localPortProbe.getLocalPort();
+ }
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ DefaultHttpClientConnectionOperator.PLAIN_SOCKET_FACTORY,
+ DefaultSchemePortResolver.INSTANCE,
+ dnsResolver,
+ (Lookup) name -> null,
+ true,
+ TimeValue.ofMilliseconds(20));
+
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+ final InetSocketAddress localAddress = new InetSocketAddress(
+ InetAddress.getLoopbackAddress(), explicitLocalPort);
+
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("http", "somehost", 80), localAddress,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create()));
+
+ assertEquals(listeningPort, ((InetSocketAddress) conn.getRemoteAddress()).getPort());
+ assertEquals(explicitLocalPort, ((InetSocketAddress) conn.getLocalAddress()).getPort());
+ conn.close();
+ }
+ }
+
+ /**
+ * Regression test: on the Happy Eyeballs racing path, a TLS handshake failure after the
+ * TCP race has already picked a winner must still close that winning socket, exactly as
+ * the sequential path's own try/catch around bind + TLS upgrade already does.
+ */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeFailure_closesWinningSocket() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close();
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicReference winningSocket = new AtomicReference<>();
+ final DetachedSocketFactory trackingFactory = (final Proxy proxy) -> {
+ final Socket s = new Socket();
+ winningSocket.set(s);
+ return s;
+ };
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IOException("handshake failed"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ trackingFactory, DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertThrows(IOException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+
+ assertTrue(winningSocket.get().isClosed(), "the winning socket must be closed when the TLS handshake fails");
+ }
+ }
+
+ /** Same as above, but the TLS strategy throws a RuntimeException rather than an IOException. */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeRuntimeFailure_closesWinningSocket() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress());
+ ServerSocket deadPortProbe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = deadPortProbe.getLocalPort();
+ deadPortProbe.close();
+
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicReference winningSocket = new AtomicReference<>();
+ final DetachedSocketFactory trackingFactory = (final Proxy proxy) -> {
+ final Socket s = new Socket();
+ winningSocket.set(s);
+ return s;
+ };
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IllegalStateException("handshake blew up"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ trackingFactory, DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertThrows(IllegalStateException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+
+ assertTrue(winningSocket.get().isClosed(), "the winning socket must be closed when the TLS handshake throws unexpectedly");
+ }
+ }
+
+ /**
+ * Regression test (reviewer-supplied probe, PR #936): a TLS failure on the address that
+ * won the TCP race must fall back to the remaining, untried address, exactly as the
+ * sequential (non-racing) path already does. Passes for both {@code happyEyeballs} values.
+ */
+ @ParameterizedTest(name = "happyEyeballs={0}")
+ @ValueSource(booleans = {false, true})
+ void tlsFailureOnFirstAddressFallsBackToNextAddress(final boolean happyEyeballs) throws Exception {
+ try (ServerSocket broken = new ServerSocket(0, 50, InetAddress.getLoopbackAddress());
+ ServerSocket healthy = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) {
+ final List remoteAddresses = Arrays.asList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), broken.getLocalPort()),
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), healthy.getLocalPort()));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final AtomicInteger handshakes = new AtomicInteger();
+ final AtomicInteger upgradedPort = new AtomicInteger();
+ final TlsSocketStrategy tls = (socket, target, port, attachment, context) -> {
+ handshakes.incrementAndGet();
+ if (socket.getPort() == broken.getLocalPort()) {
+ throw new IOException("handshake failed on " + socket.getRemoteSocketAddress());
+ }
+ upgradedPort.set(socket.getPort());
+ return Mockito.mock(SSLSocket.class);
+ };
+ final Lookup tlsLookup = scheme -> tls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ proxy -> new Socket(), DefaultSchemePortResolver.INSTANCE, dnsResolver, tlsLookup,
+ happyEyeballs, TimeValue.ofMilliseconds(250));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create()));
+
+ assertEquals(healthy.getLocalPort(), upgradedPort.get());
+ assertEquals(2, handshakes.get());
+ }
+ }
+
+ /**
+ * Regression test: when the race winner is the only address (no address left to fall
+ * back to), a TLS failure on it still propagates immediately, exactly as before this fix.
+ */
+ @Test
+ void happyEyeballsRacing_tlsHandshakeFailure_noRemainingAddress_propagatesImmediately() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final List remoteAddresses = Collections.singletonList(
+ new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+ final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class);
+ Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses);
+
+ final TlsSocketStrategy failingTls = Mockito.mock(TlsSocketStrategy.class);
+ Mockito.when(failingTls.upgrade(Mockito.any(), Mockito.anyString(), Mockito.anyInt(), Mockito.any(), Mockito.any()))
+ .thenThrow(new IOException("handshake failed"));
+ final Lookup tlsLookup = scheme -> failingTls;
+
+ final DefaultHttpClientConnectionOperator operator = new DefaultHttpClientConnectionOperator(
+ DefaultHttpClientConnectionOperator.PLAIN_SOCKET_FACTORY, DefaultSchemePortResolver.INSTANCE,
+ dnsResolver, tlsLookup, true, TimeValue.ofMilliseconds(20));
+ final DefaultManagedHttpClientConnection conn = new DefaultManagedHttpClientConnection(
+ "test", null, null, null, null, null, null, null, null);
+
+ // Happy Eyeballs only races when there is more than one address; with a single
+ // address this exercises the sequential path, which is the baseline this fix must
+ // not change when there is nothing left to fall back to.
+ assertThrows(IOException.class, () ->
+ assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ operator.connect(conn, new HttpHost("https", "somehost", 443), null,
+ TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())));
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java
new file mode 100644
index 0000000000..eec39052ec
--- /dev/null
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java
@@ -0,0 +1,340 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * .
+ *
+ */
+package org.apache.hc.client5.http.impl.io;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketException;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.hc.core5.http.HttpHost;
+import org.apache.hc.core5.util.TimeValue;
+import org.junit.jupiter.api.Test;
+
+class HappyEyeballsSocketConnectorTest {
+
+ /** A socket whose {@link #connect} blocks until {@link #close} is called, then fails, matching the real behavior of closing a socket mid-connect. */
+ private static final class BlockingSocket extends Socket {
+
+ private final CountDownLatch closed = new CountDownLatch(1);
+ volatile boolean connectAttempted;
+
+ @Override
+ public void connect(final SocketAddress endpoint, final int timeout) throws IOException {
+ connectAttempted = true;
+ try {
+ closed.await();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ throw new SocketException("Socket closed");
+ }
+
+ @Override
+ public synchronized void close() throws IOException {
+ closed.countDown();
+ super.close();
+ }
+ }
+
+ private static List addresses(final int count) throws Exception {
+ final List out = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ out.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, (byte) i}), 8080));
+ }
+ return out;
+ }
+
+ @Test
+ void singleAddress_connectsWithoutRacing() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket expected = new Socket();
+ final AtomicInteger attempts = new AtomicInteger();
+
+ final Socket actual = connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ attempts.incrementAndGet();
+ socketConsumer.accept(expected);
+ return expected;
+ });
+
+ assertEquals(expected, actual);
+ assertEquals(1, attempts.get());
+ }
+
+ @Test
+ void secondAddressWinsWhileFirstStalls_loserSocketIsClosed() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket firstSocket = new BlockingSocket();
+ final Socket secondSocket = new Socket();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ socketConsumer.accept(firstSocket);
+ firstSocket.connect(remoteAddress, 0); // blocks until closed by the race, then throws
+ return firstSocket;
+ }
+ socketConsumer.accept(secondSocket);
+ return secondSocket;
+ }));
+
+ assertEquals(secondSocket, winner);
+ assertTrue(firstSocket.connectAttempted, "the first attempt must have genuinely started connecting");
+ assertTrue(firstSocket.isClosed(), "the losing, still-connecting socket must be closed rather than leaked");
+ }
+
+ @Test
+ void allAddressesFail_aggregatedFailure() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+
+ final IOException ex = assertThrows(IOException.class, () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ throw new IOException("refused: " + remoteAddress);
+ }));
+ assertTrue(ex.getMessage() != null);
+ }
+
+ @Test
+ void firstAddressFailsFast_secondStartsWithoutWaitingOutTheFullDelay() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(250));
+ final Socket winnerSocket = new Socket();
+
+ final long start = System.nanoTime();
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ throw new IOException("refused");
+ }
+ socketConsumer.accept(winnerSocket);
+ return winnerSocket;
+ }));
+ final long elapsedMs = (System.nanoTime() - start) / 1_000_000;
+
+ // The 2nd address must not have had to wait out the 250ms stagger delay, since the
+ // 1st address failed fast rather than merely being slow: it only waits the RFC 8305
+ // minimum inter-attempt spacing (10ms).
+ assertEquals(winnerSocket, winner);
+ assertTrue(elapsedMs < 200, "must advance well before the full stagger delay elapses, took " + elapsedMs + "ms");
+ }
+
+ @Test
+ void interruptionWhileStillRacing_closesLoserSocket() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket firstSocket = new BlockingSocket();
+ final Socket secondSocket = new Socket();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ socketConsumer.accept(firstSocket);
+ firstSocket.connect(remoteAddress, 0);
+ return firstSocket;
+ }
+ socketConsumer.accept(secondSocket);
+ return secondSocket;
+ }));
+
+ assertEquals(secondSocket, winner);
+ // The executor's shutdownNow() (called in the finally block) interrupts the still
+ // "connecting" worker; its socket must still end up closed, not leaked.
+ assertTrue(firstSocket.isClosed());
+ }
+
+ @Test
+ void interruptionDuringMinimumSpacingWait_abortsBeforeStartingNextAddress() throws Exception {
+ // Regression test: sleepOrAbort() (the minimum-spacing wait after a fast failure) must
+ // propagate an interruption instead of swallowing it and continuing the race.
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(250));
+ final AtomicInteger attempts = new AtomicInteger();
+ final CountDownLatch firstFailed = new CountDownLatch(1);
+ final AtomicReference thrown = new AtomicReference<>();
+
+ final Thread caller = new Thread(() -> {
+ try {
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ attempts.incrementAndGet();
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ firstFailed.countDown();
+ throw new IOException("refused");
+ }
+ return new Socket();
+ });
+ } catch (final Throwable ex) {
+ thrown.set(ex);
+ }
+ });
+ caller.start();
+ assertTrue(firstFailed.await(5, TimeUnit.SECONDS));
+ caller.interrupt(); // races the <=10ms minimum-spacing wait that follows the failure
+ caller.join(5000);
+
+ assertFalse(caller.isAlive());
+ // Best-effort timing: if the interruption landed while connect() was still running, it
+ // must be reported as InterruptedIOException, never silently swallowed.
+ if (thrown.get() != null) {
+ assertTrue(thrown.get() instanceof InterruptedIOException,
+ "an interruption during racing must surface as InterruptedIOException: " + thrown.get());
+ }
+ }
+
+ @Test
+ void interruptingTheCallingThread_abortsAndClosesTheStillConnectingSocket() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final BlockingSocket onlySocket = new BlockingSocket();
+ final CountDownLatch connecting = new CountDownLatch(1);
+ final AtomicReference thrown = new AtomicReference<>();
+
+ final Thread caller = new Thread(() -> {
+ try {
+ connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ socketConsumer.accept(onlySocket);
+ connecting.countDown();
+ onlySocket.connect(remoteAddress, 0); // blocks until closed or interrupted
+ return onlySocket;
+ });
+ } catch (final Throwable ex) {
+ thrown.set(ex);
+ }
+ });
+ caller.start();
+ assertTrue(connecting.await(5, TimeUnit.SECONDS), "the attempt must have genuinely started connecting");
+ caller.interrupt();
+ caller.join(5000);
+
+ assertFalse(caller.isAlive(), "the calling thread must have returned after being interrupted");
+ assertTrue(thrown.get() instanceof InterruptedIOException,
+ "connect() must report the interruption rather than silently returning: was " + thrown.get());
+ assertTrue(onlySocket.isClosed(), "the still-connecting socket must be closed, not leaked, on interruption");
+ }
+
+ @Test
+ void registrationAfterRaceDecided_closesSocketImmediately() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket winnerSocket = new Socket();
+ final CountDownLatch registerNow = new CountDownLatch(1);
+ final CountDownLatch registered = new CountDownLatch(1);
+ final AtomicReference lateSocketRef = new AtomicReference<>();
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("somehost"), addresses(2), (remoteAddress, socketConsumer) -> {
+ if (remoteAddress.getAddress().getAddress()[3] == 1) {
+ // Registers strictly after the race below has already picked a winner.
+ awaitUninterruptibly(registerNow);
+ final Socket lateSocket = new Socket();
+ lateSocketRef.set(lateSocket);
+ socketConsumer.accept(lateSocket);
+ registered.countDown();
+ throw new IOException("too late");
+ }
+ socketConsumer.accept(winnerSocket);
+ return winnerSocket;
+ }));
+
+ assertEquals(winnerSocket, winner);
+ registerNow.countDown();
+ assertTrue(registered.await(5, TimeUnit.SECONDS));
+ assertTrue(lateSocketRef.get().isClosed(),
+ "a socket registered strictly after the race is decided must be closed immediately, not left open");
+ }
+
+ private static void awaitUninterruptibly(final CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
+
+ @Test
+ void doesNotRejectSingleAddressBelowStaggerIndex() throws Exception {
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final Socket socket = new Socket();
+
+ final Socket result = connector.connect(new HttpHost("somehost"), addresses(1), (remoteAddress, socketConsumer) -> {
+ socketConsumer.accept(socket);
+ return socket;
+ });
+
+ assertEquals(socket, result);
+ assertFalse(socket.isClosed());
+ }
+
+ /**
+ * Real-socket integration test (no mocks, no fakes): one address has nothing listening
+ * (genuine, OS-level immediate connection refusal) and the other is a real local server
+ * that accepts. Proves actual fallover over real loopback TCP, not just that the first
+ * address happens to succeed.
+ */
+ @Test
+ void realSockets_unreachableAddressFailsOver_toRealListeningServer() throws Exception {
+ try (ServerSocket server = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ final int listeningPort = server.getLocalPort();
+ final int deadPort = findUnusedLoopbackPort();
+
+ final HappyEyeballsSocketConnector connector = new HappyEyeballsSocketConnector(TimeValue.ofMilliseconds(20));
+ final List targets = new ArrayList<>();
+ targets.add(new InetSocketAddress(InetAddress.getLoopbackAddress(), deadPort));
+ targets.add(new InetSocketAddress(InetAddress.getLoopbackAddress(), listeningPort));
+
+ final Socket winner = assertTimeoutPreemptively(Duration.ofSeconds(5), () ->
+ connector.connect(new HttpHost("localhost"), targets, (remoteAddress, socketConsumer) -> {
+ final Socket s = new Socket();
+ socketConsumer.accept(s);
+ s.connect(remoteAddress, 2000);
+ return s;
+ }));
+
+ assertEquals(listeningPort, winner.getPort());
+ assertFalse(winner.isClosed());
+ winner.close();
+ }
+ }
+
+ /** Finds a loopback TCP port nothing is listening on, by briefly binding then closing it. */
+ private static int findUnusedLoopbackPort() throws IOException {
+ try (ServerSocket probe = new ServerSocket(0, 1, InetAddress.getLoopbackAddress())) {
+ return probe.getLocalPort();
+ }
+ }
+}
diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
index e2ec5696b8..3997b2ee21 100644
--- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
+++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/MultihomeIOSessionRequesterTest.java
@@ -28,29 +28,45 @@
package org.apache.hc.client5.http.impl.nio;
import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyLong;
+import static org.mockito.ArgumentMatchers.eq;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Deque;
import java.util.List;
+import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicReference;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.core5.concurrent.FutureCallback;
+import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.net.NamedEndpoint;
import org.apache.hc.core5.reactor.ConnectionInitiator;
import org.apache.hc.core5.reactor.IOSession;
+import org.apache.hc.core5.util.TimeValue;
import org.apache.hc.core5.util.Timeout;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
class MultihomeIOSessionRequesterTest {
@@ -158,4 +174,515 @@ void testConnectSuccessfulAfterRetries() throws Exception {
fail("Did not expect an ExecutionException", ex);
}
}
+
+ // -------------------------------------------------------------------------
+ // RFC 8305 connection racing (Happy Eyeballs v2)
+ // -------------------------------------------------------------------------
+
+ /** Captures scheduled stagger tasks instead of running them on a timer, for determinism. */
+ private static final class FakeScheduler {
+ final ScheduledExecutorService mock = Mockito.mock(ScheduledExecutorService.class);
+ final Deque pending = new ArrayDeque<>();
+
+ @SuppressWarnings("unchecked")
+ FakeScheduler() {
+ Mockito.when(mock.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
+ .thenAnswer(invocation -> {
+ pending.add(invocation.getArgument(0));
+ return Mockito.mock(ScheduledFuture.class);
+ });
+ }
+
+ /** Runs the next pending stagger task, as if its delay had elapsed. */
+ void fireNext() {
+ final Runnable task = pending.poll();
+ assertNotNull(task, "no stagger task was scheduled");
+ task.run();
+ }
+
+ int pendingCount() {
+ return pending.size();
+ }
+ }
+
+ private static List addresses(final int count) throws Exception {
+ final List out = new ArrayList<>(count);
+ for (int i = 1; i <= count; i++) {
+ out.add(new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, (byte) i}), 8080));
+ }
+ return out;
+ }
+
+ @SuppressWarnings("unchecked")
+ private static FutureCallback[] captureCallbacks(final ConnectionInitiator connectionInitiator, final int expected) {
+ final ArgumentCaptor captor = ArgumentCaptor.forClass(FutureCallback.class);
+ Mockito.verify(connectionInitiator, Mockito.times(expected))
+ .connect(any(), any(), any(), any(), any(), captor.capture());
+ return captor.getAllValues().toArray(new FutureCallback[0]);
+ }
+
+ @Test
+ void happyEyeballs_firstAddressSucceedsImmediately_noStaggerNeeded() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+ // Only the first address was ever attempted; the second was never needed.
+ Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any());
+ Mockito.verify(winnerSession, Mockito.never()).close(any(CloseMode.class));
+ }
+
+ @Test
+ void happyEyeballs_firstAddressStalls_secondWinsAfterStagger() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ final Future firstAttempt = Mockito.mock(Future.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> firstAttempt) // 1st call: stalls, no callback invoked yet.
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertFalse(future.isDone(), "must not complete before the stalled first attempt or the stagger fires");
+ assertEquals(1, scheduler.pendingCount());
+
+ scheduler.fireNext(); // simulate the 250ms stagger elapsing
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+
+ // The still-stalled first attempt must have been cancelled, not left to leak.
+ Mockito.verify(firstAttempt).cancel(true);
+ }
+
+ @Test
+ void happyEyeballs_firstAddressFailsFast_advancesPromptlyAtMinimumSpacingNotFullStagger() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.failed(new IOException("refused"));
+ return CompletableFuture.completedFuture(null);
+ })
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ // The 1st address failed immediately: the 2nd must be scheduled at the RFC 8305
+ // Section 5 minimum inter-attempt spacing (10ms), not the full 250ms stagger delay.
+ assertFalse(future.isDone());
+ final ArgumentCaptor delayCaptor = ArgumentCaptor.forClass(Long.class);
+ Mockito.verify(scheduler.mock).schedule(any(Runnable.class), delayCaptor.capture(), eq(TimeUnit.MILLISECONDS));
+ assertTrue(delayCaptor.getValue() <= 10L && delayCaptor.getValue() > 0L,
+ "must advance at the minimum spacing (<=10ms), not the full stagger delay: was " + delayCaptor.getValue());
+
+ scheduler.fireNext();
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+ Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void happyEyeballs_bothAttemptsSucceed_loserSessionIsClosedNotLeaked() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession secondSession = Mockito.mock(IOSession.class);
+ final Future firstAttempt = Mockito.mock(Future.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> firstAttempt) // stalls until completed manually below
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(secondSession);
+ return CompletableFuture.completedFuture(secondSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ // The first attempt stalls, so the stagger fires and starts the second attempt, which
+ // wins the race immediately.
+ assertFalse(future.isDone());
+ scheduler.fireNext();
+ assertTrue(future.isDone());
+ assertEquals(secondSession, future.get());
+ Mockito.verify(secondSession, Mockito.never()).close(any(CloseMode.class));
+
+ // The first address now completes late, after the race was already decided: its
+ // session must be discarded rather than leaked or allowed to override the winner.
+ final FutureCallback[] allCallbacks = captureCallbacks(connectionInitiator, 2);
+ final IOSession lateSession = Mockito.mock(IOSession.class);
+ allCallbacks[0].completed(lateSession);
+
+ Mockito.verify(lateSession).close(CloseMode.IMMEDIATE);
+ assertEquals(secondSession, future.get(), "the already-decided winner must not change");
+ }
+
+ @Test
+ void happyEyeballs_allAddressesFail_aggregatedFailure() throws Exception {
+ final List remoteAddresses = addresses(3);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.failed(new IOException("refused"));
+ return CompletableFuture.completedFuture(null);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ // All 3 addresses fail fast, one after another; each advance is scheduled at the
+ // RFC 8305 minimum inter-attempt spacing (10ms) rather than happening synchronously.
+ assertFalse(future.isDone());
+ scheduler.fireNext();
+ assertFalse(future.isDone());
+ scheduler.fireNext();
+ assertTrue(future.isDone());
+ Mockito.verify(connectionInitiator, Mockito.times(3)).connect(any(), any(), any(), any(), any(), any());
+ try {
+ future.get();
+ fail("Expected ExecutionException");
+ } catch (final ExecutionException ex) {
+ assertInstanceOf(IOException.class, ex.getCause());
+ }
+ }
+
+ @Test
+ void happyEyeballs_cancellationBeforeAnyAttemptResolves_cancelsOutstandingAndPendingStagger() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final FakeScheduler scheduler = new FakeScheduler();
+ final Future firstAttempt = Mockito.mock(Future.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> firstAttempt);
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertFalse(future.isDone());
+ assertEquals(1, scheduler.pendingCount());
+
+ future.cancel(true);
+
+ Mockito.verify(firstAttempt).cancel(true);
+ assertTrue(future.isCancelled());
+ }
+
+ @Test
+ void happyEyeballs_lateCompletionAfterCancellation_closesSessionWithoutReachingFuture() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> Mockito.mock(Future.class));
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+ future.cancel(true);
+
+ final FutureCallback[] callbacks = captureCallbacks(connectionInitiator, 1);
+ final IOSession lateSession = Mockito.mock(IOSession.class);
+ callbacks[0].completed(lateSession);
+
+ Mockito.verify(lateSession).close(CloseMode.IMMEDIATE);
+ assertTrue(future.isCancelled());
+ }
+
+ @Test
+ void happyEyeballs_singleAddress_doesNotRace() throws Exception {
+ final List remoteAddresses = addresses(1);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession session = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(session);
+ return CompletableFuture.completedFuture(session);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertTrue(future.isDone());
+ assertEquals(session, future.get());
+ assertEquals(0, scheduler.pendingCount(), "a single address must never schedule a stagger");
+ }
+
+ @Test
+ void happyEyeballs_disabledByDefault_usesSequentialPathEvenWithMultipleAddresses() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession session = Mockito.mock(IOSession.class);
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(session);
+ return CompletableFuture.completedFuture(session);
+ });
+
+ // Explicit happyEyeballsEnabled=false, as opposed to the default single-arg constructor
+ // already exercised by the other tests in this class.
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, false, TimeValue.ofMilliseconds(250));
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertTrue(future.isDone());
+ assertEquals(session, future.get());
+ Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any());
+ }
+
+ @Test
+ void happyEyeballs_respectsConfiguredDelay() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> Mockito.mock(Future.class));
+
+ final ScheduledExecutorService schedulerMock = Mockito.mock(ScheduledExecutorService.class);
+ Mockito.when(schedulerMock.schedule(any(Runnable.class), anyLong(), any(TimeUnit.class)))
+ .thenReturn(Mockito.mock(ScheduledFuture.class));
+
+ final MultihomeIOSessionRequester requester = new MultihomeIOSessionRequester(
+ dnsResolver, true, TimeValue.ofMilliseconds(777), schedulerMock);
+ requester.connect(connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ Mockito.verify(schedulerMock).schedule(any(Runnable.class), org.mockito.ArgumentMatchers.eq(777L), org.mockito.ArgumentMatchers.eq(TimeUnit.MILLISECONDS));
+ }
+
+ @Test
+ void happyEyeballs_rejectsDelayBelowRfc8305Minimum() {
+ assertThrows(IllegalArgumentException.class,
+ () -> new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(5)));
+ }
+
+ @Test
+ void happyEyeballs_unexpectedCancellationOfNonLastAttempt_advancesToNextAddress() throws Exception {
+ final List remoteAddresses = addresses(2);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession winnerSession = Mockito.mock(IOSession.class);
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ // Cancelled by something other than this race itself (e.g. an external
+ // close), not a failure and not our own decided/cancel() path.
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.cancelled();
+ return CompletableFuture.completedFuture(null);
+ })
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.completed(winnerSession);
+ return CompletableFuture.completedFuture(winnerSession);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertFalse(future.isDone());
+ scheduler.fireNext(); // the minimum-spacing advance after the unexpected cancellation
+ assertTrue(future.isDone());
+ assertEquals(winnerSession, future.get());
+ }
+
+ @Test
+ void happyEyeballs_unexpectedCancellationOfLastAttempt_failsRatherThanHangingForever() throws Exception {
+ final List remoteAddresses = addresses(1);
+ Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(namedEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ // A single address racing alone still goes through the Race (not the sequential path)
+ // when forced via the 4-arg constructor is not applicable here; use 2 addresses with
+ // the 2nd address also cancelled, so the race is driven to full exhaustion.
+ final List twoAddresses = addresses(2);
+ Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(twoAddresses);
+
+ final FakeScheduler scheduler = new FakeScheduler();
+ Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ final FutureCallback cb = invocation.getArgument(5);
+ cb.cancelled();
+ return CompletableFuture.completedFuture(null);
+ });
+
+ final MultihomeIOSessionRequester requester =
+ new MultihomeIOSessionRequester(dnsResolver, true, TimeValue.ofMilliseconds(250), scheduler.mock);
+ final Future future = requester.connect(
+ connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ assertFalse(future.isDone());
+ scheduler.fireNext();
+ assertTrue(future.isDone(), "the future must not be left pending forever after every attempt is cancelled");
+ assertTrue(future.isCancelled() || future.isDone());
+ try {
+ future.get();
+ fail("Expected an ExecutionException rather than an indefinitely pending future");
+ } catch (final ExecutionException ex) {
+ assertInstanceOf(CancellationException.class, ex.getCause());
+ }
+ }
+
+ /**
+ * Reproduces the race between {@code Race#onAttemptCompleted} picking a winner and the
+ * caller cancelling the outer {@code Future} directly (not through the Race's own
+ * {@code cancel()}): {@code ComplexFuture#completed(T)} can then return {@code false}
+ * even though the Race's own bookkeeping says it won, and the winning session must still
+ * be closed rather than silently leaked. This genuinely requires two threads contending
+ * on the same narrow window inside {@code ComplexFuture#cancel}, so the test runs many
+ * iterations under real contention and asserts the invariant (no leaked session, exactly
+ * one terminal outcome) holds on every one, rather than depending on hitting the window
+ * a specific number of times.
+ */
+ @Test
+ void happyEyeballs_concurrentExternalCancelDuringWinnerSelection_neverLeaksSession() throws Exception {
+ for (int i = 0; i < 500; i++) {
+ // 2 addresses so this goes through the Race (not the sequential) path; the 2nd
+ // attempt is left permanently stalled behind a FakeScheduler so no real timer
+ // ever fires during the test.
+ final List remoteAddresses = addresses(2);
+ final DnsResolver localDnsResolver = Mockito.mock(DnsResolver.class);
+ final ConnectionInitiator localConnectionInitiator = Mockito.mock(ConnectionInitiator.class);
+ final NamedEndpoint localEndpoint = Mockito.mock(NamedEndpoint.class);
+ Mockito.when(localEndpoint.getHostName()).thenReturn("somehost");
+ Mockito.when(localEndpoint.getPort()).thenReturn(8080);
+ Mockito.when(localDnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses);
+
+ final IOSession session = Mockito.mock(IOSession.class);
+ final AtomicReference> attemptCallback = new AtomicReference<>();
+ final FakeScheduler localScheduler = new FakeScheduler();
+ Mockito.when(localConnectionInitiator.connect(any(), any(), any(), any(), any(), any()))
+ .thenAnswer(invocation -> {
+ attemptCallback.set(invocation.getArgument(5));
+ return Mockito.mock(Future.class);
+ });
+
+ final MultihomeIOSessionRequester requester = new MultihomeIOSessionRequester(
+ localDnsResolver, true, TimeValue.ofMilliseconds(250), localScheduler.mock);
+ final Future future = requester.connect(
+ localConnectionInitiator, localEndpoint, null, Timeout.ofSeconds(5), null, null);
+
+ final CountDownLatch ready = new CountDownLatch(2);
+ final CountDownLatch go = new CountDownLatch(1);
+ final Thread canceller = new Thread(() -> {
+ ready.countDown();
+ await(go);
+ future.cancel(true);
+ });
+ final Thread completer = new Thread(() -> {
+ ready.countDown();
+ await(go);
+ attemptCallback.get().completed(session);
+ });
+ canceller.start();
+ completer.start();
+ ready.await();
+ go.countDown();
+ canceller.join(5000);
+ completer.join(5000);
+
+ // Exactly one terminal outcome, and the session is never left open.
+ assertTrue(future.isDone());
+ boolean sessionDelivered = false;
+ try {
+ sessionDelivered = future.get() == session;
+ } catch (final CancellationException | ExecutionException ex) {
+ sessionDelivered = false;
+ }
+ if (!sessionDelivered) {
+ Mockito.verify(session, Mockito.atLeastOnce()).close(CloseMode.IMMEDIATE);
+ } else {
+ Mockito.verify(session, Mockito.never()).close(any(CloseMode.class));
+ }
+ }
+ }
+
+ private static void await(final CountDownLatch latch) {
+ try {
+ latch.await();
+ } catch (final InterruptedException ex) {
+ Thread.currentThread().interrupt();
+ }
+ }
}
diff --git a/pom.xml b/pom.xml
index 89917198bb..e804b3287c 100644
--- a/pom.xml
+++ b/pom.xml
@@ -74,21 +74,21 @@
5.5
2.26.1
1.24.0
- 2.8.0
+ 2.10.0
3.11.1
2.12.3
1.7.36
- 5.14.4
+ 5.14.5
4.11.0
1
3.1.12
2.0.5
2.11.1
1.28.0
- 1.5.7-25
- 1.17.2
- 1.7.2
- 1.67.0
+ 1.6.0-1
+ 1.18.0
+ 1.8.0
+ 1.68.0
1.26.2
2.9.3
4.0.0