1 /*
2 * Copyright 2015 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.channel.ChannelFactory;
19 import io.netty.channel.EventLoop;
20 import io.netty.channel.ReflectiveChannelFactory;
21 import io.netty.channel.socket.DatagramChannel;
22 import io.netty.channel.socket.InternetProtocolFamily;
23 import io.netty.channel.socket.SocketChannel;
24 import io.netty.resolver.HostsFileEntriesResolver;
25 import io.netty.resolver.ResolvedAddressTypes;
26 import io.netty.util.concurrent.Future;
27 import io.netty.util.internal.EmptyArrays;
28 import io.netty.util.internal.ObjectUtil;
29 import io.netty.util.internal.logging.InternalLogger;
30 import io.netty.util.internal.logging.InternalLoggerFactory;
31
32 import java.net.InetSocketAddress;
33 import java.net.SocketAddress;
34 import java.util.Arrays;
35 import java.util.LinkedHashSet;
36 import java.util.Set;
37
38 import static io.netty.util.internal.ObjectUtil.checkNotNull;
39 import static io.netty.util.internal.ObjectUtil.intValue;
40
41 /**
42 * A {@link DnsNameResolver} builder.
43 */
44 public final class DnsNameResolverBuilder {
45
46 private static final InternalLogger logger = InternalLoggerFactory.getInstance(DnsNameResolverBuilder.class);
47 static final SocketAddress DEFAULT_LOCAL_ADDRESS = new InetSocketAddress(0);
48
49 volatile EventLoop eventLoop;
50 private ChannelFactory<? extends DatagramChannel> datagramChannelFactory;
51 private ChannelFactory<? extends SocketChannel> socketChannelFactory;
52 private boolean retryOnTimeout;
53
54 private DnsCache resolveCache;
55 private DnsCnameCache cnameCache;
56 private AuthoritativeDnsServerCache authoritativeDnsServerCache;
57 private SocketAddress localAddress = DEFAULT_LOCAL_ADDRESS;
58 private Integer minTtl;
59 private Integer maxTtl;
60 private Integer negativeTtl;
61 private long queryTimeoutMillis = -1;
62 private ResolvedAddressTypes resolvedAddressTypes = DnsNameResolver.DEFAULT_RESOLVE_ADDRESS_TYPES;
63 private boolean completeOncePreferredResolved;
64 private boolean recursionDesired = true;
65 private int maxQueriesPerResolve = -1;
66 private boolean traceEnabled;
67 private int maxPayloadSize = 4096;
68 private boolean optResourceEnabled = true;
69 private HostsFileEntriesResolver hostsFileEntriesResolver = HostsFileEntriesResolver.DEFAULT;
70 private DnsServerAddressStreamProvider dnsServerAddressStreamProvider =
71 DnsServerAddressStreamProviders.platformDefault();
72 private DnsServerAddressStream queryDnsServerAddressStream;
73 private DnsQueryLifecycleObserverFactory dnsQueryLifecycleObserverFactory =
74 NoopDnsQueryLifecycleObserverFactory.INSTANCE;
75 private String[] searchDomains;
76 private int ndots = -1;
77 private boolean decodeIdn = true;
78
79 private int maxNumConsolidation;
80 private DnsNameResolverChannelStrategy datagramChannelStrategy = DnsNameResolverChannelStrategy.ChannelPerResolver;
81 private boolean caseRandomizationEnabled;
82 private boolean dnsCookiesEnabled;
83
84 /**
85 * Creates a new builder.
86 */
87 public DnsNameResolverBuilder() {
88 }
89
90 /**
91 * Creates a new builder.
92 *
93 * @param eventLoop the {@link EventLoop} which will perform the communication with the DNS
94 * servers.
95 */
96 public DnsNameResolverBuilder(EventLoop eventLoop) {
97 eventLoop(eventLoop);
98 }
99
100 /**
101 * Sets the {@link EventLoop} which will perform the communication with the DNS servers.
102 *
103 * @param eventLoop the {@link EventLoop}
104 * @return {@code this}
105 */
106 public DnsNameResolverBuilder eventLoop(EventLoop eventLoop) {
107 this.eventLoop = eventLoop;
108 return this;
109 }
110
111 @Deprecated
112 protected ChannelFactory<? extends DatagramChannel> channelFactory() {
113 return this.datagramChannelFactory;
114 }
115
116 ChannelFactory<? extends DatagramChannel> datagramChannelFactory() {
117 return this.datagramChannelFactory;
118 }
119
120 /**
121 * Sets the {@link ChannelFactory} that will create a {@link DatagramChannel}.
122 * <p>
123 * If <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should be supported as well it is required
124 * to call the {@link #socketChannelFactory(ChannelFactory)} or {@link #socketChannelType(Class)} method.
125 *
126 * @param datagramChannelFactory the {@link ChannelFactory}
127 * @return {@code this}
128 * @deprecated use {@link #datagramChannelFactory(ChannelFactory)}
129 */
130 @Deprecated
131 public DnsNameResolverBuilder channelFactory(ChannelFactory<? extends DatagramChannel> datagramChannelFactory) {
132 datagramChannelFactory(datagramChannelFactory);
133 return this;
134 }
135
136 /**
137 * Sets the {@link ChannelFactory} that will create a {@link DatagramChannel}.
138 * <p>
139 * If <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should be supported as well it is required
140 * to call the {@link #socketChannelFactory(ChannelFactory)} or {@link #socketChannelType(Class)} method.
141 *
142 * @param datagramChannelFactory the {@link ChannelFactory}
143 * @return {@code this}
144 */
145 public DnsNameResolverBuilder datagramChannelFactory(
146 ChannelFactory<? extends DatagramChannel> datagramChannelFactory) {
147 this.datagramChannelFactory = datagramChannelFactory;
148 return this;
149 }
150
151 /**
152 * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type.
153 * Use as an alternative to {@link #channelFactory(ChannelFactory)}.
154 * <p>
155 * If <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should be supported as well it is required
156 * to call the {@link #socketChannelFactory(ChannelFactory)} or {@link #socketChannelType(Class)} method.
157 *
158 * @param channelType the type
159 * @return {@code this}
160 * @deprecated use {@link #datagramChannelType(Class)}
161 */
162 @Deprecated
163 public DnsNameResolverBuilder channelType(Class<? extends DatagramChannel> channelType) {
164 return datagramChannelFactory(new ReflectiveChannelFactory<DatagramChannel>(channelType));
165 }
166
167 /**
168 * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type.
169 * Use as an alternative to {@link #datagramChannelFactory(ChannelFactory)}.
170 * <p>
171 * If <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should be supported as well it is required
172 * to call the {@link #socketChannelFactory(ChannelFactory)} or {@link #socketChannelType(Class)} method.
173 *
174 * @param channelType the type
175 * @return {@code this}
176 */
177 public DnsNameResolverBuilder datagramChannelType(Class<? extends DatagramChannel> channelType) {
178 return datagramChannelFactory(new ReflectiveChannelFactory<DatagramChannel>(channelType));
179 }
180
181 /**
182 * Sets the {@link ChannelFactory} that will create a {@link SocketChannel} for
183 * <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> if needed.
184 * <p>
185 * TCP fallback is <strong>not</strong> enabled by default and must be enabled by providing a non-null
186 * {@link ChannelFactory} for this method.
187 *
188 * @param channelFactory the {@link ChannelFactory} or {@code null}
189 * if <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should not be supported.
190 * By default, TCP fallback is not enabled.
191 * @return {@code this}
192 */
193 public DnsNameResolverBuilder socketChannelFactory(ChannelFactory<? extends SocketChannel> channelFactory) {
194 return socketChannelFactory(channelFactory, false);
195 }
196
197 /**
198 * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type for
199 * <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> if needed.
200 * Use as an alternative to {@link #socketChannelFactory(ChannelFactory)}.
201 * <p>
202 * TCP fallback is <strong>not</strong> enabled by default and must be enabled by providing a non-null
203 * {@code channelType} for this method.
204 *
205 * @param channelType the type or {@code null} if <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a>
206 * should not be supported. By default, TCP fallback is not enabled.
207 * @return {@code this}
208 */
209 public DnsNameResolverBuilder socketChannelType(Class<? extends SocketChannel> channelType) {
210 return socketChannelType(channelType, false);
211 }
212
213 /**
214 * Sets the {@link ChannelFactory} that will create a {@link SocketChannel} for
215 * <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> if needed.
216 * <p>
217 * TCP fallback is <strong>not</strong> enabled by default and must be enabled by providing a non-null
218 * {@link ChannelFactory} for this method.
219 *
220 * @param channelFactory the {@link ChannelFactory} or {@code null}
221 * if <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> should not be supported.
222 * By default, TCP fallback is not enabled.
223 * @param retryOnTimeout if {@code true} the {@link DnsNameResolver} will also fallback to TCP if a timeout
224 * was detected, if {@code false} it will only try to use TCP if the response was marked
225 * as truncated.
226 * @return {@code this}
227 */
228 public DnsNameResolverBuilder socketChannelFactory(
229 ChannelFactory<? extends SocketChannel> channelFactory, boolean retryOnTimeout) {
230 this.socketChannelFactory = channelFactory;
231 this.retryOnTimeout = retryOnTimeout;
232 return this;
233 }
234
235 /**
236 * Sets the {@link ChannelFactory} as a {@link ReflectiveChannelFactory} of this type for
237 * <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a> if needed.
238 * Use as an alternative to {@link #socketChannelFactory(ChannelFactory)}.
239 * <p>
240 * TCP fallback is <strong>not</strong> enabled by default and must be enabled by providing a non-null
241 * {@code channelType} for this method.
242 *
243 * @param channelType the type or {@code null} if <a href="https://tools.ietf.org/html/rfc7766">TCP fallback</a>
244 * should not be supported. By default, TCP fallback is not enabled.
245 * @param retryOnTimeout if {@code true} the {@link DnsNameResolver} will also fallback to TCP if a timeout
246 * was detected, if {@code false} it will only try to use TCP if the response was marked
247 * as truncated.
248 * @return {@code this}
249 */
250 public DnsNameResolverBuilder socketChannelType(
251 Class<? extends SocketChannel> channelType, boolean retryOnTimeout) {
252 if (channelType == null) {
253 return socketChannelFactory(null, retryOnTimeout);
254 }
255 return socketChannelFactory(new ReflectiveChannelFactory<SocketChannel>(channelType), retryOnTimeout);
256 }
257
258 /**
259 * Sets the cache for resolution results.
260 *
261 * @param resolveCache the DNS resolution results cache
262 * @return {@code this}
263 */
264 public DnsNameResolverBuilder resolveCache(DnsCache resolveCache) {
265 this.resolveCache = resolveCache;
266 return this;
267 }
268
269 /**
270 * Sets the cache for {@code CNAME} mappings.
271 *
272 * @param cnameCache the cache used to cache {@code CNAME} mappings for a domain.
273 * @return {@code this}
274 */
275 public DnsNameResolverBuilder cnameCache(DnsCnameCache cnameCache) {
276 this.cnameCache = cnameCache;
277 return this;
278 }
279
280 /**
281 * Set the factory used to generate objects which can observe individual DNS queries.
282 * @param lifecycleObserverFactory the factory used to generate objects which can observe individual DNS queries.
283 * @return {@code this}
284 */
285 public DnsNameResolverBuilder dnsQueryLifecycleObserverFactory(DnsQueryLifecycleObserverFactory
286 lifecycleObserverFactory) {
287 this.dnsQueryLifecycleObserverFactory = checkNotNull(lifecycleObserverFactory, "lifecycleObserverFactory");
288 return this;
289 }
290
291 /**
292 * Sets the cache for authoritative NS servers
293 *
294 * @param authoritativeDnsServerCache the authoritative NS servers cache
295 * @return {@code this}
296 * @deprecated Use {@link #authoritativeDnsServerCache(AuthoritativeDnsServerCache)}
297 */
298 @Deprecated
299 public DnsNameResolverBuilder authoritativeDnsServerCache(DnsCache authoritativeDnsServerCache) {
300 this.authoritativeDnsServerCache = new AuthoritativeDnsServerCacheAdapter(authoritativeDnsServerCache);
301 return this;
302 }
303
304 /**
305 * Sets the cache for authoritative NS servers
306 *
307 * @param authoritativeDnsServerCache the authoritative NS servers cache
308 * @return {@code this}
309 */
310 public DnsNameResolverBuilder authoritativeDnsServerCache(AuthoritativeDnsServerCache authoritativeDnsServerCache) {
311 this.authoritativeDnsServerCache = authoritativeDnsServerCache;
312 return this;
313 }
314
315 /**
316 * Configure the address that will be used to bind too. If {@code null} the default will be used.
317 * @param localAddress the bind address
318 * @return {@code this}
319 */
320 public DnsNameResolverBuilder localAddress(SocketAddress localAddress) {
321 this.localAddress = localAddress;
322 return this;
323 }
324
325 /**
326 * Sets the minimum and maximum TTL of the cached DNS resource records (in seconds). If the TTL of the DNS
327 * resource record returned by the DNS server is less than the minimum TTL or greater than the maximum TTL,
328 * this resolver will ignore the TTL from the DNS server and use the minimum TTL or the maximum TTL instead
329 * respectively.
330 * The default value is {@code 0} and {@link Integer#MAX_VALUE}, which practically tells this resolver to
331 * respect the TTL from the DNS server.
332 *
333 * @param minTtl the minimum TTL
334 * @param maxTtl the maximum TTL
335 * @return {@code this}
336 */
337 public DnsNameResolverBuilder ttl(int minTtl, int maxTtl) {
338 this.maxTtl = maxTtl;
339 this.minTtl = minTtl;
340 return this;
341 }
342
343 /**
344 * Sets the TTL of the cache for the failed DNS queries (in seconds).
345 *
346 * @param negativeTtl the TTL for failed cached queries
347 * @return {@code this}
348 */
349 public DnsNameResolverBuilder negativeTtl(int negativeTtl) {
350 this.negativeTtl = negativeTtl;
351 return this;
352 }
353
354 /**
355 * Sets the timeout of each DNS query performed by this resolver (in milliseconds).
356 * {@code 0} disables the timeout. If not set or a negative number is set, the default timeout is used.
357 *
358 * @param queryTimeoutMillis the query timeout
359 * @return {@code this}
360 */
361 public DnsNameResolverBuilder queryTimeoutMillis(long queryTimeoutMillis) {
362 this.queryTimeoutMillis = queryTimeoutMillis;
363 return this;
364 }
365
366 /**
367 * Compute a {@link ResolvedAddressTypes} from some {@link InternetProtocolFamily}s.
368 * An empty input will return the default value, based on "java.net" System properties.
369 * Valid inputs are (), (IPv4), (IPv6), (Ipv4, IPv6) and (IPv6, IPv4).
370 * @param internetProtocolFamilies a valid sequence of {@link InternetProtocolFamily}s
371 * @return a {@link ResolvedAddressTypes}
372 */
373 public static ResolvedAddressTypes computeResolvedAddressTypes(InternetProtocolFamily... internetProtocolFamilies) {
374 if (internetProtocolFamilies == null || internetProtocolFamilies.length == 0) {
375 return DnsNameResolver.DEFAULT_RESOLVE_ADDRESS_TYPES;
376 }
377 if (internetProtocolFamilies.length > 2) {
378 throw new IllegalArgumentException("No more than 2 InternetProtocolFamilies");
379 }
380
381 switch(internetProtocolFamilies[0]) {
382 case IPv4:
383 return (internetProtocolFamilies.length >= 2
384 && internetProtocolFamilies[1] == InternetProtocolFamily.IPv6) ?
385 ResolvedAddressTypes.IPV4_PREFERRED: ResolvedAddressTypes.IPV4_ONLY;
386 case IPv6:
387 return (internetProtocolFamilies.length >= 2
388 && internetProtocolFamilies[1] == InternetProtocolFamily.IPv4) ?
389 ResolvedAddressTypes.IPV6_PREFERRED: ResolvedAddressTypes.IPV6_ONLY;
390 default:
391 throw new IllegalArgumentException(
392 "Couldn't resolve ResolvedAddressTypes from InternetProtocolFamily array");
393 }
394 }
395
396 /**
397 * Sets the list of the protocol families of the address resolved.
398 * You can use {@link DnsNameResolverBuilder#computeResolvedAddressTypes(InternetProtocolFamily...)}
399 * to get a {@link ResolvedAddressTypes} out of some {@link InternetProtocolFamily}s.
400 *
401 * @param resolvedAddressTypes the address types
402 * @return {@code this}
403 */
404 public DnsNameResolverBuilder resolvedAddressTypes(ResolvedAddressTypes resolvedAddressTypes) {
405 this.resolvedAddressTypes = resolvedAddressTypes;
406 return this;
407 }
408
409 /**
410 * If {@code true} {@link DnsNameResolver#resolveAll(String)} will notify the returned {@link Future} as
411 * soon as all queries for the preferred address-type are complete.
412 *
413 * @param completeOncePreferredResolved {@code true} to enable, {@code false} to disable.
414 * @return {@code this}
415 */
416 public DnsNameResolverBuilder completeOncePreferredResolved(boolean completeOncePreferredResolved) {
417 this.completeOncePreferredResolved = completeOncePreferredResolved;
418 return this;
419 }
420
421 /**
422 * Sets if this resolver has to send a DNS query with the RD (recursion desired) flag set.
423 *
424 * @param recursionDesired true if recursion is desired
425 * @return {@code this}
426 */
427 public DnsNameResolverBuilder recursionDesired(boolean recursionDesired) {
428 this.recursionDesired = recursionDesired;
429 return this;
430 }
431
432 /**
433 * Sets the maximum allowed number of DNS queries to send when resolving a host name.
434 *
435 * @param maxQueriesPerResolve the max number of queries
436 * @return {@code this}
437 */
438 public DnsNameResolverBuilder maxQueriesPerResolve(int maxQueriesPerResolve) {
439 this.maxQueriesPerResolve = maxQueriesPerResolve;
440 return this;
441 }
442
443 /**
444 * Sets if this resolver should generate the detailed trace information in an exception message so that
445 * it is easier to understand the cause of resolution failure.
446 *
447 * @param traceEnabled true if trace is enabled
448 * @return {@code this}
449 * @deprecated Prefer to {@linkplain #dnsQueryLifecycleObserverFactory(DnsQueryLifecycleObserverFactory) configure}
450 * a {@link LoggingDnsQueryLifeCycleObserverFactory} instead.
451 */
452 @Deprecated
453 public DnsNameResolverBuilder traceEnabled(boolean traceEnabled) {
454 this.traceEnabled = traceEnabled;
455 return this;
456 }
457
458 /**
459 * Sets the capacity of the datagram packet buffer (in bytes). The default value is {@code 4096} bytes.
460 *
461 * @param maxPayloadSize the capacity of the datagram packet buffer
462 * @return {@code this}
463 */
464 public DnsNameResolverBuilder maxPayloadSize(int maxPayloadSize) {
465 this.maxPayloadSize = maxPayloadSize;
466 return this;
467 }
468
469 /**
470 * Enable the automatic inclusion of a optional records that tries to give the remote DNS server a hint about
471 * how much data the resolver can read per response. Some DNSServer may not support this and so fail to answer
472 * queries. If you find problems you may want to disable this.
473 *
474 * @param optResourceEnabled if optional records inclusion is enabled
475 * @return {@code this}
476 */
477 public DnsNameResolverBuilder optResourceEnabled(boolean optResourceEnabled) {
478 this.optResourceEnabled = optResourceEnabled;
479 return this;
480 }
481
482 /**
483 * @param hostsFileEntriesResolver the {@link HostsFileEntriesResolver} used to first check
484 * if the hostname is locally aliased.
485 * @return {@code this}
486 */
487 public DnsNameResolverBuilder hostsFileEntriesResolver(HostsFileEntriesResolver hostsFileEntriesResolver) {
488 this.hostsFileEntriesResolver = hostsFileEntriesResolver;
489 return this;
490 }
491
492 protected DnsServerAddressStreamProvider nameServerProvider() {
493 return this.dnsServerAddressStreamProvider;
494 }
495
496 /**
497 * Set the {@link DnsServerAddressStreamProvider} which is used to determine which DNS server is used to resolve
498 * each hostname.
499 * @return {@code this}.
500 */
501 public DnsNameResolverBuilder nameServerProvider(DnsServerAddressStreamProvider dnsServerAddressStreamProvider) {
502 this.dnsServerAddressStreamProvider =
503 checkNotNull(dnsServerAddressStreamProvider, "dnsServerAddressStreamProvider");
504 return this;
505 }
506
507 protected DnsServerAddressStream queryServerAddressStream() {
508 return this.queryDnsServerAddressStream;
509 }
510
511 /**
512 * Set the {@link DnsServerAddressStream} which provides the server address for DNS queries.
513 * @return {@code this}.
514 */
515 public DnsNameResolverBuilder queryServerAddressStream(DnsServerAddressStream queryServerAddressStream) {
516 this.queryDnsServerAddressStream =
517 checkNotNull(queryServerAddressStream, "queryServerAddressStream");
518 return this;
519 }
520
521 /**
522 * Set the list of search domains of the resolver.
523 *
524 * @param searchDomains the search domains
525 * @return {@code this}
526 */
527 public DnsNameResolverBuilder searchDomains(Iterable<String> searchDomains) {
528 checkNotNull(searchDomains, "searchDomains");
529
530 final Set<String> domains = new LinkedHashSet<String>(4);
531
532 for (String f : searchDomains) {
533 if (f == null) {
534 break;
535 }
536
537 // Avoid duplicate entries.
538 domains.add(f);
539 }
540
541 this.searchDomains = domains.toArray(EmptyArrays.EMPTY_STRINGS);
542 return this;
543 }
544
545 /**
546 * Set the number of dots which must appear in a name before an initial absolute query is made.
547 * The default value is {@code 1}.
548 *
549 * @param ndots the ndots value
550 * @return {@code this}
551 */
552 public DnsNameResolverBuilder ndots(int ndots) {
553 this.ndots = ndots;
554 return this;
555 }
556
557 DnsCache getOrNewCache() {
558 if (this.resolveCache != null) {
559 return this.resolveCache;
560 }
561 return new DefaultDnsCache(intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE), intValue(negativeTtl, 0));
562 }
563
564 AuthoritativeDnsServerCache getOrNewAuthoritativeDnsServerCache() {
565 if (this.authoritativeDnsServerCache != null) {
566 return this.authoritativeDnsServerCache;
567 }
568 return new DefaultAuthoritativeDnsServerCache(
569 intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE),
570 // Let us use the sane ordering as DnsNameResolver will be used when returning
571 // nameservers from the cache.
572 new NameServerComparator(DnsNameResolver.preferredAddressType(resolvedAddressTypes).addressType()));
573 }
574
575 private DnsServerAddressStream newQueryServerAddressStream(
576 DnsServerAddressStreamProvider dnsServerAddressStreamProvider) {
577 return new ThreadLocalNameServerAddressStream(dnsServerAddressStreamProvider);
578 }
579
580 DnsCnameCache getOrNewCnameCache() {
581 if (this.cnameCache != null) {
582 return this.cnameCache;
583 }
584 return new DefaultDnsCnameCache(
585 intValue(minTtl, 0), intValue(maxTtl, Integer.MAX_VALUE));
586 }
587
588 /**
589 * Set if domain / host names should be decoded to unicode when received.
590 * See <a href="https://tools.ietf.org/html/rfc3492">rfc3492</a>.
591 *
592 * @param decodeIdn if should get decoded
593 * @return {@code this}
594 */
595 public DnsNameResolverBuilder decodeIdn(boolean decodeIdn) {
596 this.decodeIdn = decodeIdn;
597 return this;
598 }
599
600 /**
601 * Set the maximum size of the cache that is used to consolidate lookups for different hostnames when in-flight.
602 * This means if multiple lookups are done for the same hostname and still in-flight only one actual query will
603 * be made and the result will be cascaded to the others.
604 *
605 * @param maxNumConsolidation the maximum lookups to consolidate (different hostnames), or {@code 0} if
606 * no consolidation should be performed.
607 * @return {@code this}
608 */
609 public DnsNameResolverBuilder consolidateCacheSize(int maxNumConsolidation) {
610 this.maxNumConsolidation = ObjectUtil.checkPositiveOrZero(maxNumConsolidation, "maxNumConsolidation");
611 return this;
612 }
613
614 /**
615 * Set the strategy that is used to determine how a {@link DatagramChannel} is used by the resolver for sending
616 * queries over UDP protocol.
617 *
618 * @param datagramChannelStrategy the {@link DnsNameResolverChannelStrategy} to use when doing queries over
619 * UDP protocol.
620 * @return {@code this}
621 */
622 public DnsNameResolverBuilder datagramChannelStrategy(DnsNameResolverChannelStrategy datagramChannelStrategy) {
623 this.datagramChannelStrategy = ObjectUtil.checkNotNull(datagramChannelStrategy, "datagramChannelStrategy");
624 return this;
625 }
626
627 /**
628 * Enables or disables the randomization of the case of the name in the questions of UDP queries, also known as
629 * "0x20". The response is only accepted if it echoes the name with exactly the same case, which adds entropy
630 * that an off-path attacker needs to guess in order to spoof a response, on top of the query id and the source
631 * port. See <a href="https://tools.ietf.org/html/rfc5452#section-9.2">RFC 5452</a>.
632 * <p>
633 * Some nameservers do not preserve the case of the name in their responses. Queries to these will time out
634 * if this is enabled. This is disabled by default.
635 *
636 * @param caseRandomizationEnabled {@code true} if the case of the name should be randomized.
637 * @return {@code this}
638 */
639 public DnsNameResolverBuilder caseRandomizationEnabled(boolean caseRandomizationEnabled) {
640 this.caseRandomizationEnabled = caseRandomizationEnabled;
641 return this;
642 }
643
644 /**
645 * Enables or disables the sending of a random client cookie with every UDP query, as defined by
646 * <a href="https://tools.ietf.org/html/rfc7873">RFC 7873</a>. A response is rejected if it carries a cookie
647 * that does not echo the client cookie. Once a nameserver was seen to echo the client cookie, responses from it
648 * that omit the cookie are rejected as well.
649 * <p>
650 * The cookie is part of the OPT record, so this has no effect on queries that do not include one, which is the
651 * case if {@link #optResourceEnabled(boolean)} is {@code false} or if the query already has an OPT record.
652 * Nameservers that require a valid server cookie and so answer with {@code BADCOOKIE} are not supported.
653 * This is disabled by default.
654 *
655 * @param dnsCookiesEnabled {@code true} if DNS cookies should be used.
656 * @return {@code this}
657 */
658 public DnsNameResolverBuilder dnsCookiesEnabled(boolean dnsCookiesEnabled) {
659 this.dnsCookiesEnabled = dnsCookiesEnabled;
660 return this;
661 }
662
663 /**
664 * Returns a new {@link DnsNameResolver} instance.
665 *
666 * @return a {@link DnsNameResolver}
667 */
668 public DnsNameResolver build() {
669 if (eventLoop == null) {
670 throw new IllegalStateException("eventLoop should be specified to build a DnsNameResolver.");
671 }
672
673 if (resolveCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
674 logger.debug("resolveCache and TTLs are mutually exclusive. TTLs are ignored.");
675 }
676
677 if (cnameCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
678 logger.debug("cnameCache and TTLs are mutually exclusive. TTLs are ignored.");
679 }
680
681 if (authoritativeDnsServerCache != null && (minTtl != null || maxTtl != null || negativeTtl != null)) {
682 logger.debug("authoritativeDnsServerCache and TTLs are mutually exclusive. TTLs are ignored.");
683 }
684
685 DnsCache resolveCache = getOrNewCache();
686 DnsCnameCache cnameCache = getOrNewCnameCache();
687 AuthoritativeDnsServerCache authoritativeDnsServerCache = getOrNewAuthoritativeDnsServerCache();
688
689 DnsServerAddressStream queryDnsServerAddressStream = this.queryDnsServerAddressStream != null ?
690 this.queryDnsServerAddressStream : newQueryServerAddressStream(dnsServerAddressStreamProvider);
691
692 return new DnsNameResolver(
693 eventLoop,
694 datagramChannelFactory,
695 socketChannelFactory,
696 retryOnTimeout,
697 resolveCache,
698 cnameCache,
699 authoritativeDnsServerCache,
700 localAddress,
701 dnsQueryLifecycleObserverFactory,
702 queryTimeoutMillis,
703 resolvedAddressTypes,
704 recursionDesired,
705 maxQueriesPerResolve,
706 traceEnabled,
707 maxPayloadSize,
708 optResourceEnabled,
709 hostsFileEntriesResolver,
710 dnsServerAddressStreamProvider,
711 queryDnsServerAddressStream,
712 searchDomains,
713 ndots,
714 decodeIdn,
715 completeOncePreferredResolved,
716 maxNumConsolidation,
717 datagramChannelStrategy,
718 caseRandomizationEnabled,
719 dnsCookiesEnabled);
720 }
721
722 /**
723 * Creates a copy of this {@link DnsNameResolverBuilder}
724 *
725 * @return {@link DnsNameResolverBuilder}
726 */
727 public DnsNameResolverBuilder copy() {
728 DnsNameResolverBuilder copiedBuilder = new DnsNameResolverBuilder();
729
730 if (eventLoop != null) {
731 copiedBuilder.eventLoop(eventLoop);
732 }
733
734 if (datagramChannelFactory != null) {
735 copiedBuilder.datagramChannelFactory(datagramChannelFactory);
736 }
737
738 copiedBuilder.socketChannelFactory(socketChannelFactory, retryOnTimeout);
739
740 if (resolveCache != null) {
741 copiedBuilder.resolveCache(resolveCache);
742 }
743
744 if (cnameCache != null) {
745 copiedBuilder.cnameCache(cnameCache);
746 }
747 if (maxTtl != null && minTtl != null) {
748 copiedBuilder.ttl(minTtl, maxTtl);
749 }
750
751 if (negativeTtl != null) {
752 copiedBuilder.negativeTtl(negativeTtl);
753 }
754
755 if (authoritativeDnsServerCache != null) {
756 copiedBuilder.authoritativeDnsServerCache(authoritativeDnsServerCache);
757 }
758
759 if (dnsQueryLifecycleObserverFactory != null) {
760 copiedBuilder.dnsQueryLifecycleObserverFactory(dnsQueryLifecycleObserverFactory);
761 }
762
763 copiedBuilder.queryTimeoutMillis(queryTimeoutMillis);
764 copiedBuilder.resolvedAddressTypes(resolvedAddressTypes);
765 copiedBuilder.recursionDesired(recursionDesired);
766 copiedBuilder.maxQueriesPerResolve(maxQueriesPerResolve);
767 copiedBuilder.traceEnabled(traceEnabled);
768 copiedBuilder.maxPayloadSize(maxPayloadSize);
769 copiedBuilder.optResourceEnabled(optResourceEnabled);
770 copiedBuilder.hostsFileEntriesResolver(hostsFileEntriesResolver);
771
772 if (dnsServerAddressStreamProvider != null) {
773 copiedBuilder.nameServerProvider(dnsServerAddressStreamProvider);
774 }
775
776 if (queryDnsServerAddressStream != null) {
777 copiedBuilder.queryServerAddressStream(queryDnsServerAddressStream);
778 }
779
780 if (searchDomains != null) {
781 copiedBuilder.searchDomains(Arrays.asList(searchDomains));
782 }
783
784 copiedBuilder.ndots(ndots);
785 copiedBuilder.decodeIdn(decodeIdn);
786 copiedBuilder.completeOncePreferredResolved(completeOncePreferredResolved);
787 copiedBuilder.localAddress(localAddress);
788 copiedBuilder.consolidateCacheSize(maxNumConsolidation);
789 copiedBuilder.datagramChannelStrategy(datagramChannelStrategy);
790 copiedBuilder.caseRandomizationEnabled(caseRandomizationEnabled);
791 copiedBuilder.dnsCookiesEnabled(dnsCookiesEnabled);
792 return copiedBuilder;
793 }
794 }