feat: debug options

This commit is contained in:
FUFSoB committed 2026-10-11 11:18:48 +05:00
1 parent cacd51595c
commit e293efd1c1
33 files changed
+965 -77

No files matched your search

+7
View File
@@ -141,6 +141,13 @@ Changes and secrets need root or the userControl group.
logs [unit...] follow logs (default: all proxy-suite units); in a
terminal, in lnav: scroll back, G follows, q quits
where <domain> how a domain is routed right now
debug conns [--backend socks|tun|per-app-tun] [--host <domain|address>]... [--inbound <tag>]...
[--stall <s>] [--interval <s>]
the backend's connections as they open, stall and
close, with their rule, exit and bytes (needs root or
the secrets scope); --host, --inbound: only these;
--backend tun, per-app-tun: the TUN ones (root, and
debug.connectionLog on)
proxy [status|on|off] local proxy
proxy outbounds [list] outbounds, their source, and the current pick
+125
View File
@@ -0,0 +1,125 @@
# services.proxy-suite.debug
Troubleshooting: backend log levels, a connection recorder, DNS and zapret2 logs.
Part of the [proxy-suite options reference](./index.md).
## Options
- debug
- connectionLog
- [enable](#services-proxy-suite-debug-connectionlog-enable)
- [hosts](#services-proxy-suite-debug-connectionlog-hosts)
- [inbounds](#services-proxy-suite-debug-connectionlog-inbounds)
- [interval](#services-proxy-suite-debug-connectionlog-interval)
- [stallAfter](#services-proxy-suite-debug-connectionlog-stallafter)
- [logLevel](#services-proxy-suite-debug-loglevel)
- [perAppDns](#services-proxy-suite-debug-perappdns)
- [tgWsProxy](#services-proxy-suite-debug-tgwsproxy)
- zapret2
- [autoHostlist](#services-proxy-suite-debug-zapret2-autohostlist)
- [packets](#services-proxy-suite-debug-zapret2-packets)
<a id="services-proxy-suite-debug-connectionlog-enable"></a>
## services\.proxy-suite\.debug\.connectionLog\.enable
Record the backends’ connections to the journal: each one as it opens, with its
listener, site, rule and exit, and as it closes, with the bytes each way and how long
it lasted\. For failures that come and go: look back at the time one happened\. A unit
per backend, up while it is: proxy-suite-connection-log for the local proxy and
global or per-app TProxy, proxy-suite-connection-log-tun for the global TUN and
proxy-suite-connection-log-per-app-tun for per-app TUN, whose Clash APIs this turns
on\. The same view live: ` proxy-ctl debug conns `\. Polls the Clash API, so it needs the
sing-box or hybrid backend; a connection shorter than ` interval ` can be missed\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-debug-connectionlog-hosts"></a>
## services\.proxy-suite\.debug\.connectionLog\.hosts
Record only connections to these domains and their subdomains, or these addresses\.
Empty: every connection\.
**Type:** list of string\
**Default:** `[ ]`\
**Example:** `[ "twimg.com" "x.com" ]`
<a id="services-proxy-suite-debug-connectionlog-inbounds"></a>
## services\.proxy-suite\.debug\.connectionLog\.inbounds
Record only connections that came in on listeners whose tag starts with one of
these: “tproxy” for global and per-app TProxy, “tun-in” for the global and per-app
TUN, “per-app-pin” for apps run ` --via ` an outbound through TProxy, “mixed-in” for
the local proxy\. Empty: every listener\.
**Type:** list of string\
**Default:** `[ ]`\
**Example:** `[ "tproxy" ]`
<a id="services-proxy-suite-debug-connectionlog-interval"></a>
## services\.proxy-suite\.debug\.connectionLog\.interval
Seconds between looks at the connections\.
**Type:** positive integer or floating point number, meaning >0\
**Default:** `0.5`
<a id="services-proxy-suite-debug-connectionlog-stallafter"></a>
## services\.proxy-suite\.debug\.connectionLog\.stallAfter
Seconds a connection may wait on an answer: one that has sent since it last
received, and received nothing for this long, is logged as stalled, and again
when it resumes\. Several requests share a connection (HTTP/2), so a stall shows
only when all of them wait\. 0: never\.
**Type:** unsigned integer, meaning >=0\
**Default:** `10`
<a id="services-proxy-suite-debug-loglevel"></a>
## services\.proxy-suite\.debug\.logLevel
How much the proxy backends log to the journal (` proxy-ctl logs proxy-suite-socks `):
sing-box, and XRay where it runs (XRay has no “trace”: it logs at “debug” then)\.
“info” logs every connection with its destination and the rule that routed it\.
` /run/proxy-suite/xray-loglevel ` still overrides XRay’s level at the next start\.
**Type:** one of “warn”, “info”, “debug”, “trace”\
**Default:** `"warn"`\
**Example:** `"info"`
<a id="services-proxy-suite-debug-perappdns"></a>
## services\.proxy-suite\.debug\.perAppDns
Log every lookup the per-app DNS forwarders send on (per-app TUN and TProxy, and apps
run through an AmneziaWG interface): the name, its type, the answer’s code and how long
it took, and the lookups that got no answer\. In the journals of
proxy-suite-per-app-tun-dns, proxy-suite-per-app-tproxy-dns and
proxy-suite-per-app-via@\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-debug-tgwsproxy"></a>
## services\.proxy-suite\.debug\.tgWsProxy
Log the Telegram proxy’s debug messages\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-debug-zapret2-autohostlist"></a>
## services\.proxy-suite\.debug\.zapret2\.autoHostlist
Log why sites are or are not learned (nfqws2’s own learner)\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-debug-zapret2-packets"></a>
## services\.proxy-suite\.debug\.zapret2\.packets
Log everything nfqws2 does to the journal, every packet included\. Very verbose\.
**Type:** boolean\
**Default:** `false`
+17 -3
View File
@@ -24,6 +24,7 @@ Update the module option docs there instead of editing these files by hand.
| [gui](./gui.md) | The desktop app with a tray icon. |
| [tui](./tui.md) | The `proxy-tui` terminal UI. |
| [tools](./tools.md) | Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate. |
| [debug](./debug.md) | Troubleshooting: backend log levels, a connection recorder, DNS and zapret2 logs. |
<a id="services-proxy-suite-enable"></a>
## services\.proxy-suite\.enable
@@ -54,6 +55,22 @@ services.proxy-suite = {
userspacePackage = ‹proxy-suite's patched amneziawg-go (pkgs/amneziawg.nix)›;
wireproxyPackage = ‹proxy-suite's wireproxy-awg (pkgs/wireproxy-awg.nix)›;
};
debug = {
connectionLog = {
enable = false;
hosts = [ ];
inbounds = [ ];
interval = 0.5;
stallAfter = 10;
};
logLevel = "warn";
perAppDns = false;
tgWsProxy = false;
zapret2 = {
autoHostlist = false;
packets = false;
};
};
enable = false;
geodata = {
singBox = {
@@ -319,7 +336,6 @@ services.proxy-suite = {
file = null;
keep = 1;
maxSizeMiB = 5.0;
verbose = false;
};
poolSize = 4;
proxyProtocol = false;
@@ -413,7 +429,6 @@ services.proxy-suite = {
};
zapret2 = {
autoHostlist = {
debugLog = false;
enable = true;
extendedDetection = true;
failThreshold = 3;
@@ -430,7 +445,6 @@ services.proxy-suite = {
enable = true;
proxyFallback = true;
};
debug = false;
domains = [ ];
excludeDomains = [ ];
ipv6 = false;
-9
View File
@@ -24,7 +24,6 @@ Part of the [proxy-suite options reference](./index.md).
- [file](#services-proxy-suite-tgwsproxy-log-file)
- [keep](#services-proxy-suite-tgwsproxy-log-keep)
- [maxSizeMiB](#services-proxy-suite-tgwsproxy-log-maxsizemib)
- [verbose](#services-proxy-suite-tgwsproxy-log-verbose)
- [poolSize](#services-proxy-suite-tgwsproxy-poolsize)
- [proxyProtocol](#services-proxy-suite-tgwsproxy-proxyprotocol)
- [secret](#services-proxy-suite-tgwsproxy-secret)
@@ -147,14 +146,6 @@ Rotate the log at this size, in MiB\.
**Type:** positive integer or floating point number, meaning >0\
**Default:** `5.0`
<a id="services-proxy-suite-tgwsproxy-log-verbose"></a>
## services\.proxy-suite\.tgWsProxy\.log\.verbose
Log debug messages\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-tgwsproxy-poolsize"></a>
## services\.proxy-suite\.tgWsProxy\.poolSize
+2 -19
View File
@@ -40,7 +40,6 @@ Part of the [proxy-suite options reference](./index.md).
- zapret2
- autoHostlist
- [enable](#services-proxy-suite-zapret-zapret2-autohostlist-enable)
- [debugLog](#services-proxy-suite-zapret-zapret2-autohostlist-debuglog)
- [extendedDetection](#services-proxy-suite-zapret-zapret2-autohostlist-extendeddetection)
- [failThreshold](#services-proxy-suite-zapret-zapret2-autohostlist-failthreshold)
- [failTime](#services-proxy-suite-zapret-zapret2-autohostlist-failtime)
@@ -54,7 +53,6 @@ Part of the [proxy-suite options reference](./index.md).
- cutoff
- [enable](#services-proxy-suite-zapret-zapret2-cutoff-enable)
- [proxyFallback](#services-proxy-suite-zapret-zapret2-cutoff-proxyfallback)
- [debug](#services-proxy-suite-zapret-zapret2-debug)
- [domains](#services-proxy-suite-zapret-zapret2-domains)
- [excludeDomains](#services-proxy-suite-zapret-zapret2-excludedomains)
- [ipv6](#services-proxy-suite-zapret-zapret2-ipv6)
@@ -322,14 +320,6 @@ blocked\. When off, only ` zapret2.domains ` and ` proxy-ctl zapret auto add ` a
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-autohostlist-debuglog"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.debugLog
Log why sites are or are not learned (nfqws2’s own learner)\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-zapret-zapret2-autohostlist-extendeddetection"></a>
## services\.proxy-suite\.zapret\.zapret2\.autoHostlist\.extendedDetection
@@ -436,14 +426,6 @@ sees by IP (TUN, TProxy, per-app routing)\. Explicit direct rules still win\.
**Type:** boolean\
**Default:** `true`
<a id="services-proxy-suite-zapret-zapret2-debug"></a>
## services\.proxy-suite\.zapret\.zapret2\.debug
Log everything nfqws2 does to the journal, every packet included\. Very verbose: for troubleshooting\.
**Type:** boolean\
**Default:** `false`
<a id="services-proxy-suite-zapret-zapret2-domains"></a>
## services\.proxy-suite\.zapret\.zapret2\.domains
@@ -544,7 +526,8 @@ only where it sees the address)\. ` proxy-ctl zapret auto retry ` gives one anot
## services\.proxy-suite\.zapret\.zapret2\.strategyLog
Log each counted failure and strategy switch to the journal, per site
(` proxy-ctl logs proxy-suite-zapret `)\. Without it nfqws2 logs them only with ` debug `\.
(` proxy-ctl logs proxy-suite-zapret `)\. Without it nfqws2 logs them only with
` debug.zapret2.packets `\.
**Type:** boolean\
**Default:** `true`
+15
View File
@@ -0,0 +1,15 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
debug.connectionLog = {
enable = true;
hosts = [ "x.com" "twimg.com" ]; # leave empty for every site
inbounds = [ "tproxy" ]; # global and per-app TProxy only
};
};
}
+11
View File
@@ -0,0 +1,11 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
debug.logLevel = "info"; # every connection and the rule that routed it
};
}
+15
View File
@@ -0,0 +1,15 @@
{ config, lib, pkgs, ... }:
{
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
perAppRouting = {
enable = true;
tproxy.enable = true;
};
debug.perAppDns = true;
};
}
+101
View File
@@ -0,0 +1,101 @@
# Track down a problem
Turn on more logging, and record connections, for a problem that comes and goes. Each of
these logs to the journal; `proxy-ctl logs <unit>` follows it.
## Record connections
Pages that sometimes half load, or images left blank, are hard to catch on demand. Record
the backend's connections and look back at the time it happened:
```nix
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
debug.connectionLog = {
enable = true;
hosts = [ "x.com" "twimg.com" ]; # leave empty for every site
inbounds = [ "tproxy" ]; # global and per-app TProxy only
};
};
```
```sh
journalctl -u 'proxy-suite-connection-log*' --since "10 min ago"
```
There is a recorder per backend: `proxy-suite-connection-log` for the local proxy and TProxy,
global or per-app, `proxy-suite-connection-log-tun` for the global TUN and
`proxy-suite-connection-log-per-app-tun` for per-app TUN. Each runs while its backend does.
TUN connections come in on `tun-in`: put that in `inbounds` too, or leave it empty.
Each connection gets a line as it opens, with its listener, site, rule and exit, and one as
it closes, with the bytes each way. One that sent and got nothing back for
`stallAfter` seconds is logged as `stalled`, and as `resumed` if the answer comes. A
connection is looked at every `interval` seconds, so one shorter than that can be missed,
and the byte counts are from the last look.
The same, live and without a rebuild:
```sh
proxy-ctl debug conns --host twimg.com --inbound tproxy
```
It needs root, or the `secrets` scope: connections show every site visited. `--backend tun`
or `--backend per-app-tun` shows a TUN backend's, as root and with `debug.connectionLog` on,
which gives those backends the API it reads.
## More from the backend
```nix
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
debug.logLevel = "info"; # every connection and the rule that routed it
};
```
"debug" and "trace" log more than that, including DNS. Follow it with
`proxy-ctl logs proxy-suite-socks`.
## DNS of per-app routes
Apps run through per-app TUN or TProxy have their lookups sent on into the route. To see
each lookup, its answer and how long it took, and the ones that got no answer:
```nix
services.proxy-suite = {
enable = true;
proxy = {
enable = true;
outbounds = [ { tag = "my-vps"; urlFile = "/run/secrets/my-vps-url"; } ];
};
perAppRouting = {
enable = true;
tproxy.enable = true;
};
debug.perAppDns = true;
};
```
```sh
proxy-ctl logs proxy-suite-per-app-tproxy-dns
```
## Good to know
- All of these can log every site visited, for anyone who can read the journal. Turn them
off when done.
- zapret2 has its own: `debug.zapret2.packets` logs every packet nfqws2 handles, and
`debug.zapret2.autoHostlist` why sites are or are not learned.
## See also
- [`debug`](../options/debug.md): every option
- [Control it day to day](./control.md): `proxy-ctl logs` and the rest
+1
View File
@@ -20,6 +20,7 @@ examples follow below.
| [Group outbounds and fail over](./groups.md) | Several exits for one job, moving off one that stops working |
| [Other Linux and Android](./other-hosts.md) | You are not on NixOS |
| [Get past mobile whitelists](./whitelist-bypass.md) | Mobile internet lets only whitelisted services through |
| [Track down a problem](./debug.md) | Something fails now and then, and you want to see why |
## Complete examples
@@ -19,6 +19,8 @@ let
perAppPinSlots
perAppPinTproxy
perAppPinTun
singBoxLogLevel
connectionLogEnabled
;
inherit (constants)
xrayDnsBridgePorts
@@ -188,7 +190,7 @@ let
lib.recursiveUpdate
(
{
log.level = "warn";
log.level = singBoxLogLevel;
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
@@ -297,8 +299,8 @@ let
// lib.optionalAttrs enableClashApi (clashApiBlock clashApiPort)
)
# Fake addresses handed out survive a restart, so apps still holding one keep working. The
# start script creates the directory; nothing else is stored, since TUN configs have no
# Clash API to switch a selector with.
# start script creates the directory; nothing else is stored, since no selector of a TUN
# config is switched through the Clash API.
(
lib.optionalAttrs fakeIp {
experimental.cache_file = {
@@ -330,7 +332,9 @@ in
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = false;
enableClashApi = false;
# Only for debug.connectionLog to read the connections.
enableClashApi = connectionLogEnabled;
clashApiPort = constants.globalTunClashApiPort;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
fakeIpCache = "tun";
};
@@ -341,8 +345,8 @@ in
tunAddress = perAppRoutingTun.address;
tunIPv6Address = constants.perAppTunIPv6Address;
pins = if perAppPinTun then tunPins else null;
# The pins' selectors are switched through it.
enableClashApi = perAppPinTun;
# The pins' selectors are switched through it; debug.connectionLog reads the connections.
enableClashApi = perAppPinTun || connectionLogEnabled;
clashApiPort = constants.perAppTunClashApiPort;
tunMtu = perAppRoutingTun.mtu;
tunAutoRoute = false;
@@ -13,6 +13,7 @@ let
globalTun
globalTproxy
perAppRoutingTun
xrayLogLevel
;
inherit (constants)
globalTunIPv6Address
@@ -296,7 +297,7 @@ let
++ [ (finalRule (if (proxyCfg.routing.default == "proxy") then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
log.loglevel = xrayLogLevel;
dns = mkDnsConfig { fakeDns = enableTunFakeDns; };
inbounds =
lib.optional enableMixed {
+16
View File
@@ -628,6 +628,17 @@ let
collapseNamedOutbounds = selectionMode == "first";
# Always on with sing-box: `proxy-ctl proxy outbounds test` needs it in every selection mode.
clashApiEnabled = singBoxEnabled;
# debug.logLevel, in each backend's words.
singBoxLogLevel = cfg.debug.logLevel;
xrayLogLevel =
{
warn = "warning";
info = "info";
debug = "debug";
trace = "debug";
}
.${cfg.debug.logLevel};
connectionLogEnabled = cfg.enable && clashApiEnabled && cfg.debug.connectionLog.enable;
perAppZapretEnabled = perAppZapretCfg.enable;
# The global units each per-app backend steps aside for (constants.refuseUnderGlobal), as
# systemctl patterns: they stop it as they start, and the standby unit waits them out.
@@ -1159,6 +1170,8 @@ let
ipv6 = "fd66:21::${lib.toLower (lib.toHexString (slot + 2))}";
};
perAppTunClashApiPort = 19180;
# The global TUN backend's, for debug.connectionLog alone.
globalTunClashApiPort = 19181;
# The DNS forwarders of per-app TUN and TProxy apps (proxy-suite-per-app-<route>-dns): the
# route's at the base, pin slot n's at base + 1 + n; they ask perAppDnsUpstream with its mark.
perAppTproxyDnsBasePort = 19200;
@@ -1230,6 +1243,9 @@ in
inherit
proxyCfg
localProxy
singBoxLogLevel
xrayLogLevel
connectionLogEnabled
singBoxCfg
xrayCfg
proxyEnabled
+97
View File
@@ -0,0 +1,97 @@
{ lib, ... }:
let
inherit (lib) mkOption types;
inherit (import ./lib.nix { inherit lib; }) bool;
in
{
# Troubleshooting only: everything here logs more, some of it every site visited.
options.services.proxy-suite.debug = {
logLevel = mkOption {
type = types.enum [
"warn"
"info"
"debug"
"trace"
];
default = "warn";
description = ''
How much the proxy backends log to the journal (`proxy-ctl logs proxy-suite-socks`):
sing-box, and XRay where it runs (XRay has no "trace": it logs at "debug" then).
"info" logs every connection with its destination and the rule that routed it.
`/run/proxy-suite/xray-loglevel` still overrides XRay's level at the next start.
'';
example = "info";
};
connectionLog = {
enable = bool false ''
Record the backends' connections to the journal: each one as it opens, with its
listener, site, rule and exit, and as it closes, with the bytes each way and how long
it lasted. For failures that come and go: look back at the time one happened. A unit
per backend, up while it is: proxy-suite-connection-log for the local proxy and
global or per-app TProxy, proxy-suite-connection-log-tun for the global TUN and
proxy-suite-connection-log-per-app-tun for per-app TUN, whose Clash APIs this turns
on. The same view live: `proxy-ctl debug conns`. Polls the Clash API, so it needs the
sing-box or hybrid backend; a connection shorter than `interval` can be missed.
'';
hosts = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Record only connections to these domains and their subdomains, or these addresses.
Empty: every connection.
'';
example = [
"twimg.com"
"x.com"
];
};
inbounds = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Record only connections that came in on listeners whose tag starts with one of
these: "tproxy" for global and per-app TProxy, "tun-in" for the global and per-app
TUN, "per-app-pin" for apps run `--via` an outbound through TProxy, "mixed-in" for
the local proxy. Empty: every listener.
'';
example = [ "tproxy" ];
};
stallAfter = mkOption {
type = types.ints.unsigned;
default = 10;
description = ''
Seconds a connection may wait on an answer: one that has sent since it last
received, and received nothing for this long, is logged as stalled, and again
when it resumes. Several requests share a connection (HTTP/2), so a stall shows
only when all of them wait. 0: never.
'';
};
interval = mkOption {
type = types.numbers.positive;
default = 0.5;
description = "Seconds between looks at the connections.";
};
};
perAppDns = bool false ''
Log every lookup the per-app DNS forwarders send on (per-app TUN and TProxy, and apps
run through an AmneziaWG interface): the name, its type, the answer's code and how long
it took, and the lookups that got no answer. In the journals of
proxy-suite-per-app-tun-dns, proxy-suite-per-app-tproxy-dns and
proxy-suite-per-app-via@.
'';
zapret2 = {
packets = bool false "Log everything nfqws2 does to the journal, every packet included. Very verbose.";
autoHostlist = bool false "Log why sites are or are not learned (nfqws2's own learner).";
};
tgWsProxy = bool false "Log the Telegram proxy's debug messages.";
};
}
+1
View File
@@ -25,6 +25,7 @@
./user-control.nix
./kill-switch.nix
./host.nix
./debug.nix
];
options.services.proxy-suite.enable = lib.mkEnableOption "proxy-suite";
+8 -1
View File
@@ -23,6 +23,13 @@ in
(lib.mkRenamedOptionModule (p "tray.autostart") (p "gui.autostart"))
(lib.mkRenamedOptionModule (p "tray.pollInterval") (p "gui.refreshInterval"))
# Troubleshooting switches gathered under debug.
(lib.mkRenamedOptionModule (p "zapret.zapret2.debug") (p "debug.zapret2.packets"))
(lib.mkRenamedOptionModule (p "zapret.zapret2.autoHostlist.debugLog") (
p "debug.zapret2.autoHostlist"
))
(lib.mkRenamedOptionModule (p "tgWsProxy.log.verbose") (p "debug.tgWsProxy"))
# These were aliases; they are removal notices now, so there is one
# compatibility policy instead of two.
(rm "proxyInbounds" "Use services.proxy-suite.inbounds.")
@@ -65,7 +72,7 @@ in
(rm "tgWsProxy.cfProxyFallback" "Use services.proxy-suite.tgWsProxy.cloudflare.fallback.")
(rm "tgWsProxy.bufKb" "Use services.proxy-suite.tgWsProxy.bufferKiB.")
(rm "tgWsProxy.routingMark" "Use services.proxy-suite.tgWsProxy.fwmark.")
(rm "tgWsProxy.verbose" "Use services.proxy-suite.tgWsProxy.log.verbose.")
(rm "tgWsProxy.verbose" "Use services.proxy-suite.debug.tgWsProxy.")
(rm "tgWsProxy.logFile" "Use services.proxy-suite.tgWsProxy.log.file.")
(rm "tgWsProxy.logMaxMb" "Use services.proxy-suite.tgWsProxy.log.maxSizeMiB.")
(rm "tgWsProxy.logBackups" "Use services.proxy-suite.tgWsProxy.log.keep.")
@@ -94,12 +94,6 @@ in
};
log = {
verbose = mkOption {
type = types.bool;
default = false;
description = "Log debug messages.";
};
file = mkOption {
type = types.nullOr types.str;
default = null;
+2 -13
View File
@@ -120,16 +120,11 @@ in
default = true;
description = ''
Log each counted failure and strategy switch to the journal, per site
(`proxy-ctl logs proxy-suite-zapret`). Without it nfqws2 logs them only with `debug`.
(`proxy-ctl logs proxy-suite-zapret`). Without it nfqws2 logs them only with
`debug.zapret2.packets`.
'';
};
debug = mkOption {
type = types.bool;
default = false;
description = "Log everything nfqws2 does to the journal, every packet included. Very verbose: for troubleshooting.";
};
ipv6 = mkOption {
type = types.bool;
default = false;
@@ -160,12 +155,6 @@ in
udpOut = int 4 "UDP packets sent, with at most `udpIn` replies, that count as a failure.";
udpIn = int 1 "Most UDP replies that still count as no answer (see `udpOut`).";
debugLog = mkOption {
type = types.bool;
default = false;
description = "Log why sites are or are not learned (nfqws2's own learner).";
};
extendedDetection = mkOption {
type = types.bool;
default = true;
@@ -289,6 +289,9 @@ let
(mkAssertion (!(proxyCfg.autoProxy.enable && pureXrayEnabled))
"proxy-suite: proxy.autoProxy needs the sing-box backend: learned routes are local rule-sets that sing-box reloads from disk, and pure XRay has no equivalent"
)
(mkAssertion (!cfg.debug.connectionLog.enable || singBoxEnabled)
"proxy-suite: debug.connectionLog reads sing-box's Clash API: it needs proxy.enable = true and proxy.backend = \"sing-box\" or \"hybrid\""
)
(mkAssertion
(!cfg.sshProxy.enable || (cfg.sshProxy.server.user != null && cfg.sshProxy.server.host != null))
"proxy-suite: sshProxy.server.user and sshProxy.server.host are required when sshProxy.enable = true"
+3
View File
@@ -68,6 +68,9 @@ in
withCurlImpersonate = cfg.tools.curlImpersonate.enable;
env = {
CLASH_API = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
# The TUN backends' own, root's alone (`debug conns --backend`).
CLASH_API_TUN = "http://127.0.0.1:${toString constants.globalTunClashApiPort}";
CLASH_API_PER_APP_TUN = "http://127.0.0.1:${toString constants.perAppTunClashApiPort}";
SELECTION = selectionMode;
SUB_TAGS_FILE = toString subscriptionTagsFile;
SUB_CACHE_DIR = subscriptionCacheDir;
+93
View File
@@ -223,6 +223,98 @@ let
};
};
# debug.connectionLog: `proxy-ctl debug conns` into the journal, a unit per sing-box
# instance, up while it is.
connectionLogUnit =
let
logCfg = cfg.debug.connectionLog;
instances = [
{
unit = "proxy-suite-connection-log";
backend = "socks";
service = "proxy-suite-socks.service";
}
]
++ lib.optional globalTun.enable {
unit = "proxy-suite-connection-log-tun";
backend = "tun";
service = "proxy-suite-tun.service";
}
++ lib.optional perAppRoutingTun.enable {
unit = "proxy-suite-connection-log-per-app-tun";
backend = "per-app-tun";
service = "proxy-suite-per-app-tun.service";
};
in
lib.mkIf derived.connectionLogEnabled {
services.proxy-suite.internal.services = lib.listToAttrs (
map (instance: {
name = instance.unit;
value = mkConnectionLog logCfg instance;
}) instances
);
};
mkConnectionLog =
logCfg:
{ backend, service, ... }:
{
description = "proxy-suite - record the ${backend} backend's connections (debug.connectionLog)";
after = [ service ];
# Not BindsTo: per-app TUN stops when no app needs it, and this must not count as one.
partOf = [ service ];
wantedBy = [ service ];
serviceConfig = {
ExecStart = lib.escapeShellArgs (
[
"${control.proxyCtl}/bin/proxy-ctl"
"debug"
"conns"
"--backend"
backend
"--stall"
(toString logCfg.stallAfter)
"--interval"
(toString logCfg.interval)
]
++ lib.concatMap (h: [
"--host"
h
]) logCfg.hosts
++ lib.concatMap (i: [
"--inbound"
i
]) logCfg.inbounds
);
Restart = "on-failure";
RestartSec = 5;
# Root for the Clash API secret's sake (its file is root's), with no capability at all.
CapabilityBoundingSet = [ "" ];
NoNewPrivileges = true;
PrivateTmp = true;
# Root without capabilities still owns the disks' device nodes.
PrivateDevices = true;
ProtectSystem = "strict";
ProtectHome = true;
ProtectClock = true;
ProtectControlGroups = true;
ProtectHostname = true;
ProtectKernelLogs = true;
ProtectKernelModules = true;
ProtectKernelTunables = true;
RestrictRealtime = true;
RestrictSUIDSGID = true;
LockPersonality = true;
RestrictAddressFamilies = [
"AF_UNIX"
"AF_INET"
"AF_INET6"
];
# The API is on loopback; nothing else to reach.
IPAddressAllow = [ "localhost" ];
IPAddressDeny = [ "any" ];
};
};
# userControl.groups cannot own the spools the way userControl.group does: POSIX ACLs let
# them in, set again on every boot and whenever the groups change (a changed unit
# restarts), so a group dropped from the configuration loses what it had. With
@@ -261,6 +353,7 @@ lib.mkMerge [
autoProxyUnits
outboundGroupsUnit
clashBrokerUnit
connectionLogUnit
aclUnit
{
services.proxy-suite.internal = {
@@ -257,7 +257,7 @@ let
set -euo pipefail
${resolveInstance}
${dnsServers}
exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" "''${servers[@]}"
exec ${python3} ${proxySuiteScriptsDir}/per_app_dns.py --port "$dns_port" --mark "$mark" ${lib.optionalString cfg.debug.perAppDns "--log "}"''${servers[@]}"
'';
# A failure keeps the marking and the unreachable rule, so the apps are turned away rather
@@ -13,6 +13,7 @@ let
xrayEnabled
hybridEnabled
pureXrayEnabled
xrayLogLevel
constants
zapretCutoffProxyFallback
zapret2DirectSync
@@ -196,7 +197,8 @@ let
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
XRAY_LOGLEVEL=""
# debug.logLevel; empty keeps each config's own "warning".
XRAY_LOGLEVEL=${lib.escapeShellArg (lib.optionalString (xrayLogLevel != "warning") xrayLogLevel)}
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
+1
View File
@@ -193,6 +193,7 @@ let
]
++ map (l: "--listen ${l}") listeners
++ map (a: "--bind ${a}") bind
++ lib.optional ctx.cfg.debug.perAppDns "--log"
++ [ ctx.constants.perAppDnsUpstream ]
);
runtimeDirectory = "proxy-suite-per-app-${route}-dns";
+1 -1
View File
@@ -39,7 +39,7 @@ let
else
"args+=(--secret=${lib.escapeShellArg t.secret})"
}
${dcArgs}${mkFlagArg t.log.verbose "--verbose"}${
${dcArgs}${mkFlagArg cfg.debug.tgWsProxy "--verbose"}${
mkOptionalValueArg (t.log.file != null) "--log-file" t.log.file
}${lib.optionalString (t.log.file != null) (mkRawValueArg "--log-max-mb" t.log.maxSizeMiB)}${
lib.optionalString (t.log.file != null) (mkRawValueArg "--log-backups" t.log.keep)
+2 -2
View File
@@ -176,7 +176,7 @@ let
# (an app or a domain sent through a tunnel) it would otherwise take the default route,
# away from the connection it was meant to precede; without such routing it is a no-op.
optPrefix = lib.concatStringsSep " " (
lib.optional zapret2Cfg.debug "--debug=1"
lib.optional cfg.debug.zapret2.packets "--debug=1"
++ [
"--bind-fix4"
"--bind-fix6"
@@ -265,7 +265,7 @@ let
"AUTOHOSTLIST_INCOMING_MAXSEQ=${toString autoCfg.incomingMaxseq}"
"AUTOHOSTLIST_UDP_OUT=${toString autoCfg.udpOut}"
"AUTOHOSTLIST_UDP_IN=${toString autoCfg.udpIn}"
"AUTOHOSTLIST_DEBUGLOG=${if autoCfg.debugLog then "1" else "0"}"
"AUTOHOSTLIST_DEBUGLOG=${if cfg.debug.zapret2.autoHostlist then "1" else "0"}"
""
]
)
+70
View File
@@ -41,6 +41,33 @@ let
cfg = perAppRoutingTproxyFixture.config.services.proxy-suite;
}).perAppTproxyRulesFile;
debugFixture = evalProxySuite [
baseModule
{
services.proxy-suite = {
proxy.tun.enable = true;
perAppRouting = {
enable = true;
tproxy.enable = true;
tun.enable = true;
};
debug = {
logLevel = "trace";
perAppDns = true;
connectionLog = {
enable = true;
hosts = [ "twimg.com" ];
inbounds = [ "tproxy" ];
stallAfter = 3;
};
};
};
}
];
debugServices = debugFixture.config.systemd.services;
dnsExecStart =
fixture: fixture.config.systemd.services.proxy-suite-per-app-tproxy-dns.serviceConfig.ExecStart;
keepRunningFixture = evalProxySuite [
baseModule
{
@@ -238,5 +265,48 @@ in
assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStopScript;
true
)
# -- debug: the forwarder logs lookups, the recorder runs, XRay follows the level --
(
assert pkgs.lib.hasInfix " --log " (dnsExecStart debugFixture);
assert !pkgs.lib.hasInfix "--log" (dnsExecStart perAppRoutingTproxyFixture);
assert !(perAppRoutingTproxyFixture.config.systemd.services ? proxy-suite-connection-log);
assert pkgs.lib.hasInfix "/bin/proxy-ctl debug conns --backend socks --stall 3 --interval "
debugServices.proxy-suite-connection-log.serviceConfig.ExecStart;
assert pkgs.lib.hasSuffix " --host twimg.com --inbound tproxy"
debugServices.proxy-suite-connection-log.serviceConfig.ExecStart;
# One per sing-box instance, up with it, never keeping it up.
assert builtins.all
(
{ name, backend }:
let
unit = debugServices."proxy-suite-connection-log${name}";
service = "proxy-suite-${backend}.service";
in
pkgs.lib.hasInfix " --backend ${backend} " unit.serviceConfig.ExecStart
&& unit.partOf == [ service ]
&& unit.wantedBy == [ service ]
&& unit.bindsTo or [ ] == [ ]
)
[
{
name = "";
backend = "socks";
}
{
name = "-tun";
backend = "tun";
}
{
name = "-per-app-tun";
backend = "per-app-tun";
}
];
# XRay has no "trace".
assert pkgs.lib.hasInfix "\nXRAY_LOGLEVEL=debug\n" (
generated.readDerivation debugServices.proxy-suite-socks.serviceConfig.ExecStart
);
true
)
];
}
+1 -1
View File
@@ -32,7 +32,6 @@ let
listener.port = 2443;
listener.address = "0.0.0.0";
secretFile = "/run/secrets/tg-ws-proxy";
log.verbose = true;
log.file = "/var/log/tg-ws-proxy.log";
log.maxSizeMiB = 2.5;
log.keep = 3;
@@ -47,6 +46,7 @@ let
fakeTlsDomain = "mask.example.com";
proxyProtocol = true;
};
services.proxy-suite.debug.tgWsProxy = true;
}
];
tgAllOptionsStartScript = unitScript tgAllOptions "proxy-suite-tg-ws-proxy";
+12 -7
View File
@@ -4,17 +4,22 @@
}:
let
mkZapret2 =
zapret:
# `extra`: more of services.proxy-suite, beside zapret.
mkZapret2With =
extra: zapret:
evalProxySuite [
baseModule
{
services.proxy-suite.zapret = {
engine = "zapret2";
services.proxy-suite = {
zapret = {
engine = "zapret2";
}
// zapret;
}
// zapret;
// extra;
}
];
mkZapret2 = mkZapret2With { };
in
{
zapretDiscordYoutubeGlobal = evalProxySuite [
@@ -40,7 +45,7 @@ in
}
];
zapret2Tuned = mkZapret2 {
zapret2Tuned = mkZapret2With { debug.zapret2.autoHostlist = true; } {
enable = true;
zapret2 = {
domains = [ "pinned.example" ];
@@ -56,7 +61,6 @@ in
failThreshold = 5;
failTime = 120;
retransThreshold = 4;
debugLog = true;
extendedDetection = false;
};
};
@@ -78,6 +82,7 @@ in
strategySource = "z2k";
ports.extraTcp = [ 8444 ];
strategyLog = false;
# The old name of debug.zapret2.packets: the alias must still reach nfqws2.
debug = true;
autoHostlist.extendedDetection = false;
};
+4
View File
@@ -119,6 +119,10 @@ import ./options-doc/render-options-markdown.nix {
name = "tools";
summary = "Heavy helpers `proxy-ctl` can do without: lnav and curl-impersonate.";
}
{
name = "debug";
summary = "Troubleshooting: backend log levels, a connection recorder, DNS and zapret2 logs.";
}
];
defaultConfigText = lib.generators.toPretty { allowPrettyValues = true; } (
visibleConfig eval.options.services.proxy-suite eval.config.services.proxy-suite
+197 -2
View File
@@ -66,6 +66,13 @@ Changes and secrets need root or the userControl group.
logs [unit...] follow logs (default: all proxy-suite units); in a
terminal, in lnav: scroll back, G follows, q quits
where <domain> how a domain is routed right now
debug conns [--backend socks|tun|per-app-tun] [--host <domain|address>]... [--inbound <tag>]...
[--stall <s>] [--interval <s>]
the backend's connections as they open, stall and
close, with their rule, exit and bytes (needs root or
the secrets scope); --host, --inbound: only these;
--backend tun, per-app-tun: the TUN ones (root, and
debug.connectionLog on)
proxy [status|on|off] local proxy
proxy outbounds [list] outbounds, their source, and the current pick
@@ -760,9 +767,20 @@ COMPLETE = {
"wl": "whitelist-bypass creators and joiners",
"apps": "per-app routing profiles",
"inbounds": "server inbounds",
"debug": "troubleshooting views",
"help": "usage",
}
},
"debug": {"words": {"conns": "connections as they open, stall and close"}},
"debug conns": {
"flags": {
"--backend": "socks (default), tun or per-app-tun",
"--host": "only this domain, its subdomains, or this address",
"--inbound": "only listeners whose tag starts with this (tproxy, mixed-in, tun-in)",
"--stall": "seconds without an answer before a connection is stalled (0: never)",
"--interval": "seconds between looks",
}
},
"status": {"flags": {"--json": "machine-readable state, with the GUI's overall state"}},
"logs": {"args": lambda: _names(_snapshot_units()), "repeat": True},
"where": {"args": _autoproxy_choices},
@@ -1538,7 +1556,8 @@ class _NoRedirect(urllib.request.HTTPRedirectHandler):
return None
def _clash_direct(method, path, body, timeout, secret):
def _clash_direct(method, path, body, timeout, secret, api=None):
"""api: another backend's Clash API than CLASH_API's (`debug conns --backend`)."""
# The API is on loopback: never through the shell's HTTP(S)_PROXY.
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}), _NoRedirect)
data = None if body is None else json.dumps(body).encode()
@@ -1549,7 +1568,7 @@ def _clash_direct(method, path, body, timeout, secret):
try:
# Building the request is part of reaching the API: an unset or malformed
# CLASH_API is "unreachable", not a traceback out of `status` or `where`.
request = urllib.request.Request(f"{env('CLASH_API')}{path}", data=data, method=method, headers=headers)
request = urllib.request.Request(f"{api or env('CLASH_API')}{path}", data=data, method=method, headers=headers)
with opener.open(request, timeout=timeout) as r:
status, raw = r.status, r.read()
except urllib.error.HTTPError as e:
@@ -6281,6 +6300,181 @@ ALIASES = {
}
# --- debug ----------------------------------------------------------------------
#
# `debug conns`: the backend's connections as they open, stall and close, from the Clash
# API, for failures that come and go. proxy-suite-connection-log (debug.connectionLog) runs
# it into the journal, to look back at the time one happened.
DEBUG_CONNS_SHAPE = (
"debug conns [--backend socks|tun|per-app-tun] [--host <domain|address>]... [--inbound <tag>]... "
"[--stall <seconds>] [--interval <seconds>]"
)
# The sing-box instances: the one behind the local proxy, global and per-app TProxy (the broker's,
# for userControl), and the TUN ones, whose API is up only with debug.connectionLog (root's).
DEBUG_CONNS_BACKENDS = {
"socks": None,
"tun": ("proxy-suite-tun", "CLASH_API_TUN"),
"per-app-tun": ("proxy-suite-per-app-tun", "CLASH_API_PER_APP_TUN"),
}
def _debug_clash(backend):
"""A /connections getter for the backend: (status, body), as _clash returns."""
if DEBUG_CONNS_BACKENDS[backend] is None:
return lambda: _clash("GET", "/connections", timeout=5)
unit, api = DEBUG_CONNS_BACKENDS[backend]
def get():
# Read on every look: each start of the backend writes a new one.
try:
with open(os.path.join(runtime_dir(), unit, "clash-secret"), encoding="utf-8") as f:
secret = f.read().strip()
except FileNotFoundError:
return 0, None
except PermissionError:
die(f"The {backend} backend's connections need root.")
except (OSError, UnicodeError):
return 0, None
return _clash_direct("GET", "/connections", None, 5, secret, env(api))
return get
class ConnectionLog:
"""Lines for what changed between two looks at the Clash API's connections.
A connection stalls when it has sent since it last received, then receives nothing for
`stall` seconds: it waits on an answer. One idle both ways is not stalled. Byte counts are
the last look's, at most an interval old.
"""
def __init__(self, hosts=(), inbounds=(), stall=10.0):
self.hosts = [h.lower().rstrip(".") for h in hosts]
self.inbounds = list(inbounds)
self.stall = stall
self.live = {}
def wanted(self, metadata):
inbound = _s(metadata.get("type") or "").partition("/")[2]
if self.inbounds and not any(inbound.startswith(i) for i in self.inbounds):
return False
if not self.hosts:
return True
host = _s(metadata.get("host") or "").lower().rstrip(".")
address = _s(metadata.get("destinationIP") or "")
return any(h == address or (host and _where_suffix(host, h)) for h in self.hosts)
@staticmethod
def describe(conn):
m = conn.get("metadata") or {}
# "tproxy/tproxy-in": the listener's tag after the type.
kind = _s(m.get("type") or "")
inbound = kind.partition("/")[2] or kind
address, port, host = (_s(m.get(k) or "") for k in ("destinationIP", "destinationPort", "host"))
dest = f"{host}:{port} ({address})" if host and host != address else f"{address}:{port}"
# The API lists the chain from the outbound that dials out.
chain = ">".join(_s(x) for x in reversed(conn.get("chains") or [])) or "?"
rule = " ".join(x for x in (_s(conn.get("rule") or ""), _s(conn.get("rulePayload") or "")) if x)
return f"{inbound} {_s(m.get('network') or '')} :{_s(m.get('sourcePort') or '')} -> {dest} via {chain} [{rule}]"
def step(self, connections, now):
lines, seen = [], set()
for conn in connections:
if not isinstance(conn, dict) or not conn.get("id") or not self.wanted(conn.get("metadata") or {}):
continue
seen.add(conn["id"])
up, down = (v if isinstance(v, int) else 0 for v in (conn.get("upload"), conn.get("download")))
st = self.live.get(conn["id"])
if st is None:
st = self.live[conn["id"]] = {
"desc": self.describe(conn), "opened": now, "up": 0, "down": 0,
"answered": 0, "waiting": None, "stalled": False,
}
lines.append(f"open {st['desc']}")
if down != st["down"]:
if st["stalled"]:
lines.append(f"resumed {st['desc']}, after {now - st['waiting']:.1f}s")
st.update(answered=up, waiting=None, stalled=False)
elif up > st["answered"] and st["waiting"] is None:
# A new connection has waited since it opened.
st["waiting"] = st["opened"] if not st["down"] else now
if self.stall and st["waiting"] is not None and not st["stalled"] and now - st["waiting"] >= self.stall:
st["stalled"] = True
lines.append(f"stalled {st['desc']}: no answer for {now - st['waiting']:.0f}s, up {up} B, down {down} B")
st["up"], st["down"] = up, down
# A closed connection is gone from the API: what it moved after the last look is unknown,
# so a short one that looked unanswered may well have been answered.
for cid in [c for c in self.live if c not in seen]:
st = self.live.pop(cid)
note = (", stalled, never answered" if not st["down"] else ", stalled") if st["stalled"] else ""
lines.append(
f"close {st['desc']}: up {st['up']} B, down {st['down']} B at the last look, "
f"{now - st['opened']:.1f}s{note}"
)
return lines
def lost(self):
"""Forget every connection: the backend stopped answering, or restarted."""
count, self.live = len(self.live), {}
return f"the backend's Clash API is not answering{f'; {count} connections lost from view' if count else ''}"
def _debug_conns(*args):
hosts, inbounds, stall, interval, backend = [], [], 10.0, 0.5, "socks"
it = iter(args)
for arg in it:
value = next(it, "") if arg in ("--backend", "--host", "--inbound", "--stall", "--interval") else None
if not value:
usage(DEBUG_CONNS_SHAPE)
if arg == "--backend":
if value not in DEBUG_CONNS_BACKENDS:
die(f"--backend is one of: {', '.join(DEBUG_CONNS_BACKENDS)}")
backend = value
elif arg == "--host":
hosts.append(value)
elif arg == "--inbound":
inbounds.append(value)
else:
try:
number = float(value)
except ValueError:
number = -1.0
if number < 0 or (arg == "--interval" and number == 0):
die(f"{arg} takes a number of seconds{', above 0' if arg == '--interval' else ''}.")
stall, interval = (number, interval) if arg == "--stall" else (stall, number)
log = ConnectionLog(hosts, inbounds, stall)
connections = _debug_clash(backend)
# The journal stamps its own lines.
stamped = sys.stdout.isatty()
answering = None
while True:
status, body = connections()
now = time.monotonic()
if status == 403:
die(f"Live connections show every site visited: they need the secrets scope - {ask_group()}")
if status != 200 or not isinstance(body, dict):
lines = [log.lost()] if answering is not False else []
answering = False
else:
lines = ["the backend's Clash API answers again"] if answering is False else []
answering = True
# sing-box sends null with no connections.
lines += log.step(body.get("connections") or [], now)
for line in lines:
if stamped:
line = f"{time.strftime('%H:%M:%S')}.{int(time.time() * 1000) % 1000:03d} {line}"
print(line, flush=True)
time.sleep(interval if answering else 2)
def cmd_debug(verb="", *args):
if verb == "conns":
_debug_conns(*args)
else:
usage(DEBUG_CONNS_SHAPE)
LOGS_BACKLOG = 1000
@@ -6358,6 +6552,7 @@ COMMANDS = {
"apps": cmd_apps,
"inbounds": cmd_inbounds,
"where": cmd_where,
"debug": cmd_debug,
"__complete": cmd_complete,
}
+94
View File
@@ -2558,6 +2558,100 @@ class WhereTest(EnvTest):
)
class ConnectionLogTest(unittest.TestCase):
"""`debug conns`: opens, stalls and closes read off successive /connections looks."""
@staticmethod
def conn(cid, up, down, host="pbs.twimg.com", inbound="tproxy/tproxy-in", address="199.232.172.159"):
return {
"id": cid,
"upload": up,
"download": down,
"chains": ["vps", "proxy"],
"rule": "final",
"rulePayload": "",
"metadata": {"type": inbound, "network": "tcp", "host": host, "destinationIP": address,
"destinationPort": "443", "sourcePort": "40000"},
}
def test_stall_resume_close(self):
log = ctl.ConnectionLog(stall=5)
[opened] = log.step([self.conn("a", 500, 0)], 0)
self.assertEqual(
opened, "open tproxy-in tcp :40000 -> pbs.twimg.com:443 (199.232.172.159) via proxy>vps [final]"
)
# Sent and waited since it opened: stalled once, not on every look.
self.assertEqual(log.step([self.conn("a", 500, 0)], 4), [])
[stalled] = log.step([self.conn("a", 500, 0)], 5)
self.assertTrue(stalled.startswith("stalled ") and "no answer for 5s" in stalled)
self.assertEqual(log.step([self.conn("a", 500, 0)], 9), [])
[resumed] = log.step([self.conn("a", 500, 9000)], 10)
self.assertTrue(resumed.startswith("resumed ") and resumed.endswith("after 10.0s"))
# Idle both ways is not a stall; a new request waits from when it is seen sent.
self.assertEqual(log.step([self.conn("a", 500, 9000)], 30), [])
self.assertEqual(log.step([self.conn("a", 800, 9000)], 31), [])
self.assertEqual(log.step([self.conn("a", 800, 9000)], 35), [])
self.assertIn("no answer for 5s", log.step([self.conn("a", 800, 9000)], 36)[0])
[closed] = log.step([], 40)
self.assertTrue(closed.startswith("close ") and closed.endswith("up 800 B, down 9000 B at the last look, 40.0s, stalled"))
def test_short_connection_is_not_called_unanswered(self):
# Gone before a look saw its answer: the API keeps no closed connections.
log = ctl.ConnectionLog(stall=5)
log.step([self.conn("a", 1500, 0)], 0)
[closed] = log.step([], 0.5)
self.assertNotIn("never answered", closed)
log.step([self.conn("b", 1500, 0)], 1)
log.step([self.conn("b", 1500, 0)], 7)
self.assertTrue(log.step([], 8)[0].endswith("stalled, never answered"))
def test_filters(self):
log = ctl.ConnectionLog(hosts=["twimg.com", "1.1.1.1"], inbounds=["tproxy"])
conns = [
self.conn("sub", 1, 0, host="pbs.twimg.com"),
self.conn("other", 1, 0, host="nottwimg.com"),
self.conn("mixed", 1, 0, inbound="mixed/mixed-in"),
self.conn("ip", 1, 0, host="", address="1.1.1.1"),
]
log.step(conns, 0)
self.assertEqual(sorted(log.live), ["ip", "sub"])
self.assertEqual(ctl.ConnectionLog(stall=0).step([self.conn("a", 1, 0)], 0)[0][:4], "open")
def test_lost_backend(self):
log = ctl.ConnectionLog()
log.step([self.conn("a", 1, 0), self.conn("b", 1, 0)], 0)
self.assertEqual(log.lost(), "the backend's Clash API is not answering; 2 connections lost from view")
self.assertEqual(log.step([], 1), [])
def test_arguments(self):
for args in (["--stall"], ["--host", ""], ["--bogus"], [""], ["--backend", "xray"]):
self.assertEqual(run(ctl._debug_conns, *args)[0], 1, args)
status, _, err = run(ctl._debug_conns, "--interval", "0")
self.assertEqual((status, err.strip()), (1, "--interval takes a number of seconds, above 0."))
status, _, err = run(ctl._debug_conns, "--stall", "x")
self.assertIn("--stall takes a number of seconds", err)
def test_tun_backends_read_their_own_api(self):
with tempfile.TemporaryDirectory() as run_dir, mock.patch.dict(
os.environ, {"RUNTIME_DIR": run_dir, "CLASH_API_TUN": "http://127.0.0.1:19181"}
), mock.patch.object(ctl, "_clash_direct", return_value=(200, {"connections": None})) as direct:
get = ctl._debug_clash("tun")
# Not up: no secret yet, so no API to ask.
self.assertEqual(get(), (0, None))
direct.assert_not_called()
os.mkdir(os.path.join(run_dir, "proxy-suite-tun"))
with open(os.path.join(run_dir, "proxy-suite-tun", "clash-secret"), "w") as f:
f.write("s3cret\n")
self.assertEqual(get(), (200, {"connections": None}))
direct.assert_called_once_with("GET", "/connections", None, 5, "s3cret", "http://127.0.0.1:19181")
def test_needs_the_secrets_scope(self):
with mock.patch.object(ctl, "_clash", return_value=(403, None)):
status, _, err = run(ctl._debug_conns)
self.assertEqual(status, 1)
self.assertIn("secrets scope", err)
class RoutingRulesTest(EnvTest):
"""proxy rules: the spool proxy-ctl writes, and where each rule lands among the configuration's."""
+50 -4
View File
@@ -18,10 +18,48 @@ import re
import socket
import struct
import sys
import time
TIMEOUT = 4.0
MAX_MESSAGE = 65535
# --log (debug.perAppDns): a line per lookup sent on, to the journal.
LOG = False
QTYPES = {1: "A", 2: "NS", 5: "CNAME", 6: "SOA", 12: "PTR", 15: "MX", 16: "TXT", 28: "AAAA", 33: "SRV", 64: "SVCB", 65: "HTTPS"}
RCODES = {0: "NOERROR", 1: "FORMERR", 2: "SERVFAIL", 3: "NXDOMAIN", 4: "NOTIMP", 5: "REFUSED"}
def question(query: bytes) -> str:
"""The query's question as "name TYPE"; "?" for one that does not parse.
The name is the app's to choose: anything but printable ASCII is shown as "?".
"""
try:
labels, pos = [], 12
while (length := query[pos]) != 0:
# A question has no compression pointers.
if length & 0xC0:
return "?"
labels.append(re.sub(r"[^\x21-\x7e]", "?", query[pos + 1 : pos + 1 + length].decode("latin-1")))
pos += 1 + length
(qtype,) = struct.unpack_from("!H", query, pos + 1)
except (IndexError, struct.error):
return "?"
return f"{'.'.join(labels) or '.'} {QTYPES.get(qtype, qtype)}"
def log_lookup(port: int, proto: str, query: bytes, reply: bytes | None, started: float):
if not LOG:
return
if reply is None:
outcome = "no answer"
elif len(reply) < 4:
outcome = "malformed answer"
else:
outcome = RCODES.get(reply[3] & 0x0F, f"rcode {reply[3] & 0x0F}")
took = (time.monotonic() - started) * 1000
print(f"per-app-dns: :{port} {proto} {question(query)}: {outcome} in {took:.0f} ms", flush=True)
# The source address of the queries sent on (--bind): on a TProxy route's local route the
# kernel would pick the destination as the source, and the reply would not come back.
@@ -62,9 +100,10 @@ async def ask_udp(query: bytes, servers: list[str], mark: int) -> bytes | None:
class UdpListener(asyncio.DatagramProtocol):
def __init__(self, servers: list[str], mark: int):
def __init__(self, servers: list[str], mark: int, port: int):
self.servers = servers
self.mark = mark
self.port = port
self.transport = None
def connection_made(self, transport):
@@ -74,7 +113,9 @@ class UdpListener(asyncio.DatagramProtocol):
asyncio.ensure_future(self.answer(data, addr))
async def answer(self, query, addr):
started = time.monotonic()
reply = await ask_udp(query, self.servers, self.mark)
log_lookup(self.port, "udp", query, reply, started)
if reply is not None and self.transport is not None:
self.transport.sendto(reply, addr)
@@ -113,11 +154,13 @@ async def ask_tcp(query: bytes, servers: list[str], mark: int) -> bytes | None:
return None
def tcp_handler(servers: list[str], mark: int):
def tcp_handler(servers: list[str], mark: int, port: int):
async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
try:
while (query := await asyncio.wait_for(read_message(reader), 30)) is not None:
started = time.monotonic()
reply = await ask_tcp(query, servers, mark)
log_lookup(port, "tcp", query, reply, started)
if reply is None:
break
writer.write(struct.pack("!H", len(reply)) + reply)
@@ -156,9 +199,9 @@ async def serve(listeners: list[tuple[int, int]], servers: list[str]):
for host in ("127.0.0.1", "::1"):
try:
await loop.create_datagram_endpoint(
lambda mark=mark: UdpListener(servers, mark), local_addr=(host, port)
lambda mark=mark, port=port: UdpListener(servers, mark, port), local_addr=(host, port)
)
await asyncio.start_server(tcp_handler(servers, mark), host, port)
await asyncio.start_server(tcp_handler(servers, mark, port), host, port)
except OSError as exc:
# IPv6 may be off.
if host == "127.0.0.1":
@@ -187,8 +230,11 @@ def main() -> int:
metavar="ADDRESS",
help="the source address of the queries sent on, one per family",
)
parser.add_argument("--log", action="store_true", help="log every lookup sent on, and its answer")
parser.add_argument("servers", nargs="*", help="resolver addresses, asked in order")
args = parser.parse_args()
global LOG
LOG = args.log
for address in args.bind:
BIND[socket.AF_INET6 if ":" in address else socket.AF_INET] = address
listeners = []