"""What proxy-tui and proxy-suite-gui show and do, without drawing any of it. Reads come from proxy_ctl in-process. Every change runs proxy-ctl itself, so validation, permission errors and systemd triggers stay in one place, and its die() cannot take a front end down. """ import base64 import json import os import re import select import shlex import shutil import signal import subprocess import sys import time import urllib.parse import zlib from dataclasses import dataclass, field, replace from typing import Callable import proxy_ctl as ctl CTL = "proxy-ctl" def _die(message, status=1): # Readers run in-process: the message rides the SystemExit, so an empty tab can say why. sys.exit(message) # Clash API calls and systemctl spawns that several readers repeat within one load. MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_timer_next_run", "svc_state", "_wl", "_inbound_runtime_rows") # proxy_ctl as the CLI has it, before the patching below: its own tests put these back. CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)} ctl.die = _die _memo = {} # (reader, args) -> result, cleared at the start of every load def _per_load(fn): def wrapped(*args): key = (fn, args) if key not in _memo: _memo[key] = fn(*args) return _memo[key] return wrapped for _name in MEMOIZED: setattr(ctl, _name, _per_load(getattr(ctl, _name))) def new_load(): _memo.clear() @dataclass class Field: """One thing an action asks for before it runs: a box of its own in the form.""" name: str # its key in the values argv and stdin get label: str hint: str = "" # what it takes, or an example optional: bool = False choices: Callable = None # selected row or None -> {value: description}: offered while typing; anything else still goes fixed: bool = False # the choices are the only values: picked from a list items: bool = False # a list, each value a box of its own; its value is a list of strings current: Callable = None # items: selected row -> what it holds now. The form edits that, and runs only a change number: bool = False advanced: bool = False # folded away under "More options" @dataclass class Action: key: str label: str argv: Callable # (selected row or None, {field: value}, unit states) -> proxy-ctl argv when: Callable = None # row -> applies; None: a tab-wide action that needs no row fields: list = field(default_factory=list) # ask for these first confirm: bool | Callable = False # or row -> ask first mode: str = "run" # run: result in the feedback line; dialog: output streamed into a dialog; suspend: hand over the terminal; pause: suspend, then wait for enter; copy: last line to the clipboard offered: Callable = None # () -> this configuration has it; None: every one does tty: bool = False # it asks on the terminal: only a front end that hands the terminal over offers it stdin: Callable = None # (selected row or None, {field: value}) -> text proxy-ctl reads on stdin, or None @dataclass class Selector: """One choice a tab makes apart from its rows (the Routing tab's mode), drawn above the table.""" label: str options: Callable # () -> [(value, label)] current: Callable # () -> the value chosen now argv: Callable # value -> proxy-ctl argv that chooses it key: str = "m" # opens the choice @dataclass class Tab: id: str title: str available: Callable # unit states -> bool columns: list # (row field, heading) rows: Callable # unit states -> [row dict with a unique "key"] summary: Callable = None # () -> text above the table, read with every load actions: list = field(default_factory=list) tree: bool = False # rows carry "ancestors" (row keys) and "group": the order means something, so no sorting selector: Selector = None def ROW(_): return True # Whether the front end can hand a command the terminal to ask on. The GUI cannot: it clears this. TTY = True def offered(action): return (TTY or not action.tty) and (action.offered is None or bool(_safe(action.offered, fallback=False))) def needs_confirm(action, row): return action.confirm(row) if callable(action.confirm) else action.confirm # --- forms -------------------------------------------------------------------- def field_choices(f, row=None): """A field's choices, {value: description}; unreadable state costs the choices, not the form.""" return {str(k): str(v or "") for k, v in (_safe(f.choices, row, fallback=None) or {}).items()} if f.choices else {} def form_choices(action, row=None): """{field: its choices}, read once when a form opens.""" return {f.name: field_choices(f, row) for f in action.fields if f.choices} def items(value): """A list field's value: its values in order, once each. Text is several, space-separated (a paste).""" values = value.split() if isinstance(value, str) else [str(v).strip() for v in value or []] return list(dict.fromkeys(v for v in values if v)) def form_values(action, values): """Every field's value: text stripped, a list field's a list; what was left out is empty.""" values = values or {} return {f.name: items(values.get(f.name)) if f.items else str(values.get(f.name) or "").strip() for f in action.fields} def form_current(action, row=None): """{field: what the row holds now} for the fields that edit it, read once when a form opens.""" return {f.name: items(_safe(f.current, row, fallback=None)) for f in action.fields if f.current} def form_start(action, row=None, remembered=None): """What a form opens with: what is there now where it edits that, else what was last run from it.""" return {**{k: v for k, v in (remembered or {}).items() if k not in {f.name for f in action.fields if f.current}}, **form_current(action, row)} def form_problems(action, values, row=None, choices=None, current=None): """(field name, why) for each field the form cannot run with yet. choices and current: form_choices and form_current as already read.""" values = form_values(action, values) for f in action.fields: value = values[f.name] if not value: if not f.optional: yield f.name, f"{f.label} is needed" continue if f.number and not re.fullmatch(r"-?\d+", value): yield f.name, f"{f.label} is a number" if f.fixed: allowed = (choices or {}).get(f.name) allowed = field_choices(f, row) if allowed is None else allowed if allowed and value not in allowed: yield f.name, f"{f.label} is one of: {', '.join(allowed)}" edits = [f for f in action.fields if f.current] if edits: current = form_current(action, row) if current is None else current if all(values[f.name] == current.get(f.name, []) for f in edits): yield edits[0].name, "Nothing changed yet" def form_problem(action, values, row=None, choices=None, current=None): """Why the form cannot run yet, or "".""" return next((why for _, why in form_problems(action, values, row, choices, current)), "") def form_argv(action, row, values, states, choices=None, current=None): """(argv, stdin) the filled form runs. ValueError: it cannot run, and why.""" values = form_values(action, values) if problem := form_problem(action, values, row, choices, current): raise ValueError(problem) argv = action.argv(row, values, states) return argv, action.stdin(row, values) if action.stdin else None def field_example(f): """The example in a field's hint, or "": what an empty box shows when the whole hint does not fit.""" return f.hint.rpartition("e.g. ")[2] if "e.g. " in f.hint else "" def item_changes(was, now): """A list field's edit, item by item: (value, "kept" | "added" | "removed"), what was there first.""" return [(v, "kept" if v in now else "removed") for v in was] + [(v, "added") for v in now if v not in was] def _opt(flag, value): """--flag value, or nothing for an empty value.""" return [flag, value] if value else [] def _each(flag, values): """--flag v for every value of a list field: a repeatable flag.""" return [a for v in values for a in (flag, v)] def _extra(text): """Flags typed as on the command line: the escape hatch for those without a field.""" return shlex.split(text) if text else [] def _listed(words): """Words that never change, as a field's choices.""" return lambda _: dict.fromkeys(words, "") # Field choices, read when a form opens. Looked up through ctl at each read: tests patch it. def _outbounds(_): return {**ctl._outbound_choices(), **ctl._group_choices()} def _targets(row): return {**dict.fromkeys(ctl.RULE_TARGETS, ""), **_outbounds(row)} def _users(_): return ctl._inbound_runtime_names("users") def _listeners(_): return ctl._inbound_runtime_names("listeners") def _rule_matches(row): """What the selected runtime rule matches now, as `rules add` spells each.""" rule = next((r for r in ctl._runtime_rules() if r["name"] == row["name"]), None) return [f"{ctl.RULE_MATCH_SPELLING[kind]}{v}" for kind in ctl.RULE_MATCH_KINDS for v in rule.get(kind) or []] if rule else [] def _group_listed(row): """The members a group names itself; an inventory from before `listed` has only all of them.""" group = ctl._outbound_groups().get(row["tag"]) or {} return group.get("listed", group.get("members") or []) def _listener_users(row): return [ctl._s(u.get("name")) for u in ctl._inbound_runtime_rows("users") if row["tag"] in (u.get("listeners") or [])] def _user_listeners(row): user = next((u for u in ctl._inbound_runtime_rows("users") if ctl._s(u.get("name")) == row["name"]), {}) return [ctl._s(t) for t in user.get("listeners") or []] MATCHES = Field("matches", "Matches", "domains, addresses, geosite:x, geoip:x or ruleset:x - e.g. bank.example or 10.0.0.0/8", items=True) MEMBERS = Field("members", "Members", "outbounds and groups, in the order tried", optional=True, items=True, choices=_outbounds) DOMAIN = Field("domain", "Domain", "e.g. example.com") PROBE = Field("domain", "Domain", "e.g. example.com, or example.com/path") COMMAND = Field("command", "Command", "as in a shell, e.g. firefox --private-window") def _app_via(_): # What the shell completion offers after `apps add --via`: it knows what this host can pin. return ctl._complete_tree("apps", "add", "--via") # What proxy-ctl and systemctl print when only root may do it. # ponytail: matches the wording; an exit status of its own (77) if that ever drifts. ROOT_HINT = re.compile(r"re-run with sudo|run with sudo|run as root|Interactive authentication required|Access denied") def is_root(): return os.geteuid() == 0 def can_elevate(): """Whether running as root would get further: not on a rootless host, where the user owns everything.""" return ctl.privileged() and not is_root() def needs_root(out, status): """A failed run that root could do: the front ends offer to retry it elevated.""" return bool(status) and status > 0 and can_elevate() and any(ROOT_HINT.search(line) for line in out) STATE_ICONS = {"active": "●", "inactive": "○", "failed": "✗", "activating": "◐", "deactivating": "◐", "reloading": "◐"} # --- readers ------------------------------------------------------------------ def unit_states(units): return ctl._unit_states(units) def all_units(): # The subscription update is read for the status line and the tray; it is no service to toggle. return ctl._snapshot_units() def _lines(name): try: return [line for line in ctl.lines(ctl.read_text(ctl._zapret_auto_file(name))) if line] except OSError: return [] TOGGLES = { "proxy-suite-socks": ["proxy"], "proxy-suite-tun": ["proxy", "tun"], "proxy-suite-tproxy": ["proxy", "tproxy"], "proxy-suite-killswitch": ["killswitch"], "proxy-suite-ssh-proxy": ["ssh"], "proxy-suite-warp-tunnel": ["warp"], # WARP as an AmneziaWG outbound: `proxy-ctl warp`, not `awg`, which only knows global profiles. "proxy-suite-awg-warp": ["warp"], "proxy-suite-tg-ws-proxy": ["tg"], "proxy-suite-tor": ["tor"], "proxy-suite-zapret": ["zapret"], } AWG_PREFIX = ctl._awg_service("") AWG_RUNTIME_PREFIX = "proxy-suite-awg@" ZAPRET_LISTS = ( ("learned", "zapret-hosts-auto.txt"), ("pinned", "zapret-hosts-user.txt"), ("excluded", "zapret-hosts-user-exclude.txt"), ) def _wl_entry(row): """The whitelist-bypass creator or joiner behind a row, or None.""" return next((w for w in ctl._wl() if ctl._wl_unit(w) == row["unit"]), None) def _wl_role(*roles, platforms=None, fixed=None): def check(row): w = _wl_entry(row) return bool(w) and w["role"] in roles and (platforms is None or w.get("platform") in platforms) and (fixed is None or bool(w.get("fixedLink")) == fixed) return check def _path(text): """A typed path, whole: proxy-ctl may run elsewhere (pkexec starts it in /root).""" if not text.strip(): raise ValueError("no path given") return os.path.abspath(os.path.expanduser(text.strip())) def _wl_argv(verb, *extra): return lambda r, *_: ["wl", verb, _wl_entry(r)["name"], *extra] def _awg_profile(row): """The global AmneziaWG profile behind a row, or empty.""" unit = row["unit"] for prefix in (AWG_RUNTIME_PREFIX, AWG_PREFIX): if unit.startswith(prefix) and (name := unit.removeprefix(prefix)) in ctl._awg_profiles(): return name return "" def _unit_argv(row, verb): if profile := _awg_profile(row): return ["awg", verb, profile] if w := _wl_entry(row): return ["wl", verb, w["name"]] return [*TOGGLES[row["unit"]], verb] def toggle_argv(row, *_): return _unit_argv(row, "off" if row["state"] == "active" else "on") def restart_argv(row, *_): return _unit_argv(row, "restart") def _controllable(row): return row["unit"] in TOGGLES or bool(_awg_profile(row)) or bool(_wl_entry(row)) # Units whose failure is one run's, not something still down: once seen, it stops marking the # suite failed until a later run fails again. FAILURE_EVENTS = (ctl.SUBSCRIPTION_UPDATE,) def failure_marks(states): """unit -> when it last failed, for the failed FAILURE_EVENTS: a later failure is a new mark. Empty where the manager does not say (the supervisor): a run that does not fail ends the mark there.""" units = [u for u in FAILURE_EVENTS if states.get(u) == "failed"] if not units: return {} _, out = ctl.systemctl("show", "--property=Id,InactiveEnterTimestampMonotonic", "--", *units, capture=True, quiet=True) marks = {} for unit, block in zip(units, out.strip().split("\n\n"), strict=False): props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line) marks[unit] = props.get("InactiveEnterTimestampMonotonic", "") return {u: marks.get(u, "") for u in units} def unseen(states, marks, seen): """states with the failures already seen (unit -> mark) read as inactive: nothing counts them as failed.""" return {u: "inactive" if u in marks and seen.get(u) == marks[u] else s for u, s in states.items()} def service_rows(states): return [ {"key": u, "unit": u, "name": u.removeprefix("proxy-suite-"), "state": s} for u, s in states.items() if u != ctl.SUBSCRIPTION_UPDATE ] def route_mode_options(): """The route modes as the Routing tab's selector and the tray offer them: (mode, label).""" return [(m, ctl._route_mode_label(m)) for m in ("default", *ctl.ROUTE_MODES)] def routing_rows(_): return ctl._routing_rows() def routing_summary(): return ( f"Configured default: {ctl._route_mode_default()}; an override lasts until you switch back to default. " "Checked top to bottom: a lower # first, a runtime rule first among equals, then the final outbound. " "On sing-box, a rule's domains and addresses change without a restart." ) def outbound_rows(_): inventory = ctl._outbound_inventory() pinned = ctl._s(inventory.get("pinned") or "") sources = inventory.get("sources") or {} detours = inventory.get("detours") or {} excluded = set(inventory.get("excluded") or []) disabled = set(ctl._outbound_disabled()) groups = inventory.get("groups") or {} # One Clash API read for every group's pick, only when there are groups. nows = ctl._group_nows() if groups else {} current = ctl._outbound_current() down = {t for t, m in (ctl._group_state().get("members") or {}).items() if isinstance(m, dict) and m.get("up") is False} reputation = ctl._reputation_by_tag() # outbounds.d is root-only; the inventory says "runtime" for what the backend loaded from it. runtime = set(ctl._runtime_tags("outbound")) | {t for t, s in sources.items() if s == "runtime"} rows, path = [], [] # As `proxy-ctl proxy outbounds` prints them: a group's members under it, in its order. for depth, t, parent in ctl._outbound_tree(inventory): path = path[:depth] key = "/".join([*path, t]) chosen, live = (ctl._s(groups[parent].get("pinned") or ""), nows.get(parent, "")) if parent else (pinned, current) group = groups.get(t) if group is not None: source = f"group: {ctl._s(group.get('strategy') or 'failover')}" notes = [f"pinned {ctl._s(group['pinned'])}"] if group.get("pinned") else [f"using {nows[t]}"] if nows.get(t) else [] else: source = "runtime" if t in runtime else ctl._s(sources.get(t) or "-") notes = [f"via {ctl._s(detours[t])}"] if t in detours else [] notes += ["disabled"] if t in disabled else ["down"] if t in down else ["never picked"] if not parent and t in excluded else [] rows.append( { "key": key, "ancestors": ["/".join(path[: i + 1]) for i in range(len(path))], "depth": depth, "parent": parent, "group": group is not None, "mark": "★" if t == chosen else "▸" if t == live else "✕" if t in disabled else "", "tag": t, "name": " " * depth + t, "reputation": "-" if group is not None else reputation.get(t, "-"), "source": source, "notes": ", ".join(notes), "runtime": t in runtime or bool(group and group.get("runtime")), "parent_runtime": bool(parent and (groups.get(parent) or {}).get("runtime")), "disabled": t in disabled, } ) path = [*path, t] return rows def _in_group(row): """A pin on a group member holds its group, not the top level.""" return ["--in", row["parent"]] if row.get("parent") else [] def _exit(row): """An outbound rather than a group: what tests, links and chains take.""" return row is not None and not row.get("group") and row.get("tag") != "block" def outbound_summary(): inventory = ctl._outbound_inventory() if not inventory: return "No outbounds yet - is proxy-suite-socks running?" return ( f"Selection: {ctl._s(inventory.get('selection') or 'first')} " f"Pinned: {ctl._s(inventory.get('pinned') or '(none)')} " f"Current: {ctl._outbound_current() or '-'}" ) def awg_rows(states): return [ { "key": p, "profile": p, "unit": ctl._awg_service(p), "state": states.get(ctl._awg_service(p)) or "inactive", "source": "runtime" if ctl._awg_added(p) else "declared", } for p in ctl._awg_profiles() ] def _awg_available(_): return bool(ctl._awg_profiles()) or ctl.env("AWG_RUNTIME_GLOBAL") == "1" def _awg_add_argv(v): # The config itself goes on stdin: in argv its keys would show in ps, sudo's log and here. what = "-" if ctl._awg_source(v["source"]) else _path(v["source"]) return ["awg", "add", *([v["name"]] if v["name"] else []), what] def _awg_add_stdin(v): return v["source"] if ctl._awg_source(v["source"]) else None def subscription_rows(_): rows = [] for source, tags in (("static", ctl._sub_tags()), ("runtime", ctl._runtime_tags("subscription"))): for t in tags: mtime, count = ctl._subscription_state(t) or (None, "-") updated = ctl._ago(int(mtime), int(time.time())) + " ago" if mtime else "-" rows.append({"key": t, "tag": t, "proxies": count, "updated": updated, "source": source}) # Nothing visible and the runtime entries out of reach: an error, not an empty tab. if not rows and (hidden := ctl._runtime_hidden("subscription")): ctl.denied(hidden) return rows def subscription_summary(): text = f"{ctl.SUBSCRIPTION_UPDATE}: {ctl.svc_state(ctl.SUBSCRIPTION_UPDATE) or 'unknown'}" next_run = ctl._timer_next_run(f"{ctl.SUBSCRIPTION_UPDATE}.timer") text += f", next update {ctl._in_time(next_run)}" if next_run else "" # The path is left out: an empty tab already names it in its "✗ Cannot read" line. if ctl._runtime_hidden("subscription"): text += f"\nRuntime subscriptions are not listed - {ctl.ask_group()}." return text def autoproxy_rows(_): path = ctl._autoproxy_dir() # Unreadable is not empty: without the autoProxy scope the state stays root-only. if blocked := ctl._autoproxy_unreadable(path): ctl.denied(blocked) state = ctl._autoproxy_state(path) domains = state.get("domains") or {} rows = [ { "key": d, "domain": d, "kind": "routed", "detail": f"via {ctl._s((v or {}).get('exit'))}, learned from {ctl._s((v or {}).get('host') or d)}", "host": ctl._s((v or {}).get("host") or d), } for d, v in sorted(domains.items()) ] backlog = sorted((state.get("backlog") or {}).items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0)) rows += [ {"key": h, "domain": h, "kind": "queued", "detail": f"{ctl._s((v or {}).get('hits'))} hits", "host": h} for h, v in backlog if h not in domains ] return rows def zapret_rows(_): if ctl.env("ZAPRET_AUTO_ENABLED") != "1": return [] rows = {} strategy_rows, strategies, verdicts = ctl._zapret_strategy_rows(), ctl._zapret_strategy_map(), ctl._zapret_verdicts() for kind, name in ZAPRET_LISTS: for host in _lines(name): excluded = kind == "excluded" rows.setdefault(f"{kind}:{host}", { "key": f"{kind}:{host}", "host": host, "kind": kind, "strategy": "" if excluded else ctl._zapret_strategy_summary(host, strategy_rows, strategies), "status": "" if excluded else ctl._zapret_status(host, verdicts), }) # What zapret2 cannot fix, the proxy carries: sites no strategy got through, blocked addresses. for name, why in ctl._zapret_proxied(verdicts): rows.setdefault(f"proxied:{name}", {"key": f"proxied:{name}", "host": name, "kind": "proxied", "strategy": "", "status": why}) return list(rows.values()) def zapret_summary(): if ctl.env("ZAPRET_AUTO_ENABLED") != "1": return 'Learned hostlists need zapret.engine = "zapret2".' text = " ".join(f"{len(_lines(name))} {kind}" for kind, name in ZAPRET_LISTS) if proxied := ctl._zapret_proxied(): text += f" {len(proxied)} via the proxy (zapret2 cannot fix them)" if ctl.env("ZAPRET_CUTOFF_ENABLED") == "1": text += "\n" + " ".join(line.strip() for line in _cutoff_status().splitlines()[:2]) return text _cutoff = {} # ts mtime -> status text: a probe rewrites ts def _cutoff_status(): try: mtime = os.path.getmtime(os.path.join(ctl._zapret_cutoff_dir(), "ts")) except OSError: mtime = None if mtime not in _cutoff: _cutoff.clear() _cutoff[mtime] = _capture(["zapret", "cutoff", "status"]) return _cutoff[mtime] def inbound_rows(_): # No presence column: XRay keys the online map by user alone (no inbound dimension), # so a per-listener row could only repeat the same verdict once per listener. The # "who is online" action shows it once per user, which is the shape the data has. # A listener behind the onion service has a second row, for its .onion link, and one per # share variant. sources = ctl._inbound_runtime_names("listeners") return [ { # The TUI titles its menu with the key: no trailing "/" for the plain link. "key": "/".join(ctl._s(x.get(k)) for k in ("tag", "user", "variant") if x.get(k)), **{k: ctl._s(x.get(k) or "") for k in ("tag", "user", "type", "port", "variant")}, **({"type": f"{ctl._s(x.get('type') or '')} ({ctl._s(x.get('variant'))})"} if x.get("variant") else {}), "source": sources.get(ctl._s(x.get("tag")), "nix"), } for x in ctl._inbound_links() ] def inbound_user_rows(_): """Inbound users as `inbounds users` lists them: the declared ones, and with inbounds.runtime the runtime ones too.""" return [ { "key": ctl._s(u.get("name")), "name": ctl._s(u.get("name")), "order": ctl._s(u.get("order") if u.get("order") is not None else ""), "address": ctl._s(u.get("address") or ""), "source": ctl._s(u.get("source") or ""), "listeners": ",".join(ctl._s(t) for t in u.get("listeners") or []), "problems": "; ".join(ctl._s(p) for p in u.get("problems") or []), } for u in ctl._inbound_runtime_rows("users") ] def _inbounds_runtime(): return ctl.env("INBOUNDS_RUNTIME_ENABLED") == "1" def _runtime_row(row): return row.get("source") == "runtime" def _user_add_argv(v): return ["inbounds", "users", "add", v["name"], *_opt("--order", v["order"]), *_each("--listener", v["listeners"])] def app_rows(_): return [ { "key": ctl._s(p.get("name")), "profile": ctl._s(p.get("name")), "route": ctl._s(p.get("route")), "via": ctl._s(p.get("outbound") or ""), "source": "runtime" if p.get("runtime") else "declared", } for p in ctl._per_app_profiles() ] def _via_run_argv(v): return ["apps", "run", "--via", v["outbound"], "--", *shlex.split(v["command"])] def _via_offered(): return bool(ctl._via_outbounds()) def snapshot(states): """proxy-ctl's status snapshot for these unit states; None when it cannot be read.""" return _safe(ctl._status_snapshot, states) def status_items(states): """(label, value, style) for the status line: style is "", "ok", "warn" or "bad".""" items = [("", "root", "warn")] if is_root() else [] overall = ctl._overall_state(snapshot(states) if states else None) items.append(("", overall["label"], {"failed": "bad", "busy": "warn", "unknown": "bad"}.get(overall["badge"], ""))) if "proxy-suite-socks" in states: default = " (default)" if ctl._route_mode_current() == "default" else "" items.append(("mode ", ctl._route_mode_effective() + default, "")) items.append(("outbound ", ctl._status_outbound() or "-", "")) if autoproxy := ctl._status_autoproxy(): items.append(("autoProxy ", autoproxy, "")) if zapret := ctl._status_zapret(): items.append(("zapret ", f"{zapret} learned", "")) failed = sum(1 for s in states.values() if s == "failed") if failed: items.append(("", f"{failed} failed", "bad")) return items def filter_rows(rows, columns, text): """Every word must match: column:value in that column (by heading or field), anything else in any column.""" names = {k.lower(): name for name, heading in columns for k in (name, heading) if k} def matches(row, term): column, sep, value = term.lower().partition(":") if sep and column in names: return value in str(row.get(names[column], "")).lower() return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns) kept = [r for r in rows if all(matches(r, t) for t in text.split())] # In a tree, a match keeps the rows above it, so it still reads as where it sits. wanted = {k for r in kept for k in r.get("ancestors") or []} if not wanted: return kept keys = {r["key"] for r in kept} | wanted return [r for r in rows if r["key"] in keys] def fold_rows(rows, collapsed): """A tree tab's rows without those under a collapsed group, each group's name showing whether it is.""" out = [] for r in rows: if any(k in collapsed for k in r.get("ancestors") or []): continue if r.get("group"): r = {**r, "name": " " * r.get("depth", 0) + ("▸ " if r["key"] in collapsed else "▾ ") + r["tag"]} out.append(r) return out def _natural(value): # "port 443" before "port 2053": digit runs compare as numbers. # isdecimal, not isdigit: "²" is a digit to isdigit, but neither \d nor int() takes it. return [int(p) if p.isdecimal() else p for p in re.split(r"(\d+)", str(value or "").lower())] def _link(row, *extra): variant = row.get("variant") or "" which = ["--onion"] if variant == "onion" else ([f"--variant={variant}"] if variant else []) return ["inbounds", "link", row["tag"], *([row["user"]] if row["user"] else []), *which, *extra] def _amneziawg(row): # AmneziaWG clients take a .conf (or its vpn:// link), not an outbound JSON. return row["type"] == "amneziawg" def _kind(*kinds): return lambda row: row["kind"] in kinds def _socks(states): return "proxy-suite-socks" in states def _enabled(name): return lambda _: ctl.env(name) == "1" def _sub_url(row, user="user"): return bool(row[user]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL")) def _secret(source): # A link's userinfo and query, a JSON outbound, a config: credentials, all of them. return "://" in source or source.startswith("{") or ctl._awg_source(source) def _add_args(v): """[tag] as `proxy-ctl ... add` takes them. A link, JSON or AmneziaWG config becomes "-": _add_stdin hands it over on stdin, out of ps and pkexec's or sudo's log.""" return [*([v["tag"]] if v["tag"] else []), "-" if _secret(v["source"]) else v["source"]] def _add_stdin(v): return v["source"] if _secret(v["source"]) else None def _source_fields(what, example): """[tag] : what most adds take.""" return [ Field("tag", "Tag", "derived from the link if empty", optional=True), Field("source", what, example), ] def _zapret_auto(): return ctl.env("ZAPRET_AUTO_ENABLED") == "1" def _rule_sets(): return bool(ctl.read_json_or(ctl.env("RULE_SETS_FILE"), [])) def _runtime_rule(row): return bool(row.get("runtime")) def _zapret_toggle(row, _, states): return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"] TABS = [ Tab( "services", "Services", lambda _: True, [("name", "Unit"), ("state", "State")], service_rows, actions=[ Action( "space", "start / stop", toggle_argv, when=_controllable, # proxy off takes tun and tproxy down with it. confirm=lambda r: r["unit"] == "proxy-suite-socks" and r["state"] == "active", ), Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"), # A failed unit restarts too: that is how it gets another try. Action("ctrl+r", "restart it", restart_argv, when=lambda r: _controllable(r) and r["state"] in ("active", "failed")), Action("R", "restart everything running", lambda r, *_: ["restart"], confirm=True), Action( "n", "new Tor circuits", lambda r, *_: ["tor", "newnym"], when=lambda r: r["unit"] == "proxy-suite-tor" and r["state"] == "active", ), # whitelist-bypass: a creator makes the call its joiner joins. Action("s", "call link", _wl_argv("link"), when=_wl_role("creator"), mode="dialog"), Action("c", "copy call link", _wl_argv("link"), when=_wl_role("creator"), mode="copy"), Action("Q", "call link as QR", _wl_argv("link", "--qr"), when=_wl_role("creator"), mode="dialog"), Action( "N", "drop its call for a new one", _wl_argv("new"), when=_wl_role("creator", fixed=False), confirm=True, ), Action( "j", "set the call it joins…", # On stdin: the call link is what lets anyone into the call. lambda r, v, _: ["wl", "join", _wl_entry(r)["name"], "-"], stdin=lambda r, v: v["link"], when=_wl_role("joiner"), fields=[Field("link", "Call link", "a room id, a slug or a URL")], ), Action( "a", "replace its login with a cookies file…", lambda r, v, _: ["wl", "auth", _wl_entry(r)["name"], _path(v["path"])], when=_wl_role("creator"), fields=[Field("path", "Cookies file", "a path: cookies exported from the desktop Creator")], ), Action( "A", "replace its login with an email and password", _wl_argv("auth"), when=_wl_role("creator", platforms=ctl.WL_PASSWORD_LOGIN), mode="pause", tty=True, ), ], ), Tab( "awg", "AmneziaWG", _awg_available, [("profile", "Profile"), ("state", "State"), ("source", "Source")], awg_rows, summary=lambda: "Only one global tunnel runs at a time: starting a profile stops TUN, TProxy and any other profile.", actions=[ Action("space", "start / stop", lambda r, *_: ["awg", "off" if r["state"] == "active" else "on", r["profile"]], when=ROW), Action("ctrl+r", "restart it", lambda r, *_: ["awg", "restart", r["profile"]], when=lambda r: r["state"] in ("active", "failed")), Action("l", "follow its logs", lambda r, *_: ["logs", r["unit"]], when=ROW, mode="suspend"), Action( "n", "add a profile…", lambda r, v, _: _awg_add_argv(v), fields=[ Field("name", "Name", "e.g. home; from the config if empty", optional=True), Field("source", "Config", "vpn://… or a .conf path (or paste a whole .conf onto the table)"), ], stdin=lambda r, v: _awg_add_stdin(v), offered=lambda: ctl.env("AWG_RUNTIME_GLOBAL") == "1", ), Action("d", "remove it", lambda r, *_: ["awg", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True), ], ), Tab( "routing", "Routing", _socks, [("priority", "#"), ("name", "Rule"), ("source", "Source"), ("target", "Target"), ("matches", "Matches"), ("notes", "Notes")], routing_rows, summary=routing_summary, tree=True, selector=Selector( "Mode", route_mode_options, # Looked up at each read: tests and the front ends patch proxy_ctl's. lambda: ctl._route_mode_current(), lambda mode: ["proxy", "mode", mode], ), actions=[ Action( "n", "add a rule…", lambda r, v, _: ["proxy", "rules", "add", v["target"], *v["matches"], *_opt("--name", v["name"]), *_opt("--priority", v["priority"])], fields=[ Field("target", "Target", "proxy, direct, block or an outbound", choices=_targets), MATCHES, Field("name", "Name", "the target's if empty; an existing rule's name extends it", optional=True), Field("priority", "Priority", "lower goes first; 50 if empty", optional=True, number=True), ], ), Action( "a", "edit its domains and addresses…", lambda r, v, _: ["proxy", "rules", "matches", r["name"], "set", *v["matches"]], when=_runtime_rule, fields=[replace(MATCHES, optional=True, current=_rule_matches)], ), Action( "t", "send it elsewhere…", lambda r, v, _: ["proxy", "rules", "target", r["name"], v["target"]], when=_runtime_rule, fields=[Field("target", "Target", "proxy, direct, block or an outbound", choices=_targets)], ), Action( "y", "set its priority…", lambda r, v, _: ["proxy", "rules", "priority", r["name"], v["priority"]], when=_runtime_rule, fields=[Field("priority", "Priority", "lower goes first; the configuration's sections are at 100 to 500", number=True)], ), Action("plus", "move it up", lambda r, *_: ["proxy", "rules", "priority", r["name"], "up"], when=_runtime_rule), Action("minus", "move it down", lambda r, *_: ["proxy", "rules", "priority", r["name"], "down"], when=_runtime_rule), Action("e", "disable it", lambda r, *_: ["proxy", "rules", "disable", r["name"]], when=lambda r: _runtime_rule(r) and not r["disabled"]), Action("e", "enable it again", lambda r, *_: ["proxy", "rules", "enable", r["name"]], when=lambda r: _runtime_rule(r) and r["disabled"]), Action("d", "remove it", lambda r, *_: ["proxy", "rules", "rm", r["name"]], when=_runtime_rule, confirm=True), Action("i", "rule sets and when each was fetched", lambda r, *_: ["proxy", "rulesets", "list"], mode="dialog", offered=_rule_sets), Action("u", "fetch the rule sets now", lambda r, *_: ["proxy", "rulesets", "update"], mode="dialog", offered=_rule_sets), ], ), Tab( "outbounds", "Outbounds", _socks, [("mark", ""), ("name", "Tag"), ("reputation", "Reputation"), ("source", "Source"), ("notes", "Notes")], outbound_rows, summary=outbound_summary, tree=True, actions=[ Action("space", "fold / unfold the group", lambda r, *_: [], when=lambda r: r["group"], mode="fold"), Action( "p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"], *_in_group(r)], when=lambda r: r["mark"] != "★" and not r["disabled"] and r["tag"] != "block", ), Action("p", "unpin it", lambda r, *_: ["proxy", "unpin", *_in_group(r)], when=lambda r: r["mark"] == "★"), Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=_exit, mode="dialog"), Action("ctrl+t", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=_exit, mode="dialog"), Action( "P", "probe a domain through it…", lambda r, v, _: ["proxy", "auto", "probe", v["domain"], "--via", ctl._backend_tag(r["tag"])], when=lambda r: _exit(r) and _enabled("AUTOPROXY_ENABLED")(r), fields=[PROBE], mode="dialog", ), Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"), Action( "n", "add an outbound…", lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v)], fields=_source_fields("Link", "vless://…, its JSON or an AmneziaWG vpn://…"), stdin=lambda r, v: _add_stdin(v), ), Action( "N", "add an AmneziaWG outbound on an interface of its own…", lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v), "--interface"], fields=_source_fields("Config", "vpn://… or a .conf path - apps can then run through it (proxy-ctl apps run --via)"), stdin=lambda r, v: _add_stdin(v), offered=lambda: ctl.env("AWG_RUNTIME_IFACE_OUTBOUNDS") == "1", ), Action( "g", "add a group…", lambda r, v, _: [ "proxy", "groups", "add", v["tag"], *v["members"], *_each("--sub", v["subs"]), *_each("--match", v["match"]), *_opt("--strategy", v["strategy"]), *_opt("--interval", v["interval"]), *_extra(v["extra"]), ], fields=[ Field("tag", "Tag", "the group's own tag, e.g. auto"), MEMBERS, Field("subs", "Subscriptions", "every entry of these", optional=True, items=True, choices=lambda _: dict.fromkeys(ctl._sub_tags(), "")), Field("match", "Match", "every outbound whose tag matches, e.g. de-*", optional=True, items=True), Field("strategy", "Strategy", "failover if empty", optional=True, fixed=True, choices=_listed(ctl.GROUP_STRATEGIES)), Field("interval", "Test interval", "a duration: 30s, 1m, 1m30s", optional=True, advanced=True), Field("extra", "Other flags", "as on the command line, e.g. --no-failback", optional=True, advanced=True), ], ), Action( "m", "edit the group's members…", lambda r, v, _: ["proxy", "groups", "members", r["tag"], "set", *v["members"]], when=lambda r: r["group"] and r["runtime"], fields=[ replace( MEMBERS, hint="outbounds and groups, in the order tried; its subscriptions and patterns add theirs", choices=lambda r: {t: d for t, d in _outbounds(r).items() if t != r["tag"]}, # not itself current=_group_listed, ) ], ), Action( "M", "take it out of the group", lambda r, *_: ["proxy", "groups", "members", r["parent"], "rm", r["tag"]], when=lambda r: r["parent_runtime"], confirm=True, ), Action( "S", "change the group's strategy…", lambda r, v, _: ["proxy", "groups", "strategy", r["tag"], v["strategy"]], when=lambda r: r["group"] and r["runtime"], fields=[Field("strategy", "Strategy", "how the group picks a member", fixed=True, choices=_listed(ctl.GROUP_STRATEGIES))], ), Action( "y", "set its priority…", lambda r, v, _: ["proxy", "priority", r["tag"], v["priority"] or "--clear"], when=lambda r: not r["parent"], fields=[Field("priority", "Priority", "lower goes first; empty: back to the default order", optional=True, number=True)], ), Action("plus", "move it up", lambda r, *_: ["proxy", "priority", r["tag"], "up"], when=lambda r: not r["parent"]), Action("minus", "move it down", lambda r, *_: ["proxy", "priority", r["tag"], "down"], when=lambda r: not r["parent"]), Action( "h", "add an outbound chained through this one…", lambda r, v, _: ["proxy", "outbounds", "add", *_add_args(v), "--detour", r["tag"]], when=_exit, fields=_source_fields("Link", "vless://… or its JSON"), stdin=lambda r, v: _add_stdin(v), ), Action( "H", "chain it through another outbound…", lambda r, v, _: ["proxy", "outbounds", "chain", r["tag"], v["hop"], *([v["tag"]] if v["tag"] else [])], when=_exit, fields=[ Field("hop", "Through", "the outbound a copy of this one dials through", choices=lambda _: ctl._outbound_choices()), Field("tag", "New tag", "-via- if empty", optional=True), ], ), Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"] and not r["group"], confirm=True), Action("d", "remove the group", lambda r, *_: ["proxy", "groups", "rm", r["tag"]], when=lambda r: r["runtime"] and r["group"], confirm=True), Action( "x", "disable it", lambda r, *_: ["proxy", "outbounds", "disable", r["tag"]], when=lambda r: _exit(r) and not r["disabled"], confirm=True, ), Action("x", "enable it again", lambda r, *_: ["proxy", "outbounds", "enable", r["tag"]], when=lambda r: r["disabled"]), # Credentials: proxy-ctl refuses these without root or the group, and the dialog says so. Action("s", "share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=_exit, mode="dialog"), Action("c", "copy share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=_exit, mode="copy"), Action("Q", "share link as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=_exit, mode="dialog"), Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=_exit, mode="dialog"), Action("k", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=_exit, mode="dialog"), Action("K", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"), Action("V", "the config as it runs here", lambda r, *_: ["proxy", "config", "--raw"], mode="dialog"), ], ), Tab( "subs", "Subs", _socks, [("tag", "Tag"), ("proxies", "Proxies"), ("updated", "Updated"), ("source", "Source")], subscription_rows, summary=subscription_summary, actions=[ Action("u", "fetch all now", lambda r, *_: ["proxy", "subs", "update"], mode="dialog"), Action("l", "follow the update's logs", lambda r, *_: ["logs", "proxy-suite-subscription-update"], mode="suspend"), Action( "n", "add a subscription…", lambda r, v, _: ["proxy", "subs", "add", *_add_args(v)], fields=_source_fields("URL", "https://…"), stdin=lambda r, v: _add_stdin(v), ), Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True), Action("s", "URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"), Action("c", "copy URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="copy"), Action("Q", "URL as QR", lambda r, *_: ["proxy", "subs", "link", r["tag"], "--qr"], when=ROW, mode="dialog"), ], ), Tab( "autoproxy", "autoProxy", _enabled("AUTOPROXY_ENABLED"), [("domain", "Domain"), ("kind", "State"), ("detail", "")], autoproxy_rows, summary=ctl._status_autoproxy, actions=[ Action("w", "how is it routed", lambda r, *_: ["where", r["domain"]], when=ROW, mode="dialog"), Action("u", "learn it now", lambda r, *_: ["proxy", "auto", "learn", r["domain"]], when=_kind("queued"), mode="dialog"), Action("p", "probe it through every exit", lambda r, *_: ["proxy", "auto", "probe", r["domain"], "--keep-going"], when=ROW, mode="dialog"), Action("P", "probe a domain…", lambda r, v, _: ["proxy", "auto", "probe", v["domain"]], fields=[PROBE], mode="dialog"), Action("n", "learn a domain…", lambda r, v, _: ["proxy", "auto", "learn", v["domain"]], fields=[DOMAIN], mode="dialog"), Action("f", "forget it", lambda r, *_: ["proxy", "auto", "forget", r["domain"]], when=_kind("routed"), confirm=True), Action("u", "relearn it from the host it was learned from", lambda r, *_: ["proxy", "auto", "relearn", r["domain"]], when=_kind("routed"), mode="dialog"), Action("F", "forget everything learned", lambda r, *_: ["proxy", "auto", "clear"], confirm=True), Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"), ], ), Tab( "zapret", "zapret", lambda s: "proxy-suite-zapret" in s or ctl.env("ZAPRET_AUTO_ENABLED") == "1", [("host", "Host"), ("kind", "List"), ("strategy", "Strategy"), ("status", "Status")], zapret_rows, summary=zapret_summary, actions=[ Action("t", "give zapret2 another try", lambda r, *_: ["zapret", "auto", "retry", r["host"]], when=_kind("proxied")), Action("f", "forget it", lambda r, *_: ["zapret", "auto", "forget", r["host"]], when=_kind("learned")), Action("p", "pin it", lambda r, *_: ["zapret", "auto", "add", r["host"]], when=_kind("learned")), Action("p", "unpin it", lambda r, *_: ["zapret", "auto", "unpin", r["host"]], when=_kind("pinned")), Action("x", "exclude it", lambda r, *_: ["zapret", "auto", "exclude", r["host"]], when=_kind("learned", "pinned")), Action("x", "include it again", lambda r, *_: ["zapret", "auto", "include", r["host"]], when=_kind("excluded")), Action("n", "pin a host as blocked…", lambda r, v, _: ["zapret", "auto", "add", v["domain"]], fields=[DOMAIN], offered=_zapret_auto), Action("X", "exclude a host…", lambda r, v, _: ["zapret", "auto", "exclude", v["domain"]], fields=[DOMAIN], offered=_zapret_auto), Action("F", "forget all learned hosts", lambda r, *_: ["zapret", "auto", "clear"], confirm=True, offered=_zapret_auto), Action("P", "probe the line's cutoff again", lambda r, *_: ["zapret", "cutoff", "probe"], mode="dialog", offered=lambda: ctl.env("ZAPRET_CUTOFF_ENABLED") == "1"), Action("space", "start / stop zapret", _zapret_toggle), Action("ctrl+r", "restart zapret", lambda *_: ["zapret", "restart"]), ], ), Tab( "inbounds", "Inbounds", _enabled("INBOUNDS_ENABLED"), [("tag", "Tag"), ("user", "User"), ("type", "Type"), ("port", "Port")], inbound_rows, summary=lambda: f"proxy-suite-inbounds: {ctl.svc_state('proxy-suite-inbounds') or 'unknown'}", actions=[ Action("s", "share link", lambda r, *_: _link(r), when=ROW, mode="dialog"), Action("c", "copy share link", lambda r, *_: _link(r), when=ROW, mode="copy"), Action("Q", "share link as QR", lambda r, *_: _link(r, "--qr"), when=ROW, mode="dialog"), Action("S", "subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=lambda r: bool(r["user"]), mode="dialog"), # Without subscriptions.baseUrl there is only a file path, with a hint after it: nothing to encode or copy. Action("U", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"), Action("C", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["user"]], when=_sub_url, mode="copy"), Action("J", "client's outbound JSON", lambda r, *_: _link(r, "--json"), when=lambda r: not _amneziawg(r), mode="dialog"), Action("k", "client config", lambda r, *_: _link(r, "--config"), when=_amneziawg, mode="dialog"), Action("K", "client config as QR", lambda r, *_: _link(r, "--config", "--qr"), when=_amneziawg, mode="dialog"), Action("V", "server's inbound JSON", lambda r, *_: ["inbounds", "link", r["tag"], "--server-json"], when=ROW, mode="dialog"), Action("i", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"), Action("I", "traffic per listener", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"), Action("E", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"), Action("O", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"), Action( "n", "add a listener…", lambda r, v, _: [ "inbounds", "add", v["tag"], v["type"], *_opt("--port", v["port"]), *_opt("--reality", ",".join(v["reality"])), *_opt("--tls", v["tls"]), *_each("--user", v["users"]), *_opt("--via", v["via"]), *_opt("--transport", v["transport"]), *_extra(v["extra"]), ], fields=[ Field("tag", "Tag", "e.g. friends"), Field("type", "Type", "the protocol", fixed=True, choices=_listed(ctl.INBOUND_TYPES)), Field("port", "Port", "one from inbounds.runtime.ports if empty", optional=True, number=True), Field("reality", "REALITY", "the server names it poses as, e.g. www.microsoft.com", optional=True, items=True), Field("tls", "TLS certificate", "one from inbounds.runtime.tlsCertificates", optional=True), Field("users", "Users", "who may connect", optional=True, items=True, choices=_users), Field("via", "Via", "where its traffic exits", optional=True, choices=_outbounds), Field("transport", "Transport", "raw if empty", optional=True, fixed=True, choices=_listed(("raw", "ws", "grpc", "httpupgrade", "xhttp")), advanced=True), Field( "extra", "Other flags", "as on the command line: " + " ".join(f for f in ctl.INBOUND_ADD_FLAGS if f not in ("--port", "--reality", "--tls", "--via", "--transport")), optional=True, advanced=True, ), ], offered=_inbounds_runtime, ), Action("d", "remove it", lambda r, *_: ["inbounds", "rm", r["tag"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime), Action( "b", "edit who is on it…", lambda r, v, _: ["inbounds", "users", "on", r["tag"], *v["users"]], when=ROW, fields=[Field("users", "Users", "who may connect through this listener", optional=True, items=True, choices=_users, current=_listener_users)], offered=_inbounds_runtime, ), ], ), Tab( "inbound-users", "Users", _enabled("INBOUNDS_ENABLED"), [("name", "User"), ("order", "Order"), ("address", "Address"), ("source", "Source"), ("listeners", "Listeners"), ("problems", "Problems")], inbound_user_rows, summary=lambda: ( "Runtime users get generated secrets; a change restarts the inbounds, which drops every connection once." if _inbounds_runtime() else "Users from the configuration. inbounds.runtime would let you add and bind them here." ), actions=[ Action( "n", "add a user…", lambda r, v, _: _user_add_argv(v), fields=[ Field("name", "Name", "e.g. alice"), Field("order", "Order", "its position in links and subscriptions", optional=True, number=True), Field("listeners", "Listeners", "the ones it may connect to", optional=True, items=True, choices=_listeners), ], offered=_inbounds_runtime, ), Action("d", "remove it", lambda r, *_: ["inbounds", "users", "rm", r["name"]], when=_runtime_row, confirm=True, offered=_inbounds_runtime), Action( "e", "set its order…", lambda r, v, _: ["inbounds", "users", "order", r["name"], v["order"]], when=_runtime_row, fields=[Field("order", "Order", "its position in links and subscriptions", number=True)], offered=_inbounds_runtime, ), Action( "b", "edit its listeners…", lambda r, v, _: ["inbounds", "users", "listeners", r["name"], *v["listeners"]], when=ROW, fields=[Field("listeners", "Listeners", "the ones it may connect to", optional=True, items=True, choices=_listeners, current=_user_listeners)], offered=_inbounds_runtime, ), # The user's one subscription, as the inbounds tab has it on each of the user's rows. Action("s", "subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=ROW, mode="dialog"), Action("c", "copy subscription URL", lambda r, *_: ["inbounds", "sub", r["name"]], when=lambda r: _sub_url(r, "name"), mode="copy"), Action("Q", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["name"], "--qr"], when=lambda r: _sub_url(r, "name"), mode="dialog"), Action("i", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"), ], ), Tab( "apps", "Apps", # `apps run` is per user (its uid, systemctl --user): nothing a root session can use. lambda states: not is_root() and _enabled("PER_APP_ROUTING_ENABLED")(states), [("profile", "Profile"), ("route", "Route"), ("via", "Via"), ("source", "Source")], app_rows, actions=[ Action( "n", "add a profile…", lambda r, v, _: ["apps", "add", v["name"], *_opt("--route", v["route"]), *_opt("--via", v["via"])], fields=[ Field("name", "Name", "e.g. game"), Field("route", "Route", "how its apps are routed", optional=True, fixed=True, choices=_listed(ctl.APP_ROUTES)), Field("via", "Via", "the outbound it goes through", optional=True, choices=_app_via), ], ), Action("d", "remove it", lambda r, *_: ["apps", "rm", r["profile"]], when=lambda r: r["source"] == "runtime", confirm=True), Action("space", "run a command through it…", lambda r, v, _: ["apps", "run", r["profile"], "--", *shlex.split(v["command"])], when=ROW, fields=[COMMAND], mode="pause"), Action( "v", "run a command via an outbound…", lambda r, v, _: _via_run_argv(v), fields=[Field("outbound", "Outbound", "e.g. de", choices=lambda _: dict.fromkeys(ctl._via_outbounds(), "")), COMMAND], mode="pause", offered=_via_offered, ), ], ), ] WHERE = Action("w", "How is a domain routed", lambda r, v, _: ["where", v["domain"]], fields=[DOMAIN], mode="dialog") # The share-link schemes scripts/proxy_url_parsers.py parses. http(s) is both an HTTP proxy # and how a subscription is spelled, so for those the tab pasted into decides. PROXY_SCHEMES = ("vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic", "socks5", "socks5h", "socks4", "socks4a") HOST = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(? 1: return None, "Paste one link at a time.", None scheme = text.split("://", 1)[0].lower() if "://" in text else "" if scheme in PROXY_SCHEMES: return [*OUTBOUND_ADD, "-"], "", text if scheme in ("http", "https"): return ([*OUTBOUND_ADD, "-"] if tab_id == "outbounds" else ["proxy", "subs", "add", "-"]), "", text if scheme: return None, f"Nothing takes a {scheme}:// link.", None if HOST.fullmatch(text) and tab_id in HOST_ARGV: return [*HOST_ARGV[tab_id], text], "", None return None, "Not a share link, a subscription URL or a host.", None DEEP_LINK_SCHEME = "proxy-suite" def deep_link_argv(link): """What a proxy-suite://install-config?url=&name=... link runs, as paste_argv. The subscription pages of inbounds.manager offer it on Linux, as clash:// for Clash. Any web page can open one, so the GUI asks first. Only a subscription: the URL on stdin, and proxy-ctl refuses plain http. name is a title, so it is made a tag as proxy-ctl makes one (-2, -3... when taken); without one left, proxy-ctl names it after its host. """ parts = urllib.parse.urlsplit((link or "").strip()) if parts.scheme.lower() != DEEP_LINK_SCHEME or parts.netloc.lower() not in ("install-config", "installconfig"): return None, f"Not a {DEEP_LINK_SCHEME}://install-config link.", None query = urllib.parse.parse_qs(parts.query) url = (query.get("url") or [""])[0].strip() if url.split("://", 1)[0].lower() not in ("http", "https") or len(url.splitlines()) > 1: return None, "The link carries no subscription URL.", None tag = ctl._unique_runtime_tag("subscription", (query.get("name") or [""])[0], "") return ["proxy", "subs", "add", *([tag] if tag else []), "-"], "", url def _awg_paste(tab_id, text): """An AmneziaWG config, on stdin: an outbound where outbounds are, else a global profile.""" outbound = ctl.env("AWG_RUNTIME_OUTBOUNDS") == "1" global_ = ctl.env("AWG_RUNTIME_GLOBAL") == "1" if outbound and (tab_id == "outbounds" or not global_): return [*OUTBOUND_ADD, "-"], "", text if global_: return ["awg", "add", "-"], "", text return None, "AmneziaWG configs cannot be added here: amneziaWg.runtime is off in this configuration.", None def available_tabs(states): return [t.id for t in TABS if _safe(t.available, states, fallback=False)] def applicable(tab, row): return [a for a in tab.actions if offered(a) and (a.when is None or (row is not None and a.when(row)))] def selector_state(tab): """(options, current value) of a tab's selector, or None: without one, or unreadable.""" if tab.selector is None: return None options = _safe(tab.selector.options, fallback=None) if not options: return None return options, _safe(tab.selector.current, fallback=None) def selector_argv(tab, value): """What choosing value runs, or None when it is already the choice or no option.""" state = selector_state(tab) if state is None or value == state[1] or value not in dict(state[0]): return None return tab.selector.argv(value) def selector_line(tab): """The selector as one line of text: "Mode: ● Default … ○ Whitelist …".""" state = selector_state(tab) if state is None: return "" options, current = state return f"{tab.selector.label}: " + " ".join(f"{'●' if v == current else '○'} {label}" for v, label in options) def load_tab(tab, states): """(rows, summary) for a tab: a failed read empties the rows and says why in the summary.""" summary = (_safe(tab.summary, fallback="") or "") if tab.summary else "" try: rows = unique_keys(tab.rows(states)) except (Exception, SystemExit) as e: return [], f"✗ {str(e) or type(e).__name__}" + (f"\n{summary}" if summary else "") if not rows: hints = " ".join(f"{display_key(a.key)}: {short(a.label)}" for a in tab.actions if a.fields and a.when is None and offered(a)) summary = "Nothing here yet." + (f" {hints}" if hints else "") + (f"\n{summary}" if summary else "") return rows, summary def unique_keys(rows): """Rows keyed apart: a table refuses a repeated key, and one refusal would stop the tab updating.""" seen, out = set(), [] for r in rows: key = base = str(r.get("key")) n = 1 while key in seen: n += 1 key = f"{base}#{n}" seen.add(key) out.append(r if key == r.get("key") else {**r, "key": key}) return out def display_key(key): """A key as the front ends show it: N reads shift+n, the way ctrl+r does.""" return f"shift+{key.lower()}" if len(key) == 1 and key.isupper() else key def key_labels(actions): """(key, label) per key: the actions that toggle on one key read as one line, "pin it / unpin it".""" labels = {} for a in actions: labels.setdefault(a.key, []).append(a.label) return [(key, " / ".join(dict.fromkeys(names))) for key, names in labels.items()] def short(label): return label.split(" (")[0].removesuffix("…") LINK = re.compile(r"\b[A-Za-z][A-Za-z0-9+.-]*://[^\s'\"]+") USERINFO = re.compile(r"^([^:]+://)[^/?#]*@") QUERY_VALUE = re.compile(r"([?&][^=&#]*=)[^&#]*") # A path segment that reads as a token: a subscription's (/sub/, proxy-ctl's own # /<32 hex>) is the credential itself. TOKEN_SEGMENT = re.compile(r"(?<=/)[A-Za-z0-9_-]{16,}(?=[/?#]|$)") def _redact_link(link): scheme, _, body = link.partition("://") authority = re.split(r"[/?#]", body, maxsplit=1)[0] # One blob, credentials and all: vmess:// (base64 JSON), vpn:// (AmneziaWG's whole config, # private key and all), ss://base64(method:password@host:port), ssr://. Its server stays. if scheme.lower() == "vmess" or ("@" not in authority and ":" not in authority and scheme.lower() not in ("http", "https")): server = _blob_server(scheme.lower(), body) return f"{scheme}://***" + (f"@{server}" if server else "") link = QUERY_VALUE.sub(r"\1***", USERINFO.sub(r"\1***@", link)) head, sep, rest = link.partition("://") host, slash, path = rest.partition("/") return head + sep + host + TOKEN_SEGMENT.sub("***", slash + path) if slash else link SERVER = re.compile(r"[A-Za-z0-9.-]+(:\d+)?|\[[0-9A-Fa-f:.]+\](:\d+)?") def _blob_server(scheme, body): """host:port inside a vmess://, ss:// or vpn:// blob; "" when it cannot be read.""" body = re.split(r"[?#]", body, maxsplit=1)[0].strip() try: raw = base64.urlsafe_b64decode(body.replace("+", "-").replace("/", "_") + "=" * (-len(body) % 4)) if scheme == "vmess": data = json.loads(raw) host, port = str(data.get("add") or ""), str(data.get("port") or "") server = (f"[{host}]" if ":" in host else host) + (f":{port}" if port else "") elif scheme == "ss": _, at, server = raw.decode().rpartition("@") server = server if at else "" elif scheme == "vpn": # 4 bytes of length, then zlib'd JSON whose config text names the peer. match = re.search(r"Endpoint\s*=\s*([^\s\\\"]+)", zlib.decompress(raw[4:]).decode()) server = match.group(1) if match else "" else: return "" except (ValueError, AttributeError, zlib.error): return "" return server if SERVER.fullmatch(server) else "" def redact(text): """text with the credentials in its links blanked: the userinfo (vless://@, ss://@), the query's values (?token=…), token-like path segments, and links that are one opaque blob (vpn://, vmess://). Links go on stdin; this is for any that still reach argv.""" return LINK.sub(lambda m: _redact_link(m.group()), text) def shown(argv, via=None, stdin=None): """The command line a toast, a dialog title or a notification shows for argv; with stdin, what goes on it too, so a confirmation shows what it would add.""" line = f"{via + ' ' if via else ''}proxy-ctl {shlex.join(argv)}" if stdin is not None: if stdin.startswith("{"): fed = "" elif "\n" in stdin or not LINK.fullmatch(stdin): fed = "" # an AmneziaWG .conf: keys throughout else: fed = stdin line += f" < {fed}" return redact(line) def _capture(argv): try: p = subprocess.run([CTL, *argv], capture_output=True, text=True, stdin=subprocess.DEVNULL) except OSError as e: return f"cannot run proxy-ctl: {e}" return p.stdout + p.stderr def elevated(argv, via): """proxy-ctl argv run as root through via (sudo, pkexec): by its full path, which pkexec matches (after realpath) against the one proxy-suite's polkit action names.""" return [via, shutil.which(CTL) or CTL, *argv] def load_tab_as_root(tab, via): """load_tab in proxy-ctl run through via (pkexec): (rows, summary), or None and why it did not run.""" try: p = subprocess.run(elevated(["status", "--tab", tab.id], via), capture_output=True, text=True, stdin=subprocess.DEVNULL) except OSError as e: return None, f"cannot run {via}: {e}" if p.returncode in (126, 127) and not p.stdout and not p.stderr.strip(): return None, "authentication cancelled" # pkexec: dismissed, or not allowed try: rows, summary = json.loads(p.stdout) return rows, summary except ValueError: return None, (p.stderr.strip().splitlines() or [f"exit status {p.returncode}"])[-1] # What this GUI's and TUI's own wrappers set (pkgs/proxy-ctl.nix: PYTHONPATH, wrapGAppsHook4's # GTK paths): an app started with `apps run` would inherit them, and another nixpkgs' GTK or # Python app breaks on modules of this one's. WRAPPER_ENV = ("PYTHONPATH", "GI_TYPELIB_PATH", "GIO_EXTRA_MODULES", "GDK_PIXBUF_MODULE_FILE") def app_env(): return {k: v for k, v in os.environ.items() if k not in WRAPPER_ENV} def popen(argv, root=None, stdin=None): """proxy-ctl with its output streamed: its own process group, so stop() takes down what it spawned too. root: "pkexec" to run it as root, asking through the desktop's polkit agent. stdin: text for it to read (argv then says "-"), kept out of argv, ps and sudo's log.""" p = subprocess.Popen( elevated(argv, root) if root else [CTL, *argv], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.DEVNULL if stdin is None else subprocess.PIPE, text=True, errors="replace", start_new_session=True, env=app_env() if argv[:1] in (["apps"], ["wrap"]) else None, ) feed(p, stdin) return p def feed(p, stdin): """Hands a started process its stdin text, and closes it.""" if stdin is None: return try: p.stdin.write(stdin) p.stdin.close() except (BrokenPipeError, OSError): pass # it exited first: its output says why def output_lines(p, poll=0.2): """p's output, line by line, until EOF or soon after stop(p) even when nothing comes. Then the pipe is closed: a root process (pkexec) takes no signal of ours, and `journalctl -f` exits once its stdout is gone, the rest at their next write.""" fd, pending = p.stdout.fileno(), b"" while not getattr(p, "proxy_suite_stopped", False): if not select.select([fd], [], [], poll)[0]: continue chunk = os.read(fd, 65536) if not chunk: if pending.rstrip(b"\r"): yield pending.rstrip(b"\r").decode("utf-8", "replace") return # Lines as text mode splits them (\r too); a final \r waits for a \n that may follow. data = pending + chunk *done, pending = re.split(rb"\r\n|\r(?!$)|\n", data) yield from (line.decode("utf-8", "replace") for line in done) p.stdout.close() def stop(proc): if proc and proc.poll() is None: proc.proxy_suite_stopped = True # for output_lines try: os.killpg(proc.pid, signal.SIGTERM) except OSError: try: proc.terminate() except OSError: pass # running as root: not ours to signal def _safe(fn, *args, fallback=None): try: return fn(*args) except (Exception, SystemExit): return fallback # Unreadable state: shown empty; a tab's own rows say why in its summary. def _read_states(): return _safe(unit_states, _safe(all_units, fallback=list(ctl.ALL_SERVICES)), fallback={}) # --- tray menu ---------------------------------------------------------------- @dataclass class MenuItem: id: str label: str = "" kind: str = "normal" # normal, check, radio, separator, submenu checked: bool = False enabled: bool = True argv: list = None # proxy-ctl argv to run when clicked app: str = "" # or an app action: open, quit confirm: bool = False children: list = field(default_factory=list) def _sep(n): return MenuItem(f"sep-{n}", kind="separator") def tray_menu(snap, outbounds=None): """The tray's menu for a status snapshot (None: unreadable). outbounds: (tags, pinned) or None.""" overall = ctl._overall_state(snap) items = [MenuItem("status", overall["label"] + (f" — {len(snap['failed'])} failed" if snap and snap["failed"] else ""), enabled=False)] items.append(MenuItem("open", "Open Proxy Suite", app="open")) if snap is None: return items + [_sep(0), MenuItem("quit", "Quit", app="quit")] items.append(_sep(1)) if snap["proxy"]["available"]: active = snap["proxy"]["active"] items.append(MenuItem("proxy", "Proxy", kind="check", checked=active, argv=["proxy", "off" if active else "on"], confirm=active)) if snap["route_mode"]["available"]: current = snap["route_mode"]["current"] items.append( MenuItem( "mode", f"Routing: {ctl._route_mode_label(current)}", kind="submenu", children=[ MenuItem(f"mode-{m}", label, kind="radio", checked=m == current, argv=["proxy", "mode", m]) for m, label in route_mode_options() ], ) ) if outbounds and outbounds[0]: tags, pinned = outbounds items.append( MenuItem( "pin", f"Outbound: {pinned or 'auto'}", kind="submenu", children=[ MenuItem("pin-auto", "Automatic (unpin)", kind="radio", checked=not pinned, argv=["proxy", "unpin"]), _sep(2), *(MenuItem(f"pin-{t}", t, kind="radio", checked=t == pinned, argv=["proxy", "pin", t]) for t in tags), ], ) ) traffic = [] for name, label in (("tun", "TUN mode"), ("tproxy", "TProxy mode")): if snap[name]["available"]: active = snap[name]["active"] traffic.append(MenuItem(name, label, kind="check", checked=active, argv=["proxy", name, "off" if active else "on"])) # Available with none added yet: nothing to pick until `awg add`. if snap["awg"]["available"] and snap["awg"]["profiles"]: current = snap["awg"]["active"] traffic.append( MenuItem( "awg", f"AmneziaWG: {current or 'off'}", kind="submenu", children=[ MenuItem("awg-off", "Off", kind="radio", checked=not current, argv=["awg", "off"]), *(MenuItem(f"awg-{p}", p, kind="radio", checked=p == current, argv=["awg", "on", p]) for p in snap["awg"]["profiles"]), ], ) ) if traffic: items += [_sep(3), *traffic] if snap["zapret"]["available"]: active = snap["zapret"]["active"] items += [_sep(4), MenuItem("zapret", "zapret (DPI bypass)", kind="check", checked=active, argv=["zapret", "off" if active else "on"])] items.append(_sep(5)) if snap["subscription_update"]["available"]: busy = snap["subscription_update"]["state"] in ctl.BUSY_STATES items.append(MenuItem("subs", "Updating subscriptions…" if busy else "Update subscriptions", enabled=not busy, argv=["proxy", "subs", "update"])) items.append(MenuItem("restart", "Restart active services", argv=["restart"], confirm=True)) items += [_sep(6), MenuItem("quit", "Quit", app="quit")] return items def tray_outbounds(snap): """(tags, pinned) for the tray's pin submenu, when the proxy runs.""" if not snap or not snap["proxy"]["active"]: return None inventory = _safe(ctl._outbound_inventory, fallback={}) or {} disabled = {ctl._s(t) for t in inventory.get("disabled") or []} return [ctl._s(t) for t in inventory.get("tags") or [] if ctl._s(t) not in disabled], ctl._s(inventory.get("pinned") or "") def icon_name(overall): return "proxy-suite-" + overall["base"] + (f"-{overall['badge']}" if overall["badge"] else "")