fix: tun not working on xray backend

This commit is contained in:
FUFSoB committed 2026-06-08 00:00:08 +05:00
1 parent 39ce4d6be2
commit f060c4cd5e
7 files changed
+523 -45

No files matched your search

+10 -2
View File
@@ -165,7 +165,11 @@ let
xrayFinalRule =
tag:
{ type = "field"; network = "tcp,udp"; }
{
type = "field";
network = "tcp,udp";
ruleTag = "final-default";
}
// (
if tag == "proxy" && proxyCfg.selection == "urltest" then
{ balancerTag = "proxy"; }
@@ -197,6 +201,7 @@ let
tunMtu ? globalTun.mtu,
useOutboundRoutingMark ? false,
enableUrlTest ? proxyCfg.selection == "urltest",
domainStrategy ? "IPIfNonMatch",
}:
{
log.loglevel = "warning";
@@ -251,7 +256,7 @@ let
}
];
routing = {
domainStrategy = "IPIfNonMatch";
domainStrategy = domainStrategy;
domainMatcher = "hybrid";
rules = xrayRouteRules;
}
@@ -315,6 +320,8 @@ let
tunInterface = globalTun.interface;
tunAddress = globalTun.address;
tunMtu = globalTun.mtu;
useOutboundRoutingMark = true;
domainStrategy = "AsIs";
};
xrayPerAppTunTemplate = mkXrayConfig {
@@ -323,6 +330,7 @@ let
tunAddress = perAppTun.address;
tunMtu = perAppTun.mtu;
useOutboundRoutingMark = globalTproxy.enable;
domainStrategy = "AsIs";
};
tproxyTemplate = if xrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
+37 -30
View File
@@ -262,40 +262,47 @@ let
{ outboundTag = tag; };
mkXrayRule =
fields: tag:
({ type = "field"; } // fields // (xrayTarget tag));
ruleTag: fields: tag:
({
type = "field";
inherit ruleTag;
}
// fields
// (xrayTarget tag));
xrayDomainRules =
tag: domains:
lib.optional (domains != [ ]) (mkXrayRule {
ruleTag: tag: domains:
lib.optional (domains != [ ]) (mkXrayRule ruleTag {
domain = map (domain: "domain:${domain}") domains;
} tag);
xrayIPRules =
tag: ips:
lib.optional (ips != [ ]) (mkXrayRule {
ruleTag: tag: ips:
lib.optional (ips != [ ]) (mkXrayRule ruleTag {
ip = ips;
} tag);
xrayGeositeRules =
tag: geosites:
lib.optional (geosites != [ ]) (mkXrayRule {
ruleTag: tag: geosites:
lib.optional (geosites != [ ]) (mkXrayRule ruleTag {
domain = map (name: "geosite:${name}") geosites;
} tag);
xrayGeoIPRules =
tag: geoips:
lib.optional (geoips != [ ]) (mkXrayRule {
ruleTag: tag: geoips:
lib.optional (geoips != [ ]) (mkXrayRule ruleTag {
ip = map (name: "geoip:${name}") geoips;
} tag);
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
mkXrayCustomRuleEntries =
rule:
lib.flatten [
(xrayDomainRules rule.outbound rule.domains)
(xrayIPRules rule.outbound rule.ips)
(xrayGeositeRules rule.outbound rule.geosites)
(xrayGeoIPRules rule.outbound rule.geoips)
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound rule.domains)
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound rule.geosites)
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound rule.geoips)
];
xrayCustomRouteRules = map (
@@ -306,33 +313,33 @@ let
) customRules;
xrayProxyPrimaryRules = lib.flatten [
(xrayDomainRules "proxy" r.proxy.domains)
(xrayIPRules "proxy" r.proxy.ips)
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
];
xrayDirectRules = lib.flatten [
(xrayDomainRules "direct" direct.domains)
(xrayIPRules "direct" direct.ips)
(xrayGeositeRules "direct" direct.geosites)
(xrayGeoIPRules "direct" direct.geoips)
(xrayDomainRules "direct-domain" "direct" direct.domains)
(xrayIPRules "direct-ip" "direct" direct.ips)
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
];
xraySafetyDirectRules = [
(mkXrayRule { ip = [ "geoip:private" ]; } "direct")
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
] ++ lib.optional (
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { }
) (mkXrayRule { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct");
) (mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct");
xrayBlockRules = lib.flatten [
(xrayDomainRules "block" r.block.domains)
(xrayIPRules "block" r.block.ips)
(xrayGeositeRules "block" r.block.geosites)
(xrayGeoIPRules "block" r.block.geoips)
(xrayDomainRules "block-domain" "block" r.block.domains)
(xrayIPRules "block-ip" "block" r.block.ips)
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
];
xrayProxyGeoRules = lib.flatten [
(xrayGeositeRules "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy" r.proxy.geoips)
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
];
xrayRoutingRules =
@@ -340,8 +347,8 @@ let
++ xrayProxyPrimaryRules
++ xrayDirectRules
++ xraySafetyDirectRules
++ xrayBlockRules
++ xrayProxyGeoRules;
++ xrayProxyGeoRules
++ xrayBlockRules;
xrayRouteModeRules = {
common = [ ];
+48
View File
@@ -94,10 +94,42 @@ let
# 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;
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg globalTun.address}
tun_addr=""
tun_route_prefix=""
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"
}
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
break
@@ -110,8 +142,22 @@ let
exit 1
fi
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
${lib.optionalString perAppRoutingTproxy.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
''}
${lib.optionalString perAppRoutingTun.enable ''
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
''}
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
'';
@@ -148,6 +194,8 @@ let
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
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
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
@@ -113,9 +113,43 @@ let
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
set -euo pipefail
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
tun_addr=""
tun_route_prefix=""
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"
}
${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 flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${nft} -f ${perAppTunChainFile}
${perAppTunWaitForInterface}
tun_addr="''${tun_cidr%%/*}"
tun_route_prefix="$(cidr_network "$tun_cidr")"
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
${ip} route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
${ip} route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
${ip} rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
'';
@@ -126,7 +160,7 @@ let
# Best-effort cleanup for graceful stops and for unclean previous exits.
${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 flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true
'';
+87 -12
View File
@@ -46,6 +46,7 @@ let
null;
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
routeModeStateFile = "/run/proxy-suite/route-mode";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
@@ -187,6 +188,9 @@ let
xrayUrltestTagFilter = ''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
'';
mkOutboundScript =
@@ -272,6 +276,18 @@ let
"proxy-suite-per-app-tun"
];
routeModeBlacklistTail =
if xrayEnabled then
''
+ .proxyGeo
+ .block
''
else
''
+ .block
+ .proxyGeo
'';
routeModeCaseBlock = ''
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
@@ -287,8 +303,7 @@ let
+ .proxyPrimary
+ .direct
+ .safetyDirect
+ .block
+ .proxyGeo
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
whitelist)
@@ -301,8 +316,7 @@ let
+ .proxyPrimary
+ .direct
+ .safetyDirect
+ .block
+ .proxyGeo
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-proxy)
@@ -315,8 +329,7 @@ let
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
+ .proxyPrimary
+ .safetyDirect
+ .block
+ .proxyGeo
${routeModeBlacklistTail}
' "${routeModeRulesFile}")
;;
all-bypass)
@@ -340,20 +353,52 @@ let
mkBackendJqFilter =
if xrayEnabled then
''
def xray_final_rule($tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",balancerTag:"proxy"}
def xray_bind_outbound($interface):
if $interface == "" or .protocol == "blackhole" then
.
else
{type:"field",network:"tcp,udp",outboundTag:$tag}
.streamSettings = (.streamSettings // {})
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
| if (.streamSettings.sockopt.interface? // "") == "" then
.streamSettings.sockopt.interface = $interface
else
.
end
end;
.outbounds = $obs + .outbounds
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.users) = [{user:$user,pass:$password}]
else . end
| if $route_enabled then
.routing.rules = ($route_rules + [xray_final_rule($route_final)])
.routing.rules = ($route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
else
''
@@ -376,11 +421,15 @@ let
configFile,
routingMark ? null,
enableLocalProxyAuth ? false,
xrayTunEgressBinding ? false,
}:
pkgs.writeShellScript name ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
XRAY_LOGLEVEL=""
XRAY_TUN_BIND_INTERFACE=""
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
ROUTE_MODE=""
@@ -395,6 +444,27 @@ let
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
${writeProxychainsConfigBlock}
''}
${lib.optionalString xrayEnabled ''
if [ -r "${xrayLoglevelFile}" ]; then
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
fi
''}
${lib.optionalString xrayTunEgressBinding ''
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk '
/dev/ {
for (i = 1; i <= NF; i++) {
if ($i == "dev" && i + 1 <= NF) {
print $(i + 1)
exit
}
}
}
')"
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
exit 1
fi
''}
${routeModeCaseBlock}
@@ -410,6 +480,9 @@ let
--arg route_final "$ROUTE_FINAL" \
--arg dns_final "$DNS_FINAL" \
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
'${mkBackendJqFilter}' \
"${configFile}" > "$RUNTIME_DIR/config.json"
${lib.optionalString enableLocalProxyAuth ''
@@ -432,6 +505,7 @@ let
runtimeDir = "/run/proxy-suite-tun";
configFile = tunFile;
routingMark = if xrayEnabled then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
};
startPerAppTun = mkStartScript {
@@ -439,6 +513,7 @@ let
runtimeDir = "/run/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunEgressBinding = xrayEnabled;
};
mkSubscriptionFetchBlock =
+53
View File
@@ -242,6 +242,7 @@ let
block.domains = [ "block.example" ];
};
tproxy.enable = true;
tproxy.perApp.enable = true;
tun = {
enable = true;
perApp.enable = true;
@@ -260,6 +261,21 @@ let
xrayStartScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart
);
xrayTunStartScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStart
);
xrayTunUpScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-tun".serviceConfig.ExecStartPost
);
xrayPerAppTunStartScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStart
);
xrayPerAppTunUpScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStartPost
);
xrayPerAppTunCleanupScript = builtins.readFile (
xrayFixture.config.systemd.services."proxy-suite-per-app-tun".serviceConfig.ExecStopPost
);
xraySubscriptionFixture = evalProxySuite [
{
system.stateVersion = "26.05";
@@ -1682,6 +1698,7 @@ let
assert tproxyInbound.settings.followRedirect == true;
assert tproxyInbound.streamSettings.sockopt.tproxy == "tproxy";
assert specificRule.outboundTag == "proxy-suite-ob-primary";
assert specificRule.ruleTag == "custom-proxy-domain";
assert balancer.tag == "proxy";
assert balancer.selector == [ "proxy-suite-ob-" ];
assert balancer.strategy.type == "leastPing";
@@ -1697,13 +1714,47 @@ let
perAppTunInbound = builtins.head (
builtins.filter (inbound: inbound.tag == "tun-in") xrayPerAppTunConfig.inbounds
);
tunDirectOutbound = builtins.head (
builtins.filter (outbound: outbound.tag == "direct") xrayTunConfig.outbounds
);
tunHasFinalRuleTag = builtins.any (rule: (rule ? ruleTag) && rule.ruleTag == "final-default") xrayTunConfig.routing.rules;
tunHasDirectGeositeRule = builtins.any (rule: (rule ? ruleTag) && rule.ruleTag == "direct-geosite") xrayTunConfig.routing.rules;
in
assert tunInbound.protocol == "tun";
assert tunInbound.settings.name == "singtun0";
assert tunInbound.settings.gateway == [ "172.19.0.1/30" ];
assert tunInbound.settings.autoOutboundsInterface == "auto";
assert !(tunInbound.sniffing ? routeOnly);
assert xrayTunConfig.routing.domainStrategy == "AsIs";
assert tunHasFinalRuleTag;
assert tunHasDirectGeositeRule;
assert tunDirectOutbound.streamSettings.sockopt.mark == 2;
assert pkgs.lib.hasInfix "xray-loglevel" xrayTunStartScript;
assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayTunStartScript;
assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayTunStartScript;
assert pkgs.lib.hasInfix ".streamSettings.sockopt.interface = $interface" xrayTunStartScript;
assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayTunStartScript;
assert pkgs.lib.hasInfix "del(.observatory)" xrayTunStartScript;
assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayTunStartScript;
assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayTunUpScript;
assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript;
assert pkgs.lib.hasInfix ''route replace "$tun_route_prefix" dev singtun0 src "$tun_addr" 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 perAppTunInbound.settings.name == "psperapptun0";
assert perAppTunInbound.settings.gateway == [ "172.20.0.1/30" ];
assert !(perAppTunInbound.sniffing ? routeOnly);
assert xrayPerAppTunConfig.routing.domainStrategy == "AsIs";
assert pkgs.lib.hasInfix "XRAY_SINGLE_PROXY_TAG=" xrayPerAppTunStartScript;
assert pkgs.lib.hasInfix "ip -4 route get 1.1.1.1" xrayPerAppTunStartScript;
assert pkgs.lib.hasInfix ".streamSettings.sockopt.interface = $interface" xrayPerAppTunStartScript;
assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayPerAppTunStartScript;
assert pkgs.lib.hasInfix "del(.observatory)" xrayPerAppTunStartScript;
assert pkgs.lib.hasInfix ''tun_route_prefix="$(cidr_network "$tun_cidr")"'' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''route replace "$tun_route_prefix" dev psperapptun0 src "$tun_addr" table 101'' xrayPerAppTunUpScript;
assert pkgs.lib.hasInfix ''route flush table 101'' xrayPerAppTunCleanupScript;
true
)
(
@@ -1789,6 +1840,8 @@ let
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 ''rule del pref 8996'' tunCleanupScript;
assert pkgs.lib.hasInfix ''rule del pref 8997'' tunCleanupScript;
assert pkgs.lib.hasInfix ''route flush table 2022'' tunCleanupScript;
assert pkgs.lib.hasInfix "link del dev" tunCleanupScript;
assert pkgs.lib.hasInfix "singtun0" tunCleanupScript;
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env bash
set -euo pipefail
PROXY_CTL="${PROXY_CTL:-proxy-ctl}"
SYSTEMCTL="${SYSTEMCTL:-systemctl}"
JOURNALCTL="${JOURNALCTL:-journalctl}"
IP_BIN="${IP_BIN:-ip}"
NFT_BIN="${NFT_BIN:-nft}"
CURL_BIN="${CURL_BIN:-curl}"
TARGET_URL="${TARGET_URL:-https://whatismyipaddress.com/}"
PER_APP_TUN_PROFILE="${PER_APP_TUN_PROFILE:-tun}"
PER_APP_TPROXY_PROFILE="${PER_APP_TPROXY_PROFILE:-tproxy}"
XRAY_LOGLEVEL_FILE="${XRAY_LOGLEVEL_FILE:-/run/proxy-suite/xray-loglevel}"
ROUTE_MODE_FILE="${ROUTE_MODE_FILE:-/run/proxy-suite/route-mode}"
usage() {
cat <<'EOF'
Usage: check-xray-tun.sh [output-dir]
Runs four native XRay regression probes:
- global TUN
- per-app TUN
- global TProxy
- per-app TProxy
The script toggles proxy-suite modes while it runs and writes captures under the
chosen output directory.
EOF
}
require_cmd() {
command -v "$1" >/dev/null 2>&1 || {
echo "missing required command: $1" >&2
exit 1
}
}
capture_cmd() {
local output="$1"
local status=0
shift
if "$@" >"$output" 2>&1; then
return 0
else
status=$?
fi
{
echo
echo "[exit=$status] $*"
} >>"$output"
}
capture_path() {
local source="$1"
local target="$2"
if [ -e "$source" ]; then
cp -a "$source" "$target"
else
printf 'missing: %s\n' "$source" >"$target"
fi
}
service_active() {
"$SYSTEMCTL" is-active --quiet "$1"
}
set_global_mode() {
local mode="$1"
case "$mode" in
tun)
"$PROXY_CTL" proxy on
"$PROXY_CTL" tproxy off || true
"$PROXY_CTL" tun on
;;
tproxy)
"$PROXY_CTL" proxy on
"$PROXY_CTL" tun off || true
"$PROXY_CTL" tproxy on
;;
off)
"$PROXY_CTL" tun off || true
"$PROXY_CTL" tproxy off || true
;;
*)
echo "unsupported global mode: $mode" >&2
exit 1
;;
esac
}
capture_state() {
local probe_dir="$1"
local since="$2"
local config_path="$3"
shift 3
local services=("$@")
capture_path "$config_path" "$probe_dir/config.json"
capture_path "$ROUTE_MODE_FILE" "$probe_dir/route-mode.txt"
capture_path "$XRAY_LOGLEVEL_FILE" "$probe_dir/xray-loglevel.txt"
capture_cmd "$probe_dir/ip-rule.txt" "$IP_BIN" rule show
capture_cmd "$probe_dir/ip-route-all.txt" "$IP_BIN" -4 route show table all
capture_cmd "$probe_dir/ip-addr.txt" "$IP_BIN" -4 addr show
capture_cmd "$probe_dir/nft-ruleset.txt" "$NFT_BIN" list ruleset
for svc in "${services[@]}"; do
capture_cmd "$probe_dir/journal-${svc}.log" "$JOURNALCTL" -u "$svc" --since "$since" --no-pager
done
}
run_global_probe() {
local mode="$1"
local probe_dir="$OUTPUT_DIR/$mode"
local config_path="$2"
shift 2
local services=("$@")
local since=""
local curl_status=0
mkdir -p "$probe_dir"
set_global_mode "${mode#global-}"
sleep 2
since="$(date --iso-8601=seconds)"
if "$CURL_BIN" -4 -L -sS --max-time 20 -D "$probe_dir/headers.txt" -o "$probe_dir/body.html" "$TARGET_URL" >"$probe_dir/stdout.txt" 2>"$probe_dir/stderr.txt"; then
:
else
curl_status=$?
fi
printf '%s\n' "$curl_status" >"$probe_dir/curl-exit-code.txt"
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
set_global_mode off
}
make_wrapped_probe_script() {
local probe_dir="$1"
local script_path="$probe_dir/run-probe.sh"
cat >"$script_path" <<EOF
#!/usr/bin/env bash
set -euo pipefail
status=0
if ${CURL_BIN@Q} -4 -L -sS --max-time 20 -D ${probe_dir@Q}/headers.txt -o ${probe_dir@Q}/body.html ${TARGET_URL@Q} >${probe_dir@Q}/stdout.txt 2>${probe_dir@Q}/stderr.txt; then
:
else
status=\$?
fi
printf '%s\n' "\$status" >${probe_dir@Q}/curl-exit-code.txt
sleep 5
exit "\$status"
EOF
chmod 755 "$script_path"
printf '%s\n' "$script_path"
}
run_per_app_probe() {
local mode="$1"
local profile="$2"
local config_path="$3"
shift 3
local services=("$@")
local probe_dir="$OUTPUT_DIR/$mode"
local probe_script=""
local wrapped_pid=""
local wrapped_status=0
local since=""
mkdir -p "$probe_dir"
set_global_mode off
"$PROXY_CTL" proxy on
probe_script="$(make_wrapped_probe_script "$probe_dir")"
since="$(date --iso-8601=seconds)"
"$PROXY_CTL" wrap "$profile" -- "$probe_script" &
wrapped_pid=$!
sleep 2
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
if wait "$wrapped_pid"; then
:
else
wrapped_status=$?
fi
printf '%s\n' "$wrapped_status" >"$probe_dir/wrap-exit-code.txt"
}
restore_state() {
if [ -n "${ORIG_XRAY_LOGLEVEL+x}" ]; then
if [ -n "$ORIG_XRAY_LOGLEVEL" ]; then
printf '%s\n' "$ORIG_XRAY_LOGLEVEL" >"$XRAY_LOGLEVEL_FILE"
else
rm -f "$XRAY_LOGLEVEL_FILE"
fi
fi
if [ "$ORIG_TUN_ACTIVE" = 1 ]; then
set_global_mode tun || true
elif [ "$ORIG_TPROXY_ACTIVE" = 1 ]; then
set_global_mode tproxy || true
else
set_global_mode off || true
if [ "$ORIG_PROXY_ACTIVE" = 0 ]; then
"$PROXY_CTL" proxy off || true
fi
fi
}
if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
usage
exit 0
fi
require_cmd "$PROXY_CTL"
require_cmd "$SYSTEMCTL"
require_cmd "$JOURNALCTL"
require_cmd "$IP_BIN"
require_cmd "$NFT_BIN"
require_cmd "$CURL_BIN"
OUTPUT_DIR="${1:-/tmp/proxy-suite-xray-tun-$(date +%Y%m%d-%H%M%S)}"
mkdir -p "$OUTPUT_DIR"
ORIG_PROXY_ACTIVE=0
ORIG_TUN_ACTIVE=0
ORIG_TPROXY_ACTIVE=0
ORIG_XRAY_LOGLEVEL=""
if service_active proxy-suite-socks; then
ORIG_PROXY_ACTIVE=1
fi
if service_active proxy-suite-tun; then
ORIG_TUN_ACTIVE=1
fi
if service_active proxy-suite-tproxy; then
ORIG_TPROXY_ACTIVE=1
fi
if [ -r "$XRAY_LOGLEVEL_FILE" ]; then
ORIG_XRAY_LOGLEVEL="$(tr -d '\r\n' < "$XRAY_LOGLEVEL_FILE")"
fi
trap restore_state EXIT
printf 'info\n' >"$XRAY_LOGLEVEL_FILE"
run_global_probe global-tun /run/proxy-suite-tun/config.json proxy-suite-tun
run_per_app_probe per-app-tun "$PER_APP_TUN_PROFILE" /run/proxy-suite-per-app-tun/config.json proxy-suite-per-app-tun
run_global_probe global-tproxy /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-tproxy
run_per_app_probe per-app-tproxy "$PER_APP_TPROXY_PROFILE" /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-per-app-tproxy
printf '%s\n' "$OUTPUT_DIR"