refactor: move out large code blocks out of nix

This commit is contained in:
fufsob authored and FUFSoB committed 2026-10-04 11:54:04 +05:00
1 parent e8ace6523d
commit af5b3ff27a
47 files changed
+2220 -2070

No files matched your search

+10 -25
View File
@@ -10,31 +10,16 @@
ifPrivileged,
}:
pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
# $1 - probe-exits.json (index -> tag -> path), $2 - state.json
export PATH=${
pkgs.lib.makeBinPath [
let
fillTemplate = import ./lib/fill-template.nix;
in
pkgs.writeShellScript "proxy-suite-autoproxy" (
fillTemplate ./autoproxy-render.template.sh {
path = pkgs.lib.makeBinPath [
pkgs.coreutils
pkgs.jq
]
];
inherit serviceUser;
groupArg = ifPrivileged "-g ${serviceUser} ";
}
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 ${ifPrivileged "-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"
chmod 644 "$path.tmp"
mv -f "$path.tmp" "$path"
done
''
)
@@ -0,0 +1,21 @@
set -euo pipefail
# $1 - probe-exits.json (index -> tag -> path), $2 - state.json
export PATH=@path@
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 @groupArg@"$(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"
chmod 644 "$path.tmp"
mv -f "$path.tmp" "$path"
done
@@ -0,0 +1,381 @@
set -euo pipefail
export PATH=@path@
# --requests-only: just the `proxy-ctl proxy auto learn|forget|clear` requests.
mode=${1:-full}
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@}
export PROBE_EXITS_FILE=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
edits="$state_dir/edits"
now=$(date +%s)
ttl=$(( @ttlDays@ * 86400 ))
install -d -m @stateDirMode@ "$state_dir"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
flock 9
# Leftovers of a run that died partway; taken requests go back in line.
rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking"
for queue in "$requests" "$edits"; do
if [ -e "$queue.taking" ]; then
cat "$queue.taking" >> "$queue"
rm -f "$queue.taking"
# Made here by root: the group appends to it too.
chmod 0660 "$queue"
fi
done
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2
mv -f "$state" "$state.broken"
fi
[ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state"
# Written aside and renamed, so a killed run never truncates the state.
update() {
local tmp
tmp=$(mktemp "$state.XXXXXX")
if ! jq "$@" "$state" > "$tmp"; then
rm -f "$tmp"
echo "could not update $state; it is left as it was" >&2
return 1
fi
# mktemp makes it 0600; the state dir is 0751, so group-readable is enough.
chmod 0640 "$tmp"
mv -f "$tmp" "$state"
}
# --- 0. forget what `proxy-ctl proxy auto forget|relearn|clear` asked to ---
# Before anything else, and even with the proxy stopped: its start renders the
# rule-sets from the state again.
edited=""
if [ -s "$edits" ]; then
mv -f "$edits" "$edits.taking"
while read -r op dom; do
case "$op" in
forget)
[[ "$dom" =~ ^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$ ]] || continue
update --arg op forget --arg d "$dom" -f @editJq@
echo "forgot $dom"
;;
clear)
update --arg op clear --arg d "" -f @editJq@
echo "forgot everything learned"
;;
*) continue ;;
esac
edited=1
done < "$edits.taking"
rm -f "$edits.taking"
fi
if [ ! -r "$index" ]; then
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0
fi
# Routes through an outbound disabled since (`proxy-ctl proxy outbounds disable`)
# are forgotten like the above, so their domains get probed again without it.
inventory="$(dirname "$index")/outbounds.json"
if [ -r "$inventory" ]; then
while IFS=$'\t' read -r dom exit; do
echo "forgot $dom: its exit $exit is disabled"
update --arg op forget --arg d "$dom" -f @editJq@
edited=1
done < <(jq -r --slurpfile inv "$inventory" '($inv[0].disabled // []) as $off
| (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e]))
| "\(.key)\t\(.value.exit)"' "$state")
fi
[ -z "$edited" ] || @render@ "$index" "$state"
# $1 JSON array of exit tags, $2 registrable domain, $3 wall:<page>|refused|slow.
strike() {
update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \
-f @strikeJq@
}
# $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the
# whole domain (geo-blocks are drawn around sites); other verdicts only to
# the host probed.
record() {
update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" '
(if $r.verdict == "destination" then
.domains[$d] = {verdict: "destination", exit: $r.exit, host: $h,
path: ($r.path // "/"), at: $now}
else . end)
| .hosts[$h] = {
domain: $d,
verdict: ($r.verdict // "error"),
exit: (if $r.verdict == "destination" then $r.exit else null end),
at: $now
}
| del(.backlog[$h])'
# Exits refused on the path another egress reached: by a block page
# (wall:<page>, the site turning the address away) or by the origin.
local t why
while IFS=$'\t' read -r t why; do
strike "$(jq -cn --arg t "$t" '[$t]')" "$1" "$why"
done < <(jq -r '(.path // "") as $p | .exit as $x
| ([(.exits // [])[] | select(.tag == $x and .path == $p) | .judgement][0]) as $won
| if $x == null then empty else
# An origin refusal only counts against an exit when the winner got content.
[(.exits // [])[] | select(.path == $p and .tag != "direct" and .tag != $x
and (.judgement == "wall" or (.judgement == "blocked" and $won == "ok")))
| {tag, why: (if .judgement == "wall" then "wall:" + .block else "refused" end)}]
| unique_by(.tag)[] | "\(.tag)\t\(.why)"
end' <<<"$3")
}
# Prefixes each host line with "registrable-domain<TAB>".
# ponytail: last two labels, or three under a short list of two-label
# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly.
to_reg() {
awk -F'\t' '
BEGIN {
n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ")
for (i = 1; i <= n; i++) two[s[i]] = 1
}
{
n = split($1, l, ".")
if (n < 2) next
k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n]
print k "\t" $0
}'
}
# The pinned direct listener, since TUN/TProxy capture --noproxy too.
direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index")
# --- 1. verdicts are about this host's address; drop them if it changed ---
egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
# An error page or a captive portal must not pass for a new address: anything
# that is not one discards every verdict this host learned.
[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress=""
if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then
echo "egress is now $egress; discarding everything learned for the old address"
update --arg e "$egress" \
'{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}'
fi
# --- 2. which network (AS) each exit leaves from, once per TTL ---
while IFS=$'\t' read -r tag port; do
at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state")
[ $(( now - at )) -ge "$ttl" ] || continue
info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true)
asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true)
[ -n "$ip" ] || continue
update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \
'.exits[$t] += {ip: $ip, asn: $asn, at: $now}'
done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index")
# --- 2b. strikes older than a TTL stop counting against an exit ---
strike '[]' "" ""
# See autoproxy-rounds.jq: one exit per AS, then the rest, bad exits last.
rounds=$(jq -c --slurpfile s "$state" -f @roundsJq@ "$index")
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=$(probe_json --exits "$round1" "$1")
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
first=$out
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
printf '%s' "$out"
}
# Route changes take effect immediately, not at the end of the run.
publish() { @render@ "$index" "$state"; }
requeue=()
if [ "$mode" = full ]; then
# --- 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=$(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'
elif [ "$verdict" = ok ]; then
echo "recheck $dom: reachable directly now, dropping $exit"
update --arg d "$dom" 'del(.domains[$d])'
record "$dom" "$host" "$out"
publish
else
echo "recheck $dom: $exit no longer works ($verdict), walking again"
update --arg d "$dom" 'del(.domains[$d])'
publish
requeue+=("$dom"$'\t'"$host")
fi
done < <(jq -r --argjson now "$now" --argjson every "$ttl" '
.domains | to_entries[]
| select(.value.verdict == "destination" and ($now - .value.at) >= $every)
| "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state")
# --- 4. what clients dialled since the last run, counted per host ---
# Hit counts accumulate in a backlog that survives between runs.
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-@interval@"; fi
dialled=$(
@journalctl@ -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
@excludeHosts@
to_reg || true
)
counts=$(
printf '%s\n' "$dialled" |
awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries'
)
# Skipped: hosts of an already routed domain, hosts judged within the TTL.
# Dropped: entries older than the TTL, and those a route now covers; host
# verdicts past the TTL, which would only be probed again anyway.
update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" '
. as $s
| .lastRun = $now
| .hosts |= with_entries(select(.value.at + $ttl > $now))
| .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {});
if ($s.domains[$e.value.domain].exit != null)
or ((($s.hosts[$e.key].at // 0) + $ttl) > $now)
then .
else .[$e.key] = {
domain: $e.value.domain,
hits: ((.[$e.key].hits // 0) + $e.value.hits),
first: (.[$e.key].first // $now)
} end))
| .backlog |= with_entries(select(.value.first + $ttl > $now
and $s.domains[.value.domain].exit == null))'
# --- 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" |
@excludeSampleHosts@
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)})' ||
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 \
-f @slowJudgeJq@
# Each crawling destination gets the next exit, in probe order, that
# answers it as well as direct does (`probe --via`). None left: it
# stays direct for a TTL.
while IFS=$'\t' read -r dom host tried; do
was=${tried##*,}
# It crawled twice on the exit it was routed through.
[ -z "$was" ] || strike "$(jq -cn --arg t "$was" '[$t]')" "$dom" slow
via=""
while IFS= read -r tag; do
[[ ",$tried," != *",$tag,"* ]] || continue
tried="${tried:+$tried,}$tag"
out=$(probe_json --via "$tag" "$host")
verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true)
if [ "$verdict" = ok ]; then
via=$tag
break
fi
# Refused what direct gets, by a block page or by the origin.
if [ "$verdict" = blocked ]; then
why=$(jq -r --arg t "$tag" '[.exits[] | select(.tag == $t)] as $r
| [$r[] | select(.judgement == "wall") | "wall:" + .block][0]
// (if any($r[]; .judgement == "blocked") then "refused" else "" end)' <<<"$out" 2>/dev/null || true)
[ -z "$why" ] || strike "$(jq -cn --arg t "$tag" '[$t]')" "$dom" "$why"
fi
done < <(jq -r '.ordered[]' <<<"$rounds")
if [ -n "$via" ]; then
echo "slow $dom: crawls ${was:+via $was}${was:-directly}, routed via $via"
update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" '
.domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))}
| del(.slowWant[$d])'
else
echo "slow $dom: crawls ${was:+via $was}${was:-directly}, and no other exit reaches it; left direct"
update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])'
fi
done < <(jq -r '(.slowWant // {}) | to_entries[]
| "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state")
[ "$(jq -c '.domains' "$state")" = "$before" ] || publish
fi
fi
# --- 5. probe: requests (uncapped), then broken routes, then the backlog ---
asked=()
if [ -s "$requests" ]; then
mv -f "$requests" "$requests.taking"
mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true)
rm -f "$requests.taking"
fi
backlog=()
if [ "$mode" = full ]; then
mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" '
. as $s | (.backlog // {}) | to_entries
| map(select(($s.domains[.value.domain].exit == null)
and ((($s.hosts[.key].at // 0) + $ttl) <= $now)))
| sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state")
fi
declare -A seen routed
probe_row() {
local dom=${1%%$'\t'*} host=${1#*$'\t'} out
{ [ -z "${seen[$host]:-}" ] && [ -z "${routed[$dom]:-}" ]; } || return 1
seen[$host]=1
out=$(walk "$host")
# A probe that failed to run is no verdict; the host is probed again.
if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then
echo "probe $host -> error, not recorded"
return 0
fi
record "$dom" "$host" "$out"
if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then
routed[$dom]=1
publish
fi
# A censor verdict names an exit that got through, but zapret owns it.
echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit
elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")"
}
for row in "${asked[@]}"; do probe_row "$row" || true; done
probed=0
for row in "${requeue[@]}" "${backlog[@]}"; do
[ "$probed" -lt @probesPerRun@ ] || break
if probe_row "$row"; then probed=$(( probed + 1 )); fi
done
echo "probed ${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting"
# sing-box reloads the rewritten rule-sets itself.
@render@ "$index" "$state"
@@ -0,0 +1,21 @@
set -euo pipefail
export PATH=@path@
state_dir=${AUTOPROXY_STATE_DIR:-@stateDir@}
index=${PROBE_EXITS_FILE:-@runtimeDir@/proxy-suite-socks/probe-exits.json}
@clashApiBlock@
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
install -d -m @stateDirMode@ "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
for i in $(seq 0 10); do
[ "$i" -eq 0 ] || sleep 1
curl -sS --noproxy '*' --max-time 1 -H @<(clash_auth_header) "http://$clash_api/connections" 2>/dev/null ||
echo '{}'
done | jq -s -r --argjson min @minBytes@ \
--argjson below @slowBelowBytes@ -f @slowSampleJq@ || true
)
[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples"
+30 -406
View File
@@ -13,6 +13,7 @@
}:
let
fillTemplate = import ./lib/fill-template.nix;
apCfg = cfg.proxy.autoProxy;
derived = import ./derived.nix { inherit lib cfg; };
inherit (derived.constants) rootInSharedDirConfig;
@@ -59,415 +60,38 @@ let
clash_auth_header() { printf 'Authorization: Bearer %s\n' "$clash_secret"; }
'';
sampler = pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
export PATH=${bin}
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
index=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
${clashApiBlock}
if [ -z "$clash_api" ]; then
echo "sing-box has no Clash API (selection = \"first\"?); nothing to sample"
exit 0
fi
install -d -m ${stateDirMode} "$state_dir"
# Eleven snapshots a second apart: ten one-second deltas per connection.
lines=$(
for i in $(seq 0 10); do
[ "$i" -eq 0 ] || sleep 1
curl -sS --noproxy '*' --max-time 1 -H @<(clash_auth_header) "http://$clash_api/connections" 2>/dev/null ||
echo '{}'
done | jq -s -r --argjson min ${toString (300 * 1024)} \
--argjson below ${
toString (apCfg.slowBelowKiBps * 1024)
} -f ${jqFile ./autoproxy-slow-sample.jq} || true
)
[ -z "$lines" ] || printf '%s\n' "$lines" >> "$state_dir/samples"
'';
runner = pkgs.writeShellScript "proxy-suite-autoproxy" ''
set -euo pipefail
export PATH=${bin}
# --requests-only: just the `proxy-ctl proxy auto learn|forget|clear` requests.
mode=''${1:-full}
# Overridable to rehearse a run against a scratch copy; the units never set them.
state_dir=''${AUTOPROXY_STATE_DIR:-${lib.escapeShellArg autoProxyStateDir}}
export PROBE_EXITS_FILE=''${PROBE_EXITS_FILE:-${runtimeDir}/proxy-suite-socks/probe-exits.json}
index=$PROBE_EXITS_FILE
state="$state_dir/state.json"
requests="$state_dir/requests"
edits="$state_dir/edits"
now=$(date +%s)
ttl=$(( ${toString apCfg.ttlDays} * 86400 ))
install -d -m ${stateDirMode} "$state_dir"
# Timer runs and learn requests take turns on the state.
exec 9> "$state_dir/lock"
flock 9
# Leftovers of a run that died partway; taken requests go back in line.
rm -f "$state_dir/verdicts.json" "$state_dir/proxied-domains.txt" "$state".?????? "$state_dir/samples.taking"
for queue in "$requests" "$edits"; do
if [ -e "$queue.taking" ]; then
cat "$queue.taking" >> "$queue"
rm -f "$queue.taking"
# Made here by root: the group appends to it too.
chmod 0660 "$queue"
fi
done
if [ -e "$state" ] && ! jq -e 'type == "object"' "$state" > /dev/null 2>&1; then
echo "$state is unreadable; set aside as $state.broken, starting fresh" >&2
mv -f "$state" "$state.broken"
fi
[ -s "$state" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$state"
# Written aside and renamed, so a killed run never truncates the state.
update() {
local tmp
tmp=$(mktemp "$state.XXXXXX")
if ! jq "$@" "$state" > "$tmp"; then
rm -f "$tmp"
echo "could not update $state; it is left as it was" >&2
return 1
fi
# mktemp makes it 0600; the state dir is 0751, so group-readable is enough.
chmod 0640 "$tmp"
mv -f "$tmp" "$state"
sampler = pkgs.writeShellScript "proxy-suite-autoproxy" (
fillTemplate ./autoproxy-sample.template.sh {
path = bin;
stateDir = lib.escapeShellArg autoProxyStateDir;
inherit runtimeDir clashApiBlock stateDirMode;
minBytes = toString (300 * 1024);
slowBelowBytes = toString (apCfg.slowBelowKiBps * 1024);
slowSampleJq = jqFile ./autoproxy-slow-sample.jq;
}
);
# --- 0. forget what `proxy-ctl proxy auto forget|relearn|clear` asked to ---
# Before anything else, and even with the proxy stopped: its start renders the
# rule-sets from the state again.
edited=""
if [ -s "$edits" ]; then
mv -f "$edits" "$edits.taking"
while read -r op dom; do
case "$op" in
forget)
[[ "$dom" =~ ^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$ ]] || continue
update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq}
echo "forgot $dom"
;;
clear)
update --arg op clear --arg d "" -f ${jqFile ./autoproxy-edit.jq}
echo "forgot everything learned"
;;
*) continue ;;
esac
edited=1
done < "$edits.taking"
rm -f "$edits.taking"
fi
if [ ! -r "$index" ]; then
echo "no probe listeners - is proxy-suite-socks running with autoProxy on?"
exit 0
fi
# Routes through an outbound disabled since (`proxy-ctl proxy outbounds disable`)
# are forgotten like the above, so their domains get probed again without it.
inventory="$(dirname "$index")/outbounds.json"
if [ -r "$inventory" ]; then
while IFS=$'\t' read -r dom exit; do
echo "forgot $dom: its exit $exit is disabled"
update --arg op forget --arg d "$dom" -f ${jqFile ./autoproxy-edit.jq}
edited=1
done < <(jq -r --slurpfile inv "$inventory" '($inv[0].disabled // []) as $off
| (.domains // {}) | to_entries[] | select(.value.exit as $e | $off | index([$e]))
| "\(.key)\t\(.value.exit)"' "$state")
fi
[ -z "$edited" ] || ${render} "$index" "$state"
# $1 JSON array of exit tags, $2 registrable domain, $3 wall:<page>|refused|slow.
strike() {
update --argjson tags "$1" --arg d "$2" --arg why "$3" --argjson now "$now" --argjson ttl "$ttl" \
-f ${jqFile ./autoproxy-strike.jq}
runner = pkgs.writeShellScript "proxy-suite-autoproxy" (
fillTemplate ./autoproxy-run.template.sh {
path = bin;
stateDir = lib.escapeShellArg autoProxyStateDir;
inherit runtimeDir;
ttlDays = toString apCfg.ttlDays;
inherit stateDirMode;
editJq = jqFile ./autoproxy-edit.jq;
inherit render;
strikeJq = jqFile ./autoproxy-strike.jq;
roundsJq = jqFile ./autoproxy-rounds.jq;
interval = apCfg.interval;
inherit journalctl;
excludeHosts = lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |";
excludeSampleHosts = lib.optionalString (
excludePattern != ""
) "grep -vE '(^|\\.)(${excludePattern})'$'\\t' |";
slowJudgeJq = jqFile ./autoproxy-slow-judge.jq;
probesPerRun = toString apCfg.probesPerRun;
}
# $1 registrable domain, $2 host probed, $3 probe JSON. Routes apply to the
# whole domain (geo-blocks are drawn around sites); other verdicts only to
# the host probed.
record() {
update --arg d "$1" --arg h "$2" --argjson r "$3" --argjson now "$now" '
(if $r.verdict == "destination" then
.domains[$d] = {verdict: "destination", exit: $r.exit, host: $h,
path: ($r.path // "/"), at: $now}
else . end)
| .hosts[$h] = {
domain: $d,
verdict: ($r.verdict // "error"),
exit: (if $r.verdict == "destination" then $r.exit else null end),
at: $now
}
| del(.backlog[$h])'
# Exits refused on the path another egress reached: by a block page
# (wall:<page>, the site turning the address away) or by the origin.
local t why
while IFS=$'\t' read -r t why; do
strike "$(jq -cn --arg t "$t" '[$t]')" "$1" "$why"
done < <(jq -r '(.path // "") as $p | .exit as $x
| ([(.exits // [])[] | select(.tag == $x and .path == $p) | .judgement][0]) as $won
| if $x == null then empty else
# An origin refusal only counts against an exit when the winner got content.
[(.exits // [])[] | select(.path == $p and .tag != "direct" and .tag != $x
and (.judgement == "wall" or (.judgement == "blocked" and $won == "ok")))
| {tag, why: (if .judgement == "wall" then "wall:" + .block else "refused" end)}]
| unique_by(.tag)[] | "\(.tag)\t\(.why)"
end' <<<"$3")
}
# Prefixes each host line with "registrable-domain<TAB>".
# ponytail: last two labels, or three under a short list of two-label
# suffixes. Switch to the Public Suffix List if a domain gets merged wrongly.
to_reg() {
awk -F'\t' '
BEGIN {
n = split("co.uk org.uk ac.uk gov.uk com.au net.au org.au co.jp ne.jp or.jp com.br com.tr co.kr com.cn com.hk co.in co.za com.ua com.mx co.nz", s, " ")
for (i = 1; i <= n; i++) two[s[i]] = 1
}
{
n = split($1, l, ".")
if (n < 2) next
k = (n >= 3 && (l[n - 1] "." l[n]) in two) ? l[n - 2] "." l[n - 1] "." l[n] : l[n - 1] "." l[n]
print k "\t" $0
}'
}
# The pinned direct listener, since TUN/TProxy capture --noproxy too.
direct_url=$(jq -r '.[0] | "http://127.0.0.1:\(.port)"' "$index")
# --- 1. verdicts are about this host's address; drop them if it changed ---
egress=$(curl -sS -f --proxy "$direct_url" --max-time 10 https://api.ipify.org 2>/dev/null || true)
# An error page or a captive portal must not pass for a new address: anything
# that is not one discards every verdict this host learned.
[[ "$egress" =~ ^[0-9a-fA-F.:]+$ ]] || egress=""
if [ -n "$egress" ] && [ "$(jq -r '.egress // ""' "$state")" != "$egress" ]; then
echo "egress is now $egress; discarding everything learned for the old address"
update --arg e "$egress" \
'{egress: $e, domains: {}, hosts: {}, exits: {}, backlog: (.backlog // {}), lastRun: (.lastRun // 0)}'
fi
# --- 2. which network (AS) each exit leaves from, once per TTL ---
while IFS=$'\t' read -r tag port; do
at=$(jq -r --arg t "$tag" '.exits[$t].at // 0' "$state")
[ $(( now - at )) -ge "$ttl" ] || continue
info=$(curl -sS --proxy "http://127.0.0.1:$port" --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
ip=$(jq -r '.ip // empty' <<<"$info" 2>/dev/null || true)
asn=$(jq -r '(.org // "") | split(" ")[0]' <<<"$info" 2>/dev/null || true)
[ -n "$ip" ] || continue
update --arg t "$tag" --arg ip "$ip" --arg asn "$asn" --argjson now "$now" \
'.exits[$t] += {ip: $ip, asn: $asn, at: $now}'
done < <(jq -r '.[] | "\(.tag)\t\(.port)"' "$index")
# --- 2b. strikes older than a TTL stop counting against an exit ---
strike '[]' "" ""
# See autoproxy-rounds.jq: one exit per AS, then the rest, bad exits last.
rounds=$(jq -c --slurpfile s "$state" -f ${jqFile ./autoproxy-rounds.jq} "$index")
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=$(probe_json --exits "$round1" "$1")
verdict=$(jq -r '.verdict // "error"' <<<"$out")
if { [ "$verdict" = both-fail ] || [ "$verdict" = unreachable ]; } && [ -n "$round2" ]; then
first=$out
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
printf '%s' "$out"
}
# Route changes take effect immediately, not at the end of the run.
publish() { ${render} "$index" "$state"; }
requeue=()
if [ "$mode" = full ]; then
# --- 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=$(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'
elif [ "$verdict" = ok ]; then
echo "recheck $dom: reachable directly now, dropping $exit"
update --arg d "$dom" 'del(.domains[$d])'
record "$dom" "$host" "$out"
publish
else
echo "recheck $dom: $exit no longer works ($verdict), walking again"
update --arg d "$dom" 'del(.domains[$d])'
publish
requeue+=("$dom"$'\t'"$host")
fi
done < <(jq -r --argjson now "$now" --argjson every "$ttl" '
.domains | to_entries[]
| select(.value.verdict == "destination" and ($now - .value.at) >= $every)
| "\(.key)\t\(.value.host)\t\(.value.exit)"' "$state")
# --- 4. what clients dialled since the last run, counted per host ---
# Hit counts accumulate in a backlog that survives between runs.
last=$(jq -r '.lastRun // 0' "$state")
if [ "$last" -gt 0 ]; then since="@$last"; else since="-${apCfg.interval}"; fi
dialled=$(
${journalctl} -u proxy-suite-inbounds --since "$since" --no-pager -o cat 2>/dev/null |
sed -n 's/.* accepted tcp:\([a-zA-Z0-9._-]*\):[0-9]*.*/\1/p' |
grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' |
${lib.optionalString (excludePattern != "") "grep -vE '(^|\\.)(${excludePattern})$' |"}
to_reg || true
)
counts=$(
printf '%s\n' "$dialled" |
awk -F'\t' 'NF == 2 { n[$2]++; d[$2] = $1 } END { for (h in n) print h "\t" d[h] "\t" n[h] }' |
jq -R -s -c 'split("\n") | map(select(length > 0) | split("\t")
| {key: .[0], value: {domain: .[1], hits: (.[2] | tonumber)}}) | from_entries'
)
# Skipped: hosts of an already routed domain, hosts judged within the TTL.
# Dropped: entries older than the TTL, and those a route now covers; host
# verdicts past the TTL, which would only be probed again anyway.
update --argjson c "$counts" --argjson now "$now" --argjson ttl "$ttl" '
. as $s
| .lastRun = $now
| .hosts |= with_entries(select(.value.at + $ttl > $now))
| .backlog = (reduce ($c | to_entries[]) as $e (($s.backlog // {});
if ($s.domains[$e.value.domain].exit != null)
or ((($s.hosts[$e.key].at // 0) + $ttl) > $now)
then .
else .[$e.key] = {
domain: $e.value.domain,
hits: ((.[$e.key].hits // 0) + $e.value.hits),
first: (.[$e.key].first // $now)
} end))
| .backlog |= with_entries(select(.value.first + $ttl > $now
and $s.domains[.value.domain].exit == null))'
# --- 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)})' ||
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 \
-f ${jqFile ./autoproxy-slow-judge.jq}
# Each crawling destination gets the next exit, in probe order, that
# answers it as well as direct does (`probe --via`). None left: it
# stays direct for a TTL.
while IFS=$'\t' read -r dom host tried; do
was=''${tried##*,}
# It crawled twice on the exit it was routed through.
[ -z "$was" ] || strike "$(jq -cn --arg t "$was" '[$t]')" "$dom" slow
via=""
while IFS= read -r tag; do
[[ ",$tried," != *",$tag,"* ]] || continue
tried="''${tried:+$tried,}$tag"
out=$(probe_json --via "$tag" "$host")
verdict=$(jq -r '.verdict // ""' <<<"$out" 2>/dev/null || true)
if [ "$verdict" = ok ]; then
via=$tag
break
fi
# Refused what direct gets, by a block page or by the origin.
if [ "$verdict" = blocked ]; then
why=$(jq -r --arg t "$tag" '[.exits[] | select(.tag == $t)] as $r
| [$r[] | select(.judgement == "wall") | "wall:" + .block][0]
// (if any($r[]; .judgement == "blocked") then "refused" else "" end)' <<<"$out" 2>/dev/null || true)
[ -z "$why" ] || strike "$(jq -cn --arg t "$tag" '[$t]')" "$dom" "$why"
fi
done < <(jq -r '.ordered[]' <<<"$rounds")
if [ -n "$via" ]; then
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, routed via $via"
update --arg d "$dom" --arg h "$host" --arg e "$via" --arg tried "$tried" --argjson now "$now" '
.domains[$d] = {verdict: "slow", exit: $e, host: $h, at: $now, tried: ($tried | split(","))}
| del(.slowWant[$d])'
else
echo "slow $dom: crawls ''${was:+via $was}''${was:-directly}, and no other exit reaches it; left direct"
update --arg d "$dom" --argjson until $(( now + ttl )) '.slowSkip[$d] = $until | del(.slowWant[$d])'
fi
done < <(jq -r '(.slowWant // {}) | to_entries[]
| "\(.key)\t\(.value.host)\t\(.value.tried | join(","))"' "$state")
[ "$(jq -c '.domains' "$state")" = "$before" ] || publish
fi
fi
# --- 5. probe: requests (uncapped), then broken routes, then the backlog ---
asked=()
if [ -s "$requests" ]; then
mv -f "$requests" "$requests.taking"
mapfile -t asked < <(grep -E '^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$' "$requests.taking" | to_reg || true)
rm -f "$requests.taking"
fi
backlog=()
if [ "$mode" = full ]; then
mapfile -t backlog < <(jq -r --argjson now "$now" --argjson ttl "$ttl" '
. as $s | (.backlog // {}) | to_entries
| map(select(($s.domains[.value.domain].exit == null)
and ((($s.hosts[.key].at // 0) + $ttl) <= $now)))
| sort_by(-.value.hits) | .[] | "\(.value.domain)\t\(.key)"' "$state")
fi
declare -A seen routed
probe_row() {
local dom=''${1%%$'\t'*} host=''${1#*$'\t'} out
{ [ -z "''${seen[$host]:-}" ] && [ -z "''${routed[$dom]:-}" ]; } || return 1
seen[$host]=1
out=$(walk "$host")
# A probe that failed to run is no verdict; the host is probed again.
if [ "$(jq -r '.verdict // "error"' <<<"$out")" = error ]; then
echo "probe $host -> error, not recorded"
return 0
fi
record "$dom" "$host" "$out"
if [ "$(jq -r '.verdict // ""' <<<"$out")" = destination ]; then
routed[$dom]=1
publish
fi
# A censor verdict names an exit that got through, but zapret owns it.
echo "probe $host -> $(jq -r '(.verdict // "error") + (if .verdict == "destination" then " via " + .exit
elif .exit then " (" + .exit + " reaches it; left to zapret)" else "" end)' <<<"$out")"
}
for row in "''${asked[@]}"; do probe_row "$row" || true; done
probed=0
for row in "''${requeue[@]}" "''${backlog[@]}"; do
[ "$probed" -lt ${toString apCfg.probesPerRun} ] || break
if probe_row "$row"; then probed=$(( probed + 1 )); fi
done
echo "probed ''${#asked[@]} requested and $probed queued host(s); $(jq '(.backlog // {}) | length' "$state") still waiting"
# sing-box reloads the rewritten rule-sets itself.
${render} "$index" "$state"
'';
);
# Group: `proxy-ctl proxy auto list|queue` reads state.json, `learn` queues requests.
# Set on every unit that declares the directory - systemd re-applies the ownership
+21
View File
@@ -0,0 +1,21 @@
# A script kept in its own file beside the Nix that runs it, with its @name@ placeholders
# filled from `vars`: replaceVars, but at eval time, so the text still goes to
# writeShellScript, runCommand and the like. Each value is spliced in as "${value}" would
# be, so a path lands in the store. Every name given must be a placeholder in the file and
# every placeholder must be given, so neither side can drift from the other unnoticed.
file: vars:
let
text = builtins.readFile file;
names = builtins.attrNames vars;
placeholders = builtins.concatMap (part: if builtins.isList part then part else [ ]) (
builtins.split "@([A-Za-z_][A-Za-z0-9_]*)@" text
);
unused = builtins.filter (name: !builtins.elem name placeholders) names;
unfilled = builtins.filter (name: !(vars ? ${name})) placeholders;
in
if unused != [ ] then
throw "${toString file}: no @${builtins.head unused}@ placeholder to fill"
else if unfilled != [ ] then
throw "${toString file}: @${builtins.head unfilled}@ is not given a value"
else
builtins.replaceStrings (map (name: "@${name}@") names) (map (name: "${vars.${name}}") names) text
@@ -0,0 +1,50 @@
set -uo pipefail
proxy=(--proxy socks5h://@proxyHost@:@proxyPort@)
# The listener's login as curl config on a pipe (-K): argv is readable by every local user.
proxy_login() {
[ "$1" = proxy ] || return 0
@proxyLogin@
}
failed=0
# A download replaces the file only once sing-box has read it back, so a bad one never
# reaches the backend; a failed one keeps what was there. Its domain rules go to the copy
# DNS rules read.
fetch() {
local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp
local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M)
[ "$detour" = proxy ] && args+=("${proxy[@]}")
tmp=$(@coreutils@/bin/mktemp "$path.XXXXXX") || { failed=1; return; }
dnsTmp=$(@coreutils@/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; }
if @curl@ "${args[@]}" -K <(proxy_login "$detour") --output "$tmp" "$url" && valid "$tmp" "$format" &&
domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then
chmod 0644 "$tmp" "$dnsTmp"
mv -f "$dnsTmp" "$dns"
mv -f "$tmp" "$path"
echo "rule set $name: updated"
else
rm -f "$tmp" "$dnsTmp"
echo "rule set $name: not updated from $url; keeping the one it has" >&2
failed=1
fi
}
valid() {
if [ "$2" = binary ]; then
@singBox@ rule-set decompile --output /dev/null "$1" 2>/dev/null
else
@singBox@ rule-set compile --output /dev/null "$1" 2>/dev/null
fi
}
domains() {
if [ "$2" = binary ]; then
@singBox@ rule-set decompile --output /dev/stdout "$1"
else
cat "$1"
fi | @jq@/bin/jq '.rules = [(.rules // [])[]
| select((.type // "default") == "default"
and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex")))
| del(.ip_cidr, .ip_is_private)]'
}
@fetchRuleSets@
exit "$failed"
+23 -63
View File
@@ -8,6 +8,7 @@
}:
let
fillTemplate = import ./lib/fill-template.nix;
inherit (derived) ruleSets localProxy;
inherit (derived.constants) ruleSetsDir unprivilegedServiceConfig serviceUser;
inherit (cfg.host) privileged;
@@ -35,74 +36,33 @@ let
${singBox} rule-set compile --output "$out" ${emptySource}
'';
fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" ''
set -uo pipefail
proxy=(--proxy socks5h://${localProxy.hostPart}:${toString cfg.proxy.listener.port})
# The listener's login as curl config on a pipe (-K): argv is readable by every local user.
proxy_login() {
[ "$1" = proxy ] || return 0
${lib.optionalString withProxyAuth ''
fetchScript = pkgs.writeShellScript "proxy-suite-rulesets" (
fillTemplate ./rulesets-fetch.template.sh {
proxyHost = localProxy.hostPart;
proxyPort = toString cfg.proxy.listener.port;
proxyLogin = lib.optionalString withProxyAuth ''
local login
login=${lib.escapeShellArg auth.username}:"$(< "$CREDENTIALS_DIRECTORY/proxy-password")"
login=''${login//\\/\\\\}
printf 'proxy-user = "%s"\n' "''${login//\"/\\\"}"
''}
'';
coreutils = pkgs.coreutils;
inherit curl singBox;
jq = pkgs.jq;
fetchRuleSets = lib.concatMapStrings (rs: ''
fetch ${
lib.escapeShellArgs [
rs.name
rs.url
rs.path
rs.dnsPath
rs.format
rs.detour
]
}
'') ruleSets;
}
failed=0
# A download replaces the file only once sing-box has read it back, so a bad one never
# reaches the backend; a failed one keeps what was there. Its domain rules go to the copy
# DNS rules read.
fetch() {
local name=$1 url=$2 path=$3 dns=$4 format=$5 detour=$6 tmp dnsTmp
local args=(--fail --silent --show-error --location --max-time 120 --max-filesize 64M)
[ "$detour" = proxy ] && args+=("''${proxy[@]}")
tmp=$(${pkgs.coreutils}/bin/mktemp "$path.XXXXXX") || { failed=1; return; }
dnsTmp=$(${pkgs.coreutils}/bin/mktemp "$dns.XXXXXX") || { rm -f "$tmp"; failed=1; return; }
if ${curl} "''${args[@]}" -K <(proxy_login "$detour") --output "$tmp" "$url" && valid "$tmp" "$format" &&
domains "$tmp" "$format" > "$dnsTmp" && valid "$dnsTmp" source; then
chmod 0644 "$tmp" "$dnsTmp"
mv -f "$dnsTmp" "$dns"
mv -f "$tmp" "$path"
echo "rule set $name: updated"
else
rm -f "$tmp" "$dnsTmp"
echo "rule set $name: not updated from $url; keeping the one it has" >&2
failed=1
fi
}
valid() {
if [ "$2" = binary ]; then
${singBox} rule-set decompile --output /dev/null "$1" 2>/dev/null
else
${singBox} rule-set compile --output /dev/null "$1" 2>/dev/null
fi
}
domains() {
if [ "$2" = binary ]; then
${singBox} rule-set decompile --output /dev/stdout "$1"
else
cat "$1"
fi | ${pkgs.jq}/bin/jq '.rules = [(.rules // [])[]
| select((.type // "default") == "default"
and (has("domain") or has("domain_suffix") or has("domain_keyword") or has("domain_regex")))
| del(.ip_cidr, .ip_is_private)]'
}
${lib.concatMapStrings (rs: ''
fetch ${
lib.escapeShellArgs [
rs.name
rs.url
rs.path
rs.dnsPath
rs.format
rs.detour
]
}
'') ruleSets}
exit "$failed"
'';
);
in
{
services.proxy-suite.internal = {
@@ -0,0 +1,47 @@
var verb = action.lookup("verb");
if (typeof unit !== "string" || @verbs@.indexOf(verb) === -1) {
return null;
}
var known = @units@.indexOf(unit) !== -1;
var templates = @templates@;
for (var i = 0; !known && i < templates.length; i++) {
var template = templates[i];
if (unit.indexOf(template) !== 0) {
continue;
}
var instance = unit.slice(template.length).replace(/\.service$/, "");
if (!/^[A-Za-z0-9:_.\\-]+$/.test(instance) || unit !== template + instance + ".service") {
continue;
}
// Per-app marking follows one user's apps: only that user's own instance.
if (/-user@$/.test(template)) {
try {
var uid = polkit.spawn(["@coreutils@/bin/id", "-u", "--", subject.user]).trim();
} catch (error) {
return null;
}
if (instance !== uid) {
return null;
}
}
known = true;
}
if (!known) {
return null;
}
var scopeByUnitPrefix = @scopeByUnitPrefix@;
var scope = "services";
for (var prefix in scopeByUnitPrefix) {
if (unit.indexOf(prefix) === 0) {
scope = scopeByUnitPrefix[prefix];
break;
}
}
// Any of the subject's groups that holds the scope.
var groupScopes = @groupScopes@;
for (var group in groupScopes) {
if (groupScopes[group].indexOf(scope) !== -1 && subject.isInGroup(group)) {
return polkit.Result.YES;
}
}
+9 -49
View File
@@ -15,6 +15,7 @@
}:
let
fillTemplate = import ../lib/fill-template.nix;
# Units a narrower scope starts; every other proxy-suite unit is "services".
scopeByUnitPrefix = {
"proxy-suite-per-app-" = "perApp";
@@ -48,55 +49,14 @@ let
];
in
{
userControlPolkitRules = ''
var verb = action.lookup("verb");
if (typeof unit !== "string" || ${builtins.toJSON verbs}.indexOf(verb) === -1) {
return null;
}
var known = ${builtins.toJSON units}.indexOf(unit) !== -1;
var templates = ${builtins.toJSON templates};
for (var i = 0; !known && i < templates.length; i++) {
var template = templates[i];
if (unit.indexOf(template) !== 0) {
continue;
}
var instance = unit.slice(template.length).replace(/\.service$/, "");
if (!/^[A-Za-z0-9:_.\\-]+$/.test(instance) || unit !== template + instance + ".service") {
continue;
}
// Per-app marking follows one user's apps: only that user's own instance.
if (/-user@$/.test(template)) {
try {
var uid = polkit.spawn(["${pkgs.coreutils}/bin/id", "-u", "--", subject.user]).trim();
} catch (error) {
return null;
}
if (instance !== uid) {
return null;
}
}
known = true;
}
if (!known) {
return null;
}
var scopeByUnitPrefix = ${builtins.toJSON scopeByUnitPrefix};
var scope = "services";
for (var prefix in scopeByUnitPrefix) {
if (unit.indexOf(prefix) === 0) {
scope = scopeByUnitPrefix[prefix];
break;
}
}
// Any of the subject's groups that holds the scope.
var groupScopes = ${builtins.toJSON userControlGroupScopes};
for (var group in groupScopes) {
if (groupScopes[group].indexOf(scope) !== -1 && subject.isInGroup(group)) {
return polkit.Result.YES;
}
}
'';
userControlPolkitRules = fillTemplate ./polkit-rules.template.js {
verbs = builtins.toJSON verbs;
units = builtins.toJSON units;
templates = builtins.toJSON templates;
coreutils = pkgs.coreutils;
scopeByUnitPrefix = builtins.toJSON scopeByUnitPrefix;
groupScopes = builtins.toJSON userControlGroupScopes;
};
# Whether the subject is in any userControl group at all: the rule's first test.
userControlPolkitMember = lib.concatMapStringsSep " || " (
group: "subject.isInGroup(${builtins.toJSON group})"
@@ -0,0 +1,15 @@
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
| [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
@@ -0,0 +1,29 @@
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then
.dns.rules = .dns.rules[:@userDnsRuleCount@]
+ [.dns.rules[@userDnsRuleCount@:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])]
else . end
else . end
# autoProxy rules, after the route-mode replace so no mode drops them: pins first
# (they only match their own listener), learned rules last before final, so
# explicit rules win. All [] when off.
| .inbounds += $probe_inbounds
# The loopback probe and test listeners reach every exit: with listener.auth, the
# same login, or any local user would get past it through them.
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users)
= [{username:$user,password:$password}]
else . end
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
@@ -0,0 +1,79 @@
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
# "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit.
if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "@selectionMode@" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
# Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy.
def xray_server_names:
[.outbounds[].settings
| (.vnext[]?.address, .servers[]?.address, .address?)
| strings | select(test("^[0-9.]+$|:|^localhost$") | not)]
| unique;
# A copy of "local" answering only for them: routed direct by its tag, so looking up a
# proxy server never waits on that proxy.
def xray_pin_server_names:
xray_server_names as $names
| if $names == [] then .
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
end;
.outbounds = ($obs[0] + .outbounds)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| .dns.servers = xray_dns_server_order($dns_final)
| xray_pin_server_names
| if $xray_tun_dns_runtime then
# Without a domainStrategy a dial resolves through the system resolver, whose upstream
# queries the TUN answers with fake IPs and TProxy sends through the proxy being
# dialed. XRay's own DNS client skips fakedns.
.outbounds |= map(
if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then .
else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end)
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
# The balancer's prefix would take in proxy.selectionExclude and disabled outbounds
# too: name the rest instead. Disabling is a runtime decision, so always.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| if $ARGS.named.xray_selectable == null then . else
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
@@ -7,138 +7,19 @@
userDnsRules ? [ ],
}:
let
fillTemplate = import ../../lib/fill-template.nix;
in
if pureXrayEnabled then
''
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
# "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit.
if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
# Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy.
def xray_server_names:
[.outbounds[].settings
| (.vnext[]?.address, .servers[]?.address, .address?)
| strings | select(test("^[0-9.]+$|:|^localhost$") | not)]
| unique;
# A copy of "local" answering only for them: routed direct by its tag, so looking up a
# proxy server never waits on that proxy.
def xray_pin_server_names:
xray_server_names as $names
| if $names == [] then .
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
end;
.outbounds = ($obs[0] + .outbounds)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| .dns.servers = xray_dns_server_order($dns_final)
| xray_pin_server_names
| if $xray_tun_dns_runtime then
# Without a domainStrategy a dial resolves through the system resolver, whose upstream
# queries the TUN answers with fake IPs and TProxy sends through the proxy being
# dialed. XRay's own DNS client skips fakedns.
.outbounds |= map(
if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then .
else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end)
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
# The balancer's prefix would take in proxy.selectionExclude and disabled outbounds
# too: name the rest instead. Disabling is a runtime decision, so always.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| if $ARGS.named.xray_selectable == null then . else
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
(fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; })
else
''
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then
.dns.rules = .dns.rules[:${toString (builtins.length userDnsRules)}]
+ [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])]
else . end
else . end
# autoProxy rules, after the route-mode replace so no mode drops them: pins first
# (they only match their own listener), learned rules last before final, so
# explicit rules win. All [] when off.
| .inbounds += $probe_inbounds
# The loopback probe and test listeners reach every exit: with listener.auth, the
# same login, or any local user would get past it through them.
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users)
= [{username:$user,password:$password}]
else . end
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
''
+ lib.optionalString proxyInboundsGuardPrivate ''
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
| [{inbound: ["mixed-in"], action: "resolve"${
lib.optionalString (
(fillTemplate ./backend-filter-sing-box.template.jq {
userDnsRuleCount = toString (builtins.length userDnsRules);
})
+ lib.optionalString proxyInboundsGuardPrivate (
fillTemplate ./backend-filter-private-guard.template.jq {
resolveStrategy = lib.optionalString (
proxyInboundsGuardStrategy != null
) ", strategy: \"${proxyInboundsGuardStrategy}\""
}},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
''
) ", strategy: \"${proxyInboundsGuardStrategy}\"";
}
)
@@ -1,6 +1,7 @@
{ ctx }:
let
fillTemplate = import ../../lib/fill-template.nix;
inherit (ctx)
lib
jq
@@ -11,107 +12,17 @@ in
routingMark: xraySidecarPort: xrayDnsBridgePort:
lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]'
XRAY_CLIENTS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_PORT=${toString xraySidecarPort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
# Client ids: this run's random prefix plus a counter, so every sidecar outbound has its
# own and no other local user can guess one.
XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid)
XRAY_SIDECAR_NEXT_ID=0
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
lib.optionalString hybridEnabled (
fillTemplate ./hybrid-runtime-helpers.template.sh {
sidecarPort = toString xraySidecarPort;
dnsBridgePort = toString xrayDnsBridgePort;
inherit jq;
sidecarMark = if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark;
setSidecarMark = lib.optionalString (
xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark";
hopRoutingMark = lib.optionalString (
routingMark != null
) " + {routing_mark: ${toString routingMark}}";
}
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
# client on the sidecar's one loopback VLESS inbound, routed to it by its email, and
# stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream
# (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by.
_proxy_suite_add_xray_sidecar_obs() {
local batch
batch=$(${jq} -c \
--argjson next "$XRAY_SIDECAR_NEXT_ID" \
--rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \
--argjson port "$XRAY_SIDECAR_PORT" \
--argjson mark ${
if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark
} '
def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add;
to_entries | map(
($secret[:24] + ($next + .key | hex12)) as $id
| .value.tag as $tag
| {outbound: (.value
${lib.optionalString (
xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark"}
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
client: {id: $id, email: $tag},
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id,
packet_encoding: "xudp"}${
lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}"
})})
| {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)}
' <<< "$1")
XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(${jq} '.outbounds | length' <<< "$batch")))
# Through a file, not --argjson: a big subscription's batch outgrows the kernel's
# 128 KiB limit on one argument.
XRAY_OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
XRAY_CLIENTS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON")
XRAY_ROUTE_RULES_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON")
OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON")
}
# $1 one XRay outbound, $2 its tag.
_proxy_suite_add_xray_sidecar_ob() {
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c --arg tag "$2" '[.tag = $tag]' <<< "$1")"
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson port "$XRAY_SIDECAR_PORT" \
--slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \
--slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \
--slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \
'
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: [
{
tag: "sidecar-in",
listen: "127.0.0.1",
port: $port,
protocol: "vless",
settings: {clients: $clients[0], decryption: "none"}
}
],
outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
''
)
@@ -0,0 +1,96 @@
XRAY_OUTBOUNDS_JSON='[]'
XRAY_CLIENTS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_PORT=@sidecarPort@
XRAY_SIDECAR_DNS_PORT=@dnsBridgePort@
# Client ids: this run's random prefix plus a counter, so every sidecar outbound has its
# own and no other local user can guess one.
XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid)
XRAY_SIDECAR_NEXT_ID=0
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(@jq@ --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
}
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
# client on the sidecar's one loopback VLESS inbound, routed to it by its email, and
# stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream
# (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by.
_proxy_suite_add_xray_sidecar_obs() {
local batch
batch=$(@jq@ -c \
--argjson next "$XRAY_SIDECAR_NEXT_ID" \
--rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \
--argjson port "$XRAY_SIDECAR_PORT" \
--argjson mark @sidecarMark@ '
def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add;
to_entries | map(
($secret[:24] + ($next + .key | hex12)) as $id
| .value.tag as $tag
| {outbound: (.value
@setSidecarMark@
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
client: {id: $id, email: $tag},
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id,
packet_encoding: "xudp"}@hopRoutingMark@)})
| {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)}
' <<< "$1")
XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(@jq@ '.outbounds | length' <<< "$batch")))
# Through a file, not --argjson: a big subscription's batch outgrows the kernel's
# 128 KiB limit on one argument.
XRAY_OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
XRAY_CLIENTS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON")
XRAY_ROUTE_RULES_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON")
OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON")
}
# $1 one XRay outbound, $2 its tag.
_proxy_suite_add_xray_sidecar_ob() {
_proxy_suite_add_xray_sidecar_obs "$(@jq@ -c --arg tag "$2" '[.tag = $tag]' <<< "$1")"
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
@jq@ -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson port "$XRAY_SIDECAR_PORT" \
--slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \
--slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \
--slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \
'
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: [
{
tag: "sidecar-in",
listen: "127.0.0.1",
port: $port,
protocol: "vless",
settings: {clients: $clients[0], decryption: "none"}
}
],
outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
@@ -0,0 +1,67 @@
@readSourceFunction@
SUB_CACHE_DIR="@cacheDir@"
RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@"
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1
}
# Set when a fetch leaves a cache different from before, so the update unit restarts the
# proxy only for a change: a restart cuts every connection through it.
SUB_CACHE_CHANGED=0
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
if [ -f "$target" ] && @diffutils@/bin/cmp -s "$tmp" "$target"; then
rm -f "$tmp"
else
mv "$tmp" "$target"
SUB_CACHE_CHANGED=1
fi
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \
@backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
return 0
fi
rm -f "$links.tmp"
return 1
fi
rm -f "$cache.tmp" "$links.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
_proxy_suite_runtime_subscriptions() {
local f tag
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="${f##*/}"
tag="${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
@@ -6,6 +6,7 @@
{ ctx }:
let
fillTemplate = import ../../lib/fill-template.nix;
inherit (ctx)
lib
pkgs
@@ -30,82 +31,21 @@ let
# Defined in every script that touches a cache: the start scripts and the
# update unit.
subscriptionCacheHelpersBlock = ''
${constants.readSourceFunction pkgs}
SUB_CACHE_DIR="${subscriptionCacheDir}"
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
)
} "$1" >/dev/null 2>&1
}
# Set when a fetch leaves a cache different from before, so the update unit restarts the
# proxy only for a change: a restart cuts every connection through it.
SUB_CACHE_CHANGED=0
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
if [ -f "$target" ] && ${pkgs.diffutils}/bin/cmp -s "$tmp" "$target"; then
rm -f "$tmp"
else
mv "$tmp" "$target"
SUB_CACHE_CHANGED=1
fi
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
return 0
fi
rm -f "$links.tmp"
return 1
fi
rm -f "$cache.tmp" "$links.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
_proxy_suite_runtime_subscriptions() {
local f tag
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
subscriptionCacheHelpersBlock = fillTemplate ./subscription-cache-helpers.template.sh {
readSourceFunction = constants.readSourceFunction pkgs;
cacheDir = subscriptionCacheDir;
inherit runtimeSubscriptionsDir jq;
validCacheFilter = lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
);
diffutils = pkgs.diffutils;
pythonPath = parserScriptsPythonPath;
inherit python3 fetchSubscriptionPy;
backendArg = subscriptionBackendArg;
};
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
# start script, so this one is emitted separately from the cache helpers.
@@ -0,0 +1,77 @@
set -euo pipefail
export PATH=@path@
cd @dir@
# Root works only here, which nobody else writes to now; the group's probe requests
# come through requests/. Anything left from when the group could write here goes:
# a symlink under a name below would have root write, or read, where it points.
for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts force; do
if [ -L "$f" ] || { [ -e "$f" ] && [ ! -O "$f" ]; }; then
rm -f -- "$f"
fi
done
touch asn.txt sni.txt
force=0
if [ -e requests/force ]; then
force=1
rm -f requests/force
fi
now=$(date +%s)
# Digits only: $(( )) would run what a[$(...)] in it names.
last=$(cat ts 2>/dev/null || true)
[[ $last =~ ^[0-9]+$ ]] || last=0
# The name map belongs to this line: probe again when its network changes, else
# once a day. No answer (offline, captive portal) is no reason to probe.
info=$(curl -sS --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
egress=$(jq -r '((.org // "") | split(" ")[0]) as $as
| if ($as | test("^AS[0-9]+$")) then $as else (.ip // "") end' <<<"$info" 2>/dev/null || true)
if [ -z "$egress" ]; then
echo "no answer about this line's address; not probing"
exit 0
fi
if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] &&
[ $((now - last)) -lt 86400 ]; then
exit 0
fi
echo "probing the line from $egress"
rc=0
z2k-detect tcp16 -targets @lists@/tcp16_targets.txt -parallel 50 -asn-out asn.new || rc=$?
case "$rc" in
1)
rc=0
z2k-detect tcp16 -targets @lists@/tcp16_targets.txt -scan @lists@/sni_wl_candidates.txt \
-per-asn -batch 5 -parallel 50 -sni-out sni.new || rc=$?
# 2: no network took any name; the list of cut-off networks still stands.
if [ "$rc" != 0 ] && [ "$rc" != 2 ]; then
rm -f asn.new sni.new
echo "name search failed ($rc); keeping the previous maps"
exit 0
fi
[ -e sni.new ] || : >sni.new
;;
0)
: >asn.new
: >sni.new
;;
*)
rm -f asn.new
echo "the probe did not run ($rc); keeping the previous maps"
exit 0
;;
esac
changed=0
{ cmp -s asn.new asn.txt && cmp -s sni.new sni.txt; } || changed=1
mv -f asn.new asn.txt
mv -f sni.new sni.txt
@proxyRules@ asn.txt sni.txt @lists@/tcp16_nets.txt >proxy.json.tmp
mv -f proxy.json.tmp proxy.json
printf '%s\n' "$egress" >egress
printf '%s\n' "$now" >ts
echo "cut-off networks: $(grep -c '^[0-9]' asn.txt || true), with a name: $(grep -c '^[0-9]' sni.txt || true)"
# nfqws2 reads the maps once; learned strategies survive the restart.
if [ "$changed" = 1 ]; then
systemctl try-restart @restartUnits@
fi
+9 -81
View File
@@ -12,6 +12,7 @@
}:
let
fillTemplate = import ../lib/fill-template.nix;
inherit (import ../derived.nix { inherit lib cfg; })
constants
userControlAllows
@@ -53,10 +54,9 @@ let
| {version: 1, rules: (if length > 0 then [{ip_cidr: .}] else [] end)}'
'';
probe = pkgs.writeShellScript "proxy-suite-zapret2" ''
set -euo pipefail
export PATH=${
lib.makeBinPath [
probe = pkgs.writeShellScript "proxy-suite-zapret2" (
fillTemplate ./cutoff-probe.template.sh {
path = lib.makeBinPath [
pkgs.coreutils
pkgs.curl
pkgs.diffutils
@@ -64,84 +64,12 @@ let
pkgs.jq
pkgs.systemd
z2kDetect
]
];
dir = lib.escapeShellArg dir;
inherit lists proxyRules;
restartUnits = lib.escapeShellArgs restartUnits;
}
cd ${lib.escapeShellArg dir}
# Root works only here, which nobody else writes to now; the group's probe requests
# come through requests/. Anything left from when the group could write here goes:
# a symlink under a name below would have root write, or read, where it points.
for f in asn.txt sni.txt asn.new sni.new proxy.json proxy.json.tmp egress ts force; do
if [ -L "$f" ] || { [ -e "$f" ] && [ ! -O "$f" ]; }; then
rm -f -- "$f"
fi
done
touch asn.txt sni.txt
force=0
if [ -e requests/force ]; then
force=1
rm -f requests/force
fi
now=$(date +%s)
# Digits only: $(( )) would run what a[$(...)] in it names.
last=$(cat ts 2>/dev/null || true)
[[ $last =~ ^[0-9]+$ ]] || last=0
# The name map belongs to this line: probe again when its network changes, else
# once a day. No answer (offline, captive portal) is no reason to probe.
info=$(curl -sS --max-time 10 https://ipinfo.io/json 2>/dev/null || true)
egress=$(jq -r '((.org // "") | split(" ")[0]) as $as
| if ($as | test("^AS[0-9]+$")) then $as else (.ip // "") end' <<<"$info" 2>/dev/null || true)
if [ -z "$egress" ]; then
echo "no answer about this line's address; not probing"
exit 0
fi
if [ "$force" = 0 ] && [ "$egress" = "$(cat egress 2>/dev/null || true)" ] &&
[ $((now - last)) -lt 86400 ]; then
exit 0
fi
echo "probing the line from $egress"
rc=0
z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -parallel 50 -asn-out asn.new || rc=$?
case "$rc" in
1)
rc=0
z2k-detect tcp16 -targets ${lists}/tcp16_targets.txt -scan ${lists}/sni_wl_candidates.txt \
-per-asn -batch 5 -parallel 50 -sni-out sni.new || rc=$?
# 2: no network took any name; the list of cut-off networks still stands.
if [ "$rc" != 0 ] && [ "$rc" != 2 ]; then
rm -f asn.new sni.new
echo "name search failed ($rc); keeping the previous maps"
exit 0
fi
[ -e sni.new ] || : >sni.new
;;
0)
: >asn.new
: >sni.new
;;
*)
rm -f asn.new
echo "the probe did not run ($rc); keeping the previous maps"
exit 0
;;
esac
changed=0
{ cmp -s asn.new asn.txt && cmp -s sni.new sni.txt; } || changed=1
mv -f asn.new asn.txt
mv -f sni.new sni.txt
${proxyRules} asn.txt sni.txt ${lists}/tcp16_nets.txt >proxy.json.tmp
mv -f proxy.json.tmp proxy.json
printf '%s\n' "$egress" >egress
printf '%s\n' "$now" >ts
echo "cut-off networks: $(grep -c '^[0-9]' asn.txt || true), with a name: $(grep -c '^[0-9]' sni.txt || true)"
# nfqws2 reads the maps once; learned strategies survive the restart.
if [ "$changed" = 1 ]; then
systemctl try-restart ${lib.escapeShellArgs restartUnits}
fi
'';
);
# The probe measures this line, so its traffic leaves directly: proxyMark keeps it
# out of TUN/TProxy like the backend's own, and the conntrack bit keeps zapret2 from
+4 -44
View File
@@ -8,6 +8,7 @@
}:
let
fillTemplate = import ../lib/fill-template.nix;
zapret2Cfg = cfg.zapret.zapret2;
autoCfg = zapret2Cfg.autoHostlist;
@@ -226,50 +227,9 @@ let
# templates apart; a profile that imports a template rotates over its strategies.
mkStrategies =
config:
pkgs.runCommand "proxy-suite-zapret2-strategies.json" { nativeBuildInputs = [ pkgs.gawk ]; } ''
. ${config}
set -f
printf '%s\n' $NFQWS2_OPT | awk '
function js(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); return "\"" s "\"" }
# Numeric from the start: an unset s indexes the first section as "", not 0.
BEGIN { s = 0 }
$0 == "--new" { s++; next }
/^--template=/ { tpl[substr($0, 12)] = s; istpl[s] = 1; next }
/^--import=/ { imp[s] = substr($0, 10); next }
/^--lua-desync=/ {
fn[s]++
spec = substr($0, 14)
if (spec ~ /^circular(:|$)/) {
circ[s] = fn[s]
if (match(spec, /:key=[^:]+/)) key[s] = substr(spec, RSTART + 5, RLENGTH - 5)
} else if (match(spec, /:strategy=[0-9]+/)) {
n = substr(spec, RSTART + 10, RLENGTH - 10)
spec = substr(spec, 1, RSTART - 1) substr(spec, RSTART + RLENGTH)
if (!((s, n) in strat)) order[s] = order[s] " " n
strat[s, n] = ((s, n) in strat ? strat[s, n] "," : "") js(spec)
}
}
END {
printf "{"
for (i = 0; i <= s; i++) {
if (istpl[i]) continue
p++
if (!(i in circ)) continue
k = (i in key) ? key[i] : "circular_" p "_" circ[i]
src = (i in imp && imp[i] in tpl) ? tpl[imp[i]] : ""
printf "%s%s:{", (out++ ? "," : ""), js(k)
m = 0
for (pass = 0; pass < 2; pass++) {
j = pass ? src : i
if (j == "") continue
c = split(order[j], ns, " ")
for (x = 1; x <= c; x++) printf "%s%s:[%s]", (m++ ? "," : ""), js(ns[x]), strat[j, ns[x]]
}
printf "}"
}
print "}"
}' >"$out"
'';
pkgs.runCommand "proxy-suite-zapret2-strategies.json" { nativeBuildInputs = [ pkgs.gawk ]; } (
fillTemplate ./strategies.template.sh { inherit config; }
);
# Keep desync off TUN interfaces (it breaks proxied handshakes), off per-app
# traffic, and off exempted subnets (e.g. NATed VMs whose traffic it would break).
+12 -95
View File
@@ -6,6 +6,7 @@
}:
let
fillTemplate = import ../lib/fill-template.nix;
inherit (lib)
concatStringsSep
filter
@@ -110,101 +111,17 @@ let
# under $out because the generated options point into it.
mkProfiles =
{ hostlistSuffix, excludeSuffix }:
pkgs.runCommand "proxy-suite-zapret2-z2k-profiles"
{
nativeBuildInputs = with pkgs; [
bash
coreutils
findutils
gawk
gnugrep
gnused
];
inherit hostlistSuffix excludeSuffix;
}
''
root=$out/root
mkdir -p "$root/lists" "$root/lua" conf
cp -r ${src}/files/lists/extra_strats "$root/"
chmod -R u+w "$root"
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
cp ${src}/files/lists/cf_extra_check_ips.txt "$root/lists/"
: >"$root/lists/discovered-domains.txt"
# Its cutoff name step is emitted only on lines its probe flagged; ours is
# a no-op until the cutoff probe writes maps, so emit it unconditionally.
mkdir -p "$root/state"
echo 1 >"$root/state/tcp16.flag"
# The generator wires its detectors only when their Lua files exist.
ln -s ${src}/files/lua/*.lua "$root/lua/"
export ZAPRET2_DIR="$root" CONFIG_DIR="$PWD/conf" LISTS_DIR="$root/lists"
(
cd ${src}
bash -c '
. lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1
print_info() { echo "$*" >&2; }
print_success() { echo "$*" >&2; }
print_warning() { echo "$*" >&2; }
print_error() { echo "$*" >&2; }
create_base_config >&2 &&
generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 &&
generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 &&
create_default_strategy_files >&2 &&
generate_nfqws2_opt_from_strategies
'
) >generated
sed -n '/^NFQWS2_OPT="/,/^"$/p' generated | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >raw
grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no profiles" >&2; exit 1; }
# Its learned-host list becomes ours, its whitelist gains our excludes, and
# the circular args it pins to the zapret2 docs are dropped so autoHostlist
# fills them in. A profile with --hostlist-auto wins every flow with a known
# name (nfq2/desync.c), so learning goes in a last profile of its own with no
# strategies, as z2k's own autohostlist does: on rkn_tcp it would take
# YouTube from yt_tcp/gv_tcp below it. rkn_tcp then leaves their hosts to
# them even once learned or added by hand.
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
-v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \
-v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" '
{
for (i = 1; i <= NF; i++) {
t = $i
if (t == "--new") {
prof++
} else if (t ~ /^--filter-tcp=/ && !(prof in ports)) {
ports[prof] = substr(t, 14)
}
if (t == disc) {
t = "<HOSTLIST_NOAUTO>" hsuf
if (!seen++) { t = t " " yt; learner = prof }
} else if (t == wl) {
t = t esuf
} else if (t ~ /^--lua-desync=circular:/) {
n = split(substr(t, 23), p, ":")
t = "--lua-desync=circular"
for (j = 1; j <= n; j++)
if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j]
}
printf "%s%s", (i > 1 ? " " : ""), t
}
}
END {
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
}' raw >body
awk -v z=${src} '
match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] }
match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] }
' ${src}/files/S99zapret2.new >blobs
grep -q -- '--blob=' blobs || { echo "z2k blob registrations not found" >&2; exit 1; }
mkdir -p "$out"
cp blobs "$out/blobs"
cp body "$out/profiles"
'';
pkgs.runCommand "proxy-suite-zapret2-z2k-profiles" {
nativeBuildInputs = with pkgs; [
bash
coreutils
findutils
gawk
gnugrep
gnused
];
inherit hostlistSuffix excludeSuffix;
} (fillTemplate ./z2k-profiles.template.sh { z2k = src; });
};
in
{
@@ -0,0 +1,42 @@
. @config@
set -f
printf '%s\n' $NFQWS2_OPT | awk '
function js(s) { gsub(/\\/, "\\\\", s); gsub(/"/, "\\\"", s); return "\"" s "\"" }
# Numeric from the start: an unset s indexes the first section as "", not 0.
BEGIN { s = 0 }
$0 == "--new" { s++; next }
/^--template=/ { tpl[substr($0, 12)] = s; istpl[s] = 1; next }
/^--import=/ { imp[s] = substr($0, 10); next }
/^--lua-desync=/ {
fn[s]++
spec = substr($0, 14)
if (spec ~ /^circular(:|$)/) {
circ[s] = fn[s]
if (match(spec, /:key=[^:]+/)) key[s] = substr(spec, RSTART + 5, RLENGTH - 5)
} else if (match(spec, /:strategy=[0-9]+/)) {
n = substr(spec, RSTART + 10, RLENGTH - 10)
spec = substr(spec, 1, RSTART - 1) substr(spec, RSTART + RLENGTH)
if (!((s, n) in strat)) order[s] = order[s] " " n
strat[s, n] = ((s, n) in strat ? strat[s, n] "," : "") js(spec)
}
}
END {
printf "{"
for (i = 0; i <= s; i++) {
if (istpl[i]) continue
p++
if (!(i in circ)) continue
k = (i in key) ? key[i] : "circular_" p "_" circ[i]
src = (i in imp && imp[i] in tpl) ? tpl[imp[i]] : ""
printf "%s%s:{", (out++ ? "," : ""), js(k)
m = 0
for (pass = 0; pass < 2; pass++) {
j = pass ? src : i
if (j == "") continue
c = split(order[j], ns, " ")
for (x = 1; x <= c; x++) printf "%s%s:[%s]", (m++ ? "," : ""), js(ns[x]), strat[j, ns[x]]
}
printf "}"
}
print "}"
}' >"$out"
@@ -0,0 +1,81 @@
root=$out/root
mkdir -p "$root/lists" "$root/lua" conf
cp -r @z2k@/files/lists/extra_strats "$root/"
chmod -R u+w "$root"
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
cp @z2k@/files/lists/cf_extra_check_ips.txt "$root/lists/"
: >"$root/lists/discovered-domains.txt"
# Its cutoff name step is emitted only on lines its probe flagged; ours is
# a no-op until the cutoff probe writes maps, so emit it unconditionally.
mkdir -p "$root/state"
echo 1 >"$root/state/tcp16.flag"
# The generator wires its detectors only when their Lua files exist.
ln -s @z2k@/files/lua/*.lua "$root/lua/"
export ZAPRET2_DIR="$root" CONFIG_DIR="$PWD/conf" LISTS_DIR="$root/lists"
(
cd @z2k@
bash -c '
. lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1
print_info() { echo "$*" >&2; }
print_success() { echo "$*" >&2; }
print_warning() { echo "$*" >&2; }
print_error() { echo "$*" >&2; }
create_base_config >&2 &&
generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 &&
generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 &&
create_default_strategy_files >&2 &&
generate_nfqws2_opt_from_strategies
'
) >generated
sed -n '/^NFQWS2_OPT="/,/^"$/p' generated | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >raw
grep -q -- '--lua-desync=circular' raw || { echo "z2k generator produced no profiles" >&2; exit 1; }
# Its learned-host list becomes ours, its whitelist gains our excludes, and
# the circular args it pins to the zapret2 docs are dropped so autoHostlist
# fills them in. A profile with --hostlist-auto wins every flow with a known
# name (nfq2/desync.c), so learning goes in a last profile of its own with no
# strategies, as z2k's own autohostlist does: on rkn_tcp it would take
# YouTube from yt_tcp/gv_tcp below it. rkn_tcp then leaves their hosts to
# them even once learned or added by hand.
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
-v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \
-v hsuf="$hostlistSuffix" -v esuf="$excludeSuffix" '
{
for (i = 1; i <= NF; i++) {
t = $i
if (t == "--new") {
prof++
} else if (t ~ /^--filter-tcp=/ && !(prof in ports)) {
ports[prof] = substr(t, 14)
}
if (t == disc) {
t = "<HOSTLIST_NOAUTO>" hsuf
if (!seen++) { t = t " " yt; learner = prof }
} else if (t == wl) {
t = t esuf
} else if (t ~ /^--lua-desync=circular:/) {
n = split(substr(t, 23), p, ":")
t = "--lua-desync=circular"
for (j = 1; j <= n; j++)
if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j]
}
printf "%s%s", (i > 1 ? " " : ""), t
}
}
END {
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
}' raw >body
awk -v z=@z2k@ '
match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] }
match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] }
' @z2k@/files/S99zapret2.new >blobs
grep -q -- '--blob=' blobs || { echo "z2k blob registrations not found" >&2; exit 1; }
mkdir -p "$out"
cp blobs "$out/blobs"
cp body "$out/profiles"