some simplifications and improvements

This commit is contained in:
FUFSoB committed 2026-04-15 13:43:18 +05:00
1 parent fe41f56cc5
commit d3c68f7a9a
7 files changed
+290 -528

No files matched your search

+7 -27
View File
@@ -1752,8 +1752,7 @@ one of “udp”, “tcp”, “tls”
Netfilter mark set on packets intercepted by TProxy so policy routing Netfilter mark set on packets intercepted by TProxy so policy routing
can send them to the local loopback route table\. can send them to the local loopback route table\. Used by TProxy mode\.
Only relevant when singBox\.tproxy\.enable = true\.
@@ -2236,8 +2235,7 @@ true
Netfilter mark set on sing-box’s own outbound packets so they bypass Netfilter mark set on sing-box’s own outbound packets so they bypass
TProxy re-interception loops\. TProxy re-interception loops\. Used by TProxy mode\.
Only relevant when singBox\.tproxy\.enable = true\.
@@ -2271,8 +2269,7 @@ signed integer
Policy routing table used to redirect TProxy-marked packets to the Policy routing table used to redirect TProxy-marked packets to the
loopback interface\. loopback interface\. Used by TProxy mode\.
Only relevant when singBox\.tproxy\.enable = true\.
@@ -3290,7 +3287,6 @@ true
Whether to start proxy-suite-tproxy automatically during boot by Whether to start proxy-suite-tproxy automatically during boot by
attaching it to multi-user\.target\. attaching it to multi-user\.target\.
Only relevant when singBox\.tproxy\.enable = true\.
Cannot be enabled together with singBox\.tun\.autostart\. Cannot be enabled together with singBox\.tun\.autostart\.
@@ -3325,7 +3321,6 @@ true
Subnets whose traffic bypasses TProxy interception, except DNS (port 53)\. Subnets whose traffic bypasses TProxy interception, except DNS (port 53)\.
Only relevant when singBox\.tproxy\.enable = true\.
Typically this should include your LAN subnet(s)\. VM bridge networks Typically this should include your LAN subnet(s)\. VM bridge networks
should usually go here too, or use zapret\.cidrExemption for should usually go here too, or use zapret\.cidrExemption for
@@ -3367,8 +3362,7 @@ list of string
Listen port for the local sing-box TProxy inbound\. Listen port for the local sing-box TProxy inbound\. Used by TProxy mode\.
Only relevant when singBox\.tproxy\.enable = true\.
@@ -3435,7 +3429,6 @@ true
Address assigned to the TUN interface in CIDR notation\. Address assigned to the TUN interface in CIDR notation\.
Only relevant when singBox\.tun\.enable = true\.
@@ -3470,7 +3463,6 @@ string
Whether to start proxy-suite-tun automatically during boot by Whether to start proxy-suite-tun automatically during boot by
attaching it to multi-user\.target\. attaching it to multi-user\.target\.
Only relevant when singBox\.tun\.enable = true\.
Cannot be enabled together with singBox\.tproxy\.autostart\. Cannot be enabled together with singBox\.tproxy\.autostart\.
@@ -3505,7 +3497,6 @@ true
Name of the TUN interface created by proxy-suite-tun\. Name of the TUN interface created by proxy-suite-tun\.
Only relevant when singBox\.tun\.enable = true\.
@@ -3539,7 +3530,6 @@ string
MTU for the TUN interface created by proxy-suite-tun\. MTU for the TUN interface created by proxy-suite-tun\.
Only relevant when singBox\.tun\.enable = true\.
@@ -3716,7 +3706,6 @@ true
Map of Telegram DC ID to IP address for relay\. Map of Telegram DC ID to IP address for relay\.
Only relevant when tgWsProxy\.enable = true\.
@@ -3754,7 +3743,6 @@ attribute set of string
Address to bind tg-ws-proxy to\. Address to bind tg-ws-proxy to\.
Only relevant when tgWsProxy\.enable = true\.
@@ -3788,7 +3776,6 @@ string
Listen port for the tg-ws-proxy service\. Listen port for the tg-ws-proxy service\.
Only relevant when tgWsProxy\.enable = true\.
@@ -3927,9 +3914,8 @@ true
Whether to install an XDG autostart entry for the tray application for Whether to install an XDG autostart entry for the tray application
graphical users\. for graphical users\.
Only relevant when tray\.enable = true\.
@@ -3963,7 +3949,6 @@ true
Status polling interval in seconds for the tray application\. Status polling interval in seconds for the tray application\.
Only relevant when tray\.enable = true\.
@@ -4168,8 +4153,6 @@ true
Subnets to exempt from zapret’s NFQUEUE mangle rules\. Subnets to exempt from zapret’s NFQUEUE mangle rules\.
Only relevant when zapret\.enable = true and cidrExemption\.enable = true\.
Useful when a VM (libvirt, etc\.) is behind NAT and zapret Useful when a VM (libvirt, etc\.) is behind NAT and zapret
would corrupt its traffic through the host’s nftables\. would corrupt its traffic through the host’s nftables\.
@@ -4207,9 +4190,7 @@ list of string
zapret strategy preset name passed through to the generated zapret zapret strategy preset name passed through to the generated zapret configuration\.
configuration\.
Only relevant when zapret\.enable = true\.
@@ -4243,7 +4224,6 @@ string
zapret game traffic filter mode: “all”, “tcp”, “udp”, or “null” to disable\. zapret game traffic filter mode: “all”, “tcp”, “udp”, or “null” to disable\.
Only relevant when zapret\.enable = true\.
+1 -1
View File
@@ -47,7 +47,7 @@ in
cfg cfg
; ;
inherit (configs) tproxyFile tunFile appTunFile; inherit (configs) tproxyFile tunFile appTunFile;
inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft; inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
} }
)) ))
+30 -22
View File
@@ -11,15 +11,8 @@ let
artp = cfg.appRouting.backends.tproxy; artp = cfg.appRouting.backends.tproxy;
arz = cfg.appRouting.backends.zapret; arz = cfg.appRouting.backends.zapret;
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: '' # Shared across all three nftables rule files that do IPv4 routing.
ip daddr ${cidr} tcp dport != 53 return reservedIpBlock = ''
ip daddr ${cidr} udp dport != 53 return
'') subnets;
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
define RESERVED_IP = { define RESERVED_IP = {
10.0.0.0/8, 10.0.0.0/8,
100.64.0.0/10, 100.64.0.0/10,
@@ -31,7 +24,18 @@ let
240.0.0.0/4, 240.0.0.0/4,
255.255.255.255/32 255.255.255.255/32
} }
'';
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') subnets;
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
${reservedIpBlock}
table ip singbox { table ip singbox {
chain prerouting { chain prerouting {
type filter hook prerouting priority mangle; policy accept; type filter hook prerouting priority mangle; policy accept;
@@ -55,18 +59,7 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
''; '';
appTproxyRulesFile = pkgs.writeText "proxy-suite-app-tproxy.nft" '' appTproxyRulesFile = pkgs.writeText "proxy-suite-app-tproxy.nft" ''
define RESERVED_IP = { ${reservedIpBlock}
10.0.0.0/8,
100.64.0.0/10,
127.0.0.0/8,
169.254.0.0/16,
172.16.0.0/12,
192.0.0.0/24,
224.0.0.0/4,
240.0.0.0/4,
255.255.255.255/32
}
table ip proxy_suite_app_tproxy { table ip proxy_suite_app_tproxy {
chain prerouting { chain prerouting {
type filter hook prerouting priority mangle; policy accept; type filter hook prerouting priority mangle; policy accept;
@@ -104,10 +97,25 @@ ${lib.optionalString art.enable " meta mark ${toString art.fwmark}
} }
''; '';
appTunChainFile = pkgs.writeText "proxy-suite-app-tun-chain.nft" ''
${reservedIpBlock}
table inet proxy_suite_app_tun {
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${lib.concatMapStrings (cidr: ''
ip daddr ${cidr} return
'') art.localSubnets}
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
meta mark ${toString art.fwmark} return
}
}
'';
ip = "${pkgs.iproute2}/bin/ip"; ip = "${pkgs.iproute2}/bin/ip";
nft = "${pkgs.nftables}/bin/nft"; nft = "${pkgs.nftables}/bin/nft";
in in
{ {
inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile ip nft; inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
} }
+17 -62
View File
@@ -549,8 +549,7 @@ in
type = types.port; type = types.port;
default = 1081; default = 1081;
description = '' description = ''
Listen port for the local sing-box TProxy inbound. Listen port for the local sing-box TProxy inbound. Used by TProxy mode.
Only relevant when singBox.tproxy.enable = true.
''; '';
example = 1081; example = 1081;
}; };
@@ -560,8 +559,7 @@ in
default = 1; default = 1;
description = '' description = ''
Netfilter mark set on packets intercepted by TProxy so policy routing Netfilter mark set on packets intercepted by TProxy so policy routing
can send them to the local loopback route table. can send them to the local loopback route table. Used by TProxy mode.
Only relevant when singBox.tproxy.enable = true.
''; '';
example = 1; example = 1;
}; };
@@ -571,8 +569,7 @@ in
default = 2; default = 2;
description = '' description = ''
Netfilter mark set on sing-box's own outbound packets so they bypass Netfilter mark set on sing-box's own outbound packets so they bypass
TProxy re-interception loops. TProxy re-interception loops. Used by TProxy mode.
Only relevant when singBox.tproxy.enable = true.
''; '';
example = 2; example = 2;
}; };
@@ -582,8 +579,7 @@ in
default = 100; default = 100;
description = '' description = ''
Policy routing table used to redirect TProxy-marked packets to the Policy routing table used to redirect TProxy-marked packets to the
loopback interface. loopback interface. Used by TProxy mode.
Only relevant when singBox.tproxy.enable = true.
''; '';
example = 100; example = 100;
}; };
@@ -655,7 +651,6 @@ in
description = '' description = ''
Whether to start proxy-suite-tun automatically during boot by Whether to start proxy-suite-tun automatically during boot by
attaching it to multi-user.target. attaching it to multi-user.target.
Only relevant when singBox.tun.enable = true.
Cannot be enabled together with singBox.tproxy.autostart. Cannot be enabled together with singBox.tproxy.autostart.
''; '';
example = true; example = true;
@@ -664,30 +659,21 @@ in
interface = mkOption { interface = mkOption {
type = types.str; type = types.str;
default = "singtun0"; default = "singtun0";
description = '' description = "Name of the TUN interface created by proxy-suite-tun.";
Name of the TUN interface created by proxy-suite-tun.
Only relevant when singBox.tun.enable = true.
'';
example = "singtun0"; example = "singtun0";
}; };
address = mkOption { address = mkOption {
type = types.str; type = types.str;
default = "172.19.0.1/30"; default = "172.19.0.1/30";
description = '' description = "Address assigned to the TUN interface in CIDR notation.";
Address assigned to the TUN interface in CIDR notation.
Only relevant when singBox.tun.enable = true.
'';
example = "172.19.0.1/30"; example = "172.19.0.1/30";
}; };
mtu = mkOption { mtu = mkOption {
type = types.int; type = types.int;
default = 1400; default = 1400;
description = '' description = "MTU for the TUN interface created by proxy-suite-tun.";
MTU for the TUN interface created by proxy-suite-tun.
Only relevant when singBox.tun.enable = true.
'';
example = 1400; example = 1400;
}; };
}; };
@@ -701,7 +687,6 @@ in
description = '' description = ''
Whether to start proxy-suite-tproxy automatically during boot by Whether to start proxy-suite-tproxy automatically during boot by
attaching it to multi-user.target. attaching it to multi-user.target.
Only relevant when singBox.tproxy.enable = true.
Cannot be enabled together with singBox.tun.autostart. Cannot be enabled together with singBox.tun.autostart.
''; '';
example = true; example = true;
@@ -712,7 +697,6 @@ in
default = [ "192.168.0.0/16" ]; default = [ "192.168.0.0/16" ];
description = '' description = ''
Subnets whose traffic bypasses TProxy interception, except DNS (port 53). Subnets whose traffic bypasses TProxy interception, except DNS (port 53).
Only relevant when singBox.tproxy.enable = true.
Typically this should include your LAN subnet(s). VM bridge networks Typically this should include your LAN subnet(s). VM bridge networks
should usually go here too, or use zapret.cidrExemption for should usually go here too, or use zapret.cidrExemption for
@@ -808,15 +792,8 @@ in
}; };
}; };
# Per-outbound and per-action routing rules. # Per-outbound routing rules evaluated before global proxy/direct/block lists.
# These are evaluated before the global proxy/direct/block lists above. # Equivalent to setting outbound.routing.* directly on each outbound definition.
# Use this for fine-grained control: route specific services to specific
# servers, or override the default for particular domains/IPs/geos.
#
# Alternatively, attach routing directly to an outbound via outbound.routing.*
# which is equivalent to adding an entry here with outbound = <that tag>.
#
# Order within this list is preserved (first matching rule wins in sing-box).
rules = mkOption { rules = mkOption {
type = types.listOf routingRuleType; type = types.listOf routingRuleType;
default = [ ]; default = [ ];
@@ -1112,21 +1089,14 @@ in
configName = mkOption { configName = mkOption {
type = types.str; type = types.str;
default = "general(ALT)"; default = "general(ALT)";
description = '' description = "zapret strategy preset name passed through to the generated zapret configuration.";
zapret strategy preset name passed through to the generated zapret
configuration.
Only relevant when zapret.enable = true.
'';
example = "general(ALT)"; example = "general(ALT)";
}; };
gameFilter = mkOption { gameFilter = mkOption {
type = types.str; type = types.str;
default = "null"; default = "null";
description = '' description = ''zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.'';
zapret game traffic filter mode: "all", "tcp", "udp", or "null" to disable.
Only relevant when zapret.enable = true.
'';
example = "null"; example = "null";
}; };
@@ -1234,8 +1204,6 @@ in
]; ];
description = '' description = ''
Subnets to exempt from zapret's NFQUEUE mangle rules. Subnets to exempt from zapret's NFQUEUE mangle rules.
Only relevant when zapret.enable = true and cidrExemption.enable = true.
Useful when a VM (libvirt, etc.) is behind NAT and zapret Useful when a VM (libvirt, etc.) is behind NAT and zapret
would corrupt its traffic through the host's nftables. would corrupt its traffic through the host's nftables.
''; '';
@@ -1249,10 +1217,7 @@ in
pollInterval = mkOption { pollInterval = mkOption {
type = types.int; type = types.int;
default = 5; default = 5;
description = '' description = "Status polling interval in seconds for the tray application.";
Status polling interval in seconds for the tray application.
Only relevant when tray.enable = true.
'';
example = 5; example = 5;
}; };
@@ -1260,9 +1225,8 @@ in
type = types.bool; type = types.bool;
default = true; default = true;
description = '' description = ''
Whether to install an XDG autostart entry for the tray application for Whether to install an XDG autostart entry for the tray application
graphical users. for graphical users.
Only relevant when tray.enable = true.
''; '';
example = true; example = true;
}; };
@@ -1274,20 +1238,14 @@ in
port = mkOption { port = mkOption {
type = types.port; type = types.port;
default = 1076; default = 1076;
description = '' description = "Listen port for the tg-ws-proxy service.";
Listen port for the tg-ws-proxy service.
Only relevant when tgWsProxy.enable = true.
'';
example = 1076; example = 1076;
}; };
host = mkOption { host = mkOption {
type = types.str; type = types.str;
default = "127.0.0.1"; default = "127.0.0.1";
description = '' description = "Address to bind tg-ws-proxy to.";
Address to bind tg-ws-proxy to.
Only relevant when tgWsProxy.enable = true.
'';
example = "127.0.0.1"; example = "127.0.0.1";
}; };
@@ -1319,10 +1277,7 @@ in
dcIps = mkOption { dcIps = mkOption {
type = types.attrsOf types.str; type = types.attrsOf types.str;
default = { }; default = { };
description = '' description = "Map of Telegram DC ID to IP address for relay.";
Map of Telegram DC ID to IP address for relay.
Only relevant when tgWsProxy.enable = true.
'';
example = { example = {
"2" = "149.154.167.220"; "2" = "149.154.167.220";
"4" = "149.154.167.220"; "4" = "149.154.167.220";
+149 -300
View File
@@ -10,6 +10,7 @@
nftablesRulesFile, nftablesRulesFile,
appTproxyRulesFile, appTproxyRulesFile,
appZapretRulesFile, appZapretRulesFile,
appTunChainFile,
ip, ip,
nft, nft,
}: }:
@@ -325,31 +326,6 @@ let
appTunSliceName = "proxy-suite-app-tun.slice"; appTunSliceName = "proxy-suite-app-tun.slice";
appTproxySliceName = "proxy-suite-app-tproxy.slice"; appTproxySliceName = "proxy-suite-app-tproxy.slice";
appZapretSliceName = "proxy-suite-app-zapret.slice"; appZapretSliceName = "proxy-suite-app-zapret.slice";
appTunChainFile = pkgs.writeText "proxy-suite-app-tun-chain.nft" ''
define RESERVED_IP = {
10.0.0.0/8,
100.64.0.0/10,
127.0.0.0/8,
169.254.0.0/16,
172.16.0.0/12,
192.0.0.0/24,
224.0.0.0/4,
240.0.0.0/4,
255.255.255.255/32
}
table inet proxy_suite_app_tun {
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${lib.concatMapStrings (cidr: ''
ip daddr ${cidr} return
'') art.localSubnets}
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
meta mark ${toString art.fwmark} return
}
}
'';
appTunWaitForInterface = pkgs.writeShellScript "proxy-suite-app-tun-wait-for-interface" '' appTunWaitForInterface = pkgs.writeShellScript "proxy-suite-app-tun-wait-for-interface" ''
set -euo pipefail set -euo pipefail
for _ in $(${seqBin} 1 50); do for _ in $(${seqBin} 1 50); do
@@ -375,11 +351,21 @@ ${lib.concatMapStrings (cidr: ''
${ip} route del default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable} 2>/dev/null || true ${ip} route del default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true ${ip} rule del fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true
''; '';
appTunUserRuleStart = # Generate a "start" script that adds a per-user cgroup nftables mark rule.
pkgs.writeShellScript "proxy-suite-app-tun-user-start" '' mkUserRuleStart =
{
name,
nftFamily,
nftTable,
nftChain,
sliceName,
sliceLabel,
markRule,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
set -euo pipefail set -euo pipefail
uid="$1" uid="$1"
rule_comment_prefix="proxy-suite-app-tun-user-$uid" rule_comment_prefix="proxy-suite-${name}-user-$uid"
mark_comment="$rule_comment_prefix-mark" mark_comment="$rule_comment_prefix-mark"
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service" cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
if ! [ -d "$cgroup_root" ]; then if ! [ -d "$cgroup_root" ]; then
@@ -387,43 +373,100 @@ ${lib.concatMapStrings (cidr: ''
exit 1 exit 1
fi fi
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg appTunSliceName} | ${headBin} -n1 || true) cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app TUN slice cgroup does not exist for uid $uid under $cgroup_root" >&2 echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
exit 1 exit 1
fi fi
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/} cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }') cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
handles=$(${nft} -a list chain inet proxy_suite_app_tun output 2>/dev/null \ handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \ | ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true) | ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then if [ -n "$handles" ]; then
while IFS= read -r handle; do while IFS= read -r handle; do
[ -n "$handle" ] || continue [ -n "$handle" ] || continue
${nft} delete rule inet proxy_suite_app_tun output handle "$handle" || true ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles" done <<< "$handles"
fi fi
printf '%s\n' \ printf '%s\n' \
"add rule inet proxy_suite_app_tun output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set ${toString art.fwmark} ct mark set ${toString art.fwmark} comment \"$mark_comment\"" \ "add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
| ${nft} -f - | ${nft} -f -
''; '';
appTunUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-tun-user-stop" '' # 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 set -euo pipefail
uid="$1" uid="$1"
rule_comment_prefix="proxy-suite-app-tun-user-$uid" rule_comment_prefix="proxy-suite-${name}-user-$uid"
handles=$(${nft} -a list chain inet proxy_suite_app_tun output 2>/dev/null \ handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \ | ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true) | ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then if [ -n "$handles" ]; then
while IFS= read -r handle; do while IFS= read -r handle; do
[ -n "$handle" ] || continue [ -n "$handle" ] || continue
${nft} delete rule inet proxy_suite_app_tun output handle "$handle" || true ${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles" done <<< "$handles"
fi fi
''; '';
appTunUserRuleStart = mkUserRuleStart {
name = "app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_app_tun";
nftChain = "output";
sliceName = appTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString art.fwmark} ct mark set ${toString art.fwmark}";
};
appTunUserRuleStop = mkUserRuleStop {
name = "app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_app_tun";
nftChain = "output";
};
appTproxyUserRuleStart = mkUserRuleStart {
name = "app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_app_tproxy";
nftChain = "output";
sliceName = appTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString artp.fwmark} ct mark set ${toString artp.fwmark}";
};
appTproxyUserRuleStop = mkUserRuleStop {
name = "app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_app_tproxy";
nftChain = "output";
};
appZapretUserRuleStart = mkUserRuleStart {
name = "app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_app_zapret_mark";
nftChain = "output";
sliceName = appZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString arz.filterMark} ct mark set ct mark or ${toString arz.filterMark}";
};
appZapretUserRuleStop = mkUserRuleStop {
name = "app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_app_zapret_mark";
nftChain = "output";
};
appTproxyUpScript = pkgs.writeShellScript "proxy-suite-app-tproxy-up" '' appTproxyUpScript = pkgs.writeShellScript "proxy-suite-app-tproxy-up" ''
set -euo pipefail set -euo pipefail
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true ${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
@@ -437,104 +480,6 @@ ${lib.concatMapStrings (cidr: ''
${ip} route del local default dev lo table ${toString artp.routeTable} 2>/dev/null || true ${ip} route del local default dev lo table ${toString artp.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true ${ip} rule del fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true
''; '';
appTproxyUserRuleStart =
pkgs.writeShellScript "proxy-suite-app-tproxy-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tproxy-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 appTproxySliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app TProxy 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 ip proxy_suite_app_tproxy output 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 ip proxy_suite_app_tproxy output handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule ip proxy_suite_app_tproxy output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set ${toString artp.fwmark} ct mark set ${toString artp.fwmark} comment \"$mark_comment\"" \
| ${nft} -f -
'';
appTproxyUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-tproxy-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-tproxy-user-$uid"
handles=$(${nft} -a list chain ip proxy_suite_app_tproxy output 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 ip proxy_suite_app_tproxy output handle "$handle" || true
done <<< "$handles"
fi
'';
appZapretUserRuleStart =
pkgs.writeShellScript "proxy-suite-app-zapret-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-zapret-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 appZapretSliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: app zapret 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 inet proxy_suite_app_zapret_mark output 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 inet proxy_suite_app_zapret_mark output handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule inet proxy_suite_app_zapret_mark output socket cgroupv2 level $cgroup_level \"$cgroup_path\" meta mark set meta mark or ${toString arz.filterMark} ct mark set ct mark or ${toString arz.filterMark} comment \"$mark_comment\"" \
| ${nft} -f -
'';
appZapretUserRuleStop =
pkgs.writeShellScript "proxy-suite-app-zapret-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-app-zapret-user-$uid"
handles=$(${nft} -a list chain inet proxy_suite_app_zapret_mark output 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 inet proxy_suite_app_zapret_mark output handle "$handle" || true
done <<< "$handles"
fi
'';
proxyCtl = pkgs.writeShellApplication { proxyCtl = pkgs.writeShellApplication {
name = "proxy-ctl"; name = "proxy-ctl";
@@ -560,11 +505,8 @@ ${lib.concatMapStrings (cidr: ''
APP_ROUTING_PROFILES_FILE="${appRoutingProfilesFile}" APP_ROUTING_PROFILES_FILE="${appRoutingProfilesFile}"
PROXYCHAINS_CONFIG="${proxychainsConfigFile}" PROXYCHAINS_CONFIG="${proxychainsConfigFile}"
APP_TUN_SLICE_BASE="proxy-suite-app-tun" APP_TUN_SLICE_BASE="proxy-suite-app-tun"
APP_TUN_ANCHOR_UNIT="proxy-suite-app-tun-anchor.service"
APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy" APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy"
APP_TPROXY_ANCHOR_UNIT="proxy-suite-app-tproxy-anchor.service"
APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret" APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret"
APP_ZAPRET_ANCHOR_UNIT="proxy-suite-app-zapret-anchor.service"
ALL_SERVICES=( ALL_SERVICES=(
proxy-suite-socks proxy-suite-socks
@@ -645,34 +587,56 @@ ${lib.concatMapStrings (cidr: ''
${jq} -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$APP_ROUTING_PROFILES_FILE" ${jq} -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$APP_ROUTING_PROFILES_FILE"
} }
_tun_scope_running() { _scope_running() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-tun-*' \ ${systemctl} --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
| ${grepBin} -q . | ${grepBin} -q .
} }
_any_app_tun_user_active() { _any_user_active() {
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-tun-user@*.service' \ ${systemctl} list-units --type=service --state=active --plain --no-legend "$1*.service" \
| ${grepBin} -q . | ${grepBin} -q .
} }
_tproxy_scope_running() { _check_no_global_proxy() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-tproxy-*' \ if ${systemctl} is-active --quiet proxy-suite-tun.service; then
| ${grepBin} -q . echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles."
exit 1
fi
} }
_any_app_tproxy_user_active() { # _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-tproxy-user@*.service' \ _wrap_slice() {
| ${grepBin} -q . local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
} shift 4
if [ "$enabled" != "1" ]; then
echo "$disabled_msg"
exit 1
fi
local uid; uid="$(${idBin} -u)"
local scope_unit="$slice_base-''${profile}-$$"
local anchor_unit="$slice_base-anchor.service"
local user_svc="$slice_base-user@$uid.service"
_zapret_scope_running() { ${systemctl} --user start "$anchor_unit"
${systemctl} --user list-units --type=scope --state=running --plain --no-legend 'proxy-suite-app-zapret-*' \ ${systemctl} start "$backend_svc"
| ${grepBin} -q . ${systemctl} start "$user_svc"
}
_any_app_zapret_user_active() { local status=0
${systemctl} list-units --type=service --state=active --plain --no-legend 'proxy-suite-app-zapret-user@*.service' \ ${systemdRun} --user --scope --quiet --collect --same-dir \
| ${grepBin} -q . --slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
if ! _scope_running "$slice_base"; then
${systemctl} stop "$user_svc" || true
${systemctl} --user stop "$anchor_unit" || true
if ! _any_user_active "$slice_base-user@"; then
${systemctl} stop "$backend_svc" || true
fi
fi
exit "$status"
} }
cmd="''${1:-status}" cmd="''${1:-status}"
@@ -825,116 +789,21 @@ ${lib.concatMapStrings (cidr: ''
exec ${proxychains4} ${proxychainsQuietArg}-f "$PROXYCHAINS_CONFIG" "$@" exec ${proxychains4} ${proxychainsQuietArg}-f "$PROXYCHAINS_CONFIG" "$@"
;; ;;
tun) tun)
if [ "$APP_ROUTING_TUN_ENABLED" != "1" ]; then _wrap_slice "$APP_TUN_SLICE_BASE" "$APP_ROUTING_TUN_ENABLED" \
echo "Profile '$profile' uses route=tun, but appRouting.backends.tun.enable is false." "Profile '$profile' uses route=tun, but appRouting.backends.tun.enable is false." \
exit 1 "proxy-suite-app-tun.service" "$@"
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-tun-$profile-$$"
${systemctl} --user start "$APP_TUN_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-tun.service
${systemctl} start "proxy-suite-app-tun-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_TUN_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _tun_scope_running; then
${systemctl} stop "proxy-suite-app-tun-user@$uid.service" || true
${systemctl} --user stop "$APP_TUN_ANCHOR_UNIT" || true
if ! _any_app_tun_user_active; then
${systemctl} stop proxy-suite-app-tun.service || true
fi
fi
exit "$status"
;; ;;
tproxy) tproxy)
if [ "$APP_ROUTING_TPROXY_ENABLED" != "1" ]; then _check_no_global_proxy tproxy
echo "Profile '$profile' uses route=tproxy, but appRouting.backends.tproxy.enable is false." _wrap_slice "$APP_TPROXY_SLICE_BASE" "$APP_ROUTING_TPROXY_ENABLED" \
exit 1 "Profile '$profile' uses route=tproxy, but appRouting.backends.tproxy.enable is false." \
fi "proxy-suite-app-tproxy.service" "$@"
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
echo "Global proxy-suite-tun.service is active. Stop it before using route=tproxy profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=tproxy profiles."
exit 1
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-tproxy-$profile-$$"
${systemctl} --user start "$APP_TPROXY_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-tproxy.service
${systemctl} start "proxy-suite-app-tproxy-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_TPROXY_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _tproxy_scope_running; then
${systemctl} stop "proxy-suite-app-tproxy-user@$uid.service" || true
${systemctl} --user stop "$APP_TPROXY_ANCHOR_UNIT" || true
if ! _any_app_tproxy_user_active; then
${systemctl} stop proxy-suite-app-tproxy.service || true
fi
fi
exit "$status"
;; ;;
zapret) zapret)
if [ "$APP_ROUTING_ZAPRET_ENABLED" != "1" ]; then _check_no_global_proxy zapret
echo "Profile '$profile' uses route=zapret, but the app-zapret backend or zapret service is not enabled." _wrap_slice "$APP_ZAPRET_SLICE_BASE" "$APP_ROUTING_ZAPRET_ENABLED" \
exit 1 "Profile '$profile' uses route=zapret, but the app-zapret backend or zapret service is not enabled." \
fi "proxy-suite-app-zapret.service" "$@"
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
echo "Global proxy-suite-tun.service is active. Stop it before using route=zapret profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=zapret profiles."
exit 1
fi
uid="$(${idBin} -u)"
scope_unit="proxy-suite-app-zapret-$profile-$$"
${systemctl} --user start "$APP_ZAPRET_ANCHOR_UNIT"
${systemctl} start proxy-suite-app-zapret.service
${systemctl} start "proxy-suite-app-zapret-user@$uid.service"
if ${systemdRun} --user --scope --quiet --collect --same-dir \
--slice="$APP_ZAPRET_SLICE_BASE" \
--unit="$scope_unit" \
"$@"; then
status=0
else
status=$?
fi
if ! _zapret_scope_running; then
${systemctl} stop "proxy-suite-app-zapret-user@$uid.service" || true
${systemctl} --user stop "$APP_ZAPRET_ANCHOR_UNIT" || true
if ! _any_app_zapret_user_active; then
${systemctl} stop proxy-suite-app-zapret.service || true
fi
fi
exit "$status"
;; ;;
*) *)
echo "Route backend '$route' is not implemented in this build." echo "Route backend '$route' is not implemented in this build."
@@ -982,6 +851,17 @@ ${lib.concatMapStrings (cidr: ''
''; '';
}; };
mkAnchorService = sliceName: desc: {
description = desc;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = sliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
in in
{ {
environment.systemPackages = [ proxyCtl ]; environment.systemPackages = [ proxyCtl ];
@@ -1013,40 +893,16 @@ in
systemd.user.services = systemd.user.services =
lib.optionalAttrs art.enable { lib.optionalAttrs art.enable {
proxy-suite-app-tun-anchor = { proxy-suite-app-tun-anchor =
description = "Anchor service for proxy-suite app TUN slice"; mkAnchorService appTunSliceName "Anchor service for proxy-suite app TUN slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appTunSliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
} }
// lib.optionalAttrs artp.enable { // lib.optionalAttrs artp.enable {
proxy-suite-app-tproxy-anchor = { proxy-suite-app-tproxy-anchor =
description = "Anchor service for proxy-suite app TProxy slice"; mkAnchorService appTproxySliceName "Anchor service for proxy-suite app TProxy slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appTproxySliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
} }
// lib.optionalAttrs (arz.enable && cfg.zapret.enable) { // lib.optionalAttrs (arz.enable && cfg.zapret.enable) {
proxy-suite-app-zapret-anchor = { proxy-suite-app-zapret-anchor =
description = "Anchor service for proxy-suite app zapret slice"; mkAnchorService appZapretSliceName "Anchor service for proxy-suite app zapret slice";
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = appZapretSliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
}; };
assertions = [ assertions = [
@@ -1226,7 +1082,6 @@ in
]) sb.subscriptions; ]) sb.subscriptions;
systemd.services = { systemd.services = {
# Always-on: SOCKS5/HTTP mixed inbound, also ready for TProxy interception.
proxy-suite-socks = { proxy-suite-socks = {
description = "sing-box proxy client (SOCKS + TProxy-ready)"; description = "sing-box proxy client (SOCKS + TProxy-ready)";
after = [ "network.target" ]; after = [ "network.target" ];
@@ -1241,9 +1096,6 @@ in
}; };
} }
// lib.optionalAttrs sb.tproxy.enable { // lib.optionalAttrs sb.tproxy.enable {
# Opt-in transparent proxy. Start/stop with:
# systemctl start proxy-suite-tproxy
# systemctl stop proxy-suite-tproxy
proxy-suite-tproxy = { proxy-suite-tproxy = {
description = "sing-box TProxy – nftables rules and policy routing"; description = "sing-box TProxy – nftables rules and policy routing";
after = [ after = [
@@ -1274,9 +1126,6 @@ in
}; };
} }
// lib.optionalAttrs sb.tun.enable { // lib.optionalAttrs sb.tun.enable {
# Opt-in TUN mode (full tunnel, no nftables needed). Start/stop with:
# systemctl start proxy-suite-tun
# systemctl stop proxy-suite-tun
proxy-suite-tun = { proxy-suite-tun = {
description = "sing-box TUN proxy client"; description = "sing-box TUN proxy client";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
+6 -5
View File
@@ -1652,23 +1652,24 @@ let
( (
assert pkgs.lib.hasInfix "APP_ROUTING_TUN_ENABLED" appRoutingTunScript; assert pkgs.lib.hasInfix "APP_ROUTING_TUN_ENABLED" appRoutingTunScript;
assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" appRoutingTunScript; assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" appRoutingTunScript;
assert pkgs.lib.hasInfix "proxy-suite-app-tun-user@$uid.service" appRoutingTunScript; assert pkgs.lib.hasInfix ''APP_TUN_SLICE_BASE="proxy-suite-app-tun"'' appRoutingTunScript;
assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" appRoutingTunScript;
true true
) )
# -- appRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices -- # -- appRouting: generated proxy-ctl script dispatches tproxy profiles through systemd slices --
( (
assert pkgs.lib.hasInfix "APP_ROUTING_TPROXY_ENABLED" appRoutingTproxyScript; assert pkgs.lib.hasInfix "APP_ROUTING_TPROXY_ENABLED" appRoutingTproxyScript;
assert pkgs.lib.hasInfix "proxy-suite-app-tproxy-user@$uid.service" appRoutingTproxyScript; assert pkgs.lib.hasInfix ''APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy"'' appRoutingTproxyScript;
assert pkgs.lib.hasInfix "proxy-suite-app-tproxy-$profile-$$" appRoutingTproxyScript; assert pkgs.lib.hasInfix ''$slice_base-''${profile}-$$'' appRoutingTproxyScript;
true true
) )
# -- appRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices -- # -- appRouting: generated proxy-ctl script dispatches zapret profiles through systemd slices --
( (
assert pkgs.lib.hasInfix "APP_ROUTING_ZAPRET_ENABLED" appRoutingZapretScript; assert pkgs.lib.hasInfix "APP_ROUTING_ZAPRET_ENABLED" appRoutingZapretScript;
assert pkgs.lib.hasInfix "proxy-suite-app-zapret-user@$uid.service" appRoutingZapretScript; assert pkgs.lib.hasInfix ''APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret"'' appRoutingZapretScript;
assert pkgs.lib.hasInfix "proxy-suite-app-zapret-$profile-$$" appRoutingZapretScript; assert pkgs.lib.hasInfix ''$slice_base-''${profile}-$$'' appRoutingZapretScript;
true true
) )
+80 -111
View File
@@ -20,18 +20,55 @@ def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query)) return dict(urllib.parse.parse_qsl(query))
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
"""Strip scheme+fragment, return (userinfo, host, port_str, params).
userinfo is "" when no '@' is present."""
rest = url[len(f"{scheme}://"):]
rest, _, _ = rest.partition("#")
if "@" in rest:
userinfo, _, rest = rest.partition("@")
else:
userinfo = ""
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
return userinfo, host, port, _qs(query)
def _mk_transport(
transport_type: str,
path: str = "/",
host_header: str = "",
service_name: str = "",
) -> "dict | None":
"""Build a sing-box transport dict for ws/grpc/h2. Returns None for tcp."""
if transport_type == "ws":
return {
"type": "ws",
"path": urllib.parse.unquote(path),
"headers": {"Host": host_header},
}
elif transport_type == "grpc":
return {
"type": "grpc",
"service_name": urllib.parse.unquote(service_name),
}
elif transport_type == "h2":
return {
"type": "http",
"host": [host_header],
"path": urllib.parse.unquote(path),
}
return None
def parse_vless(url: str, tag: str) -> dict: def parse_vless(url: str, tag: str) -> dict:
""" """
vless://UUID@HOST:PORT?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=SID&flow=FLOW&type=tcp vless://UUID@HOST:PORT?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=SID&flow=FLOW&type=tcp
vless://UUID@HOST:PORT?security=tls&sni=SNI&fp=chrome&type=ws&path=/path&host=HOST vless://UUID@HOST:PORT?security=tls&sni=SNI&fp=chrome&type=ws&path=/path&host=HOST
""" """
rest = url[len("vless://"):] userinfo, host, port, params = _parse_url_parts(url, "vless")
rest, _, _ = rest.partition("#") security = params.get("security", "none")
transport = params.get("type", "tcp")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = { ob: dict = {
"type": "vless", "type": "vless",
@@ -42,9 +79,6 @@ def parse_vless(url: str, tag: str) -> dict:
"packet_encoding": "xudp", "packet_encoding": "xudp",
} }
security = params.get("security", "none")
transport = params.get("type", "tcp")
if security == "reality": if security == "reality":
ob["tls"] = { ob["tls"] = {
"enabled": True, "enabled": True,
@@ -66,23 +100,14 @@ def parse_vless(url: str, tag: str) -> dict:
if params.get("alpn"): if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",") ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws": tr = _mk_transport(
ob["transport"] = { transport,
"type": "ws", path=params.get("path", "/"),
"path": urllib.parse.unquote(params.get("path", "/")), host_header=params.get("host", host),
"headers": {"Host": params.get("host", host)}, service_name=params.get("serviceName", ""),
} )
elif transport == "grpc": if tr is not None:
ob["transport"] = { ob["transport"] = tr
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
elif transport == "h2":
ob["transport"] = {
"type": "http",
"host": [params.get("host", host)],
"path": urllib.parse.unquote(params.get("path", "/")),
}
flow = urllib.parse.unquote(params.get("flow", "")) flow = urllib.parse.unquote(params.get("flow", ""))
if flow: if flow:
@@ -129,23 +154,15 @@ def parse_vmess(url: str, tag: str) -> dict:
path = str(data.get("path") or "/") path = str(data.get("path") or "/")
h_host = str(data.get("host") or host) h_host = str(data.get("host") or host)
if net == "ws": # vmess grpc uses path as service_name; other transports use path/h_host directly
ob["transport"] = { tr = _mk_transport(
"type": "ws", net if net != "http" else "h2",
"path": path, path=path,
"headers": {"Host": h_host}, host_header=h_host,
} service_name=path.lstrip("/"),
elif net == "grpc": )
ob["transport"] = { if tr is not None:
"type": "grpc", ob["transport"] = tr
"service_name": path.lstrip("/"),
}
elif net in ("h2", "http"):
ob["transport"] = {
"type": "http",
"host": [h_host],
"path": path,
}
return ob return ob
@@ -154,15 +171,7 @@ def parse_trojan(url: str, tag: str) -> dict:
""" """
trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=... trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=...
""" """
rest = url[len("trojan://"):] userinfo, host, port, params = _parse_url_parts(url, "trojan")
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
password = urllib.parse.unquote(userinfo)
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
transport = params.get("type", "tcp") transport = params.get("type", "tcp")
ob: dict = { ob: dict = {
@@ -170,7 +179,7 @@ def parse_trojan(url: str, tag: str) -> dict:
"tag": tag, "tag": tag,
"server": host, "server": host,
"server_port": int(port), "server_port": int(port),
"password": password, "password": urllib.parse.unquote(userinfo),
"tls": { "tls": {
"enabled": True, "enabled": True,
"server_name": params.get("sni", host), "server_name": params.get("sni", host),
@@ -182,17 +191,14 @@ def parse_trojan(url: str, tag: str) -> dict:
if params.get("alpn"): if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",") ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws": tr = _mk_transport(
ob["transport"] = { transport,
"type": "ws", path=params.get("path", "/"),
"path": urllib.parse.unquote(params.get("path", "/")), host_header=params.get("host", host),
"headers": {"Host": params.get("host", host)}, service_name=params.get("serviceName", ""),
} )
elif transport == "grpc": if tr is not None:
ob["transport"] = { ob["transport"] = tr
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
return ob return ob
@@ -236,13 +242,7 @@ def parse_hysteria2(url: str, tag: str) -> dict:
hy2://... (same, shorter alias) hy2://... (same, shorter alias)
""" """
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2" scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
rest = url[len(scheme) + 3:] userinfo, host, port, params = _parse_url_parts(url, scheme)
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
ob: dict = { ob: dict = {
"type": "hysteria2", "type": "hysteria2",
@@ -267,18 +267,9 @@ def parse_tuic(url: str, tag: str) -> dict:
""" """
tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI
""" """
rest = url[len("tuic://"):] userinfo, host, port, params = _parse_url_parts(url, "tuic")
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
uuid, _, password = userinfo.partition(":") uuid, _, password = userinfo.partition(":")
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
alpn_raw = params.get("alpn", "h3")
alpn = [a for a in alpn_raw.split(",") if a]
return { return {
"type": "tuic", "type": "tuic",
@@ -306,25 +297,13 @@ def parse_socks(url: str, tag: str) -> dict:
""" """
scheme = url.split("://")[0].lower() scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5" version = "4" if scheme.startswith("socks4") else "5"
userinfo, host, port, _ = _parse_url_parts(url, scheme)
rest = url[len(scheme) + 3:] ob: dict = {"type": "socks", "tag": tag, "version": version}
rest, _, _ = rest.partition("#") if userinfo and ":" in userinfo:
ob: dict = {
"type": "socks",
"tag": tag,
"version": version,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":") username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username) ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password) ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host ob["server"] = host
ob["server_port"] = int(port) ob["server_port"] = int(port)
@@ -337,23 +316,13 @@ def parse_http_proxy(url: str, tag: str) -> dict:
https://[user:pass@]host:port[#remark] – HTTP CONNECT proxy over TLS https://[user:pass@]host:port[#remark] – HTTP CONNECT proxy over TLS
""" """
scheme = url.split("://")[0].lower() scheme = url.split("://")[0].lower()
rest = url[len(scheme) + 3:] userinfo, host, port, _ = _parse_url_parts(url, scheme)
rest, _, _ = rest.partition("#")
ob: dict = { ob: dict = {"type": "http", "tag": tag}
"type": "http", if userinfo and ":" in userinfo:
"tag": tag,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":") username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username) ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password) ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob["server"] = host ob["server"] = host
ob["server_port"] = int(port) ob["server_port"] = int(port)