Debian Codegraph @

src/govee_local_api/network.py

raw
1 from __future__ import annotations
2
3 import ipaddress
4
5
6 def _normalize_to_list(value: str | list[str]) -> list[str]:
7 """Convert a single string or iterable of strings to a normalized list."""
8 if isinstance(value, str):
9 return [value]
10 return list(value)
11
12
13 def _parse_address_and_mask(
14 address_str: str,
15 ) -> tuple[str, ipaddress.IPv4Network | None]:
16 """Parse an address string that may contain a network mask.
17
18 Supported formats:
19 - "192.168.1.100/24" (CIDR notation)
20 - "192.168.1.100/255.255.255.0" (dotted netmask)
21 - "192.168.1.100" (no mask, returns None for network)
22 - "0.0.0.0" (wildcard, returns None for network)
23
24 Returns:
25 Tuple of (ip_address, network_or_none).
26
27 Raises:
28 ValueError: If a mask is present but cannot be parsed.
29 """
30 if "/" not in address_str:
31 return (address_str, None)
32
33 ip_part, mask_part = address_str.split("/", 1)
34
35 if ip_part == "0.0.0.0":
36 return (ip_part, None)
37
38 try:
39 network = ipaddress.ip_network(f"{ip_part}/{mask_part}", strict=False)
40 except (ipaddress.AddressValueError, ValueError) as exc:
41 # A mask was explicitly given; silently dropping it would degrade
42 # transport selection to heuristics without a trace, defeating the
43 # feature the caller asked for. Fail loudly, matching how invalid
44 # IPs are rejected in the controller constructor.
45 raise ValueError(
46 f"Invalid network mask in listening address {address_str!r}"
47 ) from exc
48 if isinstance(network, ipaddress.IPv4Network):
49 return (ip_part, network)
50 return (ip_part, None)
51
52
53 def _parse_listening_addresses(
54 addresses: str | list[str],
55 ) -> tuple[list[str], list[ipaddress.IPv4Network | None]]:
56 """Parse listening addresses, extracting embedded network masks.
57
58 Returns:
59 Tuple of (list of IP addresses, list of networks or None per address).
60 """
61 raw_list = _normalize_to_list(addresses)
62 ips: list[str] = []
63 networks: list[ipaddress.IPv4Network | None] = []
64 for entry in raw_list:
65 ip, network = _parse_address_and_mask(entry)
66 ips.append(ip)
67 networks.append(network)
68 return (ips, networks)
69
70
71 _RFC1918_172_16 = ipaddress.IPv4Network("172.16.0.0/12")
72
73
74 def _is_ip_in_same_network_heuristic(
75 ip1: ipaddress.IPv4Address, ip2: ipaddress.IPv4Address
76 ) -> bool:
77 """
78 Best-effort check if two IPs are likely on the same network.
79 Uses common subnet assumptions for private networks.
80 """
81 # Check if both are in the same /24 network (common case)
82 if ip1.packed[:3] == ip2.packed[:3]:
83 return True
84
85 if not (ip1.is_private and ip2.is_private):
86 return False
87
88 # 192.168.0.0/16
89 if ip1.packed[:2] == b"\xc0\xa8" and ip2.packed[:2] == b"\xc0\xa8":
90 return True
91
92 # 10.0.0.0/8
93 if ip1.packed[0] == 10 and ip2.packed[0] == 10:
94 return True
95
96 # 172.16.0.0/12 — RFC1918 mid-range; same /12 means they're peers.
97 if ip1 in _RFC1918_172_16 and ip2 in _RFC1918_172_16:
98 return True
99
100 return False