feat(network): verify selected uplinks, roll back failures and manage NetBird policy
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Board-owned physical uplink control. No Core address or hardware constants."""
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Bounded local controller evidence. Never sent as periodic WAN telemetry."""
|
||||
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
|
||||
class Evidence:
|
||||
def record_error(self, error):
|
||||
# Class/step are sufficient to locate the failing boundary. Never copy
|
||||
# exception text or subprocess arguments, which may contain secrets.
|
||||
self.operation['failure'] = dict(
|
||||
step=self.operation.get('apply_step', self.operation.get('phase', 'unknown')),
|
||||
error_type=type(error).__name__[:80])
|
||||
if callable(getattr(error, 'get_dbus_name', None)):
|
||||
name = error.get_dbus_name()
|
||||
if isinstance(name, str) and re.fullmatch(r'[A-Za-z0-9_.]{1,160}', name):
|
||||
self.operation['failure']['dbus_error'] = name
|
||||
if isinstance(error, subprocess.CalledProcessError):
|
||||
cmd = error.cmd
|
||||
if isinstance(cmd, (tuple, list)) and list(cmd[:1]) == ['/usr/sbin/ip']:
|
||||
# ip route/rule commands contain no authentication material.
|
||||
# Preserve the actual kernel failure locally for diagnosis.
|
||||
self.operation['failure']['command'] = [str(v)[:128] for v in cmd[:32]]
|
||||
self.operation['failure']['exit_code'] = error.returncode
|
||||
raw = error.stderr or b''
|
||||
self.operation['failure']['kernel_error'] = (
|
||||
raw.decode(errors='replace') if isinstance(raw, bytes) else raw)[:512]
|
||||
self.save()
|
||||
|
||||
def record_transition(self):
|
||||
op = self.operation
|
||||
state = dict(operation_id=op['id'], phase=op['phase'], target=op.get('target'),
|
||||
previous=op.get('previous'), selected=self.watched_target(),
|
||||
fallback_enabled=self.fallback_enabled(),
|
||||
local_override=bool(op.get('local_override')),
|
||||
reason=op.get('recovery_reason', ''), message=op.get('message', ''),
|
||||
wait_reason=op.get('wait_reason', ''), failure=op.get('failure'))
|
||||
prior = op.get('diagnostic_events', [])
|
||||
if prior and prior[-1]['state'] == state:
|
||||
return
|
||||
sequence = op.get('diagnostic_sequence', 0) + 1
|
||||
op['diagnostic_sequence'] = sequence
|
||||
op['diagnostic_events'] = [*prior, dict(
|
||||
sequence=sequence, at=self.wall_clock(), monotonic_ms=self.clock()*1000,
|
||||
helper_instance=self.helper_instance, state=state)][-16:]
|
||||
|
||||
def local_evidence(self, state):
|
||||
op = self.operation or {}
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
return dict(
|
||||
schema='missioncore.uplink-evidence/v1', helper_instance=self.helper_instance,
|
||||
sampled_at=self.wall_clock(), monotonic_ms=self.clock()*1000,
|
||||
native_current_id=state.get('current_id', ''),
|
||||
selected_id=self.watched_target() if op else '',
|
||||
interface=policy.get('interface', ''), transport_mark=policy.get('mark'),
|
||||
path_proven=self.path_ok, proof_age_ms=max(0, self.clock()-self.last_probe)*1000,
|
||||
core_reply_age_ms=max(0, self.clock()-self.last_core)*1000,
|
||||
fallback_enabled=self.fallback_enabled(), phase=op.get('phase', 'unselected'),
|
||||
local_override=bool(op.get('local_override')),
|
||||
events=op.get('diagnostic_events', [])[-16:])
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Board-owned fallback permission, independent of a particular switch command."""
|
||||
|
||||
import copy
|
||||
import re
|
||||
|
||||
|
||||
class FallbackPolicy:
|
||||
def load_fallback(self):
|
||||
value = (self.operation or {}).get('fallback', dict(
|
||||
enabled=True, revision=0, operation_id=''))
|
||||
if (type(value.get('enabled')) is not bool
|
||||
or type(value.get('revision')) is not int or value['revision'] < 0):
|
||||
raise ValueError('Повреждена настройка резервного подключения.')
|
||||
self.fallback_setting = value
|
||||
|
||||
def fallback_enabled(self):
|
||||
return self.fallback_setting['enabled']
|
||||
|
||||
def select_path(self, policy):
|
||||
strict = {} if self.fallback_enabled() else {'strict': True}
|
||||
self.path_adapter.select({**policy, **strict})
|
||||
|
||||
def retain_path(self):
|
||||
op = self.operation or {}
|
||||
if self.fallback_enabled() or op.get('local_override') or not op.get('policy'):
|
||||
return
|
||||
policy = op.get('watch_policy') or op['policy']
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
|
||||
def fallback(self, body):
|
||||
if (not re.fullmatch(r'[a-f0-9]{32}', str(body['id']))
|
||||
or type(body['enabled']) is not bool or type(body['revision']) is not int):
|
||||
raise ValueError('Некорректная настройка резервного подключения.')
|
||||
if (not self.context or body['binding'] != self.context['binding']
|
||||
or self.clock() - self.last_core > 20
|
||||
or type(body['expires_at']) is not int
|
||||
or not self.wall_clock() < body['expires_at'] <= self.wall_clock() + 60):
|
||||
raise ValueError('Нет свежего подтверждения Core.')
|
||||
old = self.fallback_setting
|
||||
if body['id'] == old['operation_id']:
|
||||
if body['enabled'] != old['enabled']:
|
||||
raise ValueError('Конфликт настройки резервного подключения.')
|
||||
return self.status()
|
||||
if body['revision'] != old['revision']:
|
||||
raise ValueError('Настройка изменилась. Обновите состояние борта.')
|
||||
self.tick()
|
||||
op = self.operation
|
||||
if (not op or op['phase'] not in ('applied', 'rolled_back', 'superseded')
|
||||
or not self.path_ok or self.clock() - self.last_core > 20):
|
||||
raise ValueError('Дождитесь подтверждения текущего подключения.')
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
chosen, policy = self.proven_current(state)
|
||||
updated = dict(enabled=body['enabled'], revision=old['revision'] + 1,
|
||||
operation_id=body['id'])
|
||||
self.path_adapter.select({**policy, **({} if updated['enabled'] else {'strict': True})})
|
||||
before = copy.deepcopy(op)
|
||||
self.fallback_setting = updated
|
||||
# This explicit Core choice owns the current path, never an alternative.
|
||||
op.update(network_policy='native-fallback-v2', local_override=False,
|
||||
watch_policy=policy, watch_target=chosen['id'])
|
||||
op['profile_baseline'] = [dict(e, planned=e['saved']) for e in state['candidates']]
|
||||
self.transport_ready = True
|
||||
try:
|
||||
self.save() # Policy and selected-path ownership commit atomically.
|
||||
except Exception:
|
||||
self.operation, self.fallback_setting = before, old
|
||||
self.select_path(policy)
|
||||
raise
|
||||
return self.status()
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Installer migration from owned manual-only preferences to normal NM fallback."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
FAMILIES = ("ipv4", "ipv6")
|
||||
|
||||
|
||||
def migrate(root: Path, adapter):
|
||||
path = root / "operation.json"
|
||||
receipt = root / "native-fallback-v1.json"
|
||||
if not path.exists():
|
||||
return
|
||||
op = json.loads(path.read_text())
|
||||
if op.get("network_policy") in ("native-fallback-v1", "native-fallback-v2"):
|
||||
return
|
||||
if op.get("phase") not in ("applied", "rolled_back", "superseded"):
|
||||
raise ValueError("Завершите текущую операцию переключения перед обновлением.")
|
||||
entries = sorted(op.get("profile_baseline") or op.get("baseline", []), key=lambda e: e["id"])
|
||||
pending = root / "native-fallback-v1.pending.json"
|
||||
if pending.exists():
|
||||
adapter.restore_profiles(json.loads(pending.read_text())["changes"])
|
||||
current = adapter.profile_preferences()
|
||||
changes, skipped = [], []
|
||||
for index, entry in enumerate(entries):
|
||||
saved = entry.get("saved")
|
||||
value = current.get(entry["id"], {}).get("saved")
|
||||
if not saved or value is None or entry.get("kind") not in ("ethernet", "wifi"):
|
||||
continue
|
||||
old = entry.get("planned") or dict(
|
||||
autoconnect=entry["kind"] == "ethernet" or entry["id"] == op["target"],
|
||||
metrics={f: 10 if entry["id"] == op["target"] else 100 + index for f in FAMILIES},
|
||||
defaults={f: entry["id"] != op["target"] for f in FAMILIES},
|
||||
)
|
||||
restored = dict(value, autoconnect=saved["autoconnect"], defaults=saved["defaults"])
|
||||
if value != old and value != saved:
|
||||
skipped.append(entry["id"])
|
||||
continue
|
||||
if value == restored:
|
||||
continue
|
||||
changes.append(dict(entry, saved=value, planned=restored))
|
||||
# Persist the exact undo record before the first write. A failed installation
|
||||
# restores already changed profiles and can retry; unrelated edits survive.
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
with pending.open("w") as stream:
|
||||
os.chmod(pending, 0o600)
|
||||
json.dump(dict(changes=changes, skipped=skipped), stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
live = None
|
||||
try:
|
||||
for entry in changes:
|
||||
adapter.set_preference(entry, entry["planned"])
|
||||
live = adapter.inspect(known=entries)
|
||||
for entry in live["candidates"]:
|
||||
if entry["id"] in {e["id"] for e in changes}:
|
||||
adapter.release_reserves([entry], "")
|
||||
except Exception:
|
||||
adapter.restore_profiles(changes)
|
||||
if live:
|
||||
adapter.restore_metrics(live["candidates"])
|
||||
raise
|
||||
# Keep priorities, but take ownership only of profiles proved by this journal.
|
||||
updated = adapter.profile_preferences()
|
||||
op["profile_baseline"] = [
|
||||
dict(e, saved=updated[e["id"]]["saved"], planned=updated[e["id"]]["saved"])
|
||||
for e in entries if e["id"] in updated and e["id"] not in skipped
|
||||
]
|
||||
op["network_policy"] = "native-fallback-v1"
|
||||
temporary = path.with_suffix(".migration.tmp")
|
||||
with temporary.open("w") as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
json.dump(op, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(path)
|
||||
pending.replace(receipt)
|
||||
@@ -0,0 +1,180 @@
|
||||
"""Read-only physical-path evidence for the qualified NetBird transport.
|
||||
|
||||
NetworkManager exclusively owns connection switching. No VPN configuration edits.
|
||||
"""
|
||||
|
||||
import ipaddress
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from .quic_path import observe_udp
|
||||
from .transport_route import TransportRoute
|
||||
|
||||
NAME = re.compile(r"^[a-zA-Z0-9_.-]{1,64}$")
|
||||
|
||||
|
||||
def run(*args):
|
||||
result = subprocess.run(args, capture_output=True, timeout=8, check=True)
|
||||
if len(result.stdout) > 262144:
|
||||
raise ValueError("Слишком большой ответ сетевой службы.")
|
||||
return result.stdout.decode()
|
||||
|
||||
|
||||
def private_peer(value):
|
||||
address = ipaddress.IPv4Address(value)
|
||||
if (
|
||||
(not address.is_private and address not in ipaddress.ip_network("100.64.0.0/10"))
|
||||
or address.is_loopback
|
||||
or address.is_link_local
|
||||
):
|
||||
raise ValueError("Некорректный адрес Core.")
|
||||
return str(address)
|
||||
|
||||
|
||||
def endpoint(value):
|
||||
host, port = value.rsplit(":", 1)
|
||||
return str(ipaddress.ip_address(host.strip("[]").split("%", 1)[0])), int(port)
|
||||
|
||||
|
||||
class NetBirdPath:
|
||||
def __init__(self, root=None):
|
||||
self.routing = TransportRoute(run) if root is None else TransportRoute(run, root)
|
||||
|
||||
def status(self):
|
||||
state = json.loads(run("/usr/bin/netbird", "status", "--json"))
|
||||
if state.get("profileName") != "mission-core" or state.get("daemonVersion") != "0.82.0":
|
||||
raise ValueError("Для выбора пути нужен профиль Mission Core и NetBird 0.82.0.")
|
||||
return state
|
||||
|
||||
def prepare(self, peer, interface):
|
||||
private_peer(peer)
|
||||
self.status()
|
||||
if not NAME.fullmatch(interface):
|
||||
raise ValueError("Некорректный сетевой интерфейс.")
|
||||
route = json.loads(run("/usr/sbin/ip", "-j", "-4", "route", "get", peer))
|
||||
vpn_interface = route[0].get("dev", "") if len(route) == 1 else ""
|
||||
if not NAME.fullmatch(vpn_interface):
|
||||
raise ValueError("Не определён интерфейс VPN до Core.")
|
||||
mark = int(run("/usr/bin/wg", "show", vpn_interface, "fwmark").strip(), 0)
|
||||
if mark <= 0 or mark > 0xFFFFFFFF or mark & 0xFF:
|
||||
raise ValueError("Не подтверждена штатная метка транспорта NetBird.")
|
||||
return dict(interface=interface, peer=peer, mark=mark)
|
||||
|
||||
def select(self, policy):
|
||||
self.routing.select(policy)
|
||||
|
||||
def release(self):
|
||||
self.routing.release()
|
||||
|
||||
def route(self, address, interface, source="", mark=None):
|
||||
args = ["/usr/sbin/ip", "-j", "-4", "route", "get", address]
|
||||
if source:
|
||||
args += ["from", source]
|
||||
if mark:
|
||||
args += ["mark", hex(mark)]
|
||||
routes = json.loads(run(*args))
|
||||
return (
|
||||
len(routes) == 1
|
||||
and routes[0].get("dev") == interface
|
||||
and (not source or routes[0].get("prefsrc", routes[0].get("src", source)) == source)
|
||||
)
|
||||
|
||||
def evidence(self, policy):
|
||||
interface, peer_ip = policy["interface"], policy["peer"]
|
||||
state = self.status()
|
||||
peer = next(
|
||||
(p for p in state.get("peers", {}).get("details", []) if p.get("netbirdIp") == peer_ip),
|
||||
None,
|
||||
)
|
||||
if not peer or peer.get("status") != "Connected":
|
||||
return False
|
||||
addresses = json.loads(run("/usr/sbin/ip", "-j", "-4", "address", "show", "dev", interface))
|
||||
sources = {
|
||||
a["local"]
|
||||
for e in addresses
|
||||
for a in e.get("addr_info", [])
|
||||
if a.get("family") == "inet"
|
||||
}
|
||||
if not sources:
|
||||
return False
|
||||
if peer.get("connectionType") == "P2P":
|
||||
# The kernel's current peer endpoint, not a remembered ICE candidate.
|
||||
peer_route = json.loads(run("/usr/sbin/ip", "-j", "-4", "route", "get", peer_ip))
|
||||
iface = peer_route[0].get("dev", "") if len(peer_route) == 1 else ""
|
||||
if not NAME.fullmatch(iface):
|
||||
return False
|
||||
entries = [
|
||||
line.split() for line in run("/usr/bin/wg", "show", iface, "endpoints").splitlines()
|
||||
]
|
||||
value = next((v for k, v in entries if k == peer.get("publicKey")), "")
|
||||
destination, _ = endpoint(value)
|
||||
local, _ = endpoint(peer["iceCandidateEndpoint"]["local"])
|
||||
# A kernel WireGuard socket uses its current fwmark route. ICE's
|
||||
# remembered local candidate may predate that route change.
|
||||
if (
|
||||
not policy.get("mark")
|
||||
and peer.get("iceCandidateType", {}).get("local") == "host"
|
||||
and local not in sources
|
||||
):
|
||||
return False
|
||||
return not ipaddress.ip_address(destination).is_loopback and self.route(
|
||||
destination, interface, mark=policy.get("mark")
|
||||
)
|
||||
if peer.get("connectionType") != "Relayed":
|
||||
return False
|
||||
relay = urlsplit(peer.get("relayAddress", ""))
|
||||
if relay.scheme not in ("rel", "rels") or not relay.hostname or not relay.port:
|
||||
return False
|
||||
# Bound DNS subprocess; a failed resolver cannot stall the watchdog.
|
||||
ips = {
|
||||
line.split()[0]
|
||||
for line in run("/usr/bin/getent", "ahostsv4", relay.hostname).splitlines()
|
||||
}
|
||||
cgroup = run(
|
||||
"/usr/bin/systemctl", "show", "netbird.service", "--property=ControlGroup", "--value"
|
||||
).strip()
|
||||
if not cgroup.startswith("/") or any(c.isspace() for c in cgroup):
|
||||
return False
|
||||
quic = any(
|
||||
r.get("uri") == peer.get("relayAddress")
|
||||
and r.get("available")
|
||||
and r.get("transport") == "quic"
|
||||
for r in state.get("relays", {}).get("details", [])
|
||||
)
|
||||
sockets = []
|
||||
udp_ports = set()
|
||||
# SOCK_DIAG supplies the socket's cgroup without /proc/PID inspection.
|
||||
# The restricted service deliberately has no CAP_SYS_PTRACE.
|
||||
for line in run("/usr/bin/ss", "-Hntua", "--cgroup").splitlines():
|
||||
fields = line.split()
|
||||
if len(fields) < 7 or "cgroup:" + cgroup not in fields[6:]:
|
||||
continue
|
||||
if quic and fields[0] == "udp" and fields[1] in ("UNCONN", "ESTAB"):
|
||||
try:
|
||||
local, local_port = fields[4].rsplit(":", 1)
|
||||
local = local.strip("[]").split("%", 1)[0]
|
||||
if local in sources or local in ("*", "0.0.0.0", "::"):
|
||||
udp_ports.add(int(local_port))
|
||||
except ValueError:
|
||||
pass
|
||||
if fields[0] != "tcp" or fields[1] != "ESTAB":
|
||||
continue
|
||||
try:
|
||||
destination, port = endpoint(fields[5])
|
||||
source, _ = endpoint(fields[4])
|
||||
except ValueError:
|
||||
continue
|
||||
if destination in ips and port == relay.port:
|
||||
sockets.append(
|
||||
source in sources
|
||||
and self.route(destination, interface, source, policy.get("mark"))
|
||||
)
|
||||
if quic:
|
||||
# Upstream QUIC has an unconnected, wildcard-source UDP socket.
|
||||
# A route alone cannot prove its live path. Require an outgoing
|
||||
# header from an owned socket on the selected physical interface.
|
||||
packet = observe_udp(interface, sources, ips, relay.port, udp_ports)
|
||||
return bool(packet) and self.route(packet[1], interface, packet[0], policy.get("mark"))
|
||||
return bool(sockets) and all(sockets)
|
||||
@@ -0,0 +1,423 @@
|
||||
"""Narrow NetworkManager adapter; imports D-Bus only on the supported Linux host."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .preferences import Preferences
|
||||
|
||||
SERVICE = "org.freedesktop.NetworkManager"
|
||||
ROOT = "/org/freedesktop/NetworkManager"
|
||||
DEVICE = SERVICE + ".Device"
|
||||
|
||||
|
||||
class NetworkManager(Preferences):
|
||||
def __init__(self):
|
||||
import dbus
|
||||
|
||||
self.dbus = dbus
|
||||
self.bus = dbus.SystemBus(private=True)
|
||||
self.activation_attempts = {}
|
||||
|
||||
def epoch(self):
|
||||
return (
|
||||
Path("/proc/sys/kernel/random/boot_id").read_text().strip()
|
||||
+ ":"
|
||||
+ str(self.bus.get_name_owner(SERVICE))
|
||||
)
|
||||
|
||||
def obj(self, path):
|
||||
return self.bus.get_object(SERVICE, path)
|
||||
|
||||
def props(self, path, interface):
|
||||
return dict(
|
||||
self.dbus.Interface(self.obj(path), "org.freedesktop.DBus.Properties").GetAll(
|
||||
interface, timeout=5
|
||||
)
|
||||
)
|
||||
|
||||
def manager(self):
|
||||
return self.dbus.Interface(self.obj(ROOT), SERVICE)
|
||||
|
||||
def device_identity(self, path, props):
|
||||
kind = "Wireless" if int(props["DeviceType"]) == 2 else "Wired"
|
||||
value = self.props(path, DEVICE + "." + kind).get("PermHwAddress", "")
|
||||
return str(value).lower()
|
||||
|
||||
def same_device(self, entry, path, props):
|
||||
expected = entry.get("hardware", "")
|
||||
return (
|
||||
self.device_identity(path, props) == expected
|
||||
if expected
|
||||
else str(props["Interface"]) == entry["interface"]
|
||||
)
|
||||
|
||||
def routes(self, family):
|
||||
raw = subprocess.run(
|
||||
["/usr/sbin/ip", "-j", f"-{family}", "route", "show", "default"],
|
||||
capture_output=True,
|
||||
check=True,
|
||||
timeout=3,
|
||||
).stdout
|
||||
if len(raw) > 32768:
|
||||
raise ValueError("Слишком сложная таблица маршрутов.")
|
||||
return json.loads(raw)
|
||||
|
||||
@staticmethod
|
||||
def preference(settings):
|
||||
return dict(
|
||||
autoconnect=bool(settings["connection"].get("autoconnect", True)),
|
||||
metrics={f: int(settings.get(f, {}).get("route-metric", -1)) for f in ("ipv4", "ipv6")},
|
||||
defaults={
|
||||
f: bool(settings.get(f, {}).get("never-default", False)) for f in ("ipv4", "ipv6")
|
||||
},
|
||||
)
|
||||
|
||||
def saved(self, connection):
|
||||
return self.dbus.Interface(
|
||||
self.obj(connection), SERVICE + ".Settings.Connection"
|
||||
).GetSettings(timeout=5)
|
||||
|
||||
def inspect(self, known=()):
|
||||
# Per-device NM status is readiness, not proof of the new Core path.
|
||||
# A global synchronous CheckConnectivity can block on another interface;
|
||||
# fresh authenticated Core/path evidence commits the guarded trial.
|
||||
global_props = self.props(ROOT, SERVICE)
|
||||
version = tuple(int(x) for x in str(global_props["Version"]).split(".")[:2])
|
||||
if version < (1, 46):
|
||||
raise ValueError("Для выбора подключения нужен NetworkManager 1.46 или новее.")
|
||||
if not (
|
||||
global_props.get("ConnectivityCheckEnabled")
|
||||
and global_props.get("ConnectivityCheckAvailable")
|
||||
):
|
||||
raise ValueError("На борту отключена проверка доступности интернета.")
|
||||
routes4, routes6 = self.routes(4), self.routes(6)
|
||||
paths = list(global_props["Devices"])
|
||||
if len(paths) > 64:
|
||||
raise ValueError("Слишком много сетевых интерфейсов.")
|
||||
entries = []
|
||||
for path in paths:
|
||||
p = self.props(path, DEVICE)
|
||||
if int(p["DeviceType"]) not in (1, 2) or int(p["State"]) != 100 or not p["Managed"]:
|
||||
continue
|
||||
name = str(p["Interface"])
|
||||
has_default = any(r.get("dev") == name for r in routes4)
|
||||
dev = self.dbus.Interface(self.obj(path), DEVICE)
|
||||
settings, applied_version = dev.GetAppliedConnection(0, timeout=5)
|
||||
identity = str(settings["connection"]["uuid"])
|
||||
admitted = any(e["id"] == identity for e in known)
|
||||
if (
|
||||
not has_default
|
||||
and not admitted
|
||||
and (
|
||||
int(p["DeviceType"]) != 2
|
||||
or (
|
||||
settings.get("ipv4", {}).get("never-default")
|
||||
or settings.get("ipv4", {}).get("method") != "auto"
|
||||
)
|
||||
)
|
||||
):
|
||||
continue
|
||||
connection = str(
|
||||
self.props(p["ActiveConnection"], SERVICE + ".Connection.Active")["Connection"]
|
||||
)
|
||||
for family in ("ipv4", "ipv6"):
|
||||
part = settings.get(family, {})
|
||||
if part.get("route-table", 0) not in (0, 254) or part.get("routing-rules"):
|
||||
raise ValueError(
|
||||
"Выбор подключения недоступен при нестандартной маршрутизации."
|
||||
)
|
||||
if any(
|
||||
int(r.get("prefix", -1)) == 0 for r in part.get("route-data", [])
|
||||
) or part.get("routes"):
|
||||
raise ValueError("Выбор подключения недоступен при ручных маршрутах.")
|
||||
entries.append(
|
||||
dict(
|
||||
id=identity,
|
||||
connection=connection,
|
||||
saved=self.preference(self.saved(connection)),
|
||||
label=str(settings["connection"]["id"])[:160],
|
||||
interface=name,
|
||||
kind="wifi" if int(p["DeviceType"]) == 2 else "ethernet",
|
||||
hardware=self.device_identity(path, p),
|
||||
verified=has_default and int(p["Ip4Connectivity"]) == 4,
|
||||
available=True,
|
||||
active=True,
|
||||
local_only=not has_default and admitted,
|
||||
path=str(path),
|
||||
version=int(applied_version),
|
||||
ipv6=any(r.get("dev") == name for r in routes6),
|
||||
metrics={
|
||||
f: int(settings.get(f, {}).get("route-metric", -1))
|
||||
for f in ("ipv4", "ipv6")
|
||||
},
|
||||
defaults=self.preference(settings)["defaults"],
|
||||
)
|
||||
)
|
||||
names = {e["interface"] for e in entries}
|
||||
if any(r.get("dev") not in names or "nexthops" in r for r in routes4 + routes6):
|
||||
raise ValueError("Основной маршрут не принадлежит управляемому Wi-Fi или Ethernet.")
|
||||
if len(entries) > 16 or len({e["id"] for e in entries}) != len(entries):
|
||||
raise ValueError("Неоднозначная привязка сетевых профилей.")
|
||||
minimum = min((int(r.get("metric", 0)) for r in routes4), default=0)
|
||||
primary = {r["dev"] for r in routes4 if int(r.get("metric", 0)) == minimum}
|
||||
current = next((e["id"] for e in entries if primary == {e["interface"]}), "")
|
||||
# The admitted Core peer and physical-path proof use IPv4. A native
|
||||
# IPv6 route on another NIC must not hide a working IPv4-only uplink.
|
||||
# IPv6 remains under NetworkManager's independent family policy.
|
||||
revision = hashlib.sha256(
|
||||
json.dumps(
|
||||
[
|
||||
self.epoch(),
|
||||
entries,
|
||||
[
|
||||
{k: r.get(k) for k in ("dev", "gateway", "metric")}
|
||||
for r in routes4 + routes6
|
||||
],
|
||||
],
|
||||
sort_keys=True,
|
||||
).encode()
|
||||
).hexdigest()
|
||||
return {
|
||||
"supported": True,
|
||||
"revision": revision,
|
||||
"current_id": current,
|
||||
"candidates": entries,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def public(state):
|
||||
return {
|
||||
**state,
|
||||
"candidates": [
|
||||
{k: e[k] for k in ("id", "label", "interface", "kind",
|
||||
"verified", "available", "active")}
|
||||
for e in state["candidates"]
|
||||
],
|
||||
}
|
||||
|
||||
def checkpoint(self, entries):
|
||||
return str(
|
||||
self.manager().CheckpointCreate(
|
||||
# Do not checkpoint an initially disconnected reserve: NM's
|
||||
# rollback would Disconnect(USER_REQUESTED) it and inhibit its
|
||||
# saved profile. Only the existing working devices need undo.
|
||||
self.dbus.Array([self.dbus.ObjectPath(path) for path in sorted({
|
||||
e['path'] for e in entries if e.get('active', True)
|
||||
})], signature="o"),
|
||||
self.dbus.UInt32(90),
|
||||
self.dbus.UInt32(0),
|
||||
timeout=5,
|
||||
)
|
||||
)
|
||||
|
||||
def apply(self, entries, target):
|
||||
# Priority only. Both networks retain addresses, defaults and native
|
||||
# autoconnect. VPN transport routing is separately scoped to its mark.
|
||||
for index, e in enumerate(sorted(entries, key=lambda x: x["id"])):
|
||||
dev = self.dbus.Interface(self.obj(e["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if int(version) != e["version"] or str(settings["connection"]["uuid"]) != e["id"]:
|
||||
raise ValueError("Настройки сети изменились. Повторите выбор.")
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in settings and settings[family].get("method") not in (
|
||||
"disabled",
|
||||
"ignore",
|
||||
):
|
||||
settings[family]["route-metric"] = self.dbus.Int64(
|
||||
10 if e["id"] == target else 100 + index
|
||||
)
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
e.get('saved', {}).get('defaults', {}).get(family, False))
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
|
||||
def checkpoints(self):
|
||||
return {str(p) for p in self.props(ROOT, SERVICE)["Checkpoints"]}
|
||||
|
||||
def rollback(self, checkpoint):
|
||||
result = self.manager().CheckpointRollback(self.dbus.ObjectPath(checkpoint), timeout=15)
|
||||
if not result or any(int(status) != 0 for status in result.values()):
|
||||
raise ValueError("Борт не подтвердил восстановление всех сетевых интерфейсов.")
|
||||
|
||||
def confirm(self, checkpoint):
|
||||
self.manager().CheckpointDestroy(self.dbus.ObjectPath(checkpoint), timeout=5)
|
||||
|
||||
def restore_metrics(self, entries):
|
||||
# Restore only owned metrics on the same live UUID; missing hardware is
|
||||
# allowed. Saved profiles/passwords and foreign reconfiguration are untouched.
|
||||
live = {str(p): self.props(p, DEVICE) for p in self.props(ROOT, SERVICE)["Devices"]}
|
||||
for e in entries:
|
||||
props = live.get(e["path"], {})
|
||||
if props.get("Interface") != e["interface"] or int(props.get("State", 0)) != 100:
|
||||
continue
|
||||
dev = self.dbus.Interface(self.obj(e["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) != e["id"]:
|
||||
continue
|
||||
for family, metric in e["metrics"].items():
|
||||
if family in settings and settings[family].get("method") not in (
|
||||
"disabled",
|
||||
"ignore",
|
||||
):
|
||||
current = int(settings[family].get("route-metric", -1))
|
||||
if current not in {10, *range(100, 116), metric}:
|
||||
raise ValueError("Приоритет сети изменён другим владельцем.")
|
||||
settings[family]["route-metric"] = self.dbus.Int64(metric)
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
e.get("defaults", {}).get(family, False)
|
||||
)
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
|
||||
def release_reserves(self, entries, target, resume_wifi=True):
|
||||
"""End temporary path isolation; restore normal NM fallback immediately."""
|
||||
saved = self.profile_preferences()
|
||||
for entry in entries:
|
||||
if entry["id"] == target:
|
||||
continue
|
||||
profile = saved.get(entry["id"])
|
||||
if profile is None:
|
||||
continue
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
if not self.same_device(entry, entry["path"], props):
|
||||
raise ValueError("Сетевой интерфейс изменился во время переключения.")
|
||||
if int(props["State"]) == 100:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) != entry["id"]:
|
||||
raise ValueError("Подключение изменено средствами Ubuntu.")
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in settings:
|
||||
settings[family]["never-default"] = self.dbus.Boolean(
|
||||
profile["saved"]["defaults"][family]
|
||||
)
|
||||
settings[family]["route-metric"] = self.dbus.Int64(
|
||||
profile["saved"]["metrics"][family]
|
||||
)
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
elif resume_wifi and entry["kind"] == "wifi" and profile["saved"]["autoconnect"]:
|
||||
# Disconnect() temporarily inhibits autoconnect. Release only
|
||||
# the Wi-Fi reserve that this transaction disconnected.
|
||||
self.dbus.Interface(self.obj(entry["path"]), "org.freedesktop.DBus.Properties").Set(
|
||||
DEVICE, "Autoconnect", self.dbus.Boolean(True), timeout=5
|
||||
)
|
||||
|
||||
def resume_autoconnect(self, entries):
|
||||
profiles = self.profile_preferences()
|
||||
devices = {str(p) for p in self.props(ROOT, SERVICE)["Devices"]}
|
||||
for entry in entries:
|
||||
if entry["path"] not in devices:
|
||||
continue # A replugged device has a new native autoconnect state.
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
profile = profiles.get(entry["id"], {})
|
||||
if (
|
||||
not self.same_device(entry, entry["path"], props)
|
||||
or not profile.get("saved", {}).get("autoconnect")
|
||||
or int(props["State"]) >= 40
|
||||
or not props.get("Managed")
|
||||
):
|
||||
continue
|
||||
self.dbus.Interface(self.obj(entry["path"]), "org.freedesktop.DBus.Properties").Set(
|
||||
DEVICE, "Autoconnect", self.dbus.Boolean(True), timeout=5
|
||||
)
|
||||
|
||||
def prefer_observed(self, entries, target, profiles):
|
||||
"""Latch a proven NM failover using metrics only; keep all reserves."""
|
||||
try:
|
||||
self.persist_choice(profiles, target)
|
||||
for entry in entries:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if (
|
||||
int(version) != entry["version"]
|
||||
or str(settings["connection"]["uuid"]) != entry["id"]
|
||||
):
|
||||
raise ValueError("Подключение изменено средствами Ubuntu.")
|
||||
pref = next(e["planned"] for e in profiles if e["id"] == entry["id"])
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if (family in settings
|
||||
and settings[family].get('method') not in ('disabled', 'ignore')):
|
||||
settings[family]["route-metric"] = self.dbus.Int64(pref["metrics"][family])
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
except Exception:
|
||||
self.restore_profiles(profiles)
|
||||
self.restore_metrics(entries)
|
||||
raise
|
||||
return profiles
|
||||
|
||||
def reserves(self, baseline):
|
||||
result = []
|
||||
for path in self.props(ROOT, SERVICE)["Devices"]:
|
||||
props = self.props(path, DEVICE)
|
||||
if int(props["DeviceType"]) not in (1, 2) or not props["Managed"]:
|
||||
continue
|
||||
for connection in props.get("AvailableConnections", []):
|
||||
settings = self.dbus.Interface(
|
||||
self.obj(connection), SERVICE + ".Settings.Connection"
|
||||
).GetSettings(timeout=5)
|
||||
identity = str(settings["connection"]["uuid"])
|
||||
old = next((e for e in baseline if e["id"] == identity), None)
|
||||
if old and self.same_device(old, path, props):
|
||||
result.append(
|
||||
{
|
||||
**old,
|
||||
'verified': False,
|
||||
'active': False,
|
||||
'available': True,
|
||||
"path": str(path),
|
||||
"interface": str(props["Interface"]),
|
||||
"connection": str(connection),
|
||||
"hardware": self.device_identity(path, props),
|
||||
"saved": self.preference(settings),
|
||||
"metrics": self.preference(settings)["metrics"],
|
||||
"defaults": self.preference(settings)["defaults"],
|
||||
}
|
||||
)
|
||||
return result
|
||||
|
||||
def locally_changed(self, entries, target):
|
||||
"""An Ubuntu disconnect/profile edit wins over our pending operation."""
|
||||
profiles = self.profile_preferences()
|
||||
for entry in entries:
|
||||
current = profiles.get(entry['id'])
|
||||
if current and entry.get('planned') and current['saved'] != entry['planned']:
|
||||
return True
|
||||
for path in self.props(ROOT, SERVICE)['Devices']:
|
||||
p = self.props(path, DEVICE)
|
||||
if str(p.get('Interface')) != target:
|
||||
continue
|
||||
# USER_REQUESTED is different from carrier/DHCP loss. A disabled
|
||||
# device must remain disabled, even when a cable is still present.
|
||||
reason = p.get('StateReason', (0, 0))
|
||||
if int(p.get('State', 0)) != 100 and int(reason[1]) == 39:
|
||||
return True
|
||||
return False
|
||||
|
||||
def activate(self, entry):
|
||||
props = self.props(entry["path"], DEVICE)
|
||||
if str(props["Interface"]) != entry["interface"]:
|
||||
raise ValueError("Сетевой интерфейс изменился.")
|
||||
if int(props["State"]) == 100:
|
||||
dev = self.dbus.Interface(self.obj(entry["path"]), DEVICE)
|
||||
settings, version = dev.GetAppliedConnection(0, timeout=5)
|
||||
if str(settings["connection"]["uuid"]) == entry["id"]:
|
||||
changed = False
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if settings.get(family, {}).get("never-default"):
|
||||
settings[family]["never-default"] = self.dbus.Boolean(False)
|
||||
changed = True
|
||||
if changed:
|
||||
dev.Reapply(settings, version, self.dbus.UInt32(1), timeout=8)
|
||||
return
|
||||
if 40 <= int(props["State"]) < 100:
|
||||
return
|
||||
if time.monotonic() - self.activation_attempts.get(entry["id"], 0) < 20:
|
||||
return
|
||||
self.activation_attempts[entry["id"]] = time.monotonic()
|
||||
self.manager().ActivateConnection(
|
||||
self.dbus.ObjectPath(entry["connection"]),
|
||||
self.dbus.ObjectPath(entry["path"]),
|
||||
self.dbus.ObjectPath("/"),
|
||||
timeout=8,
|
||||
)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""Observe NM recovery; latch only a fresh, proven Core path. Never scan or disconnect."""
|
||||
|
||||
import secrets
|
||||
import time
|
||||
|
||||
TERMINAL = {"applied", "rolled_back", "superseded", "recovering"}
|
||||
|
||||
|
||||
class Observation:
|
||||
def restore_adoption(self):
|
||||
pending = (self.operation or {}).get("adoption")
|
||||
if not pending:
|
||||
return
|
||||
self.adapter.restore_profiles(pending["profiles"])
|
||||
if pending["epoch"] == self.adapter.epoch():
|
||||
self.adapter.restore_metrics(pending["entries"])
|
||||
self.operation.pop("adoption")
|
||||
self.save()
|
||||
|
||||
def observe(self):
|
||||
op = self.operation
|
||||
if not self.context or not self.path_adapter or (op and op["phase"] not in TERMINAL):
|
||||
return
|
||||
if op and op.get('profiles_pending'):
|
||||
return # Restoring profiles must complete before any recovery receipt.
|
||||
try:
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
candidates = sorted(state["candidates"], key=lambda e: e["id"] != state["current_id"])
|
||||
chosen, policy = None, None
|
||||
for candidate in candidates:
|
||||
if (op and not self.fallback_enabled() and not op.get('local_override')
|
||||
and candidate['id'] != self.watched_target()):
|
||||
continue
|
||||
proof = self.path_adapter.prepare(self.context["peer"], candidate["interface"])
|
||||
if self.path_adapter.evidence(proof):
|
||||
chosen, policy = candidate, proof
|
||||
break
|
||||
if chosen is None:
|
||||
self.observed_candidate = None
|
||||
return
|
||||
if (
|
||||
op and op["phase"] != "recovering" and chosen["id"] == self.watched_target()
|
||||
and op.get("proof_context") == self.context
|
||||
and op.get("watch_policy", op.get("policy")) == policy
|
||||
):
|
||||
self.observed_candidate = None
|
||||
return
|
||||
# Two separate authenticated Core replies, with a stable physical path.
|
||||
key = (chosen["id"], self.adapter.epoch(), str(self.context))
|
||||
pending = getattr(self, "observed_candidate", None)
|
||||
if not pending or pending[0] != key:
|
||||
self.observed_candidate = (key, self.clock())
|
||||
return
|
||||
if self.clock() - pending[1] < 10:
|
||||
return
|
||||
# A local operator owns later profile edits. We observe these without
|
||||
# rewriting them. Health/lease changes alone do not alter saved settings.
|
||||
owned = {e["id"]: e.get("planned") for e in (op or {}).get("profile_baseline", [])}
|
||||
current = self.adapter.profile_preferences()
|
||||
foreign = bool((op or {}).get("local_override")) or any(
|
||||
identity in current and current[identity]["saved"] != expected
|
||||
for identity, expected in owned.items() if expected is not None
|
||||
)
|
||||
profiles = []
|
||||
# A recovered exchange on the same physical channel requires no
|
||||
# NetworkManager reapply (which can renew DHCP and change addresses).
|
||||
if op and owned and not foreign and chosen['id'] != self.watched_target():
|
||||
affected = {e["id"]: e for e in op["profile_baseline"] if e["id"] in current}
|
||||
affected.update({e["id"]: e for e in state["candidates"]})
|
||||
profiles = self.adapter.snapshot_profiles(list(affected.values()), chosen["id"])
|
||||
for entry in profiles:
|
||||
entry["planned"]["autoconnect"] = entry["saved"]["autoconnect"]
|
||||
op["adoption"] = dict(
|
||||
profiles=profiles, entries=state["candidates"], epoch=self.adapter.epoch()
|
||||
)
|
||||
self.save()
|
||||
try:
|
||||
self.adapter.prefer_observed(state["candidates"], chosen["id"], profiles)
|
||||
except Exception:
|
||||
self.restore_adoption()
|
||||
raise
|
||||
op.pop("adoption")
|
||||
if op is None:
|
||||
self.operation = op = dict(
|
||||
network_policy="native-fallback-v2",
|
||||
id=secrets.token_hex(16), binding=self.context["binding"],
|
||||
target=chosen["id"], previous=chosen["id"], baseline=state["candidates"],
|
||||
policy=policy, known=state["candidates"], profile_baseline=[
|
||||
dict(e, planned=e["saved"]) for e in state["candidates"]
|
||||
],
|
||||
)
|
||||
if op.get('phase') == 'recovering':
|
||||
reason = op.get('recovery_reason', 'automatic')
|
||||
previous = op['target'] if reason == 'manual_rollback' else self.watched_target()
|
||||
old = next((e for e in self.known() if e['id'] == previous), None)
|
||||
if old and (previous != chosen['id'] or reason == 'manual_rollback'):
|
||||
event = dict(id=secrets.token_hex(16), at=time.time(),
|
||||
kind=('manual_rollback' if reason == 'manual_rollback'
|
||||
else 'fallback'),
|
||||
source=old['kind'], target=chosen['kind'])
|
||||
op['events'] = [*op.get('events', []), event][-8:]
|
||||
op.update(
|
||||
network_policy="native-fallback-v2",
|
||||
phase=('rolled_back' if op.get('phase') == 'recovering'
|
||||
and chosen['id'] == op['previous'] else 'superseded'),
|
||||
watch_target=chosen["id"], watch_policy=policy,
|
||||
proof_context=self.context.copy(),
|
||||
message="Связь восстановлена. Используется текущее подключение.",
|
||||
)
|
||||
if profiles:
|
||||
op["profile_baseline"] = profiles
|
||||
elif foreign:
|
||||
op["profile_baseline"] = [] # Do not resume ownership after a local edit.
|
||||
if not foreign:
|
||||
self.select_path(policy)
|
||||
op.pop('recovery_tried', None)
|
||||
op.pop('recovery_attempt_at', None)
|
||||
self.path_ok = True
|
||||
self.observed_candidate = None
|
||||
self.save()
|
||||
except Exception:
|
||||
self.observed_candidate = None
|
||||
# Never turn a failed observation into a network operation.
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Saved station-profile policy, scoped to an explicit manual transaction."""
|
||||
|
||||
import subprocess
|
||||
|
||||
SERVICE = "org.freedesktop.NetworkManager"
|
||||
|
||||
|
||||
def choice(entry, target, index):
|
||||
"""Preference is a route priority, never a ban on another connection."""
|
||||
saved = entry["saved"]
|
||||
return dict(
|
||||
autoconnect=True if entry["id"] == target else saved.get("autoconnect", True),
|
||||
metrics={f: (saved["metrics"][f] if f in entry.get("inactive_families", ())
|
||||
else 10 if entry["id"] == target else 100 + index)
|
||||
for f in ("ipv4", "ipv6")},
|
||||
defaults=dict(saved.get("defaults", {"ipv4": False, "ipv6": False})),
|
||||
)
|
||||
|
||||
|
||||
class Preferences:
|
||||
def profile_preferences(self):
|
||||
settings = self.dbus.Interface(
|
||||
self.obj("/org/freedesktop/NetworkManager/Settings"), SERVICE + ".Settings"
|
||||
)
|
||||
paths = settings.ListConnections(timeout=5)
|
||||
if len(paths) > 128:
|
||||
raise ValueError("Слишком много сетевых профилей.")
|
||||
result = {}
|
||||
for path in paths:
|
||||
data = self.saved(path)
|
||||
connection, radio = data["connection"], data.get("802-11-wireless", {})
|
||||
station = (
|
||||
connection.get("type") == "802-11-wireless"
|
||||
and radio.get("mode", "infrastructure") == "infrastructure"
|
||||
and not connection.get("master")
|
||||
and not connection.get("controller")
|
||||
and data.get("ipv4", {}).get("method") != "shared"
|
||||
)
|
||||
identity = str(connection["uuid"])
|
||||
result[identity] = dict(
|
||||
id=identity,
|
||||
connection=str(path),
|
||||
kind="wifi" if station else "other",
|
||||
saved=self.preference(data),
|
||||
inactive_families=[f for f in ('ipv4', 'ipv6')
|
||||
if data.get(f, {}).get('method') in ('disabled', 'ignore')],
|
||||
)
|
||||
return result
|
||||
|
||||
def snapshot_profiles(self, entries, target):
|
||||
# Only admitted uplinks participate. Inactive Wi-Fi profiles, local LANs,
|
||||
# VPNs, passwords and the operator's autoconnect settings stay untouched.
|
||||
profiles = self.profile_preferences()
|
||||
result = {}
|
||||
for entry in entries:
|
||||
if entry["id"] not in profiles:
|
||||
raise ValueError("Сетевой профиль изменился. Повторите выбор.")
|
||||
result[entry["id"]] = {
|
||||
**profiles[entry["id"]],
|
||||
"kind": entry["kind"],
|
||||
}
|
||||
values = sorted(result.values(), key=lambda e: e["id"])
|
||||
for index, entry in enumerate(values):
|
||||
entry["planned"] = choice(entry, target, index)
|
||||
return values
|
||||
|
||||
def set_preference(self, entry, value):
|
||||
args = [
|
||||
"/usr/bin/nmcli",
|
||||
"--wait",
|
||||
"8",
|
||||
"connection",
|
||||
"modify",
|
||||
"uuid",
|
||||
entry["id"],
|
||||
"connection.autoconnect",
|
||||
"yes" if value["autoconnect"] else "no",
|
||||
]
|
||||
for family in ("ipv4", "ipv6"):
|
||||
if family in entry.get('inactive_families', ()):
|
||||
continue
|
||||
args += [
|
||||
family + ".route-metric",
|
||||
str(value["metrics"][family]),
|
||||
family + ".never-default",
|
||||
"yes" if value["defaults"][family] else "no",
|
||||
]
|
||||
subprocess.run(args, check=True, capture_output=True, timeout=10)
|
||||
|
||||
def persist_choice(self, entries, target):
|
||||
current = self.profile_preferences()
|
||||
for entry in entries:
|
||||
if current.get(entry["id"], {}).get("saved") != entry["saved"]:
|
||||
raise ValueError("Сохранённые настройки сети изменились. Возвращаем прежнее.")
|
||||
for index, entry in enumerate(entries):
|
||||
self.set_preference(entry, entry.get("planned") or choice(entry, target, index))
|
||||
|
||||
def restore_profiles(self, entries):
|
||||
current, errors = self.profile_preferences(), []
|
||||
for entry in entries:
|
||||
value = current.get(entry["id"], {}).get("saved")
|
||||
if value is None or value == entry.get("saved"):
|
||||
continue # Deleted profiles are not recreated; unchanged ones need no write.
|
||||
if "planned" in entry and value != entry["planned"]:
|
||||
errors.append(entry["id"])
|
||||
continue # Preserve concurrent edits by another owner.
|
||||
try:
|
||||
self.set_preference(entry, entry["saved"])
|
||||
except Exception:
|
||||
errors.append(entry["id"])
|
||||
if errors:
|
||||
raise ValueError("Не все сохранённые настройки сети восстановлены.")
|
||||
@@ -0,0 +1,55 @@
|
||||
"""Bounded passive QUIC path proof. No probes or persistent packet capture."""
|
||||
|
||||
import socket
|
||||
import struct
|
||||
import time
|
||||
|
||||
|
||||
def udp_header(data):
|
||||
if len(data) < 28 or data[0] >> 4 != 4 or data[9] != 17:
|
||||
return None
|
||||
size = (data[0] & 15) * 4
|
||||
if size < 20 or len(data) < size + 8 or struct.unpack_from("!H", data, 6)[0] & 0x3FFF:
|
||||
return None
|
||||
src, dst = socket.inet_ntoa(data[12:16]), socket.inet_ntoa(data[16:20])
|
||||
sport, dport, length = struct.unpack_from("!HHH", data, size)
|
||||
if length < 8:
|
||||
return None
|
||||
return src, dst, sport, dport
|
||||
|
||||
|
||||
def observe_udp(interface, sources, destinations, port, owned_ports):
|
||||
if not owned_ports or not destinations:
|
||||
return None
|
||||
try:
|
||||
# SOCK_DGRAM removes Ethernet framing. Peek the IPv4 length, then read
|
||||
# only IPv4+UDP headers;
|
||||
# no promiscuous mode, sending or disk output. Ignore payload bytes.
|
||||
with socket.socket(socket.AF_PACKET, socket.SOCK_DGRAM, socket.htons(0x0003)) as capture:
|
||||
capture.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16384)
|
||||
capture.bind((interface, 0))
|
||||
deadline = time.monotonic() + 0.6
|
||||
for _ in range(512):
|
||||
remaining = deadline - time.monotonic()
|
||||
if remaining <= 0:
|
||||
break
|
||||
capture.settimeout(remaining)
|
||||
prefix, _ = capture.recvfrom(20, socket.MSG_PEEK)
|
||||
header_size = (prefix[0] & 15) * 4 if prefix and prefix[0] >> 4 == 4 else 20
|
||||
data, address = capture.recvfrom(min(max(header_size, 20), 60) + 8)
|
||||
if address[1] != 0x0800 or address[2] != socket.PACKET_OUTGOING:
|
||||
continue
|
||||
header = udp_header(data)
|
||||
if header is None:
|
||||
continue
|
||||
src, dst, sport, dport = header
|
||||
if (
|
||||
src in sources
|
||||
and dst in destinations
|
||||
and sport in owned_ports
|
||||
and dport == port
|
||||
):
|
||||
return src, dst
|
||||
except (OSError, AttributeError):
|
||||
pass
|
||||
return None
|
||||
@@ -0,0 +1,565 @@
|
||||
"""Bounded manual selection and observation of native NetworkManager recovery."""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
from .evidence import Evidence
|
||||
from .fallback import FallbackPolicy
|
||||
from .netbird_path import private_peer
|
||||
from .observation import Observation
|
||||
from .transport_route import RouteNotReady
|
||||
|
||||
IDENTITY = re.compile(r"^[a-f0-9]{32}$")
|
||||
BUSY = {"applying", "verifying", "rolling_back"}
|
||||
|
||||
|
||||
class Controller(Observation, FallbackPolicy, Evidence):
|
||||
def __init__(self, root: Path, adapter, clock=time.monotonic, path_adapter=None):
|
||||
self.root, self.adapter, self.clock, self.path_adapter = root, adapter, clock, path_adapter
|
||||
self.wall_clock = time.time if clock is time.monotonic else clock
|
||||
self.context = None
|
||||
self.helper_instance = secrets.token_hex(16)
|
||||
self.last_core = 0
|
||||
self.last_probe = 0
|
||||
self.path_ok = False
|
||||
self.path_failed_since = None
|
||||
self.transport_ready = False
|
||||
root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
self.path = root / "operation.json"
|
||||
self.operation = json.loads(self.path.read_text()) if self.path.exists() else None
|
||||
self.load_fallback()
|
||||
self.restore_adoption()
|
||||
if (
|
||||
self.operation
|
||||
and self.operation["phase"] == "applied"
|
||||
and "policy" not in self.operation
|
||||
):
|
||||
self.operation.update(
|
||||
phase="superseded", message="Повторите выбор подключения для проверки пути к Core."
|
||||
)
|
||||
self.save()
|
||||
if self.operation and self.operation["phase"] in BUSY:
|
||||
self.rollback("Переключение прервано. Возвращаем прежнее подключение.")
|
||||
if self.operation and self.operation['phase'] == 'recovering':
|
||||
# Monotonic deadlines are local to this boot, not durable leases.
|
||||
self.operation.pop('recovery_attempt_at', None)
|
||||
self.operation.pop('recovery_tried', None)
|
||||
self.save()
|
||||
op = self.operation or {}
|
||||
policy = op.get('watch_policy') or op.get('policy')
|
||||
if (policy and op.get('phase') in ('applied', 'rolled_back', 'superseded')
|
||||
and not op.get('local_override')):
|
||||
try:
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
op['local_override'] = True
|
||||
self.path_adapter.release()
|
||||
self.save()
|
||||
else:
|
||||
# A service/package restart must not abandon a healthy chosen
|
||||
# transport merely because NM has another unmarked default.
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
except Exception:
|
||||
self.transport_ready = False
|
||||
elif self.path_adapter and (not policy or op.get('local_override')):
|
||||
self.path_adapter.release()
|
||||
self.retain_path()
|
||||
|
||||
def save(self):
|
||||
self.operation['fallback'] = dict(self.fallback_setting)
|
||||
self.record_transition()
|
||||
path = self.path.with_suffix(".tmp")
|
||||
with path.open("w", encoding="utf8") as stream:
|
||||
os.chmod(path, 0o600)
|
||||
json.dump(self.operation, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
path.replace(self.path)
|
||||
fd = os.open(self.root, os.O_RDONLY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
def inventory(self):
|
||||
catalog = self.known()
|
||||
state = self.adapter.inspect(known=catalog)
|
||||
active = {e["id"] for e in state["candidates"]}
|
||||
state["candidates"] += [e for e in self.adapter.reserves(catalog) if e["id"] not in active]
|
||||
state["revision"] = hashlib.sha256(
|
||||
json.dumps([state["revision"], state["candidates"]], sort_keys=True).encode()
|
||||
).hexdigest()
|
||||
return state
|
||||
|
||||
def known(self):
|
||||
op = self.operation or {}
|
||||
return op.get("known", op.get("baseline", []))
|
||||
|
||||
def finish_apply(self):
|
||||
op = self.operation
|
||||
entry = next(e for e in self.inventory()["candidates"] if e["id"] == op["target"])
|
||||
op["apply_step"] = "candidate_readiness"
|
||||
self.adapter.activate(entry)
|
||||
state = self.adapter.inspect(known=op["baseline"])
|
||||
target = next(
|
||||
(
|
||||
e
|
||||
for e in state["candidates"]
|
||||
if e["id"] == self.operation["target"] and e["verified"]
|
||||
),
|
||||
None,
|
||||
)
|
||||
if not target:
|
||||
return
|
||||
if not op.get('metrics_applied'):
|
||||
op['apply_step'] = 'network_preferences'
|
||||
self.adapter.apply(state["candidates"], target["id"])
|
||||
op['metrics_applied'] = True
|
||||
op.update(wait_reason='network_preferences_pending',
|
||||
message='Ожидаем готовность подключения.')
|
||||
# NM returns before DHCP/ACD finishes republishing addresses/routes.
|
||||
# Advance on the next normal watchdog sample, never in the same call.
|
||||
self.last_probe = self.clock()
|
||||
self.save()
|
||||
return
|
||||
op['apply_step'] = 'transport_route'
|
||||
try:
|
||||
self.select_path(op["policy"])
|
||||
except RouteNotReady:
|
||||
# Reapply returns before NM republishes DHCP routes. Do not reapply
|
||||
# again on every poll: it would keep restarting the same lease.
|
||||
op.update(wait_reason='gateway_pending', message='Ожидаем готовность подключения.')
|
||||
self.save()
|
||||
return
|
||||
op.pop('wait_reason', None)
|
||||
self.transport_ready = True
|
||||
self.operation.update(phase="verifying", message="Проверяем путь связи с Core.")
|
||||
self.save()
|
||||
|
||||
def watched_target(self):
|
||||
return self.operation.get("watch_target", self.operation["target"])
|
||||
|
||||
def proven_current(self, state):
|
||||
"""Resolve the rollback baseline from the Core transport, not NM's default."""
|
||||
if not self.context or self.clock() - self.last_core > 20:
|
||||
raise ValueError("Нет свежего подтверждения Core.")
|
||||
op = self.operation
|
||||
if op and not op.get('local_override') and op.get('proof_context') == self.context:
|
||||
identity = self.watched_target()
|
||||
else:
|
||||
identity = state['current_id']
|
||||
chosen = next((e for e in state['candidates'] if e['id'] == identity), None)
|
||||
if chosen:
|
||||
policy = self.path_adapter.prepare(self.context['peer'], chosen['interface'])
|
||||
if self.path_adapter.evidence(policy):
|
||||
return chosen, policy
|
||||
raise ValueError("Текущий путь связи с Core не подтверждён. "
|
||||
"Повторите после восстановления связи.")
|
||||
|
||||
def probe(self):
|
||||
op = self.operation
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
chosen = next((e for e in state["candidates"] if e["id"] == self.watched_target()), None)
|
||||
return bool(
|
||||
op.get("network_policy") == "native-fallback-v2"
|
||||
and (op["phase"] not in BUSY or op["epoch"] == self.adapter.epoch())
|
||||
and chosen
|
||||
and (chosen["verified"] or op["phase"] not in BUSY)
|
||||
and op.get("proof_context") == self.context
|
||||
and self.path_adapter.evidence(op.get("watch_policy") or op.get("policy", {}))
|
||||
)
|
||||
|
||||
def tick(self):
|
||||
op, now = self.operation, self.clock()
|
||||
if not op:
|
||||
return
|
||||
if op["phase"] in BUSY and now >= op["deadline"]:
|
||||
self.rollback("Новое подключение не подтверждено. Возвращаем прежнее.")
|
||||
if now - self.last_probe < 5:
|
||||
return
|
||||
self.last_probe = now
|
||||
if op["phase"] == "applying":
|
||||
try:
|
||||
self.finish_apply()
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Подключение не выполнено. Возвращаем прежнее.")
|
||||
if op["phase"] in ("verifying", "applied", "superseded") or (
|
||||
op["phase"] == "rolled_back" and op.get("watch_policy")
|
||||
):
|
||||
try:
|
||||
if op['phase'] not in BUSY:
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
self.path_adapter.release()
|
||||
op['local_override'] = True
|
||||
self.save()
|
||||
elif (not self.transport_ready and not op.get('local_override')
|
||||
and op.get('network_policy') == 'native-fallback-v2'
|
||||
and self.context):
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
selected = next((e for e in state['candidates']
|
||||
if e['id'] == self.watched_target()
|
||||
and e['verified']), None)
|
||||
if selected and selected['id'] == state['current_id']:
|
||||
policy = self.path_adapter.prepare(self.context['peer'],
|
||||
selected['interface'])
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
self.retain_path()
|
||||
self.path_ok = self.probe()
|
||||
except Exception:
|
||||
self.path_ok = False
|
||||
if op["phase"] not in BUSY:
|
||||
if self.path_ok and now - self.last_core <= 35:
|
||||
self.path_failed_since = None
|
||||
else:
|
||||
if self.path_failed_since is None:
|
||||
self.path_failed_since = now
|
||||
if now - self.path_failed_since >= 15 and self.fallback_enabled():
|
||||
self.path_adapter.release()
|
||||
self.transport_ready = False
|
||||
self.release_paused()
|
||||
if not op.get('local_override'):
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(
|
||||
op.get('profile_baseline', []), policy.get('interface', '')
|
||||
):
|
||||
op['local_override'] = True
|
||||
self.save()
|
||||
else:
|
||||
op.update(phase='recovering', recovery_started=now,
|
||||
recovery_reason='automatic',
|
||||
message='Восстанавливаем связь с Core.')
|
||||
self.save()
|
||||
self.recover()
|
||||
elif op["phase"] == "recovering":
|
||||
self.recover()
|
||||
|
||||
def status(self):
|
||||
self.tick()
|
||||
try:
|
||||
result = self.adapter.public(self.inventory())
|
||||
except Exception as error:
|
||||
result = dict(
|
||||
supported=False,
|
||||
reason=str(error) if isinstance(error, ValueError) else "Сведения сети недоступны.",
|
||||
candidates=[],
|
||||
current_id="",
|
||||
revision="",
|
||||
)
|
||||
result["protocol"] = 2
|
||||
result['diagnostic'] = self.local_evidence(result)
|
||||
result['fallback'] = dict(self.fallback_setting)
|
||||
result['events'] = (self.operation or {}).get('events', [])[-8:]
|
||||
if (self.operation and not self.fallback_enabled()
|
||||
and not self.operation.get('local_override')):
|
||||
result['current_id'] = self.watched_target()
|
||||
result["path_verified"] = bool(
|
||||
self.operation
|
||||
and self.operation["phase"] in ("applied", "rolled_back", "superseded")
|
||||
and self.path_ok
|
||||
and self.clock() - self.last_core <= 35
|
||||
)
|
||||
if result['path_verified']:
|
||||
result['current_id'] = self.watched_target()
|
||||
if not self.context or self.context["provider"] != "netbird" or not self.path_adapter:
|
||||
result.update(
|
||||
supported=False, reason="Выбор пути доступен для подключения Core через NetBird."
|
||||
)
|
||||
# No private journal/profile snapshots cross the root IPC boundary.
|
||||
result["operation"] = {
|
||||
k: v
|
||||
for k, v in (self.operation or {}).items()
|
||||
if k in {"id", "binding", "target", "previous", "nonce", "phase", "deadline", "message"}
|
||||
} or None
|
||||
if result["operation"]:
|
||||
result["operation"]["path_verified"] = self.path_ok and self.operation["phase"] in (
|
||||
"verifying",
|
||||
"applied",
|
||||
)
|
||||
return result
|
||||
|
||||
def heartbeat(self, body):
|
||||
binding = body["binding"]
|
||||
if (
|
||||
not isinstance(binding, str)
|
||||
or not 1 <= len(binding) <= 160
|
||||
or body["provider"] not in ("netbird", "wireguard", "tailscale")
|
||||
):
|
||||
raise ValueError("Некорректная привязка Core.")
|
||||
private_peer(body["peer"])
|
||||
context = {k: body[k] for k in ("binding", "provider", "peer")}
|
||||
if (
|
||||
self.operation
|
||||
and self.operation["phase"] in BUSY
|
||||
and self.context
|
||||
and self.context != context
|
||||
):
|
||||
self.rollback("Привязка Core изменилась. Снято ограничение сетевого пути.")
|
||||
changed = self.context != context
|
||||
if changed or self.clock() - self.last_core > 35:
|
||||
self.observed_candidate = None
|
||||
self.context, self.last_core = context, self.clock()
|
||||
if changed and self.operation and self.operation["phase"] in (
|
||||
"applied", "rolled_back", "superseded"
|
||||
):
|
||||
self.path_ok = False
|
||||
self.operation.pop("proof_context", None)
|
||||
try:
|
||||
chosen = next(
|
||||
e for e in self.inventory()["candidates"] if e["id"] == self.watched_target()
|
||||
)
|
||||
self.operation["watch_policy"] = self.path_adapter.prepare(
|
||||
context["peer"], chosen["interface"]
|
||||
)
|
||||
self.operation["proof_context"] = context.copy()
|
||||
self.last_probe = 0
|
||||
except Exception:
|
||||
pass
|
||||
self.save()
|
||||
self.observe()
|
||||
return self.status()
|
||||
|
||||
def stage(self, body):
|
||||
identity, binding = body["id"], body["binding"]
|
||||
if (
|
||||
not IDENTITY.fullmatch(identity)
|
||||
or not self.context
|
||||
or self.context["binding"] != binding
|
||||
or self.context["provider"] != "netbird"
|
||||
or self.clock() - self.last_core > 20
|
||||
):
|
||||
raise ValueError("Нет свежего подтверждения привязки Core.")
|
||||
if (
|
||||
not isinstance(body["expires_at"], int)
|
||||
or not self.wall_clock() < body["expires_at"] <= self.wall_clock() + 60
|
||||
):
|
||||
raise ValueError("Команда переключения устарела.")
|
||||
self.tick()
|
||||
if self.operation and self.operation["id"] == identity:
|
||||
if self.operation["binding"] != binding or self.operation["target"] != body["target"]:
|
||||
raise ValueError("Конфликт команды переключения.")
|
||||
return self.status()
|
||||
if self.operation and self.operation["phase"] in BUSY | {"rollback_failed", "recovering"}:
|
||||
raise ValueError("Дождитесь завершения восстановления связи.")
|
||||
state = self.inventory()
|
||||
if state["revision"] != body["revision"]:
|
||||
raise ValueError("Подключения изменились. Обновите выбор.")
|
||||
target = next(
|
||||
(e for e in state["candidates"] if e["id"] == body["target"]
|
||||
and (e.get("available") or e["verified"])), None
|
||||
)
|
||||
if target is None:
|
||||
raise ValueError("Борт не подтвердил доступность выбранного подключения.")
|
||||
previous, previous_policy = self.proven_current(state)
|
||||
known = {e["id"]: e for e in self.known()}
|
||||
for entry in state["candidates"]:
|
||||
known[entry["id"]] = {
|
||||
**entry,
|
||||
"verified": entry["verified"] or known.get(entry["id"], {}).get("verified", False),
|
||||
}
|
||||
if len(known) > 64:
|
||||
raise ValueError("Слишком много сохранённых подключений.")
|
||||
profiles = self.adapter.snapshot_profiles(state["candidates"], target["id"])
|
||||
policy = self.path_adapter.prepare(self.context["peer"], target["interface"])
|
||||
checkpoint = self.adapter.checkpoint(state["candidates"])
|
||||
self.observed_candidate = None
|
||||
self.operation = dict(
|
||||
network_policy="native-fallback-v2",
|
||||
id=identity,
|
||||
binding=binding,
|
||||
target=target["id"],
|
||||
previous=previous['id'],
|
||||
previous_policy=previous_policy,
|
||||
checkpoint=checkpoint,
|
||||
epoch=self.adapter.epoch(),
|
||||
nonce=secrets.token_hex(16),
|
||||
phase="applying",
|
||||
deadline=int(self.clock()) + 80,
|
||||
message="Проверяем путь связи с Core.",
|
||||
policy=policy,
|
||||
proof_context=self.context.copy(),
|
||||
baseline=state["candidates"],
|
||||
profile_baseline=profiles,
|
||||
known=list(known.values()),
|
||||
events=(self.operation or {}).get('events', [])[-8:],
|
||||
diagnostic_events=(self.operation or {}).get('diagnostic_events', [])[-16:],
|
||||
diagnostic_sequence=(self.operation or {}).get('diagnostic_sequence', 0),
|
||||
)
|
||||
self.path_ok = False
|
||||
self.save()
|
||||
try:
|
||||
self.finish_apply()
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Переключение не завершено. Восстанавливаем прежнее подключение.")
|
||||
return self.status()
|
||||
|
||||
def confirm(self, body):
|
||||
self.tick()
|
||||
op = self.operation
|
||||
if not op or any(body[k] != op[k] for k in ("id", "binding", "nonce")):
|
||||
raise ValueError("Подтверждение относится к другому переключению.")
|
||||
if op["phase"] == "applied":
|
||||
return self.status()
|
||||
if op["phase"] != "verifying":
|
||||
raise ValueError("Время подтверждения истекло.")
|
||||
if not self.probe():
|
||||
# A route change between report and acknowledgement cannot commit.
|
||||
self.path_ok = False
|
||||
return self.status()
|
||||
# Save only after the new physical path and authenticated Core reply agree.
|
||||
# The checkpoint and journal remain available if persistence is interrupted.
|
||||
op["profiles_pending"] = True
|
||||
self.save()
|
||||
try:
|
||||
self.adapter.persist_choice(op["profile_baseline"], op["target"])
|
||||
self.adapter.release_reserves(op["baseline"], op["target"], resume_wifi=False)
|
||||
if not self.probe():
|
||||
raise ValueError("Путь изменился после восстановления резервных подключений.")
|
||||
self.adapter.confirm(op["checkpoint"])
|
||||
except Exception as error:
|
||||
self.record_error(error)
|
||||
self.rollback("Не удалось сохранить выбор. Возвращаем прежнее подключение.")
|
||||
return self.status()
|
||||
op.pop("profiles_pending", None)
|
||||
op.update(phase="applied", message="Подключение выбрано.")
|
||||
self.path_ok, self.last_core = True, self.clock()
|
||||
self.save()
|
||||
return self.status()
|
||||
|
||||
def rollback(self, message):
|
||||
op = self.operation
|
||||
op["phase"] = "rolling_back"
|
||||
self.path_ok = False
|
||||
self.save()
|
||||
errors = []
|
||||
try:
|
||||
self.path_adapter.release()
|
||||
except Exception:
|
||||
errors.append("routes")
|
||||
if op.get("profiles_pending"):
|
||||
try:
|
||||
self.adapter.restore_profiles(op.get("profile_baseline", op["baseline"]))
|
||||
op.pop("profiles_pending", None)
|
||||
except Exception:
|
||||
errors.append("profiles")
|
||||
try:
|
||||
if op["epoch"] == self.adapter.epoch():
|
||||
if op["checkpoint"] in self.adapter.checkpoints():
|
||||
self.adapter.rollback(op["checkpoint"])
|
||||
if op.get("baseline"):
|
||||
self.adapter.restore_metrics(op["baseline"])
|
||||
except Exception:
|
||||
errors.append("routes")
|
||||
if "routes" in errors:
|
||||
op.update(
|
||||
phase="rollback_failed",
|
||||
message="Не удалось восстановить настройки сети. Требуется проверка борта.",
|
||||
)
|
||||
else:
|
||||
op.update(phase="recovering", message=message, recovery_started=self.clock(),
|
||||
recovery_reason='manual_rollback')
|
||||
# Restore the actual previous transport first in BOTH reserve modes.
|
||||
# NM checkpoint/metric restoration alone cannot restore a VPN fwmark path.
|
||||
previous = next(e for e in op['baseline'] if e['id'] == op['previous'])
|
||||
policy = op.get('previous_policy') or {
|
||||
**op['policy'], 'interface': previous['interface']}
|
||||
op.update(watch_target=previous['id'], watch_policy=policy)
|
||||
try:
|
||||
self.select_path(policy)
|
||||
self.transport_ready = True
|
||||
op.update(recovery_attempt_at=self.clock(), recovery_tried=[previous['id']])
|
||||
except Exception:
|
||||
self.transport_ready = False # Retry recovery; never report success here.
|
||||
for entry in op.get('profile_baseline', []):
|
||||
entry['planned'] = entry['saved']
|
||||
self.save()
|
||||
if "routes" not in errors:
|
||||
self.release_paused()
|
||||
self.recover()
|
||||
|
||||
def release_paused(self):
|
||||
op = self.operation or {}
|
||||
if op.get("paused_reserves"):
|
||||
try:
|
||||
self.adapter.resume_autoconnect(op["paused_reserves"])
|
||||
op.pop("paused_reserves")
|
||||
self.save()
|
||||
except Exception:
|
||||
pass # Retry the bounded release, never disconnect another network.
|
||||
|
||||
def recover(self):
|
||||
# Native NM owns association, DHCP and saved-network discovery. Try only
|
||||
# currently active, internet-checked channels, without disconnecting any
|
||||
# interface. No old success receipt is evidence for a recovery candidate.
|
||||
op, now = self.operation, self.clock()
|
||||
try:
|
||||
if op.get('profiles_pending'):
|
||||
self.adapter.restore_profiles(op.get('profile_baseline', []))
|
||||
op.pop('profiles_pending', None)
|
||||
self.save()
|
||||
policy = op.get('watch_policy') or op.get('policy', {})
|
||||
if self.adapter.locally_changed(op.get('profile_baseline', []),
|
||||
policy.get('interface', '')):
|
||||
self.path_adapter.release()
|
||||
op.update(local_override=True, phase='superseded',
|
||||
message='Подключение изменено средствами Ubuntu.')
|
||||
self.save()
|
||||
return
|
||||
if now - op.get('recovery_attempt_at', -60) < 60:
|
||||
return
|
||||
state = self.adapter.inspect(known=self.known())
|
||||
candidates = [e for e in state['candidates'] if e['verified']]
|
||||
if not self.fallback_enabled():
|
||||
self.retain_path()
|
||||
return
|
||||
# Let native route selection recover first. On a later attempt,
|
||||
# move to the next checked channel if Core is still unreachable.
|
||||
candidates.sort(key=lambda e: (e['id'] != state['current_id'], e['id']))
|
||||
if not candidates:
|
||||
self.path_adapter.release()
|
||||
return
|
||||
tried = op.get('recovery_tried', [])
|
||||
fresh = [e for e in candidates if e['id'] not in tried]
|
||||
if not fresh:
|
||||
tried, fresh = [], candidates
|
||||
chosen = fresh[0]
|
||||
proof = self.path_adapter.prepare(op['policy']['peer'], chosen['interface'])
|
||||
op.update(recovery_attempt_at=now, recovery_tried=[*tried, chosen['id']])
|
||||
self.save()
|
||||
if chosen['id'] != state['current_id']:
|
||||
self.adapter.apply(state['candidates'], chosen['id'])
|
||||
self.select_path(proof)
|
||||
except Exception:
|
||||
# A failed trial never tears down another network. Durable operation
|
||||
# remains recovering; the next bounded attempt can use native NM.
|
||||
if self.fallback_enabled():
|
||||
self.path_adapter.release()
|
||||
|
||||
|
||||
def dispatch(controller, body):
|
||||
shapes = {
|
||||
"status": {"action"},
|
||||
"heartbeat": {"action", "binding", "provider", "peer"},
|
||||
"stage": {"action", "id", "binding", "target", "revision", "expires_at"},
|
||||
"confirm": {"action", "id", "binding", "nonce"},
|
||||
"fallback": {"action", "id", "binding", "enabled", "revision", "expires_at"},
|
||||
}
|
||||
if (
|
||||
not isinstance(body, dict)
|
||||
or body.get("action") not in shapes
|
||||
or set(body) != shapes[body["action"]]
|
||||
):
|
||||
raise ValueError("Некорректная команда сетевой службы.")
|
||||
if body["action"] == "status":
|
||||
return controller.status()
|
||||
return getattr(controller, body["action"])(body)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""A reversible route for NetBird's existing socket mark, not a second network manager.
|
||||
|
||||
Only the qualified transport's outer packets use this table. LAN traffic, DHCP,
|
||||
Ubuntu's connections and other VPNs keep their own routing and autoconnect policy.
|
||||
An empty table falls through to native routes; it never blackholes recovery.
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
TABLE, PRIORITY, PROTOCOL = 51001, 5100, 242
|
||||
|
||||
|
||||
class RouteNotReady(ValueError):
|
||||
"""The selected connection is still publishing its DHCP default route."""
|
||||
|
||||
|
||||
class TransportRoute:
|
||||
def __init__(self, run, root=Path('/var/lib/mission-core-uplink')):
|
||||
self.run = run
|
||||
self.path = root / 'transport-route.json'
|
||||
|
||||
def ip(self, *args):
|
||||
return self.run('/usr/sbin/ip', '-4', *map(str, args))
|
||||
|
||||
def routes(self):
|
||||
# "table all" also works before our private table exists.
|
||||
return [r for r in json.loads(self.ip('-j', 'route', 'show', 'table', 'all'))
|
||||
if str(r.get('table')) == str(TABLE)]
|
||||
|
||||
def rules(self):
|
||||
return [r for r in json.loads(self.ip('-j', 'rule', 'show'))
|
||||
if r.get('priority') == PRIORITY or str(r.get('table')) == str(TABLE)]
|
||||
|
||||
@staticmethod
|
||||
def route_key(row):
|
||||
keys = ('dst', 'gateway', 'dev', 'prefsrc')
|
||||
if row.get('type') == 'unreachable':
|
||||
keys += ('type', 'metric')
|
||||
return {k: row[k] for k in keys if k in row}
|
||||
|
||||
def record(self, value):
|
||||
self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
temporary = self.path.with_suffix('.tmp')
|
||||
with temporary.open('w') as stream:
|
||||
os.chmod(temporary, 0o600)
|
||||
json.dump(value, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
temporary.replace(self.path)
|
||||
|
||||
def owned(self):
|
||||
if not self.path.exists():
|
||||
if self.routes() or self.rules():
|
||||
raise ValueError('Таблица пути Core занята другой настройкой сети.')
|
||||
return [], []
|
||||
record = json.loads(self.path.read_text())
|
||||
routes, rules = self.routes(), self.rules()
|
||||
for rule in rules:
|
||||
if not (rule.get('priority') == PRIORITY
|
||||
and str(rule.get('table')) == str(TABLE)
|
||||
and int(rule.get('fwmark', '0'), 0) == record['mark']
|
||||
and str(rule.get('protocol')) == str(PROTOCOL)
|
||||
and not rule.get('fwmask')):
|
||||
raise ValueError('Правило пути Core изменено другим владельцем.')
|
||||
for row in routes:
|
||||
if (str(row.get('protocol')) != str(PROTOCOL)
|
||||
or self.route_key(row) not in record['routes']):
|
||||
raise ValueError('Маршрут пути Core изменён другим владельцем.')
|
||||
return routes, rules
|
||||
|
||||
def change_route(self, action, row):
|
||||
args = ['route', action, 'table', TABLE]
|
||||
if row.get('type'):
|
||||
args.append(row['type'])
|
||||
args.append(row['dst'])
|
||||
if row.get('gateway'):
|
||||
args += ['via', row['gateway'], 'onlink']
|
||||
if row.get('dev'):
|
||||
args += ['dev', row['dev']]
|
||||
if row.get('metric') is not None:
|
||||
args += ['metric', row['metric']]
|
||||
if row.get('prefsrc'):
|
||||
args += ['src', row['prefsrc']]
|
||||
self.ip(*args, 'protocol', PROTOCOL)
|
||||
|
||||
def release(self):
|
||||
routes, rules = self.owned()
|
||||
if not self.path.exists():
|
||||
return
|
||||
record = json.loads(self.path.read_text())
|
||||
for _ in rules:
|
||||
self.ip('rule', 'del', 'priority', PRIORITY, 'fwmark', hex(record['mark']),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
for row in routes:
|
||||
try:
|
||||
self.change_route('del', self.route_key(row))
|
||||
except subprocess.CalledProcessError:
|
||||
# DHCP may remove an address and its owned route after the snapshot.
|
||||
# Only absence of this exact row makes deletion already complete.
|
||||
if any(self.route_key(live) == self.route_key(row) for live in self.routes()):
|
||||
raise
|
||||
self.path.unlink()
|
||||
|
||||
def select(self, policy):
|
||||
interface, mark = policy['interface'], policy['mark']
|
||||
main = json.loads(self.ip('-j', 'route', 'show', 'table', 'main'))
|
||||
defaults = [r for r in main if r.get('dst') == 'default' and r.get('dev') == interface]
|
||||
strict = policy.get('strict', False)
|
||||
if (len(defaults) != 1 or not defaults[0].get('gateway')) and not strict:
|
||||
raise RouteNotReady('У выбранного подключения нет однозначного шлюза.')
|
||||
routes = [self.route_key(r) for r in main if r.get('dev') == interface
|
||||
and r.get('scope') == 'link' and r.get('dst') != 'default']
|
||||
if len(defaults) == 1 and defaults[0].get('gateway'):
|
||||
routes.append(self.route_key(defaults[0]))
|
||||
if len(routes) > 32:
|
||||
raise ValueError('Слишком сложная маршрутизация выбранного подключения.')
|
||||
if strict:
|
||||
self.retain_selected(mark, routes)
|
||||
return
|
||||
self.release()
|
||||
self.record(dict(mark=mark, routes=routes)) # Undo is durable before the first write.
|
||||
try:
|
||||
for row in routes:
|
||||
self.change_route('add', row)
|
||||
self.ip('rule', 'add', 'priority', PRIORITY, 'fwmark', hex(mark),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
except Exception as error:
|
||||
self.release()
|
||||
if isinstance(error, subprocess.CalledProcessError):
|
||||
detail = (error.stderr or b'')
|
||||
if isinstance(detail, bytes):
|
||||
detail = detail.decode(errors='replace')
|
||||
if 'Invalid prefsrc address' in detail or 'Cannot find device' in detail:
|
||||
raise RouteNotReady('Адрес выбранного подключения обновляется.') from error
|
||||
raise
|
||||
|
||||
def retain_selected(self, mark, routes):
|
||||
# When fallback is disabled, a missing selected NIC must not fall through
|
||||
# to another default. Keep the guard while refreshing DHCP/kernel routes.
|
||||
guard = dict(dst='default', type='unreachable', metric=32760)
|
||||
desired = [*routes, guard]
|
||||
live, rules = self.owned()
|
||||
if rules and int(rules[0]['fwmark'], 0) != mark:
|
||||
raise ValueError('Метка транспорта изменилась. Повторите выбор подключения.')
|
||||
current = [self.route_key(row) for row in live]
|
||||
if len(current) == len(desired) and all(row in desired for row in current) and rules:
|
||||
return
|
||||
journal = current + [row for row in desired if row not in current]
|
||||
self.record(dict(mark=mark, routes=journal))
|
||||
if guard not in current:
|
||||
self.change_route('add', guard)
|
||||
if not rules:
|
||||
self.ip('rule', 'add', 'priority', PRIORITY, 'fwmark', hex(mark),
|
||||
'table', TABLE, 'protocol', PROTOCOL)
|
||||
for row in current:
|
||||
if row not in desired:
|
||||
self.change_route('del', row)
|
||||
for row in routes:
|
||||
if row not in current:
|
||||
self.change_route('add', row)
|
||||
self.record(dict(mark=mark, routes=desired))
|
||||
Reference in New Issue
Block a user