feat: allow setting zapret configs per default domains and default configs

This commit is contained in:
FUFSoB committed 2026-06-29 23:17:00 +05:00
1 parent 5b185114b6
commit 459a864478
8 files changed
+710 -59

No files matched your search

+207 -25
View File
@@ -162,7 +162,11 @@ Update module option docs there instead of editing this file by hand.
- [hostlistRules](#services-proxy-suite-zapret-hostlistrules)
- item
- [enableDirectSync](#services-proxy-suite-zapret-hostlistrules-enabledirectsync)
- [configName](#services-proxy-suite-zapret-hostlistrules-configname)
- [defaultDomains](#services-proxy-suite-zapret-hostlistrules-defaultdomains)
- [defaultIps](#services-proxy-suite-zapret-hostlistrules-defaultips)
- [domains](#services-proxy-suite-zapret-hostlistrules-domains)
- [ips](#services-proxy-suite-zapret-hostlistrules-ips)
- [name](#services-proxy-suite-zapret-hostlistrules-name)
- [nfqwsArgs](#services-proxy-suite-zapret-hostlistrules-nfqwsargs)
- [preset](#services-proxy-suite-zapret-hostlistrules-preset)
@@ -614,22 +618,29 @@ services.proxy-suite = {
gameFilter = "null";
hostlistRules = [
{
domains = [
"googlevideo.com"
"ggpht.com"
configName = "general(ALT9)";
defaultDomains = [
"youtube"
];
name = "googlevideo";
preset = "google";
name = "youtube-alt9";
}
{
configName = "general (ALT12)";
defaultDomains = [
"discord"
];
name = "discord-alt12";
}
{
configName = "general (SIMPLE FAKE)";
domains = [
"example.com"
"example.de"
"example.org"
];
name = "example";
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
ips = [
"203.0.113.0/24"
];
name = "custom-sites";
preset = "general";
}
];
@@ -5055,10 +5066,13 @@ string
Additional named zapret hostlists with per-list DPI mitigation rules\.
Each entry generates hostlists/list-\<name>\.txt and can clone a built-in
zapret family, add custom NFQWS rule fragments, or both\.
zapret family from the active config, clone it from another configName,
add custom NFQWS rule fragments, or combine these pieces\.
Each entry must define at least one domain and at least one of preset
or nfqwsArgs\.
defaultDomains provides built-in zapret-discord-youtube domain groups
such as “youtube” and “discord”; defaultIps provides upstream IP/CIDR
groups such as “all”\. configName is a higher-level
alternative to nfqwsArgs and cannot be used together with nfqwsArgs\.
@@ -5080,22 +5094,29 @@ list of (submodule)
```nix
[
{
domains = [
"googlevideo.com"
"ggpht.com"
configName = "general(ALT9)";
defaultDomains = [
"youtube"
];
name = "googlevideo";
preset = "google";
name = "youtube-alt9";
}
{
configName = "general (ALT12)";
defaultDomains = [
"discord"
];
name = "discord-alt12";
}
{
configName = "general (SIMPLE FAKE)";
domains = [
"example.com"
"example.de"
"example.org"
];
name = "example";
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
ips = [
"203.0.113.0/24"
];
name = "custom-sites";
preset = "general";
}
]
@@ -5132,13 +5153,133 @@ true
<a id="services-proxy-suite-zapret-hostlistrules-configname"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.configName
zapret config name to clone NFQWS rules from for this hostlist\.
Names use the same matching rules as services\.proxy-suite\.zapret\.configName\.
This is a higher-level alternative to nfqwsArgs and cannot be used
together with nfqwsArgs\.
*Type:*
null or string
*Default:*
```nix
null
```
*Example:*
```nix
"general(ALT9)"
```
*Declared by:*
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
<a id="services-proxy-suite-zapret-hostlistrules-defaultdomains"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.defaultDomains
Built-in domain groups copied from zapret-discord-youtube hostlists\.
These are expanded and combined with domains\.
“youtube” uses the upstream Google/YouTube list\. “discord” uses
Discord-related domains from the upstream general list\. “other” uses
the non-Discord domains from the upstream general list\.
When preset is unset, use one defaultDomains entry per rule so the
module can infer a single rule family\. Split groups into separate
rules when they need different strategies\.
*Type:*
list of (one of “youtube”, “discord”, “other”, “instagram”, “soundcloud”, “twitter”)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"youtube"
]
```
*Declared by:*
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
<a id="services-proxy-suite-zapret-hostlistrules-defaultips"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.defaultIps
Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets\.
“all” uses the upstream ipset-all\.txt list\. The upstream bundle does
not split this list by service, so site-specific defaults remain in
defaultDomains\.
*Type:*
list of value “all” (singular enum)
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"all"
]
```
*Declared by:*
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
<a id="services-proxy-suite-zapret-hostlistrules-domains"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.domains
Domains written into the generated custom zapret hostlist file\.
Must be non-empty for every hostlistRules entry\.
Can be combined with defaultDomains\.
@@ -5169,6 +5310,43 @@ list of string
<a id="services-proxy-suite-zapret-hostlistrules-ips"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.ips
IPs or CIDRs written into the generated custom zapret ipset file\.
Can be combined with defaultIps\.
*Type:*
list of string
*Default:*
```nix
[ ]
```
*Example:*
```nix
[
"203.0.113.0/24"
"2001:db8::/32"
]
```
*Declared by:*
- [modules/proxy-suite/options/zapret\.nix](https://github.com/FUFSoB/proxy-suite-flake/blob/main/modules/proxy-suite/options/zapret.nix)
<a id="services-proxy-suite-zapret-hostlistrules-name"></a>
## services\.proxy-suite\.zapret\.hostlistRules\.\*\.name
@@ -5203,7 +5381,7 @@ string matching the pattern ^\[a-z0-9]\[a-z0-9-]\*$
Additional NFQWS argument fragments for this hostlist\.
The module injects --hostlist=… and trailing --new automatically\.
Each hostlistRules entry must define preset, nfqwsArgs, or both\.
This cannot be used together with configName\.
@@ -5238,8 +5416,12 @@ list of string
Clone the active zapret config’s built-in NFQWS rule family for this
hostlist\. Can be combined with nfqwsArgs for additional custom rules\.
Clone this built-in NFQWS rule family for this hostlist\. When
configName is set, the family is cloned from that zapret config;
otherwise it is cloned from the active global zapret config\.
When unset and defaultDomains is non-empty, rule families are
inferred from defaultDomains\.
+80 -4
View File
@@ -277,6 +277,19 @@ let
"twitter"
];
zapretDefaultDomainType = types.enum [
"youtube"
"discord"
"other"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultIpType = types.enum [
"all"
];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
@@ -293,7 +306,7 @@ let
default = [ ];
description = ''
Domains written into the generated custom zapret hostlist file.
Must be non-empty for every hostlistRules entry.
Can be combined with defaultDomains.
'';
example = [
"example.com"
@@ -301,16 +314,77 @@ let
];
};
defaultDomains = mkOption {
type = types.listOf zapretDefaultDomainType;
default = [ ];
description = ''
Built-in domain groups copied from zapret-discord-youtube hostlists.
These are expanded and combined with domains.
"youtube" uses the upstream Google/YouTube list. "discord" uses
Discord-related domains from the upstream general list. "other" uses
the non-Discord domains from the upstream general list.
When preset is unset, use one defaultDomains entry per rule so the
module can infer a single rule family. Split groups into separate
rules when they need different strategies.
'';
example = [ "youtube" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs or CIDRs written into the generated custom zapret ipset file.
Can be combined with defaultIps.
'';
example = [
"203.0.113.0/24"
"2001:db8::/32"
];
};
defaultIps = mkOption {
type = types.listOf zapretDefaultIpType;
default = [ ];
description = ''
Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets.
"all" uses the upstream ipset-all.txt list. The upstream bundle does
not split this list by service, so site-specific defaults remain in
defaultDomains.
'';
example = [ "all" ];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = ''
Clone the active zapret config's built-in NFQWS rule family for this
hostlist. Can be combined with nfqwsArgs for additional custom rules.
Clone this built-in NFQWS rule family for this hostlist. When
configName is set, the family is cloned from that zapret config;
otherwise it is cloned from the active global zapret config.
When unset and defaultDomains is non-empty, rule families are
inferred from defaultDomains.
'';
example = "google";
};
configName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
zapret config name to clone NFQWS rules from for this hostlist.
Names use the same matching rules as services.proxy-suite.zapret.configName.
This is a higher-level alternative to nfqwsArgs and cannot be used
together with nfqwsArgs.
'';
example = "general(ALT9)";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
@@ -318,7 +392,7 @@ let
Additional NFQWS argument fragments for this hostlist.
The module injects --hostlist=... and trailing --new automatically.
Each hostlistRules entry must define preset, nfqwsArgs, or both.
This cannot be used together with configName.
'';
example = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
@@ -386,6 +460,8 @@ in
subscriptionType
outboundType
dnsUpstreamType
zapretDefaultDomainType
zapretDefaultIpType
zapretPresetType
zapretHostlistRuleType
perAppRoutingProfileType
+18 -14
View File
@@ -149,30 +149,34 @@ in
description = ''
Additional named zapret hostlists with per-list DPI mitigation rules.
Each entry generates hostlists/list-<name>.txt and can clone a built-in
zapret family, add custom NFQWS rule fragments, or both.
zapret family from the active config, clone it from another configName,
add custom NFQWS rule fragments, or combine these pieces.
Each entry must define at least one domain and at least one of preset
or nfqwsArgs.
defaultDomains provides built-in zapret-discord-youtube domain groups
such as "youtube" and "discord"; defaultIps provides upstream IP/CIDR
groups such as "all". configName is a higher-level
alternative to nfqwsArgs and cannot be used together with nfqwsArgs.
'';
example = [
{
name = "googlevideo";
domains = [
"googlevideo.com"
"ggpht.com"
];
preset = "google";
name = "youtube-alt9";
defaultDomains = [ "youtube" ];
configName = "general(ALT9)";
}
{
name = "example";
name = "discord-alt12";
defaultDomains = [ "discord" ];
configName = "general (ALT12)";
}
{
name = "custom-sites";
domains = [
"example.com"
"example.de"
"example.org"
];
ips = [ "203.0.113.0/24" ];
preset = "general";
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
configName = "general (SIMPLE FAKE)";
}
];
};
+21 -2
View File
@@ -12,6 +12,7 @@ let
proxyCfg = derived.proxyCfg;
zapretCfg = cfg.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
@@ -57,7 +58,25 @@ let
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule)
) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomDefaultIps =
if syncZapretDirectUpstreamIps then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps)
) zapretCfg.hostlistRules
)
else
[ ];
@@ -82,7 +101,7 @@ let
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (lib.unique (zapretDefaultIps ++ zapretUserIps)) zapretExcludedIps
subtractItems (lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)) zapretExcludedIps
else
[ ];
@@ -0,0 +1,93 @@
{
lib,
zapret,
}:
let
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
hasInfix = lib.strings.hasInfix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
upstreamHostlist = file: parseListFile "${zapretSrc}/hostlists/${file}";
generalDomains = upstreamHostlist "list-general.txt";
isDiscordDomain = domain: domain == "dis.gd" || hasInfix "discord" domain;
domainGroups = {
youtube = upstreamHostlist "list-google.txt";
discord = builtins.filter isDiscordDomain generalDomains;
other = builtins.filter (domain: !(isDiscordDomain domain)) generalDomains;
instagram = upstreamHostlist "list-instagram.txt";
soundcloud = upstreamHostlist "list-soundcloud.txt";
twitter = upstreamHostlist "list-twitter.txt";
};
groupPresets = {
youtube = "google";
discord = "general";
other = "general";
instagram = "instagram";
soundcloud = "soundcloud";
twitter = "twitter";
};
ipGroups = {
all = upstreamHostlist "ipset-all.txt";
};
expandDefaultDomains =
groups:
lib.unique (
lib.concatMap (group: domainGroups.${group}) groups
);
expandDefaultIps =
groups:
lib.unique (
lib.concatMap (group: ipGroups.${group}) groups
);
inferPresets =
groups:
lib.unique (map (group: groupPresets.${group}) groups);
effectiveRuleDomains =
rule:
lib.unique (expandDefaultDomains rule.defaultDomains ++ rule.domains);
effectiveRuleIps =
rule:
lib.unique (expandDefaultIps rule.defaultIps ++ rule.ips);
effectiveRulePresets =
rule:
if rule.preset != null then [ rule.preset ] else inferPresets rule.defaultDomains;
effectiveRuleIpsetFamilies =
rule:
lib.optional (effectiveRuleIps rule != [ ]) "all";
in
{
inherit
domainGroups
groupPresets
ipGroups
expandDefaultDomains
expandDefaultIps
inferPresets
effectiveRuleDomains
effectiveRuleIps
effectiveRulePresets
effectiveRuleIpsetFamilies
;
}
+60 -8
View File
@@ -14,6 +14,7 @@ let
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
iptables = "${pkgs.iptables}/bin/iptables";
@@ -37,6 +38,16 @@ let
};
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
effectiveHostlistRules = map (
rule:
rule
// {
domains = zapretDomainGroups.effectiveRuleDomains rule;
ips = zapretDomainGroups.effectiveRuleIps rule;
presets = zapretDomainGroups.effectiveRulePresets rule;
ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule;
}
) zapretCfg.hostlistRules;
baseZapretPackage =
let
@@ -58,10 +69,14 @@ let
entries = map (rule: {
inherit (rule)
name
preset
configName
nfqwsArgs
ipsets
presets
;
}) zapretCfg.hostlistRules;
hasDomains = rule.domains != [ ];
hasIps = rule.ips != [ ];
}) effectiveHostlistRules;
}
);
@@ -225,11 +240,17 @@ let
domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n"
);
ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n"
);
in
''
lib.optionalString (rule.domains != [ ]) ''
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
''
) zapretCfg.hostlistRules}
+ lib.optionalString (rule.ips != [ ]) ''
cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt"
''
) effectiveHostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
@@ -352,14 +373,45 @@ in
message = "proxy-suite: zapret.hostlistRules names must be unique";
}
{
assertion = builtins.all (rule: rule.domains != [ ]) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
assertion = builtins.all (
rule: zapretDomainGroups.effectiveRuleDomains rule != [ ] || zapretDomainGroups.effectiveRuleIps rule != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
}
{
assertion = builtins.all (
rule: rule.preset != null || rule.nfqwsArgs != [ ]
rule:
rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ] || rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, nfqwsArgs, or both";
message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule == [ ]
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.preset != null || builtins.length rule.defaultDomains <= 1
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
}
{
assertion = builtins.all (
rule: !(rule.configName != null && rule.nfqwsArgs != [ ])
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.configName == null || rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
}
];
+89
View File
@@ -1184,6 +1184,32 @@ let
nfqwsArgs = [ "--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6" ];
enableDirectSync = false;
}
{
name = "youtube-general";
defaultDomains = [ "youtube" ];
configName = "general";
}
{
name = "discord-alt12";
defaultDomains = [ "discord" ];
configName = "general (ALT12)";
}
{
name = "other";
defaultDomains = [ "other" ];
preset = "general";
}
{
name = "upstream-ips";
defaultIps = [ "all" ];
configName = "general";
enableDirectSync = false;
}
{
name = "explicit-ips";
ips = [ "203.0.113.0/24" ];
configName = "general";
}
];
};
}
@@ -1240,6 +1266,37 @@ let
}
];
conflictingZapretHostlistConfigAndArgs = mkBadFixture [
{
services.proxy-suite.zapret = {
enable = true;
hostlistRules = [
{
name = "conflict";
defaultDomains = [ "youtube" ];
configName = "general";
nfqwsArgs = [ "--filter-tcp=443 --dpi-desync=fake" ];
}
];
};
}
];
configNameZapretHostlistWithoutFamily = mkBadFixture [
{
services.proxy-suite.zapret = {
enable = true;
hostlistRules = [
{
name = "missing-family";
domains = [ "example.com" ];
configName = "general";
}
];
};
}
];
proxyDirectFixture = evalProxySuite [
baseModule
{
@@ -2548,6 +2605,14 @@ let
assert missingZapretHostlistAction.success == false;
true
)
(
assert conflictingZapretHostlistConfigAndArgs.success == false;
true
)
(
assert configNameZapretHostlistWithoutFamily.success == false;
true
)
(
assert tproxyWithFirewall.config.networking.firewall.enable;
true
@@ -2784,6 +2849,17 @@ let
assert !(hasDirectDomain zapretHostlistRules "x.example");
true
)
(
assert hasDirectDomain zapretHostlistRules "youtube.com";
assert hasDirectDomain zapretHostlistRules "discord.com";
assert hasDirectDomain zapretHostlistRules "cloudflare-ech.com";
true
)
(
assert hasDirectIP zapretHostlistRules "203.0.113.0/24";
assert !(hasDirectIP zapretHostlistRules "1.1.1.0/24");
true
)
(
assert hasRuleSet blockGeoRules "block" "geosite-category-ads-all";
true
@@ -3564,6 +3640,19 @@ in
grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-googlevideo.txt"' "${zapretHostlistBase}/config"
grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-example.txt"' "${zapretHostlistBase}/config"
grep -F -- '--filter-tcp=443 --dpi-desync=fake,multisplit --hostlist="${zapretHostlistBase}/hostlists/list-example.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude.txt" --hostlist-exclude="${zapretHostlistBase}/hostlists/list-exclude-user.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude.txt" --ipset-exclude="${zapretHostlistBase}/hostlists/ipset-exclude-user.txt" --new' "${zapretHostlistBase}/config"
grep -F 'youtube.com' "${zapretHostlistBase}/hostlists/list-youtube-general.txt"
grep -F 'googlevideo.com' "${zapretHostlistBase}/hostlists/list-youtube-general.txt"
grep -F 'discord.com' "${zapretHostlistBase}/hostlists/list-discord-alt12.txt"
grep -F 'discord.gg' "${zapretHostlistBase}/hostlists/list-discord-alt12.txt"
! grep -F 'cloudflare-ech.com' "${zapretHostlistBase}/hostlists/list-discord-alt12.txt"
grep -F 'cloudflare-ech.com' "${zapretHostlistBase}/hostlists/list-other.txt"
! grep -F 'discord.com' "${zapretHostlistBase}/hostlists/list-other.txt"
grep -F '1.1.1.0/24' "${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt"
grep -F '203.0.113.0/24' "${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt"
grep -F -- '--hostlist="${zapretHostlistBase}/hostlists/list-youtube-general.txt"' "${zapretHostlistBase}/config"
grep -F -- '--dpi-desync=multisplit --dpi-desync-split-seqovl=681' "${zapretHostlistBase}/config"
grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-upstream-ips.txt"' "${zapretHostlistBase}/config"
grep -F -- '--ipset="${zapretHostlistBase}/hostlists/ipset-explicit-ips.txt"' "${zapretHostlistBase}/config"
touch "$out"
'';
}
+142 -6
View File
@@ -18,6 +18,11 @@ def _hostlist_remove_pattern(stem: str) -> str:
return rf'\s+--hostlist=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
def _ipset_remove_pattern(stem: str) -> str:
escaped = re.escape(stem)
return rf'\s+--ipset=(?:"[^"]*/hostlists/{escaped}\.txt"|[^ ]*/hostlists/{escaped}\.txt)'
def _mk_family(match_stems: list[str], remove_stems: list[str]) -> dict:
return {
"match": [f"list-{s}.txt" for s in match_stems],
@@ -33,6 +38,13 @@ FAMILY_PATTERNS = {
"twitter": _mk_family(["twitter"], ["twitter"]),
}
IPSET_PATTERNS = {
"all": {
"match": ["ipset-all.txt"],
"remove": [_ipset_remove_pattern("ipset-all")],
},
}
def locate_nfqws_block(lines: list[str]) -> tuple[int, int]:
start = None
@@ -50,6 +62,38 @@ def locate_nfqws_block(lines: list[str]) -> tuple[int, int]:
raise ValueError("Could not find the end of the NFQWS_OPT block in zapret config")
def config_name_key(name: str) -> str:
return re.sub(r"\s+", "", name)
def resolve_config(configs_dir: Path, requested_config: str) -> Path:
selected_config = configs_dir / requested_config
if selected_config.is_file():
return selected_config
requested_key = config_name_key(requested_config)
matches = [
candidate
for candidate in configs_dir.iterdir()
if candidate.is_file() and config_name_key(candidate.name) == requested_key
]
if len(matches) > 1:
matched = ", ".join(str(match) for match in matches)
raise ValueError(
f"zapret config '{requested_config}' is ambiguous after whitespace normalization: {matched}"
)
if not matches:
raise ValueError(f"zapret config '{requested_config}' not found")
return matches[0]
def read_nfqws_lines(config_path: Path) -> list[str]:
lines = config_path.read_text(encoding="utf-8").splitlines()
start, end = locate_nfqws_block(lines)
return lines[start + 1 : end]
def strip_trailing_new(line: str) -> str:
return re.sub(r"(?:\s+--new)+\s*$", "", line.strip())
@@ -78,12 +122,33 @@ def _render_args(
rendered = re.sub(pattern, "", rendered)
else:
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered)
rendered = normalize_spaces(rendered)
rendered = f'{rendered} --hostlist="{hostlist_path}"'
rendered = add_standard_excludes(rendered, standard_excludes)
return f"{normalize_spaces(rendered)} --new"
def _render_ipset_args(
line: str,
ipset_path: str,
standard_excludes: list[str],
*,
ipset_family: str | None = None,
) -> str:
rendered = strip_trailing_new(line)
if ipset_family is not None:
for pattern in IPSET_PATTERNS[ipset_family]["remove"]:
rendered = re.sub(pattern, "", rendered)
else:
rendered = re.sub(r'\s+--ipset=(?:"[^"]+"|\S+)', "", rendered)
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\S+)', "", rendered)
rendered = normalize_spaces(rendered)
rendered = f'{rendered} --ipset="{ipset_path}"'
rendered = add_standard_excludes(rendered, standard_excludes)
return f"{normalize_spaces(rendered)} --new"
def render_preset_clone(
line: str,
family: str,
@@ -101,6 +166,23 @@ def render_custom_args(
return _render_args(fragment, hostlist_path, standard_excludes)
def render_ipset_clone(
line: str,
family: str,
ipset_path: str,
standard_excludes: list[str],
) -> str:
return _render_ipset_args(line, ipset_path, standard_excludes, ipset_family=family)
def render_custom_ipset_args(
fragment: str,
ipset_path: str,
standard_excludes: list[str],
) -> str:
return _render_ipset_args(fragment, ipset_path, standard_excludes)
def clone_family_lines(
existing_lines: list[str],
family: str,
@@ -122,6 +204,27 @@ def clone_family_lines(
]
def clone_ipset_lines(
existing_lines: list[str],
family: str,
ipset_path: str,
standard_excludes: list[str],
) -> list[str]:
matches = [
line
for line in existing_lines
if any(marker in line for marker in IPSET_PATTERNS[family]["match"])
]
if not matches:
raise ValueError(
f"IP set family '{family}' is not present in the selected zapret config"
)
return [
render_ipset_clone(line, family, ipset_path, standard_excludes)
for line in matches
]
def activate_builtin_hostlists(
existing_lines: list[str],
hostlists_dir: Path,
@@ -156,6 +259,7 @@ def main() -> int:
config_path = Path(args.config)
spec_path = Path(args.spec)
hostlists_dir = config_path.parent / "hostlists"
configs_dir = config_path.parent / "configs"
standard_excludes = [
f'--hostlist-exclude="{hostlists_dir / "list-exclude.txt"}"',
f'--hostlist-exclude="{hostlists_dir / "list-exclude-user.txt"}"',
@@ -170,6 +274,18 @@ def main() -> int:
start, end = locate_nfqws_block(lines)
nfqws_lines = lines[start + 1 : end]
source_config_cache: dict[str, list[str]] = {}
def source_nfqws_lines(config_name: str | None) -> list[str]:
if not config_name:
return nfqws_lines
source_path = resolve_config(configs_dir, config_name)
cache_key = str(source_path)
if cache_key not in source_config_cache:
source_config_cache[cache_key] = read_nfqws_lines(source_path)
return source_config_cache[cache_key]
generated_lines: list[str] = (
activate_builtin_hostlists(nfqws_lines, hostlists_dir, standard_excludes)
if include_extra_upstream_lists
@@ -178,17 +294,37 @@ def main() -> int:
for entry in entries:
hostlist_path = str(hostlists_dir / f'list-{entry["name"]}.txt')
preset = entry.get("preset")
if preset:
ipset_path = str(hostlists_dir / f'ipset-{entry["name"]}.txt')
entry_nfqws_lines = source_nfqws_lines(entry.get("configName"))
presets = entry.get("presets")
if presets is None:
preset = entry.get("preset")
presets = [preset] if preset else []
ipsets = entry.get("ipsets", [])
has_domains = entry.get("hasDomains", bool(presets))
has_ips = entry.get("hasIps", bool(ipsets))
for preset in presets:
generated_lines.extend(
clone_family_lines(
nfqws_lines, preset, hostlist_path, standard_excludes
entry_nfqws_lines, preset, hostlist_path, standard_excludes
)
)
for ipset in ipsets:
generated_lines.extend(
clone_ipset_lines(
entry_nfqws_lines, ipset, ipset_path, standard_excludes
)
)
for fragment in entry.get("nfqwsArgs", []):
generated_lines.append(
render_custom_args(fragment, hostlist_path, standard_excludes)
)
if has_domains:
generated_lines.append(
render_custom_args(fragment, hostlist_path, standard_excludes)
)
if has_ips:
generated_lines.append(
render_custom_ipset_args(fragment, ipset_path, standard_excludes)
)
updated_lines = lines[:end] + generated_lines + lines[end:]
config_path.write_text("\n".join(updated_lines) + "\n", encoding="utf-8")