chore: refactoring (split)

This commit is contained in:
FUFSoB committed 2026-07-11 10:54:37 +05:00
1 parent 835651c460
commit e54c9463dd
84 files changed
+9149 -7244

No files matched your search

@@ -0,0 +1,195 @@
# Build-time sing-box backend configuration templates.
# Proxy outbounds are injected at service start time, not here.
{
lib,
derived,
rules,
}:
let
constants = derived.constants;
inherit (derived)
proxyCfg
singBoxCfg
hybridEnabled
globalTun
globalTproxy
clashApiEnabled
perAppRoutingTun
;
inherit (constants)
xrayDnsBridgePorts
;
direct = rules.direct;
defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex;
defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority;
mkDnsServer =
tag: upstream: detour:
{
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.port;
}
// lib.optionalAttrs (detour != null) { inherit detour; };
mkDnsConfig =
{
localDetour ? null,
}:
{
servers = [
(mkDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkDnsServer "local" proxyCfg.dns.local localDetour)
];
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if proxyCfg.proxyByDefault then "remote" else "local";
};
xrayDnsBridgeHijackRule = {
inbound = [ "xray-dns-in" ];
network = [
"tcp"
"udp"
];
action = "hijack-dns";
};
clashApiBlock = lib.optionalAttrs clashApiEnabled {
experimental.clash_api.external_controller =
"127.0.0.1:${toString singBoxCfg.clashApiPort}";
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu,
tunAutoRoute ? true,
tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex,
tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}:
{
log.level = "warn";
dns = mkDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listenAddress;
listen_port = proxyCfg.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock;
in
{
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
tun = mkConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunMtu = globalTun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = false;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
};
perAppTun = mkConfig {
enableTun = true;
tunInterface = perAppRoutingTun.interface;
tunAddress = perAppRoutingTun.address;
tunMtu = perAppRoutingTun.mtu;
tunAutoRoute = false;
tunAutoRedirect = false;
tunStrictRoute = false;
forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
}
@@ -0,0 +1,284 @@
# Build-time XRay backend configuration templates.
# Proxy outbounds are injected at service start time, not here.
{
lib,
derived,
rules,
}:
let
constants = derived.constants;
inherit (derived)
proxyCfg
globalTun
globalTproxy
perAppRoutingTun
;
inherit (constants)
xrayGlobalTunIPv6Address
xrayPerAppTunIPv6Address
;
fakeDnsPools = [
{
ipPool = "198.18.0.0/15";
poolSize = 32768;
}
{
ipPool = "fc00::/18";
poolSize = 32768;
}
];
dnsAddress =
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
mkDnsServer = tag: upstream: {
address = dnsAddress upstream;
inherit tag;
port = upstream.port;
queryStrategy = "UseIP";
};
mkTunDnsConfig =
{
preferRemote ? proxyCfg.proxyByDefault,
}:
let
primaryTag = if preferRemote then "remote" else "local";
secondaryTag = if preferRemote then "local" else "remote";
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
in
{
queryStrategy = "UseIP";
tag = "dns-in";
servers = [
{
address = "fakedns";
tag = "fakedns";
}
(mkDnsServer primaryTag primaryUpstream)
(mkDnsServer secondaryTag secondaryUpstream)
];
};
mkSniffing =
{
fakeDnsOnly ? false,
}:
if fakeDnsOnly then
{
enabled = true;
destOverride = [ "fakedns" ];
metadataOnly = true;
}
else
{
enabled = true;
destOverride = [
"http"
"tls"
"quic"
];
};
standardSniffing = mkSniffing { };
tunDnsHijackRule = {
type = "field";
inboundTag = [ "tun-in" ];
network = "tcp,udp";
port = 53;
outboundTag = "dns-out";
ruleTag = "dns-hijack";
};
tunDnsUpstreamRule = {
type = "field";
inboundTag = [ "dns-in" ];
network = "tcp,udp";
outboundTag = "direct";
ruleTag = "dns-upstream-direct";
};
finalRule =
tag:
{
type = "field";
network = "tcp,udp";
ruleTag = "final-default";
}
// (
if tag == "proxy" && proxyCfg.selection == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; }
);
directOutbound =
useOutboundRoutingMark:
{
protocol = "freedom";
tag = "direct";
settings = { };
}
// lib.optionalAttrs useOutboundRoutingMark {
streamSettings.sockopt.mark = globalTproxy.proxyMark;
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunIPv6Address ? null,
tunMtu ? globalTun.mtu,
useOutboundRoutingMark ? false,
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
enableTunFakeDns ? false,
}:
let
tunDnsServers = [
(if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
];
tunSniffing = mkSniffing { fakeDnsOnly = enableTunFakeDns; };
dnsConfig =
if enableTunFakeDns then
mkTunDnsConfig { }
else
{
servers = [
(mkDnsServer "remote" proxyCfg.dns.remote)
(mkDnsServer "local" proxyCfg.dns.local)
];
};
tunOutbounds = lib.optionals enableTunFakeDns [
{
protocol = "dns";
tag = "dns-out";
settings = {
userLevel = 0;
rules = [
{
action = "direct";
qType = "2-27,29-65535";
}
];
};
}
];
routingRules =
lib.optionals enableTunFakeDns [
tunDnsUpstreamRule
tunDnsHijackRule
]
++ rules.xrayRoutingRules
++ [ (finalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
dns = dnsConfig;
inbounds =
lib.optional enableMixed {
tag = "mixed-in";
protocol = "socks";
listen = proxyCfg.listenAddress;
port = proxyCfg.port;
settings = {
auth = "noauth";
udp = true;
ip = proxyCfg.listenAddress;
};
sniffing = standardSniffing;
}
++ lib.optional enableTProxy {
tag = "tproxy-in";
protocol = "tunnel";
listen = "127.0.0.1";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = standardSniffing;
}
++ lib.optional enableTun {
tag = "tun-in";
protocol = "tun";
settings = {
name = tunInterface;
mtu = tunMtu;
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
dns = tunDnsServers;
userLevel = 0;
autoOutboundsInterface = "auto";
};
sniffing = tunSniffing;
};
outbounds = tunOutbounds ++ [
(directOutbound useOutboundRoutingMark)
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
domainStrategy = domainStrategy;
domainMatcher = "hybrid";
rules = routingRules;
}
// lib.optionalAttrs enableUrlTest {
balancers = [
{
tag = "proxy";
selector = [ "proxy-suite-ob-" ];
strategy = {
type = "leastPing";
};
}
];
};
}
// lib.optionalAttrs enableUrlTest {
observatory = {
subjectSelector = [ "proxy-suite-ob-" ];
probeUrl = proxyCfg.urlTest.url;
probeInterval = proxyCfg.urlTest.interval;
};
}
// lib.optionalAttrs enableTunFakeDns { fakedns = fakeDnsPools; };
in
{
tproxy = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
};
tun = mkConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunIPv6Address = xrayGlobalTunIPv6Address;
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
perAppTun = mkConfig {
enableTun = true;
tunInterface = perAppRoutingTun.interface;
tunAddress = perAppRoutingTun.address;
tunIPv6Address = xrayPerAppTunIPv6Address;
tunMtu = perAppRoutingTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
}
+23 -464
View File
@@ -9,478 +9,37 @@
let
derived = import ./derived.nix { inherit lib cfg; };
constants = derived.constants;
inherit (derived)
proxyCfg
singBoxCfg
xrayEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
clashApiEnabled
;
inherit (constants)
xrayGlobalTunIPv6Address
xrayPerAppTunIPv6Address
xrayDnsBridgePorts
;
perAppTun = derived.perAppRoutingTun;
direct = rules.direct;
defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex;
defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority;
xrayFakeDnsPools = [
{
ipPool = "198.18.0.0/15";
poolSize = 32768;
}
{
ipPool = "fc00::/18";
poolSize = 32768;
}
];
stripCidr = cidr: builtins.head (lib.splitString "/" cidr);
mkSingBoxDnsServer =
tag: upstream: detour:
{
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.port;
}
// lib.optionalAttrs (detour != null) { inherit detour; };
mkSingBoxDnsConfig =
{
localDetour ? null,
}:
{
servers = [
(mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy")
(mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour)
];
rules =
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if proxyCfg.proxyByDefault then "remote" else "local";
};
xrayDnsBridgeHijackRule = {
inbound = [ "xray-dns-in" ];
network = [
"tcp"
"udp"
];
action = "hijack-dns";
singBoxTemplates = import ./config-templates/sing-box.nix {
inherit
lib
derived
rules
;
};
xrayTemplates = import ./config-templates/xray.nix {
inherit
lib
derived
rules
;
};
clashApiBlock = lib.optionalAttrs clashApiEnabled {
experimental = {
clash_api = {
external_controller = "127.0.0.1:${toString singBoxCfg.clashApiPort}";
};
};
};
selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates;
routeModeRules =
if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
mkSingBoxConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu,
tunAutoRoute ? true,
tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex,
tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}:
{
log.level = "warn";
dns = mkSingBoxDnsConfig {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableXrayDnsBridge {
type = "direct";
tag = "xray-dns-in";
listen = "127.0.0.1";
listen_port = xrayDnsBridgePort;
}
++ lib.optional enableMixed {
type = "mixed";
tag = "mixed-in";
listen = proxyCfg.listenAddress;
listen_port = proxyCfg.port;
}
++ lib.optional enableTProxy {
type = "tproxy";
tag = "tproxy-in";
listen = "127.0.0.1";
listen_port = globalTproxy.port;
}
++ lib.optional enableTun (
{
type = "tun";
tag = "tun-in";
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
outbounds = [
(
{
type = "direct";
tag = "direct";
}
// lib.optionalAttrs useOutboundRoutingMark { routing_mark = globalTproxy.proxyMark; }
)
{
type = "block";
tag = "block";
}
];
route = {
default_domain_resolver = "local";
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs (enableTun && tunAutoRoute) {
auto_detect_interface = true;
};
}
// lib.optionalAttrs enableClashApi clashApiBlock;
xrayDnsAddress =
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
mkXrayDnsServer = tag: upstream: {
address = xrayDnsAddress upstream;
inherit tag;
port = upstream.port;
queryStrategy = "UseIP";
};
mkXraySniffing =
{
fakeDnsOnly ? false,
}:
if fakeDnsOnly then
{
enabled = true;
destOverride = [ "fakedns" ];
metadataOnly = true;
}
else
{
enabled = true;
destOverride = [
"http"
"tls"
"quic"
];
};
xraySniffing = mkXraySniffing { };
mkXrayTunDnsConfig =
{
preferRemote ? proxyCfg.proxyByDefault,
}:
let
primaryTag = if preferRemote then "remote" else "local";
secondaryTag = if preferRemote then "local" else "remote";
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
in
{
queryStrategy = "UseIP";
tag = "dns-in";
servers = [
{
address = "fakedns";
tag = "fakedns";
}
(mkXrayDnsServer primaryTag primaryUpstream)
(mkXrayDnsServer secondaryTag secondaryUpstream)
];
};
xrayTunDnsHijackRule = {
type = "field";
inboundTag = [ "tun-in" ];
network = "tcp,udp";
port = 53;
outboundTag = "dns-out";
ruleTag = "dns-hijack";
};
xrayTunDnsUpstreamRule = {
type = "field";
inboundTag = [ "dns-in" ];
network = "tcp,udp";
outboundTag = "direct";
ruleTag = "dns-upstream-direct";
};
xrayFinalRule =
tag:
{
type = "field";
network = "tcp,udp";
ruleTag = "final-default";
}
// (
if tag == "proxy" && proxyCfg.selection == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; }
);
xrayRouteRules = rules.xrayRoutingRules ++ [
(xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct"))
];
xrayDirectOutbound =
useOutboundRoutingMark:
{
protocol = "freedom";
tag = "direct";
settings = { };
}
// lib.optionalAttrs useOutboundRoutingMark {
streamSettings.sockopt.mark = globalTproxy.proxyMark;
};
mkXrayConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? globalTun.interface,
tunAddress ? globalTun.address,
tunIPv6Address ? null,
tunMtu ? globalTun.mtu,
useOutboundRoutingMark ? false,
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
enableTunFakeDns ? false,
}:
let
tunDnsServers = [
(if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
(if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
];
xrayTunSniffing = mkXraySniffing { fakeDnsOnly = enableTunFakeDns; };
xrayDnsConfig =
if enableTunFakeDns then
mkXrayTunDnsConfig { }
else
{
servers = [
(mkXrayDnsServer "remote" proxyCfg.dns.remote)
(mkXrayDnsServer "local" proxyCfg.dns.local)
];
};
xrayTunOutbounds = lib.optionals enableTunFakeDns [
{
protocol = "dns";
tag = "dns-out";
settings = {
userLevel = 0;
rules = [
{
action = "direct";
qType = "2-27,29-65535";
}
];
};
}
];
xrayRoutingRules =
lib.optionals enableTunFakeDns [
xrayTunDnsUpstreamRule
xrayTunDnsHijackRule
]
++ rules.xrayRoutingRules
++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
in
{
log.loglevel = "warning";
dns = xrayDnsConfig;
inbounds =
lib.optional enableMixed {
tag = "mixed-in";
protocol = "socks";
listen = proxyCfg.listenAddress;
port = proxyCfg.port;
settings = {
auth = "noauth";
udp = true;
ip = proxyCfg.listenAddress;
};
sniffing = xraySniffing;
}
++ lib.optional enableTProxy {
tag = "tproxy-in";
protocol = "tunnel";
listen = "127.0.0.1";
port = globalTproxy.port;
settings = {
allowedNetwork = "tcp,udp";
followRedirect = true;
};
streamSettings.sockopt.tproxy = "tproxy";
sniffing = xraySniffing;
}
++ lib.optional enableTun {
tag = "tun-in";
protocol = "tun";
settings = {
name = tunInterface;
mtu = tunMtu;
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
dns = tunDnsServers;
userLevel = 0;
autoOutboundsInterface = "auto";
};
sniffing = xrayTunSniffing;
};
outbounds = xrayTunOutbounds ++ [
(xrayDirectOutbound useOutboundRoutingMark)
{
protocol = "blackhole";
tag = "block";
settings = { };
}
];
routing = {
domainStrategy = domainStrategy;
domainMatcher = "hybrid";
rules = xrayRoutingRules;
}
// lib.optionalAttrs enableUrlTest {
balancers = [
{
tag = "proxy";
selector = [ "proxy-suite-ob-" ];
strategy = {
type = "leastPing";
};
}
];
};
}
// lib.optionalAttrs enableUrlTest {
observatory = {
subjectSelector = [ "proxy-suite-ob-" ];
probeUrl = proxyCfg.urlTest.url;
probeInterval = proxyCfg.urlTest.interval;
};
}
// lib.optionalAttrs enableTunFakeDns { fakedns = xrayFakeDnsPools; };
singBoxTproxyTemplate = mkSingBoxConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
singBoxTunTemplate = mkSingBoxConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunMtu = globalTun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = false;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
};
singBoxPerAppTunTemplate = mkSingBoxConfig {
enableTun = true;
tunInterface = perAppTun.interface;
tunAddress = perAppTun.address;
tunMtu = perAppTun.mtu;
tunAutoRoute = false;
tunAutoRedirect = false;
tunStrictRoute = false;
forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
xrayTproxyTemplate = mkXrayConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
};
xrayTunTemplate = mkXrayConfig {
enableTun = true;
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunIPv6Address = xrayGlobalTunIPv6Address;
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
xrayPerAppTunTemplate = mkXrayConfig {
enableTun = true;
tunInterface = perAppTun.interface;
tunAddress = perAppTun.address;
tunIPv6Address = xrayPerAppTunIPv6Address;
tunMtu = perAppTun.mtu;
useOutboundRoutingMark = true;
enableTunFakeDns = true;
};
tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate;
perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate;
routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (
builtins.toJSON selectedTemplates.tproxy
);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (
builtins.toJSON selectedTemplates.tun
);
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
builtins.toJSON perAppTunTemplate
builtins.toJSON selectedTemplates.perAppTun
);
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
builtins.toJSON routeModeRules
);
in
{
inherit
+14 -210
View File
@@ -1,13 +1,12 @@
# Top-level, userControl, tray, and tgWsProxy options.
# Miscellaneous top-level proxy-suite options.
{ lib, ... }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
options.services.proxy-suite = {
enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)";
tgWsProxyOptions = import ./other/tg-ws-proxy.nix { inherit lib; };
userControlOptions = {
userControl = {
group = mkOption {
type = types.strMatching "^[a-z_][a-z0-9_-]*$";
@@ -40,7 +39,9 @@ in
'';
};
};
};
trayOptions = {
tray = {
enable = mkEnableOption "system tray indicator for proxy-suite";
@@ -65,210 +66,13 @@ in
example = true;
};
};
tgWsProxy = {
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
port = mkOption {
type = types.port;
default = 1443;
description = ''
TCP listen port for tg-ws-proxy.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy.
'';
example = 1076;
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Bind address for tg-ws-proxy.
Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you
intentionally expose the proxy to other hosts.
'';
example = "127.0.0.1";
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
MTProto proxy secret (hex string). Legacy inline form; this value ends up
in the Nix store. Prefer secretFile for real deployments.
Set exactly one of secret or secretFile when tgWsProxy.enable = true.
Generate one with: openssl rand -hex 16
'';
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the MTProto proxy secret.
Intended for use with secret managers so the secret stays out of the Nix store.
Set exactly one of secretFile or secret when tgWsProxy.enable = true.
'';
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = ''
Mapping of Telegram DC IDs to relay IPs.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection.
'';
example = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
"203" = "149.154.167.220";
};
};
verbose = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable debug logging in tg-ws-proxy.
'';
example = true;
};
logFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Optional path where tg-ws-proxy writes rotating logs.
When unset, tg-ws-proxy logs to stderr only.
'';
example = "/var/log/tg-ws-proxy.log";
};
logMaxMb = mkOption {
type = types.numbers.positive;
default = 5.0;
description = ''
Maximum tg-ws-proxy log file size in MiB before rotation.
Only used when tgWsProxy.logFile is set.
'';
example = 10.0;
};
logBackups = mkOption {
type = types.ints.positive;
default = 1;
description = ''
Number of rotated tg-ws-proxy log files to keep.
Only used when tgWsProxy.logFile is set.
'';
example = 3;
};
bufKb = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = ''
Socket send and receive buffer size for tg-ws-proxy, in KiB.
'';
example = 512;
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = ''
WebSocket connection pool size per Telegram DC.
Set to 0 to disable connection pooling.
'';
example = 8;
};
cfProxyDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
User-defined Cloudflare-proxied domains used by tg-ws-proxy for
WebSocket fallback. Each entry is passed as a separate
--cfproxy-domain argument.
'';
example = [
"cdn.example.com"
"edge.example.net"
];
};
cfProxyWorkerDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback.
These are tried before other fallback methods.
'';
example = [ "worker.example.com" ];
};
cfProxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when
direct WebSocket routing is unavailable.
'';
example = false;
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = ''
Optional SNI domain used to enable tg-ws-proxy Fake TLS masking.
When set, tg-ws-proxy emits an ee-secret connection link.
'';
example = "www.example.com";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Whether tg-ws-proxy should accept a PROXY protocol v1 header from a
fronting reverse proxy such as nginx or HAProxy.
'';
example = true;
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = ''
Whether to keep tg-ws-proxy's own relay connections out of proxy-suite
transparent routing backends.
When enabled and global TUN or TProxy mode is configured, the
tg-ws-proxy systemd service receives a packet mark and an earlier
policy-routing rule back to the main table. This prevents global TUN
from routing the local Telegram MTProto relay through the proxy backend again,
which can otherwise break tg-ws-proxy after enabling TUN mode.
'';
example = true;
};
routingMark = mkOption {
type = types.int;
default = 4;
description = ''
Packet mark used by tgWsProxy.bypassTransparentProxy to bypass
proxy-suite transparent routing. Override this only if it collides
with another local policy-routing mark on your host.
'';
example = 4;
};
};
};
in
{
options.services.proxy-suite = {
enable = lib.mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)";
}
// userControlOptions
// trayOptions
// tgWsProxyOptions;
}
@@ -0,0 +1,212 @@
# Telegram MTProto WebSocket proxy options.
{ lib }:
let
inherit (lib) mkOption mkEnableOption types;
in
{
tgWsProxy = {
enable = mkEnableOption "Telegram MTProto WebSocket proxy";
port = mkOption {
type = types.port;
default = 1443;
description = ''
TCP listen port for tg-ws-proxy.
Telegram clients connect to this endpoint when using the local MTProto
WebSocket proxy.
'';
example = 1076;
};
host = mkOption {
type = types.str;
default = "127.0.0.1";
description = ''
Bind address for tg-ws-proxy.
Keep `127.0.0.1` for local-only usage; bind to `0.0.0.0` only when you
intentionally expose the proxy to other hosts.
'';
example = "127.0.0.1";
};
secret = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
MTProto proxy secret (hex string). Legacy inline form; this value ends up
in the Nix store. Prefer secretFile for real deployments.
Set exactly one of secret or secretFile when tgWsProxy.enable = true.
Generate one with: openssl rand -hex 16
'';
example = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
};
secretFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the MTProto proxy secret.
Intended for use with secret managers so the secret stays out of the Nix store.
Set exactly one of secretFile or secret when tgWsProxy.enable = true.
'';
example = "/run/secrets/tg-ws-proxy-secret";
};
dcIps = mkOption {
type = types.attrsOf types.str;
default = { };
description = ''
Mapping of Telegram DC IDs to relay IPs.
Keys are DC IDs as strings and values are IPv4/IPv6 addresses used by
tg-ws-proxy for MTProto relay selection.
'';
example = {
"2" = "149.154.167.220";
"4" = "149.154.167.220";
"203" = "149.154.167.220";
};
};
verbose = mkOption {
type = types.bool;
default = false;
description = ''
Whether to enable debug logging in tg-ws-proxy.
'';
example = true;
};
logFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Optional path where tg-ws-proxy writes rotating logs.
When unset, tg-ws-proxy logs to stderr only.
'';
example = "/var/log/tg-ws-proxy.log";
};
logMaxMb = mkOption {
type = types.numbers.positive;
default = 5.0;
description = ''
Maximum tg-ws-proxy log file size in MiB before rotation.
Only used when tgWsProxy.logFile is set.
'';
example = 10.0;
};
logBackups = mkOption {
type = types.ints.positive;
default = 1;
description = ''
Number of rotated tg-ws-proxy log files to keep.
Only used when tgWsProxy.logFile is set.
'';
example = 3;
};
bufKb = mkOption {
type = types.ints.between 4 2147483647;
default = 256;
description = ''
Socket send and receive buffer size for tg-ws-proxy, in KiB.
'';
example = 512;
};
poolSize = mkOption {
type = types.ints.unsigned;
default = 4;
description = ''
WebSocket connection pool size per Telegram DC.
Set to 0 to disable connection pooling.
'';
example = 8;
};
cfProxyDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
User-defined Cloudflare-proxied domains used by tg-ws-proxy for
WebSocket fallback. Each entry is passed as a separate
--cfproxy-domain argument.
'';
example = [
"cdn.example.com"
"edge.example.net"
];
};
cfProxyWorkerDomains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback.
These are tried before other fallback methods.
'';
example = [ "worker.example.com" ];
};
cfProxyFallback = mkOption {
type = types.bool;
default = true;
description = ''
Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when
direct WebSocket routing is unavailable.
'';
example = false;
};
fakeTlsDomain = mkOption {
type = types.nullOr (types.strMatching ".+");
default = null;
description = ''
Optional SNI domain used to enable tg-ws-proxy Fake TLS masking.
When set, tg-ws-proxy emits an ee-secret connection link.
'';
example = "www.example.com";
};
proxyProtocol = mkOption {
type = types.bool;
default = false;
description = ''
Whether tg-ws-proxy should accept a PROXY protocol v1 header from a
fronting reverse proxy such as nginx or HAProxy.
'';
example = true;
};
bypassTransparentProxy = mkOption {
type = types.bool;
default = true;
description = ''
Whether to keep tg-ws-proxy's own relay connections out of proxy-suite
transparent routing backends.
When enabled and global TUN or TProxy mode is configured, the
tg-ws-proxy systemd service receives a packet mark and an earlier
policy-routing rule back to the main table. This prevents global TUN
from routing the local Telegram MTProto relay through the proxy backend again,
which can otherwise break tg-ws-proxy after enabling TUN mode.
'';
example = true;
};
routingMark = mkOption {
type = types.int;
default = 4;
description = ''
Packet mark used by tgWsProxy.bypassTransparentProxy to bypass
proxy-suite transparent routing. Override this only if it collides
with another local policy-routing mark on your host.
'';
example = 4;
};
};
}
+9 -319
View File
@@ -4,7 +4,7 @@
let
inherit (lib) mkOption types;
# Shared routing-rule fields (reused in both outboundType.routing and routing.rules entries)
# Reused in both outboundType.routing and routing.rules entries.
routingFields = {
domains = mkOption {
type = types.listOf types.str;
@@ -53,7 +53,6 @@ let
};
};
# An explicit routing rule – associates traffic patterns with a named outbound.
routingRuleType = types.submodule {
options = {
outbound = mkOption {
@@ -73,167 +72,12 @@ let
// routingFields;
};
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
description = ''
Unique identifier for this subscription.
Used as a prefix for all outbound tags generated from its proxy list,
e.g. "my-sub" -> tags like "my-sub-Server-DE".
This value is also used as the subscription cache filename stem under
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
identifier.
'';
example = "community-list";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal subscription URL. The response must be a base64-encoded
newline-separated list of proxy URIs (standard v2rayN format) or
a plain-text list of the same.
This value is embedded in the Nix store. Prefer urlFile for private
subscription links or tokens.
'';
example = "https://example.com/sub/token123";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the subscription URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile or url for each subscription entry.
'';
example = "/run/secrets/proxy-subscription-url";
};
};
outboundTypes = import ./types/outbounds.nix {
inherit lib;
inherit routingFields;
};
outboundType = types.submodule {
options = {
tag = mkOption {
type = types.str;
description = ''
Outbound tag used in routing rules and multi-outbound selection.
With selection = "selector" or "urltest", each outbound keeps its own
tag and can be selected directly. With selection = "first", proxy-suite
routes through a single active outbound tagged "proxy", so individual
proxy tags are mainly useful for documentation and config structure.
'';
example = "vps-de";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the proxy URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
'';
example = "/run/secrets/my-proxy-url";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal proxy URL. Convenient for non-secret configs, but the URL
will end up in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
Prefer urlFile for real credentials.
'';
example = "hy2://password@example.com:443?sni=example.com";
};
backend = mkOption {
type = types.enum [
"auto"
"sing-box"
"xray"
];
default = "auto";
description = ''
Backend preference for this outbound when both SingBox and XRay are
enabled. "auto" uses SingBox when the URL or JSON can be represented
there and falls back to XRay for XRay-only transports such as XHTTP
or ECH. Ignored by single-backend configurations.
'';
example = "xray";
};
singBoxJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw sing-box outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field
is overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound.
Use this when the proxy definition is easier to generate as native Nix
than as a single URL string. Only valid with the SingBox backend.
'';
example = {
type = "vless";
server = "example.com";
server_port = 443;
uuid = "...";
};
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field is
overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound. Only valid with the XRay backend.
'';
example = {
protocol = "vless";
settings = {
address = "example.com";
port = 443;
id = "...";
encryption = "none";
};
};
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = ''
Deprecated alias for singBoxJson. Use singBoxJson instead.
'';
};
# Shorthand for attaching routing rules directly to an outbound definition.
# Traffic matching these patterns is sent to this specific outbound.
# Only meaningful when selection = "selector" or "urltest" (with "first",
# all proxy traffic goes to the single "proxy" outbound anyway).
routing = routingFields;
};
};
zapretTypes = import ./types/zapret.nix { inherit lib; };
dnsUpstreamType = types.submodule {
options = {
@@ -269,155 +113,6 @@ let
};
};
zapretPresetType = types.enum [
"general"
"google"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultDomainType = types.enum [
"general"
"google"
"discord"
"youtube"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultIpType = types.enum [
"all"
];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Custom hostlist name. Used to generate hostlists/list-<name>.txt
inside the derived zapret config directory.
'';
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains written into the generated custom zapret hostlist file.
Can be combined with defaultDomains.
'';
example = [
"example.com"
"example.de"
];
};
defaultDomains = mkOption {
type = types.listOf zapretDefaultDomainType;
default = [ ];
description = ''
Built-in domain groups copied from zapret-discord-youtube hostlists.
These are expanded and combined with domains.
Each value maps directly to the same-named upstream file:
"general" uses list-general.txt, "google" uses list-google.txt,
and the remaining values use their corresponding list-<name>.txt.
"discord" is an alias for "general"; "youtube" is an alias for
"google".
When "general" or "discord" is used together with configName, the
module also clones the selected config's Discord UDP voice rule
(--filter-l7=discord,stun).
When preset is unset, use one defaultDomains entry per rule so the
module can infer a single rule family. Split groups into separate
rules when they need different strategies.
'';
example = [ "google" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs or CIDRs written into the generated custom zapret ipset file.
Can be combined with defaultIps.
'';
example = [
"203.0.113.0/24"
"2001:db8::/32"
];
};
defaultIps = mkOption {
type = types.listOf zapretDefaultIpType;
default = [ ];
description = ''
Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets.
"all" uses the upstream ipset-all.txt list. The upstream bundle does
not split this list by service, so site-specific defaults remain in
defaultDomains.
'';
example = [ "all" ];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = ''
Clone this built-in NFQWS rule family for this hostlist. When
configName is set, the family is cloned from that zapret config;
otherwise it is cloned from the active global zapret config.
When unset and defaultDomains is non-empty, rule families are
inferred from defaultDomains.
'';
example = "google";
};
configName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
zapret config name to clone NFQWS rules from for this hostlist.
Names use the same matching rules as services.proxy-suite.zapret.configName.
This is a higher-level alternative to nfqwsArgs and cannot be used
together with nfqwsArgs.
'';
example = "general(ALT9)";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Additional NFQWS argument fragments for this hostlist.
The module injects --hostlist=... and trailing --new automatically.
This cannot be used together with configName.
'';
example = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
};
enableDirectSync = mkOption {
type = types.bool;
default = true;
description = ''
Whether this custom hostlist should also be mirrored into proxy
direct domain routing when zapret.syncDirectRouting = true.
'';
};
};
};
perAppRoutingProfileType = types.submodule {
options = {
name = mkOption {
@@ -459,19 +154,14 @@ let
};
};
};
in
{
inherit
dnsUpstreamType
perAppRoutingProfileType
routingFields
routingRuleType
subscriptionType
outboundType
dnsUpstreamType
zapretDefaultDomainType
zapretDefaultIpType
zapretPresetType
zapretHostlistRuleType
perAppRoutingProfileType
;
}
// outboundTypes
// zapretTypes
@@ -0,0 +1,171 @@
# Subscription and outbound option type definitions.
{ lib, routingFields }:
let
inherit (lib) mkOption types;
subscriptionType = types.submodule {
options = {
tag = mkOption {
type = types.strMatching "^[A-Za-z0-9][A-Za-z0-9._-]*$";
description = ''
Unique identifier for this subscription.
Used as a prefix for all outbound tags generated from its proxy list,
e.g. "my-sub" -> tags like "my-sub-Server-DE".
This value is also used as the subscription cache filename stem under
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
identifier.
'';
example = "community-list";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal subscription URL. The response must be a base64-encoded
newline-separated list of proxy URIs (standard v2rayN format) or
a plain-text list of the same.
This value is embedded in the Nix store. Prefer urlFile for private
subscription links or tokens.
'';
example = "https://example.com/sub/token123";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the subscription URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile or url for each subscription entry.
'';
example = "/run/secrets/proxy-subscription-url";
};
};
};
outboundType = types.submodule {
options = {
tag = mkOption {
type = types.str;
description = ''
Outbound tag used in routing rules and multi-outbound selection.
With selection = "selector" or "urltest", each outbound keeps its own
tag and can be selected directly. With selection = "first", proxy-suite
routes through a single active outbound tagged "proxy", so individual
proxy tags are mainly useful for documentation and config structure.
'';
example = "vps-de";
};
urlFile = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Runtime path to a file containing the proxy URL.
Intended for use with secret managers (sops-nix, agenix, etc.).
The file is read at service start time and never lands in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
'';
example = "/run/secrets/my-proxy-url";
};
url = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
Literal proxy URL. Convenient for non-secret configs, but the URL
will end up in the Nix store.
Set exactly one of urlFile, url, or json for each outbound.
Prefer urlFile for real credentials.
'';
example = "hy2://password@example.com:443?sni=example.com";
};
backend = mkOption {
type = types.enum [
"auto"
"sing-box"
"xray"
];
default = "auto";
description = ''
Backend preference for this outbound when both SingBox and XRay are
enabled. "auto" uses SingBox when the URL or JSON can be represented
there and falls back to XRay for XRay-only transports such as XHTTP
or ECH. Ignored by single-backend configurations.
'';
example = "xray";
};
singBoxJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw sing-box outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field
is overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound.
Use this when the proxy definition is easier to generate as native Nix
than as a single URL string. Only valid with the SingBox backend.
'';
example = {
type = "vless";
server = "example.com";
server_port = 443;
uuid = "...";
};
};
xrayJson = mkOption {
type = types.nullOr types.attrs;
default = null;
description = ''
Raw XRay outbound configuration as a Nix attribute set.
Embedded directly into the config at build time. The tag field is
overridden by the outbound's tag option.
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
each outbound. Only valid with the XRay backend.
'';
example = {
protocol = "vless";
settings = {
address = "example.com";
port = 443;
id = "...";
encryption = "none";
};
};
};
json = mkOption {
type = types.nullOr types.attrs;
default = null;
visible = false;
description = ''
Deprecated alias for singBoxJson. Use singBoxJson instead.
'';
};
# Shorthand for attaching routing rules directly to an outbound definition.
# Traffic matching these patterns is sent to this specific outbound.
# Only meaningful when selection = "selector" or "urltest" (with "first",
# all proxy traffic goes to the single "proxy" outbound anyway).
routing = routingFields;
};
};
in
{
inherit subscriptionType outboundType;
}
@@ -0,0 +1,163 @@
# zapret hostlist and preset option type definitions.
{ lib }:
let
inherit (lib) mkOption types;
zapretPresetType = types.enum [
"general"
"google"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultDomainType = types.enum [
"general"
"google"
"discord"
"youtube"
"instagram"
"soundcloud"
"twitter"
];
zapretDefaultIpType = types.enum [
"all"
];
zapretHostlistRuleType = types.submodule {
options = {
name = mkOption {
type = types.strMatching "^[a-z0-9][a-z0-9-]*$";
description = ''
Custom hostlist name. Used to generate hostlists/list-<name>.txt
inside the derived zapret config directory.
'';
example = "cloudflare";
};
domains = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Domains written into the generated custom zapret hostlist file.
Can be combined with defaultDomains.
'';
example = [
"example.com"
"example.de"
];
};
defaultDomains = mkOption {
type = types.listOf zapretDefaultDomainType;
default = [ ];
description = ''
Built-in domain groups copied from zapret-discord-youtube hostlists.
These are expanded and combined with domains.
Each value maps directly to the same-named upstream file:
"general" uses list-general.txt, "google" uses list-google.txt,
and the remaining values use their corresponding list-<name>.txt.
"discord" is an alias for "general"; "youtube" is an alias for
"google".
When "general" or "discord" is used together with configName, the
module also clones the selected config's Discord UDP voice rule
(--filter-l7=discord,stun).
When preset is unset, use one defaultDomains entry per rule so the
module can infer a single rule family. Split groups into separate
rules when they need different strategies.
'';
example = [ "google" ];
};
ips = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
IPs or CIDRs written into the generated custom zapret ipset file.
Can be combined with defaultIps.
'';
example = [
"203.0.113.0/24"
"2001:db8::/32"
];
};
defaultIps = mkOption {
type = types.listOf zapretDefaultIpType;
default = [ ];
description = ''
Built-in IP/CIDR groups copied from zapret-discord-youtube ipsets.
"all" uses the upstream ipset-all.txt list. The upstream bundle does
not split this list by service, so site-specific defaults remain in
defaultDomains.
'';
example = [ "all" ];
};
preset = mkOption {
type = types.nullOr zapretPresetType;
default = null;
description = ''
Clone this built-in NFQWS rule family for this hostlist. When
configName is set, the family is cloned from that zapret config;
otherwise it is cloned from the active global zapret config.
When unset and defaultDomains is non-empty, rule families are
inferred from defaultDomains.
'';
example = "google";
};
configName = mkOption {
type = types.nullOr types.str;
default = null;
description = ''
zapret config name to clone NFQWS rules from for this hostlist.
Names use the same matching rules as services.proxy-suite.zapret.configName.
This is a higher-level alternative to nfqwsArgs and cannot be used
together with nfqwsArgs.
'';
example = "general(ALT9)";
};
nfqwsArgs = mkOption {
type = types.listOf types.str;
default = [ ];
description = ''
Additional NFQWS argument fragments for this hostlist.
The module injects --hostlist=... and trailing --new automatically.
This cannot be used together with configName.
'';
example = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
};
enableDirectSync = mkOption {
type = types.bool;
default = true;
description = ''
Whether this custom hostlist should also be mirrored into proxy
direct domain routing when zapret.syncDirectRouting = true.
'';
};
};
};
in
{
inherit
zapretDefaultDomainType
zapretDefaultIpType
zapretPresetType
zapretHostlistRuleType
;
}
+112
View File
@@ -0,0 +1,112 @@
{
lib,
cfg,
zapret,
}:
let
r = cfg.proxy.routing;
zapretCfg = cfg.zapret;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
"list-instagram.txt"
"list-soundcloud.txt"
"list-twitter.txt"
];
zapretDefaultDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles
)
else
[ ];
zapretDefaultIps =
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule)
) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomDefaultIps =
if syncZapretDirectUpstreamIps then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps)
) zapretCfg.hostlistRules
)
else
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt"
else
[ ]
)
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
)
else
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (
lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)
) zapretExcludedIps
else
[ ];
in
{
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
};
}
+34 -337
View File
@@ -10,117 +10,16 @@ let
derived = import ./derived.nix { inherit lib cfg; };
r = cfg.proxy.routing;
proxyCfg = derived.proxyCfg;
zapretCfg = cfg.zapret;
tgWsProxyCfg = cfg.tgWsProxy;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
trim = lib.strings.trim;
hasPrefix = lib.strings.hasPrefix;
splitString = lib.strings.splitString;
zapretSrc = if builtins.isAttrs zapret && zapret ? outPath then zapret.outPath else zapret;
parseListFile =
path:
lib.unique (
builtins.filter (line: line != "" && !(hasPrefix "#" line)) (
map trim (splitString "\n" (builtins.replaceStrings [ "\r" ] [ "" ] (builtins.readFile path)))
)
);
subtractItems = items: exclusions: builtins.filter (item: !(builtins.elem item exclusions)) items;
syncZapretDirectDomains = zapretCfg.enable && zapretCfg.syncDirectRouting;
syncZapretDirectUpstreamIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUpstreamIps;
syncZapretDirectUserIps = zapretCfg.enable && zapretCfg.syncDirectRoutingUserIps;
syncZapretDirectAnyIps = syncZapretDirectUpstreamIps || syncZapretDirectUserIps;
zapretDefaultDomainFiles = [
"list-general.txt"
"list-google.txt"
]
++ lib.optionals zapretCfg.includeExtraUpstreamLists [
"list-instagram.txt"
"list-soundcloud.txt"
"list-twitter.txt"
];
zapretDefaultDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (file: parseListFile "${zapretSrc}/hostlists/${file}") zapretDefaultDomainFiles
)
else
[ ];
zapretDefaultIps =
if syncZapretDirectUpstreamIps then parseListFile "${zapretSrc}/hostlists/ipset-all.txt" else [ ];
zapretUserIps = if syncZapretDirectUserIps then zapretCfg.ipsetAll else [ ];
zapretCustomDomains =
if syncZapretDirectDomains then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.effectiveRuleDomains rule)
) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomUserIps =
if syncZapretDirectUserIps then
lib.unique (
lib.concatMap (rule: lib.optionals rule.enableDirectSync rule.ips) zapretCfg.hostlistRules
)
else
[ ];
zapretCustomDefaultIps =
if syncZapretDirectUpstreamIps then
lib.unique (
lib.concatMap (
rule: lib.optionals rule.enableDirectSync (zapretDomainGroups.expandDefaultIps rule.defaultIps)
) zapretCfg.hostlistRules
)
else
[ ];
zapretExcludedDomains =
if syncZapretDirectDomains then parseListFile "${zapretSrc}/hostlists/list-exclude.txt" else [ ];
zapretExcludedIps = lib.unique (
(
if syncZapretDirectUpstreamIps then
parseListFile "${zapretSrc}/hostlists/ipset-exclude.txt"
else
[ ]
)
++ (if syncZapretDirectUserIps then zapretCfg.ipsetExclude else [ ])
);
zapretDirectDomains =
if syncZapretDirectDomains then
subtractItems (lib.unique (zapretDefaultDomains ++ zapretCfg.listGeneral ++ zapretCustomDomains)) (
lib.unique (zapretExcludedDomains ++ zapretCfg.listExclude)
)
else
[ ];
zapretDirectIps =
if syncZapretDirectAnyIps then
subtractItems (lib.unique (zapretDefaultIps ++ zapretUserIps ++ zapretCustomUserIps ++ zapretCustomDefaultIps)) zapretExcludedIps
else
[ ];
direct = {
domains = lib.unique (r.direct.domains ++ zapretDirectDomains);
ips = lib.unique (r.direct.ips ++ zapretDirectIps);
geosites = lib.unique (r.direct.geosites ++ lib.optional r.enableRuDirect "category-ru");
geoips = lib.unique (r.direct.geoips ++ lib.optional r.enableRuDirect "ru");
zapretDirect = import ./rules-zapret-direct.nix {
inherit
lib
cfg
zapret
;
};
inherit (zapretDirect) direct;
mkRule =
field: tag: items:
lib.optional (items != [ ]) {
${field} = items;
outbound = tag;
};
mkDomainRule = mkRule "domain_suffix";
mkIPRule = mkRule "ip_cidr";
mkRulesetRule = mkRule "rule_set";
customRuleCategory =
outbound:
if outbound == "direct" then
@@ -168,238 +67,36 @@ let
customRules =
perOutboundRules ++ map (rule: rule // { outbound = resolveTag rule.outbound; }) r.rules;
# Build sing-box routing rule entries from a custom rule record.
mkCustomRuleEntries =
rule:
lib.flatten [
(mkDomainRule rule.outbound rule.domains)
(mkIPRule rule.outbound rule.ips)
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
];
# All geosite names referenced anywhere (for rule-set file definitions).
allGeositeNames = lib.unique (
r.proxy.geosites
++ direct.geosites
++ r.block.geosites
++ lib.concatMap (rule: rule.geosites) customRules
);
# All geoip names referenced anywhere.
allGeoIPNames = lib.unique (
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
);
mkRuleSet = kind: pkg: name: {
tag = "${kind}-${name}";
type = "local";
format = "binary";
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
singBoxRules = import ./rules/sing-box.nix {
inherit
lib
pkgs
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
};
inherit (singBoxRules)
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
;
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
commonRules = [
{
network = [
"tcp"
"udp"
];
port = 53;
action = "hijack-dns";
}
{ action = "sniff"; }
];
customRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkCustomRuleEntries rule;
}) customRules;
proxyPrimaryRules = lib.flatten [
(mkDomainRule "proxy" r.proxy.domains)
(mkIPRule "proxy" r.proxy.ips)
];
directRules = lib.flatten [
(mkDomainRule "direct" direct.domains)
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
];
tgWsProxyRelayDirectRules =
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
{
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
outbound = "direct";
};
safetyDirectRules = [
{
ip_is_private = true;
outbound = "direct";
}
]
++ tgWsProxyRelayDirectRules;
blockRules = lib.flatten [
(mkDomainRule "block" r.block.domains)
(mkIPRule "block" r.block.ips)
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
];
proxyGeoRules = lib.flatten [
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
];
singBoxRoutingRules =
commonRules
++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules
++ directRules
++ safetyDirectRules
++ blockRules
++ proxyGeoRules;
singBoxRouteModeRules = {
common = commonRules;
custom = customRouteRules;
proxyPrimary = proxyPrimaryRules;
direct = directRules;
safetyDirect = safetyDirectRules;
block = blockRules;
proxyGeo = proxyGeoRules;
};
xrayTarget =
tag:
if tag == "proxy" && derived.selectionMode == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; };
mkXrayRule =
ruleTag: fields: tag:
(
{
type = "field";
inherit ruleTag;
}
// fields
// (xrayTarget tag)
);
xrayDomainRules =
ruleTag: tag: domains:
lib.optional (domains != [ ]) (
mkXrayRule ruleTag {
domain = map (domain: "domain:${domain}") domains;
} tag
);
xrayIPRules =
ruleTag: tag: ips:
lib.optional (ips != [ ]) (
mkXrayRule ruleTag {
ip = ips;
} tag
);
xrayGeositeRules =
ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (
mkXrayRule ruleTag {
domain = map (name: "geosite:${name}") geosites;
} tag
);
xrayGeoIPRules =
ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (
mkXrayRule ruleTag {
ip = map (name: "geoip:${name}") geoips;
} tag
);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries =
rule:
lib.flatten [
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
rule.domains
)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
rule.geosites
)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
rule.geoips
)
];
xrayCustomRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkXrayCustomRuleEntries rule;
}) customRules;
xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
];
xrayDirectRules = lib.flatten [
(xrayDomainRules "direct-domain" "direct" direct.domains)
(xrayIPRules "direct-ip" "direct" direct.ips)
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
];
xraySafetyDirectRules = [
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
]
++
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
(
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
);
xrayBlockRules = lib.flatten [
(xrayDomainRules "block-domain" "block" r.block.domains)
(xrayIPRules "block-ip" "block" r.block.ips)
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
];
xrayProxyGeoRules = lib.flatten [
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
xrayRoutingRules =
lib.concatMap (item: item.entries) xrayCustomRouteRules
++ xrayProxyPrimaryRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayProxyGeoRules
++ xrayBlockRules;
xrayRouteModeRules = {
common = [ ];
custom = xrayCustomRouteRules;
proxyPrimary = xrayProxyPrimaryRules;
direct = xrayDirectRules;
safetyDirect = xraySafetyDirectRules;
block = xrayBlockRules;
proxyGeo = xrayProxyGeoRules;
xrayRules = import ./rules/xray.nix {
inherit
lib
r
direct
tgWsProxyCfg
customRules
customRuleCategory
;
inherit (derived) selectionMode;
};
inherit (xrayRules) xrayRoutingRules xrayRouteModeRules;
routingRules = singBoxRoutingRules;
routeModeRules = singBoxRouteModeRules;
+136
View File
@@ -0,0 +1,136 @@
# sing-box routing rules and local rule-set definitions.
{
lib,
pkgs,
r,
direct,
tgWsProxyCfg,
customRules,
customRuleCategory,
}:
let
mkRule =
field: tag: items:
lib.optional (items != [ ]) {
${field} = items;
outbound = tag;
};
mkDomainRule = mkRule "domain_suffix";
mkIPRule = mkRule "ip_cidr";
mkRulesetRule = mkRule "rule_set";
mkCustomRuleEntries =
rule:
lib.flatten [
(mkDomainRule rule.outbound rule.domains)
(mkIPRule rule.outbound rule.ips)
(mkRulesetRule rule.outbound (map (s: "geosite-${s}") rule.geosites))
(mkRulesetRule rule.outbound (map (s: "geoip-${s}") rule.geoips))
];
allGeositeNames = lib.unique (
r.proxy.geosites
++ direct.geosites
++ r.block.geosites
++ lib.concatMap (rule: rule.geosites) customRules
);
allGeoIPNames = lib.unique (
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
);
mkRuleSet = kind: pkg: name: {
tag = "${kind}-${name}";
type = "local";
format = "binary";
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
};
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
commonRules = [
{
network = [
"tcp"
"udp"
];
port = 53;
action = "hijack-dns";
}
{ action = "sniff"; }
];
customRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkCustomRuleEntries rule;
}) customRules;
proxyPrimaryRules = lib.flatten [
(mkDomainRule "proxy" r.proxy.domains)
(mkIPRule "proxy" r.proxy.ips)
];
directRules = lib.flatten [
(mkDomainRule "direct" direct.domains)
(mkIPRule "direct" direct.ips)
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
];
tgWsProxyRelayDirectRules =
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
{
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
outbound = "direct";
};
safetyDirectRules = [
{
ip_is_private = true;
outbound = "direct";
}
]
++ tgWsProxyRelayDirectRules;
blockRules = lib.flatten [
(mkDomainRule "block" r.block.domains)
(mkIPRule "block" r.block.ips)
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
];
proxyGeoRules = lib.flatten [
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
];
singBoxRoutingRules =
commonRules
++ lib.concatMap (item: item.entries) customRouteRules
++ proxyPrimaryRules
++ directRules
++ safetyDirectRules
++ blockRules
++ proxyGeoRules;
singBoxRouteModeRules = {
common = commonRules;
custom = customRouteRules;
proxyPrimary = proxyPrimaryRules;
direct = directRules;
safetyDirect = safetyDirectRules;
block = blockRules;
proxyGeo = proxyGeoRules;
};
in
{
inherit
geositeRuleSets
geoIPRuleSets
singBoxRoutingRules
singBoxRouteModeRules
;
}
+142
View File
@@ -0,0 +1,142 @@
# XRay routing rule definitions.
{
lib,
r,
direct,
tgWsProxyCfg,
customRules,
customRuleCategory,
selectionMode,
}:
let
xrayTarget =
tag:
if tag == "proxy" && selectionMode == "urltest" then
{ balancerTag = "proxy"; }
else
{ outboundTag = tag; };
mkXrayRule =
ruleTag: fields: tag:
(
{
type = "field";
inherit ruleTag;
}
// fields
// (xrayTarget tag)
);
xrayDomainRules =
ruleTag: tag: domains:
lib.optional (domains != [ ]) (
mkXrayRule ruleTag {
domain = map (domain: "domain:${domain}") domains;
} tag
);
xrayIPRules =
ruleTag: tag: ips:
lib.optional (ips != [ ]) (
mkXrayRule ruleTag {
ip = ips;
} tag
);
xrayGeositeRules =
ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (
mkXrayRule ruleTag {
domain = map (name: "geosite:${name}") geosites;
} tag
);
xrayGeoIPRules =
ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (
mkXrayRule ruleTag {
ip = map (name: "geoip:${name}") geoips;
} tag
);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries =
rule:
lib.flatten [
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
rule.domains
)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
rule.geosites
)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
rule.geoips
)
];
xrayCustomRouteRules = map (rule: {
category = customRuleCategory rule.outbound;
entries = mkXrayCustomRuleEntries rule;
}) customRules;
xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
];
xrayDirectRules = lib.flatten [
(xrayDomainRules "direct-domain" "direct" direct.domains)
(xrayIPRules "direct-ip" "direct" direct.ips)
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
];
xraySafetyDirectRules = [
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
]
++
lib.optional
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
(
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
);
xrayBlockRules = lib.flatten [
(xrayDomainRules "block-domain" "block" r.block.domains)
(xrayIPRules "block-ip" "block" r.block.ips)
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
];
xrayProxyGeoRules = lib.flatten [
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
xrayRoutingRules =
lib.concatMap (item: item.entries) xrayCustomRouteRules
++ xrayProxyPrimaryRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayProxyGeoRules
++ xrayBlockRules;
xrayRouteModeRules = {
common = [ ];
custom = xrayCustomRouteRules;
proxyPrimary = xrayProxyPrimaryRules;
direct = xrayDirectRules;
safetyDirect = xraySafetyDirectRules;
block = xrayBlockRules;
proxyGeo = xrayProxyGeoRules;
};
in
{
inherit
xrayRoutingRules
xrayRouteModeRules
;
}
+80 -72
View File
@@ -15,21 +15,9 @@
}:
let
constants = derived.constants;
assertions = import ./service/assertions-lib.nix { inherit lib; };
inherit (assertions)
mkAssertion
requireEnabled
requireAvailable
uniqueValues
notEqualWhen
forbiddenValues
exactlyOneOf
;
inherit (derived)
constants
proxyCfg
singBoxCfg
proxyEnabled
singBoxEnabled
xrayEnabled
@@ -43,7 +31,27 @@ let
perAppZapretCfg
;
globalTunAutoRouteTable = constants.tunAutoRouteTableIndex;
mkAssertion = assertion: message: { inherit assertion message; };
requireEnabled =
featureEnabled: dependencyEnabled: message:
mkAssertion (!featureEnabled || dependencyEnabled) message;
requireAvailable =
featureUsed: dependencyEnabled: message:
mkAssertion (!featureUsed || dependencyEnabled) message;
uniqueValues =
condition: values: message:
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
exactlyOneOf =
condition: values: message:
mkAssertion (
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
) message;
notEqualWhen =
condition: left: right: message:
mkAssertion (!(condition && left == right)) message;
forbiddenValues =
condition: value: disallowed: message:
mkAssertion (!(condition && builtins.elem value disallowed)) message;
featureAssertions = [
(requireAvailable proxyCfg.singBox.enable proxyEnabled
@@ -144,6 +152,61 @@ let
)
];
localProxyAuthCfg = proxyCfg.auth;
localProxyAuthUsed =
localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null
|| localProxyAuthCfg.passwordFile != null;
localProxyAuthAssertions = [
(mkAssertion (
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password
localProxyAuthCfg.passwordFile
] "proxy-suite: proxy.auth requires exactly one of password or passwordFile")
];
secretAssertions = [
(exactlyOneOf tgWsProxyCfg.enable [
tgWsProxyCfg.secret
tgWsProxyCfg.secretFile
] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
];
outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf proxyEnabled
[
ob.urlFile
ob.url
ob.singBoxJson
ob.xrayJson
ob.json
]
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
)
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
(mkAssertion (
!(ob.backend == "sing-box") || singBoxEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
]) proxyCfg.outbounds;
subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf proxyEnabled [
sub.urlFile
sub.url
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
]) proxyCfg.subscriptions;
globalTunAutoRouteTable = constants.tunAutoRouteTableIndex;
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
{
condition = globalTun.enable && perAppRoutingTun.enable;
@@ -272,7 +335,6 @@ let
67108864
134217728
];
positiveNumberAssertions =
map (item: mkAssertion (!item.condition || item.value > 0) item.message)
[
@@ -338,21 +400,6 @@ let
}
];
localProxyAuthCfg = proxyCfg.auth;
localProxyAuthUsed =
localProxyAuthCfg.username != null
|| localProxyAuthCfg.password != null
|| localProxyAuthCfg.passwordFile != null;
localProxyAuthAssertions = [
(mkAssertion (
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
localProxyAuthCfg.password
localProxyAuthCfg.passwordFile
] "proxy-suite: proxy.auth requires exactly one of password or passwordFile")
];
forbiddenValueAssertions =
map (item: forbiddenValues item.condition item.value item.disallowed item.message)
[
@@ -402,52 +449,13 @@ let
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
}
];
secretAssertions = [
(exactlyOneOf tgWsProxyCfg.enable [
tgWsProxyCfg.secret
tgWsProxyCfg.secretFile
] "proxy-suite: tgWsProxy requires exactly one of secret or secretFile")
];
outboundAssertions = lib.concatMap (ob: [
(exactlyOneOf proxyEnabled
[
ob.urlFile
ob.url
ob.singBoxJson
ob.xrayJson
ob.json
]
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
)
(mkAssertion (
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
)
(mkAssertion (
!(ob.backend == "xray") || xrayEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
(mkAssertion (
!(ob.backend == "sing-box") || singBoxEnabled
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
]) proxyCfg.outbounds;
subscriptionAssertions = lib.concatMap (sub: [
(exactlyOneOf proxyEnabled [
sub.urlFile
sub.url
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
]) proxyCfg.subscriptions;
in
featureAssertions
++ perAppRoutingAssertions
++ collisionAssertions
++ positiveNumberAssertions
++ localProxyAuthAssertions
++ forbiddenValueAssertions
++ secretAssertions
++ outboundAssertions
++ subscriptionAssertions
++ collisionAssertions
++ positiveNumberAssertions
++ forbiddenValueAssertions
@@ -1,31 +0,0 @@
{ lib }:
rec {
mkAssertion = assertion: message: { inherit assertion message; };
requireEnabled =
featureEnabled: dependencyEnabled: message:
mkAssertion (!featureEnabled || dependencyEnabled) message;
requireAvailable =
featureUsed: dependencyEnabled: message:
mkAssertion (!featureUsed || dependencyEnabled) message;
uniqueValues =
condition: values: message:
mkAssertion (!condition || builtins.length values == builtins.length (lib.unique values)) message;
notEqualWhen =
condition: left: right: message:
mkAssertion (!(condition && left == right)) message;
forbiddenValues =
condition: value: disallowed: message:
mkAssertion (!(condition && builtins.elem value disallowed)) message;
exactlyOneOf =
condition: values: message:
mkAssertion (
!condition || builtins.length (builtins.filter (value: value != null) values) == 1
) message;
}
+123 -121
View File
@@ -35,127 +35,6 @@ rec {
)
);
cidrNetworkFunction = ''
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
'';
mkDefaultUplinkIPv4Source =
{
ip,
awk,
errorMessage,
}:
''
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo ${lib.escapeShellArg errorMessage} >&2
exit 1
fi
'';
mkNftDeleteTable =
{
nft,
family,
table,
}:
''
${nft} delete table ${family} ${table} 2>/dev/null || true
'';
mkIpRuleDeleteByFwmark =
{
ip,
family ? "",
fwmark,
table,
}:
''
while ${ip} ${lib.optionalString (family != "") "${family} "}rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByTable =
{
ip,
family,
table,
}:
''
while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByPriority =
{
ip,
family,
priority,
}:
''
while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done
'';
mkIpRouteFlushTable =
{
ip,
family,
table,
}:
''
${ip} ${family} route flush table ${toString table} 2>/dev/null || true
'';
mkIpLocalDefaultRouteDelete =
{
ip,
table,
}:
''
${ip} route del local default dev lo table ${toString table} 2>/dev/null || true
'';
mkIpLinkDelete =
{
ip,
interface,
}:
''
${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true
'';
flushResolvedCaches = ''
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
mkRestartingService =
{
description,
@@ -263,4 +142,127 @@ rec {
execStop = "${pkgs.coreutils}/bin/true";
extraServiceConfig.Slice = sliceName;
};
cidrNetworkFunction = ''
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
'';
mkDefaultUplinkIPv4Source =
{
ip,
awk,
errorMessage,
}:
''
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo ${lib.escapeShellArg errorMessage} >&2
exit 1
fi
'';
mkNftDeleteTable =
{
nft,
family,
table,
}:
''
${nft} delete table ${family} ${table} 2>/dev/null || true
'';
mkIpRuleDeleteByFwmark =
{
ip,
family ? "",
fwmark,
table,
}:
''
while ${ip} ${
lib.optionalString (family != "") "${family} "
}rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByTable =
{
ip,
family,
table,
}:
''
while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByPriority =
{
ip,
family,
priority,
}:
''
while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done
'';
mkIpRouteFlushTable =
{
ip,
family,
table,
}:
''
${ip} ${family} route flush table ${toString table} 2>/dev/null || true
'';
mkIpLocalDefaultRouteDelete =
{
ip,
table,
}:
''
${ip} route del local default dev lo table ${toString table} 2>/dev/null || true
'';
mkIpLinkDelete =
{
ip,
interface,
}:
''
${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true
'';
flushResolvedCaches = ''
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
}
-3
View File
@@ -71,15 +71,12 @@ let
pkgs
singBoxCfg
proxyCfg
proxyEnabled
singBoxEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
userControlCfg
perAppRoutingTun
selectionMode
collapseNamedOutbounds
hasSubscriptions
@@ -0,0 +1,78 @@
# Subscription refresh and route-mode control scripts.
{
lib,
pkgs,
proxyCfg,
routeModeStateFile,
subscriptionCacheDir,
subscriptionCacheHelpersBlock,
mkSubscriptionFetchBlock,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
restartActiveConfigConsumersBlock =
lib.concatMapStrings
(svc: ''
if ${systemctl} is-active --quiet ${svc}; then
${systemctl} restart ${svc}
fi
'')
[
"proxy-suite-socks"
"proxy-suite-tun"
"proxy-suite-per-app-tun"
];
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
set -euo pipefail
CACHE_DIR="${subscriptionCacheDir}"
mkdir -p "$CACHE_DIR"
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock}
fi
exit "$FAILED"
'';
setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" ''
set -euo pipefail
mode="''${1:-}"
case "$mode" in
default)
;;
whitelist)
;;
blacklist)
;;
all-proxy)
;;
all-bypass)
;;
*)
echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2
exit 1
;;
esac
mkdir -p "$(dirname "${routeModeStateFile}")"
if [ "$mode" = "default" ]; then
rm -f "${routeModeStateFile}"
else
printf '%s\n' "$mode" > "${routeModeStateFile}"
fi
${restartActiveConfigConsumersBlock}
'';
in
{
inherit
subscriptionUpdateScript
setRouteModeScript
;
}
+40 -333
View File
@@ -37,19 +37,7 @@ let
};
builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders)
mkNamedUnits
mkRestartingService
mkOneshotService
mkUserRuleService
mkAnchorService
;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip;
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN";
};
inherit (builders) mkNamedUnits;
inherit (context)
derived
@@ -60,19 +48,14 @@ let
;
inherit (derived)
singBoxCfg
proxyCfg
proxyEnabled
xrayEnabled
hybridEnabled
pureXrayEnabled
activeBackend
perAppRoutingCfg
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
userControlCfg
userControlEnabled
perAppZapretEnabled
@@ -83,323 +66,47 @@ let
builtinTags
;
constants = derived.constants;
inherit (constants)
tunAutoRouteTableIndex
tunAutoRouteRulePriority
xrayTunPerAppTproxyRulePriority
xrayTunPerAppTunRulePriority
xrayGlobalTunIPv6Address
xrayGlobalTunIPv6RoutePrefix
;
serviceNames = {
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
routingScripts = import ./routing-scripts.nix {
inherit
lib
pkgs
builders
ip
nft
nftablesRulesFile
constants
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
;
};
localProxyAuthEnabled =
proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg globalTun.address}
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
break
fi
${pkgs.coreutils}/bin/sleep 0.1
done
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
exit 1
fi
${defaultUplinkIPv4Source}
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString perAppRoutingTproxy.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
set -euo pipefail
# Start from a clean policy-routing state. `ip rule add` permits duplicate
# rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart.
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
${nft} -f ${nftablesRulesFile}
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
'';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
'';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTproxyRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-6";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
${builders.flushResolvedCaches}
'';
systemServiceEntries = [
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
description = "${
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box"
} proxy client (SOCKS + TProxy-ready)";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
value = mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
];
execStart = tproxyUpScript;
execStop = tproxyDownScript;
};
}
{
enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun;
value = mkRestartingService {
description = "${
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box"
} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i";
backendService = serviceNames.perAppTun;
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
execStart = perAppRouting.perAppTproxyUpScript;
execStop = perAppRouting.perAppTproxyDownScript;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app zapret marking for user %i";
backendService = serviceNames.perAppZapret;
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled;
name = "proxy-suite-route-mode@";
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
{
enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor";
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
}
{
enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor";
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
];
timerEntries = [
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
];
serviceUnits = import ./units.nix {
inherit
lib
builders
proxyCfg
proxyEnabled
hybridEnabled
pureXrayEnabled
globalTun
globalTproxy
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
hasSubscriptions
scripts
perAppRouting
routingScripts
;
};
inherit (serviceUnits)
localProxyAuthEnabled
systemServiceEntries
userServiceEntries
timerEntries
;
in
{
environment.systemPackages = [ control.proxyCtl ];
+68 -294
View File
@@ -27,310 +27,84 @@
let
builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders) mkAnchorService;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip awk;
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN";
};
perAppTunSliceName = "proxy-suite-per-app-tun.slice";
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
perAppZapretSliceName = "proxy-suite-per-app-zapret.slice";
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
[
{
name = "proxychains";
route = "proxychains";
}
]
++ lib.optionals perAppRoutingTun.enable [
{
name = "tun";
route = "tun";
}
]
++ lib.optionals perAppRoutingTproxy.enable [
{
name = "tproxy";
route = "tproxy";
}
]
++ lib.optionals perAppZapretCfg.enable [
{
name = "zapret";
route = "zapret";
}
]
);
effectivePerAppRoutingProfiles =
perAppRoutingCfg.profiles
++ builtins.filter (
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
builtins.toJSON effectivePerAppRoutingProfiles
);
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (
profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles;
inherit (constants)
xrayPerAppTunIPv6Address
xrayPerAppTunIPv6RoutePrefix
profiles = import ./per-app-routing/profiles.nix {
inherit
lib
pkgs
proxyCfg
perAppRoutingCfg
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
;
};
inherit (profiles)
effectivePerAppRoutingProfiles
effectivePerAppRoutingProfileNames
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2
exit 1
'';
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
${defaultUplinkIPv4Source}
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${lib.optionalString pureXrayEnabled ''
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
''}
'';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }}
${builders.flushResolvedCaches}
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
set -euo pipefail
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
${nft} -f ${perAppTproxyRulesFile}
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
'';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
'';
# 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
'';
perAppTunUserRuleStart = mkUserRuleStart {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
sliceName = perAppTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
};
perAppTunUserRuleStop = mkUserRuleStop {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
backendScripts = import ./per-app-routing/backend-scripts.nix {
inherit
lib
pkgs
builders
pureXrayEnabled
perAppRoutingTun
perAppRoutingTproxy
constants
perAppTunChainFile
perAppTproxyRulesFile
ip
nft
awk
seqBin
sleepBin
;
};
inherit (backendScripts)
perAppTunUpScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyDownScript
;
perAppTproxyUserRuleStart = mkUserRuleStart {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
sliceName = perAppTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
};
perAppTproxyUserRuleStop = mkUserRuleStop {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
};
perAppZapretUserRuleStart = mkUserRuleStart {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
sliceName = perAppZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}";
};
perAppZapretUserRuleStop = mkUserRuleStop {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
userRules = import ./per-app-routing/user-rules.nix {
inherit
lib
pkgs
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
perAppTunSliceName
perAppTproxySliceName
perAppZapretSliceName
nft
awk
grepBin
findBin
headBin
;
};
inherit (userRules)
perAppTunUserRuleStart
perAppTunUserRuleStop
perAppTproxyUserRuleStart
perAppTproxyUserRuleStop
perAppZapretUserRuleStart
perAppZapretUserRuleStop
;
in
{
@@ -0,0 +1,144 @@
# Per-app TUN and TProxy backend lifecycle scripts.
{
lib,
pkgs,
builders,
pureXrayEnabled,
perAppRoutingTun,
perAppRoutingTproxy,
constants,
perAppTunChainFile,
perAppTproxyRulesFile,
ip,
nft,
awk,
seqBin,
sleepBin,
}:
let
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip awk;
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN";
};
inherit (constants)
xrayPerAppTunIPv6Address
xrayPerAppTunIPv6RoutePrefix
;
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg perAppRoutingTun.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${perAppRoutingTun.interface} did not appear in time" >&2
exit 1
'';
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
${defaultUplinkIPv4Source}
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${lib.optionalString pureXrayEnabled ''
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
''}
'';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-4";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }}
${builders.flushResolvedCaches}
'';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
set -euo pipefail
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
${nft} -f ${perAppTproxyRulesFile}
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
'';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
'';
in
{
inherit
perAppTunUpScript
perAppTunDownScript
perAppTproxyUpScript
perAppTproxyDownScript
;
}
@@ -0,0 +1,95 @@
# Per-app routing profile expansion and proxychains config.
{
lib,
pkgs,
proxyCfg,
perAppRoutingCfg,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
}:
let
perAppRoutingProfileNames = map (profile: profile.name) perAppRoutingCfg.profiles;
defaultPerAppRoutingProfiles = lib.optionals perAppRoutingCfg.createDefaultProfiles (
[
{
name = "proxychains";
route = "proxychains";
}
]
++ lib.optionals perAppRoutingTun.enable [
{
name = "tun";
route = "tun";
}
]
++ lib.optionals perAppRoutingTproxy.enable [
{
name = "tproxy";
route = "tproxy";
}
]
++ lib.optionals perAppZapretCfg.enable [
{
name = "zapret";
route = "zapret";
}
]
);
effectivePerAppRoutingProfiles =
perAppRoutingCfg.profiles
++ builtins.filter (
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
builtins.toJSON effectivePerAppRoutingProfiles
);
proxychainsConfigFile =
if localProxyAuthEnabled then
"/run/proxy-suite-socks/proxychains.conf"
else
pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (
profile: profile.route == "proxychains"
) effectivePerAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectivePerAppRoutingProfiles;
hasTproxyProfiles = builtins.any (
profile: profile.route == "tproxy"
) effectivePerAppRoutingProfiles;
hasZapretProfiles = builtins.any (
profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles;
in
{
inherit
effectivePerAppRoutingProfiles
effectivePerAppRoutingProfileNames
perAppRoutingProfilesFile
proxychainsConfigFile
proxychainsQuietArg
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
}
@@ -0,0 +1,142 @@
# Per-user cgroup nftables mark-rule scripts for per-app routing backends.
{
lib,
pkgs,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
perAppTunSliceName,
perAppTproxySliceName,
perAppZapretSliceName,
nft,
awk,
grepBin,
findBin,
headBin,
}:
let
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 -
'';
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
'';
perAppTunUserRuleStart = mkUserRuleStart {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
sliceName = perAppTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString perAppRoutingTun.fwmark} ct mark set ${toString perAppRoutingTun.fwmark}";
};
perAppTunUserRuleStop = mkUserRuleStop {
name = "per-app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_tun";
nftChain = "output";
};
perAppTproxyUserRuleStart = mkUserRuleStart {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
sliceName = perAppTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString perAppRoutingTproxy.fwmark} ct mark set ${toString perAppRoutingTproxy.fwmark}";
};
perAppTproxyUserRuleStop = mkUserRuleStop {
name = "per-app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_per_app_tproxy";
nftChain = "output";
};
perAppZapretUserRuleStart = mkUserRuleStart {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
sliceName = perAppZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString perAppZapretCfg.filterMark} ct mark set ct mark or ${toString perAppZapretCfg.filterMark}";
};
perAppZapretUserRuleStop = mkUserRuleStop {
name = "per-app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_per_app_zapret_mark";
nftChain = "output";
};
in
{
inherit
perAppTunUserRuleStart
perAppTunUserRuleStop
perAppTproxyUserRuleStart
perAppTproxyUserRuleStop
perAppZapretUserRuleStart
perAppZapretUserRuleStop
;
}
@@ -0,0 +1,144 @@
{
lib,
pkgs,
builders,
ip,
nft,
nftablesRulesFile,
constants,
globalTun,
globalTproxy,
perAppRoutingTun,
perAppRoutingTproxy,
}:
let
inherit (constants)
tunAutoRouteTableIndex
tunAutoRouteRulePriority
xrayTunPerAppTproxyRulePriority
xrayTunPerAppTunRulePriority
xrayGlobalTunIPv6Address
xrayGlobalTunIPv6RoutePrefix
;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip;
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN";
};
in
{
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg globalTun.address}
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
tun_addr=""
tun_route_prefix=""
uplink_addr=""
${builders.cidrNetworkFunction}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
break
fi
${pkgs.coreutils}/bin/sleep 0.1
done
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
exit 1
fi
${defaultUplinkIPv4Source}
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString perAppRoutingTproxy.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
set -euo pipefail
# Start from a clean policy-routing state. `ip rule add` permits duplicate
# rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart.
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
${nft} -f ${nftablesRulesFile}
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
'';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e
${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
'';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTproxyRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-4";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-6";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
${builders.flushResolvedCaches}
'';
}
@@ -0,0 +1,98 @@
{
pureXrayEnabled,
selectionMode,
}:
if pureXrayEnabled then
''
def xray_bind_outbound($interface):
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr):
if $dns_final == "local" then
[$local_addr, $remote_addr]
elif $dns_final == "remote" then
[$remote_addr, $local_addr]
else
[$remote_addr, $local_addr]
end;
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| if $xray_tun_dns_runtime then
.dns.servers = xray_dns_server_order($dns_final)
| if $dns_final == "" then
.
else
(.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client)
end
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
else
''
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = $obs + .outbounds
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then .dns.rules = [] else . end
else . end
''
@@ -0,0 +1,111 @@
{
lib,
jq,
hybridEnabled,
xraySidecarRoutingMark,
}:
routingMark: xraySidecarBasePort: xrayDnsBridgePort:
lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]'
XRAY_INBOUNDS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_next_xray_sidecar_port() {
local port="$XRAY_SIDECAR_NEXT_PORT"
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
printf '%s\n' "$port"
}
_proxy_suite_add_xray_sidecar_ob() {
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
port="$(_proxy_suite_next_xray_sidecar_port)"
auth="proxy-suite-xray-$port"
inbound_tag="$tag-inbound"
ob=$(${jq} \
--arg tag "$tag" \
--argjson mark ${toString xraySidecarRoutingMark} \
'.tag = $tag
| .streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| .streamSettings.sockopt.mark = $mark
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
<<< "$ob")
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
inbound=$(${jq} -n \
--arg tag "$inbound_tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
route_rule=$(${jq} -n \
--arg inbound "$inbound_tag" \
--arg outbound "$tag" \
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
sing_ob=$(${jq} -n \
--arg tag "$tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
}}')
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson inbounds "$XRAY_INBOUNDS_JSON" \
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \
'
def bind_xray_sidecar($interface):
if $interface == "" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: $inbounds,
outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
''
@@ -0,0 +1,230 @@
# Outbound construction script fragments for backend startup scripts.
{
lib,
pkgs,
singBoxCfg,
proxyCfg,
pureXrayEnabled,
hybridEnabled,
collapseNamedOutbounds,
selectionMode,
backend,
backendArg,
xraySidecarRoutingMark,
jq,
python3,
parserScriptsPythonPath,
buildOutboundPy,
mkSubscriptionBlock,
}:
let
rawOutboundJson =
ob: tag: routingMark:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
markAttrs =
if routingMark == null then
{ }
else if pureXrayEnabled then
{ streamSettings.sockopt.mark = routingMark; }
else
{ routing_mark = routingMark; };
taggedRaw = backendRaw // {
inherit tag;
};
in
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
mkOutboundBlock =
ob: routingMark: tag:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
in
if backendRaw != null then
let
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (static ${backend} 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 pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in
''
# outbound: ${tag}
URL=$(cat "${urlSource}")
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
singBoxRawOutboundJson =
ob: tag: routingMark:
let
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
in
backendRaw // { inherit tag; } // markAttrs;
xrayRawOutboundJson =
ob: tag:
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
streamSettings.sockopt = {
mark = xraySidecarRoutingMark;
domainStrategy = "UseIP";
};
};
mkHybridOutboundBlock =
ob: routingMark: tag:
if ob.xrayJson != null then
let
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.singBoxJson != null || ob.json != null then
let
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
singBoxCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
}
'';
xrayCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark}
'';
in
if ob.backend == "xray" then
''
# outbound: ${tag} (hybrid forced XRay sidecar)
URL=$(cat "${urlSource}")
OB_JSON=$(${xrayCommand})
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.backend == "sing-box" then
''
# outbound: ${tag} (hybrid forced SingBox)
URL=$(cat "${urlSource}")
OB_JSON=$(${singBoxCommand})
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${tag} (hybrid auto)
URL=$(cat "${urlSource}")
if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$OB_JSON"
else
SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)"
if OB_JSON=$(${xrayCommand}); then
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
else
echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2
if [ -n "$SING_BOX_PARSE_ERROR" ]; then
printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2
fi
exit 1
fi
fi
'';
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2
exit 1
fi
'';
mkOutboundScript =
routingMark:
let
outboundBlocks =
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
mkBackendOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy"
else
lib.concatMapStrings (ob: mkBackendOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark
) proxyCfg.subscriptions;
wrapperBlock =
if pureXrayEnabled && selectionMode == "urltest" then
''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
''
else if collapseNamedOutbounds then
lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.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 selectionMode == "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
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.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 + requireOutboundsBlock + wrapperBlock;
in
{
inherit mkOutboundScript rawOutboundJson;
}
@@ -0,0 +1,154 @@
# Subscription cache and outbound-loading script fragments.
{
lib,
pkgs,
proxyCfg,
hasSubscriptions,
hybridEnabled,
mainBackend,
backend,
jq,
python3,
parserScriptsPythonPath,
fetchSubscriptionPy,
routingMarkJq,
}:
let
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
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} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
)
} "$1" >/dev/null 2>&1
}
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
mv "$tmp" "$target"
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
'';
mkSubscriptionBlock =
sub: routingMark:
let
cacheFile = mkSubscriptionCacheFile sub;
markFilter = routingMarkJq routingMark;
in
''
# subscription: ${sub.tag}
CACHE_DIR="${subscriptionCacheDir}"
CACHE_FILE="${cacheFile}"
_proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag}
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
_proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true
else
rm -f "$CACHE_FILE.tmp"
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
${
if hybridEnabled then
''
if [ -f "$CACHE_FILE" ]; then
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$CACHE_FILE")
fi
''
else
''
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
''
}
'';
mkSubscriptionFetchBlock =
sub:
let
cacheFile = mkSubscriptionCacheFile sub;
in
''
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
else
rm -f "${cacheFile}.tmp"
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
FAILED=1
fi
'';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
);
in
{
inherit
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionBlock
mkSubscriptionFetchBlock
subscriptionTagsFile
;
}
+105 -843
View File
@@ -1,18 +1,15 @@
# Generates proxy backend startup scripts and subscription management scripts.
# Assembles proxy backend startup and control scripts.
{
lib,
pkgs,
singBoxCfg,
proxyCfg,
proxyEnabled,
singBoxEnabled,
xrayEnabled,
hybridEnabled,
pureXrayEnabled,
activeBackend,
perAppRoutingCfg,
userControlCfg,
perAppRoutingTun,
selectionMode,
collapseNamedOutbounds,
hasSubscriptions,
@@ -32,12 +29,9 @@
let
globalTproxy = proxyCfg.tproxy;
systemctl = "${pkgs.systemd}/bin/systemctl";
backend = if activeBackend == null then "sing-box" else activeBackend;
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
backendArg = "--backend ${mainBackend}";
subscriptionBackendArg = "--backend ${subscriptionBackend}";
backendBin = if pureXrayEnabled then xray else singBox;
localProxyAuth = proxyCfg.auth;
localProxyAuthEnabled =
@@ -50,66 +44,10 @@ let
pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password
else
null;
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
routeModeStateFile = "/run/proxy-suite/route-mode";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
inherit (constants)
xrayDnsBridgePorts
xraySidecarBasePorts
;
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
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} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
)
} "$1" >/dev/null 2>&1
}
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
mv "$tmp" "$target"
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
'';
routingMarkJq =
routingMark:
@@ -120,795 +58,119 @@ let
else
" | .routing_mark = ${toString routingMark}";
rawOutboundJson =
ob: tag: routingMark:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
markAttrs =
if routingMark == null then
{ }
else if pureXrayEnabled then
{ streamSettings.sockopt.mark = routingMark; }
else
{ routing_mark = routingMark; };
taggedRaw = backendRaw // {
inherit tag;
};
in
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
subscriptionScripts = import ./script-blocks/subscriptions.nix {
inherit
lib
pkgs
proxyCfg
hasSubscriptions
hybridEnabled
mainBackend
backend
jq
python3
parserScriptsPythonPath
fetchSubscriptionPy
routingMarkJq
;
};
inherit (subscriptionScripts)
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionBlock
mkSubscriptionFetchBlock
subscriptionTagsFile
;
mkOutboundBlock =
ob: routingMark: tag:
let
backendRaw =
if pureXrayEnabled then
ob.xrayJson
else if ob.singBoxJson != null then
ob.singBoxJson
else
ob.json;
in
if backendRaw != null then
let
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (static ${backend} 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 pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
in
''
# outbound: ${tag}
URL=$(cat "${urlSource}")
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
outboundScripts = import ./script-blocks/outbounds.nix {
inherit
lib
pkgs
singBoxCfg
proxyCfg
pureXrayEnabled
hybridEnabled
collapseNamedOutbounds
selectionMode
backend
backendArg
xraySidecarRoutingMark
jq
python3
parserScriptsPythonPath
buildOutboundPy
mkSubscriptionBlock
;
};
inherit (outboundScripts) mkOutboundScript;
singBoxRawOutboundJson =
ob: tag: routingMark:
let
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
in
backendRaw // { inherit tag; } // markAttrs;
xrayRawOutboundJson =
ob: tag:
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
streamSettings.sockopt = {
mark = xraySidecarRoutingMark;
domainStrategy = "UseIP";
};
};
mkHybridOutboundBlock =
ob: routingMark: tag:
if ob.xrayJson != null then
let
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.singBoxJson != null || ob.json != null then
let
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson;
in
''
# outbound: ${tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
singBoxCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
}
'';
xrayCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark}
'';
in
if ob.backend == "xray" then
''
# outbound: ${tag} (hybrid forced XRay sidecar)
URL=$(cat "${urlSource}")
OB_JSON=$(${xrayCommand})
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.backend == "sing-box" then
''
# outbound: ${tag} (hybrid forced SingBox)
URL=$(cat "${urlSource}")
OB_JSON=$(${singBoxCommand})
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${tag} (hybrid auto)
URL=$(cat "${urlSource}")
if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$OB_JSON"
else
SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)"
if OB_JSON=$(${xrayCommand}); then
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
else
echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2
if [ -n "$SING_BOX_PARSE_ERROR" ]; then
printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2
fi
exit 1
fi
fi
'';
mkSubscriptionBlock =
sub: routingMark:
let
cacheFile = mkSubscriptionCacheFile sub;
markFilter = routingMarkJq routingMark;
in
''
# subscription: ${sub.tag}
CACHE_DIR="${subscriptionCacheDir}"
CACHE_FILE="${cacheFile}"
_proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag}
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
_proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true
else
rm -f "$CACHE_FILE.tmp"
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
${
if hybridEnabled then
''
if [ -f "$CACHE_FILE" ]; then
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$CACHE_FILE")
fi
''
else
''
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
''
}
'';
xrayUrltestTagFilter = ''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
'';
hybridRuntimeHelpersBlock =
routingMark: xraySidecarBasePort: xrayDnsBridgePort:
lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]'
XRAY_INBOUNDS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_next_xray_sidecar_port() {
local port="$XRAY_SIDECAR_NEXT_PORT"
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
printf '%s\n' "$port"
}
_proxy_suite_add_xray_sidecar_ob() {
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
port="$(_proxy_suite_next_xray_sidecar_port)"
auth="proxy-suite-xray-$port"
inbound_tag="$tag-inbound"
ob=$(${jq} \
--arg tag "$tag" \
--argjson mark ${toString xraySidecarRoutingMark} \
'.tag = $tag
| .streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| .streamSettings.sockopt.mark = $mark
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
<<< "$ob")
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
inbound=$(${jq} -n \
--arg tag "$inbound_tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
route_rule=$(${jq} -n \
--arg inbound "$inbound_tag" \
--arg outbound "$tag" \
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
sing_ob=$(${jq} -n \
--arg tag "$tag" \
--arg auth "$auth" \
--argjson port "$port" \
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
}}')
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson inbounds "$XRAY_INBOUNDS_JSON" \
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \
'
def bind_xray_sidecar($interface):
if $interface == "" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: $inbounds,
outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
'';
mkOutboundScript =
routingMark:
let
outboundBlocks =
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
(if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock)
(builtins.head proxyCfg.outbounds)
routingMark
"proxy"
else
lib.concatMapStrings (
ob: (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) ob routingMark ob.tag
) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark
) proxyCfg.subscriptions;
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2
exit 1
fi
'';
wrapperBlock =
if pureXrayEnabled && selectionMode == "urltest" then
xrayUrltestTagFilter
else if collapseNamedOutbounds then
lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.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 selectionMode == "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
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.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 + requireOutboundsBlock + wrapperBlock;
writeProxychainsConfigBlock = ''
{
printf '%s\n' 'strict_chain'
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
printf '%s\n' 'tcp_read_time_out 15000'
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listenAddress} \
${lib.escapeShellArg (toString proxyCfg.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
chmod 640 "${runtimeProxychainsConfig}"
'';
restartActiveConfigConsumersBlock =
lib.concatMapStrings
(svc: ''
if ${systemctl} is-active --quiet ${svc}; then
${systemctl} restart ${svc}
fi
'')
[
"proxy-suite-socks"
"proxy-suite-tun"
"proxy-suite-per-app-tun"
];
routeModeBlacklistTail =
if pureXrayEnabled then
''
+ .proxyGeo
+ .block
''
else
''
+ .block
+ .proxyGeo
'';
routeModeCaseBlock = ''
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
fi
case "$ROUTE_MODE" in
blacklist)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
whitelist)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-proxy)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
+ .proxyPrimary
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-bypass)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "block") | .entries) | add // [])
+ .safetyDirect
+ .block
' "${routeModeRulesFile}")
;;
*)
ROUTE_MODE=""
;;
esac
'';
mkBackendJqFilter =
if pureXrayEnabled then
''
def xray_bind_outbound($interface):
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
.
else
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr):
if $dns_final == "local" then
[$local_addr, $remote_addr]
elif $dns_final == "remote" then
[$remote_addr, $local_addr]
else
[$remote_addr, $local_addr]
end;
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| if $xray_tun_dns_runtime then
.dns.servers = xray_dns_server_order($dns_final)
| if $dns_final == "" then
.
else
(.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client)
end
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
else
''
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = $obs + .outbounds
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then .dns.rules = [] else . end
else . end
'';
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" mkBackendJqFilter;
mkStartScript =
{
name,
runtimeDir,
configFile,
routingMark ? null,
enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false,
xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}:
pkgs.writeShellScript name ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
XRAY_LOGLEVEL=""
XRAY_TUN_BIND_INTERFACE=""
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
ROUTE_MODE=""
ROUTE_FINAL=""
DNS_FINAL=""
ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
umask 077
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
${writeProxychainsConfigBlock}
''}
${lib.optionalString xrayEnabled ''
if [ -r "${xrayLoglevelFile}" ]; then
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
fi
''}
${lib.optionalString xrayTunEgressBinding ''
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk '
/dev/ {
for (i = 1; i <= NF; i++) {
if ($i == "dev" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
exit 1
fi
''}
${routeModeCaseBlock}
${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
--arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString enableLocalProxyAuth ''
chmod 600 "$RUNTIME_DIR/config.json"
''}
${
if hybridEnabled then
''
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
XRAY_SIDECAR_PID=""
_proxy_suite_cleanup_xray_sidecar() {
if [ -n "$XRAY_SIDECAR_PID" ]; then
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
fi
}
trap _proxy_suite_cleanup_xray_sidecar EXIT
trap 'exit 143' INT TERM
${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
XRAY_SIDECAR_PID="$!"
${pkgs.coreutils}/bin/sleep 0.2
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
XRAY_SIDECAR_STATUS=1
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
exit "$XRAY_SIDECAR_STATUS"
fi
${singBox} run -c "$RUNTIME_DIR/config.json" &
SING_BOX_PID="$!"
SING_BOX_STATUS=0
wait "$SING_BOX_PID" || SING_BOX_STATUS="$?"
exit "$SING_BOX_STATUS"
fi
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
''
else
''
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
''
}
'';
startSocks = mkStartScript {
name = "proxy-suite-start-socks";
runtimeDir = "/run/proxy-suite-socks";
configFile = tproxyFile;
routingMark = globalTproxy.proxyMark;
enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
hybridRuntimeHelpersBlock = import ./script-blocks/hybrid-runtime-helpers.nix {
inherit
lib
jq
hybridEnabled
xraySidecarRoutingMark
;
};
startTun = mkStartScript {
name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
backendJqFilter = import ./script-blocks/backend-jq-filter.nix {
inherit
pureXrayEnabled
selectionMode
;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" backendJqFilter;
startPerAppTun = mkStartScript {
name = "proxy-suite-start-per-app-tun";
runtimeDir = "/run/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.perAppTun;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
startScripts = import ./start-scripts.nix {
inherit
lib
pkgs
proxyCfg
perAppRoutingCfg
userControlCfg
globalTproxy
xrayEnabled
hybridEnabled
pureXrayEnabled
constants
jq
singBox
xray
backendBin
routeModeStateFile
routeModeRulesFile
xrayLoglevelFile
runtimeProxychainsConfig
localProxyAuth
localProxyAuthEnabled
localProxyAuthPasswordSource
backendJqFilterFile
hybridRuntimeHelpersBlock
subscriptionCacheHelpersBlock
mkOutboundScript
tproxyFile
tunFile
perAppTunFile
;
};
inherit (startScripts) startSocks startTun startPerAppTun;
mkSubscriptionFetchBlock =
sub:
let
cacheFile = mkSubscriptionCacheFile sub;
in
''
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
else
rm -f "${cacheFile}.tmp"
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
FAILED=1
fi
'';
controlScripts = import ./control-scripts.nix {
inherit
lib
pkgs
proxyCfg
routeModeStateFile
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionFetchBlock
;
};
inherit (controlScripts)
subscriptionUpdateScript
setRouteModeScript
;
subscriptionUpdateScript = pkgs.writeShellScript "proxy-suite-subscription-update" ''
set -euo pipefail
CACHE_DIR="${subscriptionCacheDir}"
mkdir -p "$CACHE_DIR"
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock}
fi
exit "$FAILED"
'';
setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" ''
set -euo pipefail
mode="''${1:-}"
case "$mode" in
default)
;;
whitelist)
;;
blacklist)
;;
all-proxy)
;;
all-bypass)
;;
*)
echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2
exit 1
;;
esac
mkdir -p "$(dirname "${routeModeStateFile}")"
if [ "$mode" = "default" ]; then
rm -f "${routeModeStateFile}"
else
printf '%s\n' "$mode" > "${routeModeStateFile}"
fi
${restartActiveConfigConsumersBlock}
'';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
);
in
{
inherit startSocks startTun startPerAppTun;
@@ -0,0 +1,288 @@
# Backend startup script derivations.
{
lib,
pkgs,
proxyCfg,
perAppRoutingCfg,
userControlCfg,
globalTproxy,
xrayEnabled,
hybridEnabled,
pureXrayEnabled,
constants,
jq,
singBox,
xray,
backendBin,
routeModeStateFile,
routeModeRulesFile,
xrayLoglevelFile,
runtimeProxychainsConfig,
localProxyAuth,
localProxyAuthEnabled,
localProxyAuthPasswordSource,
backendJqFilterFile,
hybridRuntimeHelpersBlock,
subscriptionCacheHelpersBlock,
mkOutboundScript,
tproxyFile,
tunFile,
perAppTunFile,
}:
let
inherit (constants)
xrayDnsBridgePorts
xraySidecarBasePorts
;
routeModeBlacklistTail =
if pureXrayEnabled then
''
+ .proxyGeo
+ .block
''
else
''
+ .block
+ .proxyGeo
'';
routeModeCaseBlock = ''
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
fi
case "$ROUTE_MODE" in
blacklist)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
whitelist)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(.entries) | add // [])
+ .proxyPrimary
+ .direct
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-proxy)
ROUTE_FINAL="proxy"
DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
+ .proxyPrimary
+ .safetyDirect
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-bypass)
ROUTE_FINAL="direct"
DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c '
.common
+ (.custom | map(select(.category == "block") | .entries) | add // [])
+ .safetyDirect
+ .block
' "${routeModeRulesFile}")
;;
*)
ROUTE_MODE=""
;;
esac
'';
writeProxychainsConfigBlock = ''
{
printf '%s\n' 'strict_chain'
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
printf '%s\n' 'tcp_read_time_out 15000'
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listenAddress} \
${lib.escapeShellArg (toString proxyCfg.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
chmod 640 "${runtimeProxychainsConfig}"
'';
mkStartScript =
{
name,
runtimeDir,
configFile,
routingMark ? null,
enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false,
xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}:
pkgs.writeShellScript name ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
XRAY_LOGLEVEL=""
XRAY_TUN_BIND_INTERFACE=""
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
ROUTE_MODE=""
ROUTE_FINAL=""
DNS_FINAL=""
ROUTE_RULES_JSON='[]'
ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
umask 077
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
${writeProxychainsConfigBlock}
''}
${lib.optionalString xrayEnabled ''
if [ -r "${xrayLoglevelFile}" ]; then
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
fi
''}
${lib.optionalString xrayTunEgressBinding ''
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk '
/dev/ {
for (i = 1; i <= NF; i++) {
if ($i == "dev" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
exit 1
fi
''}
${routeModeCaseBlock}
${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
--arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString enableLocalProxyAuth ''
chmod 600 "$RUNTIME_DIR/config.json"
''}
${
if hybridEnabled then
''
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
XRAY_SIDECAR_PID=""
_proxy_suite_cleanup_xray_sidecar() {
if [ -n "$XRAY_SIDECAR_PID" ]; then
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
fi
}
trap _proxy_suite_cleanup_xray_sidecar EXIT
trap 'exit 143' INT TERM
${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
XRAY_SIDECAR_PID="$!"
${pkgs.coreutils}/bin/sleep 0.2
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
XRAY_SIDECAR_STATUS=1
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
exit "$XRAY_SIDECAR_STATUS"
fi
${singBox} run -c "$RUNTIME_DIR/config.json" &
SING_BOX_PID="$!"
SING_BOX_STATUS=0
wait "$SING_BOX_PID" || SING_BOX_STATUS="$?"
exit "$SING_BOX_STATUS"
fi
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
''
else
''
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
''
}
'';
startSocks = mkStartScript {
name = "proxy-suite-start-socks";
runtimeDir = "/run/proxy-suite-socks";
configFile = tproxyFile;
routingMark = globalTproxy.proxyMark;
enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
};
startTun = mkStartScript {
name = "proxy-suite-start-tun";
runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
};
startPerAppTun = mkStartScript {
name = "proxy-suite-start-per-app-tun";
runtimeDir = "/run/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = xraySidecarBasePorts.perAppTun;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
in
{
inherit startSocks startTun startPerAppTun;
}
+233
View File
@@ -0,0 +1,233 @@
# Systemd unit definitions for proxy-suite services and timers.
{
lib,
builders,
proxyCfg,
proxyEnabled,
hybridEnabled,
pureXrayEnabled,
globalTun,
globalTproxy,
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretEnabled,
hasSubscriptions,
scripts,
perAppRouting,
routingScripts,
}:
let
inherit (builders)
mkAnchorService
mkRestartingService
mkOneshotService
mkUserRuleService
;
inherit (routingScripts)
xrayTunUpScript
tproxyUpScript
tproxyDownScript
tunCleanupScript
;
serviceNames = {
socks = "proxy-suite-socks";
tproxy = "proxy-suite-tproxy";
tun = "proxy-suite-tun";
perAppTun = "proxy-suite-per-app-tun";
perAppTproxy = "proxy-suite-per-app-tproxy";
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
};
backendDescription =
if pureXrayEnabled then
"XRay"
else if hybridEnabled then
"sing-box + XRay sidecar"
else
"sing-box";
localProxyAuthEnabled =
proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
systemServiceEntries = [
{
enable = proxyEnabled;
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && globalTproxy.enable;
name = serviceNames.tproxy;
value = mkOneshotService {
description = "proxy-suite TProxy - nftables rules and policy routing";
after = [
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
"${serviceNames.perAppTproxy}.service"
];
execStart = tproxyUpScript;
execStop = tproxyDownScript;
};
}
{
enable = proxyEnabled && globalTun.enable;
name = serviceNames.tun;
value = mkRestartingService {
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = serviceNames.perAppTun;
value = mkRestartingService {
description = "proxy-suite per-app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript;
runtimeDirectory = serviceNames.perAppTun;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled && perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TUN marking for user %i";
backendService = serviceNames.perAppTun;
execStart = "${perAppRouting.perAppTunUserRuleStart} %i";
execStop = "${perAppRouting.perAppTunUserRuleStop} %i";
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = serviceNames.perAppTproxy;
value = mkOneshotService {
description = "proxy-suite per-app-routing TProxy backend";
after = [
"network.target"
"${serviceNames.socks}.service"
];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tproxy}.service"
"${serviceNames.tun}.service"
];
execStart = perAppRouting.perAppTproxyUpScript;
execStop = perAppRouting.perAppTproxyDownScript;
};
}
{
enable = proxyEnabled && perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app TProxy marking for user %i";
backendService = serviceNames.perAppTproxy;
execStart = "${perAppRouting.perAppTproxyUserRuleStart} %i";
execStop = "${perAppRouting.perAppTproxyUserRuleStop} %i";
};
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-user@";
value = mkUserRuleService {
description = "Enable proxy-suite app zapret marking for user %i";
backendService = serviceNames.perAppZapret;
execStart = "${perAppRouting.perAppZapretUserRuleStart} %i";
execStop = "${perAppRouting.perAppZapretUserRuleStop} %i";
};
}
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
execStart = scripts.subscriptionUpdateScript;
stateDirectory = "proxy-suite";
};
}
{
enable = proxyEnabled;
name = "proxy-suite-route-mode@";
value = mkOneshotService {
description = "Set proxy-suite route mode to %i";
execStart = "${scripts.setRouteModeScript} %i";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
{
enable = perAppRoutingTun.enable;
name = "${serviceNames.perAppTun}-anchor";
value = mkAnchorService perAppRouting.perAppTunSliceName "Anchor service for proxy-suite app TUN slice";
}
{
enable = perAppRoutingTproxy.enable;
name = "${serviceNames.perAppTproxy}-anchor";
value = mkAnchorService perAppRouting.perAppTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
{
enable = perAppZapretEnabled;
name = "${serviceNames.perAppZapret}-anchor";
value = mkAnchorService perAppRouting.perAppZapretSliceName "Anchor service for proxy-suite app zapret slice";
}
];
timerEntries = [
{
enable = proxyEnabled && hasSubscriptions;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
];
in
{
inherit
serviceNames
localProxyAuthEnabled
systemServiceEntries
userServiceEntries
timerEntries
;
}
+1 -1
View File
@@ -75,7 +75,7 @@ in
wants = [ "network-online.target" ];
wantedBy = [ "multi-user.target" ];
serviceConfig = {
ExecStart = "${startScript}";
ExecStart = startScript;
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
Restart = "on-failure";
RestartSec = 5;
+15 -357
View File
@@ -1,4 +1,4 @@
# zapret DPI bypass configuration + optional CIDR exemption from NFQUEUE
# zapret DPI bypass services and optional CIDR exemption from NFQUEUE.
{
lib,
pkgs,
@@ -14,311 +14,22 @@ let
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
zapretDomainGroups = import ./zapret-domain-groups.nix { inherit lib zapret; };
iptables = "${pkgs.iptables}/bin/iptables";
runtimeDeps = lib.attrValues {
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
wget
bash
kmod
findutils
gnused
gnugrep
procps
util-linux
zapretPackages = import ./zapret/packages.nix {
inherit
lib
pkgs
cfg
zapret
;
};
inherit (zapretPackages)
globalZapretPackage
perAppZapretPackage
globalZapretEnv
perAppZapretEnv
;
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
effectiveHostlistRules = map (
rule:
rule
// {
domains = zapretDomainGroups.effectiveRuleDomains rule;
ips = zapretDomainGroups.effectiveRuleIps rule;
presets = zapretDomainGroups.effectiveRulePresets rule;
ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule;
protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule;
}
) zapretCfg.hostlistRules;
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
mkOptionalHostlistFile =
fileName: entries:
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
configName
nfqwsArgs
ipsets
presets
protocols
;
hasDomains = rule.domains != [ ];
hasIps = rule.ips != [ ];
}) effectiveHostlistRules;
}
);
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
patchConfigScriptSrc = builtins.path {
path = ../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
mkGlobalBypassScript =
filterMark:
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
zapret_custom_firewall_nft() {
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? zapretCfg.configName,
gameFilter ? zapretCfg.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
gnused
python3
];
}
''
set -euo pipefail
mkdir -p "$out"
cp -a ${baseZapretPackage}/. "$out/"
chmod -R u+w "$out/opt/zapret" "$out/bin"
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
requested_config=${lib.escapeShellArg configName}
configs_dir="$out/opt/zapret/configs"
selected_config="$configs_dir/$requested_config"
config_name_key() {
printf '%s' "$1" | tr -d '[:space:]'
}
if [ ! -f "$selected_config" ]; then
requested_key=$(config_name_key "$requested_config")
matched_config=""
for candidate in "$configs_dir"/*; do
[ -f "$candidate" ] || continue
candidate_name="''${candidate##*/}"
if [ "$(config_name_key "$candidate_name")" = "$requested_key" ]; then
if [ -n "$matched_config" ]; then
echo "proxy-suite: zapret config '$requested_config' is ambiguous after whitespace normalization" >&2
echo "proxy-suite: matched '$matched_config' and '$candidate'" >&2
exit 1
fi
matched_config="$candidate"
fi
done
if [ -n "$matched_config" ]; then
selected_config="$matched_config"
fi
fi
if [ -f "$selected_config" ]; then
cp "$selected_config" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '$requested_config' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
${pkgs.gnused}/bin/sed -i \
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
"$out/opt/zapret/init.d/sysv/functions"
append_list_file() {
local target="$1"
local extra_file="$2"
local tmp="$out/opt/zapret/hostlists/$target.tmp"
cat "$out/opt/zapret/hostlists/$target" > "$tmp"
${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp"
cat "$extra_file" >> "$tmp"
mv "$tmp" "$out/opt/zapret/hostlists/$target"
}
set_config_var() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
else
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
fi
}
${lib.concatMapStrings
(
{ name, file }:
lib.optionalString (file != null) ''
append_list_file ${name} ${file}
''
)
[
{
name = "list-general-user.txt";
file = listGeneralFile;
}
{
name = "list-exclude-user.txt";
file = listExcludeFile;
}
{
name = "ipset-all.txt";
file = ipsetAllFile;
}
{
name = "ipset-exclude-user.txt";
file = ipsetExcludeFile;
}
]
}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
rule:
let
domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n"
);
ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n"
);
in
lib.optionalString (rule.domains != [ ]) ''
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
''
+ lib.optionalString (rule.ips != [ ]) ''
cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt"
''
) effectiveHostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.concatMapStrings
(
{ var, value }:
lib.optionalString (value != null) ''
hex=$(printf '0x%x' ${toString value})
set_config_var ${var} "$hex"
''
)
[
{
var = "FILTER_MARK";
value = filterMark;
}
{
var = "DESYNC_MARK";
value = desyncMark;
}
{
var = "DESYNC_MARK_POSTNAT";
value = desyncMarkPostnat;
}
]
}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.gameFilter;
forceDisableFilterMark = true;
customScript =
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
};
perAppZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-per-app-zapret";
gameFilter = "all";
filterMark = perAppZapretCfg.filterMark;
qnum = perAppZapretCfg.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_per_app_zapret";
};
iptables = "${pkgs.iptables}/bin/iptables";
zapretCommonPreStart = package: ''
${package}/opt/zapret/init.d/sysv/zapret stop || true
@@ -332,13 +43,6 @@ let
fi
'';
mkZapretEnv = package: [
"ZAPRET_BASE=${package}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
globalZapretEnv = mkZapretEnv globalZapretPackage;
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
perAppZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-per-app-zapret-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
@@ -369,53 +73,7 @@ let
'') zapretCfg.cidrExemption.cidrs;
in
{
assertions = [
{
assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames);
message = "proxy-suite: zapret.hostlistRules names must be unique";
}
{
assertion = builtins.all (
rule: zapretDomainGroups.effectiveRuleDomains rule != [ ] || zapretDomainGroups.effectiveRuleIps rule != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
}
{
assertion = builtins.all (
rule:
rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ] || rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule == [ ]
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.preset != null || builtins.length rule.defaultDomains <= 1
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
}
{
assertion = builtins.all (
rule: !(rule.configName != null && rule.nfqwsArgs != [ ])
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.configName == null || rule.preset != null || rule.defaultDomains != [ ] || rule.ips != [ ] || rule.defaultIps != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
}
];
assertions = zapretPackages.assertions;
environment.systemPackages = lib.mkBefore (
lib.optionals zapretCfg.enable [ globalZapretPackage ]
@@ -0,0 +1,232 @@
# Builds derived zapret packages from the curated upstream package.
{
lib,
pkgs,
zapretCfg,
baseZapretPackage,
effectiveHostlistRules,
listGeneralFile,
listExcludeFile,
ipsetAllFile,
ipsetExcludeFile,
hostlistRuleSpec,
patchConfigScript,
}:
let
mkGlobalBypassScript =
filterMark:
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
zapret_custom_firewall_nft() {
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite per-app-zapret bypass"
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? zapretCfg.configName,
gameFilter ? zapretCfg.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
gnused
python3
];
}
''
set -euo pipefail
mkdir -p "$out"
cp -a ${baseZapretPackage}/. "$out/"
chmod -R u+w "$out/opt/zapret" "$out/bin"
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
requested_config=${lib.escapeShellArg configName}
configs_dir="$out/opt/zapret/configs"
selected_config="$configs_dir/$requested_config"
config_name_key() {
printf '%s' "$1" | tr -d '[:space:]'
}
if [ ! -f "$selected_config" ]; then
requested_key=$(config_name_key "$requested_config")
matched_config=""
for candidate in "$configs_dir"/*; do
[ -f "$candidate" ] || continue
candidate_name="''${candidate##*/}"
if [ "$(config_name_key "$candidate_name")" = "$requested_key" ]; then
if [ -n "$matched_config" ]; then
echo "proxy-suite: zapret config '$requested_config' is ambiguous after whitespace normalization" >&2
echo "proxy-suite: matched '$matched_config' and '$candidate'" >&2
exit 1
fi
matched_config="$candidate"
fi
done
if [ -n "$matched_config" ]; then
selected_config="$matched_config"
fi
fi
if [ -f "$selected_config" ]; then
cp "$selected_config" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '$requested_config' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
${pkgs.gnused}/bin/sed -i \
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
"$out/opt/zapret/init.d/sysv/functions"
append_list_file() {
local target="$1"
local extra_file="$2"
local tmp="$out/opt/zapret/hostlists/$target.tmp"
cat "$out/opt/zapret/hostlists/$target" > "$tmp"
${pkgs.gnused}/bin/sed -i -e '$a\' "$tmp"
cat "$extra_file" >> "$tmp"
mv "$tmp" "$out/opt/zapret/hostlists/$target"
}
set_config_var() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
else
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
fi
}
${lib.concatMapStrings
(
{ name, file }:
lib.optionalString (file != null) ''
append_list_file ${name} ${file}
''
)
[
{
name = "list-general-user.txt";
file = listGeneralFile;
}
{
name = "list-exclude-user.txt";
file = listExcludeFile;
}
{
name = "ipset-all.txt";
file = ipsetAllFile;
}
{
name = "ipset-exclude-user.txt";
file = ipsetExcludeFile;
}
]
}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
rule:
let
domainsFile = pkgs.writeText "proxy-suite-zapret-hostlist-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.domains) + "\n"
);
ipsetFile = pkgs.writeText "proxy-suite-zapret-ipset-${rule.name}.txt" (
lib.concatStringsSep "\n" (lib.unique rule.ips) + "\n"
);
in
lib.optionalString (rule.domains != [ ]) ''
cp ${domainsFile} "$out/opt/zapret/hostlists/list-${rule.name}.txt"
''
+ lib.optionalString (rule.ips != [ ]) ''
cp ${ipsetFile} "$out/opt/zapret/hostlists/ipset-${rule.name}.txt"
''
) effectiveHostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.concatMapStrings
(
{ var, value }:
lib.optionalString (value != null) ''
hex=$(printf '0x%x' ${toString value})
set_config_var ${var} "$hex"
''
)
[
{
var = "FILTER_MARK";
value = filterMark;
}
{
var = "DESYNC_MARK";
value = desyncMark;
}
{
var = "DESYNC_MARK_POSTNAT";
value = desyncMarkPostnat;
}
]
}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
in
{
inherit
mkDerivedZapretPackage
mkGlobalBypassScript
;
}
+201
View File
@@ -0,0 +1,201 @@
# Derived zapret packages and validation.
{
lib,
pkgs,
cfg,
zapret,
}:
let
zapretCfg = cfg.zapret;
perAppZapretCfg = zapretCfg.perApp;
zapretDomainGroups = import ../zapret-domain-groups.nix { inherit lib zapret; };
runtimeDeps = lib.attrValues {
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
wget
bash
kmod
findutils
gnused
gnugrep
procps
util-linux
;
};
effectiveHostlistRules = map (
rule:
rule
// {
domains = zapretDomainGroups.effectiveRuleDomains rule;
ips = zapretDomainGroups.effectiveRuleIps rule;
presets = zapretDomainGroups.effectiveRulePresets rule;
ipsets = zapretDomainGroups.effectiveRuleIpsetFamilies rule;
protocols = zapretDomainGroups.effectiveRuleProtocolFamilies rule;
}
) zapretCfg.hostlistRules;
hostlistRuleNames = map (rule: rule.name) zapretCfg.hostlistRules;
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
if upstreamPackages ? zapret then upstreamPackages.zapret else upstreamPackages.default;
mkOptionalHostlistFile =
fileName: entries:
if entries != [ ] then pkgs.writeText fileName (lib.concatStringsSep "\n" entries + "\n") else null;
listGeneralFile = mkOptionalHostlistFile "proxy-suite-zapret-list-general-user.txt" zapretCfg.listGeneral;
listExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-list-exclude-user.txt" zapretCfg.listExclude;
ipsetAllFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-all.txt" zapretCfg.ipsetAll;
ipsetExcludeFile = mkOptionalHostlistFile "proxy-suite-zapret-ipset-exclude-user.txt" zapretCfg.ipsetExclude;
hostlistRuleSpec = pkgs.writeText "proxy-suite-zapret-hostlist-rules.json" (
builtins.toJSON {
includeExtraUpstreamLists = zapretCfg.includeExtraUpstreamLists;
entries = map (rule: {
inherit (rule)
name
configName
nfqwsArgs
ipsets
presets
protocols
;
hasDomains = rule.domains != [ ];
hasIps = rule.ips != [ ];
}) effectiveHostlistRules;
}
);
selectedConfigName = lib.strings.sanitizeDerivationName zapretCfg.configName;
patchConfigScriptSrc = builtins.path {
path = ../../../scripts/patch-zapret-config.py;
name = "patch-zapret-config.py";
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
packageBuilder = import ./package-builder.nix {
inherit
lib
pkgs
zapretCfg
baseZapretPackage
effectiveHostlistRules
listGeneralFile
listExcludeFile
ipsetAllFile
ipsetExcludeFile
hostlistRuleSpec
patchConfigScript
;
};
inherit (packageBuilder)
mkDerivedZapretPackage
mkGlobalBypassScript
;
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = zapretCfg.gameFilter;
forceDisableFilterMark = true;
customScript =
if perAppZapretCfg.enable then mkGlobalBypassScript (toString perAppZapretCfg.filterMark) else null;
};
perAppZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-per-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-per-app-zapret";
gameFilter = "all";
filterMark = perAppZapretCfg.filterMark;
qnum = perAppZapretCfg.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_per_app_zapret";
};
mkZapretEnv = package: [
"ZAPRET_BASE=${package}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
assertions = [
{
assertion = builtins.length hostlistRuleNames == builtins.length (lib.unique hostlistRuleNames);
message = "proxy-suite: zapret.hostlistRules names must be unique";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule != [ ]
|| zapretDomainGroups.effectiveRuleIps rule != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must define domains, defaultDomains, ips, or defaultIps";
}
{
assertion = builtins.all (
rule:
rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: each zapret.hostlistRules entry must set preset, defaultDomains, ips/defaultIps, nfqwsArgs, or a valid configName source";
}
{
assertion = builtins.all (
rule:
zapretDomainGroups.effectiveRuleDomains rule == [ ]
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.nfqwsArgs != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries with domains require preset, defaultDomains, or nfqwsArgs";
}
{
assertion = builtins.all (
rule: rule.preset != null || builtins.length rule.defaultDomains <= 1
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules entries without preset may infer a rule family from only one defaultDomains entry; split groups into separate rules or set preset";
}
{
assertion = builtins.all (
rule: !(rule.configName != null && rule.nfqwsArgs != [ ])
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName cannot be used together with nfqwsArgs";
}
{
assertion = builtins.all (
rule:
rule.configName == null
|| rule.preset != null
|| rule.defaultDomains != [ ]
|| rule.ips != [ ]
|| rule.defaultIps != [ ]
) zapretCfg.hostlistRules;
message = "proxy-suite: zapret.hostlistRules.*.configName requires preset, defaultDomains, ips, or defaultIps";
}
];
in
{
inherit
globalZapretPackage
perAppZapretPackage
;
globalZapretEnv = mkZapretEnv globalZapretPackage;
perAppZapretEnv = mkZapretEnv perAppZapretPackage;
inherit assertions;
}