#!/usr/bin/env python3
# summary: Show firewall questions and blocked-connection notices.
"""starchaser firewall ask: firewall notices and outgoing questions (the starchaser firewall ask user service).

  Incoming  blocked connections produce a bell-only notice, only when a verified system program is listening.
            Once per program per network, remembered until forgotten. Internet senders, scans, sweeps, discovery,
            unknown networks, programs in home or temporary folders, fleet members and allowed connections stay
            in the Log. The notice names the process and offers an allowance only when you expected the connection.
            Public networks offer a review of network trust in Settings before any password or rule change. A lasting allowance never opens every Public network.

  Outgoing  when Settings > Firewall > "Apps reaching out" is Ask (policy defaults.out = "ask"), this is the
            asker OpenSnitch talks to (its UI protocol on $XDG_RUNTIME_DIR/starchaser-osui.sock, which the root side
            points OpenSnitch at; the opensnitch package):
            "Discord wants to connect to gateway.discord.gg (port 443)"  [Deny] [Allow app for 2 minutes] [Allow always] [Never]
              Allow always / Never are saved by OpenSnitch as sc-asked-*.json rules for that program
            One question per program at a time; no answer in 25 seconds = denied once, with the card still up.
            Until answered, retries are denied right away. An answer governs the program's next connections.
            If the question can't be shown (OpenSnitch's Python parts missing, the socket can't be made, the
            question service failed), new connections stay blocked: a notification says so once, and
            $XDG_RUNTIME_DIR/starchaser-firewall-ask.json says so to Settings (starchaser firewall state: "asker",
            with lastPing: when OpenSnitch last checked in, so Settings can tell "ready" from "connected").

  Networks  nothing is asked when a network connects; every new network starts Public. Trust is asked only
            where something needs it (Settings, in context). A network is known by what it is (the engine's
            network identity: Wi-Fi name + security + password fingerprint, a cable's router), not by its saved
            connection id, so a network that comes back under a new id keeps its choice and a look-alike gets none.
            Old network cards are closed when the service starts.

  Not kept  a change applied in Settings > Firewall went back by itself because Keep wasn't pressed (Settings may
            have been closed meanwhile): one notification saying so, pointing to History.

  Running   the firewall is set to on but its rules aren't loaded (the start-up load failed, or the table was
            removed): one notification each time that starts, so it isn't only on the Firewall page.

    starchaser firewall ask run       (the service) both of the above
    starchaser firewall ask test-in <address> <tcp|udp> <port> [trusted|public|vpn|tailscale]
                                      show the incoming question (no connection needed), as if it came in on that
                                      kind of network, and wait for your answer (up to 10 minutes), which is
                                      carried out like a real one
Testing: STARCHASER_FIREWALL_ASK_ANSWER answers notices by itself (deny|once|always|never|trust) and logs them to
$XDG_RUNTIME_DIR/starchaser-firewall-ask.log. Allowance answers really change the firewall.
STARCHASER_FIREWALL_ASK_LOG=1 only logs.
"""
import fcntl
import hashlib
import html
import ipaddress
import json
import os
os.environ["QS_DISABLE_CRASH_HANDLER"] = "1"
os.environ["STARCHASER_QML_APP"] = "firewall"
import re
import shlex
import shutil
import socket
import subprocess
import sys
import tempfile
import threading
import time
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_cli import safe_streams
from starchaser_sandbox import process_scope
from starchaser_firewall_activity import Activity
from starchaser_firewall_traffic import TrafficSampler
safe_streams()

HOME = Path.home()
PREFS = HOME / ".config/starchaser/firewall-ask.json"
POLICY = Path("/etc/starchaser/policy.json")
FLEET = HOME / ".config/starchaser/fleet.json"
PEERS = HOME / ".local/share/starchaser/devices/peers.json"
SEEN_FOR = 86400               # a paired device's address counts as its own for a day after it last answered from it
ADMIN = "/usr/local/lib/starchaser/starchaser-admin"
AREA = "/usr/local/lib/starchaser/starchaser-admin-area"
AREA_COMMANDS = {"firewall-commit", "firewall-rollback", "firewall-revert", "firewall-reload",
                 "firewall-allow-always", "firewall-mark-network", "firewall-forget-asked", "firewall-revoke-once"}
RUNTIME = Path(os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}")
OSUI_SOCK = str(RUNTIME / "starchaser-osui.sock")      # firewall.py osui_address() is the root side of this
STATUS = RUNTIME / "starchaser-firewall-ask.json"
ASK_DELAY = 3                  # wait for a scan to show itself before posting a notice
# Names for ports the app catalog doesn't cover (it comes first: see usual_app), read as "a port usually used by ..."
SERVICES = {21: "file transfer (FTP)", 23: "Telnet", 25: "email (SMTP)", 53: "DNS", 80: "web servers",
            443: "web servers", 8080: "web services", 8443: "web services", 3000: "development servers",
            5000: "development servers", 8000: "development servers", 8384: "Syncthing's settings",
            11434: "Ollama (local AI)", 6379: "Redis", 5432: "PostgreSQL", 3306: "MySQL"}
CATALOG = Path("/usr/local/share/starchaser/firewall-apps.json")          # bin/starchaser-firewall reads the same
CATALOG_REPO = HOME / ".local/share/starchaser/repo/config/firewall/apps.json"


# the network kind a blocked connection came in on (the z= field of the kernel log line), in the body's words
ZONE_WORDS = {"trusted": "a trusted network", "public": "a public network", "vpn": "a VPN", "tailscale": "Tailscale"}
# where an "Allow always" rule applies (starchaser-admin allow_always: the kind of network it came in on; unknown =
# trusted), for the notification that confirms it
ZONE_SCOPE = {"trusted": "on trusted networks", "public": "on public networks", "vpn": "over a VPN",
              "tailscale": "over Tailscale"}
# signing in to this computer or controlling it from elsewhere: from a public network (a cafe, hotel or airport),
# the question offers only 15 minutes. Includes tsshd (UDP 61000-62000), Sunshine's streaming ports, and VNC
# screens 5900-5999 (each virtual machine console takes the next one)
REMOTE_PORTS = {22, 23, 139, 445, 3389, 5985, 5986, 9090, 47984, 47989, 47990, 48002, 48010, *range(47998, 48001),
                *range(5900, 6000), *range(61000, 62001)}


def prefs() -> dict:
    try:
        return {"incoming": True, **json.loads(PREFS.read_text())}
    except (OSError, ValueError):
        return {"incoming": True}


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


def firewall_is_off() -> bool:
    """True only when the policy file was read and says Off; an unreadable file is not proof of Off."""
    p = policy()
    return bool(p) and not p.get("enabled")


class FileChanges:
    """One inotify reader for the folders the watchers below read: the policy, the root-side stats and zones, child
    requests, the trial record and this account's runtime marks. A watcher with nothing under way waits for a change
    there (pause) instead of reading its files every few seconds, which kept an idle desktop busy."""
    # IN_CLOSE_WRITE | IN_MOVED_FROM | IN_MOVED_TO | IN_CREATE | IN_DELETE
    MASK = 0x08 | 0x40 | 0x80 | 0x100 | 0x200

    def __init__(self, folders):
        import ctypes
        self.folders = [Path(f) for f in folders]
        self.cond = threading.Condition()
        self.count = 0
        self.seen = threading.local()
        self.libc = ctypes.CDLL(None, use_errno=True)
        self.fd = self.libc.inotify_init1(os.O_CLOEXEC)
        if self.fd < 0:
            raise OSError(ctypes.get_errno(), "no inotify")
        self.watch()
        threading.Thread(target=self.read, daemon=True).start()

    def watch(self) -> None:
        """Watch every folder there is (again: a folder made later, or removed and made again, is a new one)."""
        for folder in self.folders:
            if folder.is_dir():
                self.libc.inotify_add_watch(self.fd, os.fsencode(folder), self.MASK)

    def read(self) -> None:
        while True:
            try:
                raw = os.read(self.fd, 65536)
            except OSError:
                return                                  # (every wait then ends at its 30 s limit)
            offset, again = 0, False
            while offset + 16 <= len(raw):
                mask = int.from_bytes(raw[offset + 4:offset + 8], sys.byteorder)
                again |= bool(mask & 0xC000) or (mask & 0x40000100) == 0x40000100   # gone, overflow, a new folder
                offset += 16 + int.from_bytes(raw[offset + 12:offset + 16], sys.byteorder)
            if again:
                self.watch()
            with self.cond:
                self.count += 1
                self.cond.notify_all()

    def wait(self, seconds: float) -> None:
        """Until a change this thread hasn't seen yet, or `seconds`."""
        with self.cond:
            seen = getattr(self.seen, "count", self.count)
            self.cond.wait_for(lambda: self.count != seen, timeout=seconds)
            self.seen.count = self.count


def pause(seconds: float, busy: bool, changes: "FileChanges | None") -> None:
    """A watcher's wait between looks: `seconds` while something it follows is under way (an open question, a trial,
    a permission counting down, recording on, an alarm being confirmed); otherwise until one of its files changes,
    30 s at most. Without the change reader (`run` couldn't start one, or a test) it is the plain clock it always was."""
    if busy or changes is None:
        time.sleep(seconds)
    else:
        changes.wait(30)


def incoming_paused(iface: str, pause: dict | None = None) -> bool:
    """Use the current pause, not the network type recorded when a notification arrived."""
    if pause is None:
        try:
            state = json.loads(STATS.read_text())
            if not 0 <= time.time() - state["updated"] <= STATS_FRESH:
                return False
            pause = state.get("publicPause") or {}
        except (OSError, ValueError, TypeError, KeyError):
            return False
    ifaces = pause.get("ifaces") or []
    return iface in ifaces if iface else bool(ifaces)


def dbg(msg: str) -> None:
    """One journal line (tag starchaser-firewall-ask) for anything that closes, replaces or hides a card, so a card
    that vanishes by itself can be traced afterward (QA r75)."""
    print(f"starchaser firewall ask: {msg}", file=sys.stderr, flush=True)
    try:
        subprocess.run(["logger", "-t", "starchaser-firewall-ask", msg], capture_output=True, timeout=5)
    except (OSError, subprocess.TimeoutExpired):
        pass


# the incoming questions on screen now: card id -> the kind of network the connection came in on, so a question made
# moot (its network was just marked as a network you trust) can be taken off the screen instead of waiting there for 15 min
OPEN_HOLD_CARDS = set()          # the outage notice; closed on recovery without touching incoming questions
OPEN_DRIFT_CARDS = set()         # outside changes; kept separate from incoming connection questions
OPEN_TRIAL_CARDS = set()         # waiting for Keep; withdrawn when reviewed or resolved
OPEN_PAUSED_CARDS = set()        # "the app firewall is paused"; closed when the app checker is checking again
OPEN_DOWN_CARDS = set()          # "The firewall isn't running"; closed once the rules run again or it is turned off
OPEN_QUESTIONS = {}
OPEN_LOCK = threading.Lock()
MOOT_QUESTIONS = set()                        # card ids closed because they no longer need an answer (see below)
# ...and which connection each one asks about (address, tcp/udp, port): one let in for 15 minutes from Settings ›
# Firewall > Log comes off the screen too, instead of still offering Keep blocked / Allow for something already allowed
OPEN_CONNS = {}


def notify(title: str, body: str, actions: list = (), icon: str = "dialog-information", urgency: str = "normal",
           replace: str = "", want_id: bool = False, stay: bool = False, zone: str = "", conn: tuple = (),
           warn: str = "", close_after: float = 0, bell_only: bool = False, on_shown=None, question=None) -> str:
    """Show a notification; with actions, wait for the answer and return it. replace: the id of an earlier card to
    replace (notify-send -r); want_id: return the new card's id instead (notify-send -p, no actions); stay: it stays
    up until answered or closed (notify-send -t 0), without the alarm look of a critical one. bell_only sends
    straight to the bell without a popup or chime and leaves the server's timeout alone; on_shown runs only after
    a notification id confirms delivery. zone (an incoming
    question): the card's id is kept in OPEN_QUESTIONS while it waits (notify-send -p prints it before the answer),
    with conn, the (address, protocol, port, interface) it asks about, in OPEN_CONNS. warn: the key of the one button that can
    do harm (Allow always for an internet sender), sent as the x-starchaser-warn-action hint so the cockpit draws
    that button in the warning color; the body says why in words, so the hint is never the only sign.
    zone="outgoing" marks a question that must never fold or expire, without the incoming question bookkeeping.
    close_after (a question): taken off the screen after that many seconds unanswered (answers ""), when an answer
    after that would do nothing. Outgoing cards stay up; their late answers govern the next connections."""
    # testing (the QA runs): STARCHASER_FIREWALL_ASK_ANSWER=deny|once|always answers every question by itself,
    # and each question is logged to $XDG_RUNTIME_DIR/starchaser-firewall-ask.log
    auto = os.environ.get("STARCHASER_FIREWALL_ASK_ANSWER", "")
    if auto or os.environ.get("STARCHASER_FIREWALL_ASK_LOG"):
        with open(Path(os.environ.get("XDG_RUNTIME_DIR", "/tmp")) / "starchaser-firewall-ask.log", "a") as f:
            f.write(json.dumps({"time": int(time.time()), "title": title, "body": body, "answer": auto if actions else ""}) + "\n")
    if auto and actions:
        if on_shown:
            on_shown()
        return auto
    if zone == "outgoing" and question is not None:
        return outgoing_window(question)
    cmd = [*['/bin/sh', '-c', 'token="${XDG_RUNTIME_DIR:-/run/user/$(/usr/bin/id -u)}/starchaser-notifications/token"; if [ -r "$token" ]; then n=$1; shift; exec "$0" "$n" --credential-fd=3 "$@" 3<"$token"; else exec "$0" "$@"; fi'], "starchaser", "notify", "-a", "Starchaser", "-i", icon, "-u", urgency]
    if bell_only:
        cmd += ["-h", "boolean:x-starchaser-bell-only:true"]
    if replace:
        cmd += ["-r", replace]
    if warn:
        cmd += ["-h", f"string:x-starchaser-warn-action:{warn}"]
    if stay and not bell_only:
        cmd += ["-t", "0"]
    if zone == "outgoing":
        cmd += ["-h", "string:x-starchaser-ask:outgoing", "-h", "string:x-starchaser-answered:drop"]
    if zone == "trial":
        # Retired countdowns must also leave notification history.
        cmd += ["-h", "boolean:x-starchaser-transient:true"]
    if conn and actions:
        # Keep the Log route usable in the bell after this question is withdrawn.
        cmd += ["-h", "string:x-starchaser-firewall-log:" + "|".join(map(str, conn))]
    if want_id and not actions:
        cmd.append("-p")
    for key, label in actions:
        cmd += ["-A", f"{key}={label}"]
    if actions:
        cmd.append("-w")
    if actions and ((zone and zone != "outgoing") or close_after):
        return _notify_tracked(cmd + ["-p", title, body], zone, conn, close_after, on_shown, bell_only)
    try:
        # Outgoing questions wait until answered. Other persistent cards wait for a day to bound a lost server.
        return subprocess.run(cmd + [title, body], capture_output=True, text=True,
                              timeout=None if zone == "outgoing" else (86400 if stay else 600)).stdout.strip()
    except subprocess.TimeoutExpired:
        return ""


def _notify_tracked(cmd: list, zone: str, conn: tuple = (), close_after: float = 0, on_shown=None,
                    bell_only: bool = False) -> str:
    """An incoming question that can be taken back: the first line notify-send prints is the card's id (-p), the
    next the answer. A card closed by close_moot_questions() or watch_allowed() answers "moot" (no quiet time: the
    device's next try asks again, on the network as it counts now, if it's still turned away); one closed by hand
    answers nothing."""
    try:
        proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
    except OSError:
        return ""
    # both lines are read from the one buffered stream (communicate() after readline() would skip an answer the
    # first read already took in); the timer only ends a wait the notification server lost. A bell-only notice stays
    # in the bell until answered, so its wait is a day (like the outage card): after 10 minutes a late answer from
    # the bell would have reached a notify-send already killed, and done nothing
    timer = threading.Timer(86400 if zone in ("outgoing-hold", "checker-paused", "drift", "down") or bell_only else 600, proc.kill)
    timer.start()
    nid, lines, expire = "", [], None
    try:
        nid = (proc.stdout.readline() or "").strip()
        if nid.isdigit() and on_shown:
            on_shown()
        if nid.isdigit() and zone in ("outgoing-hold", "checker-paused", "drift", "trial", "down"):
            with OPEN_LOCK:
                {"trial": OPEN_TRIAL_CARDS, "drift": OPEN_DRIFT_CARDS, "down": OPEN_DOWN_CARDS,
                 "checker-paused": OPEN_PAUSED_CARDS}.get(zone, OPEN_HOLD_CARDS).add(nid)
        elif nid.isdigit() and zone:
            with OPEN_LOCK:
                OPEN_QUESTIONS[nid] = zone
                if conn:
                    OPEN_CONNS[nid] = conn
            # The policy may have turned Off while notify-send was printing the id, after the watch's last pass.
            if firewall_is_off():
                close_off_questions()
        if nid.isdigit() and close_after:
            expire = threading.Timer(close_after, close_card, args=(nid,))
            expire.daemon = True
            expire.start()
        lines = [x.strip() for x in proc.stdout.read().splitlines() if x.strip()]
        proc.wait()
    except (OSError, ValueError):
        pass
    finally:
        timer.cancel()
        if expire is not None:
            expire.cancel()
        with OPEN_LOCK:
            OPEN_HOLD_CARDS.discard(nid)
            OPEN_DRIFT_CARDS.discard(nid)
            OPEN_TRIAL_CARDS.discard(nid)
            OPEN_DOWN_CARDS.discard(nid)
            OPEN_PAUSED_CARDS.discard(nid)
            OPEN_QUESTIONS.pop(nid, None)
            OPEN_CONNS.pop(nid, None)
            moot = nid in MOOT_QUESTIONS
            MOOT_QUESTIONS.discard(nid)
    if moot:
        return "moot"
    return lines[-1] if lines else ("" if nid.isdigit() else nid)


def close_off_questions() -> None:
    """Retire incoming answers when Off, and leave a dismissible explanation with no action buttons."""
    with OPEN_LOCK:
        ids = list(OPEN_QUESTIONS)
        MOOT_QUESTIONS.update(ids)
        for nid in ids:
            OPEN_QUESTIONS.pop(nid, None)
            OPEN_CONNS.pop(nid, None)
    for nid in ids:
        close_card(nid, "the firewall is Off, so its incoming question is moot")
    if ids:
        # One explanation for all cleared questions; clear it after a minute so it is not
        # still listed once the firewall is back on.
        new_id = notify("Connection questions cleared", "The firewall was turned off, so nobody is being turned away.",
                        icon="dialog-information", want_id=True)
        if str(new_id).isdigit():
            t = threading.Timer(60, close_card, args=(str(new_id),))
            t.daemon = True
            t.start()


def close_moot_questions() -> None:
    """A network was just marked as a network you trust: when no network this computer is on still counts as Public, the
    questions about connections that came in on a public network are moot (they'd now be let in, or the rules
    decide), so they come off the screen. Another public network still connected keeps them."""
    pol = policy()
    if not isinstance(pol, dict):
        return
    # each connected network's zone as the firewall applies it: its own mark, else the one for unmarked networks (a
    # network marked Public stays Public even when unmarked ones count as Trusted). Also run on any policy change
    # (watch_allowed), so an unrelated edit, or no network read at all, must never close a question still blocked.
    zones = {str(n.get("uuid")): n.get("zone") for n in pol.get("networks") or [] if isinstance(n, dict)}
    unknown = pol.get("unknownZone") or "public"
    nets = connected_networks()
    if not nets or any((zones.get(n["uuid"]) or unknown) != "trusted" for n in nets):
        return
    with OPEN_LOCK:
        moot = [nid for nid, z in OPEN_QUESTIONS.items() if z == "public"]
        MOOT_QUESTIONS.update(moot)
    for nid in moot:
        close_card(nid, "a network you're on was marked Trusted, so its incoming question is moot")


def same_addr(a: str, b: str) -> bool:
    try:
        return ipaddress.ip_address(a) == ipaddress.ip_address(b)
    except ValueError:
        return a == b


def once_covers(o: dict, conn: tuple) -> bool:
    """A running temporary permission lets this question's connection in. addr "any" (Simple's For 15 minutes) is
    every device on its network adapter, and always names one, so the adapter must match."""
    src, proto, port = conn[:3]
    iface = conn[3] if len(conn) > 3 else ""
    addr = str(o.get("addr") or "")
    if o.get("proto") != proto or str(o.get("port")) != str(port):
        return False
    if addr == "any":
        return bool(o.get("iface")) and o["iface"] == iface
    return same_addr(addr, src) and (not o.get("iface") or o["iface"] == iface)


def saved_connection_allowed(conn: tuple, state: dict) -> bool:
    """Retire a past question only when the running saved rules unconditionally allow its exact scope."""
    mod, pol = engine(), policy()
    if not mod or not pol.get("enabled") or len(conn) < 4 or not conn[3]:
        return False
    live = state.get("live") or {}
    if not live.get("loaded") or live.get("matches") is not True or not 0 <= time.time() - state.get("updated", 0) < STATS_FRESH:
        return False
    if state.get("updated", 0) < last_change():
        return False
    src, proto, port, iface = conn[:4]
    if iface in (state.get("publicPause") or {}).get("ifaces", []):
        return False
    try:
        # Hand-written rules precede Settings rules; their effect cannot be inferred safely here.
        if mod.loaded_extra_lines() != []:
            return False
        zmap = zones_now()
        zone = zone_of(iface, zmap)
        groups = mod.peer_groups(pol, src)
        for rule, ports, _ in mod.inbound(pol, mod.catalog(), {}, zmap.get("report") or {}):
            if not (mod.zone_matches(rule, zone) and mod.peer_matches(rule, groups)
                    and mod.interface_matches(rule, iface) and mod.port_matches(ports, proto, int(port))):
                continue
            if rule.get("network") and iface not in (zmap.get("netIfaces") or {}).get(rule["network"], []):
                continue
            # A conditional restriction might still stop this attempt; keep its review available.
            return rule["action"] == "allow" and not (rule.get("rate") or rule.get("sport"))
    except (OSError, ValueError, TypeError, KeyError):
        return False
    return False


def watch_allowed(changes=None) -> None:
    """A question on screen about a connection that has since been let in for a limited time (Allow for 15 min in
    Settings > Firewall > Log, or from the command line) comes off the screen: its Keep blocked and Allow would answer
    something already decided. Read from the root-side stats file, which an allow rewrites at once. Saved rules
    also retire covered questions once the running firewall is verified, including their order and network limits.
    A question from a public network also comes off the screen when that network is marked as a network you trust somewhere else
    (Settings > Firewall, or the command line), not only by this asker's own Yes: checked when the policy file changes.
    When the firewall turns Off, close all incoming questions and show one dismissible explanation with no actions."""
    seen = None
    while True:
        pause(3, bool(OPEN_CONNS or OPEN_QUESTIONS), changes)
        if firewall_is_off():
            close_off_questions()
            continue
        with OPEN_LOCK:
            conns = dict(OPEN_CONNS)
            public_open = any(z == "public" for z in OPEN_QUESTIONS.values())
        try:
            stamp = POLICY.stat().st_mtime_ns
        except OSError:
            stamp = None
        if stamp != seen:
            if seen is not None and public_open:
                try:
                    close_moot_questions()
                except Exception as e:                 # never let it end this watch (the 15-minute allows use it too)
                    print(f"starchaser firewall ask: checking open questions: {e}", file=sys.stderr, flush=True)
            seen = stamp
        if not conns:
            continue
        try:
            state = json.loads(STATS.read_text())
            once = state.get("allowedOnce") or []
        except (OSError, ValueError, AttributeError):
            continue
        now = time.time()
        live = [o for o in once if isinstance(o, dict) and (o.get("until") or 0) > now]
        moot = [nid for nid, conn in conns.items()
                if saved_connection_allowed(conn, state) or any(once_covers(o, conn) for o in live)]
        if not moot:
            continue
        with OPEN_LOCK:
            moot = [nid for nid in moot if nid in OPEN_QUESTIONS]
            MOOT_QUESTIONS.update(moot)
        for nid in moot:
            close_card(nid, "that connection is covered by a current permission")


def catalog_apps() -> list:
    for f in (CATALOG, CATALOG_REPO):
        try:
            apps = json.loads(f.read_text()).get("apps") or []
            if apps:
                return apps
        except (OSError, ValueError, AttributeError):
            continue
    return []


def usual_app(proto: str, port: int) -> str:
    """The app that usually uses this port, in the words Settings > Firewall uses ("Remote login"), or "". Only ever
    shown as "usually used by": the port alone doesn't prove which program the connection was meant for."""
    for a in catalog_apps():
        for p in a.get("in") or []:
            m = re.fullmatch(r"(tcp|udp):(\d+)(?:-(\d+))?", str(p))
            if m and m.group(1) == proto and int(m.group(2)) <= port <= int(m.group(3) or m.group(2)):
                return a.get("plain") or a.get("name") or ""
    if port in SERVICES:
        return SERVICES[port]
    if port < 1024:                       # the system's names for high ports are cryptic ("sac"): only trust the classic ones
        try:
            return socket.getservbyport(port, proto).upper()
        except OSError:
            pass
    return ""


def port_text(proto: str, port: int) -> str:
    """Name the port; a usual app is a guess, not the program's identity."""
    app = usual_app(proto, port)
    return (f"a port usually used by {app} ({proto.upper()} port {port})" if app
            else f"{proto.upper()} port {port} (app not identified)")


def is_internet(addr: str) -> bool:
    """An address out on the internet (not this network's, a private range, link-local or Tailscale's)."""
    try:
        ip = ipaddress.ip_address(addr)
    except ValueError:
        return False
    if ip in ipaddress.ip_network("100.64.0.0/10"):         # Tailscale / carrier-grade NAT: not "the internet" here
        return False
    return ip.is_global


def ephemeral(port: int) -> bool:
    """Whether a port is in the range this computer picks from for its own outgoing connections."""
    try:
        lo, hi = (int(x) for x in Path("/proc/sys/net/ipv4/ip_local_port_range").read_text().split()[:2])
    except (OSError, ValueError):
        lo, hi = 32768, 60999
    return lo <= port <= hi


def listening(proto: str, port: int):
    """True when something on this computer listens on that port (any user's program: ss lists them all without
    root), False when nothing does, None when ss can't tell."""
    try:
        r = subprocess.run(["ss", "-H", "-ln" + ("t" if proto == "tcp" else "u"), f"sport = :{port}"],
                           capture_output=True, text=True, timeout=5)
    except (OSError, subprocess.SubprocessError):
        return None
    if r.returncode != 0:
        return None
    return bool(r.stdout.strip())


def fleet_name(addr: str) -> str:
    """The fleet's name for a sender, only when the address is where a paired Starchaser computer answered from
    recently over its pinned host key (starchaser link's list writes that). A stored or typed address is never
    enough: the network can give it to anyone after the computer moves."""
    try:
        peers = json.loads(PEERS.read_text())
    except (OSError, ValueError):
        return ""
    dev = next((p.get("id") for p in peers if isinstance(p, dict) and p.get("address") == addr
                and isinstance(p.get("lastSeen"), int) and time.time() - p["lastSeen"] < SEEN_FOR), None) \
        if isinstance(peers, list) else None
    if not isinstance(dev, str):
        return ""
    try:
        for m in json.loads(FLEET.read_text()).get("machines", []):
            if isinstance(m, dict) and (m.get("link") or {}).get("device") == dev:
                return str(m.get("name") or "")[:60]
    except (OSError, ValueError, AttributeError):
        pass
    p = next((p for p in peers if p.get("id") == dev), {})
    return str(p.get("name") or "")[:40]


def device_name(addr: str) -> tuple:
    """(name, where it came from): "yours" = the firewall's own name for it or your devices list (names you chose),
    "dns" = what the network's DNS says, which the device itself usually picked; ("", "") when nothing knows it."""
    for a in policy().get("addresses", []):
        if addr in a.get("addrs", []) or f"{addr}/32" in a.get("addrs", []):
            return (a.get("name") or "", "yours")
    fleet = fleet_name(addr)
    if fleet:
        return (fleet, "yours")
    # The same device should read the same way every time: a lookup that answers after the 1.5 s wait still lands
    # in the cache, so the next question uses its name (once it said "A device calling itself pc (…)", the next
    # time only the address, when DNS was slow).
    now = time.time()
    with _names_lock:
        hit = _names.get(addr)
        if hit and now - hit[0] < NAME_TTL:
            return (hit[1], "dns") if hit[1] else ("", "")
        busy = addr in _looking
        _looking.add(addr)

    def look():
        n = ""
        try:
            n = socket.gethostbyaddr(addr)[0]
        except (OSError, UnicodeError):              # no name (socket.herror is an OSError)
            pass
        n = re.sub(r"[^\w.-]", "", n.split(".")[0])[:40]
        with _names_lock:
            now2 = time.time()
            for k in [k for k, v in _names.items() if now2 - v[0] >= NAME_TTL]:   # a busy network: don't grow forever
                del _names[k]
            _names[addr] = (now2, n)
            _looking.discard(addr)
            # Let Log show the same announced names as the notification, without doing DNS on every page read.
            path = RUNTIME / "starchaser-firewall-device-names.json"
            tmp = None
            try:
                with tempfile.NamedTemporaryFile(mode="w", dir=RUNTIME, prefix=".firewall-device-names-", delete=False) as handle:
                    tmp = Path(handle.name)
                    json.dump(_names, handle)
                tmp.replace(path)
            except OSError:
                pass
            finally:
                if tmp is not None:
                    tmp.unlink(missing_ok=True)
    if not busy:
        t = threading.Thread(target=look, daemon=True)
        t.start()
        t.join(1.5)                                            # never wait long on DNS
    with _names_lock:
        hit = _names.get(addr)
    return (hit[1], "dns") if hit and hit[1] else ("", "")


_names = {}                    # address -> (when looked up, DNS name or "")
_names_lock = threading.Lock()
_looking = set()               # addresses with a lookup still running
NAME_TTL = 600


def who_label(addr: str, name: str, source: str, *, fragment: bool = False) -> str:
    """How a device is named on screen: the address alone when that's all there is (or the name is the address)."""
    if not name or name == addr:
        return addr
    if source == "dns":
        return f"{'a' if fragment else 'A'} device calling itself {name} ({addr})"
    return f"{name} ({addr})"


def area_knows(cmd: str) -> bool:
    """Whether the installed password door lists this command (an older door exists but refuses the firewall ones)."""
    if not os.access(AREA, os.X_OK):
        return False
    try:
        r = subprocess.run([AREA, "commands"], capture_output=True, text=True, timeout=10)
        return cmd in json.loads(r.stdout.strip().splitlines()[-1]).get("commands", [])
    except (OSError, subprocess.TimeoutExpired, ValueError, IndexError, AttributeError):
        return False


def run_in_session(argv) -> tuple:
    """Start pkexec through Hyprland so logind can find the desktop's password agent."""
    def direct():
        r = subprocess.run(argv, capture_output=True, text=True)
        return r.returncode, r.stdout, r.stderr

    if not shutil.which("hyprctl"):
        return direct()
    env = dict(os.environ, XDG_RUNTIME_DIR=str(RUNTIME))
    if not env.get("HYPRLAND_INSTANCE_SIGNATURE"):
        try:
            instances = [p for p in (RUNTIME / "hypr").glob("*") if p.is_dir()]
            env["HYPRLAND_INSTANCE_SIGNATURE"] = max(instances, key=lambda p: p.stat().st_mtime).name
        except (OSError, ValueError):
            return direct()
    try:
        directory = tempfile.TemporaryDirectory(prefix="starchaser-firewall-auth-", dir=RUNTIME)
    except OSError:
        return direct()
    with directory as folder:
        work = Path(folder)
        script, rcfile = work / "run", work / "rc"
        q = lambda name: shlex.quote(str(work / name))
        try:
            script.write_text("#!/bin/sh\numask 077\n"
                              f"echo $$ > {q('pid')}\n"
                              + " ".join(shlex.quote(str(a)) for a in argv)
                              + f" > {q('stdout')} 2> {q('stderr')}\n"
                              + f"echo $? > {q('rc.part')}\nmv {q('rc.part')} {q('rc')}\n")
            script.chmod(0o700)
            command = "hl.dsp.exec_cmd(" + json.dumps(shlex.quote(str(script)), ensure_ascii=False) + ")"
            dispatch = subprocess.run(["hyprctl", "dispatch", command], env=env,
                                      capture_output=True, text=True, timeout=10)
        except (OSError, subprocess.TimeoutExpired):
            return direct()
        if dispatch.returncode != 0:
            return direct()
        # A password box can stay open for ten minutes. Once dispatched, never retry directly:
        # that could open a second box or apply the same change twice.
        deadline = time.monotonic() + 600
        while time.monotonic() < deadline:
            if rcfile.exists():
                try:
                    return int(rcfile.read_text().strip()), (work / "stdout").read_text(), (work / "stderr").read_text()
                except (OSError, ValueError):
                    break                             # the wrapper publishes rc atomically; an invalid result cannot be retried
            try:
                if not script.exists():
                    break
                pidfile = work / "pid"
                if pidfile.exists():
                    pid = pidfile.read_text().strip()
                    if not pid.isdigit():
                        break
                    stat = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
                    if stat[0] in ("Z", "X", "x"):
                        break
            except (OSError, ValueError, IndexError):
                # The wrapper may have exited just as its result arrived.
                if rcfile.exists():
                    continue
                break
            time.sleep(0.1)
        return 127, "", "Not changed: the password request did not finish."


def settings_review(target):
    if target == "privacy": target = "network-privacy"
    subprocess.Popen(["starchaser", "settings", "firewall", "@" + target], start_new_session=True,
                     stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def allowed_confirmation(title, body, undo, label="Undo…"):
    """Wait outside the question worker; an old confirmation must never restore an old whole policy."""
    try:
        if notify(title, body, [("undo", label)], icon="security-high", bell_only=True) == "undo":
            undo()
    except OSError:
        pass


def admin(*args) -> dict:
    # the password prompt (pkexec); in a test run (answers given by env) passwordless sudo stands in for it
    via = ["pkexec"]
    if os.environ.get("STARCHASER_FIREWALL_ASK_ANSWER") and subprocess.run(["sudo", "-n", "true"], capture_output=True).returncode == 0:
        via = ["sudo", "-n"]
    door = AREA if args and args[0] in AREA_COMMANDS and area_knows(args[0]) else ADMIN
    argv = [*via, door, *args]
    if via[0] == "pkexec":
        rc, stdout, stderr = run_in_session(argv)
        r = subprocess.CompletedProcess(argv, rc, stdout, stderr)
    else:
        r = subprocess.run(argv, capture_output=True, text=True)
    # Treat an explicit dismissal as cancellation, even if a wrapper reports it with 127.
    # A bare 127 / "Not authorized" still means permission failed; never infer a cancellation from it.
    canceled = via[0] == "pkexec" and (r.returncode == 126 or
               (r.returncode == 127 and "request dismissed" in (r.stderr or "").lower()))
    dbg(f"admin {args[0] if args else '?'} via {door}: exit {r.returncode}, canceled={canceled}")
    if canceled:
        return {"ok": False, "canceled": True, "errors": "Not changed: you closed the password box."}
    try:
        return json.loads(r.stdout.strip().splitlines()[-1])
    except (ValueError, IndexError):
        if r.returncode == 127:
            return {"ok": False, "errors": "Not changed: Starchaser couldn't get permission. Try again; if no password box appears, sign out and back in."}
        return {"ok": False, "errors": r.stderr.strip() or "Not changed."}


# ---------------------------------------------------------------------------------------------- incoming
QUIET_DISMISSED = 1800         # session quiet time; the saved program/network record prevents repeat notices
# device discovery and name lookups: never a connection someone means to make to this computer (protocol, port)
DISCOVERY = {("udp", 137), ("udp", 138), ("udp", 1900), ("udp", 3702), ("udp", 5353), ("udp", 5355), ("tcp", 5355)}
# what Starchaser's own computers reach each other on (firewall.FLEET_APPS: remote login, the fast terminal, fleet
# joining, device finding, game streaming, Mission Control)
FLEET_PORTS = {("tcp", 22), ("tcp", 47744), ("tcp", 9090), ("udp", 5353), ("tcp", 47984), ("tcp", 47989),
               ("tcp", 47990), ("tcp", 48010), ("udp", 48002), ("udp", 48010),
               *(("udp", p) for p in range(47998, 48001)), *(("udp", p) for p in range(61000, 62001))}
ZONEMAP = Path("/run/starchaser/firewall-zones.json")     # the root side's zones and networks (world-readable)


def zones_now() -> dict:
    try:
        d = json.loads(ZONEMAP.read_text())
        return d if isinstance(d, dict) else {}
    except (OSError, ValueError):
        return {}


def zone_of(iface: str, zmap: dict = None) -> str:
    """The kind of network an interface counts as now ("other": in none); "" when the zones can't be read."""
    zmap = zones_now() if zmap is None else zmap
    zones = zmap.get("zones")
    if not isinstance(zones, dict):
        return ""
    return next((z for z, devs in zones.items() if iface in (devs or [])), "other")


def network_of(iface: str, zmap: dict = None) -> str:
    """The network (NetworkManager's id) an interface is connected to now, or ""."""
    zmap = zones_now() if zmap is None else zmap
    return next((str(n.get("uuid")) for n in zmap.get("networks") or []
                 if isinstance(n, dict) and n.get("device") == iface and n.get("uuid")), "")


def already_allowed(src: str, zone: str, proto: str, port: int) -> bool:
    """Whether your rules let this device in on that port on that kind of network now (an Allow always answered
    earlier, or a rule made in Settings): then it was turned away only in the moment before they applied, and
    asking again would ask about something already decided. The engine's own reading of the rules (reachable)."""
    mod, pol = engine(), policy()
    if not mod or not pol.get("enabled") or zone not in ZONE_WORDS:
        return False
    try:
        ok, rid = mod.reachable(pol, zone, src, proto, port, live={}, known=zones_now().get("report") or None)
        return bool(ok and rid)
    except Exception:
        return False


def trust_would_allow(src: str, proto: str, port: int):
    """Whether your rules would let this device in on that port once its network is Trusted: True or False, or
    None when the rules can't be read (then the notice makes no claim either way)."""
    mod, pol = engine(), policy()
    if not mod or not pol.get("enabled"):
        return None
    try:
        ok, rid = mod.reachable(pol, "trusted", src, proto, port, live={}, known=zones_now().get("report") or None)
        return bool(ok and rid)
    except Exception:
        return None


_nearby = {"time": 0.0, "addrs": set()}
_nearby_lock = threading.Lock()


def nearby_starchaser() -> set:
    """Addresses of Starchaser computers announcing themselves on the local network (the same announcement
    starchaser link's pairing looks for), looked up at most every two minutes."""
    with _nearby_lock:
        if time.time() - _nearby["time"] < 120:
            return set(_nearby["addrs"])
        _nearby["time"] = time.time()
    addrs = set()
    try:
        r = subprocess.run(["avahi-browse", "-rpt", "-k", "_starchaser._tcp"], capture_output=True, text=True, timeout=6)
        for line in r.stdout.splitlines():
            f = line.split(";")
            if len(f) >= 8 and f[0] == "=":
                addrs.add(f[7])
    except (OSError, subprocess.SubprocessError):
        pass
    with _nearby_lock:
        _nearby["addrs"] = addrs
    return addrs


def fleet_addresses() -> set:
    """Every address your fleet's computers are known by: paired devices (any address they were seen at), the
    fleet's list, and Starchaser computers announcing themselves nearby. Only ever used to NOT ask about a
    connection (which stays blocked): an address someone else could have is fine for that."""
    out = set()
    try:
        for p in json.loads(PEERS.read_text()) or []:
            if isinstance(p, dict):
                out.update(str(a) for a in [p.get("address"), p.get("tailscale"), *(p.get("addresses") or [])] if a)
    except (OSError, ValueError, TypeError):
        pass
    try:
        for m in json.loads(FLEET.read_text()).get("machines") or []:
            a = (m.get("addresses") or {}) if isinstance(m, dict) else {}
            if isinstance(a, dict):
                out.update(str(x) for x in [a.get("last"), a.get("tailscale"), *(a.get("lan") or [])] if x)
    except (OSError, ValueError, AttributeError, TypeError):
        pass
    return out


def fleet_member(src: str) -> bool:
    if fleet_name(src):
        return True
    known = fleet_addresses()
    return any(same_addr(src, a) for a in known) or any(same_addr(src, a) for a in nearby_starchaser())
MAX_OPEN = 2                   # notices waiting for actions; excess traffic stays in the Log


NOTICE_STATE = Path(os.environ.get("XDG_STATE_HOME") or HOME / ".local/state") / "starchaser/firewall-ask-notified.json"
NOTICE_LOCK = threading.Lock()
PENDING_NOTICES = set()
# Display only: listener_name() and notice/rule identity keep the verified executable basename.
LISTENER_LABELS = {"sshd": "Remote login", "sunshine": "Remote desktop streaming",
                   "smbd": "Shared folders", "cupsd": "Printer sharing"}


def listener_name(proto: str, port: int) -> str:
    """A recent root check must name a verified listener on this port."""
    try:
        data = json.loads(STATS.read_text())
        age = time.time() - data["updated"]
        if not 0 <= age <= STATS_FRESH:
            return ""
        return next((entry["name"] for entry in data.get("listeners", [])
                     if entry.get("proto") == proto and entry.get("port") == port
                     and isinstance(entry.get("name"), str) and entry["name"]), "")
    except (OSError, ValueError, TypeError, KeyError, AttributeError):
        return ""


def listener_label(proto: str, port: int, program: str) -> str:
    """Use a verified service's catalog name only on its own ports; unknown runtimes stay generic."""
    try:
        data = json.loads(STATS.read_text())
        if 0 <= time.time() - data["updated"] <= STATS_FRESH:
            hit = next((entry for entry in data.get("listeners", [])
                        if entry.get("proto") == proto and entry.get("port") == port
                        and entry.get("name") == program), {})
            for app in catalog_apps():
                if not hit.get("service") or app.get("listenerService") != hit["service"]:
                    continue
                for spec in app.get("in", []):
                    m = re.fullmatch(r"(tcp|udp):(\d+)(?:-(\d+))?", spec)
                    if m and m[1] == proto and int(m[2]) <= port <= int(m[3] or m[2]):
                        return app.get("listenerName") or app.get("plain") or app["name"]
    except (OSError, ValueError, TypeError, KeyError, AttributeError):
        pass
    return "Python" if re.fullmatch(r"python(?:[0-9]+(?:\.[0-9]+)*)?", program) else LISTENER_LABELS.get(program, program)


def notified_programs() -> dict:
    try:
        data = json.loads(NOTICE_STATE.read_text())
        return {k: v for k, v in data.items() if isinstance(k, str) and isinstance(v, (float, int))}
    except (OSError, ValueError, AttributeError):
        return {}


def forget_notified(key: str) -> None:
    with NOTICE_LOCK:     # the same lock as every other read-modify-write of the notice state (r138 review)
        data = notified_programs()
        if data.pop(key, None) is None:
            return
        try:
            NOTICE_STATE.write_text(json.dumps(data))
        except OSError:
            pass


def cancel_nothing_changed(key: str) -> None:
    """The password box was canceled: say so calmly, and let the device's next try ask again right away."""
    forget_notified(key)
    notify("Nothing changed", "You canceled, so nothing was allowed.", icon="dialog-information")


def remember_notified(key: str) -> None:
    data = notified_programs()
    data[key] = time.time()
    data = dict(sorted(data.items(), key=lambda item: item[1])[-500:])
    try:
        NOTICE_STATE.parent.mkdir(parents=True, exist_ok=True)
        with tempfile.NamedTemporaryFile("w", dir=NOTICE_STATE.parent, prefix=".firewall-ask-notified-", delete=False) as f:
            tmp = Path(f.name)
            json.dump(data, f)
            f.write("\n")
        tmp.replace(NOTICE_STATE)
    except OSError:
        if "tmp" in locals():
            tmp.unlink(missing_ok=True)


class Incoming:
    def __init__(self):
        self.quiet = {}            # (src, proto, port), (src, "*", 0) or ("*", proto, port) -> until
        self.asking = set()
        self.recent = {}           # src -> [(time, port)]
        self.by_port = {}          # (proto, port) -> [(time, src)]: many devices on one port is a sweep
        # answers given this session: (src, proto, port, where) -> the answer; where is the network's id (an answer
        # for that network), "zone:<kind>" (Allow always: every network of that kind) or "*" (Keep blocked: anywhere)
        self.answered = {}
        self.tries = {}            # (src, proto, port) -> how many times it was turned away since it was last asked
        self.lock = threading.Lock()
        self.listener_tried: dict = {}   # (src, proto, port) -> when its one quick re-look was given (r174)
        self.listener_check = 0.0  # when a skip last asked root for a fresh listeners check

    def was_answered(self, src: str, proto: str, port: int, zone: str, net: str) -> bool:
        """(holding the lock) whether this was answered this session, for this network or wider."""
        return any((src, proto, port, w) in self.answered for w in ("*", f"zone:{zone}", net) if w)

    def seen(self, src: str, dst: str, proto: str, port: int, zone: str = "", iface: str = "", usec: str = "") -> None:
        if is_internet(src) or zone not in ZONE_WORDS:
            return
        if (proto, port) in DISCOVERY:                       # device discovery and name lookups: never asked
            return
        try:
            if ipaddress.ip_address(dst).is_multicast or dst.endswith(".255"):
                return
            src = ipaddress.ip_address(src).compressed    # the kernel writes IPv6 in full
        except ValueError:
            return
        net = network_of(iface) if iface else ""
        now = time.time()
        with self.lock:
            self._prune(now)
            self.tries[(src, proto, port)] = self.tries.get((src, proto, port), 0) + 1
            if self.was_answered(src, proto, port, zone, net):
                return                                    # answered already: the Log has the rest
            hits = [(t, p) for t, p in self.recent.get(src, []) if now - t < 30] + [(now, port)]
            self.recent[src] = hits
            sweep = [(t, s) for t, s in self.by_port.get((proto, port), []) if now - t < 30 and s != src] + [(now, src)]
            self.by_port[(proto, port)] = sweep
            for key in ((src, proto, port), (src, "*", 0), ("*", proto, port)):
                if self.quiet.get(key, 0) > now:
                    return
            if len({p for _, p in hits}) > 4:                 # many ports from one device: a scan, Log only
                self.quiet[(src, "*", 0)] = now + 1800
                return
            if len({s for _, s in sweep}) > 3:                # many devices on one port: a sweep, Log only
                self.quiet[("*", proto, port)] = now + 1800
                return
            if (src, proto, port) in self.asking:
                return
            if len(self.asking) >= MAX_OPEN:
                return                                    # excess traffic stays in the Log
            self.asking.add((src, proto, port))
        threading.Thread(target=self.ask, args=(src, proto, port), kwargs={"zone": zone, "iface": iface, "net": net, "usec": usec},
                         daemon=True).start()

    PRUNE_EVERY = 60               # seconds between sweeps of the tracking maps
    MAX_TRACKED = 4096             # sources (and ports) tracked at once: a flood from many addresses can't grow it

    def _prune(self, now: float) -> None:
        """(holding the lock) drop what can't matter any more: hits older than the 30-second window, quiet times
        that ran out; and, past MAX_TRACKED, the oldest sources. Without it, probes from ever new addresses
        (a hostile network) would grow these maps for as long as the session lasts."""
        if now - getattr(self, "_pruned", 0) < self.PRUNE_EVERY and len(self.recent) < self.MAX_TRACKED \
                and len(self.by_port) < self.MAX_TRACKED and len(self.quiet) < self.MAX_TRACKED:
            return
        self._pruned = now
        for m in (self.recent, self.by_port):
            for k in [k for k, v in m.items() if not any(now - x[0] < 30 for x in v)]:
                del m[k]
            if len(m) > self.MAX_TRACKED:
                for k in sorted(m, key=lambda k: max(x[0] for x in m[k]))[:len(m) - self.MAX_TRACKED]:
                    del m[k]
        for k in [k for k, until in self.quiet.items() if until <= now]:
            del self.quiet[k]
        if len(self.tries) > self.MAX_TRACKED:            # counts only matter while a card may still show them
            for k in [k for k in self.tries if k not in self.asking][:len(self.tries) - self.MAX_TRACKED]:
                del self.tries[k]
        if len(self.answered) > 4 * self.MAX_TRACKED:     # a hostile network can't grow it forever either
            for k in list(self.answered)[:len(self.answered) - 4 * self.MAX_TRACKED]:
                del self.answered[k]
        if len(self.quiet) > self.MAX_TRACKED:         # (the shortest quiet times go first)
            for k in sorted(self.quiet, key=self.quiet.get)[:len(self.quiet) - self.MAX_TRACKED]:
                del self.quiet[k]

    SKIP_QUIET = 60                # a sighting not worth asking about: its next ones aren't looked at for a minute
    # "no system listener" is often only a root check that hasn't seen a program that just started (it runs every
    # 60 s): the device's retries are looked at again soon, after a fresh check, instead of a minute later (r174)
    LISTENER_QUIET = 10

    def worth_asking(self, src: str, proto: str, port: int, zone: str, iface: str) -> str:
        """The checks a question waits for (see "Not asked" above): "" to ask, else why not (the Log lists it)."""
        # logged while its network was still connecting (z=other, or the kind it had before): the network's kind
        # now decides, and the device's next try (a retry comes within seconds) is logged under it
        if iface:
            now = zone_of(iface)
            if now and now != (zone or "other"):
                return "zone"
        # nothing listens on that port: allowing it would let nothing in (a late packet of a connection this
        # computer made, a router asking for this computer's name, an answer to a search that already ended)
        if is_internet(src):
            return "internet"
        if zone not in ZONE_WORDS or not iface or zone_of(iface) not in ZONE_WORDS:
            return "no network"
        if (proto, port) in DISCOVERY:
            return "discovery"
        if listening(proto, port) is not True:
            return "nothing listens"
        if not listener_name(proto, port):
            return "no system listener"
        if already_allowed(src, zone, proto, port):     # your rules let it in now
            return "allowed"
        # one of your own computers on a network you trust or over Tailscale (an older one still trying to sign in,
        # say): it stays blocked unless Settings lets it in, but it isn't a stranger to ask about
        if zone in ("trusted", "vpn", "tailscale") and (proto, port) in FLEET_PORTS and fleet_member(src):
            return "fleet"
        return ""

    def ask(self, src: str, proto: str, port: int, wait: float = ASK_DELAY, zone: str = "", iface: str = "",
            net: str = "", test: bool = False, usec: str = "") -> None:
        ans = ""
        try:
            time.sleep(wait)                          # the start of a scan: let it show itself first
            with self.lock:
                if self.quiet.get((src, "*", 0), 0) > time.time() or self.quiet.get(("*", proto, port), 0) > time.time():
                    return                            # it was a scan or sweep: Log only
            why = self.worth_asking(src, proto, port, zone, iface)
            if why:
                ans = "skip"
                quiet = self.SKIP_QUIET
                if why == "no system listener":
                    key, now = (src, proto, port), time.time()
                    with self.lock:                   # one quick re-look per device and port per minute, so a
                        first = now - self.listener_tried.get(key, 0.0) >= self.SKIP_QUIET   # steady knock can't keep root busy
                        if first:
                            if len(self.listener_tried) > self.MAX_TRACKED:
                                self.listener_tried.clear()
                            self.listener_tried[key] = now
                        stale = first and now - self.listener_check >= self.LISTENER_QUIET
                        if stale:                     # one fresh check per quiet time, however many devices try
                            self.listener_check = now
                    if stale:
                        check_now()
                    if first:
                        quiet = self.LISTENER_QUIET
                if why != "zone":                      # (the zone case: its very next try should be looked at)
                    with self.lock:
                        self.quiet[(src, proto, port)] = time.time() + quiet
                if os.environ.get("STARCHASER_FIREWALL_ASK_LOG") or os.environ.get("STARCHASER_FIREWALL_ASK_ANSWER"):
                    print(f"starchaser firewall ask: not asked about {src} {proto} {port} (z={zone}): {why}",
                          file=sys.stderr, flush=True)
                return
            program_name = listener_name(proto, port)
            if not program_name:
                ans = "skip"
                return
            program = f"{program_name} ({proto.upper()} port {port})"
            display_name = listener_label(proto, port, program_name)
            # a program we have a plain name for shows only that name: the port and program name are the technical
            # detail, and "Check device and app" opens them
            display_program = display_name if display_name != program_name else f"{display_name} ({proto.upper()} port {port})"
            # what the confirmation says was let in: the plain name when there is one, else the connection number
            reach = display_name if display_name != program_name else f"connection number {port} ({proto.upper()})"
            net = network_of(iface) or net
            notice_key = f"{program_name}|{net or 'zone:' + zone}"
            name, source = device_name(src)
            who = who_label(src, name, source, fragment=True)
            short = name if name and source == "yours" else src
            network = next((n for n in connected_networks() if n.get("uuid") == net), {}) if net else {}
            where = html.escape(plain_net_name(network), quote=False) or ZONE_WORDS.get(zone, "this network")
            body = (f"{html.escape(display_program, quote=False)} on this computer received a connection attempt from {who} on {where}. "
                    "Nothing got in. Nothing to do unless you expected it.")
            # buttons name the app (and the network when trusting it): "Allow it?" alone left out what was being allowed
            app_label = _short_label(display_name, 22)
            full_net = button_net_name(network, zone)
            net_label = full_net if len(full_net) <= 26 else "this network"
            actions = [("deny", "Keep blocked"), ("once", f"Allow {app_label} for 15 min"), ("log", "Check device and app")]
            trust_reason = engine().network_trust_reason(network) if engine() and network else ""
            if trust_reason:
                body += " " + trust_reason
            if zone == "public" and UUID_RE.fullmatch(net) and not trust_reason:
                actions.append(("trust", f"Review trusting {net_label}"))
                shown_name = html.escape(display_name, quote=False)
                if trust_would_allow(src, proto, port) is False:
                    # promising "lets this device reach" here sent people to trust a network that still turned the app away
                    body += (f" Trusting {where} marks it as Trusted, but no permission lets this device reach {shown_name} yet, "
                             f"so it would stay blocked. To let in only this device, press Allow {html.escape(app_label, quote=False)} for 15 min. ")
                else:
                    body += f" Trusting {where} marks it as Trusted and lets this device reach {shown_name} there. "
                body += (" ".join(trust_preview(net).split())
                         + " Review the full change in Settings before applying. This also ends any temporary Public-network pause on this network.")
            elif zone in ("trusted", "vpn", "tailscale"):
                actions = [("deny", "Keep blocked"), ("once", f"Allow {app_label} for 15 min"),
                           ("always", f"Always allow {app_label}"), ("log", "Check device and app")]
            if incoming_paused(iface):
                body += (" Public-network connections are paused. You can save a 15-minute permission, but "
                         "connections on paused networks stay blocked until you end the pause in Settings > Firewall.")
            with NOTICE_LOCK:
                # One notice per program per network, unless you let that program in there before: then each new
                # port of it gets its own (QA 20261103-0458 005: after "Always allow Python" for port 8123, Python
                # on 8124 was turned away with no notice, and the permission seemed not to work)
                if notice_key + "|allowed" in notified_programs():
                    notice_key = f"{notice_key}|{proto}:{port}"
                if notice_key in notified_programs() or notice_key in PENDING_NOTICES:
                    ans = "skip"
                    return
                PENDING_NOTICES.add(notice_key)
            def shown():
                with NOTICE_LOCK:
                    remember_notified(notice_key)
                with self.lock:                       # a notice waiting in the bell must not use up a slot for the next one
                    self.asking.discard((src, proto, port))
            try:
                ans = notify("Blocked a connection", body, actions, icon="security-high", urgency="normal",
                             stay=True, bell_only=True, zone=zone, conn=(src, proto, port, iface), on_shown=shown)
            finally:
                with NOTICE_LOCK:
                    PENDING_NOTICES.discard(notice_key)
            if ans not in {key for key, _ in actions} | {"moot"}:
                ans = ""
            if ans in ("deny", "once", "always", "trust") and firewall_is_off():
                # answered after the firewall was turned off (or went back to Off): there's nothing to let in, and
                # an exception saved now would wait in a firewall that is off
                ans = "moot"                          # no answer is saved for a firewall that is Off
                notify("Nothing changed", "The firewall is off now, so nothing is being blocked.",
                       icon="security-high")
                return
            if ans == "log":
                subprocess.Popen(["starchaser", "settings", "firewall-log", f"{src}|{proto}|{port}|{iface}"],
                                 start_new_session=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
                                 stderr=subprocess.DEVNULL)
            elif ans == "once":
                r = admin("firewall-allow-once", src, proto, str(port), "15", *(["--iface", iface] if iface else []))
                if r.get("canceled"):
                    ans = ""
                    cancel_nothing_changed(notice_key)
                    return
                paused = incoming_paused(iface, r.get("publicPause")) if r.get("ok") else False
                if paused:
                    title = "Permission saved for 15 minutes"
                    text = (f"Saved a 15-minute permission for {short} to reach {reach}. "
                            + ("This network is still paused, so the device cannot connect here. " if iface else
                               "Public-network connections are still paused; this permission works only on other networks. ")
                            + "End the pause in Settings > Firewall to use the permission on paused networks. "
                            "The 15 minutes start now. Log lists the permission, with a way to end it sooner.")
                else:
                    title = "Allowed for 15 minutes"
                    text = (f"{short} can reach {reach} "
                            + ("on this network" if iface else "on every network")
                            + " for the next 15 minutes. Settings > Firewall > "
                            "Log lists it, with a way to end it sooner.")
                if r.get("ok"):
                    def end_permission():
                        ended = admin("firewall-revoke-once", src, proto, str(port), *(["--iface", iface] if iface else []))
                        notify("Temporary permission ended" if ended.get("ok") else "Permission couldn't be ended",
                               "New connections no longer have this temporary permission. Connections already open may continue."
                               if ended.get("ok") else ended.get("errors", "Open Firewall to try again."))
                    threading.Thread(target=allowed_confirmation, args=(title, text, end_permission), daemon=True).start()
                else:
                    notify("Not allowed", r.get("errors", ""), icon="dialog-warning")
                if not r.get("ok"):
                    ans = "failed"                     # nothing changed: it may ask again (after the quiet time)
            elif ans == "trust":
                if not review_network_trust(net):
                    ans = "failed"
                    notify("Couldn't open the network review", "Nothing changed. Open Settings > Firewall to review this network.",
                           icon="dialog-warning")
            elif ans == "always":
                # a DNS name is the device's own claim: the rule is saved under its address
                # Name the verified process and keep the port number in the saved permission.
                what = program
                if len(what) > 40:                    # starchaser-admin keeps 40 characters of it
                    what = f"{proto.upper()} port {port}"
                r = admin("firewall-allow-always", src, proto, str(port), name if source == "yours" else src, what,
                          *(["--zone", zone] if zone in ZONE_WORDS else []))
                if r.get("canceled"):
                    ans = ""
                    cancel_nothing_changed(notice_key)
                    return
                scope = ZONE_SCOPE.get(zone, ZONE_SCOPE["trusted"])
                if r.get("ok"):
                    text = f"{short} can reach {reach} {scope}. Change it in Settings > Firewall > Rules."
                else:
                    text = r.get("errors", "")
                if r.get("ok"):
                    threading.Thread(target=allowed_confirmation, args=("Allowed from now on", text + " Undo opens History for review.",
                                     lambda: settings_review("history")), daemon=True).start()
                else:
                    notify("Not allowed", text, icon="dialog-warning")
                if not r.get("ok"):
                    ans = "failed"
            elif ans == "moot":
                # taken off the screen when its network was marked as a network you trust, or when that device was let in on
                # that port from Settings: the device's next try asks again only if it's still turned away (as a
                # connection from a network you trust), so no quiet time
                pass
            if ans in ("once", "always"):
                with NOTICE_LOCK:
                    remember_notified(f"{program_name}|{net or 'zone:' + zone}|allowed")
            if ans not in ("deny", "once", "always", "moot"):   # closed, ignored or not carried out: half an hour
                with self.lock:
                    self.quiet[(src, proto, port)] = time.time() + QUIET_DISMISSED
        finally:
            with self.lock:
                # an answer holds for the session (see "Answered once" above): Keep blocked anywhere, Allow always
                # on that kind of network, Allow for 15 min on that network
                where = {"deny": "*", "always": f"zone:{zone or 'trusted'}", "once": net or f"zone:{zone}"}.get(ans)
                if where:
                    self.answered[(src, proto, port, where)] = ans
                if ans and ans != "skip":
                    self.tries.pop((src, proto, port), None)
                self.asking.discard((src, proto, port))

    def follow(self) -> None:
        while True:
            if not prefs().get("incoming") or not policy().get("enabled"):
                time.sleep(20)
                continue
            p = subprocess.Popen(["journalctl", "-k", "-f", "-n", "0", "-o", "json", "--no-pager", "-g", "sc-in-blocked"],
                                 stdout=subprocess.PIPE, text=True)
            for line in p.stdout:
                try:
                    e = json.loads(line)
                except ValueError:
                    continue
                msg = e.get("MESSAGE", "")
                if isinstance(msg, list):
                    msg = bytes(msg).decode(errors="replace")
                kv = dict(re.findall(r"(\w+)=(\S*)", msg))
                proto, port = kv.get("PROTO", "").lower(), kv.get("DPT", "")
                # "sc-in-blocked drop z=public …": the zone it came in on (firewall.py; older lines have none)
                zm = re.match(r"sc-in-blocked (?:\w+ )?z=([a-z]+) ", msg)
                # TCP: only the opening of a connection (SYN without ACK) is someone trying to connect; a late ACK,
                # FIN or RST of a connection that already ended can also be turned away, and isn't worth a question
                # (the Log still lists it). Lines without the flag words (no WINDOW=) are asked about as before.
                words = set(msg.split())
                if proto == "tcp" and "WINDOW=" in msg and ("SYN" not in words or "ACK" in words):
                    continue
                # a Wake-on-LAN magic packet (UDP 9 or 7, broadcast to the whole network) wakes a computer; it is
                # never a connection to this one. A fleet computer waking another made every other one ask "allow
                # DISCARD?"
                if proto == "udp" and port in ("7", "9"):
                    continue
                if proto in ("tcp", "udp") and port.isdigit() and kv.get("SRC"):
                    self.seen(kv["SRC"], kv.get("DST", ""), proto, int(port), zm.group(1) if zm else "", kv.get("IN", ""),
                              e.get("__REALTIME_TIMESTAMP", ""))
                if not prefs().get("incoming"):
                    break
            p.kill()
            time.sleep(5)


# ---------------------------------------------------------------------------------------------- outgoing
# Every program that runs another program's text: a missing one would get "this app" wording while Allow always
# let through every script it runs. Versioned names (tclsh8.6, lua5.4, perl5.40) count too.
INTERPRETERS = re.compile(r"^(python[0-9.]*|pypy[0-9.]*|node(js)?|bun|deno|perl[0-9.]*|ruby[0-9.]*|php[0-9.]*|java"
                          r"|lua(jit)?[0-9.-]*|tclsh[0-9.]*|wish[0-9.]*|g?awk|mawk|R(script)?|julia"
                          r"|sh|bash|zsh|fish|dash|ksh|mksh|tcsh|csh|busybox)$")


class ScopedConnection:
    """Keep the identity verified at receipt while a question waits, even if the process exits."""
    def __init__(self, conn):
        self.connection = conn
        self.scope = connection_scope(conn)

    def __getattr__(self, name):
        return getattr(self.connection, name)


def connection_scope(conn) -> str:
    return conn.scope if isinstance(conn, ScopedConnection) else process_scope(getattr(conn, "process_id", 0))


def flatpak_id(conn) -> str:
    """The verified sandbox's app ID. FLATPAK_ID is caller-controlled and is never evidence."""
    scope = connection_scope(conn)
    return scope[8:] if scope.startswith("flatpak:") else ""


def app_scoped(conn) -> bool:
    path = conn.process_path or ""
    scope = connection_scope(conn)
    return path.startswith("/") and (scope.startswith("flatpak:") or
        (scope == "host" and not path.startswith(("/app/", "/usr/lib/extensions/"))))


def can_remember(conn) -> bool:
    return app_scoped(conn) and (bool(flatpak_id(conn)) or not INTERPRETERS.fullmatch(Path(conn.process_path).name))


def identity(conn) -> tuple:
    """(answer key, display path, legacy script). Sandboxed apps share executable paths, so use their app ID.
    Without an identifiable app, only the current connection may be allowed; never share a timed answer."""
    path = conn.process_path or ""
    app = flatpak_id(conn)
    if app and path.startswith("/"):
        return "flatpak:" + app, app, ""
    if app_scoped(conn):
        return path, path, ""
    key = "unidentified:" + repr(tuple(getattr(conn, f, "") for f in
        ("user_id", "process_id", "protocol", "src_ip", "src_port", "dst_ip", "dst_port")))
    return key, path or "An unidentified program", ""


def connection_name(conn) -> str:
    app = flatpak_id(conn)
    if app:
        for directory in (HOME / ".local/share/flatpak/exports/share/applications",
                          Path("/var/lib/flatpak/exports/share/applications")):
            try:
                text = (directory / (app + ".desktop")).read_text(errors="replace")
            except OSError:
                continue
            name = re.search(r"(?m)^Name=(.+)$", text)
            if name:
                return safe_app_label(name.group(1).strip(), app)
        return app
    if not app_scoped(conn):
        # its file is known (the kernel says where it runs from) but not which app it belongs to: name the file,
        # never "couldn't identify" above the program's exact path
        path = conn.process_path or ""
        return safe_app_label(Path(path).name, Path(path).name) if path.startswith("/") and Path(path).name else \
            "A program the firewall couldn't identify"
    return app_name(conn.process_path)


def started_as(conn) -> str:
    """The command line as the person would recognize it, on one line and shortened: shown for an interpreter, never
    matched on. The program asking writes it, so the card escapes it (html.escape) before it goes in the body."""
    line = " ".join(str(a) for a in conn.process_args or [] if a is not None)
    line = re.sub(r"[\x00-\x1f\x7f\u2028\u2029]+", " ", line).strip()
    return line if len(line) <= 60 else line[:59] + "…"


def safe_app_label(name, fallback, desktop=""):
    if not re.search(r'gnome|kde|xfce|hyprland|cachyos|thunar', name, re.I): return name
    generic = re.search(r'(?m)^GenericName=(.+)$', desktop)
    label = generic.group(1).strip() if generic else 'Terminal' if 'terminal' in fallback.lower() else 'About' if 'about' in fallback.lower() else 'System program'
    return 'System program' if re.search(r'gnome|kde|xfce|hyprland|cachyos|thunar', label, re.I) else label


def app_name(path: str) -> str:
    base = Path(path).name or path
    if base.startswith("git-remote-"): return "git"
    for d in (Path("/usr/share/applications"), HOME / ".local/share/applications"):
        for f in d.glob("*.desktop") if d.is_dir() else []:
            try:
                t = f.read_text(errors="replace")
            except OSError:
                continue
            m = re.search(r"(?m)^Exec=(\S+)", t)
            if m and Path(m.group(1)).name == base:
                n = re.search(r"(?m)^Name=(.+)$", t)
                if n:
                    return safe_app_label(n.group(1).strip(), base, t)
    return safe_app_label(base, base)


ASK_OUT_WAIT = 25               # answer OpenSnitch within its wait; unanswered connections are denied
ASK_OUT_QUIET = 120             # "Allow app for 2 minutes": the program's next unmatched connections go out unasked
# Starchaser's own scripts, as the engine's Ask-mode rule knows them (firewall.py STARCHASER_SCRIPT, which also
# matches a script path on its own), run by the interpreters that rule accepts. OpenSnitch asks when its rule
# misses (a command line read a moment too early): those are answered here with no card, as Settings > Firewall ›
# Rules promises.
SCRIPT_RUNNERS = re.compile(r"^/usr/bin/(python3(\.[0-9]+)?|bash|sh)$")


def this_computer(ip: str) -> bool:
    try:
        return ipaddress.ip_address(ip).is_loopback
    except ValueError:
        return False


DNS_COMMAND = ("/usr/bin/python3", "-B", "/usr/local/lib/starchaser/firewall_dns.py")


def lookup_service(conn) -> bool:
    return bool(re.fullmatch(r"/usr/bin/python3(\.[0-9]+)?", conn.process_path or "")
                and tuple(conn.process_args or []) == DNS_COMMAND
                and conn.protocol == "tcp" and conn.dst_port == 853)


def unasked(conn) -> bool:
    """A connection Rules says is never asked about: to this computer itself, or from Starchaser's own scripts."""
    if this_computer(conn.dst_ip or "") or lookup_service(conn):
        return True
    if not SCRIPT_RUNNERS.match(conn.process_path or ""):
        return False
    # the whole command line, as the engine's rule reads it: "python3 -W /usr/bin/starchaser-x /tmp/evil.py" runs
    # evil.py, so the first word without a dash must not decide which script this is
    mod = engine()
    return bool(mod and re.search(mod.STARCHASER_SCRIPT, " ".join(str(a) for a in conn.process_args or [])))


def numeric_address(value):
    try: ipaddress.ip_address(value); return True
    except ValueError: return False


def duration_words(seconds):
    return {120: "2 minutes", 900: "15 minutes", 7200: "2 hours"}.get(seconds, "2 minutes")


def question_metadata(conn):
    mod = engine()
    row = mod.app_record(conn.process_path or "", connection_scope(conn)) if mod else {}
    known = bool(row.get("catalogId"))
    today = time.strftime('%Y-%m-%d')
    counter = RUNTIME / 'starchaser-firewall-question-counts.json'
    try: counts = json.loads(counter.read_text())
    except (OSError, ValueError): counts = {}
    if counts.get('day') != today: counts = {'day': today, 'apps': {}}
    key = row.get('id', conn.process_path or 'unidentified')
    count = counts.setdefault('apps', {}).get(key, 0) + 1
    counts['apps'][key] = count
    # Bounded, private presentation state; never used for an access decision.
    if len(counts['apps']) > 1000: counts['apps'] = {key: count}
    try:
        with tempfile.NamedTemporaryFile(mode='w', prefix='starchaser-fw-count-', dir=RUNTIME, delete=False) as stream:
            temporary = Path(stream.name); json.dump(counts, stream); temporary.chmod(0o600)
        temporary.replace(counter)
    except OSError: pass
    return {'icon': row.get('icon', ''), 'known': known, 'askedToday': count,
            # (a catalog entry says what the app is, not where it came from: curl and pacman are in it too)
            'description': connection_name(conn) + ' · ' + identity(conn)[1] if known else conn.process_path or "Unidentified program"}


_unidentified_window = threading.Lock()


def outgoing_window(conn, child=False):
    """Serialize unknown questions; other connections stay blocked in the bell."""
    if lookup_service(conn):
        return ""
    unidentified = not app_scoped(conn)
    if unidentified and not _unidentified_window.acquire(blocking=False):
        return "defer"
    try:
        return _outgoing_window(conn, child)
    finally:
        if unidentified:
            _unidentified_window.release()


def _outgoing_window(conn, child=False):
    """Private request/reply files; closing or a missing desktop never grants access."""
    cfg = HOME / ".config/quickshell/settings/firewall-question.qml"
    if not cfg.is_file() or not os.environ.get("WAYLAND_DISPLAY"):
        return ""     # the caller keeps the question pending and blocks retries
    try:
        with tempfile.TemporaryDirectory(prefix="starchaser-fw-question-", dir=RUNTIME) as folder:
            path = Path(folder) / "question.json"
            request = {"name": connection_name(conn), "destination": conn.dst_host or conn.dst_ip,
                       "path": conn.process_path or "", "remember": can_remember(conn),
                       "scoped": app_scoped(conn), "port": conn.dst_port, "protocol": conn.protocol,
                       "namedDestination": bool(conn.dst_host) and not numeric_address(conn.dst_host), "child": child, **question_metadata(conn)}
            path.write_text(json.dumps(request))
            path.chmod(0o600)
            env = dict(os.environ, STARCHASER_FIREWALL_QUESTION=str(path))
            result = subprocess.run(["qs", "-p", str(cfg)], env=env, stdout=subprocess.DEVNULL,
                                    stderr=subprocess.DEVNULL, timeout=86400)
            answer_path = path.with_suffix(".answer")
            if not answer_path.exists(): return "defer" if result.returncode == 0 else ""
            reply = json.loads(answer_path.read_text())
            action = reply.get("action")
            if action not in (("request", "deny") if child else ("always", "never", "once", "deny")): return ""
            if child and action == "request" and not can_remember(conn): return ""
            if action in ("always", "never") and not can_remember(conn): return ""
            site = bool(reply.get("site"))
            seconds = reply.get("seconds", 120)
            if seconds not in (120, 900, 7200): return ""
            return action + ("|site" if site else "|app") + "|" + str(seconds)
    except (OSError, ValueError, subprocess.TimeoutExpired):
        return ""


class OutgoingDecision(tuple):
    def __new__(cls, action, duration, site=""):
        value = super().__new__(cls, (action, duration))
        value.site = site
        return value


def destination_key(conn):
    # Host is observed, never a suffix pattern. An empty host is restricted to the numeric destination.
    return str(conn.dst_host or conn.dst_ip or "")


class Outgoing:
    def __init__(self):
        self.pending = {}          # path -> (Event, answer holder)
        self.quiet = {}            # path -> (action, until)
        self.lock = threading.Lock()

    def decide(self, conn) -> tuple:
        """Answer this connection in time; keep an unanswered card alive for the next connections."""
        if not isinstance(conn, ScopedConnection):
            conn = ScopedConnection(conn)
        path, _, _ = identity(conn)
        if hasattr(conn, "user_id"): path = (path, int(conn.user_id))
        now = time.time()
        if unasked(conn):                              # Starchaser's own script, matched by full command line: never held by
            return "allow", "once"                     # a question about the shared interpreter, and it never makes a rule
        quiet = unasked_answer(conn)
        if quiet:                                      # the policy doesn't ask about this one: its answer, at once, no card
            return quiet, "once"
        with self.lock:
            if path in self.pending:
                return "deny", "once"
            site = destination_key(conn)
            q = self.quiet.get((path, site)) or self.quiet.get(path)
            if q and q[1] > now:
                if len(q) > 2 and q[2] == "always":
                    self.quiet[(path, site) if len(q) > 3 and q[3] else path] = (q[0], now + 10, "once", q[3] if len(q) > 3 else "")
                return OutgoingDecision(q[0], q[2] if len(q) > 2 else "once", q[3] if len(q) > 3 else "")
            ev, box = threading.Event(), {"waiting": True}
            self.pending[path] = (ev, box)
            pending_apps(self.pending)
        threading.Thread(target=self.ask, args=(conn, path, ev, box), daemon=True).start()
        answered = ev.wait(ASK_OUT_WAIT)
        if answered and box.get("answer", ("", ""))[1] == "always":
            with self.lock:                            # answered in time: OpenSnitch saves this reply itself, so a rule
                answer = box["answer"]
                site = getattr(answer, "site", "")
                self.quiet[(path, site) if site else path] = (answer[0], time.time() + 10, "once", site)
        if not answered:
            with self.lock: box["waiting"] = False
        return box.get("answer", ("deny", "once")) if answered else ("deny", "once")

    def ask(self, conn, path, ev, box) -> None:
        dest = conn.dst_host or conn.dst_ip
        if this_computer(conn.dst_ip or "") or dest in ("localhost", "localhost.localdomain"):
            dest = "this computer"
        _, shown, _ = identity(conn)
        prog = Path(conn.process_path or "").name
        runner = app_scoped(conn) and not flatpak_id(conn) and bool(INTERPRETERS.match(prog))
        scoped, remember = app_scoped(conn), can_remember(conn)
        scope = f"every program run by {prog}" if runner else "this app"
        connections = f"connections from {scope}" if runner else "this app's other connections"
        how = started_as(conn) if runner else ""
        # the body is markup: the program asking chose its file name, its command line and the name it looks up
        esc = lambda t: html.escape(str(t), quote=False)
        ans = ""
        actions = [("deny", "Deny"), ("once", "Allow app for 2 minutes" if scoped else "Allow this connection")]
        if remember:
            actions += [("always", "Allow always"), ("never", "Never")]
        valid = {key for key, _ in actions}
        while ans not in valid:
            ans = notify(f"{prog if runner else connection_name(conn)} wants to connect to {dest}",
                         (f"{esc(shown)} is looking up {esc(dest)}'s address (DNS), to connect to it. Let it out?"
                          if conn.dst_port == 53
                          else f"{esc(shown)} → {esc(dest)} ({esc(conn.protocol)} port {esc(conn.dst_port)}). Let it out?")
                         + (f" {esc(prog)} runs other programs, and the firewall can't tell them apart, so each answer"
                            f" covers every program {esc(prog)} runs, not just this one." if runner else "")
                         + (f" It was started as: {esc(how)}." if how else "")
                         + " Until you answer, it stays blocked."
                         + ((f" Deny also blocks {esc(connections)} for 10 minutes without asking."
                             + f" Allow app for 2 minutes also allows {esc(connections)}"
                             + " to any destination and port when no rule matches.") if scoped else
                            " The firewall can't identify this app. Your answer covers only this connection.")
                         + ((f" Allow always remembers that permission for {esc(scope)} without a time limit."
                             + " Never remembers a block for this app until you forget it in Settings > Firewall > Rules.")
                            if remember else " Only timed answers are available." if scoped else ""),
                         actions,
                         icon="dialog-information", stay=True, zone="outgoing", question=conn)
            if ans == "defer":
                while ask_wanted():
                    resume = notify("An app is waiting for internet access", connection_name(conn) + " stays blocked until you answer.", [("review", "Review connection")], bell_only=True)
                    if resume == "review": break
                    time.sleep(3)
                ans = ""
            parts = ans.split("|")
            if parts[0] in valid and len(parts) == 3 and parts[1] in ("app", "site") and parts[2] in ("120", "900", "7200"):
                break
            if ans not in valid:
                if not ask_wanted():                  # the question no longer applies (firewall off, or not asking): stop
                    ans = "deny"
                    break
                time.sleep(1)                         # a dismissed card still needs an answer; never allow silently
        answer_parts = ans.split("|")
        ans = answer_parts[0]
        site = destination_key(conn) if len(answer_parts) == 3 and answer_parts[1] == "site" else ""
        seconds = int(answer_parts[2]) if len(answer_parts) == 3 else ASK_OUT_QUIET
        result = {"deny": ("deny", "once"), "once": ("allow", "once"), "always": ("allow", "always"), "never": ("deny", "always")}[ans]
        if site: result = OutgoingDecision(*result, site)
        with self.lock:
            # A late answer governs NEXT connections. Returning "always" there lets OpenSnitch save sc-asked-*
            # even when the AskRule which first showed this card already returned deny after 25 seconds.
            until = float("inf") if result[1] == "always" else time.time() + (600 if ans == "deny" else seconds)
            if scoped:
                self.quiet[(path, site) if site else path] = (result[0], until, result[1], site) if site else (result[0], until, result[1])
            if scoped and result[1] == "always" and box.get("waiting"):
                self.quiet[(path, site) if site else path] = (result[0], time.time() + 10, "once", site)
            box["answer"] = result
            self.pending.pop(path, None)
            pending_apps(self.pending)
            ev.set()
            saved = self.quiet.get((path, site) if site else path)
        if ans in ("always", "once") and scoped:
            def undo_answer():
                if ans == "always":
                    settings_review("apps")          # review the saved answer; never roll back a newer whole policy
                    return
                with self.lock:
                    cache_key = (path, site) if site else path
                    if self.quiet.get(cache_key) == saved:
                        self.quiet.pop(cache_key, None)
                notify("Temporary answer ended", "New connections need an answer again. Connections already open may continue.", bell_only=True)
            threading.Thread(target=allowed_confirmation,
                             args=(connection_name(conn) + (" can always use the internet" if ans == "always" else " can use the internet for " + duration_words(seconds)),
                                   "End it early here, or change it in Settings › Firewall › Apps.", undo_answer,
                                   "Review in Apps" if ans == "always" else "End now"), daemon=True).start()
        elif ans == "never":
            threading.Thread(target=allowed_confirmation,
                             args=(connection_name(conn) + " is blocked from the internet", "Change this in Settings › Firewall › Apps.",
                                   lambda: settings_review("apps"), "Review in Apps"), daemon=True).start()


_status = {}                    # what STATUS says: serving, error, time, lastPing
_status_lock = threading.Lock()


def _write_status() -> None:
    try:
        tmp = STATUS.with_name("." + STATUS.name + ".tmp")
        tmp.write_text(json.dumps(_status) + "\n")
        tmp.replace(STATUS)
    except OSError:
        pass


def pending_apps(pending):
    with _status_lock:
        keys = [key[0] if isinstance(key, tuple) else key for key in pending]
        _status['pendingApps'] = [key if key.startswith('flatpak:') else 'program:' + key for key in keys]
        _write_status()


_child_prompts = set()
_child_prompts_lock = threading.Lock()


def child_blocked(conn, record):
    app = record.get('id', '')
    with _child_prompts_lock:
        if app in _child_prompts: return
        _child_prompts.add(app)
    def offer():
        try:
            answer = outgoing_window(conn, child=True)
            if answer.startswith('request|') and can_remember(conn):
                Activity().request(app, connection_name(conn))
                notify('Request sent', 'A parent can review ' + connection_name(conn) + ' in Firewall. This app stays blocked until approved.', bell_only=True)
        finally:
            # A dismissed request can be offered again later, without a question storm.
            time.sleep(60)
            with _child_prompts_lock: _child_prompts.discard(app)
    threading.Thread(target=offer, daemon=True).start()


def review_child_request(row):
    result = notify(row['child'] + ' asked to use ' + row['name'], 'Allow needs your password. Not now keeps the app blocked.', [('allow', 'Allow'), ('later', 'Not now')], icon='security-high', bell_only=True)
    if result == 'allow':
        result = admin('firewall-child-allow', str(row['uid']), row['app'])
        if result.get('ok'): settings_review('privacy')
        else: notify('App permission was not changed', result.get('errors', 'Review the request in Firewall.'), bell_only=True)


CHILD_REQUESTS = Path('/run/starchaser/firewall-child-requests') / (str(os.getuid()) + '.json')


def watch_child_requests(changes=None):
    seen = set()
    source = CHILD_REQUESTS
    while True:
        try:
            data = json.loads(source.read_text())
            if data.get('uid') != os.getuid() or not 0 <= time.time() - data.get('time', 0) < 150: raise ValueError('Stale requests')
            for request in data.get('requests', []):
                key = (request['uid'], request['app'], request.get('time', 0))
                if key in seen: continue
                seen.add(key)
                threading.Thread(target=review_child_request, args=(request,), daemon=True).start()
            if len(seen) > 1000: seen.clear()
        except (OSError, ValueError, KeyError, TypeError): pass
        pause(3, False, changes)                           # (a request is a write to its folder)


def pinged() -> None:
    """OpenSnitch checked in (its Ping, every few seconds while it's connected): recorded at most every 5 seconds, so
    Settings can tell a question service that's ready from one OpenSnitch is actually talking to."""
    now = int(time.time())
    with _status_lock:
        if now - (_status.get("lastPing") or 0) < 5:
            return
        _status["lastPing"] = now
        _write_status()


def report(serving: bool, error: str = "") -> None:
    """Tell Settings whether the outgoing question can be shown, and the person once when it can't."""
    with _status_lock:
        if not _status:
            try:
                _status.update(json.loads(STATUS.read_text()))
            except (OSError, ValueError):
                pass
        if serving == _status.get("serving") and error == _status.get("error", ""):
            return
        _status.update(serving=serving, error=error, time=int(time.time()))
        if not serving:
            _status["lastPing"] = 0
        _write_status()
    if error:
        print(f"starchaser firewall ask: can't ask about apps reaching out: {error}", file=sys.stderr, flush=True)
        notify("Apps reaching out won't be asked about",
               "The firewall is set to ask before an app connects out, but the question can't be shown, so new "
               "connections stay blocked until questions can be answered. Try signing out and back in.",
               icon="dialog-error", urgency="critical")


def ask_wanted() -> bool:
    return bool(policy().get("enabled")) and (policy().get("defaults") or {}).get("out") == "ask"


def system_account(uid) -> bool:
    """A system account (root, a service's own user, a service's DynamicUser, nobody): never a person at the
    computer. Ordinary accounts are 1000 to 60000 (login.defs); the engine's Ask-mode rule covers 0 to 999."""
    try:
        uid = int(uid)
    except (TypeError, ValueError):
        return False
    return 0 <= uid < 1000 or 60000 < uid <= 65535


def unasked_answer(conn) -> str:
    """The answer, with no question, for a connection the policy doesn't ask about; "" when it does ask.
    OpenSnitch sends every connection no rule matched here while this asker is connected (Record outgoing activity
    and child approvals connect it, not only Ask), so the policy decides, not the fact that a question came in:
    - a system account (decision #63): never asked about or held. Block keeps it blocked, otherwise it goes out;
    - Allow: out at once, unless an app Block is set and this program can't be identified (the engine lets
      identified ones out by rule first; one it can't name can't be checked against that Block, so it stays out);
    - Block: blocked at once;
    - a child account set to need a parent's approval is answered by its own rules, never asked about here.
    An unreadable policy is not a reason to let anything out: it asks, the safe old way."""
    p = policy()
    if not p:
        return ""
    if not p.get("enabled"):
        return "allow"
    out = (p.get("defaults") or {}).get("out", "allow")
    uid = getattr(conn, "user_id", None)
    if system_account(uid):
        return "deny" if out == "block" else "allow"
    if out == "ask":
        return ""
    if out == "block":
        return "deny"
    blocks = (any(c.get("askNew") for c in p.get("children", []))
              or any(r.get("enabled", True) and r.get("dir") == "out" and r.get("app", "any") != "any"
                     and r.get("action") != "allow" for r in p.get("rules") or []))
    return "deny" if blocks and not app_scoped(conn) else "allow"


def outgoing_rule(conn, out, proto):
    """Build the actual checker reply; enforce the same scope even for a stale card or cached answer."""
    if not isinstance(conn, ScopedConnection):
        conn = ScopedConnection(conn)
    decision = out.decide(conn)
    action, duration = decision
    site = getattr(decision, "site", "")
    if duration == "always" and not can_remember(conn):
        action, duration = "deny", "once"
    key, _, _ = identity(conn)
    app = flatpak_id(conn)
    label = connection_name(conn)
    tag = hashlib.sha1((key + ":" + str(getattr(conn, "user_id", ""))).encode()).hexdigest()[:8]
    name = f"sc-asked-{re.sub(r'[^a-z0-9]+', '-', label.lower()).strip('-') or 'program'}-{tag}"
    # The verified ID covers protected app code across restarts and updates; shared runtime code has no app grant.
    operand, data = ("process.starchaser.scope.v2", "flatpak:" + app) if app else ("process.path", conn.process_path or "")
    op = proto.Operator(type="simple", operand=operand, data=data, sensitive=True)
    if not app and duration == "always":
        # The same /usr path inside a sandbox belongs to that app, not to the host program the person answered.
        op = proto.Operator(type="list", operand="list", data="", list=[op,
            proto.Operator(type="simple", operand="process.starchaser.scope.v2", data="host", sensitive=True)])
    if duration == "always" and hasattr(conn, "user_id"):
        op = proto.Operator(type="list", operand="list", data="", list=(list(op.list) if getattr(op, "type", "") == "list" else [op]) + [
            proto.Operator(type="simple", operand="user.id", data=str(conn.user_id), sensitive=True)])
    if site:
        operand = "dest.host" if conn.dst_host else "dest.ip"
        op = proto.Operator(type="list", operand="list", data="", list=(list(op.list) if getattr(op, "type", "") == "list" else [op]) + [
            proto.Operator(type="simple", operand=operand, data=site, sensitive=True)])
        name += "-site-" + hashlib.sha256(site.encode()).hexdigest()[:10]
    try:
        if policy().get("recordActivity"):
            pending_key = (identity(conn)[0], int(conn.user_id)) if hasattr(conn, "user_id") else identity(conn)[0]
            observed = "held" if action == "deny" and pending_key in getattr(out, "pending", {}) else action
            Activity().record(conn, (engine().app_record(conn.process_path or "", connection_scope(conn))["id"] if engine() else "program:" + (conn.process_path or "unknown")), label, observed)
    except Exception as e:
        print("firewall activity: " + str(e), file=sys.stderr)
    return proto.Rule(name=name, description=f"Starchaser asked: {action} {label}", enabled=True,
                      precedence=False, nolog=False, action=action, duration=duration, operator=op)


def watch_traffic(changes=None):
    def recording():
        current = policy()
        return bool(current.get("enabled") and current.get("recordActivity"))
    def app_identity(pid, executable):
        mod = engine()
        scope = process_scope(pid)
        if mod is None or (scope != "host" and not scope.startswith("flatpak:")): return None
        return mod.app_record(executable, scope)["id"]
    sampler = TrafficSampler(Activity(), app_identity, recording)
    while True:
        try: sampler.sample()
        except (OSError, ValueError, subprocess.SubprocessError): pass
        pause(3, recording(), changes)                     # (turning recording on is a write to the policy)


def record_checker_events(request):
    current = policy()
    recording = bool(current.get("recordActivity"))
    if not recording and not any(c.get("askNew") for c in current.get("children", [])): return
    for event in getattr(getattr(request, "stats", None), "events", []):
        conn = event.connection
        if getattr(conn, "user_id", -1) != os.getuid(): continue
        try:
            mod = engine()
            record = mod.app_record(conn.process_path, process_scope(conn.process_id)) if mod else {}
            app = record.get("id", "program:" + (conn.process_path or "unknown"))
            if event.rule.action == "deny" and "-approval" in event.rule.name and app != "unidentified":
                child_blocked(ScopedConnection(conn), record)
            if recording: Activity().record(conn, app,
                              record.get("name", Path(conn.process_path or "").name or "Unidentified program"),
                              event.rule.action, event.rule.name,
                              event.unixnano / 1e9 if event.unixnano else None,
                              key=hashlib.sha256(event.SerializeToString()).hexdigest())
        except Exception as e:
            print("firewall activity: " + str(e), file=sys.stderr)


def serve_opensnitch(out: Outgoing) -> None:
    """OpenSnitch's UI side, while outgoing is set to Ask."""
    sys.path.insert(0, "/usr/lib/python3/dist-packages")
    try:
        from concurrent import futures

        import grpc
        from opensnitch.proto import ui_pb2, ui_pb2_grpc
    except Exception as e:                             # missing, or present but broken (a version mismatch raises others)
        why = f"The outgoing checker's Python parts are missing ({e.name or e})" if isinstance(e, ImportError) \
            else f"The outgoing checker's Python parts don't load ({type(e).__name__}: {e})"
        while True:                                    # nothing to serve with; say so whenever Ask is on
            report(False, why if ask_wanted() else "")
            time.sleep(30)

    class Servicer(ui_pb2_grpc.UIServicer):
        def Ping(self, request, context):
            pinged()
            record_checker_events(request)
            return ui_pb2.PingReply(id=request.id)

        def AskRule(self, conn, context):
            return outgoing_rule(conn, out, ui_pb2)

        def Subscribe(self, config, context):
            return config

        def Notifications(self, request_iterator, context):
            # Keep the single UI stream alive. The daemon's zero-filled process counters are not measurements.
            while context.is_active(): time.sleep(1)
            yield from ()

        def PostAlert(self, alert, context):
            return ui_pb2.MsgResponse(id=getattr(alert, "id", 0))

    server = None
    while True:
        try:
            server = _serve_once(server, out, grpc, futures, ui_pb2_grpc, Servicer)
        except Exception as e:                         # never let the question thread die quietly: Ask would then
            if server is not None:                     # let everything out unasked with nobody told
                try:
                    server.stop(0)
                except Exception:
                    pass
            server = None
            report(False, f"the question service failed ({type(e).__name__}: {e})" if ask_wanted() else "")
        time.sleep(10)


def _serve_once(server, out, grpc, futures, ui_pb2_grpc, Servicer):
    """One round of serve_opensnitch's loop: start, rebuild or stop the server as Ask needs. Returns the server."""
    p = policy()
    want = bool(p.get("enabled")) and (ask_wanted() or bool(p.get("recordActivity")) or any(c.get("askNew") for c in p.get("children", [])))
    if want and server is None:
        try:
            os.unlink(OSUI_SOCK)
        except OSError:
            pass
        err = ""
        try:
            server = grpc.server(futures.ThreadPoolExecutor(max_workers=16))
            ui_pb2_grpc.add_UIServicer_to_server(Servicer(), server)
            if not server.add_insecure_port(f"unix://{OSUI_SOCK}"):
                raise RuntimeError(f"couldn't make {OSUI_SOCK}")
            server.start()
        except Exception as e:                     # grpc raises its own kinds; any of them means no asker
            err = str(e) or type(e).__name__
            if server is not None:
                server.stop(0)
            server = None
        report(server is not None, err)
    elif want and server is not None and not os.path.exists(OSUI_SOCK):
        server.stop(0)                             # the socket was removed: make it again right away; only a
        server = None                              # failed rebuild tells the person (an alarm the next second
        return _serve_once(server, out, grpc, futures, ui_pb2_grpc, Servicer)   # proved wrong would frighten them)
    elif not want:
        if server is not None:
            server.stop(2)
            server = None
        report(False, "")
    return server


STATS = Path("/run/starchaser/firewall-stats.json")
STATS_FRESH = 150                                   # as starchaser firewall: the check runs every 60 s


# ---------------------------------------------------------------------------------------------- networks
KEEP = "/usr/local/lib/starchaser/starchaser-firewall-keep"
ENGINE = "/usr/local/lib/starchaser/firewall.py"
UUID_RE = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
# firewall.py's HOST_ONLY (this computer's own virtual machines, containers and Android apps in Waydroid), plus
# loopback and Tailscale: never a network to ask about. Kept here so it holds even when the engine can't be loaded
HOST_ONLY = ("virbr", "vnet", "waydroid", "veth", "docker", "podman", "cni-podman", "incusbr", "lxdbr", "lxcbr", "vboxnet", "vmnet")


def connected_networks() -> list:
    """[{uuid, name, type}] for the networks this computer is on now that the firewall's Trusted/Public applies to: the
    same ones Settings > Firewall lists (no VPN, Tailscale, loopback or the virtual-machine bridges)."""
    try:
        out = subprocess.run(["nmcli", "-t", "-f", "UUID,NAME,TYPE,DEVICE", "connection", "show", "--active"],
                             capture_output=True, text=True, timeout=10).stdout
    except (OSError, subprocess.TimeoutExpired):
        return []
    mod = engine()
    prefixes = getattr(mod, "HOST_ONLY", HOST_ONLY)
    nets = []
    for line in out.splitlines():
        f = [x.replace("\0", ":") for x in line.replace("\\:", "\0").split(":")]
        if len(f) < 4 or f[2] == "loopback" or f[3].startswith(prefixes) or f[3] in ("lo", "tailscale0"):
            continue
        if re.search(r"vpn|wireguard|tun", f[2]) or not UUID_RE.fullmatch(f[0]):
            continue
        nets.append({"uuid": f[0], "name": f[1], "type": f[2], "device": f[3]})
    return nets


_ENGINE = []


def engine():
    """The firewall engine (firewall.py, read-only use: nothing here needs root), loaded once; None if it can't be."""
    if not _ENGINE:
        try:
            import importlib.util
            spec = importlib.util.spec_from_file_location("starchaser_firewall_engine", ENGINE)
            mod = importlib.util.module_from_spec(spec)
            spec.loader.exec_module(mod)
        except Exception:
            mod = None
        _ENGINE.append(mod)
    return _ENGINE[0]


if engine() is not None:
    HOST_ONLY = getattr(engine(), "HOST_ONLY", HOST_ONLY)


def keep_public(uid: str) -> dict:
    """No: record the network as Public without a password (starchaser-firewall-keep, which can only do that to a
    network nobody has marked). In a test run, passwordless sudo stands in for pkexec, as in admin()."""
    via = ["pkexec"]
    if os.environ.get("STARCHASER_FIREWALL_ASK_ANSWER") and subprocess.run(["sudo", "-n", "true"], capture_output=True).returncode == 0:
        via = ["sudo", "-n"]
    argv = [*via, KEEP, "firewall-mark-network", uid, "public"]
    if via[0] == "pkexec":
        rc, stdout, stderr = run_in_session(argv)
        r = subprocess.CompletedProcess(argv, rc, stdout, stderr)
    else:
        r = subprocess.run(argv, capture_output=True, text=True)
    if via[0] == "pkexec" and (r.returncode == 126 or
            (r.returncode == 127 and "request dismissed" in (r.stderr or "").lower())):
        return {"ok": False, "canceled": True, "errors": "Not changed: you closed the password box."}
    try:
        return json.loads(r.stdout.strip().splitlines()[-1])
    except (ValueError, IndexError):
        return {"ok": False, "errors": r.stderr.strip() or "Not changed."}


# Close an orphan network card left by an older version when the service starts.
NET_CARD = RUNTIME / "starchaser-firewall-netcard"


def clear_network_card() -> None:
    """Close orphan network cards left by older versions."""
    for rec in sorted(NET_CARD.parent.glob(NET_CARD.name + "*")):
        try:
            close_card(rec.read_text().strip(), "an older network question was still up; replaced at start")
        except OSError:
            pass
        try:
            rec.unlink()
        except OSError:
            pass


def _short_label(text: str, limit: int) -> str:
    """A name for a button: whole when it fits, otherwise cut with an ellipsis (a bell button is narrow). The cut
    falls between words when there's a space to cut at, and never inside parentheses: "Trust your cable (… and allow"
    left a bracket hanging."""
    text = " ".join(str(text or "").split())
    if len(text) <= limit:
        return text
    cut = text[:limit - 1]
    space = cut.rfind(" ")
    if space >= limit // 3:
        cut = cut[:space]
    if cut.count("(") > cut.count(")"):
        cut = cut[:cut.rfind("(")]
    return (cut.rstrip(" ,;:-") or text[:limit - 1].rstrip()) + "\u2026"


def button_net_name(net: dict, zone: str = "") -> str:
    """A network's name for a button: plain_net_name without its parenthesized note ("your cable connection", not
    "your wired connection"), lowercase like the rest of the sentence; a Wi-Fi name stays as spelled."""
    name = plain_net_name(net) if net else ""
    if not name:
        return ZONE_WORDS.get(zone, "this network")
    return " ".join(re.sub(r"\s*\([^)]*\)", "", name).split()) or name


def plain_net_name(net: dict) -> str:
    """A network's name in plain words, the same as the welcome and Settings: NetworkManager's "Wired connection 1" on a
    cable becomes "your wired connection", numbered only when there are several. A Wi-Fi name stays as is."""
    def wired(n):
        return bool(re.fullmatch(r"Wired connection \d+", n.get("name") or "")) and "ethernet" in (n.get("type") or "")
    m = re.fullmatch(r"Wired connection (\d+)", net.get("name") or "")
    if not m or not wired(net):
        return net.get("name") or ""
    if sum(1 for n in connected_networks() if wired(n)) > 1:
        return "Wired " + m.group(1)
    return "your wired connection"


def at_start(name: str) -> str:
    """A network's name where it starts a sentence: our own words get a capital ("Your wired connection
    stays Public", round 32), a Wi-Fi name stays as its owner spelled it ("iPhone"). Fleet.blockedNetName does the same."""
    return name[:1].upper() + name[1:] if re.match(r"(your |cable |this network$)", name) else name


def plain_app_name(name: str) -> str:
    """The catalog's plain name ("Remote login") for its technical one ("Remote login (SSH)"); other names unchanged."""
    for a in catalog_apps():
        if a.get("name") == name and a.get("plain"):
            return a["plain"]
    return name


def review_network_trust(uid: str) -> bool:
    """Open the existing read-only network preview; choosing Trusted still requires Apply in Settings."""
    if not UUID_RE.fullmatch(uid):
        return False
    path = RUNTIME / "starchaser-firewall-network-review"
    temp = None
    try:
        with tempfile.NamedTemporaryFile("w", dir=RUNTIME, prefix=".firewall-network-review-", delete=False) as f:
            temp = Path(f.name)
            json.dump({"uuid": uid, "time": time.time()}, f)
        temp.replace(path)
        subprocess.Popen(["starchaser", "settings", "firewall"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        return True
    except OSError:
        return False
    finally:
        if temp is not None:
            temp.unlink(missing_ok=True)


def trust_preview(uid: str) -> str:
    """What marking this network Trusted would newly let in, worked out by the engine (the same order of Allow and
    Block rules it builds the firewall from, so a Block that covers only Public networks is not skipped) and compared
    with what a Public network reaches today. Items open to only some devices say so."""
    pol = policy()
    mod = engine()
    names = []
    if mod is not None:
        try:
            pub = mod.reach(pol, "public")
            tru = mod.reach(pol, "trusted")
            was = {(i["key"], i.get("iface", ""), json.dumps(i.get("rate") or {}, sort_keys=True), tuple(i.get("sport") or [])): i
                   for i in pub}
            for i in tru:
                k = (i["key"], i.get("iface", ""), json.dumps(i.get("rate") or {}, sort_keys=True), tuple(i.get("sport") or []))
                old = was.get(k)
                if old is not None and (old["anyDevice"] or not i["anyDevice"]):
                    continue                           # Public already reaches it as widely: nothing new
                n = plain_app_name(i.get("name") or "Something")
                if not i["anyDevice"]:
                    n += " (some devices)"
                elif i.get("iface") or i.get("rate") or i.get("sport"):
                    n += " (with limits you set)"
                if n not in names:
                    names.append(n)
        except Exception:
            names = None; print("preview error", repr(sys.exc_info()[1]), file=sys.stderr)
    else:
        names = None
    if names is None:
        return "Trusting turns on what your rules allow for Trusted networks; only running apps answer (see Settings > Firewall)."
    if (pol.get("defaults") or {}).get("in") == "allow":
        names.append("other services and ports")
    # Keep the bell notice short; Settings has the full list.
    if names:
        # (three names fit; a lone "1 more" hid a real permission, so a fourth is named too, and only a longer
        # list is counted, with where to see all of it)
        shown = names if len(names) <= 4 else names[:3]
        what = ("Trusting also lets devices reach " + ", ".join(shown)
                + (f", and {len(names) - 3} more (all listed in Settings \u203a Firewall)" if len(names) > 4 else "") + ".")
    else:
        what = "Trusting lets nothing extra in under your rules today."
    return what.rstrip(".") + "; only running apps answer."


def close_card(nid: str, why: str = "") -> None:
    """Take a card we showed off the screen (the app closed it, so the cockpit drops its popup)."""
    if not nid.isdigit():
        return
    dbg(f"closing card {nid}: {why or 'no reason given'}")
    try:
        subprocess.run(["busctl", "--user", "call", "org.freedesktop.Notifications", "/org/freedesktop/Notifications",
                        "org.freedesktop.Notifications", "CloseNotification", "u", nid],
                       capture_output=True, timeout=5)
    except (OSError, subprocess.TimeoutExpired):
        pass


def check_now() -> None:
    """Start the root-side check now instead of at the timer's turn (no password: polkit allows only this unit)."""
    try:
        subprocess.run(["systemctl", "--no-ask-password", "--no-block", "start", "starchaser-firewall-stats.service"],
                       stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10)
    except (OSError, subprocess.TimeoutExpired):
        pass


def outgoing_hold_notice() -> None:
    ans = notify("New connections are being held",
                 "The program that checks apps reaching out stopped and has not come back. New connections are "
                 "paused (ones already open keep working). Open Settings > Firewall.",
                 [("settings", "Open Firewall")], icon="dialog-warning", urgency="critical", stay=True, zone="outgoing-hold")
    if ans == "settings":
        subprocess.Popen(["starchaser", "settings", "firewall", "@outgoing-protection"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def checker_paused_notice(reason: str, on_shown=None) -> None:
    """The app checker cannot start, so the app firewall is paused and nothing is held (firewall.py CHECKER_PAUSED).
    After an update that replaced the running kernel only a restart of the computer helps: the notice says that.
    on_shown runs once the card is on screen: only then does the watcher count the person as told."""
    if reason == "restart":
        title, body = ("Restart to finish the update",
                       "Until then, the app firewall is paused; your other firewall rules still apply.")
    else:
        title, body = ("The app firewall is paused",
                       "The program that checks apps reaching out keeps stopping. Your other firewall rules still "
                       "apply. Open Settings > Firewall.")
    ans = notify(title, body, [("settings", "Open Firewall")], icon="dialog-warning", stay=True, zone="checker-paused",
                 on_shown=on_shown)
    if ans == "settings":
        subprocess.Popen(["starchaser", "settings", "firewall", "@outgoing-protection"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def down_notice() -> None:
    """The alarm card, with a button to the Reload saved firewall banner. It waits for its answer here, while the
    watcher takes it down by its id (OPEN_DOWN_CARDS) once the rules run again or the firewall is turned off."""
    ans = notify("The firewall isn't running",
                 "The firewall is set to on, but its rules aren't loaded, so other computers can connect to this one. "
                 "Open Firewall and click Reload saved firewall.", [("settings", "Open Firewall")],
                 icon="dialog-error", urgency="critical", zone="down")
    if ans == "settings":
        subprocess.Popen(["starchaser", "settings", "firewall", "@rules-not-running"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def close_down_cards() -> None:
    with OPEN_LOCK:
        cards = list(OPEN_DOWN_CARDS)
    for nid in cards:
        close_card(nid, "the firewall's running notice is replaced or no longer true")


def watch_outgoing_hold(changes=None) -> None:
    """One notice per outage, and one per pause of the app firewall, including across a restart of this user
    service."""
    flag = RUNTIME / "starchaser-firewall-outgoing-noticed"
    paused_flag = RUNTIME / "starchaser-firewall-checker-paused-noticed"
    paused_sent = ""                                   # the pause whose card was sent from this process
    while True:
        try:
            st = json.loads(STATS.read_text())
            outage = st.get("outgoingOutage") or ""
            try:
                told = flag.read_text().strip()
            except OSError:
                told = ""
            fresh = time.time() - (st.get("updated") or 0) < STATS_FRESH
            if fresh and (not outage or not policy().get("enabled")):
                flag.unlink(missing_ok=True)
                with OPEN_LOCK:
                    cards = list(OPEN_HOLD_CARDS)
                for nid in cards:
                    close_card(nid, "the app checker came back or the firewall was turned off")
            elif fresh and st.get("outgoingChecker") == "down" and outage != told and policy().get("enabled"):
                flag.write_text(outage + "\n")
                threading.Thread(target=outgoing_hold_notice, daemon=True).start()
            paused = st.get("outgoingPaused") or {}
            name = f"{paused.get('reason')} {paused.get('since')}" if paused.get("reason") else ""
            try:
                paused_told = paused_flag.read_text().strip()
            except OSError:
                paused_told = ""
            if fresh and (not name or not policy().get("enabled")):
                paused_flag.unlink(missing_ok=True)
                with OPEN_LOCK:
                    cards = list(OPEN_PAUSED_CARDS)
                for nid in cards:
                    close_card(nid, "the app checker is checking again or the firewall was turned off")
            elif fresh and name not in (paused_told, paused_sent):
                # told once the card is on screen (a notice sent while the desktop restarts would be lost for good)
                paused_sent = name
                threading.Thread(target=checker_paused_notice, args=(paused["reason"],),
                                 kwargs={"on_shown": lambda name=name: paused_flag.write_text(name + "\n")},
                                 daemon=True).start()
        except (OSError, ValueError, AttributeError):
            pass
        pause(5, bool(OPEN_HOLD_CARDS or OPEN_PAUSED_CARDS), changes)


def last_change() -> float:
    """When the firewall last changed through Settings or starchaser-admin (Reload saved firewall, Put my rules back,
    a kept change): every such change writes a History entry. 0 when there is no History yet."""
    try:
        return HISTORY.stat().st_mtime
    except OSError:
        return 0.0


def rules_match_now(wait: float = 0) -> bool:
    """True only when a fresh check made after the last firewall change says the running rules match the saved ones
    (so an outside change is gone). A check from before that change (Reload loads the rules a moment before the
    check is rewritten) can't speak for it: ask for a new check and wait up to `wait` seconds for it."""
    deadline = time.time() + wait
    asked = False
    while True:
        try:
            st = json.loads(STATS.read_text())
            upd = st.get("updated") or 0
            if 0 <= time.time() - upd < STATS_FRESH and upd > last_change():
                return (st.get("live") or {}).get("matches") is True
        except (OSError, ValueError, AttributeError):
            pass
        if time.time() >= deadline:
            return False
        if not asked:
            check_now()
            asked = True
        time.sleep(1)


def drift_notice(diff: str, on_shown) -> None:
    if rules_match_now(wait=20):
        return                                        # fixed in the meantime: a card now would report a stale change
    # Lead with the choice, leaving rule details below the toast's Read more fold. Identical descriptions
    # can come from separate rules; keep their count instead of filling the card with repeated sentences.
    counts = {}
    for line in diff.splitlines():
        if line.strip():
            counts[line] = counts.get(line, 0) + 1
    details = "\n".join(line + (f" ({count} matching changes)" if count > 1 else "")
                        for line, count in counts.items())
    body = ('Changed outside Settings. Review the changes, or choose "Put my rules back" '
            'to replace the running rules with your last saved rules.\n\nDetails:\n' + details)
    answer = notify("Firewall rules changed", html.escape(body),
                    [("review", "Review"), ("restore", "Put my rules back")],
                    icon="dialog-warning", urgency="critical", stay=True, zone="drift", on_shown=on_shown)
    if answer == "restore" and rules_match_now():
        notify("Your saved rules were already running.", "Nothing needed to be put back.")
        answer = ""
    if answer == "restore":
        # --repair: the saved rules exactly as they last ran; an unapplied (even broken) hand-written edit can't
        # stop this or ride along with it
        result = admin("firewall-reload", "--repair")
        if not result.get("ok") and not result.get("canceled"):
            why = (result.get("errors") or "").strip()
            print(f"starchaser firewall ask: putting the firewall rules back failed: {why or 'no reason given'}",
                  file=sys.stderr, flush=True)
            notify("Your firewall rules could not be put back",
                   html.escape(why + ("\n\n" if why else "")) +
                   "The outside change may still be running. Open Settings > Firewall to review your rules and try again.",
                   icon="dialog-warning")
        if result.get("timed"):
            answer = "review"                         # changed hand-written rules need Settings' Keep countdown
        elif result.get("ok"):
            notify("Your saved rules are running again.", "")
    if answer == "review":
        subprocess.Popen(["starchaser", "settings", "firewall"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def forget_noticed(noticed: set, noticed_file: Path, lock) -> None:
    """Forget the outside changes already reported, in this watcher and in the session file."""
    with lock:
        if not noticed:
            return
        noticed.clear()
        try:
            noticed_file.write_text("")
        except OSError:
            pass


def watch_running(changes=None) -> None:
    """The firewall is set to on but its rules aren't loaded (the start-up load failed, or the table was removed):
    tell the person once each time that starts, so it isn't only visible on the Firewall page. Read from the
    root-side check (world-readable, every 60 seconds); an old check (the timer isn't running) says nothing.
    When a later check shows the rules loaded again (Reload saved firewall), that card is replaced by one saying so,
    so it doesn't stay on screen claiming other computers can connect; turned off instead, the card just goes.
    Outside changes also need two checks; each distinct difference is reported only once per login session,
    including across restarts of this service. Once a fresh check shows the rules match (or the firewall is off),
    those cards close and past notices are forgotten, so a change that comes back later is reported again."""
    told = ""                                          # "shown" while the alarm card is up (its id: OPEN_DOWN_CARDS)
    # "down" only counts once two different checks (a different "updated") both say so: turning the firewall Off
    # removes the table a moment before the policy file says Off, and one check landing in between would raise a
    # false alarm while Settings shows Off and its countdown
    down_seen, last_upd = 0, None
    drift_seen, drift_upd, drift_key = 0, None, ""
    noticed_file = RUNTIME / "starchaser-firewall-drift-noticed"
    try:
        noticed = set(noticed_file.read_text().splitlines())
    except OSError:
        noticed = set()
    noticed_lock = threading.Lock()
    pending = set()

    def report(diff, key):
        def shown():
            with noticed_lock:
                noticed.add(key)
                try:
                    with noticed_file.open("a") as f:
                        f.write(key + "\n")
                except OSError:
                    pass                              # still remembered in this watcher
        try:
            drift_notice(diff, shown)
        finally:
            pending.discard(key)

    while True:
        down = up = off = False
        diff, matching = "", False
        try:
            st = json.loads(STATS.read_text())
            upd = st.get("updated") or 0
            # a check from before the policy last changed can't speak for it: just after the firewall is turned on,
            # the last check still says "not loaded" until the next one
            fresh = 0 <= time.time() - upd < STATS_FRESH and upd > POLICY.stat().st_mtime
            live = st.get("live") or {}
            loaded = live.get("loaded")
            enabled = bool(policy().get("enabled"))
            # nor can one from before the last Reload: its "not loaded" raised the alarm seconds after Reload had
            # loaded the rules again (QA 2026-11-03)
            down = fresh and enabled and loaded is False and upd > last_change()
            # loaded but not matching the policy (the table came back empty or changed) isn't "running again"
            up = fresh and enabled and loaded is True and (st.get("live") or {}).get("matches") is not False
            off = not enabled
            matching = fresh and live.get("matches") is True
            # an outside change is only reported from a check made after the last Reload or saved change: the one
            # before it still shows the difference that Reload just put right
            if fresh and enabled and loaded is True and live.get("matches") is False and upd > last_change():
                diff = "\n".join(line for line in live.get("diff", []) if isinstance(line, str) and line.strip())
        except (OSError, ValueError, AttributeError):
            pass
        if not down:
            down_seen, last_upd = 0, None
        elif upd != last_upd:
            down_seen, last_upd = down_seen + 1, upd
        elif down_seen == 1:
            # one check says "not loaded" and the next is up to a minute away: ask for it now (10 s after the first,
            # past the moment turning Off spends between removing the table and saving the policy), so the warning
            # comes within about 20 seconds, not two minutes. polkit lets the person at the computer start only this
            # read-only check (50-starchaser-firewall-stats.rules)
            check_now()
        if down and down_seen >= 2 and not told:
            told = "shown"
            threading.Thread(target=down_notice, daemon=True).start()
        elif told and up:
            # the alarm card is taken down and a new, ordinary one says it's fixed: replacing the critical card in
            # place (notify-send -r) left the alarm up, since a critical card never times out and the update kept it.
            # The cockpit drops a critical card its app closed from the bell's list too, so only "running again" stays.
            close_down_cards()
            notify("The firewall is running again",
                   "Its rules are loaded, so other computers can connect only the way your rules allow.",
                   icon="security-high", bell_only=True)
            told = ""
        elif told and off:
            close_down_cards()
            told = ""
        key = hashlib.sha256(diff.encode()).hexdigest() if diff else ""
        if key != drift_key or not key:
            drift_seen, drift_upd, drift_key = 0, None, key
        if key and upd != drift_upd:
            drift_seen, drift_upd = drift_seen + 1, upd
        elif key and drift_seen == 1:
            check_now()
        if key and drift_seen >= 2 and key not in noticed and key not in pending:
            pending.add(key)
            threading.Thread(target=report, args=(diff, key), daemon=True).start()
        if matching or off:
            with OPEN_LOCK:
                cards = list(OPEN_DRIFT_CARDS)
            for nid in cards:
                close_card(nid, "the firewall rules match Settings again or the firewall was turned off")
            # the difference has cleared: if it (or one like it) comes back after "Put my rules back", say so again
            forget_noticed(noticed, noticed_file, noticed_lock)
        # the check runs every 60 seconds (10 with the page open), and each one rewrites the stats file: a wait for
        # it, except while an alarm or a difference waits for the next check, which is asked for after 10 s
        pause(10, down_seen == 1 or bool(key and drift_seen == 1) or bool(told), changes)


PENDING = Path("/run/starchaser-firewall.pending")          # starchaser-admin's public "waiting for Keep" record
HISTORY = Path("/var/lib/starchaser/firewall-history")


def newest_history() -> dict:
    """The newest History entry a person made (by its saved time, then its id), or {}. Temporary allowances
    (runtimeOnly) are recorded automatically and must not hide a "Not kept" entry."""
    best, key = {}, None
    for f in HISTORY.glob("*.json") if HISTORY.is_dir() else []:
        try:
            h = json.loads(f.read_text())
        except (OSError, ValueError):
            continue
        if not isinstance(h, dict) or h.get("runtimeOnly"):
            continue
        k = (h.get("time") or 0, str(h.get("id") or ""))
        if key is None or k > key:
            best, key = h, k
    return best


# Settings' Firewall page touches this about every second while it shows a Keep countdown, and writes "told" in it
# once it has said itself that the change went back by itself (so the notification would say it twice)
PAGE_BEAT = Path(os.environ.get("XDG_RUNTIME_DIR") or "/tmp") / "starchaser-firewall-page"
# Presence is independent of the pending-change read and the rollback acknowledgement above.
PAGE_VISIBLE = PAGE_BEAT.with_name("starchaser-firewall-page-visible")


def page_told() -> bool:
    """Whether Settings' Firewall page said "Your change was undone" itself. Waits while the page is still beating
    (it notices a moment after the change went back); a page that was closed or left stops beating, and then the
    notification is sent: at worst it's said twice, never not at all."""
    end = time.time() + 10
    while time.time() < end:
        try:
            age = time.time() - PAGE_BEAT.stat().st_mtime
            told = PAGE_BEAT.read_text().startswith("told")
        except OSError:
            return False
        if told:
            return age < 15
        if age >= 3:
            return False
        time.sleep(0.5)
    return False


def trial_notice(trial: dict) -> None:
    """Offer the Keep controls without keeping an outdated countdown in the bell."""
    if not trial_out_of_view(trial):
        return
    # Give a newly opened page time to publish presence, even before its state read finishes.
    time.sleep(3)
    try:
        current = json.loads(PENDING.read_text())
    except (OSError, ValueError):
        return
    if not isinstance(current, dict) or (current.get("id"), current.get("deadline")) != \
            (trial.get("id"), trial.get("deadline")) or not trial_out_of_view(current):
        return
    left = trial["deadline"] - time.time()
    if left <= 0:
        return
    deadline = time.strftime("%I:%M:%S %p", time.localtime(trial["deadline"])).lstrip("0")
    answer = notify("Firewall change waiting for Keep",
                    f"Your change will go back at {deadline} unless you press Keep. Open Firewall to review it.",
                    [("review", "Open Firewall")], icon="security-high", stay=True, zone="trial", close_after=left)
    if answer == "review":
        subprocess.Popen(["starchaser", "settings", "firewall"], start_new_session=True,
                         stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)


def trial_out_of_view(trial: dict | None) -> bool:
    if not trial or (trial.get("deadline") or 0) <= time.time():
        return False
    try:
        return time.time() - PAGE_VISIBLE.stat().st_mtime >= 3
    except OSError:
        return True


def watch_not_kept(changes=None) -> None:
    """Keep a trial reachable after leaving Settings, and report an automatic rollback once."""
    last = None
    noticed = None
    while True:
        try:
            try:
                cur = json.loads(PENDING.read_text())
            except (OSError, ValueError):
                cur = None
            if not isinstance(cur, dict) or not cur.get("id"):
                cur = None
            key = (cur["id"], cur.get("deadline")) if trial_out_of_view(cur) else None
            if key != noticed or key is None:
                with OPEN_LOCK:
                    cards = list(OPEN_TRIAL_CARDS)
                for nid in cards:
                    close_card(nid, "the firewall trial was reviewed, extended, or ended")
                noticed = key
                if key:
                    threading.Thread(target=trial_notice, args=(cur,), daemon=True).start()
            if last and not cur:
                h = newest_history()
                undid = h.get("undid")
                if str(h.get("summary") or "").startswith("Not kept: went back by itself") \
                        and (not undid or not last.get("history") or undid == last.get("history")) \
                        and not page_told():
                    notify("Firewall change undone",
                           "Your firewall change was undone because Keep wasn't pressed in time. "
                           "Settings > Firewall > History can put it back.", icon="dialog-information")
            last = cur
        except Exception as e:                         # never let the thread die quietly
            print(f"starchaser firewall ask: not-kept watch: {type(e).__name__}: {e}", file=sys.stderr, flush=True)
        pause(3, last is not None or noticed is not None, changes)     # (a trial starts with a write to its record)


def watch_runtime_access(changes=None):
    """One quiet Public chip, temporary countdowns and one bell line when a permission ends."""
    previous, known, public_until, public_net = {}, set(), 0, ""
    last_pause = None
    output = RUNTIME / "starchaser-firewall-chip.json"
    last = ""
    while True:
        try:
            stats = json.loads(STATS.read_text())
            zones = zones_now()
            p = policy()
            grants = {"|".join(str(o.get(k, "")) for k in ("addr", "proto", "port", "iface")): o
                      for o in stats.get("allowedOnce", []) if o.get("until", 0) > time.time()}
            if previous.keys() - grants.keys():
                notify("Temporary access ended", "The temporary firewall permission ended. Connections already open may stay open.", bell_only=True)
            paused = bool(stats.get("publicPause", {}).get("on"))
            if last_pause is True and not paused:
                notify("Public pause ended", "Your saved permissions apply again. You can review them in Firewall.", bell_only=True)
            last_pause = paused
            previous = grants
            for net in zones.get("networks", []):
                key = (net.get("uuid", ""), net.get("device", ""))
                public = net.get("device") in zones.get("zones", {}).get("public", [])
                if public and key not in known:
                    public_until, public_net = int(time.time()) + 60, net.get("uuid", "")
                if public: known.add(key)
            # A network left then rejoined is a new join, but do not repeat a chip on every poll.
            active = {(n.get("uuid", ""), n.get("device", "")) for n in zones.get("networks", [])}
            known.intersection_update(active)
            private = (p.get("privacy") or {}).get("quietPublic") or bool(stats.get("publicPause", {}).get("on"))
            mod = engine()
            if not private and mod and stats.get("live", {}).get("matches") is True:
                private = not bool(mod.reach(p, "public"))
            private = private and bool(p.get("enabled")) and stats.get("live", {}).get("matches") is True and time.time() - stats.get("updated", 0) < 150
            message = "Public network. New sharing connections are blocked." if private else "Public network. Review sharing permissions."
            value = json.dumps({"publicUntil": public_until, "network": public_net, "message": message, "wired": any(n.get("uuid") == public_net and "ethernet" in n.get("type", "") for n in zones.get("networks", [])),
                                "temporaryUntil": min((o['until'] for o in grants.values()), default=0), "count": len(grants)})
            if value != last:
                tmp = output.with_name(f".{output.name}.{os.getpid()}.tmp"); tmp.write_text(value); tmp.replace(output); last = value
        except (OSError, ValueError, TypeError, KeyError): pass
        pause(3, bool(previous) or public_until > time.time(), changes)   # (a permission counting down, a new public chip)


def main(argv: list) -> None:
    cmd = argv[0] if argv else ""
    if cmd == "run":
        # Lock before cleanup or any worker starts; a second service must not close the first service's cards.
        # Keep the file in place so all callers lock the same inode. The open file holds it for the whole run.
        with (RUNTIME / "starchaser-firewall-ask.lock").open("a") as lock:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except BlockingIOError:
                return
            clear_network_card()
            try:
                changes = FileChanges([POLICY.parent, STATS.parent, CHILD_REQUESTS.parent, PENDING.parent, RUNTIME])
            except OSError:
                changes = None
            inc, out = Incoming(), Outgoing()
            pending_apps(out.pending)       # nothing is held by a new asker: a list the last one left is stale
            threading.Thread(target=serve_opensnitch, args=(out,), daemon=True).start()
            threading.Thread(target=watch_running, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_outgoing_hold, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_runtime_access, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_traffic, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_child_requests, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_not_kept, args=(changes,), daemon=True).start()
            threading.Thread(target=watch_allowed, args=(changes,), daemon=True).start()
            inc.follow()
    elif cmd == "test-in":
        if len(argv) not in (4, 5) or argv[2] not in ("tcp", "udp") or not argv[3].isdigit() \
                or not 0 < int(argv[3]) < 65536 or (len(argv) == 5 and argv[4] not in ZONE_WORDS):
            print(f"starchaser firewall ask: test-in needs an address, tcp or udp, a port from 1 to 65535 and "
                  f"optionally a kind of network ({', '.join(ZONE_WORDS)}).\n{USAGE}", file=sys.stderr)
            sys.exit(2)
        try:
            src = ipaddress.ip_address(argv[1]).compressed
        except ValueError:
            print(f"starchaser firewall ask: test-in: {argv[1]} is not an address.\n{USAGE}", file=sys.stderr)
            sys.exit(2)
        zmap = zones_now()
        zone = argv[4] if len(argv) == 5 else "trusted"
        iface = next(iter((zmap.get("zones") or {}).get(zone) or []), "")
        Incoming().ask(src, argv[2], int(argv[3]), wait=0, zone=zone, iface=iface, test=True)
    else:
        print(f"starchaser firewall ask: {'unknown command ' + repr(cmd) if cmd else 'no command given'}.\n{USAGE}",
              file=sys.stderr)
        sys.exit(2)


USAGE = ("Usage: starchaser firewall ask run | test-in <address> <tcp|udp> <port> [network kind]\n"
         "Run 'starchaser firewall ask --help' for more help.")
# --help: short and plain (the notes at the top of this file are for whoever works on it)
HELP = f"""{USAGE.splitlines()[0]}

The firewall's notices: a bell notice when a device reaches a listening system program, and (when Settings > Firewall > Apps reaching out
is Ask) a card when an app wants to connect out. It runs as a background service; you don't need to start it.

  run              ask the questions (what the background service runs)
  test-in <address> <tcp|udp> <port> [network kind]
                   show a notice for a listening system program reached from <address>
                   (network kind: {', '.join(ZONE_WORDS)})
                   Your answers to a test question are real: they change what the firewall allows.

Settings > Firewall turns these questions on or off."""


if __name__ == "__main__":
    if sys.argv[1:2] in (["-h"], ["--help"], ["help"]):      # usage on request is not an error
        print(HELP)
        sys.exit(0)
    main(sys.argv[1:])
