Commit b76c2eb3 by PLN (Algolia)

devname: announce the LAN face with avahi on Linux, find the LAN address portably

lan_ip asks the kernel for the route source toward the mDNS group (then
the default route) instead of parsing ifconfig, and accepts RFC 1918
only. Announcing goes through the platform: dns-sd -P on macOS,
avahi-publish -a -R on Linux. Without an announcer (avahi missing or
avahi-daemon down) the gate stays shut with a clear reason and no ssh
probe; loopback names are untouched. The machine's own .local name is
never re-announced, and names removed from the registry are withdrawn.
parent 55b5723a
...@@ -53,6 +53,7 @@ import fcntl ...@@ -53,6 +53,7 @@ import fcntl
import hashlib import hashlib
import html import html
import http.server import http.server
import ipaddress
import json import json
import math import math
import os import os
...@@ -233,6 +234,16 @@ class Platform: ...@@ -233,6 +234,16 @@ class Platform:
def default_lan_host(self): def default_lan_host(self):
return short_hostname() return short_hostname()
def announce_argv(self, name, ip):
return None # argv of a long-lived process that announces name -> ip over mDNS
def announcer_problem(self):
"""None when this machine can announce LAN names, else why not (the LAN face then stays off)."""
return "no mDNS announcer known on this platform"
def firewall_hints(self):
return []
def short_hostname(): def short_hostname():
"""This machine's first hostname label as a DNS-safe slug (XPS24 -> xps24); avahi announces it as <it>.local.""" """This machine's first hostname label as a DNS-safe slug (XPS24 -> xps24); avahi announces it as <it>.local."""
...@@ -259,6 +270,18 @@ class MacPlatform(Platform): ...@@ -259,6 +270,18 @@ class MacPlatform(Platform):
# this setup has always used (phones' bookmarks, the issued SAN cert). Override via config.json. # this setup has always used (phones' bookmarks, the issued SAN cert). Override via config.json.
return "mac" return "mac"
def announce_argv(self, name, ip):
return [self.find_tool("dns-sd") or "dns-sd", "-P", name, "_http._tcp", ".", "443", name, ip]
def announcer_problem(self):
return None if self.find_tool("dns-sd") else "dns-sd not found"
def firewall_hints(self):
fw = "/usr/libexec/ApplicationFirewall/socketfilterfw"
caddy = os.path.realpath(CADDY) if CADDY else "$(readlink -f $(which caddy))"
return [f"if the application firewall is on, LAN devices get connection-refused until caddy is allowed: "
f"sudo {fw} --add {caddy} && sudo {fw} --unblockapp {caddy}"]
def log_dir(self): def log_dir(self):
return os.path.join(HOME, "Library", "Logs", "devname") return os.path.join(HOME, "Library", "Logs", "devname")
...@@ -348,7 +371,7 @@ class LinuxPlatform(Platform): ...@@ -348,7 +371,7 @@ class LinuxPlatform(Platform):
name = "linux" name = "linux"
supervisor = "systemd" supervisor = "systemd"
running_words = ("active", "not active") running_words = ("active", "not active")
tool_dirs = ("/usr/bin", "/usr/local/bin", "~/.local/bin", "~/go/bin") tool_dirs = ("/usr/bin", "/usr/local/bin", "~/.local/bin", "~/go/bin", "/usr/sbin")
unit = "devname.service" unit = "devname.service"
hints = { hints = {
"debian": { "debian": {
...@@ -463,6 +486,30 @@ WantedBy=default.target ...@@ -463,6 +486,30 @@ WantedBy=default.target
return "enabled (starts at boot)", "sudo systemctl disable --now caddy" return "enabled (starts at boot)", "sudo systemctl disable --now caddy"
return None return None
def announce_argv(self, name, ip):
# -a: an address record (what phones resolve); -R: no reverse PTR, since every name shares one IP
# and a second PTR claim for it would collide. Multi-label names (a.b.host.local) [inferred: works].
return [self.find_tool("avahi-publish") or "avahi-publish", "-a", "-R", name, ip]
def announcer_problem(self):
if not self.find_tool("avahi-publish"):
return "avahi-publish not found (" + self.install_hint("avahi") + ")"
if self.systemd:
rc, state = run_out(["systemctl", "is-active", "avahi-daemon.service"])
if rc is not None and state != "active":
return "avahi-daemon is not running (sudo systemctl enable --now avahi-daemon)"
return None
def firewall_hints(self):
hints = []
if self.find_tool("ufw"):
hints.append("if ufw is active, let the home LAN reach caddy and mDNS: "
"sudo ufw allow from 192.168.0.0/16 to any port 80,443 proto tcp && sudo ufw allow 5353/udp")
if self.find_tool("firewall-cmd"):
hints.append("if firewalld is running: sudo firewall-cmd --permanent --add-service=http "
"--add-service=https --add-service=mdns && sudo firewall-cmd --reload")
return hints
def linger(self): def linger(self):
"""True/False: does the user manager (and so the agent) start at boot, before any login?""" """True/False: does the user manager (and so the agent) start at boot, before any login?"""
rc, out = run_out(["loginctl", "show-user", str(os.getuid()), "--property=Linger", "--value"]) rc, out = run_out(["loginctl", "show-user", str(os.getuid()), "--property=Linger", "--value"])
...@@ -811,47 +858,85 @@ def write_gate(open_, detail): ...@@ -811,47 +858,85 @@ def write_gate(open_, detail):
os.replace(tmp, LAN_GATE) os.replace(tmp, LAN_GATE)
LAN_V4 = tuple(ipaddress.ip_network(n) for n in ("192.168.0.0/16", "10.0.0.0/8", "172.16.0.0/12"))
def route_source(dest):
"""The source address the kernel picks toward dest. A UDP connect sends no packet: it only routes."""
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.connect((dest, 5353))
return s.getsockname()[0]
def lan_ip(): def lan_ip():
"""The Mac's private-range IPv4 — the address LAN devices will connect to — or None.""" """This machine's private-range IPv4 (RFC 1918), the address LAN devices will connect to, or None.
try: Asks the kernel for the route to the mDNS group first (the interface announcements leave by), then
out = subprocess.run(["ifconfig"], capture_output=True, text=True, timeout=5).stdout the default route (TEST-NET-1, never contacted): no ifconfig/ipconfig parsing, same on macOS and Linux.
except (OSError, subprocess.TimeoutExpired): A VPN's CGNAT or public address is refused, so the LAN face never advertises a tunnel."""
return None for dest in ("224.0.0.251", "192.0.2.1"):
m = re.search(r"^\s+inet ((?:192\.168|10\.)\S+|172\.(?:1[6-9]|2\d|3[01])\.\S+) ", out, re.M) try:
return m.group(1) if m else None addr = ipaddress.ip_address(route_source(dest))
except (OSError, ValueError):
continue
if any(addr in net for net in LAN_V4):
return str(addr)
return None
def start_lan_announcer(): class Announcer:
"""Every HANDSHAKE_SECS: make domovoy prove itself, then open or close the LAN face. """One long-lived mDNS registration process per LAN name (macOS dns-sd -P, Linux avahi-publish -a -R).
Open = render the .mac.local blocks + one dns-sd -P proxy registration per name (and mac.local The machine's own .local name is never re-announced: its OS responder owns it, a second claim collides."""
itself). -P, not -R: a plain -R service registration publishes no A record, so phones (and
avahi on the Pi) time out resolving the name — measured 2026-11-09. Closed = tear both down. def __init__(self, plat, popen=None):
Loopback names never change with the gate.""" self.plat, self.popen, self.procs = plat, popen or subprocess.Popen, {} # name -> (Popen, ip)
procs = {} # lan name -> (dns-sd Popen, advertised ip)
def stop(self, name=None):
def stop(name=None): for n in ([name] if name else list(self.procs)):
for n in ([name] if name else list(procs)): p = self.procs.pop(n, None)
p = procs.pop(n, None)
if p and p[0].poll() is None: if p and p[0].poll() is None:
p[0].terminate() p[0].terminate()
def reconcile(names): def reconcile(self, names, ip):
ip = lan_ip()
if not ip: if not ip:
stop() # no private address: nothing LAN-side to point the records at self.stop() # no private address: nothing LAN-side to point the records at
return return
for n in sorted(names): wanted = set(names) - {self.plat.own_mdns_name()}
p = procs.get(n) for n in list(self.procs):
if n not in wanted:
self.stop(n) # name removed from the registry: withdraw it
for n in sorted(wanted):
p = self.procs.get(n)
if p is None or p[0].poll() is not None or p[1] != ip: # new, died, or dhcp moved us if p is None or p[0].poll() is not None or p[1] != ip: # new, died, or dhcp moved us
stop(n) self.stop(n)
procs[n] = (subprocess.Popen(["dns-sd", "-P", n, "_http._tcp", ".", "443", n, ip], argv = self.plat.announce_argv(n, ip)
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), ip) if argv:
self.procs[n] = (self.popen(argv, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL), ip)
def gate_state():
"""(open, detail) for the LAN face: needs an mDNS announcer on this machine AND the ssh handshake."""
problem = PLAT.announcer_problem()
if problem:
return False, f"{problem}: LAN face off, loopback untouched"
if handshake_ok():
return True, f"{HANDSHAKE_HOST} handshake ok"
return False, f"{HANDSHAKE_HOST} handshake failed: no announce, LAN face closed"
def start_lan_announcer():
"""Every HANDSHAKE_SECS: make domovoy prove itself, then open or close the LAN face.
Open = render the LAN_SUFFIX blocks + one mDNS registration per name (and GATEWAY_HOST).
macOS uses dns-sd -P, not -R: a plain -R service registration publishes no A record, so phones
(and avahi on the Pi) time out resolving the name — measured 2026-11-09. Linux uses
avahi-publish -a -R (address record, no reverse PTR: many names share one IP). Closed = tear both
down. Loopback names never change with the gate."""
ann = Announcer(PLAT)
def loop(): def loop():
while True: while True:
ok = handshake_ok() ok, detail = gate_state()
prev = lan_gate_open() prev = lan_gate_open()
write_gate(ok, "domovoy handshake ok" if ok else "domovoy handshake failed: no announce, LAN face closed") write_gate(ok, detail)
if ok != prev: if ok != prev:
try: try:
with locked(): with locked():
...@@ -861,11 +946,11 @@ def start_lan_announcer(): ...@@ -861,11 +946,11 @@ def start_lan_announcer():
if ok: if ok:
try: try:
reg = load() reg = load()
reconcile({h[:-len(SUFFIX)] + LAN_SUFFIX for h in reg["entries"]} | {GATEWAY_HOST}) ann.reconcile({h[:-len(SUFFIX)] + LAN_SUFFIX for h in reg["entries"]} | {GATEWAY_HOST}, lan_ip())
except Exception as ex: except Exception as ex:
print(f"devname: lan announce failed: {ex}", file=sys.stderr, flush=True) print(f"devname: lan announce failed: {ex}", file=sys.stderr, flush=True)
else: else:
stop() ann.stop()
time.sleep(HANDSHAKE_SECS) time.sleep(HANDSHAKE_SECS)
threading.Thread(target=loop, daemon=True, name="lan-announcer").start() threading.Thread(target=loop, daemon=True, name="lan-announcer").start()
......
...@@ -666,6 +666,84 @@ class PlatformTests(unittest.TestCase): ...@@ -666,6 +666,84 @@ class PlatformTests(unittest.TestCase):
self.run.table[("systemctl", "is-enabled", "caddy.service")] = (1, "disabled") self.run.table[("systemctl", "is-enabled", "caddy.service")] = (1, "disabled")
self.assertIsNone(plat.system_caddy()) self.assertIsNone(plat.system_caddy())
# LAN face plumbing: address lookup, announcers, gate
def test_lan_ip_takes_the_first_private_route_source(self):
cases = [({"224.0.0.251": "192.168.1.20"}, "192.168.1.20"),
({"224.0.0.251": "100.101.1.2", "192.0.2.1": "10.0.0.7"}, "10.0.0.7"), # VPN CGNAT skipped
({"224.0.0.251": "172.20.3.4"}, "172.20.3.4"),
({"224.0.0.251": "8.8.4.4", "192.0.2.1": "169.254.3.3"}, None), # public, link-local
({}, None)] # offline: no route
for routes, want in cases:
def fake(dest, routes=routes):
if dest not in routes:
raise OSError("network unreachable")
return routes[dest]
with mock.patch.object(self.dn, "route_source", side_effect=fake):
self.assertEqual(self.dn.lan_ip(), want, routes)
def test_announce_argv_per_platform(self):
with mock.patch.object(self.dn.shutil, "which", side_effect=lambda t: f"/usr/bin/{t}"):
mac = self.dn.MacPlatform().announce_argv("a.mac.local", "192.168.1.2")
linux = self.dn.LinuxPlatform(self.UBUNTU, systemd=True).announce_argv("a.xps24.local", "192.168.1.2")
self.assertEqual(mac, ["/usr/bin/dns-sd", "-P", "a.mac.local", "_http._tcp", ".", "443", "a.mac.local", "192.168.1.2"])
self.assertEqual(linux, ["/usr/bin/avahi-publish", "-a", "-R", "a.xps24.local", "192.168.1.2"])
self.assertIsNone(self.dn.Platform({}).announce_argv("a.x.local", "192.168.1.2"))
def test_announcer_problem_degrades_the_lan_face_cleanly(self):
linux = self.dn.LinuxPlatform(self.UBUNTU, systemd=True)
with mock.patch.object(self.dn.shutil, "which", return_value=None), \
mock.patch.object(linux, "tool_dirs", ()):
self.assertIn("apt install avahi-daemon avahi-utils", linux.announcer_problem())
self.use(linux, FakeRun({("systemctl", "is-active", "avahi-daemon.service"): (3, "inactive")}))
with mock.patch.object(self.dn.shutil, "which", return_value="/usr/bin/avahi-publish"):
self.assertIn("avahi-daemon is not running", linux.announcer_problem())
self.run.table[("systemctl", "is-active", "avahi-daemon.service")] = (0, "active")
self.assertIsNone(linux.announcer_problem())
with mock.patch.object(self.dn.shutil, "which", return_value=None), \
mock.patch.object(self.dn.MacPlatform, "tool_dirs", ()):
self.assertEqual(self.dn.MacPlatform().announcer_problem(), "dns-sd not found")
def test_gate_stays_shut_without_an_announcer_and_never_calls_ssh(self):
self.use(self.dn.Platform({}))
with mock.patch.object(self.dn, "handshake_ok", side_effect=AssertionError("no ssh without an announcer")):
ok, detail = self.dn.gate_state()
self.assertFalse(ok)
self.assertIn("LAN face off, loopback untouched", detail)
linux = self.use(self.dn.LinuxPlatform(self.UBUNTU, systemd=True))
with mock.patch.object(linux, "announcer_problem", return_value=None):
with mock.patch.object(self.dn, "handshake_ok", return_value=True):
self.assertEqual(self.dn.gate_state(), (True, "domovoy-admin handshake ok"))
with mock.patch.object(self.dn, "handshake_ok", return_value=False):
self.assertFalse(self.dn.gate_state()[0])
def test_announcer_reconciles_and_skips_the_machines_own_name(self):
started = []
class Proc:
def __init__(self, argv, **kw):
self.argv, self.alive = argv, True
started.append(self)
def poll(self):
return None if self.alive else 0
def terminate(self):
self.alive = False
linux = self.dn.LinuxPlatform(self.UBUNTU, systemd=True)
with mock.patch.object(self.dn.socket, "gethostname", return_value="xps24"), \
mock.patch.object(self.dn.shutil, "which", side_effect=lambda t: f"/usr/bin/{t}"):
ann = self.dn.Announcer(linux, popen=Proc)
ann.reconcile({"a.xps24.local", "b.xps24.local", "xps24.local"}, "192.168.1.2")
self.assertEqual(sorted(p.argv[3] for p in started), ["a.xps24.local", "b.xps24.local"]) # own name: avahi's
ann.reconcile({"a.xps24.local", "b.xps24.local"}, "192.168.1.2")
self.assertEqual(len(started), 2) # steady state: nothing respawned
ann.reconcile({"a.xps24.local"}, "192.168.1.9") # b removed, dhcp moved us
self.assertFalse([p for p in started if p.argv[3] == "b.xps24.local"][0].alive)
self.assertEqual(started[-1].argv[-1], "192.168.1.9")
ann.reconcile({"a.xps24.local"}, None) # lost the LAN: withdraw everything
self.assertFalse(any(p.alive for p in started))
# any other Unix: no supervisor, a clear refusal # any other Unix: no supervisor, a clear refusal
def test_other_platform_refuses_agent_and_points_at_serve(self): def test_other_platform_refuses_agent_and_points_at_serve(self):
self.use(self.dn.Platform({})) self.use(self.dn.Platform({}))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment