View Javadoc
1   /*
2    * Copyright 2014 The Netty Project
3    *
4    * The Netty Project licenses this file to you under the Apache License,
5    * version 2.0 (the "License"); you may not use this file except in compliance
6    * with the License. You may obtain a copy of the License at:
7    *
8    *   https://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13   * License for the specific language governing permissions and limitations
14   * under the License.
15   */
16  package io.netty.resolver.dns;
17  
18  import io.netty.bootstrap.Bootstrap;
19  import io.netty.buffer.ByteBuf;
20  import io.netty.buffer.Unpooled;
21  import io.netty.channel.AddressedEnvelope;
22  import io.netty.channel.Channel;
23  import io.netty.channel.ChannelFactory;
24  import io.netty.channel.ChannelFuture;
25  import io.netty.channel.ChannelFutureListener;
26  import io.netty.channel.ChannelHandler;
27  import io.netty.channel.ChannelHandlerAdapter;
28  import io.netty.channel.ChannelHandlerContext;
29  import io.netty.channel.ChannelInboundHandlerAdapter;
30  import io.netty.channel.ChannelInitializer;
31  import io.netty.channel.ChannelOption;
32  import io.netty.channel.EventLoop;
33  import io.netty.channel.FixedRecvByteBufAllocator;
34  import io.netty.channel.socket.DatagramChannel;
35  import io.netty.channel.socket.DatagramPacket;
36  import io.netty.channel.socket.SocketChannel;
37  import io.netty.channel.socket.SocketProtocolFamily;
38  import io.netty.handler.codec.CorruptedFrameException;
39  import io.netty.handler.codec.dns.DatagramDnsQueryEncoder;
40  import io.netty.handler.codec.dns.DatagramDnsResponse;
41  import io.netty.handler.codec.dns.DatagramDnsResponseDecoder;
42  import io.netty.handler.codec.dns.DefaultDnsRawRecord;
43  import io.netty.handler.codec.dns.DnsQuestion;
44  import io.netty.handler.codec.dns.DnsRawRecord;
45  import io.netty.handler.codec.dns.DnsRecord;
46  import io.netty.handler.codec.dns.DnsRecordType;
47  import io.netty.handler.codec.dns.DnsResponse;
48  import io.netty.resolver.DefaultHostsFileEntriesResolver;
49  import io.netty.resolver.HostsFileEntries;
50  import io.netty.resolver.HostsFileEntriesResolver;
51  import io.netty.resolver.InetNameResolver;
52  import io.netty.resolver.ResolvedAddressTypes;
53  import io.netty.util.AttributeKey;
54  import io.netty.util.NetUtil;
55  import io.netty.util.ReferenceCountUtil;
56  import io.netty.util.concurrent.EventExecutor;
57  import io.netty.util.concurrent.Future;
58  import io.netty.util.concurrent.FutureListener;
59  import io.netty.util.concurrent.GenericFutureListener;
60  import io.netty.util.concurrent.Promise;
61  import io.netty.util.internal.EmptyArrays;
62  import io.netty.util.internal.PlatformDependent;
63  import io.netty.util.internal.StringUtil;
64  import io.netty.util.internal.SystemPropertyUtil;
65  import io.netty.util.internal.logging.InternalLogger;
66  import io.netty.util.internal.logging.InternalLoggerFactory;
67  import org.jetbrains.annotations.VisibleForTesting;
68  
69  import java.lang.reflect.Method;
70  import java.net.IDN;
71  import java.net.Inet4Address;
72  import java.net.Inet6Address;
73  import java.net.InetAddress;
74  import java.net.InetSocketAddress;
75  import java.net.NetworkInterface;
76  import java.net.SocketAddress;
77  import java.net.UnknownHostException;
78  import java.util.ArrayList;
79  import java.util.Arrays;
80  import java.util.Collection;
81  import java.util.Collections;
82  import java.util.Comparator;
83  import java.util.Enumeration;
84  import java.util.HashMap;
85  import java.util.Iterator;
86  import java.util.List;
87  import java.util.Locale;
88  import java.util.Map;
89  import java.util.concurrent.TimeUnit;
90  
91  import static io.netty.resolver.dns.DefaultDnsServerAddressStreamProvider.DNS_PORT;
92  import static io.netty.util.internal.ObjectUtil.checkNotNull;
93  import static io.netty.util.internal.ObjectUtil.checkPositive;
94  
95  /**
96   * A DNS-based {@link InetNameResolver}.
97   */
98  public class DnsNameResolver extends InetNameResolver {
99      /**
100      * An attribute used to mark all channels created by the {@link DnsNameResolver}.
101      */
102     public static final AttributeKey<Boolean> DNS_PIPELINE_ATTRIBUTE =
103             AttributeKey.newInstance("io.netty.resolver.dns.pipeline");
104 
105     private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsNameResolver.class);
106     private static final String LOCALHOST = "localhost";
107     private static final String DOT_LOCALHOST = '.' + LOCALHOST;
108     private static final String WINDOWS_HOST_NAME;
109     private static final DnsRecord[] EMPTY_ADDITIONALS = new DnsRecord[0];
110     private static final DnsRecordType[] IPV4_ONLY_RESOLVED_RECORD_TYPES =
111             {DnsRecordType.A};
112     private static final SocketProtocolFamily[] IPV4_ONLY_RESOLVED_PROTOCOL_FAMILIES =
113             {SocketProtocolFamily.INET};
114     private static final DnsRecordType[] IPV4_PREFERRED_RESOLVED_RECORD_TYPES =
115             {DnsRecordType.A, DnsRecordType.AAAA};
116     private static final SocketProtocolFamily[] IPV4_PREFERRED_RESOLVED_PROTOCOL_FAMILIES =
117             {SocketProtocolFamily.INET, SocketProtocolFamily.INET6};
118     private static final DnsRecordType[] IPV6_ONLY_RESOLVED_RECORD_TYPES =
119             {DnsRecordType.AAAA};
120     private static final SocketProtocolFamily[] IPV6_ONLY_RESOLVED_PROTOCOL_FAMILIES =
121             {SocketProtocolFamily.INET6};
122     private static final DnsRecordType[] IPV6_PREFERRED_RESOLVED_RECORD_TYPES =
123             {DnsRecordType.AAAA, DnsRecordType.A};
124     private static final SocketProtocolFamily[] IPV6_PREFERRED_RESOLVED_PROTOCOL_FAMILIES =
125             {SocketProtocolFamily.INET6, SocketProtocolFamily.INET};
126 
127     private static final ChannelHandler NOOP_HANDLER = new ChannelHandlerAdapter() {
128         @Override
129         public boolean isSharable() {
130             return true;
131         }
132     };
133 
134     /**
135      * System property to control RFC 6761 localhost resolution.
136      * <p>
137      * When {@code true} (the default), {@code localhost} and {@code *.localhost}
138      * are resolved to the loopback address without querying DNS servers. When
139      * {@code false}, only the pre-#16749 rules apply (Windows {@code localhost}
140      * and the Windows machine hostname). Set to {@code false} when
141      * {@code *.localhost} hostnames must resolve via DNS to non-loopback
142      * addresses.
143      *
144      * @see <a href="https://github.com/netty/netty/issues/16744">Issue 16744</a>
145      * @see <a href="https://www.rfc-editor.org/rfc/rfc6761.html#section-6.3">RFC 6761</a>
146      */
147     private static final String RESOLVE_LOCALHOST_WITHOUT_DNS_PROPERTY =
148             "io.netty.resolver.dns.resolveLocalhostWithoutDns";
149 
150     /** The runtime value of {@link #RESOLVE_LOCALHOST_WITHOUT_DNS_PROPERTY}. */
151     @VisibleForTesting
152     static boolean resolveLocalhostWithoutDns;
153 
154     static final ResolvedAddressTypes DEFAULT_RESOLVE_ADDRESS_TYPES;
155     static final String[] DEFAULT_SEARCH_DOMAINS;
156     private static final UnixResolverOptions DEFAULT_OPTIONS;
157 
158     static {
159         if (NetUtil.isIpV4StackPreferred() || !anyInterfaceSupportsIpV6()) {
160             DEFAULT_RESOLVE_ADDRESS_TYPES = ResolvedAddressTypes.IPV4_ONLY;
161         } else {
162             if (NetUtil.isIpV6AddressesPreferred()) {
163                 DEFAULT_RESOLVE_ADDRESS_TYPES = ResolvedAddressTypes.IPV6_PREFERRED;
164             } else {
165                 DEFAULT_RESOLVE_ADDRESS_TYPES = ResolvedAddressTypes.IPV4_PREFERRED;
166             }
167         }
168         logger.debug("Default ResolvedAddressTypes: {}", DEFAULT_RESOLVE_ADDRESS_TYPES);
169 
170         String hostName;
171         try {
172             hostName = PlatformDependent.isWindows() ? InetAddress.getLocalHost().getHostName() : null;
173         } catch (Exception ignore) {
174             hostName = null;
175         }
176         WINDOWS_HOST_NAME = hostName;
177         logger.debug("Windows hostname: {}", WINDOWS_HOST_NAME);
178 
179         String[] searchDomains;
180         try {
181             List<String> list = PlatformDependent.isWindows()
182                     ? getSearchDomainsHack()
183                     : UnixResolverDnsServerAddressStreamProvider.parseEtcResolverSearchDomains();
184             searchDomains = list.toArray(EmptyArrays.EMPTY_STRINGS);
185         } catch (Exception ignore) {
186             // Failed to get the system name search domain list.
187             searchDomains = EmptyArrays.EMPTY_STRINGS;
188         }
189         DEFAULT_SEARCH_DOMAINS = searchDomains;
190         logger.debug("Default search domains: {}", Arrays.toString(DEFAULT_SEARCH_DOMAINS));
191 
192         UnixResolverOptions options;
193         try {
194             options = UnixResolverDnsServerAddressStreamProvider.parseEtcResolverOptions();
195         } catch (Exception ignore) {
196             options = UnixResolverOptions.newBuilder().build();
197         }
198         DEFAULT_OPTIONS = options;
199         logger.debug("Default {}", DEFAULT_OPTIONS);
200 
201         resolveLocalhostWithoutDns =
202                 SystemPropertyUtil.getBoolean(RESOLVE_LOCALHOST_WITHOUT_DNS_PROPERTY, true);
203         if (logger.isDebugEnabled()) {
204             logger.debug("-D{}: {}", RESOLVE_LOCALHOST_WITHOUT_DNS_PROPERTY, resolveLocalhostWithoutDns);
205         }
206     }
207 
208     /**
209      * Returns {@code true} if any {@link NetworkInterface} supports {@code IPv6}, {@code false} otherwise.
210      */
211     private static boolean anyInterfaceSupportsIpV6() {
212         for (NetworkInterface iface : NetUtil.NETWORK_INTERFACES) {
213             Enumeration<InetAddress> addresses = iface.getInetAddresses();
214             while (addresses.hasMoreElements()) {
215                 InetAddress inetAddress = addresses.nextElement();
216                 if (inetAddress instanceof Inet6Address && !inetAddress.isAnyLocalAddress() &&
217                         !inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
218                     return true;
219                 }
220             }
221         }
222         return false;
223     }
224 
225     @SuppressWarnings("unchecked")
226     private static List<String> getSearchDomainsHack() throws Exception {
227         // Only try if not using Java9 and later
228         // See https://github.com/netty/netty/issues/9500
229         if (PlatformDependent.javaVersion() < 9) {
230             // This code on Java 9+ yields a warning about illegal reflective access that will be denied in
231             // a future release. There doesn't seem to be a better way to get search domains for Windows yet.
232             Class<?> configClass = Class.forName("sun.net.dns.ResolverConfiguration");
233             Method open = configClass.getMethod("open");
234             Method nameservers = configClass.getMethod("searchlist");
235             Object instance = open.invoke(null);
236 
237             return (List<String>) nameservers.invoke(instance);
238         }
239         return Collections.emptyList();
240     }
241 
242     private static final DatagramDnsResponseDecoder DATAGRAM_DECODER = new DatagramDnsResponseDecoder() {
243         @Override
244         protected DnsResponse decodeResponse(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
245             DnsResponse response = super.decodeResponse(ctx, packet);
246             if (packet.content().isReadable()) {
247                 // If there is still something to read we did stop parsing because of a truncated message.
248                 // This can happen if we enabled EDNS0 but our MTU is not big enough to handle all the
249                 // data.
250                 response.setTruncated(true);
251 
252                 if (logger.isDebugEnabled()) {
253                     logger.debug("{} RECEIVED: UDP [{}: {}] truncated packet received, consider adjusting "
254                                     + "maxPayloadSize for the {}.", ctx.channel(), response.id(), packet.sender(),
255                             StringUtil.simpleClassName(DnsNameResolver.class));
256                 }
257             }
258             return response;
259         }
260     };
261     private static final DatagramDnsQueryEncoder DATAGRAM_ENCODER = new DatagramDnsQueryEncoder();
262 
263     private static final GenericFutureListener<Future<? super AddressedEnvelope<? extends DnsResponse,
264             InetSocketAddress>>> RELEASE_LISTENER = future -> {
265         if (future.isSuccess()) {
266             AddressedEnvelope<? extends DnsResponse, InetSocketAddress> result =
267                     (AddressedEnvelope<? extends DnsResponse, InetSocketAddress>) future.getNow();
268             ReferenceCountUtil.release(result);
269         }
270     };
271 
272     // Comparator that ensures we will try first to use the nameservers that use our preferred address type.
273     private final Comparator<InetSocketAddress> nameServerComparator;
274     /**
275      * Manages the {@link DnsQueryContext}s in progress and their query IDs.
276      */
277     private final DnsQueryContextManager queryContextManager = new DnsQueryContextManager();
278 
279     /**
280      * Cache for {@link #doResolve(String, Promise)} and {@link #doResolveAll(String, Promise)}.
281      */
282     private final DnsCache resolveCache;
283     private final AuthoritativeDnsServerCache authoritativeDnsServerCache;
284     private final DnsCnameCache cnameCache;
285     private final DnsServerAddressStream queryDnsServerAddressStream;
286 
287     private final long queryTimeoutMillis;
288     private final int maxQueriesPerResolve;
289     private final ResolvedAddressTypes resolvedAddressTypes;
290     private final SocketProtocolFamily[] resolvedInternetProtocolFamilies;
291     private final boolean recursionDesired;
292     private final int maxPayloadSize;
293     private final boolean optResourceEnabled;
294     private final HostsFileEntriesResolver hostsFileEntriesResolver;
295     private final DnsServerAddressStreamProvider dnsServerAddressStreamProvider;
296     private final String[] searchDomains;
297     private final int ndots;
298     private final boolean supportsAAAARecords;
299     private final boolean supportsARecords;
300     private final SocketProtocolFamily preferredAddressType;
301     private final DnsRecordType[] resolveRecordTypes;
302     private final boolean decodeIdn;
303     private final DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory;
304     private final boolean completeOncePreferredResolved;
305     // null if neither case randomization nor DNS cookies are enabled.
306     private final DnsQueryProtection queryProtection;
307     private final DnsResolveChannelProvider resolveChannelProvider;
308     private final Bootstrap socketBootstrap;
309     private final boolean retryWithTcpOnTimeout;
310 
311     private final int maxNumConsolidation;
312     private final Map<DnsQuestion, Promise<AddressedEnvelope<? extends DnsResponse,
313             InetSocketAddress>>> inflightLookups;
314 
315     /**
316      * Creates a new DNS-based name resolver that communicates with the specified list of DNS servers.
317      *
318      * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS servers
319      * @param channelFactory the {@link ChannelFactory} that will create a {@link DatagramChannel}
320      * @param resolveCache the DNS resolved entries cache
321      * @param authoritativeDnsServerCache the cache used to find the authoritative DNS server for a domain
322      * @param dnsQueryLifecycleObserverFactory used to generate new instances of {@link DnsQueryLifecycleObserver} which
323      *                                         can be used to track metrics for DNS servers.
324      * @param queryTimeoutMillis timeout of each DNS query in millis. {@code 0} disables the timeout. If not set or a
325      *                           negative number is set, the default timeout is used.
326      * @param resolvedAddressTypes the preferred address types
327      * @param recursionDesired if recursion desired flag must be set
328      * @param maxQueriesPerResolve the maximum allowed number of DNS queries for a given name resolution
329      * @param traceEnabled if trace is enabled
330      * @param maxPayloadSize the capacity of the datagram packet buffer
331      * @param optResourceEnabled if automatic inclusion of a optional records is enabled
332      * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to check for local aliases
333      * @param dnsServerAddressStreamProvider The {@link DnsServerAddressStreamProvider} used to determine the name
334      *                                       servers for each hostname lookup.
335      * @param searchDomains the list of search domain
336      *                      (can be null, if so, will try to default to the underlying platform ones)
337      * @param ndots the ndots value
338      * @param decodeIdn {@code true} if domain / host names should be decoded to unicode when received.
339      *                        See <a href="https://tools.ietf.org/html/rfc3492">rfc3492</a>.
340      * @deprecated Use {@link DnsNameResolverBuilder}.
341      */
342     @Deprecated
343     public DnsNameResolver(
344             EventLoop eventLoop,
345             ChannelFactory<? extends DatagramChannel> channelFactory,
346             final DnsCache resolveCache,
347             final DnsCache authoritativeDnsServerCache,
348             DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory,
349             long queryTimeoutMillis,
350             ResolvedAddressTypes resolvedAddressTypes,
351             boolean recursionDesired,
352             int maxQueriesPerResolve,
353             boolean traceEnabled,
354             int maxPayloadSize,
355             boolean optResourceEnabled,
356             HostsFileEntriesResolver hostsFileEntriesResolver,
357             DnsServerAddressStreamProvider dnsServerAddressStreamProvider,
358             String[] searchDomains,
359             int ndots,
360             boolean decodeIdn) {
361         this(eventLoop, channelFactory, resolveCache,
362              new AuthoritativeDnsServerCacheAdapter(authoritativeDnsServerCache), dnsQueryLifecycleObserverFactory,
363              queryTimeoutMillis, resolvedAddressTypes, recursionDesired, maxQueriesPerResolve, traceEnabled,
364              maxPayloadSize, optResourceEnabled, hostsFileEntriesResolver, dnsServerAddressStreamProvider,
365              searchDomains, ndots, decodeIdn);
366     }
367 
368     /**
369      * Creates a new DNS-based name resolver that communicates with the specified list of DNS servers.
370      *
371      * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS servers
372      * @param channelFactory the {@link ChannelFactory} that will create a {@link DatagramChannel}
373      * @param resolveCache the DNS resolved entries cache
374      * @param authoritativeDnsServerCache the cache used to find the authoritative DNS server for a domain
375      * @param dnsQueryLifecycleObserverFactory used to generate new instances of {@link DnsQueryLifecycleObserver} which
376      *                                         can be used to track metrics for DNS servers.
377      * @param queryTimeoutMillis timeout of each DNS query in millis. {@code 0} disables the timeout. If not set or a
378      *                           negative number is set, the default timeout is used.
379      * @param resolvedAddressTypes the preferred address types
380      * @param recursionDesired if recursion desired flag must be set
381      * @param maxQueriesPerResolve the maximum allowed number of DNS queries for a given name resolution
382      * @param traceEnabled if trace is enabled
383      * @param maxPayloadSize the capacity of the datagram packet buffer
384      * @param optResourceEnabled if automatic inclusion of a optional records is enabled
385      * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to check for local aliases
386      * @param dnsServerAddressStreamProvider The {@link DnsServerAddressStreamProvider} used to determine the name
387      *                                       servers for each hostname lookup.
388      * @param searchDomains the list of search domain
389      *                      (can be null, if so, will try to default to the underlying platform ones)
390      * @param ndots the ndots value
391      * @param decodeIdn {@code true} if domain / host names should be decoded to unicode when received.
392      *                        See <a href="https://tools.ietf.org/html/rfc3492">rfc3492</a>.
393      * @deprecated Use {@link DnsNameResolverBuilder}.
394      */
395     @Deprecated
396     public DnsNameResolver(
397             EventLoop eventLoop,
398             ChannelFactory<? extends DatagramChannel> channelFactory,
399             final DnsCache resolveCache,
400             final AuthoritativeDnsServerCache authoritativeDnsServerCache,
401             DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory,
402             long queryTimeoutMillis,
403             ResolvedAddressTypes resolvedAddressTypes,
404             boolean recursionDesired,
405             int maxQueriesPerResolve,
406             boolean traceEnabled,
407             int maxPayloadSize,
408             boolean optResourceEnabled,
409             HostsFileEntriesResolver hostsFileEntriesResolver,
410             DnsServerAddressStreamProvider dnsServerAddressStreamProvider,
411             String[] searchDomains,
412             int ndots,
413             boolean decodeIdn) {
414         this(eventLoop, channelFactory, null, false, resolveCache,
415                 NoopDnsCnameCache.INSTANCE, authoritativeDnsServerCache, null,
416              dnsQueryLifecycleObserverFactory, queryTimeoutMillis, resolvedAddressTypes, recursionDesired,
417              maxQueriesPerResolve, traceEnabled, maxPayloadSize, optResourceEnabled, hostsFileEntriesResolver,
418              dnsServerAddressStreamProvider, new ThreadLocalNameServerAddressStream(dnsServerAddressStreamProvider),
419              searchDomains, ndots, decodeIdn, false, 0, DnsNameResolverChannelStrategy.ChannelPerResolver,
420              false, false);
421     }
422 
423     @SuppressWarnings("deprecation")
424     DnsNameResolver(
425             EventLoop eventLoop,
426             ChannelFactory<? extends DatagramChannel> channelFactory,
427             ChannelFactory<? extends SocketChannel> socketChannelFactory,
428             boolean retryWithTcpOnTimeout,
429             final DnsCache resolveCache,
430             final DnsCnameCache cnameCache,
431             final AuthoritativeDnsServerCache authoritativeDnsServerCache,
432             SocketAddress localAddress,
433             DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory,
434             long queryTimeoutMillis,
435             ResolvedAddressTypes resolvedAddressTypes,
436             boolean recursionDesired,
437             int maxQueriesPerResolve,
438             boolean traceEnabled,
439             final int maxPayloadSize,
440             boolean optResourceEnabled,
441             HostsFileEntriesResolver hostsFileEntriesResolver,
442             DnsServerAddressStreamProvider dnsServerAddressStreamProvider,
443             DnsServerAddressStream queryDnsServerAddressStream,
444             String[] searchDomains,
445             int ndots,
446             boolean decodeIdn,
447             boolean completeOncePreferredResolved,
448             int maxNumConsolidation, DnsNameResolverChannelStrategy datagramChannelStrategy) {
449         this(eventLoop, channelFactory, socketChannelFactory, retryWithTcpOnTimeout, resolveCache, cnameCache,
450                 authoritativeDnsServerCache, localAddress, dnsQueryLifecycleObserverFactory, queryTimeoutMillis,
451                 resolvedAddressTypes, recursionDesired, maxQueriesPerResolve, traceEnabled, maxPayloadSize,
452                 optResourceEnabled, hostsFileEntriesResolver, dnsServerAddressStreamProvider,
453                 queryDnsServerAddressStream, searchDomains, ndots, decodeIdn, completeOncePreferredResolved,
454                 maxNumConsolidation, datagramChannelStrategy, false, false);
455     }
456 
457     @SuppressWarnings("deprecation")
458     DnsNameResolver(
459             EventLoop eventLoop,
460             ChannelFactory<? extends DatagramChannel> channelFactory,
461             ChannelFactory<? extends SocketChannel> socketChannelFactory,
462             boolean retryWithTcpOnTimeout,
463             final DnsCache resolveCache,
464             final DnsCnameCache cnameCache,
465             final AuthoritativeDnsServerCache authoritativeDnsServerCache,
466             SocketAddress localAddress,
467             DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory,
468             long queryTimeoutMillis,
469             ResolvedAddressTypes resolvedAddressTypes,
470             boolean recursionDesired,
471             int maxQueriesPerResolve,
472             boolean traceEnabled,
473             final int maxPayloadSize,
474             boolean optResourceEnabled,
475             HostsFileEntriesResolver hostsFileEntriesResolver,
476             DnsServerAddressStreamProvider dnsServerAddressStreamProvider,
477             DnsServerAddressStream queryDnsServerAddressStream,
478             String[] searchDomains,
479             int ndots,
480             boolean decodeIdn,
481             boolean completeOncePreferredResolved,
482             int maxNumConsolidation, DnsNameResolverChannelStrategy datagramChannelStrategy,
483             boolean caseRandomizationEnabled, boolean dnsCookiesEnabled) {
484         super(eventLoop);
485         this.queryTimeoutMillis = queryTimeoutMillis >= 0
486             ? queryTimeoutMillis
487             : TimeUnit.SECONDS.toMillis(DEFAULT_OPTIONS.timeout());
488         this.resolvedAddressTypes = resolvedAddressTypes != null ? resolvedAddressTypes : DEFAULT_RESOLVE_ADDRESS_TYPES;
489         this.recursionDesired = recursionDesired;
490         this.maxQueriesPerResolve = maxQueriesPerResolve > 0 ? maxQueriesPerResolve : DEFAULT_OPTIONS.attempts();
491         this.maxPayloadSize = checkPositive(maxPayloadSize, "maxPayloadSize");
492         this.optResourceEnabled = optResourceEnabled;
493         this.hostsFileEntriesResolver = checkNotNull(hostsFileEntriesResolver, "hostsFileEntriesResolver");
494         this.dnsServerAddressStreamProvider =
495                 checkNotNull(dnsServerAddressStreamProvider, "dnsServerAddressStreamProvider");
496         this.queryDnsServerAddressStream = checkNotNull(queryDnsServerAddressStream, "queryDnsServerAddressStream");
497         this.resolveCache = checkNotNull(resolveCache, "resolveCache");
498         this.cnameCache = checkNotNull(cnameCache, "cnameCache");
499         this.dnsQueryLifecycleObserverFactory = traceEnabled ?
500                 dnsQueryLifecycleObserverFactory instanceof NoopDnsQueryLifecycleObserverFactory ?
501                         new LoggingDnsQueryLifeCycleObserverFactory() :
502                         new BiDnsQueryLifecycleObserverFactory(new LoggingDnsQueryLifeCycleObserverFactory(),
503                                                                dnsQueryLifecycleObserverFactory) :
504                 checkNotNull(dnsQueryLifecycleObserverFactory, "dnsQueryLifecycleObserverFactory");
505         this.searchDomains = searchDomains != null ? searchDomains.clone() : DEFAULT_SEARCH_DOMAINS;
506         this.ndots = ndots >= 0 ? ndots : DEFAULT_OPTIONS.ndots();
507         this.decodeIdn = decodeIdn;
508         this.completeOncePreferredResolved = completeOncePreferredResolved;
509         this.retryWithTcpOnTimeout = retryWithTcpOnTimeout;
510         this.queryProtection = caseRandomizationEnabled || dnsCookiesEnabled ?
511                 new DnsQueryProtection(caseRandomizationEnabled, dnsCookiesEnabled) : null;
512         if (socketChannelFactory == null) {
513             socketBootstrap = null;
514         } else {
515             socketBootstrap = new Bootstrap();
516             socketBootstrap.option(ChannelOption.SO_REUSEADDR, true)
517                     .group(executor())
518                     .channelFactory(socketChannelFactory)
519                     .attr(DNS_PIPELINE_ATTRIBUTE, Boolean.TRUE)
520                     .handler(NOOP_HANDLER);
521             if (queryTimeoutMillis > 0 && queryTimeoutMillis <= Integer.MAX_VALUE) {
522                 // Set the connect timeout to the same as queryTimeout as otherwise it might take a long
523                 // time for the query to fail in case of a connection timeout.
524                 socketBootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, (int) queryTimeoutMillis);
525             }
526         }
527         switch (this.resolvedAddressTypes) {
528             case IPV4_ONLY:
529                 supportsAAAARecords = false;
530                 supportsARecords = true;
531                 resolveRecordTypes = IPV4_ONLY_RESOLVED_RECORD_TYPES;
532                 resolvedInternetProtocolFamilies = IPV4_ONLY_RESOLVED_PROTOCOL_FAMILIES;
533                 break;
534             case IPV4_PREFERRED:
535                 supportsAAAARecords = true;
536                 supportsARecords = true;
537                 resolveRecordTypes = IPV4_PREFERRED_RESOLVED_RECORD_TYPES;
538                 resolvedInternetProtocolFamilies = IPV4_PREFERRED_RESOLVED_PROTOCOL_FAMILIES;
539                 break;
540             case IPV6_ONLY:
541                 supportsAAAARecords = true;
542                 supportsARecords = false;
543                 resolveRecordTypes = IPV6_ONLY_RESOLVED_RECORD_TYPES;
544                 resolvedInternetProtocolFamilies = IPV6_ONLY_RESOLVED_PROTOCOL_FAMILIES;
545                 break;
546             case IPV6_PREFERRED:
547                 supportsAAAARecords = true;
548                 supportsARecords = true;
549                 resolveRecordTypes = IPV6_PREFERRED_RESOLVED_RECORD_TYPES;
550                 resolvedInternetProtocolFamilies = IPV6_PREFERRED_RESOLVED_PROTOCOL_FAMILIES;
551                 break;
552             default:
553                 throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
554         }
555         preferredAddressType = preferredAddressType(this.resolvedAddressTypes);
556         this.authoritativeDnsServerCache = checkNotNull(authoritativeDnsServerCache, "authoritativeDnsServerCache");
557         nameServerComparator = new NameServerComparator(addressType(preferredAddressType));
558         this.maxNumConsolidation = maxNumConsolidation;
559         if (maxNumConsolidation > 0) {
560             inflightLookups = new HashMap<>();
561         } else {
562             inflightLookups = null;
563         }
564 
565         final DnsResponseHandler responseHandler = new DnsResponseHandler(queryContextManager);
566         Bootstrap bootstrap = new Bootstrap()
567                 .channelFactory(channelFactory)
568                 .group(eventLoop)
569                 .attr(DNS_PIPELINE_ATTRIBUTE, Boolean.TRUE)
570                 .handler(new ChannelInitializer<DatagramChannel>() {
571                     @Override
572                     protected void initChannel(DatagramChannel ch) {
573                         ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(maxPayloadSize));
574                         ch.pipeline().addLast(DATAGRAM_ENCODER, DATAGRAM_DECODER, responseHandler);
575                     }
576                 });
577         if (localAddress == null) {
578             bootstrap.option(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true);
579         }
580         this.resolveChannelProvider = newProvider(datagramChannelStrategy, bootstrap, localAddress);
581     }
582 
583     private static DnsResolveChannelProvider newProvider(DnsNameResolverChannelStrategy channelStrategy,
584                                                          Bootstrap bootstrap, SocketAddress localAddress) {
585         switch (channelStrategy) {
586             case ChannelPerResolver:
587                 return new DnsResolveChannelPerResolverProvider(bootstrap, localAddress);
588             case ChannelPerResolution:
589                 return new DnsResolveChannelPerResolutionProvider(bootstrap, localAddress);
590             default:
591                 throw new IllegalArgumentException("Unknown DnsNameResolverChannelStrategy: " + channelStrategy);
592         }
593     }
594 
595     static SocketProtocolFamily preferredAddressType(ResolvedAddressTypes resolvedAddressTypes) {
596         switch (resolvedAddressTypes) {
597         case IPV4_ONLY:
598         case IPV4_PREFERRED:
599             return SocketProtocolFamily.INET;
600         case IPV6_ONLY:
601         case IPV6_PREFERRED:
602             return SocketProtocolFamily.INET6;
603         default:
604             throw new IllegalArgumentException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
605         }
606     }
607 
608     // Only here to override in unit tests.
609     InetSocketAddress newRedirectServerAddress(InetAddress server) {
610         return new InetSocketAddress(server, DNS_PORT);
611     }
612 
613     final DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory() {
614         return dnsQueryLifecycleObserverFactory;
615     }
616 
617     /**
618      * Creates a new {@link DnsServerAddressStream} to following a redirected DNS query. By overriding this
619      * it provides the opportunity to sort the name servers before following a redirected DNS query.
620      *
621      * @param hostname the hostname.
622      * @param nameservers The addresses of the DNS servers which are used in the event of a redirect. This may
623      *                    contain resolved and unresolved addresses so the used {@link DnsServerAddressStream} must
624      *                    allow unresolved addresses if you want to include these as well.
625      * @return A {@link DnsServerAddressStream} which will be used to follow the DNS redirect or {@code null} if
626      *         none should be followed.
627      */
628     protected DnsServerAddressStream newRedirectDnsServerStream(
629             @SuppressWarnings("unused") String hostname, List<InetSocketAddress> nameservers) {
630         DnsServerAddressStream cached = authoritativeDnsServerCache().get(hostname);
631         if (cached == null || cached.size() == 0) {
632             // If there is no cache hit (which may be the case for example when a NoopAuthoritativeDnsServerCache
633             // is used), we will just directly use the provided nameservers.
634             Collections.sort(nameservers, nameServerComparator);
635             return new SequentialDnsServerAddressStream(nameservers, 0);
636         }
637         return cached;
638     }
639 
640     /**
641      * Returns the resolution cache.
642      */
643     public DnsCache resolveCache() {
644         return resolveCache;
645     }
646 
647     /**
648      * Returns the {@link DnsCnameCache}.
649      */
650     public DnsCnameCache cnameCache() {
651         return cnameCache;
652     }
653 
654     /**
655      * Returns the cache used for authoritative DNS servers for a domain.
656      */
657     public AuthoritativeDnsServerCache authoritativeDnsServerCache() {
658         return authoritativeDnsServerCache;
659     }
660 
661     /**
662      * Returns the timeout of each DNS query performed by this resolver (in milliseconds).
663      * The default value is 5 seconds.
664      */
665     public long queryTimeoutMillis() {
666         return queryTimeoutMillis;
667     }
668 
669     /**
670      * Returns the dns server address stream used for DNS queries (not resolve).
671      */
672     public DnsServerAddressStream queryDnsServerAddressStream() {
673         return queryDnsServerAddressStream;
674     }
675 
676     /**
677      * Returns the {@link ResolvedAddressTypes} resolved by {@link #resolve(String)}.
678      * The default value depends on the value of the system property {@code "java.net.preferIPv6Addresses"}.
679      */
680     public ResolvedAddressTypes resolvedAddressTypes() {
681         return resolvedAddressTypes;
682     }
683 
684     SocketProtocolFamily[] resolvedInternetProtocolFamiliesUnsafe() {
685         return resolvedInternetProtocolFamilies;
686     }
687 
688     final String[] searchDomains() {
689         return searchDomains;
690     }
691 
692     final int ndots() {
693         return ndots;
694     }
695 
696     final boolean supportsAAAARecords() {
697         return supportsAAAARecords;
698     }
699 
700     final boolean supportsARecords() {
701         return supportsARecords;
702     }
703 
704     final SocketProtocolFamily preferredAddressType() {
705         return preferredAddressType;
706     }
707 
708     final DnsRecordType[] resolveRecordTypes() {
709         return resolveRecordTypes;
710     }
711 
712     final boolean isDecodeIdn() {
713         return decodeIdn;
714     }
715 
716     /**
717      * Returns {@code true} if and only if this resolver sends a DNS query with the RD (recursion desired) flag set.
718      * The default value is {@code true}.
719      */
720     public boolean isRecursionDesired() {
721         return recursionDesired;
722     }
723 
724     /**
725      * Returns the maximum allowed number of DNS queries to send when resolving a host name.
726      * The default value is {@code 8}.
727      */
728     public int maxQueriesPerResolve() {
729         return maxQueriesPerResolve;
730     }
731 
732     /**
733      * Returns the capacity of the datagram packet buffer (in bytes).  The default value is {@code 4096} bytes.
734      */
735     public int maxPayloadSize() {
736         return maxPayloadSize;
737     }
738 
739     /**
740      * Returns {@code true} if the case of the name in the questions of UDP queries is randomized ("0x20").
741      */
742     public boolean isCaseRandomizationEnabled() {
743         return queryProtection != null && queryProtection.isCaseRandomizationEnabled();
744     }
745 
746     /**
747      * Returns {@code true} if a client cookie as defined by RFC 7873 is sent with UDP queries and validated in the
748      * responses.
749      */
750     public boolean isDnsCookiesEnabled() {
751         return queryProtection != null && queryProtection.isCookiesEnabled();
752     }
753 
754     /**
755      * Returns the automatic inclusion of a optional records that tries to give the remote DNS server a hint about how
756      * much data the resolver can read per response is enabled.
757      */
758     public boolean isOptResourceEnabled() {
759         return optResourceEnabled;
760     }
761 
762     /**
763      * Returns the component that tries to resolve hostnames against the hosts file prior to asking to
764      * remotes DNS servers.
765      */
766     public HostsFileEntriesResolver hostsFileEntriesResolver() {
767         return hostsFileEntriesResolver;
768     }
769 
770     /**
771      * Closes the internal datagram channel used for sending and receiving DNS messages, and clears all DNS resource
772      * records from the cache. Attempting to send a DNS query or to resolve a domain name will fail once this method
773      * has been called.
774      */
775     @Override
776     public void close() {
777         resolveChannelProvider.close();
778         resolveCache.clear();
779         cnameCache.clear();
780         authoritativeDnsServerCache.clear();
781     }
782 
783     @Override
784     protected EventLoop executor() {
785         return (EventLoop) super.executor();
786     }
787 
788     private InetAddress resolveHostsFileEntry(String hostname) {
789         if (hostsFileEntriesResolver == null) {
790             return null;
791         }
792         InetAddress address = hostsFileEntriesResolver.address(hostname, resolvedAddressTypes);
793         return address == null && isLocalHostAddress(hostname)? getLocalHostAddress() : address;
794     }
795 
796     private List<InetAddress> resolveHostsFileEntries(String hostname) {
797         if (hostsFileEntriesResolver == null) {
798             return null;
799         }
800         List<InetAddress> addresses;
801         if (hostsFileEntriesResolver instanceof DefaultHostsFileEntriesResolver) {
802             addresses = ((DefaultHostsFileEntriesResolver) hostsFileEntriesResolver)
803                     .addresses(hostname, resolvedAddressTypes);
804         } else {
805             InetAddress address = hostsFileEntriesResolver.address(hostname, resolvedAddressTypes);
806             addresses = address != null? Collections.singletonList(address) : null;
807         }
808         return addresses == null && isLocalHostAddress(hostname)?
809                 Collections.singletonList(getLocalHostAddress()) : addresses;
810     }
811 
812     /**
813      * Checks whether the given hostname refers to the current computer. This is the case for:
814      * <ul>
815      *     <li>localhost.</li>
816      *     <li>any domain within .localhost.</li>
817      *     <li>the hostname of the local computer on Windows</li>
818      * </ul>
819      * <p>
820      * According to RFC 6761 Section 6.3, localhost and subdomains of localhost should be resolved to the loopback
821      * address by name resolution libraries without querying DNS servers. The hostname of the local machine can usually
822      * be resolved from the hosts file, but on Windows, this is no longer possible.
823      * <p>
824      * RFC 6761 behavior for {@code localhost} and {@code *.localhost} can be
825      * disabled via the {@code io.netty.resolver.dns.resolveLocalhostWithoutDns}
826      * system property.
827      *
828      * @param hostname the hostname that's being looked up
829      * @return true if the hostname should point to the loopback address. False otherwise.
830      * @see <a href="https://github.com/netty/netty/issues/5386">Issue 5386</a>
831      * @see <a href="https://github.com/netty/netty/issues/11142">Issue 11142</a>
832      * @see <a href="https://github.com/netty/netty/issues/16744">Issue 16744</a>
833      * @see <a href="https://www.rfc-editor.org/rfc/rfc6761.html#section-6.3">RFC 6761</a>
834      */
835     private static boolean isLocalHostAddress(String hostname) {
836         if (PlatformDependent.isWindows() && WINDOWS_HOST_NAME != null &&
837             WINDOWS_HOST_NAME.equalsIgnoreCase(hostname)) {
838             return true;
839         }
840 
841         if (!resolveLocalhostWithoutDns) {
842             return PlatformDependent.isWindows() && LOCALHOST.equalsIgnoreCase(hostname);
843         }
844 
845         if (hostname.endsWith(".")) {
846             hostname = hostname.substring(0, hostname.length() - 1);
847         }
848         return hostname.equalsIgnoreCase(LOCALHOST)
849                 || hostname.toLowerCase(Locale.US).endsWith(DOT_LOCALHOST);
850     }
851 
852     private InetAddress getLocalHostAddress() {
853         switch (resolvedAddressTypes) {
854         case IPV4_ONLY:
855         case IPV4_PREFERRED:
856             return NetUtil.LOCALHOST4;
857         case IPV6_ONLY:
858         case IPV6_PREFERRED:
859             return NetUtil.LOCALHOST6;
860         default:
861             throw new IllegalStateException("Unknown ResolvedAddressTypes " + resolvedAddressTypes);
862         }
863     }
864 
865     /**
866      * Resolves the specified name into an address.
867      *
868      * @param inetHost the name to resolve
869      * @param additionals additional records ({@code OPT})
870      *
871      * @return the address as the result of the resolution
872      */
873     public final Future<InetAddress> resolve(String inetHost, Iterable<DnsRecord> additionals) {
874         return resolve(inetHost, additionals, executor().<InetAddress>newPromise());
875     }
876 
877     /**
878      * Resolves the specified name into an address.
879      *
880      * @param inetHost the name to resolve
881      * @param additionals additional records ({@code OPT})
882      * @param promise the {@link Promise} which will be fulfilled when the name resolution is finished
883      *
884      * @return the address as the result of the resolution
885      */
886     public final Future<InetAddress> resolve(String inetHost, Iterable<DnsRecord> additionals,
887                                              Promise<InetAddress> promise) {
888         checkNotNull(promise, "promise");
889         DnsRecord[] additionalsArray = toArray(additionals, true);
890         try {
891             doResolve(inetHost, additionalsArray, promise, resolveCache);
892             return promise;
893         } catch (Exception e) {
894             return promise.setFailure(e);
895         }
896     }
897 
898     /**
899      * Resolves the specified host name and port into a list of address.
900      *
901      * @param inetHost the name to resolve
902      * @param additionals additional records ({@code OPT})
903      *
904      * @return the list of the address as the result of the resolution
905      */
906     public final Future<List<InetAddress>> resolveAll(String inetHost, Iterable<DnsRecord> additionals) {
907         return resolveAll(inetHost, additionals, executor().<List<InetAddress>>newPromise());
908     }
909 
910     /**
911      * Resolves the specified host name and port into a list of address.
912      *
913      * @param inetHost the name to resolve
914      * @param additionals additional records ({@code OPT})
915      * @param promise the {@link Promise} which will be fulfilled when the name resolution is finished
916      *
917      * @return the list of the address as the result of the resolution
918      */
919     public final Future<List<InetAddress>> resolveAll(String inetHost, Iterable<DnsRecord> additionals,
920                                                       Promise<List<InetAddress>> promise) {
921         checkNotNull(promise, "promise");
922         DnsRecord[] additionalsArray = toArray(additionals, true);
923         try {
924             doResolveAll(inetHost, additionalsArray, promise, resolveCache);
925             return promise;
926         } catch (Exception e) {
927             return promise.setFailure(e);
928         }
929     }
930 
931     @Override
932     protected void doResolve(String inetHost, Promise<InetAddress> promise) throws Exception {
933         doResolve(inetHost, EMPTY_ADDITIONALS, promise, resolveCache);
934     }
935 
936     /**
937      * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
938      * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
939      * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
940      * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
941      * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
942      *
943      * @param question the question
944      *
945      * @return the list of the {@link DnsRecord}s as the result of the resolution
946      */
947     public final Future<List<DnsRecord>> resolveAll(DnsQuestion question) {
948         return resolveAll(question, EMPTY_ADDITIONALS, executor().<List<DnsRecord>>newPromise());
949     }
950 
951     /**
952      * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
953      * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
954      * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
955      * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
956      * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
957      *
958      * @param question the question
959      * @param additionals additional records ({@code OPT})
960      *
961      * @return the list of the {@link DnsRecord}s as the result of the resolution
962      */
963     public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals) {
964         return resolveAll(question, additionals, executor().<List<DnsRecord>>newPromise());
965     }
966 
967     /**
968      * Resolves the {@link DnsRecord}s that are matched by the specified {@link DnsQuestion}. Unlike
969      * {@link #query(DnsQuestion)}, this method handles redirection, CNAMEs and multiple name servers.
970      * If the specified {@link DnsQuestion} is {@code A} or {@code AAAA}, this method looks up the configured
971      * {@link HostsFileEntries} before sending a query to the name servers. If a match is found in the
972      * {@link HostsFileEntries}, a synthetic {@code A} or {@code AAAA} record will be returned.
973      *
974      * @param question the question
975      * @param additionals additional records ({@code OPT})
976      * @param promise the {@link Promise} which will be fulfilled when the resolution is finished
977      *
978      * @return the list of the {@link DnsRecord}s as the result of the resolution
979      */
980     public final Future<List<DnsRecord>> resolveAll(DnsQuestion question, Iterable<DnsRecord> additionals,
981                                                     Promise<List<DnsRecord>> promise) {
982         final DnsRecord[] additionalsArray = toArray(additionals, true);
983         return resolveAll(question, additionalsArray, promise);
984     }
985 
986     private Future<List<DnsRecord>> resolveAll(final DnsQuestion question, final DnsRecord[] additionals,
987                                                final Promise<List<DnsRecord>> promise) {
988         checkNotNull(question, "question");
989         checkNotNull(promise, "promise");
990 
991         // Respect /etc/hosts as well if the record type is A or AAAA.
992         final DnsRecordType type = question.type();
993         final String hostname = question.name();
994 
995         if (type == DnsRecordType.A || type == DnsRecordType.AAAA) {
996             final List<InetAddress> hostsFileEntries = resolveHostsFileEntries(hostname);
997             if (hostsFileEntries != null) {
998                 List<DnsRecord> result = new ArrayList<DnsRecord>();
999                 for (InetAddress hostsFileEntry : hostsFileEntries) {
1000                     ByteBuf content = null;
1001                     if (hostsFileEntry instanceof Inet4Address) {
1002                         if (type == DnsRecordType.A) {
1003                             content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress());
1004                         }
1005                     } else if (hostsFileEntry instanceof Inet6Address) {
1006                         if (type == DnsRecordType.AAAA) {
1007                             content = Unpooled.wrappedBuffer(hostsFileEntry.getAddress());
1008                         }
1009                     }
1010                     if (content != null) {
1011                         // Our current implementation does not support reloading the hosts file,
1012                         // so use a fairly large TTL (1 day, i.e. 86400 seconds).
1013                         result.add(new DefaultDnsRawRecord(hostname, type, 86400, content));
1014                     }
1015                 }
1016 
1017                 if (!result.isEmpty()) {
1018                     if (!trySuccess(promise, result)) {
1019                         // We were not able to transfer ownership, release the records to prevent leaks.
1020                         for (DnsRecord r: result) {
1021                             ReferenceCountUtil.safeRelease(r);
1022                         }
1023                     }
1024                     return promise;
1025                 }
1026             }
1027         }
1028 
1029         ChannelFuture f = resolveChannelProvider.nextResolveChannel(promise);
1030         if (f.isDone()) {
1031             resolveAllNow(f, hostname, question, additionals, promise);
1032         } else {
1033             f.addListener((ChannelFutureListener) f1 -> resolveAllNow(f1, hostname, question, additionals, promise));
1034         }
1035         return promise;
1036     }
1037 
1038     private void resolveAllNow(ChannelFuture f, String hostname, final DnsQuestion question,
1039                                final DnsRecord[] additionals, final Promise<List<DnsRecord>> promise) {
1040         if (f.isSuccess()) {
1041             // It was not A/AAAA question or there was no entry in /etc/hosts.
1042             final DnsServerAddressStream nameServerAddrs =
1043                     dnsServerAddressStreamProvider.nameServerAddressStream(hostname);
1044 
1045             new DnsRecordResolveContext(DnsNameResolver.this, f.channel(), promise, question, additionals,
1046                     nameServerAddrs, maxQueriesPerResolve).resolve(promise);
1047         } else {
1048             UnknownHostException e = toException(f, hostname, question, additionals);
1049             promise.setFailure(e);
1050         }
1051     }
1052 
1053     private static UnknownHostException toException(
1054             ChannelFuture f, String hostname, DnsQuestion question, DnsRecord[] additionals) {
1055         UnknownHostException e = new UnknownHostException(
1056                 "Failed to resolve '" + hostname + "', couldn't setup transport: " + f.channel());
1057         e.initCause(f.cause());
1058 
1059         if (question != null) {
1060             ReferenceCountUtil.release(question);
1061         }
1062         for (DnsRecord record : additionals) {
1063             ReferenceCountUtil.release(record);
1064         }
1065         return e;
1066     }
1067 
1068     private static DnsRecord[] toArray(Iterable<DnsRecord> additionals, boolean validateType) {
1069         checkNotNull(additionals, "additionals");
1070         if (additionals instanceof Collection) {
1071             Collection<DnsRecord> records = (Collection<DnsRecord>) additionals;
1072             for (DnsRecord r: additionals) {
1073                 validateAdditional(r, validateType);
1074             }
1075             return records.toArray(new DnsRecord[records.size()]);
1076         }
1077 
1078         Iterator<DnsRecord> additionalsIt = additionals.iterator();
1079         if (!additionalsIt.hasNext()) {
1080             return EMPTY_ADDITIONALS;
1081         }
1082         List<DnsRecord> records = new ArrayList<DnsRecord>();
1083         do {
1084             DnsRecord r = additionalsIt.next();
1085             validateAdditional(r, validateType);
1086             records.add(r);
1087         } while (additionalsIt.hasNext());
1088 
1089         return records.toArray(new DnsRecord[records.size()]);
1090     }
1091 
1092     private static void validateAdditional(DnsRecord record, boolean validateType) {
1093         checkNotNull(record, "record");
1094         if (validateType && record instanceof DnsRawRecord) {
1095             throw new IllegalArgumentException("DnsRawRecord implementations not allowed: " + record);
1096         }
1097     }
1098 
1099     private InetAddress loopbackAddress() {
1100         switch (preferredAddressType()) {
1101             case INET:
1102                 return NetUtil.LOCALHOST4;
1103             case INET6:
1104                 return NetUtil.LOCALHOST6;
1105             default:
1106                 throw new UnsupportedOperationException("Only INET and INET6 are supported");
1107         }
1108     }
1109 
1110     /**
1111      * Hook designed for extensibility so one can pass a different cache on each resolution attempt
1112      * instead of using the global one.
1113      */
1114     protected void doResolve(String inetHost,
1115                              final DnsRecord[] additionals,
1116                              final Promise<InetAddress> promise,
1117                              final DnsCache resolveCache) throws Exception {
1118         if (inetHost == null || inetHost.isEmpty()) {
1119             // If an empty hostname is used we should use "localhost", just like InetAddress.getByName(...) does.
1120             promise.setSuccess(loopbackAddress());
1121             return;
1122         }
1123         final InetAddress address = NetUtil.createInetAddressFromIpAddressString(inetHost);
1124         if (address != null) {
1125             // The inetHost is actually an ipaddress.
1126             promise.setSuccess(address);
1127             return;
1128         }
1129 
1130         final String hostname = hostname(inetHost);
1131 
1132         InetAddress hostsFileEntry = resolveHostsFileEntry(hostname);
1133         if (hostsFileEntry != null) {
1134             promise.setSuccess(hostsFileEntry);
1135             return;
1136         }
1137 
1138         if (!doResolveCached(hostname, additionals, promise, resolveCache)) {
1139             ChannelFuture f = resolveChannelProvider.nextResolveChannel(promise);
1140             if (f.isDone()) {
1141                 doResolveNow(f, hostname, additionals, promise, resolveCache);
1142             } else {
1143                 f.addListener((ChannelFutureListener) f1 ->
1144                         doResolveNow(f1, hostname, additionals, promise, resolveCache));
1145             }
1146         }
1147     }
1148 
1149     private void doResolveNow(ChannelFuture f, final String hostname, final DnsRecord[] additionals,
1150                               final Promise<InetAddress> promise,
1151                               final DnsCache resolveCache) {
1152         if (f.isSuccess()) {
1153             doResolveUncached(f.channel(), hostname, additionals, promise,
1154                     resolveCache, completeOncePreferredResolved);
1155         } else {
1156             UnknownHostException e = toException(f, hostname, null, additionals);
1157             promise.setFailure(e);
1158         }
1159     }
1160 
1161     private boolean doResolveCached(String hostname,
1162                                     DnsRecord[] additionals,
1163                                     Promise<InetAddress> promise,
1164                                     DnsCache resolveCache) {
1165         final List<? extends DnsCacheEntry> cachedEntries = resolveCache.get(hostname, additionals);
1166         if (cachedEntries == null || cachedEntries.isEmpty()) {
1167             return false;
1168         }
1169 
1170         Throwable cause = cachedEntries.get(0).cause();
1171         if (cause == null) {
1172             final int numEntries = cachedEntries.size();
1173             // Find the first entry with the preferred address type.
1174             for (SocketProtocolFamily f : resolvedInternetProtocolFamilies) {
1175                 for (int i = 0; i < numEntries; i++) {
1176                     final DnsCacheEntry e = cachedEntries.get(i);
1177                     final Class<? extends InetAddress> addressType = addressType(f);
1178                     if (addressType != null && addressType.isInstance(e.address())) {
1179                         trySuccess(promise, e.address());
1180                         return true;
1181                     }
1182                 }
1183             }
1184             return false;
1185         } else {
1186             tryFailure(promise, cause);
1187             return true;
1188         }
1189     }
1190 
1191     static Class<? extends InetAddress> addressType(SocketProtocolFamily f) {
1192         switch (f) {
1193             case INET:
1194                 return Inet4Address.class;
1195             case INET6:
1196                 return Inet6Address.class;
1197             default:
1198                 return null;
1199         }
1200     }
1201 
1202     static <T> boolean trySuccess(Promise<T> promise, T result) {
1203         final boolean notifiedRecords = promise.trySuccess(result);
1204         if (!notifiedRecords) {
1205             // There is nothing really wrong with not be able to notify the promise as we may have raced here because
1206             // of multiple queries that have been executed. Log it with trace level anyway just in case the user
1207             // wants to better understand what happened.
1208             logger.trace("Failed to notify success ({}) to a promise: {}", result, promise);
1209         }
1210         return notifiedRecords;
1211     }
1212 
1213     private static void tryFailure(Promise<?> promise, Throwable cause) {
1214         if (!promise.tryFailure(cause)) {
1215             // There is nothing really wrong with not be able to notify the promise as we may have raced here because
1216             // of multiple queries that have been executed. Log it with trace level anyway just in case the user
1217             // wants to better understand what happened.
1218             logger.trace("Failed to notify failure to a promise: {}", promise, cause);
1219         }
1220     }
1221 
1222     private void doResolveUncached(Channel channel,
1223                                    String hostname,
1224                                    DnsRecord[] additionals,
1225                                    final Promise<InetAddress> promise,
1226                                    DnsCache resolveCache, boolean completeEarlyIfPossible) {
1227         final Promise<List<InetAddress>> allPromise = executor().newPromise();
1228         doResolveAllUncached(channel, hostname, additionals, promise, allPromise,
1229                 resolveCache, completeEarlyIfPossible);
1230         allPromise.addListener((FutureListener<List<InetAddress>>) future -> {
1231             if (future.isSuccess()) {
1232                 trySuccess(promise, future.getNow().get(0));
1233             } else {
1234                 tryFailure(promise, future.cause());
1235             }
1236         });
1237     }
1238 
1239     @Override
1240     protected void doResolveAll(String inetHost, Promise<List<InetAddress>> promise) throws Exception {
1241         doResolveAll(inetHost, EMPTY_ADDITIONALS, promise, resolveCache);
1242     }
1243 
1244     /**
1245      * Hook designed for extensibility so one can pass a different cache on each resolution attempt
1246      * instead of using the global one.
1247      */
1248     protected void doResolveAll(String inetHost,
1249                                 final DnsRecord[] additionals,
1250                                 final Promise<List<InetAddress>> promise,
1251                                 final DnsCache resolveCache) throws Exception {
1252         if (inetHost == null || inetHost.isEmpty()) {
1253             // If an empty hostname is used we should use "localhost", just like InetAddress.getAllByName(...) does.
1254             promise.setSuccess(Collections.singletonList(loopbackAddress()));
1255             return;
1256         }
1257         final InetAddress address = NetUtil.createInetAddressFromIpAddressString(inetHost);
1258         if (address != null) {
1259             // The unresolvedAddress was created via a String that contains an ipaddress.
1260             promise.setSuccess(Collections.singletonList(address));
1261             return;
1262         }
1263 
1264         final String hostname = hostname(inetHost);
1265 
1266         List<InetAddress> hostsFileEntries = resolveHostsFileEntries(hostname);
1267         if (hostsFileEntries != null) {
1268             promise.setSuccess(hostsFileEntries);
1269             return;
1270         }
1271 
1272         if (!doResolveAllCached(hostname, additionals, promise, resolveCache, this.searchDomains(),
1273                 ndots(), resolvedInternetProtocolFamilies)) {
1274             ChannelFuture f = resolveChannelProvider.nextResolveChannel(promise);
1275             if (f.isDone()) {
1276                 doResolveAllNow(f, hostname, additionals, promise, resolveCache);
1277             } else {
1278                 f.addListener((ChannelFutureListener) f1 ->
1279                         doResolveAllNow(f1, hostname, additionals, promise, resolveCache));
1280             }
1281         }
1282     }
1283 
1284     private void doResolveAllNow(ChannelFuture f, final String hostname, final DnsRecord[] additionals,
1285                               final Promise<List<InetAddress>> promise,
1286                               final DnsCache resolveCache) {
1287         if (f.isSuccess()) {
1288             doResolveAllUncached(f.channel(), hostname, additionals, promise, promise,
1289                     resolveCache, completeOncePreferredResolved);
1290         } else {
1291             UnknownHostException e = toException(f, hostname, null, additionals);
1292             promise.setFailure(e);
1293         }
1294     }
1295 
1296     private static boolean hasEntries(List<? extends DnsCacheEntry> cachedEntries) {
1297         return cachedEntries != null && !cachedEntries.isEmpty();
1298     }
1299 
1300     static boolean doResolveAllCached(String hostname,
1301                                       DnsRecord[] additionals,
1302                                       Promise<List<InetAddress>> promise,
1303                                       DnsCache resolveCache,
1304                                       String[] searchDomains,
1305                                       int ndots,
1306                                       SocketProtocolFamily[] resolvedInternetProtocolFamilies) {
1307         List<? extends DnsCacheEntry> cachedEntries = resolveCache.get(hostname, additionals);
1308         boolean resolvedWithSearchDomains = searchDomains != null && ndots > 0 && !StringUtil.endsWith(hostname, '.');
1309         if (!hasEntries(cachedEntries) && resolvedWithSearchDomains) {
1310             for (String searchDomain : searchDomains) {
1311                 final String initialHostname = hostname + '.' + searchDomain;
1312                 final List<? extends DnsCacheEntry> entries = resolveCache.get(initialHostname, additionals);
1313                 // Only a positive cache entry lets us draw a conclusion about the bare hostname. A negative entry
1314                 // just means that this specific search domain permutation does not exist, which must neither
1315                 // short-circuit the remaining search domains nor the lookup of the bare hostname itself.
1316                 if (hasEntries(entries) && entries.get(0).cause() == null) {
1317                     cachedEntries = entries;
1318                     break;
1319                 }
1320             }
1321         }
1322         if (!hasEntries(cachedEntries)) {
1323             return false;
1324         }
1325 
1326         Throwable cause = cachedEntries.get(0).cause();
1327         if (cause == null) {
1328             List<InetAddress> result = null;
1329             final int numEntries = cachedEntries.size();
1330             for (SocketProtocolFamily f : resolvedInternetProtocolFamilies) {
1331                 for (int i = 0; i < numEntries; i++) {
1332                     final DnsCacheEntry e = cachedEntries.get(i);
1333                     Class<? extends InetAddress> addressType = addressType(f);
1334                     if (addressType != null && addressType.isInstance(e.address())) {
1335                         if (result == null) {
1336                             result = new ArrayList<InetAddress>(numEntries);
1337                         }
1338                         result.add(e.address());
1339                     }
1340                 }
1341             }
1342             if (result != null) {
1343                 trySuccess(promise, result);
1344                 return true;
1345             }
1346             return false;
1347         } else {
1348             tryFailure(promise, cause);
1349             return true;
1350         }
1351     }
1352 
1353     private void doResolveAllUncached(final Channel channel,
1354                                       final String hostname,
1355                                       final DnsRecord[] additionals,
1356                                       final Promise<?> originalPromise,
1357                                       final Promise<List<InetAddress>> promise,
1358                                       final DnsCache resolveCache,
1359                                       final boolean completeEarlyIfPossible) {
1360         // Call doResolveUncached0(...) in the EventLoop as we may need to submit multiple queries which would need
1361         // to submit multiple Runnable at the end if we are not already on the EventLoop.
1362         EventExecutor executor = executor();
1363         if (executor.inEventLoop()) {
1364             doResolveAllUncached0(channel, hostname, additionals, originalPromise,
1365                                   promise, resolveCache, completeEarlyIfPossible);
1366         } else {
1367             executor.execute(new Runnable() {
1368                 @Override
1369                 public void run() {
1370                     doResolveAllUncached0(channel, hostname, additionals, originalPromise,
1371                                           promise, resolveCache, completeEarlyIfPossible);
1372                 }
1373             });
1374         }
1375     }
1376 
1377     private void doResolveAllUncached0(final Channel channel,
1378                                        final String hostname,
1379                                        final DnsRecord[] additionals,
1380                                        final Promise<?> originalPromise,
1381                                        final Promise<List<InetAddress>> promise,
1382                                        final DnsCache resolveCache,
1383                                        final boolean completeEarlyIfPossible) {
1384 
1385         assert executor().inEventLoop();
1386         final DnsServerAddressStream nameServerAddrs =
1387                 dnsServerAddressStreamProvider.nameServerAddressStream(hostname);
1388         DnsAddressResolveContext ctx = new DnsAddressResolveContext(this, channel,
1389                 originalPromise, hostname, additionals, nameServerAddrs, maxQueriesPerResolve, resolveCache,
1390                 authoritativeDnsServerCache, completeEarlyIfPossible);
1391         ctx.resolve(promise);
1392     }
1393 
1394     private static String hostname(String inetHost) {
1395         String hostname = IDN.toASCII(inetHost);
1396         // Check for https://bugs.java.com/bugdatabase/view_bug.do?bug_id=6894622
1397         if (StringUtil.endsWith(inetHost, '.') && !StringUtil.endsWith(hostname, '.')) {
1398             hostname += ".";
1399         }
1400         return hostname;
1401     }
1402 
1403     /**
1404      * Sends a DNS query with the specified question.
1405      */
1406     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(DnsQuestion question) {
1407         return query(nextNameServerAddress(), question);
1408     }
1409 
1410     /**
1411      * Sends a DNS query with the specified question with additional records.
1412      */
1413     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1414             DnsQuestion question, Iterable<DnsRecord> additionals) {
1415         return query(nextNameServerAddress(), question, additionals);
1416     }
1417 
1418     /**
1419      * Sends a DNS query with the specified question.
1420      */
1421     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1422             DnsQuestion question, Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
1423         return query(nextNameServerAddress(), question, Collections.<DnsRecord>emptyList(), promise);
1424     }
1425 
1426     private InetSocketAddress nextNameServerAddress() {
1427         return queryDnsServerAddressStream.next();
1428     }
1429 
1430     /**
1431      * Sends a DNS query with the specified question using the specified name server list.
1432      */
1433     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1434             final InetSocketAddress nameServerAddr, final DnsQuestion question) {
1435         return query(nameServerAddr, question, Collections.<DnsRecord>emptyList());
1436     }
1437 
1438     /**
1439      * Sends a DNS query with the specified question with additional records using the specified name server list.
1440      */
1441     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1442             final InetSocketAddress nameServerAddr, final DnsQuestion question, final Iterable<DnsRecord> additionals) {
1443         return query(nameServerAddr, question, additionals,
1444                 executor().<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>>newPromise());
1445     }
1446 
1447     /**
1448      * Sends a DNS query with the specified question using the specified name server list.
1449      */
1450     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1451             final InetSocketAddress nameServerAddr, final DnsQuestion question,
1452             final Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
1453         return query(nameServerAddr, question, Collections.<DnsRecord>emptyList(), promise);
1454     }
1455 
1456     /**
1457      * Sends a DNS query with the specified question with additional records using the specified name server list.
1458      */
1459     public Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> query(
1460             final InetSocketAddress nameServerAddr, final DnsQuestion question,
1461             final Iterable<DnsRecord> additionals,
1462             final Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
1463 
1464         ChannelFuture f = resolveChannelProvider.nextResolveChannel(promise);
1465         final DnsRecord[] additionalsArray = toArray(additionals, false);
1466         if (f.isDone()) {
1467             if (f.isSuccess()) {
1468                 return doQuery(f.channel(), nameServerAddr, question,
1469                         NoopDnsQueryLifecycleObserver.INSTANCE, additionalsArray,
1470                         true, promise);
1471             } else {
1472                 UnknownHostException e = toException(f, question.name(), question, additionalsArray);
1473                 promise.setFailure(e);
1474                 return executor().newFailedFuture(e);
1475             }
1476         } else {
1477             f.addListener((ChannelFutureListener) f1 -> {
1478                 if (f1.isSuccess()) {
1479                     // doQuery(...) completes and returns the caller's own promise, so just run the query
1480                     // against it and return that same promise below; no separate promise to bridge is needed.
1481                     doQuery(f1.channel(), nameServerAddr, question, NoopDnsQueryLifecycleObserver.INSTANCE,
1482                             additionalsArray, true, promise);
1483                 } else {
1484                     promise.tryFailure(toException(f1, question.name(), question, additionalsArray));
1485                 }
1486             });
1487             return cast(promise);
1488         }
1489     }
1490 
1491     /**
1492      * Returns {@code true} if the {@link Throwable} was caused by an timeout or transport error.
1493      * These methods can be used on the {@link Future#cause()} that is returned by the various methods exposed by this
1494      * {@link DnsNameResolver}.
1495      */
1496     public static boolean isTransportOrTimeoutError(Throwable cause) {
1497         return cause != null && cause.getCause() instanceof DnsNameResolverException;
1498     }
1499 
1500     /**
1501      * Returns {@code true} if the {@link Throwable} was caused by an timeout.
1502      * These methods can be used on the {@link Future#cause()} that is returned by the various methods exposed by this
1503      * {@link DnsNameResolver}.
1504      */
1505     public static boolean isTimeoutError(Throwable cause) {
1506         return cause != null && cause.getCause() instanceof DnsNameResolverTimeoutException;
1507     }
1508 
1509     @SuppressWarnings("unchecked")
1510     final Future<AddressedEnvelope<DnsResponse, InetSocketAddress>> doQuery(
1511             Channel channel,
1512             InetSocketAddress nameServerAddr, DnsQuestion question,
1513             final DnsQueryLifecycleObserver queryLifecycleObserver,
1514             DnsRecord[] additionals, boolean flush,
1515             Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> promise) {
1516         final Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> castPromise = cast(
1517                 checkNotNull(promise, "promise"));
1518         final int payloadSize = isOptResourceEnabled() ? maxPayloadSize() : 0;
1519 
1520         if (inflightLookups != null && (additionals == null || additionals.length == 0)) {
1521             Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> inflight =
1522                     inflightLookups.get(question);
1523             if (inflight != null) {
1524                 // We have a query / response inflight, let's just cascade on it to reduce the network traffic.
1525                 inflight.addListener(f -> {
1526                     if (f.isSuccess()) {
1527                         // Notify the observer and after that the promise
1528                         queryLifecycleObserver.querySucceed();
1529                         AddressedEnvelope<? extends DnsResponse, InetSocketAddress> result =
1530                                 (AddressedEnvelope<? extends DnsResponse, InetSocketAddress>) f.getNow();
1531 
1532                         // Retain the result as the listener on the promise is responsible to release it.
1533                         ReferenceCountUtil.retain(result);
1534                         if (!promise.trySuccess(result)) {
1535                             // The promise was already cancelled or failed, so nobody will release the result;
1536                             // release the reference we just retained to avoid leaking it.
1537                             ReferenceCountUtil.release(result);
1538                         }
1539                     } else {
1540                         Throwable cause = f.cause();
1541                         if (isTimeoutError(cause)) {
1542                             doQueryNow(channel, nameServerAddr, question, queryLifecycleObserver,
1543                                     additionals, flush, payloadSize, castPromise);
1544                         } else {
1545                             // Notify the observer and after that the promise
1546                             queryLifecycleObserver.queryFailed(cause);
1547                             promise.tryFailure(cause);
1548                         }
1549                     }
1550                 });
1551                 return castPromise;
1552             } else if (inflightLookups.size() < maxNumConsolidation) {
1553                 // Create a new promise as we need to ensure we are the first that will add a listener to it to retain
1554                 // the result before anyone can release it.
1555                 Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> newPromise =
1556                         executor().newPromise();
1557                 Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> old =
1558                         inflightLookups.put(question, newPromise);
1559                 assert old == null;
1560 
1561                 newPromise.addListener(f -> {
1562                     // Remove the promise and add another listener to it that will call release() on the result.
1563                     // As the execution of the listeners is guaranteed to be in the same order as how these were added
1564                     // we know that all previous added listeners had a chance to handle the result already.
1565                     Promise<AddressedEnvelope<? extends DnsResponse, InetSocketAddress>> p =
1566                             inflightLookups.remove(question);
1567                     assert p == newPromise;
1568 
1569                     if (f.isSuccess()) {
1570                         // On success we need to retain the result so listeners that are added after this one
1571                         // will still be able to use the result.
1572                         AddressedEnvelope<? extends DnsResponse, InetSocketAddress> result =
1573                                 (AddressedEnvelope<? extends DnsResponse, InetSocketAddress>) f.getNow();
1574                         ReferenceCountUtil.retain(result);
1575                         if (!promise.trySuccess(result)) {
1576                             // The promise was already cancelled or failed; release the reference we retained
1577                             // (the one held by newPromise is released by RELEASE_LISTENER below).
1578                             ReferenceCountUtil.release(result);
1579                         }
1580                     } else {
1581                         promise.tryFailure(f.cause());
1582                     }
1583 
1584                     // Always release newPromise's own reference, even if the hand-off above failed.
1585                     p.addListener(RELEASE_LISTENER);
1586                 });
1587 
1588                 doQueryNow(channel, nameServerAddr, question, queryLifecycleObserver,
1589                         additionals, flush, payloadSize, cast(newPromise));
1590 
1591                 // Return the original castPromise which will be notified by the newPromise that we used above.
1592                 // This was it's impossible for the user to add any extra listeners to the newPromise itself, which
1593                 // is needed to guarantee the correct life-cycle of the reference counted response.
1594                 return castPromise;
1595             }
1596         }
1597         doQueryNow(channel, nameServerAddr, question, queryLifecycleObserver,
1598                 additionals, flush, payloadSize, castPromise);
1599         return castPromise;
1600     }
1601 
1602     private void doQueryNow(
1603             Channel channel,
1604             InetSocketAddress nameServerAddr, DnsQuestion question,
1605             final DnsQueryLifecycleObserver queryLifecycleObserver,
1606             DnsRecord[] additionals, boolean flush,
1607             int payloadSize,
1608             Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> promise) {
1609         DnsQueryContext queryContext = new DatagramDnsQueryContext(channel, nameServerAddr,
1610                 queryContextManager, queryLifecycleObserver, payloadSize,
1611                 isRecursionDesired(), queryTimeoutMillis(), question, additionals,
1612                 promise, socketBootstrap, retryWithTcpOnTimeout, queryProtection);
1613         queryContext.writeQuery(flush);
1614     }
1615 
1616     @SuppressWarnings("unchecked")
1617     private static Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>> cast(Promise<?> promise) {
1618         return (Promise<AddressedEnvelope<DnsResponse, InetSocketAddress>>) promise;
1619     }
1620 
1621     final DnsServerAddressStream newNameServerAddressStream(String hostname) {
1622         return dnsServerAddressStreamProvider.nameServerAddressStream(hostname);
1623     }
1624 
1625     private static final class DnsResponseHandler extends ChannelInboundHandlerAdapter {
1626 
1627         private final DnsQueryContextManager queryContextManager;
1628 
1629         DnsResponseHandler(DnsQueryContextManager queryContextManager) {
1630             this.queryContextManager = queryContextManager;
1631         }
1632 
1633         @Override
1634         public boolean isSharable() {
1635             return true;
1636         }
1637 
1638         @Override
1639         public void channelRead(ChannelHandlerContext ctx, Object msg) {
1640             final Channel qCh = ctx.channel();
1641             final DatagramDnsResponse res = (DatagramDnsResponse) msg;
1642             final int queryId = res.id();
1643             logger.debug("{} RECEIVED: UDP [{}: {}], {}", qCh, queryId, res.sender(), res);
1644 
1645             final DnsQueryContext qCtx = queryContextManager.get(res.sender(), queryId);
1646             if (qCtx == null) {
1647                 logger.debug("{} Received a DNS response with an unknown ID: UDP [{}: {}]",
1648                         qCh, queryId, res.sender());
1649                 res.release();
1650                 return;
1651             } else if (qCtx.isDone()) {
1652                 logger.debug("{} Received a DNS response for a query that was timed out or cancelled: UDP [{}: {}]",
1653                         qCh, queryId, res.sender());
1654                 res.release();
1655                 return;
1656             }
1657 
1658             // The context will handle truncation itself.
1659             qCtx.finishSuccess(res, res.isTruncated());
1660         }
1661 
1662         @Override
1663         public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
1664             if (cause instanceof CorruptedFrameException) {
1665                 logger.debug("{} Unable to decode DNS response: UDP", ctx.channel(), cause);
1666             } else {
1667                 logger.warn("{} Unexpected exception: UDP", ctx.channel(), cause);
1668             }
1669         }
1670     }
1671 
1672     private interface DnsResolveChannelProvider {
1673 
1674         /**
1675          * Return the next {@link ChannelFuture} that contains the {@link Channel} that should be used for resolving
1676          * a chain of queries.
1677          *
1678          * @param resolutionFuture  the {@link Future} that will be notified once th resolution completes.
1679          * @return                  the {@link ChannelFuture}
1680          */
1681         <T> ChannelFuture nextResolveChannel(Future<T> resolutionFuture);
1682 
1683         /**
1684          * Close the {@link DnsResolveChannelProvider} and so cleanup resources if needed.
1685          */
1686         void close();
1687     }
1688 
1689     private static ChannelFuture registerOrBind(Bootstrap bootstrap, SocketAddress localAddress) {
1690         return localAddress == null ? bootstrap.register() : bootstrap.bind(localAddress);
1691     }
1692 
1693     private static final class DnsResolveChannelPerResolverProvider implements DnsResolveChannelProvider {
1694 
1695         private final ChannelFuture resolveChannelFuture;
1696 
1697         DnsResolveChannelPerResolverProvider(Bootstrap bootstrap, SocketAddress localAddress) {
1698             resolveChannelFuture = registerOrBind(bootstrap, localAddress);
1699         }
1700 
1701         @Override
1702         public <T> ChannelFuture nextResolveChannel(Future<T> resolutionFuture) {
1703             return resolveChannelFuture;
1704         }
1705 
1706         @Override
1707         public void close() {
1708             resolveChannelFuture.channel().close();
1709         }
1710     }
1711 
1712     private static final class DnsResolveChannelPerResolutionProvider implements DnsResolveChannelProvider {
1713 
1714         private final Bootstrap bootstrap;
1715         private final SocketAddress localAddress;
1716 
1717         DnsResolveChannelPerResolutionProvider(Bootstrap bootstrap, SocketAddress localAddress) {
1718             this.bootstrap = bootstrap;
1719             this.localAddress = localAddress;
1720         }
1721 
1722         @Override
1723         public <T> ChannelFuture nextResolveChannel(Future<T> resolutionFuture) {
1724             final ChannelFuture f = registerOrBind(bootstrap, localAddress);
1725             resolutionFuture.addListener((FutureListener<T>) future -> {
1726                 // Always just close the Channel once the resolution is considered complete.
1727                 f.channel().close();
1728             });
1729             return f;
1730         }
1731 
1732         @Override
1733         public void close() {
1734             // NOOP
1735         }
1736     }
1737 }