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

@@ -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"