"""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("Не все сохранённые настройки сети восстановлены.")