1#![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#[non_exhaustive]
56#[derive(Clone, Debug, Default)]
57#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
58pub struct ResolverConfig {
59 #[cfg_attr(feature = "serde", serde(default))]
61 pub domain: Option<Name>,
62 #[cfg_attr(feature = "serde", serde(default))]
64 pub search: Vec<Name>,
65 pub name_servers: Vec<NameServerConfig>,
67}
68
69impl ResolverConfig {
70 pub fn udp_and_tcp(config: &ServerGroup<'_>) -> Self {
74 Self {
75 domain: None,
77 search: vec![],
78 name_servers: config.udp_and_tcp().collect(),
79 }
80 }
81
82 #[cfg(feature = "__tls")]
86 pub fn tls(config: &ServerGroup<'_>) -> Self {
87 Self {
88 domain: None,
90 search: vec![],
91 name_servers: config.tls().collect(),
92 }
93 }
94
95 #[cfg(feature = "__https")]
99 pub fn https(config: &ServerGroup<'_>) -> Self {
100 Self {
101 domain: None,
103 search: vec![],
104 name_servers: config.https().collect(),
105 }
106 }
107
108 #[cfg(feature = "__quic")]
112 pub fn quic(config: &ServerGroup<'_>) -> Self {
113 Self {
114 domain: None,
116 search: vec![],
117 name_servers: config.quic().collect(),
118 }
119 }
120
121 #[cfg(feature = "__h3")]
125 pub fn h3(config: &ServerGroup<'_>) -> Self {
126 Self {
127 domain: None,
129 search: vec![],
130 name_servers: config.h3().collect(),
131 }
132 }
133
134 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 pub fn from_name_servers(name_servers: Vec<NameServerConfig>) -> Self {
157 Self::from_parts(None, vec![], name_servers)
158 }
159
160 pub fn into_parts(self) -> (Option<Name>, Vec<Name>, Vec<NameServerConfig>) {
162 (self.domain, self.search, self.name_servers)
163 }
164
165 pub fn domain(&self) -> Option<&Name> {
169 self.domain.as_ref()
170 }
171
172 pub fn set_domain(&mut self, domain: Name) {
174 self.domain = Some(domain.clone());
175 self.search = vec![domain];
176 }
177
178 pub fn search(&self) -> &[Name] {
182 &self.search
183 }
184
185 pub fn add_search(&mut self, search: Name) {
187 self.search.push(search)
188 }
189
190 pub fn add_name_server(&mut self, name_server: NameServerConfig) {
193 self.name_servers.push(name_server);
194 }
195
196 pub fn name_servers(&self) -> &[NameServerConfig] {
198 &self.name_servers
199 }
200}
201
202#[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 pub ip: IpAddr,
213 #[cfg_attr(feature = "serde", serde(default = "default_trust_negative_responses"))]
223 pub trust_negative_responses: bool,
224 pub connections: Vec<ConnectionConfig>,
226}
227
228impl NameServerConfig {
229 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 pub fn udp(ip: IpAddr) -> Self {
240 Self {
241 ip,
242 trust_negative_responses: true,
243 connections: vec![ConnectionConfig::udp()],
244 }
245 }
246
247 pub fn tcp(ip: IpAddr) -> Self {
249 Self {
250 ip,
251 trust_negative_responses: true,
252 connections: vec![ConnectionConfig::tcp()],
253 }
254 }
255
256 #[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 #[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 #[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 #[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 #[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 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#[derive(Clone, Debug)]
342#[cfg_attr(feature = "serde", derive(Serialize))]
343#[non_exhaustive]
344pub struct ConnectionConfig {
345 pub port: u16,
347 pub protocol: ProtocolConfig,
349 pub bind_addr: Option<SocketAddr>,
351}
352
353impl ConnectionConfig {
354 pub fn udp() -> Self {
356 Self::new(ProtocolConfig::Udp)
357 }
358
359 pub fn tcp() -> Self {
361 Self::new(ProtocolConfig::Tcp)
362 }
363
364 #[cfg(feature = "__tls")]
366 pub fn tls(server_name: Arc<str>) -> Self {
367 Self::new(ProtocolConfig::Tls { server_name })
368 }
369
370 #[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 #[cfg(feature = "__quic")]
381 pub fn quic(server_name: Arc<str>) -> Self {
382 Self::new(ProtocolConfig::Quic { server_name })
383 }
384
385 #[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 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#[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 server_name: Arc<str>,
443 },
444 #[cfg(feature = "__https")]
445 Https {
446 server_name: Arc<str>,
448 path: Arc<str>,
450 },
451 #[cfg(feature = "__quic")]
452 Quic {
453 server_name: Arc<str>,
455 },
456 #[cfg(feature = "__h3")]
457 H3 {
458 server_name: Arc<str>,
460 path: Arc<str>,
462 #[cfg_attr(feature = "serde", serde(default))]
464 disable_grease: bool,
465 },
466}
467
468impl ProtocolConfig {
469 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 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 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#[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 #[cfg_attr(feature = "serde", serde(default = "default_ndots"))]
530 pub ndots: usize,
531 #[cfg_attr(
533 feature = "serde",
534 serde(default = "default_timeout", with = "duration")
535 )]
536 pub timeout: Duration,
537 #[cfg_attr(feature = "serde", serde(default = "default_attempts"))]
539 pub attempts: usize,
540 pub edns0: bool,
542 #[cfg(feature = "__dnssec")]
544 pub validate: bool,
545 pub ip_strategy: LookupIpStrategy,
547 #[cfg_attr(feature = "serde", serde(default = "default_cache_size"))]
549 pub cache_size: u64,
550 pub use_hosts_file: ResolveHosts,
552 #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
557 pub positive_min_ttl: Option<Duration>,
558 #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
563 pub negative_min_ttl: Option<Duration>,
564 #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
569 pub positive_max_ttl: Option<Duration>,
570 #[cfg_attr(feature = "serde", serde(with = "duration_opt"))]
575 pub negative_max_ttl: Option<Duration>,
576 #[cfg_attr(feature = "serde", serde(default = "default_num_concurrent_reqs"))]
581 pub num_concurrent_reqs: usize,
582 #[cfg_attr(feature = "serde", serde(default = "default_max_active_requests"))]
590 pub max_active_requests: usize,
591 #[cfg_attr(feature = "serde", serde(default = "default_preserve_intermediates"))]
593 pub preserve_intermediates: bool,
594 pub try_tcp_on_error: bool,
596 pub server_ordering_strategy: ServerOrderingStrategy,
598 #[cfg_attr(feature = "serde", serde(default = "default_recursion_desired"))]
602 pub recursion_desired: bool,
603 pub avoid_local_udp_ports: Arc<HashSet<u16>>,
605 pub os_port_selection: bool,
616 pub case_randomization: bool,
624 pub trust_anchor: Option<PathBuf>,
628 pub allow_answers: Vec<IpNet>,
631 pub deny_answers: Vec<IpNet>,
633 #[cfg_attr(feature = "serde", serde(default = "default_edns_payload_len"))]
637 pub edns_payload_len: u16,
638 #[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 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 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
739#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
740pub enum LookupIpStrategy {
741 Ipv4Only,
743 Ipv6Only,
745 Ipv4AndIpv6,
747 #[default]
749 Ipv6AndIpv4,
750 Ipv6thenIpv4,
752 Ipv4thenIpv6,
754}
755
756#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
758#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
759#[non_exhaustive]
760pub enum ServerOrderingStrategy {
761 #[default]
764 QueryStatistics,
765 UserProvidedOrder,
768 RoundRobin,
771}
772
773#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
775#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
776pub enum ResolveHosts {
777 Always,
780 Never,
782 #[default]
785 Auto,
786}
787
788#[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 #[default]
802 Disabled,
803 #[cfg(any(feature = "__tls", feature = "__quic"))]
805 Enabled {
806 #[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 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 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#[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 #[cfg_attr(
888 feature = "serde",
889 serde(default = "default_persistence_period", with = "duration")
890 )]
891 pub persistence_period: Duration,
892
893 #[cfg_attr(
895 feature = "serde",
896 serde(default = "default_damping_period", with = "duration")
897 )]
898 pub damping_period: Duration,
899
900 #[cfg_attr(feature = "serde", serde(default = "default_max_concurrent_probes"))]
902 pub max_concurrent_probes: u8,
903
904 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
919fn default_persistence_period() -> Duration {
921 Duration::from_secs(60 * 60 * 24 * 3) }
923
924fn default_damping_period() -> Duration {
926 Duration::from_secs(24 * 60 * 60) }
928
929fn 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))]
937pub struct OpportunisticEncryptionPersistence {
939 pub path: PathBuf,
941
942 #[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) }
954
955pub 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
971pub 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
985pub 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#[derive(Clone, Copy, Debug)]
1001pub struct ServerGroup<'a> {
1002 pub ips: &'a [IpAddr],
1004 pub server_name: &'a str,
1006 pub path: &'a str,
1008}
1009
1010impl<'a> ServerGroup<'a> {
1011 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 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 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 #[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 #[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 #[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 #[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 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 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 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 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}