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.
dnskit/core/lookup.py ADDED
@@ -0,0 +1,218 @@
1
+ """Record lookups across one or more record types."""
2
+
3
+ import errno
4
+ import re
5
+ import time
6
+ from collections.abc import Sequence
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from dataclasses import dataclass
9
+ from enum import StrEnum
10
+ from typing import Any
11
+
12
+ import dns.exception
13
+ import dns.rdatatype
14
+ import dns.resolver
15
+
16
+ from dnskit.core.nameservers import ResolverChoice, choose_nameserver, system_nameservers
17
+
18
+ DEFAULT_RTYPES: tuple[str, ...] = ("A", "AAAA", "MX", "CNAME", "NS", "TXT")
19
+ # Record types whose values are character strings ("part one" "part two").
20
+ TEXT_RTYPES = frozenset({"TXT", "SPF"})
21
+
22
+ _TXT_STRING = re.compile(r'"((?:[^"\\]|\\.)*)"')
23
+ _TXT_ESCAPE = re.compile(r"\\(\d{3}|.)")
24
+
25
+ # errno values meaning "this machine has no route to the network". Windows socket errors
26
+ # carry WSA codes (10050 WSAENETDOWN, 10051 WSAENETUNREACH, 10065 WSAEHOSTUNREACH).
27
+ _NO_ROUTE_ERRNOS = {errno.ENETDOWN, errno.ENETUNREACH, errno.EHOSTUNREACH, 10050, 10051, 10065}
28
+
29
+
30
+ class LookupStatus(StrEnum):
31
+ OK = "ok"
32
+ NXDOMAIN = "nxdomain"
33
+ NO_ANSWER = "no_answer"
34
+ SERVFAIL = "servfail"
35
+ TIMEOUT = "timeout"
36
+ NO_NETWORK = "no_network"
37
+ NO_NAMESERVERS = "no_nameservers" # every nameserver refused or errored otherwise
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Record:
42
+ value: str
43
+ ttl: int
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class LookupResult:
48
+ rtype: str
49
+ status: LookupStatus
50
+ records: tuple[Record, ...] = ()
51
+ elapsed_ms: float = 0.0
52
+
53
+
54
+ @dataclass(frozen=True)
55
+ class LookupReport:
56
+ name: str
57
+ nameserver: str
58
+ nameserver_source: str
59
+ results: tuple[LookupResult, ...]
60
+ elapsed_ms: float
61
+ # How the system nameserver was picked (probe results, cache use). None with --server.
62
+ resolver_choice: ResolverChoice | None = None
63
+
64
+
65
+ def lookup(
66
+ name: str,
67
+ rtypes: Sequence[str] = DEFAULT_RTYPES,
68
+ nameserver: str | None = None,
69
+ timeout: float = 5.0,
70
+ refresh: bool = False,
71
+ ) -> LookupReport:
72
+ """Query `name` for each of `rtypes` in parallel against one chosen resolver.
73
+
74
+ Without `nameserver`, the fastest system nameserver is used (a recent choice is reused
75
+ from the cache unless `refresh`), with the others as fallbacks. An explicit `nameserver`
76
+ always wins and never touches the cache. Expected DNS failures are reported per type via
77
+ `LookupResult.status`; an unknown record type raises ValueError.
78
+ """
79
+ rtypes = [_validate_rtype(rtype) for rtype in rtypes]
80
+
81
+ start = time.perf_counter()
82
+ selection = _choose_nameservers(nameserver, refresh)
83
+ nameservers = selection.nameservers
84
+
85
+ with ThreadPoolExecutor(max_workers=len(rtypes)) as pool:
86
+ results = tuple(
87
+ pool.map(lambda rtype: _query_one(name, rtype, nameservers, timeout), rtypes)
88
+ )
89
+
90
+ return LookupReport(
91
+ name=name,
92
+ nameserver=nameservers[0],
93
+ nameserver_source=selection.source,
94
+ results=results,
95
+ elapsed_ms=(time.perf_counter() - start) * 1000,
96
+ resolver_choice=selection.choice,
97
+ )
98
+
99
+
100
+ def _validate_rtype(rtype: str) -> str:
101
+ """Return `rtype` upper-cased, or raise ValueError if dnspython doesn't know it."""
102
+ rtype = rtype.upper()
103
+ try:
104
+ dns.rdatatype.from_text(rtype)
105
+ except dns.rdatatype.UnknownRdatatype as exc:
106
+ raise ValueError(
107
+ f"Unknown record type: {rtype}. Common types are {', '.join(DEFAULT_RTYPES)}."
108
+ ) from exc
109
+ return rtype
110
+
111
+
112
+ @dataclass(frozen=True)
113
+ class _Selection:
114
+ nameservers: list[str] # in the order to try them
115
+ source: str # how the first one was picked, for display
116
+ choice: ResolverChoice | None # None when an explicit nameserver was given
117
+
118
+
119
+ def _choose_nameservers(nameserver: str | None, refresh: bool = False) -> _Selection:
120
+ if nameserver is not None:
121
+ return _Selection([nameserver], "--server", None)
122
+
123
+ candidates = system_nameservers()
124
+ if not candidates:
125
+ raise ValueError(
126
+ "No nameservers are configured on this computer — it may be offline. Connect to "
127
+ "a network, or pass a nameserver explicitly with --server."
128
+ )
129
+
130
+ choice = choose_nameserver(candidates, use_cache=not refresh)
131
+ if choice.nameserver is None:
132
+ return _Selection(candidates, "system order (no nameserver answered probe)", choice)
133
+
134
+ source = f"auto: fastest of {len(candidates)} system nameservers"
135
+ if choice.latency_ms is not None:
136
+ source += f", {choice.latency_ms:.0f} ms"
137
+ return _Selection(choice.ordered(), source, choice)
138
+
139
+
140
+ def _make_resolver(nameservers: Sequence[str], timeout: float) -> dns.resolver.Resolver:
141
+ resolver = dns.resolver.Resolver(configure=False)
142
+ resolver.nameservers = list(nameservers)
143
+ resolver.lifetime = timeout
144
+ return resolver
145
+
146
+
147
+ def _query_one(
148
+ name: str,
149
+ rtype: str,
150
+ nameservers: Sequence[str],
151
+ timeout: float,
152
+ retry_after: float | None = None,
153
+ ) -> LookupResult:
154
+ """One lookup, within `timeout` in total.
155
+
156
+ dnspython re-sends an unanswered query only after 2 s, so with a shorter `timeout` one
157
+ lost packet means a timeout. `retry_after` re-sends sooner, to ride out packet loss.
158
+ """
159
+ resolver = _make_resolver(nameservers, timeout)
160
+ if retry_after is not None:
161
+ resolver.timeout = retry_after
162
+ start = time.perf_counter()
163
+
164
+ def failed(status: LookupStatus) -> LookupResult:
165
+ return LookupResult(rtype, status, elapsed_ms=(time.perf_counter() - start) * 1000)
166
+
167
+ try:
168
+ answer = resolver.resolve(name, rtype)
169
+ except dns.resolver.NXDOMAIN:
170
+ return failed(LookupStatus.NXDOMAIN)
171
+ except dns.resolver.NoAnswer:
172
+ return failed(LookupStatus.NO_ANSWER)
173
+ except dns.exception.Timeout:
174
+ return failed(LookupStatus.TIMEOUT)
175
+ except dns.resolver.NoNameservers as exc:
176
+ return failed(_classify_nameserver_errors(exc.kwargs.get("errors") or []))
177
+ except OSError as exc:
178
+ no_route = _is_no_route(exc)
179
+ return failed(LookupStatus.NO_NETWORK if no_route else LookupStatus.NO_NAMESERVERS)
180
+
181
+ ttl = answer.rrset.ttl if answer.rrset is not None else 0
182
+ records = tuple(Record(rdata.to_text(), ttl) for rdata in answer)
183
+ return LookupResult(
184
+ rtype, LookupStatus.OK, records, elapsed_ms=(time.perf_counter() - start) * 1000
185
+ )
186
+
187
+
188
+ def txt_text(value: str) -> str:
189
+ """A TXT record's text as dnspython prints it, unquoted: the strings joined, escapes undone.
190
+
191
+ `"v=spf1 include:a" " -all"` becomes `v=spf1 include:a -all`. A value without quotes is
192
+ returned unchanged.
193
+ """
194
+ parts = _TXT_STRING.findall(value)
195
+ if not parts:
196
+ return value
197
+ unescape = _TXT_ESCAPE.sub
198
+ return "".join(
199
+ unescape(lambda m: chr(int(m[1])) if m[1].isdigit() else m[1], part) for part in parts
200
+ )
201
+
202
+
203
+ def _classify_nameserver_errors(errors: Sequence[tuple[Any, ...]]) -> LookupStatus:
204
+ """Work out why every nameserver failed, from dnspython's NoNameservers error list.
205
+
206
+ Each entry is (nameserver, tcp, port, error, response); `error` is an exception, or the
207
+ rcode text (e.g. "SERVFAIL") when the server answered with an error code.
208
+ """
209
+ reasons = [entry[3] for entry in errors]
210
+ if any(str(reason) == "SERVFAIL" for reason in reasons):
211
+ return LookupStatus.SERVFAIL
212
+ if reasons and all(isinstance(r, OSError) and _is_no_route(r) for r in reasons):
213
+ return LookupStatus.NO_NETWORK
214
+ return LookupStatus.NO_NAMESERVERS
215
+
216
+
217
+ def _is_no_route(exc: OSError) -> bool:
218
+ return exc.errno in _NO_ROUTE_ERRNOS or getattr(exc, "winerror", None) in _NO_ROUTE_ERRNOS