bind.py python
47 lines 1.4 KB
Raw
sha256:a78e7e5a8740e03315f325d19edeb3aa1b306b3337d04abbaa9a9e0f3bbeb7a1 docs: MuseHub-first before ISR #74 — staging solidify NEXT Human 1 day ago
1 """Loopback bind policy for ``overseer app`` (§Q0.5)."""
2
3 from __future__ import annotations
4
5 import ipaddress
6 import socket
7
8
9 DEFAULT_PORT = 8765
10 ALLOWED_BIND_LITERALS = frozenset({"127.0.0.1", "localhost", "::1"})
11
12
13 def normalize_bind_address(bind: str) -> str:
14 """Normalize an allowed bind literal to the address passed to ``HTTPServer``."""
15 text = bind.strip()
16 if text == "localhost":
17 return "127.0.0.1"
18 return text
19
20
21 def validate_bind_address(bind: str) -> str | None:
22 """Return normalized bind address, or ``None`` when the literal is refused."""
23 text = bind.strip()
24 if text not in ALLOWED_BIND_LITERALS:
25 return None
26 return normalize_bind_address(text)
27
28
29 def is_loopback_peer(host: str) -> bool:
30 """Return whether ``host`` is a loopback peer address."""
31 try:
32 return ipaddress.ip_address(host).is_loopback
33 except ValueError:
34 return False
35
36
37 def port_is_available(bind: str, port: int) -> bool:
38 """Return whether ``port`` can be bound on ``bind``."""
39 family = socket.AF_INET6 if bind == "::1" else socket.AF_INET
40 probe_host = bind if bind != "127.0.0.1" else "127.0.0.1"
41 with socket.socket(family, socket.SOCK_STREAM) as sock:
42 sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
43 try:
44 sock.bind((probe_host, port))
45 except OSError:
46 return False
47 return True
File History 1 commit
sha256:a78e7e5a8740e03315f325d19edeb3aa1b306b3337d04abbaa9a9e0f3bbeb7a1 docs: MuseHub-first before ISR #74 — staging solidify NEXT Human 1 day ago