dnskit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,223 @@
1
+ """Discovering, probing and choosing the system's nameservers."""
2
+
3
+ import json
4
+ import os
5
+ import sys
6
+ import time
7
+ from collections.abc import Sequence
8
+ from concurrent.futures import ThreadPoolExecutor
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ import dns.message
13
+ import dns.query
14
+ import dns.rcode
15
+ import dns.resolver
16
+
17
+ from dnskit.core.adapters import AdapterScan, is_loopback, normalize_ip, scan_adapters
18
+
19
+ # How long a probed choice is reused, so repeated commands use the same nameserver.
20
+ CACHE_TTL_S = 300.0
21
+ # Probe timeout: a nameserver that can't answer a trivial query within this is "failed".
22
+ PROBE_TIMEOUT_S = 1.0
23
+ # A nameserver that answers, but slower than this, is reported as slow.
24
+ SLOW_THRESHOLD_MS = 250.0
25
+
26
+ _CACHE_VERSION = 1
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class ProbeResult:
31
+ nameserver: str
32
+ latency_ms: float | None # None means no usable answer within the timeout
33
+
34
+
35
+ @dataclass(frozen=True)
36
+ class ResolverChoice:
37
+ """The outcome of probing the system nameservers, fresh or from the cache."""
38
+
39
+ nameserver: str | None # fastest responder, or None if none answered
40
+ probes: tuple[ProbeResult, ...] # in system order
41
+ probed_at: float # Unix time of the probe
42
+ from_cache: bool
43
+
44
+ @property
45
+ def failed(self) -> tuple[ProbeResult, ...]:
46
+ return tuple(p for p in self.probes if p.latency_ms is None)
47
+
48
+ @property
49
+ def slow(self) -> tuple[ProbeResult, ...]:
50
+ return tuple(
51
+ p for p in self.probes if p.latency_ms is not None and p.latency_ms > SLOW_THRESHOLD_MS
52
+ )
53
+
54
+ @property
55
+ def latency_ms(self) -> float | None:
56
+ return next((p.latency_ms for p in self.probes if p.nameserver == self.nameserver), None)
57
+
58
+ def ordered(self) -> list[str]:
59
+ """All probed nameservers, fastest first; non-responders last, in system order."""
60
+ responsive = sorted(
61
+ (p for p in self.probes if p.latency_ms is not None), key=lambda p: p.latency_ms or 0.0
62
+ )
63
+ return [p.nameserver for p in responsive] + [p.nameserver for p in self.failed]
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class SystemNameservers:
68
+ """The OS's configured nameservers, split by whether a connected adapter uses them."""
69
+
70
+ configured: tuple[str, ...] # everything the OS configuration lists, in system order
71
+ usable: tuple[str, ...] # the ones to query, in system order
72
+ ignored: tuple[str, ...] # configured, but on no connected adapter ("ghosts")
73
+
74
+
75
+ def configured_nameservers() -> list[str]:
76
+ """Every nameserver in the OS configuration, as dnspython reads it, in system order.
77
+
78
+ On Windows this is every interface in the registry, including disconnected adapters and
79
+ leftovers from adapters that no longer exist; `system_nameservers` filters those out.
80
+ """
81
+ try:
82
+ resolver = dns.resolver.Resolver()
83
+ except dns.resolver.NoResolverConfiguration:
84
+ return []
85
+ return [str(ns) for ns in resolver.nameservers]
86
+
87
+
88
+ def classify_nameservers(
89
+ configured: Sequence[str] | None = None, scan: AdapterScan | None = None
90
+ ) -> SystemNameservers:
91
+ """Split the configured nameservers into those on a connected adapter and the rest.
92
+
93
+ Like the OS's own DNS client, only nameservers of connected adapters are usable; local
94
+ stubs (127.0.0.53, ::1) always are. When adapters can't be matched to nameservers, or
95
+ the filter would leave nothing (e.g. offline), every configured nameserver is usable.
96
+ """
97
+ configured = tuple(configured_nameservers() if configured is None else configured)
98
+ scan = scan_adapters() if scan is None else scan
99
+ if not scan.dns_per_adapter:
100
+ return SystemNameservers(configured, configured, ())
101
+ connected = scan.connected_dns()
102
+ usable = tuple(ns for ns in configured if normalize_ip(ns) in connected or is_loopback(ns))
103
+ if not usable:
104
+ return SystemNameservers(configured, configured, ())
105
+ return SystemNameservers(configured, usable, tuple(ns for ns in configured if ns not in usable))
106
+
107
+
108
+ def system_nameservers() -> list[str]:
109
+ """The nameservers this computer actually uses: configured, on a connected adapter."""
110
+ return list(classify_nameservers().usable)
111
+
112
+
113
+ def probe(nameserver: str, timeout: float) -> float | None:
114
+ """Send one recursive query to `nameserver`; return latency in ms, or None if unusable."""
115
+ query = dns.message.make_query(".", "NS")
116
+ start = time.perf_counter()
117
+ try:
118
+ response = dns.query.udp(query, nameserver, timeout=timeout)
119
+ except Exception:
120
+ return None
121
+ if response.rcode() != dns.rcode.NOERROR:
122
+ return None
123
+ return (time.perf_counter() - start) * 1000
124
+
125
+
126
+ def probe_all(candidates: Sequence[str], timeout: float = PROBE_TIMEOUT_S) -> list[ProbeResult]:
127
+ """Probe every candidate in parallel and wait for all of them. Keeps input order."""
128
+ if not candidates:
129
+ return []
130
+ with ThreadPoolExecutor(max_workers=len(candidates)) as pool:
131
+ latencies = list(pool.map(lambda ns: probe(ns, timeout), candidates))
132
+ return [ProbeResult(ns, latency) for ns, latency in zip(candidates, latencies, strict=True)]
133
+
134
+
135
+ def choose_nameserver(
136
+ candidates: Sequence[str],
137
+ *,
138
+ use_cache: bool = True,
139
+ ttl: float = CACHE_TTL_S,
140
+ timeout: float = PROBE_TIMEOUT_S,
141
+ ) -> ResolverChoice:
142
+ """Pick the fastest of `candidates`, reusing a recent choice when one is cached.
143
+
144
+ A cached choice is reused only if it is younger than `ttl` and was made for exactly the
145
+ same nameserver list (a changed list means the network changed). A fresh probe waits
146
+ for every candidate (up to `timeout`) so failed and slow servers can be reported; it is
147
+ cached only if some nameserver answered. `use_cache=False` always probes, and still
148
+ saves the result for later runs.
149
+ """
150
+ candidates = list(candidates)
151
+ if use_cache:
152
+ cached = _load_cached_choice(candidates, ttl)
153
+ if cached is not None:
154
+ return cached
155
+
156
+ probes = tuple(probe_all(candidates, timeout))
157
+ responsive = [p for p in probes if p.latency_ms is not None]
158
+ fastest = min(responsive, key=lambda p: p.latency_ms or 0.0) if responsive else None
159
+ choice = ResolverChoice(
160
+ nameserver=fastest.nameserver if fastest else None,
161
+ probes=probes,
162
+ probed_at=_now(),
163
+ from_cache=False,
164
+ )
165
+ if choice.nameserver is not None:
166
+ _save_choice(candidates, choice)
167
+ return choice
168
+
169
+
170
+ def cache_path() -> Path:
171
+ """Where the resolver choice is cached. Override the directory with DNSKIT_CACHE_DIR."""
172
+ if override := os.environ.get("DNSKIT_CACHE_DIR"):
173
+ base = Path(override)
174
+ elif sys.platform == "win32" and (local := os.environ.get("LOCALAPPDATA")):
175
+ base = Path(local) / "dnskit"
176
+ else:
177
+ xdg = os.environ.get("XDG_CACHE_HOME")
178
+ base = (Path(xdg) if xdg else Path.home() / ".cache") / "dnskit"
179
+ return base / "resolver.json"
180
+
181
+
182
+ def _now() -> float:
183
+ return time.time()
184
+
185
+
186
+ def _load_cached_choice(candidates: list[str], ttl: float) -> ResolverChoice | None:
187
+ """Return the cached choice if it is still valid for `candidates`; any problem is a miss."""
188
+ try:
189
+ data = json.loads(cache_path().read_text(encoding="utf-8"))
190
+ if not isinstance(data, dict):
191
+ return None
192
+ if data.get("version") != _CACHE_VERSION or data.get("system") != candidates:
193
+ return None
194
+ probed_at = float(data["probed_at"])
195
+ age = _now() - probed_at
196
+ if not 0 <= age < ttl:
197
+ return None
198
+ probes = tuple(ProbeResult(str(ns), latency) for ns, latency in data["probes"])
199
+ chosen = str(data["nameserver"])
200
+ except (OSError, ValueError, KeyError, TypeError):
201
+ return None
202
+ if [p.nameserver for p in probes] != candidates or chosen not in candidates:
203
+ return None
204
+ return ResolverChoice(chosen, probes, probed_at, from_cache=True)
205
+
206
+
207
+ def _save_choice(candidates: list[str], choice: ResolverChoice) -> None:
208
+ """Write the choice atomically; failing to cache is not an error."""
209
+ data = {
210
+ "version": _CACHE_VERSION,
211
+ "system": candidates,
212
+ "nameserver": choice.nameserver,
213
+ "probed_at": choice.probed_at,
214
+ "probes": [[p.nameserver, p.latency_ms] for p in choice.probes],
215
+ }
216
+ path = cache_path()
217
+ try:
218
+ path.parent.mkdir(parents=True, exist_ok=True)
219
+ tmp = path.with_suffix(f".{os.getpid()}.tmp")
220
+ tmp.write_text(json.dumps(data), encoding="utf-8")
221
+ tmp.replace(path)
222
+ except OSError:
223
+ pass
dnskit/core/outside.py ADDED
@@ -0,0 +1,113 @@
1
+ """Is DNS to outside servers blocked? VPNs and firewalls often allow DNS only to their own.
2
+
3
+ `trace`, `dnssec --server` and `propagation` send queries straight to servers on the
4
+ internet (root servers, public resolvers). Many VPNs (DNS leak protection) and firewalls
5
+ drop those and let DNS through only to the network's own DNS server, so the queries just
6
+ time out. This module tells that apart from being offline, and explains it.
7
+ """
8
+
9
+ import errno
10
+ import socket
11
+ from dataclasses import dataclass
12
+
13
+ from dnskit.core.adapters import scan_adapters
14
+ from dnskit.core.diagnosis import Diagnosis
15
+ from dnskit.core.nameservers import PROBE_TIMEOUT_S, classify_nameservers, probe_all
16
+
17
+ # An outside DNS server used to test for a firewall on this computer (Quad9).
18
+ FIREWALL_TEST_SERVER = "9.9.9.9"
19
+
20
+ # errno values for "this computer isn't allowed to connect": a local firewall said no.
21
+ # Windows: 10013 WSAEACCES (e.g. a VPN's kill switch, Windows Firewall rules).
22
+ _DENIED_ERRNOS = {errno.EACCES, errno.EPERM, 10013}
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class DnsBlocking:
27
+ """Why outside DNS servers might not answer, measured when they didn't."""
28
+
29
+ working_nameservers: tuple[str, ...] # this computer's own DNS servers that answered
30
+ vpns: tuple[str, ...] # names of connected VPN adapters
31
+ local_firewall: bool # this computer refused to even open a connection to port 53
32
+
33
+ @property
34
+ def system_works(self) -> bool:
35
+ return bool(self.working_nameservers)
36
+
37
+
38
+ def check_blocking(timeout: float = PROBE_TIMEOUT_S) -> DnsBlocking:
39
+ """Probe this computer's own DNS servers and look for a VPN and a local firewall."""
40
+ scan = scan_adapters()
41
+ nameservers = classify_nameservers(scan=scan).usable
42
+ probes = probe_all(nameservers, timeout)
43
+ return DnsBlocking(
44
+ working_nameservers=tuple(p.nameserver for p in probes if p.latency_ms is not None),
45
+ vpns=tuple(a.name for a in scan.connected_vpns),
46
+ local_firewall=firewall_blocks(FIREWALL_TEST_SERVER, timeout),
47
+ )
48
+
49
+
50
+ def firewall_blocks(address: str, timeout: float) -> bool:
51
+ """True if this computer refuses a TCP connection to `address` port 53 outright."""
52
+ family = socket.AF_INET6 if ":" in address else socket.AF_INET
53
+ try:
54
+ with socket.socket(family, socket.SOCK_STREAM) as sock:
55
+ sock.settimeout(timeout)
56
+ sock.connect((address, 53))
57
+ except OSError as exc:
58
+ return exc.errno in _DENIED_ERRNOS or getattr(exc, "winerror", None) in _DENIED_ERRNOS
59
+ return False
60
+
61
+
62
+ def blocked_diagnosis(
63
+ blocking: DnsBlocking, what: str, alternative: str = "", one: bool = False
64
+ ) -> Diagnosis:
65
+ """Explain why `what` (e.g. "the root servers"; one server if `one`) didn't answer.
66
+
67
+ `alternative` is appended to the suggestion: what the command did or can do instead.
68
+ """
69
+ tail = f" {alternative}" if alternative else ""
70
+ fine = (
71
+ f" {_capitalize(what)} {'is' if one else 'are'} almost certainly fine; "
72
+ f"{'it just can' if one else 'they just can'}'t be reached from here."
73
+ )
74
+ if not blocking.system_works:
75
+ return Diagnosis(
76
+ title="No DNS server answers: this computer looks offline",
77
+ explanation=f"No reply from {what}, and this computer's own DNS servers don't "
78
+ "answer either, so it probably has no working network connection.",
79
+ suggestion="Check your Wi-Fi, Ethernet or VPN connection and try again. "
80
+ "`dnskit local` checks this computer's DNS setup step by step." + tail,
81
+ )
82
+
83
+ own = ", ".join(blocking.working_nameservers)
84
+ firewall = (
85
+ " This computer itself refused to connect to an outside DNS server, so the block is "
86
+ "a firewall on this computer" + (" (the VPN's kill switch)." if blocking.vpns else ".")
87
+ if blocking.local_firewall
88
+ else ""
89
+ )
90
+ if blocking.vpns:
91
+ vpn = ", ".join(blocking.vpns)
92
+ return Diagnosis(
93
+ title="Direct DNS queries are blocked by the VPN",
94
+ explanation=f"No reply from {what}, but this computer's own DNS server ({own}) "
95
+ f"works. {vpn} (VPN) is connected, and VPNs usually block DNS to every server "
96
+ "except their own, so DNS can't leak outside the tunnel (DNS leak protection)."
97
+ f"{firewall}{fine}",
98
+ suggestion=f"Disconnect {vpn} and run this again, or run it on another network." + tail,
99
+ )
100
+ return Diagnosis(
101
+ title="Direct DNS queries are blocked by a firewall",
102
+ explanation=f"No reply from {what}, but this computer's own DNS server ({own}) works. "
103
+ "A firewall is probably blocking DNS (port 53) to outside servers and allowing only "
104
+ f"the network's own DNS server: work, school, hotel and some home networks do this."
105
+ f"{firewall}{fine}",
106
+ suggestion="Run this on another network (a phone hotspot works), or ask the network's "
107
+ "administrator. On your own network, look for firewall rules blocking outgoing port "
108
+ "53." + tail,
109
+ )
110
+
111
+
112
+ def _capitalize(text: str) -> str:
113
+ return text[:1].upper() + text[1:]
@@ -0,0 +1,277 @@
1
+ """Has a DNS change reached resolvers around the world? Ask public resolvers in many regions.
2
+
3
+ After a record changes, each resolver keeps serving its cached copy until that copy's TTL
4
+ runs out, so for a while some answer old and some new. This asks global anycast
5
+ resolvers plus resolvers in fixed countries, and reports what share give the most common
6
+ answer.
7
+ """
8
+
9
+ import time
10
+ from collections.abc import Sequence
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from dataclasses import dataclass
13
+
14
+ from dnskit.core.compare import Agreement, rank_answers
15
+ from dnskit.core.diagnosis import Diagnosis
16
+ from dnskit.core.lookup import LookupResult, LookupStatus, _query_one, _validate_rtype
17
+ from dnskit.core.outside import DnsBlocking, blocked_diagnosis, check_blocking
18
+ from dnskit.core.reach import parse_target
19
+
20
+ GLOBAL_REGION = "Global (anycast)"
21
+ # Shown with the global group: where its answers come from.
22
+ ANYCAST_NOTE = (
23
+ "Global (anycast) resolvers answer from their site nearest to you, so they show what "
24
+ "people near you see, not what other regions see."
25
+ )
26
+
27
+
28
+ @dataclass(frozen=True)
29
+ class PublicResolver:
30
+ name: str # operator, e.g. "Quad9"
31
+ address: str
32
+ location: str # the country it answers from; "nearest site" for anycast
33
+ region: str # for grouping: GLOBAL_REGION, "Americas", "Europe", "Asia"
34
+
35
+ @property
36
+ def anycast(self) -> bool:
37
+ return self.region == GLOBAL_REGION
38
+
39
+
40
+ # Plain (port 53), unfiltered public resolvers. The global anycast services answer from
41
+ # whichever of their sites is nearest the user, so only resolvers with a fixed location
42
+ # are grouped by region.
43
+ PROPAGATION_RESOLVERS: tuple[PublicResolver, ...] = (
44
+ PublicResolver("Google", "8.8.8.8", "nearest site", GLOBAL_REGION),
45
+ PublicResolver("Cloudflare", "1.1.1.1", "nearest site", GLOBAL_REGION),
46
+ PublicResolver("Quad9", "9.9.9.9", "nearest site", GLOBAL_REGION),
47
+ PublicResolver("OpenDNS", "208.67.222.222", "nearest site", GLOBAL_REGION),
48
+ PublicResolver("Hurricane Electric", "74.82.42.42", "nearest site", GLOBAL_REGION),
49
+ PublicResolver("Control D", "76.76.2.0", "nearest site", GLOBAL_REGION),
50
+ PublicResolver("AdGuard", "94.140.14.140", "nearest site", GLOBAL_REGION),
51
+ PublicResolver("CIRA Shield", "149.112.121.10", "Canada", "Americas"),
52
+ PublicResolver("DNS.WATCH", "84.200.69.80", "Germany", "Europe"),
53
+ PublicResolver("Yandex", "77.88.8.8", "Russia", "Europe"),
54
+ PublicResolver("KT", "168.126.63.1", "South Korea", "Asia"),
55
+ PublicResolver("AliDNS", "223.5.5.5", "China", "Asia"),
56
+ PublicResolver("DNSPod", "119.29.29.29", "China", "Asia"),
57
+ PublicResolver("114DNS", "114.114.114.114", "China", "Asia"),
58
+ )
59
+
60
+ # Per resolver. Healthy ones answer in well under a second even from far away, and every
61
+ # resolver is asked at once, so a dead one costs this much on the total.
62
+ PROPAGATION_TIMEOUT_S = 1.5
63
+ # Re-send an unanswered query this often within the timeout: on a lossy path a
64
+ # single dropped packet would otherwise make a healthy far-away resolver time out.
65
+ PROPAGATION_RETRY_S = 0.5
66
+
67
+
68
+ @dataclass(frozen=True)
69
+ class PropagationAnswer:
70
+ resolver: PublicResolver
71
+ result: LookupResult
72
+ agreement: Agreement
73
+
74
+ @property
75
+ def ttl(self) -> int | None:
76
+ return self.result.records[0].ttl if self.result.records else None
77
+
78
+
79
+ @dataclass(frozen=True)
80
+ class PropagationReport:
81
+ name: str
82
+ rtype: str
83
+ answers: tuple[PropagationAnswer, ...] # in PROPAGATION_RESOLVERS order
84
+ has_majority: bool
85
+ distinct_answers: int
86
+ elapsed_ms: float
87
+ # Set when most resolvers didn't respond: whether a VPN or firewall blocks them.
88
+ blocking: DnsBlocking | None = None
89
+
90
+ @property
91
+ def responded(self) -> tuple[PropagationAnswer, ...]:
92
+ return tuple(a for a in self.answers if a.agreement is not Agreement.FAILED)
93
+
94
+ @property
95
+ def failed(self) -> tuple[PropagationAnswer, ...]:
96
+ return tuple(a for a in self.answers if a.agreement is Agreement.FAILED)
97
+
98
+ @property
99
+ def majority(self) -> tuple[PropagationAnswer, ...]:
100
+ return tuple(a for a in self.answers if a.agreement is Agreement.MAJORITY)
101
+
102
+ @property
103
+ def differing(self) -> tuple[PropagationAnswer, ...]:
104
+ return tuple(a for a in self.answers if a.agreement is Agreement.DIFFERS)
105
+
106
+ @property
107
+ def blocked(self) -> bool:
108
+ """Too few resolvers could be reached to measure anything, because of a block."""
109
+ return self.blocking is not None and len(self.responded) < 2
110
+
111
+ @property
112
+ def percent(self) -> float:
113
+ """Share of the responding resolvers that give the most common answer."""
114
+ if not self.responded or not self.has_majority:
115
+ return 0.0
116
+ return 100 * len(self.majority) / len(self.responded)
117
+
118
+ @property
119
+ def location_based(self) -> bool:
120
+ """The differences look like geo-DNS (a CDN answering by region), not propagation.
121
+
122
+ True for an A/AAAA lookup when every global anycast resolver that answered (at least
123
+ two) gives the most common answer and only fixed-location resolvers give addresses
124
+ that differ. Anycast resolvers spread over many networks would also lag if a change
125
+ were still propagating; a CDN instead gives other countries their own addresses.
126
+ """
127
+ if self.rtype not in ("A", "AAAA") or not self.has_majority or not self.differing:
128
+ return False
129
+ anycast = [a for a in self.responded if a.resolver.anycast]
130
+ return (
131
+ len(anycast) >= 2
132
+ and all(a.agreement is Agreement.MAJORITY for a in anycast)
133
+ and self.majority[0].result.status is LookupStatus.OK
134
+ and all(a.result.status is LookupStatus.OK for a in self.differing)
135
+ )
136
+
137
+ @property
138
+ def complete(self) -> bool:
139
+ """Every resolver that responded (at least two) gives the same answer."""
140
+ return len(self.responded) >= 2 and not self.differing and not self.blocked
141
+
142
+
143
+ def propagation(
144
+ target: str,
145
+ rtype: str = "A",
146
+ timeout: float = PROPAGATION_TIMEOUT_S,
147
+ resolvers: Sequence[PublicResolver] | None = None,
148
+ ) -> PropagationReport:
149
+ """Ask every resolver in PROPAGATION_RESOLVERS (or `resolvers`, e.g. from the config
150
+ file) for `target`/`rtype`, all at once.
151
+
152
+ Each is asked on its own (no fallback). Answers compare as in `compare()`. When more
153
+ than half don't respond, `check_blocking` finds out whether a VPN or firewall is the
154
+ cause. An invalid name or record type raises ValueError.
155
+ """
156
+ name = parse_target(target)
157
+ rtype = _validate_rtype(rtype)
158
+ resolvers = PROPAGATION_RESOLVERS if resolvers is None else tuple(resolvers)
159
+ start = time.perf_counter()
160
+ with ThreadPoolExecutor(max_workers=len(resolvers)) as pool:
161
+ results = list(
162
+ pool.map(
163
+ lambda r: _query_one(
164
+ name, rtype, [r.address], timeout, retry_after=PROPAGATION_RETRY_S
165
+ ),
166
+ resolvers,
167
+ )
168
+ )
169
+ ranking = rank_answers(results)
170
+ answers = tuple(
171
+ PropagationAnswer(resolver, result, agreement)
172
+ for resolver, result, agreement in zip(resolvers, results, ranking.agreements, strict=True)
173
+ )
174
+ failed = sum(1 for a in answers if a.agreement is Agreement.FAILED)
175
+ blocking = check_blocking() if failed > len(answers) / 2 else None
176
+ return PropagationReport(
177
+ name=name,
178
+ rtype=rtype,
179
+ answers=answers,
180
+ has_majority=ranking.has_majority,
181
+ distinct_answers=ranking.distinct_answers,
182
+ elapsed_ms=(time.perf_counter() - start) * 1000,
183
+ blocking=blocking,
184
+ )
185
+
186
+
187
+ def explain_propagation(report: PropagationReport) -> Diagnosis:
188
+ """What the spread of answers means, and what to do."""
189
+ name, rtype = report.name, report.rtype
190
+ responded = len(report.responded)
191
+ if report.blocking is not None and responded < 2:
192
+ reached = (
193
+ f"Only {responded} of {len(report.answers)} resolvers could be reached"
194
+ if responded
195
+ else "None of the resolvers could be reached"
196
+ )
197
+ return blocked_diagnosis(
198
+ report.blocking,
199
+ f"{len(report.failed)} of the {len(report.answers)} public resolvers",
200
+ f"{reached}, so propagation can't be measured from here. An online checker "
201
+ '(search for "DNS propagation checker") works from anywhere.',
202
+ )
203
+ if responded == 0:
204
+ return Diagnosis(
205
+ title="No resolver answered",
206
+ explanation=f"None of the {len(report.answers)} resolvers gave an answer for "
207
+ f"{name} {rtype}.",
208
+ suggestion="Check your connection and try again, perhaps with a longer --timeout.",
209
+ )
210
+ if not report.differing:
211
+ if report.majority and report.majority[0].result.status is LookupStatus.NXDOMAIN:
212
+ what = f"{name} doesn't exist"
213
+ elif report.majority and report.majority[0].result.status is LookupStatus.NO_ANSWER:
214
+ what = f"{name} has no {rtype} records"
215
+ else:
216
+ what = "the same records"
217
+ return Diagnosis(
218
+ title=f"Fully propagated: all {responded} resolvers agree",
219
+ explanation=f"Every resolver that answered says {what}. If you changed this "
220
+ "record, the change has reached all of them (or the old answer had expired "
221
+ "everywhere already).",
222
+ suggestion="If someone still sees the old answer, their own computer or router "
223
+ "has it cached: flushing the DNS cache or restarting the router clears it "
224
+ "(`dnskit local` shows the flush command).",
225
+ )
226
+
227
+ stale = [a.ttl for a in report.differing if a.ttl is not None]
228
+ wait = (
229
+ f" The others will update when their cached copies expire, within about "
230
+ f"{_duration(max(stale))} (the longest remaining TTL among them)."
231
+ if stale
232
+ else " The others will update when their cached copies expire."
233
+ )
234
+ if report.location_based:
235
+ return _location_based(report)
236
+ if not report.has_majority:
237
+ title = f"No consensus: {report.distinct_answers} different answers"
238
+ else:
239
+ title = f"Still propagating: {report.percent:.0f}% give the most common answer"
240
+ others = len(report.differing)
241
+ return Diagnosis(
242
+ title=title,
243
+ explanation=f"{len(report.majority)} of {responded} resolvers that answered give the "
244
+ f"most common answer and {others} {'gives' if others == 1 else 'give'} another."
245
+ f"{wait} The most "
246
+ "common answer isn't necessarily the new one: check it against what you set. "
247
+ "Domains on a CDN or geo-DNS give different addresses by region on purpose, so for "
248
+ "them differences are normal.",
249
+ suggestion="Wait and run this again. To speed up future changes, lower the record's "
250
+ "TTL a day before changing it.",
251
+ )
252
+
253
+
254
+ def _location_based(report: PropagationReport) -> Diagnosis:
255
+ anycast = sum(1 for a in report.responded if a.resolver.anycast)
256
+ where = ", ".join(f"{a.resolver.name} in {a.resolver.location}" for a in report.differing)
257
+ others = len(report.differing)
258
+ return Diagnosis(
259
+ title="Probably location-based DNS, not propagation",
260
+ explanation=f"All {anycast} global resolvers agree, and the {others} "
261
+ f"{'resolver that differs is' if others == 1 else 'resolvers that differ are all'} "
262
+ f"in another country ({where}). Sites on a CDN or geo-DNS give each region its "
263
+ "own nearby servers on purpose, so this is normal for them. If you didn't just "
264
+ "change this record, nothing is wrong.",
265
+ suggestion="If you did change it, check that the most common answer is the value "
266
+ "you set: if it is, the change has reached the resolvers near you. Run this again "
267
+ "later: answers that are location-based stay different, while stale ones catch up "
268
+ "when their TTL runs out.",
269
+ )
270
+
271
+
272
+ def _duration(seconds: int) -> str:
273
+ if seconds < 120:
274
+ return f"{seconds} seconds"
275
+ if seconds < 7200:
276
+ return f"{round(seconds / 60)} minutes"
277
+ return f"{round(seconds / 3600)} hours"