refactor
This commit is contained in:
13 files changed
+1404
-1299
No files matched your search
@@ -8,8 +8,8 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
sb = cfg.singBox;
|
singBoxCfg = cfg.singBox;
|
||||||
art = cfg.appRouting.backends.tun;
|
appRoutingTun = cfg.appRouting.backends.tun;
|
||||||
direct = rules.direct;
|
direct = rules.direct;
|
||||||
|
|
||||||
mkDnsServer =
|
mkDnsServer =
|
||||||
@@ -26,11 +26,11 @@ let
|
|||||||
{ localDetour ? null }:
|
{ localDetour ? null }:
|
||||||
{
|
{
|
||||||
servers = [
|
servers = [
|
||||||
(mkDnsServer "remote" sb.dns.remote "proxy")
|
(mkDnsServer "remote" singBoxCfg.dns.remote "proxy")
|
||||||
(mkDnsServer "local" sb.dns.local localDetour)
|
(mkDnsServer "local" singBoxCfg.dns.local localDetour)
|
||||||
];
|
];
|
||||||
rules =
|
rules =
|
||||||
lib.optional (builtins.elem "google" sb.routing.proxy.geosites) {
|
lib.optional (builtins.elem "google" singBoxCfg.routing.proxy.geosites) {
|
||||||
rule_set = [ "geosite-google" ];
|
rule_set = [ "geosite-google" ];
|
||||||
server = "remote";
|
server = "remote";
|
||||||
}
|
}
|
||||||
@@ -38,13 +38,13 @@ let
|
|||||||
rule_set = map (s: "geosite-${s}") direct.geosites;
|
rule_set = map (s: "geosite-${s}") direct.geosites;
|
||||||
server = "local";
|
server = "local";
|
||||||
};
|
};
|
||||||
final = if sb.proxyByDefault then "remote" else "local";
|
final = if singBoxCfg.proxyByDefault then "remote" else "local";
|
||||||
};
|
};
|
||||||
|
|
||||||
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
|
clashApiBlock = lib.optionalAttrs (singBoxCfg.selection != "first") {
|
||||||
experimental = {
|
experimental = {
|
||||||
clash_api = {
|
clash_api = {
|
||||||
external_controller = "127.0.0.1:${toString sb.clashApiPort}";
|
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
@@ -54,9 +54,9 @@ let
|
|||||||
enableMixed ? false,
|
enableMixed ? false,
|
||||||
enableTProxy ? false,
|
enableTProxy ? false,
|
||||||
enableTun ? false,
|
enableTun ? false,
|
||||||
tunInterface ? sb.tun.interface,
|
tunInterface ? singBoxCfg.tun.interface,
|
||||||
tunAddress ? sb.tun.address,
|
tunAddress ? singBoxCfg.tun.address,
|
||||||
tunMtu ? sb.tun.mtu,
|
tunMtu ? singBoxCfg.tun.mtu,
|
||||||
tunAutoRoute ? true,
|
tunAutoRoute ? true,
|
||||||
tunAutoRedirect ? true,
|
tunAutoRedirect ? true,
|
||||||
tunStrictRoute ? true,
|
tunStrictRoute ? true,
|
||||||
@@ -78,14 +78,14 @@ let
|
|||||||
lib.optional enableMixed {
|
lib.optional enableMixed {
|
||||||
type = "mixed";
|
type = "mixed";
|
||||||
tag = "mixed-in";
|
tag = "mixed-in";
|
||||||
listen = sb.listenAddress;
|
listen = singBoxCfg.listenAddress;
|
||||||
listen_port = sb.port;
|
listen_port = singBoxCfg.port;
|
||||||
}
|
}
|
||||||
++ lib.optional enableTProxy {
|
++ lib.optional enableTProxy {
|
||||||
type = "tproxy";
|
type = "tproxy";
|
||||||
tag = "tproxy-in";
|
tag = "tproxy-in";
|
||||||
listen = "127.0.0.1";
|
listen = "127.0.0.1";
|
||||||
listen_port = sb.tproxyPort;
|
listen_port = singBoxCfg.tproxyPort;
|
||||||
}
|
}
|
||||||
++ lib.optional enableTun {
|
++ lib.optional enableTun {
|
||||||
type = "tun";
|
type = "tun";
|
||||||
@@ -106,7 +106,7 @@ let
|
|||||||
type = "direct";
|
type = "direct";
|
||||||
tag = "direct";
|
tag = "direct";
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = sb.proxyMark; }
|
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = singBoxCfg.proxyMark; }
|
||||||
)
|
)
|
||||||
{
|
{
|
||||||
type = "block";
|
type = "block";
|
||||||
@@ -118,7 +118,7 @@ let
|
|||||||
default_domain_resolver = "local";
|
default_domain_resolver = "local";
|
||||||
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
||||||
rules = rules.routingRules;
|
rules = rules.routingRules;
|
||||||
final = if sb.proxyByDefault then "proxy" else "direct";
|
final = if singBoxCfg.proxyByDefault then "proxy" else "direct";
|
||||||
}
|
}
|
||||||
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
|
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
|
||||||
}
|
}
|
||||||
@@ -133,9 +133,9 @@ let
|
|||||||
|
|
||||||
tunTemplate = mkConfig {
|
tunTemplate = mkConfig {
|
||||||
enableTun = true;
|
enableTun = true;
|
||||||
tunInterface = sb.tun.interface;
|
tunInterface = singBoxCfg.tun.interface;
|
||||||
tunAddress = sb.tun.address;
|
tunAddress = singBoxCfg.tun.address;
|
||||||
tunMtu = sb.tun.mtu;
|
tunMtu = singBoxCfg.tun.mtu;
|
||||||
tunAutoRoute = true;
|
tunAutoRoute = true;
|
||||||
tunAutoRedirect = true;
|
tunAutoRedirect = true;
|
||||||
tunStrictRoute = true;
|
tunStrictRoute = true;
|
||||||
@@ -145,16 +145,16 @@ let
|
|||||||
|
|
||||||
appTunTemplate = mkConfig {
|
appTunTemplate = mkConfig {
|
||||||
enableTun = true;
|
enableTun = true;
|
||||||
tunInterface = art.interface;
|
tunInterface = appRoutingTun.interface;
|
||||||
tunAddress = art.address;
|
tunAddress = appRoutingTun.address;
|
||||||
tunMtu = art.mtu;
|
tunMtu = appRoutingTun.mtu;
|
||||||
tunAutoRoute = false;
|
tunAutoRoute = false;
|
||||||
tunAutoRedirect = false;
|
tunAutoRedirect = false;
|
||||||
tunStrictRoute = false;
|
tunStrictRoute = false;
|
||||||
forceLocalDnsViaProxy = false;
|
forceLocalDnsViaProxy = false;
|
||||||
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
|
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
|
||||||
# rules do not re-intercept sing-box's own packets.
|
# rules do not re-intercept sing-box's own packets.
|
||||||
useOutboundRoutingMark = sb.tproxy.enable;
|
useOutboundRoutingMark = singBoxCfg.tproxy.enable;
|
||||||
enableClashApi = false;
|
enableClashApi = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ in
|
|||||||
;
|
;
|
||||||
};
|
};
|
||||||
in
|
in
|
||||||
import ./service.nix {
|
import ./service {
|
||||||
inherit
|
inherit
|
||||||
config
|
config
|
||||||
lib
|
lib
|
||||||
|
|||||||
@@ -6,10 +6,10 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
sb = cfg.singBox;
|
singBoxCfg = cfg.singBox;
|
||||||
art = cfg.appRouting.backends.tun;
|
appRoutingTun = cfg.appRouting.backends.tun;
|
||||||
artp = cfg.appRouting.backends.tproxy;
|
appRoutingTproxy = cfg.appRouting.backends.tproxy;
|
||||||
arz = cfg.appRouting.backends.zapret;
|
appRoutingZapret = cfg.appRouting.backends.zapret;
|
||||||
|
|
||||||
# Shared across all three nftables rule files that do IPv4 routing.
|
# Shared across all three nftables rule files that do IPv4 routing.
|
||||||
reservedIpBlock = ''
|
reservedIpBlock = ''
|
||||||
@@ -31,8 +31,8 @@ let
|
|||||||
ip daddr ${cidr} udp dport != 53 return
|
ip daddr ${cidr} udp dport != 53 return
|
||||||
'') subnets;
|
'') subnets;
|
||||||
|
|
||||||
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
|
tproxyLocalSubnetLines = mkLocalSubnetLines singBoxCfg.tproxy.localSubnets;
|
||||||
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
|
appTproxyLocalSubnetLines = mkLocalSubnetLines appRoutingTproxy.localSubnets;
|
||||||
|
|
||||||
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
|
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
|
||||||
${reservedIpBlock}
|
${reservedIpBlock}
|
||||||
@@ -44,16 +44,16 @@ let
|
|||||||
# be skipped just because the host has an RFC1918 source address.
|
# be skipped just because the host has an RFC1918 source address.
|
||||||
iifname != "lo" ip saddr $RESERVED_IP return
|
iifname != "lo" ip saddr $RESERVED_IP return
|
||||||
${tproxyLocalSubnetLines}
|
${tproxyLocalSubnetLines}
|
||||||
ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
|
ip protocol tcp tproxy to 127.0.0.1:${toString singBoxCfg.tproxyPort} meta mark set ${toString singBoxCfg.fwmark}
|
||||||
ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
|
ip protocol udp tproxy to 127.0.0.1:${toString singBoxCfg.tproxyPort} meta mark set ${toString singBoxCfg.fwmark}
|
||||||
}
|
}
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority mangle; policy accept;
|
type route hook output priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${tproxyLocalSubnetLines}
|
${tproxyLocalSubnetLines}
|
||||||
meta mark ${toString sb.proxyMark} return
|
meta mark ${toString singBoxCfg.proxyMark} return
|
||||||
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"}${lib.optionalString artp.enable " meta mark ${toString artp.fwmark} return\n"} ip protocol tcp meta mark set ${toString sb.fwmark}
|
${lib.optionalString appRoutingTun.enable " meta mark ${toString appRoutingTun.fwmark} return\n"}${lib.optionalString appRoutingTproxy.enable " meta mark ${toString appRoutingTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString singBoxCfg.fwmark}
|
||||||
ip protocol udp meta mark set ${toString sb.fwmark}
|
ip protocol udp meta mark set ${toString singBoxCfg.fwmark}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
@@ -66,18 +66,18 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
|
|||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
iifname != "lo" ip saddr $RESERVED_IP return
|
iifname != "lo" ip saddr $RESERVED_IP return
|
||||||
${appTproxyLocalSubnetLines}
|
${appTproxyLocalSubnetLines}
|
||||||
ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
|
ct mark ${toString appRoutingTproxy.fwmark} meta mark set ${toString appRoutingTproxy.fwmark}
|
||||||
meta mark ${toString artp.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort}
|
meta mark ${toString appRoutingTproxy.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString singBoxCfg.tproxyPort}
|
||||||
meta mark ${toString artp.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort}
|
meta mark ${toString appRoutingTproxy.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString singBoxCfg.tproxyPort}
|
||||||
}
|
}
|
||||||
|
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority mangle; policy accept;
|
type route hook output priority mangle; policy accept;
|
||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${appTproxyLocalSubnetLines}
|
${appTproxyLocalSubnetLines}
|
||||||
meta mark ${toString sb.proxyMark} return
|
meta mark ${toString singBoxCfg.proxyMark} return
|
||||||
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"} ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
|
${lib.optionalString appRoutingTun.enable " meta mark ${toString appRoutingTun.fwmark} return\n"} ct mark ${toString appRoutingTproxy.fwmark} meta mark set ${toString appRoutingTproxy.fwmark}
|
||||||
meta mark ${toString artp.fwmark} return
|
meta mark ${toString appRoutingTproxy.fwmark} return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
@@ -86,13 +86,13 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
|
|||||||
table inet proxy_suite_app_zapret_mark {
|
table inet proxy_suite_app_zapret_mark {
|
||||||
chain prerouting {
|
chain prerouting {
|
||||||
type filter hook prerouting priority -103; policy accept;
|
type filter hook prerouting priority -103; policy accept;
|
||||||
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
|
ct mark and ${toString appRoutingZapret.filterMark} == ${toString appRoutingZapret.filterMark} meta mark set meta mark or ${toString appRoutingZapret.filterMark}
|
||||||
}
|
}
|
||||||
|
|
||||||
chain output {
|
chain output {
|
||||||
type route hook output priority -103; policy accept;
|
type route hook output priority -103; policy accept;
|
||||||
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
|
ct mark and ${toString appRoutingZapret.filterMark} == ${toString appRoutingZapret.filterMark} meta mark set meta mark or ${toString appRoutingZapret.filterMark}
|
||||||
meta mark and ${toString arz.filterMark} == ${toString arz.filterMark} return
|
meta mark and ${toString appRoutingZapret.filterMark} == ${toString appRoutingZapret.filterMark} return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
@@ -105,9 +105,9 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
|
|||||||
ip daddr $RESERVED_IP return
|
ip daddr $RESERVED_IP return
|
||||||
${lib.concatMapStrings (cidr: ''
|
${lib.concatMapStrings (cidr: ''
|
||||||
ip daddr ${cidr} return
|
ip daddr ${cidr} return
|
||||||
'') art.localSubnets}
|
'') appRoutingTun.localSubnets}
|
||||||
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
|
ct mark ${toString appRoutingTun.fwmark} meta mark set ${toString appRoutingTun.fwmark}
|
||||||
meta mark ${toString art.fwmark} return
|
meta mark ${toString appRoutingTun.fwmark} return
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
'';
|
'';
|
||||||
|
|||||||
@@ -8,8 +8,8 @@
|
|||||||
|
|
||||||
let
|
let
|
||||||
r = cfg.singBox.routing;
|
r = cfg.singBox.routing;
|
||||||
sb = cfg.singBox;
|
singBoxCfg = cfg.singBox;
|
||||||
z = cfg.zapret;
|
zapretCfg = cfg.zapret;
|
||||||
|
|
||||||
trim = lib.strings.trim;
|
trim = lib.strings.trim;
|
||||||
hasPrefix = lib.strings.hasPrefix;
|
hasPrefix = lib.strings.hasPrefix;
|
||||||
@@ -27,16 +27,16 @@ let
|
|||||||
|
|
||||||
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
|
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
|
||||||
|
|
||||||
syncZapretDirectDomains = z.enable && z.syncDirectRouting;
|
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
|
||||||
syncZapretDirectUpstreamIps = z.enable && z.syncDirectRoutingUpstreamIps;
|
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
|
||||||
syncZapretDirectUserIps = z.enable && z.syncDirectRoutingUserIps;
|
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
|
||||||
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
|
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
|
||||||
|
|
||||||
zapretDefaultDomainFiles = [
|
zapretDefaultDomainFiles = [
|
||||||
"list-general.txt"
|
"list-general.txt"
|
||||||
"list-google.txt"
|
"list-google.txt"
|
||||||
]
|
]
|
||||||
++ lib.optionals z.includeExtraUpstreamLists [
|
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
|
||||||
"list-instagram.txt"
|
"list-instagram.txt"
|
||||||
"list-soundcloud.txt"
|
"list-soundcloud.txt"
|
||||||
"list-twitter.txt"
|
"list-twitter.txt"
|
||||||
@@ -51,10 +51,10 @@ let
|
|||||||
[ ];
|
[ ];
|
||||||
zapretDefaultIps =
|
zapretDefaultIps =
|
||||||
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
|
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
|
||||||
zapretUserIps = if syncZapretDirectUserIps then z.ipsetAll else [ ];
|
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
|
||||||
zapretCustomDomains =
|
zapretCustomDomains =
|
||||||
if syncZapretDirectDomains then
|
if syncZapretDirectDomains then
|
||||||
lib.unique (lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) z.hostlistRules)
|
lib.unique (lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.domains) zapretCfg.hostlistRules)
|
||||||
else
|
else
|
||||||
[ ];
|
[ ];
|
||||||
zapretExcludedDomains =
|
zapretExcludedDomains =
|
||||||
@@ -66,13 +66,13 @@ let
|
|||||||
else
|
else
|
||||||
[ ]
|
[ ]
|
||||||
)
|
)
|
||||||
++ (if syncZapretDirectUserIps then z.ipsetExclude else [ ])
|
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
|
||||||
);
|
);
|
||||||
|
|
||||||
zapretDirectDomains =
|
zapretDirectDomains =
|
||||||
if syncZapretDirectDomains then
|
if syncZapretDirectDomains then
|
||||||
subtractItems (lib.unique (zapretDefaultDomains ++ z.listGeneral ++ zapretCustomDomains)) (
|
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
|
||||||
lib.unique (zapretExcludedDomains ++ z.listExclude)
|
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
|
||||||
)
|
)
|
||||||
else
|
else
|
||||||
[ ];
|
[ ];
|
||||||
@@ -119,7 +119,7 @@ let
|
|||||||
"block"
|
"block"
|
||||||
];
|
];
|
||||||
resolveTag =
|
resolveTag =
|
||||||
tag: if sb.selection == "first" && !builtins.elem tag builtinTags then "proxy" else tag;
|
tag: if singBoxCfg.selection == "first" && !builtins.elem tag builtinTags then "proxy" else tag;
|
||||||
|
|
||||||
# Collect per-outbound routing attached directly to outbound definitions.
|
# Collect per-outbound routing attached directly to outbound definitions.
|
||||||
perOutboundRules = lib.concatMap (
|
perOutboundRules = lib.concatMap (
|
||||||
@@ -137,7 +137,7 @@ let
|
|||||||
geoips
|
geoips
|
||||||
;
|
;
|
||||||
}
|
}
|
||||||
) sb.outbounds;
|
) singBoxCfg.outbounds;
|
||||||
|
|
||||||
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
||||||
customRules =
|
customRules =
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
{
|
{
|
||||||
lib,
|
lib,
|
||||||
cfg,
|
cfg,
|
||||||
sb,
|
singBoxCfg,
|
||||||
t,
|
tgWsProxyCfg,
|
||||||
ar,
|
appRoutingCfg,
|
||||||
art,
|
appRoutingTun,
|
||||||
artp,
|
appRoutingTproxy,
|
||||||
arz,
|
appRoutingZapret,
|
||||||
builtinTags,
|
builtinTags,
|
||||||
outboundTags,
|
outboundTags,
|
||||||
invalidRoutingTargets,
|
invalidRoutingTargets,
|
||||||
@@ -19,7 +19,7 @@
|
|||||||
|
|
||||||
[
|
[
|
||||||
{
|
{
|
||||||
assertion = !sb.enable || (sb.outbounds != [ ] || sb.subscriptions != [ ]);
|
assertion = !singBoxCfg.enable || (singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]);
|
||||||
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
|
message = "proxy-suite: at least one outbound or subscription is required when singBox.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
@@ -35,15 +35,15 @@
|
|||||||
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
|
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(sb.tproxy.enable && sb.tproxy.autostart && sb.tun.enable && sb.tun.autostart);
|
assertion = !(singBoxCfg.tproxy.enable && singBoxCfg.tproxy.autostart && singBoxCfg.tun.enable && singBoxCfg.tun.autostart);
|
||||||
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
|
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = ar.enable || ar.profiles == [ ];
|
assertion = appRoutingCfg.enable || appRoutingCfg.profiles == [ ];
|
||||||
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
|
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !ar.proxychains.enable || ar.enable;
|
assertion = !appRoutingCfg.proxychains.enable || appRoutingCfg.enable;
|
||||||
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
|
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
@@ -51,117 +51,117 @@
|
|||||||
message = "proxy-suite: appRouting profile names must be unique";
|
message = "proxy-suite: appRouting profile names must be unique";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !hasProxychainsProfiles || ar.proxychains.enable;
|
assertion = !hasProxychainsProfiles || appRoutingCfg.proxychains.enable;
|
||||||
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
|
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !art.enable || ar.enable;
|
assertion = !appRoutingTun.enable || appRoutingCfg.enable;
|
||||||
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
|
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(hasTunProfiles && !art.enable);
|
assertion = !(hasTunProfiles && !appRoutingTun.enable);
|
||||||
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
|
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !artp.enable || ar.enable;
|
assertion = !appRoutingTproxy.enable || appRoutingCfg.enable;
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
|
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(hasTproxyProfiles && !artp.enable);
|
assertion = !(hasTproxyProfiles && !appRoutingTproxy.enable);
|
||||||
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
|
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !arz.enable || ar.enable;
|
assertion = !appRoutingZapret.enable || appRoutingCfg.enable;
|
||||||
message = "proxy-suite: appRouting.backends.zapret.enable requires appRouting.enable = true";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.enable requires appRouting.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !arz.enable || cfg.zapret.enable;
|
assertion = !appRoutingZapret.enable || cfg.zapret.enable;
|
||||||
message = "proxy-suite: appRouting.backends.zapret.enable requires zapret.enable = true";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.enable requires zapretgWsProxyCfg.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(hasZapretProfiles && (!arz.enable || !cfg.zapret.enable));
|
assertion = !(hasZapretProfiles && (!appRoutingZapret.enable || !cfg.zapret.enable));
|
||||||
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapret.enable = true and zapret.enable = true";
|
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapretgWsProxyCfg.enable = true and zapretgWsProxyCfg.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.fwmark);
|
assertion = !(appRoutingTun.enable && singBoxCfg.tproxy.enable && appRoutingTun.fwmark == singBoxCfg.fwmark);
|
||||||
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
|
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.proxyMark);
|
assertion = !(appRoutingTun.enable && singBoxCfg.tproxy.enable && appRoutingTun.fwmark == singBoxCfg.proxyMark);
|
||||||
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
|
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && sb.tproxy.enable && art.routeTable == sb.routeTable);
|
assertion = !(appRoutingTun.enable && singBoxCfg.tproxy.enable && appRoutingTun.routeTable == singBoxCfg.routeTable);
|
||||||
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
|
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(artp.enable && artp.fwmark == sb.fwmark);
|
assertion = !(appRoutingTproxy.enable && appRoutingTproxy.fwmark == singBoxCfg.fwmark);
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
|
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(artp.enable && artp.fwmark == sb.proxyMark);
|
assertion = !(appRoutingTproxy.enable && appRoutingTproxy.fwmark == singBoxCfg.proxyMark);
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
|
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(artp.enable && artp.routeTable == sb.routeTable);
|
assertion = !(appRoutingTproxy.enable && appRoutingTproxy.routeTable == singBoxCfg.routeTable);
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
|
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && artp.enable && art.fwmark == artp.fwmark);
|
assertion = !(appRoutingTun.enable && appRoutingTproxy.enable && appRoutingTun.fwmark == appRoutingTproxy.fwmark);
|
||||||
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
|
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && artp.enable && art.routeTable == artp.routeTable);
|
assertion = !(appRoutingTun.enable && appRoutingTproxy.enable && appRoutingTun.routeTable == appRoutingTproxy.routeTable);
|
||||||
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
|
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && arz.filterMark == sb.fwmark);
|
assertion = !(appRoutingZapret.enable && appRoutingZapret.filterMark == singBoxCfg.fwmark);
|
||||||
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.fwmark";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.filterMark must differ from singBox.fwmark";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && arz.filterMark == sb.proxyMark);
|
assertion = !(appRoutingZapret.enable && appRoutingZapret.filterMark == singBoxCfg.proxyMark);
|
||||||
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.proxyMark";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.filterMark must differ from singBox.proxyMark";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && arz.enable && art.fwmark == arz.filterMark);
|
assertion = !(appRoutingTun.enable && appRoutingZapret.enable && appRoutingTun.fwmark == appRoutingZapret.filterMark);
|
||||||
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapret.filterMark must differ";
|
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapretgWsProxyCfg.filterMark must differ";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(artp.enable && arz.enable && artp.fwmark == arz.filterMark);
|
assertion = !(appRoutingTproxy.enable && appRoutingZapret.enable && appRoutingTproxy.fwmark == appRoutingZapret.filterMark);
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapret.filterMark must differ";
|
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapretgWsProxyCfg.filterMark must differ";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && builtins.elem arz.filterMark [ 536870912 1073741824 ]);
|
assertion = !(appRoutingZapret.enable && builtins.elem appRoutingZapret.filterMark [ 536870912 1073741824 ]);
|
||||||
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use zapret internal desync mark bits";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.filterMark must not use zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && builtins.elem sb.fwmark [ 67108864 134217728 ]);
|
assertion = !(appRoutingZapret.enable && builtins.elem singBoxCfg.fwmark [ 67108864 134217728 ]);
|
||||||
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
|
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && builtins.elem sb.proxyMark [ 67108864 134217728 ]);
|
assertion = !(appRoutingZapret.enable && builtins.elem singBoxCfg.proxyMark [ 67108864 134217728 ]);
|
||||||
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
|
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(art.enable && arz.enable && builtins.elem art.fwmark [ 67108864 134217728 ]);
|
assertion = !(appRoutingTun.enable && appRoutingZapret.enable && builtins.elem appRoutingTun.fwmark [ 67108864 134217728 ]);
|
||||||
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
|
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(artp.enable && arz.enable && builtins.elem artp.fwmark [ 67108864 134217728 ]);
|
assertion = !(appRoutingTproxy.enable && appRoutingZapret.enable && builtins.elem appRoutingTproxy.fwmark [ 67108864 134217728 ]);
|
||||||
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
|
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = !(arz.enable && builtins.elem arz.filterMark [ 67108864 134217728 ]);
|
assertion = !(appRoutingZapret.enable && builtins.elem appRoutingZapret.filterMark [ 67108864 134217728 ]);
|
||||||
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use app-zapret internal desync mark bits";
|
message = "proxy-suite: appRouting.backends.zapretgWsProxyCfg.filterMark must not use app-zapret internal desync mark bits";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion =
|
assertion =
|
||||||
!t.enable
|
!tgWsProxyCfg.enable
|
||||||
||
|
||
|
||||||
builtins.length (
|
builtins.length (
|
||||||
builtins.filter (x: x != null) [
|
builtins.filter (x: x != null) [
|
||||||
t.secret
|
tgWsProxyCfg.secret
|
||||||
t.secretFile
|
tgWsProxyCfg.secretFile
|
||||||
]
|
]
|
||||||
) == 1;
|
) == 1;
|
||||||
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
|
message = "proxy-suite: tgWsProxy requires exactly one of secret or secretFile";
|
||||||
@@ -179,7 +179,7 @@
|
|||||||
) == 1;
|
) == 1;
|
||||||
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
|
message = "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json";
|
||||||
}
|
}
|
||||||
]) sb.outbounds
|
]) singBoxCfg.outbounds
|
||||||
++ lib.concatMap (sub: [
|
++ lib.concatMap (sub: [
|
||||||
{
|
{
|
||||||
assertion =
|
assertion =
|
||||||
@@ -191,4 +191,4 @@
|
|||||||
) == 1;
|
) == 1;
|
||||||
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
|
message = "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url";
|
||||||
}
|
}
|
||||||
]) sb.subscriptions
|
]) singBoxCfg.subscriptions
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,657 @@
|
|||||||
|
# App routing backend infrastructure (TUN, TProxy, zapret) and the proxy-ctl management tool.
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
cfg,
|
||||||
|
singBoxCfg,
|
||||||
|
appRoutingCfg,
|
||||||
|
appRoutingTun,
|
||||||
|
appRoutingTproxy,
|
||||||
|
appRoutingZapret,
|
||||||
|
appTunChainFile,
|
||||||
|
appTproxyRulesFile,
|
||||||
|
appZapretRulesFile,
|
||||||
|
ip,
|
||||||
|
nft,
|
||||||
|
awk,
|
||||||
|
grepBin,
|
||||||
|
findBin,
|
||||||
|
headBin,
|
||||||
|
seqBin,
|
||||||
|
sleepBin,
|
||||||
|
jq,
|
||||||
|
proxychains4,
|
||||||
|
systemdRun,
|
||||||
|
systemctl,
|
||||||
|
journalctl,
|
||||||
|
idBin,
|
||||||
|
clashApi,
|
||||||
|
selection,
|
||||||
|
subscriptionTagsList,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
appTunSliceName = "proxy-suite-app-tun.slice";
|
||||||
|
appTproxySliceName = "proxy-suite-app-tproxy.slice";
|
||||||
|
appZapretSliceName = "proxy-suite-app-zapret.slice";
|
||||||
|
|
||||||
|
appRoutingProfileNames = map (profile: profile.name) appRoutingCfg.profiles;
|
||||||
|
defaultAppRoutingProfiles =
|
||||||
|
lib.optionals appRoutingCfg.createDefaultProfiles [
|
||||||
|
{
|
||||||
|
name = "proxychains";
|
||||||
|
route = "proxychains";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals appRoutingTun.enable [
|
||||||
|
{
|
||||||
|
name = "tun";
|
||||||
|
route = "tun";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals appRoutingTproxy.enable [
|
||||||
|
{
|
||||||
|
name = "tproxy";
|
||||||
|
route = "tproxy";
|
||||||
|
}
|
||||||
|
]
|
||||||
|
++ lib.optionals (appRoutingZapret.enable && cfg.zapret.enable) [
|
||||||
|
{
|
||||||
|
name = "zapret";
|
||||||
|
route = "zapret";
|
||||||
|
}
|
||||||
|
];
|
||||||
|
effectiveAppRoutingProfiles =
|
||||||
|
appRoutingCfg.profiles
|
||||||
|
++ builtins.filter (profile: !(builtins.elem profile.name appRoutingProfileNames)) defaultAppRoutingProfiles;
|
||||||
|
effectiveAppRoutingProfileNames = map (profile: profile.name) effectiveAppRoutingProfiles;
|
||||||
|
|
||||||
|
appRoutingProfilesFile = pkgs.writeText "proxy-suite-app-routing-profiles.json" (
|
||||||
|
builtins.toJSON effectiveAppRoutingProfiles
|
||||||
|
);
|
||||||
|
|
||||||
|
proxychainsConfigFile = pkgs.writeText "proxy-suite-proxychains.conf" ''
|
||||||
|
strict_chain
|
||||||
|
${lib.optionalString appRoutingCfg.proxychains.quiet "quiet_mode"}
|
||||||
|
${lib.optionalString appRoutingCfg.proxychains.proxyDns "proxy_dns"}
|
||||||
|
tcp_read_time_out 15000
|
||||||
|
tcp_connect_time_out 8000
|
||||||
|
|
||||||
|
[ProxyList]
|
||||||
|
socks5 ${singBoxCfg.listenAddress} ${toString singBoxCfg.port}
|
||||||
|
'';
|
||||||
|
proxychainsQuietArg = lib.optionalString appRoutingCfg.proxychains.quiet "-q ";
|
||||||
|
|
||||||
|
hasProxychainsProfiles = builtins.any (profile: profile.route == "proxychains") effectiveAppRoutingProfiles;
|
||||||
|
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectiveAppRoutingProfiles;
|
||||||
|
hasTproxyProfiles = builtins.any (profile: profile.route == "tproxy") effectiveAppRoutingProfiles;
|
||||||
|
hasZapretProfiles = builtins.any (profile: profile.route == "zapret") effectiveAppRoutingProfiles;
|
||||||
|
|
||||||
|
appTunWaitForInterface = pkgs.writeShellScript "proxy-suite-app-tun-wait-for-interface" ''
|
||||||
|
set -euo pipefail
|
||||||
|
for _ in $(${seqBin} 1 50); do
|
||||||
|
if ${ip} link show dev ${lib.escapeShellArg appRoutingTun.interface} >/dev/null 2>&1; then
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
${sleepBin} 0.1
|
||||||
|
done
|
||||||
|
echo "proxy-suite: app TUN interface ${appRoutingTun.interface} did not appear in time" >&2
|
||||||
|
exit 1
|
||||||
|
'';
|
||||||
|
|
||||||
|
appTunUpScript = pkgs.writeShellScript "proxy-suite-app-tun-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
|
||||||
|
${nft} -f ${appTunChainFile}
|
||||||
|
${appTunWaitForInterface}
|
||||||
|
${ip} route replace default dev ${lib.escapeShellArg appRoutingTun.interface} table ${toString appRoutingTun.routeTable}
|
||||||
|
${ip} rule add fwmark ${toString appRoutingTun.fwmark} table ${toString appRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
appTunDownScript = pkgs.writeShellScript "proxy-suite-app-tun-down" ''
|
||||||
|
set -euo pipefail
|
||||||
|
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
|
||||||
|
${ip} route del default dev ${lib.escapeShellArg appRoutingTun.interface} table ${toString appRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
${ip} rule del fwmark ${toString appRoutingTun.fwmark} table ${toString appRoutingTun.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
appTproxyUpScript = pkgs.writeShellScript "proxy-suite-app-tproxy-up" ''
|
||||||
|
set -euo pipefail
|
||||||
|
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
|
||||||
|
${nft} -f ${appTproxyRulesFile}
|
||||||
|
${ip} route replace local default dev lo table ${toString appRoutingTproxy.routeTable}
|
||||||
|
${ip} rule add fwmark ${toString appRoutingTproxy.fwmark} table ${toString appRoutingTproxy.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
appTproxyDownScript = pkgs.writeShellScript "proxy-suite-app-tproxy-down" ''
|
||||||
|
set -euo pipefail
|
||||||
|
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
|
||||||
|
${ip} route del local default dev lo table ${toString appRoutingTproxy.routeTable} 2>/dev/null || true
|
||||||
|
${ip} rule del fwmark ${toString appRoutingTproxy.fwmark} table ${toString appRoutingTproxy.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Generate a "start" script that adds a per-user cgroup nftables mark rule.
|
||||||
|
mkUserRuleStart =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
nftFamily,
|
||||||
|
nftTable,
|
||||||
|
nftChain,
|
||||||
|
sliceName,
|
||||||
|
sliceLabel,
|
||||||
|
markRule,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
|
||||||
|
set -euo pipefail
|
||||||
|
uid="$1"
|
||||||
|
rule_comment_prefix="proxy-suite-${name}-user-$uid"
|
||||||
|
mark_comment="$rule_comment_prefix-mark"
|
||||||
|
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
|
||||||
|
if ! [ -d "$cgroup_root" ]; then
|
||||||
|
echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
|
||||||
|
if [ -z "$cgroup_dir" ]; then
|
||||||
|
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
|
||||||
|
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
|
||||||
|
|
||||||
|
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||||
|
| ${grepBin} -F "comment \"$rule_comment_prefix" \
|
||||||
|
| ${awk} '{ print $NF }' || true)
|
||||||
|
if [ -n "$handles" ]; then
|
||||||
|
while IFS= read -r handle; do
|
||||||
|
[ -n "$handle" ] || continue
|
||||||
|
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
|
||||||
|
done <<< "$handles"
|
||||||
|
fi
|
||||||
|
|
||||||
|
printf '%s\n' \
|
||||||
|
"add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
|
||||||
|
| ${nft} -f -
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Generate a "stop" script that removes all per-user cgroup nftables mark rules.
|
||||||
|
mkUserRuleStop =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
nftFamily,
|
||||||
|
nftTable,
|
||||||
|
nftChain,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript "proxy-suite-${name}-user-stop" ''
|
||||||
|
set -euo pipefail
|
||||||
|
uid="$1"
|
||||||
|
rule_comment_prefix="proxy-suite-${name}-user-$uid"
|
||||||
|
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
|
||||||
|
| ${grepBin} -F "comment \"$rule_comment_prefix" \
|
||||||
|
| ${awk} '{ print $NF }' || true)
|
||||||
|
if [ -n "$handles" ]; then
|
||||||
|
while IFS= read -r handle; do
|
||||||
|
[ -n "$handle" ] || continue
|
||||||
|
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
|
||||||
|
done <<< "$handles"
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
appTunUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "app-tun";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_app_tun";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = appTunSliceName;
|
||||||
|
sliceLabel = "app TUN";
|
||||||
|
markRule = "meta mark set ${toString appRoutingTun.fwmark} ct mark set ${toString appRoutingTun.fwmark}";
|
||||||
|
};
|
||||||
|
appTunUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "app-tun";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_app_tun";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
appTproxyUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "app-tproxy";
|
||||||
|
nftFamily = "ip";
|
||||||
|
nftTable = "proxy_suite_app_tproxy";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = appTproxySliceName;
|
||||||
|
sliceLabel = "app TProxy";
|
||||||
|
markRule = "meta mark set ${toString appRoutingTproxy.fwmark} ct mark set ${toString appRoutingTproxy.fwmark}";
|
||||||
|
};
|
||||||
|
appTproxyUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "app-tproxy";
|
||||||
|
nftFamily = "ip";
|
||||||
|
nftTable = "proxy_suite_app_tproxy";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
appZapretUserRuleStart = mkUserRuleStart {
|
||||||
|
name = "app-zapret";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_app_zapret_mark";
|
||||||
|
nftChain = "output";
|
||||||
|
sliceName = appZapretSliceName;
|
||||||
|
sliceLabel = "app zapret";
|
||||||
|
markRule = "meta mark set meta mark or ${toString appRoutingZapret.filterMark} ct mark set ct mark or ${toString appRoutingZapret.filterMark}";
|
||||||
|
};
|
||||||
|
appZapretUserRuleStop = mkUserRuleStop {
|
||||||
|
name = "app-zapret";
|
||||||
|
nftFamily = "inet";
|
||||||
|
nftTable = "proxy_suite_app_zapret_mark";
|
||||||
|
nftChain = "output";
|
||||||
|
};
|
||||||
|
|
||||||
|
mkAnchorService = sliceName: desc: {
|
||||||
|
description = desc;
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
Slice = sliceName;
|
||||||
|
ExecStart = "${pkgs.coreutils}/bin/true";
|
||||||
|
ExecStop = "${pkgs.coreutils}/bin/true";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
proxyCtl = pkgs.writeShellApplication {
|
||||||
|
name = "proxy-ctl";
|
||||||
|
runtimeInputs = with pkgs; [
|
||||||
|
coreutils
|
||||||
|
curl
|
||||||
|
gawk
|
||||||
|
gnugrep
|
||||||
|
jq
|
||||||
|
proxychains-ng
|
||||||
|
systemd
|
||||||
|
];
|
||||||
|
text = ''
|
||||||
|
# Embedded at build time from module config
|
||||||
|
CLASH_API="${clashApi}"
|
||||||
|
SELECTION="${selection}"
|
||||||
|
SUB_TAGS=(${subscriptionTagsList})
|
||||||
|
APP_ROUTING_ENABLED="${if appRoutingCfg.enable then "1" else "0"}"
|
||||||
|
APP_ROUTING_PROXYCHAINS_ENABLED="${if appRoutingCfg.proxychains.enable then "1" else "0"}"
|
||||||
|
APP_ROUTING_TUN_ENABLED="${if appRoutingTun.enable then "1" else "0"}"
|
||||||
|
APP_ROUTING_TPROXY_ENABLED="${if appRoutingTproxy.enable then "1" else "0"}"
|
||||||
|
APP_ROUTING_ZAPRET_ENABLED="${if (appRoutingZapret.enable && cfg.zapret.enable) then "1" else "0"}"
|
||||||
|
APP_ROUTING_PROFILES_FILE="${appRoutingProfilesFile}"
|
||||||
|
PROXYCHAINS_CONFIG="${proxychainsConfigFile}"
|
||||||
|
APP_TUN_SLICE_BASE="proxy-suite-app-tun"
|
||||||
|
APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy"
|
||||||
|
APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret"
|
||||||
|
|
||||||
|
ALL_SERVICES=(
|
||||||
|
proxy-suite-socks
|
||||||
|
proxy-suite-tproxy
|
||||||
|
proxy-suite-tun
|
||||||
|
proxy-suite-tg-ws-proxy
|
||||||
|
proxy-suite-zapret-vm-exempt
|
||||||
|
zapret-discord-youtube
|
||||||
|
)
|
||||||
|
|
||||||
|
_usage() {
|
||||||
|
echo "Usage: proxy-ctl <command> [args]"
|
||||||
|
echo ""
|
||||||
|
echo "Commands:"
|
||||||
|
echo " status [--tray] show status of all proxy-suite services"
|
||||||
|
echo " proxy on|off enable/disable the core SOCKS proxy"
|
||||||
|
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||||
|
echo " tun on|off enable/disable TUN mode"
|
||||||
|
echo " zapret on|off enable/disable zapret-discord-youtube"
|
||||||
|
echo " restart restart active global proxy-suite services"
|
||||||
|
echo " logs [service] follow service logs (default: proxy-suite-socks)"
|
||||||
|
echo " outbounds list outbounds and current selection"
|
||||||
|
echo " select <tag> switch to a specific outbound (selector mode)"
|
||||||
|
echo " apps list configured per-app routing profiles"
|
||||||
|
echo " wrap <profile> -- <cmd> run a command via an appRouting profile"
|
||||||
|
echo " subscription list show subscriptions, cache age, and proxy count"
|
||||||
|
echo " subscription update force-refresh all subscription caches and restart"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
_svc_status() {
|
||||||
|
local svc="$1"
|
||||||
|
if ! systemctl cat "$svc" &>/dev/null; then
|
||||||
|
return
|
||||||
|
fi
|
||||||
|
local state
|
||||||
|
state=$(systemctl is-active "$svc" 2>/dev/null || true)
|
||||||
|
printf " %-44s %s\n" "$svc" "$state"
|
||||||
|
}
|
||||||
|
|
||||||
|
_bool() {
|
||||||
|
if "$@"; then
|
||||||
|
printf true
|
||||||
|
else
|
||||||
|
printf false
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_svc_exists() {
|
||||||
|
systemctl cat "$1" &>/dev/null
|
||||||
|
}
|
||||||
|
|
||||||
|
_svc_active() {
|
||||||
|
systemctl is-active --quiet "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
_status_tray() {
|
||||||
|
printf 'socks_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||||
|
printf 'socks_active=%s\n' "$(_bool _svc_active proxy-suite-socks)"
|
||||||
|
printf 'tproxy_available=%s\n' "$(_bool _svc_exists proxy-suite-tproxy)"
|
||||||
|
printf 'tproxy_active=%s\n' "$(_bool _svc_active proxy-suite-tproxy)"
|
||||||
|
printf 'tun_available=%s\n' "$(_bool _svc_exists proxy-suite-tun)"
|
||||||
|
printf 'tun_active=%s\n' "$(_bool _svc_active proxy-suite-tun)"
|
||||||
|
printf 'zapret_available=%s\n' "$(_bool _svc_exists zapret-discord-youtube)"
|
||||||
|
printf 'zapret_active=%s\n' "$(_bool _svc_active zapret-discord-youtube)"
|
||||||
|
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||||
|
}
|
||||||
|
|
||||||
|
_ensure_app_routing() {
|
||||||
|
if [ "$APP_ROUTING_ENABLED" != "1" ]; then
|
||||||
|
echo "appRouting is not enabled in services.proxy-suite.appRouting."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_profile_route() {
|
||||||
|
local profile="$1"
|
||||||
|
${jq} -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$APP_ROUTING_PROFILES_FILE"
|
||||||
|
}
|
||||||
|
|
||||||
|
_scope_running() {
|
||||||
|
${systemctl} --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
|
||||||
|
| ${grepBin} -q .
|
||||||
|
}
|
||||||
|
|
||||||
|
_any_user_active() {
|
||||||
|
${systemctl} list-units --type=service --state=active --plain --no-legend "$1*.service" \
|
||||||
|
| ${grepBin} -q .
|
||||||
|
}
|
||||||
|
|
||||||
|
_check_no_global_proxy() {
|
||||||
|
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
|
||||||
|
echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
|
||||||
|
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
|
||||||
|
_wrap_slice() {
|
||||||
|
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
|
||||||
|
shift 4
|
||||||
|
if [ "$enabled" != "1" ]; then
|
||||||
|
echo "$disabled_msg"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
local uid; uid="$(${idBin} -u)"
|
||||||
|
local scope_unit="$slice_base-''${profile}-$$"
|
||||||
|
local anchor_unit="$slice_base-anchor.service"
|
||||||
|
local user_svc="$slice_base-user@$uid.service"
|
||||||
|
|
||||||
|
${systemctl} --user start "$anchor_unit"
|
||||||
|
${systemctl} start "$backend_svc"
|
||||||
|
${systemctl} start "$user_svc"
|
||||||
|
|
||||||
|
local status=0
|
||||||
|
${systemdRun} --user --scope --quiet --collect --same-dir \
|
||||||
|
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||||
|
|
||||||
|
if ! _scope_running "$slice_base"; then
|
||||||
|
${systemctl} stop "$user_svc" || true
|
||||||
|
${systemctl} --user stop "$anchor_unit" || true
|
||||||
|
if ! _any_user_active "$slice_base-user@"; then
|
||||||
|
${systemctl} stop "$backend_svc" || true
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
exit "$status"
|
||||||
|
}
|
||||||
|
|
||||||
|
cmd="''${1:-status}"
|
||||||
|
shift || true
|
||||||
|
|
||||||
|
case "$cmd" in
|
||||||
|
status)
|
||||||
|
if [ "''${1:-}" = "--tray" ]; then
|
||||||
|
_status_tray
|
||||||
|
else
|
||||||
|
echo "proxy-suite services:"
|
||||||
|
for svc in "''${ALL_SERVICES[@]}"; do
|
||||||
|
_svc_status "$svc"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
|
||||||
|
proxy)
|
||||||
|
case "''${1:-on}" in
|
||||||
|
on)
|
||||||
|
systemctl start proxy-suite-socks
|
||||||
|
;;
|
||||||
|
off)
|
||||||
|
systemctl stop proxy-suite-tproxy || true
|
||||||
|
systemctl stop proxy-suite-tun || true
|
||||||
|
systemctl stop proxy-suite-socks
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Usage: proxy-ctl proxy on|off"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
tproxy)
|
||||||
|
case "''${1:-on}" in
|
||||||
|
on) systemctl start proxy-suite-tproxy ;;
|
||||||
|
off) systemctl stop proxy-suite-tproxy ;;
|
||||||
|
*) echo "Usage: proxy-ctl tproxy on|off"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
tun)
|
||||||
|
case "''${1:-on}" in
|
||||||
|
on) systemctl start proxy-suite-tun ;;
|
||||||
|
off) systemctl stop proxy-suite-tun ;;
|
||||||
|
*) echo "Usage: proxy-ctl tun on|off"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
zapret)
|
||||||
|
case "''${1:-on}" in
|
||||||
|
on) systemctl start zapret-discord-youtube ;;
|
||||||
|
off) systemctl stop zapret-discord-youtube ;;
|
||||||
|
*) echo "Usage: proxy-ctl zapret on|off"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
restart)
|
||||||
|
systemctl restart proxy-suite-socks
|
||||||
|
if systemctl is-active --quiet proxy-suite-tproxy; then
|
||||||
|
systemctl restart proxy-suite-tproxy
|
||||||
|
fi
|
||||||
|
if systemctl is-active --quiet proxy-suite-tun; then
|
||||||
|
systemctl restart proxy-suite-tun
|
||||||
|
fi
|
||||||
|
if systemctl is-active --quiet zapret-discord-youtube; then
|
||||||
|
systemctl restart zapret-discord-youtube
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
|
||||||
|
logs)
|
||||||
|
svc="''${1:-proxy-suite-socks}"
|
||||||
|
shift || true
|
||||||
|
exec journalctl -fu "$svc" "$@"
|
||||||
|
;;
|
||||||
|
|
||||||
|
outbounds)
|
||||||
|
data=$(curl -sf "$CLASH_API/proxies/proxy" 2>/dev/null) || {
|
||||||
|
echo "Clash API not available."
|
||||||
|
echo " - Make sure proxy-suite-socks is running"
|
||||||
|
echo " - selection must be 'selector' or 'urltest' (currently: $SELECTION)"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
now=$(echo "$data" | jq -r '.now // "n/a"')
|
||||||
|
ob_type=$(echo "$data" | jq -r '.type // "n/a"')
|
||||||
|
echo "Type: $ob_type"
|
||||||
|
echo "Current: $now"
|
||||||
|
echo ""
|
||||||
|
echo "Available:"
|
||||||
|
echo "$data" | jq -r '.all[]? | " " + .'
|
||||||
|
;;
|
||||||
|
|
||||||
|
select)
|
||||||
|
tag="''${1:?Usage: proxy-ctl select <outbound-tag>}"
|
||||||
|
if [ "$SELECTION" != "selector" ]; then
|
||||||
|
echo "selection must be 'selector' (currently: $SELECTION)"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
payload=$(jq -cn --arg name "$tag" '{name:$name}')
|
||||||
|
if curl -sf -X PUT "$CLASH_API/proxies/proxy" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d "$payload" >/dev/null; then
|
||||||
|
echo "Switched to: $tag"
|
||||||
|
else
|
||||||
|
echo "Failed – is proxy-suite-socks running with selector mode?"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
|
||||||
|
apps)
|
||||||
|
_ensure_app_routing
|
||||||
|
if [ "$(${jq} 'length' "$APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then
|
||||||
|
echo "No appRouting profiles configured."
|
||||||
|
else
|
||||||
|
printf " %-24s %s\n" "PROFILE" "ROUTE"
|
||||||
|
${jq} -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \
|
||||||
|
"$APP_ROUTING_PROFILES_FILE" \
|
||||||
|
| while IFS=$'\t' read -r profile route; do
|
||||||
|
printf "%-26s %s\n" "$profile" "$route"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
|
||||||
|
wrap)
|
||||||
|
profile="''${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
|
||||||
|
shift || true
|
||||||
|
if [ "''${1:-}" = "--" ]; then
|
||||||
|
shift
|
||||||
|
fi
|
||||||
|
if [ "$#" -eq 0 ]; then
|
||||||
|
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
_ensure_app_routing
|
||||||
|
route="$(_profile_route "$profile")"
|
||||||
|
if [ -z "$route" ] || [ "$route" = "null" ]; then
|
||||||
|
echo "Unknown appRouting profile: $profile"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
case "$route" in
|
||||||
|
direct)
|
||||||
|
exec "$@"
|
||||||
|
;;
|
||||||
|
proxychains)
|
||||||
|
if [ "$APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then
|
||||||
|
echo "Profile '$profile' uses route=proxychains, but appRouting.proxychains.enable is false."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
exec ${proxychains4} ${proxychainsQuietArg}-f "$PROXYCHAINS_CONFIG" "$@"
|
||||||
|
;;
|
||||||
|
tun)
|
||||||
|
_wrap_slice "$APP_TUN_SLICE_BASE" "$APP_ROUTING_TUN_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=tun, but appRouting.backends.tun.enable is false." \
|
||||||
|
"proxy-suite-app-tun.service" "$@"
|
||||||
|
;;
|
||||||
|
tproxy)
|
||||||
|
_check_no_global_proxy tproxy
|
||||||
|
_wrap_slice "$APP_TPROXY_SLICE_BASE" "$APP_ROUTING_TPROXY_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=tproxy, but appRouting.backends.tproxy.enable is false." \
|
||||||
|
"proxy-suite-app-tproxy.service" "$@"
|
||||||
|
;;
|
||||||
|
zapret)
|
||||||
|
_check_no_global_proxy zapret
|
||||||
|
_wrap_slice "$APP_ZAPRET_SLICE_BASE" "$APP_ROUTING_ZAPRET_ENABLED" \
|
||||||
|
"Profile '$profile' uses route=zapret, but the app-zapret backend or zapret service is not enabled." \
|
||||||
|
"proxy-suite-app-zapret.service" "$@"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Route backend '$route' is not implemented in this build."
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
subscription)
|
||||||
|
subcmd="''${1:-list}"
|
||||||
|
shift || true
|
||||||
|
case "$subcmd" in
|
||||||
|
list)
|
||||||
|
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||||
|
if [ ''${#SUB_TAGS[@]} -eq 0 ]; then
|
||||||
|
echo "No subscriptions configured."
|
||||||
|
else
|
||||||
|
printf " %-30s %-22s %s\n" "TAG" "LAST UPDATED" "PROXIES"
|
||||||
|
for t in "''${SUB_TAGS[@]}"; do
|
||||||
|
cache="$CACHE_DIR/$t.json"
|
||||||
|
if [ -f "$cache" ]; then
|
||||||
|
age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown")
|
||||||
|
count=$(jq 'length' "$cache" 2>/dev/null || echo "?")
|
||||||
|
else
|
||||||
|
age="(no cache)"
|
||||||
|
count="-"
|
||||||
|
fi
|
||||||
|
printf " %-30s %-22s %s\n" "$t" "$age" "$count"
|
||||||
|
done
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
update)
|
||||||
|
systemctl start proxy-suite-subscription-update
|
||||||
|
echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update"
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "Usage: proxy-ctl subscription list|update"; exit 1 ;;
|
||||||
|
esac
|
||||||
|
;;
|
||||||
|
|
||||||
|
*)
|
||||||
|
_usage
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit
|
||||||
|
appTunSliceName
|
||||||
|
appTproxySliceName
|
||||||
|
appZapretSliceName
|
||||||
|
appTunUpScript
|
||||||
|
appTunDownScript
|
||||||
|
appTproxyUpScript
|
||||||
|
appTproxyDownScript
|
||||||
|
appTunUserRuleStart
|
||||||
|
appTunUserRuleStop
|
||||||
|
appTproxyUserRuleStart
|
||||||
|
appTproxyUserRuleStop
|
||||||
|
appZapretUserRuleStart
|
||||||
|
appZapretUserRuleStop
|
||||||
|
mkAnchorService
|
||||||
|
effectiveAppRoutingProfiles
|
||||||
|
effectiveAppRoutingProfileNames
|
||||||
|
appRoutingProfilesFile
|
||||||
|
proxychainsConfigFile
|
||||||
|
proxychainsQuietArg
|
||||||
|
hasProxychainsProfiles
|
||||||
|
hasTunProfiles
|
||||||
|
hasTproxyProfiles
|
||||||
|
hasZapretProfiles
|
||||||
|
proxyCtl
|
||||||
|
;
|
||||||
|
}
|
||||||
@@ -0,0 +1,290 @@
|
|||||||
|
# Assembles all sing-box systemd services from the sub-modules.
|
||||||
|
{
|
||||||
|
config,
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
cfg,
|
||||||
|
tproxyFile,
|
||||||
|
tunFile,
|
||||||
|
appTunFile,
|
||||||
|
nftablesRulesFile,
|
||||||
|
appTproxyRulesFile,
|
||||||
|
appZapretRulesFile,
|
||||||
|
appTunChainFile,
|
||||||
|
ip,
|
||||||
|
nft,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
singBoxCfg = cfg.singBox;
|
||||||
|
appRoutingCfg = cfg.appRouting;
|
||||||
|
appRoutingTun = appRoutingCfg.backends.tun;
|
||||||
|
appRoutingTproxy = appRoutingCfg.backends.tproxy;
|
||||||
|
appRoutingZapret = appRoutingCfg.backends.zapret;
|
||||||
|
userControlCfg = cfg.userControl;
|
||||||
|
|
||||||
|
builtinTags = [ "proxy" "direct" "block" ];
|
||||||
|
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
|
||||||
|
invalidRoutingTargets = lib.unique (
|
||||||
|
map (rule: rule.outbound) (
|
||||||
|
builtins.filter (rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)) singBoxCfg.routing.rules
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
# Tool paths – defined once here and passed into sub-modules as needed.
|
||||||
|
jq = "${pkgs.jq}/bin/jq";
|
||||||
|
python3 = "${pkgs.python3}/bin/python3";
|
||||||
|
singBox = "${pkgs.sing-box}/bin/sing-box";
|
||||||
|
proxychains4 = "${pkgs.proxychains-ng}/bin/proxychains4";
|
||||||
|
systemdRun = "${pkgs.systemd}/bin/systemd-run";
|
||||||
|
systemctl = "${pkgs.systemd}/bin/systemctl";
|
||||||
|
journalctl = "${pkgs.systemd}/bin/journalctl";
|
||||||
|
idBin = "${pkgs.coreutils}/bin/id";
|
||||||
|
grepBin = "${pkgs.gnugrep}/bin/grep";
|
||||||
|
awk = "${pkgs.gawk}/bin/awk";
|
||||||
|
sleepBin = "${pkgs.coreutils}/bin/sleep";
|
||||||
|
headBin = "${pkgs.coreutils}/bin/head";
|
||||||
|
seqBin = "${pkgs.coreutils}/bin/seq";
|
||||||
|
findBin = "${pkgs.findutils}/bin/find";
|
||||||
|
|
||||||
|
proxySuiteScriptsDir = ../../../scripts;
|
||||||
|
parserScriptsPythonPath = proxySuiteScriptsDir;
|
||||||
|
buildOutboundPy = "${proxySuiteScriptsDir}/build-outbound.py";
|
||||||
|
fetchSubscriptionPy = "${proxySuiteScriptsDir}/fetch-subscription.py";
|
||||||
|
|
||||||
|
polkit = import ./polkit.nix {
|
||||||
|
inherit lib cfg userControlCfg;
|
||||||
|
};
|
||||||
|
|
||||||
|
scripts = import ./scripts.nix {
|
||||||
|
inherit lib pkgs singBoxCfg appRoutingTun;
|
||||||
|
inherit jq python3 singBox parserScriptsPythonPath buildOutboundPy fetchSubscriptionPy;
|
||||||
|
inherit tproxyFile tunFile appTunFile;
|
||||||
|
};
|
||||||
|
|
||||||
|
appRouting = import ./app-routing.nix {
|
||||||
|
inherit lib pkgs cfg singBoxCfg appRoutingCfg appRoutingTun appRoutingTproxy appRoutingZapret;
|
||||||
|
inherit appTunChainFile appTproxyRulesFile appZapretRulesFile;
|
||||||
|
inherit ip nft;
|
||||||
|
inherit awk grepBin findBin headBin seqBin sleepBin;
|
||||||
|
inherit jq proxychains4 systemdRun systemctl journalctl idBin;
|
||||||
|
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
|
||||||
|
selection = singBoxCfg.selection;
|
||||||
|
inherit (scripts) subscriptionTagsList;
|
||||||
|
};
|
||||||
|
in
|
||||||
|
{
|
||||||
|
environment.systemPackages = [ appRouting.proxyCtl ];
|
||||||
|
|
||||||
|
# nftables must be on for TProxy to work.
|
||||||
|
networking.nftables.enable = lib.mkIf (
|
||||||
|
singBoxCfg.tproxy.enable || appRoutingTun.enable || appRoutingTproxy.enable || appRoutingZapret.enable
|
||||||
|
) (lib.mkDefault true);
|
||||||
|
|
||||||
|
users.groups = lib.mkIf (cfg.enable && polkit.userControlEnabled) {
|
||||||
|
"${userControlCfg.group}" = { };
|
||||||
|
};
|
||||||
|
|
||||||
|
security.polkit.enable = lib.mkIf (cfg.enable && polkit.userControlEnabled) true;
|
||||||
|
security.polkit.extraConfig = lib.mkIf (cfg.enable && polkit.userControlEnabled) (lib.mkAfter ''
|
||||||
|
polkit.addRule(function(action, subject) {
|
||||||
|
if (!subject.isInGroup("${userControlCfg.group}")) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (action.id !== "org.freedesktop.systemd1.manage-units") {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
var unit = action.lookup("unit");
|
||||||
|
${polkit.userControlPolkitRules}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
'');
|
||||||
|
|
||||||
|
systemd.user.services =
|
||||||
|
lib.optionalAttrs appRoutingTun.enable {
|
||||||
|
proxy-suite-app-tun-anchor =
|
||||||
|
appRouting.mkAnchorService appRouting.appTunSliceName "Anchor service for proxy-suite app TUN slice";
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs appRoutingTproxy.enable {
|
||||||
|
proxy-suite-app-tproxy-anchor =
|
||||||
|
appRouting.mkAnchorService appRouting.appTproxySliceName "Anchor service for proxy-suite app TProxy slice";
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs (appRoutingZapret.enable && cfg.zapret.enable) {
|
||||||
|
proxy-suite-app-zapret-anchor =
|
||||||
|
appRouting.mkAnchorService appRouting.appZapretSliceName "Anchor service for proxy-suite app zapret slice";
|
||||||
|
};
|
||||||
|
|
||||||
|
assertions = import ../service-assertions.nix {
|
||||||
|
inherit lib cfg;
|
||||||
|
inherit singBoxCfg appRoutingCfg appRoutingTun appRoutingTproxy appRoutingZapret;
|
||||||
|
tgWsProxyCfg = cfg.tgWsProxy;
|
||||||
|
inherit builtinTags outboundTags invalidRoutingTargets;
|
||||||
|
inherit (appRouting)
|
||||||
|
effectiveAppRoutingProfileNames
|
||||||
|
hasProxychainsProfiles
|
||||||
|
hasTunProfiles
|
||||||
|
hasTproxyProfiles
|
||||||
|
hasZapretProfiles
|
||||||
|
;
|
||||||
|
};
|
||||||
|
|
||||||
|
systemd.services = {
|
||||||
|
proxy-suite-socks = {
|
||||||
|
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||||
|
after = [ "network.target" ];
|
||||||
|
wantedBy = [ "multi-user.target" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = "${scripts.startSocks}";
|
||||||
|
Restart = "on-failure";
|
||||||
|
RestartSec = 5;
|
||||||
|
RuntimeDirectory = "proxy-suite-socks";
|
||||||
|
StateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs singBoxCfg.tproxy.enable {
|
||||||
|
proxy-suite-tproxy = {
|
||||||
|
description = "sing-box TProxy – nftables rules and policy routing";
|
||||||
|
after = [
|
||||||
|
"network.target"
|
||||||
|
"proxy-suite-socks.service"
|
||||||
|
];
|
||||||
|
wantedBy = lib.optionals singBoxCfg.tproxy.autostart [ "multi-user.target" ];
|
||||||
|
requires = [ "proxy-suite-socks.service" ];
|
||||||
|
conflicts = [
|
||||||
|
"proxy-suite-tun.service"
|
||||||
|
"proxy-suite-app-tproxy.service"
|
||||||
|
];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||||
|
${nft} delete table ip singbox 2>/dev/null || true
|
||||||
|
${nft} -f ${nftablesRulesFile}
|
||||||
|
${ip} route add local default dev lo table ${toString singBoxCfg.routeTable}
|
||||||
|
${ip} rule add fwmark ${toString singBoxCfg.fwmark} table ${toString singBoxCfg.routeTable}
|
||||||
|
'';
|
||||||
|
ExecStop = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
|
||||||
|
${nft} delete table ip singbox 2>/dev/null || true
|
||||||
|
${ip} route del local default dev lo table ${toString singBoxCfg.routeTable} 2>/dev/null || true
|
||||||
|
${ip} rule del fwmark ${toString singBoxCfg.fwmark} table ${toString singBoxCfg.routeTable} 2>/dev/null || true
|
||||||
|
'';
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs singBoxCfg.tun.enable {
|
||||||
|
proxy-suite-tun = {
|
||||||
|
description = "sing-box TUN proxy client";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wantedBy = lib.optionals singBoxCfg.tun.autostart [ "multi-user.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
conflicts = [ "proxy-suite-tproxy.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = "${scripts.startTun}";
|
||||||
|
Restart = "on-failure";
|
||||||
|
RestartSec = 5;
|
||||||
|
RuntimeDirectory = "proxy-suite-tun";
|
||||||
|
StateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs appRoutingTun.enable {
|
||||||
|
proxy-suite-app-tun = {
|
||||||
|
description = "sing-box app-routing TUN backend";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
serviceConfig = {
|
||||||
|
ExecStart = "${scripts.startAppTun}";
|
||||||
|
ExecStartPost = "${appRouting.appTunUpScript}";
|
||||||
|
ExecStopPost = "${appRouting.appTunDownScript}";
|
||||||
|
Restart = "on-failure";
|
||||||
|
RestartSec = 5;
|
||||||
|
RuntimeDirectory = "proxy-suite-app-tun";
|
||||||
|
StateDirectory = "proxy-suite";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
"proxy-suite-app-tun-user@" = {
|
||||||
|
description = "Enable proxy-suite app TUN marking for user %i";
|
||||||
|
requires = [ "proxy-suite-app-tun.service" ];
|
||||||
|
after = [ "proxy-suite-app-tun.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = "${appRouting.appTunUserRuleStart} %i";
|
||||||
|
ExecStop = "${appRouting.appTunUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs appRoutingTproxy.enable {
|
||||||
|
proxy-suite-app-tproxy = {
|
||||||
|
description = "proxy-suite app-routing TProxy backend";
|
||||||
|
after = [
|
||||||
|
"network.target"
|
||||||
|
"proxy-suite-socks.service"
|
||||||
|
];
|
||||||
|
requires = [ "proxy-suite-socks.service" ];
|
||||||
|
conflicts = [
|
||||||
|
"proxy-suite-tproxy.service"
|
||||||
|
"proxy-suite-tun.service"
|
||||||
|
];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = "${appRouting.appTproxyUpScript}";
|
||||||
|
ExecStop = "${appRouting.appTproxyDownScript}";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
"proxy-suite-app-tproxy-user@" = {
|
||||||
|
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||||
|
requires = [ "proxy-suite-app-tproxy.service" ];
|
||||||
|
after = [ "proxy-suite-app-tproxy.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = "${appRouting.appTproxyUserRuleStart} %i";
|
||||||
|
ExecStop = "${appRouting.appTproxyUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs (appRoutingZapret.enable && cfg.zapret.enable) {
|
||||||
|
"proxy-suite-app-zapret-user@" = {
|
||||||
|
description = "Enable proxy-suite app zapret marking for user %i";
|
||||||
|
requires = [ "proxy-suite-app-zapret.service" ];
|
||||||
|
after = [ "proxy-suite-app-zapret.service" ];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
RemainAfterExit = true;
|
||||||
|
ExecStart = "${appRouting.appZapretUserRuleStart} %i";
|
||||||
|
ExecStop = "${appRouting.appZapretUserRuleStop} %i";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
// lib.optionalAttrs scripts.hasSubscriptions {
|
||||||
|
proxy-suite-subscription-update = {
|
||||||
|
description = "Refresh proxy-suite subscription caches";
|
||||||
|
after = [ "network-online.target" ];
|
||||||
|
wants = [ "network-online.target" ];
|
||||||
|
serviceConfig = {
|
||||||
|
Type = "oneshot";
|
||||||
|
StateDirectory = "proxy-suite";
|
||||||
|
ExecStart = "${scripts.subscriptionUpdateScript}";
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
systemd.timers = lib.optionalAttrs scripts.hasSubscriptions {
|
||||||
|
proxy-suite-subscription-update = {
|
||||||
|
description = "Periodic proxy-suite subscription refresh";
|
||||||
|
wantedBy = [ "timers.target" ];
|
||||||
|
timerConfig = {
|
||||||
|
OnBootSec = "5m";
|
||||||
|
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# Polkit rules granting proxy-suite group members passwordless control over services.
|
||||||
|
{ lib, cfg, userControlCfg }:
|
||||||
|
|
||||||
|
let
|
||||||
|
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
|
||||||
|
|
||||||
|
userControlPolkitRules =
|
||||||
|
lib.optionalString userControlCfg.perApp.enable ''
|
||||||
|
if (unit.indexOf("proxy-suite-app-") === 0) {
|
||||||
|
return polkit.Result.YES;
|
||||||
|
}
|
||||||
|
''
|
||||||
|
+ lib.optionalString userControlCfg.global.enable ''
|
||||||
|
if ((unit.indexOf("proxy-suite-") === 0 &&
|
||||||
|
unit.indexOf("proxy-suite-app-") !== 0) ||
|
||||||
|
unit === "zapret-discord-youtube.service") {
|
||||||
|
return polkit.Result.YES;
|
||||||
|
}
|
||||||
|
'';
|
||||||
|
in
|
||||||
|
{ inherit userControlEnabled userControlPolkitRules; }
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
# Generates the sing-box startup scripts and subscription management scripts.
|
||||||
|
{
|
||||||
|
lib,
|
||||||
|
pkgs,
|
||||||
|
singBoxCfg,
|
||||||
|
appRoutingTun,
|
||||||
|
jq,
|
||||||
|
python3,
|
||||||
|
singBox,
|
||||||
|
parserScriptsPythonPath,
|
||||||
|
buildOutboundPy,
|
||||||
|
fetchSubscriptionPy,
|
||||||
|
tproxyFile,
|
||||||
|
tunFile,
|
||||||
|
appTunFile,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
mkSubscriptionUrlSource =
|
||||||
|
sub:
|
||||||
|
if sub.urlFile != null then
|
||||||
|
sub.urlFile
|
||||||
|
else
|
||||||
|
pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url;
|
||||||
|
|
||||||
|
mkSubscriptionFetchCommand =
|
||||||
|
sub:
|
||||||
|
let
|
||||||
|
urlSource = mkSubscriptionUrlSource sub;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
printf '%s' "$(cat "${urlSource}")" \
|
||||||
|
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag}
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Build the shell code block for a single outbound entry.
|
||||||
|
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
|
||||||
|
# routingMark is null or an int; added to outbound JSON if set.
|
||||||
|
mkOutboundBlock =
|
||||||
|
ob: routingMark: tag:
|
||||||
|
let
|
||||||
|
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
|
||||||
|
in
|
||||||
|
if ob.json != null then
|
||||||
|
let
|
||||||
|
outboundJson = builtins.toJSON (
|
||||||
|
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
|
||||||
|
);
|
||||||
|
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
# outbound: ${tag} (static json)
|
||||||
|
OB_JSON=$(cat "${jsonFile}")
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
''
|
||||||
|
else
|
||||||
|
let
|
||||||
|
urlSource =
|
||||||
|
if ob.urlFile != null then
|
||||||
|
ob.urlFile
|
||||||
|
else
|
||||||
|
# Literal URL – write to nix store so the script can cat it.
|
||||||
|
# Less secret than urlFile, but convenient for non-sensitive configs.
|
||||||
|
pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||||
|
in
|
||||||
|
''
|
||||||
|
# outbound: ${tag}
|
||||||
|
URL=$(cat "${urlSource}")
|
||||||
|
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --tag ${lib.escapeShellArg tag}${markArg})
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Build the shell code block for a single subscription entry.
|
||||||
|
# Fetches subscription into the cache on first run; subsequent starts use the cache.
|
||||||
|
mkSubscriptionBlock =
|
||||||
|
sub: routingMark:
|
||||||
|
''
|
||||||
|
# subscription: ${sub.tag}
|
||||||
|
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||||
|
CACHE_FILE="$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
|
||||||
|
if [ ! -f "$CACHE_FILE" ]; then
|
||||||
|
mkdir -p "$CACHE_DIR"
|
||||||
|
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
|
||||||
|
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
|
||||||
|
else
|
||||||
|
rm -f "$CACHE_FILE.tmp"
|
||||||
|
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [ -f "$CACHE_FILE" ]; then
|
||||||
|
SUB_JSON=$(cat "$CACHE_FILE")
|
||||||
|
${lib.optionalString (routingMark != null) ''
|
||||||
|
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
|
||||||
|
''}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
|
||||||
|
mkOutboundScript =
|
||||||
|
routingMark:
|
||||||
|
let
|
||||||
|
outboundBlocks =
|
||||||
|
if singBoxCfg.selection == "first" && singBoxCfg.outbounds != [ ] then
|
||||||
|
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
|
||||||
|
mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy"
|
||||||
|
else
|
||||||
|
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds;
|
||||||
|
|
||||||
|
subscriptionBlocks =
|
||||||
|
lib.concatMapStrings (sub: mkSubscriptionBlock sub routingMark) singBoxCfg.subscriptions;
|
||||||
|
|
||||||
|
wrapperBlock =
|
||||||
|
if singBoxCfg.selection == "first" then
|
||||||
|
# When there are no static outbounds, subscription outbounds keep their
|
||||||
|
# real tags. Rename the first one to "proxy" so routing rules resolve.
|
||||||
|
lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.subscriptions != [ ]) ''
|
||||||
|
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
|
||||||
|
if [ -n "$FIRST_TAG" ]; then
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
|
||||||
|
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
|
||||||
|
fi
|
||||||
|
''
|
||||||
|
else if singBoxCfg.selection == "selector" then
|
||||||
|
''
|
||||||
|
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
|
||||||
|
WRAPPER=$(${jq} -n \
|
||||||
|
--argjson tags "$TAGS" \
|
||||||
|
--arg default "$FIRST" \
|
||||||
|
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||||
|
''
|
||||||
|
else
|
||||||
|
# urltest
|
||||||
|
''
|
||||||
|
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||||
|
WRAPPER=$(${jq} -n \
|
||||||
|
--argjson tags "$TAGS" \
|
||||||
|
--arg url ${lib.escapeShellArg singBoxCfg.urlTest.url} \
|
||||||
|
--arg interval ${lib.escapeShellArg singBoxCfg.urlTest.interval} \
|
||||||
|
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||||
|
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
|
||||||
|
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||||
|
'';
|
||||||
|
in
|
||||||
|
outboundBlocks + subscriptionBlocks + wrapperBlock;
|
||||||
|
|
||||||
|
mkStartScript =
|
||||||
|
{
|
||||||
|
name,
|
||||||
|
runtimeDir,
|
||||||
|
configFile,
|
||||||
|
routingMark ? null,
|
||||||
|
}:
|
||||||
|
pkgs.writeShellScript name ''
|
||||||
|
set -euo pipefail
|
||||||
|
RUNTIME_DIR="${runtimeDir}"
|
||||||
|
mkdir -p "$RUNTIME_DIR"
|
||||||
|
OUTBOUNDS_JSON='[]'
|
||||||
|
|
||||||
|
${mkOutboundScript routingMark}
|
||||||
|
|
||||||
|
${jq} --argjson obs "$OUTBOUNDS_JSON" \
|
||||||
|
'.outbounds = $obs + .outbounds' \
|
||||||
|
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||||
|
|
||||||
|
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||||
|
'';
|
||||||
|
|
||||||
|
startSocks = mkStartScript {
|
||||||
|
name = "proxy-suite-start-socks";
|
||||||
|
runtimeDir = "/run/proxy-suite-socks";
|
||||||
|
configFile = tproxyFile;
|
||||||
|
routingMark = singBoxCfg.proxyMark;
|
||||||
|
};
|
||||||
|
|
||||||
|
startTun = mkStartScript {
|
||||||
|
name = "proxy-suite-start-tun";
|
||||||
|
runtimeDir = "/run/proxy-suite-tun";
|
||||||
|
configFile = tunFile;
|
||||||
|
routingMark = null;
|
||||||
|
};
|
||||||
|
|
||||||
|
startAppTun = mkStartScript {
|
||||||
|
name = "proxy-suite-start-app-tun";
|
||||||
|
runtimeDir = "/run/proxy-suite-app-tun";
|
||||||
|
configFile = appTunFile;
|
||||||
|
# Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN
|
||||||
|
# proxy outbounds with a host-global mark.
|
||||||
|
routingMark = if singBoxCfg.tproxy.enable then singBoxCfg.proxyMark else null;
|
||||||
|
};
|
||||||
|
|
||||||
|
# Shell code to fetch a single subscription into the cache (used in update service).
|
||||||
|
mkSubscriptionFetchBlock =
|
||||||
|
sub:
|
||||||
|
''
|
||||||
|
if ${mkSubscriptionFetchCommand sub} > "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"; then
|
||||||
|
mv "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp" \
|
||||||
|
"$CACHE_DIR/${lib.escapeShellArg sub.tag}.json"
|
||||||
|
echo "Updated subscription: ${sub.tag}"
|
||||||
|
else
|
||||||
|
rm -f "$CACHE_DIR/${lib.escapeShellArg sub.tag}.json.tmp"
|
||||||
|
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
|
||||||
|
FAILED=1
|
||||||
|
fi
|
||||||
|
'';
|
||||||
|
|
||||||
|
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
|
||||||
|
set -euo pipefail
|
||||||
|
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||||
|
mkdir -p "$CACHE_DIR"
|
||||||
|
FAILED=0
|
||||||
|
|
||||||
|
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions}
|
||||||
|
|
||||||
|
if [ "$FAILED" -eq 0 ]; then
|
||||||
|
systemctl restart proxy-suite-socks
|
||||||
|
systemctl is-active --quiet proxy-suite-tun && systemctl restart proxy-suite-tun || true
|
||||||
|
fi
|
||||||
|
exit "$FAILED"
|
||||||
|
'';
|
||||||
|
|
||||||
|
hasSubscriptions = singBoxCfg.subscriptions != [ ];
|
||||||
|
subscriptionTagsList = lib.concatStringsSep " " (map (sub: lib.escapeShellArg sub.tag) singBoxCfg.subscriptions);
|
||||||
|
in
|
||||||
|
{
|
||||||
|
inherit startSocks startTun startAppTun;
|
||||||
|
inherit subscriptionUpdateScript hasSubscriptions subscriptionTagsList;
|
||||||
|
}
|
||||||
@@ -9,8 +9,8 @@
|
|||||||
}:
|
}:
|
||||||
|
|
||||||
let
|
let
|
||||||
z = cfg.zapret;
|
zapretCfg = cfg.zapret;
|
||||||
arz = cfg.appRouting.backends.zapret;
|
appRoutingZapret = cfg.appRouting.backends.zapret;
|
||||||
|
|
||||||
iptables = "${pkgs.iptables}/bin/iptables";
|
iptables = "${pkgs.iptables}/bin/iptables";
|
||||||
|
|
||||||
@@ -33,7 +33,7 @@ let
|
|||||||
;
|
;
|
||||||
};
|
};
|
||||||
|
|
||||||
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
|
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
|
||||||
|
|
||||||
baseZapretPackage =
|
baseZapretPackage =
|
||||||
let
|
let
|
||||||
@@ -47,25 +47,25 @@ let
|
|||||||
else
|
else
|
||||||
null;
|
null;
|
||||||
|
|
||||||
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" z.listGeneral;
|
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
|
||||||
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" z.listExclude;
|
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
|
||||||
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" z.ipsetAll;
|
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
|
||||||
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" z.ipsetExclude;
|
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
|
||||||
|
|
||||||
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
|
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
|
||||||
builtins.toJSON {
|
builtins.toJSON {
|
||||||
includeExtraUpstreamLists = z.includeExtraUpstreamLists;
|
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
|
||||||
entries = map (rule: {
|
entries = map (rule: {
|
||||||
inherit (rule)
|
inherit (rule)
|
||||||
name
|
name
|
||||||
preset
|
preset
|
||||||
nfqwsArgs
|
nfqwsArgs
|
||||||
;
|
;
|
||||||
}) z.hostlistRules;
|
}) zapretCfg.hostlistRules;
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
selectedConfigName = lib.strings.sanitizeDerivationName z.configName;
|
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
|
||||||
patchConfigScriptSrc = builtins.path {
|
patchConfigScriptSrc = builtins.path {
|
||||||
path = ../../scripts/patch-zapret-config.py;
|
path = ../../scripts/patch-zapret-config.py;
|
||||||
name = "patch-zapret-config.py";
|
name = "patch-zapret-config.py";
|
||||||
@@ -87,8 +87,8 @@ let
|
|||||||
{
|
{
|
||||||
packageName,
|
packageName,
|
||||||
pidDir,
|
pidDir,
|
||||||
configName ? z.configName,
|
configName ? zapretCfg.configName,
|
||||||
gameFilter ? z.gameFilter,
|
gameFilter ? zapretCfg.gameFilter,
|
||||||
forceDisableFilterMark ? false,
|
forceDisableFilterMark ? false,
|
||||||
filterMark ? null,
|
filterMark ? null,
|
||||||
qnum ? null,
|
qnum ? null,
|
||||||
@@ -187,7 +187,7 @@ let
|
|||||||
''
|
''
|
||||||
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
|
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
|
||||||
''
|
''
|
||||||
) z.hostlistRules}
|
) zapretCfg.hostlistRules}
|
||||||
|
|
||||||
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
|
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
|
||||||
|
|
||||||
@@ -226,17 +226,17 @@ let
|
|||||||
globalZapretPackage = mkDerivedZapretPackage {
|
globalZapretPackage = mkDerivedZapretPackage {
|
||||||
packageName = "proxy-suite-zapret-${selectedConfigName}";
|
packageName = "proxy-suite-zapret-${selectedConfigName}";
|
||||||
pidDir = "/run/proxy-suite-zapret";
|
pidDir = "/run/proxy-suite-zapret";
|
||||||
gameFilter = z.gameFilter;
|
gameFilter = zapretCfg.gameFilter;
|
||||||
forceDisableFilterMark = true;
|
forceDisableFilterMark = true;
|
||||||
customScript = if arz.enable then mkGlobalBypassScript (toString arz.filterMark) else null;
|
customScript = if appRoutingZapret.enable then mkGlobalBypassScript (toString appRoutingZapret.filterMark) else null;
|
||||||
};
|
};
|
||||||
|
|
||||||
appZapretPackage = mkDerivedZapretPackage {
|
appZapretPackage = mkDerivedZapretPackage {
|
||||||
packageName = "proxy-suite-app-zapret-${selectedConfigName}";
|
packageName = "proxy-suite-app-zapret-${selectedConfigName}";
|
||||||
pidDir = "/run/proxy-suite-app-zapret";
|
pidDir = "/run/proxy-suite-app-zapret";
|
||||||
gameFilter = "all";
|
gameFilter = "all";
|
||||||
filterMark = arz.filterMark;
|
filterMark = appRoutingZapret.filterMark;
|
||||||
qnum = arz.qnum;
|
qnum = appRoutingZapret.qnum;
|
||||||
modeFilter = "none";
|
modeFilter = "none";
|
||||||
desyncMark = 134217728;
|
desyncMark = 134217728;
|
||||||
desyncMarkPostnat = 67108864;
|
desyncMarkPostnat = 67108864;
|
||||||
@@ -279,12 +279,12 @@ let
|
|||||||
exemptStart = lib.concatMapStrings (cidr: ''
|
exemptStart = lib.concatMapStrings (cidr: ''
|
||||||
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
||||||
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
||||||
'') z.cidrExemption.cidrs;
|
'') zapretCfg.cidrExemption.cidrs;
|
||||||
|
|
||||||
exemptStop = lib.concatMapStrings (cidr: ''
|
exemptStop = lib.concatMapStrings (cidr: ''
|
||||||
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
|
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
|
||||||
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
|
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
|
||||||
'') z.cidrExemption.cidrs;
|
'') zapretCfg.cidrExemption.cidrs;
|
||||||
in
|
in
|
||||||
{
|
{
|
||||||
assertions = [
|
assertions = [
|
||||||
@@ -293,18 +293,18 @@ in
|
|||||||
message = "proxy-suite: zapret.hostlistRules names must be unique";
|
message = "proxy-suite: zapret.hostlistRules names must be unique";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = builtins.all (rule: rule.domains != [ ]) z.hostlistRules;
|
assertion = builtins.all (rule: rule.domains != [ ]) zapretCfg.hostlistRules;
|
||||||
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
|
message = "proxy-suite: each zapret.hostlistRules entry must define at least one domain";
|
||||||
}
|
}
|
||||||
{
|
{
|
||||||
assertion = builtins.all (rule: rule.preset != null || rule.nfqwsArgs != [ ]) z.hostlistRules;
|
assertion = builtins.all (rule: rule.preset != null || 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, nfqwsArgs, or both";
|
||||||
}
|
}
|
||||||
];
|
];
|
||||||
|
|
||||||
environment.systemPackages =
|
environment.systemPackages =
|
||||||
lib.mkBefore (
|
lib.mkBefore (
|
||||||
[ globalZapretPackage ] ++ lib.optionals arz.enable [ appZapretPackage ]
|
[ globalZapretPackage ] ++ lib.optionals appRoutingZapret.enable [ appZapretPackage ]
|
||||||
);
|
);
|
||||||
|
|
||||||
systemd.services.zapret-discord-youtube = {
|
systemd.services.zapret-discord-youtube = {
|
||||||
@@ -323,7 +323,7 @@ in
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
systemd.services.proxy-suite-app-zapret = lib.mkIf arz.enable {
|
systemd.services.proxy-suite-app-zapret = lib.mkIf appRoutingZapret.enable {
|
||||||
description = "proxy-suite app-routing zapret backend";
|
description = "proxy-suite app-routing zapret backend";
|
||||||
after = [ "network.target" ];
|
after = [ "network.target" ];
|
||||||
conflicts = [
|
conflicts = [
|
||||||
@@ -343,7 +343,7 @@ in
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf z.cidrExemption.enable {
|
systemd.services.proxy-suite-zapret-vm-exempt = lib.mkIf zapretCfg.cidrExemption.enable {
|
||||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||||
after = [ "zapret-discord-youtube.service" ];
|
after = [ "zapret-discord-youtube.service" ];
|
||||||
wants = [ "zapret-discord-youtube.service" ];
|
wants = [ "zapret-discord-youtube.service" ];
|
||||||
|
|||||||
@@ -12,38 +12,24 @@ BUILTIN_ACTIVATION_FALLBACKS = {
|
|||||||
"list-twitter.txt": "general",
|
"list-twitter.txt": "general",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
def _hostlist_remove_pattern(stem: str) -> str:
|
||||||
|
escaped = re.escape(stem)
|
||||||
|
return rf'\s+--hostlist=(?:"[^"]*/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],
|
||||||
|
"remove": [_hostlist_remove_pattern(f"list-{s}") for s in remove_stems],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
FAMILY_PATTERNS = {
|
FAMILY_PATTERNS = {
|
||||||
"general": {
|
"general": _mk_family(["general", "general-user"], ["general", "general-user"]),
|
||||||
"match": ["list-general.txt", "list-general-user.txt"],
|
"google": _mk_family(["google"], ["google"]),
|
||||||
"remove": [
|
"instagram": _mk_family(["instagram"], ["instagram"]),
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general\.txt"|[^ ]*/hostlists/list-general\.txt)',
|
"soundcloud": _mk_family(["soundcloud"], ["soundcloud"]),
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-general-user\.txt"|[^ ]*/hostlists/list-general-user\.txt)',
|
"twitter": _mk_family(["twitter"], ["twitter"]),
|
||||||
],
|
|
||||||
},
|
|
||||||
"google": {
|
|
||||||
"match": ["list-google.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-google\.txt"|[^ ]*/hostlists/list-google\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"instagram": {
|
|
||||||
"match": ["list-instagram.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-instagram\.txt"|[^ ]*/hostlists/list-instagram\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"soundcloud": {
|
|
||||||
"match": ["list-soundcloud.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-soundcloud\.txt"|[^ ]*/hostlists/list-soundcloud\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
"twitter": {
|
|
||||||
"match": ["list-twitter.txt"],
|
|
||||||
"remove": [
|
|
||||||
r'\s+--hostlist=(?:"[^"]*/hostlists/list-twitter\.txt"|[^ ]*/hostlists/list-twitter\.txt)',
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -78,19 +64,32 @@ def add_standard_excludes(line: str, standard_excludes: list[str]) -> str:
|
|||||||
return line
|
return line
|
||||||
|
|
||||||
|
|
||||||
|
def _render_args(
|
||||||
|
line: str,
|
||||||
|
hostlist_path: str,
|
||||||
|
standard_excludes: list[str],
|
||||||
|
*,
|
||||||
|
preset_family: str | None = None,
|
||||||
|
) -> str:
|
||||||
|
rendered = strip_trailing_new(line)
|
||||||
|
if preset_family is not None:
|
||||||
|
for pattern in FAMILY_PATTERNS[preset_family]["remove"]:
|
||||||
|
rendered = re.sub(pattern, "", rendered)
|
||||||
|
else:
|
||||||
|
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\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_preset_clone(
|
def render_preset_clone(
|
||||||
line: str,
|
line: str,
|
||||||
family: str,
|
family: str,
|
||||||
hostlist_path: str,
|
hostlist_path: str,
|
||||||
standard_excludes: list[str],
|
standard_excludes: list[str],
|
||||||
) -> str:
|
) -> str:
|
||||||
rendered = strip_trailing_new(line)
|
return _render_args(line, hostlist_path, standard_excludes, preset_family=family)
|
||||||
for pattern in FAMILY_PATTERNS[family]["remove"]:
|
|
||||||
rendered = re.sub(pattern, "", 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_custom_args(
|
def render_custom_args(
|
||||||
@@ -98,12 +97,7 @@ def render_custom_args(
|
|||||||
hostlist_path: str,
|
hostlist_path: str,
|
||||||
standard_excludes: list[str],
|
standard_excludes: list[str],
|
||||||
) -> str:
|
) -> str:
|
||||||
rendered = strip_trailing_new(fragment)
|
return _render_args(fragment, hostlist_path, standard_excludes)
|
||||||
rendered = re.sub(r'\s+--hostlist=(?:"[^"]+"|\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 clone_family_lines(
|
def clone_family_lines(
|
||||||
|
|||||||
@@ -47,6 +47,22 @@ def _mk_transport(
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_tls(server_name: str, fp: "str | None" = None, alpn: "str | None" = None) -> dict:
|
||||||
|
tls: dict = {"enabled": True, "server_name": server_name}
|
||||||
|
if fp:
|
||||||
|
tls["utls"] = {"enabled": True, "fingerprint": fp}
|
||||||
|
if alpn:
|
||||||
|
tls["alpn"] = alpn.split(",")
|
||||||
|
return tls
|
||||||
|
|
||||||
|
|
||||||
|
def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||||
|
if userinfo and ":" in userinfo:
|
||||||
|
username, _, password = userinfo.partition(":")
|
||||||
|
return urllib.parse.unquote(username), urllib.parse.unquote(password)
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
|
||||||
def parse_vless(url: str, tag: str) -> dict:
|
def parse_vless(url: str, tag: str) -> dict:
|
||||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||||
security = params.get("security", "none")
|
security = params.get("security", "none")
|
||||||
@@ -62,25 +78,14 @@ def parse_vless(url: str, tag: str) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
if security == "reality":
|
if security == "reality":
|
||||||
ob["tls"] = {
|
ob["tls"] = _mk_tls(params.get("sni", host), fp=params.get("fp", "chrome"))
|
||||||
|
ob["tls"]["reality"] = {
|
||||||
"enabled": True,
|
"enabled": True,
|
||||||
"server_name": params.get("sni", host),
|
"public_key": params["pbk"],
|
||||||
"utls": {"enabled": True, "fingerprint": params.get("fp", "chrome")},
|
"short_id": params.get("sid", ""),
|
||||||
"reality": {
|
|
||||||
"enabled": True,
|
|
||||||
"public_key": params["pbk"],
|
|
||||||
"short_id": params.get("sid", ""),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
elif security == "tls":
|
elif security == "tls":
|
||||||
ob["tls"] = {
|
ob["tls"] = _mk_tls(params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn"))
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
}
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
tr = _mk_transport(
|
tr = _mk_transport(
|
||||||
transport,
|
transport,
|
||||||
@@ -123,11 +128,11 @@ def parse_vmess(url: str, tag: str) -> dict:
|
|||||||
}
|
}
|
||||||
|
|
||||||
if tls_field in ("tls", "reality"):
|
if tls_field in ("tls", "reality"):
|
||||||
ob["tls"] = {"enabled": True, "server_name": sni}
|
ob["tls"] = _mk_tls(
|
||||||
if data.get("fp"):
|
sni,
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": str(data["fp"])}
|
fp=str(data["fp"]) if data.get("fp") else None,
|
||||||
if data.get("alpn"):
|
alpn=str(data["alpn"]) if data.get("alpn") else None,
|
||||||
ob["tls"]["alpn"] = str(data["alpn"]).split(",")
|
)
|
||||||
|
|
||||||
path = str(data.get("path") or "/")
|
path = str(data.get("path") or "/")
|
||||||
h_host = str(data.get("host") or host)
|
h_host = str(data.get("host") or host)
|
||||||
@@ -154,17 +159,9 @@ def parse_trojan(url: str, tag: str) -> dict:
|
|||||||
"server": host,
|
"server": host,
|
||||||
"server_port": int(port),
|
"server_port": int(port),
|
||||||
"password": urllib.parse.unquote(userinfo),
|
"password": urllib.parse.unquote(userinfo),
|
||||||
"tls": {
|
"tls": _mk_tls(params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")),
|
||||||
"enabled": True,
|
|
||||||
"server_name": params.get("sni", host),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if params.get("fp"):
|
|
||||||
ob["tls"]["utls"] = {"enabled": True, "fingerprint": params["fp"]}
|
|
||||||
if params.get("alpn"):
|
|
||||||
ob["tls"]["alpn"] = params["alpn"].split(",")
|
|
||||||
|
|
||||||
tr = _mk_transport(
|
tr = _mk_transport(
|
||||||
transport,
|
transport,
|
||||||
path=params.get("path", "/"),
|
path=params.get("path", "/"),
|
||||||
@@ -256,10 +253,10 @@ def parse_socks(url: str, tag: str) -> dict:
|
|||||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||||
|
|
||||||
ob: dict = {"type": "socks", "tag": tag, "version": version}
|
ob: dict = {"type": "socks", "tag": tag, "version": version}
|
||||||
if userinfo and ":" in userinfo:
|
username, password = _mk_auth(userinfo)
|
||||||
username, _, password = userinfo.partition(":")
|
if username is not None:
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
ob["username"] = username
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
ob["password"] = password
|
||||||
ob["server"] = host
|
ob["server"] = host
|
||||||
ob["server_port"] = int(port)
|
ob["server_port"] = int(port)
|
||||||
|
|
||||||
@@ -271,10 +268,10 @@ def parse_http_proxy(url: str, tag: str) -> dict:
|
|||||||
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
userinfo, host, port, _ = _parse_url_parts(url, scheme)
|
||||||
|
|
||||||
ob: dict = {"type": "http", "tag": tag}
|
ob: dict = {"type": "http", "tag": tag}
|
||||||
if userinfo and ":" in userinfo:
|
username, password = _mk_auth(userinfo)
|
||||||
username, _, password = userinfo.partition(":")
|
if username is not None:
|
||||||
ob["username"] = urllib.parse.unquote(username)
|
ob["username"] = username
|
||||||
ob["password"] = urllib.parse.unquote(password)
|
ob["password"] = password
|
||||||
ob["server"] = host
|
ob["server"] = host
|
||||||
ob["server_port"] = int(port)
|
ob["server_port"] = int(port)
|
||||||
|
|
||||||
|
|||||||
Reference in new issue
Block a user