feat: allow using suite on non-nixos systems

This commit is contained in:
FUFSoB committed 2026-09-17 13:27:08 +05:00
1 parent e852bef400
commit 3b568bb54e
63 files changed
+3572 -523

No files matched your search

+60 -19
View File
@@ -165,8 +165,29 @@ def readable(path):
return bool(path) and os.access(path, os.R_OK)
def privileged():
"""Whether the services run as root: off on rootless hosts (home-manager, nix-on-droid)."""
return env("PRIVILEGED", "1") == "1"
def service_manager():
"""What runs the units: systemd, systemd-user (home-manager), or supervisor (nix-on-droid)."""
return env("SERVICE_MANAGER", "systemd")
def state_dir():
return env("STATE_DIR", "/var/lib/proxy-suite")
def runtime_dir():
"""The parent of the units' runtime directories (proxy-suite-socks, ...)."""
return env("RUNTIME_DIR", "/run")
def ask_group():
"""What lets a refused user in: root, or userControl's group with the scope for it."""
if not privileged():
return "check its owner and permissions"
return f"join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo"
@@ -212,8 +233,28 @@ def _exec(argv):
die(f"proxy-ctl: {argv[0]}: {e.strerror}", 126 if isinstance(e, PermissionError) else 127)
def _manager_argv(tool, args):
"""tool (systemctl, journalctl) with args, aimed at the manager that runs the units.
Under systemd-user every unit is a user unit, so a --user of the caller's is redundant.
Without systemd (nix-on-droid), proxy-suitectl answers both.
"""
if service_manager() == "systemd-user":
return [tool, "--user", *(a for a in args if a != "--user")]
if service_manager() == "supervisor":
ctl = env("SUPERVISOR_CTL", "proxy-suitectl")
rest = [a for a in args if a != "--user"]
return [ctl, "journal", *rest] if tool == "journalctl" else [ctl, *rest]
return [tool, *args]
def systemctl(*args, capture=False, quiet=False):
return _run(["systemctl", *args], capture=capture, quiet=quiet)
return _run(_manager_argv("systemctl", args), capture=capture, quiet=quiet)
def journal_hint(unit, count=None):
"""The command that shows unit's log, for messages."""
return " ".join(_manager_argv("journalctl", ["-u", unit, *(["-n", str(count)] if count else [])]))
def must(*args):
@@ -522,7 +563,7 @@ def _unit_states(units):
"""unit -> ActiveState for the units that exist, in one systemctl call."""
if not units:
return {}
_, out = _run(["systemctl", "show", "--property=Id,LoadState,ActiveState", "--", *units], capture=True, quiet=True)
_, out = systemctl("show", "--property=Id,LoadState,ActiveState", "--", *units, capture=True, quiet=True)
states = {}
for unit, block in zip(units, out.strip().split("\n\n")):
props = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)
@@ -874,7 +915,7 @@ TEST_DOWNLOAD_SECONDS = 10
def _runtime_file(name):
return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", "/run/proxy-suite-socks/outbounds.json")), name)
return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", f"{runtime_dir()}/proxy-suite-socks/outbounds.json")), name)
def _test_ping(endpoint, timeout=3):
@@ -1156,8 +1197,8 @@ def cmd_unpin(*_):
def _runtime_dir(kind):
if kind == "outbound":
return env("RUNTIME_OUTBOUNDS_DIR", "/var/lib/proxy-suite/outbounds.d")
return env("RUNTIME_SUBS_DIR", "/var/lib/proxy-suite/subscriptions.d")
return env("RUNTIME_OUTBOUNDS_DIR", f"{state_dir()}/outbounds.d")
return env("RUNTIME_SUBS_DIR", f"{state_dir()}/subscriptions.d")
def _runtime_hidden(kind):
@@ -1275,7 +1316,7 @@ def _runtime_reload():
def _subscription_cache(tag):
return os.path.join(env("SUB_CACHE_DIR", "/var/lib/proxy-suite/subscriptions"), f"{tag}.json")
return os.path.join(env("SUB_CACHE_DIR", f"{state_dir()}/subscriptions"), f"{tag}.json")
def _runtime_entry_verify(kind, tag):
@@ -1413,7 +1454,7 @@ def _probe_paths():
def _probe_exits_file():
return env("PROBE_EXITS_FILE", "/run/proxy-suite-socks/probe-exits.json")
return env("PROBE_EXITS_FILE", f"{runtime_dir()}/proxy-suite-socks/probe-exits.json")
def _probe_site(url):
@@ -1756,7 +1797,7 @@ def _reputation_by_tag():
def _autoproxy_dir():
return env("AUTOPROXY_STATE_DIR", "/var/lib/proxy-suite/autoproxy")
return env("AUTOPROXY_STATE_DIR", f"{state_dir()}/autoproxy")
def _require_autoproxy():
@@ -1924,10 +1965,10 @@ def cmd_proxy_learn(host="", *_):
if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]:
sys.stdout.flush()
print(f"The probe run failed. {host} is still queued and will be tried again at the next run.", file=sys.stderr)
die("Details: journalctl -u proxy-suite-autoproxy-learn -n 20")
die(f"Details: {journal_hint('proxy-suite-autoproxy-learn', 20)}")
h = (_autoproxy_state(path).get("hosts") or {}).get(host)
if h is None:
print("No verdict recorded; see: journalctl -u proxy-suite-autoproxy-learn")
print(f"No verdict recorded; see: {journal_hint('proxy-suite-autoproxy-learn')}")
elif h.get("exit"):
print(f"{_s(h.get('domain'))}: {_s(h.get('verdict'))} - routed via {_s(h['exit'])} from now on, no restart needed")
else:
@@ -1947,7 +1988,7 @@ def cmd_zapret(*args):
def _zapret_state_dir():
return env("ZAPRET_STATE_DIR", "/var/lib/proxy-suite/zapret2")
return env("ZAPRET_STATE_DIR", f"{state_dir()}/zapret2")
def _zapret_auto_file(name):
@@ -2074,7 +2115,7 @@ def cmd_zapret_cutoff(verb="status", *_):
denied(path, "write")
print("Probing this line; this takes a few minutes...")
if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]:
die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30")
die(f"The probe failed. Details: {journal_hint('proxy-suite-zapret2-cutoff', 30)}")
elif verb != "status":
usage("zapret cutoff [status|probe]")
@@ -2253,7 +2294,7 @@ def cmd_where(domain="", *_):
local = " and ".join(sorted(live))
if env("INBOUNDS_ENABLED") == "1":
inbounds_path = "/run/proxy-suite-inbounds/config.json"
inbounds_path = f"{runtime_dir()}/proxy-suite-inbounds/config.json"
if not readable(inbounds_path):
_where_row("inbounds", f"routing is not readable - {ask_group()}")
else:
@@ -2474,7 +2515,7 @@ def _inbound_links():
def _inbound_server_json(tag):
"""The XRay inbound as the server runs it, secrets and all."""
path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", "/run/proxy-suite-inbounds/links.json")), "config.json")
path = os.path.join(os.path.dirname(env("INBOUNDS_LINKS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/links.json")), "config.json")
if not os.path.isfile(path):
die("No inbound config yet - is proxy-suite-inbounds running?")
if not readable(path):
@@ -2530,7 +2571,7 @@ def _inbound_stats(*args):
days = rest.pop(0)
if rest or kind not in STATS_KINDS or not re.fullmatch(r"[1-9][0-9]*", days):
usage("inbounds stats [days] [--by user|inbound|outbound]")
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
# Collect what XRay counted since the last run first; root and userControl
# members may, anyone else reads what the timer last wrote.
systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True)
@@ -2581,7 +2622,7 @@ def _inbound_presence():
except (ValueError, AttributeError):
die("Unexpected answer from the inbounds' stats API.")
# As the timer last wrote it: the API already told who is online now.
path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json")
path = env("INBOUNDS_STATS_FILE", f"{state_dir()}/inbound-stats.json")
seen = (read_json(path).get("seen") or {}) if readable(path) else {}
# Users nobody has seen yet, when the links say who exists.
path = env("INBOUNDS_LINKS_FILE")
@@ -2626,7 +2667,7 @@ def _inbound_subscriptions(*args):
qr = True
else:
user = arg
path = env("INBOUNDS_SUBS_FILE", "/run/proxy-suite-inbounds/subscriptions.json")
path = env("INBOUNDS_SUBS_FILE", f"{runtime_dir()}/proxy-suite-inbounds/subscriptions.json")
base = env("INBOUNDS_SUB_BASE_URL")
if not os.path.isfile(path):
die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?")
@@ -2699,9 +2740,9 @@ ALIASES = {
def cmd_logs(*units):
if units:
# One -u per unit: a bare second name would be taken as a journal match.
_exec(["journalctl", "-f", *(f"--unit={u}" for u in units)])
_exec(_manager_argv("journalctl", ["-f", *(f"--unit={u}" for u in units)]))
# journalctl takes unit globs, so the default needs no unit list of its own.
_exec(["journalctl", "-f", "-u", "proxy-suite-*"])
_exec(_manager_argv("journalctl", ["-f", "-u", "proxy-suite-*"]))
COMMANDS = {
+1
View File
@@ -1044,6 +1044,7 @@ class ProxySuiteGui(Adw.Application):
action.connect("activate", callback)
self.add_action(action)
elevated = Gio.SimpleAction.new_stateful("elevated", None, GLib.Variant.new_boolean(False))
elevated.set_enabled(ctl.privileged())
elevated.connect("change-state", self.on_elevated)
self.add_action(elevated)
retry = Gio.SimpleAction.new("retry-root", GLib.VariantType.new("as"))
+6 -1
View File
@@ -94,9 +94,14 @@ 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 not is_root() and any(ROOT_HINT.search(line) for line in out)
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": "◐"}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -558,7 +558,7 @@ class ProxyTui(App):
def check_action(self, action, parameters):
if action in ("retry_root", "switch_root"):
return not model.is_root()
return model.can_elevate()
# A row action that does not apply: its key does nothing.
if action != "act" or self.screen is not self.main:
return True
+46
View File
@@ -291,6 +291,52 @@ class ProbeWalkTest(EnvTest):
self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out)
class ServiceManagerTest(EnvTest):
def calls(self):
seen = []
self.patch("_run", lambda argv, **kw: seen.append(argv) or (0, ""))
return seen
def test_system_units(self):
seen = self.calls()
ctl.systemctl("--user", "start", "anchor.service")
ctl.systemctl("start", "proxy-suite-socks")
self.assertEqual(seen, [["systemctl", "--user", "start", "anchor.service"], ["systemctl", "start", "proxy-suite-socks"]])
self.assertEqual(ctl.journal_hint("proxy-suite-autoproxy-learn", 20), "journalctl -u proxy-suite-autoproxy-learn -n 20")
def test_user_units(self):
# home-manager: every unit is the user's, and a --user of the caller's is not doubled.
os.environ["SERVICE_MANAGER"] = "systemd-user"
seen = self.calls()
ctl.systemctl("--user", "stop", "anchor.service")
ctl._unit_states(["proxy-suite-socks"])
self.assertEqual(seen[0], ["systemctl", "--user", "stop", "anchor.service"])
self.assertEqual(seen[1][:3], ["systemctl", "--user", "show"])
self.assertEqual(ctl.journal_hint("proxy-suite-socks"), "journalctl --user -u proxy-suite-socks")
def test_supervisor_units(self):
# nix-on-droid: proxy-suitectl stands in for systemctl and journalctl.
os.environ.update(SERVICE_MANAGER="supervisor", SUPERVISOR_CTL="/bin/proxy-suitectl")
seen = self.calls()
ctl.systemctl("--user", "stop", "anchor.service")
ctl._unit_states(["proxy-suite-socks"])
self.assertEqual(seen[0], ["/bin/proxy-suitectl", "stop", "anchor.service"])
self.assertEqual(seen[1][:2], ["/bin/proxy-suitectl", "show"])
self.assertEqual(ctl.journal_hint("proxy-suite-socks", 5), "/bin/proxy-suitectl journal -u proxy-suite-socks -n 5")
def test_paths_follow_host_dirs(self):
for name in ("SUB_CACHE_DIR", "AUTOPROXY_STATE_DIR", "INBOUNDS_STATS_FILE", "OUTBOUND_INVENTORY_FILE"):
os.environ.pop(name, None)
os.environ.update(STATE_DIR="/home/u/.local/state/proxy-suite", RUNTIME_DIR="/tmp/ps")
self.assertEqual(ctl._autoproxy_dir(), "/home/u/.local/state/proxy-suite/autoproxy")
self.assertEqual(os.path.dirname(ctl._subscription_cache("x")), "/home/u/.local/state/proxy-suite/subscriptions")
def test_rootless_hosts_never_ask_for_root(self):
self.assertIn("sudo", ctl.ask_group())
os.environ["PRIVILEGED"] = "0"
self.assertNotIn("sudo", ctl.ask_group())
class AutoProxyTest(EnvTest):
def setUp(self):
super().setUp()
+172
View File
@@ -0,0 +1,172 @@
import json
import os
import shutil
import subprocess
import sys
import tempfile
import time
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
SUPERVISOR = os.path.join(HERE, "proxy_supervisor.py")
def wait_for(predicate, timeout=10):
deadline = time.time() + timeout
while time.time() < deadline:
value = predicate()
if value:
return value
time.sleep(0.05)
raise AssertionError("timed out")
class SupervisorTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.mkdtemp(prefix="proxy-supervisor-")
self.run_dir = os.path.join(self.tmp, "run")
self.manifest = os.path.join(self.tmp, "manifest.json")
self.env = dict(
os.environ,
# Deeper than a socket address holds.
PROXY_SUITE_SUPERVISOR_DIR=os.path.join(self.tmp, "x" * 100, "supervisor"),
PROXY_SUITE_MANIFEST=self.manifest,
HOME=self.tmp,
)
self.write_manifest()
def tearDown(self):
subprocess.run([sys.executable, SUPERVISOR, "shutdown"], env=self.env, capture_output=True)
# The daemon removes its socket once every unit is down.
try:
wait_for(lambda: not self.daemon_running(), timeout=30)
finally:
shutil.rmtree(self.tmp, ignore_errors=True)
def daemon_running(self):
return os.path.exists(os.path.join(self.env["PROXY_SUITE_SUPERVISOR_DIR"], "control.sock"))
def write_manifest(self, crash_times=1, marker="one"):
out = os.path.join(self.tmp, "out")
sh = lambda text: ["/bin/sh -c " + json.dumps(text)]
manifest = {
"services": {
# Fails the first crash_times starts, then stays up.
"proxy-suite-counter": {
"Unit": {"Description": "counter"},
"Service": {
"Type": "simple",
"Restart": "on-failure",
"RestartSec": "100ms",
"Environment": [json.dumps(f"MARKER={marker}")],
"ExecStartPre": [f'/bin/sh -c "mkdir -p {out}"'],
"ExecStart": sh(
f'n=$(cat {out}/starts 2>/dev/null || echo 0); n=$((n+1)); echo $n > {out}/starts; '
f'echo "start $n $MARKER"; [ $n -gt {crash_times} ] || exit 3; exec sleep 1000'
),
"ExecStopPost": sh(f"echo stopped >> {out}/stops"),
},
"Install": {"WantedBy": ["default.target"]},
},
"proxy-suite-once": {
"Unit": {"Description": "oneshot", "After": ["proxy-suite-counter.service"]},
"Service": {
"Type": "oneshot",
"RemainAfterExit": True,
"ExecStart": sh(f"echo ran >> {out}/once"),
},
"Install": {"WantedBy": ["default.target"]},
},
"proxy-suite-tick": {
"Unit": {"Description": "timer job"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo tick >> {out}/ticks")},
},
"proxy-suite-pin@": {
"Unit": {"Description": "template"},
"Service": {"Type": "oneshot", "ExecStart": sh(f"echo '%I' >> {out}/pins")},
},
},
"timers": {
"proxy-suite-tick": {
"Unit": {"Description": "tick"},
"Timer": {"OnActiveSec": "1s", "OnUnitActiveSec": "1s"},
"Install": {"WantedBy": ["timers.target"]},
},
},
"paths": {},
"tmpfiles": [f"d {self.run_dir} 0700 - - -"],
}
with open(self.manifest + ".tmp", "w") as f:
json.dump(manifest, f)
os.replace(self.manifest + ".tmp", self.manifest)
def ctl(self, *args):
p = subprocess.run([sys.executable, SUPERVISOR, *args], env=self.env, capture_output=True, text=True, timeout=60)
return p.returncode, p.stdout
def read(self, name):
try:
with open(os.path.join(self.tmp, "out", name)) as f:
return f.read().split()
except FileNotFoundError:
return []
def test_without_daemon(self):
self.assertEqual(self.ctl("is-active", "--quiet", "proxy-suite-counter"), (3, ""))
status, out = self.ctl("show", "--property=Id,LoadState,ActiveState", "--", "proxy-suite-counter", "nope")
self.assertEqual(status, 0)
self.assertEqual(
out.split("\n\n"),
["Id=proxy-suite-counter.service\nLoadState=loaded\nActiveState=inactive", "Id=nope.service\nLoadState=not-found\nActiveState=inactive\n"],
)
self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0)
self.assertFalse(self.daemon_running())
def test_boot_restart_timers_and_stop(self):
self.assertEqual(self.ctl("boot")[0], 0)
self.assertTrue(os.path.isdir(self.run_dir))
# Crashed once, restarted, then up.
wait_for(lambda: self.ctl("show", "-p", "SubState", "--value", "proxy-suite-counter")[1].strip() == "running")
self.assertEqual(self.read("starts"), ["2"])
self.assertEqual(self.read("stops"), ["stopped"])
self.assertEqual(self.read("once"), ["ran"])
self.assertEqual(self.ctl("is-active", "proxy-suite-once"), (0, "active\n"))
status, out = self.ctl("list-timers", "-o", "json", "proxy-suite-tick.timer")
timers = json.loads(out)
self.assertEqual([t["activates"] for t in timers], ["proxy-suite-tick.service"])
self.assertGreater(timers[0]["next"], (time.time() - 5) * 1e6)
wait_for(lambda: len(self.read("ticks")) >= 2)
# Template instances get %I unescaped.
self.assertEqual(self.ctl("start", "proxy-suite-pin@de\\x2dfra.service")[0], 0)
self.assertEqual(self.read("pins"), ["de-fra"])
status, out = self.ctl("journal", "-u", "proxy-suite-count*", "-o", "cat", "--since", "-1h", "--no-pager")
self.assertEqual([l for l in out.splitlines() if l.startswith("start")][:2], ["start 1 one", "start 2 one"])
self.assertIn("proxy-suitectl: exited with status 3; restarting", out)
self.assertEqual(self.ctl("journal", "-u", "proxy-suite-counter", "-n", "1", "-o", "cat")[1], "start 2 one\n")
self.assertEqual(self.ctl("stop", "proxy-suite-counter")[0], 0)
self.assertEqual(self.ctl("is-active", "proxy-suite-counter"), (3, "inactive\n"))
self.assertEqual(self.read("stops"), ["stopped", "stopped"])
# try-restart leaves a stopped unit stopped.
self.assertEqual(self.ctl("try-restart", "proxy-suite-counter")[0], 0)
self.assertEqual(self.ctl("is-active", "proxy-suite-counter")[0], 3)
def test_boot_again_restarts_changed_units(self):
self.write_manifest(crash_times=0)
self.ctl("boot")
wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0)
pid = self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip()
self.write_manifest(crash_times=0, marker="two")
self.assertEqual(self.ctl("boot")[0], 0)
wait_for(lambda: self.ctl("is-active", "proxy-suite-counter")[0] == 0)
self.assertNotEqual(self.ctl("show", "-p", "MainPID", "--value", "proxy-suite-counter")[1].strip(), pid)
self.assertIn("start 2 two", self.ctl("journal", "-u", "proxy-suite-counter", "-o", "cat")[1])
# The unchanged oneshot is not run again.
self.assertEqual(self.read("once"), ["ran"])
if __name__ == "__main__":
unittest.main()