"""Apply and confirm per-interface IPv4 profiles using the existing dhcpcd unit.""" import fnmatch import ipaddress import json import os from pathlib import Path import re import socket import subprocess import sys import time import uuid BASE = Path(sys.argv[2]) IP = sys.argv[3] SYSTEMCTL = sys.argv[4] STATE = Path("/var/lib/seiugw-network") RUN = Path("/run/seiugw-network") CONFIRMED = STATE / "profiles.json" EFFECTIVE = RUN / "dhcpcd.conf" TRIAL = RUN / "trial" TRIAL_SECONDS = 120 def atomic_write(path, content, mode=0o600): temporary = path.with_suffix(".tmp") with temporary.open("w", encoding="utf-8") as output: os.fchmod(output.fileno(), mode) output.write(content) output.flush() os.fsync(output.fileno()) temporary.replace(path) directory = os.open(path.parent, os.O_DIRECTORY) try: os.fsync(directory) finally: os.close(directory) def configuration(profiles): lines = [BASE.read_text(), "# IPv4 profiles managed by SE-Inno Universalgateway"] for name, profile in sorted(profiles.items()): lines.extend(["", f"interface {name}", f"metric {profile['metric']}"]) if profile["mode"] == "static": lines.append(f"static ip_address={profile['address']}/{profile['prefixLength']}") if profile["gateway"]: lines.append(f"static routers={profile['gateway']}") if profile["dns"]: lines.append("static domain_name_servers=" + " ".join(profile["dns"])) return "\n".join(lines) + "\n" def install(profiles): atomic_write(EFFECTIVE, configuration(profiles), 0o644) def configured_profiles(): return json.loads(CONFIRMED.read_text()) if CONFIRMED.exists() else {} def ip_json(*args): return json.loads(subprocess.check_output([IP, "-j", "-4", *args], timeout=3)) def inventory(): settings = {} for line in BASE.read_text().splitlines(): words = line.partition("#")[0].split() if words and words[0] in ("allowinterfaces", "denyinterfaces"): settings.setdefault(words[0], []).extend(words[1:]) allowed = settings.get("allowinterfaces", []) denied = settings.get("denyinterfaces", []) routes = ip_json("route", "show", "default") cards = {} for link in ip_json("address", "show"): name = link["ifname"] device = Path("/sys/class/net") / name if not re.fullmatch(r"[A-Za-z0-9_.-]{1,15}", name) or name.startswith("-"): continue if not (device / "device").exists() or (device / "type").read_text().strip() != "1": continue if any(fnmatch.fnmatchcase(name, pattern) for pattern in denied): continue if allowed and not any(fnmatch.fnmatchcase(name, pattern) for pattern in allowed): continue ipv4 = [{"address": info["local"], "prefixLength": info["prefixlen"], "dynamic": info.get("dynamic", False)} for info in link["addr_info"] if info["family"] == "inet" and info.get("scope") == "global"] cards[name] = {"name": name, "macAddress": (device / "address").read_text().strip(), "addresses": ipv4, "routes": [route for route in routes if route.get("dev") == name]} return cards def unicast(value): if not isinstance(value, str): raise ValueError("Eine gültige IPv4-Adresse ist erforderlich.") address = ipaddress.IPv4Address(value) if address.is_unspecified or address.is_multicast or address.is_loopback or address.is_reserved: raise ValueError("Eine nutzbare IPv4-Adresse ist erforderlich.") return address def validate(profile, cards, profiles): name = profile.get("interface") if not isinstance(name, str) or name not in cards: raise ValueError("Diese Netzwerkkarte kann nicht verwaltet werden.") mode = profile.get("mode") metric = profile.get("metric") if mode not in ("dhcp", "static") or type(metric) is not int or not 1 <= metric <= 65535: raise ValueError("Bitte Modus und Routenmetrik (1–65535) prüfen.") result = {"interface": name, "mode": mode, "metric": metric, "address": None, "prefixLength": None, "gateway": None, "dns": []} if mode == "dhcp": return result address = unicast(profile.get("address")) prefix = profile.get("prefixLength") if type(prefix) is not int or not 1 <= prefix <= 32: raise ValueError("Die Präfixlänge muss zwischen 1 und 32 liegen.") subnet = ipaddress.IPv4Network((address, prefix), strict=False) if prefix <= 30 and address in (subnet.network_address, subnet.broadcast_address): raise ValueError("Die Adresse darf keine Netz- oder Broadcast-Adresse sein.") gateway = unicast(profile["gateway"]) if profile.get("gateway") else None if gateway is not None and (gateway not in subnet or gateway == address or (prefix <= 30 and gateway in (subnet.network_address, subnet.broadcast_address))): raise ValueError("Das Standardgateway muss eine andere nutzbare Adresse im selben Subnetz sein.") dns = profile.get("dns") or [] if not isinstance(dns, list) or len(dns) > 4: raise ValueError("Bis zu vier IPv4-DNS-Server sind zulässig.") if any(other != name and (any(item["address"] == str(address) for item in card["addresses"]) or profiles.get(other, {}).get("address") == str(address)) for other, card in cards.items()): raise ValueError("Die Adresse ist bereits einer anderen Netzwerkkarte zugeordnet.") result.update(address=str(address), prefixLength=prefix, gateway=str(gateway) if gateway else None, dns=list(dict.fromkeys(str(unicast(item)) for item in dns))) return result def restart_dhcp(): return subprocess.Popen([SYSTEMCTL, "restart", "dhcpcd.service"]) class NetworkControl: def __init__(self): self.profiles = configured_profiles() self.change = None self.job = None self.notice = None if TRIAL.exists(): self.revert("Nicht bestätigte Netzwerkeinstellungen wurden zurückgesetzt.") def revert(self, notice): install(self.profiles) # Queue another restart even if a previous systemctl client is still waiting. self.job = restart_dhcp() self.change = None self.notice = notice def tick(self): now = time.monotonic() if self.job is not None and self.job.poll() is not None: success = self.job.returncode == 0 self.job = None if self.change and not success: self.revert("Der Netzwerkdienst konnte die Änderung nicht laden. Vorheriges Profil wiederhergestellt.") elif not self.change: if success: TRIAL.unlink(missing_ok=True) else: self.notice = "Rücksetzen gespeichert. Der DHCP-Dienst meldet einen Startfehler." if self.change is None: return if now >= self.change["deadline"]: self.revert("Zeit abgelaufen. Vorheriges Profil wiederhergestellt.") elif not self.change["started"] and now >= self.change["start"]: self.change["started"] = True try: install(self.profiles | {self.change["profile"]["interface"]: self.change["profile"]}) self.job = restart_dhcp() except OSError: self.revert("Netzwerkeinstellungen konnten nicht angewendet werden.") def status(self, cards): pending = None if self.change: change = self.change profile = change["profile"] card = cards.get(profile["interface"], {}) addresses = card.get("addresses", []) ready = change["started"] and self.job is None and any( candidate["dynamic"] if profile["mode"] == "dhcp" else candidate["address"] == profile["address"] and candidate["prefixLength"] == profile["prefixLength"] for candidate in addresses) pending = {"id": change["id"], "profile": profile, "ready": ready, "secondsLeft": max(0, round(change["deadline"] - time.monotonic()))} return {"interfaces": list(cards.values()), "profiles": self.profiles, "pending": pending, "busy": self.job is not None, "notice": self.notice} def handle(self, request): if not isinstance(request, dict): raise ValueError("Ungültige Netzwerk-Anfrage.") action = request.get("action") cards = inventory() if action == "apply": if self.change or self.job: raise ValueError("Es läuft bereits eine Netzwerkänderung.") profile = request.get("profile") if not isinstance(profile, dict): raise ValueError("Das Netzwerkprofil fehlt.") profile = validate(profile, cards, self.profiles) now = time.monotonic() atomic_write(TRIAL, "pending\n") self.change = {"id": uuid.uuid4().hex, "profile": profile, "start": now + 2, "deadline": now + TRIAL_SECONDS, "started": False} self.notice = None elif action in ("confirm", "revert"): if not self.change or self.change["id"] != request.get("id"): raise ValueError("Diese Netzwerkänderung ist nicht mehr offen.") if action == "revert": self.revert("Vorheriges Profil wiederhergestellt.") else: if not self.status(cards)["pending"]["ready"]: raise ValueError("Die neue Adresse ist noch nicht aktiv.") profile = self.change["profile"] profiles = self.profiles | {profile["interface"]: profile} atomic_write(CONFIRMED, json.dumps(profiles)) self.profiles, self.change = profiles, None TRIAL.unlink(missing_ok=True) self.notice = "Netzwerkeinstellungen gespeichert." elif action != "status": raise ValueError("Ungültige Netzwerkaktion.") return self.status(cards) def serve(): control = NetworkControl() listener = socket.socket(fileno=3) # systemd ListenStream listener.settimeout(0.5) while True: control.tick() try: client, _ = listener.accept() except TimeoutError: continue with client: client.settimeout(2) try: request = client.makefile("rb").read(8193) if len(request) > 8192: raise ValueError("Netzwerk-Anfrage zu groß.") result = control.handle(json.loads(request)) except ValueError as error: result = {"error": str(error)} except (OSError, subprocess.SubprocessError) as error: print(error, file=sys.stderr, flush=True) result = {"error": "Der Netzwerkdienst konnte die Anfrage nicht verarbeiten."} try: client.sendall(json.dumps(result).encode()) except OSError: pass if __name__ == "__main__": if sys.argv[1] == "prepare": # A tentative change exists only in /run; a reboot loads the confirmed profiles. install(configured_profiles()) else: serve()