From 97332c17742e2c25c35df78373ffbb8f48ab2ed6 Mon Sep 17 00:00:00 2001 From: FUFSoB Date: Thu, 17 Sep 2026 18:15:55 +0500 Subject: [PATCH] fix: multiple fixes --- README.md | 12 +- docs/options/userControl.md | 4 +- modules/proxy-suite/autoproxy-edit.jq | 23 ++ modules/proxy-suite/autoproxy.nix | 64 +++- modules/proxy-suite/hosts/nix-on-droid.nix | 5 + modules/proxy-suite/options/user-control.nix | 4 +- .../proxy-suite/service/control-scripts.nix | 26 ++ .../script-blocks/backend-jq-filter.nix | 18 +- .../service/script-blocks/outbounds.nix | 35 +- modules/proxy-suite/service/scripts.nix | 2 +- modules/proxy-suite/service/start-scripts.nix | 6 +- nix/checks/hosts.nix | 3 + nix/checks/repo.nix | 113 +++++++ nix/checks/route-mode.nix | 3 +- pkgs/patches/sing-tun-netlink-groups-probe.go | 21 ++ pkgs/proxy-ctl/proxy_ctl.py | 306 ++++++++++++++++-- pkgs/proxy-ctl/proxy_gui.py | 4 +- pkgs/proxy-ctl/proxy_model.py | 84 ++++- pkgs/proxy-ctl/proxy_tui.py | 56 +++- pkgs/proxy-ctl/test_proxy_ctl.py | 134 ++++++++ pkgs/proxy-ctl/test_proxy_model.py | 51 ++- pkgs/proxy-ctl/test_proxy_tui.py | 36 ++- pkgs/sing-box-rootless-netlink.nix | 26 ++ 23 files changed, 940 insertions(+), 96 deletions(-) create mode 100644 modules/proxy-suite/autoproxy-edit.jq create mode 100644 pkgs/patches/sing-tun-netlink-groups-probe.go create mode 100644 pkgs/sing-box-rootless-netlink.nix diff --git a/README.md b/README.md index ba818f0..dd80e66 100644 --- a/README.md +++ b/README.md @@ -179,10 +179,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 [--detour ] + proxy outbounds add [tag] [--detour ] 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 remove a runtime outbound + proxy outbounds disable|enable 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 [--qr|--json|--config] @@ -192,7 +195,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 add a subscription at runtime + proxy subs add [tag] add a subscription at runtime; no tag: named after its host proxy subs rm remove a runtime subscription proxy subs link [--qr] its URL proxy config [--raw] client config to import elsewhere; --raw: as running @@ -202,6 +205,9 @@ Secrets and changes need root, or the userControl group. proxy auto probe [/path] [--json] [--keep-going] [--exits a,b | --via tag] find an exit that reaches a domain proxy auto learn probe now and route it if an exit works + proxy auto forget drop what was learned about it: direct until learned again + proxy auto relearn 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 diff --git a/docs/options/userControl.md b/docs/options/userControl.md index e61e0a3..4b611cd 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -51,9 +51,9 @@ What userControl\.group may do; empty allows every scope\. - “services”: turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and ` restart `\. - “perApp”: the per-app backend units used by ` proxy-ctl apps run `\. - “routing”: ` proxy pin `, ` proxy unpin ` and ` proxy mode `\. - - “outbounds”: add and remove runtime outbounds and subscriptions, and update subscriptions\. + - “outbounds”: add and remove runtime outbounds and subscriptions, disable and enable outbounds, and update subscriptions\. - “secrets”: read share links, subscription URLs and the running configs\. - - “autoProxy”: read what autoProxy learned, and ` proxy auto learn `\. + - “autoProxy”: read what autoProxy learned, and ` proxy auto learn|forget|relearn|clear `\. - “zapret”: edit zapret2’s learned hosts, and ` zapret cutoff probe `\. - “stats”: ` inbounds stats `\. diff --git a/modules/proxy-suite/autoproxy-edit.jq b/modules/proxy-suite/autoproxy-edit.jq new file mode 100644 index 0000000..1151f21 --- /dev/null +++ b/modules/proxy-suite/autoproxy-edit.jq @@ -0,0 +1,23 @@ +# One `proxy-ctl proxy auto forget|clear` request, applied under the prober's lock. +# $op "forget": domain $d goes back to direct, and every verdict and strike about it +# goes too, so the next time it is dialled it is probed from scratch. +# $op "clear": the same for every domain. What each exit is (ip, asn), the backlog +# and the egress address stay: they are about the exits and the clients, not a verdict. +def rebad: + (.strikes // {}) as $s + | . + {bad: (($s | length) >= 2), + badBy: ($s | to_entries | sort_by(.value.at) | map("\(.key) \(.value.why)"))}; + +if $op == "clear" then + .domains = {} + | .hosts = {} + | del(.slowWant, .slowSkip) + | .exits = ((.exits // {}) | map_values(.strikes = {} | rebad)) +elif $op == "forget" then + .domains = ((.domains // {}) | del(.[$d])) + | .hosts = ((.hosts // {}) | with_entries(select(.value.domain != $d))) + | .backlog = ((.backlog // {}) | with_entries(select(.value.domain != $d))) + | if .slowWant then .slowWant |= del(.[$d]) else . end + | if .slowSkip then .slowSkip |= del(.[$d]) else . end + | .exits = ((.exits // {}) | map_values(if .strikes then (.strikes |= del(.[$d]) | rebad) else . end)) +else . end diff --git a/modules/proxy-suite/autoproxy.nix b/modules/proxy-suite/autoproxy.nix index 5522eb0..4ec2fc1 100644 --- a/modules/proxy-suite/autoproxy.nix +++ b/modules/proxy-suite/autoproxy.nix @@ -78,7 +78,7 @@ let set -euo pipefail export PATH=${bin} - # --requests-only: just the `proxy-ctl proxy auto learn` requests. + # --requests-only: just the `proxy-ctl proxy auto learn|forget|clear` requests. mode=''${1:-full} # Overridable to rehearse a run against a scratch copy; the units never set them. @@ -87,13 +87,10 @@ let index=$PROBE_EXITS_FILE state="$state_dir/state.json" requests="$state_dir/requests" + edits="$state_dir/edits" now=$(date +%s) ttl=$(( ${toString apCfg.ttlDays} * 86400 )) - if [ ! -r "$index" ]; then - echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" - exit 0 - fi install -d -m ${stateDirMode} "$state_dir" # Timer runs and learn requests take turns on the state. @@ -102,12 +99,14 @@ let # Leftovers of a run that died partway; taken requests go back in line. rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking" - if [ -e "$requests.taking" ]; then - cat "$requests.taking" >> "$requests" - rm -f "$requests.taking" - # Made here by root: the group appends to it too. - chmod 0660 "$requests" - fi + for queue in "$requests" "$edits"; do + if [ -e "$queue.taking" ]; then + cat "$queue.taking" >> "$queue" + rm -f "$queue.taking" + # Made here by root: the group appends to it too. + chmod 0660 "$queue" + fi + done if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2 @@ -129,6 +128,49 @@ let mv -f "$tmp" "$state" } + # --- 0. forget what `proxy-ctl proxy auto forget|relearn|clear` asked to --- + # Before anything else, and even with the proxy stopped: its start renders the + # rule-sets from the state again. + edited="" + if [ -s "$edits" ]; then + mv -f "$edits" "$edits.taking" + while read -r op dom; do + case "$op" in + forget) + [[ "$dom" =~ ^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$ ]] || continue + update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq} + echo "forgot $dom" + ;; + clear) + update --arg op clear --arg d "" -f ${jqFile ./autoproxy-edit.jq} + echo "forgot everything learned" + ;; + *) continue ;; + esac + edited=1 + done < "$edits.taking" + rm -f "$edits.taking" + fi + + if [ ! -r "$index" ]; then + echo "no probe listeners - is proxy-suite-socks running with autoProxy on?" + exit 0 + fi + + # Routes through an outbound disabled since (`proxy-ctl proxy outbounds disable`) + # are forgotten like the above, so their domains get probed again without it. + inventory="$(dirname "$index")/outbounds.json" + if [ -r "$inventory" ]; then + while IFS=$'\t' read -r dom exit; do + echo "forgot $dom: its exit $exit is disabled" + update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq} + edited=1 + done < <(jq -r --slurpfile inv "$inventory" '($inv[0].disabled // []) as $off + | (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e])) + | "\(.key)\t\(.value.exit)"' "$state") + fi + [ -z "$edited" ] || ${render} "$index" "$state" + # $1 JSON array of exit tags, $2 registrable domain, $3 wall:|refused|slow. strike() { update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \ diff --git a/modules/proxy-suite/hosts/nix-on-droid.nix b/modules/proxy-suite/hosts/nix-on-droid.nix index ca821b6..7b9b865 100644 --- a/modules/proxy-suite/hosts/nix-on-droid.nix +++ b/modules/proxy-suite/hosts/nix-on-droid.nix @@ -5,6 +5,7 @@ config, lib, pkgs, + proxySuiteUpstream, ... }: @@ -84,6 +85,10 @@ in firewallPackage = null; resolvconfPackage = null; }; + # An app may not join netlink's route groups: without this sing-box fails to start. + services.proxy-suite.proxy.singBox.package = lib.mkDefault ( + import ../../../pkgs/sing-box-rootless-netlink.nix { inherit (proxySuiteUpstream) sing-box; } + ); } (lib.mkIf cfg.enable { diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index 610d6ff..23016d2 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -32,9 +32,9 @@ in - "services": turn the proxy-suite units on and off (proxy, tun, tproxy, zapret, ssh, warp, tg, awg, inbounds), and `restart`. - "perApp": the per-app backend units used by `proxy-ctl apps run`. - "routing": `proxy pin`, `proxy unpin` and `proxy mode`. - - "outbounds": add and remove runtime outbounds and subscriptions, and update subscriptions. + - "outbounds": add and remove runtime outbounds and subscriptions, disable and enable outbounds, and update subscriptions. - "secrets": read share links, subscription URLs and the running configs. - - "autoProxy": read what autoProxy learned, and `proxy auto learn`. + - "autoProxy": read what autoProxy learned, and `proxy auto learn|forget|relearn|clear`. - "zapret": edit zapret2's learned hosts, and `zapret cutoff probe`. - "stats": `inbounds stats`. ''; diff --git a/modules/proxy-suite/service/control-scripts.nix b/modules/proxy-suite/service/control-scripts.nix index 00872a4..68ef069 100644 --- a/modules/proxy-suite/service/control-scripts.nix +++ b/modules/proxy-suite/service/control-scripts.nix @@ -7,6 +7,7 @@ routeModeStateFile, pinnedOutboundFile, outboundInventoryFile, + runtimeOutboundsDir, subscriptionCacheDir, subscriptionCacheHelpersBlock, mkSubscriptionFetchBlock, @@ -95,6 +96,16 @@ let echo "proxy-suite: unknown outbound '$tag'" >&2 exit 1 fi + # Disabled means nothing picks it on its own, a pin included. + case "$tag" in + */* | . | ..) ;; + *) + if [ -e "${runtimeOutboundsDir}/$tag.disabled" ]; then + echo "proxy-suite: outbound '$tag' is disabled; enable it first: proxy-ctl proxy outbounds enable $tag" >&2 + exit 1 + fi + ;; + esac mkdir -p "$(dirname "${pinnedOutboundFile}")" printf '%s\n' "$tag" > "${pinnedOutboundFile}" # Live switch when the running config exposes a selector; the persisted pin @@ -147,6 +158,21 @@ let esac done + # A pin on a disabled outbound goes with it, so enabling the outbound later does not + # bring the pin back. Here rather than through the unpin unit: disabling is the + # outbounds scope's, pinning the routing scope's. + if [ -r "${pinnedOutboundFile}" ]; then + PINNED="$(tr -d '\r\n[:space:]' < "${pinnedOutboundFile}" 2>/dev/null || true)" + case "$PINNED" in + "" | */* | . | ..) ;; + *) + if [ -e "${runtimeOutboundsDir}/$PINNED.disabled" ]; then + rm -f "${pinnedOutboundFile}" + fi + ;; + esac + fi + ${restartActiveConfigConsumersBlock} ''; in diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index d68d04a..d1ff833 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -4,7 +4,6 @@ selectionMode, proxyInboundsGuardPrivate, userDnsRules ? [ ], - selectionExclude ? [ ], }: if pureXrayEnabled then @@ -72,14 +71,15 @@ if pureXrayEnabled then | if $route_enabled then .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) else . end - ${lib.optionalString (selectionExclude != [ ]) '' - # The balancer's prefix would take in proxy.selectionExclude too: name the rest instead. - # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; - # rename one of them if that matters. - | ($xray_selectable | map("proxy-suite-ob-" + .)) as $candidates - | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end - | if .observatory then .observatory.subjectSelector = $candidates else . end - ''} + # The balancer's prefix would take in proxy.selectionExclude and disabled outbounds + # too: name the rest instead. Disabling is a runtime decision, so always. + # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; + # rename one of them if that matters. + | if $ARGS.named.xray_selectable == null then . else + ($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates + | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end + | if .observatory then .observatory.subjectSelector = $candidates else . end + end | if $xray_single_proxy_tag == "" then . else diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 81ac6a7..10f46c3 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -496,6 +496,20 @@ let # entry that went away, say - is dropped rather than left to break the config. pinBlock = '' OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON") + + # `proxy-ctl proxy outbounds disable` leaves .disabled next to the runtime entries: + # the outbound stays, so rules and chains naming it still work, but nothing picks it on + # its own - selection, autoProxy and a pin. Markers for tags that are gone are ignored. + DISABLED_TAGS_JSON='[]' + if [ -d "${runtimeOutboundsDir}" ]; then + for DISABLED_MARKER in "${runtimeOutboundsDir}"/*.disabled; do + [ -e "$DISABLED_MARKER" ] || continue + DISABLED_TAG="''${DISABLED_MARKER##*/}" + DISABLED_TAGS_JSON=$(${jq} -c --arg t "''${DISABLED_TAG%.disabled}" '. + [$t]' <<< "$DISABLED_TAGS_JSON") + done + fi + DISABLED_TAGS_JSON=$(${jq} -c --argjson tags "$OUTBOUND_TAGS_JSON" 'map(select(. as $t | $tags | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON") + PINNED_OUTBOUND="" if [ -r "${pinnedOutboundFile}" ]; then PINNED_OUTBOUND="$(tr -d '\r\n[:space:]' < "${pinnedOutboundFile}" 2>/dev/null || true)" @@ -505,21 +519,27 @@ let echo "proxy-suite: warning: pinned outbound '$PINNED_OUTBOUND' is not available; picking automatically" >&2 PINNED_OUTBOUND="" fi + if [ -n "$PINNED_OUTBOUND" ] \ + && ${jq} -e --arg t "$PINNED_OUTBOUND" 'index($t) != null' <<< "$DISABLED_TAGS_JSON" >/dev/null; then + echo "proxy-suite: warning: pinned outbound '$PINNED_OUTBOUND' is disabled; picking automatically" >&2 + PINNED_OUTBOUND="" + fi ''; - # What selection may pick on its own: all but proxy.selectionExclude. A pin and a - # selector switched by hand still reach the excluded ones. + # What selection may pick on its own: all but proxy.selectionExclude and disabled + # outbounds. A pin still reaches the excluded ones, and a selector switched by hand both. selectableBlock = '' SELECTABLE_TAGS_JSON=$(${jq} -c --argjson ex ${lib.escapeShellArg (builtins.toJSON proxyCfg.selectionExclude)} \ - 'map(select(. as $t | $ex | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON") + --argjson disabled "$DISABLED_TAGS_JSON" \ + 'map(select(. as $t | ($ex + $disabled) | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON") if [ -z "$PINNED_OUTBOUND" ] && [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 0 ]; then - echo "proxy-suite: every outbound is in proxy.selectionExclude, so there is nothing to select; pin one, or exclude fewer" >&2 + echo "proxy-suite: every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one (proxy-ctl proxy outbounds enable), or exclude fewer" >&2 exit 1 fi ''; # proxy-ctl reads this unprivileged: tags, where each came from, the pin, what each one - # chains through, and what selection leaves alone. + # chains through, what selection leaves alone, and what was disabled. inventoryBlock = '' ${jq} -n \ --argjson tags "$OUTBOUND_TAGS_JSON" \ @@ -529,10 +549,11 @@ let --argjson obs "$OUTBOUNDS_JSON" \ --argjson xobs "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}" \ --argjson selectable "$SELECTABLE_TAGS_JSON" \ + --argjson disabled "$DISABLED_TAGS_JSON" \ '{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection, detours: ([($xobs + $obs)[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h | select($h != null) | {key: .tag, value: $h}] | from_entries), - excluded: ($tags - $selectable)}' \ + excluded: ($tags - $selectable), disabled: $disabled}' \ > "$RUNTIME_DIR/outbounds.json" chmod 644 "$RUNTIME_DIR/outbounds.json" ''; @@ -640,4 +661,6 @@ let in { inherit mkOutboundScript rawOutboundJson; + # For the checks: which outbounds a pin and selection may take. + selectionBlocks = pinBlock + selectableBlock + inventoryBlock; } diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 9b707aa..7c4687e 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -154,7 +154,6 @@ let proxyInboundsGuardPrivate ; userDnsRules = proxyCfg.dns.singBox.rules; - inherit (proxyCfg) selectionExclude; }; backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; @@ -234,6 +233,7 @@ let routeModeStateFile pinnedOutboundFile outboundInventoryFile + runtimeOutboundsDir subscriptionCacheDir subscriptionCacheHelpersBlock mkSubscriptionFetchBlock diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index a529445..a2b62a2 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -205,12 +205,14 @@ let [ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json" # direct is always exit 0; state is keyed by tag, so shifting indices are - # harmless. + # harmless. Disabled outbounds are no exit: the prober drops what was learned + # through them. PROBE_EXITS_JSON=$(${jq} -c \ --argjson max ${toString proxyCfg.autoProxy.maxExits} \ --argjson base ${toString proxyCfg.autoProxy.probeBasePort} \ + --argjson disabled "''${DISABLED_TAGS_JSON:-[]}" \ --arg dir "$AUTOPROXY_DIR" ' - (["direct"] + map(select(. != "direct")))[0:$max] + (["direct"] + map(select(. != "direct" and (. as $t | $disabled | index([$t]) | not))))[0:$max] | to_entries | map({i: .key, tag: .value, port: ($base + .key), rule_set: ("autoproxy-" + (.key | tostring)), diff --git a/nix/checks/hosts.nix b/nix/checks/hosts.nix index 6f6d697..502fc5b 100644 --- a/nix/checks/hosts.nix +++ b/nix/checks/hosts.nix @@ -204,6 +204,9 @@ in assert lib.hasInfix "proxy-suitectl boot" nodCfg.build.activationAfter.proxySuite; assert lib.hasInfix "proxy-suitectl ensure" nodCfg.environment.etc.profile.text; assert forced nodCfg.build.activationAfter.proxySuite; + # Android bans apps from netlink's route groups, which stock sing-box subscribes to. + assert nodCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false; + assert !(hmCfg.services.proxy-suite.proxy.singBox.package.passthru.rootlessNetlink or false); true ) ( diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index dba44ad..e7496fc 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -111,6 +111,8 @@ printf '%s\n' ' ls "$RUNTIME_OUTBOUNDS_DIR" > "$OUTBOUND_INVENTORY_FILE.spool"' printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'($spool | split("\n") | map(select(endswith(".url") or endswith(".json")) | sub("\\.(url|json)$"; ""))) as $new | .tags = (.tags + $new | unique) | .sources = reduce $new[] as $t (.sources; .[$t] = "runtime")'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' + printf '%s\n' ' jq --rawfile spool "$OUTBOUND_INVENTORY_FILE.spool" '"'"'.disabled = ($spool | split("\n") | map(select(endswith(".disabled")) | sub("\\.disabled$"; ""))) | .excluded = (.excluded + .disabled | unique)'"'"' "$OUTBOUND_INVENTORY_FILE" > "$OUTBOUND_INVENTORY_FILE.tmp"' + printf '%s\n' ' mv "$OUTBOUND_INVENTORY_FILE.tmp" "$OUTBOUND_INVENTORY_FILE"' printf '%s\n' 'fi' printf '%s\n' 'exit 0' } > stub/systemctl @@ -213,6 +215,21 @@ run proxy outbounds rm from-json | grep -q 'Removed outbound: from-json' [ ! -e obd/from-json.json ] + # Without a tag one is made from the link; a tag after the link is a mix-up. + run proxy outbounds add 'vless://u@de.example.net:443#DE%201' > named + grep -q 'Tag: DE-1 (none given' named + grep -q 'Added outbound: DE-1' named + ! run proxy outbounds add http://example.com:1 x 2>/dev/null + run proxy outbounds rm DE-1 > /dev/null + + # Disabling leaves a marker the start script reads; a pin refuses it until enabled. + run proxy outbounds disable own-vps | grep -q 'Disabled: own-vps' + [ -e obd/own-vps.disabled ] + run proxy outbounds | grep -q -- '-own-vps *static, disabled$' + ! run proxy pin own-vps 2>/dev/null + run proxy outbounds enable own-vps | grep -q 'Enabled: own-vps' + [ ! -e obd/own-vps.disabled ] + # Subscriptions use the same spool machinery, verified by cache file. printf '%s\n' '[{},{}]' > cache/extra.json run proxy subs add extra https://example.com/sub | grep -q 'Added subscription: extra (2 proxies)' @@ -596,6 +613,41 @@ touch "$out" ''; + # `proxy-ctl proxy auto forget|clear`, as the runner applies them. + autoproxy-edit = + pkgs.runCommand "proxy-suite-autoproxy-edit-check" { nativeBuildInputs = [ pkgs.jq ]; } '' + edit() { jq -c --arg op "$1" --arg d "$2" -f ${../../modules/proxy-suite/autoproxy-edit.jq} <<<"$3"; } + s='{ + "domains": {"last.fm": {"exit": "a", "host": "www.last.fm"}, "pximg.net": {"exit": "b", "host": "i.pximg.net"}}, + "hosts": {"www.last.fm": {"domain": "last.fm"}, "cdn.last.fm": {"domain": "last.fm"}, "i.pximg.net": {"domain": "pximg.net"}}, + "backlog": {"api.last.fm": {"domain": "last.fm", "hits": 3}, "x.test": {"domain": "x.test", "hits": 1}}, + "slowWant": {"last.fm": 1}, "slowSkip": {"pximg.net": 1}, + "exits": { + "a": {"asn": "AS1", "strikes": {"last.fm": {"why": "refused", "at": 1}, "sekai.test": {"why": "slow", "at": 2}}, "bad": true, + "badBy": ["last.fm refused", "sekai.test slow"]}, + "b": {"asn": "AS2"} + }, + "egress": "203.0.113.1", "lastRun": 5 + }' + + # Forget: every trace of the one domain, and a strike it made no longer counts. + f="$(edit forget last.fm "$s")" + jq -e '(.domains | keys) == ["pximg.net"]' <<<"$f" > /dev/null + jq -e '(.hosts | keys) == ["i.pximg.net"] and (.backlog | keys) == ["x.test"]' <<<"$f" > /dev/null + jq -e '.slowWant == {} and .slowSkip == {"pximg.net": 1}' <<<"$f" > /dev/null + jq -e '.exits.a | .asn == "AS1" and (.bad | not) and .badBy == ["sekai.test slow"]' <<<"$f" > /dev/null + jq -e '.exits.b == {"asn": "AS2"}' <<<"$f" > /dev/null + # A domain it never knew changes nothing. + jq -e --argjson s "$s" '. == $s' <<<"$(edit forget nope.test "$s")" > /dev/null + + # Clear: every route and verdict; the exits, backlog and egress stay. + c="$(edit clear "" "$s")" + jq -e '.domains == {} and .hosts == {} and (has("slowWant") | not) and (has("slowSkip") | not)' <<<"$c" > /dev/null + jq -e '.exits.a | .asn == "AS1" and .strikes == {} and (.bad | not) and .badBy == []' <<<"$c" > /dev/null + jq -e '(.backlog | keys) == ["api.last.fm", "x.test"] and .egress == "203.0.113.1" and .lastRun == 5' <<<"$c" > /dev/null + touch "$out" + ''; + # A probe that exits 0 printing nothing: jq reads "" as no input at all, so the # "error" guard downstream saw "" instead of "error" and let it through to # `--argjson r ""`, which failed every autoProxy run until the state changed. @@ -716,6 +768,67 @@ touch "$out" ''; + # `proxy-ctl proxy outbounds disable` markers, as the start script reads them. + outbound-disabled = + let + inherit + (import ../../modules/proxy-suite/service/script-blocks/outbounds.nix { + lib = pkgs.lib; + inherit pkgs; + jq = "${pkgs.jq}/bin/jq"; + proxyCfg.selectionExclude = [ "ex" ]; + selectionMode = "urltest"; + hybridEnabled = false; + # Relative: the build directory. + pinnedOutboundFile = "pinned"; + runtimeOutboundsDir = "obd"; + singBoxCfg = null; + sshProxyCfg = null; + warpCfg = null; + awgOutbounds = null; + constants = null; + pureXrayEnabled = null; + collapseNamedOutbounds = null; + backend = null; + backendArg = null; + xraySidecarRoutingMark = null; + python3 = null; + parserScriptsPythonPath = null; + buildOutboundPy = null; + mkSubscriptionBlock = null; + mkSubscriptionLoadHelperBlock = null; + runtimeSubscriptionsBlock = null; + }) + selectionBlocks + ; + selection = pkgs.writeShellScript "outbound-selection" '' + set -euo pipefail + ${selectionBlocks} + ''; + in + pkgs.runCommand "proxy-suite-outbound-disabled-check" { nativeBuildInputs = [ pkgs.jq ]; } '' + mkdir obd + export RUNTIME_DIR="$PWD" OUTBOUND_SOURCES_JSON='{}' + export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]' + + # A marker takes its outbound out of selection and drops a pin on it; stale markers do nothing. + touch obd/a.disabled obd/gone.disabled + echo a > pinned + ${selection} 2> err + grep -q "pinned outbound 'a' is disabled" err + jq -e '.pinned == "" and .disabled == ["a"] and .excluded == ["a", "ex"]' outbounds.json > /dev/null + + # With nothing left to select and no pin the start fails, saying how out. + touch obd/b.disabled + ! ${selection} 2> err + grep -q "outbounds enable" err + # A pin on one still enabled carries it. + echo ex > pinned + ${selection} + jq -e '.pinned == "ex" and .disabled == ["a", "b"]' outbounds.json > /dev/null + touch "$out" + ''; + proxy-ctl-amneziawg = pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check" { diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index 3faea31..e1c6cc0 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -57,6 +57,7 @@ let routeModeStateFile = "/run/proxy-suite/route-mode"; pinnedOutboundFile = "/var/lib/proxy-suite/pinned-outbound"; outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; + runtimeOutboundsDir = "/var/lib/proxy-suite/outbounds.d"; subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/sing-box"; subscriptionCacheHelpersBlock = ""; mkSubscriptionFetchBlock = _: ""; @@ -157,7 +158,7 @@ in shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR=" == "/var/lib/proxy-suite/subscriptions.d"; assert pkgs.lib.hasInfix "proxy pin [tag]" minimalProxyCtlScript; - assert pkgs.lib.hasInfix "proxy outbounds add " minimalProxyCtlScript; + assert pkgs.lib.hasInfix "proxy outbounds add [tag] " minimalProxyCtlScript; true ) ]; diff --git a/pkgs/patches/sing-tun-netlink-groups-probe.go b/pkgs/patches/sing-tun-netlink-groups-probe.go new file mode 100644 index 0000000..e2df465 --- /dev/null +++ b/pkgs/patches/sing-tun-netlink-groups-probe.go @@ -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 +} diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 1853132..ba3e60b 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -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 [--detour ] + proxy outbounds add [tag] [--detour ] 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 remove a runtime outbound + proxy outbounds disable|enable 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 [--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 add a subscription at runtime + proxy subs add [tag] add a subscription at runtime; no tag: named after its host proxy subs rm remove a runtime subscription proxy subs link [--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 [/path] [--json] [--keep-going] [--exits a,b | --via tag] find an exit that reaches a domain proxy auto learn probe now and route it if an exit works + proxy auto forget drop what was learned about it: direct until learned again + proxy auto relearn 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] ", "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] ", "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 [--detour ]") + usage("proxy outbounds add [tag] [--detour ]") _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 |rm |test [tag...]|link ]") + usage("proxy outbounds [list|add [tag] |rm |disable |enable |test [tag...]|link ]") 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 = " [--detour ]" if kind == "outbound" else "" - if not tag or not url: - usage(f"proxy {_runtime_noun(kind)} add {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 ------------------------------------------------------- +# +# .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 ") + _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 ") + 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 |rm |link ]") + usage("proxy subs [list|update|add [tag] |rm |link ]") # --- 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 ") - 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 ") + _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} ") + 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 ------------------------------------------------------------------- diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index eab499a..d7b364a 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -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): diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index 948ba4a..b61263e 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -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] , 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=" "), + Action( + "n", + "add a runtime outbound (tag optional)…", + lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t)], + prompt="[tag] - 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=" ", + prompt="[tag] - 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=" "), + Action( + "n", + "add a runtime subscription (tag optional)…", + lambda r, t, _: ["proxy", "subs", "add", *_add_args(t)], + prompt="[tag] - 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="[/path]", mode="dialog"), Action("E", "learn a domain…", lambda r, t, _: ["proxy", "auto", "learn", t], prompt="", 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): diff --git a/pkgs/proxy-ctl/proxy_tui.py b/pkgs/proxy-ctl/proxy_tui.py index fbce537..14af363 100644 --- a/pkgs/proxy-ctl/proxy_tui.py +++ b/pkgs/proxy-ctl/proxy_tui.py @@ -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"]) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index f19dfce..d9d63c3 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -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): diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index a7f1977..a520b7e 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -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") diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index e38f2c1..8fb3911 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -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()) diff --git a/pkgs/sing-box-rootless-netlink.nix b/pkgs/sing-box-rootless-netlink.nix new file mode 100644 index 0000000..f2e0bd3 --- /dev/null +++ b/pkgs/sing-box-rootless-netlink.nix @@ -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; + }; +})