fix: multiple fixes
This commit is contained in:
23 files changed
+940
-96
No files matched your search
@@ -0,0 +1,21 @@
|
||||
//go:build linux
|
||||
|
||||
package tun
|
||||
|
||||
import "golang.org/x/sys/unix"
|
||||
|
||||
// netlinkGroupsBanned reports whether this process may not join NETLINK_ROUTE's
|
||||
// multicast groups, which the monitor subscribes to. Android's SELinux policy lets an
|
||||
// app open the socket but not join them; sing-tun only checks on GOOS=android, and
|
||||
// nix-on-droid runs linux binaries.
|
||||
func netlinkGroupsBanned() bool {
|
||||
fd, err := unix.Socket(unix.AF_NETLINK, unix.SOCK_RAW|unix.SOCK_CLOEXEC, unix.NETLINK_ROUTE)
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
defer unix.Close(fd)
|
||||
return unix.Bind(fd, &unix.SockaddrNetlink{
|
||||
Family: unix.AF_NETLINK,
|
||||
Groups: unix.RTMGRP_LINK | unix.RTMGRP_IPV4_IFADDR | unix.RTMGRP_IPV6_IFADDR | unix.RTMGRP_IPV4_ROUTE | unix.RTMGRP_IPV6_ROUTE,
|
||||
}) != nil
|
||||
}
|
||||
+274
-32
@@ -3,6 +3,7 @@
|
||||
Configuration arrives through the environment the Nix wrapper sets.
|
||||
"""
|
||||
|
||||
import base64
|
||||
import datetime
|
||||
import http.client
|
||||
import importlib
|
||||
@@ -55,10 +56,13 @@ Secrets and changes need root, or the userControl group.
|
||||
|
||||
proxy [status|on|off] local proxy backend
|
||||
proxy outbounds [list] outbounds, where each came from, and the pick
|
||||
proxy outbounds add <tag> <url|json|-> [--detour <tag>]
|
||||
proxy outbounds add [tag] <url|json|-> [--detour <tag>]
|
||||
add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin),
|
||||
chained through another outbound with --detour
|
||||
chained through another outbound with --detour; the tag first,
|
||||
or left out to name it after the link
|
||||
proxy outbounds rm <tag> remove a runtime outbound
|
||||
proxy outbounds disable|enable <tag> keep an outbound out of automatic use (selection, autoProxy, pins),
|
||||
or let it back in; declared ones too
|
||||
proxy outbounds test [tag...] [--ping] [--delay] [--download]
|
||||
TCP ping, real delay, download speed (default: ping, delay)
|
||||
proxy outbounds link <tag> [--qr|--json|--config]
|
||||
@@ -68,7 +72,7 @@ Secrets and changes need root, or the userControl group.
|
||||
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
|
||||
show or override the routing mode
|
||||
proxy subs [list|update] subscription caches; update refetches them
|
||||
proxy subs add <tag> <url> add a subscription at runtime
|
||||
proxy subs add [tag] <url> add a subscription at runtime; no tag: named after its host
|
||||
proxy subs rm <tag> remove a runtime subscription
|
||||
proxy subs link <tag> [--qr] its URL
|
||||
proxy config [--raw] client config to import elsewhere; --raw: as running
|
||||
@@ -78,6 +82,9 @@ Secrets and changes need root, or the userControl group.
|
||||
proxy auto probe <domain>[/path] [--json] [--keep-going] [--exits a,b | --via tag]
|
||||
find an exit that reaches a domain
|
||||
proxy auto learn <domain> probe now and route it if an exit works
|
||||
proxy auto forget <domain> drop what was learned about it: direct until learned again
|
||||
proxy auto relearn <domain> forget it, then probe the host it was learned from now
|
||||
proxy auto clear forget every learned route and verdict
|
||||
proxy auto queue [count] destinations waiting to be probed
|
||||
|
||||
zapret [status|on|off] DPI bypass
|
||||
@@ -399,8 +406,10 @@ COMPLETE = {
|
||||
"proxy outbounds": {
|
||||
"words": {
|
||||
"list": "outbounds, where each came from, and the pick",
|
||||
"add": "add an outbound at runtime: a URL or JSON",
|
||||
"add": "add an outbound at runtime: [tag] <url or JSON>",
|
||||
"rm": "remove a runtime outbound",
|
||||
"disable": "keep it out of automatic use",
|
||||
"enable": "let a disabled outbound back in",
|
||||
"test": "TCP ping, real delay, download speed",
|
||||
"link": "its URL, QR code, JSON or client config",
|
||||
}
|
||||
@@ -411,6 +420,8 @@ COMPLETE = {
|
||||
"flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"},
|
||||
},
|
||||
"proxy outbounds rm": {"args": lambda: _names(_runtime_tags("outbound"))},
|
||||
"proxy outbounds disable": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}},
|
||||
"proxy outbounds enable": {"args": lambda: _names(_outbound_disabled())},
|
||||
"proxy outbounds test": {
|
||||
"args": _outbound_choices,
|
||||
"repeat": True,
|
||||
@@ -420,13 +431,13 @@ COMPLETE = {
|
||||
"--download": "timed download through each outbound",
|
||||
},
|
||||
},
|
||||
"proxy pin": {"args": _outbound_choices},
|
||||
"proxy pin": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}},
|
||||
"proxy mode": {"args": lambda: {"default": f"config default ({_route_mode_default()})", **ROUTE_MODE_LABELS}},
|
||||
"proxy subs": {
|
||||
"words": {
|
||||
"list": "subscription caches",
|
||||
"update": "refetch the subscriptions",
|
||||
"add": "add a subscription at runtime",
|
||||
"add": "add a subscription at runtime: [tag] <url>",
|
||||
"rm": "remove a runtime subscription",
|
||||
"link": "its URL",
|
||||
}
|
||||
@@ -440,9 +451,14 @@ COMPLETE = {
|
||||
"list": "what autoProxy routed, and via which exit",
|
||||
"probe": "find an exit that reaches a domain",
|
||||
"learn": "probe now and route it if an exit works",
|
||||
"forget": "drop what was learned about a domain",
|
||||
"relearn": "forget a domain, then probe it again now",
|
||||
"clear": "forget every learned route and verdict",
|
||||
"queue": "destinations waiting to be probed",
|
||||
}
|
||||
},
|
||||
"proxy auto forget": {"args": _autoproxy_choices},
|
||||
"proxy auto relearn": {"args": _autoproxy_choices},
|
||||
"proxy auto probe": {
|
||||
"flags": {
|
||||
"--json": "machine-readable result",
|
||||
@@ -819,7 +835,7 @@ def cmd_proxy(verb="status", *args):
|
||||
_toggle("proxy-suite-tproxy", "proxy tproxy", *args)
|
||||
elif verb == "auto":
|
||||
cmd_proxy_auto(*args)
|
||||
elif verb in ("probe", "learn", "queue", "learned"):
|
||||
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
|
||||
cmd_proxy_auto(verb, *args)
|
||||
else:
|
||||
usage("proxy [status|on|off|outbounds|pin|unpin|mode|subs|tun|tproxy|auto|config]")
|
||||
@@ -836,16 +852,20 @@ def cmd_outbounds(verb="list", *args):
|
||||
detour = args[i + 1] if i + 1 < len(args) else ""
|
||||
del args[i : i + 2]
|
||||
if not detour:
|
||||
usage("proxy outbounds add <tag> <url|json|-> [--detour <tag>]")
|
||||
usage("proxy outbounds add [tag] <url|json|-> [--detour <tag>]")
|
||||
_runtime_entry_add("outbound", *args, detour=detour)
|
||||
elif verb in ("rm", "remove", "del"):
|
||||
_runtime_entry_rm("outbound", *args)
|
||||
elif verb == "disable":
|
||||
cmd_outbound_disable(*args)
|
||||
elif verb == "enable":
|
||||
cmd_outbound_enable(*args)
|
||||
elif verb == "test":
|
||||
cmd_outbounds_test(*args)
|
||||
elif verb == "link":
|
||||
_outbound_link(*args)
|
||||
else:
|
||||
usage("proxy outbounds [list|add <tag> <url|json|->|rm <tag>|test [tag...]|link <tag>]")
|
||||
usage("proxy outbounds [list|add [tag] <url|json|->|rm <tag>|disable <tag>|enable <tag>|test [tag...]|link <tag>]")
|
||||
|
||||
|
||||
def _outbound_inventory():
|
||||
@@ -867,6 +887,11 @@ def _outbound_tags():
|
||||
return [_s(t) for t in _outbound_inventory().get("tags") or []]
|
||||
|
||||
|
||||
def _outbound_disabled():
|
||||
"""Disabled outbounds, as the running backend took them."""
|
||||
return [_s(t) for t in _outbound_inventory().get("disabled") or []]
|
||||
|
||||
|
||||
def _require_outbound_inventory():
|
||||
if not _outbound_tags():
|
||||
die("No outbounds are available yet - is proxy-suite-socks running?")
|
||||
@@ -1056,6 +1081,7 @@ def _outbounds_list():
|
||||
sources = inventory.get("sources") or {}
|
||||
detours = inventory.get("detours") or {}
|
||||
excluded = set(inventory.get("excluded") or [])
|
||||
disabled = set(_outbound_disabled())
|
||||
current = _outbound_current()
|
||||
reputation = _reputation_by_tag()
|
||||
|
||||
@@ -1073,7 +1099,10 @@ def _outbounds_list():
|
||||
mark = "*"
|
||||
elif not pinned and tag == current:
|
||||
mark = ">"
|
||||
notes = ([f"via {_s(detours[tag])}"] if tag in detours else []) + (["never picked"] if tag in excluded else [])
|
||||
elif tag in disabled:
|
||||
mark = "-"
|
||||
notes = [f"via {_s(detours[tag])}"] if tag in detours else []
|
||||
notes += ["disabled"] if tag in disabled else ["never picked"] if tag in excluded else []
|
||||
print(f" {mark}{tag:<34} {rep(tag)}{', '.join([_s(sources.get(tag) or '-'), *notes])}")
|
||||
|
||||
|
||||
@@ -1174,12 +1203,14 @@ def cmd_pin(tag="", *_):
|
||||
status, tag = _run(
|
||||
["fzf", "--prompt=pin> ", "--height=40%", "--reverse", f"--header=pinned: {pinned}"],
|
||||
capture=True,
|
||||
stdin="".join(f"{t}\n" for t in _outbound_tags()),
|
||||
stdin="".join(f"{t}\n" for t in _outbound_tags() if t not in _outbound_disabled()),
|
||||
)
|
||||
tag = tag.strip("\n")
|
||||
# Dismissed.
|
||||
if status or not tag:
|
||||
return
|
||||
if os.path.exists(_outbound_disabled_marker(tag)):
|
||||
die(f"Outbound '{tag}' is disabled; enable it first: proxy-ctl proxy outbounds enable {tag}")
|
||||
status, escaped = _run(["systemd-escape", "--", tag], capture=True)
|
||||
if status:
|
||||
sys.exit(status)
|
||||
@@ -1262,16 +1293,92 @@ def _check_runtime_tag(kind, tag):
|
||||
die(f"A subscription named '{tag}' is declared in the configuration.")
|
||||
|
||||
|
||||
def _runtime_entry_add(kind, tag="", url="", *_, detour=""):
|
||||
RUNTIME_TAG_MAX = 32
|
||||
|
||||
|
||||
def _runtime_source(kind, arg):
|
||||
"""Whether an add argument is the entry itself rather than its tag."""
|
||||
return "://" in arg or (kind == "outbound" and (arg == "-" or arg.lstrip().startswith("{")))
|
||||
|
||||
|
||||
def _vmess_name(url):
|
||||
"""The name inside a vmess:// link, whose body is base64 JSON rather than a URL."""
|
||||
body = url.split("://", 1)[1].split("#", 1)[0].strip()
|
||||
try:
|
||||
decoded = json.loads(base64.b64decode(body + "=" * (-len(body) % 4)).decode("utf-8"))
|
||||
except (ValueError, UnicodeDecodeError):
|
||||
return ""
|
||||
return _s(decoded.get("ps") or decoded.get("add") or "") if isinstance(decoded, dict) else ""
|
||||
|
||||
|
||||
def _host_label(host):
|
||||
"""The name a host goes by: sub.provider.com -> provider; an address as it is."""
|
||||
if re.fullmatch(r"[0-9.]+|[0-9a-fA-F:]+", host):
|
||||
return host
|
||||
labels = [label for label in host.split(".") if label]
|
||||
return labels[-2] if len(labels) >= 2 else labels[0] if labels else ""
|
||||
|
||||
|
||||
def _runtime_tag_for(kind, source):
|
||||
"""A tag for an entry added without one: the name the link carries, else where it points.
|
||||
|
||||
Never one already taken: -2, -3... after it.
|
||||
"""
|
||||
text = source.strip()
|
||||
name = ""
|
||||
if text.startswith("{"):
|
||||
try:
|
||||
ob = json.loads(text)
|
||||
except ValueError:
|
||||
ob = None
|
||||
if isinstance(ob, dict):
|
||||
name = _s(ob.get("tag") or ob.get("type") or ob.get("protocol") or "")
|
||||
else:
|
||||
try:
|
||||
parts = urllib.parse.urlsplit(text)
|
||||
host = parts.hostname or ""
|
||||
except ValueError:
|
||||
parts, host = None, ""
|
||||
if parts:
|
||||
name = urllib.parse.unquote(parts.fragment)
|
||||
if not name and parts.scheme.lower() == "vmess":
|
||||
name = _vmess_name(text)
|
||||
if not name and host:
|
||||
label = _host_label(host)
|
||||
name = label if kind == "subscription" else f"{parts.scheme.lower()}-{label}"
|
||||
base = re.sub(r"[^A-Za-z0-9._-]+", "-", name).strip("-._")[:RUNTIME_TAG_MAX].strip("-._")
|
||||
base = base or ("sub" if kind == "subscription" else "outbound")
|
||||
taken = {"proxy", "direct", "block", *_runtime_tags(kind), *(_outbound_tags() if kind == "outbound" else _sub_tags())}
|
||||
tag, n = base, 1
|
||||
while tag in taken:
|
||||
n += 1
|
||||
suffix = f"-{n}"
|
||||
tag = base[: RUNTIME_TAG_MAX - len(suffix)] + suffix
|
||||
return tag
|
||||
|
||||
|
||||
def _runtime_entry_add(kind, *args, detour=""):
|
||||
what = "<url|json|-> [--detour <tag>]" if kind == "outbound" else "<url>"
|
||||
if not tag or not url:
|
||||
usage(f"proxy {_runtime_noun(kind)} add <tag> {what}")
|
||||
_check_runtime_tag(kind, tag)
|
||||
shape = f"proxy {_runtime_noun(kind)} add [tag] {what}"
|
||||
if len(args) == 1 and _runtime_source(kind, args[0]):
|
||||
tag, url = "", args[0]
|
||||
elif len(args) == 2 and _runtime_source(kind, args[0]):
|
||||
die(f"The tag goes first, the {'URL or JSON' if kind == 'outbound' else 'URL'} after it: proxy-ctl {shape}")
|
||||
elif len(args) == 2 and args[1]:
|
||||
tag, url = args
|
||||
else:
|
||||
usage(shape)
|
||||
if tag:
|
||||
_check_runtime_tag(kind, tag)
|
||||
# The start script checks the chain again, and leaves the outbound out if it breaks later.
|
||||
if detour and (detour == tag or detour not in _outbound_tags()):
|
||||
die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds")
|
||||
if kind == "outbound" and url == "-":
|
||||
url = sys.stdin.read()
|
||||
if not tag:
|
||||
tag = _runtime_tag_for(kind, url)
|
||||
_check_runtime_tag(kind, tag)
|
||||
print(f"Tag: {tag} (none given; pass one first to choose it)")
|
||||
ext = ".url"
|
||||
if kind == "outbound" and url.lstrip().startswith("{"):
|
||||
url, ext = _runtime_json_outbound(url), ".json"
|
||||
@@ -1307,8 +1414,10 @@ def _runtime_entry_rm(kind, tag="", *_):
|
||||
die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.")
|
||||
try:
|
||||
os.unlink(path)
|
||||
if kind == "outbound" and os.path.exists(os.path.join(_runtime_dir(kind), f"{tag}.detour")):
|
||||
os.unlink(os.path.join(_runtime_dir(kind), f"{tag}.detour"))
|
||||
# Its hop, and a disable left from it: a new entry of this name would inherit them.
|
||||
for extra in (".detour", ".disabled") if kind == "outbound" else ():
|
||||
if os.path.exists(os.path.join(_runtime_dir(kind), tag + extra)):
|
||||
os.unlink(os.path.join(_runtime_dir(kind), tag + extra))
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError:
|
||||
@@ -1322,6 +1431,71 @@ def _runtime_reload():
|
||||
die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-outbound-reload")
|
||||
|
||||
|
||||
# --- disabled outbounds -------------------------------------------------------
|
||||
#
|
||||
# <tag>.disabled in the runtime outbound dir, for declared outbounds as much as runtime
|
||||
# ones. The outbound stays in the config, so rules and chains naming it still reach
|
||||
# it; selection, autoProxy's probes and pins leave it alone, and autoProxy forgets
|
||||
# the routes it learned through it.
|
||||
|
||||
|
||||
def _outbound_disabled_marker(tag):
|
||||
return os.path.join(_runtime_dir("outbound"), f"{tag}.disabled")
|
||||
|
||||
|
||||
def cmd_outbound_disable(tag="", *_):
|
||||
if not tag:
|
||||
usage("proxy outbounds disable <tag>")
|
||||
_require_outbound_inventory()
|
||||
inventory = _outbound_inventory()
|
||||
if tag not in _outbound_tags():
|
||||
die(f"Unknown outbound: {tag}")
|
||||
marker = _outbound_disabled_marker(tag)
|
||||
if os.path.exists(marker) and tag in _outbound_disabled():
|
||||
print(f"Already disabled: {tag}")
|
||||
return
|
||||
pinned = _s(inventory.get("pinned") or "")
|
||||
excluded = set(inventory.get("excluded") or [])
|
||||
# With none left to pick the proxy would not start, pinned or not: an unpin falls back to selection.
|
||||
if [t for t in _outbound_tags() if t not in excluded] == [tag]:
|
||||
die(f"'{tag}' is the only outbound selection can pick; enable or add another first.")
|
||||
old = os.umask(0o027)
|
||||
try:
|
||||
with open(marker, "w", encoding="utf-8"):
|
||||
pass
|
||||
except OSError:
|
||||
denied(marker, "write")
|
||||
finally:
|
||||
os.umask(old)
|
||||
# The reload drops a pin on it too.
|
||||
_runtime_reload()
|
||||
if tag in _outbound_disabled():
|
||||
print(f"Disabled: {tag} - never picked, pinned or probed; rules and chains naming it still use it.")
|
||||
else:
|
||||
sys.stdout.flush()
|
||||
print(f"Saved, but the running proxy does not list '{tag}' as disabled yet. Check: proxy-ctl logs", file=sys.stderr)
|
||||
|
||||
|
||||
def cmd_outbound_enable(tag="", *_):
|
||||
if not tag:
|
||||
usage("proxy outbounds enable <tag>")
|
||||
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", tag):
|
||||
die(f"Not disabled: {tag}")
|
||||
marker = _outbound_disabled_marker(tag)
|
||||
if not os.path.exists(marker):
|
||||
if tag in _outbound_disabled():
|
||||
die(f"Cannot see the marker for '{tag}' in {_runtime_dir('outbound')} - {ask_group()}")
|
||||
die(f"Not disabled: {tag}")
|
||||
try:
|
||||
os.unlink(marker)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError:
|
||||
denied(marker, "remove")
|
||||
_runtime_reload()
|
||||
print(f"Enabled: {tag} - selection and autoProxy may use it again.")
|
||||
|
||||
|
||||
def _subscription_cache(tag):
|
||||
return os.path.join(env("SUB_CACHE_DIR", f"{state_dir()}/subscriptions"), f"{tag}.json")
|
||||
|
||||
@@ -1420,7 +1594,7 @@ def cmd_subscription(verb="list", *args):
|
||||
must("start", "proxy-suite-subscription-update")
|
||||
print("Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update")
|
||||
else:
|
||||
usage("proxy subs [list|update|add <tag> <url>|rm <tag>|link <tag>]")
|
||||
usage("proxy subs [list|update|add [tag] <url>|rm <tag>|link <tag>]")
|
||||
|
||||
|
||||
# --- proxy auto: reachability probe -------------------------------------------
|
||||
@@ -1850,10 +2024,16 @@ def cmd_proxy_auto(verb="list", *args):
|
||||
cmd_proxy_probe(*args)
|
||||
elif verb == "learn":
|
||||
cmd_proxy_learn(*args)
|
||||
elif verb == "forget":
|
||||
cmd_proxy_forget(*args)
|
||||
elif verb == "relearn":
|
||||
cmd_proxy_relearn(*args)
|
||||
elif verb == "clear":
|
||||
cmd_proxy_clear(*args)
|
||||
elif verb == "queue":
|
||||
cmd_proxy_queue(*args)
|
||||
else:
|
||||
usage("proxy auto [list|probe|learn|queue]")
|
||||
usage("proxy auto [list|probe|learn|forget|relearn|clear|queue]")
|
||||
|
||||
|
||||
def _autoproxy_next_run():
|
||||
@@ -1956,30 +2136,92 @@ def cmd_proxy_learned(*_):
|
||||
print(f" {_s(tag):<28} {', '.join(_s(b) for b in by)}")
|
||||
|
||||
|
||||
def cmd_proxy_learn(host="", *_):
|
||||
"""Queues the host for the prober's own unit, recorded under the same lock as a timer run."""
|
||||
_require_autoproxy()
|
||||
path = _autoproxy_dir()
|
||||
if not HOSTNAME.fullmatch(host):
|
||||
usage("proxy auto learn <domain>")
|
||||
requests = os.path.join(path, "requests")
|
||||
def _autoproxy_queue(name, line):
|
||||
"""Appends a line for the prober's own unit, which takes it under the same lock as a timer run."""
|
||||
path = os.path.join(_autoproxy_dir(), name)
|
||||
try:
|
||||
with open(requests, "a", encoding="utf-8") as f:
|
||||
f.write(f"{host}\n")
|
||||
with open(path, "a", encoding="utf-8") as f:
|
||||
f.write(f"{line}\n")
|
||||
except OSError:
|
||||
denied(requests, "write")
|
||||
print(f"Probing {host} through each exit...")
|
||||
denied(path, "write")
|
||||
|
||||
|
||||
def _autoproxy_run(what):
|
||||
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)
|
||||
print(f"The probe run failed. {what} is still queued and will be tried again at the next run.", file=sys.stderr)
|
||||
die(f"Details: {journal_hint('proxy-suite-autoproxy-learn', 20)}")
|
||||
h = (_autoproxy_state(path).get("hosts") or {}).get(host)
|
||||
|
||||
|
||||
def _autoproxy_report(host):
|
||||
h = (_autoproxy_state(_autoproxy_dir()).get("hosts") or {}).get(host)
|
||||
if h is None:
|
||||
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:
|
||||
print(f"{host}: {_s(h.get('verdict'))} - nothing to route")
|
||||
return h
|
||||
|
||||
|
||||
def cmd_proxy_learn(host="", *_):
|
||||
_require_autoproxy()
|
||||
if not HOSTNAME.fullmatch(host):
|
||||
usage("proxy auto learn <domain>")
|
||||
_autoproxy_queue("requests", host)
|
||||
print(f"Probing {host} through each exit...")
|
||||
_autoproxy_run(host)
|
||||
_autoproxy_report(host)
|
||||
|
||||
|
||||
def _autoproxy_learned(name, verb):
|
||||
"""(registrable domain, its route or None) for a domain or one of its hosts."""
|
||||
_require_autoproxy()
|
||||
if not HOSTNAME.fullmatch(name):
|
||||
usage(f"proxy auto {verb} <domain>")
|
||||
path = _autoproxy_dir()
|
||||
_require_autoproxy_readable(path)
|
||||
state = _autoproxy_state(path)
|
||||
domains = state.get("domains") or {}
|
||||
if name in domains:
|
||||
return name, domains[name]
|
||||
judged = (state.get("hosts") or {}).get(name) or (state.get("backlog") or {}).get(name) or {}
|
||||
domain = _s(judged.get("domain") or "")
|
||||
if domain:
|
||||
return domain, domains.get(domain)
|
||||
# A host under a routed domain: the route covers it.
|
||||
for d in domains:
|
||||
if name.endswith(f".{d}"):
|
||||
return d, domains[d]
|
||||
return name, None
|
||||
|
||||
|
||||
def cmd_proxy_forget(name="", *_):
|
||||
domain, route = _autoproxy_learned(name, "forget")
|
||||
_autoproxy_queue("edits", f"forget {domain}")
|
||||
_autoproxy_run(f"Forgetting {domain}")
|
||||
via = f" (was via {_s(route.get('exit'))})" if route else ""
|
||||
print(f"Forgot {domain}{via}: direct until it is dialled and learned again.")
|
||||
|
||||
|
||||
def cmd_proxy_relearn(name="", *_):
|
||||
domain, route = _autoproxy_learned(name, "relearn")
|
||||
host = _s((route or {}).get("host") or "") or name
|
||||
was = _s((route or {}).get("exit") or "")
|
||||
_autoproxy_queue("edits", f"forget {domain}")
|
||||
_autoproxy_queue("requests", host)
|
||||
print(f"Forgot {domain}{f' (was via {was})' if was else ''}; probing {host} through each exit...")
|
||||
_autoproxy_run(host)
|
||||
h = _autoproxy_report(host)
|
||||
if was and h and _s(h.get("exit") or "") == was:
|
||||
print(f"Same exit as before. To keep {domain} off it: proxy-ctl proxy outbounds disable {was}")
|
||||
|
||||
|
||||
def cmd_proxy_clear(*_):
|
||||
_require_autoproxy()
|
||||
_autoproxy_queue("edits", "clear")
|
||||
_autoproxy_run("Forgetting everything")
|
||||
print("Forgot every learned route and verdict: all direct until dialled and learned again.")
|
||||
|
||||
|
||||
# --- zapret -------------------------------------------------------------------
|
||||
|
||||
@@ -44,6 +44,8 @@ CELL_CLASSES = {
|
||||
"runtime": ["accent"],
|
||||
"pinned": ["accent"],
|
||||
"excluded": ["dim-label"],
|
||||
"✕": ["dim-label"],
|
||||
"disabled": ["dim-label"],
|
||||
"queued": ["warning"],
|
||||
}
|
||||
TAB_ICONS = {
|
||||
@@ -251,7 +253,7 @@ def cell_text(name, value):
|
||||
return value, CELL_CLASSES.get(value, [])
|
||||
|
||||
|
||||
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "queued"}
|
||||
BADGE_VALUES = {"ok", "bad", "runtime", "pinned", "excluded", "disabled", "queued"}
|
||||
|
||||
|
||||
def is_badge(name, value):
|
||||
|
||||
@@ -180,6 +180,7 @@ def outbound_rows(_):
|
||||
sources = inventory.get("sources") or {}
|
||||
detours = inventory.get("detours") or {}
|
||||
excluded = set(inventory.get("excluded") or [])
|
||||
disabled = set(ctl._outbound_disabled())
|
||||
current = ctl._outbound_current()
|
||||
reputation = ctl._reputation_by_tag()
|
||||
# outbounds.d is root-only; the inventory says "runtime" for what the backend loaded from it.
|
||||
@@ -187,13 +188,17 @@ def outbound_rows(_):
|
||||
return [
|
||||
{
|
||||
"key": t,
|
||||
"mark": "★" if t == pinned else "▸" if t == current else "",
|
||||
"mark": "★" if t == pinned else "▸" if t == current else "✕" if t in disabled else "",
|
||||
"tag": t,
|
||||
"reputation": reputation.get(t, "-"),
|
||||
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
|
||||
# As `proxy-ctl proxy outbounds` prints them.
|
||||
"notes": ", ".join(([f"via {ctl._s(detours[t])}"] if t in detours else []) + (["never picked"] if t in excluded else [])),
|
||||
"notes": ", ".join(
|
||||
([f"via {ctl._s(detours[t])}"] if t in detours else [])
|
||||
+ (["disabled"] if t in disabled else ["never picked"] if t in excluded else [])
|
||||
),
|
||||
"runtime": t in runtime,
|
||||
"disabled": t in disabled,
|
||||
}
|
||||
for t in ctl._outbound_tags()
|
||||
]
|
||||
@@ -243,12 +248,18 @@ def autoproxy_rows(_):
|
||||
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'))}"}
|
||||
{
|
||||
"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"}
|
||||
{"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
|
||||
]
|
||||
@@ -373,6 +384,12 @@ def _sub_url(row):
|
||||
return bool(row["user"]) and bool(ctl.env("INBOUNDS_SUB_BASE_URL"))
|
||||
|
||||
|
||||
def _add_args(text):
|
||||
"""[tag] <url>, or JSON with spaces in it, as `proxy-ctl ... add` takes them."""
|
||||
text = text.strip()
|
||||
return [text] if text.startswith("{") else text.split(None, 1)
|
||||
|
||||
|
||||
def _zapret_toggle(row, _, states):
|
||||
return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"]
|
||||
|
||||
@@ -420,7 +437,7 @@ TABS = [
|
||||
outbound_rows,
|
||||
summary=outbound_summary,
|
||||
actions=[
|
||||
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★"),
|
||||
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★" and not r["disabled"]),
|
||||
Action("u", "unpin: let the selection pick", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
|
||||
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("D", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=ROW, mode="dialog"),
|
||||
@@ -433,15 +450,28 @@ TABS = [
|
||||
mode="dialog",
|
||||
),
|
||||
Action("T", "test all", lambda r, *_: ["proxy", "outbounds", "test"], mode="dialog"),
|
||||
Action("n", "add a runtime outbound…", lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1)], prompt="<tag> <url or JSON>"),
|
||||
Action(
|
||||
"n",
|
||||
"add a runtime outbound (tag optional)…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)],
|
||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
||||
),
|
||||
Action(
|
||||
"h",
|
||||
"add an outbound chained through this one…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "add", *t.split(None, 1), "--detour", r["tag"]],
|
||||
"add an outbound chained through this one (tag optional)…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--detour", r["tag"]],
|
||||
when=ROW,
|
||||
prompt="<tag> <url or JSON>",
|
||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
||||
),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||
Action(
|
||||
"x",
|
||||
"disable it (never picked, pinned or probed)",
|
||||
lambda r, *_: ["proxy", "outbounds", "disable", r["tag"]],
|
||||
when=lambda r: not r["disabled"],
|
||||
confirm=True,
|
||||
),
|
||||
Action("e", "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("l", "its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("c", "copy its URL", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
|
||||
@@ -461,7 +491,12 @@ TABS = [
|
||||
actions=[
|
||||
Action("u", "refetch all", 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 runtime subscription…", lambda r, t, _: ["proxy", "subs", "add", *t.split(None, 1)], prompt="<tag> <url>"),
|
||||
Action(
|
||||
"n",
|
||||
"add a runtime subscription (tag optional)…",
|
||||
lambda r, t, _: ["proxy", "subs", "add", *_add_args(t)],
|
||||
prompt="[tag] <url> - e.g. work https://… or just https://…",
|
||||
),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "subs", "rm", r["tag"]], when=lambda r: r["source"] == "runtime", confirm=True),
|
||||
Action("k", "its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("y", "copy its URL", lambda r, *_: ["proxy", "subs", "link", r["tag"]], when=ROW, mode="copy"),
|
||||
@@ -481,6 +516,9 @@ TABS = [
|
||||
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, t, _: ["proxy", "auto", "probe", t], prompt="<domain>[/path]", mode="dialog"),
|
||||
Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="<domain>", mode="dialog"),
|
||||
Action("f", "forget it (direct until learned again)", lambda r, *_: ["proxy", "auto", "forget", r["domain"]], when=_kind("routed"), confirm=True),
|
||||
Action("R", "relearn it from the host it was learned from", lambda r, *_: ["proxy", "auto", "relearn", r["domain"]], when=_kind("routed"), mode="dialog"),
|
||||
Action("C", "forget everything learned", lambda r, *_: ["proxy", "auto", "clear"], confirm=True),
|
||||
Action("i", "routed, judged and bad exits", lambda r, *_: ["proxy", "auto", "list"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
@@ -518,13 +556,14 @@ TABS = [
|
||||
Action("S", "subscription URL as QR", lambda r, *_: ["inbounds", "sub", r["user"], "--qr"], when=_sub_url, mode="dialog"),
|
||||
Action("y", "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("w", "client config", lambda r, *_: _link(r, "--config"), when=_amneziawg, mode="dialog"),
|
||||
Action("W", "client config as QR", lambda r, *_: _link(r, "--config", "--qr"), when=_amneziawg, mode="dialog"),
|
||||
# Not w/W or o: those are the screen's where and last output.
|
||||
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("t", "traffic per user", lambda r, *_: ["inbounds", "stats"], mode="dialog"),
|
||||
Action("I", "traffic per inbound", lambda r, *_: ["inbounds", "stats", "--by", "inbound"], mode="dialog"),
|
||||
Action("O", "traffic per exit", lambda r, *_: ["inbounds", "stats", "--by", "outbound"], mode="dialog"),
|
||||
Action("o", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
|
||||
Action("n", "who is online", lambda r, *_: ["inbounds", "online"], mode="dialog"),
|
||||
],
|
||||
),
|
||||
Tab(
|
||||
@@ -555,7 +594,7 @@ 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 = tab.rows(states)
|
||||
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:
|
||||
@@ -564,6 +603,20 @@ def load_tab(tab, states):
|
||||
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 short(label):
|
||||
return label.split(" (")[0].removesuffix("…")
|
||||
|
||||
@@ -722,7 +775,8 @@ def tray_outbounds(snap):
|
||||
if not snap or not snap["proxy"]["active"]:
|
||||
return None
|
||||
inventory = _safe(ctl._outbound_inventory, fallback={}) or {}
|
||||
return [ctl._s(t) for t in inventory.get("tags") or []], ctl._s(inventory.get("pinned") 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):
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
What it shows and does lives in proxy_model, shared with proxy-suite-gui; this is the drawing.
|
||||
"""
|
||||
|
||||
import faulthandler
|
||||
import os
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import tempfile
|
||||
import traceback
|
||||
|
||||
from rich.text import Text
|
||||
from textual import events, work
|
||||
@@ -61,6 +64,28 @@ GLOBAL_KEYS = [
|
||||
("q", "quit"),
|
||||
]
|
||||
|
||||
|
||||
def trace_path():
|
||||
"""Where a stuck TUI's stacks go: kill -USR1 writes them, and a failed load or display adds its traceback."""
|
||||
return os.path.join(os.environ.get("XDG_RUNTIME_DIR") or tempfile.gettempdir(), f"proxy-tui-{os.getuid()}.trace")
|
||||
|
||||
|
||||
def open_trace():
|
||||
try:
|
||||
fd = os.open(trace_path(), os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600)
|
||||
if os.fstat(fd).st_uid != os.getuid(): # someone else's file in a shared /tmp
|
||||
os.close(fd)
|
||||
return None
|
||||
return os.fdopen(fd, "a", buffering=1)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def log_trace(what):
|
||||
if trace := open_trace():
|
||||
with trace:
|
||||
trace.write(f"--- {what}\n{traceback.format_exc()}\n")
|
||||
|
||||
KEY_LINE = [("menu", "⏎", "actions"), ("filter", "/", "filter"), ("help", "?", "keys"), ("quit", "q", "quit")]
|
||||
FEEDBACK_SECONDS = 10
|
||||
|
||||
@@ -120,6 +145,8 @@ CELL_STYLES = {
|
||||
"runtime": "cyan",
|
||||
"pinned": "cyan",
|
||||
"excluded": "dim",
|
||||
"✕": "dim",
|
||||
"disabled": "dim",
|
||||
"queued": "yellow",
|
||||
}
|
||||
|
||||
@@ -478,11 +505,17 @@ class ProxyTui(App):
|
||||
|
||||
@work(thread=True, exclusive=True, group="load")
|
||||
def load(self, tab_id):
|
||||
model.new_load()
|
||||
states = _read_states()
|
||||
visible = model.available_tabs(states)
|
||||
status = _safe(status_text, states, fallback=["status unavailable"])
|
||||
rows, summary = model.load_tab(self.tabs[tab_id], states)
|
||||
try:
|
||||
model.new_load()
|
||||
states = _read_states()
|
||||
visible = model.available_tabs(states)
|
||||
status = _safe(status_text, states, fallback=["status unavailable"])
|
||||
rows, summary = model.load_tab(self.tabs[tab_id], states)
|
||||
except Exception as e:
|
||||
# A dead worker would leave the tab as it was, for good; the next refresh tries again.
|
||||
log_trace(f"load {tab_id}")
|
||||
states, visible, status = self.states, self.shown, self.status
|
||||
rows, summary = [], f"✗ load failed: {str(e) or type(e).__name__} (traceback in {trace_path()})"
|
||||
self.call_from_thread(self.fill, tab_id, states, visible, status, rows, summary)
|
||||
|
||||
def show_status(self):
|
||||
@@ -493,6 +526,16 @@ class ProxyTui(App):
|
||||
self.fill(tab_id, *self.loaded[tab_id])
|
||||
|
||||
def fill(self, tab_id, states, visible, status, rows, summary):
|
||||
try:
|
||||
self.fill_table(tab_id, states, visible, status, rows, summary)
|
||||
except Exception as e:
|
||||
log_trace(f"fill {tab_id}")
|
||||
widget = self.main.query_one(f"#{tab_id}-summary", Static)
|
||||
_update(widget, Text(f"✗ display failed: {str(e) or type(e).__name__} (traceback in {trace_path()})"))
|
||||
widget.display = True
|
||||
|
||||
def fill_table(self, tab_id, states, visible, status, rows, summary):
|
||||
rows = model.unique_keys(rows)
|
||||
self.loaded[tab_id] = (states, visible, status, rows, summary)
|
||||
self.states, self.status = states, status
|
||||
# A read root could do: ! retries runs, not reads, so the way out is the whole TUI under sudo.
|
||||
@@ -631,6 +674,7 @@ class ProxyTui(App):
|
||||
text.append(f" {key:<9}", style=ACCENT)
|
||||
text.append(f"{label}\n")
|
||||
text.append("\n")
|
||||
text.append(f"Stuck? kill -USR1 {os.getpid()} writes where it is to {trace_path()}\n", style="dim")
|
||||
self.push_screen(Output("Keys", text))
|
||||
|
||||
def perform(self, action, row):
|
||||
@@ -786,6 +830,8 @@ class ProxyTui(App):
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if trace := open_trace():
|
||||
faulthandler.register(signal.SIGUSR1, file=trace, all_threads=True)
|
||||
if ProxyTui().run() == "root":
|
||||
# The wrapper by name: sudo resets the environment, and the wrapper sets it again.
|
||||
os.execvp("sudo", ["sudo", shutil.which("proxy-tui") or "proxy-tui"])
|
||||
@@ -401,6 +401,42 @@ class AutoProxyTest(EnvTest):
|
||||
self.assertRegex(learned, r"spotify.com .*-> primary")
|
||||
self.assertIn("ok=1", learned)
|
||||
|
||||
def test_forget(self):
|
||||
state = {
|
||||
"domains": {"last.fm": {"verdict": "destination", "exit": "primary", "host": "www.last.fm"}},
|
||||
"hosts": {"www.last.fm": {"domain": "last.fm", "verdict": "destination", "exit": "primary"}},
|
||||
}
|
||||
self.write("state.json", state)
|
||||
started = []
|
||||
self.patch("systemctl", lambda *args, **kw: started.append(args) or (0, ""))
|
||||
# A host names its domain: the route is the domain's.
|
||||
out = ok(ctl.cmd_proxy_forget, "www.last.fm")
|
||||
self.assertEqual(ctl.read_text(self.path("edits")), "forget last.fm\n")
|
||||
self.assertEqual(started, [("start", "proxy-suite-autoproxy-learn.service")])
|
||||
self.assertIn("Forgot last.fm (was via primary)", out)
|
||||
self.assertNotEqual(run(ctl.cmd_proxy_forget, "x;rm -rf /")[0], 0)
|
||||
|
||||
def test_relearn(self):
|
||||
before = {
|
||||
"domains": {"last.fm": {"verdict": "destination", "exit": "primary", "host": "www.last.fm"}},
|
||||
"hosts": {"www.last.fm": {"domain": "last.fm", "verdict": "destination", "exit": "primary"}},
|
||||
}
|
||||
self.write("state.json", before)
|
||||
self.state_on_start(before) # the same exit wins again
|
||||
out = ok(ctl.cmd_proxy_relearn, "last.fm")
|
||||
# Forgotten first, then probed again from the host it was learned from.
|
||||
self.assertEqual(ctl.read_text(self.path("edits")), "forget last.fm\n")
|
||||
self.assertEqual(ctl.read_text(self.path("requests")), "www.last.fm\n")
|
||||
self.assertIn("probing www.last.fm", out)
|
||||
self.assertIn("proxy-ctl proxy outbounds disable primary", out)
|
||||
|
||||
def test_clear(self):
|
||||
self.patch("systemctl", lambda *args, **kw: (1, ""))
|
||||
status, _, err = run(ctl.cmd_proxy_clear)
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("still queued", err)
|
||||
self.assertEqual(ctl.read_text(self.path("edits")), "clear\n")
|
||||
|
||||
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
|
||||
def test_unreadable_state_asks_for_sudo(self):
|
||||
os.chmod(self.dir, 0)
|
||||
@@ -412,6 +448,104 @@ class AutoProxyTest(EnvTest):
|
||||
self.assertIn("proxy-suite group, or re-run with sudo", err)
|
||||
|
||||
|
||||
class RuntimeEntryTest(EnvTest):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.environ.update(
|
||||
RUNTIME_OUTBOUNDS_DIR=self.path("outbounds.d"),
|
||||
RUNTIME_SUBS_DIR=self.path("subscriptions.d"),
|
||||
SUB_CACHE_DIR=self.path("subscriptions"),
|
||||
OUTBOUND_INVENTORY_FILE=self.path("outbounds.json"),
|
||||
SUB_TAGS_FILE=self.write("sub-tags.json", ["provider"]),
|
||||
)
|
||||
os.makedirs(self.path("outbounds.d"))
|
||||
os.makedirs(self.path("subscriptions.d"))
|
||||
self.declared, self.pinned, self.started = ["primary", "vless-example"], "", []
|
||||
self.backend_start()
|
||||
self.patch("systemctl", self.systemctl)
|
||||
|
||||
def backend_start(self):
|
||||
"""What the start script leaves: runtime entries and disable markers read into the inventory."""
|
||||
names = os.listdir(self.path("outbounds.d"))
|
||||
tags = self.declared + ctl._runtime_tags("outbound")
|
||||
disabled = [t for t in tags if f"{t}.disabled" in names]
|
||||
if self.pinned in disabled:
|
||||
self.pinned = ""
|
||||
self.write("outbounds.json", {"tags": tags, "pinned": self.pinned, "excluded": disabled, "disabled": disabled})
|
||||
for tag in ctl._runtime_tags("subscription"):
|
||||
self.write(f"subscriptions/{tag}.json", {"outbounds": []})
|
||||
|
||||
def systemctl(self, *args, **kw):
|
||||
self.started.append(args[1] if args[:1] == ("start",) else args)
|
||||
if args[1:] == ("proxy-suite-outbound-reload.service",) and os.path.exists(self.path(f"outbounds.d/{self.pinned}.disabled")):
|
||||
self.pinned = ""
|
||||
self.backend_start()
|
||||
return 0, ""
|
||||
|
||||
def test_tag_for(self):
|
||||
tag = ctl._runtime_tag_for
|
||||
self.assertEqual(tag("outbound", "vless://u@de1.example.net:443?security=reality#%F0%9F%87%A9%F0%9F%87%AA%20DE-1"), "DE-1")
|
||||
self.assertEqual(tag("outbound", "trojan://p@1.2.3.4:443"), "trojan-1.2.3.4")
|
||||
# Declared tags are taken as much as runtime ones.
|
||||
self.assertEqual(tag("outbound", "vless://u@www.example.org:443"), "vless-example-2")
|
||||
self.assertEqual(tag("outbound", '{"type": "socks", "server": "127.0.0.1"}'), "socks")
|
||||
self.assertEqual(tag("outbound", '{"tag": "proxy", "type": "socks"}'), "proxy-2") # reserved
|
||||
self.assertEqual(tag("outbound", "vmess://" + __import__("base64").b64encode(b'{"ps": "JP 2", "add": "jp.test"}').decode()), "JP-2")
|
||||
self.assertEqual(tag("outbound", "{not json"), "outbound")
|
||||
self.assertEqual(tag("subscription", "https://sub.provider.com/api/v1/client?token=x"), "provider-2")
|
||||
self.assertEqual(tag("subscription", "https://panel.work.test/s#" + "x" * 40), "x" * 32)
|
||||
self.write("outbounds.d/DE-1.url", "vless://u@de1.example.net:443\n")
|
||||
self.assertEqual(tag("outbound", "vless://u@x:1#DE-1"), "DE-1-2")
|
||||
|
||||
def test_add_forms(self):
|
||||
# A URL alone: the tag comes from it.
|
||||
out = ok(ctl.cmd_subscription, "add", "https://sub.work.test/s")
|
||||
self.assertIn("Tag: work (none given", out)
|
||||
self.assertEqual(ctl.read_text(self.path("subscriptions.d/work.url")), "https://sub.work.test/s\n")
|
||||
# Tag, then URL.
|
||||
ok(ctl.cmd_subscription, "add", "home", "https://sub.home.test/s")
|
||||
self.assertTrue(os.path.exists(self.path("subscriptions.d/home.url")))
|
||||
# The other way round is a mistake worth naming.
|
||||
status, _, err = run(ctl.cmd_subscription, "add", "https://sub.x.test/s", "x")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("The tag goes first", err)
|
||||
self.assertNotEqual(run(ctl.cmd_subscription, "add", "lonely")[0], 0)
|
||||
# Outbound JSON alone, and a JSON-looking word for a subscription is not a source.
|
||||
self.assertIn("Tag: socks", ok(ctl.cmd_outbounds, "add", '{"type": "socks", "server": "127.0.0.1", "server_port": 1080}'))
|
||||
self.assertTrue(os.path.exists(self.path("outbounds.d/socks.json")))
|
||||
self.assertNotEqual(run(ctl.cmd_subscription, "add", "-")[0], 0)
|
||||
|
||||
def test_disable_enable(self):
|
||||
self.pinned = "primary"
|
||||
self.backend_start()
|
||||
out = ok(ctl.cmd_outbounds, "disable", "primary")
|
||||
self.assertTrue(os.path.exists(self.path("outbounds.d/primary.disabled")))
|
||||
# The reload drops the pin with it.
|
||||
self.assertEqual(self.started, ["proxy-suite-outbound-reload.service"])
|
||||
self.assertEqual(ctl._outbound_inventory()["pinned"], "")
|
||||
self.assertIn("Disabled: primary", out)
|
||||
self.assertIn("Already disabled", ok(ctl.cmd_outbounds, "disable", "primary"))
|
||||
# The last one selection could pick stays.
|
||||
status, _, err = run(ctl.cmd_outbounds, "disable", "vless-example")
|
||||
self.assertNotEqual(status, 0)
|
||||
self.assertIn("only outbound", err)
|
||||
self.assertNotEqual(run(ctl.cmd_outbounds, "disable", "nope")[0], 0)
|
||||
self.assertNotEqual(run(ctl.cmd_pin, "primary")[0], 0)
|
||||
|
||||
self.started.clear()
|
||||
self.assertIn("Enabled: primary", ok(ctl.cmd_outbounds, "enable", "primary"))
|
||||
self.assertFalse(os.path.exists(self.path("outbounds.d/primary.disabled")))
|
||||
self.assertEqual(self.started, ["proxy-suite-outbound-reload.service"])
|
||||
self.assertNotEqual(run(ctl.cmd_outbounds, "enable", "primary")[0], 0)
|
||||
self.assertNotEqual(run(ctl.cmd_outbounds, "enable", "../primary")[0], 0)
|
||||
|
||||
def test_rm_takes_the_marker_along(self):
|
||||
ok(ctl.cmd_outbounds, "add", "de", "vless://u@de.test:443")
|
||||
ok(ctl.cmd_outbounds, "disable", "de")
|
||||
ok(ctl.cmd_outbounds, "rm", "de")
|
||||
self.assertEqual(os.listdir(self.path("outbounds.d")), [])
|
||||
|
||||
|
||||
class ZapretAutoTest(EnvTest):
|
||||
@unittest.skipIf(os.geteuid() == 0, "root writes anything")
|
||||
def test_clear_replaces_what_it_cannot_write(self):
|
||||
|
||||
@@ -84,10 +84,10 @@ class ModelTest(unittest.TestCase):
|
||||
actions = {a.key: a for a in tab.actions}
|
||||
awg = {"key": "awg/u", "tag": "awg", "user": "u", "type": "amneziawg", "port": "51820"}
|
||||
vless = {"key": "in/u", "tag": "in", "user": "u", "type": "vless", "port": "443"}
|
||||
self.assertEqual(actions["w"].argv(awg), ["inbounds", "link", "awg", "u", "--config"])
|
||||
self.assertEqual(actions["W"].argv(awg), ["inbounds", "link", "awg", "u", "--config", "--qr"])
|
||||
self.assertTrue(actions["w"].when(awg) and actions["W"].when(awg) and actions["J"].when(vless))
|
||||
self.assertFalse(actions["w"].when(vless) or actions["W"].when(vless) or actions["J"].when(awg))
|
||||
self.assertEqual(actions["k"].argv(awg), ["inbounds", "link", "awg", "u", "--config"])
|
||||
self.assertEqual(actions["K"].argv(awg), ["inbounds", "link", "awg", "u", "--config", "--qr"])
|
||||
self.assertTrue(actions["k"].when(awg) and actions["K"].when(awg) and actions["J"].when(vless))
|
||||
self.assertFalse(actions["k"].when(vless) or actions["K"].when(vless) or actions["J"].when(awg))
|
||||
|
||||
def test_inbound_rows_carry_no_presence(self):
|
||||
"""XRay keys the online map by user, not by inbound, so a per-listener row
|
||||
@@ -152,7 +152,7 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
|
||||
self.assertIn("Pinned: b", summary)
|
||||
with mock.patch.object(ctl, "env", lambda name, default="": ""):
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "l", "c", "Q", "J", "F", "X"])
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["u", "t", "D", "T", "n", "h", "x", "l", "c", "Q", "J", "F", "X"])
|
||||
chain = next(a for a in tab.actions if a.key == "h")
|
||||
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
|
||||
# Probe exits go by the backend's tag.
|
||||
@@ -168,6 +168,47 @@ class ModelTest(unittest.TestCase):
|
||||
rows, _ = model.load_tab(tab, {})
|
||||
self.assertEqual([(r["source"], r["runtime"]) for r in rows], [("runtime", True), ("-", False)])
|
||||
|
||||
def test_disabled_outbound(self):
|
||||
"""Disabled: marked, never offered a pin, and enabled again rather than disabled twice."""
|
||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||
inventory = {"tags": ["a", "b"], "pinned": "", "excluded": ["b"], "disabled": ["b"]}
|
||||
with mock.patch.object(ctl, "_outbound_current", lambda: "a"), mock.patch.object(ctl, "_reputation_by_tag", lambda: {}), mock.patch.object(ctl, "_runtime_tags", lambda kind: []), mock.patch.object(ctl, "_outbound_inventory", lambda: inventory), mock.patch.object(ctl, "env", lambda name, default="": ""):
|
||||
rows, _ = model.load_tab(tab, {})
|
||||
self.assertEqual([(r["mark"], r["notes"], r["disabled"]) for r in rows], [("▸", "", False), ("✕", "disabled", True)])
|
||||
keys = [a.key for a in model.applicable(tab, rows[1])]
|
||||
self.assertIn("e", keys)
|
||||
self.assertNotIn("p", keys)
|
||||
self.assertNotIn("x", keys)
|
||||
self.assertEqual(next(a for a in tab.actions if a.key == "x").argv(rows[0], "", {}), ["proxy", "outbounds", "disable", "a"])
|
||||
with mock.patch.object(ctl, "_outbound_inventory", lambda: inventory):
|
||||
self.assertEqual(model.tray_outbounds({"proxy": {"active": True}}), (["a"], ""))
|
||||
|
||||
def test_add_prompt_takes_an_optional_tag(self):
|
||||
subs = next(t for t in model.TABS if t.id == "subs")
|
||||
add = next(a for a in subs.actions if a.key == "n")
|
||||
self.assertIn("[tag]", add.prompt)
|
||||
self.assertEqual(add.argv(None, "https://x.test/s", {}), ["proxy", "subs", "add", "https://x.test/s"])
|
||||
self.assertEqual(add.argv(None, " work https://x.test/s ", {}), ["proxy", "subs", "add", "work", "https://x.test/s"])
|
||||
outbounds = next(t for t in model.TABS if t.id == "outbounds")
|
||||
add = next(a for a in outbounds.actions if a.key == "n")
|
||||
# JSON has spaces in it: all one argument.
|
||||
self.assertEqual(add.argv(None, '{"type": "socks"}', {}), ["proxy", "outbounds", "add", '{"type": "socks"}'])
|
||||
|
||||
def test_autoproxy_forget_relearn_clear(self):
|
||||
tab = next(t for t in model.TABS if t.id == "autoproxy")
|
||||
state = {"domains": {"last.fm": {"exit": "de", "host": "www.last.fm"}}, "backlog": {"a.test": {"domain": "a.test", "hits": 2}}}
|
||||
with mock.patch.object(ctl, "_autoproxy_unreadable", lambda path: ""), mock.patch.object(ctl, "_autoproxy_state", lambda path: state):
|
||||
routed, queued = model.autoproxy_rows({})
|
||||
self.assertEqual(routed["detail"], "via de, learned from www.last.fm")
|
||||
actions = {a.key: a for a in tab.actions}
|
||||
for key in ("f", "R"):
|
||||
self.assertIn(actions[key], model.applicable(tab, routed))
|
||||
self.assertNotIn(actions[key], model.applicable(tab, queued))
|
||||
self.assertEqual(actions["f"].argv(routed, "", {}), ["proxy", "auto", "forget", "last.fm"])
|
||||
self.assertEqual(actions["R"].argv(routed, "", {}), ["proxy", "auto", "relearn", "last.fm"])
|
||||
self.assertEqual(actions["C"].argv(None, "", {}), ["proxy", "auto", "clear"])
|
||||
self.assertTrue(actions["f"].confirm and actions["C"].confirm)
|
||||
|
||||
def test_load_tab_as_root(self):
|
||||
"""The GUI's root read: proxy-ctl status --tab through pkexec, and what a refusal says."""
|
||||
tab = next(t for t in model.TABS if t.id == "routing")
|
||||
|
||||
@@ -23,7 +23,10 @@ class TuiTest(unittest.TestCase):
|
||||
"zapret-hosts-user-exclude.txt": ["kept.example"],
|
||||
}
|
||||
self.capture, self.awg, self.current = "", [], mock.Mock(return_value="")
|
||||
self.env = env = {"ZAPRET_AUTO_ENABLED": "1"}
|
||||
# The host's own /var/lib/proxy-suite is not the test's.
|
||||
state = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(state.cleanup)
|
||||
self.env = env = {"ZAPRET_AUTO_ENABLED": "1", "STATE_DIR": state.name}
|
||||
for target, name, value in [
|
||||
(model, "unit_states", lambda units: {u: s for u, s in self.units.items() if u in units}),
|
||||
(model, "_capture", lambda argv: self.capture),
|
||||
@@ -87,6 +90,37 @@ class TuiTest(unittest.TestCase):
|
||||
# Items never split across lines.
|
||||
self.assertEqual(tui.pack(["[b]aaa[/]", "bbb", "ccc"], 9), "[b]aaa[/] bbb\nccc")
|
||||
|
||||
def test_tab_keys_leave_screen_keys_alone(self):
|
||||
"""A tab's action key hides the screen's key of the same name while that tab has focus."""
|
||||
screen = {k for b in tui.MainScreen.BINDINGS for k in b.key.split(",")}
|
||||
same_meaning = {("autoproxy", "w")} # how is this domain routed: the row's own
|
||||
for tab in tui.TABS:
|
||||
for action in tab.actions:
|
||||
if (tab.id, action.key) not in same_meaning:
|
||||
self.assertNotIn(action.key, screen, f"{tab.id}: {action.label}")
|
||||
|
||||
def test_failed_load_keeps_the_tui_going(self, rows=None):
|
||||
async def run():
|
||||
tui_trace = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(tui_trace.cleanup)
|
||||
with mock.patch.dict(tui.os.environ, {"XDG_RUNTIME_DIR": tui_trace.name}):
|
||||
with mock.patch.object(model, "load_tab", side_effect=RuntimeError("boom")):
|
||||
app = tui.ProxyTui()
|
||||
async with app.run_test(size=(100, 30)) as pilot:
|
||||
await self.settle(app, pilot)
|
||||
self.assertIn("✗ load failed: boom", str(app.main.query_one("#services-summary").content))
|
||||
with open(tui.trace_path()) as trace:
|
||||
self.assertIn("RuntimeError: boom", trace.read())
|
||||
# Reads work again: the next refresh fills the tab.
|
||||
model.load_tab.side_effect = None
|
||||
model.load_tab.return_value = ([{"key": "u", "unit": "u"}, {"key": "u", "unit": "u again"}], "")
|
||||
app.action_reload()
|
||||
await self.settle(app, pilot)
|
||||
self.assertEqual([k.value for k in app.table("services").rows], ["u", "u#2"])
|
||||
self.assertEqual(app.main.query_one("#services-summary").display, False)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
def test_ui(self):
|
||||
# Not IsolatedAsyncioTestCase: its asyncio debug mode makes Textual crawl.
|
||||
asyncio.run(self.ui())
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# sing-box for hosts where an app may not join netlink's route groups (nix-on-droid).
|
||||
#
|
||||
# The network monitor subscribes to route, link and address changes, and Android's
|
||||
# SELinux policy refuses an app that. sing-tun only checks for that on GOOS=android,
|
||||
# so a linux build starts the monitor anyway and the whole service fails with
|
||||
# "subscribe netlink groups: permission denied". Checking when the monitor is created
|
||||
# instead makes that fail, and sing-box then goes on without one unless
|
||||
# auto_detect_interface asks for it, which only TUN configs do.
|
||||
{ sing-box }:
|
||||
|
||||
sing-box.overrideAttrs (old: {
|
||||
postConfigure = (old.postConfigure or "") + ''
|
||||
tun=vendor/github.com/sagernet/sing-tun
|
||||
chmod -R u+w "$tun"
|
||||
cp ${./patches/sing-tun-netlink-groups-probe.go} "$tun/monitor_linux_groups_probe.go"
|
||||
substituteInPlace "$tun/monitor_linux.go" --replace-fail \
|
||||
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {' \
|
||||
'func NewNetworkUpdateMonitor(logger logger.Logger) (NetworkUpdateMonitor, error) {
|
||||
if netlinkGroupsBanned() {
|
||||
return nil, ErrNetlinkBanned
|
||||
}'
|
||||
'';
|
||||
passthru = (old.passthru or { }) // {
|
||||
rootlessNetlink = true;
|
||||
};
|
||||
})
|
||||
Reference in new issue
Block a user