various fixes

This commit is contained in:
FUFSoB committed 2026-05-18 09:18:21 +05:00
1 parent 1198a63f3e
commit 70c0454446
11 files changed
+413 -181

No files matched your search

+21 -11
View File
@@ -66,6 +66,8 @@ let
tunAddress ? globalTun.address, tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu, tunMtu ? globalTun.mtu,
tunAutoRoute ? true, tunAutoRoute ? true,
tunAutoRouteTableIndex ? 2022,
tunAutoRouteRuleIndex ? 9000,
tunAutoRedirect ? true, tunAutoRedirect ? true,
tunStrictRoute ? true, tunStrictRoute ? true,
forceLocalDnsViaProxy ? false, forceLocalDnsViaProxy ? false,
@@ -95,17 +97,25 @@ let
listen = "127.0.0.1"; listen = "127.0.0.1";
listen_port = globalTproxy.port; listen_port = globalTproxy.port;
} }
++ lib.optional enableTun { ++ lib.optional enableTun (
type = "tun"; {
tag = "tun-in"; type = "tun";
interface_name = tunInterface; tag = "tun-in";
address = [ tunAddress ]; interface_name = tunInterface;
mtu = tunMtu; address = [ tunAddress ];
auto_route = tunAutoRoute; mtu = tunMtu;
auto_redirect = tunAutoRedirect; auto_route = tunAutoRoute;
strict_route = tunStrictRoute; auto_redirect = tunAutoRedirect;
stack = "mixed"; strict_route = tunStrictRoute;
}; stack = "mixed";
}
// lib.optionalAttrs tunAutoRoute {
# Keep sing-box auto_route indexes explicit so service cleanup can
# reliably remove stale policy-routing state after unclean stops.
iproute2_table_index = tunAutoRouteTableIndex;
iproute2_rule_index = tunAutoRouteRuleIndex;
}
);
# proxy outbound(s) are prepended at runtime by the start script # proxy outbound(s) are prepended at runtime by the start script
outbounds = [ outbounds = [
@@ -36,6 +36,8 @@ let
perAppZapretCfg perAppZapretCfg
; ;
globalTunAutoRouteTable = 2022;
featureAssertions = [ featureAssertions = [
(requireAvailable singBoxCfg.enable ( (requireAvailable singBoxCfg.enable (
singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ] singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]
@@ -123,6 +125,24 @@ let
]; ];
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [ collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.interface;
right = perAppRoutingTun.interface;
message = "proxy-suite: singBox.tun.interface and singBox.tun.perApp.interface must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = globalTun.address;
right = perAppRoutingTun.address;
message = "proxy-suite: singBox.tun.address and singBox.tun.perApp.address must differ";
}
{
condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable;
message = "proxy-suite: singBox.tun.perApp.routeTable must differ from the global TUN auto-route table 2022";
}
{ {
condition = perAppRoutingTun.enable && globalTproxy.enable; condition = perAppRoutingTun.enable && globalTproxy.enable;
left = perAppRoutingTun.fwmark; left = perAppRoutingTun.fwmark;
@@ -202,6 +222,64 @@ let
134217728 134217728
]; ];
positiveNumberAssertions = map (item: mkAssertion (!item.condition || item.value > 0) item.message) [
{
condition = globalTun.enable;
value = globalTun.mtu;
message = "proxy-suite: singBox.tun.mtu must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.mtu;
message = "proxy-suite: singBox.tun.perApp.mtu must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.fwmark;
message = "proxy-suite: singBox.tproxy.fwmark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.proxyMark;
message = "proxy-suite: singBox.tproxy.proxyMark must be greater than zero";
}
{
condition = globalTproxy.enable;
value = globalTproxy.routeTable;
message = "proxy-suite: singBox.tproxy.routeTable must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.fwmark;
message = "proxy-suite: singBox.tun.perApp.fwmark must be greater than zero";
}
{
condition = perAppRoutingTun.enable;
value = perAppRoutingTun.routeTable;
message = "proxy-suite: singBox.tun.perApp.routeTable must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.fwmark;
message = "proxy-suite: singBox.tproxy.perApp.fwmark must be greater than zero";
}
{
condition = perAppRoutingTproxy.enable;
value = perAppRoutingTproxy.routeTable;
message = "proxy-suite: singBox.tproxy.perApp.routeTable must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.filterMark;
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
}
{
condition = perAppZapretCfg.enable;
value = perAppZapretCfg.qnum;
message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
}
];
localProxyAuthCfg = singBoxCfg.auth; localProxyAuthCfg = singBoxCfg.auth;
localProxyAuthUsed = localProxyAuthUsed =
localProxyAuthCfg.username != null localProxyAuthCfg.username != null
@@ -286,6 +364,7 @@ in
featureAssertions featureAssertions
++ perAppRoutingAssertions ++ perAppRoutingAssertions
++ collisionAssertions ++ collisionAssertions
++ positiveNumberAssertions
++ localProxyAuthAssertions ++ localProxyAuthAssertions
++ forbiddenValueAssertions ++ forbiddenValueAssertions
++ secretAssertions ++ secretAssertions
+2
View File
@@ -46,6 +46,7 @@ rec {
wants ? [ ], wants ? [ ],
requires ? [ ], requires ? [ ],
conflicts ? [ ], conflicts ? [ ],
execStartPre ? null,
execStartPost ? null, execStartPost ? null,
execStopPost ? null, execStopPost ? null,
extraServiceConfig ? { }, extraServiceConfig ? { },
@@ -70,6 +71,7 @@ rec {
RuntimeDirectory = runtimeDirectory; RuntimeDirectory = runtimeDirectory;
} }
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; } // lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; } // lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; } // lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
// extraServiceConfig; // extraServiceConfig;
+42 -4
View File
@@ -85,17 +85,47 @@ let
singBoxCfg.auth.username != null singBoxCfg.auth.username != null
&& (singBoxCfg.auth.password != null || singBoxCfg.auth.passwordFile != null); && (singBoxCfg.auth.password != null || singBoxCfg.auth.passwordFile != null);
# Must match the explicit iproute2_* indexes written to the global TUN
# sing-box template in config.nix.
tunAutoRouteTableIndex = 2022;
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" '' 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.
${nft} delete table ip singbox 2>/dev/null || true ${nft} delete table ip singbox 2>/dev/null || true
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
${nft} -f ${nftablesRulesFile} ${nft} -f ${nftablesRulesFile}
${ip} route add local default dev lo table ${toString globalTproxy.routeTable} ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} ${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
''; '';
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e
${nft} delete table ip singbox 2>/dev/null || true ${nft} delete table ip singbox 2>/dev/null || true
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true ${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true '';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
set +e
# sing-box 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.
${nft} delete table inet sing-box 2>/dev/null || true
while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true
''; '';
systemServiceEntries = [ systemServiceEntries = [
@@ -139,7 +169,9 @@ let
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ]; wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ]; conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun; execStart = scripts.startTun;
execStopPost = tunCleanupScript;
runtimeDirectory = serviceNames.tun; runtimeDirectory = serviceNames.tun;
stateDirectory = "proxy-suite"; stateDirectory = "proxy-suite";
}; };
@@ -151,6 +183,7 @@ let
description = "sing-box per-app-routing TUN backend"; description = "sing-box per-app-routing TUN backend";
after = [ "network-online.target" ]; after = [ "network-online.target" ];
wants = [ "network-online.target" ]; wants = [ "network-online.target" ];
execStartPre = perAppRouting.perAppTunDownScript;
execStart = scripts.startPerAppTun; execStart = scripts.startPerAppTun;
execStartPost = perAppRouting.perAppTunUpScript; execStartPost = perAppRouting.perAppTunUpScript;
execStopPost = perAppRouting.perAppTunDownScript; execStopPost = perAppRouting.perAppTunDownScript;
@@ -264,9 +297,14 @@ in
{ {
environment.systemPackages = [ control.proxyCtl ]; environment.systemPackages = [ control.proxyCtl ];
# nftables must be on for TProxy to work. # nftables must be on for transparent routing backends. Global TUN uses
# sing-box auto_redirect, which programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf ( networking.nftables.enable = lib.mkIf (
globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretEnabled globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true); ) (lib.mkDefault true);
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) { users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
@@ -120,25 +120,33 @@ let
''; '';
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" '' perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
set -euo pipefail set +e
# Best-effort cleanup for graceful stops and for unclean previous exits.
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true ${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
while ${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
${ip} route del default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true ${ip} route del default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true ${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true
''; '';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
set -euo pipefail set -euo pipefail
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
${nft} -f ${perAppTproxyRulesFile} ${nft} -f ${perAppTproxyRulesFile}
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable} ${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true ${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''; '';
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set -euo pipefail set +e
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true ${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
''; '';
# Generate a "start" script that adds a per-user cgroup nftables mark rule. # Generate a "start" script that adds a per-user cgroup nftables mark rule.
+54 -118
View File
@@ -23,6 +23,7 @@
let let
globalTproxy = singBoxCfg.tproxy; globalTproxy = singBoxCfg.tproxy;
systemctl = "${pkgs.systemd}/bin/systemctl";
localProxyAuth = singBoxCfg.auth; localProxyAuth = singBoxCfg.auth;
localProxyAuthEnabled = localProxyAuthEnabled =
localProxyAuth.username != null localProxyAuth.username != null
@@ -139,6 +140,13 @@ let
sub: mkSubscriptionBlock sub routingMark sub: mkSubscriptionBlock sub routingMark
) singBoxCfg.subscriptions; ) singBoxCfg.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 = wrapperBlock =
if collapseNamedOutbounds then if collapseNamedOutbounds then
# When there are no static outbounds, subscription outbounds keep their # When there are no static outbounds, subscription outbounds keep their
@@ -173,7 +181,7 @@ let
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON") OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
''; '';
in in
outboundBlocks + subscriptionBlocks + wrapperBlock; outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock;
writeProxychainsConfigBlock = '' writeProxychainsConfigBlock = ''
{ {
@@ -195,6 +203,16 @@ let
modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist";
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"
];
mkStartScript = mkStartScript =
{ {
name, name,
@@ -212,8 +230,9 @@ let
ROUTE_MODE="" ROUTE_MODE=""
ROUTE_FINAL="" ROUTE_FINAL=""
DNS_FINAL="" DNS_FINAL=""
ROUTE_RULES_JSON="" ROUTE_RULES_JSON='[]'
CLEAR_DNS_RULES=0 ROUTE_MODE_ACTIVE=false
CLEAR_DNS_RULES=false
${lib.optionalString enableLocalProxyAuth '' ${lib.optionalString enableLocalProxyAuth ''
umask 077 umask 077
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
@@ -227,6 +246,7 @@ let
blacklist) blacklist)
ROUTE_FINAL="proxy" ROUTE_FINAL="proxy"
DNS_FINAL="remote" DNS_FINAL="remote"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c ' ROUTE_RULES_JSON=$(${jq} -c '
.common .common
+ (.custom | map(.entries) | add // []) + (.custom | map(.entries) | add // [])
@@ -240,6 +260,7 @@ let
whitelist) whitelist)
ROUTE_FINAL="direct" ROUTE_FINAL="direct"
DNS_FINAL="local" DNS_FINAL="local"
ROUTE_MODE_ACTIVE=true
ROUTE_RULES_JSON=$(${jq} -c ' ROUTE_RULES_JSON=$(${jq} -c '
.common .common
+ (.custom | map(.entries) | add // []) + (.custom | map(.entries) | add // [])
@@ -253,7 +274,8 @@ let
all-proxy) all-proxy)
ROUTE_FINAL="proxy" ROUTE_FINAL="proxy"
DNS_FINAL="remote" DNS_FINAL="remote"
CLEAR_DNS_RULES=1 ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c ' ROUTE_RULES_JSON=$(${jq} -c '
.common .common
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
@@ -266,7 +288,8 @@ let
all-bypass) all-bypass)
ROUTE_FINAL="direct" ROUTE_FINAL="direct"
DNS_FINAL="local" DNS_FINAL="local"
CLEAR_DNS_RULES=1 ROUTE_MODE_ACTIVE=true
CLEAR_DNS_RULES=true
ROUTE_RULES_JSON=$(${jq} -c ' ROUTE_RULES_JSON=$(${jq} -c '
.common .common
+ (.custom | map(select(.category == "block") | .entries) | add // []) + (.custom | map(select(.category == "block") | .entries) | add // [])
@@ -281,85 +304,30 @@ let
${mkOutboundScript routingMark} ${mkOutboundScript routingMark}
${ ${jq} \
if enableLocalProxyAuth then --argjson obs "$OUTBOUNDS_JSON" \
'' --argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
if [ -n "$ROUTE_MODE" ]; then --arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
if [ "$CLEAR_DNS_RULES" -eq 1 ]; then --arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
${jq} \ --argjson route_enabled "$ROUTE_MODE_ACTIVE" \
--argjson obs "$OUTBOUNDS_JSON" \ --argjson route_rules "$ROUTE_RULES_JSON" \
--arg user ${lib.escapeShellArg localProxyAuth.username} \ --arg route_final "$ROUTE_FINAL" \
--arg password "$LOCAL_PROXY_PASSWORD" \ --arg dns_final "$DNS_FINAL" \
--argjson route_rules "$ROUTE_RULES_JSON" \ --argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg route_final "$ROUTE_FINAL" \ '.outbounds = $obs + .outbounds
--arg dns_final "$DNS_FINAL" \ | if $auth_enabled then
'.outbounds = $obs + .outbounds (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
| (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] else . end
| .route.rules = $route_rules | if $route_enabled then
| .route.final = $route_final .route.rules = $route_rules
| .dns.rules = [] | .route.final = $route_final
| .dns.final = $dns_final' \ | .dns.final = $dns_final
"${configFile}" > "$RUNTIME_DIR/config.json" | if $clear_dns_rules then .dns.rules = [] else . end
else else . end' \
${jq} \ "${configFile}" > "$RUNTIME_DIR/config.json"
--argjson obs "$OUTBOUNDS_JSON" \ ${lib.optionalString enableLocalProxyAuth ''
--arg user ${lib.escapeShellArg localProxyAuth.username} \ chmod 600 "$RUNTIME_DIR/config.json"
--arg password "$LOCAL_PROXY_PASSWORD" \ ''}
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
'.outbounds = $obs + .outbounds
| (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
| .route.rules = $route_rules
| .route.final = $route_final
| .dns.final = $dns_final' \
"${configFile}" > "$RUNTIME_DIR/config.json"
fi
else
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--arg user ${lib.escapeShellArg localProxyAuth.username} \
--arg password "$LOCAL_PROXY_PASSWORD" \
'.outbounds = $obs + .outbounds
| (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]' \
"${configFile}" > "$RUNTIME_DIR/config.json"
fi
chmod 600 "$RUNTIME_DIR/config.json"
''
else
''
if [ -n "$ROUTE_MODE" ]; then
if [ "$CLEAR_DNS_RULES" -eq 1 ]; then
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
'.outbounds = $obs + .outbounds
| .route.rules = $route_rules
| .route.final = $route_final
| .dns.rules = []
| .dns.final = $dns_final' \
"${configFile}" > "$RUNTIME_DIR/config.json"
else
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson route_rules "$ROUTE_RULES_JSON" \
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
'.outbounds = $obs + .outbounds
| .route.rules = $route_rules
| .route.final = $route_final
| .dns.final = $dns_final' \
"${configFile}" > "$RUNTIME_DIR/config.json"
fi
else
${jq} --argjson obs "$OUTBOUNDS_JSON" \
'.outbounds = $obs + .outbounds' \
"${configFile}" > "$RUNTIME_DIR/config.json"
fi
''
}
exec ${singBox} run -c "$RUNTIME_DIR/config.json" exec ${singBox} run -c "$RUNTIME_DIR/config.json"
''; '';
@@ -410,26 +378,10 @@ let
CACHE_DIR="${subscriptionCacheDir}" CACHE_DIR="${subscriptionCacheDir}"
mkdir -p "$CACHE_DIR" mkdir -p "$CACHE_DIR"
FAILED=0 FAILED=0
SOCKS_WAS_ACTIVE=0
TUN_WAS_ACTIVE=0
PER_APP_TUN_WAS_ACTIVE=0
systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true
systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true
systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions} ${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions}
if [ "$FAILED" -eq 0 ]; then if [ "$FAILED" -eq 0 ]; then
if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then ${restartActiveConfigConsumersBlock}
systemctl restart proxy-suite-socks
fi
if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then
systemctl restart proxy-suite-tun
fi
if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then
systemctl restart proxy-suite-per-app-tun
fi
fi fi
exit "$FAILED" exit "$FAILED"
''; '';
@@ -462,23 +414,7 @@ let
printf '%s\n' "$mode" > "${routeModeStateFile}" printf '%s\n' "$mode" > "${routeModeStateFile}"
fi fi
SOCKS_WAS_ACTIVE=0 ${restartActiveConfigConsumersBlock}
TUN_WAS_ACTIVE=0
PER_APP_TUN_WAS_ACTIVE=0
systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true
systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true
systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true
if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then
systemctl restart proxy-suite-socks
fi
if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then
systemctl restart proxy-suite-tun
fi
if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then
systemctl restart proxy-suite-per-app-tun
fi
''; '';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
+13 -5
View File
@@ -296,14 +296,22 @@ let
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true ${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
''; '';
exemptStart = lib.concatMapStrings (cidr: '' exemptStart = ''
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN set -euo pipefail
''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN ${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
'') zapretCfg.cidrExemption.cidrs; '') zapretCfg.cidrExemption.cidrs;
exemptStop = lib.concatMapStrings (cidr: '' exemptStop = ''
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true set +e
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true ''
+ lib.concatMapStrings (cidr: ''
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
'') zapretCfg.cidrExemption.cidrs; '') zapretCfg.cidrExemption.cidrs;
in in
{ {
+63 -12
View File
@@ -285,6 +285,9 @@ let
services.proxy-suite.singBox.tproxy.enable = true; services.proxy-suite.singBox.tproxy.enable = true;
} }
]; ];
tproxyManualServiceConfig = tproxyManualFixture.config.systemd.services."proxy-suite-tproxy".serviceConfig;
tproxyManualStartScript = builtins.readFile tproxyManualServiceConfig.ExecStart;
tproxyManualStopScript = builtins.readFile tproxyManualServiceConfig.ExecStop;
tproxyAutostartFixture = evalProxySuite [ tproxyAutostartFixture = evalProxySuite [
baseModule baseModule
@@ -401,6 +404,8 @@ let
]; ];
dnsRemoteOverrideConfig = mkTProxyConfig dnsRemoteOverrideFixture; dnsRemoteOverrideConfig = mkTProxyConfig dnsRemoteOverrideFixture;
tunDefaultConfig = mkTunConfig tunManualFixture; tunDefaultConfig = mkTunConfig tunManualFixture;
tunServiceConfig = tunManualFixture.config.systemd.services."proxy-suite-tun".serviceConfig;
tunCleanupScript = builtins.readFile tunServiceConfig.ExecStopPost;
zapretSyncFixture = evalProxySuite [ zapretSyncFixture = evalProxySuite [
baseModule baseModule
@@ -908,8 +913,9 @@ let
perAppRoutingTunWrapper = _perAppRoutingTun.wrapper; perAppRoutingTunWrapper = _perAppRoutingTun.wrapper;
perAppRoutingTunScript = _perAppRoutingTun.script; perAppRoutingTunScript = _perAppRoutingTun.script;
perAppRoutingTunProfiles = _perAppRoutingTun.profiles; perAppRoutingTunProfiles = _perAppRoutingTun.profiles;
perAppRoutingTunStartScript = perAppRoutingTunServiceConfig = perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig;
builtins.readFile perAppRoutingTunFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart; perAppRoutingTunStartScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStart;
perAppRoutingTunCleanupScript = builtins.readFile perAppRoutingTunServiceConfig.ExecStopPost;
perAppRoutingTunConfig = mkPerAppTunConfig perAppRoutingTunFixture; perAppRoutingTunConfig = mkPerAppTunConfig perAppRoutingTunFixture;
perAppRoutingTunDirectOutbound = perAppRoutingTunDirectOutbound =
builtins.head (builtins.filter (item: item.tag == "direct") perAppRoutingTunConfig.outbounds); builtins.head (builtins.filter (item: item.tag == "direct") perAppRoutingTunConfig.outbounds);
@@ -965,8 +971,9 @@ let
perAppRoutingTproxyWrapper = _perAppRoutingTproxy.wrapper; perAppRoutingTproxyWrapper = _perAppRoutingTproxy.wrapper;
perAppRoutingTproxyScript = _perAppRoutingTproxy.script; perAppRoutingTproxyScript = _perAppRoutingTproxy.script;
perAppRoutingTproxyProfiles = _perAppRoutingTproxy.profiles; perAppRoutingTproxyProfiles = _perAppRoutingTproxy.profiles;
perAppRoutingTproxyStartScript = perAppRoutingTproxyServiceConfig = perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig;
builtins.readFile perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy".serviceConfig.ExecStart; perAppRoutingTproxyStartScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStart;
perAppRoutingTproxyStopScript = builtins.readFile perAppRoutingTproxyServiceConfig.ExecStop;
perAppRoutingTproxyUserStartExec = perAppRoutingTproxyUserStartExec =
perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".serviceConfig.ExecStart; perAppRoutingTproxyFixture.config.systemd.services."proxy-suite-per-app-tproxy-user@".serviceConfig.ExecStart;
perAppRoutingTproxyUserStartScript = perAppRoutingTproxyUserStartScript =
@@ -1368,11 +1375,39 @@ let
== [ "multi-user.target" ]; == [ "multi-user.target" ];
true true
) )
(
assert pkgs.lib.hasInfix "set -euo pipefail" tproxyManualStartScript;
assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStartScript;
assert pkgs.lib.hasInfix "route replace local default dev lo table 100" tproxyManualStartScript;
assert pkgs.lib.hasInfix "set +e" tproxyManualStopScript;
assert pkgs.lib.hasInfix "rule del fwmark 1 table 100" tproxyManualStopScript;
true
)
( (
assert tunManualFixture.config.services.proxy-suite.singBox.tun.autostart == false; assert tunManualFixture.config.services.proxy-suite.singBox.tun.autostart == false;
assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ]; assert tunManualFixture.config.systemd.services."proxy-suite-tun".wantedBy == [ ];
true true
) )
(
let
inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds);
in
assert inbound.iproute2_table_index == 2022;
assert inbound.iproute2_rule_index == 9000;
true
)
(
assert tunManualFixture.config.networking.nftables.enable;
true
)
(
assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost;
assert pkgs.lib.hasInfix ''delete table inet sing-box'' tunCleanupScript;
assert pkgs.lib.hasInfix ''rule del table 2022'' tunCleanupScript;
assert pkgs.lib.hasInfix ''route flush table 2022'' tunCleanupScript;
assert pkgs.lib.hasInfix "link del dev 'singtun0'" tunCleanupScript;
true
)
( (
assert assert
tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy tunAutostartFixture.config.systemd.services."proxy-suite-tun".wantedBy
@@ -1700,20 +1735,20 @@ let
true true
) )
# -- subscription/runtime: refresh only restarts sing-box units that were already active -- # -- subscription/runtime: refresh only restarts sing-box units that are active --
( (
assert pkgs.lib.hasInfix ''SOCKS_WAS_ACTIVE=0'' subscriptionOnlyUpdateScript; assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-socks'' subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then'' subscriptionOnlyUpdateScript; assert pkgs.lib.hasInfix ''restart proxy-suite-socks'' subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then'' subscriptionOnlyUpdateScript; assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-tun'' subscriptionOnlyUpdateScript;
assert pkgs.lib.hasInfix ''systemctl restart proxy-suite-socks'' subscriptionOnlyUpdateScript; assert !(pkgs.lib.hasInfix ''SOCKS_WAS_ACTIVE'' subscriptionOnlyUpdateScript);
true true
) )
# -- subscription/runtime: refresh also handles the per-app TUN sing-box service when present -- # -- subscription/runtime: refresh also handles the per-app TUN sing-box service when present --
( (
assert pkgs.lib.hasInfix ''PER_APP_TUN_WAS_ACTIVE=0'' subscriptionPerAppTunUpdateScript; assert pkgs.lib.hasInfix ''is-active --quiet proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript;
assert pkgs.lib.hasInfix ''systemctl is-active --quiet proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; assert pkgs.lib.hasInfix ''restart proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript;
assert pkgs.lib.hasInfix ''systemctl restart proxy-suite-per-app-tun'' subscriptionPerAppTunUpdateScript; assert !(pkgs.lib.hasInfix ''PER_APP_TUN_WAS_ACTIVE'' subscriptionPerAppTunUpdateScript);
true true
) )
@@ -1862,6 +1897,14 @@ let
true true
) )
# -- proxy-ctl: restart skips services that are not present in zapret-only or tg-only builds --
(
assert pkgs.lib.hasInfix "if _svc_exists proxy-suite-socks; then" minimalProxyCtlScript;
assert pkgs.lib.hasInfix "_svc_exists \"$svc\" && _svc_active \"$svc\"" minimalProxyCtlScript;
assert pkgs.lib.hasInfix "proxy-suite-tg-ws-proxy" minimalProxyCtlScript;
true
)
# -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 -- # -- perAppRouting: generated proxy-ctl script dispatches through proxychains4 --
( (
assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG='-q'" perAppRoutingProxychainsScript; assert pkgs.lib.hasInfix "export PROXYCHAINS_QUIET_ARG='-q'" perAppRoutingProxychainsScript;
@@ -1911,6 +1954,8 @@ let
assert inbound.auto_route == false; assert inbound.auto_route == false;
assert inbound.auto_redirect == false; assert inbound.auto_redirect == false;
assert inbound.strict_route == false; assert inbound.strict_route == false;
assert !(inbound ? iproute2_table_index);
assert !(inbound ? iproute2_rule_index);
true true
) )
@@ -1945,6 +1990,9 @@ let
assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun"; assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun";
assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@"; assert perAppRoutingTunFixture.config.systemd.services ? "proxy-suite-per-app-tun-user@";
assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor"; assert perAppRoutingTunFixture.config.systemd.user.services ? "proxy-suite-per-app-tun-anchor";
assert perAppRoutingTunServiceConfig.ExecStartPre == perAppRoutingTunServiceConfig.ExecStopPost;
assert pkgs.lib.hasInfix "link del dev 'psperapptun0'" perAppRoutingTunCleanupScript;
assert pkgs.lib.hasInfix "rule del fwmark 16 table 101" perAppRoutingTunCleanupScript;
true true
) )
@@ -2019,8 +2067,11 @@ let
# -- perAppRouting: app TProxy startup installs nftables and loopback policy route -- # -- perAppRouting: app TProxy startup installs nftables and loopback policy route --
( (
assert pkgs.lib.hasInfix "proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript; assert pkgs.lib.hasInfix "proxy_suite_per_app_tproxy" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "route replace local default dev lo table 102" perAppRoutingTproxyStartScript; assert pkgs.lib.hasInfix "route replace local default dev lo table 102" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "rule add fwmark 17 table 102" perAppRoutingTproxyStartScript; assert pkgs.lib.hasInfix "rule add fwmark 17 table 102" perAppRoutingTproxyStartScript;
assert pkgs.lib.hasInfix "set +e" perAppRoutingTproxyStopScript;
assert pkgs.lib.hasInfix "rule del fwmark 17 table 102" perAppRoutingTproxyStopScript;
true true
) )
+51 -17
View File
@@ -57,6 +57,21 @@ _svc_active() {
systemctl is-active --quiet "$1" systemctl is-active --quiet "$1"
} }
_require_service() {
local svc="$1" message="$2"
if ! _svc_exists "$svc"; then
echo "$message"
exit 1
fi
}
_stop_if_exists() {
local svc="$1"
if _svc_exists "$svc"; then
systemctl stop "$svc" || true
fi
}
_route_mode_default() { _route_mode_default() {
printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}" printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}"
} }
@@ -159,6 +174,18 @@ _check_no_global_proxy() {
fi fi
} }
_cleanup_slice_if_idle() {
local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4"
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
}
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...] # _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
_wrap_slice() { _wrap_slice() {
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4" local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
@@ -171,22 +198,21 @@ _wrap_slice() {
local scope_unit="$slice_base-${profile}-$$" local scope_unit="$slice_base-${profile}-$$"
local anchor_unit="$slice_base-anchor.service" local anchor_unit="$slice_base-anchor.service"
local user_svc="$slice_base-user@$uid.service" local user_svc="$slice_base-user@$uid.service"
systemctl --user start "$anchor_unit"
systemctl start "$backend_svc"
systemctl start "$user_svc"
local status=0 local status=0
systemd-run --user --scope --quiet --collect --same-dir \
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
if ! _scope_running "$slice_base"; then systemctl --user start "$anchor_unit" || status=$?
systemctl stop "$user_svc" || true if [ "$status" -eq 0 ]; then
systemctl --user stop "$anchor_unit" || true systemctl start "$backend_svc" || status=$?
if ! _any_user_active "$slice_base-user@"; then
systemctl stop "$backend_svc" || true
fi
fi fi
if [ "$status" -eq 0 ]; then
systemctl start "$user_svc" || status=$?
fi
if [ "$status" -eq 0 ]; then
systemd-run --user --scope --quiet --collect --same-dir \
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
fi
_cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc"
exit "$status" exit "$status"
} }
@@ -210,11 +236,13 @@ cmd_status() {
cmd_proxy() { cmd_proxy() {
case "${1:-on}" in case "${1:-on}" in
on) on)
_require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled."
systemctl start proxy-suite-socks systemctl start proxy-suite-socks
;; ;;
off) off)
systemctl stop proxy-suite-tproxy || true _require_service proxy-suite-socks "SOCKS proxy service is not available because singBox is not enabled."
systemctl stop proxy-suite-tun || true _stop_if_exists proxy-suite-tproxy
_stop_if_exists proxy-suite-tun
systemctl stop proxy-suite-socks systemctl stop proxy-suite-socks
;; ;;
*) *)
@@ -228,6 +256,7 @@ cmd_mode_toggle() {
local name="$1" local name="$1"
local default_action="${2:-on}" local default_action="${2:-on}"
local display="${4:-${name#proxy-suite-}}" local display="${4:-${name#proxy-suite-}}"
_require_service "$name" "Service '$name' is not available in this proxy-suite configuration."
case "${3:-$default_action}" in case "${3:-$default_action}" in
on) on)
systemctl start "$name" systemctl start "$name"
@@ -272,13 +301,17 @@ cmd_route_mode() {
RESTART_SERVICES=( RESTART_SERVICES=(
proxy-suite-tproxy proxy-suite-tproxy
proxy-suite-tun proxy-suite-tun
proxy-suite-tg-ws-proxy
zapret-discord-youtube zapret-discord-youtube
) )
cmd_restart() { cmd_restart() {
systemctl restart proxy-suite-socks if _svc_exists proxy-suite-socks; then
systemctl restart proxy-suite-socks
fi
for svc in "${RESTART_SERVICES[@]}"; do for svc in "${RESTART_SERVICES[@]}"; do
if systemctl is-active --quiet "$svc"; then if _svc_exists "$svc" && _svc_active "$svc"; then
systemctl restart "$svc" systemctl restart "$svc"
fi fi
done done
@@ -421,6 +454,7 @@ cmd_subscription() {
done done
;; ;;
update) update)
_require_service proxy-suite-subscription-update "Subscription updates are unavailable because no subscriptions are configured."
systemctl start proxy-suite-subscription-update systemctl start proxy-suite-subscription-update
echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update" echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update"
;; ;;
+42 -9
View File
@@ -10,6 +10,15 @@ def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query)) return dict(urllib.parse.parse_qsl(query))
def _split_host_port(hostpart: str) -> tuple[str, str]:
host, separator, port = hostpart.rpartition(":")
if not separator or not host or not port:
raise ValueError("URL must include host and port")
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
return host, port
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]: def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
rest = url[len(f"{scheme}://") :] rest = url[len(f"{scheme}://") :]
rest, _, _ = rest.partition("#") rest, _, _ = rest.partition("#")
@@ -18,9 +27,7 @@ def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
else: else:
userinfo = "" userinfo = ""
hostpart, _, query = rest.partition("?") hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":") host, port = _split_host_port(hostpart)
if host.startswith("[") and host.endswith("]"):
host = host[1:-1]
return userinfo, host, port, _qs(query) return userinfo, host, port, _qs(query)
@@ -183,18 +190,44 @@ def parse_trojan(url: str, tag: str) -> dict:
return ob return ob
def parse_shadowsocks(url: str, tag: str) -> dict: def _decode_ss_userinfo(userinfo: str) -> tuple[str, str]:
userinfo, host, port, _ = _parse_url_parts(url, "ss") plain = urllib.parse.unquote(userinfo)
if ":" in plain:
return tuple(plain.split(":", 1))
pad = "=" * (-len(userinfo) % 4) pad = "=" * (-len(userinfo) % 4)
try: try:
decoded = base64.urlsafe_b64decode(userinfo + pad).decode() decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
if ":" not in decoded: if ":" not in decoded:
raise ValueError raise ValueError
method, password = decoded.split(":", 1) return tuple(decoded.split(":", 1))
except (binascii.Error, UnicodeDecodeError, ValueError): except (binascii.Error, UnicodeDecodeError, ValueError) as exc:
plain = urllib.parse.unquote(userinfo) raise ValueError("invalid shadowsocks userinfo") from exc
method, password = plain.split(":", 1)
def parse_shadowsocks(url: str, tag: str) -> dict:
# Support both SIP002 form:
# ss://base64(method:password)@host:port#name
# and legacy subscriptions that base64-encode the whole endpoint:
# ss://base64(method:password@host:port)#name
rest = url[len("ss://") :]
rest, _, _ = rest.partition("#")
endpoint, _, _ = rest.partition("?")
if "@" in endpoint:
userinfo, host, port, _ = _parse_url_parts(url, "ss")
else:
pad = "=" * (-len(endpoint) % 4)
try:
decoded = base64.urlsafe_b64decode(endpoint + pad).decode()
except (binascii.Error, UnicodeDecodeError) as exc:
raise ValueError("invalid shadowsocks URL") from exc
userinfo, separator, hostpart = decoded.rpartition("@")
if not separator:
raise ValueError("invalid legacy shadowsocks URL")
host, port = _split_host_port(hostpart)
method, password = _decode_ss_userinfo(userinfo)
return { return {
"type": "shadowsocks", "type": "shadowsocks",
+33
View File
@@ -55,6 +55,39 @@ class BuildOutboundTests(unittest.TestCase):
self.assertEqual(ob["type"], "shadowsocks") self.assertEqual(ob["type"], "shadowsocks")
self.assertEqual(ob["method"], "chacha20-ietf-poly1305") self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
def test_shadowsocks_legacy_full_base64(self):
legacy = (
base64.urlsafe_b64encode(
b"chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388"
)
.decode()
.rstrip("=")
)
ob = run_parser(f"ss://{legacy}#Legacy Server")
self.assertEqual(ob["type"], "shadowsocks")
self.assertEqual(ob["server"], "legacy.example.com")
self.assertEqual(ob["server_port"], 8388)
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
self.assertEqual(ob["password"], "passw0rd")
def test_shadowsocks_plain_userinfo(self):
ob = run_parser("ss://none:plain%20pass@plain.example.com:8388")
self.assertEqual(ob["type"], "shadowsocks")
self.assertEqual(ob["method"], "none")
self.assertEqual(ob["password"], "plain pass")
def test_shadowsocks_legacy_ipv6_strips_brackets(self):
legacy = (
base64.urlsafe_b64encode(b"none:pass@[2001:db8::1]:8388")
.decode()
.rstrip("=")
)
ob = run_parser(f"ss://{legacy}#Legacy IPv6")
self.assertEqual(ob["server"], "2001:db8::1")
self.assertEqual(ob["server_port"], 8388)
def test_hysteria2(self): def test_hysteria2(self):
ob = run_parser( ob = run_parser(
"hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask" "hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"