1use std::collections::BTreeSet;
14use std::fmt::Write as _;
15use std::net::{IpAddr, SocketAddr};
16use std::time::Duration;
17
18use serde::Serialize;
19
20use crate::generic::Error;
21use crate::read::Reader;
22use crate::status;
23
24mod client;
25mod wire;
26
27pub use client::{ClientConfig, Resolver, parse_resolv_conf, parse_scutil};
28pub use wire::{Failure, Record, query};
29
30pub const QUERY_TIMEOUT: Duration = Duration::from_secs(2);
32
33pub const RESOLVE_TIMEOUT: Duration = Duration::from_secs(4);
35
36pub const TOTAL_TIMEOUT: Duration = Duration::from_secs(6);
38
39pub trait Probes: Sync {
41 fn query(
43 &self,
44 server: SocketAddr,
45 name: &str,
46 kind: Record,
47 ) -> impl Future<Output = Result<Vec<IpAddr>, Failure>> + Send;
48
49 fn resolve(&self, name: &str) -> impl Future<Output = Result<Vec<IpAddr>, Failure>> + Send;
51
52 fn client_config(&self) -> impl Future<Output = Option<ClientConfig>> + Send;
54}
55
56#[derive(Debug, Clone, Copy, Default)]
59pub struct System;
60
61impl Probes for System {
62 async fn query(
63 &self,
64 server: SocketAddr,
65 name: &str,
66 kind: Record,
67 ) -> Result<Vec<IpAddr>, Failure> {
68 wire::query(server, name, kind, QUERY_TIMEOUT).await
69 }
70
71 async fn resolve(&self, name: &str) -> Result<Vec<IpAddr>, Failure> {
72 let lookup = async {
73 let addresses = tokio::net::lookup_host((name, 0)).await?;
74 Ok(addresses.collect())
75 };
76 resolved(tokio::time::timeout(RESOLVE_TIMEOUT, lookup).await.ok())
77 }
78
79 async fn client_config(&self) -> Option<ClientConfig> {
80 client::read().await
81 }
82}
83
84fn resolved(result: Option<std::io::Result<Vec<SocketAddr>>>) -> Result<Vec<IpAddr>, Failure> {
86 match result {
87 None => Err(Failure::Timeout),
88 Some(Err(error)) => Err(Failure::Network(error.to_string())),
89 Some(Ok(addresses)) => Ok(addresses.iter().map(SocketAddr::ip).collect()),
90 }
91}
92
93#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
95#[error(
96 "{0:?} is not a host name: letters, digits, `-` and `_` in labels of up to 63 \
97 characters, separated by dots"
98)]
99pub struct InvalidName(pub String);
100
101pub fn check_name(text: &str) -> Result<String, InvalidName> {
108 let name = bare(text);
109 let valid = name.len() <= 253 && name.split('.').all(is_label);
111 if valid && name.parse::<IpAddr>().is_err() {
112 Ok(text.to_owned())
113 } else {
114 Err(InvalidName(text.to_owned()))
115 }
116}
117
118fn bare(name: &str) -> &str {
120 name.strip_suffix('.').unwrap_or(name)
121}
122
123fn is_label(label: &str) -> bool {
125 (1..=63).contains(&label.len())
126 && label
127 .chars()
128 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
129}
130
131pub fn parse_server(text: &str) -> Result<SocketAddr, String> {
138 text.parse::<SocketAddr>()
139 .or_else(|_| text.parse::<IpAddr>().map(|ip| SocketAddr::new(ip, 53)))
140 .map_err(|_| format!("{text:?} is not an address like 192.168.178.1 or 192.168.178.1:53"))
141}
142
143#[derive(Debug, Clone, PartialEq, Eq)]
145pub struct Request {
146 pub name: String,
148 pub expected: Option<IpAddr>,
150 pub router_dns: Option<SocketAddr>,
153}
154
155#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
157pub struct Report {
158 pub name: String,
159 pub router: RouterView,
160 pub router_answer: Answer,
162 pub client_answer: Answer,
164 pub client_config: Option<ClientConfig>,
166 pub expected: Option<Expected>,
168 pub verdict: Verdict,
169}
170
171#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
173pub struct RouterView {
174 pub domain: Option<String>,
176 pub dns_servers: Vec<String>,
178 pub address: Option<String>,
180 pub host: Option<HostEntry>,
182}
183
184#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
186pub struct HostEntry {
187 pub name: String,
188 pub ip: Option<String>,
189 pub active: bool,
190}
191
192#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
194#[serde(rename_all = "snake_case")]
195pub enum Status {
196 Answered,
197 NoSuchName,
199 NoAddress,
201 Failed,
203 Skipped,
205}
206
207#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
209pub struct Answer {
210 pub server: Option<String>,
212 pub name: String,
214 pub status: Status,
215 pub addresses: Vec<IpAddr>,
216 pub note: Option<String>,
219}
220
221impl Answer {
222 fn skipped(name: &str, server: Option<String>, note: &str) -> Self {
224 Self {
225 server,
226 name: name.to_owned(),
227 status: Status::Skipped,
228 addresses: Vec::new(),
229 note: Some(note.to_owned()),
230 }
231 }
232
233 fn from_results(
235 name: &str,
236 server: Option<String>,
237 results: Vec<Result<Vec<IpAddr>, Failure>>,
238 ) -> Self {
239 let mut addresses = Vec::new();
240 let mut failures = Vec::new();
241 for result in results {
242 match result {
243 Ok(found) => addresses.extend(found),
244 Err(failure) => failures.push(failure),
245 }
246 }
247 let mut seen = BTreeSet::new();
248 addresses.retain(|a| seen.insert(*a));
249 let failed = failures
250 .iter()
251 .find(|f| !matches!(f, Failure::NoSuchName | Failure::NoRecord));
252 let (status, failure) = if !addresses.is_empty() {
253 let note = failed.map(|f| format!("incomplete, a query failed: {f}"));
254 return Self {
255 server,
256 name: name.to_owned(),
257 status: Status::Answered,
258 addresses,
259 note,
260 };
261 } else if let Some(failure) = failed {
262 (Status::Failed, Some(failure))
263 } else if let Some(failure) = failures.iter().find(|f| **f == Failure::NoSuchName) {
264 (Status::NoSuchName, Some(failure))
265 } else {
266 (Status::NoAddress, failures.first())
267 };
268 Self {
269 server,
270 name: name.to_owned(),
271 status,
272 addresses,
273 note: failure.map(ToString::to_string),
274 }
275 }
276
277 fn answered(&self) -> bool {
278 self.status == Status::Answered
279 }
280
281 fn has(&self, address: IpAddr) -> Option<bool> {
284 if !self.answered() {
285 return None;
286 }
287 let has = self.addresses.contains(&address);
288 (has || self.note.is_none()).then_some(has)
289 }
290
291 fn list(&self) -> String {
293 join(&self.addresses)
294 }
295}
296
297#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
300pub struct Expected {
301 pub address: IpAddr,
302 pub router: Option<bool>,
303 pub client: Option<bool>,
304}
305
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
308#[serde(rename_all = "snake_case")]
309pub enum Cause {
310 Ok,
312 Mdns,
314 NotForwarded,
317 SearchDomainMissing,
319 ClientFails,
321 ClientOnly,
323 StaleRecord,
325 UnexpectedAddress,
327 RouterNoRecord,
330 UnknownName,
332 RouterUnreachable,
334 RouterUnknown,
336}
337
338#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
340pub struct Verdict {
341 pub cause: Cause,
342 pub message: String,
343}
344
345impl Verdict {
346 fn new(cause: Cause, message: impl Into<String>) -> Self {
347 Self {
348 cause,
349 message: message.into(),
350 }
351 }
352}
353
354pub async fn diagnose(
363 reader: &mut Reader,
364 probes: &impl Probes,
365 request: &Request,
366) -> Result<Report, Error> {
367 let name = request.name.as_str();
368 let mut router = router_view(reader).await?;
369 router.host = host_entry(&status::hosts(reader).await?.hosts, name, &router);
370 let server = request.router_dns.or_else(|| {
371 router
372 .address
373 .as_deref()
374 .and_then(|a| a.parse::<IpAddr>().ok())
375 .map(|ip| SocketAddr::new(ip, 53))
376 });
377 let (router_answer, client_answer, client_config) =
378 ask(probes, name, router.domain.as_deref(), server).await;
379 let expected = request.expected.map(|address| Expected {
380 address,
381 router: router_answer.has(address),
382 client: client_answer.has(address),
383 });
384 let mut report = Report {
385 name: name.to_owned(),
386 router,
387 router_answer,
388 client_answer,
389 client_config,
390 expected,
391 verdict: Verdict::new(Cause::Ok, String::new()),
392 };
393 report.verdict = verdict(&report);
394 Ok(report)
395}
396
397async fn router_view(reader: &mut Reader) -> Result<RouterView, Error> {
400 let info = reader
401 .try_read("LANHostConfigManagement1", "GetInfo", &[])
402 .await?
403 .unwrap_or_default();
404 let list = |name| {
405 info.get(name).map_or_else(Vec::new, |v| {
406 v.split(',')
407 .map(str::trim)
408 .filter(|s| !s.is_empty())
409 .map(str::to_owned)
410 .collect::<Vec<_>>()
411 })
412 };
413 Ok(RouterView {
414 domain: info
415 .text("NewDomainName")
416 .map(|d| d.trim().trim_matches('.').to_owned())
417 .filter(|d| !d.is_empty() && d != "(none)"),
418 dns_servers: list("NewDNSServers"),
419 address: list("NewIPRouters").into_iter().next(),
420 host: None,
421 })
422}
423
424fn host_entry(hosts: &[status::Host], name: &str, router: &RouterView) -> Option<HostEntry> {
428 let label = host_label(name, router.domain.as_deref())?;
429 let mut matches: Vec<&status::Host> = hosts
430 .iter()
431 .filter(|h| {
432 h.name
433 .as_deref()
434 .is_some_and(|n| n.eq_ignore_ascii_case(label))
435 })
436 .collect();
437 matches.sort_by_key(|h| !h.active);
438 matches.first().map(|host| HostEntry {
439 name: host.name.clone().unwrap_or_default(),
440 ip: host.ip.clone(),
441 active: host.active,
442 })
443}
444
445fn host_label<'a>(name: &'a str, domain: Option<&str>) -> Option<&'a str> {
447 let name = bare(name);
448 let Some((label, rest)) = name.split_once('.') else {
449 return Some(name);
450 };
451 let rest = rest.to_ascii_lowercase();
452 (rest == "local" || domain.is_some_and(|d| d.eq_ignore_ascii_case(&rest))).then_some(label)
453}
454
455fn is_mdns(name: &str) -> bool {
457 bare(name)
458 .rsplit('.')
459 .next()
460 .is_some_and(|label| label.eq_ignore_ascii_case("local"))
461}
462
463async fn ask(
466 probes: &impl Probes,
467 name: &str,
468 domain: Option<&str>,
469 server: Option<SocketAddr>,
470) -> (Answer, Answer, Option<ClientConfig>) {
471 let full = match domain {
475 Some(domain) if !name.contains('.') => format!("{name}.{domain}"),
476 _ => bare(name).to_owned(),
477 };
478 let shown = server.map(show_server);
479 if is_mdns(name) {
480 let note = "a .local name is resolved by mDNS, not asked by DNS";
481 return (
482 Answer::skipped(&full, shown, note),
483 Answer::skipped(name, None, note),
484 probes.client_config().await,
485 );
486 }
487 let router = async {
488 let Some(server) = server else {
489 return Answer::skipped(&full, None, "the address of the router is unknown");
490 };
491 let (a, aaaa) = tokio::join!(
492 probes.query(server, &full, Record::A),
493 probes.query(server, &full, Record::Aaaa)
494 );
495 Answer::from_results(&full, shown.clone(), vec![a, aaaa])
496 };
497 let client = async { Answer::from_results(name, None, vec![probes.resolve(name).await]) };
498 let all = async { tokio::join!(router, client, probes.client_config()) };
499 tokio::time::timeout(TOTAL_TIMEOUT, all)
500 .await
501 .unwrap_or_else(|_| {
502 let failed = |name: &str, server| Answer {
503 server,
504 name: name.to_owned(),
505 status: Status::Failed,
506 addresses: Vec::new(),
507 note: Some(Failure::Timeout.to_string()),
508 };
509 (failed(&full, shown.clone()), failed(name, None), None)
510 })
511}
512
513fn show_server(server: SocketAddr) -> String {
515 if server.port() == 53 {
516 server.ip().to_string()
517 } else {
518 server.to_string()
519 }
520}
521
522fn join(addresses: &[IpAddr]) -> String {
524 addresses
525 .iter()
526 .map(ToString::to_string)
527 .collect::<Vec<_>>()
528 .join(", ")
529}
530
531fn differ(one: &[IpAddr], other: &[IpAddr]) -> bool {
535 [true, false].into_iter().any(|v4| {
536 let family = |list: &[IpAddr]| -> BTreeSet<IpAddr> {
537 list.iter().copied().filter(|a| a.is_ipv4() == v4).collect()
538 };
539 let (one, other) = (family(one), family(other));
540 !one.is_empty() && !other.is_empty() && one != other
541 })
542}
543
544pub fn verdict(report: &Report) -> Verdict {
546 let router = &report.router_answer;
547 let client = &report.client_answer;
548 if is_mdns(&report.name) {
549 return mdns(report);
550 }
551 if router.status == Status::Skipped {
552 return Verdict::new(
553 Cause::RouterUnknown,
554 "the DNS server of the router is unknown, so it was not asked; give it with \
555 --router-dns",
556 );
557 }
558 match (router.answered(), client.answered()) {
559 (true, true) => both_answer(report),
560 (true, false) => client_fails(report),
561 (false, true) => Verdict::new(
562 Cause::ClientOnly,
563 format!(
564 "this machine resolves the name ({}), but the router does not ({}): the \
565 answer comes from elsewhere, like /etc/hosts, another DNS server or a VPN",
566 client.list(),
567 router.note.as_deref().unwrap_or("no address"),
568 ),
569 ),
570 (false, false) => nobody_answers(report),
571 }
572}
573
574fn mdns(report: &Report) -> Verdict {
576 let mut message = "names in .local are resolved by mDNS (Bonjour, Avahi), not by DNS, \
577 so they were not checked"
578 .to_owned();
579 if let (Some(host), Some(domain)) = (&report.router.host, &report.router.domain) {
580 let _ = write!(
581 message,
582 "; the router knows the host as {}.{domain}",
583 host.name
584 );
585 }
586 Verdict::new(Cause::Mdns, message)
587}
588
589fn both_answer(report: &Report) -> Verdict {
591 let router = &report.router_answer;
592 let client = &report.client_answer;
593 if differ(&router.addresses, &client.addresses) {
594 return Verdict::new(
595 Cause::StaleRecord,
596 format!(
597 "the router answers {} and this machine {}: one of them has a stale record, \
598 or this machine asks another server; clear the DNS cache of this machine",
599 router.list(),
600 client.list()
601 ),
602 );
603 }
604 match &report.expected {
605 Some(expected) if expected.router == Some(false) || expected.client == Some(false) => {
606 Verdict::new(
607 Cause::UnexpectedAddress,
608 format!(
609 "both answer {}, not {}: the host has another address now, or the \
610 record is stale",
611 router.list(),
612 expected.address
613 ),
614 )
615 }
616 _ => Verdict::new(
617 Cause::Ok,
618 format!("the router and this machine both answer {}", router.list()),
619 ),
620 }
621}
622
623fn client_fails(report: &Report) -> Verdict {
625 let name = report.name.as_str();
626 let domain = report.router.domain.as_deref();
627 let config = report.client_config.as_ref();
628 if let (Some(domain), Some(config)) = (domain, config) {
629 let searched = config
630 .search()
631 .iter()
632 .any(|s| s.eq_ignore_ascii_case(domain));
633 if !name.contains('.') && !searched {
634 return Verdict::new(
635 Cause::SearchDomainMissing,
636 format!(
637 "the router answers {name}.{domain}, but this machine does not add the \
638 search domain {domain} to {name}; use the full name, or add {domain} to \
639 the search domains of this machine"
640 ),
641 );
642 }
643 }
644 let router_address = report
645 .router_answer
646 .server
647 .as_deref()
648 .or(report.router.address.as_deref());
649 let asked = if name.contains('.') {
652 name
653 } else {
654 report.router_answer.name.as_str()
655 };
656 let servers = config
657 .and_then(|c| c.resolver_for(asked))
658 .map_or_else(Vec::new, |r| r.nameservers.clone());
659 let identified = !servers.is_empty()
660 && servers
661 .iter()
662 .all(|s| s.parse::<IpAddr>().is_ok_and(|ip| ip.is_ipv4()))
663 && !servers.iter().any(|s| Some(s.as_str()) == router_address);
664 let local = domain.is_none_or(|domain| in_domain(bare(name), domain));
666 if identified && local {
667 let zone = domain.unwrap_or(name);
668 let router = router_address.unwrap_or("the router");
669 let asks = if servers.iter().all(|s| client::is_local(s)) {
670 format!(
671 "a resolver on this machine ({}), whose upstream servers are unknown",
672 servers.join(", ")
673 )
674 } else {
675 servers.join(", ")
676 };
677 return Verdict::new(
678 Cause::NotForwarded,
679 format!(
680 "the router answers, but this machine asks {asks}, which does not forward \
681 {zone} to the router; add conditional forwarding of {zone} to {router} there"
682 ),
683 );
684 }
685 Verdict::new(
686 Cause::ClientFails,
687 format!(
688 "the router answers, but this machine does not resolve the name ({}); which \
689 server it asks is unknown, a VPN or a local setting may take over name resolution",
690 report.client_answer.note.as_deref().unwrap_or("no address")
691 ),
692 )
693}
694
695fn in_domain(name: &str, domain: &str) -> bool {
698 let (name, domain) = (name.to_ascii_lowercase(), domain.to_ascii_lowercase());
699 !name.contains('.') || name == domain || name.ends_with(&format!(".{domain}"))
700}
701
702fn nobody_answers(report: &Report) -> Verdict {
704 let router = &report.router_answer;
705 if router.status == Status::Failed {
706 return Verdict::new(
707 Cause::RouterUnreachable,
708 format!(
709 "the DNS server of the router ({}) did not answer ({}); check the address, or \
710 give another with --router-dns",
711 router.server.as_deref().unwrap_or("unknown"),
712 router.note.as_deref().unwrap_or("no answer"),
713 ),
714 );
715 }
716 if let Some(host) = &report.router.host {
717 return Verdict::new(
718 Cause::RouterNoRecord,
719 format!(
720 "the router knows the host {} ({}, {}), but its DNS server does not answer \
721 for {}",
722 host.name,
723 host.ip.as_deref().unwrap_or("no address"),
724 if host.active { "active" } else { "inactive" },
725 router.name
726 ),
727 );
728 }
729 Verdict::new(
730 Cause::UnknownName,
731 "neither the router nor this machine resolve the name, and the router knows no host \
732 of this name; the host may have another name on the router, see fritz hosts",
733 )
734}
735
736#[cfg(test)]
737mod tests;