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,139 @@
1
+ """TCP connection tests and IPv6 health: can this computer reach what DNS points it at?"""
2
+
3
+ import ipaddress
4
+ import socket
5
+ import time
6
+ from collections.abc import Sequence
7
+ from dataclasses import dataclass
8
+ from enum import StrEnum
9
+
10
+ from dnskit.core.lookup import LookupStatus, _is_no_route, _query_one
11
+
12
+ # A dual-stack name whose AAAA lookup and IPv6 web servers are reliably up.
13
+ IPV6_TEST_HOST = "www.google.com"
14
+ IPV6_TEST_PORT = 443
15
+ # Any global IPv6 address works for finding the outgoing route; no packet is sent to it.
16
+ _IPV6_ROUTE_PROBE = ("2001:4860:4860::8888", 53)
17
+
18
+
19
+ class ConnectError(StrEnum):
20
+ REFUSED = "refused" # the host answered, but nothing accepts connections on that port
21
+ TIMEOUT = "timed out" # no reply: a firewall drops it, or the host is down
22
+ UNREACHABLE = "unreachable" # no route to the address from this computer
23
+ FAILED = "failed" # any other socket error
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class ConnectAttempt:
28
+ address: str
29
+ port: int
30
+ latency_ms: float | None # None when it failed
31
+ error: ConnectError | None = None
32
+ message: str = "" # the OS's error text, for failures
33
+
34
+ @property
35
+ def ok(self) -> bool:
36
+ return self.error is None
37
+
38
+ @property
39
+ def version(self) -> int:
40
+ return ipaddress.ip_address(self.address).version
41
+
42
+
43
+ def tcp_connect(address: str, port: int, timeout: float) -> ConnectAttempt:
44
+ """Open (and close) a TCP connection to `address`:`port`. Never raises."""
45
+ family = socket.AF_INET6 if ":" in address else socket.AF_INET
46
+ start = time.perf_counter()
47
+ try:
48
+ with socket.socket(family, socket.SOCK_STREAM) as sock:
49
+ sock.settimeout(timeout)
50
+ sock.connect((address, port))
51
+ except TimeoutError:
52
+ return ConnectAttempt(address, port, None, ConnectError.TIMEOUT, "no reply")
53
+ except ConnectionRefusedError as exc:
54
+ return ConnectAttempt(address, port, None, ConnectError.REFUSED, _message(exc))
55
+ except OSError as exc:
56
+ error = ConnectError.UNREACHABLE if _is_no_route(exc) else ConnectError.FAILED
57
+ return ConnectAttempt(address, port, None, error, _message(exc))
58
+ return ConnectAttempt(address, port, (time.perf_counter() - start) * 1000)
59
+
60
+
61
+ def _message(exc: OSError) -> str:
62
+ return exc.strerror or str(exc) or type(exc).__name__
63
+
64
+
65
+ # --- IPv6 health --------------------------------------------------------------------------
66
+
67
+
68
+ class IPv6State(StrEnum):
69
+ WORKING = "working"
70
+ NOT_AVAILABLE = "not available" # no IPv6 address/route: fine, IPv4 is used
71
+ BROKEN = "broken" # IPv6 route and AAAA answers, but connections fail
72
+ UNKNOWN = "unknown" # couldn't test: the AAAA lookup failed
73
+
74
+
75
+ @dataclass(frozen=True)
76
+ class IPv6Check:
77
+ state: IPv6State
78
+ local_address: str | None # this computer's IPv6 address used for the internet
79
+ host: str # the name tested
80
+ attempt: ConnectAttempt | None # the IPv6 connection test, when one was made
81
+ summary: str
82
+
83
+
84
+ def ipv6_source_address() -> str | None:
85
+ """This computer's global IPv6 address towards the internet, or None without one.
86
+
87
+ Connecting a UDP socket only picks a route and a source address; nothing is sent.
88
+ """
89
+ try:
90
+ with socket.socket(socket.AF_INET6, socket.SOCK_DGRAM) as sock:
91
+ sock.connect(_IPV6_ROUTE_PROBE)
92
+ address = sock.getsockname()[0].split("%", 1)[0]
93
+ except OSError:
94
+ return None
95
+ try:
96
+ return address if ipaddress.ip_address(address).is_global else None
97
+ except ValueError:
98
+ return None
99
+
100
+
101
+ def check_ipv6(nameservers: Sequence[str], timeout: float) -> IPv6Check:
102
+ """Test IPv6: an IPv6 route, an AAAA lookup through `nameservers`, then a connection."""
103
+ host = IPV6_TEST_HOST
104
+ local = ipv6_source_address()
105
+ if local is None:
106
+ return IPv6Check(
107
+ IPv6State.NOT_AVAILABLE,
108
+ None,
109
+ host,
110
+ None,
111
+ "not available (no IPv6 address); IPv4 is used, which is fine",
112
+ )
113
+ if not nameservers:
114
+ return IPv6Check(IPv6State.UNKNOWN, local, host, None, "couldn't test (no DNS server)")
115
+ result = _query_one(host, "AAAA", nameservers, timeout)
116
+ if result.status is not LookupStatus.OK or not result.records:
117
+ return IPv6Check(
118
+ IPv6State.UNKNOWN,
119
+ local,
120
+ host,
121
+ None,
122
+ f"couldn't test (the AAAA lookup for {host} failed: {result.status})",
123
+ )
124
+ attempt = tcp_connect(result.records[0].value, IPV6_TEST_PORT, timeout)
125
+ if attempt.ok:
126
+ return IPv6Check(
127
+ IPv6State.WORKING,
128
+ local,
129
+ host,
130
+ attempt,
131
+ f"working ({host} over IPv6 in {attempt.latency_ms:.0f} ms)",
132
+ )
133
+ return IPv6Check(
134
+ IPv6State.BROKEN,
135
+ local,
136
+ host,
137
+ attempt,
138
+ f"broken: {host} has IPv6 addresses, but connecting to {attempt.address} {attempt.error}",
139
+ )
@@ -0,0 +1,100 @@
1
+ """Plain-English explanations and next steps for lookup failures.
2
+
3
+ Returned as data so every front end (CLI now, web UI later) can present them its own way.
4
+ """
5
+
6
+ import ipaddress
7
+ from dataclasses import dataclass
8
+
9
+ from dnskit.core.lookup import LookupStatus
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class Diagnosis:
14
+ title: str
15
+ explanation: str
16
+ suggestion: str
17
+
18
+
19
+ def explain(
20
+ status: LookupStatus, name: str, rtype: str, timeout: float | None = None
21
+ ) -> Diagnosis | None:
22
+ """Explain a lookup status for `name`/`rtype`. Returns None for a successful lookup."""
23
+ match status:
24
+ case LookupStatus.OK:
25
+ return None
26
+ case LookupStatus.NXDOMAIN:
27
+ return Diagnosis(
28
+ title="Domain doesn't exist",
29
+ explanation=f"{name} isn't registered in DNS — the nameserver answered that "
30
+ "no such name exists (NXDOMAIN).",
31
+ suggestion="Check the spelling for typos. If this domain used to work, its "
32
+ "registration may have expired — check it with a WHOIS lookup.",
33
+ )
34
+ case LookupStatus.NO_ANSWER:
35
+ return Diagnosis(
36
+ title=f"No {rtype} records",
37
+ explanation=f"{name} exists, but has no {rtype} records.",
38
+ suggestion="This is often normal (for example, many domains have no AAAA "
39
+ f"records). Run `dnskit lookup {name}` to see which record types it does have.",
40
+ )
41
+ case LookupStatus.SERVFAIL:
42
+ return Diagnosis(
43
+ title="Nameserver failure (SERVFAIL)",
44
+ explanation=f"The resolver tried to look up {name} but failed. This usually "
45
+ "points to a problem with the domain's own nameservers or a broken DNSSEC "
46
+ "signature, not with your connection.",
47
+ suggestion="Try a different public resolver (such as 1.1.1.1 or 8.8.8.8). If "
48
+ "they fail too, the domain's DNS hosting is broken — contact the domain owner "
49
+ "or their DNS provider.",
50
+ )
51
+ case LookupStatus.TIMEOUT:
52
+ within = f" within {timeout:g} seconds" if timeout is not None else " in time"
53
+ return Diagnosis(
54
+ title="Query timed out",
55
+ explanation=f"No nameserver replied{within}.",
56
+ suggestion="Check your internet connection, then try a different resolver "
57
+ "(such as 1.1.1.1) or a longer timeout. A firewall or VPN blocking DNS "
58
+ "(port 53) can also cause this.",
59
+ )
60
+ case LookupStatus.NO_NETWORK:
61
+ return Diagnosis(
62
+ title="No network connection",
63
+ explanation="Couldn't reach any nameserver — this computer appears to be "
64
+ "offline or has no route to the internet.",
65
+ suggestion="Check your Wi-Fi, Ethernet or VPN connection and try again. "
66
+ "`dnskit resolvers` shows which nameservers are reachable.",
67
+ )
68
+ case LookupStatus.NO_NAMESERVERS:
69
+ return Diagnosis(
70
+ title="All nameservers refused or failed",
71
+ explanation=f"Every nameserver rejected the query for {name} or returned an error.",
72
+ suggestion="The resolver may not accept queries from your network. Try a "
73
+ "public resolver such as 1.1.1.1, or run `dnskit resolvers` to check which "
74
+ "nameservers respond.",
75
+ )
76
+
77
+
78
+ def explain_reverse(
79
+ status: LookupStatus, ip: str, timeout: float | None = None
80
+ ) -> Diagnosis | None:
81
+ """Explain a PTR lookup status for `ip`, with advice specific to reverse DNS."""
82
+ if status in (LookupStatus.NXDOMAIN, LookupStatus.NO_ANSWER):
83
+ if ipaddress.ip_address(ip).is_private:
84
+ suggestion = (
85
+ f"{ip} is a private or reserved address, so public resolvers can't know its "
86
+ "name. Ask your local network's DNS server (usually your router) by passing its "
87
+ "IP as the resolver."
88
+ )
89
+ else:
90
+ suggestion = (
91
+ "Reverse DNS is set by whoever owns the IP address (usually the ISP or hosting "
92
+ "provider). Ask them to add a PTR record if you need one — for example, mail "
93
+ "servers often require it."
94
+ )
95
+ return Diagnosis(
96
+ title="No reverse DNS name",
97
+ explanation=f"{ip} has no PTR record, so there's no hostname registered for it.",
98
+ suggestion=suggestion,
99
+ )
100
+ return explain(status, ip, "PTR", timeout)