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,521 @@
1
+ """Network adapters and the DNS servers configured on each, read from the operating system.
2
+
3
+ Each OS has its own reader; they all return an `AdapterScan`. The parsing of command output
4
+ (macOS, Linux) is split into pure functions so it can be tested with sample text.
5
+ """
6
+
7
+ import dataclasses
8
+ import ipaddress
9
+ import re
10
+ import subprocess
11
+ import sys
12
+ from collections.abc import Callable, Container, Iterable
13
+ from dataclasses import dataclass
14
+ from pathlib import Path
15
+
16
+ # Windows lists these deprecated site-local addresses on IPv6 interfaces that have no DNS
17
+ # server configured. They are placeholders, never real servers, so they are dropped.
18
+ PLACEHOLDER_DNS = frozenset({"fec0:0:0:ffff::1", "fec0:0:0:ffff::2", "fec0:0:0:ffff::3"})
19
+
20
+ _COMMAND_TIMEOUT_S = 5.0
21
+
22
+ # Words in an adapter's name or description that mark it as a VPN.
23
+ _VPN_WORDS = re.compile(
24
+ r"vpn|\btap\b|tap-windows|wireguard|wintun|tailscale|zerotier|nordlynx|anyconnect"
25
+ r"|globalprotect|pangp|fortinet|forticlient|juniper|pulse secure|cisco.*secure client",
26
+ re.IGNORECASE,
27
+ )
28
+ _TUNNEL_NAMES = re.compile(r"^(u?tun|wg|ppp|ipsec)\d+$")
29
+
30
+
31
+ @dataclass(frozen=True)
32
+ class Adapter:
33
+ id: str # OS identifier: the interface GUID on Windows, the interface name elsewhere
34
+ name: str # friendly name, e.g. "Wi-Fi", "Ethernet 2", "en0"
35
+ description: str # driver or hardware description; "" when the OS doesn't give one
36
+ connected: bool
37
+ dns_servers: tuple[str, ...] # in the adapter's order
38
+ # A bridge member (e.g. Wi-Fi in a network bridge) carries traffic for another adapter
39
+ # and has no IP or DNS settings of its own: this is that adapter's name.
40
+ bridged_into: str | None = None
41
+
42
+ @property
43
+ def vpn(self) -> bool:
44
+ return is_vpn(self)
45
+
46
+
47
+ @dataclass(frozen=True)
48
+ class RegistryEntry:
49
+ """Windows only: a registry value that lists a nameserver."""
50
+
51
+ interface_id: str # the interface GUID, as in Adapter.id
52
+ value: str # "NameServer" (set by hand) or "DhcpNameServer" (from DHCP)
53
+ nameservers: tuple[str, ...]
54
+
55
+
56
+ @dataclass(frozen=True)
57
+ class AdapterScan:
58
+ adapters: tuple[Adapter, ...]
59
+ # Whether the OS reported each adapter's DNS servers. Without that (Linux without
60
+ # systemd-resolved), nameservers can't be matched to adapters.
61
+ dns_per_adapter: bool
62
+ registry: tuple[RegistryEntry, ...] = () # Windows only
63
+ error: str | None = None # why adapters couldn't be read, if they couldn't
64
+
65
+ @property
66
+ def connected(self) -> tuple[Adapter, ...]:
67
+ """Connected adapters with their own network settings (not bridge members)."""
68
+ return tuple(a for a in self.adapters if a.connected and a.bridged_into is None)
69
+
70
+ @property
71
+ def connected_vpns(self) -> tuple[Adapter, ...]:
72
+ return tuple(a for a in self.connected if a.vpn)
73
+
74
+ def connected_dns(self) -> set[str]:
75
+ return {normalize_ip(ns) for a in self.connected for ns in a.dns_servers}
76
+
77
+ def adapters_listing(self, nameserver: str) -> tuple[Adapter, ...]:
78
+ """Adapters that list `nameserver`, connected ones first."""
79
+ key = normalize_ip(nameserver)
80
+ owners = [a for a in self.adapters if key in {normalize_ip(ns) for ns in a.dns_servers}]
81
+ return tuple(sorted(owners, key=lambda a: not a.connected))
82
+
83
+ def registry_listing(self, nameserver: str) -> tuple[RegistryEntry, ...]:
84
+ key = normalize_ip(nameserver)
85
+ return tuple(e for e in self.registry if key in {normalize_ip(ns) for ns in e.nameservers})
86
+
87
+
88
+ def normalize_ip(address: str) -> str:
89
+ """Canonical text for an IP address (zone id dropped), so equal addresses compare equal."""
90
+ try:
91
+ return ipaddress.ip_address(address.split("%", 1)[0]).compressed
92
+ except ValueError:
93
+ return address
94
+
95
+
96
+ def is_vpn(adapter: Adapter) -> bool:
97
+ """Whether the adapter looks like a VPN, judging by its name and description.
98
+
99
+ Generic tunnel interfaces (tun0, utun3, wg0, ppp0) only count when they have DNS
100
+ servers: macOS always has a few utun interfaces for its own services.
101
+ """
102
+ text = f"{adapter.name} {adapter.description}"
103
+ if _VPN_WORDS.search(text):
104
+ return True
105
+ return bool(adapter.dns_servers) and bool(_TUNNEL_NAMES.match(adapter.name))
106
+
107
+
108
+ def is_loopback(address: str) -> bool:
109
+ """True for a local DNS stub such as 127.0.0.53 (systemd-resolved) or ::1."""
110
+ try:
111
+ return ipaddress.ip_address(address.split("%", 1)[0]).is_loopback
112
+ except ValueError:
113
+ return False
114
+
115
+
116
+ def scan_adapters() -> AdapterScan:
117
+ """Read this computer's network adapters and their DNS servers. Never raises."""
118
+ try:
119
+ if sys.platform == "win32":
120
+ return _windows_scan()
121
+ if sys.platform == "darwin":
122
+ return _macos_scan()
123
+ if sys.platform.startswith("linux"):
124
+ return _linux_scan()
125
+ except Exception as exc: # an OS quirk must not break lookups
126
+ return AdapterScan((), dns_per_adapter=False, error=f"{type(exc).__name__}: {exc}")
127
+ return AdapterScan((), dns_per_adapter=False, error=f"not supported on {sys.platform}")
128
+
129
+
130
+ def _clean_dns(servers: list[str]) -> tuple[str, ...]:
131
+ """Drop placeholders and duplicates, keeping order."""
132
+ seen: dict[str, None] = {}
133
+ for server in servers:
134
+ if normalize_ip(server) not in PLACEHOLDER_DNS:
135
+ seen.setdefault(server, None)
136
+ return tuple(seen)
137
+
138
+
139
+ def _run(args: list[str]) -> str | None:
140
+ """Run a command and return its stdout, or None if it's missing or fails."""
141
+ try:
142
+ completed = subprocess.run(
143
+ args, capture_output=True, text=True, timeout=_COMMAND_TIMEOUT_S, check=False
144
+ )
145
+ except (OSError, subprocess.SubprocessError):
146
+ return None
147
+ return completed.stdout if completed.returncode == 0 else None
148
+
149
+
150
+ # --- Windows ------------------------------------------------------------------------------
151
+
152
+ _IF_TYPE_SOFTWARE_LOOPBACK = 24
153
+ _IF_OPER_STATUS_UP = 1
154
+ _INTERFACES_KEY = r"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces"
155
+
156
+
157
+ def _windows_scan() -> AdapterScan:
158
+ adapters = _windows_adapters()
159
+ try:
160
+ members = _windows_bridge_members(adapters)
161
+ except Exception: # bridge members are extra detail; never lose the adapter list over them
162
+ members = []
163
+ return AdapterScan(
164
+ tuple(adapters.values()) + tuple(members),
165
+ dns_per_adapter=True,
166
+ registry=tuple(_windows_registry()),
167
+ )
168
+
169
+
170
+ def _windows_adapters() -> dict[int, Adapter]: # pragma: no cover (Windows API; checked live)
171
+ """Adapters from GetAdaptersAddresses: the same data as Get-DnsClientServerAddress.
172
+
173
+ Keyed by interface index. Only adapters with TCP/IP bound are listed, so bridge members
174
+ (which have none) come from `_windows_bridge_members`.
175
+ """
176
+ import ctypes
177
+
178
+ class _Adapter(ctypes.Structure): # IP_ADAPTER_ADDRESSES_LH, up to OperStatus
179
+ pass
180
+
181
+ class _SocketAddress(ctypes.Structure):
182
+ _fields_ = [("lpSockaddr", ctypes.c_void_p), ("iSockaddrLength", ctypes.c_int)]
183
+
184
+ class _DnsServer(ctypes.Structure): # IP_ADAPTER_DNS_SERVER_ADDRESS_XP
185
+ pass
186
+
187
+ _DnsServer._fields_ = [
188
+ ("Length", ctypes.c_ulong),
189
+ ("Reserved", ctypes.c_ulong),
190
+ ("Next", ctypes.POINTER(_DnsServer)),
191
+ ("Address", _SocketAddress),
192
+ ]
193
+ _Adapter._fields_ = [
194
+ ("Length", ctypes.c_ulong),
195
+ ("IfIndex", ctypes.c_ulong),
196
+ ("Next", ctypes.POINTER(_Adapter)),
197
+ ("AdapterName", ctypes.c_char_p),
198
+ ("FirstUnicastAddress", ctypes.c_void_p),
199
+ ("FirstAnycastAddress", ctypes.c_void_p),
200
+ ("FirstMulticastAddress", ctypes.c_void_p),
201
+ ("FirstDnsServerAddress", ctypes.POINTER(_DnsServer)),
202
+ ("DnsSuffix", ctypes.c_wchar_p),
203
+ ("Description", ctypes.c_wchar_p),
204
+ ("FriendlyName", ctypes.c_wchar_p),
205
+ ("PhysicalAddress", ctypes.c_ubyte * 8),
206
+ ("PhysicalAddressLength", ctypes.c_ulong),
207
+ ("Flags", ctypes.c_ulong),
208
+ ("Mtu", ctypes.c_ulong),
209
+ ("IfType", ctypes.c_ulong),
210
+ ("OperStatus", ctypes.c_int),
211
+ ]
212
+
213
+ get_adapters = ctypes.windll.iphlpapi.GetAdaptersAddresses # type: ignore[attr-defined,unused-ignore]
214
+ af_unspec, skip_unicast_anycast_multicast = 0, 0x7
215
+ error_buffer_overflow = 111
216
+ size = ctypes.c_ulong(16 * 1024)
217
+ for _ in range(3): # the adapter list can grow between calls
218
+ buffer = ctypes.create_string_buffer(size.value)
219
+ status = get_adapters(
220
+ af_unspec, skip_unicast_anycast_multicast, None, buffer, ctypes.byref(size)
221
+ )
222
+ if status != error_buffer_overflow:
223
+ break
224
+ if status != 0:
225
+ raise OSError(status, "GetAdaptersAddresses failed")
226
+
227
+ adapters = {}
228
+ node = ctypes.cast(buffer, ctypes.POINTER(_Adapter))
229
+ while node:
230
+ entry = node.contents
231
+ if entry.IfType != _IF_TYPE_SOFTWARE_LOOPBACK:
232
+ servers = []
233
+ dns = entry.FirstDnsServerAddress
234
+ while dns:
235
+ address = dns.contents.Address
236
+ raw = ctypes.string_at(address.lpSockaddr, address.iSockaddrLength)
237
+ if (ip := _sockaddr_ip(raw)) is not None:
238
+ servers.append(ip)
239
+ dns = dns.contents.Next
240
+ adapters[entry.IfIndex] = Adapter(
241
+ id=(entry.AdapterName or b"").decode("ascii", "replace").lower(),
242
+ name=entry.FriendlyName or "",
243
+ description=entry.Description or "",
244
+ connected=entry.OperStatus == _IF_OPER_STATUS_UP,
245
+ dns_servers=_clean_dns(servers),
246
+ )
247
+ node = entry.Next
248
+ return adapters
249
+
250
+
251
+ def _windows_bridge_members(
252
+ adapters: dict[int, Adapter],
253
+ ) -> list[Adapter]: # pragma: no cover (Windows API; checked live)
254
+ """Adapters bridged into one of `adapters`, from the interface stack (GetIfStackTable).
255
+
256
+ Between an adapter and its members the stack holds filter drivers (e.g. the WFP filter),
257
+ which GetIfTable2 flags, and unnamed internal layers; both are skipped to reach the
258
+ member itself.
259
+ """
260
+ import ctypes
261
+ import uuid
262
+
263
+ class _Row(ctypes.Structure): # MIB_IF_ROW2
264
+ _fields_ = [
265
+ ("InterfaceLuid", ctypes.c_uint64),
266
+ ("InterfaceIndex", ctypes.c_ulong),
267
+ ("InterfaceGuid", ctypes.c_ubyte * 16),
268
+ ("Alias", ctypes.c_wchar * 257),
269
+ ("Description", ctypes.c_wchar * 257),
270
+ ("PhysicalAddressLength", ctypes.c_ulong),
271
+ ("PhysicalAddress", ctypes.c_ubyte * 32),
272
+ ("PermanentPhysicalAddress", ctypes.c_ubyte * 32),
273
+ ("Mtu", ctypes.c_ulong),
274
+ ("Type", ctypes.c_ulong),
275
+ ("TunnelType", ctypes.c_int),
276
+ ("MediaType", ctypes.c_int),
277
+ ("PhysicalMediumType", ctypes.c_int),
278
+ ("AccessType", ctypes.c_int),
279
+ ("DirectionType", ctypes.c_int),
280
+ ("InterfaceAndOperStatusFlags", ctypes.c_ubyte),
281
+ ("OperStatus", ctypes.c_int),
282
+ ("AdminStatus", ctypes.c_int),
283
+ ("MediaConnectState", ctypes.c_int),
284
+ ("NetworkGuid", ctypes.c_ubyte * 16),
285
+ ("ConnectionType", ctypes.c_int),
286
+ ("Counters", ctypes.c_uint64 * 20), # link speeds and traffic counters
287
+ ]
288
+
289
+ iphlpapi = ctypes.windll.iphlpapi # type: ignore[attr-defined,unused-ignore]
290
+ filter_interface = 0x2 # bit 1 of InterfaceAndOperStatusFlags
291
+
292
+ table = ctypes.c_void_p()
293
+ if iphlpapi.GetIfTable2(ctypes.byref(table)) != 0 or table.value is None:
294
+ return []
295
+ base = table.value
296
+ try:
297
+ count = ctypes.c_ulong.from_address(base).value
298
+ rows = (_Row * count).from_address(base + ctypes.alignment(_Row))
299
+ interfaces = {
300
+ row.InterfaceIndex: Adapter(
301
+ id=f"{{{uuid.UUID(bytes_le=bytes(row.InterfaceGuid))}}}",
302
+ name=row.Alias,
303
+ description=row.Description,
304
+ connected=row.OperStatus == _IF_OPER_STATUS_UP,
305
+ dns_servers=(),
306
+ )
307
+ for row in rows
308
+ if row.Alias and not row.InterfaceAndOperStatusFlags & filter_interface
309
+ }
310
+ finally:
311
+ iphlpapi.FreeMibTable(table)
312
+
313
+ if iphlpapi.GetIfStackTable(ctypes.byref(table)) != 0 or table.value is None:
314
+ return []
315
+ base = table.value
316
+ try:
317
+ count = ctypes.c_ulong.from_address(base).value
318
+ pairs = (ctypes.c_ulong * (2 * count)).from_address(base + ctypes.sizeof(ctypes.c_ulong))
319
+ stack = list(zip(pairs[0::2], pairs[1::2], strict=True)) # (higher, lower) per row
320
+ finally:
321
+ iphlpapi.FreeMibTable(table)
322
+
323
+ return [
324
+ dataclasses.replace(interfaces[member], bridged_into=adapters[parent].name)
325
+ for member, parent in bridge_members(stack, adapters, interfaces).items()
326
+ if member not in adapters
327
+ ]
328
+
329
+
330
+ def bridge_members(
331
+ stack: Iterable[tuple[int, int]], parents: Iterable[int], interfaces: Container[int]
332
+ ) -> dict[int, int]:
333
+ """Member interface -> the parent it's bridged into, from (higher, lower) stack rows.
334
+
335
+ Walks down from each parent; an index not in `interfaces` (a filter driver layer) is
336
+ passed through, and the first real interface found on each path is a member.
337
+ """
338
+ lowers: dict[int, list[int]] = {}
339
+ for higher, lower in stack:
340
+ if higher and lower: # 0 marks the top or bottom of a stack
341
+ lowers.setdefault(higher, []).append(lower)
342
+ members: dict[int, int] = {}
343
+ for parent in parents:
344
+ pending, seen = list(lowers.get(parent, ())), {parent}
345
+ while pending:
346
+ index = pending.pop(0)
347
+ if index in seen:
348
+ continue
349
+ seen.add(index)
350
+ if index in interfaces:
351
+ members.setdefault(index, parent)
352
+ else:
353
+ pending.extend(lowers.get(index, ()))
354
+ return members
355
+
356
+
357
+ def _sockaddr_ip(raw: bytes) -> str | None:
358
+ """The IP address in a raw Windows SOCKADDR (sockaddr_in or sockaddr_in6)."""
359
+ family = int.from_bytes(raw[:2], "little")
360
+ if family == 2 and len(raw) >= 8: # AF_INET: family, port, 4-byte address
361
+ return str(ipaddress.IPv4Address(raw[4:8]))
362
+ if family == 23 and len(raw) >= 24: # AF_INET6: family, port, flowinfo, 16-byte address
363
+ return str(ipaddress.IPv6Address(raw[8:24]))
364
+ return None
365
+
366
+
367
+ def _windows_registry() -> list[RegistryEntry]:
368
+ """Every interface's NameServer/DhcpNameServer value: what dnspython reads."""
369
+ if sys.platform != "win32": # also tells type checkers on other systems to skip the rest
370
+ return []
371
+ import winreg
372
+
373
+ entries = []
374
+ try:
375
+ root = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, _INTERFACES_KEY)
376
+ except OSError:
377
+ return []
378
+ with root:
379
+ index = 0
380
+ while True:
381
+ try:
382
+ interface_id = winreg.EnumKey(root, index)
383
+ except OSError:
384
+ break
385
+ index += 1
386
+ try:
387
+ key = winreg.OpenKey(root, interface_id)
388
+ except OSError:
389
+ continue
390
+ with key:
391
+ for value in ("NameServer", "DhcpNameServer"):
392
+ try:
393
+ text = winreg.QueryValueEx(key, value)[0]
394
+ except OSError:
395
+ continue
396
+ servers = parse_registry_nameservers(str(text))
397
+ if servers:
398
+ entries.append(RegistryEntry(interface_id.lower(), value, servers))
399
+ return entries
400
+
401
+
402
+ def parse_registry_nameservers(text: str) -> tuple[str, ...]:
403
+ """Registry nameserver lists are separated by commas or spaces."""
404
+ return tuple(part for part in re.split(r"[,\s]+", text) if part)
405
+
406
+
407
+ # --- macOS --------------------------------------------------------------------------------
408
+
409
+
410
+ def _macos_scan() -> AdapterScan:
411
+ ifconfig = _run(["ifconfig", "-a"])
412
+ if ifconfig is None:
413
+ return AdapterScan((), dns_per_adapter=False, error="couldn't run ifconfig")
414
+ scoped = parse_scutil_dns(_run(["scutil", "--dns"]) or "")
415
+ bridges = parse_bridge_members(ifconfig)
416
+ adapters = tuple(
417
+ Adapter(name, name, "", connected, scoped.get(name, ()), bridges.get(name))
418
+ for name, connected in parse_ifconfig(ifconfig)
419
+ )
420
+ return AdapterScan(adapters, dns_per_adapter=bool(scoped))
421
+
422
+
423
+ def parse_ifconfig(text: str) -> list[tuple[str, bool]]:
424
+ """(interface, connected) for each non-loopback interface in `ifconfig -a` output.
425
+
426
+ An interface with a `status:` line is connected when it says `active`; one without
427
+ (e.g. a VPN tunnel) is connected when its flags include both UP and RUNNING.
428
+ """
429
+ interfaces: list[tuple[str, bool]] = []
430
+ name, flags, status = None, set[str](), None
431
+
432
+ def flush() -> None:
433
+ if name is not None and "LOOPBACK" not in flags:
434
+ connected = status == "active" if status else {"UP", "RUNNING"} <= flags
435
+ interfaces.append((name, connected))
436
+
437
+ for line in text.splitlines():
438
+ if header := re.match(r"^(\S+?): flags=\w+<([^>]*)>", line):
439
+ flush()
440
+ name, flags, status = header[1], set(header[2].split(",")), None
441
+ elif match := re.match(r"^\s+status: (\S+)", line):
442
+ status = match[1]
443
+ flush()
444
+ return interfaces
445
+
446
+
447
+ def parse_bridge_members(text: str) -> dict[str, str]:
448
+ """Member interface -> bridge, from the `member:` lines of bridges in `ifconfig -a`."""
449
+ members: dict[str, str] = {}
450
+ name = None
451
+ for line in text.splitlines():
452
+ if header := re.match(r"^(\S+?): flags=", line):
453
+ name = header[1]
454
+ elif (match := re.match(r"^\s+member: (\S+)", line)) and name is not None:
455
+ members[match[1]] = name
456
+ return members
457
+
458
+
459
+ def parse_scutil_dns(text: str) -> dict[str, tuple[str, ...]]:
460
+ """Interface name -> nameservers, from the scoped section of `scutil --dns`."""
461
+ _, found, scoped = text.partition("DNS configuration (for scoped queries)")
462
+ if not found:
463
+ return {}
464
+ result: dict[str, list[str]] = {}
465
+ for block in re.split(r"\n(?=resolver #\d+)", scoped):
466
+ interface = re.search(r"if_index\s*:\s*\d+\s*\((\S+)\)", block)
467
+ servers = re.findall(r"nameserver\[\d+\]\s*:\s*(\S+)", block)
468
+ if interface and servers:
469
+ result.setdefault(interface[1], []).extend(servers)
470
+ return {name: _clean_dns(servers) for name, servers in result.items()}
471
+
472
+
473
+ # --- Linux --------------------------------------------------------------------------------
474
+
475
+
476
+ def _linux_scan(sys_net: Path = Path("/sys/class/net")) -> AdapterScan:
477
+ per_link = parse_resolvectl_dns(_run(["resolvectl", "dns"]) or "")
478
+ links = sorted(path for path in sys_net.iterdir() if path.name != "lo")
479
+ # A bridge lists its members as entries of its brif/ directory.
480
+ bridges = {
481
+ member.name: path.name
482
+ for path in links
483
+ if (path / "brif").is_dir()
484
+ for member in (path / "brif").iterdir()
485
+ }
486
+ adapters = tuple(
487
+ Adapter(
488
+ path.name,
489
+ path.name,
490
+ "",
491
+ _linux_connected(path, _read_text),
492
+ per_link.get(path.name, ()),
493
+ bridges.get(path.name),
494
+ )
495
+ for path in links
496
+ )
497
+ return AdapterScan(adapters, dns_per_adapter=bool(per_link))
498
+
499
+
500
+ def _read_text(path: Path) -> str | None:
501
+ try:
502
+ return path.read_text(encoding="utf-8").strip()
503
+ except OSError:
504
+ return None
505
+
506
+
507
+ def _linux_connected(path: Path, read: Callable[[Path], str | None]) -> bool:
508
+ """Up with a carrier. `operstate` is "unknown" for some virtual links (e.g. tun)."""
509
+ state = read(path / "operstate")
510
+ if state == "up":
511
+ return True
512
+ return state == "unknown" and read(path / "carrier") == "1"
513
+
514
+
515
+ def parse_resolvectl_dns(text: str) -> dict[str, tuple[str, ...]]:
516
+ """Link name -> nameservers, from `resolvectl dns` (lines like `Link 2 (eth0): 1.1.1.1`)."""
517
+ result = {}
518
+ for line in text.splitlines():
519
+ if match := re.match(r"^Link \d+ \(([^)]+)\):\s*(.*)$", line.strip()):
520
+ result[match[1]] = _clean_dns(match[2].split())
521
+ return result