#!/usr/bin/env python3
# summary: Read and change network connections.
"""starchaser network: read and change NetworkManager connection settings for Settings > Network.

    starchaser network radios                        Airplane mode and hotspot status
    starchaser network airplane on|off               turn wireless radios off or restore them
    starchaser network hotspot on|off                share the connection; on reads name and password as JSON on stdin
    starchaser network get                       connections, their settings and live addresses (JSON); also
                                                 routeOverlaps: a VPN offering a route to a network this computer is
                                                 on (the route guard keeps that traffic on the cable or Wi-Fi)
    starchaser network set [file|-] [--timeout N] change one connection (JSON below); with --timeout, put the
                                                 old settings back after N seconds unless confirmed
                                                 (a detached watchdog: survives Settings closing or the
                                                 network dropping)
    starchaser network confirm                   keep the change (JSON; ok false, exit 1, when it already went back)
    starchaser network revert                    put the previous settings back now (JSON; "already" when they were)
    starchaser network vpn up|down <uuid>        connect or disconnect a VPN, waiting up to 30 seconds (JSON result)
    starchaser network connect <uuid>           connect a saved wired connection (JSON result)
    starchaser network forget <uuid>             delete a saved connection (a Wi-Fi network out of range, say)
    starchaser network wifi-join [--hidden] [--password-stdin] [--] <ssid>
                                                 join a Wi-Fi network, saved for everyone. The password is one line on
                                                 stdin with --password-stdin (none without it: an open network or a
                                                 saved one), never on a command line or in the environment (sudo
                                                 --preserve-env writes the variables it keeps to the system journal);
                                                 --hidden for one that doesn't show its name. JSON {"ok", "why":
                                                 "" | "password" | "missing" | "other", "errors": plain words}. A failed
                                                 join deletes the profile it made, never one saved before (that one gets
                                                 the typed password in place of its old one once it works). 20 s at most

Change JSON: {"uuid": "...", "autoconnect": true,
              "ipv4": {"method": "auto|manual|disabled", "addresses": ["192.0.2.10/24"], "gateway": "192.0.2.1",
                       "dns": ["1.1.1.1"]},
              "ipv6": {"method": "auto|manual|disabled", "addresses": [], "gateway": "", "dns": []}}
"dns" non-empty with method auto = use these servers instead of the ones DHCP hands out.
Runs as the desktop user: NetworkManager's polkit policy lets the active session modify system connections.
"""
import contextlib
import fcntl
import ipaddress
import json
import os
import re
import selectors
import shutil
import subprocess
import sys
import time
import uuid as uuidlib
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams
safe_streams()

STATE = Path(os.environ.get("XDG_STATE_HOME", Path.home() / ".local/state")) / "starchaser"
PENDING = STATE / "network-pending.json"     # {"id", "uuid", "deadline", "previous": {key: value}}
LOCK = STATE / "network.lock"                # held by set, watchdog, confirm and revert: one change at a time
KEYS = ["connection.autoconnect", "connection.metered",
        "ipv4.method", "ipv4.addresses", "ipv4.gateway", "ipv4.dns", "ipv4.ignore-auto-dns",
        "ipv6.method", "ipv6.addresses", "ipv6.gateway", "ipv6.dns", "ipv6.ignore-auto-dns"]
WIFI_KEYS = ["802-11-wireless.cloned-mac-address"]
INFO = ["connection.id", "connection.uuid", "connection.type", "connection.interface-name", "connection.master",
        "802-11-wireless.ssid", "802-11-wireless-security.key-mgmt"]


def nm(*args, check=False) -> subprocess.CompletedProcess:
    return subprocess.run(["nmcli", *args], capture_output=True, text=True, timeout=30, check=check)


def unescape(v: str) -> str:
    return v.replace("\\:", ":").replace("\\\\", "\\")


def fields(out: str) -> dict:
    d = {}
    for line in out.splitlines():
        k, sep, v = line.partition(":")
        if sep:
            d.setdefault(k, unescape(v))
    return d


def multi(out: str, prefix: str) -> list:
    return [unescape(l.partition(":")[2]) for l in out.splitlines() if l.startswith(prefix)]


def split_list(v: str) -> list:
    return [x.strip() for x in v.split(",") if x.strip()]


def settings(uid: str) -> dict:
    r = nm("-t", "-f", ",".join(INFO + KEYS + WIFI_KEYS), "connection", "show", uid)
    # 802-11-wireless.* only exists on Wi-Fi profiles; ask again without it
    if r.returncode != 0:
        r = nm("-t", "-f", ",".join([k for k in INFO if not k.startswith("802")] + KEYS), "connection", "show", uid)
    return fields(r.stdout)


def device_info(dev: str) -> dict:
    out = nm("-t", "-f", "GENERAL.HWADDR,GENERAL.STATE,IP4.ADDRESS,IP4.GATEWAY,IP4.DNS,IP6.ADDRESS,IP6.GATEWAY",
             "device", "show", dev).stdout
    f = fields(out)
    def sysread(p):
        try:
            return Path(p).read_text().strip()
        except OSError:
            return ""
    speed = sysread(f"/sys/class/net/{dev}/speed")
    brif = Path(f"/sys/class/net/{dev}/brif")
    ports = sorted(x.name for x in brif.iterdir()) if brif.is_dir() else []
    return {"ports": ports, "mac": f.get("GENERAL.HWADDR", ""), "state": f.get("GENERAL.STATE", ""),
            "ip4": multi(out, "IP4.ADDRESS"), "gw4": f.get("IP4.GATEWAY", ""), "dns4": multi(out, "IP4.DNS"),
            "ip6": [a for a in multi(out, "IP6.ADDRESS")], "gw6": f.get("IP6.GATEWAY", ""),
            "speed": int(speed) if speed.lstrip("-").isdigit() and int(speed) > 0 else 0}


def connections() -> list:
    out = []
    for line in nm("-t", "-f", "UUID,TYPE,DEVICE,ACTIVE", "connection", "show").stdout.splitlines():
        parts = [unescape(p) for p in line.replace("\\:", "\0").split(":")]
        parts = [p.replace("\0", ":") for p in parts]
        if len(parts) < 4:
            continue
        uid, typ, dev, active = parts[:4]
        if typ == "loopback" or dev == "virbr0" or dev.startswith("vnet"):
            continue      # not "your network": loopback, libvirt's private NAT bridge, VM taps
        s = settings(uid)
        c = {
            "uuid": uid, "name": s.get("connection.id", ""), "type": typ, "device": dev, "active": active == "yes",
            "interface": s.get("connection.interface-name", ""), "master": s.get("connection.master", ""),
            "ssid": s.get("802-11-wireless.ssid", ""),
            "wifiShareable": typ == "802-11-wireless" and s.get("802-11-wireless-security.key-mgmt", "") in ("", "--", "wpa-psk", "sae", "owe"),
            "autoconnect": s.get("connection.autoconnect") == "yes",
            "lowData": s.get("connection.metered") == "yes",
            "privateAddress": s.get("802-11-wireless.cloned-mac-address", "").replace("--", "") or "default",
        }
        for fam in ("ipv4", "ipv6"):
            c[fam] = {"method": s.get(f"{fam}.method", "auto"),
                      "addresses": split_list(s.get(f"{fam}.addresses", "")),
                      "gateway": s.get(f"{fam}.gateway", ""),
                      "dns": split_list(s.get(f"{fam}.dns", "")),
                      "ignoreAutoDns": s.get(f"{fam}.ignore-auto-dns") == "yes"}
        if dev:
            c["live"] = device_info(dev)
        out.append(c)
    return out


def validate(ch: dict) -> list:
    errs = []
    if "lowData" in ch and not isinstance(ch["lowData"], bool): errs.append("Low-data mode must be on or off.")
    if "privateAddress" in ch and ch["privateAddress"] not in ("default", "random", "permanent", "stable", "stable-ssid"):
        errs.append("Choose a private or permanent hardware address.")
    for fam, ver in (("ipv4", 4), ("ipv6", 6)):
        f = ch.get(fam) or {}
        if not isinstance(f, dict):
            errs.append(f"{fam}: expected a JSON object with method and addresses")
            continue
        m = f.get("method", "auto")
        if m not in ("auto", "manual", "disabled", "ignore", "link-local", "shared", "dhcp"):
            errs.append(f"{fam}: unknown method {m}")
        if m == "manual" and not f.get("addresses"):
            errs.append(f"{'IPv4' if ver == 4 else 'IPv6'} manual needs an address")
        addrs = f.get("addresses") or []
        if not isinstance(addrs, list):
            errs.append(f"{fam}: addresses must be a list of IP addresses")
            addrs = []
        for a in addrs:
            try:
                if ipaddress.ip_interface(a).version != ver:
                    raise ValueError
                if "/" not in a:
                    errs.append(f"{a}: add the subnet, like /24")
            except ValueError:
                errs.append(f"{a} isn't an IPv{ver} address")
        if f.get("gateway"):
            try:
                if ipaddress.ip_address(f["gateway"]).version != ver:
                    raise ValueError
            except ValueError:
                errs.append(f"{f['gateway']} isn't an IPv{ver} router address")
        dns = f.get("dns") or []
        if not isinstance(dns, list):
            errs.append(f"{fam}: dns must be a list of DNS server addresses")
            dns = []
        for d in dns:
            try:
                ipaddress.ip_address(d)
            except ValueError:
                errs.append(f"{d} isn't a DNS server address")
    return errs


def to_keys(ch: dict) -> dict:
    k = {}
    if "lowData" in ch: k["connection.metered"] = "yes" if ch["lowData"] else "no"
    # "default" clears the choice: Home networks then use the real address, every other network a steady private one
    if "privateAddress" in ch: k["802-11-wireless.cloned-mac-address"] = "" if ch["privateAddress"] == "default" else ch["privateAddress"]
    if "autoconnect" in ch:
        k["connection.autoconnect"] = "yes" if ch["autoconnect"] else "no"
    for fam in ("ipv4", "ipv6"):
        f = ch.get(fam)
        if not f:
            continue
        # only what the change names is written: Settings sends just the parts you edited, so a profile's extra
        # addresses, a method the page has no button for, or DNS settings you didn't touch stay as they are
        m = f.get("method")
        if m is not None:
            manual = m == "manual"
            k[f"{fam}.method"] = m
            k[f"{fam}.addresses"] = ",".join(f.get("addresses") or []) if manual else ""
            k[f"{fam}.gateway"] = (f.get("gateway") or "") if manual else ""
        if "dns" in f or m == "disabled":
            dns = (f.get("dns") or []) if m != "disabled" else []
            k[f"{fam}.dns"] = ",".join(dns)
            k[f"{fam}.ignore-auto-dns"] = "yes" if dns else "no"
    return k


def current(uid: str, keys) -> dict:
    s = settings(uid)
    return {key: s.get(key, "") for key in keys}


def activate(uid: str) -> str:
    """Make the saved settings live if the profile is in use: reapply in place (no link drop), else re-up it.
    A profile that isn't in use is only saved, never brought up: on a bridged machine an idle Ethernet
    profile shares the port with the bridge, and activating it would pull the port out of the bridge."""
    dev = next((c["device"] for c in connections() if c["uuid"] == uid and c["active"]), "")
    if not dev:
        return ""
    if nm("device", "reapply", dev).returncode == 0:
        return ""
    r = nm("connection", "up", "uuid", uid)
    return "" if r.returncode == 0 else (r.stderr.strip() or r.stdout.strip())


def write_settings(uid: str, keys: dict) -> str:
    args = []
    for key, val in keys.items():
        args += [key, val]
    r = nm("connection", "modify", "uuid", uid, *args)
    if r.returncode != 0:
        return r.stderr.strip() or "nmcli refused the change"
    return activate(uid)


def pending() -> dict:
    try:
        return json.loads(PENDING.read_text())
    except (OSError, ValueError):
        return {}


def write_pending(data: dict) -> None:
    """Write the pending record safely: temp file, flush, fsync, rename."""
    tmp = PENDING.with_suffix(f".{os.getpid()}.tmp")
    tmp.write_text(json.dumps(data))
    tmp_fd = os.open(str(tmp), os.O_RDONLY)
    try:
        os.fsync(tmp_fd)
    finally:
        os.close(tmp_fd)
    tmp.replace(PENDING)


@contextlib.contextmanager
def locked():
    """Serialize every command that reads and then changes the pending undo, so a watchdog firing mid-change
    can't put the old settings back over a newer one, and two changes can't delete each other's undo."""
    STATE.mkdir(parents=True, exist_ok=True)
    with open(LOCK, "a") as f:
        fcntl.flock(f, fcntl.LOCK_EX)
        try:
            yield
        finally:
            fcntl.flock(f, fcntl.LOCK_UN)


def restore(p: dict) -> str:
    err = write_settings(p["uuid"], p["previous"])
    PENDING.unlink(missing_ok=True)
    return err


def expire_pending() -> None:
    """An unconfirmed change whose countdown ran out with no watchdog left to act (a restart or sign-out ended it):
    put the old settings back now, the way the watchdog would have, so the change doesn't stay for good and Settings
    doesn't show a Keep box that can't be answered. A live watchdog fires at the deadline itself; the few seconds'
    grace leave it that turn. Call under locked()."""
    p = pending()
    try:
        deadline = float(p.get("deadline", 0))
    except (TypeError, ValueError):
        deadline = 0
    if p and "uuid" in p and isinstance(p.get("previous"), dict) and 0 < deadline < time.time() - 3:
        restore(p)


def needs_secret(text: str) -> bool:
    t = text.lower()
    return "secrets were required" in t or "no secrets" in t or "no agents" in t


def vpn_error(text: str, up: bool, name: str = "") -> str:
    """nmcli's error for a VPN, in plain words. A timeout doesn't prove the server is unreachable, and nothing
    here can tell whether a password helper is running, so those stay general. A missing password or key points
    to what can add it: the terminal button the page shows, and the connection editor only when it's installed
    (its menu row is hidden otherwise, so naming it sent people looking for nothing)."""
    t = text.lower()
    if "unknown connection" in t:
        return "There is no saved connection with that id."
    if needs_secret(text):
        who = name or "This VPN"
        msg = f"{who} needs a password or key that isn't saved. Connect in a terminal to type it in."
        if shutil.which("nm-connection-editor"):
            msg += " To save it, open the menu (Super + Space) and choose Network connections (advanced)."
        return msg
    if "timeout" in t or "timed out" in t:
        return "Couldn't connect to the VPN in time. Check your internet connection and try again."
    return "Couldn't connect to the VPN." if up else "Couldn't disconnect the VPN."


# ---- joining a Wi-Fi network (the welcome's "Other network…", both installers' joins)
# The join makes a saved profile (or reuses the one already saved for that name) and brings it up with
# `nmcli connection up … passwd-file`: the password reaches nmcli through a pipe, never on a command line and never
# through nmcli's typed question. That question comes pre-filled with the saved password and adds what's typed to the
# end of it, so a network whose password changed could never be joined again (the VM test saved psk=<old><new>). A
# profile for a network that doesn't show its name is marked hidden, so NetworkManager asks for it by name itself and
# no scan has to have seen it first (a radio that just started had not, and the first join failed).
# NetworkManager asks for the password ("need authentication") once at the start and again each time the network turns
# it down, and nmcli would hand over the same password every time until its time limit ran out. So one question more
# than expected is the "wrong password" answer (counted on `nmcli monitor`), and the join is stopped right there.
# NetworkManager asks nmcli for a password only when the profile has none it may use. So a profile saved before first
# tries its own saved password (one that still works is never replaced by a mistyped one); when the network turns that
# down, the profile is switched to "ask each time" for one more try with the typed password, and back to "saved for
# everyone" after, holding the typed password in place of the old one (never added to it, as nmcli's typed question
# did). A profile this join made is deleted again when the join fails; one saved before always stays.
JOIN_WAIT = 20                              # seconds in all (a network that doesn't answer, say)
ASKED = re.compile(r"^(.+): connecting \(need authentication\)$", re.M)


def wifi_uuids(ssid: str) -> list:
    """The saved Wi-Fi profiles for this network name (by the network's name, not the profile's), in nmcli's order."""
    found = []
    for line in nm("-t", "-f", "UUID,TYPE", "connection", "show").stdout.splitlines():
        uid, _, kind = line.partition(":")
        if kind == "802-11-wireless" and nm("-g", "802-11-wireless.ssid", "connection", "show", "uuid",
                                           uid).stdout.strip() == ssid:
            found.append(uid)
    return found


def wifi_devices() -> set:
    out = nm("-t", "-f", "DEVICE,TYPE", "device").stdout
    return {unescape(l.rpartition(":")[0]) for l in out.splitlines() if l.endswith(":wifi")}


def wifi_security(ssid: str):
    """What the last scan says the network asks for ("" for none, "WPA2", "WPA2 WPA3", "WPA2 802.1X"…), None when the
    scan didn't see it."""
    for line in nm("-t", "-f", "SSID,SECURITY", "device", "wifi", "list", "--rescan", "no").stdout.splitlines():
        parts = [p.replace("\0", ":") for p in line.replace("\\:", "\0").split(":")]
        if len(parts) >= 2 and unescape(parts[0]) == ssid:
            return "" if parts[1].strip() in ("", "--") else parts[1].strip()
    return None


def wifi_up(uid: str, password: str, wait: int, turns: int) -> tuple:
    """Bring a Wi-Fi profile up, the password given on a pipe. Stopped at the `turns`-th password question (the
    password was turned down). Returns (exit code or None when stopped, password questions seen, whether it got as
    far as asking for an address, nmcli's error)."""
    devs = wifi_devices()
    mon = subprocess.Popen(["nmcli", "monitor"], stdin=subprocess.DEVNULL, stdout=subprocess.PIPE,
                           stderr=subprocess.DEVNULL)
    # listening before anything happens: it says "NetworkManager is running" first, once it is
    seen, first = b"", selectors.DefaultSelector()
    first.register(mon.stdout, selectors.EVENT_READ)
    if first.select(2):
        seen = os.read(mon.stdout.fileno(), 4096)
    first.close()
    cmd, fds = ["nmcli", "--wait", str(wait), "connection", "up", "uuid", uid], ()
    if password:
        rfd, wfd = os.pipe()
        os.write(wfd, f"802-11-wireless-security.psk:{password}\n".encode())
        os.close(wfd)
        cmd += ["passwd-file", f"/dev/fd/{rfd}"]
        fds = (rfd,)
    try:
        p = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             pass_fds=fds)
    finally:
        for fd in fds:
            os.close(fd)
    err, asked, stopped = b"", 0, False
    sel = selectors.DefaultSelector()
    sel.register(p.stdout, selectors.EVENT_READ, "out")
    sel.register(p.stderr, selectors.EVENT_READ, "err")
    sel.register(mon.stdout, selectors.EVENT_READ, "mon")
    deadline = time.monotonic() + wait + 2
    while (p.stdout in sel.get_map() or p.stderr in sel.get_map()) and time.monotonic() < deadline:
        for key, _ in sel.select(0.5):
            data = os.read(key.fileobj.fileno(), 4096)
            if not data:
                sel.unregister(key.fileobj)
            elif key.data == "err":
                err += data
            elif key.data == "mon":
                seen += data
        asked = sum(1 for d in ASKED.findall(seen.decode(errors="replace")) if not devs or d in devs)
        if asked >= turns:                   # asked again: the password didn't work
            stopped = True
            break
    if p.stdout in sel.get_map() or p.stderr in sel.get_map():
        stopped = True                       # turned down, or nmcli overstayed its own time limit
        p.terminate()
    mon.terminate()
    try:
        code = p.wait(5)
    except subprocess.TimeoutExpired:
        p.kill()
        code = p.wait()
    try:
        mon.wait(5)
    except subprocess.TimeoutExpired:
        mon.kill()
    text = seen.decode(errors="replace")
    return (None if stopped else code), asked, "(getting IP configuration)" in text, err.decode(errors="replace")


def wifi_join(ssid: str, password: str, hidden: bool) -> dict:
    """Join a Wi-Fi network, saving it for everyone. A join that fails deletes the profile it made (so a wrong
    password is never kept and retried at every start), and never one that was saved before."""
    def fail(why, msg):
        return {"ok": False, "why": why, "errors": msg}
    end = time.monotonic() + JOIN_WAIT
    sec = None if hidden else wifi_security(ssid)
    if sec is not None and "802.1X" in sec:
        return fail("other", f"{ssid} is a work or school network that needs its own sign-in name, which can't be set "
                             "up here yet. Use another Wi-Fi network (a phone's hotspot works) or a network cable.")
    if sec == "" or (sec is not None and sec.split() == ["OWE"]):
        key = "owe" if sec else ""           # open: no password to give
        password = ""
    elif sec is not None and "WPA1" not in sec and "WPA2" not in sec and "WPA3" in sec:
        key = "sae"                          # WPA3 only
    else:
        key = "wpa-psk" if password or sec else ""   # a hidden one with no password typed: tried as open
    saved = wifi_uuids(ssid)
    if key in ("wpa-psk", "sae") and not password and not saved:      # a saved one may have its password
        return fail("password", f"{ssid} needs a password. Type it and try again.")
    if key == "wpa-psk" and password and len(password) < 8:
        return fail("password", "This network's password is at least 8 characters.")
    if key == "wpa-psk" and (len(password) > 64 or (len(password) == 64 and not re.fullmatch(r"[0-9a-fA-F]+", password))):
        return fail("password", "This network's password is at most 63 characters.")

    made, asking, have, tried = "", False, ["", "", ""], None
    left = lambda: max(5, int(end - time.monotonic()))
    if saved:
        uid = saved[0]
        have = [x.strip() for x in nm("-g", "802-11-wireless.hidden,802-11-wireless-security.key-mgmt,"
                                      "802-11-wireless-security.psk-flags", "connection", "show", "uuid",
                                      uid).stdout.splitlines()] + ["", "", ""]
        change = (["802-11-wireless.hidden", "yes"] if hidden and have[0] != "yes" else []) + \
                 (["802-11-wireless-security.key-mgmt", key] if key and have[1] != key else [])
        if change:
            nm("connection", "modify", "uuid", uid, *change)
        asking = bool(key and password)      # the typed password is used, not the saved one
        if asking and have[1] and have[2] in ("", "0"):
            # its saved password first: one that still works is never replaced by a mistyped one
            tried = wifi_up(uid, "", left(), 2)
            if tried[0] == 0:
                return {"ok": True, "why": "", "errors": ""}
            nm("connection", "down", "uuid", uid)
            # the saved one turned down: on to the typed one, when there's time. Otherwise (no network answered,
            # say) the typed one can't do better: that's the answer
            if not (tried[1] >= 2 or "secrets were required" in tried[3].lower()) or end - time.monotonic() < 5:
                asking = False
        if asking:
            nm("connection", "modify", "uuid", uid, "802-11-wireless-security.psk-flags", "1")
    else:
        # not connected by itself while it has no password yet: switched on for good once the join works
        r = nm("connection", "add", "type", "wifi", "con-name", ssid, "ssid", ssid, "connection.autoconnect", "no",
               *(["802-11-wireless.hidden", "yes"] if hidden else []),
               *(["802-11-wireless-security.key-mgmt", key] if key else []))
        m = re.search(r"\(([0-9a-f-]{36})\)", r.stdout)
        if r.returncode != 0 or not m:
            return fail("other", f"Couldn't connect to {ssid}. Try again, or pick another network.")
        uid = made = m.group(1)
    code, asked, answered, err = tried if tried and not asking else (None, 0, False, "")
    if made or asking or not tried:
        try:
            code, asked, answered, err = wifi_up(uid, password if key else "", left(), 2)
        finally:
            if made and code != 0:
                nm("connection", "delete", "uuid", made)
            elif not made and code != 0:
                nm("connection", "down", "uuid", uid)   # stop it trying; the saved profile itself stays
            if asking:
                # saved for everyone again: the password that just worked (NetworkManager keeps the one it was given
                # last, so after a failed try that's the typed one: the old one had already been turned down)
                nm("connection", "modify", "uuid", uid, "802-11-wireless-security.psk-flags",
                   "0" if code == 0 else have[2] or "0")
    if code == 0:
        if made:
            nm("connection", "modify", "uuid", made, "connection.autoconnect", "yes")
        return {"ok": True, "why": "", "errors": ""}
    t = err.lower()
    if (key and asked >= 2) or "secrets were required" in t:
        return fail("password", f"{ssid} needs a password. Type it and try again." if not password else
                                f"Wrong password for {ssid}. Check it (capital letters count) and try again.")
    # a hidden network asked its password first (before it was even found) and never got an address:
    # no network by that name answered
    if re.search(r"could not be found|no network with ssid|ssid-not-found|failed to scan hidden", t) or \
            (asked <= 1 and not answered and re.search(r"timeout|timed out", t)):
        if hidden and not password:
            return fail("missing", f"No open network named {ssid} answered. Check the name (capital letters count), "
                                   "and type its password if it has one.")
        return fail("missing", f"No network named {ssid} answered. Check the name (capital letters count), or move closer.")
    return fail("other", f"Couldn't connect to {ssid}. Try again, or pick another network.")


def route_overlaps() -> list:
    """A VPN (Tailscale, say) offering a route to a network this computer is on: [{network, vpn, wifi, kept}] from
    the route guard (route_guard.py, read-only: no root needed). kept: Starchaser's rule keeps that network's traffic
    on the cable or Wi-Fi. [] when the guard's code isn't installed (an older system)."""
    import importlib.util
    for f in (Path("/usr/local/lib/starchaser/route_guard.py"),
              Path(__file__).resolve().parent.parent / "system/usr/local/lib/starchaser/route_guard.py"):
        if not f.is_file():
            continue
        try:
            spec = importlib.util.spec_from_file_location("starchaser_route_guard", f)
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
            seen, out = set(), []
            for o in mod.status().get("overlaps") or []:
                if o["network"] in seen:
                    continue
                seen.add(o["network"])
                out.append({k: o.get(k) for k in ("network", "interface", "vpn", "wifi", "kept")})
            return out
        except Exception:                              # only a note on the page: never break reading the settings
            return []
    return []


def radio_file():
    return STATE / 'radio-state.json'


def read_radios():
    try:
        return json.loads(radio_file().read_text())
    except (OSError, ValueError):
        return {}


def save_radios(value):
    STATE.mkdir(parents=True, exist_ok=True, mode=0o700)
    target = radio_file()
    temporary = target.with_name(f'.{target.name}.{os.getpid()}.tmp')
    try:
        fd = os.open(temporary, os.O_CREAT | os.O_TRUNC | os.O_WRONLY, 0o600)
        with os.fdopen(fd, 'w') as stream:
            json.dump(value, stream)
            stream.flush()
            os.fsync(stream.fileno())
        os.replace(temporary, target)
    finally:
        temporary.unlink(missing_ok=True)


def checked(*args, input=None):
    result = subprocess.run(args, input=input, capture_output=True, text=True, timeout=30, check=False)
    if result.returncode:
        raise ValueError(result.stderr.strip() or "The radio change couldn't finish.")
    return result.stdout.strip()


def radio_status():
    saved = read_radios()
    wifi = checked('nmcli', 'radio', 'wifi') == 'enabled'
    wwan = checked('nmcli', 'radio', 'wwan') == 'enabled'
    bluetooth = json.loads(checked('rfkill', '--json', '--output', 'TYPE,SOFT')).get('rfkilldevices', [])
    bt_off = all(d.get('soft') == 'blocked' for d in bluetooth if d.get('type') == 'bluetooth')
    active = checked('nmcli', '-t', '-f', 'UUID', 'connection', 'show', '--active').splitlines()
    return {'ok': True, 'airplane': not wifi and not wwan and bt_off,
            'hotspot': bool(saved.get('hotspot') and saved['hotspot'] in active), 'hotspotName': saved.get('hotspotName', '')}


def airplane_change(value):
    saved = read_radios()
    if value == 'on':
        if radio_status()['airplane']:
            return radio_status()
        if 'beforeAirplane' not in saved:
            previous = {'wifi': checked('nmcli', 'radio', 'wifi'), 'wwan': checked('nmcli', 'radio', 'wwan'),
                        'bluetooth': json.loads(checked('rfkill', '--json', '--output', 'ID,TYPE,SOFT')).get('rfkilldevices', [])}
            saved['beforeAirplane'] = previous
            save_radios(saved)  # Keep the first snapshot until every radio has been restored.
        checked('nmcli', 'radio', 'all', 'off')
        checked('rfkill', 'block', 'bluetooth')
    elif value == 'off':
        previous = saved.get('beforeAirplane', {})
        for radio in ('wifi', 'wwan'):
            checked('nmcli', 'radio', radio, 'off' if previous.get(radio) == 'disabled' else 'on')
        devices = previous.get('bluetooth')
        if devices is None:
            checked('rfkill', 'unblock', 'bluetooth')
        else:
            for device in devices:
                if device.get('type') == 'bluetooth' and device.get('soft') == 'unblocked' and str(device.get('id', '')).isdigit():
                    checked('rfkill', 'unblock', str(device['id']))
        saved.pop('beforeAirplane', None)
        save_radios(saved)
    else:
        raise ValueError('Choose on or off for Airplane mode.')
    return radio_status()


def remove_hotspot(saved, active):
    uid = saved.get('hotspot')
    if uid:
        if active:
            checked('nmcli', 'connection', 'down', 'uuid', uid)
        profiles = checked('nmcli', '-t', '-f', 'UUID', 'connection', 'show').splitlines()
        if uid in profiles:
            checked('nmcli', 'connection', 'delete', 'uuid', uid)
    saved.pop('hotspot', None)
    saved.pop('hotspotName', None)
    save_radios(saved)


def hotspot_change(value, data):
    saved = read_radios()
    if value == 'off':
        remove_hotspot(saved, radio_status()['hotspot'] if saved.get('hotspot') else False)
        return radio_status()
    if value != 'on':
        raise ValueError('Choose on or off for the hotspot.')
    name, password = data.get('name', ''), data.get('password', '')
    if not isinstance(name, str) or not 1 <= len(name.encode()) <= 32 or any(c in name for c in '\n\r\0'):
        raise ValueError('Use a hotspot name between 1 and 32 bytes without line breaks.')
    if not isinstance(password, str) or not 8 <= len(password) <= 63 or not all(32 <= ord(c) <= 126 for c in password):
        raise ValueError('Use a hotspot password of 8 to 63 letters, numbers, or symbols.')
    status = radio_status()
    if status['airplane']:
        raise ValueError('Turn off Airplane mode before starting a hotspot.')
    if status['hotspot']:
        raise ValueError('Stop the current hotspot before starting another.')
    if saved.get('hotspot'):
        # Disconnection and reboot leave the profile saved but inactive. Retire only
        # that profile, then use the name and password entered for this new start.
        remove_hotspot(saved, False)
    uid = str(uuidlib.uuid4())
    try:
        # Adding a profile uses the desktop's normal permissions; loading a keyfile
        # asks for administrator reload permission. Keep the secret off argv and disk.
        checked('nmcli', 'connection', 'add', 'type', 'wifi', 'con-name', 'Starchaser hotspot', 'ssid', name,
                'connection.uuid', uid, 'connection.autoconnect', 'no', '802-11-wireless.mode', 'ap',
                '802-11-wireless-security.key-mgmt', 'wpa-psk', '802-11-wireless-security.psk-flags', '2',
                'ipv4.method', 'shared', 'ipv6.method', 'disabled')
        checked('nmcli', '--wait', '20', 'connection', 'up', 'uuid', uid, 'passwd-file', '/dev/stdin',
                input=f'802-11-wireless-security.psk:{password}\n')
    except (OSError, ValueError, subprocess.SubprocessError):
        nm('connection', 'delete', 'uuid', uid)  # Best effort: remove only the profile we created.
        raise
    saved.update(hotspot=uid, hotspotName=name)
    save_radios(saved)
    return radio_status()


def main(argv: list) -> None:
    cmd = argv[0] if argv else "get"
    if cmd in ("airplane", "hotspot", "radios"):
        expected = 1 if cmd == "radios" else 2
        if len(argv) != expected or (cmd != "radios" and argv[1] not in ("on", "off")):
            print("Choose radios, airplane on|off, or hotspot on|off.", file=sys.stderr)
            sys.exit(2)
        try:
            with locked():
                result = radio_status() if cmd == "radios" else airplane_change(argv[1]) if cmd == "airplane" else hotspot_change(argv[1], json.load(sys.stdin) if argv[1] == "on" else {})
        except (OSError, ValueError, subprocess.SubprocessError) as error:
            result = {"ok": False, "errors": str(error)}
        print(json.dumps(result))
        sys.exit(0 if result["ok"] else 1)
    if cmd == "get":
        if len(argv) > 1:
            print(f"starchaser network: get takes nothing after it (got {argv[1]!r})", file=sys.stderr)
            sys.exit(2)
        with locked():
            expire_pending()
            p = pending()
        print(json.dumps({"connections": connections(),
                          "pending": {"uuid": p["uuid"], "deadline": p["deadline"]} if p else None,
                          "routeOverlaps": route_overlaps()}))
    elif cmd == "set":
        # strict: a misspelled option ("--timout 20") must not change the connection with no way back
        timeout, args, rest = 0, [], argv[1:]
        def refuse(msg):
            print(json.dumps({"ok": False, "errors": msg}))
            sys.exit(2)
        while rest:
            a = rest.pop(0)
            if a == "--timeout" or a.startswith("--timeout="):
                v = a.split("=", 1)[1] if "=" in a else (rest.pop(0) if rest else "")
                try:
                    timeout = int(v)
                except ValueError:
                    refuse("--timeout needs a whole number of seconds")
                if not 1 <= timeout <= 600:
                    refuse("--timeout has to be between 1 and 600 seconds")
            elif a.startswith("-") and a != "-":
                refuse(f"set doesn't know the option {a}")
            else:
                args.append(a)
        if len(args) > 1:
            refuse("set takes one change file")
        try:
            ch = json.loads(sys.stdin.read() if not args or args[0] == "-" else Path(args[0]).read_text())
        except OSError:
            print(json.dumps({"ok": False, "errors": f"couldn't read {args[0]}"}))
            sys.exit(2)
        except ValueError:
            print(json.dumps({"ok": False, "errors": "the change isn't valid JSON"}))
            sys.exit(2)
        if not isinstance(ch, dict):
            print(json.dumps({"ok": False, "errors": "the change must be a JSON object"}))
            sys.exit(2)
        uid = ch.get("uuid", "")
        errs = validate(ch) if uid else ["no connection given"]
        if errs:
            print(json.dumps({"ok": False, "errors": "; ".join(errs)}))
            sys.exit(2)
        keys = to_keys(ch)
        if not keys:
            print(json.dumps({"ok": True, "errors": ""}))     # nothing named to change
            return
        with locked():
            expire_pending()
            p = pending()
            if p and p.get("uuid") != uid:          # a different connection is still unconfirmed: keep it as is
                restore(p)
                p = {}
            # first change in a row keeps the original. A later change in the same row can name keys the first one
            # didn't (Settings sends only what you edited): their originals are read now, before this write (the
            # waiting change never touched them), so Revert doesn't blank them
            previous = dict(p.get("previous") or {})
            new = [k for k in keys if k not in previous]
            if new:
                previous.update(current(uid, new))
            if p and timeout <= 0:
                # an untimed change to the connection that was waiting for a confirmation: that change is meant
                # to stay, so drop the undo before writing; the old watchdog then finds nothing to put back
                PENDING.unlink(missing_ok=True)
            err = write_settings(uid, keys)
            if timeout > 0:
                token = uuidlib.uuid4().hex
                write_pending({"id": token, "uuid": uid, "deadline": time.time() + timeout,
                                               "previous": {**previous, **{k: previous.get(k, "") for k in keys}}})
                subprocess.Popen([sys.executable, os.path.abspath(__file__), "watchdog", token, str(timeout)],
                                 start_new_session=True, stdin=subprocess.DEVNULL,
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
            elif p and err:                         # the change didn't take: the earlier one is still unconfirmed
                write_pending(p)
        print(json.dumps({"ok": not err, "errors": err}))
        if err:
            sys.exit(1)
    elif cmd == "watchdog":                     # internal: watchdog <id> <seconds>
        time.sleep(float(argv[2]))
        with locked():
            p = pending()
            if p.get("id") == argv[1]:
                restore(p)
    elif cmd in ("confirm", "revert") and len(argv) > 1:
        print(f"starchaser network: {cmd} takes no more arguments", file=sys.stderr)
        sys.exit(2)
    elif cmd == "confirm":
        # under the lock, so the watchdog can't put the old settings back between the look and the keep. Nothing
        # waiting means the countdown already ran out (or someone answered elsewhere): say so, don't claim "kept"
        with locked():
            p = pending()
            PENDING.unlink(missing_ok=True)
        if not p:
            print(json.dumps({"ok": False, "errors": "The settings already went back. Apply them again to keep them."}))
            sys.exit(1)
        print(json.dumps({"ok": True, "errors": "", "kept": True}))
    elif cmd == "revert":
        with locked():
            p = pending()
            err = restore(p) if p else None
        if err is None:
            # what was asked for is already the case: the earlier settings are back
            print(json.dumps({"ok": True, "errors": "", "already": True,
                              "note": "The settings had already gone back by themselves."}))
            return
        print(json.dumps({"ok": not err, "errors": err}))
        sys.exit(1 if err else 0)
    elif cmd == "connect":
        if len(argv) != 2 or not argv[1] or argv[1].startswith("-"):
            print("starchaser network: connect needs one saved connection id.", file=sys.stderr)
            sys.exit(2)
        try:
            connection = next((c for c in connections() if c["uuid"] == argv[1]), None)
            if not connection or connection["type"] != "802-3-ethernet" or connection.get("master"):
                result = {"ok": False, "errors": "Choose a saved wired connection."}
            elif connection["active"]:
                result = {"ok": True, "errors": ""}
            else:
                r = nm("--wait", "20", "connection", "up", "uuid", argv[1])
                result = {"ok": r.returncode == 0, "errors": "" if r.returncode == 0 else
                          "Couldn't connect. Check the network cable and router, then try again."}
        except (OSError, subprocess.TimeoutExpired):
            result = {"ok": False, "errors": "Couldn't connect. Check the network cable and router, then try again."}
        print(json.dumps(result))
        sys.exit(0 if result["ok"] else 1)
    elif cmd == "vpn":
        if len(argv) != 3 or argv[1] not in ("up", "down") or argv[2].startswith("-"):
            print("starchaser network: vpn needs up or down and a connection id. Run 'starchaser network --help' for more help.", file=sys.stderr)
            sys.exit(2)
        up = argv[1] == "up"
        secret = False
        try:
            name = nm("-g", "connection.id", "connection", "show", "uuid", argv[2]).stdout.strip()
        except (OSError, subprocess.TimeoutExpired):
            name = ""
        try:
            r = subprocess.run(["nmcli", "--wait", "30", "connection", argv[1], "uuid", argv[2]],
                               capture_output=True, text=True, timeout=45)
            ok, err = r.returncode == 0, "" if r.returncode == 0 else vpn_error(r.stderr + r.stdout, up, name)
            secret = not ok and up and needs_secret(r.stderr + r.stdout)
        except subprocess.TimeoutExpired:
            ok, err = False, vpn_error("timeout", up)
        except OSError:
            ok, err = False, vpn_error("", up)
        print(json.dumps({"ok": ok, "errors": err, "needsSecret": secret}))
        sys.exit(0 if ok else 1)
    elif cmd == "wifi-join":
        opts, rest = set(), argv[1:]
        while rest and rest[0] in ("--hidden", "--password-stdin"):
            opts.add(rest.pop(0))
        ended = rest[:1] == ["--"]               # after "--", a name may start with "-"
        if ended:
            rest = rest[1:]
        if len(rest) != 1 or not rest[0] or (rest[0].startswith("-") and not ended):
            print(json.dumps({"ok": False, "why": "other",
                              "errors": "Usage: starchaser network wifi-join [--hidden] [--password-stdin] [--] <ssid>"}))
            sys.exit(2)
        ssid, password = rest[0], ""
        if "--password-stdin" in opts:
            # one line; only its newline is taken off (spaces at either end belong to the password)
            password = sys.stdin.readline()
            if password.endswith("\n"):
                password = password[:-1]
        try:
            r = wifi_join(ssid, password, "--hidden" in opts)
        except (OSError, subprocess.TimeoutExpired):
            r = {"ok": False, "why": "other", "errors": f"Couldn't connect to {ssid}. Try again, or pick another network."}
        print(json.dumps(r))
        sys.exit(0 if r["ok"] else 1)
    elif cmd == "forget":
        if len(argv) != 2 or argv[1].startswith("-"):
            print("starchaser network: forget needs one connection id. Run 'starchaser network --help' for more help.", file=sys.stderr)
            sys.exit(2)
        try:
            r = nm("connection", "delete", "uuid", argv[1])
            ok = r.returncode == 0
        except (OSError, subprocess.TimeoutExpired):
            ok = False
        print(json.dumps({"ok": ok, "errors": "" if ok else "Couldn't forget that network."}))
        sys.exit(0 if ok else 1)
    else:
        print(f"starchaser network: unknown command {cmd!r}. Run 'starchaser network --help' for more help.", file=sys.stderr)
        sys.exit(2)


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]) or any(a in ("-h", "--help") for a in sys.argv[2:]):      # usage on request is not an error
        print(__doc__)
        sys.exit(0)
    try:
        main(sys.argv[1:])
    except FileNotFoundError as e:
        # a helper program that isn't installed: one plain line, never a Python traceback (Settings reads this too)
        sys.exit(f"starchaser network: {e.filename or 'a needed program'} isn't installed on this computer.")
    except OSError as error:
        # a state folder it may not read or write: one plain line, never a Python traceback
        sys.exit(f"starchaser network: couldn't read or save the network settings ({error.strerror}). "
                 "Check that you can write to ~/.local/state.")
