1use std::net::IpAddr;
6use std::path::Path;
7use std::time::Duration;
8
9use serde::Serialize;
10use tokio::io::AsyncReadExt as _;
11
12const MAX_CONFIG: u64 = 256 * 1024;
14
15pub(crate) const CONFIG_TIMEOUT: Duration = Duration::from_secs(3);
17
18#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
20pub struct ClientConfig {
21 pub source: String,
23 pub resolvers: Vec<Resolver>,
26}
27
28#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
30pub struct Resolver {
31 pub domain: Option<String>,
33 pub nameservers: Vec<String>,
35 pub search: Vec<String>,
37 pub options: Option<String>,
39}
40
41impl ClientConfig {
42 pub fn resolver_for(&self, name: &str) -> Option<&Resolver> {
45 let name = name.trim_end_matches('.').to_ascii_lowercase();
46 self.resolvers
47 .iter()
48 .filter(|r| {
49 r.domain.as_deref().is_some_and(|domain| {
50 let domain = domain.to_ascii_lowercase();
51 name == domain || name.ends_with(&format!(".{domain}"))
52 })
53 })
54 .max_by_key(|r| r.domain.as_ref().map_or(0, String::len))
55 .or_else(|| self.resolvers.iter().find(|r| r.domain.is_none()))
56 }
57
58 pub fn search(&self) -> Vec<&str> {
60 let mut search: Vec<&str> = Vec::new();
61 for domain in self
62 .resolvers
63 .iter()
64 .filter(|r| r.domain.is_none())
65 .flat_map(|r| &r.search)
66 {
67 if !search.contains(&domain.as_str()) {
68 search.push(domain);
69 }
70 }
71 search
72 }
73}
74
75pub fn parse_scutil(text: &str) -> ClientConfig {
78 let mut resolvers = Vec::new();
79 let mut current: Option<Resolver> = None;
80 for line in text.lines() {
81 let line = line.trim();
82 if line.starts_with("DNS configuration (") {
83 break;
84 }
85 if line.starts_with("resolver #") {
86 resolvers.extend(current.replace(Resolver::default()));
87 continue;
88 }
89 let (Some(resolver), Some((key, value))) = (current.as_mut(), line.split_once(':')) else {
90 continue;
91 };
92 let value = value.trim().to_owned();
93 match key.trim() {
94 "domain" => resolver.domain = Some(value),
95 "options" => resolver.options = Some(value),
96 key if key.starts_with("nameserver[") => resolver.nameservers.push(value),
97 key if key.starts_with("search domain[") => resolver.search.push(value),
98 _ => {}
99 }
100 }
101 resolvers.extend(current);
102 ClientConfig {
103 source: "scutil --dns".to_owned(),
104 resolvers: forward(resolvers),
105 }
106}
107
108pub fn parse_resolv_conf(text: &str) -> ClientConfig {
111 let mut resolver = Resolver::default();
112 for line in text.lines() {
113 let mut words = line.split_whitespace();
114 match words.next() {
115 Some("nameserver") => resolver.nameservers.extend(words.next().map(str::to_owned)),
116 Some("search" | "domain") => {
118 resolver.search = words
119 .take_while(|w| !w.starts_with(['#', ';']))
120 .map(str::to_owned)
121 .collect();
122 }
123 _ => {}
124 }
125 }
126 ClientConfig {
127 source: "/etc/resolv.conf".to_owned(),
128 resolvers: vec![resolver],
129 }
130}
131
132fn forward(resolvers: Vec<Resolver>) -> Vec<Resolver> {
134 resolvers
135 .into_iter()
136 .filter(|r| {
137 !r.domain
138 .as_deref()
139 .is_some_and(|d| d.trim_end_matches('.').ends_with("arpa"))
140 })
141 .collect()
142}
143
144pub(crate) fn is_local(server: &str) -> bool {
147 server
148 .split('%')
149 .next()
150 .and_then(|s| s.parse::<IpAddr>().ok())
151 .is_some_and(|ip| ip.is_loopback())
152}
153
154#[derive(Debug, Clone, Copy, PartialEq, Eq)]
156enum Source {
157 Scutil,
159 ResolvConf,
161}
162
163fn source(os: &str) -> Option<Source> {
166 match os {
167 "macos" => Some(Source::Scutil),
168 "windows" => None,
169 _ => Some(Source::ResolvConf),
170 }
171}
172
173pub(crate) async fn read() -> Option<ClientConfig> {
175 read_from(source(std::env::consts::OS)?).await
176}
177
178async fn read_from(source: Source) -> Option<ClientConfig> {
180 let text = match source {
181 Source::Scutil => run("scutil", &["--dns"], CONFIG_TIMEOUT).await?,
182 Source::ResolvConf => read_file(Path::new("/etc/resolv.conf"), CONFIG_TIMEOUT).await?,
183 };
184 Some(source.parse(&text))
185}
186
187impl Source {
188 fn parse(self, text: &str) -> ClientConfig {
190 match self {
191 Source::Scutil => parse_scutil(text),
192 Source::ResolvConf => parse_resolv_conf(text),
193 }
194 }
195}
196
197pub(crate) async fn run(program: &str, args: &[&str], timeout: Duration) -> Option<String> {
200 let output = async {
201 let mut child = tokio::process::Command::new(program)
202 .args(args)
203 .stdin(std::process::Stdio::null())
204 .stdout(std::process::Stdio::piped())
205 .stderr(std::process::Stdio::null())
206 .kill_on_drop(true)
207 .spawn()
208 .ok()?;
209 let mut text = String::new();
210 child
211 .stdout
212 .take()?
213 .take(MAX_CONFIG)
214 .read_to_string(&mut text)
215 .await
216 .ok()?;
217 child.wait().await.ok()?.success().then_some(text)
218 };
219 tokio::time::timeout(timeout, output).await.ok().flatten()
220}
221
222pub(crate) async fn read_file(path: &Path, timeout: Duration) -> Option<String> {
224 let read = async {
225 let mut text = String::new();
226 tokio::fs::File::open(path)
227 .await
228 .ok()?
229 .take(MAX_CONFIG)
230 .read_to_string(&mut text)
231 .await
232 .ok()?;
233 Some(text)
234 };
235 tokio::time::timeout(timeout, read).await.ok().flatten()
236}
237
238#[cfg(test)]
239mod tests {
240 use super::*;
241
242 const SCUTIL: &str = "\
243DNS configuration
244
245resolver #1
246 search domain[0] : fritz.box
247 search domain[1] : example.org
248 nameserver[0] : 192.168.178.1
249 nameserver[1] : fd00::1
250 if_index : 14 (en0)
251 flags : Request A records, Request AAAA records
252
253resolver #2
254 domain : local
255 options : mdns
256 timeout : 5
257
258resolver #3
259 domain : 254.169.in-addr.arpa
260 options : mdns
261
262resolver #4
263 domain : corp.example
264 nameserver[0] : 10.8.0.1
265
266DNS configuration (for scoped queries)
267
268resolver #1
269 search domain[0] : other.example
270 nameserver[0] : 192.168.178.1
271";
272
273 const RESOLV_CONF: &str = "\
274# Generated
275nameserver 127.0.0.53
276nameserver
277options edns0 trust-ad
278domain old.example
279search fritz.box lan # comment
280";
281
282 #[test]
283 fn parses_scutil() {
284 let config = parse_scutil(SCUTIL);
285 assert_eq!(config.source, "scutil --dns");
286 assert_eq!(
287 config.resolvers,
288 [
289 Resolver {
290 domain: None,
291 nameservers: vec!["192.168.178.1".to_owned(), "fd00::1".to_owned()],
292 search: vec!["fritz.box".to_owned(), "example.org".to_owned()],
293 options: None,
294 },
295 Resolver {
296 domain: Some("local".to_owned()),
297 options: Some("mdns".to_owned()),
298 ..Resolver::default()
299 },
300 Resolver {
301 domain: Some("corp.example".to_owned()),
302 nameservers: vec!["10.8.0.1".to_owned()],
303 ..Resolver::default()
304 },
305 ]
306 );
307 assert_eq!(config.search(), ["fritz.box", "example.org"]);
308 let twice = ClientConfig {
309 source: String::new(),
310 resolvers: vec![config.resolvers[0].clone(), config.resolvers[0].clone()],
311 };
312 assert_eq!(twice.search(), ["fritz.box", "example.org"]);
313 assert_eq!(parse_scutil("").resolvers, []);
314 }
315
316 #[test]
317 fn parses_resolv_conf() {
318 let config = parse_resolv_conf(RESOLV_CONF);
319 assert_eq!(config.source, "/etc/resolv.conf");
320 assert_eq!(
321 config.resolvers,
322 [Resolver {
323 nameservers: vec!["127.0.0.53".to_owned()],
324 search: vec!["fritz.box".to_owned(), "lan".to_owned()],
325 ..Resolver::default()
326 }]
327 );
328 }
329
330 #[test]
331 fn finds_the_resolver_for_a_name() {
332 let config = parse_scutil(SCUTIL);
333 let domain = |name| config.resolver_for(name).and_then(|r| r.domain.clone());
334 assert_eq!(domain("printer.local"), Some("local".to_owned()));
335 assert_eq!(domain("A.Corp.Example."), Some("corp.example".to_owned()));
336 assert_eq!(domain("corp.example"), Some("corp.example".to_owned()));
337 assert_eq!(domain("nas.fritz.box"), None);
338 assert!(config.resolver_for("nas").is_some());
339 assert!(ClientConfig::default().resolver_for("nas").is_none());
340 }
341
342 #[test]
343 fn knows_local_servers() {
344 assert!(is_local("127.0.0.53"));
345 assert!(is_local("::1"));
346 assert!(!is_local("192.168.178.1"));
347 assert!(!is_local("fe80::1%en0"));
348 assert!(!is_local("name"));
349 }
350
351 #[cfg(unix)]
352 #[tokio::test]
353 async fn runs_commands_with_limits() {
354 assert_eq!(
355 run("echo", &["resolver"], CONFIG_TIMEOUT).await.as_deref(),
356 Some("resolver\n")
357 );
358 assert_eq!(run("false", &[], CONFIG_TIMEOUT).await, None);
359 assert_eq!(
360 run("fritz-no-such-command", &[], CONFIG_TIMEOUT).await,
361 None
362 );
363 assert_eq!(run("printf", &["\\377"], CONFIG_TIMEOUT).await, None);
365 let slow = run("sleep", &["5"], Duration::from_millis(50));
366 assert_eq!(slow.await, None);
367 }
368
369 #[tokio::test]
370 async fn reads_files_with_limits() {
371 let dir = tempfile::tempdir().unwrap();
372 let path = dir.path().join("resolv.conf");
373 std::fs::write(&path, "x".repeat(300 * 1024)).unwrap();
374 let text = read_file(&path, CONFIG_TIMEOUT).await.unwrap();
375 assert_eq!(text.len(), 256 * 1024);
376 assert_eq!(
377 read_file(&dir.path().join("missing"), CONFIG_TIMEOUT).await,
378 None
379 );
380 std::fs::write(&path, [0xff, 0xfe]).unwrap();
381 assert_eq!(read_file(&path, CONFIG_TIMEOUT).await, None);
382 }
383
384 #[tokio::test]
385 async fn reads_the_configuration_of_this_machine() {
386 assert_eq!(source("macos"), Some(Source::Scutil));
387 assert_eq!(source("linux"), Some(Source::ResolvConf));
388 assert_eq!(source("windows"), None);
389 assert_eq!(Source::Scutil.parse(SCUTIL), parse_scutil(SCUTIL));
390 assert_eq!(
391 Source::ResolvConf.parse("nameserver 192.0.2.1\n"),
392 parse_resolv_conf("nameserver 192.0.2.1\n")
393 );
394 for source in [Source::Scutil, Source::ResolvConf] {
396 if let Some(config) = read_from(source).await {
397 assert_ne!(config.source, "");
398 }
399 }
400 let _ = read().await;
401 }
402}