From 655f0dddde3bd2117eedaea09a7b52391c2812f5 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Wed, 25 Nov 2026 18:45:28 +0100 Subject: [PATCH 01/15] Route GitHub Issues notifications to commits@ instead of dev@ No notifications block meant issue events defaulted to dev@hc.apache.org via the Apache Git Service. Harmless at normal volume, but the Jira Issues migration (INFRA-28579) is about to import 2347 issues here, which would flood the list. Point issues at commits@hc.apache.org instead, same pattern apache/maven and apache/opennlp use after their own Jira migrations. --- .asf.yaml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.asf.yaml b/.asf.yaml index 6156e99e89..bd96d25d13 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -15,6 +15,9 @@ # specific language governing permissions and limitations # under the License. +notifications: + issues: commits@hc.apache.org + github: features: issues: true From 393f88469d5201f76c4260a22d6bb6b864ba300d Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Wed, 25 Nov 2026 18:49:27 +0100 Subject: [PATCH 02/15] Fix mailing list domain in notifications.issues The ASF Git Service's .asf.yaml validator rejected commits@hc.apache.org: notifications targets must be the project's real @httpcomponents.apache.org list, not the hc.apache.org vanity domain used on the website/mail links. --- .asf.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.asf.yaml b/.asf.yaml index bd96d25d13..ce596ce6b6 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -16,7 +16,7 @@ # under the License. notifications: - issues: commits@hc.apache.org + issues: commits@httpcomponents.apache.org github: features: From a6a2713515e9337b8fd54e5cdaf6e3ad72722be1 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Wed, 25 Nov 2026 19:29:12 +0100 Subject: [PATCH 03/15] Point notifications.issues at the new notifications@ list Neither commits@hc.apache.org nor commits@httpcomponents.apache.org validated. Infra is creating notifications@hc.apache.org instead (INFRA-28579, simpler than a new list under httpcomponents.apache.org). Don't merge until confirmed created. --- .asf.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.asf.yaml b/.asf.yaml index ce596ce6b6..09b87150f5 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -16,7 +16,7 @@ # under the License. notifications: - issues: commits@httpcomponents.apache.org + issues: notifications@hc.apache.org github: features: From ef4fd794dde5e6186a1cf398434a2847d846ad88 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Thu, 26 Nov 2026 09:28:16 +0100 Subject: [PATCH 04/15] Re-save .asf.yaml to re-trigger notifications validation The mapping was fixed in apache/infrastructure-asfyaml#152 (httpcomponents -> hc), but issue notifications still went to dev@ after the merge. No content change, just a fresh push to .asf.yaml to force the Git Service to re-evaluate the notifications block. --- .asf.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.asf.yaml b/.asf.yaml index 09b87150f5..55dd8702f0 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -16,6 +16,8 @@ # under the License. notifications: + # Re-saved 2026-11-26 after the httpcomponents->hc domain mapping fix in + # apache/infrastructure-asfyaml#152, to force re-validation. issues: notifications@hc.apache.org github: From adf333106f8cb17d1d9f84bc0bbe725aa77e6a5a Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Thu, 26 Nov 2026 10:50:28 +0100 Subject: [PATCH 05/15] Temporarily revert .asf.yaml notifications::issues to dev@hc.apache.org Per Infra (Bob), force a real value-diff push to .asf.yaml so the Git Service fully reprocesses notifications::issues end to end, rather than a no-op comment-only re-save. Restored to notifications@hc.apache.org in a follow-up commit. --- .asf.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/.asf.yaml b/.asf.yaml index 55dd8702f0..3fa9ca359d 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -16,9 +16,11 @@ # under the License. notifications: - # Re-saved 2026-11-26 after the httpcomponents->hc domain mapping fix in - # apache/infrastructure-asfyaml#152, to force re-validation. - issues: notifications@hc.apache.org + # Temporary revert, 2026-11-26: Infra (Bob) asked for an explicit + # value change (not a no-op comment) to force the Git Service to + # reprocess notifications::issues end to end. Restored to + # notifications@hc.apache.org in a follow-up commit/push. + issues: dev@hc.apache.org github: features: From 2f22ea55c2152ed5b4720b566e227944780eb55d Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Thu, 26 Nov 2026 10:51:19 +0100 Subject: [PATCH 06/15] Restore .asf.yaml notifications::issues to notifications@hc.apache.org Second half of the revert/restore cycle Infra (Bob) asked for, to force the Git Service to fully reprocess notifications::issues end to end. --- .asf.yaml | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/.asf.yaml b/.asf.yaml index 3fa9ca359d..09b87150f5 100644 --- a/.asf.yaml +++ b/.asf.yaml @@ -16,11 +16,7 @@ # under the License. notifications: - # Temporary revert, 2026-11-26: Infra (Bob) asked for an explicit - # value change (not a no-op comment) to force the Git Service to - # reprocess notifications::issues end to end. Restored to - # notifications@hc.apache.org in a follow-up commit/push. - issues: dev@hc.apache.org + issues: notifications@hc.apache.org github: features: From 782dbd443707184fabb9d117c1e5c6cb014adff2 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Fri, 9 Jan 2026 18:52:22 +0100 Subject: [PATCH 07/15] Add RFC6724-based DNS resolver with configurable family preference. Define INTERLEAVE as no-bias and align tests and debug output. --- .../Rfc6724AddressSelectingDnsResolver.java | 595 ++++++++++++++++++ .../http/config/ProtocolFamilyPreference.java | 67 ++ ...fc6724AddressSelectingDnsResolverTest.java | 170 +++++ 3 files changed, 832 insertions(+) create mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java create mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java create mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java b/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java new file mode 100644 index 0000000000..357b0dcf60 --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java @@ -0,0 +1,595 @@ +/* + * ==================================================================== + * 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 java.net.DatagramSocket; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import org.apache.hc.client5.http.config.ProtocolFamilyPreference; +import org.apache.hc.core5.annotation.Contract; +import org.apache.hc.core5.annotation.ThreadingBehavior; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * {@code Rfc6724AddressSelectingDnsResolver} wraps a delegate {@link DnsResolver} + * and applies RFC 6724 destination address selection rules to the returned + * addresses. It can also enforce or bias a protocol family preference. + * + *

The canonical hostname lookup is delegated unchanged.

+ * + *

+ * {@link ProtocolFamilyPreference#INTERLEAVE} is treated as "no family bias": + * the resolver keeps the RFC 6724 sorted order intact. Family interleaving, if + * desired, should be handled at dial time (e.g. Happy Eyeballs). + *

+ * + * @since 5.6 + */ +@Contract(threading = ThreadingBehavior.IMMUTABLE) +public final class Rfc6724AddressSelectingDnsResolver implements DnsResolver { + + private static final Logger LOG = LoggerFactory.getLogger(Rfc6724AddressSelectingDnsResolver.class); + + private static final int PROBE_PORT = 53; // UDP connect trick; no packets sent + + private final DnsResolver delegate; + private final ProtocolFamilyPreference familyPreference; + + /** + * Creates a new resolver that applies RFC 6724 ordering with no family bias (INTERLEAVE). + * + * @param delegate underlying resolver to use. + */ + public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { + this(delegate, ProtocolFamilyPreference.INTERLEAVE); + } + + /** + * Creates a new resolver that applies RFC 6724 ordering and a specific protocol family preference. + * + * @param delegate underlying resolver to use. + * @param familyPreference family preference to apply (e.g. PREFER_IPV6, IPV4_ONLY). + */ + public Rfc6724AddressSelectingDnsResolver( + final DnsResolver delegate, + final ProtocolFamilyPreference familyPreference) { + this.delegate = java.util.Objects.requireNonNull(delegate, "delegate"); + this.familyPreference = familyPreference != null ? familyPreference : ProtocolFamilyPreference.INTERLEAVE; + } + + @Override + public InetAddress[] resolve(final String host) throws UnknownHostException { + if (LOG.isDebugEnabled()) { + LOG.debug("{} resolving host '{}' via delegate {}", simpleName(), host, delegate.getClass().getName()); + LOG.debug("{} familyPreference={}", simpleName(), familyPreference); + } + + final InetAddress[] resolved = delegate.resolve(host); + if (resolved == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} delegate returned null for '{}'", simpleName(), host); + } + return null; + } + if (LOG.isDebugEnabled()) { + LOG.debug("{} delegate returned {} addresses for '{}': {}", simpleName(), resolved.length, host, fmt(resolved)); + } + if (resolved.length <= 1) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} nothing to sort/filter (<=1 address). Returning as-is.", simpleName()); + } + return resolved; + } + + // 1) Filter by family if forced + final List candidates = new ArrayList<>(resolved.length); + switch (familyPreference) { + case IPV4_ONLY: { + for (final InetAddress a : resolved) { + if (a instanceof Inet4Address) { + candidates.add(a); + } + } + break; + } + case IPV6_ONLY: { + for (final InetAddress a : resolved) { + if (a instanceof Inet6Address) { + candidates.add(a); + } + } + break; + } + default: { + candidates.addAll(Arrays.asList(resolved)); + break; + } + } + + if (LOG.isDebugEnabled()) { + LOG.debug("{} after family filter {} -> {} candidate(s): {}", simpleName(), familyPreference, candidates.size(), fmt(candidates)); + } + + if (candidates.isEmpty()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} no address of requested family; returning empty for '{}'", simpleName(), host); + } + return new InetAddress[0]; + } + + // 2) RFC 6724 sort (uses UDP connect to infer source addresses; no packets sent) + final List rfcSorted = sortByRfc6724(candidates); + + // 3) Apply preference bias + final List ordered = applyFamilyPreference(rfcSorted, familyPreference); + + if (LOG.isDebugEnabled()) { + LOG.debug("{} final ordered list for '{}': {}", simpleName(), host, fmt(ordered)); + } + + return ordered.toArray(new InetAddress[0]); + } + + @Override + public String resolveCanonicalHostname(final String host) throws UnknownHostException { + if (LOG.isDebugEnabled()) { + LOG.debug("{} resolveCanonicalHostname('{}') via delegate {}", simpleName(), host, delegate.getClass().getName()); + } + return delegate.resolveCanonicalHostname(host); + } + + // --- RFC 6724 helpers --- + + private static List sortByRfc6724(final List addrs) { + if (addrs.size() < 2) { + return addrs; + } + if (LOG.isDebugEnabled()) { + LOG.debug("RFC6724 input candidates: {}", fmt(addrs)); + } + + final List sockAddrs = new ArrayList<>(addrs.size()); + for (final InetAddress a : addrs) { + sockAddrs.add(new InetSocketAddress(a, PROBE_PORT)); + } + final List srcs = srcAddrs(sockAddrs); + + final List infos = new ArrayList<>(addrs.size()); + for (int i = 0; i < addrs.size(); i++) { + final InetAddress dst = addrs.get(i); + final InetAddress src = srcs.get(i); + infos.add(new Info(dst, src, ipAttrOf(dst), ipAttrOf(src))); + } + + if (LOG.isDebugEnabled()) { + for (final Info info : infos) { + LOG.debug("RFC6724 candidate dst={} src={} dst[scope={},prec={},label={}] src[scope={},prec={},label={}]", + addr(info.dst), addr(info.src), + info.dstAttr.scope, info.dstAttr.precedence, info.dstAttr.label, + info.srcAttr.scope, info.srcAttr.precedence, info.srcAttr.label); + } + } + + infos.sort(RFC6724_COMPARATOR); + + final List out = new ArrayList<>(infos.size()); + for (final Info info : infos) { + out.add(info.dst); + } + + if (LOG.isDebugEnabled()) { + LOG.debug("RFC6724 output order: {}", fmt(out)); + } + return out; + } + + private static List applyFamilyPreference( + final List rfcSorted, + final ProtocolFamilyPreference pref) { + + if (rfcSorted.size() <= 1) { + return rfcSorted; + } + + switch (pref) { + case PREFER_IPV6: + case PREFER_IPV4: { + final boolean preferV6 = pref == ProtocolFamilyPreference.PREFER_IPV6; + final List first = new ArrayList<>(); + final List second = new ArrayList<>(); + for (final InetAddress a : rfcSorted) { + final boolean isV6 = a instanceof Inet6Address; + if (preferV6 && isV6 || !preferV6 && !isV6) { + first.add(a); + } else { + second.add(a); + } + } + final List merged = new ArrayList<>(rfcSorted.size()); + merged.addAll(first); + merged.addAll(second); + if (LOG.isDebugEnabled()) { + LOG.debug("Family preference {} applied. First bucket={}, second bucket={}", pref, fmt(first), fmt(second)); + LOG.debug("Family preference output: {}", fmt(merged)); + } + return merged; + } + case IPV4_ONLY: + case IPV6_ONLY: { + // already filtered earlier + if (LOG.isDebugEnabled()) { + LOG.debug("Family preference {} enforced earlier. Order unchanged: {}", pref, fmt(rfcSorted)); + } + return rfcSorted; + } + case INTERLEAVE: + default: { + // No family bias. Keep RFC 6724 order intact. + if (LOG.isDebugEnabled()) { + LOG.debug("INTERLEAVE treated as no-bias. Order unchanged: {}", fmt(rfcSorted)); + } + return rfcSorted; + } + } + } + + private static List srcAddrs(final List addrs) { + final List srcs = new ArrayList<>(addrs.size()); + for (final InetSocketAddress dest : addrs) { + InetAddress src = null; + try (final DatagramSocket s = new DatagramSocket()) { + s.connect(dest); // does not send packets; OS picks source addr/if + src = s.getLocalAddress(); + } catch (final SocketException ignore) { + if (LOG.isDebugEnabled()) { + LOG.debug("RFC6724 could not infer source address for {}: {}", dest, ignore.toString()); + } + } + srcs.add(src); + } + if (LOG.isDebugEnabled()) { + final List printable = new ArrayList<>(srcs.size()); + for (final InetAddress a : srcs) { + printable.add(addr(a)); + } + LOG.debug("RFC6724 inferred source addresses: {}", printable); + } + return srcs; + } + + // --- RFC 6724 score structs --- + + private static final class Info { + final InetAddress dst; + final InetAddress src; + final Attr dstAttr; + final Attr srcAttr; + + Info(final InetAddress dst, final InetAddress src, final Attr dstAttr, final Attr srcAttr) { + this.dst = dst; + this.src = src; + this.dstAttr = dstAttr; + this.srcAttr = srcAttr; + } + } + + private static final class Attr { + final Scope scope; + final int precedence; + final int label; + + Attr(final Scope scope, final int precedence, final int label) { + this.scope = scope; + this.precedence = precedence; + this.label = label; + } + } + + private enum Scope { + INTERFACE_LOCAL(0x1), + LINK_LOCAL(0x2), + ADMIN_LOCAL(0x4), + SITE_LOCAL(0x5), + ORG_LOCAL(0x8), + GLOBAL(0xe); + + final int value; + + Scope(final int v) { + this.value = v; + } + + static Scope fromValue(final int v) { + switch (v) { + case 0x1: { + return INTERFACE_LOCAL; + } + case 0x2: { + return LINK_LOCAL; + } + case 0x4: { + return ADMIN_LOCAL; + } + case 0x5: { + return SITE_LOCAL; + } + case 0x8: { + return ORG_LOCAL; + } + default: { + return GLOBAL; + } + } + } + } + + private static Attr ipAttrOf(final InetAddress ip) { + if (ip == null) { + return new Attr(Scope.GLOBAL, 0, 0); + } + final PolicyEntry e = classify(ip); + return new Attr(classifyScope(ip), e.precedence, e.label); + } + + private static Scope classifyScope(final InetAddress ip) { + if (ip.isLoopbackAddress()) { + return Scope.INTERFACE_LOCAL; + } + if (ip.isLinkLocalAddress()) { + return Scope.LINK_LOCAL; + } + if (ip.isMulticastAddress()) { + if (ip instanceof Inet6Address) { + // RFC 4291: low 4 bits of second byte are scope. + return Scope.fromValue(ip.getAddress()[1] & 0x0f); + } + return Scope.GLOBAL; + } + if (ip.isSiteLocalAddress()) { + return Scope.SITE_LOCAL; + } + return Scope.GLOBAL; + } + + private static final class PolicyEntry { + final Network prefix; + final int precedence; + final int label; + + PolicyEntry(final Network prefix, final int precedence, final int label) { + this.prefix = prefix; + this.precedence = precedence; + this.label = label; + } + } + + private static final class Network { + final byte[] ip; + final int bits; + + Network(final byte[] ip, final int bits) { + this.ip = ip; + this.bits = bits; + } + + boolean contains(final InetAddress addr) { + final byte[] a = addr instanceof Inet4Address ? v4toMapped(addr.getAddress()) : addr.getAddress(); + if (a.length != ip.length) { + return false; + } + final int fullBytes = bits / 8; + for (int i = 0; i < fullBytes; i++) { + if (a[i] != ip[i]) { + return false; + } + } + final int rem = bits % 8; + if (rem == 0) { + return true; + } + final int mask = 0xff << 8 - rem; + return (a[fullBytes] & mask) == (ip[fullBytes] & mask); + } + + private static byte[] v4toMapped(final byte[] v4) { + final byte[] mapped = new byte[16]; + mapped[10] = (byte) 0xff; + mapped[11] = (byte) 0xff; + System.arraycopy(v4, 0, mapped, 12, 4); + return mapped; + } + } + + private static Network toPrefix(final String text, final int bits) { + try { + return new Network(InetAddress.getByName(text).getAddress(), bits); + } catch (final UnknownHostException ex) { + throw new IllegalArgumentException(ex); + } + } + + private static final List POLICY_TABLE = + Collections.unmodifiableList(Arrays.asList( + new PolicyEntry(toPrefix("::1", 128), 50, 0), + new PolicyEntry(toPrefix("::ffff:0:0", 96), 35, 4), + new PolicyEntry(toPrefix("::", 96), 1, 3), + new PolicyEntry(toPrefix("2001::", 32), 5, 5), + new PolicyEntry(toPrefix("2002::", 16), 30, 2), + new PolicyEntry(toPrefix("3ffe::", 16), 1, 12), + new PolicyEntry(toPrefix("fec0::", 10), 1, 11), + new PolicyEntry(toPrefix("fc00::", 7), 3, 13), + new PolicyEntry(toPrefix("::", 0), 40, 1) + )); + + private static PolicyEntry classify(final InetAddress ip) { + for (final PolicyEntry e : POLICY_TABLE) { + if (e.prefix.contains(ip)) { + return e; + } + } + return new PolicyEntry(null, 40, 1); + } + + private static final Comparator RFC6724_COMPARATOR = (a, b) -> { + final InetAddress DA = a.dst; + final InetAddress DB = b.dst; + final InetAddress SourceDA = a.src; + final InetAddress SourceDB = b.src; + final Attr attrDA = a.dstAttr; + final Attr attrDB = b.dstAttr; + final Attr attrSourceDA = a.srcAttr; + final Attr attrSourceDB = b.srcAttr; + + final int preferDA = -1; + final int preferDB = 1; + + // Rule 1: Avoid unusable destinations. + final boolean validA = SourceDA != null && !SourceDA.isAnyLocalAddress(); + final boolean validB = SourceDB != null && !SourceDB.isAnyLocalAddress(); + if (!validA && !validB) { + return 0; + } + if (!validB) { + return preferDA; + } + if (!validA) { + return preferDB; + } + + // Rule 2: Prefer matching scope. + if (attrDA.scope == attrSourceDA.scope && attrDB.scope != attrSourceDB.scope) { + return preferDA; + } + if (attrDA.scope != attrSourceDA.scope && attrDB.scope == attrSourceDB.scope) { + return preferDB; + } + + // Rule 5: Prefer matching label. + if (attrSourceDA.label == attrDA.label && attrSourceDB.label != attrDB.label) { + return preferDA; + } + if (attrSourceDA.label != attrDA.label && attrSourceDB.label == attrDB.label) { + return preferDB; + } + + // Rule 6: Prefer higher precedence. + if (attrDA.precedence > attrDB.precedence) { + return preferDA; + } + if (attrDA.precedence < attrDB.precedence) { + return preferDB; + } + + // Rule 8: Prefer smaller scope. + if (attrDA.scope.value < attrDB.scope.value) { + return preferDA; + } + if (attrDA.scope.value > attrDB.scope.value) { + return preferDB; + } + + // Rule 9: Longest common prefix (IPv6 only). + if (DA instanceof Inet6Address && DB instanceof Inet6Address) { + final int commonA = commonPrefixLen(SourceDA, DA); + final int commonB = commonPrefixLen(SourceDB, DB); + if (commonA > commonB) { + return preferDA; + } + if (commonA < commonB) { + return preferDB; + } + } + + // Rule 10: Otherwise equal (original order preserved by stable sort). + return 0; + }; + + private static int commonPrefixLen(final InetAddress a, final InetAddress b) { + if (a == null || b == null || a.getClass() != b.getClass()) { + return 0; + } + final byte[] aa = a.getAddress(); + final byte[] bb = b.getAddress(); + final int len = Math.min(aa.length, bb.length); + int bits = 0; + for (int i = 0; i < len; i++) { + final int x = (aa[i] ^ bb[i]) & 0xFF; + if (x == 0) { + bits += 8; + } else { + for (int j = 7; j >= 0; j--) { + if ((x & 1 << j) != 0) { + return bits; + } + bits++; + } + return bits; + } + } + return bits; + } + + private static String addr(final InetAddress a) { + if (a == null) { + return "null"; + } + final String family = a instanceof Inet6Address ? "IPv6" : "IPv4"; + return family + "(" + a.getHostAddress() + ")"; + } + + private static List fmt(final InetAddress[] arr) { + final List out = new ArrayList<>(arr.length); + for (final InetAddress a : arr) { + out.add(addr(a)); + } + return out; + } + + private static List fmt(final List arr) { + final List out = new ArrayList<>(arr.size()); + for (final InetAddress a : arr) { + out.add(addr(a)); + } + return out; + } + + private static String simpleName() { + return "Rfc6724Resolver"; + } +} 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..705ad6f8fd --- /dev/null +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/config/ProtocolFamilyPreference.java @@ -0,0 +1,67 @@ +/* + * ==================================================================== + * 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 { + /** Keep families as returned (or RFC 6724 ordered). */ + DEFAULT, + /** + * Prefer IPv4 addresses but allow IPv6 as a fallback. + */ + PREFER_IPV4, + + /** + * Prefer IPv6 addresses but allow IPv4 as a fallback. + */ + PREFER_IPV6, + + /** + * Use only IPv4 addresses. + */ + IPV4_ONLY, + + /** + * Use only IPv6 addresses. + */ + IPV6_ONLY, + + /** + * Interleave address families (v6, then v4, then v6, …) when multiple + * addresses are available. When staggered connects are enabled, the first + * address of the other family is delayed by a small offset. + */ + INTERLEAVE +} + diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java new file mode 100644 index 0000000000..63f46833c9 --- /dev/null +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java @@ -0,0 +1,170 @@ +/* + * ==================================================================== + * 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.assertInstanceOf; +import static org.mockito.Mockito.when; + +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.hc.client5.http.config.ProtocolFamilyPreference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.Mockito; + +class Rfc6724AddressSelectingDnsResolverTest { + + private DnsResolver delegate; + + @BeforeEach + void setUp() { + delegate = Mockito.mock(DnsResolver.class); + } + + @Test + void ipv4Only_filtersOutIPv6() throws Exception { + final InetAddress v4 = InetAddress.getByName("203.0.113.10"); // TEST-NET-3 + final InetAddress v6 = InetAddress.getByName("2001:db8::10"); // documentation prefix + + when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v6, v4}); + + final Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY); + + final InetAddress[] ordered = r.resolve("dual.example"); + Assertions.assertNotNull(ordered); + assertEquals(1, ordered.length); + assertInstanceOf(Inet4Address.class, ordered[0]); + assertEquals(v4, ordered[0]); + } + + @Test + void ipv6Only_filtersOutIPv4() throws Exception { + final InetAddress v4 = InetAddress.getByName("192.0.2.1"); // TEST-NET-1 + final InetAddress v6 = InetAddress.getByName("2001:db8::1"); + + when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v4, v6}); + + final Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV6_ONLY); + + final InetAddress[] ordered = r.resolve("dual.example"); + Assertions.assertNotNull(ordered); + assertEquals(1, ordered.length); + assertInstanceOf(Inet6Address.class, ordered[0]); + assertEquals(v6, ordered[0]); + } + + @Test + void ipv4Only_emptyWhenNoIPv4Candidates() throws Exception { + final InetAddress v6a = InetAddress.getByName("2001:db8::1"); + final InetAddress v6b = InetAddress.getByName("2001:db8::2"); + + when(delegate.resolve("v6only.example")).thenReturn(new InetAddress[]{v6a, v6b}); + + final Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY); + + final InetAddress[] ordered = r.resolve("v6only.example"); + Assertions.assertNotNull(ordered); + assertEquals(0, ordered.length); + } + + @Test + void interleave_isDefault_and_hasNoFamilyBias() throws Exception { + final InetAddress v6a = InetAddress.getByName("2001:db8::1"); + final InetAddress v6b = InetAddress.getByName("2001:db8::2"); + final InetAddress v4a = InetAddress.getByName("192.0.2.1"); + final InetAddress v4b = InetAddress.getByName("203.0.113.10"); + + when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v6a, v6b, v4a, v4b}); + + final Rfc6724AddressSelectingDnsResolver rDefault = new Rfc6724AddressSelectingDnsResolver(delegate); + final Rfc6724AddressSelectingDnsResolver rInterleave = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); + + final InetAddress[] outDefault = rDefault.resolve("dual.example"); + final InetAddress[] outInterleave = rInterleave.resolve("dual.example"); + + assertArrayEquals(outDefault, outInterleave); + Assertions.assertNotNull(outInterleave); + assertEquals(4, outInterleave.length); + } + + @Test + void preferIpv6_groupsAllV6First_preservingRelativeOrder() throws Exception { + final InetAddress v4a = InetAddress.getByName("192.0.2.1"); + final InetAddress v6a = InetAddress.getByName("2001:db8::1"); + final InetAddress v4b = InetAddress.getByName("203.0.113.10"); + final InetAddress v6b = InetAddress.getByName("2001:db8::2"); + + when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v4a, v6a, v4b, v6b}); + + final Rfc6724AddressSelectingDnsResolver baseline = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); + final InetAddress[] baseOut = baseline.resolve("dual.example"); + + final Rfc6724AddressSelectingDnsResolver preferV6 = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV6); + final InetAddress[] out = preferV6.resolve("dual.example"); + + // Expected: stable partition of the RFC-sorted baseline. + final List baseV6 = new ArrayList<>(); + final List baseV4 = new ArrayList<>(); + for (final InetAddress a : baseOut) { + if (a instanceof Inet6Address) { + baseV6.add(a); + } else { + baseV4.add(a); + } + } + final List expected = new ArrayList<>(baseOut.length); + expected.addAll(baseV6); + expected.addAll(baseV4); + + assertEquals(expected, Arrays.asList(out)); + assertInstanceOf(Inet6Address.class, out[0]); + } + + @Test + void canonicalHostname_delegates() throws Exception { + when(delegate.resolveCanonicalHostname("example.org")).thenReturn("canon.example.org"); + final Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); + assertEquals("canon.example.org", r.resolveCanonicalHostname("example.org")); + Mockito.verify(delegate).resolveCanonicalHostname("example.org"); + } + +} From f7aaa5ee06f76f29e865b9e2f8b8d2d572229a6c Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Tue, 13 Jan 2026 12:01:53 +0100 Subject: [PATCH 08/15] Implement true INTERLEAVE ordering. Add manual gated IT to dump DEFAULT vs INTERLEAVE results. Expand unit coverage for scope mapping and core RFC comparison rules. --- .../testing/ManualRfc6724ResolverIT.java | 87 +++++ .../Rfc6724AddressSelectingDnsResolver.java | 365 +++++++++++------- .../http/config/ProtocolFamilyPreference.java | 19 +- ...fc6724AddressSelectingDnsResolverTest.java | 345 +++++++++++++---- .../http/examples/Rfc6724ResolverExample.java | 67 ++++ 5 files changed, 666 insertions(+), 217 deletions(-) create mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java create mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java new file mode 100644 index 0000000000..7503e8c12e --- /dev/null +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java @@ -0,0 +1,87 @@ +/* + * ==================================================================== + * 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.testing; + +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.net.Inet6Address; +import java.net.InetAddress; + +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.Rfc6724AddressSelectingDnsResolver; +import org.apache.hc.client5.http.SystemDefaultDnsResolver; +import org.apache.hc.client5.http.config.ProtocolFamilyPreference; +import org.junit.jupiter.api.Test; + +class ManualRfc6724ResolverIT { + + private static final String PROP_ENABLE = "httpclient.rfc6724.it"; + private static final String PROP_HOST = "httpclient.rfc6724.host"; + + @Test + void resolve_and_dump_order() throws Exception { + assumeTrue(Boolean.getBoolean(PROP_ENABLE), + "Enable with -Dhttpclient.rfc6724.it=true"); + + final String host = System.getProperty(PROP_HOST, "localhost"); + + final DnsResolver base = SystemDefaultDnsResolver.INSTANCE; + + System.out.println("Host: " + host); + + dump(base, host, ProtocolFamilyPreference.DEFAULT); + System.out.println(); + dump(base, host, ProtocolFamilyPreference.INTERLEAVE); + } + + private static void dump( + final DnsResolver base, + final String host, + final ProtocolFamilyPreference pref) throws Exception { + + final Rfc6724AddressSelectingDnsResolver resolver = + new Rfc6724AddressSelectingDnsResolver(base, pref); + + final InetAddress[] out = resolver.resolve(host); + + int v4 = 0; + int v6 = 0; + + System.out.println("Preference: " + pref); + for (final InetAddress a : out) { + if (a instanceof Inet6Address) { + v6++; + System.out.println(" IPv6 " + a.getHostAddress()); + } else { + v4++; + System.out.println(" IPv4 " + a.getHostAddress()); + } + } + System.out.println("Counts: IPv4=" + v4 + " IPv6=" + v6); + } +} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java b/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java index 357b0dcf60..48f0e061f7 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java @@ -39,6 +39,8 @@ import java.util.Collections; import java.util.Comparator; import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; import org.apache.hc.client5.http.config.ProtocolFamilyPreference; import org.apache.hc.core5.annotation.Contract; @@ -48,18 +50,18 @@ /** * {@code Rfc6724AddressSelectingDnsResolver} wraps a delegate {@link DnsResolver} - * and applies RFC 6724 destination address selection rules to the returned - * addresses. It can also enforce or bias a protocol family preference. + * and applies RFC 6724 destination address selection rules (RFC 6724 §6) + * to the returned addresses. It can also enforce or bias a protocol family preference. * *

The canonical hostname lookup is delegated unchanged.

* *

- * {@link ProtocolFamilyPreference#INTERLEAVE} is treated as "no family bias": - * the resolver keeps the RFC 6724 sorted order intact. Family interleaving, if - * desired, should be handled at dial time (e.g. Happy Eyeballs). + * {@link ProtocolFamilyPreference#DEFAULT} keeps the RFC 6724 sorted order intact (no family bias). + * {@link ProtocolFamilyPreference#INTERLEAVE} interleaves IPv6 and IPv4 addresses (v6, v4, v6, …), + * preserving the relative order within each family as produced by RFC 6724 sorting. *

* - * @since 5.6 + * @since 5.7 */ @Contract(threading = ThreadingBehavior.IMMUTABLE) public final class Rfc6724AddressSelectingDnsResolver implements DnsResolver { @@ -68,16 +70,29 @@ public final class Rfc6724AddressSelectingDnsResolver implements DnsResolver { private static final int PROBE_PORT = 53; // UDP connect trick; no packets sent + @FunctionalInterface + interface SourceAddressResolver { + InetAddress resolveSource(final InetSocketAddress destination) throws SocketException; + } + + private static final SourceAddressResolver DEFAULT_SOURCE_ADDRESS_RESOLVER = destination -> { + try (final DatagramSocket socket = new DatagramSocket()) { + socket.connect(destination); + return socket.getLocalAddress(); + } + }; + private final DnsResolver delegate; private final ProtocolFamilyPreference familyPreference; + private final SourceAddressResolver sourceAddressResolver; /** - * Creates a new resolver that applies RFC 6724 ordering with no family bias (INTERLEAVE). + * Creates a new resolver that applies RFC 6724 ordering with no family bias (DEFAULT). * * @param delegate underlying resolver to use. */ public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { - this(delegate, ProtocolFamilyPreference.INTERLEAVE); + this(delegate, ProtocolFamilyPreference.DEFAULT); } /** @@ -89,78 +104,57 @@ public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { public Rfc6724AddressSelectingDnsResolver( final DnsResolver delegate, final ProtocolFamilyPreference familyPreference) { - this.delegate = java.util.Objects.requireNonNull(delegate, "delegate"); - this.familyPreference = familyPreference != null ? familyPreference : ProtocolFamilyPreference.INTERLEAVE; + this(delegate, familyPreference, DEFAULT_SOURCE_ADDRESS_RESOLVER); + } + + // Package-private for unit tests: allows deterministic source address inference. + Rfc6724AddressSelectingDnsResolver( + final DnsResolver delegate, + final ProtocolFamilyPreference familyPreference, + final SourceAddressResolver sourceAddressResolver) { + this.delegate = Objects.requireNonNull(delegate, "delegate"); + this.familyPreference = familyPreference != null ? familyPreference : ProtocolFamilyPreference.DEFAULT; + this.sourceAddressResolver = sourceAddressResolver != null ? sourceAddressResolver : DEFAULT_SOURCE_ADDRESS_RESOLVER; } @Override public InetAddress[] resolve(final String host) throws UnknownHostException { - if (LOG.isDebugEnabled()) { - LOG.debug("{} resolving host '{}' via delegate {}", simpleName(), host, delegate.getClass().getName()); - LOG.debug("{} familyPreference={}", simpleName(), familyPreference); - } - final InetAddress[] resolved = delegate.resolve(host); + if (resolved == null) { if (LOG.isDebugEnabled()) { - LOG.debug("{} delegate returned null for '{}'", simpleName(), host); + LOG.debug("{} resolved '{}' -> null", simpleName(), host); } return null; } - if (LOG.isDebugEnabled()) { - LOG.debug("{} delegate returned {} addresses for '{}': {}", simpleName(), resolved.length, host, fmt(resolved)); - } + if (resolved.length <= 1) { if (LOG.isDebugEnabled()) { - LOG.debug("{} nothing to sort/filter (<=1 address). Returning as-is.", simpleName()); + LOG.debug("{} resolved '{}' -> {}", simpleName(), host, fmt(resolved)); } return resolved; } - // 1) Filter by family if forced - final List candidates = new ArrayList<>(resolved.length); - switch (familyPreference) { - case IPV4_ONLY: { - for (final InetAddress a : resolved) { - if (a instanceof Inet4Address) { - candidates.add(a); - } - } - break; - } - case IPV6_ONLY: { - for (final InetAddress a : resolved) { - if (a instanceof Inet6Address) { - candidates.add(a); - } - } - break; - } - default: { - candidates.addAll(Arrays.asList(resolved)); - break; - } + if (LOG.isTraceEnabled()) { + LOG.trace("{} resolving host '{}' via delegate {}", simpleName(), host, delegate.getClass().getName()); + LOG.trace("{} familyPreference={}", simpleName(), familyPreference); + LOG.trace("{} delegate returned {} addresses for '{}': {}", simpleName(), resolved.length, host, fmt(resolved)); } - if (LOG.isDebugEnabled()) { - LOG.debug("{} after family filter {} -> {} candidate(s): {}", simpleName(), familyPreference, candidates.size(), fmt(candidates)); - } + final List candidates = filterCandidates(resolved, familyPreference); if (candidates.isEmpty()) { if (LOG.isDebugEnabled()) { - LOG.debug("{} no address of requested family; returning empty for '{}'", simpleName(), host); + LOG.debug("{} resolved '{}' -> []", simpleName(), host); } return new InetAddress[0]; } - // 2) RFC 6724 sort (uses UDP connect to infer source addresses; no packets sent) final List rfcSorted = sortByRfc6724(candidates); - - // 3) Apply preference bias final List ordered = applyFamilyPreference(rfcSorted, familyPreference); if (LOG.isDebugEnabled()) { - LOG.debug("{} final ordered list for '{}': {}", simpleName(), host, fmt(ordered)); + LOG.debug("{} resolved '{}' -> {}", simpleName(), host, fmt(ordered)); } return ordered.toArray(new InetAddress[0]); @@ -168,27 +162,74 @@ public InetAddress[] resolve(final String host) throws UnknownHostException { @Override public String resolveCanonicalHostname(final String host) throws UnknownHostException { - if (LOG.isDebugEnabled()) { - LOG.debug("{} resolveCanonicalHostname('{}') via delegate {}", simpleName(), host, delegate.getClass().getName()); + if (LOG.isTraceEnabled()) { + LOG.trace("{} resolveCanonicalHostname('{}') via delegate {}", simpleName(), host, delegate.getClass().getName()); } return delegate.resolveCanonicalHostname(host); } + private static boolean isUsableDestination(final InetAddress ip) { + if (ip == null) { + return false; + } + if (ip.isAnyLocalAddress()) { + return false; + } + // HTTP/TCP is for unicast destinations; multicast is not a valid connect target. + if (ip.isMulticastAddress()) { + return false; + } + return true; + } + + private static List filterCandidates( + final InetAddress[] resolved, + final ProtocolFamilyPreference pref) { + + final List out = new ArrayList<>(resolved.length); + for (final InetAddress a : resolved) { + if (!isUsableDestination(a)) { + continue; + } + switch (pref) { + case IPV4_ONLY: { + if (a instanceof Inet4Address) { + out.add(a); + } + break; + } + case IPV6_ONLY: { + if (a instanceof Inet6Address) { + out.add(a); + } + break; + } + default: { + out.add(a); + break; + } + } + } + return out; + } + // --- RFC 6724 helpers --- - private static List sortByRfc6724(final List addrs) { + private List sortByRfc6724(final List addrs) { if (addrs.size() < 2) { return addrs; } - if (LOG.isDebugEnabled()) { - LOG.debug("RFC6724 input candidates: {}", fmt(addrs)); + + if (LOG.isTraceEnabled()) { + LOG.trace("RFC6724 input candidates: {}", fmt(addrs)); } - final List sockAddrs = new ArrayList<>(addrs.size()); + final List socketAddresses = new ArrayList<>(addrs.size()); for (final InetAddress a : addrs) { - sockAddrs.add(new InetSocketAddress(a, PROBE_PORT)); + socketAddresses.add(new InetSocketAddress(a, PROBE_PORT)); } - final List srcs = srcAddrs(sockAddrs); + + final List srcs = inferSourceAddresses(socketAddresses); final List infos = new ArrayList<>(addrs.size()); for (int i = 0; i < addrs.size(); i++) { @@ -197,9 +238,9 @@ private static List sortByRfc6724(final List addrs) { infos.add(new Info(dst, src, ipAttrOf(dst), ipAttrOf(src))); } - if (LOG.isDebugEnabled()) { + if (LOG.isTraceEnabled()) { for (final Info info : infos) { - LOG.debug("RFC6724 candidate dst={} src={} dst[scope={},prec={},label={}] src[scope={},prec={},label={}]", + LOG.trace("RFC6724 candidate dst={} src={} dst[scope={},prec={},label={}] src[scope={},prec={},label={}]", addr(info.dst), addr(info.src), info.dstAttr.scope, info.dstAttr.precedence, info.dstAttr.label, info.srcAttr.scope, info.srcAttr.precedence, info.srcAttr.label); @@ -213,12 +254,39 @@ private static List sortByRfc6724(final List addrs) { out.add(info.dst); } - if (LOG.isDebugEnabled()) { - LOG.debug("RFC6724 output order: {}", fmt(out)); + if (LOG.isTraceEnabled()) { + LOG.trace("RFC6724 output order: {}", fmt(out)); } + return out; } + private List inferSourceAddresses(final List destinations) { + final List srcs = new ArrayList<>(destinations.size()); + + for (final InetSocketAddress dest : destinations) { + InetAddress src = null; + try { + src = sourceAddressResolver.resolveSource(dest); + } catch (final SocketException ignore) { + if (LOG.isTraceEnabled()) { + LOG.trace("RFC6724 could not infer source address for {}: {}", dest, ignore.toString()); + } + } + srcs.add(src); + } + + if (LOG.isTraceEnabled()) { + final List printable = new ArrayList<>(srcs.size()); + for (final InetAddress a : srcs) { + printable.add(addr(a)); + } + LOG.trace("RFC6724 inferred source addresses: {}", printable); + } + + return srcs; + } + private static List applyFamilyPreference( final List rfcSorted, final ProtocolFamilyPreference pref) { @@ -231,66 +299,69 @@ private static List applyFamilyPreference( case PREFER_IPV6: case PREFER_IPV4: { final boolean preferV6 = pref == ProtocolFamilyPreference.PREFER_IPV6; - final List first = new ArrayList<>(); - final List second = new ArrayList<>(); - for (final InetAddress a : rfcSorted) { - final boolean isV6 = a instanceof Inet6Address; - if (preferV6 && isV6 || !preferV6 && !isV6) { - first.add(a); - } else { - second.add(a); - } + + // Stable: preserves the RFC6724 order within each family. + final List out = rfcSorted.stream() + .sorted(Comparator.comparingInt(a -> ((a instanceof Inet6Address) == preferV6) ? 0 : 1)) + .collect(Collectors.toList()); + + if (LOG.isTraceEnabled()) { + LOG.trace("Family preference {} applied. Output: {}", pref, fmt(out)); } - final List merged = new ArrayList<>(rfcSorted.size()); - merged.addAll(first); - merged.addAll(second); - if (LOG.isDebugEnabled()) { - LOG.debug("Family preference {} applied. First bucket={}, second bucket={}", pref, fmt(first), fmt(second)); - LOG.debug("Family preference output: {}", fmt(merged)); + return out; + } + case INTERLEAVE: { + final List out = interleaveFamilies(rfcSorted); + if (LOG.isTraceEnabled()) { + LOG.trace("Family preference {} applied. Output: {}", pref, fmt(out)); } - return merged; + return out; } case IPV4_ONLY: case IPV6_ONLY: { // already filtered earlier - if (LOG.isDebugEnabled()) { - LOG.debug("Family preference {} enforced earlier. Order unchanged: {}", pref, fmt(rfcSorted)); - } return rfcSorted; } - case INTERLEAVE: + case DEFAULT: default: { // No family bias. Keep RFC 6724 order intact. - if (LOG.isDebugEnabled()) { - LOG.debug("INTERLEAVE treated as no-bias. Order unchanged: {}", fmt(rfcSorted)); - } return rfcSorted; } } } - private static List srcAddrs(final List addrs) { - final List srcs = new ArrayList<>(addrs.size()); - for (final InetSocketAddress dest : addrs) { - InetAddress src = null; - try (final DatagramSocket s = new DatagramSocket()) { - s.connect(dest); // does not send packets; OS picks source addr/if - src = s.getLocalAddress(); - } catch (final SocketException ignore) { - if (LOG.isDebugEnabled()) { - LOG.debug("RFC6724 could not infer source address for {}: {}", dest, ignore.toString()); - } + private static List interleaveFamilies(final List rfcSorted) { + final List v6 = new ArrayList<>(); + final List v4 = new ArrayList<>(); + + for (final InetAddress a : rfcSorted) { + if (a instanceof Inet6Address) { + v6.add(a); + } else { + v4.add(a); } - srcs.add(src); } - if (LOG.isDebugEnabled()) { - final List printable = new ArrayList<>(srcs.size()); - for (final InetAddress a : srcs) { - printable.add(addr(a)); + + if (v6.isEmpty() || v4.isEmpty()) { + return rfcSorted; + } + + final boolean startWithV6 = rfcSorted.get(0) instanceof Inet6Address; + final List first = startWithV6 ? v6 : v4; + final List second = startWithV6 ? v4 : v6; + + final List out = new ArrayList<>(rfcSorted.size()); + int i = 0; + int j = 0; + while (i < first.size() || j < second.size()) { + if (i < first.size()) { + out.add(first.get(i++)); + } + if (j < second.size()) { + out.add(second.get(j++)); } - LOG.debug("RFC6724 inferred source addresses: {}", printable); } - return srcs; + return out; } // --- RFC 6724 score structs --- @@ -376,7 +447,7 @@ private static Scope classifyScope(final InetAddress ip) { } if (ip.isMulticastAddress()) { if (ip instanceof Inet6Address) { - // RFC 4291: low 4 bits of second byte are scope. + // RFC 6724 §3.1 and RFC 4291: low 4 bits of second byte are scope for IPv6 multicast. return Scope.fromValue(ip.getAddress()[1] & 0x0f); } return Scope.GLOBAL; @@ -423,8 +494,10 @@ boolean contains(final InetAddress addr) { if (rem == 0) { return true; } - final int mask = 0xff << 8 - rem; - return (a[fullBytes] & mask) == (ip[fullBytes] & mask); + final int mask = 0xff << (8 - rem); + final int aByte = a[fullBytes] & 0xff; + final int ipByte = ip[fullBytes] & 0xff; + return (aByte & mask) == (ipByte & mask); } private static byte[] v4toMapped(final byte[] v4) { @@ -467,72 +540,74 @@ private static PolicyEntry classify(final InetAddress ip) { } private static final Comparator RFC6724_COMPARATOR = (a, b) -> { - final InetAddress DA = a.dst; - final InetAddress DB = b.dst; - final InetAddress SourceDA = a.src; - final InetAddress SourceDB = b.src; - final Attr attrDA = a.dstAttr; - final Attr attrDB = b.dstAttr; - final Attr attrSourceDA = a.srcAttr; - final Attr attrSourceDB = b.srcAttr; - - final int preferDA = -1; - final int preferDB = 1; + final InetAddress aDst = a.dst; + final InetAddress bDst = b.dst; + final InetAddress aSrc = a.src; + final InetAddress bSrc = b.src; + final Attr aDstAttr = a.dstAttr; + final Attr bDstAttr = b.dstAttr; + final Attr aSrcAttr = a.srcAttr; + final Attr bSrcAttr = b.srcAttr; + + final int preferA = -1; + final int preferB = 1; + + // RFC 6724 §6: destination address selection rules. // Rule 1: Avoid unusable destinations. - final boolean validA = SourceDA != null && !SourceDA.isAnyLocalAddress(); - final boolean validB = SourceDB != null && !SourceDB.isAnyLocalAddress(); + final boolean validA = aSrc != null && !aSrc.isAnyLocalAddress(); + final boolean validB = bSrc != null && !bSrc.isAnyLocalAddress(); if (!validA && !validB) { return 0; } if (!validB) { - return preferDA; + return preferA; } if (!validA) { - return preferDB; + return preferB; } // Rule 2: Prefer matching scope. - if (attrDA.scope == attrSourceDA.scope && attrDB.scope != attrSourceDB.scope) { - return preferDA; + if (aDstAttr.scope == aSrcAttr.scope && bDstAttr.scope != bSrcAttr.scope) { + return preferA; } - if (attrDA.scope != attrSourceDA.scope && attrDB.scope == attrSourceDB.scope) { - return preferDB; + if (aDstAttr.scope != aSrcAttr.scope && bDstAttr.scope == bSrcAttr.scope) { + return preferB; } // Rule 5: Prefer matching label. - if (attrSourceDA.label == attrDA.label && attrSourceDB.label != attrDB.label) { - return preferDA; + if (aSrcAttr.label == aDstAttr.label && bSrcAttr.label != bDstAttr.label) { + return preferA; } - if (attrSourceDA.label != attrDA.label && attrSourceDB.label == attrDB.label) { - return preferDB; + if (aSrcAttr.label != aDstAttr.label && bSrcAttr.label == bDstAttr.label) { + return preferB; } // Rule 6: Prefer higher precedence. - if (attrDA.precedence > attrDB.precedence) { - return preferDA; + if (aDstAttr.precedence > bDstAttr.precedence) { + return preferA; } - if (attrDA.precedence < attrDB.precedence) { - return preferDB; + if (aDstAttr.precedence < bDstAttr.precedence) { + return preferB; } // Rule 8: Prefer smaller scope. - if (attrDA.scope.value < attrDB.scope.value) { - return preferDA; + if (aDstAttr.scope.value < bDstAttr.scope.value) { + return preferA; } - if (attrDA.scope.value > attrDB.scope.value) { - return preferDB; + if (aDstAttr.scope.value > bDstAttr.scope.value) { + return preferB; } - // Rule 9: Longest common prefix (IPv6 only). - if (DA instanceof Inet6Address && DB instanceof Inet6Address) { - final int commonA = commonPrefixLen(SourceDA, DA); - final int commonB = commonPrefixLen(SourceDB, DB); + // Rule 9: Longest matching prefix (IPv6 only). + if (aDst instanceof Inet6Address && bDst instanceof Inet6Address) { + final int commonA = commonPrefixLen(aSrc, aDst); + final int commonB = commonPrefixLen(bSrc, bDst); if (commonA > commonB) { - return preferDA; + return preferA; } if (commonA < commonB) { - return preferDB; + return preferB; } } @@ -554,7 +629,7 @@ private static int commonPrefixLen(final InetAddress a, final InetAddress b) { bits += 8; } else { for (int j = 7; j >= 0; j--) { - if ((x & 1 << j) != 0) { + if ((x & (1 << j)) != 0) { return bits; } bits++; 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 index 705ad6f8fd..7ad272e3f6 100644 --- 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 @@ -35,33 +35,38 @@ * @since 5.7 */ public enum ProtocolFamilyPreference { - /** Keep families as returned (or RFC 6724 ordered). */ + + /** + * No family bias. Preserve RFC 6724 order. + */ DEFAULT, + /** - * Prefer IPv4 addresses but allow IPv6 as a fallback. + * Prefer IPv4 addresses (stable: preserves RFC order within each family). */ PREFER_IPV4, /** - * Prefer IPv6 addresses but allow IPv4 as a fallback. + * Prefer IPv6 addresses (stable: preserves RFC order within each family). */ PREFER_IPV6, /** - * Use only IPv4 addresses. + * Filter out all non-IPv4 addresses. */ IPV4_ONLY, /** - * Use only IPv6 addresses. + * Filter out all non-IPv6 addresses. */ IPV6_ONLY, /** * Interleave address families (v6, then v4, then v6, …) when multiple - * addresses are available. When staggered connects are enabled, the first - * address of the other family is delayed by a small offset. + * addresses are available, preserving the relative order within each family + * as produced by RFC 6724 sorting. */ INTERLEAVE + } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java index 63f46833c9..3690a99aeb 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java @@ -24,47 +24,51 @@ * . * */ + 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.assertInstanceOf; -import static org.mockito.Mockito.when; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.lang.reflect.Method; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; -import java.util.ArrayList; +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.junit.jupiter.api.Assertions; +import org.apache.hc.client5.http.impl.InMemoryDnsResolver; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import org.mockito.Mockito; class Rfc6724AddressSelectingDnsResolverTest { - private DnsResolver delegate; + private static final Rfc6724AddressSelectingDnsResolver.SourceAddressResolver NO_SOURCE_ADDR = + (final InetSocketAddress dest) -> null; + + private InMemoryDnsResolver delegate; @BeforeEach void setUp() { - delegate = Mockito.mock(DnsResolver.class); + delegate = new InMemoryDnsResolver(); } @Test void ipv4Only_filtersOutIPv6() throws Exception { - final InetAddress v4 = InetAddress.getByName("203.0.113.10"); // TEST-NET-3 - final InetAddress v6 = InetAddress.getByName("2001:db8::10"); // documentation prefix + final InetAddress v4 = inet("203.0.113.10"); // TEST-NET-3 + final InetAddress v6 = inet("2001:db8::10"); // documentation prefix - when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v6, v4}); + delegate.add("dual.example", v6, v4); final Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY); + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR); final InetAddress[] ordered = r.resolve("dual.example"); - Assertions.assertNotNull(ordered); assertEquals(1, ordered.length); assertInstanceOf(Inet4Address.class, ordered[0]); assertEquals(v4, ordered[0]); @@ -72,16 +76,15 @@ void ipv4Only_filtersOutIPv6() throws Exception { @Test void ipv6Only_filtersOutIPv4() throws Exception { - final InetAddress v4 = InetAddress.getByName("192.0.2.1"); // TEST-NET-1 - final InetAddress v6 = InetAddress.getByName("2001:db8::1"); + final InetAddress v4 = inet("192.0.2.1"); // TEST-NET-1 + final InetAddress v6 = inet("2001:db8::1"); - when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v4, v6}); + delegate.add("dual.example", v4, v6); final Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV6_ONLY); + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV6_ONLY, NO_SOURCE_ADDR); final InetAddress[] ordered = r.resolve("dual.example"); - Assertions.assertNotNull(ordered); assertEquals(1, ordered.length); assertInstanceOf(Inet6Address.class, ordered[0]); assertEquals(v6, ordered[0]); @@ -89,82 +92,294 @@ void ipv6Only_filtersOutIPv4() throws Exception { @Test void ipv4Only_emptyWhenNoIPv4Candidates() throws Exception { - final InetAddress v6a = InetAddress.getByName("2001:db8::1"); - final InetAddress v6b = InetAddress.getByName("2001:db8::2"); + final InetAddress v6a = inet("2001:db8::1"); + final InetAddress v6b = inet("2001:db8::2"); - when(delegate.resolve("v6only.example")).thenReturn(new InetAddress[]{v6a, v6b}); + delegate.add("v6only.example", v6a, v6b); final Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY); + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR); final InetAddress[] ordered = r.resolve("v6only.example"); - Assertions.assertNotNull(ordered); assertEquals(0, ordered.length); } @Test - void interleave_isDefault_and_hasNoFamilyBias() throws Exception { - final InetAddress v6a = InetAddress.getByName("2001:db8::1"); - final InetAddress v6b = InetAddress.getByName("2001:db8::2"); - final InetAddress v4a = InetAddress.getByName("192.0.2.1"); - final InetAddress v4b = InetAddress.getByName("203.0.113.10"); + 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"); - when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v6a, v6b, v4a, v4b}); + delegate.add("dual.example", v6a, v6b, v4a, v4b); - final Rfc6724AddressSelectingDnsResolver rDefault = new Rfc6724AddressSelectingDnsResolver(delegate); - final Rfc6724AddressSelectingDnsResolver rInterleave = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); + final Rfc6724AddressSelectingDnsResolver r1 = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR); + final Rfc6724AddressSelectingDnsResolver r2 = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR); - final InetAddress[] outDefault = rDefault.resolve("dual.example"); - final InetAddress[] outInterleave = rInterleave.resolve("dual.example"); + final InetAddress[] out1 = r1.resolve("dual.example"); + final InetAddress[] out2 = r2.resolve("dual.example"); - assertArrayEquals(outDefault, outInterleave); - Assertions.assertNotNull(outInterleave); - assertEquals(4, outInterleave.length); + assertArrayEquals(out1, out2); + assertEquals(4, out1.length); } @Test - void preferIpv6_groupsAllV6First_preservingRelativeOrder() throws Exception { - final InetAddress v4a = InetAddress.getByName("192.0.2.1"); - final InetAddress v6a = InetAddress.getByName("2001:db8::1"); - final InetAddress v4b = InetAddress.getByName("203.0.113.10"); - final InetAddress v6b = InetAddress.getByName("2001:db8::2"); + 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 Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE, NO_SOURCE_ADDR); + + final InetAddress[] out = r.resolve("dual.example"); + assertEquals(Arrays.asList(v6a, v4a, v6b, v4b), Arrays.asList(out)); + } - when(delegate.resolve("dual.example")).thenReturn(new InetAddress[]{v4a, v6a, v4b, v6b}); + @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"); - final Rfc6724AddressSelectingDnsResolver baseline = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); - final InetAddress[] baseOut = baseline.resolve("dual.example"); + delegate.add("dual.example", v4a, v6a, v4b, v6b); final Rfc6724AddressSelectingDnsResolver preferV6 = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.PREFER_IPV6); + new Rfc6724AddressSelectingDnsResolver(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]); + } - // Expected: stable partition of the RFC-sorted baseline. - final List baseV6 = new ArrayList<>(); - final List baseV4 = new ArrayList<>(); - for (final InetAddress a : baseOut) { - if (a instanceof Inet6Address) { - baseV6.add(a); - } else { - baseV4.add(a); - } - } - final List expected = new ArrayList<>(baseOut.length); - expected.addAll(baseV6); - expected.addAll(baseV4); + @Test + void filtersOutMulticastDestinations() throws Exception { + final InetAddress multicastV6 = inet("ff02::1"); + final InetAddress v6 = inet("2001:db8::1"); - assertEquals(expected, Arrays.asList(out)); - assertInstanceOf(Inet6Address.class, out[0]); + delegate.add("mcast.example", multicastV6, v6); + + final Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR); + + final InetAddress[] out = r.resolve("mcast.example"); + assertEquals(1, out.length); + assertEquals(v6, out[0]); + } + + // ------------------------------------------------------------------------- + // New: direct tests for classifyScope(..) and Scope.fromValue(..) via reflection + // (Scope and classifyScope are private in the resolver). + // ------------------------------------------------------------------------- + + @Test + void classifyScope_loopback_linkLocal_siteLocal_global() throws Exception { + final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; + + assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("127.0.0.1"))); + assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("::1"))); + + assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("169.254.0.1"))); + assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("fe80::1"))); + + assertEquals("SITE_LOCAL", classifyScope(resolverClass, inet("10.0.0.1"))); + + assertEquals("GLOBAL", classifyScope(resolverClass, inet("8.8.8.8"))); + assertEquals("GLOBAL", classifyScope(resolverClass, inet("2003::1"))); + } + + @Test + void classifyScope_ipv6Multicast_usesLowNibbleScope() throws Exception { + final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; + + // ff01::1 -> scope 0x1 -> INTERFACE_LOCAL + assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("ff01::1"))); + // ff02::1 -> scope 0x2 -> LINK_LOCAL + assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("ff02::1"))); + // ff04::1 -> scope 0x4 -> ADMIN_LOCAL + assertEquals("ADMIN_LOCAL", classifyScope(resolverClass, inet("ff04::1"))); + // ff05::1 -> scope 0x5 -> SITE_LOCAL + assertEquals("SITE_LOCAL", classifyScope(resolverClass, inet("ff05::1"))); + // ff08::1 -> scope 0x8 -> ORG_LOCAL + assertEquals("ORG_LOCAL", classifyScope(resolverClass, inet("ff08::1"))); + // ff0e::1 -> scope 0xe -> GLOBAL (default branch) + assertEquals("GLOBAL", classifyScope(resolverClass, inet("ff0e::1"))); + } + + @Test + void scopeFromValue_mapsKnownConstants_andDefaultsToGlobal() throws Exception { + final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; + final Class scopeClass = findDeclaredClass(resolverClass, "Scope"); + assertNotNull(scopeClass); + + assertEquals("INTERFACE_LOCAL", scopeFromValue(scopeClass, 0x1)); + assertEquals("LINK_LOCAL", scopeFromValue(scopeClass, 0x2)); + assertEquals("ADMIN_LOCAL", scopeFromValue(scopeClass, 0x4)); + assertEquals("SITE_LOCAL", scopeFromValue(scopeClass, 0x5)); + assertEquals("ORG_LOCAL", scopeFromValue(scopeClass, 0x8)); + + assertEquals("GLOBAL", scopeFromValue(scopeClass, 0x0)); + assertEquals("GLOBAL", scopeFromValue(scopeClass, 0xe)); + assertEquals("GLOBAL", scopeFromValue(scopeClass, 0xf)); } @Test - void canonicalHostname_delegates() throws Exception { - when(delegate.resolveCanonicalHostname("example.org")).thenReturn("canon.example.org"); + 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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.INTERLEAVE); - assertEquals("canon.example.org", r.resolveCanonicalHostname("example.org")); - Mockito.verify(delegate).resolveCanonicalHostname("example.org"); + new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = + new Rfc6724AddressSelectingDnsResolver(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 addr_fmt_simpleName() throws Exception { + final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; + + final Method addr = resolverClass.getDeclaredMethod("addr", InetAddress.class); + addr.setAccessible(true); + + final Method fmtArr = resolverClass.getDeclaredMethod("fmt", InetAddress[].class); + fmtArr.setAccessible(true); + + final Method fmtList = resolverClass.getDeclaredMethod("fmt", List.class); + fmtList.setAccessible(true); + + final Method simpleName = resolverClass.getDeclaredMethod("simpleName"); + simpleName.setAccessible(true); + + assertEquals("null", (String) addr.invoke(null, new Object[]{null})); + + final InetAddress v4 = inet("192.0.2.1"); + final InetAddress v6 = inet("2001:db8::1"); + + final String s4 = (String) addr.invoke(null, v4); + final String s6 = (String) addr.invoke(null, v6); + + assertEquals("IPv4(" + v4.getHostAddress() + ")", s4); + assertEquals("IPv6(" + v6.getHostAddress() + ")", s6); + + @SuppressWarnings("unchecked") final List arrOut = (List) fmtArr.invoke(null, new Object[]{new InetAddress[]{v6, v4}}); + assertEquals(Arrays.asList("IPv6(" + v6.getHostAddress() + ")", "IPv4(" + v4.getHostAddress() + ")"), arrOut); + + @SuppressWarnings("unchecked") final List listOut = (List) fmtList.invoke(null, Arrays.asList(v4, v6)); + assertEquals(Arrays.asList("IPv4(" + v4.getHostAddress() + ")", "IPv6(" + v6.getHostAddress() + ")"), listOut); + + assertNotNull((String) simpleName.invoke(null)); + assertEquals("Rfc6724Resolver", (String) simpleName.invoke(null)); + } + + private static InetAddress inet(final String s) { + try { + return InetAddress.getByName(s); + } catch (final UnknownHostException ex) { + throw new AssertionError(ex); + } + } + + private static Rfc6724AddressSelectingDnsResolver.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; + }; + } + + private static String classifyScope(final Class resolverClass, final InetAddress ip) throws Exception { + final Method m = resolverClass.getDeclaredMethod("classifyScope", InetAddress.class); + m.setAccessible(true); + final Object scope = m.invoke(null, ip); + return scope != null ? scope.toString() : null; + } + + private static String scopeFromValue(final Class scopeClass, final int v) throws Exception { + final Method m = scopeClass.getDeclaredMethod("fromValue", int.class); + m.setAccessible(true); + final Object scope = m.invoke(null, v); + return scope != null ? scope.toString() : null; + } + + private static Class findDeclaredClass(final Class outer, final String simpleName) { + for (final Class c : outer.getDeclaredClasses()) { + if (simpleName.equals(c.getSimpleName())) { + return c; + } + } + return null; + } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java new file mode 100644 index 0000000000..4113bcc4b8 --- /dev/null +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java @@ -0,0 +1,67 @@ +/* + * ==================================================================== + * 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.Rfc6724AddressSelectingDnsResolver; +import org.apache.hc.client5.http.SystemDefaultDnsResolver; +import org.apache.hc.client5.http.config.ProtocolFamilyPreference; + +public final class Rfc6724ResolverExample { + + 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; + + final DnsResolver resolver = new Rfc6724AddressSelectingDnsResolver(SystemDefaultDnsResolver.INSTANCE, pref); + + final InetAddress[] out = resolver.resolve(host); + + System.out.println("Host: " + host); + System.out.println("Preference: " + pref); + if (out == null) { + System.out.println("Result: null"); + return; + } + if (out.length == 0) { + System.out.println("Result: []"); + return; + } + for (final InetAddress a : out) { + final String family = a instanceof java.net.Inet6Address ? "IPv6" : "IPv4"; + System.out.println(" " + family + " " + a.getHostAddress()); + } + } + + private Rfc6724ResolverExample() { + } +} From f0de6cf85eb53ecb9951477d36647b81a2598b77 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Thu, 15 Jan 2026 20:29:30 +0100 Subject: [PATCH 09/15] Apply RFC 6724 destination ordering and family preferences to DNS results. Tighten resolver semantics and filtering for HTTP/TCP connect targets. --- .../AddressSelectingDnsResolverIT.java | 254 +++++++ .../testing/ManualRfc6724ResolverIT.java | 87 --- ....java => AddressSelectingDnsResolver.java} | 283 ++++---- .../http/AddressSelectingDnsResolverTest.java | 657 ++++++++++++++++++ ...fc6724AddressSelectingDnsResolverTest.java | 385 ---------- ...> AddressSelectingDnsResolverExample.java} | 34 +- 6 files changed, 1095 insertions(+), 605 deletions(-) create mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/AddressSelectingDnsResolverIT.java delete mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java rename httpclient5/src/main/java/org/apache/hc/client5/http/{Rfc6724AddressSelectingDnsResolver.java => AddressSelectingDnsResolver.java} (69%) create mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/AddressSelectingDnsResolverTest.java delete mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java rename httpclient5/src/test/java/org/apache/hc/client5/http/examples/{Rfc6724ResolverExample.java => AddressSelectingDnsResolverExample.java} (67%) diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/AddressSelectingDnsResolverIT.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/AddressSelectingDnsResolverIT.java new file mode 100644 index 0000000000..9f365669fa --- /dev/null +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/AddressSelectingDnsResolverIT.java @@ -0,0 +1,254 @@ +/* + * ==================================================================== + * 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.testing; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.apache.hc.client5.http.AddressSelectingDnsResolver; +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.SystemDefaultDnsResolver; +import org.apache.hc.client5.http.config.ProtocolFamilyPreference; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; + +@EnabledIfSystemProperty(named = "httpclient.rfc6724.it", matches = "true") +class AddressSelectingDnsResolverIT { + + private static final String PROP_HOST = "httpclient.rfc6724.host"; + + @Test + void interleave_isStableInterleavingOfDefault_forSameResolution() throws Exception { + final String host = System.getProperty(PROP_HOST, "localhost"); + + final InetAddress[] resolvedOnce = SystemDefaultDnsResolver.INSTANCE.resolve(host); + + final DnsResolver captured = new DnsResolver() { + @Override + public InetAddress[] resolve(final String h) throws UnknownHostException { + if (!host.equals(h)) { + throw new UnknownHostException(h); + } + return resolvedOnce.clone(); + } + + @Override + public String resolveCanonicalHostname(final String h) throws UnknownHostException { + return SystemDefaultDnsResolver.INSTANCE.resolveCanonicalHostname(h); + } + }; + + final AddressSelectingDnsResolver rDefault = + new AddressSelectingDnsResolver(captured, ProtocolFamilyPreference.DEFAULT); + + final AddressSelectingDnsResolver rInterleave = + new AddressSelectingDnsResolver(captured, ProtocolFamilyPreference.INTERLEAVE); + + final InetAddress[] outDefault = rDefault.resolve(host); + final InetAddress[] outInterleave = rInterleave.resolve(host); + + // 0) Both outputs must be permutations of the captured, single resolution. + Assertions.assertNotNull(outDefault); + assertSameElements(Arrays.asList(resolvedOnce), Arrays.asList(outDefault)); + Assertions.assertNotNull(outInterleave); + assertSameElements(Arrays.asList(resolvedOnce), Arrays.asList(outInterleave)); + + // 1) Same elements between DEFAULT and INTERLEAVE (no drops, no additions). + assertSameElements(Arrays.asList(outDefault), Arrays.asList(outInterleave)); + + // 2) Family counts must match between DEFAULT and INTERLEAVE. + final Counts cDefault = countFamilies(outDefault); + final Counts cInterleave = countFamilies(outInterleave); + assertEquals(cDefault.v4, cInterleave.v4); + assertEquals(cDefault.v6, cInterleave.v6); + + // 3) INTERLEAVE must be the stable interleaving of the DEFAULT-ordered list. + final List expected = expectedInterleaveFromBaseline(Arrays.asList(outDefault)); + assertEquals(expected, Arrays.asList(outInterleave)); + + // 4) If both families are present, the first 2*min(v4,v6) addresses must alternate by family. + final int pairs = Math.min(cInterleave.v4, cInterleave.v6); + if (pairs > 0) { + assertAlternatingPrefix(outInterleave, 2 * pairs); + } + + // 5) Relative order within each family is preserved from DEFAULT. + assertFamilyRelativeOrderPreserved(outDefault, outInterleave); + + // Diagnostics for manual runs. + System.out.println("Host: " + host); + dump("DEFAULT", outDefault); + dump("INTERLEAVE", outInterleave); + } + + private static void assertSameElements(final List a, final List b) { + assertEquals(a.size(), b.size()); + + final List remaining = new ArrayList<>(b); + for (final InetAddress x : a) { + assertTrue(remaining.remove(x), "Missing address: " + x); + } + assertTrue(remaining.isEmpty(), "Extra addresses: " + remaining); + } + + private static final class Counts { + final int v4; + final int v6; + + Counts(final int v4, final int v6) { + this.v4 = v4; + this.v6 = v6; + } + } + + private static Counts countFamilies(final InetAddress[] out) { + int v4 = 0; + int v6 = 0; + for (final InetAddress a : out) { + if (a instanceof Inet6Address) { + v6++; + } else { + v4++; + } + } + return new Counts(v4, v6); + } + + private static void assertAlternatingPrefix(final InetAddress[] out, final int length) { + if (length <= 1) { + return; + } + final boolean firstV6 = out[0] instanceof Inet6Address; + for (int i = 0; i < length; i++) { + final boolean expectV6 = firstV6 == (i % 2 == 0); + final boolean isV6 = out[i] instanceof Inet6Address; + assertEquals(expectV6, isV6, "Not alternating at index " + i); + } + } + + private static void assertFamilyRelativeOrderPreserved( + final InetAddress[] base, + final InetAddress[] interleaved) { + + final List baseV6 = new ArrayList<>(); + final List baseV4 = new ArrayList<>(); + for (final InetAddress a : base) { + if (a instanceof Inet6Address) { + baseV6.add(a); + } else { + baseV4.add(a); + } + } + + final List gotV6 = new ArrayList<>(); + final List gotV4 = new ArrayList<>(); + for (final InetAddress a : interleaved) { + if (a instanceof Inet6Address) { + gotV6.add(a); + } else { + gotV4.add(a); + } + } + + assertEquals(baseV6, gotV6, "IPv6 relative order changed"); + assertEquals(baseV4, gotV4, "IPv4 relative order changed"); + } + + private static List expectedInterleaveFromBaseline(final List baseline) { + if (baseline.size() <= 1) { + return baseline; + } + + final List v6 = new ArrayList<>(); + final List v4 = new ArrayList<>(); + + for (final InetAddress a : baseline) { + if (a instanceof Inet6Address) { + v6.add(a); + } else { + v4.add(a); + } + } + + if (v6.isEmpty() || v4.isEmpty()) { + return baseline; + } + + final boolean startV6 = baseline.get(0) instanceof Inet6Address; + + final List out = new ArrayList<>(baseline.size()); + int i6 = 0; + int i4 = 0; + + while (i6 < v6.size() || i4 < v4.size()) { + if (startV6) { + if (i6 < v6.size()) { + out.add(v6.get(i6++)); + } + if (i4 < v4.size()) { + out.add(v4.get(i4++)); + } + } else { + if (i4 < v4.size()) { + out.add(v4.get(i4++)); + } + if (i6 < v6.size()) { + out.add(v6.get(i6++)); + } + } + } + + return out; + } + + private static void dump(final String label, final InetAddress[] out) { + int v4 = 0; + int v6 = 0; + + System.out.println("Preference: " + label); + for (final InetAddress a : out) { + if (a instanceof Inet6Address) { + v6++; + System.out.println(" IPv6 " + a.getHostAddress()); + } else { + v4++; + System.out.println(" IPv4 " + a.getHostAddress()); + } + } + System.out.println("Counts: IPv4=" + v4 + " IPv6=" + v6); + System.out.println(); + } +} diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java deleted file mode 100644 index 7503e8c12e..0000000000 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/ManualRfc6724ResolverIT.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ==================================================================== - * 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.testing; - -import static org.junit.jupiter.api.Assumptions.assumeTrue; - -import java.net.Inet6Address; -import java.net.InetAddress; - -import org.apache.hc.client5.http.DnsResolver; -import org.apache.hc.client5.http.Rfc6724AddressSelectingDnsResolver; -import org.apache.hc.client5.http.SystemDefaultDnsResolver; -import org.apache.hc.client5.http.config.ProtocolFamilyPreference; -import org.junit.jupiter.api.Test; - -class ManualRfc6724ResolverIT { - - private static final String PROP_ENABLE = "httpclient.rfc6724.it"; - private static final String PROP_HOST = "httpclient.rfc6724.host"; - - @Test - void resolve_and_dump_order() throws Exception { - assumeTrue(Boolean.getBoolean(PROP_ENABLE), - "Enable with -Dhttpclient.rfc6724.it=true"); - - final String host = System.getProperty(PROP_HOST, "localhost"); - - final DnsResolver base = SystemDefaultDnsResolver.INSTANCE; - - System.out.println("Host: " + host); - - dump(base, host, ProtocolFamilyPreference.DEFAULT); - System.out.println(); - dump(base, host, ProtocolFamilyPreference.INTERLEAVE); - } - - private static void dump( - final DnsResolver base, - final String host, - final ProtocolFamilyPreference pref) throws Exception { - - final Rfc6724AddressSelectingDnsResolver resolver = - new Rfc6724AddressSelectingDnsResolver(base, pref); - - final InetAddress[] out = resolver.resolve(host); - - int v4 = 0; - int v6 = 0; - - System.out.println("Preference: " + pref); - for (final InetAddress a : out) { - if (a instanceof Inet6Address) { - v6++; - System.out.println(" IPv6 " + a.getHostAddress()); - } else { - v4++; - System.out.println(" IPv4 " + a.getHostAddress()); - } - } - System.out.println("Counts: IPv4=" + v4 + " IPv6=" + v6); - } -} diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java b/httpclient5/src/main/java/org/apache/hc/client5/http/AddressSelectingDnsResolver.java similarity index 69% rename from httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java rename to httpclient5/src/main/java/org/apache/hc/client5/http/AddressSelectingDnsResolver.java index 48f0e061f7..8798caec59 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/AddressSelectingDnsResolver.java @@ -38,6 +38,7 @@ import java.util.Arrays; import java.util.Collections; import java.util.Comparator; +import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; @@ -49,7 +50,7 @@ import org.slf4j.LoggerFactory; /** - * {@code Rfc6724AddressSelectingDnsResolver} wraps a delegate {@link DnsResolver} + * {@code AddressSelectingDnsResolver} wraps a delegate {@link DnsResolver} * and applies RFC 6724 destination address selection rules (RFC 6724 §6) * to the returned addresses. It can also enforce or bias a protocol family preference. * @@ -64,9 +65,9 @@ * @since 5.7 */ @Contract(threading = ThreadingBehavior.IMMUTABLE) -public final class Rfc6724AddressSelectingDnsResolver implements DnsResolver { +public final class AddressSelectingDnsResolver implements DnsResolver { - private static final Logger LOG = LoggerFactory.getLogger(Rfc6724AddressSelectingDnsResolver.class); + private static final Logger LOG = LoggerFactory.getLogger(AddressSelectingDnsResolver.class); private static final int PROBE_PORT = 53; // UDP connect trick; no packets sent @@ -91,7 +92,7 @@ interface SourceAddressResolver { * * @param delegate underlying resolver to use. */ - public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { + public AddressSelectingDnsResolver(final DnsResolver delegate) { this(delegate, ProtocolFamilyPreference.DEFAULT); } @@ -101,14 +102,14 @@ public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { * @param delegate underlying resolver to use. * @param familyPreference family preference to apply (e.g. PREFER_IPV6, IPV4_ONLY). */ - public Rfc6724AddressSelectingDnsResolver( + public AddressSelectingDnsResolver( final DnsResolver delegate, final ProtocolFamilyPreference familyPreference) { this(delegate, familyPreference, DEFAULT_SOURCE_ADDRESS_RESOLVER); } // Package-private for unit tests: allows deterministic source address inference. - Rfc6724AddressSelectingDnsResolver( + AddressSelectingDnsResolver( final DnsResolver delegate, final ProtocolFamilyPreference familyPreference, final SourceAddressResolver sourceAddressResolver) { @@ -123,47 +124,62 @@ public InetAddress[] resolve(final String host) throws UnknownHostException { if (resolved == null) { if (LOG.isDebugEnabled()) { - LOG.debug("{} resolved '{}' -> null", simpleName(), host); + LOG.debug("resolved '{}' -> null", host); } return null; } - if (resolved.length <= 1) { - if (LOG.isDebugEnabled()) { - LOG.debug("{} resolved '{}' -> {}", simpleName(), host, fmt(resolved)); - } - return resolved; - } - if (LOG.isTraceEnabled()) { - LOG.trace("{} resolving host '{}' via delegate {}", simpleName(), host, delegate.getClass().getName()); - LOG.trace("{} familyPreference={}", simpleName(), familyPreference); - LOG.trace("{} delegate returned {} addresses for '{}': {}", simpleName(), resolved.length, host, fmt(resolved)); + LOG.trace("resolving host '{}' via delegate {}", host, delegate.getClass().getName()); + LOG.trace("familyPreference={}", familyPreference); + LOG.trace("delegate returned {} addresses for '{}': {}", resolved.length, host, fmt(resolved)); } + // Always filter, even for a single address — the family preference may exclude it. final List candidates = filterCandidates(resolved, familyPreference); if (candidates.isEmpty()) { if (LOG.isDebugEnabled()) { - LOG.debug("{} resolved '{}' -> []", simpleName(), host); + LOG.debug("resolved '{}' -> []", host); + } + return null; + } + + if (candidates.size() == 1) { + if (LOG.isDebugEnabled()) { + LOG.debug("resolved '{}' -> {}", host, fmt(candidates)); } - return new InetAddress[0]; + return candidates.toArray(new InetAddress[0]); } final List rfcSorted = sortByRfc6724(candidates); final List ordered = applyFamilyPreference(rfcSorted, familyPreference); if (LOG.isDebugEnabled()) { - LOG.debug("{} resolved '{}' -> {}", simpleName(), host, fmt(ordered)); + LOG.debug("resolved '{}' -> {}", host, fmt(ordered)); } return ordered.toArray(new InetAddress[0]); } + @Override + public List resolve(final String host, final int port) throws UnknownHostException { + final InetAddress[] ordered = resolve(host); + if (ordered == null) { + // Do NOT fall back to createUnresolved: an unresolved address would let + // downstream code re-resolve the hostname and bypass family filtering + // (e.g. IPV4_ONLY / IPV6_ONLY). + throw new UnknownHostException(host); + } + return Arrays.stream(ordered) + .map(a -> new InetSocketAddress(a, port)) + .collect(Collectors.toList()); + } + @Override public String resolveCanonicalHostname(final String host) throws UnknownHostException { if (LOG.isTraceEnabled()) { - LOG.trace("{} resolveCanonicalHostname('{}') via delegate {}", simpleName(), host, delegate.getClass().getName()); + LOG.trace("resolveCanonicalHostname('{}') via delegate {}", host, delegate.getClass().getName()); } return delegate.resolveCanonicalHostname(host); } @@ -176,43 +192,32 @@ private static boolean isUsableDestination(final InetAddress ip) { return false; } // HTTP/TCP is for unicast destinations; multicast is not a valid connect target. - if (ip.isMulticastAddress()) { - return false; - } - return true; + return !ip.isMulticastAddress(); } + private static List filterCandidates( final InetAddress[] resolved, final ProtocolFamilyPreference pref) { - final List out = new ArrayList<>(resolved.length); - for (final InetAddress a : resolved) { - if (!isUsableDestination(a)) { - continue; - } - switch (pref) { - case IPV4_ONLY: { - if (a instanceof Inet4Address) { - out.add(a); - } - break; - } - case IPV6_ONLY: { - if (a instanceof Inet6Address) { - out.add(a); - } - break; - } - default: { - out.add(a); - break; - } - } + return Arrays.stream(resolved) + .filter(AddressSelectingDnsResolver::isUsableDestination) + .filter(a -> shouldInclude(pref, a)) + .collect(Collectors.toList()); + } + + private static boolean shouldInclude(final ProtocolFamilyPreference pref, final InetAddress a) { + switch (pref) { + case IPV4_ONLY: + return a instanceof Inet4Address; + case IPV6_ONLY: + return a instanceof Inet6Address; + default: + return true; } - return out; } + // --- RFC 6724 helpers --- private List sortByRfc6724(final List addrs) { @@ -224,17 +229,9 @@ private List sortByRfc6724(final List addrs) { LOG.trace("RFC6724 input candidates: {}", fmt(addrs)); } - final List socketAddresses = new ArrayList<>(addrs.size()); - for (final InetAddress a : addrs) { - socketAddresses.add(new InetSocketAddress(a, PROBE_PORT)); - } - - final List srcs = inferSourceAddresses(socketAddresses); - final List infos = new ArrayList<>(addrs.size()); - for (int i = 0; i < addrs.size(); i++) { - final InetAddress dst = addrs.get(i); - final InetAddress src = srcs.get(i); + for (final InetAddress dst : addrs) { + final InetAddress src = inferSourceAddress(new InetSocketAddress(dst, PROBE_PORT)); infos.add(new Info(dst, src, ipAttrOf(dst), ipAttrOf(src))); } @@ -249,10 +246,9 @@ private List sortByRfc6724(final List addrs) { infos.sort(RFC6724_COMPARATOR); - final List out = new ArrayList<>(infos.size()); - for (final Info info : infos) { - out.add(info.dst); - } + final List out = infos.stream() + .map(info -> info.dst) + .collect(Collectors.toList()); if (LOG.isTraceEnabled()) { LOG.trace("RFC6724 output order: {}", fmt(out)); @@ -261,30 +257,15 @@ private List sortByRfc6724(final List addrs) { return out; } - private List inferSourceAddresses(final List destinations) { - final List srcs = new ArrayList<>(destinations.size()); - - for (final InetSocketAddress dest : destinations) { - InetAddress src = null; - try { - src = sourceAddressResolver.resolveSource(dest); - } catch (final SocketException ignore) { - if (LOG.isTraceEnabled()) { - LOG.trace("RFC6724 could not infer source address for {}: {}", dest, ignore.toString()); - } - } - srcs.add(src); - } - - if (LOG.isTraceEnabled()) { - final List printable = new ArrayList<>(srcs.size()); - for (final InetAddress a : srcs) { - printable.add(addr(a)); + private InetAddress inferSourceAddress(final InetSocketAddress destination) { + try { + return sourceAddressResolver.resolveSource(destination); + } catch (final SocketException ex) { + if (LOG.isTraceEnabled()) { + LOG.trace("RFC6724 could not infer source address for {}: {}", destination, ex.toString()); } - LOG.trace("RFC6724 inferred source addresses: {}", printable); + return null; } - - return srcs; } private static List applyFamilyPreference( @@ -351,14 +332,14 @@ private static List interleaveFamilies(final List rfcS final List second = startWithV6 ? v4 : v6; final List out = new ArrayList<>(rfcSorted.size()); - int i = 0; - int j = 0; - while (i < first.size() || j < second.size()) { - if (i < first.size()) { - out.add(first.get(i++)); + final Iterator it1 = first.iterator(); + final Iterator it2 = second.iterator(); + while (it1.hasNext() || it2.hasNext()) { + if (it1.hasNext()) { + out.add(it1.next()); } - if (j < second.size()) { - out.add(second.get(j++)); + if (it2.hasNext()) { + out.add(it2.next()); } } return out; @@ -380,7 +361,8 @@ private static final class Info { } } - private static final class Attr { + // Package-private for unit testing. + static final class Attr { final Scope scope; final int precedence; final int label; @@ -392,7 +374,8 @@ private static final class Attr { } } - private enum Scope { + // Package-private for unit testing. + enum Scope { INTERFACE_LOCAL(0x1), LINK_LOCAL(0x2), ADMIN_LOCAL(0x4), @@ -423,14 +406,18 @@ static Scope fromValue(final int v) { case 0x8: { return ORG_LOCAL; } - default: { + case 0xe: { return GLOBAL; } + default: { + throw new IllegalArgumentException("Unknown scope value: 0x" + Integer.toHexString(v)); + } } } } - private static Attr ipAttrOf(final InetAddress ip) { + // Package-private for unit testing. + static Attr ipAttrOf(final InetAddress ip) { if (ip == null) { return new Attr(Scope.GLOBAL, 0, 0); } @@ -438,19 +425,49 @@ private static Attr ipAttrOf(final InetAddress ip) { return new Attr(classifyScope(ip), e.precedence, e.label); } - private static Scope classifyScope(final InetAddress ip) { + // Package-private for unit testing. + // + // RFC 6724 §3.1 scope assignment: + // IPv6 ::1 → link-local (interface-local is multicast-only per RFC 4291 §2.7) + // IPv6 link-local → link-local + // IPv6 site-local → site-local (deprecated but still defined) + // IPv6 multicast → scope nibble from second byte (RFC 4291) + // IPv6 ULA (fc00::/7) → global (handled via policy table, not scope) + // IPv6 everything else → global + // + // IPv4 127/8 → link-local + // IPv4 169.254/16 → link-local + // IPv4 everything else → global (including RFC1918 and 100.64/10) + // + static Scope classifyScope(final InetAddress ip) { + if (ip instanceof Inet4Address) { + // IPv4 scope rules per RFC 6724 §3.1: + // Only loopback (127/8) and link-local (169.254/16) get link-local scope; + // all other IPv4 addresses (including RFC1918 private and 100.64/10) are global. + if (ip.isLoopbackAddress() || ip.isLinkLocalAddress()) { + return Scope.LINK_LOCAL; + } + return Scope.GLOBAL; + } + + // IPv6 scope rules. if (ip.isLoopbackAddress()) { - return Scope.INTERFACE_LOCAL; + // Interface-local scope (0x1) is a multicast-only concept (RFC 4291 §2.7). + // For unicast, the smallest meaningful scope is link-local. + return Scope.LINK_LOCAL; } if (ip.isLinkLocalAddress()) { return Scope.LINK_LOCAL; } if (ip.isMulticastAddress()) { - if (ip instanceof Inet6Address) { - // RFC 6724 §3.1 and RFC 4291: low 4 bits of second byte are scope for IPv6 multicast. - return Scope.fromValue(ip.getAddress()[1] & 0x0f); + // RFC 6724 §3.1 and RFC 4291: low 4 bits of second byte encode scope for IPv6 multicast. + // Not all nibble values map to a known Scope constant; treat unknown values as GLOBAL. + final int nibble = ip.getAddress()[1] & 0x0f; + try { + return Scope.fromValue(nibble); + } catch (final IllegalArgumentException e) { + return Scope.GLOBAL; } - return Scope.GLOBAL; } if (ip.isSiteLocalAddress()) { return Scope.SITE_LOCAL; @@ -470,7 +487,8 @@ private static final class PolicyEntry { } } - private static final class Network { + // Package-private for unit testing. + static final class Network { final byte[] ip; final int bits; @@ -511,7 +529,16 @@ private static byte[] v4toMapped(final byte[] v4) { private static Network toPrefix(final String text, final int bits) { try { - return new Network(InetAddress.getByName(text).getAddress(), bits); + byte[] address = InetAddress.getByName(text).getAddress(); + if (address.length == 4 && bits > 32) { + // The JDK collapses an IPv4-mapped IPv6 literal (e.g. "::ffff:0:0") into a + // 4-byte Inet4Address, regardless of its textual form. Network#contains() + // always compares IPv4 destinations against their 16-byte mapped form + // (Network#v4toMapped), so a policy entry built from the collapsed 4-byte + // address would never match: re-expand it to the intended 16-byte prefix. + address = Network.v4toMapped(address); + } + return new Network(address, bits); } catch (final UnknownHostException ex) { throw new IllegalArgumentException(ex); } @@ -553,6 +580,11 @@ private static PolicyEntry classify(final InetAddress ip) { final int preferB = 1; // RFC 6724 §6: destination address selection rules. + // + // Rules 3, 4 and 7 are not implementable with standard JDK APIs: + // Rule 3 (Avoid deprecated source addresses) — InetAddress exposes no deprecation state. + // Rule 4 (Prefer home addresses) — Mobile IPv6 concept; not applicable to an HTTP client. + // Rule 7 (Prefer native transport) — JDK provides no encapsulation/tunneling info. // Rule 1: Avoid unusable destinations. final boolean validA = aSrc != null && !aSrc.isAnyLocalAddress(); @@ -575,6 +607,10 @@ private static PolicyEntry classify(final InetAddress ip) { return preferB; } + // Rule 3: Avoid deprecated addresses — skipped (see above). + + // Rule 4: Prefer home addresses — skipped (see above). + // Rule 5: Prefer matching label. if (aSrcAttr.label == aDstAttr.label && bSrcAttr.label != bDstAttr.label) { return preferA; @@ -591,6 +627,8 @@ private static PolicyEntry classify(final InetAddress ip) { return preferB; } + // Rule 7: Prefer native transport — skipped (see above). + // Rule 8: Prefer smaller scope. if (aDstAttr.scope.value < bDstAttr.scope.value) { return preferA; @@ -599,8 +637,16 @@ private static PolicyEntry classify(final InetAddress ip) { return preferB; } - // Rule 9: Longest matching prefix (IPv6 only). - if (aDst instanceof Inet6Address && bDst instanceof Inet6Address) { + // Rule 9: Use longest matching prefix (RFC 6724 §6). + // Applies when DA and DB belong to the same address family. + // + // Note: this is an approximation. A fully correct implementation would + // use the source address's on-link prefix length (from the interface + // configuration / routing table), not the bit-wise common-prefix of + // source and destination. The JDK does not expose interface prefix + // lengths for source address selection, so we fall back to + // CommonPrefixLen(Source(D), D) as a reasonable heuristic. + if (aDst.getClass() == bDst.getClass()) { final int commonA = commonPrefixLen(aSrc, aDst); final int commonB = commonPrefixLen(bSrc, bDst); if (commonA > commonB) { @@ -640,7 +686,7 @@ private static int commonPrefixLen(final InetAddress a, final InetAddress b) { return bits; } - private static String addr(final InetAddress a) { + static String addr(final InetAddress a) { if (a == null) { return "null"; } @@ -648,23 +694,16 @@ private static String addr(final InetAddress a) { return family + "(" + a.getHostAddress() + ")"; } - private static List fmt(final InetAddress[] arr) { - final List out = new ArrayList<>(arr.length); - for (final InetAddress a : arr) { - out.add(addr(a)); - } - return out; + static List fmt(final InetAddress[] arr) { + return Arrays.stream(arr) + .map(AddressSelectingDnsResolver::addr) + .collect(Collectors.toList()); } - private static List fmt(final List arr) { - final List out = new ArrayList<>(arr.size()); - for (final InetAddress a : arr) { - out.add(addr(a)); - } - return out; + static List fmt(final List arr) { + return arr.stream() + .map(AddressSelectingDnsResolver::addr) + .collect(Collectors.toList()); } - private static String simpleName() { - return "Rfc6724Resolver"; - } } 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/Rfc6724AddressSelectingDnsResolverTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java deleted file mode 100644 index 3690a99aeb..0000000000 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolverTest.java +++ /dev/null @@ -1,385 +0,0 @@ -/* - * ==================================================================== - * 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.assertInstanceOf; -import static org.junit.jupiter.api.Assertions.assertNotNull; - -import java.lang.reflect.Method; -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 Rfc6724AddressSelectingDnsResolverTest { - - private static final Rfc6724AddressSelectingDnsResolver.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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.IPV4_ONLY, NO_SOURCE_ADDR); - - final InetAddress[] ordered = r.resolve("v6only.example"); - assertEquals(0, ordered.length); - } - - @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 Rfc6724AddressSelectingDnsResolver r1 = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR); - final Rfc6724AddressSelectingDnsResolver r2 = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver preferV6 = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(delegate, ProtocolFamilyPreference.DEFAULT, NO_SOURCE_ADDR); - - final InetAddress[] out = r.resolve("mcast.example"); - assertEquals(1, out.length); - assertEquals(v6, out[0]); - } - - // ------------------------------------------------------------------------- - // New: direct tests for classifyScope(..) and Scope.fromValue(..) via reflection - // (Scope and classifyScope are private in the resolver). - // ------------------------------------------------------------------------- - - @Test - void classifyScope_loopback_linkLocal_siteLocal_global() throws Exception { - final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; - - assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("127.0.0.1"))); - assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("::1"))); - - assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("169.254.0.1"))); - assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("fe80::1"))); - - assertEquals("SITE_LOCAL", classifyScope(resolverClass, inet("10.0.0.1"))); - - assertEquals("GLOBAL", classifyScope(resolverClass, inet("8.8.8.8"))); - assertEquals("GLOBAL", classifyScope(resolverClass, inet("2003::1"))); - } - - @Test - void classifyScope_ipv6Multicast_usesLowNibbleScope() throws Exception { - final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; - - // ff01::1 -> scope 0x1 -> INTERFACE_LOCAL - assertEquals("INTERFACE_LOCAL", classifyScope(resolverClass, inet("ff01::1"))); - // ff02::1 -> scope 0x2 -> LINK_LOCAL - assertEquals("LINK_LOCAL", classifyScope(resolverClass, inet("ff02::1"))); - // ff04::1 -> scope 0x4 -> ADMIN_LOCAL - assertEquals("ADMIN_LOCAL", classifyScope(resolverClass, inet("ff04::1"))); - // ff05::1 -> scope 0x5 -> SITE_LOCAL - assertEquals("SITE_LOCAL", classifyScope(resolverClass, inet("ff05::1"))); - // ff08::1 -> scope 0x8 -> ORG_LOCAL - assertEquals("ORG_LOCAL", classifyScope(resolverClass, inet("ff08::1"))); - // ff0e::1 -> scope 0xe -> GLOBAL (default branch) - assertEquals("GLOBAL", classifyScope(resolverClass, inet("ff0e::1"))); - } - - @Test - void scopeFromValue_mapsKnownConstants_andDefaultsToGlobal() throws Exception { - final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; - final Class scopeClass = findDeclaredClass(resolverClass, "Scope"); - assertNotNull(scopeClass); - - assertEquals("INTERFACE_LOCAL", scopeFromValue(scopeClass, 0x1)); - assertEquals("LINK_LOCAL", scopeFromValue(scopeClass, 0x2)); - assertEquals("ADMIN_LOCAL", scopeFromValue(scopeClass, 0x4)); - assertEquals("SITE_LOCAL", scopeFromValue(scopeClass, 0x5)); - assertEquals("ORG_LOCAL", scopeFromValue(scopeClass, 0x8)); - - assertEquals("GLOBAL", scopeFromValue(scopeClass, 0x0)); - assertEquals("GLOBAL", scopeFromValue(scopeClass, 0xe)); - assertEquals("GLOBAL", scopeFromValue(scopeClass, 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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 Rfc6724AddressSelectingDnsResolver r = - new Rfc6724AddressSelectingDnsResolver(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 addr_fmt_simpleName() throws Exception { - final Class resolverClass = Rfc6724AddressSelectingDnsResolver.class; - - final Method addr = resolverClass.getDeclaredMethod("addr", InetAddress.class); - addr.setAccessible(true); - - final Method fmtArr = resolverClass.getDeclaredMethod("fmt", InetAddress[].class); - fmtArr.setAccessible(true); - - final Method fmtList = resolverClass.getDeclaredMethod("fmt", List.class); - fmtList.setAccessible(true); - - final Method simpleName = resolverClass.getDeclaredMethod("simpleName"); - simpleName.setAccessible(true); - - assertEquals("null", (String) addr.invoke(null, new Object[]{null})); - - final InetAddress v4 = inet("192.0.2.1"); - final InetAddress v6 = inet("2001:db8::1"); - - final String s4 = (String) addr.invoke(null, v4); - final String s6 = (String) addr.invoke(null, v6); - - assertEquals("IPv4(" + v4.getHostAddress() + ")", s4); - assertEquals("IPv6(" + v6.getHostAddress() + ")", s6); - - @SuppressWarnings("unchecked") final List arrOut = (List) fmtArr.invoke(null, new Object[]{new InetAddress[]{v6, v4}}); - assertEquals(Arrays.asList("IPv6(" + v6.getHostAddress() + ")", "IPv4(" + v4.getHostAddress() + ")"), arrOut); - - @SuppressWarnings("unchecked") final List listOut = (List) fmtList.invoke(null, Arrays.asList(v4, v6)); - assertEquals(Arrays.asList("IPv4(" + v4.getHostAddress() + ")", "IPv6(" + v6.getHostAddress() + ")"), listOut); - - assertNotNull((String) simpleName.invoke(null)); - assertEquals("Rfc6724Resolver", (String) simpleName.invoke(null)); - } - - private static InetAddress inet(final String s) { - try { - return InetAddress.getByName(s); - } catch (final UnknownHostException ex) { - throw new AssertionError(ex); - } - } - - private static Rfc6724AddressSelectingDnsResolver.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; - }; - } - - private static String classifyScope(final Class resolverClass, final InetAddress ip) throws Exception { - final Method m = resolverClass.getDeclaredMethod("classifyScope", InetAddress.class); - m.setAccessible(true); - final Object scope = m.invoke(null, ip); - return scope != null ? scope.toString() : null; - } - - private static String scopeFromValue(final Class scopeClass, final int v) throws Exception { - final Method m = scopeClass.getDeclaredMethod("fromValue", int.class); - m.setAccessible(true); - final Object scope = m.invoke(null, v); - return scope != null ? scope.toString() : null; - } - - private static Class findDeclaredClass(final Class outer, final String simpleName) { - for (final Class c : outer.getDeclaredClasses()) { - if (simpleName.equals(c.getSimpleName())) { - return c; - } - } - return null; - } -} diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java similarity index 67% rename from httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java rename to httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java index 4113bcc4b8..a7c6656da7 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/examples/Rfc6724ResolverExample.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/examples/AddressSelectingDnsResolverExample.java @@ -30,11 +30,11 @@ import java.net.InetAddress; import org.apache.hc.client5.http.DnsResolver; -import org.apache.hc.client5.http.Rfc6724AddressSelectingDnsResolver; +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 Rfc6724ResolverExample { +public final class AddressSelectingDnsResolverExample { public static void main(final String[] args) throws Exception { final String host = args.length > 0 ? args[0] : "localhost"; @@ -42,26 +42,38 @@ public static void main(final String[] args) throws Exception { ? ProtocolFamilyPreference.valueOf(args[1]) : ProtocolFamilyPreference.DEFAULT; - final DnsResolver resolver = new Rfc6724AddressSelectingDnsResolver(SystemDefaultDnsResolver.INSTANCE, pref); + 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); + } - System.out.println("Host: " + host); - System.out.println("Preference: " + pref); - if (out == null) { - System.out.println("Result: null"); + private static void printAddresses(final InetAddress[] addresses) { + if (addresses == null) { + System.out.println(" null"); return; } - if (out.length == 0) { - System.out.println("Result: []"); + if (addresses.length == 0) { + System.out.println(" []"); return; } - for (final InetAddress a : out) { + 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 Rfc6724ResolverExample() { + private AddressSelectingDnsResolverExample() { } } From ed522f637b6d424f409d03b82b7263d9711982e7 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Tue, 10 Nov 2026 21:05:55 +0100 Subject: [PATCH 10/15] Stagger connection attempts across resolved addresses (RFC 8305) Races connection attempts across a host's resolved addresses instead of trying them strictly sequentially: first address immediately, each next one after a configurable delay (250ms default) unless an earlier one fails first, in which case the next address starts at the RFC 8305 Section 5 minimum spacing (10ms). First success wins; the rest are cancelled or closed. An attempt cancelled from outside the race is treated like a failure so the future is never left pending forever. A winning session can be selected by the race at the same moment the caller cancels the outer Future directly. ComplexFuture#completed then returns false; close the session instead of silently dropping it. Opt-in, off by default; disabled behavior is unchanged. --- .../DefaultAsyncClientConnectionOperator.java | 15 +- .../nio/MultihomeConnectionInitiator.java | 31 ++ .../impl/nio/MultihomeIOSessionRequester.java | 362 ++++++++++++ ...ngAsyncClientConnectionManagerBuilder.java | 57 +- .../nio/MultihomeIOSessionRequesterTest.java | 527 ++++++++++++++++++ 5 files changed, 989 insertions(+), 3 deletions(-) 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/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(); + } + } } From 5b9837710dc84eb49c6d1fb0e70ba3b1174cd5e6 Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Tue, 10 Nov 2026 21:32:00 +0100 Subject: [PATCH 11/15] Race connection attempts across resolved addresses for the Classic client Replaces the one-thread-per-address, sleep-based stagger with a single dispatcher that starts the first address immediately and waits up to the connection attempt delay for an outstanding attempt to finish before starting the next; on a failure it advances immediately, at the RFC 8305 minimum spacing (10ms), instead of waiting out the full delay. No worker thread ever sleeps a delay itself, bounding concurrency to the number of resolved addresses actually in flight. Socket registration goes through a small atomic registry instead of a bare reference: deciding a winner and a worker registering its socket can happen at the same instant, and whichever runs second closes the socket, so nothing registered around that moment survives open regardless of timing. shutdownNow() alone cannot abort a blocking Socket#connect; closing the socket is what actually does that, on every exit path (winner found, every address failed, or interrupted) via one cleanup call in a finally block. An interruption during the minimum-spacing wait is now propagated instead of swallowed, aborting the race immediately like interruption anywhere else in it. Racing is skipped in favor of the existing sequential path when a specific, non-ephemeral local port is requested, since binding several attempts to it concurrently would trade a real connect failure for a spurious bind conflict. Public, blocking connect() behavior, TLS, SOCKS and local binding are otherwise unchanged. --- .../sync/TestHappyEyeballsTlsFallback.java | 231 ++++++++++++ .../DefaultHttpClientConnectionOperator.java | 133 +++++++ .../impl/io/HappyEyeballsSocketConnector.java | 293 +++++++++++++++ ...ingHttpClientConnectionManagerBuilder.java | 41 ++- ...faultHttpClientConnectionOperatorTest.java | 277 ++++++++++++++ .../io/HappyEyeballsSocketConnectorTest.java | 340 ++++++++++++++++++ 6 files changed, 1314 insertions(+), 1 deletion(-) create mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestHappyEyeballsTlsFallback.java create mode 100644 httpclient5/src/main/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnector.java create mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/DefaultHttpClientConnectionOperatorTest.java create mode 100644 httpclient5/src/test/java/org/apache/hc/client5/http/impl/io/HappyEyeballsSocketConnectorTest.java diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestHappyEyeballsTlsFallback.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestHappyEyeballsTlsFallback.java new file mode 100644 index 0000000000..d4f341f172 --- /dev/null +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/sync/TestHappyEyeballsTlsFallback.java @@ -0,0 +1,231 @@ +/* + * ==================================================================== + * 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.testing.sync; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.util.Arrays; +import java.util.List; + +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManager; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy; +import org.apache.hc.client5.http.ssl.NoopHostnameVerifier; +import org.apache.hc.client5.testing.SSLTestContexts; +import org.apache.hc.client5.testing.tls.TlsHandshakeTimeoutServer; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.impl.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap; +import org.apache.hc.core5.http.io.entity.EntityUtils; +import org.apache.hc.core5.io.CloseMode; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; + +/** + * Regression tests for the Happy Eyeballs (RFC 8305) racing path of the Classic client, + * against a real {@link CloseableHttpClient}, real local TCP/TLS servers and a real TLS + * handshake (PR #936 review comment, 2026-11-19): a TLS failure on the address that won the + * TCP race must still fall back to the remaining, untried address, the same as the + * non-racing (sequential) path and master already do. + */ +class TestHappyEyeballsTlsFallback { + + private HttpServer healthyServer; + private ServerSocket resetProbe; + private TlsHandshakeTimeoutServer stallingServer; + + @AfterEach + void shutDown() throws IOException { + if (healthyServer != null) { + healthyServer.close(CloseMode.GRACEFUL); + } + if (resetProbe != null) { + resetProbe.close(); + } + if (stallingServer != null) { + stallingServer.close(); + } + } + + private HttpServer startHealthyServer() throws Exception { + final HttpServer server = ServerBootstrap.bootstrap() + .setLocalAddress(InetAddress.getLoopbackAddress()) + .setSslContext(SSLTestContexts.createServerSSLContext()) + .register("localhost", "*", (request, response, context) -> response.setCode(HttpStatus.SC_OK)) + .create(); + server.start(); + return server; + } + + private CloseableHttpClient clientFor(final List remoteAddresses, final boolean happyEyeballs) throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses); + final PoolingHttpClientConnectionManager connMgr = PoolingHttpClientConnectionManagerBuilder.create() + .setDnsResolver(dnsResolver) + .setDefaultConnectionConfig(ConnectionConfig.custom() + .setConnectTimeout(Timeout.ofSeconds(5)) + .setSocketTimeout(Timeout.ofSeconds(5)) + .build()) + .setTlsSocketStrategy(new DefaultClientTlsStrategy( + SSLTestContexts.createClientSSLContext(), NoopHostnameVerifier.INSTANCE)) + .setHappyEyeballsEnabled(happyEyeballs) + .setConnectionAttemptDelay(TimeValue.ofMilliseconds(50)) + .build(); + return HttpClientBuilder.create() + .setConnectionManager(connMgr) + .disableAutomaticRetries() + .build(); + } + + private static void assertServedByHealthyServer(final CloseableHttpClient client) throws IOException { + final HttpGet request = new HttpGet("https://localhost/"); + client.execute(request, response -> { + Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); + EntityUtils.consume(response.getEntity()); + return null; + }); + } + + /** + * Scenario 1: TCP accepted, TLS handshake fails immediately (the server accepts the TCP + * connection and resets it before any TLS record is exchanged). + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tcpAcceptedTlsFailsImmediately_fallsBackToHealthyAddress(final boolean happyEyeballs) throws Exception { + resetProbe = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + final int brokenPort = resetProbe.getLocalPort(); + final Thread resetThread = new Thread(() -> { + try { + while (!resetProbe.isClosed()) { + final java.net.Socket accepted = resetProbe.accept(); + accepted.setSoLinger(true, 0); // RST on close instead of a clean FIN + accepted.close(); + } + } catch (final IOException ignore) { + // Expected once the probe socket is closed by shutDown(). + } + }, "reset-probe"); + resetThread.setDaemon(true); + resetThread.start(); + + healthyServer = startHealthyServer(); + final int healthyPort = healthyServer.getLocalPort(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort), + new InetSocketAddress(InetAddress.getLoopbackAddress(), healthyPort)); + + try (CloseableHttpClient client = clientFor(remoteAddresses, happyEyeballs)) { + assertServedByHealthyServer(client); + } + } + + /** + * Scenario 2: TCP accepted, TLS handshake stalls until the handshake/connect timeout. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tcpAcceptedTlsStallsUntilTimeout_fallsBackToHealthyAddress(final boolean happyEyeballs) throws Exception { + stallingServer = new TlsHandshakeTimeoutServer(false); + stallingServer.start(); + final int stallingPort = stallingServer.getPort(); + + healthyServer = startHealthyServer(); + final int healthyPort = healthyServer.getLocalPort(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), stallingPort), + new InetSocketAddress(InetAddress.getLoopbackAddress(), healthyPort)); + + try (CloseableHttpClient client = clientFor(remoteAddresses, happyEyeballs)) { + assertServedByHealthyServer(client); + } + } + + /** + * When every address fails TLS, the final exception must still be reported (no address is + * left silently unreported, and the connection attempt does not hang). + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void allAddressesFailTls_throws(final boolean happyEyeballs) throws Exception { + resetProbe = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + final int brokenPort1 = resetProbe.getLocalPort(); + final Thread resetThread = new Thread(() -> { + try { + while (!resetProbe.isClosed()) { + final java.net.Socket accepted = resetProbe.accept(); + accepted.setSoLinger(true, 0); + accepted.close(); + } + } catch (final IOException ignore) { + // Expected once the probe socket is closed by shutDown(). + } + }, "reset-probe-2"); + resetThread.setDaemon(true); + resetThread.start(); + + try (ServerSocket resetProbe2 = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + final int brokenPort2 = resetProbe2.getLocalPort(); + final Thread resetThread2 = new Thread(() -> { + try { + while (!resetProbe2.isClosed()) { + final java.net.Socket accepted = resetProbe2.accept(); + accepted.setSoLinger(true, 0); + accepted.close(); + } + } catch (final IOException ignore) { + // Expected once resetProbe2 is closed by the try-with-resources above. + } + }, "reset-probe-3"); + resetThread2.setDaemon(true); + resetThread2.start(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort1), + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort2)); + + try (CloseableHttpClient client = clientFor(remoteAddresses, happyEyeballs)) { + final HttpGet request = new HttpGet("https://localhost/"); + Assertions.assertThrows(IOException.class, () -> client.execute(request, response -> null)); + } + } + } +} 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/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(); + } + } +} From 2a78479febf57508760cbc75d2ee237a0b2ddc9a Mon Sep 17 00:00:00 2001 From: shinseongsu Date: Mon, 30 Nov 2026 23:14:39 +0900 Subject: [PATCH 12/15] Skip malformed auth challenge headers instead of dropping all of them Since the challenge parsing was reworked, a single malformed WWW-Authenticate or Proxy-Authenticate header causes all challenges in the response to be discarded, so a valid Basic or Digest challenge in another header is no longer used and the 401 is returned as is. Before that change only the malformed header was skipped. The empty map returned in that case is also immutable, so a response that carries Authentication-Info together with a malformed challenge header fails with UnsupportedOperationException. Parse each header separately again and skip only the ones that fail. --- .../http/impl/auth/AuthenticationHandler.java | 47 +++++++--------- .../impl/auth/TestAuthenticationHandler.java | 53 +++++++++++++++++++ 2 files changed, 73 insertions(+), 27 deletions(-) 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..bfa9998896 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; @@ -164,37 +164,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; } /** 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); From 90b61a8612f5d5cb401c09b1aa7b4add8c73910f Mon Sep 17 00:00:00 2001 From: Arturo Bernal Date: Sat, 21 Nov 2026 17:31:08 +0100 Subject: [PATCH 13/15] Fall back to remaining addresses when TLS fails after a connect (RFC 8305) MultihomeIOSessionRequester only retried a TCP-level connect failure across the resolved addresses; a TLS failure on an address that had already connected at the TCP level, racing or not, ended the whole attempt instead of trying the others, the same regression #936 fixed for the classic client. Adds a SessionValidator hook run on every connected session before it is accepted, shared by the plain sequential path and the race's post-win fallback, mirroring DefaultHttpClientConnectionOperator's connectSequentially. Hardens cancellation around that fallback: a cancel arriving while a TLS-triggered fallback attempt is in flight reaches the live attempt, in both the plain sequential path and the racing path's post-win fallback. executeNext() checks future.isDone() before starting a new attempt, at the top of executeNext() itself and in onFailure(), the two places that start a new attempt, and holds a single ReentrantLock per connectSequentially() run, shared across all its attempts, across the index check and the future's dependency retarget, so a same-thread reentrant rejection and a cross-thread one can never race on which attempt is tracked. Race's own six synchronized blocks are converted the same way, matching the project's lock discipline for virtual threads. A TlsStrategy that reports an outcome and then throws, in violation of its contract, is a no-op on the second signal instead of double-advancing the fallback. The handshake result is reported before the onAfterTlsHandshake hook runs, so a throwing hook cannot hang the connect() future. The cancellation this hardening targets can still be lost underneath it, in httpcore5: SingleCoreIOReactor#processConnectionRequest connects and completes an IOSessionRequest before assigning it a closeable, so a cancel() landing in that window returns true without anything to close. A separate, narrower check-then-set race in ComplexFuture#setDependency itself is also unclosed. Both are out of scope here and belong in httpcore5. TestHttpAsyncMinimalTlsHandshake.testTlsHandshakeFailure is pinned to a literal address: "localhost" resolves to more than one address in this environment, and a TLS failure is no longer necessarily final for the last-tried address, so a second, unlistened-on address could mask the TLS failure the test asserts. TestHappyEyeballsTlsFallbackAsync's probe accepts the TCP connection, reads the ClientHello and replies in plaintext, producing a real SSLException. Its cancel-during-fallback scenario's own server observes the client disconnecting directly, so the test cannot pass merely because cancelling a future completes it locally regardless of whether cancellation propagated anywhere. This test is flaky under heavy CPU load (the cancel can still land in the httpcore5 window above); a validated fix exists but is not applied here. Unit tests cover: the isDone() guard at both its entry points (the racing one directly, via Race.onWinnerRejected()'s call into executeNext(); the sequential one indirectly, via onFailure(), which does not on its own exercise the top-of-executeNext() guard); the session never being closed when a throwing onAfterTlsHandshake hook is swallowed; and the double-invocation guard on both the callback and the throw-without-callback paths. --- .../TestHappyEyeballsTlsFallbackAsync.java | 295 ++++++++++++++ .../TestHttpAsyncMinimalTlsHandshake.java | 9 +- .../DefaultAsyncClientConnectionOperator.java | 172 +++++--- .../impl/nio/MultihomeIOSessionRequester.java | 346 +++++++++++++--- ...aultAsyncClientConnectionOperatorTest.java | 370 ++++++++++++++++++ .../nio/MultihomeIOSessionRequesterTest.java | 48 +++ 6 files changed, 1130 insertions(+), 110 deletions(-) create mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHappyEyeballsTlsFallbackAsync.java diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHappyEyeballsTlsFallbackAsync.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHappyEyeballsTlsFallbackAsync.java new file mode 100644 index 0000000000..c9f3e07dfb --- /dev/null +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHappyEyeballsTlsFallbackAsync.java @@ -0,0 +1,295 @@ +/* + * ==================================================================== + * 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.testing.async; + +import java.io.IOException; +import java.io.InputStream; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.apache.hc.client5.http.DnsResolver; +import org.apache.hc.client5.http.async.methods.SimpleHttpRequest; +import org.apache.hc.client5.http.async.methods.SimpleHttpResponse; +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; +import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManager; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy; +import org.apache.hc.client5.testing.SSLTestContexts; +import org.apache.hc.client5.testing.tls.TlsHandshakeTimeoutServer; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.impl.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap; +import org.apache.hc.core5.io.CloseMode; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.mockito.Mockito; + +/** + * Regression tests for the Happy Eyeballs (RFC 8305) racing path of the async client, against a + * real {@link CloseableHttpAsyncClient}, real local TCP/TLS servers and a real TLS handshake: a + * TLS failure on the address that won the TCP race must still fall back to the remaining, + * untried address, the same as the non-racing (sequential) path and the classic client's + * {@code TestHappyEyeballsTlsFallback} already do. + */ +class TestHappyEyeballsTlsFallbackAsync { + + private HttpServer healthyServer; + private final List tlsRejectProbes = new ArrayList<>(); + private TlsHandshakeTimeoutServer stallingServer; + + @AfterEach + void shutDown() throws IOException { + if (healthyServer != null) { + healthyServer.close(CloseMode.GRACEFUL); + } + for (final ServerSocket probe : tlsRejectProbes) { + probe.close(); + } + if (stallingServer != null) { + stallingServer.close(); + } + } + + /** + * Starts a listener that accepts a TCP connection, reads whatever the client sends (the + * TLS ClientHello), and replies with a plaintext, non-TLS response: the client's TLS engine + * fails the handshake with a genuine {@code SSLException} ("Unrecognized SSL message, got + * plaintext connection?" or similar) once it tries to parse this as a TLS record. Unlike a + * bare TCP reset, this exercises {@code TlsStrategy#upgrade} and its failure path, which is + * what the TLS-fallback scenarios below are named for and must actually fail at. + */ + private ServerSocket startTlsRejectProbe(final String threadName) throws IOException { + final ServerSocket probe = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + tlsRejectProbes.add(probe); + final Thread rejectThread = new Thread(() -> { + while (!probe.isClosed()) { + try (Socket accepted = probe.accept()) { + final byte[] clientHello = new byte[4096]; + accepted.getInputStream().read(clientHello); + accepted.getOutputStream().write( + "not a TLS server\n".getBytes(StandardCharsets.US_ASCII)); + accepted.getOutputStream().flush(); + } catch (final IOException ignore) { + // Expected once the probe socket is closed by the test, and tolerated if + // the client already moved on (e.g. a losing racing attempt cancelled + // first): either way this loop keeps accepting until the probe closes. + } + } + }, threadName); + rejectThread.setDaemon(true); + rejectThread.start(); + return probe; + } + + private HttpServer startHealthyServer() throws Exception { + final HttpServer server = ServerBootstrap.bootstrap() + .setLocalAddress(InetAddress.getLoopbackAddress()) + .setSslContext(SSLTestContexts.createServerSSLContext()) + .register("localhost", "*", (request, response, context) -> response.setCode(HttpStatus.SC_OK)) + .create(); + server.start(); + return server; + } + + private CloseableHttpAsyncClient clientFor(final List remoteAddresses, final boolean happyEyeballs) throws Exception { + return clientFor(remoteAddresses, happyEyeballs, Timeout.ofSeconds(5)); + } + + private CloseableHttpAsyncClient clientFor(final List remoteAddresses, final boolean happyEyeballs, + final Timeout connectAndSocketTimeout) throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses); + final PoolingAsyncClientConnectionManager connMgr = PoolingAsyncClientConnectionManagerBuilder.create() + .setDnsResolver(dnsResolver) + .setDefaultConnectionConfig(ConnectionConfig.custom() + .setConnectTimeout(connectAndSocketTimeout) + .setSocketTimeout(connectAndSocketTimeout) + .build()) + .setTlsStrategy(new DefaultClientTlsStrategy(SSLTestContexts.createClientSSLContext())) + .setHappyEyeballsEnabled(happyEyeballs) + .setConnectionAttemptDelay(TimeValue.ofMilliseconds(50)) + .build(); + final CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create() + .setConnectionManager(connMgr) + .disableAutomaticRetries() + .build(); + client.start(); + return client; + } + + private static void assertServedByHealthyServer(final CloseableHttpAsyncClient client) throws Exception { + final SimpleHttpRequest request = SimpleHttpRequest.create("GET", "https://localhost/"); + final SimpleHttpResponse response = client.execute(request, null).get(); + Assertions.assertEquals(HttpStatus.SC_OK, response.getCode()); + } + + /** + * Scenario 1: TCP accepted, TLS handshake fails immediately (the server accepts the TCP + * connection and replies with a plaintext, non-TLS response to the ClientHello). + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tcpAcceptedTlsFailsImmediately_fallsBackToHealthyAddress(final boolean happyEyeballs) throws Exception { + final int brokenPort = startTlsRejectProbe("tls-reject-probe-async").getLocalPort(); + + healthyServer = startHealthyServer(); + final int healthyPort = healthyServer.getLocalPort(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort), + new InetSocketAddress(InetAddress.getLoopbackAddress(), healthyPort)); + + try (CloseableHttpAsyncClient client = clientFor(remoteAddresses, happyEyeballs)) { + assertServedByHealthyServer(client); + } + } + + /** + * Scenario 2: TCP accepted, TLS handshake stalls until the handshake/connect timeout. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tcpAcceptedTlsStallsUntilTimeout_fallsBackToHealthyAddress(final boolean happyEyeballs) throws Exception { + stallingServer = new TlsHandshakeTimeoutServer(false); + stallingServer.start(); + final int stallingPort = stallingServer.getPort(); + + healthyServer = startHealthyServer(); + final int healthyPort = healthyServer.getLocalPort(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), stallingPort), + new InetSocketAddress(InetAddress.getLoopbackAddress(), healthyPort)); + + try (CloseableHttpAsyncClient client = clientFor(remoteAddresses, happyEyeballs)) { + assertServedByHealthyServer(client); + } + } + + /** + * When every address fails TLS, the final exception must still be reported (no address is + * left silently unreported, and the connection attempt does not hang). + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void allAddressesFailTls_throws(final boolean happyEyeballs) throws Exception { + final int brokenPort1 = startTlsRejectProbe("tls-reject-probe-async-2").getLocalPort(); + final int brokenPort2 = startTlsRejectProbe("tls-reject-probe-async-3").getLocalPort(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort1), + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort2)); + + try (CloseableHttpAsyncClient client = clientFor(remoteAddresses, happyEyeballs)) { + final SimpleHttpRequest request = SimpleHttpRequest.create("GET", "https://localhost/"); + Assertions.assertThrows(ExecutionException.class, () -> client.execute(request, null).get()); + } + } + + /** + * Cancelling after a real TLS failure on one address has triggered fallback to the next + * must reach that next, in-flight attempt: nothing may complete on it afterward. This is + * checked on the SERVER side of the pending attempt, not on the client's response future: + * cancelling a future completes it locally regardless of whether the cancellation actually + * propagated anywhere, so only the pending attempt's own server observing the connection + * being aborted (rather than running to completion) is real proof. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void cancelDuringFallbackAfterRealTlsFailure_abortsPendingAttempt(final boolean happyEyeballs) throws Exception { + final int brokenPort = startTlsRejectProbe("tls-reject-probe-cancel").getLocalPort(); + + try (ServerSocket pending = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + final CountDownLatch pendingAccepted = new CountDownLatch(1); + final CompletableFuture clientGoneAtNanos = new CompletableFuture<>(); + final Thread pendingThread = new Thread(() -> { + try (Socket accepted = pending.accept()) { + pendingAccepted.countDown(); + // Never answers: the handshake, and so this attempt, stays genuinely + // pending until the client goes away, by cancellation or its own timeout. + try { + final InputStream in = accepted.getInputStream(); + final byte[] buf = new byte[4096]; + while (in.read(buf) != -1) { + // Swallow the ClientHello; never respond. + } + } catch (final IOException ignore) { + // The client closed the connection: treated the same as a clean EOF. + } + clientGoneAtNanos.complete(System.nanoTime()); + } catch (final IOException ex) { + clientGoneAtNanos.completeExceptionally(ex); + } + }, "pending-attempt-probe"); + pendingThread.setDaemon(true); + pendingThread.start(); + + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), brokenPort), + new InetSocketAddress(InetAddress.getLoopbackAddress(), pending.getLocalPort())); + + // Long enough that reaching it, instead of being cancelled, is unambiguous. + try (CloseableHttpAsyncClient client = clientFor(remoteAddresses, happyEyeballs, Timeout.ofSeconds(20))) { + final SimpleHttpRequest request = SimpleHttpRequest.create("GET", "https://localhost/"); + final Future responseFuture = client.execute(request, null); + + Assertions.assertTrue(pendingAccepted.await(5, TimeUnit.SECONDS), + "fallback attempt never reached the pending address"); + Assertions.assertFalse(responseFuture.isDone()); + Assertions.assertTrue(responseFuture.cancel(true)); + + // If cancellation reached the pending attempt, its server sees the client gone + // (EOF or reset) within a couple of seconds; if it was lost, the server keeps + // waiting on it until the 20-second connect timeout above elapses instead. + try { + clientGoneAtNanos.get(2, TimeUnit.SECONDS); + } catch (final TimeoutException ex) { + Assertions.fail("pending attempt still open on the server 2 s after cancel(): " + + "cancellation was lost"); + } + } + } + } +} diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimalTlsHandshake.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimalTlsHandshake.java index 50c7cfb57d..8915c39f07 100644 --- a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimalTlsHandshake.java +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/async/TestHttpAsyncMinimalTlsHandshake.java @@ -70,7 +70,14 @@ void testSuccessfulTlsHandshake() throws Exception { @Test void testTlsHandshakeFailure() throws Exception { - final HttpHost target = startServer(); + // "localhost" can resolve to more than one address (127.0.0.1 and ::1); the server + // only listens on one of them. Since a TLS failure is no longer necessarily final for + // a request's last attempted address (the client now falls back to any other resolved + // address, the same way a TCP-level failure always has), resolving to an address the + // server isn't listening on would mask the TLS failure this test means to assert with + // an unrelated connection-refused error. A single literal address has only one. + final HttpHost serverHost = startServer(); + final HttpHost target = new HttpHost(serverHost.getSchemeName(), "127.0.0.1", serverHost.getPort()); configureClient(builder -> builder.setTlsStrategy(new DefaultClientTlsStrategy(SSLContexts.createDefault()))); 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 6bf559f4d6..aa9187dec1 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 @@ -33,6 +33,8 @@ import java.net.SocketAddress; import java.nio.file.Path; import java.util.concurrent.Future; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicReference; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.SchemePortResolver; @@ -45,10 +47,10 @@ import org.apache.hc.client5.http.routing.RoutingSupport; import org.apache.hc.core5.annotation.Internal; import org.apache.hc.core5.concurrent.CallbackContribution; +import org.apache.hc.core5.concurrent.Cancellable; import org.apache.hc.core5.concurrent.ComplexCancellable; import org.apache.hc.core5.concurrent.ComplexFuture; import org.apache.hc.core5.concurrent.FutureCallback; -import org.apache.hc.core5.concurrent.FutureContribution; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.URIScheme; import org.apache.hc.core5.http.config.Lookup; @@ -159,10 +161,31 @@ public Future connect( LOG.debug("{} connecting {}->{} ({})", endpointHost, localAddress, remoteAddress, connectTimeout); } + // Holds the connection produced by whichever attempt the session requester ultimately + // accepts: with Happy Eyeballs racing or multiple resolved addresses, the validator + // below may run more than once, against a different session each time, before one is + // accepted. + final AtomicReference acceptedConnection = new AtomicReference<>(); + // The session request may complete before connect returns, and its callback can register the // TLS handshake with the future. Install a holder first so the session request cannot replace it. final ComplexCancellable sessionCancellable = new ComplexCancellable(); future.setDependency(sessionCancellable); + // sessionFuture does not exist yet at the point the validator below is built, since it is + // itself an argument of the call that creates it; cancelSessionFuture is the one stable + // reference the validator can capture, resolved through this holder once connect() returns. + final AtomicReference> sessionFutureRef = new AtomicReference<>(); + final Cancellable cancelSessionFuture = () -> { + final Future sf = sessionFutureRef.get(); + return sf != null && sf.cancel(true); + }; + // Set before connect() is called, not only after: a mocked or otherwise synchronous + // ConnectionInitiator can invoke the validator below before connect() returns, which + // would already have moved sessionCancellable's dependency on to "close this + // connection" by the time connect() returns. Only the validator itself is ever + // allowed to move the dependency again after this, so whichever runs first always + // wins and nothing here clobbers it back. + sessionCancellable.setDependency(cancelSessionFuture); final Future sessionFuture = sessionRequester.connect( connectionInitiator, remoteEndpoint, @@ -170,56 +193,109 @@ public Future connect( localAddress, connectTimeout, tlsConfig.getHttpVersionPolicy(), - new FutureCallback() { + (session, validated) -> { + // Validates a connected session before the requester accepts it as final: + // on a TLS failure here, the requester tries the next address, if one + // remains, instead of this method surfacing a connected but unusable + // session. See MultihomeIOSessionRequester.SessionValidator. + final DefaultManagedAsyncClientConnection connection = new DefaultManagedAsyncClientConnection(session); + onAfterSocketConnect(context, endpointHost); + if (LOG.isDebugEnabled()) { + LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(connection), endpointHost, + connection.getLocalAddress(), connection.getRemoteAddress()); + } + final TlsStrategy tlsStrategy = tlsStrategyLookup != null ? tlsStrategyLookup.lookup(endpointHost.getSchemeName()) : null; + if (tlsStrategy != null) { + // Guards against a TlsStrategy that, in violation of its contract, + // reports an outcome through the callback below and then also throws + // out of #upgrade (the catch block below): only the first of the two + // is ever reported, and the second is a safe no-op rather than a + // double-advance of the session requester's fallback. + final AtomicBoolean settled = new AtomicBoolean(); + try { + final Timeout socketTimeout = connection.getSocketTimeout(); + final Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout() != null ? tlsConfig.getHandshakeTimeout() : connectTimeout; + final NamedEndpoint tlsName = endpointName != null ? endpointName : endpointHost; + // The session request for this specific attempt is already done, so + // cancelling it would not stop the handshake: track closing this + // connection instead, for as long as this attempt is the one in + // flight. On rejection below, tracking reverts to sessionFuture, + // which the requester may still be using to try another address. + sessionCancellable.setDependency(() -> { + connection.close(CloseMode.IMMEDIATE); + return true; + }); + onBeforeTlsHandshake(context, endpointHost); + if (LOG.isDebugEnabled()) { + LOG.debug("{} {} upgrading to TLS", ConnPoolSupport.getId(connection), tlsName); + } + tlsStrategy.upgrade( + connection, + tlsName, + attachment, + handshakeTimeout, + new FutureCallback() { - @Override - public void completed(final IOSession session) { - final DefaultManagedAsyncClientConnection connection = new DefaultManagedAsyncClientConnection(session); - onAfterSocketConnect(context, endpointHost); - if (LOG.isDebugEnabled()) { - LOG.debug("{} {} connected {}->{}", ConnPoolSupport.getId(connection), endpointHost, - connection.getLocalAddress(), connection.getRemoteAddress()); - } - final TlsStrategy tlsStrategy = tlsStrategyLookup != null ? tlsStrategyLookup.lookup(endpointHost.getSchemeName()) : null; - if (tlsStrategy != null) { - try { - final Timeout socketTimeout = connection.getSocketTimeout(); - final Timeout handshakeTimeout = tlsConfig.getHandshakeTimeout() != null ? tlsConfig.getHandshakeTimeout() : connectTimeout; - final NamedEndpoint tlsName = endpointName != null ? endpointName : endpointHost; - // The session request is already done, so cancelling it would not stop - // the handshake. Close the connection instead. - future.setDependency(() -> { - connection.close(CloseMode.IMMEDIATE); - return true; - }); - onBeforeTlsHandshake(context, endpointHost); - if (LOG.isDebugEnabled()) { - LOG.debug("{} {} upgrading to TLS", ConnPoolSupport.getId(connection), tlsName); - } - tlsStrategy.upgrade( - connection, - tlsName, - attachment, - handshakeTimeout, - new FutureContribution(future) { - - @Override - public void completed(final TransportSecurityLayer transportSecurityLayer) { - connection.setSocketTimeout(socketTimeout); - future.completed(connection); - onAfterTlsHandshake(context, endpointHost); - if (LOG.isDebugEnabled()) { - LOG.debug("{} {} upgraded to TLS", ConnPoolSupport.getId(connection), tlsName); - } + @Override + public void completed(final TransportSecurityLayer transportSecurityLayer) { + if (!settled.compareAndSet(false, true)) { + return; } + // Report the result before invoking the hook below, so a hook + // that throws can never orphan a result that has already been + // accepted. + connection.setSocketTimeout(socketTimeout); + acceptedConnection.set(connection); + validated.completed(session); + onAfterTlsHandshake(context, endpointHost); + if (LOG.isDebugEnabled()) { + LOG.debug("{} {} upgraded to TLS", ConnPoolSupport.getId(connection), tlsName); + } + } - }); - } catch (final Exception ex) { - future.failed(ex); + @Override + public void failed(final Exception ex) { + if (!settled.compareAndSet(false, true)) { + return; + } + sessionCancellable.setDependency(cancelSessionFuture); + validated.failed(ex); + } + + @Override + public void cancelled() { + if (!settled.compareAndSet(false, true)) { + return; + } + // Unlike #failed, a cancellation is always terminal: + // the session requester's own future is already + // being cancelled by this same call chain (through + // #validated, below), which also cancels the outer + // future that depends on it, so there is no later + // attempt for sessionCancellable to be redirected to. + validated.cancelled(); + } + + }); + } catch (final Exception ex) { + if (!settled.compareAndSet(false, true)) { + return; } - } else { - future.completed(connection); + sessionCancellable.setDependency(cancelSessionFuture); + validated.failed(ex); } + } else { + acceptedConnection.set(connection); + validated.completed(session); + } + }, + new FutureCallback() { + + @Override + public void completed(final IOSession session) { + // The validator above has already built and TLS-upgraded, if + // configured, the connection for whichever attempt was accepted. + future.completed(acceptedConnection.get()); } @Override @@ -233,7 +309,9 @@ public void cancelled() { } }); - sessionCancellable.setDependency(() -> sessionFuture.cancel(true)); + // Only resolves what cancelSessionFuture cancels; does not itself move + // sessionCancellable's dependency, which the validator may already have moved on. + sessionFutureRef.set(sessionFuture); return future; } 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 58c80cb13a..b703c6436f 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 @@ -41,6 +41,8 @@ import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.ReentrantLock; +import java.util.function.Consumer; import org.apache.hc.client5.http.ConnectExceptionSupport; import org.apache.hc.client5.http.DnsResolver; @@ -131,6 +133,27 @@ public Future connect( final Timeout connectTimeout, final Object attachment, final FutureCallback callback) { + return connect(connectionInitiator, remoteEndpoint, remoteAddress, localAddress, connectTimeout, attachment, null, callback); + } + + /** + * Same as {@link #connect(ConnectionInitiator, NamedEndpoint, SocketAddress, SocketAddress, + * Timeout, Object, FutureCallback)}, but every session this call connects is first passed to + * {@code validator}, if one is given, before being reported as the final outcome. + * + * @param validator accepts or rejects a freshly connected session; may be {@code null} to + * accept every connected session unconditionally, as the overload without + * this parameter does. + */ + Future connect( + final ConnectionInitiator connectionInitiator, + final NamedEndpoint remoteEndpoint, + final SocketAddress remoteAddress, + final SocketAddress localAddress, + final Timeout connectTimeout, + final Object attachment, + final SessionValidator validator, + final FutureCallback callback) { final ComplexFuture future = new ComplexFuture<>(callback); if (remoteAddress != null) { @@ -141,7 +164,12 @@ public Future connect( final Future sessionFuture = connectionInitiator.connect(remoteEndpoint, remoteAddress, localAddress, connectTimeout, attachment, new FutureCallback() { @Override public void completed(final IOSession session) { - future.completed(session); + acceptOrReject(session, validator, future, + // A single, explicitly given address has no fallback to offer. + cause -> enhanceAndFail(future, remoteEndpoint, cause, + (remoteAddress instanceof InetSocketAddress) ? + new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } : + new InetAddress[] {})); } @Override @@ -150,14 +178,10 @@ public void failed(final Exception cause) { LOG.debug("{}:{} connection to {} failed ({}); terminating operation", remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); } - if (cause instanceof IOException) { - future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, - (remoteAddress instanceof InetSocketAddress) ? - new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } : - new InetAddress[] {})); - } else { - future.failed(cause); - } + enhanceAndFail(future, remoteEndpoint, cause, + (remoteAddress instanceof InetSocketAddress) ? + new InetAddress[] { ((InetSocketAddress) remoteAddress).getAddress() } : + new InetAddress[] {}); } @Override @@ -191,16 +215,153 @@ public void cancelled() { if (happyEyeballsEnabled && remoteAddresses.size() > 1) { final Race race = new Race(connectionInitiator, remoteEndpoint, remoteAddresses, localAddress, - connectTimeout, attachment, future); + connectTimeout, attachment, validator, future); race.start(); return future; } + connectSequentially(connectionInitiator, remoteEndpoint, remoteAddresses, localAddress, + connectTimeout, attachment, validator, future); + return future; + } + + public Future connect( + final ConnectionInitiator connectionInitiator, + final NamedEndpoint remoteEndpoint, + final SocketAddress localAddress, + final Timeout connectTimeout, + final Object attachment, + final FutureCallback callback) { + return connect(connectionInitiator, remoteEndpoint, null, localAddress, connectTimeout, attachment, null, callback); + } + + /** + * Accepts or rejects a session that has just connected, before {@link #connect} reports it + * as the final outcome. A rejected session is closed, and {@link #connect} tries the next + * address, if one remains, rather than surfacing a connected session that failed a check + * layered on top of the raw connection (for example a TLS handshake) as a successful + * outcome. Within a race, a rejection ends racing rather than continuing it: the remaining + * addresses, if any, are tried sequentially (see {@link Race#onWinnerRejected}). + * + *

The exception type reported to the final {@code callback} on rejection is not + * necessarily the one this validator reported: a rejection that exhausts every address is + * folded in with ordinary connect failures through {@link + * org.apache.hc.client5.http.ConnectExceptionSupport#enhance}, which can, for example, + * remap a timeout into {@code ConnectTimeoutException} regardless of whether the timeout + * happened during the TCP connect or a validator check afterward.

+ */ + @FunctionalInterface + interface SessionValidator { + void validate(IOSession session, FutureCallback callback); + } + + private static void enhanceAndFail( + final ComplexFuture future, + final NamedEndpoint remoteEndpoint, + final Exception cause, + final InetAddress[] addresses) { + if (cause instanceof IOException) { + future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses)); + } else { + future.failed(cause); + } + } + + /** + * Runs {@code validator} against a freshly connected {@code session}, if one is given; + * otherwise accepts the session unconditionally. On rejection, closes the session and + * invokes {@code onRejected} with the rejection cause so the caller can fall back to + * another address, or fail outright if none remains. + */ + private static void acceptOrReject( + final IOSession session, + final SessionValidator validator, + final ComplexFuture future, + final Consumer onRejected) { + if (validator == null) { + deliver(session, future); + return; + } + validator.validate(session, new FutureCallback() { + @Override + public void completed(final IOSession validatedSession) { + deliver(validatedSession, future); + } + + @Override + public void failed(final Exception cause) { + session.close(CloseMode.IMMEDIATE); + onRejected.accept(cause); + } + + @Override + public void cancelled() { + session.close(CloseMode.IMMEDIATE); + future.cancel(); + } + }); + } + + /** + * Completes {@code future} with {@code session}, unless it was already completed or + * cancelled by something else (for example the caller, concurrently) in the brief window + * before this call: {@link ComplexFuture#completed} reports that by returning {@code false}, + * in which case the session must still be closed here rather than silently leaked. + */ + private static void deliver(final IOSession session, final ComplexFuture future) { + if (!future.completed(session)) { + session.close(CloseMode.IMMEDIATE); + } + } + + /** + * Connects to each of {@code remoteAddresses} in turn, stopping at the first one that + * completes both the TCP connection and, where {@code validator} is given, its check. A + * TCP-level failure or a validator rejection moves on to the next address; the last + * address's failure is reported via {@code future}, enhanced via + * {@link ConnectExceptionSupport}. + */ + private void connectSequentially( + final ConnectionInitiator connectionInitiator, + final NamedEndpoint remoteEndpoint, + final List remoteAddresses, + final SocketAddress localAddress, + final Timeout connectTimeout, + final Object attachment, + final SessionValidator validator, + final ComplexFuture future) { + final Runnable runnable = new Runnable() { private final AtomicInteger attempt = new AtomicInteger(0); + // Guards the body of executeNext() against a different thread concurrently + // rejecting the same attempt and recursing into executeNext() for the next one: an + // unguarded reader could otherwise observe this attempt's index as still current + // and set future's dependency back to its (already superseded) session future, + // losing track of the one the other thread already started. A same-thread, + // reentrant rejection (recursing into the next attempt before this call returns) + // needs no locking to stay correct: it is covered instead by the attempt-index + // check at the end of this method, since ReentrantLock already permits the + // recursive re-entry on the same thread regardless. + private final ReentrantLock lock = new ReentrantLock(); + void executeNext() { + lock.lock(); + try { + executeNextLocked(); + } finally { + lock.unlock(); + } + } + + private void executeNextLocked() { + if (future.isDone()) { + // The caller already cancelled, or the operation otherwise already + // completed; starting another attempt now would only leak a connection + // nobody will ever use. + return; + } final int index = attempt.getAndIncrement(); final InetSocketAddress remoteAddress = remoteAddresses.get(index); @@ -223,32 +384,12 @@ public void completed(final IOSession session) { LOG.debug("{}:{} connected {}->{} as {}", remoteEndpoint.getHostName(), remoteEndpoint.getPort(), localAddress, remoteAddress, session.getId()); } - future.completed(session); + acceptOrReject(session, validator, future, cause -> onFailure(remoteAddress, cause)); } @Override public void failed(final Exception cause) { - if (attempt.get() >= remoteAddresses.size()) { - if (LOG.isDebugEnabled()) { - LOG.debug("{}:{} connection to {} failed ({}); terminating operation", - remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); - } - if (cause instanceof IOException) { - final InetAddress[] addresses = remoteAddresses.stream() - .filter(addr -> addr instanceof InetSocketAddress) - .map(addr -> ((InetSocketAddress) addr).getAddress()) - .toArray(InetAddress[]::new); - future.failed(ConnectExceptionSupport.enhance((IOException) cause, remoteEndpoint, addresses)); - } else { - future.failed(cause); - } - } else { - if (LOG.isDebugEnabled()) { - LOG.debug("{}:{} connection to {} failed ({}); retrying connection to the next address", - remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); - } - executeNext(); - } + onFailure(remoteAddress, cause); } @Override @@ -257,7 +398,43 @@ public void cancelled() { } }); - future.setDependency(sessionFuture); + // A same-thread, reentrant rejection above can already have recursed into + // executeNext() for the next attempt and set future's dependency to it before + // this line runs; only apply this (now stale) assignment if no later attempt + // has started in the meantime. + if (attempt.get() == index + 1) { + // ComplexFuture#setDependency checks isDone() and then sets the dependency + // as two separate steps, which can still interleave with a concurrent + // #cancel() between them; a cancellation landing in that narrow window is + // lost. Closing it needs a change to ComplexFuture itself. + future.setDependency(sessionFuture); + } + } + + private void onFailure(final InetSocketAddress remoteAddress, final Exception cause) { + if (future.isDone()) { + // The caller already cancelled, or the operation otherwise already + // completed; starting another attempt now would only leak a connection + // nobody will ever use. + return; + } + if (attempt.get() >= remoteAddresses.size()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{}:{} connection to {} failed ({}); terminating operation", + remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); + } + final InetAddress[] addresses = remoteAddresses.stream() + .filter(addr -> addr instanceof InetSocketAddress) + .map(addr -> ((InetSocketAddress) addr).getAddress()) + .toArray(InetAddress[]::new); + enhanceAndFail(future, remoteEndpoint, cause, addresses); + } else { + if (LOG.isDebugEnabled()) { + LOG.debug("{}:{} connection to {} failed ({}); retrying connection to the next address", + remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); + } + executeNext(); + } } @Override @@ -267,17 +444,6 @@ public void run() { }; runnable.run(); - return future; - } - - public Future connect( - final ConnectionInitiator connectionInitiator, - final NamedEndpoint remoteEndpoint, - final SocketAddress localAddress, - final Timeout connectTimeout, - final Object attachment, - final FutureCallback callback) { - return connect(connectionInitiator, remoteEndpoint, null, localAddress, connectTimeout, attachment, callback); } /** @@ -297,9 +463,10 @@ private final class Race implements Cancellable { private final SocketAddress localAddress; private final Timeout connectTimeout; private final Object attachment; + private final SessionValidator validator; private final ComplexFuture future; - private final Object lock = new Object(); + private final ReentrantLock lock = new ReentrantLock(); private final List> inFlight = new ArrayList<>(); private int nextIndex; private int outstanding; @@ -315,6 +482,7 @@ private final class Race implements Cancellable { final SocketAddress localAddress, final Timeout connectTimeout, final Object attachment, + final SessionValidator validator, final ComplexFuture future) { this.connectionInitiator = connectionInitiator; this.remoteEndpoint = remoteEndpoint; @@ -322,6 +490,7 @@ private final class Race implements Cancellable { this.localAddress = localAddress; this.connectTimeout = connectTimeout; this.attachment = attachment; + this.validator = validator; 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()). @@ -329,8 +498,11 @@ private final class Race implements Cancellable { } void start() { - synchronized (lock) { + lock.lock(); + try { scheduleNextPromptlyLocked(); + } finally { + lock.unlock(); } } @@ -412,16 +584,20 @@ public void cancelled() { } private void onStaggerElapsed() { - synchronized (lock) { + lock.lock(); + try { pendingStagger = null; startNextLocked(); + } finally { + lock.unlock(); } } private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOSession session) { final boolean won; final List> losers; - synchronized (lock) { + lock.lock(); + try { outstanding--; won = !decided && !cancelled; if (won) { @@ -431,6 +607,8 @@ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOS } else { losers = null; } + } finally { + lock.unlock(); } if (won) { if (LOG.isDebugEnabled()) { @@ -440,17 +618,7 @@ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOS 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); - } + acceptOrReject(session, validator, future, cause -> onWinnerRejected(remoteAddress, cause)); } else { // A duplicate winner (concurrent success) or a late completion after the // race was already decided/cancelled: never leak the socket. @@ -462,10 +630,38 @@ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOS } } + /** + * The address that won the TCP race failed {@link #validator}'s check (for example, a + * TLS handshake layered on top of it). Racing is over by this point: every other + * in-flight attempt was already cancelled when the winner was decided, and any address + * not yet attempted is simply never tried, so the remaining addresses, if any, are + * tried sequentially, exactly as the base non-racing path tries its addresses: the + * reliability this race was built to provide now comes from trying every address, not + * from trying several of them at once. + */ + private void onWinnerRejected(final InetSocketAddress winnerAddress, final Exception cause) { + final List remaining = withoutAddress(remoteAddresses, winnerAddress); + if (remaining.isEmpty()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{}:{} connection to {} failed validation after racing ({}); no address remains", + remoteEndpoint.getHostName(), remoteEndpoint.getPort(), winnerAddress, cause.getClass()); + } + enhanceAndFail(future, remoteEndpoint, cause, new InetAddress[] { winnerAddress.getAddress() }); + return; + } + if (LOG.isDebugEnabled()) { + LOG.debug("{}:{} connection to {} failed validation after racing ({}); retrying connection to the remaining address(es)", + remoteEndpoint.getHostName(), remoteEndpoint.getPort(), winnerAddress, cause.getClass()); + } + connectSequentially(connectionInitiator, remoteEndpoint, remaining, localAddress, + connectTimeout, attachment, validator, future); + } + private void onAttemptFailed(final InetSocketAddress remoteAddress, final Exception cause) { boolean advance = false; boolean last = false; - synchronized (lock) { + lock.lock(); + try { outstanding--; if (decided || cancelled) { return; @@ -483,6 +679,8 @@ private void onAttemptFailed(final InetSocketAddress remoteAddress, final Except // but still respecting the minimum inter-attempt spacing. scheduleNextPromptlyLocked(); } + } finally { + lock.unlock(); } if (last) { if (LOG.isDebugEnabled()) { @@ -503,7 +701,8 @@ private void onAttemptFailed(final InetSocketAddress remoteAddress, final Except private void onAttemptCancelled(final InetSocketAddress remoteAddress) { boolean advance = false; boolean last = false; - synchronized (lock) { + lock.lock(); + try { outstanding--; if (decided || cancelled) { // Expected: either this race decided a winner and cancelled every other @@ -520,6 +719,8 @@ private void onAttemptCancelled(final InetSocketAddress remoteAddress) { if (advance) { scheduleNextPromptlyLocked(); } + } finally { + lock.unlock(); } if (last) { if (LOG.isDebugEnabled()) { @@ -545,13 +746,16 @@ private void finish(final Exception cause) { @Override public boolean cancel() { final List> toCancel; - synchronized (lock) { + lock.lock(); + try { if (decided || cancelled) { return false; } cancelled = true; cancelPendingStaggerLocked(); toCancel = new ArrayList<>(inFlight); + } finally { + lock.unlock(); } for (final Future attemptFuture : toCancel) { attemptFuture.cancel(true); @@ -569,4 +773,22 @@ private void cancelPendingStaggerLocked() { } + /** + * 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; + } + } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java index 20c065e6ec..774810e5ef 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java @@ -26,22 +26,36 @@ */ 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.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.util.Arrays; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLHandshakeException; + +import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.nio.ManagedAsyncClientConnection; import org.apache.hc.core5.concurrent.FutureCallback; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.config.RegistryBuilder; 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.reactor.ConnectionInitiator; import org.apache.hc.core5.reactor.IOSession; +import org.apache.hc.core5.reactor.ssl.TransportSecurityLayer; +import org.apache.hc.core5.util.TimeValue; import org.apache.hc.core5.util.Timeout; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.Mockito; class DefaultAsyncClientConnectionOperatorTest { @@ -71,4 +85,360 @@ void testCancelDuringTlsHandshakeClosesSession() throws Exception { Mockito.verify(ioSession).close(CloseMode.IMMEDIATE); } + /** + * A hook that throws after the TLS handshake succeeds must not be able to orphan an + * already-accepted result: the result is reported before the hook runs, so an exception + * there can only ever be lost noise, never a future that hangs forever, and never a reason + * to close the session that was already delivered to the caller. + */ + @Test + void testHookThrowingAfterSuccessDoesNotHangFuture() throws Exception { + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + Mockito.doAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(4); + callback.completed(Mockito.mock(TransportSecurityLayer.class)); + return null; + }).when(tlsStrategy).upgrade(any(), any(), any(), any(), any()); + + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, null) { + @Override + protected void onAfterTlsHandshake(final HttpContext context, final HttpHost endpointHost) { + throw new IllegalStateException("broken onAfterTlsHandshake hook"); + } + }; + + final IOSession ioSession = Mockito.mock(IOSession.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(5); + callback.completed(ioSession); + return CompletableFuture.completedFuture(ioSession); + }); + + final HttpHost target = new HttpHost("https", InetAddress.getLoopbackAddress(), "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + // Bounded wait: if the hook's exception re-orphans the result, this times out instead + // of hanging the test suite indefinitely, making a regression fail fast and visibly. + final ManagedAsyncClientConnection connection = future.get(5, TimeUnit.SECONDS); + assertNotNull(connection); + Mockito.verify(ioSession, Mockito.never()).close(any(CloseMode.class)); + } + + /** + * Once a TLS validator rejects the address that connected first and the session requester + * falls back to the next address, the outer connect() future must still be able to cancel + * that in-flight fallback attempt. + * Before the fix, the TLS handshake setup replaced the outer future's dependency with + * "close this one connection", permanently detaching it from the session requester, so a + * cancellation issued after the fallback started was silently lost. + */ + @Test + void testCancelDuringFallbackAfterTlsRejectionCancelsNextAttempt() throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver); + + final IOSession firstSession = Mockito.mock(IOSession.class); + @SuppressWarnings("unchecked") + final Future secondAttempt = Mockito.mock(Future.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + // Address #1 connects at the TCP level immediately. + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }) + .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test. + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + // Reject address #1's TLS handshake, triggering fallback to address #2. + @SuppressWarnings("unchecked") + final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); + Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture()); + tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("untrusted certificate")); + Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any()); + + // Address #2 is now the in-flight fallback attempt; cancelling here must reach it. + future.cancel(true); + Mockito.verify(secondAttempt).cancel(true); + } + + /** + * A TLS handshake that is itself cancelled (as opposed to one that fails a check) must be + * propagated as a cancellation, not folded into the same "rejected, try the next address" + * path a validation failure takes: there is no reason to attempt another address after the + * caller's own cancellation. + */ + @Test + void testTlsHandshakeCancellationDoesNotFallBackToNextAddress() throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver); + + final IOSession firstSession = Mockito.mock(IOSession.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }); + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + @SuppressWarnings("unchecked") + final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); + Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture()); + tlsCallbackCaptor.getValue().cancelled(); + + Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any()); + assertTrue(future.isCancelled()); + } + + /** + * Cancelling before the first address's TLS validation ever begins must still reach that + * first, in-flight TCP connect attempt. The dependency tracking this relies on is set + * before {@code sessionRequester.connect(...)} is called, not only after it returns, since + * a synchronous {@link ConnectionInitiator} can otherwise invoke the TLS validator, and + * move tracking on to a later stage, before this method's own call returns. + */ + @Test + void testCancelDuringFirstConnectAttemptReachesIt() throws Exception { + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, null); + + @SuppressWarnings("unchecked") + final Future firstAttempt = Mockito.mock(Future.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> firstAttempt); // Never calls back: the connect itself is still pending. + + final HttpHost target = new HttpHost("https", InetAddress.getLoopbackAddress(), "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + future.cancel(true); + Mockito.verify(firstAttempt).cancel(true); + Mockito.verify(tlsStrategy, Mockito.never()).upgrade(any(), any(), any(), any(), any()); + } + + /** + * A {@link TlsStrategy} that reports failure through its callback and then also throws + * out of {@code upgrade()} violates its contract, but must not be allowed to advance the + * session requester's fallback twice for what the caller only sees as one failed attempt. + * Three addresses are needed to observe a double-advance as an extra connect() call: with + * only two, a second, spurious advance lands past the end of the address list and is + * absorbed as ordinary exhaustion instead, masking the bug. + */ + @Test + void testTlsStrategyFailingThenThrowingAdvancesFallbackOnlyOnce() throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + final InetSocketAddress address3 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 3}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2, address3)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + Mockito.doAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(4); + callback.failed(new SSLHandshakeException("untrusted certificate")); + throw new IllegalStateException("broken TlsStrategy: throws after reporting failure"); + }).when(tlsStrategy).upgrade(any(), any(), any(), any(), any()); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver); + + @SuppressWarnings("unchecked") + final Future secondAttempt = Mockito.mock(Future.class); + @SuppressWarnings("unchecked") + final Future thirdAttempt = Mockito.mock(Future.class); + final IOSession firstSession = Mockito.mock(IOSession.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + // Address #1: connects, then rejected twice by the broken strategy above. + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }) + .thenAnswer(invocation -> secondAttempt) // Address #2: the correct, single fallback target. + .thenAnswer(invocation -> thirdAttempt); // Address #3: must never be reached. + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + // One address rejected (reported twice by the broken strategy) still falls back to + // exactly the next address, not two addresses further. + Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any()); + assertFalse(future.isDone()); + } + + /** + * A {@link TlsStrategy} that throws out of {@code upgrade()} without ever invoking its + * callback must still be treated as a rejection of that address: the catch block is the + * only thing that reports this failure, and must both fall back to the next address and + * leave cancellation tracking pointed at it. + */ + @Test + void testTlsStrategyThrowingWithoutCallbackFallsBackAndStaysCancellable() throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + Mockito.doThrow(new IllegalStateException("synchronous upgrade failure")) + .when(tlsStrategy).upgrade(any(), any(), any(), any(), any()); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver); + + final IOSession firstSession = Mockito.mock(IOSession.class); + @SuppressWarnings("unchecked") + final Future secondAttempt = Mockito.mock(Future.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }) + .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test. + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any()); + future.cancel(true); + Mockito.verify(secondAttempt).cancel(true); + } + + /** + * The same TLS-rejection fallback must also work after Happy Eyeballs racing decides a + * winner, not only on the plain sequential (non-racing) path: {@link + * MultihomeIOSessionRequester.Race#onWinnerRejected} falls back by calling the same + * sequential machinery the other tests in this class exercise directly. + */ + @Test + void testCancelDuringFallbackAfterRacingWinnerTlsRejectionCancelsNextAttempt() throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver, + true, TimeValue.ofMilliseconds(250)); + + final IOSession firstSession = Mockito.mock(IOSession.class); + @SuppressWarnings("unchecked") + final Future secondAttempt = Mockito.mock(Future.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + // Address #1 wins the race immediately: it is the only attempt racing + // ever starts, since it completes before address #2's stagger delay + // would even be scheduled. + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }) + .thenAnswer(invocation -> secondAttempt); // Address #2's TCP connect never resolves in this test. + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + // Reject the racing winner's TLS handshake, triggering fallback to address #2. + @SuppressWarnings("unchecked") + final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); + Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture()); + tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("untrusted certificate")); + Mockito.verify(connectionInitiator, Mockito.times(2)).connect(any(), any(), any(), any(), any(), any()); + + // Address #2 is now the in-flight fallback attempt; cancelling here must reach it. + future.cancel(true); + Mockito.verify(secondAttempt).cancel(true); + } + + /** + * Cancelling while the winning address's TLS handshake is still pending, before the + * strategy reports any outcome at all, must stop the overall operation outright: once the + * strategy later reports the handshake failed (because the connection it was using was + * just closed), no new attempt against the next address must start. + * + *

With racing enabled, {@code Race.onWinnerRejected()} calls {@code executeNext()} + * directly, so this variant is what exercises the {@code isDone()} guard at the top of + * that method. Without racing, the sequential path reaches {@code onFailure()} first, + * whose own {@code isDone()} guard is what stops it there; this variant does not, on its + * own, exercise the top-of-{@code executeNext()} guard. + */ + private int cancelDuringHandshakeThenReportedFailed(final boolean happyEyeballs) throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver, + happyEyeballs, TimeValue.ofMilliseconds(250)); + + final IOSession firstSession = Mockito.mock(IOSession.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }); + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + @SuppressWarnings("unchecked") + final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); + Mockito.verify(tlsStrategy).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture()); + + future.cancel(true); + assertTrue(future.isCancelled()); + // Only now does the strategy learn the handshake failed, because the cancellation + // above closed the connection it was using. + tlsCallbackCaptor.getValue().failed(new SSLHandshakeException("connection closed")); + return Mockito.mockingDetails(connectionInitiator).getInvocations().size(); + } + + @Test + void testCancelDuringHandshakeDoesNotStartNewAttemptSequential() throws Exception { + assertEquals(1, cancelDuringHandshakeThenReportedFailed(false)); + } + + @Test + void testCancelDuringHandshakeDoesNotStartNewAttemptRacing() throws Exception { + assertEquals(1, cancelDuringHandshakeThenReportedFailed(true)); + } + } 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 3997b2ee21..d8284eb94a 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 @@ -54,6 +54,7 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import org.apache.hc.client5.http.DnsResolver; @@ -175,6 +176,53 @@ void testConnectSuccessfulAfterRetries() throws Exception { } } + /** + * A {@link ConnectionInitiator} whose {@code connect()} for one address invokes its + * callback synchronously, before returning, can make the sequential fallback path + * recurse into the next attempt from inside that same call: the next attempt's own + * dependency assignment must survive the original call unwinding afterward, rather than + * being overwritten back to the (now finished) attempt that triggered it. + */ + @Test + void testCancelAfterSynchronousFailureReachesNextAttempt() throws Exception { + final InetAddress address1 = InetAddress.getByAddress(new byte[]{10, 0, 0, 1}); + final InetAddress address2 = InetAddress.getByAddress(new byte[]{10, 0, 0, 2}); + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(address1, 8080), + new InetSocketAddress(address2, 8080)); + + Mockito.when(namedEndpoint.getHostName()).thenReturn("somehost"); + Mockito.when(namedEndpoint.getPort()).thenReturn(8080); + Mockito.when(dnsResolver.resolve("somehost", 8080)).thenReturn(remoteAddresses); + + final AtomicBoolean secondAttemptCancelled = new AtomicBoolean(); + final CompletableFuture secondAttemptFuture = new CompletableFuture() { + @Override + public boolean cancel(final boolean mayInterruptIfRunning) { + secondAttemptCancelled.set(true); + return super.cancel(mayInterruptIfRunning); + } + }; + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + // Address 1 fails synchronously, inline, inside this very call: the + // fallback to address 2 below runs, and returns, before this call does. + final FutureCallback callback = invocation.getArgument(5); + final CompletableFuture future = new CompletableFuture<>(); + callback.failed(new IOException("connection refused")); + future.completeExceptionally(new IOException("connection refused")); + return future; + }) + .thenAnswer(invocation -> secondAttemptFuture); // Address 2: left pending. + + final Future future = sessionRequester.connect( + connectionInitiator, namedEndpoint, null, Timeout.ofSeconds(30), null, null); + + future.cancel(true); + assertTrue(secondAttemptCancelled.get(), + "cancellation did not reach the in-flight second attempt"); + } + // ------------------------------------------------------------------------- // RFC 8305 connection racing (Happy Eyeballs v2) // ------------------------------------------------------------------------- From 784824349d27279efbfae68661539e47a4af2685 Mon Sep 17 00:00:00 2001 From: abdelrahman mohamed Date: Tue, 1 Dec 2026 22:50:05 +0200 Subject: [PATCH 14/15] Stop trying other addresses when the peer's certificate is rejected A TLS failure on one resolved address made both transports try the next one, whatever the cause. When the peer's certificate is untrusted or does not match the host name, every address of the host presents the same certificate, so the remaining attempts can only fail the same way and just add a handshake timeout or round trip each. Treat such a failure as final in both the classic and the async transport, with or without Happy Eyeballs racing: the handshake fails with a CertificateException or an SSLPeerUnverifiedException anywhere in its cause chain. Any other IOException, including a handshake timeout, a connection reset, the peer closing mid-handshake or a TLS alert, still moves on to the next address, since those cannot be told apart from a transient failure by type and may well succeed elsewhere. The check lives in ConnectExceptionSupport so both transports apply the same rule. H2-only clients are not covered yet. --- .../client5/http/ConnectExceptionSupport.java | 34 ++++++++ .../DefaultHttpClientConnectionOperator.java | 13 ++- .../impl/nio/MultihomeIOSessionRequester.java | 16 ++-- .../http/ConnectExceptionSupportTest.java | 30 +++++++ ...faultHttpClientConnectionOperatorTest.java | 83 +++++++++++++++++++ ...aultAsyncClientConnectionOperatorTest.java | 70 ++++++++++++++++ 6 files changed, 238 insertions(+), 8 deletions(-) diff --git a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectExceptionSupport.java b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectExceptionSupport.java index b7b72d80c0..5950e8964b 100644 --- a/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectExceptionSupport.java +++ b/httpclient5/src/main/java/org/apache/hc/client5/http/ConnectExceptionSupport.java @@ -30,7 +30,13 @@ import java.net.ConnectException; import java.net.InetAddress; import java.net.SocketTimeoutException; +import java.security.cert.CertificateException; import java.util.Arrays; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.hc.core5.annotation.Internal; import org.apache.hc.core5.net.NamedEndpoint; @@ -83,4 +89,32 @@ public static IOException enhance( } } + /** + * Determines whether a connection attempt failed because the peer's certificate or + * identity was rejected: an untrusted, expired or otherwise invalid certificate, or a + * host name that does not match it. The whole cause chain is examined, since TLS + * implementations usually report such failures as an {@link javax.net.ssl.SSLHandshakeException} + * caused by a {@link CertificateException}. + *

+ * All addresses of a host are expected to present the same certificate, so such a failure + * is final: trying the next resolved address would fail in the same way. Any other + * {@link IOException}, including a handshake timeout, a connection reset or a TLS alert, + * may well succeed on another address. + *

+ * + * @param ex the exception to examine; may be {@code null}. + * @return {@code true} if {@code ex} or any of its causes is a {@link CertificateException} + * or an {@link SSLPeerUnverifiedException}. + * @since 5.7 + */ + public static boolean isPeerCertificateFailure(final Throwable ex) { + final Set seen = Collections.newSetFromMap(new IdentityHashMap<>()); + for (Throwable cause = ex; cause != null && seen.add(cause); cause = cause.getCause()) { + if (cause instanceof CertificateException || cause instanceof SSLPeerUnverifiedException) { + return true; + } + } + return false; + } + } 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 062d861d93..6e4965b3d3 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 @@ -282,7 +282,11 @@ public void connect( } catch (final IOException ex) { Closer.closeQuietly(socket); final List remaining = withoutAddress(remoteAddresses, winnerAddress); - if (remaining.isEmpty()) { + // A rejected peer certificate would be rejected on every address alike. + if (remaining.isEmpty() || ConnectExceptionSupport.isPeerCertificateFailure(ex)) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} connection to {} failed after racing ({}); terminating operation", endpointHost, winnerAddress, ex.getClass()); + } throw ConnectExceptionSupport.enhance(ex, endpointHost); } if (LOG.isDebugEnabled()) { @@ -318,7 +322,9 @@ private static List withoutAddress( /** * 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 + * {@link IOException} from either step moves on to the next address, unless the peer's + * certificate was rejected (see {@link ConnectExceptionSupport#isPeerCertificateFailure}), + * which is final; 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. */ @@ -364,7 +370,8 @@ private void connectSequentially( throw ex; } catch (final IOException ex) { Closer.closeQuietly(socket); - if (last) { + // A rejected peer certificate would be rejected on every address alike. + if (last || ConnectExceptionSupport.isPeerCertificateFailure(ex)) { if (LOG.isDebugEnabled()) { LOG.debug("{} connection to {} failed ({}); terminating operation", endpointHost, remoteAddress, ex.getClass()); } 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 b703c6436f..1cbacbc81a 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 @@ -241,7 +241,9 @@ public Future connect( * address, if one remains, rather than surfacing a connected session that failed a check * layered on top of the raw connection (for example a TLS handshake) as a successful * outcome. Within a race, a rejection ends racing rather than continuing it: the remaining - * addresses, if any, are tried sequentially (see {@link Race#onWinnerRejected}). + * addresses, if any, are tried sequentially (see {@link Race#onWinnerRejected}). A rejection + * caused by the peer's certificate (see {@link ConnectExceptionSupport#isPeerCertificateFailure}) + * is final and no other address is tried. * *

The exception type reported to the final {@code callback} on rejection is not * necessarily the one this validator reported: a rejection that exhausts every address is @@ -317,7 +319,9 @@ private static void deliver(final IOSession session, final ComplexFuture= remoteAddresses.size()) { + // A rejected peer certificate would be rejected on every address alike. + if (attempt.get() >= remoteAddresses.size() || ConnectExceptionSupport.isPeerCertificateFailure(cause)) { if (LOG.isDebugEnabled()) { LOG.debug("{}:{} connection to {} failed ({}); terminating operation", remoteEndpoint.getHostName(), remoteEndpoint.getPort(), remoteAddress, cause.getClass()); @@ -641,9 +646,10 @@ private void onAttemptCompleted(final InetSocketAddress remoteAddress, final IOS */ private void onWinnerRejected(final InetSocketAddress winnerAddress, final Exception cause) { final List remaining = withoutAddress(remoteAddresses, winnerAddress); - if (remaining.isEmpty()) { + // A rejected peer certificate would be rejected on every address alike. + if (remaining.isEmpty() || ConnectExceptionSupport.isPeerCertificateFailure(cause)) { if (LOG.isDebugEnabled()) { - LOG.debug("{}:{} connection to {} failed validation after racing ({}); no address remains", + LOG.debug("{}:{} connection to {} failed validation after racing ({}); not retrying other addresses", remoteEndpoint.getHostName(), remoteEndpoint.getPort(), winnerAddress, cause.getClass()); } enhanceAndFail(future, remoteEndpoint, cause, new InetAddress[] { winnerAddress.getAddress() }); diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/ConnectExceptionSupportTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/ConnectExceptionSupportTest.java index 0f19045114..2e014009f7 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/ConnectExceptionSupportTest.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/ConnectExceptionSupportTest.java @@ -29,6 +29,11 @@ import java.io.IOException; import java.net.InetAddress; +import java.net.SocketTimeoutException; +import java.security.cert.CertificateException; + +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.hc.core5.http.HttpHost; import org.junit.jupiter.api.Assertions; @@ -103,4 +108,29 @@ void testHttpHostConnectExceptionFromCauseHostAndRemoteAddress() throws Exceptio Assertions.assertEquals("Connect to http://localhost [/1.2.3.4, /5.6.7.8] refused", ctx.getMessage()); } + @Test + void testIsPeerCertificateFailure() { + final SSLHandshakeException untrusted = new SSLHandshakeException("PKIX path building failed"); + untrusted.initCause(new CertificateException("unable to find valid certification path")); + Assertions.assertTrue(ConnectExceptionSupport.isPeerCertificateFailure(untrusted)); + Assertions.assertTrue(ConnectExceptionSupport.isPeerCertificateFailure( + new IOException(new IOException(new SSLPeerUnverifiedException("Certificate doesn't match"))))); + Assertions.assertTrue(ConnectExceptionSupport.isPeerCertificateFailure( + new SSLPeerUnverifiedException("Certificate doesn't match"))); + } + + @Test + void testIsNotPeerCertificateFailure() { + Assertions.assertFalse(ConnectExceptionSupport.isPeerCertificateFailure(null)); + Assertions.assertFalse(ConnectExceptionSupport.isPeerCertificateFailure( + new SSLHandshakeException("Remote host terminated the handshake"))); + Assertions.assertFalse(ConnectExceptionSupport.isPeerCertificateFailure( + new SocketTimeoutException("Read timed out"))); + // A cyclic cause chain must not loop forever. + final IOException first = new IOException("first"); + final IOException second = new IOException("second", first); + first.initCause(second); + Assertions.assertFalse(ConnectExceptionSupport.isPeerCertificateFailure(first)); + } + } 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 index f2d1a33a28..f30991f207 100644 --- 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 @@ -27,6 +27,7 @@ package org.apache.hc.client5.http.impl.io; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively; import static org.junit.jupiter.api.Assertions.assertTrue; @@ -37,6 +38,7 @@ import java.net.Proxy; import java.net.ServerSocket; import java.net.Socket; +import java.security.cert.CertificateException; import java.time.Duration; import java.util.Arrays; import java.util.Collections; @@ -44,6 +46,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; +import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; import javax.net.ssl.SSLSocket; import org.apache.hc.client5.http.DnsResolver; @@ -274,4 +278,83 @@ void happyEyeballsRacing_tlsHandshakeFailure_noRemainingAddress_propagatesImmedi TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create()))); } } + + /** + * A TLS failure caused by the peer's certificate (an untrusted certificate, or a host name + * that does not match it) would fail the same way on every address, so it must be reported + * at once instead of trying the remaining addresses. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tlsCertificateFailureDoesNotFallBackToNextAddress(final boolean happyEyeballs) throws Exception { + final SSLHandshakeException untrusted = new SSLHandshakeException("PKIX path building failed"); + untrusted.initCause(new CertificateException("unable to find valid certification path")); + final IOException ex = assertThrows(IOException.class, () -> + connectWithFirstAddressFailing(happyEyeballs, untrusted, 1)); + assertSame(untrusted, ex); + } + + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tlsPeerUnverifiedFailureDoesNotFallBackToNextAddress(final boolean happyEyeballs) throws Exception { + // A host name mismatch found after the handshake, wrapped one level deeper. + final IOException hostnameMismatch = new IOException("TLS upgrade failed", + new SSLPeerUnverifiedException("Certificate for doesn't match")); + final IOException ex = assertThrows(IOException.class, () -> + connectWithFirstAddressFailing(happyEyeballs, hostnameMismatch, 1)); + assertSame(hostnameMismatch, ex); + } + + /** + * A handshake failure that is not about the certificate, such as the peer closing the + * connection mid-handshake, may well succeed on another address. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void tlsNonCertificateHandshakeFailureFallsBackToNextAddress(final boolean happyEyeballs) throws Exception { + connectWithFirstAddressFailing(happyEyeballs, new SSLHandshakeException("Remote host terminated the handshake"), 2); + } + + /** + * Connects to two loopback addresses whose TLS upgrade fails with {@code failure} on the + * first one and succeeds on the second one, and checks that exactly + * {@code expectedHandshakes} handshakes were attempted. + */ + private static void connectWithFirstAddressFailing( + final boolean happyEyeballs, + final IOException failure, + final int expectedHandshakes) throws Exception { + try (ServerSocket first = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + ServerSocket second = new ServerSocket(0, 50, InetAddress.getLoopbackAddress())) { + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), first.getLocalPort()), + new InetSocketAddress(InetAddress.getLoopbackAddress(), second.getLocalPort())); + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses); + + final AtomicInteger handshakes = new AtomicInteger(); + final TlsSocketStrategy tls = (socket, target, port, attachment, context) -> { + handshakes.incrementAndGet(); + if (socket.getPort() == first.getLocalPort()) { + throw failure; + } + 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); + + try { + assertTimeoutPreemptively(Duration.ofSeconds(5), () -> + operator.connect(conn, new HttpHost("https", "somehost", 443), null, + TimeValue.ofSeconds(5), SocketConfig.DEFAULT, HttpClientContext.create())); + } finally { + assertEquals(expectedHandshakes, handshakes.get()); + } + } + } } diff --git a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java index 774810e5ef..0fac7e89bb 100644 --- a/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java +++ b/httpclient5/src/test/java/org/apache/hc/client5/http/impl/nio/DefaultAsyncClientConnectionOperatorTest.java @@ -29,17 +29,22 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import java.net.InetAddress; import java.net.InetSocketAddress; +import java.security.cert.CertificateException; import java.util.Arrays; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.net.ssl.SSLHandshakeException; +import javax.net.ssl.SSLPeerUnverifiedException; import org.apache.hc.client5.http.DnsResolver; import org.apache.hc.client5.http.nio.ManagedAsyncClientConnection; @@ -55,6 +60,8 @@ import org.apache.hc.core5.util.TimeValue; import org.apache.hc.core5.util.Timeout; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; @@ -441,4 +448,67 @@ void testCancelDuringHandshakeDoesNotStartNewAttemptRacing() throws Exception { assertEquals(1, cancelDuringHandshakeThenReportedFailed(true)); } + /** + * A TLS failure caused by the peer's certificate would fail the same way on every + * address, so it must end the operation at once instead of trying the next address, with + * or without racing, exactly as the classic transport does. + */ + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void testTlsCertificateFailureDoesNotFallBackToNextAddress(final boolean happyEyeballs) throws Exception { + final SSLHandshakeException untrusted = new SSLHandshakeException("PKIX path building failed"); + untrusted.initCause(new CertificateException("unable to find valid certification path")); + assertSame(untrusted, failFirstTlsHandshake(happyEyeballs, untrusted)); + } + + @ParameterizedTest(name = "happyEyeballs={0}") + @ValueSource(booleans = {false, true}) + void testTlsPeerUnverifiedFailureDoesNotFallBackToNextAddress(final boolean happyEyeballs) throws Exception { + final SSLHandshakeException hostnameMismatch = new SSLHandshakeException("TLS upgrade failed"); + hostnameMismatch.initCause(new SSLPeerUnverifiedException("Certificate for doesn't match")); + assertSame(hostnameMismatch, failFirstTlsHandshake(happyEyeballs, hostnameMismatch)); + } + + /** + * Connects to two addresses, fails the first address's TLS handshake with {@code failure}, + * checks that no connection to the second address was attempted, and returns the cause the + * operation failed with. + */ + private Throwable failFirstTlsHandshake(final boolean happyEyeballs, final Exception failure) throws Exception { + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + final InetSocketAddress address1 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 1}), 443); + final InetSocketAddress address2 = new InetSocketAddress(InetAddress.getByAddress(new byte[]{10, 0, 0, 2}), 443); + Mockito.when(dnsResolver.resolve("somehost", 443)).thenReturn(Arrays.asList(address1, address2)); + + final TlsStrategy tlsStrategy = Mockito.mock(TlsStrategy.class); + final DefaultAsyncClientConnectionOperator operator = new DefaultAsyncClientConnectionOperator( + RegistryBuilder.create().register("https", tlsStrategy).build(), null, dnsResolver, + happyEyeballs, TimeValue.ofMilliseconds(250)); + + final IOSession firstSession = Mockito.mock(IOSession.class); + final ConnectionInitiator connectionInitiator = Mockito.mock(ConnectionInitiator.class); + Mockito.when(connectionInitiator.connect(any(), any(), any(), any(), any(), any())) + .thenAnswer(invocation -> { + final FutureCallback callback = invocation.getArgument(5); + callback.completed(firstSession); + return CompletableFuture.completedFuture(firstSession); + }) + .thenAnswer(invocation -> new CompletableFuture()); + + final HttpHost target = new HttpHost("https", null, "somehost", 443); + final Future future = operator.connect( + connectionInitiator, target, null, null, Timeout.ofSeconds(30), null, null, null); + + @SuppressWarnings("unchecked") + final ArgumentCaptor> tlsCallbackCaptor = ArgumentCaptor.forClass(FutureCallback.class); + Mockito.verify(tlsStrategy, Mockito.times(1)).upgrade(any(), any(), any(), any(), tlsCallbackCaptor.capture()); + tlsCallbackCaptor.getValue().failed(failure); + + Mockito.verify(connectionInitiator, Mockito.times(1)).connect(any(), any(), any(), any(), any(), any()); + Mockito.verify(firstSession).close(CloseMode.IMMEDIATE); + assertTrue(future.isDone()); + final ExecutionException ex = assertThrows(ExecutionException.class, future::get); + return ex.getCause(); + } + } From aa8b52ff4a7e96e5d0124237848cd1d3e5c1c7cf Mon Sep 17 00:00:00 2001 From: abdelrahman mohamed Date: Tue, 1 Dec 2026 23:12:31 +0200 Subject: [PATCH 15/15] Test that certificate failures do not try other addresses against a real server Runs both the classic and the async client, with and without Happy Eyeballs, against a real TLS server whose certificate is either untrusted or issued to another host name, with the host name checked by JSSE during the handshake (BUILTIN) or by the client afterwards (CLIENT). In every case the request must fail with a certificate failure and the second resolved address must never be connected to. --- .../TestTlsCertificateFailureNoFallback.java | 189 ++++++++++++++++++ 1 file changed, 189 insertions(+) create mode 100644 httpclient5-testing/src/test/java/org/apache/hc/client5/testing/tls/TestTlsCertificateFailureNoFallback.java diff --git a/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/tls/TestTlsCertificateFailureNoFallback.java b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/tls/TestTlsCertificateFailureNoFallback.java new file mode 100644 index 0000000000..1eed5ce045 --- /dev/null +++ b/httpclient5-testing/src/test/java/org/apache/hc/client5/testing/tls/TestTlsCertificateFailureNoFallback.java @@ -0,0 +1,189 @@ +/* + * ==================================================================== + * 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.testing.tls; + +import java.io.IOException; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ExecutionException; +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.async.methods.SimpleHttpRequest; +import org.apache.hc.client5.http.classic.methods.HttpGet; +import org.apache.hc.client5.http.config.ConnectionConfig; +import org.apache.hc.client5.http.impl.async.CloseableHttpAsyncClient; +import org.apache.hc.client5.http.impl.async.HttpAsyncClientBuilder; +import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; +import org.apache.hc.client5.http.impl.classic.HttpClientBuilder; +import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder; +import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder; +import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy; +import org.apache.hc.client5.http.ssl.DefaultHostnameVerifier; +import org.apache.hc.client5.http.ssl.HostnameVerificationPolicy; +import org.apache.hc.client5.testing.SSLTestContexts; +import org.apache.hc.core5.http.HttpStatus; +import org.apache.hc.core5.http.impl.bootstrap.HttpServer; +import org.apache.hc.core5.http.impl.bootstrap.ServerBootstrap; +import org.apache.hc.core5.io.CloseMode; +import org.apache.hc.core5.ssl.SSLContexts; +import org.apache.hc.core5.util.TimeValue; +import org.apache.hc.core5.util.Timeout; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Mockito; + +/** + * A TLS failure caused by the peer's certificate fails the same way on every resolved address, + * so both the classic and the async client must report it at once, against a real TLS server, + * instead of connecting to the remaining addresses. Covers an untrusted certificate, and a + * certificate that does not match the host name, checked either by JSSE during the handshake + * ({@link HostnameVerificationPolicy#BUILTIN}) or by the client afterwards + * ({@link HostnameVerificationPolicy#CLIENT}). + */ +class TestTlsCertificateFailureNoFallback { + + private HttpServer tlsServer; + private ServerSocket secondAddress; + private final AtomicInteger secondAddressConnections = new AtomicInteger(); + + @BeforeEach + void setUp() throws Exception { + // The server certificate is issued to "localhost"; the requests below ask for "somehost". + tlsServer = ServerBootstrap.bootstrap() + .setLocalAddress(InetAddress.getLoopbackAddress()) + .setSslContext(SSLTestContexts.createServerSSLContext()) + .register("*", (request, response, context) -> response.setCode(HttpStatus.SC_OK)) + .create(); + tlsServer.start(); + + secondAddress = new ServerSocket(0, 50, InetAddress.getLoopbackAddress()); + final Thread acceptor = new Thread(() -> { + while (!secondAddress.isClosed()) { + try (Socket ignored = secondAddress.accept()) { + secondAddressConnections.incrementAndGet(); + } catch (final IOException ignore) { + // The listener was closed by the test. + } + } + }, "second-address"); + acceptor.setDaemon(true); + acceptor.start(); + } + + @AfterEach + void tearDown() throws IOException { + if (tlsServer != null) { + tlsServer.close(CloseMode.IMMEDIATE); + } + if (secondAddress != null) { + secondAddress.close(); + } + } + + private DnsResolver dnsResolver() throws Exception { + final List remoteAddresses = Arrays.asList( + new InetSocketAddress(InetAddress.getLoopbackAddress(), tlsServer.getLocalPort()), + new InetSocketAddress(InetAddress.getLoopbackAddress(), secondAddress.getLocalPort())); + final DnsResolver dnsResolver = Mockito.mock(DnsResolver.class); + Mockito.when(dnsResolver.resolve(Mockito.anyString(), Mockito.anyInt())).thenReturn(remoteAddresses); + return dnsResolver; + } + + private static DefaultClientTlsStrategy tlsStrategy(final String failure) throws Exception { + if ("UNTRUSTED".equals(failure)) { + // The default trust store does not contain the test CA. + return new DefaultClientTlsStrategy(SSLContexts.createDefault(), HostnameVerificationPolicy.BUILTIN, null); + } + final HostnameVerificationPolicy policy = HostnameVerificationPolicy.valueOf(failure); + return new DefaultClientTlsStrategy(SSLTestContexts.createClientSSLContext(), policy, + policy == HostnameVerificationPolicy.CLIENT ? new DefaultHostnameVerifier() : null); + } + + private static ConnectionConfig connectionConfig() { + return ConnectionConfig.custom() + .setConnectTimeout(Timeout.ofSeconds(5)) + .setSocketTimeout(Timeout.ofSeconds(5)) + .build(); + } + + private void assertNoFallback(final Throwable failure) { + Assertions.assertTrue(ConnectExceptionSupport.isPeerCertificateFailure(failure), + () -> "expected a certificate failure, got " + failure); + Assertions.assertEquals(0, secondAddressConnections.get(), "the second address must not be tried"); + } + + @ParameterizedTest(name = "{0}, happyEyeballs={1}") + @CsvSource({"UNTRUSTED,false", "UNTRUSTED,true", "BUILTIN,false", "BUILTIN,true", "CLIENT,false", "CLIENT,true"}) + void classicClientDoesNotTryNextAddress(final String failure, final boolean happyEyeballs) throws Exception { + try (CloseableHttpClient client = HttpClientBuilder.create() + .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create() + .setDnsResolver(dnsResolver()) + .setDefaultConnectionConfig(connectionConfig()) + .setTlsSocketStrategy(tlsStrategy(failure)) + .setHappyEyeballsEnabled(happyEyeballs) + // Long enough that racing never starts the second address before the + // first one has connected. + .setConnectionAttemptDelay(TimeValue.ofSeconds(2)) + .build()) + .disableAutomaticRetries() + .build()) { + final IOException ex = Assertions.assertThrows(IOException.class, () -> + client.execute(new HttpGet("https://somehost/"), response -> null)); + assertNoFallback(ex); + } + } + + @ParameterizedTest(name = "{0}, happyEyeballs={1}") + @CsvSource({"UNTRUSTED,false", "UNTRUSTED,true", "BUILTIN,false", "BUILTIN,true", "CLIENT,false", "CLIENT,true"}) + void asyncClientDoesNotTryNextAddress(final String failure, final boolean happyEyeballs) throws Exception { + try (CloseableHttpAsyncClient client = HttpAsyncClientBuilder.create() + .setConnectionManager(PoolingAsyncClientConnectionManagerBuilder.create() + .setDnsResolver(dnsResolver()) + .setDefaultConnectionConfig(connectionConfig()) + .setTlsStrategy(tlsStrategy(failure)) + .setHappyEyeballsEnabled(happyEyeballs) + .setConnectionAttemptDelay(TimeValue.ofSeconds(2)) + .build()) + .disableAutomaticRetries() + .build()) { + client.start(); + final ExecutionException ex = Assertions.assertThrows(ExecutionException.class, () -> + client.execute(SimpleHttpRequest.create("GET", "https://somehost/"), null).get()); + assertNoFallback(ex.getCause()); + } + } + +}