arturobernalg commented on code in PR #778: URL: https://github.com/apache/httpcomponents-client/pull/778#discussion_r2695597017
########## httpclient5/src/main/java/org/apache/hc/client5/http/Rfc6724AddressSelectingDnsResolver.java: ########## @@ -0,0 +1,670 @@ +/* + * ==================================================================== + * 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 + * <http://www.apache.org/>. + * + */ + +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 java.util.Objects; +import java.util.stream.Collectors; + +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 (RFC 6724 §6) + * to the returned addresses. It can also enforce or bias a protocol family preference. + * + * <p>The canonical hostname lookup is delegated unchanged.</p> + * + * <p> + * {@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. + * </p> + * + * @since 5.7 + */ +@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 + + @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 (DEFAULT). + * + * @param delegate underlying resolver to use. + */ + public Rfc6724AddressSelectingDnsResolver(final DnsResolver delegate) { + this(delegate, ProtocolFamilyPreference.DEFAULT); + } + + /** + * 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, 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 { + final InetAddress[] resolved = delegate.resolve(host); + + if (resolved == null) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} resolved '{}' -> null", simpleName(), 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)); + } + + final List<InetAddress> candidates = filterCandidates(resolved, familyPreference); + + if (candidates.isEmpty()) { + if (LOG.isDebugEnabled()) { + LOG.debug("{} resolved '{}' -> []", simpleName(), host); + } + return new InetAddress[0]; Review Comment: I prefer keeping null only when the delegate returns null, and returning an empty array when all resolved candidates are filtered out to avoid introducing NPEs for callers. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
