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