fix: bug fixes
This commit is contained in:
31 files changed
+626
-121
No files matched your search
@@ -4,7 +4,7 @@
|
||||
# because sing-box refuses to start when a local rule-set path is missing, so
|
||||
# every file it will be told about must exist first; the prober needs it to
|
||||
# publish what it learns, which sing-box then picks up without a restart.
|
||||
{ pkgs }:
|
||||
{ pkgs, serviceUser }:
|
||||
|
||||
pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
||||
set -euo pipefail
|
||||
@@ -17,13 +17,17 @@ pkgs.writeShellScript "proxy-suite-autoproxy" ''
|
||||
jq -c '.[]' "$1" | while IFS= read -r exit; do
|
||||
tag=$(jq -r '.tag' <<<"$exit")
|
||||
path=$(jq -r '.path' <<<"$exit")
|
||||
# sing-box, running as ${serviceUser}, watches this directory to reload the
|
||||
# files: that takes read on it, not just the search the state dir grants.
|
||||
# Asserted on every render, since StateDirectory= re-owns the tree when the
|
||||
# units' Group= changes.
|
||||
install -d -m 0750 -g ${serviceUser} "$(dirname "$path")"
|
||||
# Written aside and renamed into place: sing-box reloads on rename (as well
|
||||
# as on in-place writes), and it never reads a half-written file.
|
||||
jq -c --arg t "$tag" '
|
||||
[(.domains // {}) | to_entries[] | select(.value.exit == $t) | .key] as $d
|
||||
| {version: 1, rules: (if ($d | length) > 0 then [{domain_suffix: $d}] else [] end)}
|
||||
' "$2" > "$path.tmp"
|
||||
# sing-box reads it as proxy-suite-daemon through the 0751 state dir.
|
||||
chmod 644 "$path.tmp"
|
||||
mv -f "$path.tmp" "$path"
|
||||
done
|
||||
|
||||
@@ -14,7 +14,10 @@ let
|
||||
apCfg = cfg.proxy.autoProxy;
|
||||
# The autoProxy scope's group writes the directory: `proxy auto learn` queues there.
|
||||
stateDirMode = if userControlAllows "autoProxy" then "0771" else "0751";
|
||||
render = import ./autoproxy-render.nix { inherit pkgs; };
|
||||
render = import ./autoproxy-render.nix {
|
||||
inherit pkgs;
|
||||
inherit ((import ./derived.nix { inherit lib cfg; }).constants) serviceUser;
|
||||
};
|
||||
jqFile =
|
||||
path:
|
||||
builtins.path {
|
||||
@@ -213,13 +216,24 @@ let
|
||||
round1=$(jq -r .r1 <<<"$rounds")
|
||||
round2=$(jq -r .r2 <<<"$rounds")
|
||||
|
||||
# Every probe goes through here: a zero exit with nothing on stdout is no verdict
|
||||
# either, and empty is the one answer that slips through the checks downstream --
|
||||
# jq reads it as no input at all, so `.verdict // "error"' yields "" rather than
|
||||
# "error", and `--argjson r ""' then kills the run. Stdin is the caller's loop.
|
||||
probe_json() {
|
||||
local out
|
||||
out=$(proxy-ctl proxy auto probe --json "$@" < /dev/null 2>/dev/null || true)
|
||||
[ -n "$out" ] || out='{}'
|
||||
printf '%s' "$out"
|
||||
}
|
||||
|
||||
walk() {
|
||||
local out first verdict
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$round1" "$1" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$round1" "$1")
|
||||
verdict=$(jq -r '.verdict // "error"' <<<"$out")
|
||||
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
|
||||
first=$out
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$round2" "$1" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$round2" "$1")
|
||||
# Round 1's refusals count against its exits too (see record).
|
||||
out=$(jq -c --argjson f "$first" '.exits = ($f.exits // []) + (.exits // [])' <<<"$out")
|
||||
fi
|
||||
@@ -234,7 +248,7 @@ let
|
||||
# --- 3. re-check remembered exits, once per TTL ---
|
||||
# Probed routes only; slowness routes are judged by the sampler (4b).
|
||||
while IFS=$'\t' read -r dom host exit; do
|
||||
out=$(proxy-ctl proxy auto probe --json --exits "$exit" "$host" 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --exits "$exit" "$host")
|
||||
verdict=$(jq -r '.verdict // "error"' <<<"$out")
|
||||
if [ "$verdict" = destination ] && [ "$(jq -r '.exit // ""' <<<"$out")" = "$exit" ]; then
|
||||
update --arg d "$dom" --argjson now "$now" '.domains[$d].at = $now'
|
||||
@@ -293,14 +307,17 @@ let
|
||||
# --- 4b. what the sampler saw crawl (see autoproxy-slow-judge.jq) ---
|
||||
if [ -s "$state_dir/samples" ]; then
|
||||
mv -f "$state_dir/samples" "$state_dir/samples.taking"
|
||||
# Not `|| echo '[]'`: a grep that matches nothing fails the pipeline after
|
||||
# jq already printed [], and "[]\n[]" is no JSON for --argjson.
|
||||
obs=$(
|
||||
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}'$'\t' "$state_dir/samples.taking" |
|
||||
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |"}
|
||||
to_reg |
|
||||
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
|
||||
| {d: .[0], h: .[1], exit: .[2], slow: (.[3] == "slow"), peak: (.[4] | tonumber)})' ||
|
||||
echo '[]'
|
||||
true
|
||||
)
|
||||
[ -n "$obs" ] || obs='[]'
|
||||
rm -f "$state_dir/samples.taking"
|
||||
before=$(jq -c '.domains' "$state")
|
||||
update --argjson o "$obs" --argjson now "$now" --argjson ttl "$ttl" --argjson hits 3 \
|
||||
@@ -317,7 +334,7 @@ let
|
||||
while IFS= read -r tag; do
|
||||
[[ ",$tried," != *",$tag,"* ]] || continue
|
||||
tried="''${tried:+$tried,}$tag"
|
||||
out=$(proxy-ctl proxy auto probe --json --via "$tag" "$host" < /dev/null 2>/dev/null || echo '{}')
|
||||
out=$(probe_json --via "$tag" "$host")
|
||||
verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true)
|
||||
if [ "$verdict" = ok ]; then
|
||||
via=$tag
|
||||
@@ -402,8 +419,8 @@ let
|
||||
# on each start.
|
||||
stateDirConfig = {
|
||||
StateDirectory = "proxy-suite/autoproxy";
|
||||
# 0751 and a 027 umask: sing-box (proxy-suite) can open the rule-sets, which are
|
||||
# made 0644, and nothing else.
|
||||
# 0751 and a 027 umask: sing-box (proxy-suite-daemon) reaches the rule-sets through
|
||||
# rules/, which its group reads (autoproxy-render.nix), and nothing else.
|
||||
StateDirectoryMode = stateDirMode;
|
||||
UMask = "0027";
|
||||
}
|
||||
|
||||
@@ -51,6 +51,11 @@ let
|
||||
# The sing-box tunnel; asOutbound = "interface" comes in through the AmneziaWG profile list.
|
||||
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
|
||||
|
||||
# Two ports per "singBox" AmneziaWG outbound, above the autoProxy prober's own
|
||||
# listeners (proxy.autoProxy.probeBasePort, 18540 by default, one per exit):
|
||||
# both bind loopback, so an overlap leaves whichever unit starts second dead.
|
||||
awgTunnelBasePort = 18600;
|
||||
|
||||
# AmneziaWG profiles are either global (proxy-ctl awg on) or outbounds tagged with their name.
|
||||
awgProfiles = lib.optionalAttrs cfg.amneziaWg.enable cfg.amneziaWg.profiles;
|
||||
awgGlobalProfiles = lib.filterAttrs (_: profile: profile.asOutbound == null) awgProfiles;
|
||||
@@ -65,8 +70,8 @@ let
|
||||
kind = profile.asOutbound;
|
||||
interface = profile.interfaceName;
|
||||
# Loopback listeners of a "singBox" tunnel, as warpCfg.tunnelPort/directPort.
|
||||
tunnelPort = 18540 + 2 * index;
|
||||
directPort = 18541 + 2 * index;
|
||||
tunnelPort = awgTunnelBasePort + 2 * index;
|
||||
directPort = awgTunnelBasePort + 1 + 2 * index;
|
||||
}
|
||||
) (builtins.filter (name: awgProfiles.${name}.asOutbound != null) (builtins.attrNames awgProfiles));
|
||||
awgInterfaceOutbounds = builtins.filter (ob: ob.kind == "interface") awgOutbounds;
|
||||
|
||||
@@ -69,6 +69,23 @@ let
|
||||
description = "gRPC service name.";
|
||||
example = "GunService";
|
||||
};
|
||||
|
||||
trustedXForwardedFor = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = ''
|
||||
Header names that mark a request as coming from the web server in front (ws, httpupgrade,
|
||||
xhttp, grpc). When one of them is present, XRay takes the client address from
|
||||
"X-Forwarded-For" instead of the socket. Needed for a listener on a loopback `address`:
|
||||
XRay otherwise sees 127.0.0.1, which it refuses to record, so `proxy-ctl inbounds online`
|
||||
shows every user as never seen and the stats keep no last-seen time.
|
||||
|
||||
Set it only when the web server in front sets both the named header and "X-Forwarded-For"
|
||||
on every request it forwards, overwriting whatever the client sent: any client that can
|
||||
reach the listener directly could otherwise claim any address.
|
||||
'';
|
||||
example = [ "X-Real-IP" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -87,11 +87,28 @@ let
|
||||
++ (if syncZapretDirectUserIps then zapretCfg.zapret-discord-youtube.excludeIps else [ ])
|
||||
);
|
||||
|
||||
# A zapret hostlist marks an exact-match entry with "^" (nfqws syntax, used by
|
||||
# list-general.txt for the DoH resolvers). No proxy backend has such a prefix, so
|
||||
# "^dns.google" copied straight through matches nothing and the entry silently
|
||||
# stops bypassing; as a plain suffix it covers the name itself, which is the point.
|
||||
# The generated nfqws hostlists keep the prefix: only the routing sync drops it.
|
||||
stripExactPrefix = lib.removePrefix "^";
|
||||
|
||||
zapretDirectDomains =
|
||||
if syncZapretDirectDomains then
|
||||
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains)) (
|
||||
lib.unique (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
|
||||
)
|
||||
subtractItems
|
||||
(lib.unique (
|
||||
map stripExactPrefix (
|
||||
zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains
|
||||
)
|
||||
))
|
||||
(
|
||||
lib.unique (
|
||||
map stripExactPrefix (
|
||||
zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains
|
||||
)
|
||||
)
|
||||
)
|
||||
else
|
||||
[ ];
|
||||
zapretDirectIps =
|
||||
|
||||
@@ -56,6 +56,23 @@ let
|
||||
condition: value: disallowed: message:
|
||||
mkAssertion (!(condition && builtins.elem value disallowed)) message;
|
||||
|
||||
# Every loopback listener proxy-suite opens with a fixed port of its own, which
|
||||
# the autoProxy prober's range must stay clear of.
|
||||
reservedLoopbackPorts =
|
||||
builtins.attrValues constants.xrayDnsBridgePorts
|
||||
++ [
|
||||
constants.inboundStatsApiPort
|
||||
constants.outboundTestPort
|
||||
]
|
||||
++ lib.optionals derived.warpOutboundEnabled [
|
||||
derived.warpCfg.tunnelPort
|
||||
derived.warpCfg.directPort
|
||||
]
|
||||
++ lib.concatMap (ob: [
|
||||
ob.tunnelPort
|
||||
ob.directPort
|
||||
]) (builtins.filter (ob: ob.kind == "singBox") derived.awgOutbounds);
|
||||
|
||||
featureAssertions = [
|
||||
# Declaring no outbound at all is legal: they can be added at runtime with
|
||||
# `proxy-ctl proxy outbounds add`. Only a warning here; the backend still
|
||||
@@ -322,6 +339,22 @@ let
|
||||
)
|
||||
"proxy-suite: a proxyInbounds listener port collides with a port proxy-suite uses internally (the inbounds' stats API on ${toString derived.constants.inboundStatsApiPort}, or 18533-18535)"
|
||||
)
|
||||
# The prober opens one loopback listener per exit from probeBasePort; the WARP
|
||||
# and AmneziaWG tunnels open two each from their own bases. They all bind
|
||||
# 127.0.0.1, so an overlap leaves whichever unit starts second dead.
|
||||
(mkAssertion
|
||||
(
|
||||
!(proxyEnabled && proxyCfg.autoProxy.enable)
|
||||
|| !lib.any (
|
||||
port:
|
||||
port >= proxyCfg.autoProxy.probeBasePort
|
||||
&& port < proxyCfg.autoProxy.probeBasePort + proxyCfg.autoProxy.maxExits
|
||||
) reservedLoopbackPorts
|
||||
)
|
||||
"proxy-suite: proxy.autoProxy.probeBasePort ${toString proxyCfg.autoProxy.probeBasePort} and the next ${toString proxyCfg.autoProxy.maxExits} ports cover one proxy-suite already listens on (${
|
||||
lib.concatMapStringsSep ", " toString reservedLoopbackPorts
|
||||
}); move probeBasePort"
|
||||
)
|
||||
]
|
||||
++ lib.concatMap (
|
||||
ib:
|
||||
|
||||
@@ -102,6 +102,18 @@ let
|
||||
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
|
||||
# A live switch skips the restart that rewrites the inventory, and the pin
|
||||
# is only ever read from there: without this the outbound reads as merely
|
||||
# current, and the front ends offer no unpin until the next restart.
|
||||
if [ -f "${outboundInventoryFile}" ]; then
|
||||
INVENTORY_TMP=$(mktemp "${outboundInventoryFile}.XXXXXX")
|
||||
if ${jq} --arg t "$tag" '.pinned = $t' "${outboundInventoryFile}" > "$INVENTORY_TMP"; then
|
||||
chmod 644 "$INVENTORY_TMP"
|
||||
mv -f "$INVENTORY_TMP" "${outboundInventoryFile}"
|
||||
else
|
||||
rm -f "$INVENTORY_TMP"
|
||||
fi
|
||||
fi
|
||||
${restartActiveBlock tunConsumers}
|
||||
exit 0
|
||||
fi
|
||||
|
||||
@@ -275,4 +275,39 @@ lib.mkMerge [
|
||||
|
||||
systemd.timers = mkNamedUnits timerEntries;
|
||||
}
|
||||
|
||||
# A certificate or key XRay cannot read is copied in at start (proxy-inbounds-scripts.nix),
|
||||
# and a copy never sees a renewal: restart the inbounds when a declared one changes.
|
||||
# ponytail: files named only inside xrayJson are not watched; declare tls.* for those.
|
||||
(
|
||||
let
|
||||
certFiles = lib.unique (
|
||||
lib.concatMap (
|
||||
l:
|
||||
lib.filter (f: f != null) [
|
||||
l.tls.certificateFile
|
||||
l.tls.keyFile
|
||||
]
|
||||
) (builtins.attrValues cfg.inbounds.listeners)
|
||||
);
|
||||
in
|
||||
lib.mkIf (cfg.enable && proxyInboundsEnabled && certFiles != [ ]) {
|
||||
systemd.paths.proxy-suite-inbounds-certs = {
|
||||
description = "proxy-suite - watch the inbounds' TLS certificates for renewals";
|
||||
wantedBy = [ "paths.target" ];
|
||||
pathConfig.PathChanged = certFiles;
|
||||
};
|
||||
systemd.services.proxy-suite-inbounds-certs = {
|
||||
description = "proxy-suite - restart the inbounds onto a renewed certificate";
|
||||
serviceConfig.Type = "oneshot";
|
||||
script = ''
|
||||
# XRay reloads the files it reads itself; only copies go stale.
|
||||
[ -d /run/proxy-suite-inbounds/tls ] || exit 0
|
||||
# A renewal writes the chain and the key one after the other.
|
||||
sleep 10
|
||||
${pkgs.systemd}/bin/systemctl try-restart proxy-suite-inbounds.service
|
||||
'';
|
||||
};
|
||||
}
|
||||
)
|
||||
]
|
||||
@@ -200,13 +200,14 @@ let
|
||||
'';
|
||||
|
||||
# Adds XRay's counters to the daily totals, read and reset in one call, and notes who
|
||||
# is online.
|
||||
# ponytail: a restart of the inbounds loses what was counted since the last run, at
|
||||
# most one timer interval; collect from ExecStop if that matters.
|
||||
# is online. Run by a timer, and by the inbounds' ExecStop, so a restart loses nothing.
|
||||
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbounds" ''
|
||||
set -euo pipefail
|
||||
file=${lib.escapeShellArg constants.inboundStatsFile}
|
||||
api=--server=127.0.0.1:${toString constants.inboundStatsApiPort}
|
||||
# A timer run and a stop can overlap: each reads and resets part, and both rewrite the file.
|
||||
exec 9> "$file.lock"
|
||||
${pkgs.util-linux}/bin/flock 9
|
||||
if ! reading=$(${xray} api statsquery "$api" -pattern "" -reset 2> /dev/null); then
|
||||
echo "the inbounds' stats API is not answering; nothing collected"
|
||||
exit 0
|
||||
|
||||
@@ -40,7 +40,10 @@ let
|
||||
xraySidecarBasePorts
|
||||
;
|
||||
|
||||
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
|
||||
autoProxyRender = import ../autoproxy-render.nix {
|
||||
inherit pkgs;
|
||||
inherit (constants) serviceUser;
|
||||
};
|
||||
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
|
||||
userControlGroup = lib.escapeShellArg userControlCfg.group;
|
||||
chgrp = "${pkgs.coreutils}/bin/chgrp";
|
||||
@@ -171,9 +174,13 @@ let
|
||||
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
|
||||
${subscriptionCacheHelpersBlock}
|
||||
${lib.optionalString enableLocalProxyAuth ''
|
||||
umask 077
|
||||
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||
${writeProxychainsConfigBlock}
|
||||
# The umask stays in the subshell: left set, it also narrowed everything
|
||||
# written below, and autoProxy's state.json is group-readable by design.
|
||||
(
|
||||
umask 077
|
||||
${writeProxychainsConfigBlock}
|
||||
)
|
||||
''}
|
||||
${lib.optionalString xrayEnabled ''
|
||||
if [ -r "${xrayLoglevelFile}" ]; then
|
||||
@@ -210,7 +217,7 @@ let
|
||||
AUTOPROXY_RULES_JSON='[]'
|
||||
${lib.optionalString enableAutoProxy ''
|
||||
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
|
||||
# 0751: sing-box, running as ${constants.serviceUser}, reads the rule-sets inside;
|
||||
# 0751: sing-box, running as ${constants.serviceUser}, reaches the rules/ inside;
|
||||
# 0771 with userControl's autoProxy scope, whose group queues learn requests there.
|
||||
install -d -m ${if userControlAllows "autoProxy" then "0771" else "0751"} "$AUTOPROXY_DIR"
|
||||
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
|
||||
@@ -225,7 +232,7 @@ let
|
||||
| to_entries
|
||||
| map({i: .key, tag: .value, port: ($base + .key),
|
||||
rule_set: ("autoproxy-" + (.key | tostring)),
|
||||
path: ($dir + "/rs-" + (.key | tostring) + ".json")})
|
||||
path: ($dir + "/rules/rs-" + (.key | tostring) + ".json")})
|
||||
' <<< "$EXIT_TAGS_JSON")
|
||||
printf '%s\n' "$PROBE_EXITS_JSON" > "$RUNTIME_DIR/probe-exits.json"
|
||||
# proxy-ctl reads it unprivileged; it holds tags and loopback ports only.
|
||||
|
||||
@@ -105,7 +105,12 @@ let
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.startInbounds;
|
||||
runtimeDirectory = serviceNames.inbounds;
|
||||
extraServiceConfig = xrayAssetEnv;
|
||||
# The collector's file.
|
||||
stateDirectory = "proxy-suite";
|
||||
# While XRay still runs: what it counted since the last timer run.
|
||||
extraServiceConfig = xrayAssetEnv // {
|
||||
ExecStop = scripts.collectInboundStats;
|
||||
};
|
||||
};
|
||||
}
|
||||
{
|
||||
@@ -246,8 +251,9 @@ let
|
||||
enable = proxyEnabled;
|
||||
name = "proxy-suite-outbound-pin@";
|
||||
value = mkOneshotService {
|
||||
description = "Pin the proxy-suite outbound to %i";
|
||||
execStart = "${scripts.pinOutboundScript} %i";
|
||||
# %I: proxy-ctl systemd-escapes the tag, so "ssh-proxy" arrives as ssh\x2dproxy.
|
||||
description = "Pin the proxy-suite outbound to %I";
|
||||
execStart = "${scripts.pinOutboundScript} %I";
|
||||
stateDirectory = "proxy-suite";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user