feat: add proxy tests

This commit is contained in:
fufsob committed 2026-09-14 05:31:20 +00:00
1 parent 0af4104fdb
commit b8903a094d
9 files changed
+325 -16

No files matched your search

+2
View File
@@ -114,6 +114,8 @@ A group without a verb shows its status or list.
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay)
proxy select [<tag>|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
+1 -1
View File
@@ -1259,7 +1259,7 @@ pkgs.sing-box
<a id="services-proxy-suite-proxy-singbox-clashapiport"></a>
## services\.proxy-suite\.proxy\.singBox\.clashApiPort
Port of sing-box’s Clash API, used with selection “selector” or “urltest”\.
Loopback port of sing-box’s Clash API, which switches and tests outbounds\.
*Type:*
16 bit unsigned integer; between 0 and 65535 (both inclusive)
+1 -1
View File
@@ -3,7 +3,7 @@
# $below in any second (paced streams burst, so they read fast). Probe listeners are
# skipped; chains[0] is the carrying exit.
[.[] | [(.connections // [])[]
| select((.metadata.type // "") | test("/probe-in-") | not)
| select((.metadata.type // "") | test("/(probe-in-|proxy-suite-test-in$)") | not)
| {id, host: (.metadata.host // ""), exit: (.chains[0] // ""), d: .download}]]
| . as $s
| [range(1; length) as $i
+4 -1
View File
@@ -134,7 +134,8 @@ let
hasAvailableOutbounds =
hasStaticOutbounds || hasSubscriptions || sshProxyOutboundEnabled || warpOutboundEnabled;
collapseNamedOutbounds = selectionMode == "first";
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
# Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode.
clashApiEnabled = singBoxEnabled;
perAppZapretEnabled = perAppZapretCfg.enable;
zapretCutoffEnabled =
zapretEngine == "zapret2"
@@ -170,6 +171,8 @@ let
outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json";
inboundStatsApiPort = 18536;
# Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches.
outboundTestPort = 18537;
inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json";
tunAutoRouteTableIndex = 2022;
+1 -1
View File
@@ -167,7 +167,7 @@ in
clashApiPort = mkOption {
type = types.port;
default = 9090;
description = ''Port of sing-box's Clash API, used with selection "selector" or "urltest".'';
description = "Loopback port of sing-box's Clash API, which switches and tests outbounds.";
};
};
@@ -34,6 +34,7 @@
let
inherit (constants)
autoProxyStateDir
outboundTestPort
xrayDnsBridgePorts
xraySidecarBasePorts
;
@@ -144,6 +145,7 @@ let
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
enableOutboundTest ? false,
enableZapretCutoff ? false,
}:
pkgs.writeShellScript name ''
@@ -236,6 +238,60 @@ let
fi
''}
${lib.optionalString enableOutboundTest ''
# proxy-ctl proxy outbounds test. Servers for its ping, keyed by the user's tag:
# the wrapper may have renamed one outbound "proxy" or prefixed them all, and a
# hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's.
ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp"
${jq} -c --argjson sidecar "''${XRAY_OUTBOUNDS_JSON:-[]}" --arg collapsed "''${PROXY_TAG:-}" '
def endpoint:
if .server then {server, port: .server_port}
elif (.peers | type) == "array" then {server: .peers[0].address, port: .peers[0].port}
elif .settings.address then {server: .settings.address, port: .settings.port}
elif .settings.vnext then {server: .settings.vnext[0].address, port: .settings.vnext[0].port}
elif .settings.servers then {server: .settings.servers[0].address, port: .settings.servers[0].port}
elif .settings.peers then
.settings.peers[0].endpoint | capture("^\\[?(?<server>.*?)\\]?:(?<port>[0-9]+)$") | .port |= tonumber
else null end;
def udp: (.type // .protocol) as $t | ["hysteria", "hysteria2", "tuic", "wireguard"] | index($t) != null;
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| [.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-") | if . == "proxy" then $collapsed else . end) as $tag
| ($real[.tag] // .) | select(endpoint != null)
| {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}]
| from_entries
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP"
# Where each proxy server is: not credentials, but not for every local user either.
${
if userControlCfg.allow != [ ] || localProxyAuthEnabled then
''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"
chmod 640 "$ENDPOINTS_TMP"
''
else
''chmod 600 "$ENDPOINTS_TMP"''
}
mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json"
${lib.optionalString (!pureXrayEnabled) ''
# Delay and download: a loopback listener pinned to a selector over every real
# exit, switched one outbound at a time through the Clash API.
OUTBOUNDS_JSON=$(${jq} -c --argjson tags "$EXIT_TAGS_JSON" \
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags}]' <<< "$OUTBOUNDS_JSON")
PROBE_INBOUNDS_JSON=$(${jq} -c '. + [{type: "mixed", tag: "proxy-suite-test-in",
listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c \
'. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON")
${jq} -n --argjson tags "$EXIT_TAGS_JSON" --arg collapsed "''${PROXY_TAG:-}" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} '
{port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url,
outbounds: ($tags | map({key: (if . == "proxy" then $collapsed else . end), value: .}) | from_entries)}
' > "$RUNTIME_DIR/outbound-test.json"
# Tags and a loopback port only.
chmod 644 "$RUNTIME_DIR/outbound-test.json"
''}
''}
${lib.optionalString enableZapretCutoff ''
# zapret2's cutoff probe lists the prefixes of cut-off networks no whitelisted
# name gets through; the proxy carries those. sing-box refuses a missing
@@ -326,6 +382,7 @@ let
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
enableOutboundTest = true;
};
startTun = mkStartScript {
+3 -2
View File
@@ -402,13 +402,14 @@
sample=${../../modules/proxy-suite/autoproxy-slow-sample.jq}
judge=${../../modules/proxy-suite/autoproxy-slow-judge.jq}
# A steady crawl, a burst, probe traffic, and a tiny flow.
# A steady crawl, a burst, probe and outbound-test traffic, and a tiny flow.
res="$(jq -n -c '[range(0; 11) as $t | {connections: [
{id: "a", metadata: {host: "i.pximg.net", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 50000)},
{id: "b", metadata: {host: "audio.example", type: "mixed/mixed-in"}, chains: ["direct"], download: (if $t >= 5 then 2000000 else 0 end)},
{id: "c", metadata: {host: "probe.example", type: "mixed/probe-in-0"}, chains: ["direct"], download: ($t * 50000)},
{id: "d", metadata: {host: "tiny.example", type: "mixed/mixed-in"}, chains: ["direct"], download: ($t * 1000)},
{id: "e", metadata: {host: "far.example", type: "mixed/mixed-in"}, chains: ["primary", "proxy"], download: ($t * 50000)}
{id: "e", metadata: {host: "far.example", type: "mixed/mixed-in"}, chains: ["primary", "proxy"], download: ($t * 50000)},
{id: "f", metadata: {host: "speed.example", type: "mixed/proxy-suite-test-in"}, chains: ["primary", "proxy-suite-test"], download: ($t * 50000)}
]}][]' | jq -s -r --argjson min 307200 --argjson below 153600 -f "$sample")"
printf '%s\n' "$res"
test "$(wc -l <<<"$res")" = 3
+178 -10
View File
@@ -4,15 +4,20 @@ Configuration arrives through the environment the Nix wrapper sets.
"""
import datetime
import http.client
import json
import os
import re
import signal
import socket
import subprocess
import sys
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from concurrent.futures import ThreadPoolExecutor
ALL_SERVICES = [
"proxy-suite-socks",
@@ -47,6 +52,8 @@ A group without a verb shows its status or list.
proxy outbounds [list] outbounds, where each came from, and the pick
proxy outbounds add <tag> <url> add an outbound at runtime
proxy outbounds rm <tag> remove a runtime outbound
proxy outbounds test [tag...] [--ping] [--delay] [--download]
TCP ping, real delay, download speed (default: ping, delay)
proxy select [<tag>|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
@@ -252,7 +259,7 @@ 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 outbounds": ["list", "add", "rm", "test"],
"proxy subs": ["list", "update", "add", "rm"],
"proxy mode": ["default", *ROUTE_MODES],
"proxy tun": ["status", "on", "off"],
@@ -270,6 +277,8 @@ def _complete_tree(words):
return simple[words]
if words == "proxy outbounds rm":
return _runtime_tags("outbound")
if words == "proxy outbounds test":
return _outbound_tags()
if words == "proxy subs rm":
return _runtime_tags("subscription")
if words == "proxy select":
@@ -471,8 +480,10 @@ def cmd_outbounds(verb="list", *args):
_runtime_entry_add("outbound", *args)
elif verb in ("rm", "remove", "del"):
_runtime_entry_rm("outbound", *args)
elif verb == "test":
cmd_outbounds_test(*args)
else:
usage("proxy outbounds [list|add <tag> <url>|rm <tag>]")
usage("proxy outbounds [list|add <tag> <url>|rm <tag>|test [tag...]]")
def _outbound_inventory():
@@ -504,17 +515,174 @@ def _outbound_current():
Empty otherwise, which is normal for selection = "first" and for XRay.
"""
api = env("CLASH_API")
if not api:
return ""
status, body = _clash("GET", "/proxies/proxy", timeout=5)
now = body.get("now") if status == 200 and isinstance(body, dict) else None
return "" if now is None else _s(now)
def _clash(method, path, body=None, timeout=10):
"""(HTTP status, JSON body or None) from the backend's Clash API; status 0 when unreachable."""
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
data = None if body is None else json.dumps(body).encode()
request = urllib.request.Request(
f"{env('CLASH_API')}{path}", data=data, method=method, headers={"Content-Type": "application/json"}
)
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)
with opener.open(request, timeout=timeout) as r:
status, raw = r.status, r.read()
except urllib.error.HTTPError as e:
status, raw = e.code, e.read()
except (OSError, ValueError, http.client.HTTPException):
return 0, None
try:
return status, json.loads(raw) if raw else None
except ValueError:
return status, None
# --- proxy outbounds test -----------------------------------------------------
#
# ping: a TCP connect to each outbound's server, from this host. delay: the
# backend's own URL test through the outbound, over the Clash API. download: a
# timed fetch through the loopback test listener, its selector switched to one
# outbound at a time. The socks start script writes what each needs next to the
# inventory: outbound-endpoints.json (servers; root and userControl only) and, on
# sing-box, outbound-test.json (listener, selector, user tag -> backend tag).
OUTBOUND_TESTS = ("ping", "delay", "download")
TEST_DOWNLOAD_HOST = "speed.cloudflare.com"
# Cloudflare refuses 100 MB and more; the fetch stops at the time limit anyway.
TEST_DOWNLOAD_PATH = "/__down?bytes=99000000"
TEST_DOWNLOAD_SECONDS = 10
def _runtime_file(name):
return os.path.join(os.path.dirname(env("OUTBOUND_INVENTORY_FILE", "/run/proxy-suite-socks/outbounds.json")), name)
def _test_ping(endpoint, timeout=3):
if not endpoint:
return "-"
# QUIC and WireGuard servers have no TCP handshake to time.
if endpoint.get("network") == "udp":
return "udp"
try:
family, kind, proto, _, addr = socket.getaddrinfo(endpoint["server"], endpoint["port"], type=socket.SOCK_STREAM)[0]
except (OSError, UnicodeError, KeyError, TypeError):
return "no DNS"
with socket.socket(family, kind, proto) as s:
s.settimeout(timeout)
start = time.monotonic()
try:
s.connect(addr)
except TimeoutError:
return "timeout"
except ConnectionRefusedError:
return "refused"
except OSError:
return "failed"
return f"{(time.monotonic() - start) * 1000:.0f} ms"
def _test_delay(backend_tag, url):
query = urllib.parse.urlencode({"url": url, "timeout": 8000})
status, body = _clash("GET", f"/proxies/{urllib.parse.quote(backend_tag, safe='')}/delay?{query}", timeout=12)
if status == 200 and isinstance(body, dict) and "delay" in body:
return f"{_s(body['delay'])} ms"
return {0: "no API", 504: "timeout"}.get(status, "failed")
def _timed_download(port):
"""Megabits per second through the test listener, None when nothing arrived.
A CONNECT tunnel by hand, so no proxy variable in the environment can send it
anywhere else.
"""
conn = http.client.HTTPSConnection("127.0.0.1", port, timeout=TEST_DOWNLOAD_SECONDS)
conn.set_tunnel(TEST_DOWNLOAD_HOST)
got = 0
start = time.monotonic()
try:
conn.request("GET", TEST_DOWNLOAD_PATH, headers={"User-Agent": "proxy-ctl"})
response = conn.getresponse()
while response.status == 200 and time.monotonic() - start < TEST_DOWNLOAD_SECONDS:
chunk = response.read(65536)
if not chunk:
break
got += len(chunk)
except (OSError, http.client.HTTPException):
pass
finally:
conn.close()
return got * 8 / (time.monotonic() - start) / 1e6 if got else None
def _test_download(backend_tag, test):
# ponytail: no lock, so two concurrent download tests measure each other's pick.
status, _ = _clash("PUT", f"/proxies/{urllib.parse.quote(test['selector'], safe='')}", {"name": backend_tag})
if not 200 <= status < 300:
return "failed" if status else "no API"
mbps = _timed_download(test["port"])
return "failed" if mbps is None else f"{mbps:.1f} Mbit/s"
def cmd_outbounds_test(*args):
flags = [a for a in args if a.startswith("-")]
for flag in flags:
if flag[2:] not in OUTBOUND_TESTS or not flag.startswith("--"):
die(f"Unknown option: {flag}")
tests = [t for t in OUTBOUND_TESTS if f"--{t}" in flags] or ["ping", "delay"]
_require_outbound_inventory()
known = _outbound_tags()
tags = [a for a in args if not a.startswith("-")] or known
for tag in tags:
if tag not in known:
die(f"Unknown outbound: {tag}")
notes = []
endpoints = {}
if "ping" in tests:
try:
endpoints = read_json(_runtime_file("outbound-endpoints.json"))
except PermissionError:
notes.append("ping: cannot read the servers - enable userControl, or run with sudo.")
except (OSError, ValueError):
pass
test = {}
if "delay" in tests or "download" in tests:
try:
test = read_json(_runtime_file("outbound-test.json"))
except (OSError, ValueError):
message = "Real delay and download need the sing-box or hybrid backend (restart proxy-suite-socks after an upgrade)."
if flags:
die(message)
tests.remove("delay")
notes.append(message)
backend = test.get("outbounds") or {}
def cell(kind, tag):
if kind == "ping":
return _test_ping(endpoints.get(tag))
if not backend.get(tag):
return "-"
if kind == "delay":
return _test_delay(backend[tag], test.get("url") or "https://www.gstatic.com/generate_204")
return _test_download(backend[tag], test)
# Ping and delay all at once, and done before any download competes with them.
with ThreadPoolExecutor(max_workers=16) as pool:
futures = {(k, t): pool.submit(cell, k, t) for t in tags for k in tests if k != "download"}
early = {key: f.result() for key, f in futures.items()}
width = max([12] + [len(t) + 2 for t in tags])
print(f" {'TAG':<{width}}" + "".join(f"{k.upper():<12}" for k in tests).rstrip())
for tag in tags:
# Downloads one at a time: they share the test listener.
cells = [early[(k, tag)] if k != "download" else cell(k, tag) for k in tests]
print((f" {tag:<{width}}" + "".join(f"{c:<12}" for c in cells)).rstrip(), flush=True)
for note in notes:
print(note, file=sys.stderr)
def _outbounds_list():
+78
View File
@@ -5,6 +5,7 @@ import datetime
import io
import json
import os
import socket
import tempfile
import unittest
from unittest import mock
@@ -406,5 +407,82 @@ class AppsRunTest(EnvTest):
self.assertIn("perAppRouting.zapret.enable is false", run(ctl.cmd_apps, "run", "zapret", "--", "curl")[2])
class OutboundTestTest(EnvTest):
def setUp(self):
super().setUp()
os.environ["OUTBOUND_INVENTORY_FILE"] = self.write("outbounds.json", {"tags": ["own-vps", "de", "wg"], "selection": "first"})
self.write(
"outbound-test.json",
{
"port": 18537,
"selector": "proxy-suite-test",
"url": "https://t.test/204",
# selection = "first": the backend knows the pick as "proxy".
"outbounds": {"own-vps": "proxy", "de": "de", "wg": "wg"},
},
)
self.calls = []
def clash(method, path, body=None, timeout=10):
self.calls.append((method, path, body))
if path.startswith("/proxies/de/delay"):
return 503, {"message": "An error occurred in the delay test"}
if method == "GET":
return 200, {"delay": 88}
return 204, None
self.patch("_clash", clash)
self.patch("_timed_download", lambda port: 12.34)
def test_ping(self):
with socket.socket() as server:
server.bind(("127.0.0.1", 0))
server.listen()
port = server.getsockname()[1]
self.assertRegex(ctl._test_ping({"server": "127.0.0.1", "port": port, "network": "tcp"}), r"^\d+ ms$")
self.assertEqual(ctl._test_ping({"server": "127.0.0.1", "port": port}), "refused")
# No TCP handshake to time on a QUIC or WireGuard server.
self.assertEqual(ctl._test_ping({"server": "127.0.0.1", "port": port, "network": "udp"}), "udp")
self.assertEqual(ctl._test_ping(None), "-")
def test_every_test(self):
self.write("outbound-endpoints.json", {"own-vps": {"server": "127.0.0.1", "port": 9, "network": "udp"}})
out = ok(ctl.cmd_outbounds, "test", "--ping", "--delay", "--download")
self.assertRegex(out, r"(?m)^ TAG +PING +DELAY +DOWNLOAD$")
self.assertRegex(out, r"(?m)^ own-vps +udp +88 ms +12\.3 Mbit/s$")
self.assertRegex(out, r"(?m)^ de +- +failed +12\.3 Mbit/s$")
self.assertTrue(any(c[1].startswith("/proxies/proxy/delay?") and "t.test" in c[1] for c in self.calls))
# Downloads switch the test selector, one outbound at a time, in order.
puts = [c for c in self.calls if c[0] == "PUT"]
self.assertEqual([c[2]["name"] for c in puts], ["proxy", "de", "wg"])
self.assertEqual({c[1] for c in puts}, {"/proxies/proxy-suite-test"})
def test_default_and_arguments(self):
out = ok(ctl.cmd_outbounds, "test", "de")
self.assertEqual(ctl.lines(out)[0], " TAG PING DELAY")
self.assertEqual(len(ctl.lines(out)), 2)
self.assertFalse(any(c[0] == "PUT" for c in self.calls))
self.assertNotEqual(run(ctl.cmd_outbounds, "test", "nope")[0], 0)
self.assertNotEqual(run(ctl.cmd_outbounds, "test", "--bogus")[0], 0)
def test_without_sing_box(self):
# Pure XRay: servers, but no test listener.
os.remove(self.path("outbound-test.json"))
status, out, err = run(ctl.cmd_outbounds, "test")
self.assertEqual(status, 0)
self.assertEqual(ctl.lines(out)[0], " TAG PING")
self.assertIn("sing-box or hybrid", err)
status, _, err = run(ctl.cmd_outbounds, "test", "--download")
self.assertNotEqual(status, 0)
self.assertIn("sing-box or hybrid", err)
@unittest.skipIf(os.geteuid() == 0, "root reads anything")
def test_unreadable_servers(self):
os.chmod(self.write("outbound-endpoints.json", {}), 0)
status, _, err = run(ctl.cmd_outbounds, "test", "--ping")
self.assertEqual(status, 0)
self.assertIn("enable userControl, or run with sudo", err)
if __name__ == "__main__":
unittest.main()