1pub mod cli;
2pub mod resolvers;
3
4use std::{
5 fmt::Debug,
6 net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
7 str::FromStr,
8 sync::Arc,
9};
10
11use anyhow::{Context, anyhow};
12use hickory_resolver::{
13 config::{
14 ConnectionConfig, LookupIpStrategy, NameServerConfig, ResolveHosts, ResolverConfig,
15 ResolverOpts,
16 },
17 net::{DnsError as HickoryDnsError, NetError},
18};
19use strum::EnumString;
20
21use crate::dns::cli::DnsCli;
22
23pub const DEFAULT_RESOLVERS: &[IpAddr] = &[
25 IpAddr::V4(Ipv4Addr::new(1, 1, 1, 1)), IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)), IpAddr::V4(Ipv4Addr::new(9, 9, 9, 9)), IpAddr::V6(Ipv6Addr::new(0x2606, 0x4700, 0x4700, 0, 0, 0, 0, 0x1111)), IpAddr::V6(Ipv6Addr::new(0x2001, 0x4860, 0x4860, 0, 0, 0, 0, 0x8888)), IpAddr::V6(Ipv6Addr::new(0x2620, 0x00fe, 0, 0, 0, 0, 0, 0x00fe)), ];
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, EnumString)]
35#[strum(serialize_all = "snake_case")]
36pub enum LookupStrategy {
37 Ipv4Only,
39 Ipv6Only,
41 #[default]
43 Ipv4AndIpv6,
44 Ipv6ThenIpv4,
46 Ipv4ThenIpv6,
48}
49
50impl From<LookupStrategy> for LookupIpStrategy {
51 fn from(value: LookupStrategy) -> Self {
52 match value {
53 LookupStrategy::Ipv4Only => Self::Ipv4Only,
54 LookupStrategy::Ipv6Only => Self::Ipv6Only,
55 LookupStrategy::Ipv4AndIpv6 => Self::Ipv4AndIpv6,
56 LookupStrategy::Ipv6ThenIpv4 => Self::Ipv6thenIpv4,
57 LookupStrategy::Ipv4ThenIpv6 => Self::Ipv4thenIpv6,
58 }
59 }
60}
61
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub enum Protocol {
65 Clear(u16),
66 Tls(u16),
67 Https(u16),
68}
69
70impl FromStr for Protocol {
71 type Err = anyhow::Error;
72
73 fn from_str(s: &str) -> Result<Self, Self::Err> {
74 let mut iter = s.split(":");
75 let (proto, port) = (iter.next().unwrap(), iter.next());
76 let port = if let Some(v) = port {
77 Some(v.parse::<u16>().context("unable to parse port")?)
78 } else {
79 None
80 };
81
82 match proto {
83 "clear" => Ok(Self::Clear(port.unwrap_or(53))),
84 "tls" => Ok(Self::Tls(port.unwrap_or(853))),
85 "https" => Ok(Self::Https(port.unwrap_or(443))),
86 _ => Err(anyhow!("unknown DNS protocol: {proto}")),
87 }
88 }
89}
90
91#[derive(Debug, Clone)]
93pub struct Options {
94 pub opts: ResolverOpts,
95 pub cfg: ResolverConfig,
96}
97
98impl Options {
99 pub fn simple(addrs: &[IpAddr], port: u16) -> Self {
101 let mut opts = ResolverOpts::default();
102 opts.use_hosts_file = ResolveHosts::Never;
103 opts.preserve_intermediates = false;
104 opts.try_tcp_on_error = true;
105
106 let connections = vec![
107 {
108 let mut cfg = ConnectionConfig::udp();
109 cfg.port = port;
110 cfg
111 },
112 {
113 let mut cfg = ConnectionConfig::tcp();
114 cfg.port = port;
115 cfg
116 },
117 ];
118
119 let name_servers = addrs
120 .iter()
121 .map(|x| NameServerConfig::new(*x, true, connections.clone()))
122 .collect();
123 let cfg = ResolverConfig::from_parts(None, vec![], name_servers);
124
125 Self { opts, cfg }
126 }
127}
128
129impl Default for Options {
130 fn default() -> Self {
131 use clap::Parser;
133 #[derive(clap::Parser)]
134 struct Cli {
135 #[command(flatten)]
136 dns: DnsCli,
137 }
138 let cli = Cli::parse_from([""]);
139
140 Self::from(&cli.dns)
141 }
142}
143
144pub struct SocketAddrs {
146 pub iter: Box<dyn Iterator<Item = IpAddr> + Send>,
147}
148
149impl Iterator for SocketAddrs {
150 type Item = SocketAddr;
151
152 fn next(&mut self) -> Option<Self::Item> {
153 self.iter.next().map(|ip_addr| SocketAddr::new(ip_addr, 0))
154 }
155}
156
157impl From<&DnsCli> for Options {
158 fn from(c: &DnsCli) -> Self {
159 Self {
160 opts: ResolverOpts::from(c),
161 cfg: ResolverConfig::from(c),
162 }
163 }
164}
165
166impl From<&DnsCli> for ResolverOpts {
167 fn from(c: &DnsCli) -> Self {
168 let mut opts = Self::default();
169 opts.cache_size = c.dns_cache_size;
170 opts.timeout = c.dns_timeout;
171 opts.attempts = c.dns_attempts;
172 opts.ip_strategy = c.dns_lookup_strategy.into();
173 opts.use_hosts_file = ResolveHosts::Never;
174 opts.preserve_intermediates = false;
175 opts.validate = !c.dns_dnssec_disabled;
176 opts.try_tcp_on_error = true;
177
178 opts
179 }
180}
181
182impl From<&DnsCli> for ResolverConfig {
183 fn from(c: &DnsCli) -> Self {
184 let mut cfg = Self::default();
185
186 for srv in &c.dns_servers {
187 let connections = match c.dns_protocol {
188 Protocol::Clear(port) => vec![
189 {
190 let mut cfg = ConnectionConfig::udp();
191 cfg.port = port;
192 cfg
193 },
194 {
195 let mut cfg = ConnectionConfig::tcp();
196 cfg.port = port;
197 cfg
198 },
199 ],
200 Protocol::Tls(port) => vec![{
201 let mut cfg = ConnectionConfig::tls(Arc::from(c.dns_tls_name.as_str()));
202 cfg.port = port;
203 cfg
204 }],
205 Protocol::Https(port) => vec![{
206 let mut cfg = ConnectionConfig::https(Arc::from(c.dns_tls_name.as_str()), None);
207 cfg.port = port;
208 cfg
209 }],
210 };
211
212 let name_server = NameServerConfig::new(*srv, true, connections);
213 cfg.add_name_server(name_server);
214 }
215
216 cfg
217 }
218}
219
220#[derive(thiserror::Error, Debug)]
221pub enum DnsError {
222 #[error("Resolver error: {0}")]
223 Resolver(#[from] NetError),
224 #[error("{0}")]
225 Other(#[from] anyhow::Error),
226}
227
228pub fn is_error_negative_lookup(e: &NetError) -> bool {
230 e.is_no_records_found()
231 || e.is_nx_domain()
232 || matches!(e, NetError::Dns(HickoryDnsError::Nsec { .. }))
233}
234
235#[cfg(test)]
236mod test {
237 use super::*;
238
239 #[test]
240 fn test_protocol_from_str_defaults() {
241 assert_eq!(Protocol::from_str("clear").unwrap(), Protocol::Clear(53));
242 assert_eq!(Protocol::from_str("tls").unwrap(), Protocol::Tls(853));
243 assert_eq!(Protocol::from_str("https").unwrap(), Protocol::Https(443));
244 }
245
246 #[test]
247 fn test_protocol_from_str_custom_port() {
248 assert_eq!(
249 Protocol::from_str("clear:5353").unwrap(),
250 Protocol::Clear(5353)
251 );
252 assert_eq!(Protocol::from_str("tls:8853").unwrap(), Protocol::Tls(8853));
253 assert_eq!(
254 Protocol::from_str("https:8443").unwrap(),
255 Protocol::Https(8443)
256 );
257 }
258
259 #[test]
260 fn test_protocol_from_str_unknown_protocol() {
261 assert!(Protocol::from_str("quic").is_err());
262 }
263
264 #[test]
265 fn test_protocol_from_str_invalid_port() {
266 assert!(Protocol::from_str("clear:notaport").is_err());
267 }
268
269 #[test]
270 fn test_lookup_strategy_conversion() {
271 assert_eq!(
272 LookupIpStrategy::from(LookupStrategy::Ipv4Only),
273 LookupIpStrategy::Ipv4Only
274 );
275 assert_eq!(
276 LookupIpStrategy::from(LookupStrategy::Ipv6Only),
277 LookupIpStrategy::Ipv6Only
278 );
279 assert_eq!(
280 LookupIpStrategy::from(LookupStrategy::Ipv4AndIpv6),
281 LookupIpStrategy::Ipv4AndIpv6
282 );
283 assert_eq!(
284 LookupIpStrategy::from(LookupStrategy::Ipv6ThenIpv4),
285 LookupIpStrategy::Ipv6thenIpv4
286 );
287 assert_eq!(
288 LookupIpStrategy::from(LookupStrategy::Ipv4ThenIpv6),
289 LookupIpStrategy::Ipv4thenIpv6
290 );
291 }
292
293 #[test]
294 fn test_socket_addrs_iterator() {
295 let mut addrs = SocketAddrs {
296 iter: Box::new(vec![IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1))].into_iter()),
297 };
298
299 assert_eq!(
300 addrs.next(),
301 Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 0))
302 );
303 assert_eq!(addrs.next(), None);
304 }
305}