fix: zapret2 improvements

This commit is contained in:
FUFSoB committed 2026-10-04 17:07:45 +05:00
1 parent 65082aad88
commit 552bfd53b1
30 files changed
+872 -49

No files matched your search

+6
View File
@@ -553,6 +553,9 @@ let
# The cut-off networks no whitelisted name fixes go through the proxy outbound.
zapretCutoffProxyFallback =
zapretCutoffEnabled && zapretCfg.zapret2.cutoff.proxyFallback && hasAvailableOutbounds;
# directSync for what zapret2 pins and learns at runtime: a rule-set the proxy reloads.
# The fixed lists go in with the routing rules (rules-zapret-direct.nix).
zapret2DirectSync = zapretEngine == "zapret2" && zapretGlobalEnabled && zapretCfg.directSync.enable;
userControlEnabled = userControlCfg.enable;
# Whether userControl.group, which owns proxy-suite's files, holds a scope; no scopes
# listed means all of them. The groups in userControl.groups get theirs through ACLs.
@@ -678,6 +681,8 @@ let
# Not under zapret2/, which the zapret scope's group writes to: root works here by
# fixed names (the group asks for probes in requests/).
zapret2CutoffDir = "${stateDir}/zapret2-cutoff";
# The same for the rule-set of zapret2's runtime hosts: what is in it skips the proxy.
zapret2DirectDir = "${stateDir}/zapret2-direct";
# Conntrack bit on the cutoff probe's own connections, which zapret2 leaves alone.
zapret2CutoffProbeCtMark = 33554432; # 0x2000000
@@ -878,6 +883,7 @@ in
zapretGlobalEnabled
zapretCutoffEnabled
zapretCutoffProxyFallback
zapret2DirectSync
userControlCfg
userControlEnabled
userControlAllows
+9 -3
View File
@@ -32,10 +32,14 @@ let
checked =
value: if envUnavailable != null then throw "proxy-suite helpers: ${envUnavailable}" else value;
urls = checked {
urls = checked rec {
http = "http://${credentials}${hostPort}";
# socks5h: names are resolved by the proxy, so they follow its routing.
socks = "socks5h://${credentials}${hostPort}";
socks5h = "socks5h://${credentials}${hostPort}";
# socks5: names are resolved locally. For programs that refuse socks5h, like
# Chromium and Electron apps (VS Code's http.proxy).
socks5 = "socks5://${credentials}${hostPort}";
socks = socks5h;
};
httpVars = [
@@ -63,7 +67,9 @@ let
or (throw "proxy-suite helpers: protocol must be \"http\", \"socks\" or \"all\", not \"${protocol}\"");
envFor =
protocol:
lib.genAttrs (varsOf protocol) (name: if builtins.elem name httpVars then urls.http else urls.socks)
lib.genAttrs (varsOf protocol) (
name: if builtins.elem name httpVars then urls.http else urls.socks5h
)
// noProxy;
# A copy of `package` whose programs (all of bin/, or the named ones) are replaced by
+5 -1
View File
@@ -31,7 +31,11 @@ in
# What zapret feeds back into the client routing table.
directSync = {
enable = bool true "Send zapret's domains direct in the proxy routing, so zapret handles them.";
enable = bool true ''
Send zapret's domains direct in the proxy routing, so zapret handles them. With zapret2,
also the sites it pins and learns at runtime, after your own rules and autoProxy's.
The all-proxy and all-bypass route modes leave them out, like every direct list.
'';
upstreamIps = bool false "Also send zapret's upstream IP lists direct.";
userIps = bool true "Also send `zapret-discord-youtube.ips` (minus `excludeIps`) direct.";
};
+43 -2
View File
@@ -4,6 +4,7 @@ let
inherit (lib) mkEnableOption mkOption types;
int = (import ./lib.nix { inherit lib; }).positiveInt;
fromSource = what: "`null`: use the ${what} from `strategySource`.";
portOrRange = types.either types.port (types.strMatching "[0-9]+(-[0-9]+)?");
in
{
options.services.proxy-suite.zapret.zapret2 = {
@@ -63,16 +64,56 @@ in
tcp = mkOption {
type = types.nullOr types.str;
default = null;
description = "TCP ports zapret2 handles. Must include every port a profile uses. ${fromSource "ports"}";
description = "TCP ports zapret2 handles. The ports the profiles filter on and `extraTcp` are always added. ${fromSource "ports"}";
example = "80,443";
};
udp = mkOption {
type = types.nullOr types.str;
default = null;
description = "UDP ports zapret2 handles. Must include every port a profile uses. ${fromSource "ports"}";
description = "UDP ports zapret2 handles. The ports the profiles filter on and `extraUdp` are always added. ${fromSource "ports"}";
example = "443";
};
extraTcp = mkOption {
type = types.listOf portOrRange;
default = [ ];
description = ''
More TCP ports, handled like the profiles' own: each profile that recognizes its traffic
(`--filter-l7`, e.g. TLS) gets them too, so TLS to a blocked site on one of these ports
gets the same strategies. A profile without `--filter-l7` keeps its ports.
'';
example = [
8444
"9000-9010"
];
};
extraUdp = mkOption {
type = types.listOf portOrRange;
default = [ ];
description = ''
More UDP ports, handled like the profiles' own: each profile that recognizes its traffic
(`--filter-l7`, e.g. STUN, Discord, QUIC) gets them too, so a game's or call app's STUN
on these ports gets the same strategies as Discord's.
'';
example = [ "27015-27030" ];
};
};
strategyLog = mkOption {
type = types.bool;
default = true;
description = ''
Log each counted failure and strategy switch to the journal, per site
(`proxy-ctl logs proxy-suite-zapret`). Without it nfqws2 logs them only with `debug`.
'';
};
debug = mkOption {
type = types.bool;
default = false;
description = "Log everything nfqws2 does to the journal, every packet included. Very verbose: for troubleshooting.";
};
ipv6 = mkOption {
+13 -2
View File
@@ -81,6 +81,12 @@ let
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
# zapret2's own pinned domains; what it learns at runtime is not synced.
zapret2 = zapretCfg.engine == "zapret2";
zapret2Domains = lib.optionals (syncZapretDirectDomains && zapret2) zapretCfg.zapret2.domains;
zapret2ExcludedDomains = lib.optionals (
syncZapretDirectDomains && zapret2
) zapretCfg.zapret2.excludeDomains;
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
@@ -103,12 +109,17 @@ let
subtractItems
(lib.unique (
map stripExactPrefix (
zapretDefaultDomains ++ zapretCfg.zapret-discord-youtube.domains ++ zapretCustomDomains
zapretDefaultDomains
++ zapretCfg.zapret-discord-youtube.domains
++ zapretCustomDomains
++ zapret2Domains
)
))
(
lib.unique (
map stripExactPrefix (zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains)
map stripExactPrefix (
zapretExcludedDomains ++ zapretCfg.zapret-discord-youtube.excludeDomains ++ zapret2ExcludedDomains
)
)
)
else
@@ -15,6 +15,7 @@ let
pureXrayEnabled
constants
zapretCutoffProxyFallback
zapret2DirectSync
jq
singBox
xray
@@ -185,6 +186,7 @@ let
enableAutoProxy ? false,
enableOutboundTest ? false,
enableZapretCutoff ? false,
enableZapretDirect ? false,
excludeServiceUserFromTun ? false,
}:
pkgs.writeShellScript "proxy-suite-core" ''
@@ -364,6 +366,25 @@ let
fi
''}
${lib.optionalString enableZapretDirect ''
# directSync for the hosts zapret2 pins and learns at runtime: direct, so zapret2
# sees them. Last, after explicit rules, autoProxy's exits and the cutoff's networks,
# which zapret2 cannot fix. all-proxy and all-bypass keep no direct lists.
case "$ROUTE_MODE" in
all-proxy | all-bypass) ;;
*)
ZAPRET_RULE_SET=${lib.escapeShellArg "${constants.zapret2DirectDir}/direct.json"}
# The sync unit owns the directory's mode: what is in it skips the proxy.
mkdir -p "$(dirname "$ZAPRET_RULE_SET")"
[ -s "$ZAPRET_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$ZAPRET_RULE_SET"
chmod 644 "$ZAPRET_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$ZAPRET_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-hosts", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-hosts"], outbound: "direct"}]' <<< "$AUTOPROXY_RULES_JSON")
;;
esac
''}
# umask: the file holds credentials until the chmod below; the process
# substitutions keep them out of the argv every local user can read.
(umask 077 && ${jq} \
@@ -498,6 +519,7 @@ let
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
enableZapretDirect = zapret2DirectSync && !pureXrayEnabled;
enableOutboundTest = true;
};
+8
View File
@@ -22,6 +22,7 @@ let
userControlAnyAllows
userControlExtraGroupsFor
zapretGlobalEnabled
zapret2DirectSync
;
inherit
(import ./zapret/common.nix {
@@ -131,8 +132,15 @@ let
;
};
directSync = import ./zapret2/direct-sync.nix { inherit lib pkgs cfg; };
in
{
services.proxy-suite.internal.services.proxy-suite-zapret2-direct =
lib.mkIf zapret2DirectSync directSync.service;
services.proxy-suite.internal.paths.proxy-suite-zapret2-direct =
lib.mkIf zapret2DirectSync directSync.path;
services.proxy-suite.internal.earlyPackages = [ runtime.package ];
services.proxy-suite.internal.services.proxy-suite-zapret2-cutoff =
@@ -0,0 +1,54 @@
# directSync for the hosts zapret2 pins (`proxy-ctl zapret auto add`) and learns at
# runtime: a rule-set the proxy sends direct, so zapret2 sees their traffic. Rebuilt
# whenever a host list changes; sing-box reloads it on the rename.
{
lib,
pkgs,
cfg,
}:
let
fillTemplate = import ../lib/fill-template.nix;
inherit (import ../derived.nix { inherit lib cfg; }) constants;
stateDir = constants.zapret2StateDir;
ruleSet = "${constants.zapret2DirectDir}/direct.json";
sync = pkgs.writeShellScript "proxy-suite-zapret2" (
fillTemplate ./direct-sync.template.sh {
path = lib.makeBinPath [
pkgs.coreutils
pkgs.diffutils
pkgs.jq
];
}
);
in
{
inherit sync ruleSet;
service = {
description = "proxy-suite - send the hosts zapret2 pins and learns direct in the proxy";
# Ahead of the proxy at boot, so it starts with the hosts already in.
before = [ "proxy-suite-socks.service" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
Type = "oneshot";
ExecStart = "${sync} ${lib.escapeShellArg stateDir} ${lib.escapeShellArg ruleSet}";
# Root's alone, like the cutoff's: what is in it skips the proxy, so the zapret
# scope's group, which edits the host lists, only reaches it through them.
StateDirectory = "proxy-suite/zapret2-direct";
StateDirectoryMode = "0755";
}
// constants.rootInSharedDirConfig;
};
path = {
description = "proxy-suite - watch zapret2's host lists for directSync";
wantedBy = [ "paths.target" ];
pathConfig.PathChanged = map (name: "${stateDir}/${name}") [
"zapret-hosts-user.txt"
"zapret-hosts-auto.txt"
"zapret-hosts-user-exclude.txt"
];
};
}
@@ -0,0 +1,36 @@
# $1: zapret2's state directory, $2: the rule-set to write. The hosts zapret2 pins and
# learns, less the excluded ones, as a sing-box source rule-set the proxy sends direct.
# Rewritten only when it changes: sing-box reloads it on every rename.
set -euo pipefail
export PATH=@path@
dir=$1
out=$2
lists() {
local f
for f in "$@"; do
[ -r "$f" ] && cat "$f"
done
true
}
lists "$dir/zapret-hosts-user.txt" "$dir/zapret-hosts-auto.txt" \
| jq -R -n -c --rawfile excluded <(lists "$dir/zapret-hosts-user-exclude.txt") '
# nfqws hostlists: one host per line, "#" comments, "^" for the name alone.
def hosts: map(gsub("^\\s+|\\s+$"; "") | ascii_downcase | ltrimstr("^"))
| map(select(. != "" and (startswith("#") | not)));
($excluded | split("\n") | hosts) as $excluded
| ([inputs] | hosts | unique) - $excluded
| map(select(test("^[0-9.]+$|:"))) as $ips
| {version: 1, rules: (
[(. - $ips) | select(length > 0) | {domain_suffix: .}]
+ [$ips | select(length > 0)
| {ip_cidr: map(. + (if test(":") then "/128" else "/32" end))}])}
' >"$out.tmp"
if cmp -s "$out.tmp" "$out"; then
rm "$out.tmp"
else
chmod 644 "$out.tmp"
mv "$out.tmp" "$out"
fi
@@ -0,0 +1,47 @@
-- z2k-state-persist.lua keeps a host's strategy in memory and writes it to state.tsv
-- only while the change is new: a write it skips is never retried, unless some other
-- host changes later. It skips one within 2 s of the last (for router flash) and one
-- while another writer holds the lock (the per-app instance, proxy-ctl). A restart
-- then loses the switch. Every change is written now, and a minute after a change
-- the whole state is written once more, whatever happened to the first write.
local api = z2k_state_persist
if not (api and api._set_interval and api._state and api.flush) then
error("proxy-suite: z2k-state-persist.lua no longer exports _set_interval, _state and flush")
end
api._set_interval(0)
local RECHECK = 60 -- seconds
local function digest()
local rows = {}
for askey, hosts in pairs(api._state()) do
for host, rec in pairs(hosts) do
rows[#rows + 1] = table.concat({
tostring(askey), tostring(host), tostring(rec.strategy), tostring(rec.mode),
tostring(rec.sni), tostring(rec.deleted),
}, "\t")
end
end
table.sort(rows)
return table.concat(rows, "\n")
end
-- From the start: a write that failed on the first packet is retried too.
local checked, seen = os.time(), digest()
-- Checked on traffic, not on a timer: a timer would keep nfqws2 --dry-run from exiting.
local rotate = circular
if type(rotate) == "function" then
function circular(ctx, desync)
local verdict = rotate(ctx, desync)
local now = os.time()
if now - checked >= RECHECK then
checked = now
local d = digest()
if d ~= seen then api.flush() end
seen = d
end
return verdict
end
end
+62
View File
@@ -0,0 +1,62 @@
# nfqws2's options in, with the extra ports (xtcp, xudp) joined to every profile that
# tells its traffic by protocol (--filter-l7). The ports to queue go to the file named
# by `ports`: the base lists (btcp, budp), the extras, and every port a profile filters
# on, since a profile port the queue lacks never sees a packet. Overlaps are merged:
# nftables refuses overlapping intervals in a set.
function mark(proto, list, n, p, i, r, lo, hi, port) {
n = split(list, p, ",")
for (i = 1; i <= n; i++) {
# ~negated, * and empty name nothing to queue.
if (p[i] !~ /^[0-9]+(-[0-9]+)?$/) continue
split(p[i], r, "-")
lo = r[1] + 0
hi = (p[i] ~ /-/) ? r[2] + 0 : lo
if (lo < 1) lo = 1
if (hi > 65535) hi = 65535
for (port = lo; port <= hi; port++) queued[proto, port] = 1
}
}
function ranges(proto, port, lo, out) {
out = ""
lo = 0
for (port = 1; port <= 65536; port++) {
if ((proto, port) in queued) {
if (!lo) lo = port
} else if (lo) {
out = out (out == "" ? "" : ",") (lo == port - 1 ? lo : lo "-" (port - 1))
lo = 0
}
}
return out
}
{
for (i = 1; i <= NF; i++) tok[++n] = $i
}
END {
prof = 0
for (i = 1; i <= n; i++) {
if (tok[i] == "--new") prof++
else if (tok[i] ~ /^--filter-l7=/) l7[prof] = 1
}
prof = 0
for (i = 1; i <= n; i++) {
t = tok[i]
if (t == "--new") {
prof++
} else if (t ~ /^--filter-tcp=/) {
if ((prof in l7) && xtcp != "") t = t "," xtcp
mark("tcp", substr(t, 14))
} else if (t ~ /^--filter-udp=/) {
if ((prof in l7) && xudp != "") t = t "," xudp
mark("udp", substr(t, 14))
}
printf "%s%s", (i > 1 ? " " : ""), t
}
mark("tcp", btcp "," xtcp)
mark("udp", budp "," xudp)
printf "NFQWS2_PORTS_TCP=%s\nNFQWS2_PORTS_UDP=%s\n", ranges("tcp"), ranges("udp") >ports
}
@@ -0,0 +1,60 @@
-- circular keys a site's strategy by the host's last nld labels (nld=2: example.com),
-- so one strategy serves a site and its subdomains. Under a public suffix of two
-- labels that lumps unrelated sites together: every *.co.uk shared one strategy, and
-- one that worked kept the failures of another from counting. nld now counts from the
-- public suffix (the list's ICANN section): foo.co.uk, not co.uk. A key the state layer
-- remembered under the old scheme is simply no longer used.
local exact, wild, except = {}, {}, {}
for rule in io.lines("@suffixes@") do
if rule:sub(1, 1) == "!" then
except[rule:sub(2)] = true
elseif rule:sub(1, 2) == "*." then
wild[rule:sub(3)] = true
else
exact[rule] = true
end
end
-- How many trailing labels the public suffix spans: the longest rule that matches, an
-- exception taking one label off its rule, and a single label when no rule does.
local function suffix_labels(labels)
local n = #labels
for i = 1, n do
local tail = table.concat(labels, ".", i, n)
if except[tail] then return n - i end
if exact[tail] or (i < n and wild[table.concat(labels, ".", i + 1, n)]) then return n - i + 1 end
end
return 1
end
local cache, cached = {}, 0
local function public_suffix_nld(host, nld)
local id = nld .. " " .. host
local key = cache[id]
if key then return key end
local labels = {}
for label in host:lower():gsub("%.$", ""):gmatch("[^.]+") do labels[#labels + 1] = label end
if #labels == 0 then return nil end
local first = math.max(1, #labels - (suffix_labels(labels) + nld - 1) + 1)
key = table.concat(labels, ".", first)
if cached >= 8192 then cache, cached = {}, 0 end
cache[id], cached = key, cached + 1
return key
end
local standard = standard_hostkey
if type(standard) ~= "function" then
error("proxy-suite: zapret-auto.lua no longer defines standard_hostkey")
end
function standard_hostkey(desync)
local nld = tonumber(desync.arg.nld)
local track = desync.track
if nld and nld > 0 and track and track.hostname and not track.hostname_is_ip then
local key = public_suffix_nld(track.hostname, nld)
if key then return key end
end
return standard(desync)
end
@@ -0,0 +1,29 @@
# The ICANN section of the public suffix list, one rule per line, every label in the
# xn-- form a TLS SNI carries ("рф" is "xn--p1ai" on the wire).
import sys
def ascii_label(label):
return label if label == "*" or label.isascii() else "xn--" + label.encode("punycode").decode()
def ascii_rule(rule):
bang = "!" if rule.startswith("!") else ""
return bang + ".".join(ascii_label(label) for label in rule.removeprefix("!").lower().split("."))
inside = False
rules = []
with open(sys.argv[1], encoding="utf-8") as f:
for line in f:
line = line.strip()
if line == "// ===BEGIN ICANN DOMAINS===":
inside = True
elif line == "// ===END ICANN DOMAINS===":
break
elif inside and line and not line.startswith("//"):
rules.append(ascii_rule(line.split()[0]))
if len(rules) < 1000:
sys.exit(f"only {len(rules)} ICANN rules: did the list's format change?")
print("\n".join(rules))
+36 -5
View File
@@ -109,18 +109,45 @@ let
end
'';
# The state layer wraps circular, so it loads after the source's Lua.
publicSuffixHostkey = pkgs.writeText "proxy-suite-zapret2-public-suffix-hostkey.lua" (
fillTemplate ./public-suffix-hostkey.lua {
suffixes =
pkgs.runCommand "proxy-suite-zapret2-public-suffixes"
{
nativeBuildInputs = [ pkgs.python3 ];
}
"python3 ${./public-suffixes.py} ${pkgs.publicsuffix-list}/share/publicsuffix/public_suffix_list.dat >$out";
}
);
# The state layer wraps circular, so it loads after the source's Lua; the writes it
# skips are retried after it, and the log wraps them all, to report the switch that stuck.
#
# --bind-fix: a fake leaves by the interface its connection does. Under policy routing
# (an app or a domain sent through a tunnel) it would otherwise take the default route,
# away from the connection it was meant to precede; without such routing it is a no-op.
optPrefix = lib.concatStringsSep " " (
map (file: "--lua-init=@${file}") (
lib.optional zapret2Cfg.debug "--debug=1"
++ [
"--bind-fix4"
"--bind-fix6"
]
++ source.daemonArgs
++ map (file: "--lua-init=@${file}") (
source.luaInit
++ [
publicSuffixHostkey
failStamp
"${zapret2Sources.z2k}/files/lua/z2k-state-persist.lua"
./persist-every.lua
]
++ lib.optional zapret2Cfg.strategyLog ./strategy-log.lua
)
++ lib.mapAttrsToList (name: file: "--blob=${name}:@${blobPath file}") zapret2Cfg.blobs
);
portList = lib.concatMapStringsSep "," toString;
# Detector args a circular instance leaves unset come from autoHostlist, so
# learning and rotation agree; each source keeps its own fails and time.
circularFill = lib.concatStringsSep " " (
@@ -169,8 +196,6 @@ let
++ lib.optional (!zapret2Cfg.ipv6) "DISABLE_IPV6=1"
++ [
"NFQWS2_ENABLE=1"
"NFQWS2_PORTS_TCP=${orSource zapret2Cfg.ports.tcp source.ports.tcp}"
"NFQWS2_PORTS_UDP=${orSource zapret2Cfg.ports.udp source.ports.udp}"
"NFQWS2_TCP_PKT_OUT=${toString packetWindow.tcpOut}"
"NFQWS2_TCP_PKT_IN=${toString packetWindow.tcpIn}"
"NFQWS2_UDP_PKT_OUT=${toString packetWindow.udpOut}"
@@ -194,6 +219,10 @@ let
{
nativeBuildInputs = [ pkgs.gawk ];
inherit circularFill optPrefix;
basePortsTcp = orSource zapret2Cfg.ports.tcp source.ports.tcp;
basePortsUdp = orSource zapret2Cfg.ports.udp source.ports.udp;
extraPortsTcp = portList zapret2Cfg.ports.extraTcp;
extraPortsUdp = portList zapret2Cfg.ports.extraUdp;
}
''
opt="$optPrefix $(cat ${blobsFile}) $(cat ${profilesFile})"
@@ -212,13 +241,15 @@ let
printf "%s%s", (i > 1 ? " " : ""), t
}
}')
opt=$(printf '%s\n' "$opt" | awk -v btcp="$basePortsTcp" -v budp="$basePortsUdp" \
-v xtcp="$extraPortsTcp" -v xudp="$extraPortsUdp" -v ports=ports -f ${./ports.awk})
case "$opt" in
*"'"*)
echo "nfqws2 options must not contain a single quote" >&2
exit 1
;;
esac
{ cat ${header}; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
{ cat ${header} ports; printf "NFQWS2_OPT='%s'\n" "$opt"; } >"$out"
'';
# {circular key: {strategy: [its desync instances]}}, for proxy-ctl to name the
+37 -8
View File
@@ -31,6 +31,14 @@ let
else
builtins.head (splitString stop (builtins.elemAt parts 1));
# The same for a fix to a pinned file: one that no longer applies must fail the build.
patch =
what: from: to: text:
if lib.hasInfix from text then
replaceStrings [ from ] [ to ] text
else
throw "proxy-suite: expected `${from}` in ${what}; did a flake input bump change it?";
keenetic =
let
src = sources.nfqws2-keenetic;
@@ -46,29 +54,46 @@ let
)
);
lists = "--hostlist=${src}/etc/nfqws2/lists/user.list --hostlist-exclude=${src}/etc/nfqws2/lists/exclude.list";
circular = "--lua-desync=circular:fails=2:time=300:retrans=3:nld=2";
tcpPayload = "--payload=tls_client_hello,mtproto_initial";
udpPayload = "--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown";
in
{
# Its init script's order. QUIC reads the learned list but never adds to it:
# browsers retry over TCP. The UDP profile carries no SNI, so no lists.
#
# circular counts failures on the packets Lua is handed, and nfqws2 hands it no
# incoming ones by default. As shipped it never saw a reset or a server's reply
# (only a silent drop rotated TCP), and on UDP, behind <n2, only the first packet
# of the udp_out it waits for: UDP never rotated. circular gets them now, as in
# zapret2's manual, and the strategies after it keep their own filters. The NFQUEUE
# window still bounds what reaches Lua.
profiles = [
# Its first UDP strategy's fake has no blob, which zapret2 rejects on every
# packet; nfqws1's default for unknown UDP was 64 zero bytes.
(replaceStrings
[ "--lua-desync=fake:repeats=6:strategy=1" ]
[
(lib.pipe (args "NFQWS_ARGS_UDP") [
(patch "NFQWS_ARGS_UDP" "--lua-desync=fake:repeats=6:strategy=1"
"--lua-desync=fake:blob=0x${lib.fixedWidthString 128 "0" ""}:repeats=6:strategy=1"
]
(args "NFQWS_ARGS_UDP")
)
)
(patch "NFQWS_ARGS_UDP" "--out-range=<n2 ${udpPayload} ${circular}"
"--out-range=a --in-range=a ${udpPayload} ${circular} --out-range=<n2 --in-range=x"
)
])
"${args "NFQWS_ARGS_QUIC"} <HOSTLIST_NOAUTO> ${lists}"
# No 16 KB cutoff name step: its fake ClientHello ahead of these strategies
# broke every host on a line where the strategies alone work.
"${args "NFQWS_ARGS"} <HOSTLIST> ${lists}"
# broke every host on a line where the strategies alone work. Its HTTP strategy
# has no strategy=N, so circular must not take http_req: it would skip it.
"${
patch "NFQWS_ARGS" "${tcpPayload} ${circular}"
"--in-range=-s5556 ${tcpPayload},tls_server_hello,empty,unknown ${circular} --in-range=x ${tcpPayload}"
(args "NFQWS_ARGS")
} <HOSTLIST> ${lists}"
];
blobArgs = map (replaceStrings [ "@/opt/etc/nfqws2/" ] [ "@${src}/etc/nfqws2/" ]) (
filter (hasPrefix "--blob=") (words (quoted "NFQWS_BASE_ARGS"))
);
luaInit = [ ];
daemonArgs = [ ];
ports = {
tcp = bare "TCP_PORTS";
udp = replaceStrings [ ":" ] [ "-" ] (bare "UDP_PORTS");
@@ -93,6 +118,10 @@ let
"z2k-range-rand"
"z2k-modern-core"
];
# As its S99zapret2 runs nfqws2: a connection without SNI (some TVs and apps, a
# SYN before the ClientHello its syndata strategies act on) takes the name last
# seen on that IP, so it still meets its site's profile and strategy.
daemonArgs = [ "--ipcache-hostname=1" ];
ports = {
tcp = ports "NFQWS2_PORTS_TCP";
udp = ports "NFQWS2_PORTS_UDP";
@@ -0,0 +1,57 @@
-- One journal line per counted failure and per strategy switch. nfqws2 logs them
-- only with --debug, among every packet's lines. Loaded after z2k-state-persist.lua,
-- so the switch it reports is the one that stuck, after its sticky-success revert.
local count, rotate = automate_failure_counter, circular
-- host record -> its strategy when the failure count was reached: circular, or
-- z2k's QUIC silence timer, switches it right after.
local pending = setmetatable({}, { __mode = "k" })
-- "<circular key> <host>": the record knows neither, autostate maps them to it.
local function name(hrec)
for askey, hosts in pairs(autostate or {}) do
for host, rec in pairs(hosts) do
if rec == hrec then return tostring(askey) .. " " .. tostring(host) end
end
end
return "?"
end
local function log(hrec, text)
io.stderr:write("zapret2: ", name(hrec), ": ", text, "\n")
end
local function of(hrec)
return tostring(hrec.nstrategy or 1) .. "/" .. tostring(hrec.ctstrategy or "?")
end
function automate_failure_counter(hrec, crec, fails, maxtime)
local duplicate = crec and crec.failure
local reached = count(hrec, crec, fails, maxtime)
if reached then
pending[hrec] = hrec.nstrategy or 1
elseif not duplicate and hrec.failure_counter then
log(hrec, "failure " .. tostring(hrec.failure_counter) .. "/" .. tostring(fails) .. " on strategy " .. of(hrec))
end
return reached
end
local function report()
for hrec, before in pairs(pending) do
pending[hrec] = nil
if (hrec.nstrategy or 1) ~= before then
log(hrec, "switched from strategy " .. tostring(before) .. " to " .. of(hrec))
else
log(hrec, "failed enough to switch, but stays on strategy " .. of(hrec) .. ": it worked moments ago, or that strategy is final")
end
end
end
if type(rotate) == "function" then
function circular(ctx, desync)
local verdict = rotate(ctx, desync)
-- Also what the QUIC timer switched since the last packet.
if next(pending) then report() end
return verdict
end
end