Skip to main content

hickory_resolver/
config.rs

1// Copyright 2015-2017 Benjamin Fry <benjaminfry@me.com>
2//
3// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
4// https://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
5// https://opensource.org/licenses/MIT>, at your option. This file may not be
6// copied, modified, or distributed except according to those terms.
7
8//! Configuration for a resolver
9#![allow(clippy::use_self)]
10
11use std::collections::HashSet;
12use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
13use std::path::PathBuf;
14use std::sync::Arc;
15use std::time::Duration;
16#[cfg(all(
17    feature = "recursor",
18    feature = "toml",
19    feature = "serde",
20    any(feature = "__tls", feature = "__quic")
21))]
22use std::{fs, io};
23
24use ipnet::IpNet;
25#[cfg(feature = "serde")]
26use serde::{Deserialize, Serialize};
27use tracing::warn;
28#[cfg(all(
29    feature = "recursor",
30    feature = "toml",
31    feature = "serde",
32    any(feature = "__tls", feature = "__quic")
33))]
34use tracing::{debug, info};
35
36#[cfg(all(
37    feature = "recursor",
38    feature = "toml",
39    feature = "serde",
40    any(feature = "__tls", feature = "__quic")
41))]
42use crate::name_server_pool::NameServerTransportState;
43#[cfg(any(feature = "__https", feature = "__h3"))]
44use crate::net::http::DEFAULT_DNS_QUERY_PATH;
45use crate::net::xfer::Protocol;
46use crate::proto::access_control::{AccessControlSet, AccessControlSetBuilder};
47use crate::proto::op::DEFAULT_MAX_PAYLOAD_LEN;
48use crate::proto::rr::Name;
49
50/// Configuration for the upstream nameservers to use for resolution.
51///
52/// The `Default` implementation of this struct will be removed in a future version. Use
53/// [`Self::from_name_servers()`] instead. Note that a `ResolverConfig` with no name servers will
54/// produce a nonfunctional resolver.
55#[non_exhaustive]
56#[derive(Clone, Debug, Default)]
57#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
58pub struct ResolverConfig {
59    /// Base search domain
60    #[cfg_attr(feature = "serde", serde(default))]
61    pub domain: Option<Name>,
62    /// Search domains
63    #[cfg_attr(feature = "serde", serde(default))]
64    pub search: Vec<Name>,
65    /// Name servers to use for resolution
66    pub name_servers: Vec<NameServerConfig>,
67}
68
69impl ResolverConfig {
70    /// Create a new `ResolverConfig` from [`ServerGroup`] configuration.
71    ///
72    /// Connects via UDP and TCP.
73    pub fn udp_and_tcp(config: &ServerGroup<'_>) -> Self {
74        Self {
75            // TODO: this should get the hostname and use the basename as the default
76            domain: None,
77            search: vec![],
78            name_servers: config.udp_and_tcp().collect(),
79        }
80    }
81
82    /// Create a new `ResolverConfig` from [`ServerGroup`] configuration.
83    ///
84    /// Only connects via TLS.
85    #[cfg(feature = "__tls")]
86    pub fn tls(config: &ServerGroup<'_>) -> Self {
87        Self {
88            // TODO: this should get the hostname and use the basename as the default
89            domain: None,
90            search: vec![],
91            name_servers: config.tls().collect(),
92        }
93    }
94
95    /// Create a new `ResolverConfig` from [`ServerGroup`] configuration.
96    ///
97    /// Only connects via HTTPS (HTTP/2).
98    #[cfg(feature = "__https")]
99    pub fn https(config: &ServerGroup<'_>) -> Self {
100        Self {
101            // TODO: this should get the hostname and use the basename as the default
102            domain: None,
103            search: vec![],
104            name_servers: config.https().collect(),
105        }
106    }
107
108    /// Create a new `ResolverConfig` from [`ServerGroup`] configuration.
109    ///
110    /// Only connects via QUIC.
111    #[cfg(feature = "__quic")]
112    pub fn quic(config: &ServerGroup<'_>) -> Self {
113        Self {
114            // TODO: this should get the hostname and use the basename as the default
115            domain: None,
116            search: vec![],
117            name_servers: config.quic().collect(),
118        }
119    }
120
121    /// Create a new `ResolverConfig` from [`ServerGroup`] configuration.
122    ///
123    /// Only connects via HTTP/3.
124    #[cfg(feature = "__h3")]
125    pub fn h3(config: &ServerGroup<'_>) -> Self {
126        Self {
127            // TODO: this should get the hostname and use the basename as the default
128            domain: None,
129            search: vec![],
130            name_servers: config.h3().collect(),
131        }
132    }
133
134    /// Create a ResolverConfig with all parts specified
135    ///
136    /// # Arguments
137    ///
138    /// * `domain` - domain of the entity querying results. If the `Name` being looked up is not an FQDN, then this is the first part appended to attempt a lookup. `ndots` in the `ResolverOption` does take precedence over this.
139    /// * `search` - additional search domains that are attempted if the `Name` is not found in `domain`, defaults to `vec![]`
140    /// * `name_servers` - set of name servers to use for lookups
141    pub fn from_parts(
142        domain: Option<Name>,
143        search: Vec<Name>,
144        name_servers: Vec<NameServerConfig>,
145    ) -> Self {
146        Self {
147            domain,
148            search,
149            name_servers,
150        }
151    }
152
153    /// Create a ResolverConfig from a list of name server configurations.
154    ///
155    /// No base domain for relative names will be set, and no additional search domains will be set.
156    pub fn from_name_servers(name_servers: Vec<NameServerConfig>) -> Self {
157        Self::from_parts(None, vec![], name_servers)
158    }
159
160    /// Take the `domain`, `search`, and `name_servers` from the config.
161    pub fn into_parts(self) -> (Option<Name>, Vec<Name>, Vec<NameServerConfig>) {
162        (self.domain, self.search, self.name_servers)
163    }
164
165    /// Returns the local domain
166    ///
167    /// By default any names will be appended to all non-fully-qualified-domain names, and searched for after any ndots rules
168    pub fn domain(&self) -> Option<&Name> {
169        self.domain.as_ref()
170    }
171
172    /// Set the domain of the entity querying results.
173    pub fn set_domain(&mut self, domain: Name) {
174        self.domain = Some(domain.clone());
175        self.search = vec![domain];
176    }
177
178    /// Returns the search domains
179    ///
180    /// These will be queried after any local domain and then in the order of the set of search domains
181    pub fn search(&self) -> &[Name] {
182        &self.search
183    }
184
185    /// Add a search domain
186    pub fn add_search(&mut self, search: Name) {
187        self.search.push(search)
188    }
189
190    // TODO: consider allowing options per NameServer... like different timeouts?
191    /// Add the configuration for a name server
192    pub fn add_name_server(&mut self, name_server: NameServerConfig) {
193        self.name_servers.push(name_server);
194    }
195
196    /// Returns a reference to the name servers
197    pub fn name_servers(&self) -> &[NameServerConfig] {
198        &self.name_servers
199    }
200}
201
202/// Configuration for the NameServer
203#[derive(Clone, Debug)]
204#[cfg_attr(
205    feature = "serde",
206    derive(Serialize, Deserialize),
207    serde(deny_unknown_fields)
208)]
209#[non_exhaustive]
210pub struct NameServerConfig {
211    /// The address which the DNS NameServer is registered at.
212    pub ip: IpAddr,
213    /// Whether to trust `NXDOMAIN` responses from upstream nameservers.
214    ///
215    /// When this is `true`, and an empty `NXDOMAIN` response with an empty answers set is
216    /// received, the query will not be retried against other configured name servers.
217    ///
218    /// (On a response with any other error response code, the query will still be retried
219    /// regardless of this configuration setting.)
220    ///
221    /// Defaults to `true`.
222    #[cfg_attr(feature = "serde", serde(default = "default_trust_negative_responses"))]
223    pub trust_negative_responses: bool,
224    /// Connection protocols configured for this server.
225    pub connections: Vec<ConnectionConfig>,
226}
227
228impl NameServerConfig {
229    /// Constructs a nameserver configuration with a UDP and TCP connections
230    pub fn udp_and_tcp(ip: IpAddr) -> Self {
231        Self {
232            ip,
233            trust_negative_responses: true,
234            connections: vec![ConnectionConfig::udp(), ConnectionConfig::tcp()],
235        }
236    }
237
238    /// Constructs a nameserver configuration with a single UDP connection
239    pub fn udp(ip: IpAddr) -> Self {
240        Self {
241            ip,
242            trust_negative_responses: true,
243            connections: vec![ConnectionConfig::udp()],
244        }
245    }
246
247    /// Constructs a nameserver configuration with a single TCP connection
248    pub fn tcp(ip: IpAddr) -> Self {
249        Self {
250            ip,
251            trust_negative_responses: true,
252            connections: vec![ConnectionConfig::tcp()],
253        }
254    }
255
256    /// Constructs a nameserver configuration with a single TLS connection
257    #[cfg(feature = "__tls")]
258    pub fn tls(ip: IpAddr, server_name: Arc<str>) -> Self {
259        Self {
260            ip,
261            trust_negative_responses: true,
262            connections: vec![ConnectionConfig::tls(server_name)],
263        }
264    }
265
266    /// Constructs a nameserver configuration with a single HTTP/2 connection
267    #[cfg(feature = "__https")]
268    pub fn https(ip: IpAddr, server_name: Arc<str>, path: Option<Arc<str>>) -> Self {
269        Self {
270            ip,
271            trust_negative_responses: true,
272            connections: vec![ConnectionConfig::https(server_name, path)],
273        }
274    }
275
276    /// Constructs a nameserver configuration with a single QUIC connection
277    #[cfg(feature = "__quic")]
278    pub fn quic(ip: IpAddr, server_name: Arc<str>) -> Self {
279        Self {
280            ip,
281            trust_negative_responses: true,
282            connections: vec![ConnectionConfig::quic(server_name)],
283        }
284    }
285
286    /// Constructs a nameserver configuration with a single HTTP/3 connection
287    #[cfg(feature = "__h3")]
288    pub fn h3(ip: IpAddr, server_name: Arc<str>, path: Option<Arc<str>>) -> Self {
289        Self {
290            ip,
291            trust_negative_responses: true,
292            connections: vec![ConnectionConfig::h3(server_name, path)],
293        }
294    }
295
296    /// Constructs a nameserver configuration for opportunistic encryption.
297    ///
298    /// This will include configurations for plaintext UDP/TCP as well as DNS-over-TLS and/or
299    /// DNS-over-QUIC depending on feature flag support.
300    ///
301    /// Notably, the TLS and QUIC configurations will **not** verify peer certificates, in
302    /// keeping with RFC 9539's requirement. See [RFC 9539 §4.6.3.4] for more information.
303    ///
304    /// [RFC 9539 §4.6.3.4]: https://www.rfc-editor.org/rfc/rfc9539.html#section-4.6.3.4
305    #[cfg(any(feature = "__tls", feature = "__quic"))]
306    pub fn opportunistic_encryption(ip: IpAddr) -> Self {
307        Self {
308            ip,
309            trust_negative_responses: true,
310            connections: vec![
311                ConnectionConfig::udp(),
312                ConnectionConfig::tcp(),
313                #[cfg(feature = "__tls")]
314                ConnectionConfig::tls(Arc::from(ip.to_string())),
315                #[cfg(feature = "__quic")]
316                ConnectionConfig::quic(Arc::from(ip.to_string())),
317            ],
318        }
319    }
320
321    /// Create a new [`NameServerConfig`] from its constituent parts.
322    pub fn new(
323        ip: IpAddr,
324        trust_negative_responses: bool,
325        connections: Vec<ConnectionConfig>,
326    ) -> Self {
327        Self {
328            ip,
329            trust_negative_responses,
330            connections,
331        }
332    }
333}
334
335#[cfg(feature = "serde")]
336fn default_trust_negative_responses() -> bool {
337    true
338}
339
340/// Configuration for a connection to a nameserver
341#[derive(Clone, Debug)]
342#[cfg_attr(feature = "serde", derive(Serialize))]
343#[non_exhaustive]
344pub struct ConnectionConfig {
345    /// The remote port to connect to
346    pub port: u16,
347    /// The protocol to use for the connection
348    pub protocol: ProtocolConfig,
349    /// The client address (IP and port) to use for connecting to the server
350    pub bind_addr: Option<SocketAddr>,
351}
352
353impl ConnectionConfig {
354    /// Constructs a new ConnectionConfig for UDP
355    pub fn udp() -> Self {
356        Self::new(ProtocolConfig::Udp)
357    }
358
359    /// Constructs a new ConnectionConfig for TCP
360    pub fn tcp() -> Self {
361        Self::new(ProtocolConfig::Tcp)
362    }
363
364    /// Constructs a new ConnectionConfig for TLS
365    #[cfg(feature = "__tls")]
366    pub fn tls(server_name: Arc<str>) -> Self {
367        Self::new(ProtocolConfig::Tls { server_name })
368    }
369
370    /// Constructs a new ConnectionConfig for HTTPS (HTTP/2)
371    #[cfg(feature = "__https")]
372    pub fn https(server_name: Arc<str>, path: Option<Arc<str>>) -> Self {
373        Self::new(ProtocolConfig::Https {
374            server_name,
375            path: path.unwrap_or_else(|| Arc::from(DEFAULT_DNS_QUERY_PATH)),
376        })
377    }
378
379    /// Constructs a new ConnectionConfig for QUIC
380    #[cfg(feature = "__quic")]
381    pub fn quic(server_name: Arc<str>) -> Self {
382        Self::new(ProtocolConfig::Quic { server_name })
383    }
384
385    /// Constructs a new ConnectionConfig for HTTP/3
386    #[cfg(feature = "__h3")]
387    pub fn h3(server_name: Arc<str>, path: Option<Arc<str>>) -> Self {
388        Self::new(ProtocolConfig::H3 {
389            server_name,
390            path: path.unwrap_or_else(|| Arc::from(DEFAULT_DNS_QUERY_PATH)),
391            disable_grease: false,
392        })
393    }
394
395    /// Constructs a new ConnectionConfig with the specified [`ProtocolConfig`].
396    pub fn new(protocol: ProtocolConfig) -> Self {
397        Self {
398            port: protocol.default_port(),
399            protocol,
400            bind_addr: None,
401        }
402    }
403}
404
405#[cfg(feature = "serde")]
406impl<'de> Deserialize<'de> for ConnectionConfig {
407    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
408        #[derive(Deserialize)]
409        #[serde(deny_unknown_fields)]
410        struct OptionalParts {
411            #[serde(default)]
412            port: Option<u16>,
413            protocol: ProtocolConfig,
414            #[serde(default)]
415            bind_addr: Option<SocketAddr>,
416        }
417
418        let parts = OptionalParts::deserialize(deserializer)?;
419        Ok(Self {
420            port: parts.port.unwrap_or_else(|| parts.protocol.default_port()),
421            protocol: parts.protocol,
422            bind_addr: parts.bind_addr,
423        })
424    }
425}
426
427/// Protocol configuration
428#[allow(missing_docs)]
429#[derive(Clone, Debug, Default, PartialEq)]
430#[cfg_attr(
431    feature = "serde",
432    derive(Serialize, Deserialize),
433    serde(deny_unknown_fields, rename_all = "snake_case", tag = "type")
434)]
435pub enum ProtocolConfig {
436    #[default]
437    Udp,
438    Tcp,
439    #[cfg(feature = "__tls")]
440    Tls {
441        /// The server name to use in the TLS handshake.
442        server_name: Arc<str>,
443    },
444    #[cfg(feature = "__https")]
445    Https {
446        /// The server name to use in the TLS handshake.
447        server_name: Arc<str>,
448        /// The path (or endpoint) to use for the DNS query.
449        path: Arc<str>,
450    },
451    #[cfg(feature = "__quic")]
452    Quic {
453        /// The server name to use in the TLS handshake.
454        server_name: Arc<str>,
455    },
456    #[cfg(feature = "__h3")]
457    H3 {
458        /// The server name to use in the TLS handshake.
459        server_name: Arc<str>,
460        /// The path (or endpoint) to use for the DNS query.
461        path: Arc<str>,
462        /// Whether to disable sending "grease"
463        #[cfg_attr(feature = "serde", serde(default))]
464        disable_grease: bool,
465    },
466}
467
468impl ProtocolConfig {
469    /// Get the [`Protocol`] for this [`ProtocolConfig`].
470    pub fn to_protocol(&self) -> Protocol {
471        match self {
472            ProtocolConfig::Udp => Protocol::Udp,
473            ProtocolConfig::Tcp => Protocol::Tcp,
474            #[cfg(feature = "__tls")]
475            ProtocolConfig::Tls { .. } => Protocol::Tls,
476            #[cfg(feature = "__https")]
477            ProtocolConfig::Https { .. } => Protocol::Https,
478            #[cfg(feature = "__quic")]
479            ProtocolConfig::Quic { .. } => Protocol::Quic,
480            #[cfg(feature = "__h3")]
481            ProtocolConfig::H3 { .. } => Protocol::H3,
482        }
483    }
484
485    /// Returns the TLS server name, if the protocol uses TLS.
486    pub fn server_name(&self) -> Option<&Arc<str>> {
487        match self {
488            ProtocolConfig::Udp | ProtocolConfig::Tcp => None,
489            #[cfg(feature = "__tls")]
490            ProtocolConfig::Tls { server_name } => Some(server_name),
491            #[cfg(feature = "__https")]
492            ProtocolConfig::Https { server_name, .. } => Some(server_name),
493            #[cfg(feature = "__quic")]
494            ProtocolConfig::Quic { server_name } => Some(server_name),
495            #[cfg(feature = "__h3")]
496            ProtocolConfig::H3 { server_name, .. } => Some(server_name),
497        }
498    }
499
500    /// Default port for the protocol.
501    pub fn default_port(&self) -> u16 {
502        match self {
503            ProtocolConfig::Udp => 53,
504            ProtocolConfig::Tcp => 53,
505            #[cfg(feature = "__tls")]
506            ProtocolConfig::Tls { .. } => 853,
507            #[cfg(feature = "__https")]
508            ProtocolConfig::Https { .. } => 443,
509            #[cfg(feature = "__quic")]
510            ProtocolConfig::Quic { .. } => 853,
511            #[cfg(feature = "__h3")]
512            ProtocolConfig::H3 { .. } => 443,
513        }
514    }
515}
516
517/// Configuration for the Resolver
518#[derive(Debug, Clone)]
519#[cfg_attr(
520    feature = "serde",
521    derive(Serialize, Deserialize),
522    serde(default, deny_unknown_fields)
523)]
524#[non_exhaustive]
525pub struct ResolverOpts {
526    /// Sets the number of dots that must appear (unless it's a final dot representing the root)
527    ///  before a query is assumed to include the TLD. The default is one, which means that `www`
528    ///  would never be assumed to be a TLD, and would always be appended to either the search
529    #[cfg_attr(feature = "serde", serde(default = "default_ndots"))]
530    pub ndots: usize,
531    /// Specify the timeout for a request. Defaults to 5 seconds
532    #[cfg_attr(
533        feature = "serde",
534        serde(default = "default_timeout", with = "duration")
535    )]
536    pub timeout: Duration,
537    /// Number of retries after lookup failure before giving up. Defaults to 2
538    #[cfg_attr(feature = "serde", serde(default = "default_attempts"))]
539    pub attempts: usize,
540    /// Enable edns, for larger records
541    pub edns0: bool,
542    /// Use DNSSEC to validate the request
543    #[cfg(feature = "__dnssec")]
544    pub validate: bool,
545    /// The strategy for the Resolver to use when looking up host IP addresses
546    pub ip_strategy: LookupIpStrategy,
547    /// Cache size is in number of responses (some responses can be large)
548    #[cfg_attr(feature = "serde", serde(default = "default_cache_size"))]
549    pub cache_size: u64,
550    /// Check /etc/hosts file before dns requery (only works for unix like OS)
551    pub use_hosts_file: ResolveHosts,
552    /// Optional minimum TTL for positive responses.
553    ///
554    /// If this is set, any positive responses with a TTL lower than this value will have a TTL of
555    /// `positive_min_ttl` instead. Otherwise, this will default to 0 seconds.
556    #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
557    pub positive_min_ttl: Option<Duration>,
558    /// Optional minimum TTL for negative (`NXDOMAIN`) responses.
559    ///
560    /// If this is set, any negative responses with a TTL lower than this value will have a TTL of
561    /// `negative_min_ttl` instead. Otherwise, this will default to 0 seconds.
562    #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
563    pub negative_min_ttl: Option<Duration>,
564    /// Optional maximum TTL for positive responses.
565    ///
566    /// If this is set, any positive responses with a TTL higher than this value will have a TTL of
567    /// `positive_max_ttl` instead. Otherwise, this will default to [`MAX_TTL`](crate::MAX_TTL) seconds.
568    #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
569    pub positive_max_ttl: Option<Duration>,
570    /// Optional maximum TTL for negative (`NXDOMAIN`) responses.
571    ///
572    /// If this is set, any negative responses with a TTL higher than this value will have a TTL of
573    /// `negative_max_ttl` instead. Otherwise, this will default to [`MAX_TTL`](crate::MAX_TTL) seconds.
574    #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
575    pub negative_max_ttl: Option<Duration>,
576    /// Number of concurrent requests per query
577    ///
578    /// Where more than one nameserver is configured, this configures the resolver to send queries
579    /// to a number of servers in parallel. Defaults to 2; 0 or 1 will execute requests serially.
580    #[cfg_attr(feature = "serde", serde(default = "default_num_concurrent_reqs"))]
581    pub num_concurrent_reqs: usize,
582    /// Maximum number of active (in-flight) requests per multiplexed connection.
583    ///
584    /// This limits how many DNS queries can be simultaneously pending on a single
585    /// connection to an upstream nameserver. When the limit is reached, new requests
586    /// will return a busy error.
587    ///
588    /// Defaults to 32. Higher values allow more parallelism but consume more memory.
589    #[cfg_attr(feature = "serde", serde(default = "default_max_active_requests"))]
590    pub max_active_requests: usize,
591    /// Preserve all intermediate records in the lookup response, such as CNAME records
592    #[cfg_attr(feature = "serde", serde(default = "default_preserve_intermediates"))]
593    pub preserve_intermediates: bool,
594    /// Try queries over TCP if they fail over UDP.
595    pub try_tcp_on_error: bool,
596    /// The server ordering strategy that the resolver should use.
597    pub server_ordering_strategy: ServerOrderingStrategy,
598    /// Request upstream recursive resolvers to not perform any recursion.
599    ///
600    /// This is true by default, disabling this is useful for requesting single records, but may prevent successful resolution.
601    #[cfg_attr(feature = "serde", serde(default = "default_recursion_desired"))]
602    pub recursion_desired: bool,
603    /// Local UDP ports to avoid when making outgoing queries
604    pub avoid_local_udp_ports: Arc<HashSet<u16>>,
605    /// Request UDP bind ephemeral ports directly from the OS
606    ///
607    /// Boolean parameter to specify whether to use the operating system's standard UDP port
608    /// selection logic instead of Hickory's logic to securely select a random source port. We do
609    /// not recommend using this option unless absolutely necessary, as the operating system may
610    /// select ephemeral ports from a smaller range than Hickory, which can make response poisoning
611    /// attacks easier to conduct. Some operating systems (notably, Windows) might display a
612    /// user-prompt to allow a Hickory-specified port to be used, and setting this option will
613    /// prevent those prompts from being displayed. If os_port_selection is true, avoid_local_udp_ports
614    /// will be ignored.
615    pub os_port_selection: bool,
616    /// Enable case randomization.
617    ///
618    /// Randomize the case of letters in query names, and require that responses preserve the case
619    /// of the query name, in order to mitigate spoofing attacks. This is only applied over UDP.
620    ///
621    /// This implements the mechanism described in
622    /// [draft-vixie-dnsext-dns0x20-00](https://datatracker.ietf.org/doc/html/draft-vixie-dnsext-dns0x20-00).
623    pub case_randomization: bool,
624    /// Path to a DNSSEC trust anchor file.
625    ///
626    /// If this is provided, `validate` will automatically be set to `true`, enabling DNSSEC validation.
627    pub trust_anchor: Option<PathBuf>,
628    /// Exceptions to `deny_answer_addresses`. Networks listed here will be allowed, even if the IP address
629    /// matches a network in `deny_answer_addresses`.
630    pub allow_answers: Vec<IpNet>,
631    /// Networks listed here will be removed from any answers returned by an upstream server.
632    pub deny_answers: Vec<IpNet>,
633    /// Configure the EDNS UDP payload size used in queries.
634    ///
635    /// See [DnsRequestOptions::edns_payload_len][crate::proto::op::DnsRequestOptions::edns_payload_len].
636    #[cfg_attr(feature = "serde", serde(default = "default_edns_payload_len"))]
637    pub edns_payload_len: u16,
638    /// Report the IP of the name server for query result metrics.
639    ///
640    /// When `false`, metrics are aggregated under a static "aggregate" address label to avoid
641    /// cardinality blowup. For this reason, you might want to leave this disabled when querying a
642    /// large or unbounded set of DNS servers.
643    #[cfg_attr(feature = "serde", serde(default))]
644    #[cfg(feature = "metrics")]
645    pub enable_per_name_server_metrics: bool,
646}
647
648impl ResolverOpts {
649    pub(crate) fn answer_address_filter(&self) -> AccessControlSet {
650        let name = "resolver_answer_filter";
651        AccessControlSetBuilder::new(name)
652            .allow(self.allow_answers.iter())
653            .deny(self.deny_answers.iter())
654            .build()
655            .inspect_err(|err| warn!("{err}"))
656            .unwrap_or_else(|_| AccessControlSet::empty(name))
657    }
658}
659
660impl Default for ResolverOpts {
661    /// Default values for the Resolver configuration.
662    ///
663    /// This follows the resolv.conf defaults as defined in the [Linux man pages](https://man7.org/linux/man-pages/man5/resolv.conf.5.html)
664    fn default() -> Self {
665        Self {
666            ndots: default_ndots(),
667            timeout: default_timeout(),
668            attempts: default_attempts(),
669            edns0: true,
670            #[cfg(feature = "__dnssec")]
671            validate: false,
672            ip_strategy: LookupIpStrategy::default(),
673            cache_size: default_cache_size(),
674            use_hosts_file: ResolveHosts::default(),
675            positive_min_ttl: None,
676            negative_min_ttl: None,
677            positive_max_ttl: None,
678            negative_max_ttl: None,
679            num_concurrent_reqs: default_num_concurrent_reqs(),
680            max_active_requests: default_max_active_requests(),
681
682            // Defaults to `true` to match the behavior of dig and nslookup.
683            preserve_intermediates: default_preserve_intermediates(),
684
685            try_tcp_on_error: false,
686            server_ordering_strategy: ServerOrderingStrategy::default(),
687            recursion_desired: default_recursion_desired(),
688            avoid_local_udp_ports: Arc::default(),
689            os_port_selection: false,
690            case_randomization: false,
691            trust_anchor: None,
692            allow_answers: vec![],
693            deny_answers: vec![],
694            edns_payload_len: default_edns_payload_len(),
695            #[cfg(feature = "metrics")]
696            enable_per_name_server_metrics: false,
697        }
698    }
699}
700
701fn default_ndots() -> usize {
702    1
703}
704
705fn default_timeout() -> Duration {
706    Duration::from_secs(5)
707}
708
709fn default_attempts() -> usize {
710    2
711}
712
713fn default_cache_size() -> u64 {
714    8_192
715}
716
717fn default_num_concurrent_reqs() -> usize {
718    2
719}
720
721fn default_max_active_requests() -> usize {
722    32
723}
724
725fn default_preserve_intermediates() -> bool {
726    true
727}
728
729fn default_recursion_desired() -> bool {
730    true
731}
732
733fn default_edns_payload_len() -> u16 {
734    DEFAULT_MAX_PAYLOAD_LEN
735}
736
737/// The lookup ip strategy
738#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
739#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
740pub enum LookupIpStrategy {
741    /// Only query for A (Ipv4) records
742    Ipv4Only,
743    /// Only query for AAAA (Ipv6) records
744    Ipv6Only,
745    /// Query for A and AAAA in parallel, ordering A before AAAA
746    Ipv4AndIpv6,
747    /// Query for AAAA and A in parallel, ordering AAAA before A
748    #[default]
749    Ipv6AndIpv4,
750    /// Query for Ipv6 if that fails, query for Ipv4
751    Ipv6thenIpv4,
752    /// Query for Ipv4 if that fails, query for Ipv6 (default)
753    Ipv4thenIpv6,
754}
755
756/// The strategy for establishing the query order of name servers in a pool.
757#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
758#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
759#[non_exhaustive]
760pub enum ServerOrderingStrategy {
761    /// Servers are ordered based on collected query statistics. The ordering
762    /// may vary over time.
763    #[default]
764    QueryStatistics,
765    /// The order provided to the resolver is used. The ordering does not vary
766    /// over time.
767    UserProvidedOrder,
768    /// The order of servers is rotated in a round-robin fashion. This is useful for
769    /// load balancing and ensuring that all servers are used evenly.
770    RoundRobin,
771}
772
773/// Whether the system hosts file should be respected by the resolver.
774#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
775#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
776pub enum ResolveHosts {
777    /// Always attempt to look up IP addresses from the system hosts file.
778    /// If the hostname cannot be found, query the DNS.
779    Always,
780    /// The DNS will always be queried.
781    Never,
782    /// Use local resolver configurations only when this resolver is not used in
783    /// a DNS forwarder. This is the default.
784    #[default]
785    Auto,
786}
787
788/// Configuration for enabling RFC 9539 opportunistic encryption.
789///
790/// Controls how a recursive resolver probes name servers to discover if they support
791/// encrypted transports.
792#[derive(Debug, Clone, Default, Eq, PartialEq)]
793#[cfg_attr(
794    feature = "serde",
795    derive(Serialize, Deserialize),
796    serde(rename_all = "snake_case")
797)]
798#[non_exhaustive]
799pub enum OpportunisticEncryption {
800    /// Opportunistic encryption will not be performed.
801    #[default]
802    Disabled,
803    /// Opportunistic encryption will be performed.
804    #[cfg(any(feature = "__tls", feature = "__quic"))]
805    Enabled {
806        /// Configuration parameters for opportunistic encryption.
807        #[cfg_attr(feature = "serde", serde(flatten))]
808        config: OpportunisticEncryptionConfig,
809    },
810}
811
812impl OpportunisticEncryption {
813    #[cfg(all(
814        feature = "recursor",
815        feature = "toml",
816        feature = "serde",
817        any(feature = "__tls", feature = "__quic")
818    ))]
819    pub(super) fn persisted_state(&self) -> Result<Option<NameServerTransportState>, String> {
820        let OpportunisticEncryption::Enabled {
821            config:
822                OpportunisticEncryptionConfig {
823                    persistence: Some(OpportunisticEncryptionPersistence { path, .. }),
824                    ..
825                },
826        } = self
827        else {
828            return Ok(None);
829        };
830
831        let state = match fs::read_to_string(path) {
832            Ok(toml_content) => toml::from_str(&toml_content).map_err(|e| {
833                format!(
834                    "failed to parse opportunistic encryption state TOML file: {file_path}: {e}",
835                    file_path = path.display()
836                )
837            })?,
838            Err(e) if e.kind() == io::ErrorKind::NotFound => {
839                info!(
840                    state_file = %path.display(),
841                    "no pre-existing opportunistic encryption state TOML file, starting with default state",
842                );
843                NameServerTransportState::default()
844            }
845            Err(e) => {
846                return Err(format!(
847                    "failed to read opportunistic encryption state TOML file: {file_path}: {e}",
848                    file_path = path.display()
849                ));
850            }
851        };
852
853        debug!(
854            path = %path.display(),
855            nameserver_count = state.nameserver_count(),
856            "loaded opportunistic encryption state"
857        );
858
859        Ok(Some(state))
860    }
861
862    /// Returns true if opportunistic encryption is enabled.
863    pub fn is_enabled(&self) -> bool {
864        match self {
865            Self::Disabled => false,
866            #[cfg(any(feature = "__tls", feature = "__quic"))]
867            Self::Enabled { .. } => true,
868        }
869    }
870
871    /// Returns the maximum number of concurrent probes if opportunistic encrypt is enabled.
872    pub fn max_concurrent_probes(&self) -> Option<u8> {
873        match self {
874            Self::Disabled => None,
875            #[cfg(any(feature = "__tls", feature = "__quic"))]
876            Self::Enabled { config, .. } => Some(config.max_concurrent_probes),
877        }
878    }
879}
880
881/// Configuration parameters for opportunistic encryption.
882#[derive(Debug, Clone, Eq, PartialEq)]
883#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
884#[cfg_attr(feature = "serde", serde(default, deny_unknown_fields))]
885pub struct OpportunisticEncryptionConfig {
886    /// How long the recursive resolver remembers a successful encrypted transport connection.
887    #[cfg_attr(
888        feature = "serde",
889        serde(default = "default_persistence_period", with = "duration")
890    )]
891    pub persistence_period: Duration,
892
893    /// How long the recursive resolver remembers a failed encrypted transport connection.
894    #[cfg_attr(
895        feature = "serde",
896        serde(default = "default_damping_period", with = "duration")
897    )]
898    pub damping_period: Duration,
899
900    /// Maximum number of concurrent opportunistic encryption probes.
901    #[cfg_attr(feature = "serde", serde(default = "default_max_concurrent_probes"))]
902    pub max_concurrent_probes: u8,
903
904    /// Optional configuration for persistence of opportunistic encryption probe state.
905    pub persistence: Option<OpportunisticEncryptionPersistence>,
906}
907
908impl Default for OpportunisticEncryptionConfig {
909    fn default() -> Self {
910        Self {
911            persistence_period: default_persistence_period(),
912            damping_period: default_damping_period(),
913            max_concurrent_probes: default_max_concurrent_probes(),
914            persistence: None,
915        }
916    }
917}
918
919/// The RFC 9539 suggested default for the resolver persistence period.
920fn default_persistence_period() -> Duration {
921    Duration::from_secs(60 * 60 * 24 * 3) // 3 days
922}
923
924/// The RFC 9539 suggested default for the resolver damping period.
925fn default_damping_period() -> Duration {
926    Duration::from_secs(24 * 60 * 60) // 1 day
927}
928
929/// A conservative default for the maximum number of in-flight opportunistic probe requests.
930fn default_max_concurrent_probes() -> u8 {
931    10
932}
933
934#[derive(Debug, Clone, Eq, PartialEq)]
935#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
936#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
937/// Configuration for persistence of opportunistic encryption probe state.
938pub struct OpportunisticEncryptionPersistence {
939    /// Path to a TOML state file that may be used for saving/loading opportunistic encryption state.
940    pub path: PathBuf,
941
942    /// Interval after which opportunistic encryption state is periodically saved to `path`.
943    #[cfg_attr(
944        feature = "serde",
945        serde(default = "default_save_interval", with = "duration")
946    )]
947    pub save_interval: Duration,
948}
949
950#[cfg(feature = "serde")]
951fn default_save_interval() -> Duration {
952    Duration::from_secs(60 * 10) // 10 minutes
953}
954
955/// Google Public DNS configuration.
956///
957/// Please see Google's [privacy statement](https://developers.google.com/speed/public-dns/privacy)
958/// for important information about what they track, many ISP's track similar information in DNS.
959/// To use the system configuration see: `Resolver::from_system_conf`.
960pub const GOOGLE: ServerGroup<'static> = ServerGroup {
961    ips: &[
962        IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)),
963        IpAddr::V4(Ipv4Addr::new(8, 8, 4, 4)),
964        IpAddr::V6(Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888)),
965        IpAddr::V6(Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8844)),
966    ],
967    server_name: "dns.google",
968    path: "/dns-query",
969};
970
971/// Cloudflare's 1.1.1.1 DNS service configuration.
972///
973/// See <https://www.cloudflare.com/dns/> for more information.
974pub const CLOUDFLARE: ServerGroup<'static> = ServerGroup {
975    ips: &[
976        IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)),
977        IpAddr::V4(Ipv4Addr::new(1, 0, 0, 1)),
978        IpAddr::V6(Ipv6Addr::new(0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1111)),
979        IpAddr::V6(Ipv6Addr::new(0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1001)),
980    ],
981    server_name: "cloudflare-dns.com",
982    path: "/dns-query",
983};
984
985/// The Quad9 DNS service configuration.
986///
987/// See <https://www.quad9.net/faq/> for more information.
988pub const QUAD9: ServerGroup<'static> = ServerGroup {
989    ips: &[
990        IpAddr::V4(Ipv4Addr::new(9, 9, 9, 9)),
991        IpAddr::V4(Ipv4Addr::new(149, 112, 112, 112)),
992        IpAddr::V6(Ipv6Addr::new(0x2620, 0x00fe, 0, 0, 0, 0, 0, 0x00fe)),
993        IpAddr::V6(Ipv6Addr::new(0x2620, 0x00fe, 0, 0, 0, 0, 0, 0x0009)),
994    ],
995    server_name: "dns.quad9.net",
996    path: "/dns-query",
997};
998
999/// A group of DNS servers.
1000#[derive(Clone, Copy, Debug)]
1001pub struct ServerGroup<'a> {
1002    /// IP addresses of the DNS servers in this group.
1003    pub ips: &'a [IpAddr],
1004    /// The TLS server name to use for servers.
1005    pub server_name: &'a str,
1006    /// The query path to use for HTTP queries.
1007    pub path: &'a str,
1008}
1009
1010impl<'a> ServerGroup<'a> {
1011    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1012    pub fn udp_and_tcp(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1013        self.ips.iter().map(|&ip| {
1014            NameServerConfig::new(
1015                ip,
1016                true,
1017                vec![ConnectionConfig::udp(), ConnectionConfig::tcp()],
1018            )
1019        })
1020    }
1021
1022    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1023    pub fn udp(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1024        self.ips
1025            .iter()
1026            .map(|&ip| NameServerConfig::new(ip, true, vec![ConnectionConfig::udp()]))
1027    }
1028
1029    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1030    pub fn tcp(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1031        self.ips
1032            .iter()
1033            .map(|&ip| NameServerConfig::new(ip, true, vec![ConnectionConfig::tcp()]))
1034    }
1035
1036    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1037    #[cfg(feature = "__tls")]
1038    pub fn tls(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1039        let this = *self;
1040        self.ips.iter().map(move |&ip| {
1041            NameServerConfig::new(
1042                ip,
1043                true,
1044                vec![ConnectionConfig::tls(Arc::from(this.server_name))],
1045            )
1046        })
1047    }
1048
1049    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1050    #[cfg(feature = "__https")]
1051    pub fn https(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1052        let this = *self;
1053        self.ips.iter().map(move |&ip| {
1054            NameServerConfig::new(
1055                ip,
1056                true,
1057                vec![ConnectionConfig::https(
1058                    Arc::from(this.server_name),
1059                    Some(Arc::from(this.path)),
1060                )],
1061            )
1062        })
1063    }
1064
1065    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1066    #[cfg(feature = "__quic")]
1067    pub fn quic(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1068        let this = *self;
1069        self.ips.iter().map(move |&ip| {
1070            NameServerConfig::new(
1071                ip,
1072                true,
1073                vec![ConnectionConfig::quic(Arc::from(this.server_name))],
1074            )
1075        })
1076    }
1077
1078    /// Create an iterator with `NameServerConfig` for each IP address in the group.
1079    #[cfg(feature = "__h3")]
1080    pub fn h3(&self) -> impl Iterator<Item = NameServerConfig> + 'a {
1081        let this = *self;
1082        self.ips.iter().map(move |&ip| {
1083            NameServerConfig::new(
1084                ip,
1085                true,
1086                vec![ConnectionConfig::h3(
1087                    Arc::from(this.server_name),
1088                    Some(Arc::from(this.path)),
1089                )],
1090            )
1091        })
1092    }
1093}
1094
1095#[cfg(feature = "serde")]
1096pub(crate) mod duration {
1097    use std::time::Duration;
1098
1099    use serde::{Deserialize, Deserializer, Serialize, Serializer};
1100
1101    /// This is an alternate serialization function for a [`Duration`] that emits a single number,
1102    /// representing the number of seconds, instead of a struct with `secs` and `nanos` fields.
1103    pub(super) fn serialize<S: Serializer>(
1104        duration: &Duration,
1105        serializer: S,
1106    ) -> Result<S::Ok, S::Error> {
1107        duration.as_secs().serialize(serializer)
1108    }
1109
1110    /// This is an alternate deserialization function for a [`Duration`] that expects a single number,
1111    /// representing the number of seconds, instead of a struct with `secs` and `nanos` fields.
1112    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
1113        deserializer: D,
1114    ) -> Result<Duration, D::Error> {
1115        Ok(Duration::from_secs(u64::deserialize(deserializer)?))
1116    }
1117}
1118
1119#[cfg(feature = "serde")]
1120pub(crate) mod duration_opt {
1121    use std::time::Duration;
1122
1123    use serde::{Deserialize, Deserializer, Serialize, Serializer};
1124
1125    /// This is an alternate serialization function for an optional [`Duration`] that emits a single
1126    /// number, representing the number of seconds, instead of a struct with `secs` and `nanos` fields.
1127    pub(super) fn serialize<S: Serializer>(
1128        duration: &Option<Duration>,
1129        serializer: S,
1130    ) -> Result<S::Ok, S::Error> {
1131        struct Wrapper<'a>(&'a Duration);
1132
1133        impl Serialize for Wrapper<'_> {
1134            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
1135                super::duration::serialize(self.0, serializer)
1136            }
1137        }
1138
1139        match duration {
1140            Some(duration) => serializer.serialize_some(&Wrapper(duration)),
1141            None => serializer.serialize_none(),
1142        }
1143    }
1144
1145    /// This is an alternate deserialization function for an optional [`Duration`] that expects a single
1146    /// number, representing the number of seconds, instead of a struct with `secs` and `nanos` fields.
1147    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
1148        deserializer: D,
1149    ) -> Result<Option<Duration>, D::Error> {
1150        Ok(Option::<u64>::deserialize(deserializer)?.map(Duration::from_secs))
1151    }
1152}
1153
1154#[cfg(all(test, feature = "serde"))]
1155mod tests {
1156    use super::*;
1157
1158    #[cfg(feature = "serde")]
1159    #[test]
1160    fn default_opts() {
1161        let code = ResolverOpts::default();
1162        let json = serde_json::from_str::<ResolverOpts>("{}").unwrap();
1163        assert_eq!(code.ndots, json.ndots);
1164        assert_eq!(code.timeout, json.timeout);
1165        assert_eq!(code.attempts, json.attempts);
1166        assert_eq!(code.edns0, json.edns0);
1167        #[cfg(feature = "__dnssec")]
1168        assert_eq!(code.validate, json.validate);
1169        assert_eq!(code.ip_strategy, json.ip_strategy);
1170        assert_eq!(code.cache_size, json.cache_size);
1171        assert_eq!(code.use_hosts_file, json.use_hosts_file);
1172        assert_eq!(code.positive_min_ttl, json.positive_min_ttl);
1173        assert_eq!(code.negative_min_ttl, json.negative_min_ttl);
1174        assert_eq!(code.positive_max_ttl, json.positive_max_ttl);
1175        assert_eq!(code.negative_max_ttl, json.negative_max_ttl);
1176        assert_eq!(code.num_concurrent_reqs, json.num_concurrent_reqs);
1177        assert_eq!(code.preserve_intermediates, json.preserve_intermediates);
1178        assert_eq!(code.try_tcp_on_error, json.try_tcp_on_error);
1179        assert_eq!(code.recursion_desired, json.recursion_desired);
1180        assert_eq!(code.server_ordering_strategy, json.server_ordering_strategy);
1181        assert_eq!(code.avoid_local_udp_ports, json.avoid_local_udp_ports);
1182        assert_eq!(code.os_port_selection, json.os_port_selection);
1183        assert_eq!(code.case_randomization, json.case_randomization);
1184        assert_eq!(code.trust_anchor, json.trust_anchor);
1185        #[cfg(feature = "metrics")]
1186        assert_eq!(
1187            code.enable_per_name_server_metrics,
1188            json.enable_per_name_server_metrics
1189        );
1190    }
1191}