From 0af4104fdb714ebed655828e2c03b1e97b31ec4f Mon Sep 17 00:00:00 2001 From: fufsob Date: Mon, 14 Sep 2026 05:02:14 +0000 Subject: [PATCH] fix: rewrite proxy-ctl to python --- nix/checks/per-app-routing-proxychains.nix | 6 - nix/checks/per-app-routing-tproxy.nix | 4 - nix/checks/per-app-routing-tun.nix | 9 - nix/checks/per-app-routing-zapret.nix | 4 - nix/checks/repo.nix | 359 +--- nix/checks/route-mode.nix | 6 - pkgs/proxy-ctl-lib.sh | 1589 --------------- pkgs/proxy-ctl.nix | 14 +- pkgs/proxy-ctl.sh | 45 - pkgs/proxy-ctl/completions/_proxy-ctl | 5 + .../completions/proxy-ctl.bash} | 0 pkgs/proxy-ctl/completions/proxy-ctl.fish | 2 + pkgs/proxy-ctl/proxy_ctl.py | 1776 +++++++++++++++++ pkgs/proxy-ctl/test_proxy_ctl.py | 410 ++++ 14 files changed, 2243 insertions(+), 1986 deletions(-) delete mode 100644 pkgs/proxy-ctl-lib.sh delete mode 100644 pkgs/proxy-ctl.sh create mode 100644 pkgs/proxy-ctl/completions/_proxy-ctl rename pkgs/{proxy-ctl-completion.bash => proxy-ctl/completions/proxy-ctl.bash} (100%) create mode 100644 pkgs/proxy-ctl/completions/proxy-ctl.fish create mode 100644 pkgs/proxy-ctl/proxy_ctl.py create mode 100644 pkgs/proxy-ctl/test_proxy_ctl.py diff --git a/nix/checks/per-app-routing-proxychains.nix b/nix/checks/per-app-routing-proxychains.nix index 3b200b6..2138d44 100644 --- a/nix/checks/per-app-routing-proxychains.nix +++ b/nix/checks/per-app-routing-proxychains.nix @@ -98,7 +98,6 @@ in # -- perAppRouting: proxy-ctl script embeds wrap/apps commands -- ( - assert pkgs.lib.hasInfix "help | -h | --help)" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "Usage: proxy-ctl " perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "local proxy backend" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "restart active services" @@ -118,8 +117,6 @@ in # -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds -- ( - assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript; - assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript; assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript; true ) @@ -127,9 +124,6 @@ in # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- ( assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG=-q" perAppRoutingProxychainsScript; - assert pkgs.lib.hasInfix - "exec proxychains4 $PROXYCHAINS_QUIET_ARG -f \"$PROXYCHAINS_CONFIG\" \"$@\"" - perAppRoutingProxychainsScript; true ) ]; diff --git a/nix/checks/per-app-routing-tproxy.nix b/nix/checks/per-app-routing-tproxy.nix index 5e2b42d..b2a9026 100644 --- a/nix/checks/per-app-routing-tproxy.nix +++ b/nix/checks/per-app-routing-tproxy.nix @@ -46,10 +46,6 @@ in # -- perAppRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices -- ( assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED"'' - perAppRoutingTproxyScript; - assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript; true ) diff --git a/nix/checks/per-app-routing-tun.nix b/nix/checks/per-app-routing-tun.nix index 4346309..fa46365 100644 --- a/nix/checks/per-app-routing-tun.nix +++ b/nix/checks/per-app-routing-tun.nix @@ -74,15 +74,6 @@ in # -- perAppRouting: generated proxy-ctl script dispatches tun profiles through systemd slices -- ( assert pkgs.lib.hasInfix "PER_APP_ROUTING_TUN_ENABLED" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" - perAppRoutingTunScript; - assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED"'' - perAppRoutingTunScript; - assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript; - assert pkgs.lib.hasInfix "trap cleanup_slice EXIT" perAppRoutingTunScript; true ) diff --git a/nix/checks/per-app-routing-zapret.nix b/nix/checks/per-app-routing-zapret.nix index 293420e..298ca35 100644 --- a/nix/checks/per-app-routing-zapret.nix +++ b/nix/checks/per-app-routing-zapret.nix @@ -170,10 +170,6 @@ in # -- perAppRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices -- ( assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; - assert pkgs.lib.hasInfix - ''_wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED"'' - perAppRoutingZapretScript; - assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript; true ) diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index 5d9f161..106d80d 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -46,16 +46,14 @@ pkgs.runCommand "proxy-suite-proxy-ctl-subscription-list-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.gawk pkgs.jq ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" - chmod +x "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} mkdir -p cache printf '%s\n' '["plain","hybrid","bad"]' > tags.json @@ -78,10 +76,10 @@ PROXYCHAINS_QUIET_ARG="" \ ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ DEFAULT_ROUTE_MODE="blacklist" \ - bash "$proxy_ctl" proxy subs list > output + python3 "$proxy_ctl" proxy subs list > output # The old spelling still dispatches. env SUB_TAGS_FILE="$PWD/tags.json" SUB_CACHE_DIR="$PWD/cache" \ - bash "$proxy_ctl" subscription list | cmp - output + python3 "$proxy_ctl" subscription list | cmp - output awk '$1 == "plain" { found = 1; if ($NF != "2") exit 1 } END { exit found ? 0 : 1 }' output awk '$1 == "hybrid" { found = 1; if ($NF != "3") exit 1 } END { exit found ? 0 : 1 }' output @@ -94,7 +92,7 @@ pkgs.runCommand "proxy-suite-proxy-ctl-outbounds-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.curl pkgs.gawk @@ -103,9 +101,7 @@ ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" - chmod +x "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} # systemd is not in the sandbox. The reload stub stands in for the start # script, which is what actually republishes the inventory. @@ -149,7 +145,7 @@ PROXYCHAINS_QUIET_ARG="" \ ROUTE_MODE_STATE_FILE="$PWD/route-mode" \ DEFAULT_ROUTE_MODE="blacklist" \ - bash "$proxy_ctl" "$@" + python3 "$proxy_ctl" "$@" } # Listing works from the inventory alone, with no Clash API answering. @@ -213,15 +209,14 @@ pkgs.runCommand "proxy-suite-proxy-ctl-zapret-auto-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.gawk pkgs.gnugrep ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} state="$PWD/state" mkdir -p "$state" @@ -230,7 +225,7 @@ : > "$state/zapret-hosts-user-exclude.txt" run() { - env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto "$@" + env ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto "$@" } run list | grep -qx blocked.example @@ -266,14 +261,14 @@ printf 'AS12389\n' > "$state/cutoff/egress" printf '24940\n14061\n' > "$state/cutoff/asn.txt" printf '24940\t300.ya.ru\n' > "$state/cutoff/sni.txt" - cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret cutoff) + cutoff=$(env ZAPRET_CUTOFF_ENABLED=1 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret cutoff) printf '%s\n' "$cutoff" | grep -q 'from AS12389$' printf '%s\n' "$cutoff" | grep -qx 'Cutoff: 2 network(s)' printf '%s\n' "$cutoff" | grep -qE '^ AS24940 +300\.ya\.ru$' printf '%s\n' "$cutoff" | grep -qE '^ AS14061 +no name - proxy fallback$' # Without the zapret2 engine there is nothing to inspect. - ! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" bash "$proxy_ctl" zapret auto list + ! env ZAPRET_AUTO_ENABLED=0 ZAPRET_STATE_DIR="$state" python3 "$proxy_ctl" zapret auto list touch "$out" ''; @@ -282,7 +277,7 @@ pkgs.runCommand "proxy-suite-proxy-ctl-complete-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.gawk pkgs.gnugrep @@ -290,8 +285,7 @@ ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} printf '%s\n' '["home","work"]' > awg.json jq -n '[{name:"torrent",route:"direct"}]' > profiles.json @@ -301,11 +295,11 @@ env AWG_PROFILES_FILE="$PWD/awg.json" \ PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \ OUTBOUND_INVENTORY_FILE="$PWD/inventory.json" \ - bash "$proxy_ctl" __complete "$@" + python3 "$proxy_ctl" __complete "$@" } # Every group the help lists must complete, or the table has drifted. - bash "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups + python3 "$proxy_ctl" help | awk '/^ [a-z]/ { print $1 }' | sort -u > groups run > top while read -r group; do grep -qx "$group" top || { echo "help lists $group, completion does not" >&2; exit 1; } @@ -330,7 +324,12 @@ # A shell completing must never die, however unreadable the state is. run inbounds link | cmp - /dev/null - env AWG_PROFILES_FILE=/nonexistent bash "$proxy_ctl" __complete awg on + env AWG_PROFILES_FILE=/nonexistent python3 "$proxy_ctl" __complete awg on + + # Every shell's completion file at least parses. + bash -n ${../../pkgs/proxy-ctl/completions/proxy-ctl.bash} + ${pkgs.zsh}/bin/zsh -n ${../../pkgs/proxy-ctl/completions/_proxy-ctl} + HOME="$TMPDIR" ${pkgs.fish}/bin/fish --no-execute ${../../pkgs/proxy-ctl/completions/proxy-ctl.fish} touch "$out" ''; @@ -339,15 +338,14 @@ pkgs.runCommand "proxy-suite-proxy-ctl-where-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.gnugrep pkgs.jq ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} mkdir -p ap zap jq -n '{domains:{"spotify.com":{exit:"community-de",host:"open.spotify.com",at:0}}}' > ap/state.json @@ -358,7 +356,7 @@ run() { env AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$PWD/ap" \ ZAPRET_AUTO_ENABLED=1 ZAPRET_STATE_DIR="$PWD/zap" \ - bash "$proxy_ctl" where "$@" + python3 "$proxy_ctl" where "$@" } # Piping into `grep -q` would race the script against SIGPIPE. @@ -382,248 +380,19 @@ # A URL is accepted where a hostname is. verdict https://open.spotify.com/track/x '^ domain *open.spotify.com$' - ! bash "$proxy_ctl" where 2>/dev/null + ! python3 "$proxy_ctl" where 2>/dev/null touch "$out" ''; - # The verdict table, fed tuples measured on a real censored network. - proxy-ctl-proxy-probe = - pkgs.runCommand "proxy-suite-proxy-ctl-proxy-probe-check" - { - nativeBuildInputs = [ - pkgs.bash - pkgs.coreutils - pkgs.gnugrep - pkgs.jq - ]; - } - '' - cat > "$TMPDIR/test.sh" <<'EOF' - set -euo pipefail - . ${../../pkgs/proxy-ctl-lib.sh} - - expect() { - local want="$1" direct="$2" via="$3" got - got="$(_probe_verdict "$direct" "$via")" - if [ "$got" != "$want" ]; then - echo "FAIL: expected $want, got $got" >&2 - echo " direct=$direct" >&2 - echo " proxy =$via" >&2 - exit 1 - fi - } - - # Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt. - expect destination '0|0.146175|403|6633|' '0|0.230116|200|4302|' - - # The same through a redirect: claude.ai/robots.txt. - expect destination \ - '0|0.141625|302|143|https://claude.com/app-unavailable-in-region' \ - '0|0.181276|200|281|' - - # TLS never completed: censorship, zapret's job. - expect censor '35|0.000000|000|0|' '0|0.119348|200|6258|' - - # Handshake, then silence: the post-handshake throttle. - expect censor '0|0.125029|000|0|' '0|0.143772|200|32881|' - - # Direct works. Nothing to do, whoever else also works. - expect ok '0|0.099546|200|2678|' '0|0.146822|200|2678|' - - # robots.txt legitimately absent is not a failure. - expect ok '0|0.161330|404|559|' '0|0.214667|404|559|' - - # An ordinary redirect must not read as a block. - expect ok \ - '0|0.10|301|0|https://www.example.com/robots.txt' \ - '0|0.20|301|0|https://www.example.com/robots.txt' - - # Refused everywhere: not an egress problem. - expect both-fail '0|0.10|403|100|' '0|0.20|403|100|' - - # Nothing reaches it at all - a dead name, not a blocked one. - expect unreachable '6|0.000000|000|0|' '35|0.000000|000|0|' - - # --- redirect chains --- - # spotify.com: the block is four same-site hops in. - curl() { - local url - for url; do :; done - echo x >> "$TMPDIR/curl-calls" - case "$url" in - https://spotify.test/) printf '0|0.1|301|0|https://www.spotify.test/' ;; - https://www.spotify.test/) printf '0|0.1|301|0|https://open.spotify.test/' ;; - https://open.spotify.test/) printf '0|0.1|302|93|https://accounts.spotify.test/login' ;; - https://accounts.spotify.test/login) - printf '0|0.1|301|0|https://www.spotify.test/int/why-not-available/' ;; - https://redir.test/) printf '0|0.1|301|0|https://elsewhere.example/' ;; - https://loop.test/) printf '0|0.1|301|0|https://loop.test/' ;; - *) printf '0|0.1|200|10|' ;; - esac - } - test "$(_probe_exit_verdict "$(_probe_fetch spotify.test / --noproxy '*')")" = blocked - # Leaving the site ends the walk. - test "$(_probe_exit_verdict "$(_probe_fetch redir.test / --noproxy '*')")" = ok - # A redirect loop inside the site still stops. - : > "$TMPDIR/curl-calls" - _probe_fetch loop.test / --noproxy '*' > /dev/null - test "$(wc -l < "$TMPDIR/curl-calls")" -le 6 - unset -f curl - - # --- which path decides: the apex, robots.txt only breaks ties --- - _svc_active() { return 0; } - # No listener index: only this host and the local proxy. - PROBE_EXITS_FILE=/nonexistent - - # A curl that cannot start is an error, not a dead site. - ! (PROBE_CURL=/nonexistent cmd_proxy_probe --json x.test) 2> "$TMPDIR/curl-err" - grep -q 'Cannot run /nonexistent' "$TMPDIR/curl-err" - - probe_with() { - # $1 apex-direct $2 apex-proxy $3 robots-direct $4 robots-proxy - _probe_fetch() { - case "$2" in - /) [ "$3" = --noproxy ] && printf '%s' "$APEX_DIRECT" || printf '%s' "$APEX_PROXY" ;; - *) [ "$3" = --noproxy ] && printf '%s' "$ROBOTS_DIRECT" || printf '%s' "$ROBOTS_PROXY" ;; - esac - } - APEX_DIRECT="$1" APEX_PROXY="$2" ROBOTS_DIRECT="$3" ROBOTS_PROXY="$4" \ - cmd_proxy_probe --json example.test - } - - # last.fm: apex geo-blocked, robots.txt served everywhere. - out="$(probe_with '0|0.11|403|424|' '0|0.17|200|59809|' '0|0.11|200|400|' '0|0.17|200|400|')" - grep -q '"verdict":"destination"' <<<"$out" - grep -q '"url":"https://example.test/"' <<<"$out" - - # chatgpt.com: apex 403 everywhere, robots.txt separates. - out="$(probe_with '0|0.14|403|6633|' '0|0.23|403|8442|' '0|0.14|403|6633|' '0|0.23|200|4302|')" - grep -q '"verdict":"destination"' <<<"$out" - grep -q '"url":"https://example.test/robots.txt"' <<<"$out" - - # A working apex is never second-guessed by the fallback path. - # set -e: proxy-ctl runs under it, and $() does not inherit it. - out="$(set -e; probe_with '0|0.10|200|500|' '0|0.20|200|500|' '0|0.10|403|10|' '0|0.20|200|10|')" - grep -q '"verdict":"ok"' <<<"$out" - - # --- walking more than two exits --- - # Direct and the first proxy share a WAF; only the third exit gets through. - printf '%s' '[{"i":0,"tag":"direct","port":18540}, - {"i":1,"tag":"fi","port":18541},{"i":2,"tag":"de","port":18542}]' \ - > "$TMPDIR/exits.json" - PROBE_EXITS_FILE="$TMPDIR/exits.json" - _probe_fetch() { - # every exit, direct included, goes through its pinned listener - case "$4" in - *:18540 | *:18541) printf '0|0.10|403|919|' ;; - *:18542) printf '0|0.10|200|500|' ;; - esac - } - out="$(cmd_proxy_probe --json sekai.test)" - jq -e '.verdict == "destination" and .exit == "de"' <<<"$out" > /dev/null - - # --keep-going tries every exit but keeps the first that worked. - out="$(cmd_proxy_probe --json --keep-going --exits de,fi sekai.test)" - jq -e '.exit == "de" and [.exits[].tag] == ["direct", "de", "fi", "direct", "de", "fi"]' \ - <<<"$out" > /dev/null - - # --exits restricts and orders the walk; direct is always tried first. - out="$(cmd_proxy_probe --json --exits de sekai.test)" - jq -e '[.exits[].tag] == ["direct", "de"]' <<<"$out" > /dev/null - - # An empty list probes direct only (every exit shares one network). - out="$(cmd_proxy_probe --json --exits "" sekai.test)" - jq -e '([.exits[].tag] | unique) == ["direct"] and .exit == null' <<<"$out" > /dev/null - - # --via: can this exit carry what direct reaches? - out="$(cmd_proxy_probe --json --via de sekai.test)" - jq -e '.verdict == "ok" and ([.exits[].tag] | unique) == ["de", "direct"]' <<<"$out" > /dev/null - out="$(cmd_proxy_probe --json --via fi sekai.test)" - jq -e '.verdict == "blocked"' <<<"$out" > /dev/null - ! (cmd_proxy_probe --json --via nowhere sekai.test) 2> /dev/null - # A given path is probed as is, for that probe only. - out="$(cmd_proxy_probe --json --via de sekai.test/robots.txt)" - jq -e '.url == "https://sekai.test/robots.txt" and ([.exits[].path] | unique) == ["/robots.txt"]' \ - <<<"$out" > /dev/null - out="$(cmd_proxy_probe --json --via fi sekai.test)" - jq -e '([.exits[].path] | unique) == ["/", "/robots.txt"]' <<<"$out" > /dev/null - - # Refused a front page direct gets: not a stand-in (www.reddit.com). - _probe_fetch() { - case "$4:$2" in - *:18541:/) printf '0|0.10|403|190240|' ;; - *) printf '0|0.10|200|500|' ;; - esac - } - out="$(cmd_proxy_probe --json --via fi geo.test)" - jq -e '.verdict == "blocked"' <<<"$out" > /dev/null - # i.pximg.net: the front page is 400 everywhere, so robots.txt decides. - _probe_fetch() { - case "$2" in - /) printf '0|0.10|400|0|' ;; - *) printf '0|0.10|200|43|' ;; - esac - } - out="$(cmd_proxy_probe --json --via fi cdn.test)" - jq -e '.verdict == "ok"' <<<"$out" > /dev/null - - # --- proxy-ctl proxy auto learn --- - learn_dir="$TMPDIR/learn" - mkdir -p "$learn_dir" - systemctl() { - # stands in for the requests-only run - printf '%s' '{"domains":{"last.fm":{"verdict":"destination","exit":"primary","host":"www.last.fm"}}, - "hosts":{"www.last.fm":{"domain":"last.fm","verdict":"destination","exit":"primary"}}}' \ - > "$learn_dir/state.json" - } - ! (AUTOPROXY_ENABLED=0 cmd_proxy_learn www.last.fm) 2> /dev/null - # It lands in a root-owned file and then in a URL: hostnames only. - ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn 'x;rm -rf /') 2> /dev/null - ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn '-evil.test/path') 2> /dev/null - out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm)" - test "$(cat "$learn_dir/requests")" = www.last.fm - grep -q 'last.fm: destination - routed via primary' <<<"$out" - - # A verdict that routes nothing is kept for its host and reported. - systemctl() { - printf '%s' '{"domains":{}, - "hosts":{"api.example.test":{"domain":"example.test","verdict":"ok","exit":null}}}' \ - > "$learn_dir/state.json" - } - out="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn api.example.test)" - grep -q 'api.example.test: ok - nothing to route' <<<"$out" - - # A failed run is reported in plain words, and the request is not lost. - systemctl() { return 1; } - : > "$learn_dir/requests" - ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learn www.last.fm) 2> "$TMPDIR/learn-err" - grep -q 'still queued' "$TMPDIR/learn-err" - grep -qx www.last.fm "$learn_dir/requests" - - # --- queue and learned ---------------------------------------------- - systemctl() { return 0; } - printf '%s' '{"domains":{"spotify.com":{"verdict":"destination","exit":"primary","host":"www.spotify.com","at":0}}, - "hosts":{"www.spotify.com":{"domain":"spotify.com","verdict":"destination","exit":"primary"}, - "gew1-spclient.spotify.com":{"domain":"spotify.com","verdict":"ok","exit":null}}, - "backlog":{"a.example":{"domain":"example","hits":2},"b.example":{"domain":"example","hits":9}}}' \ - > "$learn_dir/state.json" - q="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue)" - grep -qx ' www.last.fm' <<<"$q" - # Most-dialled first. - test "$(grep -oE '[ab]\.example' <<<"$q" | head -n 1)" = b.example - l="$(AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_learned)" - grep -q 'spotify.com .*-> primary' <<<"$l" - grep -q 'ok=1' <<<"$l" - # An unreadable state directory asks for sudo. - chmod 000 "$learn_dir" - ! (AUTOPROXY_ENABLED=1 AUTOPROXY_STATE_DIR="$learn_dir" cmd_proxy_queue) 2> "$TMPDIR/q-err" - chmod 755 "$learn_dir" - grep -q 'enable userControl, or run with sudo' "$TMPDIR/q-err" - EOF - bash "$TMPDIR/test.sh" - touch "$out" - ''; + # proxy_ctl.py's function-level tests: the probe verdict table and exit walk, + # autoProxy learn/queue, inbound stats and subscriptions, apps run. + proxy-ctl-unit = + pkgs.runCommand "proxy-suite-proxy-ctl-unit-check" { nativeBuildInputs = [ pkgs.python3 ]; } '' + export PYTHONDONTWRITEBYTECODE=1 + python ${../../pkgs/proxy-ctl}/test_proxy_ctl.py + touch "$out" + ''; # autoProxy slowness routing: sampler and judge. autoproxy-slowness = @@ -685,17 +454,11 @@ touch "$out" ''; - # Per-user inbound traffic: collection and `proxy-ctl inbounds stats`. + # Per-user inbound traffic collection; `proxy-ctl inbounds stats` is in proxy-ctl-unit. inbound-stats = pkgs.runCommand "proxy-suite-inbound-stats-check" { - nativeBuildInputs = [ - pkgs.bash - pkgs.coreutils - pkgs.gawk - pkgs.gnugrep - pkgs.jq - ]; + nativeBuildInputs = [ pkgs.jq ]; } '' add=${../../modules/proxy-suite/inbound-stats-add.jq} @@ -716,40 +479,6 @@ old="$(jq -c '.days["2024-01-01"] = {fufsob: {up: 1}}' <<<"$s")" jq -e '.days["2024-01-01"] == null' <<<"$(a '{}' "$old")" > /dev/null - jq -c '.days["2026-09-10"] = {fufsob: {down: 1073741824, up: 1048576}}' <<<"$s" > "$TMPDIR/stats.json" - cat > "$TMPDIR/test.sh" <<'EOF' - set -euo pipefail - . ${../../pkgs/proxy-ctl-lib.sh} - id() { echo 1000; } - date() { echo 2026-09-10; } - export INBOUNDS_STATS_FILE="$TMPDIR/stats.json" - out="$(_inbound_stats 2)" - printf '%s\n' "$out" - # Newest day first, sizes readable, then totals over the period. - test "$(grep -oE '^ 2026-09-1[01]' <<<"$out" | head -n 1)" = " 2026-09-11" - grep -qE '^ 2026-09-11 +fufsob +5\.7 MiB +4 KiB$' <<<"$out" - grep -qE '^ 2026-09-11 +phone +0 B +0 B$' <<<"$out" - grep -qE '^ 2026-09-10 +fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out" - grep -qE '^ fufsob +1\.0 GiB +1\.0 MiB$' <<<"$out" - ! (_inbound_stats 0) 2> /dev/null - # Nothing collected yet says so, rather than printing an empty table. - ! (INBOUNDS_STATS_FILE="$TMPDIR/none.json" _inbound_stats 7) 2> "$TMPDIR/err" - grep -q 'No traffic recorded yet' "$TMPDIR/err" - - # --- proxy-ctl inbounds sub ----------------------------------------- - printf '%s' '[{"user":"fufsob","token":"aaa"},{"user":"teri","token":"bbb"}]' > "$TMPDIR/subs.json" - export INBOUNDS_SUBS_FILE="$TMPDIR/subs.json" - test "$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub/ _inbound_subscriptions teri)" = https://vpn.example/sub/bbb - # Without a user: names only, never a token. - out="$(INBOUNDS_SUB_BASE_URL=https://vpn.example/sub _inbound_subscriptions 2> /dev/null)" - test "$(wc -l <<<"$out")" = 2 - ! grep -qE 'aaa|bbb' <<<"$out" - ! (_inbound_subscriptions nobody) 2> /dev/null - # Without a base URL: the file path, and no QR code. - test "$(INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob 2> /dev/null)" = "$TMPDIR/subs/aaa" - ! (INBOUNDS_SUB_BASE_URL= _inbound_subscriptions fufsob --qr) 2> /dev/null - EOF - bash "$TMPDIR/test.sh" touch "$out" ''; @@ -757,16 +486,14 @@ pkgs.runCommand "proxy-suite-proxy-ctl-amneziawg-check" { nativeBuildInputs = [ - pkgs.bash + pkgs.python3 pkgs.coreutils pkgs.gnugrep pkgs.jq ]; } '' - proxy_ctl="$TMPDIR/proxy-ctl" - cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl" - chmod +x "$proxy_ctl" + proxy_ctl=${../../pkgs/proxy-ctl/proxy_ctl.py} mkdir -p bin cat > bin/systemctl <<'SH' @@ -797,17 +524,17 @@ export SYSTEMCTL_LOG="$PWD/systemctl.log" export AWG_PROFILES_FILE="$PWD/awg-profiles.json" - bash "$proxy_ctl" awg list > list-output + python3 "$proxy_ctl" awg list > list-output grep -q 'home.*active' list-output grep -q 'work.*inactive' list-output - bash "$proxy_ctl" awg on work - bash "$proxy_ctl" awg off home - bash "$proxy_ctl" awg restart home + python3 "$proxy_ctl" awg on work + python3 "$proxy_ctl" awg off home + python3 "$proxy_ctl" awg restart home grep -q '^start proxy-suite-awg-work$' "$SYSTEMCTL_LOG" grep -q '^stop proxy-suite-awg-home$' "$SYSTEMCTL_LOG" grep -q '^restart proxy-suite-awg-home$' "$SYSTEMCTL_LOG" - if bash "$proxy_ctl" awg on missing 2> error-output; then + if python3 "$proxy_ctl" awg on missing 2> error-output; then exit 1 fi grep -q 'Unknown AmneziaWG profile' error-output diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index 1fcf47b..e787e29 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -82,12 +82,6 @@ in ( assert pkgs.lib.hasInfix "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"'' - minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''printf 'default_route_mode=%s\n' "$(_route_mode_default)"'' - minimalProxyCtlScript; - assert pkgs.lib.hasInfix ''systemctl start "proxy-suite-route-mode@''${action}.service"'' - minimalProxyCtlScript; true ) diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh deleted file mode 100644 index ca9d915..0000000 --- a/pkgs/proxy-ctl-lib.sh +++ /dev/null @@ -1,1589 +0,0 @@ -ALL_SERVICES=( - proxy-suite-socks - proxy-suite-tproxy - proxy-suite-tun - proxy-suite-inbounds - proxy-suite-ssh-proxy - proxy-suite-tg-ws-proxy - proxy-suite-zapret-vm-exempt - zapret-discord-youtube -) - -RESTART_SERVICES=( - proxy-suite-tproxy - proxy-suite-tun - proxy-suite-inbounds - proxy-suite-ssh-proxy - proxy-suite-tg-ws-proxy - zapret-discord-youtube -) - -_help() { - cat <<'EOF' -Usage: proxy-ctl [verb] [args] -A group without a verb shows its status or list. - - status [--tray] services and routing mode - restart restart active services - logs [unit] follow logs (default: every proxy-suite unit) - where how this host is routed right now - - proxy [status|on|off] local proxy backend - proxy outbounds [list] outbounds, where each came from, and the pick - proxy outbounds add add an outbound at runtime - proxy outbounds rm remove a runtime outbound - proxy select [|auto] pin the priority outbound (no tag: pick from a menu) - 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 rm remove a runtime subscription - proxy tun [status|on|off] global TUN mode - proxy tproxy [status|on|off] global TProxy mode - proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl) - 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 (sudo) - proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) - - zapret [status|on|off] DPI bypass - zapret auto [list] hosts zapret2 learned as blocked - zapret auto add|forget|exclude - pin, forget, or never learn a host (sudo) - zapret auto clear forget learned hosts and strategies (sudo) - zapret cutoff [status] networks this line cuts at 16 KB, and their names - zapret cutoff probe probe this line again now (sudo) - - awg [list] AmneziaWG profiles and their state - awg on | off [profile] | restart [profile] - - ssh [status|on|off] SSH SOCKS5 tunnel - - apps [list] per-app routing profiles - apps run -- [args] run a command through a profile - - inbounds [list] server inbounds - inbounds link [user] [--qr] client share link - inbounds sub [user] [--qr] subscription users, or one user's URL - inbounds stats [days] traffic per user (sudo, or userControl) -EOF -} - -# Completion candidates for the words already typed, one per line. The tree -# lives here, next to _help, not in the completion file. -_complete_tree() { - local profile - case "$*" in - "") printf '%s\n' status restart logs where proxy zapret awg ssh apps inbounds help ;; - proxy) printf '%s\n' status on off outbounds select mode subs tun tproxy auto ;; - "proxy outbounds") printf '%s\n' list add rm ;; - "proxy outbounds rm") _runtime_tags outbound ;; - "proxy subs") printf '%s\n' list update add rm ;; - "proxy subs rm") _runtime_tags subscription ;; - "proxy select") printf 'auto\n'; _outbound_tags ;; - "proxy mode") printf '%s\n' default whitelist blacklist all-proxy all-bypass ;; - "proxy tun" | "proxy tproxy" | ssh) printf '%s\n' status on off ;; - zapret) printf '%s\n' status on off auto cutoff ;; - "proxy auto") printf '%s\n' list probe learn queue ;; - "zapret auto") printf '%s\n' list add forget exclude clear ;; - "zapret cutoff") printf '%s\n' status probe ;; - "zapret auto forget" | "zapret auto exclude") cat "$(_zapret_auto_file zapret-hosts-auto.txt)" ;; - awg) printf '%s\n' list on off restart ;; - "awg on" | "awg off" | "awg restart") printf '%s\n' "${AWG_PROFILES[@]}" ;; - apps) printf '%s\n' list run ;; - "apps run") jq -r '.[].name' "$PER_APP_ROUTING_PROFILES_FILE" ;; - inbounds) printf '%s\n' list link sub stats ;; - "inbounds link") jq -r '.[].tag' "$INBOUNDS_LINKS_FILE" | sort -u ;; - "inbounds sub") jq -r '.[].user' "$INBOUNDS_SUBS_FILE" ;; - logs) - printf '%s\n' "${ALL_SERVICES[@]}" - for profile in "${AWG_PROFILES[@]}"; do - _awg_service "$profile" - echo - done - ;; - where) jq -r '(.domains // {}) | keys[]' "$(_autoproxy_dir)/state.json" ;; - esac -} - -# The hidden verb the installed bash completion calls. Completing must never -# die or say anything, however unreadable the state behind an arm is. -cmd_complete() { - _complete_tree "$@" 2>/dev/null || true -} - -_die() { - echo "$*" >&2 - exit 1 -} - -_usage() { - _die "Usage: proxy-ctl $*" -} - -_bool() { - if "$@"; then printf true; else printf false; fi -} - -_svc_exists() { - systemctl cat "$1" &>/dev/null -} - -_svc_active() { - systemctl is-active --quiet "$1" -} - -_svc_status() { - _svc_exists "$1" || return 0 - printf " %-44s %s\n" "$1" "$(systemctl is-active "$1" 2>/dev/null || true)" -} - -_stop_if_exists() { - if _svc_exists "$1"; then systemctl stop "$1" || true; fi -} - -_toggle() { - local unit="$1" name="$2" verb="${3:-status}" - _svc_exists "$unit" || _die "$name is not enabled in this configuration." - case "$verb" in - status) systemctl is-active "$unit" || true ;; - on) systemctl start "$unit" ;; - off) systemctl stop "$unit" ;; - *) _usage "$name [status|on|off]" ;; - esac -} - -# Prints the QR code instead when $2 is 1. -_emit() { - if [ "$2" = 1 ]; then - printf '%s' "$1" | qrencode -t ANSIUTF8 - else - printf '%s\n' "$1" - fi -} - -# --- status ------------------------------------------------------------------ - -_route_mode_default() { - printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}" -} - -_route_mode_effective() { - local mode="" - if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then - mode=$(tr -d '\r\n[:space:]' < "${ROUTE_MODE_STATE_FILE}" 2>/dev/null || true) - fi - case "$mode" in - whitelist|blacklist|all-proxy|all-bypass) printf '%s' "$mode" ;; - *) _route_mode_default ;; - esac -} - -_route_mode_current() { - if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then - _route_mode_effective - else - printf 'default' - fi -} - -_route_mode_label() { - case "$1" in - default) printf 'Default (%s)' "$(_route_mode_label "$(_route_mode_default)")" ;; - whitelist) printf 'Whitelist (direct by default)' ;; - blacklist) printf 'Blacklist (proxy by default)' ;; - all-proxy) printf 'All Proxy (override)' ;; - all-bypass) printf 'All Bypass (override)' ;; - *) printf 'Unknown' ;; - esac -} - -_status_tray() { - local pair key svc - for pair in \ - socks:proxy-suite-socks \ - tproxy:proxy-suite-tproxy \ - tun:proxy-suite-tun \ - zapret:zapret-discord-youtube; do - key="${pair%%:*}" - svc="${pair##*:}" - printf '%s_available=%s\n' "$key" "$(_bool _svc_exists "$svc")" - printf '%s_active=%s\n' "$key" "$(_bool _svc_active "$svc")" - done - printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)" - printf 'route_mode_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)" - printf 'route_mode=%s\n' "$(_route_mode_current)" - printf 'default_route_mode=%s\n' "$(_route_mode_default)" - printf 'awg_available=%s\n' "$(_bool test "${#AWG_PROFILES[@]}" -gt 0)" - printf 'awg_active=%s\n' "$(_active_awg_profiles | head -n1)" - printf 'awg_profiles=%s\n' "$(IFS=,; echo "${AWG_PROFILES[*]}")" -} - -_status_row() { - printf " %-44s %s\n" "$1" "$2" -} - -# Nothing to say about a state that is absent or unreadable. -_status_row_if() { - [ -z "$2" ] || _status_row "$1" "$2" -} - -# The pin when there is one, otherwise whatever the backend is dialling. -_status_outbound() { - local pinned current - pinned="$(_outbound_inventory | jq -r '.pinned // ""' 2>/dev/null || true)" - if [ -n "$pinned" ]; then - printf '%s (pinned)' "$pinned" - return - fi - current="$(_outbound_current)" - if [ -n "$current" ]; then printf '%s' "$current"; fi -} - -_status_autoproxy() { - local state next - [ "${AUTOPROXY_ENABLED:-0}" = 1 ] || return 0 - state="$(_autoproxy_dir)/state.json" - [ -r "$state" ] || return 0 - printf '%s routed, %s queued' \ - "$(jq '(.domains // {}) | length' "$state" 2>/dev/null || echo '?')" \ - "$(jq '(.backlog // {}) | length' "$state" 2>/dev/null || echo '?')" - next="$(_autoproxy_next_run)" - if [ -n "$next" ]; then printf ', next run %s' "$(_in_time "$next")"; fi -} - -_status_zapret() { - local auto - [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ] || return 0 - auto="$(_zapret_auto_file zapret-hosts-auto.txt)" - [ -r "$auto" ] || return 0 - printf '%s learned' "$(grep -c . "$auto" || true)" -} - -cmd_status() { - if [ "${1:-}" = "--tray" ]; then - _status_tray - return - fi - local svc profile - echo "proxy-suite services:" - for svc in "${ALL_SERVICES[@]}"; do - _svc_status "$svc" - done - for profile in "${AWG_PROFILES[@]}"; do - _svc_status "$(_awg_service "$profile")" - done - if _svc_exists proxy-suite-socks || [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ]; then - echo "" - echo "routing:" - if _svc_exists proxy-suite-socks; then - _status_row "active mode" "$(_route_mode_label "$(_route_mode_current)")" - _status_row_if "outbound" "$(_status_outbound)" - _status_row_if "autoProxy" "$(_status_autoproxy)" - fi - _status_row_if "zapret2" "$(_status_zapret)" - fi -} - -# Restarts what is running; starting something that was stopped on purpose is -# what `proxy on` is for. -cmd_restart() { - local svc profile - if _svc_exists proxy-suite-socks && _svc_active proxy-suite-socks; then - systemctl restart proxy-suite-socks - fi - for svc in "${RESTART_SERVICES[@]}"; do - if _svc_exists "$svc" && _svc_active "$svc"; then - systemctl restart "$svc" - fi - done - for profile in "${AWG_PROFILES[@]}"; do - if _svc_active "$(_awg_service "$profile")"; then - systemctl restart "$(_awg_service "$profile")" - fi - done -} - -# --- proxy ------------------------------------------------------------------- - -cmd_proxy() { - local verb="${1:-status}" - shift || true - case "$verb" in - status | on) _toggle proxy-suite-socks proxy "$verb" ;; - off) - _svc_exists proxy-suite-socks || _die "proxy is not enabled in this configuration." - _stop_if_exists proxy-suite-tproxy - _stop_if_exists proxy-suite-tun - systemctl stop proxy-suite-socks - ;; - outbounds) cmd_outbounds "$@" ;; - select) cmd_select "$@" ;; - mode) cmd_route_mode "$@" ;; - subs) cmd_subscription "$@" ;; - tun) _toggle proxy-suite-tun "proxy tun" "$@" ;; - tproxy) _toggle proxy-suite-tproxy "proxy tproxy" "$@" ;; - auto) cmd_proxy_auto "$@" ;; - probe | learn | queue | learned) cmd_proxy_auto "$verb" "$@" ;; - *) _usage "proxy [status|on|off|outbounds|select|mode|subs|tun|tproxy|auto]" ;; - esac -} - -cmd_outbounds() { - local verb="${1:-list}" - shift || true - case "$verb" in - list) _outbounds_list ;; - add) _runtime_entry_add outbound "$@" ;; - rm | remove | del) _runtime_entry_rm outbound "$@" ;; - *) _usage "proxy outbounds [list|add |rm ]" ;; - esac -} - -# The inventory the running backend wrote: tags, where each came from, and the -# pin. Absent until the proxy has started once. -_outbound_inventory() { - if [ -r "${OUTBOUND_INVENTORY_FILE:-}" ]; then - cat "$OUTBOUND_INVENTORY_FILE" - else - printf '%s' '{}' - fi -} - -_outbound_tags() { - _outbound_inventory | jq -r '(.tags // [])[]' -} - -_require_outbound_inventory() { - if [ "$(_outbound_inventory | jq -r '(.tags // []) | length')" = 0 ]; then - _die "No outbounds are available yet - is proxy-suite-socks running?" - fi -} - -# What the backend is dialling right now, when it exposes a selector. Empty -# otherwise, which is the normal case for selection = "first" and for XRay. -_outbound_current() { - curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null | jq -r '.now // empty' 2>/dev/null || true -} - -_outbounds_list() { - local inv pinned current selection mark tag source - _require_outbound_inventory - inv=$(_outbound_inventory) - pinned=$(jq -r '.pinned // ""' <<<"$inv") - selection=$(jq -r '.selection // "first"' <<<"$inv") - current=$(_outbound_current) - - echo "Selection: $selection" - if [ -n "$pinned" ]; then - echo "Pinned: $pinned" - else - echo "Pinned: (auto)" - fi - if [ -n "$current" ]; then - echo "Current: $current" - fi - echo "" - printf " %-34s %s\n" "TAG" "SOURCE" - while IFS=$'\t' read -r tag source; do - mark=" " - if [ "$tag" = "$pinned" ]; then - mark="*" - elif [ -z "$pinned" ] && [ "$tag" = "$current" ]; then - mark=">" - fi - printf " %s%-34s %s\n" "$mark" "$tag" "$source" - done < <(jq -r '. as $i | (.tags // [])[] | [., (($i.sources // {})[.] // "-")] | @tsv' <<<"$inv") -} - -# Runs in a command substitution, so anything fatal has to be checked by the -# caller first: an exit here would only leave the subshell. -_select_outbound_menu() { - local inv pinned - inv=$(_outbound_inventory) - pinned=$(jq -r '.pinned // ""' <<<"$inv") - { printf 'auto\n'; jq -r '(.tags // [])[]' <<<"$inv"; } | - fzf --prompt='outbound> ' --height=40% --reverse \ - --header="pinned: ${pinned:-auto} (auto = let the configured selection decide)" -} - -cmd_select() { - local tag="${1:-}" escaped - if [ -z "$tag" ]; then - if [ ! -t 0 ] || [ ! -t 1 ]; then - _usage "proxy select |auto" - fi - _require_outbound_inventory - # Empty when the menu was dismissed. - tag="$(_select_outbound_menu)" || return 0 - [ -n "$tag" ] || return 0 - fi - [ -n "$tag" ] || _usage "proxy select [|auto]" - escaped="$(systemd-escape -- "$tag")" - systemctl start "proxy-suite-outbound-select@${escaped}.service" || - _die "Failed - see: proxy-ctl logs proxy-suite-outbound-select@${escaped}" - if [ "$tag" = auto ]; then - echo "Selecting automatically again." - else - echo "Pinned: $tag" - fi -} - -# --- runtime outbounds and subscriptions ------------------------------------- -# -# One URL per file in a spool directory the userControl group may write. The -# backend reads them at start, which the reload unit triggers. - -_runtime_dir() { - if [ "$1" = outbound ]; then - printf '%s' "${RUNTIME_OUTBOUNDS_DIR:-/var/lib/proxy-suite/outbounds.d}" - else - printf '%s' "${RUNTIME_SUBS_DIR:-/var/lib/proxy-suite/subscriptions.d}" - fi -} - -_runtime_noun() { - if [ "$1" = outbound ]; then printf 'outbounds'; else printf 'subs'; fi -} - -_runtime_tags() { - local dir f tag - dir="$(_runtime_dir "$1")" - [ -d "$dir" ] || return 0 - for f in "$dir"/*.url; do - [ -e "$f" ] || continue - tag="${f##*/}" - printf '%s\n' "${tag%.url}" - done -} - -_check_runtime_tag() { - local kind="$1" tag="$2" t - case "$tag" in - proxy | direct | block) - _die "'$tag' is reserved; pick another $kind tag." - ;; - esac - if ! [[ "$tag" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]]; then - _die "Invalid $kind tag '$tag': letters, digits, dot, dash and underscore only." - fi - if _runtime_tags "$kind" | grep -qxF "$tag"; then - _die "A runtime $kind named '$tag' already exists; remove it first." - fi - if [ "$kind" = outbound ]; then - if _outbound_tags | grep -qxF "$tag"; then - _die "An outbound named '$tag' already exists." - fi - else - for t in "${SUB_TAGS[@]}"; do - if [ "$t" = "$tag" ]; then - _die "A subscription named '$tag' is declared in the configuration." - fi - done - fi -} - -_runtime_entry_add() { - local kind="$1" tag="${2:-}" url="${3:-}" file - if [ -z "$tag" ] || [ -z "$url" ]; then - _usage "proxy $(_runtime_noun "$kind") add " - fi - _check_runtime_tag "$kind" "$tag" - case "$url" in - *[[:space:]]*) _die "A URL cannot contain whitespace." ;; - esac - file="$(_runtime_dir "$kind")/$tag.url" - ( umask 027; printf '%s\n' "$url" > "$file" ) 2>/dev/null || - _die "Cannot write $file - join the ${USER_CONTROL_GROUP:-proxy-suite} group, or re-run with sudo." - _runtime_reload - _runtime_entry_verify "$kind" "$tag" -} - -_runtime_entry_rm() { - local kind="$1" tag="${2:-}" file - [ -n "$tag" ] || _usage "proxy $(_runtime_noun "$kind") rm " - file="$(_runtime_dir "$kind")/$tag.url" - if [ ! -e "$file" ]; then - _die "No runtime $kind named '$tag'. Ones declared in the NixOS configuration are removed there." - fi - rm -f "$file" 2>/dev/null || - _die "Cannot remove $file - join the ${USER_CONTROL_GROUP:-proxy-suite} group, or re-run with sudo." - _runtime_reload - echo "Removed $kind: $tag" -} - -_runtime_reload() { - systemctl start proxy-suite-outbound-reload.service || - _die "Saved, but applying it failed - see: proxy-ctl logs proxy-suite-outbound-reload" -} - -# Only the backend parses the URL, so confirm the entry actually came up. -_runtime_entry_verify() { - local kind="$1" tag="$2" cache - if [ "$kind" = outbound ]; then - if _outbound_tags | grep -qxF "$tag"; then - echo "Added outbound: $tag" - return - fi - else - cache="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}/$tag.json" - if [ -f "$cache" ]; then - echo "Added subscription: $tag ($(_subscription_proxy_count "$cache" 2>/dev/null || echo '?') proxies)" - return - fi - fi - echo "Saved $kind '$tag', but it did not come up. Check: proxy-ctl logs" >&2 - echo "Remove it again with: proxy-ctl proxy $(_runtime_noun "$kind") rm $tag" >&2 - exit 1 -} - -cmd_route_mode() { - local action="${1:-status}" - _svc_exists proxy-suite-socks || _die "proxy is not enabled in this configuration." - case "$action" in - status) _route_mode_current; echo ;; - default|whitelist|blacklist|all-proxy|all-bypass) - systemctl start "proxy-suite-route-mode@${action}.service" - echo "Switched to: $(_route_mode_label "$action")" - ;; - *) _usage "proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]" ;; - esac -} - -_subscription_proxy_count() { - jq ' - if type == "array" then length - elif type == "object" and (.singBox | type == "array") and (.xray | type == "array") - then (.singBox | length) + (.xray | length) - else error("unsupported subscription cache shape") - end - ' "$1" -} - -_subscription_row() { - local tag="$1" source="$2" dir="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}" - local cache="$dir/$tag.json" age count - if [ -f "$cache" ]; then - age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown") - count=$(_subscription_proxy_count "$cache" 2>/dev/null || echo "?") - else - age="(no cache)" - count="-" - fi - printf " %-30s %-22s %-9s %s\n" "$tag" "$age" "$count" "$source" -} - -_subscription_list() { - local t runtime - runtime="$(_runtime_tags subscription)" - if [ ${#SUB_TAGS[@]} -eq 0 ] && [ -z "$runtime" ]; then - echo "No subscriptions configured." - return - fi - printf " %-30s %-22s %-9s %s\n" "TAG" "LAST UPDATED" "PROXIES" "SOURCE" - for t in "${SUB_TAGS[@]}"; do - _subscription_row "$t" static - done - while IFS= read -r t; do - [ -n "$t" ] || continue - _subscription_row "$t" runtime - done <<<"$runtime" -} - -cmd_subscription() { - local verb="${1:-list}" - shift || true - case "$verb" in - list) _subscription_list ;; - add) _runtime_entry_add subscription "$@" ;; - rm | remove | del) _runtime_entry_rm subscription "$@" ;; - update) - _svc_exists proxy-suite-subscription-update || _die "The proxy is not enabled in this configuration." - systemctl start proxy-suite-subscription-update - echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update" - ;; - *) _usage "proxy subs [list|update|add |rm ]" ;; - esac -} - -# --- proxy auto: reachability probe ------------------------------------------ -# -# Fetches a URL through one exit after another (direct first) and finds one -# whose origin answers. The exits are the per-exit loopback listeners -# proxy-suite-socks opens for autoProxy (PROBE_EXITS_FILE); without them, only -# this host and the local proxy. The apex decides when any exit gets content -# from it; robots.txt breaks ties when the apex is refused everywhere. - -PROBE_PATH="${PROBE_PATH:-/}" -PROBE_PATH_FALLBACK="${PROBE_PATH_FALLBACK:-/robots.txt}" -PROBE_UA="${PROBE_UA:-Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe}" -PROBE_EXITS_FILE="${PROBE_EXITS_FILE:-/run/proxy-suite-socks/probe-exits.json}" -PROBE_BLOCK_REDIRECT='unavailable|not-available|blocked|geo|region|restricted' - -# Last two labels: only used to keep redirect following on one site. -_probe_site() { - local host="${1#*://}" - host="${host%%[/:?#]*}" - printf '%s' "$host" | awk -F. '{ print $(NF - 1) "." $NF }' -} - -# $1 domain, $2 path, rest: curl egress selector. Echoes -# "||||" for the -# first hop that is not a same-site redirect: a block can sit at the end of a -# chain (spotify.com -> www -> open -> accounts -> why-not-available). -_probe_fetch() { - local domain="$1" path="$2" url site result hop rc - local -a ua=() - shift 2 - url="https://${domain}${path}" - site="$(_probe_site "$url")" - # An impersonating curl must keep its browser's own User-Agent. - [ -n "${PROBE_CURL:-}" ] || ua=(-A "$PROBE_UA") - for hop in 1 2 3 4 5 6; do - rc=0 - result="$("${PROBE_CURL:-curl}" -sS -o /dev/null \ - "${ua[@]}" \ - --connect-timeout "${PROBE_CONNECT_TIMEOUT:-8}" \ - --max-time "${PROBE_MAX_TIME:-15}" \ - -w '%{exitcode}|%{time_appconnect}|%{http_code}|%{size_download}|%{redirect_url}' \ - "$@" "$url" 2>/dev/null)" || rc=$? - # Not a dead site: curl itself did not start. - if [ -z "$result" ] && [ "$rc" -ge 126 ]; then - _die "Cannot run ${PROBE_CURL:-curl} (exit $rc)." - fi - [ -n "$result" ] || result='99|0|000|0|' - case "$(_probe_field "$result" 3)" in - 3??) ;; - *) break ;; - esac - _probe_redirect_is_block "$result" && break - url="$(_probe_field "$result" 5)" - { [ -n "$url" ] && [ "$(_probe_site "$url")" = "$site" ]; } || break - : "$hop" - done - printf '%s' "$result" -} - -_probe_field() { - printf '%s' "$1" | cut -d'|' -f"$2" -} - -# curl reports appconnect 0 when TLS never finished. -_probe_tls_ok() { - case "$(_probe_field "$1" 2)" in - "" | 0 | 0.000000) return 1 ;; - *) return 0 ;; - esac -} - -_probe_http_ok() { - case "$(_probe_field "$1" 3)" in - 2?? | 401 | 404) return 0 ;; - 3??) ! _probe_redirect_is_block "$1" ;; - *) return 1 ;; - esac -} - -_probe_redirect_is_block() { - printf '%s' "$(_probe_field "$1" 5)" | grep -qiE "$PROBE_BLOCK_REDIRECT" -} - -# dead: failed before the origin spoke (the censor's doing, zapret's job). -# blocked: the origin answered and refused (a proxy hop can fix it). -_probe_exit_verdict() { - if ! _probe_tls_ok "$1" || [ "$(_probe_field "$1" 3)" = "000" ]; then - printf 'dead' - elif _probe_http_ok "$1"; then - printf 'ok' - else - printf 'blocked' - fi -} - -_probe_verdict() { - local direct via - direct="$(_probe_exit_verdict "$1")" - via="$(_probe_exit_verdict "$2")" - if [ "$direct" = ok ]; then - printf 'ok' - elif [ "$via" = ok ]; then - if [ "$direct" = dead ]; then printf 'censor'; else printf 'destination'; fi - elif [ "$direct" = dead ]; then - printf 'unreachable' - else - printf 'both-fail' - fi -} - -_probe_verdict_text() { - case "$1" in - ok) printf 'reachable directly - nothing to do' ;; - destination) printf 'destination-side block - route via %s' "${2:-proxy}" ;; - censor) printf 'censor-side block - zapret2 territory, do not proxy' ;; - both-fail) printf 'fails through every egress - not an egress problem' ;; - unreachable) printf 'no egress reaches it at all' ;; - *) printf 'inconclusive' ;; - esac -} - -_probe_describe() { - local r="$1" status location - if ! _probe_tls_ok "$r"; then - printf 'no TLS (curl exit %s)' "$(_probe_field "$r" 1)" - return - fi - status="$(_probe_field "$r" 3)" - location="$(_probe_field "$r" 5)" - if [ "$status" = "000" ]; then - printf 'TLS %ss, then no response' "$(_probe_field "$r" 2)" - return - fi - printf 'TLS %ss, %s, %s bytes' "$(_probe_field "$r" 2)" "$status" "$(_probe_field "$r" 4)" - [ -n "$location" ] && printf ' -> %s' "$location" - return 0 -} - -# "tagproxy-url" per exit, in order; an empty url means this host. -_probe_exits() { - if [ -r "$PROBE_EXITS_FILE" ]; then - jq -r '.[] | "\(.tag)\thttp://127.0.0.1:\(.port)"' "$PROBE_EXITS_FILE" - else - printf 'direct\t\n' - printf 'proxy\t%s\n' "${LOCAL_PROXY_URL:-http://127.0.0.1:1080}" - fi -} - -_probe_fetch_exit() { - if [ -n "$3" ]; then - _probe_fetch "$1" "$2" --proxy "$3" - else - _probe_fetch "$1" "$2" --noproxy '*' - fi -} - -# Walks EXIT_TAGS/EXIT_URLS (direct first) and stops at the first exit that -# gets content; PROBE_KEEP_GOING=1 still tries the rest, keeping that one. -# Sets WALK_VERDICT, WALK_EXIT, WALK_PATH, WALK_DIRECT, WALK_VIA -# and WALK_ROWS ("tagpathresultjudgement" per request). -_probe_walk() { - local domain="$1" path direct result judgement i first_direct="" - WALK_ROWS=() - WALK_VERDICT="" - WALK_EXIT="" - WALK_VIA="" - for path in "$PROBE_PATH" ${PROBE_PATH_FALLBACK:+"$PROBE_PATH_FALLBACK"}; do - direct="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[0]}")" - judgement="$(_probe_exit_verdict "$direct")" - WALK_ROWS+=("${EXIT_TAGS[0]}"$'\t'"$path"$'\t'"$direct"$'\t'"$judgement") - [ -n "$first_direct" ] || first_direct="$direct" - if [ "$judgement" = ok ] && [ -z "$WALK_VERDICT" ]; then - WALK_VERDICT=ok - WALK_PATH="$path" - WALK_DIRECT="$direct" - [ "${PROBE_KEEP_GOING:-0}" = 1 ] || return 0 - fi - for ((i = 1; i < ${#EXIT_TAGS[@]}; i++)); do - result="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[i]}")" - judgement="$(_probe_exit_verdict "$result")" - WALK_ROWS+=("${EXIT_TAGS[i]}"$'\t'"$path"$'\t'"$result"$'\t'"$judgement") - if [ "$judgement" = ok ] && [ -z "$WALK_VERDICT" ]; then - WALK_VERDICT="$(_probe_verdict "$direct" "$result")" - WALK_EXIT="${EXIT_TAGS[i]}" - WALK_PATH="$path" - WALK_DIRECT="$direct" - WALK_VIA="$result" - [ "${PROBE_KEEP_GOING:-0}" = 1 ] || return 0 - fi - done - done - [ -z "$WALK_VERDICT" ] || return 0 - WALK_PATH="$PROBE_PATH" - WALK_DIRECT="$first_direct" - if [ "$(_probe_exit_verdict "$first_direct")" = dead ]; then - WALK_VERDICT=unreachable - else - WALK_VERDICT=both-fail - fi -} - -# --via: can EXIT_TAGS[1] carry what direct reaches? It must get content on -# some path and fail on none where direct succeeds. Verdict "ok" or "blocked". -_probe_stand_in() { - local domain="$1" path direct via dj vj got=0 - WALK_ROWS=() - WALK_VERDICT=ok - WALK_EXIT="${EXIT_TAGS[1]}" - WALK_PATH="$PROBE_PATH" - for path in "$PROBE_PATH" ${PROBE_PATH_FALLBACK:+"$PROBE_PATH_FALLBACK"}; do - direct="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[0]}")" - via="$(_probe_fetch_exit "$domain" "$path" "${EXIT_URLS[1]}")" - dj="$(_probe_exit_verdict "$direct")" - vj="$(_probe_exit_verdict "$via")" - WALK_ROWS+=("${EXIT_TAGS[0]}"$'\t'"$path"$'\t'"$direct"$'\t'"$dj") - WALK_ROWS+=("${EXIT_TAGS[1]}"$'\t'"$path"$'\t'"$via"$'\t'"$vj") - if [ "$path" = "$PROBE_PATH" ]; then - WALK_DIRECT="$direct" - WALK_VIA="$via" - fi - [ "$vj" != ok ] || got=1 - if [ "$dj" = ok ] && [ "$vj" != ok ]; then WALK_VERDICT=blocked; fi - done - [ "$got" = 1 ] || WALK_VERDICT=blocked -} - -cmd_proxy_probe() { - local json=0 domain="" want="" have_want=0 via="" row tag PROBE_KEEP_GOING=0 - local -a rows wanted - while [ $# -gt 0 ]; do - case "$1" in - --json) json=1 ;; - --keep-going) PROBE_KEEP_GOING=1 ;; - --exits) - want="${2?--exits needs a comma-separated list of exit tags}" - have_want=1 - shift - ;; - --via) - via="${2?--via needs an exit tag}" - want="$via" - have_want=1 - shift - ;; - -*) _die "Unknown option: $1" ;; - *) domain="$1" ;; - esac - shift - done - - [ -n "$domain" ] || _usage "proxy auto probe [/path] [--json] [--keep-going] [--exits a,b | --via tag]" - domain="${domain#*://}" - if [[ "$domain" == */* ]]; then - local PROBE_PATH="/${domain#*/}" PROBE_PATH_FALLBACK="" - domain="${domain%%/*}" - fi - - _svc_active proxy-suite-socks || _die "The local proxy (proxy-suite-socks) is not running; a probe needs its exits." - - # direct first, then every exit in order, or the ones asked for in that order. - mapfile -t rows < <(_probe_exits) - EXIT_TAGS=() - EXIT_URLS=() - for row in "${rows[@]}"; do - if [ "${row%%$'\t'*}" = direct ]; then - EXIT_TAGS+=(direct) - EXIT_URLS+=("${row#*$'\t'}") - fi - done - if [ "$have_want" = 1 ]; then - IFS=, read -ra wanted <<<"$want" - else - wanted=() - for row in "${rows[@]}"; do wanted+=("${row%%$'\t'*}"); done - fi - for tag in "${wanted[@]}"; do - [ "$tag" = direct ] && continue - for row in "${rows[@]}"; do - if [ "${row%%$'\t'*}" = "$tag" ]; then - EXIT_TAGS+=("$tag") - EXIT_URLS+=("${row#*$'\t'}") - break - fi - done - done - if [ "${#EXIT_TAGS[@]}" -eq 0 ] || [ "${EXIT_TAGS[0]}" != direct ]; then - _die "No direct exit to probe from ($PROBE_EXITS_FILE)." - fi - if [ -n "$via" ] && [ "${#EXIT_TAGS[@]}" -ne 2 ]; then - _die "No exit named $via other than direct ($PROBE_EXITS_FILE)." - fi - - if [ -n "$via" ]; then - _probe_stand_in "$domain" - else - _probe_walk "$domain" - fi - - if [ "$json" = 1 ]; then - printf '%s\n' "${WALK_ROWS[@]}" | jq -R -s -c \ - --arg domain "$domain" \ - --arg url "https://${domain}${WALK_PATH}" \ - --arg path "$WALK_PATH" \ - --arg verdict "$WALK_VERDICT" \ - --arg exit "$WALK_EXIT" \ - --arg direct "$WALK_DIRECT" \ - --arg via "$WALK_VIA" ' - (split("\n") | map(select(length > 0) | split("\t") - | {tag: .[0], path: .[1], result: .[2], judgement: .[3]})) as $exits - | {domain: $domain, url: $url, path: $path, verdict: $verdict, - exit: (if $exit == "" then null else $exit end), - direct: $direct, proxy: $via, exits: $exits}' - return - fi - - local t p r j chosen - printf ' domain %s\n' "$domain" - printf ' probe https://%s%s\n' "$domain" "$WALK_PATH" - printf ' exits\n' - for row in "${WALK_ROWS[@]}"; do - IFS=$'\t' read -r t p r j <<<"$row" - chosen="" - [ "$t" = "$WALK_EXIT" ] && [ "$p" = "$WALK_PATH" ] && chosen=" <- chosen" - printf ' %-18s %-12s %-44s %s%s\n' "$t" "$p" "$(_probe_describe "$r")" "$j" "$chosen" - done - if [ -n "$via" ]; then - if [ "$WALK_VERDICT" = ok ]; then - printf ' verdict %s answers it as well as direct does - it can carry it\n' "$via" - else - printf ' verdict %s answers it worse than direct does\n' "$via" - fi - return - fi - printf ' verdict %s\n' "$(_probe_verdict_text "$WALK_VERDICT" "$WALK_EXIT")" - case "$WALK_VERDICT" in - destination) - printf ' pin: proxy.routing.rules = [ { outbound = "%s"; domains = [ "%s" ]; } ]\n' \ - "$WALK_EXIT" "$domain" - ;; - censor) - printf ' try: proxy-ctl zapret auto add %s\n' "$domain" - ;; - esac -} - -_autoproxy_dir() { - printf '%s' "${AUTOPROXY_STATE_DIR:-/var/lib/proxy-suite/autoproxy}" -} - -_require_autoproxy() { - [ "${AUTOPROXY_ENABLED:-0}" = 1 ] || _die "proxy.autoProxy is not enabled in this configuration." -} - -# Root-only without userControl: say so rather than show an empty queue. -_require_autoproxy_readable() { - [ -d "$1" ] || _die "No autoProxy state yet - the prober has not completed a run." - { [ -x "$1" ] && [ -r "$1" ]; } || _die "Cannot read $1 - enable userControl, or run with sudo." -} - -cmd_proxy_auto() { - local verb="${1:-list}" - shift || true - case "$verb" in - list | learned) cmd_proxy_learned ;; - probe) cmd_proxy_probe "$@" ;; - learn) cmd_proxy_learn "$@" ;; - queue) cmd_proxy_queue "$@" ;; - *) _usage "proxy auto [list|probe|learn|queue]" ;; - esac -} - -# The timer is relative, so only list-timers knows the next run. Empty when -# none is armed. -_autoproxy_next_run() { - local next - next="$(systemctl list-timers -o json proxy-suite-autoproxy.timer 2>/dev/null | - jq -r '.[0].next // empty' 2>/dev/null || true)" - if [ -n "$next" ] && [ "$next" != 0 ]; then printf '%s' "$((next / 1000000))"; fi -} - -_in_time() { - local left=$(($1 - $(date +%s))) - if [ "$left" -lt 60 ]; then printf 'under a minute'; else printf 'in %s min' "$((left / 60))"; fi -} - -cmd_proxy_queue() { - local dir top="${1:-20}" waiting next - _require_autoproxy - [[ "$top" =~ ^[0-9]+$ ]] || _usage "proxy auto queue [count]" - dir="$(_autoproxy_dir)" - _require_autoproxy_readable "$dir" - - echo "Requested with proxy-ctl proxy auto learn:" - if [ -s "$dir/requests" ] || [ -s "$dir/requests.taking" ]; then - cat "$dir/requests" "$dir/requests.taking" 2>/dev/null | awk '{ print " " $0 }' - else - echo " (none)" - fi - - waiting="$(jq '(.backlog // {}) | length' "$dir/state.json" 2>/dev/null || echo 0)" - echo "" - echo "Waiting to be probed, most-dialled first ($waiting):" - if [ "$waiting" -gt 0 ]; then - jq -r --argjson top "$top" '(.backlog // {}) | to_entries | sort_by(-.value.hits) - | .[:$top][] | " \(.value.hits)\t\(.key)"' "$dir/state.json" - [ "$waiting" -le "$top" ] || echo " ... and $((waiting - top)) more" - else - echo " (none)" - fi - - next="$(_autoproxy_next_run)" - if [ -n "$next" ]; then - echo "" - echo "Next run: $(date -d "@$next" '+%H:%M:%S'), $(_in_time "$next")" - elif [ "$(systemctl show -p ActiveState --value proxy-suite-autoproxy.service 2>/dev/null)" = activating ]; then - echo "" - echo "Next run: one is running now" - fi -} - -cmd_proxy_learned() { - local dir - _require_autoproxy - dir="$(_autoproxy_dir)" - _require_autoproxy_readable "$dir" - - if ! jq -e '(.domains // {}) | length > 0' "$dir/state.json" > /dev/null 2>&1; then - echo "Nothing routed yet." - else - echo "Routed through an exit:" - jq -r --argjson now "$(date +%s)" ' - .domains | to_entries | sort_by(.key)[] - | ((($now - (.value.at // 0)) / 60) | floor) as $m - | "\(.key)\t\(.value.exit)\t\(.value.host)\(if .value.verdict == "slow" then ", which crawled directly" else "" end)\t\(if $m < 120 then "\($m)m" else "\($m / 60 | floor)h" end)"' \ - "$dir/state.json" | - awk -F'\t' '{ printf " %-28s -> %-12s (learned from %s, checked %s ago)\n", $1, $2, $3, $4 }' - fi - - echo "" - echo "Hosts judged: $(jq -r '[(.hosts // {})[] | .verdict] | group_by(.) - | map("\(.[0])=\(length)") | join(" ") | if . == "" then "none yet" else . end' \ - "$dir/state.json" 2>/dev/null || echo "none yet")" -} - -# Queues the host for the prober's own unit, so it is recorded under the same -# lock as a timer run. -cmd_proxy_learn() { - local host="${1:-}" dir - _require_autoproxy - dir="$(_autoproxy_dir)" - # Lands in a root-owned file and then in a URL: hostnames only. - [[ "$host" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || _usage "proxy auto learn " - printf '%s\n' "$host" >> "$dir/requests" 2>/dev/null || _die "Cannot write $dir/requests - re-run with sudo." - echo "Probing $host through each exit..." - if ! systemctl start proxy-suite-autoproxy-learn.service 2> /dev/null; then - echo "The probe run failed. $host is still queued and will be tried again at the next run." >&2 - _die "Details: journalctl -u proxy-suite-autoproxy-learn -n 20" - fi - jq -r --arg h "$host" ' - (.hosts // {})[$h] - | if . == null then "No verdict recorded; see: journalctl -u proxy-suite-autoproxy-learn" - elif .exit then "\(.domain): \(.verdict) - routed via \(.exit) from now on, no restart needed" - else "\($h): \(.verdict) - nothing to route" end' "$dir/state.json" -} - -# --- zapret ------------------------------------------------------------------ - -cmd_zapret() { - if [ "${1:-}" = auto ]; then - shift - cmd_zapret_auto "$@" - return - fi - if [ "${1:-}" = cutoff ]; then - shift - cmd_zapret_cutoff "$@" - return - fi - _toggle zapret-discord-youtube zapret "$@" -} - -_zapret_auto_file() { - printf '%s/%s' "${ZAPRET_STATE_DIR:-/var/lib/proxy-suite/zapret2}" "$1" -} - -# nfqws2 re-reads a list when its mtime changes; no reload needed. -_zapret_auto_edit() { - local file="$1" domain="$2" action="$3" tmp - if [ ! -e "$file" ] && [ "$action" = drop ]; then - return 0 - fi - tmp=$(mktemp "$file.XXXXXX" 2>/dev/null) || _die "Cannot write $file - re-run with sudo." - grep -v -x -F -- "$domain" "$file" 2>/dev/null >"$tmp" || true - if [ "$action" = add ]; then - printf '%s\n' "$domain" >>"$tmp" - fi - chmod 0644 "$tmp" - if ! mv "$tmp" "$file"; then - rm -f "$tmp" - _die "Cannot replace $file - re-run with sudo." - fi -} - -# Remembered strategies are keyed by the domain circular rotates on (usually the -# apex); z2k-state-persist.lua applies external deletions live. -_zapret_strategy_drop() { - local file domain="$1" tmp - file=$(_zapret_auto_file circular/state.tsv) - [ -s "$file" ] || return 0 - tmp=$(mktemp "$file.XXXXXX" 2>/dev/null) || _die "Cannot write $file - re-run with sudo." - awk -F'\t' -v d="$domain" '/^#/ || ($2 != d && substr(d, length(d) - length($2)) != "." $2)' "$file" >"$tmp" - chmod 0644 "$tmp" - if ! mv "$tmp" "$file"; then - rm -f "$tmp" - _die "Cannot replace $file - re-run with sudo." - fi -} - -cmd_zapret_auto() { - local verb="${1:-list}" domain="${2:-}" auto user exclude state - [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ] || _die "Learned hostlists need zapret.engine = \"zapret2\"." - auto=$(_zapret_auto_file zapret-hosts-auto.txt) - user=$(_zapret_auto_file zapret-hosts-user.txt) - exclude=$(_zapret_auto_file zapret-hosts-user-exclude.txt) - - case "$verb" in - add | forget | exclude) - [[ "$domain" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || _usage "zapret auto $verb " - ;; - esac - case "$verb" in - list) - if [ -s "$auto" ]; then cat "$auto"; else echo "No hostnames learned yet."; fi - ;; - add) - _zapret_auto_edit "$user" "$domain" add - echo "Pinned $domain (always bypassed)." - ;; - forget) - _zapret_auto_edit "$auto" "$domain" drop - _zapret_strategy_drop "$domain" - echo "Forgot $domain. It is learned again if it keeps failing; 'exclude' prevents that." - ;; - exclude) - _zapret_auto_edit "$auto" "$domain" drop - _zapret_strategy_drop "$domain" - _zapret_auto_edit "$exclude" "$domain" add - echo "Excluded $domain. It is no longer touched or learned." - ;; - clear) - : >"$auto" 2>/dev/null || _die "Cannot write $auto - re-run with sudo." - state=$(_zapret_auto_file circular/state.tsv) - if [ -e "$state" ]; then - : >"$state" 2>/dev/null || _die "Cannot write $state - re-run with sudo." - fi - echo "Cleared learned hosts and remembered strategies." - ;; - *) _usage "zapret auto [list|add|forget|exclude|clear]" ;; - esac -} - -# --- zapret cutoff ------------------------------------------------------------- -# -# The 16 KB cutoff probe's verdict: which networks this line cuts after the -# handshake, and the whitelisted name that gets each through. Networks without a -# name are what the proxy fallback routes. - -cmd_zapret_cutoff() { - local dir="${ZAPRET_STATE_DIR:-/var/lib/proxy-suite/zapret2}/cutoff" verb="${1:-status}" cut - [ "${ZAPRET_CUTOFF_ENABLED:-0}" = 1 ] || _die "The cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable." - case "$verb" in - status) ;; - probe) - : >"$dir/force" 2>/dev/null || _die "Cannot write $dir - re-run with sudo." - echo "Probing this line; this takes a few minutes..." - systemctl start proxy-suite-zapret2-cutoff.service || - _die "The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30" - ;; - *) _usage "zapret cutoff [status|probe]" ;; - esac - if ! [ -s "$dir/ts" ]; then - echo "Not probed yet." - return - fi - echo "Probed: $(date -d "@$(cat "$dir/ts")" '+%F %R') from $(cat "$dir/egress" 2>/dev/null)" - cut=$(grep -c '^[0-9]' "$dir/asn.txt" 2>/dev/null || true) - if [ "${cut:-0}" = 0 ]; then - echo "Cutoff: none on this line" - return - fi - echo "Cutoff: ${cut} network(s)" - awk -F'\t' ' - FILENAME == ARGV[1] { if ($1 ~ /^[0-9]+$/) name[$1] = $2; next } - $1 ~ /^[0-9]+$/ { printf " AS%-8s %s\n", $1, ($1 in name ? name[$1] : "no name - proxy fallback") } - ' "$dir/sni.txt" "$dir/asn.txt" -} - -# --- where ------------------------------------------------------------------- -# -# What the runtime state says about one host. Hostlists and autoProxy both key -# on an apex, so a miss on the full name retries each parent label. - -_where_row() { - printf ' %-14s %s\n' "$1" "$2" -} - -_where_parents() { - local d="$1" - while [ -n "$d" ]; do - printf '%s\n' "$d" - case "$d" in - *.*) d="${d#*.}" ;; - *) d="" ;; - esac - done -} - -# The first parent of $2 that file $1 lists, empty when none is. -_where_in_list() { - local file="$1" d - [ -r "$file" ] || return 0 - while IFS= read -r d; do - if grep -qxF -- "$d" "$file" 2>/dev/null; then - printf '%s' "$d" - return 0 - fi - done < <(_where_parents "$2") -} - -_where_in_autoproxy() { - local state="$1" d - while IFS= read -r d; do - if jq -e --arg d "$d" 'has("domains") and (.domains | has($d))' "$state" > /dev/null 2>&1; then - printf '%s' "$d" - return 0 - fi - done < <(_where_parents "$2") -} - -cmd_where() { - local domain="${1:-}" state hit exit_tag outbound excluded pinned learned verdict="" - [ -n "$domain" ] || _usage "where " - domain="${domain#*://}" - domain="${domain%%/*}" - _where_row domain "$domain" - - if _svc_exists proxy-suite-socks; then - _where_row "route mode" "$(_route_mode_label "$(_route_mode_current)")" - outbound="$(_status_outbound)" - [ -z "$outbound" ] || _where_row outbound "$outbound" - fi - - if [ "${AUTOPROXY_ENABLED:-0}" = 1 ]; then - state="$(_autoproxy_dir)/state.json" - if [ ! -r "$state" ]; then - _where_row autoProxy "state is not readable - enable userControl, or run with sudo" - else - hit="$(_where_in_autoproxy "$state" "$domain")" - if [ -z "$hit" ]; then - _where_row autoProxy "not routed" - else - exit_tag="$(jq -r --arg d "$hit" '.domains[$d].exit' "$state")" - _where_row autoProxy "$(jq -r --arg d "$hit" --argjson now "$(date +%s)" ' - .domains[$d] | ((($now - (.at // 0)) / 60) | floor) as $m - | "routed via \(.exit), learned from \(.host), checked \( - if $m < 120 then "\($m)m" else "\($m / 60 | floor)h" end) ago"' "$state")" - verdict="proxied via $exit_tag" - fi - fi - fi - - if [ "${ZAPRET_AUTO_ENABLED:-0}" = 1 ]; then - excluded="$(_where_in_list "$(_zapret_auto_file zapret-hosts-user-exclude.txt)" "$domain")" - pinned="$(_where_in_list "$(_zapret_auto_file zapret-hosts-user.txt)" "$domain")" - learned="$(_where_in_list "$(_zapret_auto_file zapret-hosts-auto.txt)" "$domain")" - if [ -n "$excluded" ]; then - _where_row zapret2 "excluded ($excluded) - never bypassed, never learned" - elif [ -n "$pinned" ]; then - _where_row zapret2 "pinned ($pinned) - always bypassed" - [ -n "$verdict" ] || verdict="direct, with the zapret2 bypass" - elif [ -n "$learned" ]; then - _where_row zapret2 "learned ($learned) - bypassed" - [ -n "$verdict" ] || verdict="direct, with the zapret2 bypass" - else - _where_row zapret2 "not learned, not pinned, not excluded" - fi - fi - - echo " -> ${verdict:-nothing runtime matches it; the configured routing decides}" - echo " Declared proxy.routing.rules are not visible here. Test what reaches it:" - echo " proxy-ctl proxy auto probe $domain" -} - -# --- awg --------------------------------------------------------------------- - -_awg_service() { - printf 'proxy-suite-awg-%s' "$1" -} - -_require_awg_profile() { - local profile - for profile in "${AWG_PROFILES[@]}"; do - [ "$profile" = "$1" ] && return 0 - done - _die "Unknown AmneziaWG profile: $1" -} - -_active_awg_profiles() { - local profile - for profile in "${AWG_PROFILES[@]}"; do - if _svc_active "$(_awg_service "$profile")"; then - printf '%s\n' "$profile" - fi - done -} - -cmd_awg() { - local verb="${1:-list}" profile active - shift || true - if [ "$#" -gt 0 ]; then - _require_awg_profile "$1" - fi - case "$verb" in - list | status) - if [ "${#AWG_PROFILES[@]}" -eq 0 ]; then - echo "No AmneziaWG profiles configured." - return - fi - printf " %-24s %s\n" "PROFILE" "STATUS" - for profile in "${AWG_PROFILES[@]}"; do - active="$(systemctl is-active "$(_awg_service "$profile")" 2>/dev/null || true)" - printf " %-24s %s\n" "$profile" "${active:-unknown}" - done - ;; - on) - [ "$#" -gt 0 ] || _usage "awg on " - systemctl start "$(_awg_service "$1")" - ;; - off | restart) - if [ "$#" -gt 0 ]; then - active="$1" - else - active="$(_active_awg_profiles)" - if [ -z "$active" ]; then - [ "$verb" = off ] && return - _die "No AmneziaWG profile is active." - fi - fi - [ "$verb" = off ] && verb=stop - while IFS= read -r profile; do - systemctl "$verb" "$(_awg_service "$profile")" - done <<< "$active" - ;; - *) _usage "awg [list] | on | off [profile] | restart [profile]" ;; - esac -} - -# --- apps -------------------------------------------------------------------- - -_ensure_app_routing() { - [ "${PER_APP_ROUTING_ENABLED:-0}" = "1" ] || _die "perAppRouting is not enabled in this configuration." -} - -_check_no_global_proxy() { - local svc - for svc in proxy-suite-tun proxy-suite-tproxy; do - if _svc_active "$svc.service"; then - _die "Global $svc.service is active. Stop it before using route=$1 profiles." - fi - done -} - -_cleanup_slice_if_idle() { - local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4" - if ! systemctl --user list-units --type=scope --state=running --plain --no-legend "$slice_base-*" | grep -q .; then - systemctl stop "$user_svc" || true - systemctl --user stop "$anchor_unit" || true - if ! systemctl list-units --type=service --state=active --plain --no-legend "$slice_base-user@*.service" | grep -q .; then - systemctl stop "$backend_svc" || true - fi - fi -} - -# _wrap_slice -_wrap_slice() { - local slice_base="$1" profile="$2" enabled="$3" disabled_msg="$4" backend_svc="$5" - shift 5 - [ "$enabled" = "1" ] || _die "$disabled_msg" - local uid; uid="$(id -u)" - local scope_unit="$slice_base-${profile}-$$" - local anchor_unit="$slice_base-anchor.service" - local user_svc="$slice_base-user@$uid.service" - local status=0 - - cleanup_slice() { - _cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc" - } - trap cleanup_slice EXIT - - systemctl --user start "$anchor_unit" || status=$? - [ "$status" -ne 0 ] || systemctl start "$backend_svc" || status=$? - [ "$status" -ne 0 ] || systemctl start "$user_svc" || status=$? - if [ "$status" -eq 0 ]; then - systemd-run --user --scope --quiet --collect --same-dir \ - --slice="$slice_base" --unit="$scope_unit" "$@" || status=$? - fi - exit "$status" -} - -cmd_apps() { - local verb="${1:-list}" - shift || true - _ensure_app_routing - case "$verb" in - list) - if [ "$(jq 'length' "$PER_APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then - echo "No perAppRouting profiles configured." - return - fi - printf " %-24s %s\n" "PROFILE" "ROUTE" - jq -r '.[] | "\(.name)\t\(.route)"' "$PER_APP_ROUTING_PROFILES_FILE" | - awk -F'\t' '{ printf " %-24s %s\n", $1, $2 }' - ;; - run) cmd_apps_run "$@" ;; - *) _usage "apps [list] | run -- [args]" ;; - esac -} - -cmd_apps_run() { - local profile="${1:-}" route - shift || true - [ "${1:-}" != "--" ] || shift - { [ -n "$profile" ] && [ "$#" -gt 0 ]; } || _usage "apps run -- [args]" - - route="$(jq -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$PER_APP_ROUTING_PROFILES_FILE")" - [ -n "$route" ] || _die "Unknown perAppRouting profile: $profile" - - case "$route" in - direct) exec "$@" ;; - proxychains) - [ "$PER_APP_ROUTING_PROXYCHAINS_ENABLED" = "1" ] || - _die "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false." - [ -r "$PROXYCHAINS_CONFIG" ] || - _die "Proxychains config is not readable: $PROXYCHAINS_CONFIG (is proxy-suite-socks running?)" - exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@" - ;; - tun) - _check_no_global_proxy tun - _wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED" \ - "Profile '$profile' uses route=tun, but perAppRouting.tun.enable is false." \ - "proxy-suite-per-app-tun.service" "$@" - ;; - tproxy) - _check_no_global_proxy tproxy - _wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED" \ - "Profile '$profile' uses route=tproxy, but perAppRouting.tproxy.enable is false." \ - "proxy-suite-per-app-tproxy.service" "$@" - ;; - zapret) - _check_no_global_proxy zapret - _wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED" \ - "Profile '$profile' uses route=zapret, but perAppRouting.zapret.enable is false." \ - "proxy-suite-per-app-zapret.service" "$@" - ;; - *) _die "Route backend '$route' is not implemented." ;; - esac -} - -# --- inbounds ---------------------------------------------------------------- - -# Links carry listener credentials, so the file is root/group-only. -_inbound_links() { - [ -f "$INBOUNDS_LINKS_FILE" ] || - _die "No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?" - [ -r "$INBOUNDS_LINKS_FILE" ] || _die "Share links are not readable by this user. Enable userControl, or run as root." - cat "$INBOUNDS_LINKS_FILE" -} - -_inbound_link_for() { - local tag="$1" user="${2:-}" matches count - matches="$(_inbound_links | jq -c --arg tag "$tag" --arg user "$user" '[.[] | select(.tag == $tag) | select($user == "" or .user == $user)]')" - count="$(jq 'length' <<< "$matches")" - [ "$count" -ne 0 ] || _die "Unknown inbound, or no share link for it: $tag" - if [ "$count" -ne 1 ]; then - echo "Multiple users match '$tag'; specify one of:" >&2 - jq -r '.[].user' <<< "$matches" | sed 's/^/ /' >&2 - exit 1 - fi - jq -r '.[0].link' <<< "$matches" -} - -# Per-user traffic over the last $1 days, newest first, then totals. -_inbound_stats() { - local days="$1" file="${INBOUNDS_STATS_FILE:-/var/lib/proxy-suite/inbound-stats.json}" since - [[ "$days" =~ ^[1-9][0-9]*$ ]] || _usage "inbounds stats [days]" - # Collect what XRay counted since the last run first; root and userControl - # members may, anyone else reads what the timer last wrote. - systemctl --no-ask-password start proxy-suite-inbound-stats.service 2>/dev/null || true - [ -e "$file" ] || _die "No traffic recorded yet - the collector runs every 5 minutes." - [ -r "$file" ] || _die "Cannot read $file - enable userControl, or run with sudo." - since="$(date -d "-$((days - 1)) days" +%F)" - echo "Traffic through the inbounds since $since, by user:" - jq -r --arg since "$since" ' - [(.days // {}) | to_entries[] | select(.key >= $since) | .key as $d - | .value | to_entries[] | [$d, .key, (.value.down // 0), (.value.up // 0)]] - | (group_by(.[0]) | reverse | .[] | sort_by(.[1])[] | "day\t" + (map(tostring) | join("\t"))), - (group_by(.[1])[] | "total\t\t\(.[0][1])\t\(map(.[2]) | add)\t\(map(.[3]) | add)")' "$file" | - awk -F'\t' ' - function h(b) { - if (b >= 1073741824) return sprintf("%.1f GiB", b / 1073741824) - if (b >= 1048576) return sprintf("%.1f MiB", b / 1048576) - if (b >= 1024) return sprintf("%.0f KiB", b / 1024) - return b " B" - } - $1 == "day" { - if (!d++) printf " %-12s %-20s %10s %10s\n", "DAY", "USER", "DOWN", "UP" - printf " %-12s %-20s %10s %10s\n", $2, $3, h($4), h($5) - } - $1 == "total" { - if (!t++) printf "\n %-33s %10s %10s\n", "TOTAL", "DOWN", "UP" - printf " %-33s %10s %10s\n", $3, h($4), h($5) - } - END { if (!d) print " (nothing recorded)" }' -} - -# Without a user: user names only, since each URL is its user's secret. -_inbound_subscriptions() { - local user="" qr=0 file="${INBOUNDS_SUBS_FILE:-/run/proxy-suite-inbounds/subscriptions.json}" - local base="${INBOUNDS_SUB_BASE_URL:-}" arg token - for arg; do - case "$arg" in - --qr) qr=1 ;; - *) user="$arg" ;; - esac - done - [ -f "$file" ] || - _die "No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?" - [ -r "$file" ] || _die "Subscriptions are not readable by this user. Enable userControl, or run as root." - if [ -z "$user" ]; then - [ "$qr" = 0 ] || _usage "inbounds sub --qr" - jq -r '.[] | " " + .user' "$file" - echo "Show one with: proxy-ctl inbounds sub [--qr]" >&2 - return - fi - token="$(jq -r --arg u "$user" 'first(.[] | select(.user == $u) | .token) // empty' "$file")" - [ -n "$token" ] || _die "No subscription for user: $user" - if [ -n "$base" ]; then - _emit "${base%/}/$token" "$qr" - else - [ "$qr" = 0 ] || _die "A QR code needs inbounds.subscriptions.baseUrl." - echo "${file%.json}/$token" - echo "Set inbounds.subscriptions.baseUrl to get a URL instead of a path." >&2 - fi -} - -cmd_inbounds() { - local verb="${1:-list}" qr=0 arg link state - local -a args=() - shift || true - [ "${INBOUNDS_ENABLED:-0}" = 1 ] || _die "inbounds is not enabled in this configuration." - case "$verb" in - list) - state="$(systemctl is-active proxy-suite-inbounds 2>/dev/null || true)" - printf " %-24s %-16s %-14s %-8s %s\n" TAG USER TYPE PORT STATE - _inbound_links \ - | jq -r --arg state "$state" '.[] | "\(.tag)\t\(.user)\t\(.type)\t\(.port)\t\($state)"' \ - | awk -F'\t' '{printf " %-24s %-16s %-14s %-8s %s\n", $1, $2, $3, $4, $5}' - ;; - link | qr) - [ "$verb" = link ] || qr=1 - for arg; do - if [ "$arg" = --qr ]; then qr=1; else args+=("$arg"); fi - done - [ "${#args[@]}" -gt 0 ] || _usage "inbounds link [user] [--qr]" - link="$(_inbound_link_for "${args[@]}")" - _emit "$link" "$qr" - ;; - stats) _inbound_stats "${1:-7}" ;; - sub) _inbound_subscriptions "$@" ;; - *) _usage "inbounds [list] | link [user] [--qr] | sub [user] [--qr] | stats [days]" ;; - esac -} diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 9525ead..6924730 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -38,8 +38,9 @@ }: let - unwrapped = pkgs.writeShellScriptBin "proxy-ctl" ( - builtins.readFile ./proxy-ctl-lib.sh + "\n" + builtins.readFile ./proxy-ctl.sh + # Not writePython3Bin: its flake8 pass would gate the build on style. + unwrapped = pkgs.writeScriptBin "proxy-ctl" ( + "#!${pkgs.python3}/bin/python3\n" + builtins.readFile ./proxy-ctl/proxy_ctl.py ); wrapperEnv = { CLASH_API = clashApi; @@ -93,8 +94,11 @@ pkgs.symlinkJoin { # curl. The newest Chrome profile the package ships, since the set varies by # version; the build fails if there is none. postBuild = '' - install -Dm644 ${./proxy-ctl-completion.bash} \ + install -Dm644 ${./proxy-ctl/completions/proxy-ctl.bash} \ "$out/share/bash-completion/completions/proxy-ctl" + install -Dm644 ${./proxy-ctl/completions/_proxy-ctl} "$out/share/zsh/site-functions/_proxy-ctl" + install -Dm644 ${./proxy-ctl/completions/proxy-ctl.fish} \ + "$out/share/fish/vendor_completions.d/proxy-ctl.fish" probe_curl=$(ls ${pkgs.curl-impersonate}/bin/curl_chrome[0-9]* | grep -E '/curl_chrome[0-9]+$' | sort -V | tail -n 1) [ -x "$probe_curl" ] wrapProgram "$out/bin/proxy-ctl" \ @@ -103,12 +107,8 @@ pkgs.symlinkJoin { lib.makeBinPath [ # curl-impersonate's curl_chrome* wrappers are `#!/usr/bin/env bash`. pkgs.bash - pkgs.coreutils pkgs.curl pkgs.fzf - pkgs.gawk - pkgs.gnugrep - pkgs.jq pkgs.proxychains-ng pkgs.qrencode pkgs.systemd diff --git a/pkgs/proxy-ctl.sh b/pkgs/proxy-ctl.sh deleted file mode 100644 index 28faed4..0000000 --- a/pkgs/proxy-ctl.sh +++ /dev/null @@ -1,45 +0,0 @@ -set -euo pipefail - -PROXYCHAINS_QUIET_ARG="${PROXYCHAINS_QUIET_ARG:-}" -SUB_TAGS=() -AWG_PROFILES=() -if [ -f "${SUB_TAGS_FILE:-}" ]; then - mapfile -t SUB_TAGS < <(jq -r '.[]' "$SUB_TAGS_FILE") -fi -if [ -f "${AWG_PROFILES_FILE:-}" ]; then - mapfile -t AWG_PROFILES < <(jq -r '.[]' "$AWG_PROFILES_FILE") -fi - -# Old spellings: still accepted, not in the help. -case "${1:-}" in - tun | tproxy | outbounds | select) set -- proxy "$@" ;; - route-mode) shift; set -- proxy mode "$@" ;; - subscription) shift; set -- proxy subs "$@" ;; - wrap) shift; set -- apps run "$@" ;; -esac - -cmd="${1:-status}" -shift || true - -case "$cmd" in - help | -h | --help) _help ;; - status) cmd_status "$@" ;; - restart) cmd_restart ;; - logs) - if [ "$#" -gt 0 ]; then exec journalctl -fu "$@"; fi - # journalctl takes unit globs, so the default needs no unit list of its own. - exec journalctl -f -u 'proxy-suite-*' -u zapret-discord-youtube - ;; - proxy) cmd_proxy "$@" ;; - zapret) cmd_zapret "$@" ;; - awg) cmd_awg "$@" ;; - ssh) _toggle proxy-suite-ssh-proxy ssh "$@" ;; - apps) cmd_apps "$@" ;; - inbounds) cmd_inbounds "$@" ;; - where) cmd_where "$@" ;; - __complete) cmd_complete "$@" ;; - *) - _help >&2 - exit 1 - ;; -esac diff --git a/pkgs/proxy-ctl/completions/_proxy-ctl b/pkgs/proxy-ctl/completions/_proxy-ctl new file mode 100644 index 0000000..da3e0bd --- /dev/null +++ b/pkgs/proxy-ctl/completions/_proxy-ctl @@ -0,0 +1,5 @@ +#compdef proxy-ctl +# proxy-ctl knows its own verbs, tags, profiles and units: ask it. +local -a candidates +candidates=(${(f)"$(proxy-ctl __complete ${(Q)words[2,CURRENT-1]} 2>/dev/null)"}) +compadd -a candidates diff --git a/pkgs/proxy-ctl-completion.bash b/pkgs/proxy-ctl/completions/proxy-ctl.bash similarity index 100% rename from pkgs/proxy-ctl-completion.bash rename to pkgs/proxy-ctl/completions/proxy-ctl.bash diff --git a/pkgs/proxy-ctl/completions/proxy-ctl.fish b/pkgs/proxy-ctl/completions/proxy-ctl.fish new file mode 100644 index 0000000..dabe141 --- /dev/null +++ b/pkgs/proxy-ctl/completions/proxy-ctl.fish @@ -0,0 +1,2 @@ +# proxy-ctl knows its own verbs, tags, profiles and units: ask it. +complete -c proxy-ctl -f -a '(proxy-ctl __complete (commandline -xpc)[2..] 2>/dev/null)' diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py new file mode 100644 index 0000000..8da9316 --- /dev/null +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -0,0 +1,1776 @@ +"""proxy-ctl: control proxy-suite services and inspect their runtime state. + +Configuration arrives through the environment the Nix wrapper sets. +""" + +import datetime +import json +import os +import re +import signal +import subprocess +import sys +import tempfile +import time +import urllib.request + +ALL_SERVICES = [ + "proxy-suite-socks", + "proxy-suite-tproxy", + "proxy-suite-tun", + "proxy-suite-inbounds", + "proxy-suite-ssh-proxy", + "proxy-suite-tg-ws-proxy", + "proxy-suite-zapret-vm-exempt", + "zapret-discord-youtube", +] + +RESTART_SERVICES = [ + "proxy-suite-tproxy", + "proxy-suite-tun", + "proxy-suite-inbounds", + "proxy-suite-ssh-proxy", + "proxy-suite-tg-ws-proxy", + "zapret-discord-youtube", +] + +HELP = """\ +Usage: proxy-ctl [verb] [args] +A group without a verb shows its status or list. + + status [--tray] services and routing mode + restart restart active services + logs [unit] follow logs (default: every proxy-suite unit) + where how this host is routed right now + + proxy [status|on|off] local proxy backend + proxy outbounds [list] outbounds, where each came from, and the pick + proxy outbounds add add an outbound at runtime + proxy outbounds rm remove a runtime outbound + proxy select [|auto] pin the priority outbound (no tag: pick from a menu) + 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 rm remove a runtime subscription + proxy tun [status|on|off] global TUN mode + proxy tproxy [status|on|off] global TProxy mode + proxy auto [list] what autoProxy routed, and via which exit (sudo, or userControl) + 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 (sudo) + proxy auto queue [count] destinations waiting to be probed (sudo, or userControl) + + zapret [status|on|off] DPI bypass + zapret auto [list] hosts zapret2 learned as blocked + zapret auto add|forget|exclude + pin, forget, or never learn a host (sudo) + zapret auto clear forget learned hosts and strategies (sudo) + zapret cutoff [status] networks this line cuts at 16 KB, and their names + zapret cutoff probe probe this line again now (sudo) + + awg [list] AmneziaWG profiles and their state + awg on | off [profile] | restart [profile] + + ssh [status|on|off] SSH SOCKS5 tunnel + + apps [list] per-app routing profiles + apps run -- [args] run a command through a profile + + inbounds [list] server inbounds + inbounds link [user] [--qr] client share link + inbounds sub [user] [--qr] subscription users, or one user's URL + inbounds stats [days] traffic per user (sudo, or userControl) +""" + +ROUTE_MODES = ["whitelist", "blacklist", "all-proxy", "all-bypass"] +ROUTE_MODE_LABELS = { + "whitelist": "Whitelist (direct by default)", + "blacklist": "Blacklist (proxy by default)", + "all-proxy": "All Proxy (override)", + "all-bypass": "All Bypass (override)", +} + +# A hostname: it lands in root-owned files and then in URLs. +HOSTNAME = re.compile(r"[A-Za-z0-9.-]+\.[A-Za-z]{2,}") + + +# --- plumbing ----------------------------------------------------------------- + + +def env(name, default=""): + return os.environ.get(name) or default + + +def die(message, status=1): + sys.stdout.flush() + print(message, file=sys.stderr) + sys.exit(status) + + +def usage(text): + die(f"Usage: proxy-ctl {text}") + + +def _s(value): + """A JSON value the way `jq -r` prints it.""" + return value if isinstance(value, str) else json.dumps(value) + + +def read_json(path): + with open(path, encoding="utf-8") as f: + return json.load(f) + + +def read_text(path): + with open(path, encoding="utf-8", errors="replace") as f: + return f.read() + + +def lines(text): + """Lines the way awk and grep see them: a missing final newline is fine.""" + if not text: + return [] + parts = text.split("\n") + return parts[:-1] if text.endswith("\n") else parts + + +def readable(path): + return bool(path) and os.access(path, os.R_OK) + + +def _run(argv, capture=False, quiet=False, stdin=None): + """Runs argv; (exit status, stdout if captured). A missing binary is 127.""" + sys.stdout.flush() + try: + p = subprocess.run( + argv, + input=stdin, + stdout=subprocess.PIPE if capture else (subprocess.DEVNULL if quiet else None), + stderr=subprocess.DEVNULL if quiet else None, + text=True, + ) + except OSError: + return 127, "" + return p.returncode, p.stdout or "" + + +def _run_foreground(argv): + """Waits on argv the way a shell does: Ctrl-C is the child's to handle.""" + sys.stdout.flush() + try: + p = subprocess.Popen(argv) + except OSError: + return 127 + old = signal.signal(signal.SIGINT, signal.SIG_IGN) + try: + return p.wait() + finally: + signal.signal(signal.SIGINT, old) + + +def _exec(argv): + sys.stdout.flush() + try: + os.execvp(argv[0], argv) + except OSError as e: + die(f"proxy-ctl: {argv[0]}: {e.strerror}", 126 if isinstance(e, PermissionError) else 127) + + +def systemctl(*args, capture=False, quiet=False): + return _run(["systemctl", *args], capture=capture, quiet=quiet) + + +def must(*args): + """systemctl that ends proxy-ctl with its status when it fails.""" + status, _ = systemctl(*args) + if status: + sys.exit(status) + + +def svc_exists(unit): + return systemctl("cat", unit, quiet=True)[0] == 0 + + +def svc_active(unit): + return systemctl("is-active", "--quiet", unit)[0] == 0 + + +def svc_state(unit): + return systemctl("is-active", unit, capture=True, quiet=True)[1].rstrip("\n") + + +def _bool(value): + return "true" if value else "false" + + +def _toggle(unit, name, verb="status", *_): + if not svc_exists(unit): + die(f"{name} is not enabled in this configuration.") + if verb == "status": + systemctl("is-active", unit) + elif verb == "on": + must("start", unit) + elif verb == "off": + must("stop", unit) + else: + usage(f"{name} [status|on|off]") + + +def _emit(text, qr): + """Prints text, or its QR code.""" + if not qr: + print(text) + return + status, _ = _run(["qrencode", "-t", "ANSIUTF8"], stdin=text) + if status: + sys.exit(status) + + +def _json_list(path): + try: + return [_s(x) for x in read_json(path)] + except (OSError, ValueError, TypeError): + return [] + + +def _sub_tags(): + return _json_list(env("SUB_TAGS_FILE")) + + +def _awg_profiles(): + return _json_list(env("AWG_PROFILES_FILE")) + + +# --- completion --------------------------------------------------------------- +# +# Candidates for the words already typed, one per line. The tree lives here, +# next to HELP, not in the completion files. + + +def _complete_tree(words): + simple = { + "": ["status", "restart", "logs", "where", "proxy", "zapret", "awg", "ssh", "apps", "inbounds", "help"], + "proxy": ["status", "on", "off", "outbounds", "select", "mode", "subs", "tun", "tproxy", "auto"], + "proxy outbounds": ["list", "add", "rm"], + "proxy subs": ["list", "update", "add", "rm"], + "proxy mode": ["default", *ROUTE_MODES], + "proxy tun": ["status", "on", "off"], + "proxy tproxy": ["status", "on", "off"], + "ssh": ["status", "on", "off"], + "zapret": ["status", "on", "off", "auto", "cutoff"], + "proxy auto": ["list", "probe", "learn", "queue"], + "zapret auto": ["list", "add", "forget", "exclude", "clear"], + "zapret cutoff": ["status", "probe"], + "awg": ["list", "on", "off", "restart"], + "apps": ["list", "run"], + "inbounds": ["list", "link", "sub", "stats"], + } + if words in simple: + return simple[words] + if words == "proxy outbounds rm": + return _runtime_tags("outbound") + if words == "proxy subs rm": + return _runtime_tags("subscription") + if words == "proxy select": + return ["auto", *_outbound_tags()] + if words in ("zapret auto forget", "zapret auto exclude"): + return lines(read_text(_zapret_auto_file("zapret-hosts-auto.txt"))) + if words in ("awg on", "awg off", "awg restart"): + return _awg_profiles() + if words == "apps run": + return [_s(p["name"]) for p in read_json(env("PER_APP_ROUTING_PROFILES_FILE"))] + if words == "inbounds link": + return sorted({_s(x["tag"]) for x in read_json(env("INBOUNDS_LINKS_FILE"))}) + if words == "inbounds sub": + return [_s(x["user"]) for x in read_json(env("INBOUNDS_SUBS_FILE"))] + if words == "logs": + return [*ALL_SERVICES, *map(_awg_service, _awg_profiles())] + if words == "where": + return sorted(read_json(os.path.join(_autoproxy_dir(), "state.json")).get("domains") or {}) + return [] + + +def cmd_complete(*words): + """The hidden verb the shell completions call. It never fails or speaks.""" + try: + candidates = _complete_tree(" ".join(words)) + except Exception: + return + for word in candidates: + print(word) + + +# --- status ------------------------------------------------------------------- + + +def _route_mode_default(): + return env("DEFAULT_ROUTE_MODE", "blacklist") + + +def _route_mode_effective(): + mode = "" + try: + mode = re.sub(r"\s", "", read_text(env("ROUTE_MODE_STATE_FILE"))) + except OSError: + pass + return mode if mode in ROUTE_MODES else _route_mode_default() + + +def _route_mode_current(): + return _route_mode_effective() if readable(env("ROUTE_MODE_STATE_FILE")) else "default" + + +def _route_mode_label(mode): + if mode == "default": + return f"Default ({ROUTE_MODE_LABELS.get(_route_mode_default(), 'Unknown')})" + return ROUTE_MODE_LABELS.get(mode, "Unknown") + + +def _status_tray(): + for key, svc in ( + ("socks", "proxy-suite-socks"), + ("tproxy", "proxy-suite-tproxy"), + ("tun", "proxy-suite-tun"), + ("zapret", "zapret-discord-youtube"), + ): + print(f"{key}_available={_bool(svc_exists(svc))}") + print(f"{key}_active={_bool(svc_active(svc))}") + profiles = _awg_profiles() + active = _active_awg_profiles() + print(f"subscription_update_available={_bool(svc_exists('proxy-suite-subscription-update'))}") + print(f"route_mode_available={_bool(svc_exists('proxy-suite-socks'))}") + print(f"route_mode={_route_mode_current()}") + print(f"default_route_mode={_route_mode_default()}") + print(f"awg_available={_bool(profiles)}") + print(f"awg_active={active[0] if active else ''}") + print(f"awg_profiles={','.join(profiles)}") + + +def _status_row(key, value): + print(f" {key:<44} {value}") + + +def _status_row_if(key, value): + """Nothing to say about a state that is absent or unreadable.""" + if value: + _status_row(key, value) + + +def _svc_status(unit): + if svc_exists(unit): + _status_row(unit, svc_state(unit)) + + +def _status_outbound(): + """The pin when there is one, otherwise whatever the backend is dialling.""" + pinned = _outbound_inventory().get("pinned") + if pinned: + return f"{_s(pinned)} (pinned)" + return _outbound_current() + + +def _status_autoproxy(): + if env("AUTOPROXY_ENABLED") != "1": + return "" + state = os.path.join(_autoproxy_dir(), "state.json") + if not readable(state): + return "" + counts = [] + for key in ("domains", "backlog"): + try: + counts.append(str(len(read_json(state).get(key) or {}))) + except (OSError, ValueError, AttributeError, TypeError): + counts.append("?") + text = f"{counts[0]} routed, {counts[1]} queued" + next_run = _autoproxy_next_run() + if next_run: + text += f", next run {_in_time(next_run)}" + return text + + +def _status_zapret(): + if env("ZAPRET_AUTO_ENABLED") != "1": + return "" + auto = _zapret_auto_file("zapret-hosts-auto.txt") + if not readable(auto): + return "" + try: + return f"{sum(1 for line in lines(read_text(auto)) if line)} learned" + except OSError: + return "" + + +def cmd_status(*args): + if args[:1] == ("--tray",): + _status_tray() + return + print("proxy-suite services:") + for svc in ALL_SERVICES: + _svc_status(svc) + for profile in _awg_profiles(): + _svc_status(_awg_service(profile)) + socks = svc_exists("proxy-suite-socks") + if socks or env("ZAPRET_AUTO_ENABLED") == "1": + print() + print("routing:") + if socks: + _status_row("active mode", _route_mode_label(_route_mode_current())) + _status_row_if("outbound", _status_outbound()) + _status_row_if("autoProxy", _status_autoproxy()) + _status_row_if("zapret2", _status_zapret()) + + +def cmd_restart(*_): + """Restarts what is running; starting something stopped on purpose is `proxy on`.""" + for svc in ["proxy-suite-socks", *RESTART_SERVICES]: + if svc_exists(svc) and svc_active(svc): + must("restart", svc) + for profile in _awg_profiles(): + if svc_active(_awg_service(profile)): + must("restart", _awg_service(profile)) + + +# --- proxy -------------------------------------------------------------------- + + +def cmd_proxy(verb="status", *args): + if verb in ("status", "on"): + _toggle("proxy-suite-socks", "proxy", verb) + elif verb == "off": + if not svc_exists("proxy-suite-socks"): + die("proxy is not enabled in this configuration.") + for svc in ("proxy-suite-tproxy", "proxy-suite-tun"): + if svc_exists(svc): + systemctl("stop", svc) + must("stop", "proxy-suite-socks") + elif verb == "outbounds": + cmd_outbounds(*args) + elif verb == "select": + cmd_select(*args) + elif verb == "mode": + cmd_route_mode(*args) + elif verb == "subs": + cmd_subscription(*args) + elif verb == "tun": + _toggle("proxy-suite-tun", "proxy tun", *args) + elif verb == "tproxy": + _toggle("proxy-suite-tproxy", "proxy tproxy", *args) + elif verb == "auto": + cmd_proxy_auto(*args) + elif verb in ("probe", "learn", "queue", "learned"): + cmd_proxy_auto(verb, *args) + else: + usage("proxy [status|on|off|outbounds|select|mode|subs|tun|tproxy|auto]") + + +def cmd_outbounds(verb="list", *args): + if verb == "list": + _outbounds_list() + elif verb == "add": + _runtime_entry_add("outbound", *args) + elif verb in ("rm", "remove", "del"): + _runtime_entry_rm("outbound", *args) + else: + usage("proxy outbounds [list|add |rm ]") + + +def _outbound_inventory(): + """What the running backend wrote: tags, their sources, and the pin. + + Empty until the proxy has started once. + """ + path = env("OUTBOUND_INVENTORY_FILE") + if not readable(path): + return {} + try: + inventory = read_json(path) + except (OSError, ValueError): + return {} + return inventory if isinstance(inventory, dict) else {} + + +def _outbound_tags(): + return [_s(t) for t in _outbound_inventory().get("tags") or []] + + +def _require_outbound_inventory(): + if not _outbound_tags(): + die("No outbounds are available yet - is proxy-suite-socks running?") + + +def _outbound_current(): + """What the backend dials right now, when it exposes a selector. + + Empty otherwise, which is normal for selection = "first" and for XRay. + """ + api = env("CLASH_API") + if not api: + return "" + # The API is on loopback: never through the shell's HTTP(S)_PROXY. + opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) + try: + with opener.open(f"{api}/proxies/proxy", timeout=5) as r: + now = json.load(r).get("now") + except Exception: + return "" + return "" if now is None else _s(now) + + +def _outbounds_list(): + _require_outbound_inventory() + inventory = _outbound_inventory() + pinned = _s(inventory.get("pinned") or "") + sources = inventory.get("sources") or {} + current = _outbound_current() + + print(f"Selection: {_s(inventory.get('selection') or 'first')}") + print(f"Pinned: {pinned or '(auto)'}") + if current: + print(f"Current: {current}") + print() + print(f" {'TAG':<34} SOURCE") + for tag in _outbound_tags(): + mark = " " + if tag == pinned: + mark = "*" + elif not pinned and tag == current: + mark = ">" + print(f" {mark}{tag:<34} {_s(sources.get(tag) or '-')}") + + +def cmd_select(tag="", *_): + if not tag: + if not (os.isatty(0) and os.isatty(1)): + usage("proxy select |auto") + _require_outbound_inventory() + pinned = _s(_outbound_inventory().get("pinned") or "") or "auto" + status, tag = _run( + [ + "fzf", + "--prompt=outbound> ", + "--height=40%", + "--reverse", + f"--header=pinned: {pinned} (auto = let the configured selection decide)", + ], + capture=True, + stdin="".join(f"{t}\n" for t in ["auto", *_outbound_tags()]), + ) + tag = tag.strip("\n") + # Dismissed. + if status or not tag: + return + status, escaped = _run(["systemd-escape", "--", tag], capture=True) + if status: + sys.exit(status) + escaped = escaped.rstrip("\n") + if systemctl("start", f"proxy-suite-outbound-select@{escaped}.service")[0]: + die(f"Failed - see: proxy-ctl logs proxy-suite-outbound-select@{escaped}") + print("Selecting automatically again." if tag == "auto" else f"Pinned: {tag}") + + +# --- runtime outbounds and subscriptions -------------------------------------- +# +# One URL per file in a spool directory the userControl group may write. The +# backend reads them at start, which the reload unit triggers. + + +def _runtime_dir(kind): + if kind == "outbound": + return env("RUNTIME_OUTBOUNDS_DIR", "/var/lib/proxy-suite/outbounds.d") + return env("RUNTIME_SUBS_DIR", "/var/lib/proxy-suite/subscriptions.d") + + +def _runtime_noun(kind): + return "outbounds" if kind == "outbound" else "subs" + + +def _runtime_tags(kind): + try: + names = os.listdir(_runtime_dir(kind)) + except OSError: + return [] + return sorted(n[: -len(".url")] for n in names if n.endswith(".url")) + + +def _check_runtime_tag(kind, tag): + if tag in ("proxy", "direct", "block"): + die(f"'{tag}' is reserved; pick another {kind} tag.") + if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._-]*", tag): + die(f"Invalid {kind} tag '{tag}': letters, digits, dot, dash and underscore only.") + if tag in _runtime_tags(kind): + die(f"A runtime {kind} named '{tag}' already exists; remove it first.") + if kind == "outbound": + if tag in _outbound_tags(): + die(f"An outbound named '{tag}' already exists.") + elif tag in _sub_tags(): + die(f"A subscription named '{tag}' is declared in the configuration.") + + +def _runtime_entry_add(kind, tag="", url="", *_): + if not tag or not url: + usage(f"proxy {_runtime_noun(kind)} add ") + _check_runtime_tag(kind, tag) + if re.search(r"\s", url): + die("A URL cannot contain whitespace.") + path = os.path.join(_runtime_dir(kind), f"{tag}.url") + old = os.umask(0o027) + try: + with open(path, "w", encoding="utf-8") as f: + f.write(f"{url}\n") + except OSError: + die(f"Cannot write {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.") + finally: + os.umask(old) + _runtime_reload() + _runtime_entry_verify(kind, tag) + + +def _runtime_entry_rm(kind, tag="", *_): + if not tag: + usage(f"proxy {_runtime_noun(kind)} rm ") + path = os.path.join(_runtime_dir(kind), f"{tag}.url") + if not os.path.exists(path): + die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.") + try: + os.unlink(path) + except FileNotFoundError: + pass + except OSError: + die(f"Cannot remove {path} - join the {env('USER_CONTROL_GROUP', 'proxy-suite')} group, or re-run with sudo.") + _runtime_reload() + print(f"Removed {kind}: {tag}") + + +def _runtime_reload(): + if systemctl("start", "proxy-suite-outbound-reload.service")[0]: + die("Saved, but applying it failed - see: proxy-ctl logs proxy-suite-outbound-reload") + + +def _subscription_cache(tag): + return os.path.join(env("SUB_CACHE_DIR", "/var/lib/proxy-suite/subscriptions"), f"{tag}.json") + + +def _runtime_entry_verify(kind, tag): + """Only the backend parses the URL, so confirm the entry actually came up.""" + if kind == "outbound": + if tag in _outbound_tags(): + print(f"Added outbound: {tag}") + return + elif os.path.isfile(_subscription_cache(tag)): + print(f"Added subscription: {tag} ({_subscription_proxy_count_text(_subscription_cache(tag))} proxies)") + return + sys.stdout.flush() + print(f"Saved {kind} '{tag}', but it did not come up. Check: proxy-ctl logs", file=sys.stderr) + print(f"Remove it again with: proxy-ctl proxy {_runtime_noun(kind)} rm {tag}", file=sys.stderr) + sys.exit(1) + + +def cmd_route_mode(action="status", *_): + if not svc_exists("proxy-suite-socks"): + die("proxy is not enabled in this configuration.") + if action == "status": + print(_route_mode_current()) + elif action in ("default", *ROUTE_MODES): + must("start", f"proxy-suite-route-mode@{action}.service") + print(f"Switched to: {_route_mode_label(action)}") + else: + usage("proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]") + + +def _subscription_proxy_count(path): + cache = read_json(path) + if isinstance(cache, list): + return len(cache) + if isinstance(cache, dict) and isinstance(cache.get("singBox"), list) and isinstance(cache.get("xray"), list): + return len(cache["singBox"]) + len(cache["xray"]) + raise ValueError("unsupported subscription cache shape") + + +def _subscription_proxy_count_text(path): + try: + return str(_subscription_proxy_count(path)) + except (OSError, ValueError): + return "?" + + +def _subscription_row(tag, source): + cache = _subscription_cache(tag) + if os.path.isfile(cache): + try: + age = datetime.datetime.fromtimestamp(os.path.getmtime(cache)).strftime("%Y-%m-%d %H:%M:%S") + except OSError: + age = "unknown" + count = _subscription_proxy_count_text(cache) + else: + age = "(no cache)" + count = "-" + print(f" {tag:<30} {age:<22} {count:<9} {source}") + + +def _subscription_list(): + static = _sub_tags() + runtime = _runtime_tags("subscription") + if not static and not runtime: + print("No subscriptions configured.") + return + print(f" {'TAG':<30} {'LAST UPDATED':<22} {'PROXIES':<9} SOURCE") + for tag in static: + _subscription_row(tag, "static") + for tag in runtime: + _subscription_row(tag, "runtime") + + +def cmd_subscription(verb="list", *args): + if verb == "list": + _subscription_list() + elif verb == "add": + _runtime_entry_add("subscription", *args) + elif verb in ("rm", "remove", "del"): + _runtime_entry_rm("subscription", *args) + elif verb == "update": + if not svc_exists("proxy-suite-subscription-update"): + die("The proxy is not enabled in this configuration.") + 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 ]") + + +# --- proxy auto: reachability probe ------------------------------------------- +# +# Fetches a URL through one exit after another (direct first) and finds one +# whose origin answers. The exits are the per-exit loopback listeners +# proxy-suite-socks opens for autoProxy (PROBE_EXITS_FILE); without them, only +# this host and the local proxy. The apex decides when any exit gets content +# from it; robots.txt breaks ties when the apex is refused everywhere. +# +# A fetch result is "||||". + +PROBE_BLOCK_REDIRECT = re.compile(r"unavailable|not-available|blocked|geo|region|restricted", re.I) +PROBE_WRITE_OUT = "%{exitcode}|%{time_appconnect}|%{http_code}|%{size_download}|%{redirect_url}" + + +def _probe_paths(): + fallback = env("PROBE_PATH_FALLBACK", "/robots.txt") + return [env("PROBE_PATH", "/"), *([fallback] if fallback else [])] + + +def _probe_exits_file(): + return env("PROBE_EXITS_FILE", "/run/proxy-suite-socks/probe-exits.json") + + +def _probe_site(url): + """Last two labels: only used to keep redirect following on one site.""" + host = url.split("://", 1)[-1] + host = re.split(r"[/:?#]", host, maxsplit=1)[0] + return ".".join(host.split(".")[-2:]) + + +def run_curl(argv): + return _run(argv, capture=True, quiet=True) + + +def _probe_fetch(domain, path, *selector): + """The first hop that is not a same-site redirect. + + A block can sit at the end of a chain (spotify.com -> www -> open -> + accounts -> why-not-available). `selector` picks the egress. + """ + url = f"https://{domain}{path}" + site = _probe_site(url) + curl = env("PROBE_CURL") + # An impersonating curl must keep its browser's own User-Agent. + ua = [] if curl else ["-A", env("PROBE_UA", "Mozilla/5.0 (X11; Linux x86_64) proxy-suite-probe")] + result = "" + for _ in range(6): + status, result = run_curl( + [ + curl or "curl", + "-sS", + "-o", + "/dev/null", + *ua, + "--connect-timeout", + env("PROBE_CONNECT_TIMEOUT", "8"), + "--max-time", + env("PROBE_MAX_TIME", "15"), + "-w", + PROBE_WRITE_OUT, + *selector, + url, + ] + ) + # Not a dead site: curl itself did not start. + if not result and status >= 126: + die(f"Cannot run {curl or 'curl'} (exit {status}).") + result = result or "99|0|000|0|" + if not re.fullmatch(r"3..", _probe_field(result, 3)) or _probe_redirect_is_block(result): + break + url = _probe_field(result, 5) + if not url or _probe_site(url) != site: + break + return result + + +def _probe_field(result, n): + fields = result.split("|", 4) + return fields[n - 1] if n <= len(fields) else "" + + +def _probe_tls_ok(result): + """curl reports appconnect 0 when TLS never finished.""" + return _probe_field(result, 2) not in ("", "0", "0.000000") + + +def _probe_redirect_is_block(result): + return bool(PROBE_BLOCK_REDIRECT.search(_probe_field(result, 5))) + + +def _probe_http_ok(result): + code = _probe_field(result, 3) + if re.fullmatch(r"2..", code) or code in ("401", "404"): + return True + if re.fullmatch(r"3..", code): + return not _probe_redirect_is_block(result) + return False + + +def _probe_exit_verdict(result): + """dead: failed before the origin spoke (the censor's doing, zapret's job). + + blocked: the origin answered and refused (a proxy hop can fix it). + """ + if not _probe_tls_ok(result) or _probe_field(result, 3) == "000": + return "dead" + return "ok" if _probe_http_ok(result) else "blocked" + + +def _probe_verdict(direct, via): + d = _probe_exit_verdict(direct) + v = _probe_exit_verdict(via) + if d == "ok": + return "ok" + if v == "ok": + return "censor" if d == "dead" else "destination" + return "unreachable" if d == "dead" else "both-fail" + + +def _probe_verdict_text(verdict, exit_tag): + return { + "ok": "reachable directly - nothing to do", + "destination": f"destination-side block - route via {exit_tag or 'proxy'}", + "censor": "censor-side block - zapret2 territory, do not proxy", + "both-fail": "fails through every egress - not an egress problem", + "unreachable": "no egress reaches it at all", + }.get(verdict, "inconclusive") + + +def _probe_describe(result): + if not _probe_tls_ok(result): + return f"no TLS (curl exit {_probe_field(result, 1)})" + status = _probe_field(result, 3) + if status == "000": + return f"TLS {_probe_field(result, 2)}s, then no response" + text = f"TLS {_probe_field(result, 2)}s, {status}, {_probe_field(result, 4)} bytes" + location = _probe_field(result, 5) + return f"{text} -> {location}" if location else text + + +def _probe_exits(): + """(tag, proxy url) per exit, in order; an empty url means this host.""" + path = _probe_exits_file() + if readable(path): + return [(_s(e["tag"]), f"http://127.0.0.1:{_s(e['port'])}") for e in read_json(path)] + return [("direct", ""), ("proxy", env("LOCAL_PROXY_URL", "http://127.0.0.1:1080"))] + + +def _probe_fetch_exit(domain, path, proxy_url): + if proxy_url: + return _probe_fetch(domain, path, "--proxy", proxy_url) + return _probe_fetch(domain, path, "--noproxy", "*") + + +def _walk(**fields): + return {"rows": [], "verdict": "", "exit": "", "path": "", "direct": "", "via": "", **fields} + + +def _probe_walk(domain, exits, paths, keep_going): + """Walks exits (direct first) and stops at the first that gets content. + + keep_going still tries the rest, keeping that first one. rows are + (tag, path, result, judgement) per request. + """ + w = _walk() + (direct_tag, direct_url), others = exits[0], exits[1:] + first_direct = "" + for path in paths: + direct = _probe_fetch_exit(domain, path, direct_url) + judgement = _probe_exit_verdict(direct) + w["rows"].append((direct_tag, path, direct, judgement)) + first_direct = first_direct or direct + if judgement == "ok" and not w["verdict"]: + w.update(verdict="ok", path=path, direct=direct) + if not keep_going: + return w + for tag, url in others: + result = _probe_fetch_exit(domain, path, url) + judgement = _probe_exit_verdict(result) + w["rows"].append((tag, path, result, judgement)) + if judgement == "ok" and not w["verdict"]: + w.update(verdict=_probe_verdict(direct, result), exit=tag, path=path, direct=direct, via=result) + if not keep_going: + return w + if not w["verdict"]: + dead = _probe_exit_verdict(first_direct) == "dead" + w.update(path=paths[0], direct=first_direct, verdict="unreachable" if dead else "both-fail") + return w + + +def _probe_stand_in(domain, exits, paths): + """--via: can exits[1] carry what direct reaches? + + It must get content on some path and fail on none where direct succeeds. + Verdict "ok" or "blocked". + """ + w = _walk(verdict="ok", exit=exits[1][0], path=paths[0]) + got = False + for path in paths: + direct = _probe_fetch_exit(domain, path, exits[0][1]) + via = _probe_fetch_exit(domain, path, exits[1][1]) + dj = _probe_exit_verdict(direct) + vj = _probe_exit_verdict(via) + w["rows"] += [(exits[0][0], path, direct, dj), (exits[1][0], path, via, vj)] + if path == paths[0]: + w.update(direct=direct, via=via) + got = got or vj == "ok" + if dj == "ok" and vj != "ok": + w["verdict"] = "blocked" + if not got: + w["verdict"] = "blocked" + return w + + +def cmd_proxy_probe(*args): + json_out = keep_going = False + domain = via = "" + wanted = None + args = list(args) + while args: + arg = args.pop(0) + if arg == "--json": + json_out = True + elif arg == "--keep-going": + keep_going = True + elif arg in ("--exits", "--via"): + if not args: + die("--exits needs a comma-separated list of exit tags" if arg == "--exits" else "--via needs an exit tag") + value = args.pop(0) + wanted = value.split(",") + if arg == "--via": + via = value + elif arg.startswith("-"): + die(f"Unknown option: {arg}") + else: + domain = arg + + if not domain: + usage("proxy auto probe [/path] [--json] [--keep-going] [--exits a,b | --via tag]") + domain = domain.split("://", 1)[-1] + paths = _probe_paths() + if "/" in domain: + domain, path = domain.split("/", 1) + paths = [f"/{path}"] + + if not svc_active("proxy-suite-socks"): + die("The local proxy (proxy-suite-socks) is not running; a probe needs its exits.") + + # direct first, then every exit in order, or the ones asked for in that order. + rows = _probe_exits() + exits = [row for row in rows if row[0] == "direct"] + for tag in [row[0] for row in rows] if wanted is None else wanted: + if tag != "direct": + exits += [row for row in rows if row[0] == tag][:1] + if not exits or exits[0][0] != "direct": + die(f"No direct exit to probe from ({_probe_exits_file()}).") + if via and len(exits) != 2: + die(f"No exit named {via} other than direct ({_probe_exits_file()}).") + + w = _probe_stand_in(domain, exits, paths) if via else _probe_walk(domain, exits, paths, keep_going) + + if json_out: + out = { + "domain": domain, + "url": f"https://{domain}{w['path']}", + "path": w["path"], + "verdict": w["verdict"], + "exit": w["exit"] or None, + "direct": w["direct"], + "proxy": w["via"], + "exits": [dict(zip(("tag", "path", "result", "judgement"), row)) for row in w["rows"]], + } + print(json.dumps(out, separators=(",", ":"), ensure_ascii=False)) + return + + print(f" domain {domain}") + print(f" probe https://{domain}{w['path']}") + print(" exits") + for tag, path, result, judgement in w["rows"]: + chosen = " <- chosen" if tag == w["exit"] and path == w["path"] else "" + print(f" {tag:<18} {path:<12} {_probe_describe(result):<44} {judgement}{chosen}") + if via: + if w["verdict"] == "ok": + print(f" verdict {via} answers it as well as direct does - it can carry it") + else: + print(f" verdict {via} answers it worse than direct does") + return + print(f" verdict {_probe_verdict_text(w['verdict'], w['exit'])}") + if w["verdict"] == "destination": + print(f' pin: proxy.routing.rules = [ {{ outbound = "{w["exit"]}"; domains = [ "{domain}" ]; }} ]') + elif w["verdict"] == "censor": + print(f" try: proxy-ctl zapret auto add {domain}") + + +def _autoproxy_dir(): + return env("AUTOPROXY_STATE_DIR", "/var/lib/proxy-suite/autoproxy") + + +def _require_autoproxy(): + if env("AUTOPROXY_ENABLED") != "1": + die("proxy.autoProxy is not enabled in this configuration.") + + +def _require_autoproxy_readable(path): + """Root-only without userControl: say so rather than show an empty queue.""" + if not os.path.isdir(path): + die("No autoProxy state yet - the prober has not completed a run.") + if not os.access(path, os.R_OK | os.X_OK): + die(f"Cannot read {path} - enable userControl, or run with sudo.") + + +def _autoproxy_state(path): + try: + state = read_json(os.path.join(path, "state.json")) + except (OSError, ValueError): + return {} + return state if isinstance(state, dict) else {} + + +def cmd_proxy_auto(verb="list", *args): + if verb in ("list", "learned"): + cmd_proxy_learned() + elif verb == "probe": + cmd_proxy_probe(*args) + elif verb == "learn": + cmd_proxy_learn(*args) + elif verb == "queue": + cmd_proxy_queue(*args) + else: + usage("proxy auto [list|probe|learn|queue]") + + +def _autoproxy_next_run(): + """Epoch seconds of the next timer run, None when none is armed. + + The timer is relative, so only list-timers knows it. + """ + _, out = systemctl("list-timers", "-o", "json", "proxy-suite-autoproxy.timer", capture=True, quiet=True) + try: + next_run = json.loads(out)[0].get("next") + except (ValueError, IndexError, AttributeError, TypeError, KeyError): + return None + return int(next_run) // 1000000 if isinstance(next_run, (int, float)) and next_run else None + + +def _in_time(epoch): + left = epoch - int(time.time()) + return "under a minute" if left < 60 else f"in {left // 60} min" + + +def _ago(at, now): + minutes = (now - (at or 0)) // 60 + return f"{minutes}m" if minutes < 120 else f"{minutes // 60}h" + + +def cmd_proxy_queue(top="20", *_): + _require_autoproxy() + if not re.fullmatch(r"[0-9]+", top): + usage("proxy auto queue [count]") + top = int(top) + path = _autoproxy_dir() + _require_autoproxy_readable(path) + + print("Requested with proxy-ctl proxy auto learn:") + requested = "" + for name in ("requests", "requests.taking"): + try: + requested += read_text(os.path.join(path, name)) + except OSError: + pass + for line in lines(requested) or ["(none)"]: + print(f" {line}") + + backlog = _autoproxy_state(path).get("backlog") or {} + print() + print(f"Waiting to be probed, most-dialled first ({len(backlog)}):") + if backlog: + entries = sorted(backlog.items(), key=lambda kv: -((kv[1] or {}).get("hits") or 0)) + for host, entry in entries[:top]: + print(f" {_s((entry or {}).get('hits'))}\t{host}") + if len(backlog) > top: + print(f" ... and {len(backlog) - top} more") + else: + print(" (none)") + + next_run = _autoproxy_next_run() + if next_run: + print() + print(f"Next run: {datetime.datetime.fromtimestamp(next_run):%H:%M:%S}, {_in_time(next_run)}") + elif systemctl("show", "-p", "ActiveState", "--value", "proxy-suite-autoproxy.service", capture=True, quiet=True)[1].strip() == "activating": + print() + print("Next run: one is running now") + + +def cmd_proxy_learned(*_): + _require_autoproxy() + path = _autoproxy_dir() + _require_autoproxy_readable(path) + state = _autoproxy_state(path) + domains = state.get("domains") or {} + + if not domains: + print("Nothing routed yet.") + else: + print("Routed through an exit:") + now = int(time.time()) + for domain, d in sorted(domains.items()): + host = _s(d.get("host")) + if d.get("verdict") == "slow": + host += ", which crawled directly" + print(f" {domain:<28} -> {_s(d.get('exit')):<12} (learned from {host}, checked {_ago(d.get('at'), now)} ago)") + + counts = {} + for h in (state.get("hosts") or {}).values(): + verdict = _s(h.get("verdict")) + counts[verdict] = counts.get(verdict, 0) + 1 + judged = " ".join(f"{v}={n}" for v, n in sorted(counts.items())) + print() + print(f"Hosts judged: {judged or 'none yet'}") + + +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") + try: + with open(requests, "a", encoding="utf-8") as f: + f.write(f"{host}\n") + except OSError: + die(f"Cannot write {requests} - re-run with sudo.") + print(f"Probing {host} through each exit...") + if systemctl("start", "proxy-suite-autoproxy-learn.service", quiet=True)[0]: + sys.stdout.flush() + print(f"The probe run failed. {host} is still queued and will be tried again at the next run.", file=sys.stderr) + die("Details: journalctl -u proxy-suite-autoproxy-learn -n 20") + h = (_autoproxy_state(path).get("hosts") or {}).get(host) + if h is None: + print("No verdict recorded; see: journalctl -u 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") + + +# --- zapret ------------------------------------------------------------------- + + +def cmd_zapret(*args): + if args[:1] == ("auto",): + cmd_zapret_auto(*args[1:]) + elif args[:1] == ("cutoff",): + cmd_zapret_cutoff(*args[1:]) + else: + _toggle("zapret-discord-youtube", "zapret", *args) + + +def _zapret_state_dir(): + return env("ZAPRET_STATE_DIR", "/var/lib/proxy-suite/zapret2") + + +def _zapret_auto_file(name): + return os.path.join(_zapret_state_dir(), name) + + +def _replace_lines(path, keep, extra=()): + """Rewrites path with the lines keep() accepts, plus extra. + + Via a temp file in the same directory, world-readable: unprivileged + proxy-ctl reads these lists too. + """ + try: + old = lines(read_text(path)) if os.path.exists(path) else [] + fd, tmp = tempfile.mkstemp(prefix=os.path.basename(path) + ".", dir=os.path.dirname(path) or ".") + except OSError: + die(f"Cannot write {path} - re-run with sudo.") + try: + with os.fdopen(fd, "w", encoding="utf-8") as f: + f.writelines(f"{line}\n" for line in [*filter(keep, old), *extra]) + os.chmod(tmp, 0o644) + os.replace(tmp, path) + except OSError: + try: + os.unlink(tmp) + except OSError: + pass + die(f"Cannot replace {path} - re-run with sudo.") + + +def _zapret_auto_edit(path, domain, action): + """nfqws2 re-reads a list when its mtime changes; no reload needed.""" + if action == "drop" and not os.path.exists(path): + return + _replace_lines(path, lambda line: line != domain, [domain] if action == "add" else []) + + +def _zapret_strategy_drop(domain): + """Forgets strategies remembered for domain or any parent of it. + + They are keyed by the domain circular rotates on (usually the apex); + z2k-state-persist.lua applies external deletions live. + """ + path = _zapret_auto_file("circular/state.tsv") + if not (os.path.isfile(path) and os.path.getsize(path) > 0): + return + + def keep(line): + fields = line.split("\t") + key = fields[1] if len(fields) > 1 else "" + return line.startswith("#") or (key != domain and not domain.endswith(f".{key}")) + + _replace_lines(path, keep) + + +def _truncate(path): + try: + open(path, "w").close() + except OSError: + die(f"Cannot write {path} - re-run with sudo.") + + +def cmd_zapret_auto(verb="list", domain="", *_): + if env("ZAPRET_AUTO_ENABLED") != "1": + die('Learned hostlists need zapret.engine = "zapret2".') + auto = _zapret_auto_file("zapret-hosts-auto.txt") + user = _zapret_auto_file("zapret-hosts-user.txt") + exclude = _zapret_auto_file("zapret-hosts-user-exclude.txt") + + if verb in ("add", "forget", "exclude") and not HOSTNAME.fullmatch(domain): + usage(f"zapret auto {verb} ") + if verb == "list": + if os.path.isfile(auto) and os.path.getsize(auto) > 0: + sys.stdout.write(read_text(auto)) + else: + print("No hostnames learned yet.") + elif verb == "add": + _zapret_auto_edit(user, domain, "add") + print(f"Pinned {domain} (always bypassed).") + elif verb == "forget": + _zapret_auto_edit(auto, domain, "drop") + _zapret_strategy_drop(domain) + print(f"Forgot {domain}. It is learned again if it keeps failing; 'exclude' prevents that.") + elif verb == "exclude": + _zapret_auto_edit(auto, domain, "drop") + _zapret_strategy_drop(domain) + _zapret_auto_edit(exclude, domain, "add") + print(f"Excluded {domain}. It is no longer touched or learned.") + elif verb == "clear": + _truncate(auto) + state = _zapret_auto_file("circular/state.tsv") + if os.path.exists(state): + _truncate(state) + print("Cleared learned hosts and remembered strategies.") + else: + usage("zapret auto [list|add|forget|exclude|clear]") + + +# --- zapret cutoff ------------------------------------------------------------ +# +# The 16 KB cutoff probe's verdict: which networks this line cuts after the +# handshake, and the whitelisted name that gets each through. Networks without a +# name are what the proxy fallback routes. + + +def _tsv(path): + try: + return [line.split("\t") for line in lines(read_text(path))] + except OSError: + return [] + + +def cmd_zapret_cutoff(verb="status", *_): + path = os.path.join(_zapret_state_dir(), "cutoff") + if env("ZAPRET_CUTOFF_ENABLED") != "1": + die('The cutoff probe needs zapret.engine = "zapret2" with zapret2.cutoff.enable.') + if verb == "probe": + try: + open(os.path.join(path, "force"), "w").close() + except OSError: + die(f"Cannot write {path} - re-run with sudo.") + print("Probing this line; this takes a few minutes...") + if systemctl("start", "proxy-suite-zapret2-cutoff.service")[0]: + die("The probe failed. Details: journalctl -u proxy-suite-zapret2-cutoff -n 30") + elif verb != "status": + usage("zapret cutoff [status|probe]") + + try: + ts = int(read_text(os.path.join(path, "ts")).strip()) + except (OSError, ValueError): + print("Not probed yet.") + return + try: + egress = read_text(os.path.join(path, "egress")).rstrip("\n") + except OSError: + egress = "" + print(f"Probed: {datetime.datetime.fromtimestamp(ts):%Y-%m-%d %H:%M} from {egress}") + asn = _tsv(os.path.join(path, "asn.txt")) + cut = sum(1 for row in asn if row[0][:1].isdigit()) + if not cut: + print("Cutoff: none on this line") + return + print(f"Cutoff: {cut} network(s)") + names = {row[0]: row[1] if len(row) > 1 else "" for row in _tsv(os.path.join(path, "sni.txt")) if row[0].isdigit()} + for row in asn: + if row[0].isdigit(): + print(f" AS{row[0]:<8} {names.get(row[0], 'no name - proxy fallback')}") + + +# --- where -------------------------------------------------------------------- +# +# What the runtime state says about one host. Hostlists and autoProxy both key +# on an apex, so a miss on the full name retries each parent label. + + +def _where_row(key, value): + print(f" {key:<14} {value}") + + +def _where_parents(domain): + while domain: + yield domain + domain = domain.split(".", 1)[1] if "." in domain else "" + + +def _where_in(names, domain): + """The first parent of domain that names holds, empty when none is.""" + return next((d for d in _where_parents(domain) if d in names), "") + + +def _where_in_list(path, domain): + if not readable(path): + return "" + try: + return _where_in(set(lines(read_text(path))), domain) + except OSError: + return "" + + +def cmd_where(domain="", *_): + if not domain: + usage("where ") + domain = domain.split("://", 1)[-1].split("/", 1)[0] + verdict = "" + _where_row("domain", domain) + + if svc_exists("proxy-suite-socks"): + _where_row("route mode", _route_mode_label(_route_mode_current())) + outbound = _status_outbound() + if outbound: + _where_row("outbound", outbound) + + if env("AUTOPROXY_ENABLED") == "1": + if not readable(os.path.join(_autoproxy_dir(), "state.json")): + _where_row("autoProxy", "state is not readable - enable userControl, or run with sudo") + else: + domains = _autoproxy_state(_autoproxy_dir()).get("domains") + hit = _where_in(domains if isinstance(domains, dict) else {}, domain) + if not hit: + _where_row("autoProxy", "not routed") + else: + d = domains[hit] + exit_tag = _s(d.get("exit")) + ago = _ago(d.get("at"), int(time.time())) + _where_row("autoProxy", f"routed via {exit_tag}, learned from {_s(d.get('host'))}, checked {ago} ago") + verdict = f"proxied via {exit_tag}" + + if env("ZAPRET_AUTO_ENABLED") == "1": + excluded = _where_in_list(_zapret_auto_file("zapret-hosts-user-exclude.txt"), domain) + pinned = _where_in_list(_zapret_auto_file("zapret-hosts-user.txt"), domain) + learned = _where_in_list(_zapret_auto_file("zapret-hosts-auto.txt"), domain) + if excluded: + _where_row("zapret2", f"excluded ({excluded}) - never bypassed, never learned") + elif pinned: + _where_row("zapret2", f"pinned ({pinned}) - always bypassed") + verdict = verdict or "direct, with the zapret2 bypass" + elif learned: + _where_row("zapret2", f"learned ({learned}) - bypassed") + verdict = verdict or "direct, with the zapret2 bypass" + else: + _where_row("zapret2", "not learned, not pinned, not excluded") + + print(f" -> {verdict or 'nothing runtime matches it; the configured routing decides'}") + print(" Declared proxy.routing.rules are not visible here. Test what reaches it:") + print(f" proxy-ctl proxy auto probe {domain}") + + +# --- awg ---------------------------------------------------------------------- + + +def _awg_service(profile): + return f"proxy-suite-awg-{profile}" + + +def _active_awg_profiles(): + return [p for p in _awg_profiles() if svc_active(_awg_service(p))] + + +def cmd_awg(verb="list", *args): + profiles = _awg_profiles() + if args and args[0] not in profiles: + die(f"Unknown AmneziaWG profile: {args[0]}") + if verb in ("list", "status"): + if not profiles: + print("No AmneziaWG profiles configured.") + return + print(f" {'PROFILE':<24} STATUS") + for profile in profiles: + print(f" {profile:<24} {svc_state(_awg_service(profile)) or 'unknown'}") + elif verb == "on": + if not args: + usage("awg on ") + must("start", _awg_service(args[0])) + elif verb in ("off", "restart"): + targets = list(args[:1]) or _active_awg_profiles() + if not targets: + if verb == "off": + return + die("No AmneziaWG profile is active.") + for profile in targets: + must("stop" if verb == "off" else "restart", _awg_service(profile)) + else: + usage("awg [list] | on | off [profile] | restart [profile]") + + +# --- apps --------------------------------------------------------------------- + +SLICE_ROUTES = { + "tun": ("proxy-suite-per-app-tun", "PER_APP_ROUTING_TUN_ENABLED", "perAppRouting.tun.enable"), + "tproxy": ("proxy-suite-per-app-tproxy", "PER_APP_ROUTING_TPROXY_ENABLED", "perAppRouting.tproxy.enable"), + "zapret": ("proxy-suite-per-app-zapret", "PER_APP_ROUTING_ZAPRET_ENABLED", "perAppRouting.zapret.enable"), +} + + +def _per_app_profiles(): + try: + return read_json(env("PER_APP_ROUTING_PROFILES_FILE")) + except (OSError, ValueError): + die(f"Cannot read perAppRouting profiles: {env('PER_APP_ROUTING_PROFILES_FILE')}") + + +def _ensure_app_routing(): + if env("PER_APP_ROUTING_ENABLED") != "1": + die("perAppRouting is not enabled in this configuration.") + + +def _check_no_global_proxy(route): + for svc in ("proxy-suite-tun", "proxy-suite-tproxy"): + if svc_active(f"{svc}.service"): + die(f"Global {svc}.service is active. Stop it before using route={route} profiles.") + + +def _has_units(*args): + return bool(re.search(".", systemctl(*args, capture=True)[1])) + + +def _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc): + if _has_units("--user", "list-units", "--type=scope", "--state=running", "--plain", "--no-legend", f"{slice_base}-*"): + return + systemctl("stop", user_svc) + systemctl("--user", "stop", anchor_unit) + if not _has_units("list-units", "--type=service", "--state=active", "--plain", "--no-legend", f"{slice_base}-user@*.service"): + systemctl("stop", backend_svc) + + +def _wrap_slice(slice_base, profile, backend_svc, cmd): + """Runs cmd in a user scope inside the route's slice, then stops what went idle.""" + uid = os.getuid() + scope_unit = f"{slice_base}-{profile}-{os.getpid()}" + anchor_unit = f"{slice_base}-anchor.service" + user_svc = f"{slice_base}-user@{uid}.service" + # SIGTERM still cleans up, as it did behind bash's EXIT trap. + signal.signal(signal.SIGTERM, lambda *_: sys.exit(143)) + try: + status = systemctl("--user", "start", anchor_unit)[0] + status = status or systemctl("start", backend_svc)[0] + status = status or systemctl("start", user_svc)[0] + if not status: + status = _run_foreground( + [ + "systemd-run", + "--user", + "--scope", + "--quiet", + "--collect", + "--same-dir", + f"--slice={slice_base}", + f"--unit={scope_unit}", + *cmd, + ] + ) + finally: + _cleanup_slice_if_idle(slice_base, anchor_unit, user_svc, backend_svc) + sys.exit(status) + + +def cmd_apps(verb="list", *args): + _ensure_app_routing() + if verb == "list": + profiles = _per_app_profiles() + if not profiles: + print("No perAppRouting profiles configured.") + return + print(f" {'PROFILE':<24} ROUTE") + for p in profiles: + print(f" {_s(p.get('name')):<24} {_s(p.get('route'))}") + elif verb == "run": + cmd_apps_run(*args) + else: + usage("apps [list] | run -- [args]") + + +def cmd_apps_run(profile="", *cmd): + if cmd[:1] == ("--",): + cmd = cmd[1:] + if not profile or not cmd: + usage("apps run -- [args]") + + route = next((_s(p.get("route")) for p in _per_app_profiles() if p.get("name") == profile), "") + if not route: + die(f"Unknown perAppRouting profile: {profile}") + + if route == "direct": + _exec(list(cmd)) + elif route == "proxychains": + if env("PER_APP_ROUTING_PROXYCHAINS_ENABLED") != "1": + die(f"Profile '{profile}' uses route=proxychains, but perAppRouting.proxychains.enable is false.") + config = env("PROXYCHAINS_CONFIG") + if not readable(config): + die(f"Proxychains config is not readable: {config} (is proxy-suite-socks running?)") + _exec(["proxychains4", *env("PROXYCHAINS_QUIET_ARG").split(), "-f", config, *cmd]) + elif route in SLICE_ROUTES: + slice_base, enabled, option = SLICE_ROUTES[route] + _check_no_global_proxy(route) + if env(enabled) != "1": + die(f"Profile '{profile}' uses route={route}, but {option} is false.") + _wrap_slice(slice_base, profile, f"{slice_base}.service", list(cmd)) + else: + die(f"Route backend '{route}' is not implemented.") + + +# --- inbounds ----------------------------------------------------------------- + + +def _inbound_links(): + """Links carry listener credentials, so the file is root/group-only.""" + path = env("INBOUNDS_LINKS_FILE") + if not os.path.isfile(path): + die("No share links available. Is proxy-suite-inbounds running, and is inbounds.shareLinks enabled?") + if not readable(path): + die("Share links are not readable by this user. Enable userControl, or run as root.") + return read_json(path) + + +def _inbound_link_for(tag, user="", *_): + matches = [x for x in _inbound_links() if x.get("tag") == tag and (not user or x.get("user") == user)] + if not matches: + die(f"Unknown inbound, or no share link for it: {tag}") + if len(matches) > 1: + sys.stdout.flush() + print(f"Multiple users match '{tag}'; specify one of:", file=sys.stderr) + for x in matches: + print(f" {_s(x.get('user'))}", file=sys.stderr) + sys.exit(1) + return _s(matches[0].get("link")) + + +def _human_bytes(b): + if b >= 1073741824: + return f"{b / 1073741824:.1f} GiB" + if b >= 1048576: + return f"{b / 1048576:.1f} MiB" + if b >= 1024: + return f"{b / 1024:.0f} KiB" + return f"{b:g} B" + + +def _today(): + return datetime.date.today() + + +def _inbound_stats(days): + """Per-user traffic over the last `days` days, newest first, then totals.""" + path = env("INBOUNDS_STATS_FILE", "/var/lib/proxy-suite/inbound-stats.json") + if not re.fullmatch(r"[1-9][0-9]*", days): + usage("inbounds stats [days]") + # Collect what XRay counted since the last run first; root and userControl + # members may, anyone else reads what the timer last wrote. + systemctl("--no-ask-password", "start", "proxy-suite-inbound-stats.service", quiet=True) + if not os.path.exists(path): + die("No traffic recorded yet - the collector runs every 5 minutes.") + if not readable(path): + die(f"Cannot read {path} - enable userControl, or run with sudo.") + since = (_today() - datetime.timedelta(days=int(days) - 1)).isoformat() + print(f"Traffic through the inbounds since {since}, by user:") + + records = [ + (day, user, (c or {}).get("down") or 0, (c or {}).get("up") or 0) + for day, users in (read_json(path).get("days") or {}).items() + if day >= since + for user, c in users.items() + ] + if not records: + print(" (nothing recorded)") + return + row = " {:<12} {:<20} {:>10} {:>10}" + print(row.format("DAY", "USER", "DOWN", "UP")) + # Newest day first, users in order within a day. + for day, user, down, up in sorted(sorted(records, key=lambda r: r[1]), key=lambda r: r[0], reverse=True): + print(row.format(day, user, _human_bytes(down), _human_bytes(up))) + totals = {} + for _, user, down, up in records: + d, u = totals.get(user, (0, 0)) + totals[user] = (d + down, u + up) + total = " {:<33} {:>10} {:>10}" + print() + print(total.format("TOTAL", "DOWN", "UP")) + for user, (down, up) in sorted(totals.items()): + print(total.format(user, _human_bytes(down), _human_bytes(up))) + + +def _inbound_subscriptions(*args): + """Without a user: user names only, since each URL is its user's secret.""" + user = "" + qr = False + for arg in args: + if arg == "--qr": + qr = True + else: + user = arg + path = env("INBOUNDS_SUBS_FILE", "/run/proxy-suite-inbounds/subscriptions.json") + base = env("INBOUNDS_SUB_BASE_URL") + if not os.path.isfile(path): + die("No subscriptions available. Is proxy-suite-inbounds running, and is inbounds.subscriptions enabled?") + if not readable(path): + die("Subscriptions are not readable by this user. Enable userControl, or run as root.") + subs = read_json(path) + if not user: + if qr: + usage("inbounds sub --qr") + for s in subs: + print(f" {_s(s.get('user'))}") + sys.stdout.flush() + print("Show one with: proxy-ctl inbounds sub [--qr]", file=sys.stderr) + return + token = next((s.get("token") for s in subs if s.get("user") == user), None) + if not token: + die(f"No subscription for user: {user}") + if base: + _emit(f"{base.removesuffix('/')}/{_s(token)}", qr) + else: + if qr: + die("A QR code needs inbounds.subscriptions.baseUrl.") + print(f"{path.removesuffix('.json')}/{_s(token)}") + sys.stdout.flush() + print("Set inbounds.subscriptions.baseUrl to get a URL instead of a path.", file=sys.stderr) + + +def cmd_inbounds(verb="list", *args): + if env("INBOUNDS_ENABLED") != "1": + die("inbounds is not enabled in this configuration.") + if verb == "list": + state = svc_state("proxy-suite-inbounds") + row = " {:<24} {:<16} {:<14} {:<8} {}" + print(row.format("TAG", "USER", "TYPE", "PORT", "STATE")) + for x in _inbound_links(): + print(row.format(*(_s(x.get(k)) for k in ("tag", "user", "type", "port")), state)) + elif verb in ("link", "qr"): + rest = [a for a in args if a != "--qr"] + if not rest: + usage("inbounds link [user] [--qr]") + _emit(_inbound_link_for(*rest), verb == "qr" or "--qr" in args) + elif verb == "stats": + _inbound_stats(args[0] if args else "7") + elif verb == "sub": + _inbound_subscriptions(*args) + else: + usage("inbounds [list] | link [user] [--qr] | sub [user] [--qr] | stats [days]") + + +# --- main --------------------------------------------------------------------- + +# Old spellings: still accepted, not in the help. +ALIASES = { + "tun": ["proxy", "tun"], + "tproxy": ["proxy", "tproxy"], + "outbounds": ["proxy", "outbounds"], + "select": ["proxy", "select"], + "route-mode": ["proxy", "mode"], + "subscription": ["proxy", "subs"], + "wrap": ["apps", "run"], +} + + +def cmd_logs(*units): + if units: + _exec(["journalctl", "-fu", *units]) + # journalctl takes unit globs, so the default needs no unit list of its own. + _exec(["journalctl", "-f", "-u", "proxy-suite-*", "-u", "zapret-discord-youtube"]) + + +COMMANDS = { + "help": lambda *_: sys.stdout.write(HELP), + "-h": lambda *_: sys.stdout.write(HELP), + "--help": lambda *_: sys.stdout.write(HELP), + "status": cmd_status, + "restart": cmd_restart, + "logs": cmd_logs, + "proxy": cmd_proxy, + "zapret": cmd_zapret, + "awg": cmd_awg, + "ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args), + "apps": cmd_apps, + "inbounds": cmd_inbounds, + "where": cmd_where, + "__complete": cmd_complete, +} + + +def main(argv): + # Die quietly on a closed pipe (`proxy-ctl help | head`), as a shell tool does. + signal.signal(signal.SIGPIPE, signal.SIG_DFL) + if argv and argv[0] in ALIASES: + argv = ALIASES[argv[0]] + argv[1:] + cmd, args = (argv[0], argv[1:]) if argv else ("status", []) + if cmd not in COMMANDS: + sys.stderr.write(HELP) + sys.exit(1) + try: + COMMANDS[cmd](*args) + except KeyboardInterrupt: + sys.exit(130) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py new file mode 100644 index 0000000..863b41e --- /dev/null +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -0,0 +1,410 @@ +#!/usr/bin/env python3 + +import contextlib +import datetime +import io +import json +import os +import tempfile +import unittest +from unittest import mock + +import proxy_ctl as ctl + + +def run(fn, *args): + """(exit status, stdout, stderr) of a proxy-ctl function.""" + out, err = io.StringIO(), io.StringIO() + status = 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + fn(*args) + except SystemExit as e: + status = e.code + return status, out.getvalue(), err.getvalue() + + +def ok(fn, *args): + status, out, err = run(fn, *args) + assert status == 0, (status, out, err) + return out + + +class EnvTest(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.dir = self.tmp.name + patcher = mock.patch.dict(os.environ, {}, clear=False) + patcher.start() + self.addCleanup(patcher.stop) + self.addCleanup(self.tmp.cleanup) + + def path(self, name): + return os.path.join(self.dir, name) + + def write(self, name, content): + path = self.path(name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w") as f: + f.write(content if isinstance(content, str) else json.dumps(content)) + return path + + def patch(self, name, value): + patcher = mock.patch.object(ctl, name, value) + patcher.start() + self.addCleanup(patcher.stop) + + +# The verdict table, fed tuples measured on a real censored network. +class ProbeVerdictTest(unittest.TestCase): + def expect(self, want, direct, via): + self.assertEqual(ctl._probe_verdict(direct, via), want, (direct, via)) + + def test_table(self): + # Origin refuses direct, accepts the proxy: chatgpt.com/robots.txt. + self.expect("destination", "0|0.146175|403|6633|", "0|0.230116|200|4302|") + # The same through a redirect: claude.ai/robots.txt. + self.expect("destination", "0|0.141625|302|143|https://claude.com/app-unavailable-in-region", "0|0.181276|200|281|") + # TLS never completed: censorship, zapret's job. + self.expect("censor", "35|0.000000|000|0|", "0|0.119348|200|6258|") + # Handshake, then silence: the post-handshake throttle. + self.expect("censor", "0|0.125029|000|0|", "0|0.143772|200|32881|") + # Direct works. Nothing to do, whoever else also works. + self.expect("ok", "0|0.099546|200|2678|", "0|0.146822|200|2678|") + # robots.txt legitimately absent is not a failure. + self.expect("ok", "0|0.161330|404|559|", "0|0.214667|404|559|") + # An ordinary redirect must not read as a block. + self.expect("ok", "0|0.10|301|0|https://www.example.com/robots.txt", "0|0.20|301|0|https://www.example.com/robots.txt") + # Refused everywhere: not an egress problem. + self.expect("both-fail", "0|0.10|403|100|", "0|0.20|403|100|") + # Nothing reaches it at all - a dead name, not a blocked one. + self.expect("unreachable", "6|0.000000|000|0|", "35|0.000000|000|0|") + + +class ProbeFetchTest(EnvTest): + def test_redirect_chains(self): + calls = [] + table = { + "https://spotify.test/": "0|0.1|301|0|https://www.spotify.test/", + "https://www.spotify.test/": "0|0.1|301|0|https://open.spotify.test/", + "https://open.spotify.test/": "0|0.1|302|93|https://accounts.spotify.test/login", + "https://accounts.spotify.test/login": "0|0.1|301|0|https://www.spotify.test/int/why-not-available/", + "https://redir.test/": "0|0.1|301|0|https://elsewhere.example/", + "https://loop.test/": "0|0.1|301|0|https://loop.test/", + } + + def curl(argv): + calls.append(argv[-1]) + return 0, table.get(argv[-1], "0|0.1|200|10|") + + self.patch("run_curl", curl) + # spotify.com: the block is four same-site hops in. + self.assertEqual(ctl._probe_exit_verdict(ctl._probe_fetch("spotify.test", "/", "--noproxy", "*")), "blocked") + # Leaving the site ends the walk. + self.assertEqual(ctl._probe_exit_verdict(ctl._probe_fetch("redir.test", "/", "--noproxy", "*")), "ok") + # A redirect loop inside the site still stops. + calls.clear() + ctl._probe_fetch("loop.test", "/", "--noproxy", "*") + self.assertLessEqual(len(calls), 6) + + def test_curl_that_cannot_start(self): + # An error, not a dead site. + os.environ.update(PROBE_CURL="/nonexistent", PROBE_EXITS_FILE="/nonexistent") + self.patch("svc_active", lambda unit: True) + status, _, err = run(ctl.cmd_proxy_probe, "--json", "x.test") + self.assertNotEqual(status, 0) + self.assertIn("Cannot run /nonexistent", err) + + +class ProbeWalkTest(EnvTest): + def setUp(self): + super().setUp() + self.patch("svc_active", lambda unit: True) + os.environ["PROBE_EXITS_FILE"] = "/nonexistent" + + def probe(self, *args): + return json.loads(ok(ctl.cmd_proxy_probe, "--json", *args)) + + def probe_with(self, apex_direct, apex_proxy, robots_direct, robots_proxy): + """No listener index: only this host and the local proxy.""" + + def fetch(domain, path, flag, url): + if path == "/": + return apex_direct if flag == "--noproxy" else apex_proxy + return robots_direct if flag == "--noproxy" else robots_proxy + + self.patch("_probe_fetch", fetch) + return self.probe("example.test") + + # --- which path decides: the apex, robots.txt only breaks ties --- + def test_apex_decides(self): + # last.fm: apex geo-blocked, robots.txt served everywhere. + out = self.probe_with("0|0.11|403|424|", "0|0.17|200|59809|", "0|0.11|200|400|", "0|0.17|200|400|") + self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/")) + + def test_robots_breaks_ties(self): + # chatgpt.com: apex 403 everywhere, robots.txt separates. + out = self.probe_with("0|0.14|403|6633|", "0|0.23|403|8442|", "0|0.14|403|6633|", "0|0.23|200|4302|") + self.assertEqual((out["verdict"], out["url"]), ("destination", "https://example.test/robots.txt")) + + def test_working_apex_is_not_second_guessed(self): + out = self.probe_with("0|0.10|200|500|", "0|0.20|200|500|", "0|0.10|403|10|", "0|0.20|200|10|") + self.assertEqual(out["verdict"], "ok") + + # --- walking more than two exits --- + def use_exits(self, fetch): + os.environ["PROBE_EXITS_FILE"] = self.write( + "exits.json", + [{"i": 0, "tag": "direct", "port": 18540}, {"i": 1, "tag": "fi", "port": 18541}, {"i": 2, "tag": "de", "port": 18542}], + ) + self.patch("_probe_fetch", fetch) + + def test_multi_exit(self): + # Direct and the first proxy share a WAF; only the third exit gets through. + # Every exit, direct included, goes through its pinned listener. + self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|") + out = self.probe("sekai.test") + self.assertEqual((out["verdict"], out["exit"]), ("destination", "de")) + + # --keep-going tries every exit but keeps the first that worked. + out = self.probe("--keep-going", "--exits", "de,fi", "sekai.test") + self.assertEqual(out["exit"], "de") + self.assertEqual([e["tag"] for e in out["exits"]], ["direct", "de", "fi", "direct", "de", "fi"]) + + # --exits restricts and orders the walk; direct is always tried first. + out = self.probe("--exits", "de", "sekai.test") + self.assertEqual([e["tag"] for e in out["exits"]], ["direct", "de"]) + + # An empty list probes direct only (every exit shares one network). + out = self.probe("--exits", "", "sekai.test") + self.assertEqual({e["tag"] for e in out["exits"]}, {"direct"}) + self.assertIsNone(out["exit"]) + + # --via: can this exit carry what direct reaches? + out = self.probe("--via", "de", "sekai.test") + self.assertEqual(out["verdict"], "ok") + self.assertEqual({e["tag"] for e in out["exits"]}, {"de", "direct"}) + self.assertEqual(self.probe("--via", "fi", "sekai.test")["verdict"], "blocked") + self.assertNotEqual(run(ctl.cmd_proxy_probe, "--json", "--via", "nowhere", "sekai.test")[0], 0) + + # A given path is probed as is, for that probe only. + out = self.probe("--via", "de", "sekai.test/robots.txt") + self.assertEqual(out["url"], "https://sekai.test/robots.txt") + self.assertEqual({e["path"] for e in out["exits"]}, {"/robots.txt"}) + out = self.probe("--via", "fi", "sekai.test") + self.assertEqual({e["path"] for e in out["exits"]}, {"/", "/robots.txt"}) + + def test_via_refused_front_page(self): + # Refused a front page direct gets: not a stand-in (www.reddit.com). + self.use_exits(lambda domain, path, flag, url: "0|0.10|403|190240|" if url.endswith(":18541") and path == "/" else "0|0.10|200|500|") + self.assertEqual(self.probe("--via", "fi", "geo.test")["verdict"], "blocked") + + def test_via_robots_decides(self): + # i.pximg.net: the front page is 400 everywhere, so robots.txt decides. + self.use_exits(lambda domain, path, flag, url: "0|0.10|400|0|" if path == "/" else "0|0.10|200|43|") + self.assertEqual(self.probe("--via", "fi", "cdn.test")["verdict"], "ok") + + def test_text_output(self): + self.use_exits(lambda domain, path, flag, url: "0|0.10|200|500|" if url.endswith(":18542") else "0|0.10|403|919|") + out = ok(ctl.cmd_proxy_probe, "sekai.test") + self.assertRegex(out, r"(?m)^ de +/ +TLS 0\.10s, 200, 500 bytes +ok <- chosen$") + self.assertIn('pin: proxy.routing.rules = [ { outbound = "de"; domains = [ "sekai.test" ]; } ]', out) + + +class AutoProxyTest(EnvTest): + def setUp(self): + super().setUp() + os.environ.update(AUTOPROXY_ENABLED="1", AUTOPROXY_STATE_DIR=self.dir) + + def state_on_start(self, state): + def systemctl(*args, **kw): + if args[:1] == ("start",): + self.write("state.json", state) + return 0, "" + + self.patch("systemctl", systemctl) + + def test_learn(self): + self.state_on_start( + { + "domains": {"last.fm": {"verdict": "destination", "exit": "primary", "host": "www.last.fm"}}, + "hosts": {"www.last.fm": {"domain": "last.fm", "verdict": "destination", "exit": "primary"}}, + } + ) + with mock.patch.dict(os.environ, AUTOPROXY_ENABLED="0"): + self.assertNotEqual(run(ctl.cmd_proxy_learn, "www.last.fm")[0], 0) + # It lands in a root-owned file and then in a URL: hostnames only. + self.assertNotEqual(run(ctl.cmd_proxy_learn, "x;rm -rf /")[0], 0) + self.assertNotEqual(run(ctl.cmd_proxy_learn, "-evil.test/path")[0], 0) + out = ok(ctl.cmd_proxy_learn, "www.last.fm") + self.assertEqual(ctl.read_text(self.path("requests")), "www.last.fm\n") + self.assertIn("last.fm: destination - routed via primary", out) + + def test_learn_nothing_to_route(self): + # A verdict that routes nothing is kept for its host and reported. + self.state_on_start({"domains": {}, "hosts": {"api.example.test": {"domain": "example.test", "verdict": "ok", "exit": None}}}) + self.assertIn("api.example.test: ok - nothing to route", ok(ctl.cmd_proxy_learn, "api.example.test")) + + def test_learn_failed_run(self): + # A failed run is reported in plain words, and the request is not lost. + self.patch("systemctl", lambda *args, **kw: (1, "")) + status, _, err = run(ctl.cmd_proxy_learn, "www.last.fm") + self.assertNotEqual(status, 0) + self.assertIn("still queued", err) + self.assertIn("www.last.fm\n", ctl.read_text(self.path("requests"))) + + def test_queue_and_learned(self): + self.patch("systemctl", lambda *args, **kw: (0, "")) + self.write("requests", "www.last.fm\n") + self.write( + "state.json", + { + "domains": {"spotify.com": {"verdict": "destination", "exit": "primary", "host": "www.spotify.com", "at": 0}}, + "hosts": { + "www.spotify.com": {"domain": "spotify.com", "verdict": "destination", "exit": "primary"}, + "gew1-spclient.spotify.com": {"domain": "spotify.com", "verdict": "ok", "exit": None}, + }, + "backlog": {"a.example": {"domain": "example", "hits": 2}, "b.example": {"domain": "example", "hits": 9}}, + }, + ) + q = ok(ctl.cmd_proxy_queue) + self.assertIn("\n www.last.fm\n", q) + # Most-dialled first. + self.assertLess(q.index("b.example"), q.index("a.example")) + learned = ok(ctl.cmd_proxy_learned) + self.assertRegex(learned, r"spotify.com .*-> primary") + self.assertIn("ok=1", learned) + + @unittest.skipIf(os.geteuid() == 0, "root reads anything") + def test_unreadable_state_asks_for_sudo(self): + os.chmod(self.dir, 0) + try: + status, _, err = run(ctl.cmd_proxy_queue) + finally: + os.chmod(self.dir, 0o755) + self.assertNotEqual(status, 0) + self.assertIn("enable userControl, or run with sudo", err) + + +class InboundsTest(EnvTest): + def test_stats(self): + self.patch("systemctl", lambda *args, **kw: (0, "")) + self.patch("_today", lambda: datetime.date(2026, 9, 11)) + os.environ["INBOUNDS_STATS_FILE"] = self.write( + "stats.json", + { + "days": { + "2026-09-11": {"fufsob": {"down": 6000000, "up": 4000}, "phone": {"up": 0}}, + "2026-09-10": {"fufsob": {"down": 1073741824, "up": 1048576}}, + "2026-09-01": {"fufsob": {"down": 1, "up": 1}}, + } + }, + ) + out = ok(ctl._inbound_stats, "2") + # Newest day first, sizes readable, then totals over the period. + self.assertLess(out.index(" 2026-09-11"), out.index(" 2026-09-10")) + self.assertNotIn("2026-09-01", out) + self.assertRegex(out, r"(?m)^ 2026-09-11 +fufsob +5\.7 MiB +4 KiB$") + self.assertRegex(out, r"(?m)^ 2026-09-11 +phone +0 B +0 B$") + self.assertRegex(out, r"(?m)^ 2026-09-10 +fufsob +1\.0 GiB +1\.0 MiB$") + self.assertRegex(out, r"(?m)^ fufsob +1\.0 GiB +1\.0 MiB$") + self.assertNotEqual(run(ctl._inbound_stats, "0")[0], 0) + # Nothing collected yet says so, rather than printing an empty table. + os.environ["INBOUNDS_STATS_FILE"] = self.path("none.json") + status, _, err = run(ctl._inbound_stats, "7") + self.assertNotEqual(status, 0) + self.assertIn("No traffic recorded yet", err) + + def test_subscriptions(self): + os.environ["INBOUNDS_SUBS_FILE"] = self.write("subs.json", [{"user": "fufsob", "token": "aaa"}, {"user": "teri", "token": "bbb"}]) + os.environ["INBOUNDS_SUB_BASE_URL"] = "https://vpn.example/sub/" + self.assertEqual(ok(ctl._inbound_subscriptions, "teri"), "https://vpn.example/sub/bbb\n") + # Without a user: names only, never a token. + out = ok(ctl._inbound_subscriptions) + self.assertEqual(out, " fufsob\n teri\n") + self.assertNotEqual(run(ctl._inbound_subscriptions, "nobody")[0], 0) + # Without a base URL: the file path, and no QR code. + os.environ["INBOUNDS_SUB_BASE_URL"] = "" + self.assertEqual(ok(ctl._inbound_subscriptions, "fufsob"), self.path("subs") + "/aaa\n") + self.assertNotEqual(run(ctl._inbound_subscriptions, "fufsob", "--qr")[0], 0) + + +class AppsRunTest(EnvTest): + def setUp(self): + super().setUp() + self.calls = [] + self.active = set() + self.execed = None + os.environ.update( + PER_APP_ROUTING_ENABLED="1", + PER_APP_ROUTING_PROXYCHAINS_ENABLED="1", + PER_APP_ROUTING_TUN_ENABLED="1", + PER_APP_ROUTING_TPROXY_ENABLED="1", + PER_APP_ROUTING_ZAPRET_ENABLED="1", + PROXYCHAINS_QUIET_ARG="-q", + PROXYCHAINS_CONFIG=self.write("proxychains.conf", ""), + PER_APP_ROUTING_PROFILES_FILE=self.write( + "profiles.json", + [{"name": n, "route": n} for n in ("direct", "proxychains", "tun", "tproxy", "zapret")], + ), + ) + + def systemctl(*args, **kw): + self.calls.append(args) + if args[:2] == ("is-active", "--quiet"): + return (0 if args[2] in self.active else 3), "" + return 0, "" + + def exec_(argv): + self.execed = argv + raise SystemExit(0) + + self.patch("systemctl", systemctl) + self.patch("_exec", exec_) + self.patch("_run_foreground", lambda argv: self.calls.append(tuple(argv)) or self.scope_status) + self.scope_status = 0 + self.addCleanup(lambda: ctl.signal.signal(ctl.signal.SIGTERM, ctl.signal.SIG_DFL)) + + def test_direct_and_proxychains_exec(self): + run(ctl.cmd_apps, "run", "direct", "--", "firefox", "-P") + self.assertEqual(self.execed, ["firefox", "-P"]) + run(ctl.cmd_apps, "run", "proxychains", "--", "curl", "x") + self.assertEqual(self.execed, ["proxychains4", "-q", "-f", os.environ["PROXYCHAINS_CONFIG"], "curl", "x"]) + os.environ["PROXYCHAINS_CONFIG"] = self.path("missing.conf") + self.assertIn("Proxychains config is not readable", run(ctl.cmd_apps, "run", "proxychains", "--", "curl")[2]) + + def test_slice_routes(self): + for route in ("tun", "tproxy", "zapret"): + self.calls.clear() + status, _, _ = run(ctl.cmd_apps, "run", route, "--", "curl", "x") + self.assertEqual(status, 0) + base = f"proxy-suite-per-app-{route}" + scope = next(c for c in self.calls if c[0] == "systemd-run") + self.assertIn(f"--unit={base}-{route}-{os.getpid()}", scope) + self.assertIn(f"--slice={base}", scope) + self.assertEqual(scope[-2:], ("curl", "x")) + self.assertIn(("start", f"{base}-user@{os.getuid()}.service"), self.calls) + # Nothing else runs in the slice, so it is torn down afterwards. + self.assertIn(("stop", f"{base}.service"), self.calls) + self.assertIn(("--user", "stop", f"{base}-anchor.service"), self.calls) + + def test_cleanup_when_scope_fails(self): + self.scope_status = 3 + status, _, _ = run(ctl.cmd_apps, "run", "tun", "--", "false") + self.assertEqual(status, 3) + self.assertIn(("stop", "proxy-suite-per-app-tun.service"), self.calls) + + def test_global_proxy_refused(self): + self.active = {"proxy-suite-tun.service"} + status, _, err = run(ctl.cmd_apps, "run", "tproxy", "--", "curl") + self.assertNotEqual(status, 0) + self.assertIn("Global proxy-suite-tun.service is active", err) + self.assertFalse(any(c[0] == "systemd-run" for c in self.calls)) + + def test_disabled_route(self): + os.environ["PER_APP_ROUTING_ZAPRET_ENABLED"] = "0" + self.assertIn("perAppRouting.zapret.enable is false", run(ctl.cmd_apps, "run", "zapret", "--", "curl")[2]) + + +if __name__ == "__main__": + unittest.main()