diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 7511c20..267cb96 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -9,6 +9,7 @@ let derived = import ./derived.nix { inherit lib cfg; }; + constants = derived.constants; inherit (derived) proxyCfg singBoxCfg @@ -19,10 +20,15 @@ let globalTproxy clashApiEnabled ; + inherit (constants) + xrayGlobalTunIPv6Address + xrayPerAppTunIPv6Address + xrayDnsBridgePorts + ; perAppTun = derived.perAppRoutingTun; direct = rules.direct; - xrayGlobalTunIPv6Address = "fd66:19::1/64"; - xrayPerAppTunIPv6Address = "fd66:20::1/64"; + defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex; + defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority; xrayFakeDnsPools = [ { ipPool = "198.18.0.0/15"; @@ -92,15 +98,15 @@ let tunAddress ? globalTun.address, tunMtu ? globalTun.mtu, tunAutoRoute ? true, - tunAutoRouteTableIndex ? 2022, - tunAutoRouteRuleIndex ? 9000, + tunAutoRouteTableIndex ? defaultTunAutoRouteTableIndex, + tunAutoRouteRuleIndex ? defaultTunAutoRouteRulePriority, tunAutoRedirect ? true, tunStrictRoute ? true, forceLocalDnsViaProxy ? false, useOutboundRoutingMark ? false, enableClashApi ? clashApiEnabled, enableXrayDnsBridge ? hybridEnabled, - xrayDnsBridgePort ? 18533, + xrayDnsBridgePort ? xrayDnsBridgePorts.socks, }: { log.level = "warn"; @@ -405,7 +411,7 @@ let enableMixed = true; enableTProxy = true; useOutboundRoutingMark = true; - xrayDnsBridgePort = 18533; + xrayDnsBridgePort = xrayDnsBridgePorts.socks; }; singBoxTunTemplate = mkSingBoxConfig { @@ -418,7 +424,7 @@ let tunStrictRoute = true; forceLocalDnsViaProxy = false; enableClashApi = false; - xrayDnsBridgePort = 18534; + xrayDnsBridgePort = xrayDnsBridgePorts.tun; }; singBoxPerAppTunTemplate = mkSingBoxConfig { @@ -432,7 +438,7 @@ let forceLocalDnsViaProxy = false; useOutboundRoutingMark = globalTproxy.enable; enableClashApi = false; - xrayDnsBridgePort = 18535; + xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; }; xrayTproxyTemplate = mkXrayConfig { diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index de53482..19daeb6 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -52,6 +52,29 @@ let clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first"; perAppZapretEnabled = perAppZapretCfg.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 ( map (rule: rule.outbound) ( @@ -82,6 +105,7 @@ in perAppZapretEnabled userControlCfg userControlEnabled + constants selectionMode builtinTags outboundTags diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 452b3e4..d34e6bd 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -15,6 +15,7 @@ }: let + constants = derived.constants; assertions = import ./service/assertions-lib.nix { inherit lib; }; inherit (assertions) mkAssertion @@ -42,7 +43,7 @@ let perAppZapretCfg ; - globalTunAutoRouteTable = 2022; + globalTunAutoRouteTable = constants.tunAutoRouteTableIndex; featureAssertions = [ (requireAvailable proxyCfg.singBox.enable proxyEnabled @@ -160,7 +161,7 @@ let condition = globalTun.enable && perAppRoutingTun.enable; left = perAppRoutingTun.routeTable; 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; diff --git a/modules/proxy-suite/service/builders.nix b/modules/proxy-suite/service/builders.nix index 5597aeb..7dbe837 100644 --- a/modules/proxy-suite/service/builders.nix +++ b/modules/proxy-suite/service/builders.nix @@ -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 = { description, diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index e874f8a..8cdc089 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -17,6 +17,7 @@ let derived = import ../derived.nix { inherit lib cfg; }; + constants = derived.constants; inherit (derived) singBoxCfg proxyCfg @@ -82,6 +83,7 @@ let selectionMode collapseNamedOutbounds hasSubscriptions + constants ; inherit jq @@ -111,6 +113,7 @@ let perAppRoutingCfg perAppRoutingTun perAppRoutingTproxy + constants ; perAppZapretCfg = perAppZapretCfg; inherit perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index b316425..74c4306 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -45,6 +45,12 @@ let 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) derived polkit @@ -76,6 +82,15 @@ let invalidRoutingTargets builtinTags ; + constants = derived.constants; + inherit (constants) + tunAutoRouteTableIndex + tunAutoRouteRulePriority + xrayTunPerAppTproxyRulePriority + xrayTunPerAppTunRulePriority + xrayGlobalTunIPv6Address + xrayGlobalTunIPv6RoutePrefix + ; serviceNames = { socks = "proxy-suite-socks"; @@ -91,19 +106,6 @@ let proxyCfg.auth.username != 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" '' set -euo pipefail @@ -114,28 +116,7 @@ let tun_route_prefix="" uplink_addr="" - 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" - } + ${builders.cidrNetworkFunction} for _ in $(${pkgs.coreutils}/bin/seq 1 50); do if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then @@ -149,20 +130,7 @@ let exit 1 fi - uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk ' - /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 + ${defaultUplinkIPv4Source} while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done @@ -196,9 +164,13 @@ let # Start from a clean policy-routing state. `ip rule add` permits duplicate # rules on some iproute2 versions, and a stale rule can keep packets routed # into a dead local table after a failed restart. - ${nft} delete table ip singbox 2>/dev/null || true - while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done - ${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = globalTproxy.fwmark; + table = globalTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} ${nft} -f ${nftablesRulesFile} ${ip} route replace local default dev lo table ${toString globalTproxy.routeTable} @@ -208,9 +180,13 @@ let tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" '' set +e - ${nft} delete table ip singbox 2>/dev/null || true - while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done - ${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "singbox"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = globalTproxy.fwmark; + table = globalTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = globalTproxy.routeTable; }} ''; tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" '' @@ -219,18 +195,28 @@ let # SingBox normally removes these on graceful shutdown, but stale # auto_route/auto_redirect state leaves the host routing through a dead TUN # interface after `proxy-ctl tun off` or an unclean service stop. - ${nft} delete table inet sing-box 2>/dev/null || true - - while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done - while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done - 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} -6 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 - - ${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true - ${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }} + ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-4"; + priority = xrayTunPerAppTproxyRulePriority; + }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-4"; + priority = xrayTunPerAppTunRulePriority; + }} + ${builders.mkIpRuleDeleteByPriority { + inherit ip; + family = "-6"; + priority = xrayTunPerAppTunRulePriority; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }} + ${builders.mkIpLinkDelete { inherit ip; interface = globalTun.interface; }} + ${builders.flushResolvedCaches} ''; systemServiceEntries = [ diff --git a/modules/proxy-suite/service/per-app-routing.nix b/modules/proxy-suite/service/per-app-routing.nix index 58d3dcc..fd7d861 100644 --- a/modules/proxy-suite/service/per-app-routing.nix +++ b/modules/proxy-suite/service/per-app-routing.nix @@ -9,6 +9,7 @@ perAppRoutingCfg, perAppRoutingTun, perAppRoutingTproxy, + constants, perAppZapretCfg, perAppTunChainFile, perAppTproxyRulesFile, @@ -26,6 +27,10 @@ let builders = import ./builders.nix { inherit lib pkgs; }; inherit (builders) mkAnchorService; + defaultUplinkIPv4Source = builders.mkDefaultUplinkIPv4Source { + inherit ip awk; + errorMessage = "proxy-suite: could not determine the default uplink IPv4 address for app TUN"; + }; perAppTunSliceName = "proxy-suite-per-app-tun.slice"; perAppTproxySliceName = "proxy-suite-per-app-tproxy.slice"; @@ -99,8 +104,10 @@ let hasZapretProfiles = builtins.any ( profile: profile.route == "zapret" ) effectivePerAppRoutingProfiles; - xrayPerAppTunIPv6Address = "fd66:20::1/64"; - xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64"; + inherit (constants) + xrayPerAppTunIPv6Address + xrayPerAppTunIPv6RoutePrefix + ; perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" '' set -euo pipefail @@ -124,50 +131,26 @@ let tun_route_prefix="" uplink_addr="" - cidr_network() { - local cidr="$1" - local addr="''${cidr%/*}" - local prefix="''${cidr#*/}" - local o1 o2 o3 o4 ip mask net + ${builders.cidrNetworkFunction} - 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} -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 + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-4"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-6"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} ${nft} -f ${perAppTunChainFile} ${perAppTunWaitForInterface} - 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 "proxy-suite: could not determine the default uplink IPv4 address for app TUN" >&2 - exit 1 - fi + ${defaultUplinkIPv4Source} tun_addr="''${tun_cidr%%/*}" tun_route_prefix="$(cidr_network "$tun_cidr")" ${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface} @@ -186,21 +169,35 @@ let set +e # Best-effort cleanup for graceful stops and for unclean previous exits. - ${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true - 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 - ${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true - ${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "proxy_suite_per_app_tun"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-4"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + family = "-6"; + fwmark = perAppRoutingTun.fwmark; + table = perAppRoutingTun.routeTable; + }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-4"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpRouteFlushTable { inherit ip; family = "-6"; table = perAppRoutingTun.routeTable; }} + ${builders.mkIpLinkDelete { inherit ip; interface = perAppRoutingTun.interface; }} + ${builders.flushResolvedCaches} ''; perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" '' set -euo pipefail - ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true - while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done - ${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = perAppRoutingTproxy.fwmark; + table = perAppRoutingTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} ${nft} -f ${perAppTproxyRulesFile} ${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable} @@ -210,9 +207,13 @@ let perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" '' set +e - ${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true - while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done - ${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true + ${builders.mkNftDeleteTable { inherit nft; family = "ip"; table = "proxy_suite_per_app_tproxy"; }} + ${builders.mkIpRuleDeleteByFwmark { + inherit ip; + fwmark = perAppRoutingTproxy.fwmark; + table = perAppRoutingTproxy.routeTable; + }} + ${builders.mkIpLocalDefaultRouteDelete { inherit ip; table = perAppRoutingTproxy.routeTable; }} ''; # Generate a "start" script that adds a per-user cgroup nftables mark rule. diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 9cc5031..2f8db35 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -16,6 +16,7 @@ selectionMode, collapseNamedOutbounds, hasSubscriptions, + constants, jq, python3, singBox, @@ -34,11 +35,7 @@ let systemctl = "${pkgs.systemd}/bin/systemctl"; backend = if activeBackend == null then "sing-box" else activeBackend; mainBackend = if pureXrayEnabled then "xray" else "sing-box"; - subscriptionBackend = - if hybridEnabled then - "hybrid" - else - mainBackend; + subscriptionBackend = if hybridEnabled then "hybrid" else mainBackend; backendArg = "--backend ${mainBackend}"; subscriptionBackendArg = "--backend ${subscriptionBackend}"; backendBin = if pureXrayEnabled then xray else singBox; @@ -58,6 +55,10 @@ let xrayLoglevelFile = "/run/proxy-suite/xray-loglevel"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; xraySidecarRoutingMark = globalTproxy.proxyMark; + inherit (constants) + xrayDnsBridgePorts + xraySidecarBasePorts + ; mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; @@ -695,8 +696,8 @@ let enableLocalProxyAuth ? false, xrayTunEgressBinding ? false, xrayTunDnsRuntime ? false, - xraySidecarBasePort ? 33080, - xrayDnsBridgePort ? 18533, + xraySidecarBasePort ? xraySidecarBasePorts.socks, + xrayDnsBridgePort ? xrayDnsBridgePorts.socks, }: pkgs.writeShellScript name '' set -euo pipefail @@ -815,8 +816,8 @@ let configFile = tproxyFile; routingMark = globalTproxy.proxyMark; enableLocalProxyAuth = localProxyAuthEnabled; - xraySidecarBasePort = 33080; - xrayDnsBridgePort = 18533; + xraySidecarBasePort = xraySidecarBasePorts.socks; + xrayDnsBridgePort = xrayDnsBridgePorts.socks; }; startTun = mkStartScript { @@ -826,8 +827,8 @@ let routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null; xrayTunEgressBinding = xrayEnabled; xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = 33180; - xrayDnsBridgePort = 18534; + xraySidecarBasePort = xraySidecarBasePorts.tun; + xrayDnsBridgePort = xrayDnsBridgePorts.tun; }; startPerAppTun = mkStartScript { @@ -837,8 +838,8 @@ let routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null; xrayTunEgressBinding = xrayEnabled; xrayTunDnsRuntime = pureXrayEnabled; - xraySidecarBasePort = 33280; - xrayDnsBridgePort = 18535; + xraySidecarBasePort = xraySidecarBasePorts.perAppTun; + xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; }; mkSubscriptionFetchBlock = diff --git a/nix/checks.nix b/nix/checks.nix index 7af4a99..d4fa042 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -216,6 +216,10 @@ let }; minimal = evalProxySuite [ baseModule ]; + checkConstants = (import ../modules/proxy-suite/derived.nix { + lib = pkgs.lib; + cfg = minimal.config.services.proxy-suite; + }).constants; _minimalProxyCtl = mkProxyCtlDerived minimal; minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; minimalProxyCtlScript = _minimalProxyCtl.script; @@ -2238,10 +2242,10 @@ let assert !(hybridTproxyConfig ? routing); assert dnsBridgeInbound.type == "direct"; assert dnsBridgeInbound.listen == "127.0.0.1"; - assert dnsBridgeInbound.listen_port == 18533; + assert dnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.socks; assert mixedInbound.type == "mixed"; assert tproxyInbound.type == "tproxy"; - assert tunDnsBridgeInbound.listen_port == 18534; + assert tunDnsBridgeInbound.listen_port == checkConstants.xrayDnsBridgePorts.tun; assert dnsBridgeRouteRule.network == [ "tcp" @@ -2250,12 +2254,18 @@ let assert pkgs.lib.hasInfix "/bin/sing-box 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_NEXT_PORT=33080" hybridStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18533" hybridStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=33180" hybridTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18534" hybridTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=33280" hybridPerAppTunStartScript; - assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=18535" hybridPerAppTunStartScript; + assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.socks}" + hybridStartScript; + assert pkgs.lib.hasInfix "XRAY_SIDECAR_DNS_PORT=${toString checkConstants.xrayDnsBridgePorts.socks}" + hybridStartScript; + assert pkgs.lib.hasInfix "XRAY_SIDECAR_NEXT_PORT=${toString checkConstants.xraySidecarBasePorts.tun}" + 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 xray" hybridStartScript; assert pkgs.lib.hasInfix "_proxy_suite_add_xray_sidecar_ob" hybridStartScript; @@ -2348,7 +2358,7 @@ let assert tunInbound.settings.gateway == [ "172.19.0.1/30" - "fd66:19::1/64" + checkConstants.xrayGlobalTunIPv6Address ]; assert builtins.length tunInbound.settings.dns == 2; assert tunInbound.settings.autoOutboundsInterface == "auto"; @@ -2401,28 +2411,39 @@ let assert pkgs.lib.hasInfix "xray_rewrite_proxy_rule" xrayBackendJqFilter; assert pkgs.lib.hasInfix ".protocol == \"dns\"" xrayBackendJqFilter; 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 ''addr replace "$tun_cidr" dev singtun0'' xrayTunUpScript; assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev singtun0'' xrayTunUpScript; 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; - 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; - 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; - 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.gateway == [ "172.20.0.1/30" - "fd66:20::1/64" + checkConstants.xrayPerAppTunIPv6Address ]; assert builtins.length perAppTunInbound.settings.dns == 2; assert perAppTunInbound.sniffing.destOverride == [ "fakedns" ]; @@ -2443,7 +2464,7 @@ let assert pkgs.lib.hasInfix "del(.routing.balancers)" xrayBackendJqFilter; assert pkgs.lib.hasInfix "del(.observatory)" xrayBackendJqFilter; 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 ''addr replace "$tun_cidr" dev psperapptun0'' xrayPerAppTunUpScript; assert pkgs.lib.hasInfix ''-6 addr replace "$tun6_cidr" dev psperapptun0'' xrayPerAppTunUpScript; @@ -2550,8 +2571,8 @@ let let inbound = builtins.head (builtins.filter (item: item.tag == "tun-in") tunDefaultConfig.inbounds); in - assert inbound.iproute2_table_index == 2022; - assert inbound.iproute2_rule_index == 9000; + assert inbound.iproute2_table_index == checkConstants.tunAutoRouteTableIndex; + assert inbound.iproute2_rule_index == checkConstants.tunAutoRouteRulePriority; assert tunDefaultConfig.route.auto_detect_interface == true; true ) @@ -2562,10 +2583,14 @@ 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 "rule del table ${toString checkConstants.tunAutoRouteTableIndex}" + tunCleanupScript; + assert pkgs.lib.hasInfix "rule del pref ${toString checkConstants.xrayTunPerAppTproxyRulePriority}" + 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 "singtun0" tunCleanupScript; true @@ -3114,7 +3139,8 @@ let assert pkgs.lib.hasInfix "systemd-run --user --scope --quiet --collect --same-dir" 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; assert pkgs.lib.hasInfix "$slice_base-user@$uid.service" 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 - ''_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; assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingTproxyScript; true @@ -3136,7 +3162,7 @@ let ( assert pkgs.lib.hasInfix "PER_APP_ROUTING_ZAPRET_ENABLED" perAppRoutingZapretScript; 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; assert pkgs.lib.hasInfix "$slice_base-\${profile}-$$" perAppRoutingZapretScript; true diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index ef2c5e7..b7d6b43 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -28,30 +28,75 @@ touch "$out" ''; - options-doc = pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } '' - diff -u ${../../docs/options.md} ${generatedOptionsDoc} - touch "$out" - ''; + options-doc = + pkgs.runCommand "proxy-suite-options-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } + '' + diff -u ${../../docs/options.md} ${generatedOptionsDoc} + touch "$out" + ''; - readme-doc = pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } '' - diff -u ${../../README.md} ${generatedReadmeDoc} - touch "$out" - ''; + readme-doc = + pkgs.runCommand "proxy-suite-readme-doc-check" { nativeBuildInputs = [ pkgs.diffutils ]; } + '' + diff -u ${../../README.md} ${generatedReadmeDoc} + 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"); + proxy-ctl-subscription-list = + pkgs.runCommand "proxy-suite-proxy-ctl-subscription-list-check" + { + nativeBuildInputs = [ + pkgs.bash + pkgs.coreutils + 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 - ( - 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"); + mkdir -p cache + printf '%s\n' '["plain","hybrid","bad"]' > tags.json + printf '%s\n' '[{},{}]' > cache/plain.json + printf '%s\n' '{"singBox":[{},{}],"xray":[{}]}' > cache/hybrid.json + printf '%s\n' '{"singBox":[{}]}' > cache/bad.json + + env \ + 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"); } diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index c632467..f849a85 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -186,10 +186,10 @@ _cleanup_slice_if_idle() { fi } -# _wrap_slice [cmd...] +# _wrap_slice [cmd...] _wrap_slice() { - local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4" - shift 4 + local slice_base="$1" profile="$2" enabled="$3" disabled_msg="$4" backend_svc="$5" + shift 5 if [ "$enabled" != "1" ]; then echo "$disabled_msg" exit 1 @@ -220,6 +220,22 @@ _wrap_slice() { 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() { if [ "${1:-}" = "--tray" ]; then _status_tray @@ -409,19 +425,19 @@ cmd_wrap() { ;; 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." \ "proxy-suite-per-app-tun.service" "$@" ;; 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." \ "proxy-suite-per-app-tproxy.service" "$@" ;; 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." \ "proxy-suite-per-app-zapret.service" "$@" ;; @@ -450,7 +466,7 @@ cmd_subscription() { cache="$CACHE_DIR/$t.json" if [ -f "$cache" ]; then 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 age="(no cache)" count="-" diff --git a/pkgs/proxy-suite-tray.nix b/pkgs/proxy-suite-tray.nix index 8412010..a1f6f8c 100644 --- a/pkgs/proxy-suite-tray.nix +++ b/pkgs/proxy-suite-tray.nix @@ -18,8 +18,6 @@ pkgs.stdenv.mkDerivation { buildPhase = '' $CC -o proxy-suite-tray main.c \ $(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} \ -O2 -Wall -Werror=discarded-qualifiers ''; diff --git a/pkgs/proxy-suite-tray/main.c b/pkgs/proxy-suite-tray/main.c index 9f3d2b2..4e9fe12 100644 --- a/pkgs/proxy-suite-tray/main.c +++ b/pkgs/proxy-suite-tray/main.c @@ -11,17 +11,14 @@ #ifndef PROXY_CTL_BIN #define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl" #endif +#define ROUTE_MODE_CHOICE_COUNT 5 static AppIndicator *indicator; static GtkWidget *menu; static GtkWidget *status_item; static GtkWidget *proxy_item; static GtkWidget *route_mode_item; -static GtkWidget *route_mode_default_item; -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 *route_mode_items[ROUTE_MODE_CHOICE_COUNT]; static GtkWidget *tproxy_item; static GtkWidget *tun_item; static GtkWidget *zapret_item; @@ -49,6 +46,21 @@ typedef enum ROUTE_MODE_ALL_BYPASS } 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 { gboolean loaded; @@ -169,17 +181,7 @@ static GDBusMessage *on_session_bus_message( return message; } -static gboolean run_proxy_ctl1(const char *arg1) -{ - gchar *argv[] = { - (gchar *)PROXY_CTL_BIN, - (gchar *)arg1, - NULL}; - - return command_succeeds(argv); -} - -static gboolean run_proxy_ctl2(const char *arg1, const char *arg2) +static gboolean proxy_ctl_command(const char *arg1, const char *arg2, gchar **stdout_text) { gchar *argv[] = { (gchar *)PROXY_CTL_BIN, @@ -187,39 +189,47 @@ static gboolean run_proxy_ctl2(const char *arg1, const char *arg2) (gchar *)arg2, NULL}; + if (stdout_text) + { + return command_stdout(argv, stdout_text); + } 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) { 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) { if (!value) { 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, "whitelist") == 0) - { - 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; + if (strcmp(value, route_mode_infos[i].id) == 0) + { + return route_mode_infos[i].mode; + } } return ROUTE_MODE_UNKNOWN; } @@ -250,13 +260,8 @@ static ServiceState get_service_state(void) { ServiceState state = {0}; 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; } @@ -351,9 +356,10 @@ static const char *traffic_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) { case ROUTE_MODE_WHITELIST: @@ -363,61 +369,36 @@ static const char *route_mode_label(const ServiceState *state) 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) { - switch (mode) + for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) { - case ROUTE_MODE_DEFAULT: - return 0; - case ROUTE_MODE_WHITELIST: - 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; + if (route_mode_infos[i].mode == mode) + { + return (gint)i; + } } + return -1; } static void sync_route_mode_widgets(RouteMode mode) { 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_whitelist_item) - { - gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_whitelist_item), mode == ROUTE_MODE_WHITELIST); - } - 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 (route_mode_items[i]) + { + gtk_check_menu_item_set_active( + GTK_CHECK_MENU_ITEM(route_mode_items[i]), + mode == route_mode_infos[i].mode); + } } if (controls_route_mode_combo) { @@ -670,11 +651,11 @@ static void on_proxy_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.socks) { - run_proxy_ctl2("proxy", "off"); + run_proxy_ctl("proxy", "off"); } else { - run_proxy_ctl2("proxy", "on"); + run_proxy_ctl("proxy", "on"); } update_status(); } @@ -686,11 +667,11 @@ static void on_tproxy_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.tproxy) { - run_proxy_ctl2("tproxy", "off"); + run_proxy_ctl("tproxy", "off"); } else { - run_proxy_ctl2("tproxy", "on"); + run_proxy_ctl("tproxy", "on"); } update_status(); } @@ -707,7 +688,7 @@ static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data) { return; } - run_proxy_ctl2("route-mode", mode); + run_proxy_ctl("route-mode", mode); update_status(); } @@ -731,7 +712,7 @@ static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data) { return; } - run_proxy_ctl2("route-mode", mode); + run_proxy_ctl("route-mode", mode); update_status(); } @@ -742,11 +723,11 @@ static void on_tun_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.tun) { - run_proxy_ctl2("tun", "off"); + run_proxy_ctl("tun", "off"); } else { - run_proxy_ctl2("tun", "on"); + run_proxy_ctl("tun", "on"); } update_status(); } @@ -758,11 +739,11 @@ static void on_zapret_toggle(GtkWidget *item, gpointer data) ServiceState state = get_service_state(); if (state.zapret) { - run_proxy_ctl2("zapret", "off"); + run_proxy_ctl("zapret", "off"); } else { - run_proxy_ctl2("zapret", "on"); + run_proxy_ctl("zapret", "on"); } update_status(); } @@ -771,7 +752,7 @@ static void on_restart(GtkWidget *item, gpointer data) { (void)item; (void)data; - run_proxy_ctl1("restart"); + run_proxy_ctl("restart", NULL); update_status(); } @@ -779,7 +760,7 @@ static void on_subscription_update(GtkWidget *item, gpointer data) { (void)item; (void)data; - run_proxy_ctl2("subscription", "update"); + run_proxy_ctl("subscription", "update"); } 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); 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)"); - 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(controls_route_mode_combo), "all-proxy", "All Proxy (override)"); - gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-bypass", "All Bypass (override)"); + 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), + 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); 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"); 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)"); - 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); - - GSList *route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_default_item)); - route_mode_whitelist_item = gtk_radio_menu_item_new_with_label(route_group, "Whitelist (direct by default)"); - g_signal_connect(route_mode_whitelist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "whitelist"); - gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_whitelist_item); - - route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_whitelist_item)); - route_mode_blacklist_item = gtk_radio_menu_item_new_with_label(route_group, "Blacklist (proxy by default)"); - g_signal_connect(route_mode_blacklist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "blacklist"); - 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); + for (gsize i = 0; i < G_N_ELEMENTS(route_mode_infos); ++i) + { + route_mode_items[i] = gtk_radio_menu_item_new_with_label( + route_group, + route_mode_infos[i].control_label); + g_signal_connect( + route_mode_items[i], + "toggled", + G_CALLBACK(on_route_mode_menu_toggled), + (gpointer)route_mode_infos[i].id); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_items[i]); + route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_items[i])); + } 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); diff --git a/scripts/proxy_parsing.py b/scripts/proxy_parsing.py index 3c97713..a555a5e 100644 --- a/scripts/proxy_parsing.py +++ b/scripts/proxy_parsing.py @@ -6,7 +6,7 @@ import sys import urllib.parse import urllib.request -from proxy_url_parsers import PARSERS +from proxy_url_parsers import BACKEND_AWARE_PARSERS, PARSERS 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}'") parser = PARSERS[scheme] - try: + if scheme in BACKEND_AWARE_PARSERS: return parser(url, tag, backend) - except TypeError: - return parser(url, tag) + return parser(url, tag) 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}" +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( lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box" ) -> list[dict]: @@ -261,15 +278,7 @@ def parse_subscription( if scheme not in PARSERS: continue - remark = line.split("#", 1)[1] if "#" in line else "" - 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}" + tag = _subscription_tag(line, tag_prefix, index, seen_tags) try: outbound = build_outbound(line, tag, routing_mark, backend) @@ -294,15 +303,7 @@ def parse_hybrid_subscription( if scheme not in PARSERS: continue - remark = line.split("#", 1)[1] if "#" in line else "" - 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}" + tag = _subscription_tag(line, tag_prefix, index, seen_tags) try: outbound = build_outbound(line, tag, routing_mark, "sing-box") diff --git a/scripts/proxy_url_parsers.py b/scripts/proxy_url_parsers.py index eb83a8e..b2169c6 100644 --- a/scripts/proxy_url_parsers.py +++ b/scripts/proxy_url_parsers.py @@ -416,3 +416,7 @@ PARSERS = { "http": parse_http_proxy, "https": parse_http_proxy, } + +BACKEND_AWARE_PARSERS = { + "vless", +} diff --git a/scripts/test-build-outbound.py b/scripts/test-build-outbound.py index 5550e98..7502dbc 100644 --- a/scripts/test-build-outbound.py +++ b/scripts/test-build-outbound.py @@ -4,6 +4,7 @@ import base64 import json import unittest +import proxy_parsing from proxy_parsing import build_outbound @@ -245,6 +246,19 @@ class BuildOutboundTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, "unsupported scheme"): 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__": unittest.main() diff --git a/scripts/test-fetch-subscription.py b/scripts/test-fetch-subscription.py index 93b58ff..46c4541 100644 --- a/scripts/test-fetch-subscription.py +++ b/scripts/test-fetch-subscription.py @@ -132,6 +132,16 @@ class FetchSubscriptionTests(unittest.TestCase): "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): payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all") obs = run_fetcher(payload, backend="hybrid")