fix: various fixes

This commit is contained in:
FUFSoB committed 2026-06-24 23:08:16 +05:00
1 parent 22ebfa171d
commit 7ca7f4000b
17 files changed
+584 -353

No files matched your search

+14 -8
View File
@@ -9,6 +9,7 @@
let let
derived = import ./derived.nix { inherit lib cfg; }; derived = import ./derived.nix { inherit lib cfg; };
constants = derived.constants;
inherit (derived) inherit (derived)
proxyCfg proxyCfg
singBoxCfg singBoxCfg
@@ -19,10 +20,15 @@ let
globalTproxy globalTproxy
clashApiEnabled clashApiEnabled
; ;
inherit (constants)
xrayGlobalTunIPv6Address
xrayPerAppTunIPv6Address
xrayDnsBridgePorts
;
perAppTun = derived.perAppRoutingTun; perAppTun = derived.perAppRoutingTun;
direct = rules.direct; direct = rules.direct;
xrayGlobalTunIPv6Address = "fd66:19::1/64"; defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex;
xrayPerAppTunIPv6Address = "fd66:20::1/64"; defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority;
xrayFakeDnsPools = [ xrayFakeDnsPools = [
{ {
ipPool = "198.18.0.0/15"; ipPool = "198.18.0.0/15";
@@ -92,15 +98,15 @@ let
tunAddress ? globalTun.address, tunAddress ? globalTun.address,
tunMtu ? globalTun.mtu, tunMtu ? globalTun.mtu,
tunAutoRoute ? true, tunAutoRoute ? true,
tunAutoRouteTableIndex ? 2022, tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex,
tunAutoRouteRuleIndex ? 9000, tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority,
tunAutoRedirect ? true, tunAutoRedirect ? true,
tunStrictRoute ? true, tunStrictRoute ? true,
forceLocalDnsViaProxy ? false, forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false, useOutboundRoutingMark ? false,
enableClashApi ? clashApiEnabled, enableClashApi ? clashApiEnabled,
enableXrayDnsBridge ? hybridEnabled, enableXrayDnsBridge ? hybridEnabled,
xrayDnsBridgePort ? 18533, xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}: }:
{ {
log.level = "warn"; log.level = "warn";
@@ -405,7 +411,7 @@ let
enableMixed = true; enableMixed = true;
enableTProxy = true; enableTProxy = true;
useOutboundRoutingMark = true; useOutboundRoutingMark = true;
xrayDnsBridgePort = 18533; xrayDnsBridgePort = xrayDnsBridgePorts.socks;
}; };
singBoxTunTemplate = mkSingBoxConfig { singBoxTunTemplate = mkSingBoxConfig {
@@ -418,7 +424,7 @@ let
tunStrictRoute = true; tunStrictRoute = true;
forceLocalDnsViaProxy = false; forceLocalDnsViaProxy = false;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = 18534; xrayDnsBridgePort = xrayDnsBridgePorts.tun;
}; };
singBoxPerAppTunTemplate = mkSingBoxConfig { singBoxPerAppTunTemplate = mkSingBoxConfig {
@@ -432,7 +438,7 @@ let
forceLocalDnsViaProxy = false; forceLocalDnsViaProxy = false;
useOutboundRoutingMark = globalTproxy.enable; useOutboundRoutingMark = globalTproxy.enable;
enableClashApi = false; enableClashApi = false;
xrayDnsBridgePort = 18535; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
}; };
xrayTproxyTemplate = mkXrayConfig { xrayTproxyTemplate = mkXrayConfig {
+24
View File
@@ -52,6 +52,29 @@ let
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first"; clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
perAppZapretEnabled = perAppZapretCfg.enable; perAppZapretEnabled = perAppZapretCfg.enable;
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable; userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
constants = {
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
xrayTunPerAppTproxyRulePriority = 8996;
xrayTunPerAppTunRulePriority = 8997;
xrayGlobalTunIPv6Address = "fd66:19::1/64";
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
xrayPerAppTunIPv6Address = "fd66:20::1/64";
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64";
xrayDnsBridgePorts = {
socks = 18533;
tun = 18534;
perAppTun = 18535;
};
xraySidecarBasePorts = {
socks = 33080;
tun = 33180;
perAppTun = 33280;
};
};
invalidRoutingTargets = lib.unique ( invalidRoutingTargets = lib.unique (
map (rule: rule.outbound) ( map (rule: rule.outbound) (
@@ -82,6 +105,7 @@ in
perAppZapretEnabled perAppZapretEnabled
userControlCfg userControlCfg
userControlEnabled userControlEnabled
constants
selectionMode selectionMode
builtinTags builtinTags
outboundTags outboundTags
+3 -2
View File
@@ -15,6 +15,7 @@
}: }:
let let
constants = derived.constants;
assertions = import ./service/assertions-lib.nix { inherit lib; }; assertions = import ./service/assertions-lib.nix { inherit lib; };
inherit (assertions) inherit (assertions)
mkAssertion mkAssertion
@@ -42,7 +43,7 @@ let
perAppZapretCfg perAppZapretCfg
; ;
globalTunAutoRouteTable = 2022; globalTunAutoRouteTable = constants.tunAutoRouteTableIndex;
featureAssertions = [ featureAssertions = [
(requireAvailable proxyCfg.singBox.enable proxyEnabled (requireAvailable proxyCfg.singBox.enable proxyEnabled
@@ -160,7 +161,7 @@ let
condition = globalTun.enable && perAppRoutingTun.enable; condition = globalTun.enable && perAppRoutingTun.enable;
left = perAppRoutingTun.routeTable; left = perAppRoutingTun.routeTable;
right = globalTunAutoRouteTable; right = globalTunAutoRouteTable;
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table 2022"; message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table ${toString globalTunAutoRouteTable}";
} }
{ {
condition = perAppRoutingTun.enable && globalTproxy.enable; condition = perAppRoutingTun.enable && globalTproxy.enable;
+121
View File
@@ -35,6 +35,127 @@ rec {
) )
); );
cidrNetworkFunction = ''
cidr_network() {
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
'';
mkDefaultUplinkIPv4Source =
{
ip,
awk,
errorMessage,
}:
''
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo ${lib.escapeShellArg errorMessage} >&2
exit 1
fi
'';
mkNftDeleteTable =
{
nft,
family,
table,
}:
''
${nft} delete table ${family} ${table} 2>/dev/null || true
'';
mkIpRuleDeleteByFwmark =
{
ip,
family ? "",
fwmark,
table,
}:
''
while ${ip} ${lib.optionalString (family != "") "${family} "}rule del fwmark ${toString fwmark} table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByTable =
{
ip,
family,
table,
}:
''
while ${ip} ${family} rule del table ${toString table} 2>/dev/null; do :; done
'';
mkIpRuleDeleteByPriority =
{
ip,
family,
priority,
}:
''
while ${ip} ${family} rule del pref ${toString priority} 2>/dev/null; do :; done
'';
mkIpRouteFlushTable =
{
ip,
family,
table,
}:
''
${ip} ${family} route flush table ${toString table} 2>/dev/null || true
'';
mkIpLocalDefaultRouteDelete =
{
ip,
table,
}:
''
${ip} route del local default dev lo table ${toString table} 2>/dev/null || true
'';
mkIpLinkDelete =
{
ip,
interface,
}:
''
${ip} link del dev ${lib.escapeShellArg interface} 2>/dev/null || true
'';
flushResolvedCaches = ''
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
'';
mkRestartingService = mkRestartingService =
{ {
description, description,
+3
View File
@@ -17,6 +17,7 @@
let let
derived = import ../derived.nix { inherit lib cfg; }; derived = import ../derived.nix { inherit lib cfg; };
constants = derived.constants;
inherit (derived) inherit (derived)
singBoxCfg singBoxCfg
proxyCfg proxyCfg
@@ -82,6 +83,7 @@ let
selectionMode selectionMode
collapseNamedOutbounds collapseNamedOutbounds
hasSubscriptions hasSubscriptions
constants
; ;
inherit inherit
jq jq
@@ -111,6 +113,7 @@ let
perAppRoutingCfg perAppRoutingCfg
perAppRoutingTun perAppRoutingTun
perAppRoutingTproxy perAppRoutingTproxy
constants
; ;
perAppZapretCfg = perAppZapretCfg; perAppZapretCfg = perAppZapretCfg;
inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile; inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile;
+53 -67
View File
@@ -45,6 +45,12 @@ let
mkAnchorService mkAnchorService
; ;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip;
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN";
};
inherit (context) inherit (context)
derived derived
polkit polkit
@@ -76,6 +82,15 @@ let
invalidRoutingTargets invalidRoutingTargets
builtinTags builtinTags
; ;
constants = derived.constants;
inherit (constants)
tunAutoRouteTableIndex
tunAutoRouteRulePriority
xrayTunPerAppTproxyRulePriority
xrayTunPerAppTunRulePriority
xrayGlobalTunIPv6Address
xrayGlobalTunIPv6RoutePrefix
;
serviceNames = { serviceNames = {
socks = "proxy-suite-socks"; socks = "proxy-suite-socks";
@@ -91,19 +106,6 @@ let
proxyCfg.auth.username != null proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null); && (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
# Must match the explicit iproute2_* indexes written to the global SingBox TUN
# template in config.nix. XRay uses the same table for manual Linux
# policy routing because XRay's autoSystemRoutingTable is not Linux-ready.
tunAutoRouteTableIndex = 2022;
tunAutoRouteRulePriority = 9000;
# Keep app-scoped marks ahead of the global XRay TUN catch-all. Without
# these priorities, iproute2's default priority lets global TUN capture
# packets intended for per-app routing tables.
xrayTunPerAppTproxyRulePriority = 8996;
xrayTunPerAppTunRulePriority = 8997;
xrayGlobalTunIPv6Address = "fd66:19::1/64";
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" '' xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail set -euo pipefail
@@ -114,28 +116,7 @@ let
tun_route_prefix="" tun_route_prefix=""
uplink_addr="" uplink_addr=""
cidr_network() { ${builders.cidrNetworkFunction}
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
if [ "$prefix" -eq 0 ]; then
mask=0
else
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
fi
net=$((ip & mask))
printf '%d.%d.%d.%d/%s' \
$(((net >> 24) & 255)) \
$(((net >> 16) & 255)) \
$(((net >> 8) & 255)) \
$((net & 255)) \
"$prefix"
}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
@@ -149,20 +130,7 @@ let
exit 1 exit 1
fi fi
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk ' ${defaultUplinkIPv4Source}
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN" >&2
exit 1
fi
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
@@ -196,9 +164,13 @@ let
# Start from a clean policy-routing state. `ip rule add` permits duplicate # 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 # rules on some iproute2 versions, and a stale rule can keep packets routed
# into a dead local table after a failed restart. # into a dead local table after a failed restart.
${nft} delete table ip singbox 2>/dev/null || true ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByFwmark {
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
${nft} -f ${nftablesRulesFile} ${nft} -f ${nftablesRulesFile}
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable} ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
@@ -208,9 +180,13 @@ let
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
set +e set +e
${nft} delete table ip singbox 2>/dev/null || true ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }}
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByFwmark {
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true inherit ip;
fwmark = globalTproxy.fwmark;
table = globalTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }}
''; '';
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
@@ -219,18 +195,28 @@ let
# SingBox normally removes these on graceful shutdown, but stale # SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN # auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop. # interface after `proxy-ctl tun off` or an unclean service stop.
${nft} delete table inet sing-box 2>/dev/null || true ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByPriority {
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done inherit ip;
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done family = "-4";
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done priority = xrayTunPerAppTproxyRulePriority;
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true }}
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true ${builders.mkIpRuleDeleteByPriority {
inherit ip;
${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true family = "-4";
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRuleDeleteByPriority {
inherit ip;
family = "-6";
priority = xrayTunPerAppTunRulePriority;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }}
${builders.flushResolvedCaches}
''; '';
systemServiceEntries = [ systemServiceEntries = [
+57 -56
View File
@@ -9,6 +9,7 @@
perAppRoutingCfg, perAppRoutingCfg,
perAppRoutingTun, perAppRoutingTun,
perAppRoutingTproxy, perAppRoutingTproxy,
constants,
perAppZapretCfg, perAppZapretCfg,
perAppTunChainFile, perAppTunChainFile,
perAppTproxyRulesFile, perAppTproxyRulesFile,
@@ -26,6 +27,10 @@
let let
builders = import ./builders.nix { inherit lib pkgs; }; builders = import ./builders.nix { inherit lib pkgs; };
inherit (builders) mkAnchorService; inherit (builders) mkAnchorService;
defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source {
inherit ip awk;
errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN";
};
perAppTunSliceName = "proxy-suite-per-app-tun.slice"; perAppTunSliceName = "proxy-suite-per-app-tun.slice";
perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice";
@@ -99,8 +104,10 @@ let
hasZapretProfiles = builtins.any ( hasZapretProfiles = builtins.any (
profile: profile.route == "zapret" profile: profile.route == "zapret"
) effectivePerAppRoutingProfiles; ) effectivePerAppRoutingProfiles;
xrayPerAppTunIPv6Address = "fd66:20::1/64"; inherit (constants)
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64"; xrayPerAppTunIPv6Address
xrayPerAppTunIPv6RoutePrefix
;
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" '' perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
set -euo pipefail set -euo pipefail
@@ -124,50 +131,26 @@ let
tun_route_prefix="" tun_route_prefix=""
uplink_addr="" uplink_addr=""
cidr_network() { ${builders.cidrNetworkFunction}
local cidr="$1"
local addr="''${cidr%/*}"
local prefix="''${cidr#*/}"
local o1 o2 o3 o4 ip mask net
IFS=. read -r o1 o2 o3 o4 <<<"$addr" ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4)) ${builders.mkIpRuleDeleteByFwmark {
if [ "$prefix" -eq 0 ]; then inherit ip;
mask=0 family = "-4";
else fwmark = perAppRoutingTun.fwmark;
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF)) table = perAppRoutingTun.routeTable;
fi }}
net=$((ip & mask)) ${builders.mkIpRuleDeleteByFwmark {
inherit ip;
printf '%d.%d.%d.%d/%s' \ family = "-6";
$(((net >> 24) & 255)) \ fwmark = perAppRoutingTun.fwmark;
$(((net >> 16) & 255)) \ table = perAppRoutingTun.routeTable;
$(((net >> 8) & 255)) \ }}
$((net & 255)) \ ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
"$prefix" ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
}
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${nft} -f ${perAppTunChainFile} ${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface} ${perAppTunWaitForInterface}
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} ' ${defaultUplinkIPv4Source}
/src/ {
for (i = 1; i <= NF; i++) {
if ($i == "src" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$uplink_addr" ]; then
echo "proxy-suite: could not determine the default uplink IPv4 address for app TUN" >&2
exit 1
fi
tun_addr="''${tun_cidr%%/*}" tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")" tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
@@ -186,21 +169,35 @@ let
set +e set +e
# Best-effort cleanup for graceful stops and for unclean previous exits. # Best-effort cleanup for graceful stops and for unclean previous exits.
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }}
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByFwmark {
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done inherit ip;
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true family = "-4";
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true fwmark = perAppRoutingTun.fwmark;
${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true table = perAppRoutingTun.routeTable;
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true }}
${builders.mkIpRuleDeleteByFwmark {
inherit ip;
family = "-6";
fwmark = perAppRoutingTun.fwmark;
table = perAppRoutingTun.routeTable;
}}
${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }}
${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }}
${builders.flushResolvedCaches}
''; '';
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' 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 ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByFwmark {
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
${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}
@@ -210,9 +207,13 @@ let
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
set +e set +e
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }}
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done ${builders.mkIpRuleDeleteByFwmark {
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true inherit ip;
fwmark = perAppRoutingTproxy.fwmark;
table = perAppRoutingTproxy.routeTable;
}}
${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }}
''; '';
# Generate a "start" script that adds a per-user cgroup nftables mark rule. # Generate a "start" script that adds a per-user cgroup nftables mark rule.
+14 -13
View File
@@ -16,6 +16,7 @@
selectionMode, selectionMode,
collapseNamedOutbounds, collapseNamedOutbounds,
hasSubscriptions, hasSubscriptions,
constants,
jq, jq,
python3, python3,
singBox, singBox,
@@ -34,11 +35,7 @@ let
systemctl = "${pkgs.systemd}/bin/systemctl"; systemctl = "${pkgs.systemd}/bin/systemctl";
backend = if activeBackend == null then "sing-box" else activeBackend; backend = if activeBackend == null then "sing-box" else activeBackend;
mainBackend = if pureXrayEnabled then "xray" else "sing-box"; mainBackend = if pureXrayEnabled then "xray" else "sing-box";
subscriptionBackend = subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend;
if hybridEnabled then
"hybrid"
else
mainBackend;
backendArg = "--backend ${mainBackend}"; backendArg = "--backend ${mainBackend}";
subscriptionBackendArg = "--backend ${subscriptionBackend}"; subscriptionBackendArg = "--backend ${subscriptionBackend}";
backendBin = if pureXrayEnabled then xray else singBox; backendBin = if pureXrayEnabled then xray else singBox;
@@ -58,6 +55,10 @@ let
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel"; xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark; xraySidecarRoutingMark = globalTproxy.proxyMark;
inherit (constants)
xrayDnsBridgePorts
xraySidecarBasePorts
;
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
@@ -695,8 +696,8 @@ let
enableLocalProxyAuth ? false, enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false, xrayTunEgressBinding ? false,
xrayTunDnsRuntime ? false, xrayTunDnsRuntime ? false,
xraySidecarBasePort ? 33080, xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? 18533, xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
}: }:
pkgs.writeShellScript name '' pkgs.writeShellScript name ''
set -euo pipefail set -euo pipefail
@@ -815,8 +816,8 @@ let
configFile = tproxyFile; configFile = tproxyFile;
routingMark = globalTproxy.proxyMark; routingMark = globalTproxy.proxyMark;
enableLocalProxyAuth = localProxyAuthEnabled; enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = 33080; xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = 18533; xrayDnsBridgePort = xrayDnsBridgePorts.socks;
}; };
startTun = mkStartScript { startTun = mkStartScript {
@@ -826,8 +827,8 @@ let
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled; xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = 33180; xraySidecarBasePort = xraySidecarBasePorts.tun;
xrayDnsBridgePort = 18534; xrayDnsBridgePort = xrayDnsBridgePorts.tun;
}; };
startPerAppTun = mkStartScript { startPerAppTun = mkStartScript {
@@ -837,8 +838,8 @@ let
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled; xrayTunEgressBinding = xrayEnabled;
xrayTunDnsRuntime = pureXrayEnabled; xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarBasePort = 33280; xraySidecarBasePort = xraySidecarBasePorts.perAppTun;
xrayDnsBridgePort = 18535; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
}; };
mkSubscriptionFetchBlock = mkSubscriptionFetchBlock =
+56 -30
View File
@@ -216,6 +216,10 @@ let
}; };
minimal = evalProxySuite [ baseModule ]; minimal = evalProxySuite [ baseModule ];
checkConstants = (import ../modules/proxy-suite/derived.nix {
lib = pkgs.lib;
cfg = minimal.config.services.proxy-suite;
}).constants;
_minimalProxyCtl = mkProxyCtlDerived minimal; _minimalProxyCtl = mkProxyCtlDerived minimal;
minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; minimalProxyCtlWrapper = _minimalProxyCtl.wrapper;
minimalProxyCtlScript = _minimalProxyCtl.script; minimalProxyCtlScript = _minimalProxyCtl.script;
@@ -2238,10 +2242,10 @@ let
assert !(hybridTproxyConfig ? routing); assert !(hybridTproxyConfig ? routing);
assert dnsBridgeInbound.type == "direct"; assert dnsBridgeInbound.type == "direct";
assert dnsBridgeInbound.listen == "127.0.0.1"; assert dnsBridgeInbound.listen == "127.0.0.1";
assert dnsBridgeInbound.listen_port == 18533; assert dnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.socks;
assert mixedInbound.type == "mixed"; assert mixedInbound.type == "mixed";
assert tproxyInbound.type == "tproxy"; assert tproxyInbound.type == "tproxy";
assert tunDnsBridgeInbound.listen_port == 18534; assert tunDnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.tun;
assert assert
dnsBridgeRouteRule.network == [ dnsBridgeRouteRule.network == [
"tcp" "tcp"
@@ -2250,12 +2254,18 @@ let
assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript; assert pkgs.lib.hasInfix "/bin/sing-box run -c" hybridStartScript;
assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript; assert pkgs.lib.hasInfix "/bin/xray run -c" hybridStartScript;
assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript; assert pkgs.lib.hasInfix "xray-sidecar.json" hybridStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=33080" hybridStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}"
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18533" hybridStartScript; hybridStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=33180" hybridTunStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}"
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18534" hybridTunStartScript; hybridStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=33280" hybridPerAppTunStartScript; assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}"
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18535" hybridPerAppTunStartScript; hybridTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.tun}"
hybridTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.perAppTun}"
hybridPerAppTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.perAppTun}"
hybridPerAppTunStartScript;
assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript; assert pkgs.lib.hasInfix "--backend sing-box" hybridStartScript;
assert pkgs.lib.hasInfix "--backend xray" hybridStartScript; assert pkgs.lib.hasInfix "--backend xray" hybridStartScript;
assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript; assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript;
@@ -2348,7 +2358,7 @@ let
assert assert
tunInbound.settings.gateway == [ tunInbound.settings.gateway == [
"172.19.0.1/30" "172.19.0.1/30"
"fd66:19::1/64" checkConstants.xrayGlobalTunIPv6Address
]; ];
assert builtins.length tunInbound.settings.dns == 2; assert builtins.length tunInbound.settings.dns == 2;
assert tunInbound.settings.autoOutboundsInterface == "auto"; assert tunInbound.settings.autoOutboundsInterface == "auto";
@@ -2401,28 +2411,39 @@ let
assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayBackendJqFilter; assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayBackendJqFilter;
assert pkgs.lib.hasInfix ".protocol == \"dns\"" xrayBackendJqFilter; assert pkgs.lib.hasInfix ".protocol == \"dns\"" xrayBackendJqFilter;
assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayTunUpScript; assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayTunUpScript;
assert pkgs.lib.hasInfix "fd66:19::1/64" xrayTunUpScript; assert pkgs.lib.hasInfix checkConstants.xrayGlobalTunIPv6Address xrayTunUpScript;
assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayTunUpScript; assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayTunUpScript;
assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript; assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript;
assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev singtun0'' xrayTunUpScript; assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev singtun0'' xrayTunUpScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix
''route replace "$tun_route_prefix" dev singtun0 src "$tun_addr" table 2022'' ''route replace "$tun_route_prefix" dev singtun0 src "$tun_addr" table ${toString checkConstants.tunAutoRouteTableIndex}''
xrayTunUpScript; xrayTunUpScript;
assert pkgs.lib.hasInfix ''route replace default dev singtun0 src "$uplink_addr" table 2022'' assert pkgs.lib.hasInfix ''route replace default dev singtun0 src "$uplink_addr" table ${toString checkConstants.tunAutoRouteTableIndex}''
xrayTunUpScript; xrayTunUpScript;
assert pkgs.lib.hasInfix ''-6 route replace "$tun6_route_prefix" dev singtun0 table 2022'' assert pkgs.lib.hasInfix ''-6 route replace "$tun6_route_prefix" dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}''
xrayTunUpScript;
assert pkgs.lib.hasInfix "-6 route replace default dev singtun0 table ${toString checkConstants.tunAutoRouteTableIndex}"
xrayTunUpScript;
assert pkgs.lib.hasInfix
"rule add pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority} fwmark 17 table 102"
xrayTunUpScript;
assert pkgs.lib.hasInfix
"rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101"
xrayTunUpScript;
assert pkgs.lib.hasInfix
"rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}"
xrayTunUpScript;
assert pkgs.lib.hasInfix
"-6 rule add pref ${toString checkConstants.xrayTunPerAppTunRulePriority} fwmark 16 table 101"
xrayTunUpScript;
assert pkgs.lib.hasInfix
"-6 rule add pref ${toString checkConstants.tunAutoRouteRulePriority} not fwmark 2 table ${toString checkConstants.tunAutoRouteTableIndex}"
xrayTunUpScript; xrayTunUpScript;
assert pkgs.lib.hasInfix "-6 route replace default dev singtun0 table 2022" xrayTunUpScript;
assert pkgs.lib.hasInfix "rule add pref 8996 fwmark 17 table 102" xrayTunUpScript;
assert pkgs.lib.hasInfix "rule add pref 8997 fwmark 16 table 101" xrayTunUpScript;
assert pkgs.lib.hasInfix "rule add pref 9000 not fwmark 2 table 2022" xrayTunUpScript;
assert pkgs.lib.hasInfix "-6 rule add pref 8997 fwmark 16 table 101" xrayTunUpScript;
assert pkgs.lib.hasInfix "-6 rule add pref 9000 not fwmark 2 table 2022" xrayTunUpScript;
assert perAppTunInbound.settings.name == "psperapptun0"; assert perAppTunInbound.settings.name == "psperapptun0";
assert assert
perAppTunInbound.settings.gateway == [ perAppTunInbound.settings.gateway == [
"172.20.0.1/30" "172.20.0.1/30"
"fd66:20::1/64" checkConstants.xrayPerAppTunIPv6Address
]; ];
assert builtins.length perAppTunInbound.settings.dns == 2; assert builtins.length perAppTunInbound.settings.dns == 2;
assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ]; assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ];
@@ -2443,7 +2464,7 @@ let
assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter; assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter;
assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter; assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter;
assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayPerAppTunUpScript; assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix "fd66:20::1/64" xrayPerAppTunUpScript; assert pkgs.lib.hasInfix checkConstants.xrayPerAppTunIPv6Address xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayPerAppTunUpScript; assert pkgs.lib.hasInfix ''uplink_addr="$('' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript; assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' xrayPerAppTunUpScript; assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' xrayPerAppTunUpScript;
@@ -2550,8 +2571,8 @@ let
let let
inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds); inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds);
in in
assert inbound.iproute2_table_index == 2022; assert inbound.iproute2_table_index == checkConstants.tunAutoRouteTableIndex;
assert inbound.iproute2_rule_index == 9000; assert inbound.iproute2_rule_index == checkConstants.tunAutoRouteRulePriority;
assert tunDefaultConfig.route.auto_detect_interface == true; assert tunDefaultConfig.route.auto_detect_interface == true;
true true
) )
@@ -2562,10 +2583,14 @@ let
( (
assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost; assert tunServiceConfig.ExecStartPre == tunServiceConfig.ExecStopPost;
assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript; assert pkgs.lib.hasInfix "delete table inet sing-box" tunCleanupScript;
assert pkgs.lib.hasInfix "rule del table 2022" tunCleanupScript; assert pkgs.lib.hasInfix "rule del table ${toString checkConstants.tunAutoRouteTableIndex}"
assert pkgs.lib.hasInfix "rule del pref 8996" tunCleanupScript; tunCleanupScript;
assert pkgs.lib.hasInfix "rule del pref 8997" tunCleanupScript; assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority}"
assert pkgs.lib.hasInfix "route flush table 2022" tunCleanupScript; tunCleanupScript;
assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTunRulePriority}"
tunCleanupScript;
assert pkgs.lib.hasInfix "route flush table ${toString checkConstants.tunAutoRouteTableIndex}"
tunCleanupScript;
assert pkgs.lib.hasInfix "link del dev" tunCleanupScript; assert pkgs.lib.hasInfix "link del dev" tunCleanupScript;
assert pkgs.lib.hasInfix "singtun0" tunCleanupScript; assert pkgs.lib.hasInfix "singtun0" tunCleanupScript;
true true
@@ -3114,7 +3139,8 @@ let
assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir"
perAppRoutingTunScript; perAppRoutingTunScript;
assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript; assert pkgs.lib.hasInfix "_check_no_global_proxy tun" perAppRoutingTunScript;
assert pkgs.lib.hasInfix ''_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED"'' assert pkgs.lib.hasInfix
''_wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED"''
perAppRoutingTunScript; perAppRoutingTunScript;
assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript; assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" perAppRoutingTunScript;
assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript; assert pkgs.lib.hasInfix "cleanup_slice()" perAppRoutingTunScript;
@@ -3126,7 +3152,7 @@ let
( (
assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript; assert pkgs.lib.hasInfix "PER_APP_ROUTING_TPROXY_ENABLED" perAppRoutingTproxyScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix
''_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED"'' ''_wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED"''
perAppRoutingTproxyScript; perAppRoutingTproxyScript;
assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript; assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript;
true true
@@ -3136,7 +3162,7 @@ let
( (
assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript;
assert pkgs.lib.hasInfix assert pkgs.lib.hasInfix
''_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED"'' ''_wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED"''
perAppRoutingZapretScript; perAppRoutingZapretScript;
assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript; assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript;
true true
+68 -23
View File
@@ -28,30 +28,75 @@
touch "$out" touch "$out"
''; '';
options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } '' options-doc =
diff -u ${../../docs/options.md} ${generatedOptionsDoc} pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; }
touch "$out" ''
''; diff -u ${../../docs/options.md} ${generatedOptionsDoc}
touch "$out"
'';
readme-doc = pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } '' readme-doc =
diff -u ${../../README.md} ${generatedReadmeDoc} pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; }
touch "$out" ''
''; diff -u ${../../README.md} ${generatedReadmeDoc}
touch "$out"
'';
readme-doc-source = builtins.seq proxy-ctl-subscription-list =
( pkgs.runCommand "proxy-suite-proxy-ctl-subscription-list-check"
assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource); {
assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource); nativeBuildInputs = [
true pkgs.bash
) pkgs.coreutils
(pkgs.writeText "proxy-suite-readme-doc-source-check" "ok"); pkgs.gawk
pkgs.jq
];
}
''
proxy_ctl="$TMPDIR/proxy-ctl"
cat ${../../pkgs/proxy-ctl-lib.sh} ${../../pkgs/proxy-ctl.sh} > "$proxy_ctl"
chmod +x "$proxy_ctl"
package-source = builtins.seq mkdir -p cache
( printf '%s\n' '["plain","hybrid","bad"]' > tags.json
assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource); printf '%s\n' '[{},{}]' > cache/plain.json
assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource); printf '%s\n' '{"singBox":[{},{}],"xray":[{}]}' > cache/hybrid.json
assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource); printf '%s\n' '{"singBox":[{}]}' > cache/bad.json
true
) env \
(pkgs.writeText "proxy-suite-package-source-check" "ok"); SUB_TAGS_FILE="$PWD/tags.json" \
SUB_CACHE_DIR="$PWD/cache" \
CLASH_API="http://127.0.0.1:9090" \
SELECTION="first" \
PER_APP_ROUTING_ENABLED="0" \
PER_APP_ROUTING_PROXYCHAINS_ENABLED="0" \
PER_APP_ROUTING_TUN_ENABLED="0" \
PER_APP_ROUTING_TPROXY_ENABLED="0" \
PER_APP_ROUTING_ZAPRET_ENABLED="0" \
PER_APP_ROUTING_PROFILES_FILE="$PWD/profiles.json" \
PROXYCHAINS_CONFIG="$PWD/proxychains.conf" \
PROXYCHAINS_QUIET_ARG="" \
ROUTE_MODE_STATE_FILE="$PWD/route-mode" \
DEFAULT_ROUTE_MODE="blacklist" \
bash "$proxy_ctl" subscription list > output
awk '$1 == "plain" { found = 1; if ($NF != "2") exit 1 } END { exit found ? 0 : 1 }' output
awk '$1 == "hybrid" { found = 1; if ($NF != "3") exit 1 } END { exit found ? 0 : 1 }' output
awk '$1 == "bad" { found = 1; if ($NF != "?") exit 1 } END { exit found ? 0 : 1 }' output
touch "$out"
'';
readme-doc-source = builtins.seq (
assert !(pkgs.lib.hasInfix "environment.systemPackages" readmeDocSource);
assert !(pkgs.lib.hasInfix "packageByPattern" readmeDocSource);
true
) (pkgs.writeText "proxy-suite-readme-doc-source-check" "ok");
package-source = builtins.seq (
assert !(pkgs.lib.hasInfix "../../pkgs/proxy-suite-tray.nix" trayModuleSource);
assert !(pkgs.lib.hasInfix "../../pkgs/tg-ws-proxy.nix" tgWsProxyModuleSource);
assert !(pkgs.lib.hasInfix "../../../pkgs/proxy-ctl.nix" controlModuleSource);
true
) (pkgs.writeText "proxy-suite-package-source-check" "ok");
} }
+23 -7
View File
@@ -186,10 +186,10 @@ _cleanup_slice_if_idle() {
fi fi
} }
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...] # _wrap_slice <slice_base> <profile> <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" profile="$2" enabled="$3" disabled_msg="$4" backend_svc="$5"
shift 4 shift 5
if [ "$enabled" != "1" ]; then if [ "$enabled" != "1" ]; then
echo "$disabled_msg" echo "$disabled_msg"
exit 1 exit 1
@@ -220,6 +220,22 @@ _wrap_slice() {
exit "$status" exit "$status"
} }
_subscription_proxy_count() {
local cache="$1"
jq '
if type == "array" then
length
elif type == "object"
and (.singBox | type == "array")
and (.xray | type == "array")
then
(.singBox | length) + (.xray | length)
else
error("unsupported subscription cache shape")
end
' "$cache"
}
cmd_status() { cmd_status() {
if [ "${1:-}" = "--tray" ]; then if [ "${1:-}" = "--tray" ]; then
_status_tray _status_tray
@@ -409,19 +425,19 @@ cmd_wrap() {
;; ;;
tun) tun)
_check_no_global_proxy tun _check_no_global_proxy tun
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \ _wrap_slice "proxy-suite-per-app-tun" "$profile" "$PER_APP_ROUTING_TUN_ENABLED" \
"Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \ "Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \
"proxy-suite-per-app-tun.service" "$@" "proxy-suite-per-app-tun.service" "$@"
;; ;;
tproxy) tproxy)
_check_no_global_proxy tproxy _check_no_global_proxy tproxy
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \ _wrap_slice "proxy-suite-per-app-tproxy" "$profile" "$PER_APP_ROUTING_TPROXY_ENABLED" \
"Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \ "Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \
"proxy-suite-per-app-tproxy.service" "$@" "proxy-suite-per-app-tproxy.service" "$@"
;; ;;
zapret) zapret)
_check_no_global_proxy zapret _check_no_global_proxy zapret
_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED" \ _wrap_slice "proxy-suite-per-app-zapret" "$profile" "$PER_APP_ROUTING_ZAPRET_ENABLED" \
"Profile '$profile' uses route=zapret, but zapret.perApp.enable is false." \ "Profile '$profile' uses route=zapret, but zapret.perApp.enable is false." \
"proxy-suite-per-app-zapret.service" "$@" "proxy-suite-per-app-zapret.service" "$@"
;; ;;
@@ -450,7 +466,7 @@ cmd_subscription() {
cache="$CACHE_DIR/$t.json" cache="$CACHE_DIR/$t.json"
if [ -f "$cache" ]; then if [ -f "$cache" ]; then
age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown") age=$(date -r "$cache" "+%Y-%m-%d %H:%M:%S" 2>/dev/null || echo "unknown")
count=$(jq 'length' "$cache" 2>/dev/null || echo "?") count=$(_subscription_proxy_count "$cache" 2>/dev/null || echo "?")
else else
age="(no cache)" age="(no cache)"
count="-" count="-"
-2
View File
@@ -18,8 +18,6 @@ pkgs.stdenv.mkDerivation {
buildPhase = '' buildPhase = ''
$CC -o proxy-suite-tray main.c \ $CC -o proxy-suite-tray main.c \
$(pkg-config --cflags --libs gtk+-3.0 ayatana-appindicator3-0.1) \ $(pkg-config --cflags --libs gtk+-3.0 ayatana-appindicator3-0.1) \
-DSYSTEMCTL_BIN='"${pkgs.systemd}/bin/systemctl"' \
-DPKEXEC_BIN='"/run/wrappers/bin/pkexec"' \
-DPOLL_INTERVAL=${toString pollInterval} \ -DPOLL_INTERVAL=${toString pollInterval} \
-O2 -Wall -Werror=discarded-qualifiers -O2 -Wall -Werror=discarded-qualifiers
''; '';
+97 -123
View File
@@ -11,17 +11,14 @@
#ifndef PROXY_CTL_BIN #ifndef PROXY_CTL_BIN
#define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl" #define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl"
#endif #endif
#define ROUTE_MODE_CHOICE_COUNT 5
static AppIndicator *indicator; static AppIndicator *indicator;
static GtkWidget *menu; static GtkWidget *menu;
static GtkWidget *status_item; static GtkWidget *status_item;
static GtkWidget *proxy_item; static GtkWidget *proxy_item;
static GtkWidget *route_mode_item; static GtkWidget *route_mode_item;
static GtkWidget *route_mode_default_item; static GtkWidget *route_mode_items[ROUTE_MODE_CHOICE_COUNT];
static GtkWidget *route_mode_whitelist_item;
static GtkWidget *route_mode_blacklist_item;
static GtkWidget *route_mode_all_proxy_item;
static GtkWidget *route_mode_all_bypass_item;
static GtkWidget *tproxy_item; static GtkWidget *tproxy_item;
static GtkWidget *tun_item; static GtkWidget *tun_item;
static GtkWidget *zapret_item; static GtkWidget *zapret_item;
@@ -49,6 +46,21 @@ typedef enum
ROUTE_MODE_ALL_BYPASS ROUTE_MODE_ALL_BYPASS
} RouteMode; } RouteMode;
typedef struct
{
RouteMode mode;
const char *id;
const char *status_label;
const char *control_label;
} RouteModeInfo;
static const RouteModeInfo route_mode_infos[ROUTE_MODE_CHOICE_COUNT] = {
{ROUTE_MODE_DEFAULT, "default", "Default", "Default (stop overriding)"},
{ROUTE_MODE_WHITELIST, "whitelist", "Whitelist (direct by default)", "Whitelist (direct by default)"},
{ROUTE_MODE_BLACKLIST, "blacklist", "Blacklist (proxy by default)", "Blacklist (proxy by default)"},
{ROUTE_MODE_ALL_PROXY, "all-proxy", "All Proxy (override)", "All Proxy (override)"},
{ROUTE_MODE_ALL_BYPASS, "all-bypass", "All Bypass (override)", "All Bypass (override)"}};
typedef struct typedef struct
{ {
gboolean loaded; gboolean loaded;
@@ -169,17 +181,7 @@ static GDBusMessage *on_session_bus_message(
return message; return message;
} }
static gboolean run_proxy_ctl1(const char *arg1) static gboolean proxy_ctl_command(const char *arg1, const char *arg2, gchar **stdout_text)
{
gchar *argv[] = {
(gchar *)PROXY_CTL_BIN,
(gchar *)arg1,
NULL};
return command_succeeds(argv);
}
static gboolean run_proxy_ctl2(const char *arg1, const char *arg2)
{ {
gchar *argv[] = { gchar *argv[] = {
(gchar *)PROXY_CTL_BIN, (gchar *)PROXY_CTL_BIN,
@@ -187,39 +189,47 @@ static gboolean run_proxy_ctl2(const char *arg1, const char *arg2)
(gchar *)arg2, (gchar *)arg2,
NULL}; NULL};
if (stdout_text)
{
return command_stdout(argv, stdout_text);
}
return command_succeeds(argv); return command_succeeds(argv);
} }
static gboolean run_proxy_ctl(const char *arg1, const char *arg2)
{
return proxy_ctl_command(arg1, arg2, NULL);
}
static gboolean parse_proxy_ctl_bool(const char *value) static gboolean parse_proxy_ctl_bool(const char *value)
{ {
return value && strcmp(value, "true") == 0; return value && strcmp(value, "true") == 0;
} }
static const RouteModeInfo *route_mode_info_by_mode(RouteMode mode)
{
for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
{
if (route_mode_infos[i].mode == mode)
{
return &route_mode_infos[i];
}
}
return NULL;
}
static RouteMode parse_route_mode(const char *value) static RouteMode parse_route_mode(const char *value)
{ {
if (!value) if (!value)
{ {
return ROUTE_MODE_UNKNOWN; return ROUTE_MODE_UNKNOWN;
} }
if (strcmp(value, "default") == 0) for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
{ {
return ROUTE_MODE_DEFAULT; if (strcmp(value, route_mode_infos[i].id) == 0)
} {
if (strcmp(value, "whitelist") == 0) return route_mode_infos[i].mode;
{ }
return ROUTE_MODE_WHITELIST;
}
if (strcmp(value, "blacklist") == 0)
{
return ROUTE_MODE_BLACKLIST;
}
if (strcmp(value, "all-proxy") == 0)
{
return ROUTE_MODE_ALL_PROXY;
}
if (strcmp(value, "all-bypass") == 0)
{
return ROUTE_MODE_ALL_BYPASS;
} }
return ROUTE_MODE_UNKNOWN; return ROUTE_MODE_UNKNOWN;
} }
@@ -250,13 +260,8 @@ static ServiceState get_service_state(void)
{ {
ServiceState state = {0}; ServiceState state = {0};
gchar *stdout_text = NULL; gchar *stdout_text = NULL;
gchar *argv[] = {
(gchar *)PROXY_CTL_BIN,
(gchar *)"status",
(gchar *)"--tray",
NULL};
if (!command_stdout(argv, &stdout_text)) if (!proxy_ctl_command("status", "--tray", &stdout_text))
{ {
return state; return state;
} }
@@ -351,9 +356,10 @@ static const char *traffic_mode_label(const ServiceState *state)
static const char *route_mode_label(const ServiceState *state) static const char *route_mode_label(const ServiceState *state)
{ {
switch (state->route_mode) const RouteModeInfo *info;
if (state->route_mode == ROUTE_MODE_DEFAULT)
{ {
case ROUTE_MODE_DEFAULT:
switch (state->default_route_mode) switch (state->default_route_mode)
{ {
case ROUTE_MODE_WHITELIST: case ROUTE_MODE_WHITELIST:
@@ -363,61 +369,36 @@ static const char *route_mode_label(const ServiceState *state)
default: default:
return "Default"; return "Default";
} }
case ROUTE_MODE_WHITELIST:
return "Whitelist (direct by default)";
case ROUTE_MODE_BLACKLIST:
return "Blacklist (proxy by default)";
case ROUTE_MODE_ALL_PROXY:
return "All Proxy (override)";
case ROUTE_MODE_ALL_BYPASS:
return "All Bypass (override)";
default:
return "Unknown";
} }
info = route_mode_info_by_mode(state->route_mode);
return info ? info->status_label : "Unknown";
} }
static gint route_mode_combo_index(RouteMode mode) static gint route_mode_combo_index(RouteMode mode)
{ {
switch (mode) for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
{ {
case ROUTE_MODE_DEFAULT: if (route_mode_infos[i].mode == mode)
return 0; {
case ROUTE_MODE_WHITELIST: return (gint)i;
return 1; }
case ROUTE_MODE_BLACKLIST:
return 2;
case ROUTE_MODE_ALL_PROXY:
return 3;
case ROUTE_MODE_ALL_BYPASS:
return 4;
default:
return -1;
} }
return -1;
} }
static void sync_route_mode_widgets(RouteMode mode) static void sync_route_mode_widgets(RouteMode mode)
{ {
updating_route_mode_widgets = TRUE; updating_route_mode_widgets = TRUE;
if (route_mode_default_item) for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
{ {
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_default_item), mode == ROUTE_MODE_DEFAULT); if (route_mode_items[i])
} {
if (route_mode_whitelist_item) gtk_check_menu_item_set_active(
{ GTK_CHECK_MENU_ITEM(route_mode_items[i]),
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_whitelist_item), mode == ROUTE_MODE_WHITELIST); mode == route_mode_infos[i].mode);
} }
if (route_mode_blacklist_item)
{
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_blacklist_item), mode == ROUTE_MODE_BLACKLIST);
}
if (route_mode_all_proxy_item)
{
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_proxy_item), mode == ROUTE_MODE_ALL_PROXY);
}
if (route_mode_all_bypass_item)
{
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_bypass_item), mode == ROUTE_MODE_ALL_BYPASS);
} }
if (controls_route_mode_combo) if (controls_route_mode_combo)
{ {
@@ -670,11 +651,11 @@ static void on_proxy_toggle(GtkWidget *item, gpointer data)
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.socks) if (state.socks)
{ {
run_proxy_ctl2("proxy", "off"); run_proxy_ctl("proxy", "off");
} }
else else
{ {
run_proxy_ctl2("proxy", "on"); run_proxy_ctl("proxy", "on");
} }
update_status(); update_status();
} }
@@ -686,11 +667,11 @@ static void on_tproxy_toggle(GtkWidget *item, gpointer data)
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.tproxy) if (state.tproxy)
{ {
run_proxy_ctl2("tproxy", "off"); run_proxy_ctl("tproxy", "off");
} }
else else
{ {
run_proxy_ctl2("tproxy", "on"); run_proxy_ctl("tproxy", "on");
} }
update_status(); update_status();
} }
@@ -707,7 +688,7 @@ static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data)
{ {
return; return;
} }
run_proxy_ctl2("route-mode", mode); run_proxy_ctl("route-mode", mode);
update_status(); update_status();
} }
@@ -731,7 +712,7 @@ static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data)
{ {
return; return;
} }
run_proxy_ctl2("route-mode", mode); run_proxy_ctl("route-mode", mode);
update_status(); update_status();
} }
@@ -742,11 +723,11 @@ static void on_tun_toggle(GtkWidget *item, gpointer data)
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.tun) if (state.tun)
{ {
run_proxy_ctl2("tun", "off"); run_proxy_ctl("tun", "off");
} }
else else
{ {
run_proxy_ctl2("tun", "on"); run_proxy_ctl("tun", "on");
} }
update_status(); update_status();
} }
@@ -758,11 +739,11 @@ static void on_zapret_toggle(GtkWidget *item, gpointer data)
ServiceState state = get_service_state(); ServiceState state = get_service_state();
if (state.zapret) if (state.zapret)
{ {
run_proxy_ctl2("zapret", "off"); run_proxy_ctl("zapret", "off");
} }
else else
{ {
run_proxy_ctl2("zapret", "on"); run_proxy_ctl("zapret", "on");
} }
update_status(); update_status();
} }
@@ -771,7 +752,7 @@ static void on_restart(GtkWidget *item, gpointer data)
{ {
(void)item; (void)item;
(void)data; (void)data;
run_proxy_ctl1("restart"); run_proxy_ctl("restart", NULL);
update_status(); update_status();
} }
@@ -779,7 +760,7 @@ static void on_subscription_update(GtkWidget *item, gpointer data)
{ {
(void)item; (void)item;
(void)data; (void)data;
run_proxy_ctl2("subscription", "update"); run_proxy_ctl("subscription", "update");
} }
static void on_open_controls(GtkWidget *item, gpointer data) static void on_open_controls(GtkWidget *item, gpointer data)
@@ -851,11 +832,13 @@ static void build_controls_window(void)
gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_status_label, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_status_label, FALSE, FALSE, 0);
controls_route_mode_combo = gtk_combo_box_text_new(); controls_route_mode_combo = gtk_combo_box_text_new();
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "default", "Default (stop overriding)"); for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "whitelist", "Whitelist (direct by default)"); {
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "blacklist", "Blacklist (proxy by default)"); gtk_combo_box_text_append(
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-proxy", "All Proxy (override)"); GTK_COMBO_BOX_TEXT(controls_route_mode_combo),
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-bypass", "All Bypass (override)"); route_mode_infos[i].id,
route_mode_infos[i].control_label);
}
g_signal_connect(controls_route_mode_combo, "changed", G_CALLBACK(on_route_mode_combo_changed), NULL); g_signal_connect(controls_route_mode_combo, "changed", G_CALLBACK(on_route_mode_combo_changed), NULL);
gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_combo, FALSE, FALSE, 0); gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_combo, FALSE, FALSE, 0);
} }
@@ -948,30 +931,21 @@ static void build_menu(void)
{ {
route_mode_item = gtk_menu_item_new_with_label("[Routing] Mode: Unknown"); route_mode_item = gtk_menu_item_new_with_label("[Routing] Mode: Unknown");
GtkWidget *route_mode_menu = gtk_menu_new(); GtkWidget *route_mode_menu = gtk_menu_new();
GSList *route_group = NULL;
route_mode_default_item = gtk_radio_menu_item_new_with_label(NULL, "Default (stop overriding)"); for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i)
g_signal_connect(route_mode_default_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "default"); {
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_default_item); route_mode_items[i] = gtk_radio_menu_item_new_with_label(
route_group,
GSList *route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_default_item)); route_mode_infos[i].control_label);
route_mode_whitelist_item = gtk_radio_menu_item_new_with_label(route_group, "Whitelist (direct by default)"); g_signal_connect(
g_signal_connect(route_mode_whitelist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "whitelist"); route_mode_items[i],
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_whitelist_item); "toggled",
G_CALLBACK(on_route_mode_menu_toggled),
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_whitelist_item)); (gpointer)route_mode_infos[i].id);
route_mode_blacklist_item = gtk_radio_menu_item_new_with_label(route_group, "Blacklist (proxy by default)"); gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_items[i]);
g_signal_connect(route_mode_blacklist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "blacklist"); route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_items[i]));
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_blacklist_item); }
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_blacklist_item));
route_mode_all_proxy_item = gtk_radio_menu_item_new_with_label(route_group, "All Proxy (override)");
g_signal_connect(route_mode_all_proxy_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-proxy");
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_proxy_item);
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_all_proxy_item));
route_mode_all_bypass_item = gtk_radio_menu_item_new_with_label(route_group, "All Bypass (override)");
g_signal_connect(route_mode_all_bypass_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-bypass");
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_bypass_item);
gtk_menu_item_set_submenu(GTK_MENU_ITEM(route_mode_item), route_mode_menu); gtk_menu_item_set_submenu(GTK_MENU_ITEM(route_mode_item), route_mode_menu);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), route_mode_item); gtk_menu_shell_append(GTK_MENU_SHELL(menu), route_mode_item);
+23 -22
View File
@@ -6,7 +6,7 @@ import sys
import urllib.parse import urllib.parse
import urllib.request import urllib.request
from proxy_url_parsers import PARSERS from proxy_url_parsers import BACKEND_AWARE_PARSERS, PARSERS
def detect_scheme(url: str) -> str: def detect_scheme(url: str) -> str:
@@ -19,10 +19,9 @@ def _parse_url(url: str, tag: str, backend: str) -> dict:
raise ValueError(f"unsupported scheme '{scheme}'") raise ValueError(f"unsupported scheme '{scheme}'")
parser = PARSERS[scheme] parser = PARSERS[scheme]
try: if scheme in BACKEND_AWARE_PARSERS:
return parser(url, tag, backend) return parser(url, tag, backend)
except TypeError: return parser(url, tag)
return parser(url, tag)
def _xray_sockopt(routing_mark: int | None) -> dict: def _xray_sockopt(routing_mark: int | None) -> dict:
@@ -250,6 +249,24 @@ def make_tag(prefix: str, remark: str, index: int) -> str:
return f"{prefix}-{index}" return f"{prefix}-{index}"
def _remark_from_line(line: str) -> str:
return line.split("#", 1)[1] if "#" in line else ""
def _unique_tag(base_tag: str, seen_tags: set[str]) -> str:
if base_tag not in seen_tags:
return base_tag
suffix = 2
while f"{base_tag}-{suffix}" in seen_tags:
suffix += 1
return f"{base_tag}-{suffix}"
def _subscription_tag(line: str, tag_prefix: str, index: int, seen_tags: set[str]) -> str:
return _unique_tag(make_tag(tag_prefix, _remark_from_line(line), index), seen_tags)
def parse_subscription( def parse_subscription(
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box" lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
) -> list[dict]: ) -> list[dict]:
@@ -261,15 +278,7 @@ def parse_subscription(
if scheme not in PARSERS: if scheme not in PARSERS:
continue continue
remark = line.split("#", 1)[1] if "#" in line else "" tag = _subscription_tag(line, tag_prefix, index, seen_tags)
base_tag = make_tag(tag_prefix, remark, index)
tag = base_tag
if tag in seen_tags:
suffix = 2
while f"{base_tag}-{suffix}" in seen_tags:
suffix += 1
tag = f"{base_tag}-{suffix}"
try: try:
outbound = build_outbound(line, tag, routing_mark, backend) outbound = build_outbound(line, tag, routing_mark, backend)
@@ -294,15 +303,7 @@ def parse_hybrid_subscription(
if scheme not in PARSERS: if scheme not in PARSERS:
continue continue
remark = line.split("#", 1)[1] if "#" in line else "" tag = _subscription_tag(line, tag_prefix, index, seen_tags)
base_tag = make_tag(tag_prefix, remark, index)
tag = base_tag
if tag in seen_tags:
suffix = 2
while f"{base_tag}-{suffix}" in seen_tags:
suffix += 1
tag = f"{base_tag}-{suffix}"
try: try:
outbound = build_outbound(line, tag, routing_mark, "sing-box") outbound = build_outbound(line, tag, routing_mark, "sing-box")
+4
View File
@@ -416,3 +416,7 @@ PARSERS = {
"http": parse_http_proxy, "http": parse_http_proxy,
"https": parse_http_proxy, "https": parse_http_proxy,
} }
BACKEND_AWARE_PARSERS = {
"vless",
}
+14
View File
@@ -4,6 +4,7 @@ import base64
import json import json
import unittest import unittest
import proxy_parsing
from proxy_parsing import build_outbound from proxy_parsing import build_outbound
@@ -245,6 +246,19 @@ class BuildOutboundTests(unittest.TestCase):
with self.assertRaisesRegex(ValueError, "unsupported scheme"): with self.assertRaisesRegex(ValueError, "unsupported scheme"):
run_parser("wireguard://example.com") run_parser("wireguard://example.com")
def test_backend_aware_parser_type_error_is_not_arity_fallback(self):
def broken_parser(url: str, tag: str, backend: str):
raise TypeError("real parser bug")
proxy_parsing.PARSERS["broken"] = broken_parser
proxy_parsing.BACKEND_AWARE_PARSERS.add("broken")
try:
with self.assertRaisesRegex(TypeError, "real parser bug"):
build_outbound("broken://example.com:443", "test-outbound")
finally:
del proxy_parsing.PARSERS["broken"]
proxy_parsing.BACKEND_AWARE_PARSERS.remove("broken")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+10
View File
@@ -132,6 +132,16 @@ class FetchSubscriptionTests(unittest.TestCase):
"udp://1.1.1.1", "udp://1.1.1.1",
) )
def test_hybrid_subscription_deduplicates_tags_across_backend_lists(self):
payload = _make_b64_payload(
VLESS_URI + "#Same",
VLESS_XHTTP_URI + "#Same",
VLESS_ECH_URI + "#Same",
)
obs = run_fetcher(payload, tag_prefix="sub", backend="hybrid")
tags = [ob["tag"] for ob in obs["singBox"] + obs["xray"]]
self.assertEqual(tags, ["sub-Same", "sub-Same-2", "sub-Same-3"])
def test_hybrid_subscription_all_invalid_returns_empty_backend_lists(self): def test_hybrid_subscription_all_invalid_returns_empty_backend_lists(self):
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all") payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
obs = run_fetcher(payload, backend="hybrid") obs = run_fetcher(payload, backend="hybrid")