diff --git a/README.md b/README.md index ecfcdab..b159954 100644 --- a/README.md +++ b/README.md @@ -118,7 +118,9 @@ A group without a verb shows its status or list. proxy [status|on|off] local proxy backend proxy outbounds [list] outbounds, where each came from, and the pick - proxy outbounds add add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin) + proxy outbounds add [--detour ] + add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin), + chained through another outbound with --detour proxy outbounds rm remove a runtime outbound proxy outbounds test [tag...] [--ping] [--delay] [--download] TCP ping, real delay, download speed (default: ping, delay) diff --git a/docs/options/index.md b/docs/options/index.md index f6ee6bd..be412c9 100644 --- a/docs/options/index.md +++ b/docs/options/index.md @@ -174,6 +174,7 @@ services.proxy-suite = { rules = [ ]; }; selection = "first"; + selectionExclude = [ ]; singBox = { clashApiPort = 9090; package = pkgs.sing-box; diff --git a/docs/options/proxy.md b/docs/options/proxy.md index fe5893b..6e40dba 100644 --- a/docs/options/proxy.md +++ b/docs/options/proxy.md @@ -81,6 +81,7 @@ Part of the [proxy-suite options reference](./index.md). - [ips](#services-proxy-suite-proxy-routing-rules-ips) - [outbound](#services-proxy-suite-proxy-routing-rules-outbound) - [selection](#services-proxy-suite-proxy-selection) + - [selectionExclude](#services-proxy-suite-proxy-selectionexclude) - singBox - [package](#services-proxy-suite-proxy-singbox-package) - [clashApiPort](#services-proxy-suite-proxy-singbox-clashapiport) @@ -345,9 +346,9 @@ null In TUN mode (global and per-app), answer A queries from the TUN with a fake address and AAAA ones with nothing; sing-box maps the address back to the name when the connection comes\. Saves a lookup per new site and no real lookup leaves for proxied names\. Names that -proxy\.dns\.singBox\.rules or the direct geosites send elsewhere keep real answers\. Mappings -do not survive a restart: an app holding a fake address fails until it looks the name up -again\. sing-box and hybrid backends; XRay’s TUN already uses its own fake DNS\. +proxy\.dns\.singBox\.rules or the direct routing lists send elsewhere keep real answers\. The +addresses handed out are kept in /var/lib/proxy-suite/fakeip, so they survive a restart\. +sing-box and hybrid backends; XRay’s TUN already uses its own fake DNS\. *Type:* boolean @@ -444,7 +445,9 @@ one of “udp”, “tcp”, “tls” ## services\.proxy-suite\.proxy\.dns\.remote -Resolver used through the proxy; the DNS default when proxy\.routing\.default is proxy\. +Resolver used through the proxy; the DNS default when proxy\.routing\.default is proxy\. On +sing-box, names the routing sends through the proxy are always looked up here, so the ISP +never sees them, and direct ones locally\. *Type:* submodule @@ -1401,6 +1404,32 @@ one of “first”, “selector”, “urltest” "urltest" ``` + +## services\.proxy-suite\.proxy\.selectionExclude + +Outbound tags selection never picks on its own: hops other outbounds chain through +(` detour `), or exits only routing rules name\. Subscription entries, ` warp `, ` ssh-proxy ` +and AmneziaWG tags work too\. A pin still reaches them, and so does a selector switched by +hand\. + +*Type:* +list of string + +*Default:* + +```nix +[ ] +``` + +*Example:* + +```nix +[ + "ru-vps" + "warp" +] +``` + ## services\.proxy-suite\.proxy\.singBox\.package diff --git a/modules/proxy-suite/config-templates/sing-box.nix b/modules/proxy-suite/config-templates/sing-box.nix index c3a7ac0..bd4ae4f 100644 --- a/modules/proxy-suite/config-templates/sing-box.nix +++ b/modules/proxy-suite/config-templates/sing-box.nix @@ -20,7 +20,6 @@ let inherit (constants) xrayDnsBridgePorts ; - direct = rules.direct; defaultTunAutoRouteTableIndex = constants.tunAutoRouteTableIndex; defaultTunAutoRouteRulePriority = constants.tunAutoRouteRulePriority; @@ -62,14 +61,7 @@ let # The route mode keeps the user's rules and fake IP, and may drop what sits between. rules = proxyCfg.dns.singBox.rules - ++ lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) { - rule_set = [ "geosite-google" ]; - server = "remote"; - } - ++ lib.optional (direct.geosites != [ ]) { - rule_set = map (s: "geosite-${s}") direct.geosites; - server = "local"; - } + ++ rules.singBoxDnsRules # Only what apps ask through the TUN: the XRay sidecar's and sing-box's own lookups # need real addresses. ++ lib.optional fakeIp { @@ -119,14 +111,19 @@ let enableClashApi ? clashApiEnabled, enableXrayDnsBridge ? hybridEnabled, xrayDnsBridgePort ? xrayDnsBridgePorts.socks, + # Names the fake IP cache: TUN configs only. + fakeIpCache ? null, }: + let + fakeIp = fakeIpCache != null && proxyCfg.dns.fakeIp.enable; + in + lib.recursiveUpdate ( { log.level = "warn"; dns = mkDnsConfig { localDetour = if forceLocalDnsViaProxy then "proxy" else null; - inherit useOutboundRoutingMark; - fakeIp = enableTun && proxyCfg.dns.fakeIp.enable; + inherit useOutboundRoutingMark fakeIp; }; inbounds = @@ -190,7 +187,17 @@ let auto_detect_interface = true; }; } - // lib.optionalAttrs enableClashApi clashApiBlock; + // lib.optionalAttrs enableClashApi clashApiBlock) + # Fake addresses handed out survive a restart, so apps still holding one keep working. The + # start script creates the directory; nothing else is stored, since TUN configs have no + # Clash API to switch a selector with. + (lib.optionalAttrs fakeIp { + experimental.cache_file = { + enabled = true; + path = "${constants.fakeIpCacheDir}/${fakeIpCache}.db"; + store_fakeip = true; + }; + }); in { tproxy = mkConfig { @@ -211,6 +218,7 @@ in forceLocalDnsViaProxy = false; enableClashApi = false; xrayDnsBridgePort = xrayDnsBridgePorts.tun; + fakeIpCache = "tun"; }; perAppTun = mkConfig { @@ -225,5 +233,6 @@ in useOutboundRoutingMark = globalTproxy.enable; enableClashApi = false; xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun; + fakeIpCache = "per-app-tun"; }; } diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 7cb032f..fac9b9e 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -104,8 +104,21 @@ let proxyInboundViaTags = lib.unique ( builtins.filter (via: !builtins.elem via builtinTags) (map (ib: ib.via) proxyInbounds) ); + # The pinned outbounds and every hop they chain through, which the inbound service renders + # too. A hop that is not a static outbound (a subscription entry, warp) has no tag here. + proxyInboundViaHops = + tags: + let + hops = lib.unique ( + builtins.filter (hop: hop != null && !builtins.elem hop tags) ( + map (ob: ob.detour) (builtins.filter (ob: builtins.elem ob.tag tags) proxyCfg.outbounds) + ) + ); + in + if hops == [ ] then tags else proxyInboundViaHops (tags ++ hops); + proxyInboundViaChain = proxyInboundViaHops proxyInboundViaTags; proxyInboundViaOutbounds = builtins.filter ( - ob: builtins.elem ob.tag proxyInboundViaTags + ob: builtins.elem ob.tag proxyInboundViaChain ) proxyCfg.outbounds; proxyInboundUdpTypes = [ @@ -242,6 +255,8 @@ let outboundInventoryFile = "/run/proxy-suite-socks/outbounds.json"; inboundStatsApiPort = 18536; + # sing-box's fake IP caches, one per TUN config; the start script hands it to the backend. + fakeIpCacheDir = "/var/lib/proxy-suite/fakeip"; # Loopback listener behind the selector `proxy-ctl proxy outbounds test` switches. outboundTestPort = 18537; inboundStatsFile = "/var/lib/proxy-suite/inbound-stats.json"; @@ -275,7 +290,7 @@ let # Subscription tags are deliberately not accepted: they only exist at runtime. invalidInboundViaTargets = builtins.filter ( tag: !builtins.elem tag outboundTags - ) proxyInboundViaTags; + ) proxyInboundViaChain; invalidRoutingTargets = lib.unique ( map (rule: rule.outbound) ( diff --git a/modules/proxy-suite/options/proxy-dns.nix b/modules/proxy-suite/options/proxy-dns.nix index faa663e..1af2fea 100644 --- a/modules/proxy-suite/options/proxy-dns.nix +++ b/modules/proxy-suite/options/proxy-dns.nix @@ -24,7 +24,11 @@ in remote = mkOption { type = t.dnsUpstreamType; default = cloudflare; - description = "Resolver used through the proxy; the DNS default when proxy.routing.default is proxy."; + description = '' + Resolver used through the proxy; the DNS default when proxy.routing.default is proxy. On + sing-box, names the routing sends through the proxy are always looked up here, so the ISP + never sees them, and direct ones locally. + ''; example = { type = "tls"; address = "1.1.1.1"; @@ -64,9 +68,9 @@ in In TUN mode (global and per-app), answer A queries from the TUN with a fake address and AAAA ones with nothing; sing-box maps the address back to the name when the connection comes. Saves a lookup per new site and no real lookup leaves for proxied names. Names that - proxy.dns.singBox.rules or the direct geosites send elsewhere keep real answers. Mappings - do not survive a restart: an app holding a fake address fails until it looks the name up - again. sing-box and hybrid backends; XRay's TUN already uses its own fake DNS. + proxy.dns.singBox.rules or the direct routing lists send elsewhere keep real answers. The + addresses handed out are kept in /var/lib/proxy-suite/fakeip, so they survive a restart. + sing-box and hybrid backends; XRay's TUN already uses its own fake DNS. ''; }; diff --git a/modules/proxy-suite/options/proxy-outbounds.nix b/modules/proxy-suite/options/proxy-outbounds.nix index fa0c48b..9d13e98 100644 --- a/modules/proxy-suite/options/proxy-outbounds.nix +++ b/modules/proxy-suite/options/proxy-outbounds.nix @@ -68,6 +68,18 @@ in example = "urltest"; }; + selectionExclude = mkOption { + type = types.listOf types.str; + default = [ ]; + description = '' + Outbound tags selection never picks on its own: hops other outbounds chain through + (`detour`), or exits only routing rules name. Subscription entries, `warp`, `ssh-proxy` + and AmneziaWG tags work too. A pin still reaches them, and so does a selector switched by + hand. + ''; + example = [ "ru-vps" "warp" ]; + }; + urlTest = { url = mkOption { type = types.str; diff --git a/modules/proxy-suite/outbound-detours.jq b/modules/proxy-suite/outbound-detours.jq index 2610c10..21eab6f 100644 --- a/modules/proxy-suite/outbound-detours.jq +++ b/modules/proxy-suite/outbound-detours.jq @@ -5,7 +5,8 @@ # the backend: sing-box sets detour, XRay sockopt.dialerProxy. In hybrid, .xray holds the # sidecar's outbounds, each also standing in .outbounds as a loopback SOCKS hop: a # sing-box outbound may chain through either, a sidecar one only through another -# sidecar one, since the sidecar cannot dial through sing-box. +# sidecar one, since the sidecar cannot dial through sing-box. Each error is +# {tag, message}, the tag being the outbound that cannot be chained. def dialer($h): .streamSettings.sockopt.dialerProxy = $h; ([.outbounds[].tag]) as $tags @@ -19,14 +20,14 @@ def dialer($h): .streamSettings.sockopt.dialerProxy = $h; ) | from_entries) as $hops | .errors = ( [$hops | to_entries[] | select(.value as $v | $tags | index([$v]) | not) - | "outbound '\(.key)' chains through '\(.value)', which is not an outbound"] + | {tag: .key, message: "outbound '\(.key)' chains through '\(.value)', which is not an outbound"}] + [$hops | keys[] as $t | select([limit($hops | length + 1; $t | recurse($hops[.] // empty))][1:] | any(. == $t)) - | "outbound '\($t)' chains back to itself"] + | {tag: $t, message: "outbound '\($t)' chains back to itself"}] + (if $kind == "hybrid" then [$hops | to_entries[] | select((.key as $t | $xtags | index([$t])) and (.value as $v | $xtags | index([$v]) | not)) - | "outbound '\(.key)' runs on XRay and can only chain through another XRay outbound, not '\(.value)'"] + | {tag: .key, message: "outbound '\(.key)' runs on XRay and can only chain through another XRay outbound, not '\(.value)'"}] else [] end) ) | if .errors != [] then . diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 996b032..f304739 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -84,6 +84,7 @@ let geoIPRuleSets singBoxRoutingRules singBoxRouteModeRules + singBoxDnsRules ; xrayRules = import ./rules/xray.nix { @@ -111,6 +112,7 @@ in geoIPRuleSets singBoxRoutingRules singBoxRouteModeRules + singBoxDnsRules xrayRoutingRules xrayRouteModeRules routeModeRules diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index 2943ed1..f02dc5d 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -116,6 +116,31 @@ let ++ blockRules ++ proxyGeoRules; + # DNS follows the routing: a name that goes through the proxy is looked up through it, so + # the ISP's resolver never sees it and cannot spoof the answer; a direct one is looked up + # locally. In the routing's order; block entries resolve however the final says. + mkDnsRules = + server: domains: geosites: + lib.optional (domains != [ ]) { + domain_suffix = domains; + inherit server; + } + ++ lib.optional (geosites != [ ]) { + rule_set = map (s: "geosite-${s}") geosites; + inherit server; + }; + dnsServerFor = category: if category == "direct" then "local" else "remote"; + singBoxDnsRules = + lib.concatMap ( + rule: + lib.optionals (customRuleCategory rule.outbound != "block") ( + mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites + ) + ) customRules + ++ mkDnsRules "remote" r.proxy.domains [ ] + ++ mkDnsRules "local" direct.domains direct.geosites + ++ mkDnsRules "remote" [ ] r.proxy.geosites; + singBoxRouteModeRules = { common = commonRules; custom = customRouteRules; @@ -132,5 +157,6 @@ in geoIPRuleSets singBoxRoutingRules singBoxRouteModeRules + singBoxDnsRules ; } diff --git a/modules/proxy-suite/service-assertions.nix b/modules/proxy-suite/service-assertions.nix index 5078c19..82cd8fc 100644 --- a/modules/proxy-suite/service-assertions.nix +++ b/modules/proxy-suite/service-assertions.nix @@ -269,14 +269,11 @@ let proxyInboundAssertions = [ (mkAssertion (!proxyInboundsEnabled || derived.invalidInboundViaTargets == [ ]) - "proxy-suite: inbounds via targets are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies cannot be named here because their tags only exist at runtime; use via = \"proxy\" to reach those." + "proxy-suite: inbounds via targets, or the hops they chain through, are not defined in proxy.outbounds: ${lib.concatStringsSep ", " derived.invalidInboundViaTargets}. Subscription proxies, warp, ssh-proxy and AmneziaWG outbounds cannot be named here because the inbound service does not run them; use via = \"proxy\" to reach those." ) (mkAssertion (!proxyInboundsEnabled || singBoxOnlyPinnedTags == [ ]) "proxy-suite: inbounds via targets a sing-box-only outbound: ${lib.concatStringsSep ", " singBoxOnlyPinnedTags}. The inbound service runs XRay, so a pinned outbound needs url, urlFile, or xrayJson." ) - (mkAssertion ( - !proxyInboundsEnabled || builtins.all (ob: ob.detour == null) derived.proxyInboundViaOutbounds - ) "proxy-suite: inbounds via targets a chained outbound (one with detour), which the inbound service cannot render; use via = \"proxy\"") (requireEnabled (proxyInboundsEnabled && derived.proxyInboundViaTags != [ ]) proxyEnabled "proxy-suite: inbounds pins a listener to a proxy.outbounds tag, which requires proxy.enable = true" ) diff --git a/modules/proxy-suite/service/proxy-inbounds-scripts.nix b/modules/proxy-suite/service/proxy-inbounds-scripts.nix index 540e16d..4f2d65f 100644 --- a/modules/proxy-suite/service/proxy-inbounds-scripts.nix +++ b/modules/proxy-suite/service/proxy-inbounds-scripts.nix @@ -54,6 +54,10 @@ let mkViaOutboundBlock = ob: let + # A chained one dials through its hop, which the chain put in this config too. + dialerBlock = lib.optionalString (ob.detour != null) '' + OB_JSON=$(${jq} -c --arg hop ${lib.escapeShellArg ob.detour} '.streamSettings.sockopt.dialerProxy = $hop' <<< "$OB_JSON") + ''; urlSource = if ob.urlFile != null then ob.urlFile @@ -70,6 +74,7 @@ let builtins.toJSON (ob.xrayJson // { inherit (ob) tag; }) ) }) + ${dialerBlock} OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") '' else @@ -78,6 +83,7 @@ let URL=$(cat ${lib.escapeShellArg urlSource}) OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \ --backend xray --tag ${lib.escapeShellArg ob.tag}) + ${dialerBlock} OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON") ''; diff --git a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix index b4dda1e..9e41fee 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -3,7 +3,8 @@ pureXrayEnabled, selectionMode, proxyInboundsGuardPrivate, - userDnsRules, + userDnsRules ? [ ], + selectionExclude ? [ ], }: if pureXrayEnabled then @@ -76,6 +77,14 @@ if pureXrayEnabled then | if $route_enabled then .routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)]) else . end + ${lib.optionalString (selectionExclude != [ ]) '' + # The balancer's prefix would take in proxy.selectionExclude too: name the rest instead. + # ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop"; + # rename one of them if that matters. + | ($xray_selectable | map("proxy-suite-ob-" + .)) as $candidates + | if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end + | if .observatory then .observatory.subjectSelector = $candidates else . end + ''} | if $xray_single_proxy_tag == "" then . else diff --git a/modules/proxy-suite/service/script-blocks/outbounds.nix b/modules/proxy-suite/service/script-blocks/outbounds.nix index 7fdd205..97105fb 100644 --- a/modules/proxy-suite/service/script-blocks/outbounds.nix +++ b/modules/proxy-suite/service/script-blocks/outbounds.nix @@ -441,13 +441,18 @@ let mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock; runtimeOutboundsBlock = '' - # outbounds added at runtime + # outbounds added at runtime, and the hop each one chains through (.detour) + RUNTIME_DETOURS_JSON='{}' while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do [ -n "$RUNTIME_OB_TAG" ] || continue case "$RUNTIME_OB_SRC" in *.json) _proxy_suite_add_json_outbound "$RUNTIME_OB_TAG" "$RUNTIME_OB_SRC" runtime ;; *) _proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime ;; - esac || echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2 + esac || { echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2; continue; } + if [ -s "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" ]; then + RUNTIME_DETOURS_JSON=$(${jq} -c --arg t "$RUNTIME_OB_TAG" --rawfile h "${runtimeOutboundsDir}/$RUNTIME_OB_TAG.detour" \ + '.[$t] = ($h | rtrimstr("\n"))' <<< "$RUNTIME_DETOURS_JSON") + fi done < <(_proxy_suite_runtime_outbounds) ''; @@ -465,26 +470,43 @@ let "xray" else "sing-box"; - detourBlock = lib.optionalString (detours.outbounds != { } || detours.subscriptions != { }) '' + # Always there: `proxy-ctl proxy outbounds add --detour` chains runtime outbounds too. A + # declared chain that cannot be built fails the start. A runtime one is left out with a + # warning, like any other runtime outbound that does not come up, rather than going out + # unchained; whatever chained through it is checked again. + detourBlock = '' # outbound chaining - DETOUR_RESULT=$(${jq} -c --argjson xob "${ - if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]" - }" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \ - | ${jq} -c -f ${ - builtins.path { - name = "proxy-suite-outbound-detours"; - path = ../../outbound-detours.jq; - } - } \ - --argjson d ${lib.escapeShellArg (builtins.toJSON detours)} \ - --argjson sources "$OUTBOUND_SOURCES_JSON" \ - --arg kind ${detourKind}) - if ${jq} -e '.errors != []' <<< "$DETOUR_RESULT" >/dev/null; then - ${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$DETOUR_RESULT" >&2 - exit 1 - fi - OUTBOUNDS_JSON=$(${jq} -c '.outbounds' <<< "$DETOUR_RESULT") - ${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c '.xray' <<< "$DETOUR_RESULT")''} + DETOURS_JSON=$(${jq} -c --argjson runtime "$RUNTIME_DETOURS_JSON" '.outbounds = $runtime + .outbounds' \ + <<< ${lib.escapeShellArg (builtins.toJSON detours)}) + while [ "$DETOURS_JSON" != '{"outbounds":{},"subscriptions":{}}' ]; do + DETOUR_RESULT=$(${jq} -c --argjson xob "${ + if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]" + }" '{outbounds: ., xray: $xob}' <<< "$OUTBOUNDS_JSON" \ + | ${jq} -c -f ${ + builtins.path { + name = "proxy-suite-outbound-detours"; + path = ../../outbound-detours.jq; + } + } \ + --argjson d "$DETOURS_JSON" \ + --argjson sources "$OUTBOUND_SOURCES_JSON" \ + --arg kind ${detourKind}) + DETOUR_DROP=$(${jq} -c --argjson sources "$OUTBOUND_SOURCES_JSON" \ + '[.errors[] | select($sources[.tag] == "runtime")] | unique_by(.tag)' <<< "$DETOUR_RESULT") + if ${jq} -e --argjson sources "$OUTBOUND_SOURCES_JSON" 'any(.errors[]; $sources[.tag] != "runtime")' <<< "$DETOUR_RESULT" >/dev/null; then + ${jq} -r '.errors[] | "proxy-suite: " + .message' <<< "$DETOUR_RESULT" >&2 + exit 1 + fi + if [ "$DETOUR_DROP" = '[]' ]; then + OUTBOUNDS_JSON=$(${jq} -c '.outbounds' <<< "$DETOUR_RESULT") + ${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c '.xray' <<< "$DETOUR_RESULT")''} + break + fi + ${jq} -r '.[] | "proxy-suite: warning: ignoring runtime outbound '"'"'\(.tag)'"'"': \(.message)"' <<< "$DETOUR_DROP" >&2 + OUTBOUNDS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '[.[] | select(.tag as $t | $drop | any(.tag == $t) | not)]' <<< "$OUTBOUNDS_JSON") + ${lib.optionalString hybridEnabled ''XRAY_OUTBOUNDS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '[.[] | select(.tag as $t | $drop | any(.tag == $t) | not)]' <<< "$XRAY_OUTBOUNDS_JSON")''} + DETOURS_JSON=$(${jq} -c --argjson drop "$DETOUR_DROP" '.outbounds |= with_entries(select(.key as $t | $drop | any(.tag == $t) | not))' <<< "$DETOURS_JSON") + done ''; requireOutboundsBlock = '' @@ -510,14 +532,32 @@ let fi ''; - # proxy-ctl reads this unprivileged: tags, where each came from, and the pin. + # What selection may pick on its own: all but proxy.selectionExclude. A pin and a + # selector switched by hand still reach the excluded ones. + selectableBlock = '' + SELECTABLE_TAGS_JSON=$(${jq} -c --argjson ex ${lib.escapeShellArg (builtins.toJSON proxyCfg.selectionExclude)} \ + 'map(select(. as $t | $ex | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON") + if [ -z "$PINNED_OUTBOUND" ] && [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 0 ]; then + echo "proxy-suite: every outbound is in proxy.selectionExclude, so there is nothing to select; pin one, or exclude fewer" >&2 + exit 1 + fi + ''; + + # proxy-ctl reads this unprivileged: tags, where each came from, the pin, what each one + # chains through, and what selection leaves alone. inventoryBlock = '' ${jq} -n \ --argjson tags "$OUTBOUND_TAGS_JSON" \ --argjson sources "$OUTBOUND_SOURCES_JSON" \ --arg pinned "$PINNED_OUTBOUND" \ --arg selection ${lib.escapeShellArg selectionMode} \ - '{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson xobs "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}" \ + --argjson selectable "$SELECTABLE_TAGS_JSON" \ + '{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection, + detours: ([($xobs + $obs)[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h + | select($h != null) | {key: .tag, value: $h}] | from_entries), + excluded: ($tags - $selectable)}' \ > "$RUNTIME_DIR/outbounds.json" chmod 644 "$RUNTIME_DIR/outbounds.json" ''; @@ -548,15 +588,15 @@ let # which is the same path a single-outbound config already takes. if [ -n "$PINNED_OUTBOUND" ]; then XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PINNED_OUTBOUND" - elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then - XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")" + elif [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 1 ]; then + XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")" fi '' else if collapseNamedOutbounds then '' PROXY_TAG="$PINNED_OUTBOUND" if [ -z "$PROXY_TAG" ]; then - PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") + PROXY_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON") fi OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \ 'map(if .tag == $t then .tag = "proxy" else . end @@ -568,7 +608,7 @@ let TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON") DEFAULT_TAG="$PINNED_OUTBOUND" if [ -z "$DEFAULT_TAG" ]; then - DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON") + DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON") fi WRAPPER=$(${jq} -n \ --argjson tags "$TAGS" \ @@ -588,7 +628,7 @@ let '{type:"selector",tag:"proxy",outbounds:$tags,default:$default}') else WRAPPER=$(${jq} -n \ - --argjson tags "$TAGS" \ + --argjson tags "$SELECTABLE_TAGS_JSON" \ --arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \ --arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \ --argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \ @@ -614,6 +654,7 @@ let + detourBlock + requireOutboundsBlock + pinBlock + + selectableBlock + inventoryBlock + wrapperBlock + exitTagsBlock; diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 493b6df..da442d0 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -151,6 +151,7 @@ let proxyInboundsGuardPrivate ; userDnsRules = proxyCfg.dns.singBox.rules; + inherit (proxyCfg) selectionExclude; }; backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 1a0d078..98e5689 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -338,6 +338,7 @@ let --arg xray_loglevel "$XRAY_LOGLEVEL" \ --arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \ --arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \ + --argjson xray_selectable "$SELECTABLE_TAGS_JSON" \ --argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \ --arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \ --arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \ @@ -349,6 +350,10 @@ let ${pkgs.coreutils}/bin/chgrp ${constants.serviceUser} "$backend_config" chmod ${if enableLocalProxyAuth then "640" else "g+r"} "$backend_config" done + FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json") + if [ -n "$FAKE_IP_CACHE" ]; then + install -d -m 0700 -o ${constants.serviceUser} -g ${constants.serviceUser} "$(dirname "$FAKE_IP_CACHE")" + fi ${ if hybridEnabled then diff --git a/nix/checks/chaining-dns.nix b/nix/checks/chaining-dns.nix index 523475d..3e777dc 100644 --- a/nix/checks/chaining-dns.nix +++ b/nix/checks/chaining-dns.nix @@ -68,11 +68,71 @@ let in { assertions = [ - # Detours are resolved at start, once subscription entries exist; without any, nothing is added. + # Detours are resolved at start, once subscription and runtime entries exist. ( assert pkgs.lib.hasInfix ''{"outbounds":{"exit":"primary"},"subscriptions":{"sub":"primary"}}'' (startScript chained); assert pkgs.lib.hasInfix "proxy-suite-outbound-detours" (startScript chained); - assert !(pkgs.lib.hasInfix "outbound chaining" (startScript (evalProxySuite [ baseModule ]))); + assert pkgs.lib.hasInfix ''/var/lib/proxy-suite/outbounds.d/$RUNTIME_OB_TAG.detour'' (startScript chained); + true + ) + + # Selection leaves proxy.selectionExclude alone; the inventory says so. + ( + let + script = startScript (evalProxySuite [ + baseModule + { services.proxy-suite.proxy.selectionExclude = [ "primary" ]; } + ]); + in + assert pkgs.lib.hasInfix ''--argjson ex '["primary"]' '' script; + assert pkgs.lib.hasInfix ''excluded: ($tags - $selectable)'' script; + true + ) + + # An inbound pinned to a chained outbound gets the whole chain. + ( + let + script = generated.readDerivation + (evalProxySuite [ + { + system.stateVersion = "26.05"; + services.proxy-suite = { + enable = true; + proxy = { + enable = true; + outbounds = [ + { + tag = "hop"; + url = "http://hop.example.com:8080"; + } + { + tag = "exit"; + url = "http://exit.example.com:8080"; + detour = "hop"; + } + ]; + }; + inbounds = { + enable = true; + serverAddress = "203.0.113.1"; + listeners.main = { + type = "socks"; + port = 1081; + via = "exit"; + users = [ + { + name = "a"; + password = "b"; + } + ]; + }; + }; + }; + } + ]).config.systemd.services."proxy-suite-inbounds".serviceConfig.ExecStart; + in + assert pkgs.lib.hasInfix "# via outbound: hop" script; + assert pkgs.lib.hasInfix "--arg hop hop '.streamSettings.sockopt.dialerProxy = $hop'" script; true ) @@ -89,9 +149,66 @@ in assert tunDns.strategy == "ipv4_only"; true ) + # Fake addresses survive a restart, one cache per TUN config. + ( + assert (mkTunConfig dnsFixture).experimental.cache_file.path == "/var/lib/proxy-suite/fakeip/tun.db"; + assert (mkTunConfig dnsFixture).experimental.cache_file.store_fakeip; + true + ) + # DNS follows the routing: proxied names through remote, direct ones local, in its order. + ( + let + routed = evalProxySuite [ + baseModule + { + services.proxy-suite.proxy.routing = { + proxy = { + domains = [ "blocked.example" ]; + geosites = [ "google" ]; + }; + rules = [ + { + outbound = "direct"; + domains = [ "bank.example" ]; + } + { + outbound = "block"; + domains = [ "ads.example" ]; + } + ]; + }; + } + ]; + rules = map (r: { + inherit (r) server; + match = r.domain_suffix or r.rule_set; + }) (mkTProxyConfig routed).dns.rules; + in + assert + rules == [ + { + server = "local"; + match = [ "bank.example" ]; + } + { + server = "remote"; + match = [ "blocked.example" ]; + } + { + server = "local"; + match = [ "geosite-category-ru" ]; + } + { + server = "remote"; + match = [ "geosite-google" ]; + } + ]; + true + ) # TProxy has no TUN to hand fake addresses to. ( assert !(builtins.any (s: s.tag == "fakeip") tproxyDns.servers); + assert !((mkTProxyConfig dnsFixture).experimental ? cache_file); assert builtins.head tproxyDns.rules == { domain_suffix = [ "corp.example" ]; server = "corp"; }; true ) @@ -125,6 +242,35 @@ in ]; }; } + # An inbound cannot chain through what the inbound service does not run. + { + enable = true; + proxy = { + enable = true; + outbounds = [ + { + tag = "exit"; + url = "http://exit.example.com:8080"; + detour = "warp"; + } + ]; + }; + inbounds = { + enable = true; + serverAddress = "203.0.113.1"; + listeners.main = { + type = "socks"; + port = 1081; + via = "exit"; + users = [ + { + name = "a"; + password = "b"; + } + ]; + }; + }; + } # The sing-box DNS options need sing-box. { enable = true; diff --git a/nix/checks/core-proxy.nix b/nix/checks/core-proxy.nix index 10d9ab1..0c4079f 100644 --- a/nix/checks/core-proxy.nix +++ b/nix/checks/core-proxy.nix @@ -8,8 +8,6 @@ hasRuleSet, dnsHasRuleSet, dnsServerByTag, - mkBadFixtureRaw, - mkFailingAssertions, }: let @@ -21,8 +19,6 @@ let minimal mkRoutingRules mkTProxyConfig - mkBadFixtureRaw - mkFailingAssertions ; }; inherit (fixtures) @@ -38,7 +34,6 @@ let proxyDirectConfig urlTestCustomStartScript noProxyBackendDefaultFixture - invalidCoreProxyAssertions blockGeoRules routingOrDomainRules routingOrGeoIPRules @@ -71,7 +66,6 @@ let ruDefaultConfig urlTestCustomStartScript noProxyBackendDefaultFixture - invalidCoreProxyAssertions ; }; in diff --git a/nix/checks/core-proxy/fixtures.nix b/nix/checks/core-proxy/fixtures.nix index 210f9d4..523307e 100644 --- a/nix/checks/core-proxy/fixtures.nix +++ b/nix/checks/core-proxy/fixtures.nix @@ -5,8 +5,6 @@ minimal, mkRoutingRules, mkTProxyConfig, - mkBadFixtureRaw, - mkFailingAssertions, }: let @@ -138,21 +136,6 @@ let } ]; - invalidCoreProxyAssertions = mkFailingAssertions mkBadFixtureRaw [ - [ - { - system.stateVersion = "26.05"; - services.proxy-suite = { - enable = true; - proxy = { - enable = true; - backend = "sing-box"; - }; - }; - } - ] - ]; - blockGeoRules = mkRoutingRules (evalProxySuite [ baseModule { @@ -188,7 +171,6 @@ in urlTestCustomFixture urlTestCustomStartScript noProxyBackendDefaultFixture - invalidCoreProxyAssertions blockGeoRules routingOrDomainRules routingOrGeoIPRules diff --git a/nix/checks/core-proxy/service-defaults.nix b/nix/checks/core-proxy/service-defaults.nix index 8ca490b..08dc8cb 100644 --- a/nix/checks/core-proxy/service-defaults.nix +++ b/nix/checks/core-proxy/service-defaults.nix @@ -7,7 +7,6 @@ ruDefaultConfig, urlTestCustomStartScript, noProxyBackendDefaultFixture, - invalidCoreProxyAssertions, }: { @@ -53,6 +52,5 @@ assert !(noProxyBackendDefaultFixture.config.systemd.services ? "proxy-suite-socks"); true ) - ] - ++ invalidCoreProxyAssertions; + ]; } diff --git a/nix/checks/lib.nix b/nix/checks/lib.nix index 5cc4b66..67ceb4a 100644 --- a/nix/checks/lib.nix +++ b/nix/checks/lib.nix @@ -176,21 +176,33 @@ let }; }; }; - mkFixture = + # A bad fixture must fail on its own merits. Without a root file system and with a boot + # loader, NixOS's own assertions fail every system, so any case passed as bad. + mkBootableToplevel = + modules: + forceEval + (evalProxySuite ( + [ + { + fileSystems."/" = { + device = "none"; + fsType = "tmpfs"; + }; + boot.loader.grub.enable = false; + } + ] + ++ modules + )).config.system.build.toplevel.drvPath; + mkBadFixture = modules: mkBootableToplevel ([ baseModule ] ++ modules); + mkBadFixtureRaw = mkBootableToplevel; + mkBadProxySuiteFixture = proxySuiteConfig: - evalProxySuite [ + mkBootableToplevel [ { system.stateVersion = "26.05"; services.proxy-suite = proxySuiteConfig; } ]; - mkBadFixture = - modules: - forceEval ((evalProxySuite ([ baseModule ] ++ modules)).config.system.build.toplevel.drvPath); - mkBadFixtureRaw = - modules: forceEval ((evalProxySuite modules).config.system.build.toplevel.drvPath); - mkBadProxySuiteFixture = - proxySuiteConfig: forceEval ((mkFixture proxySuiteConfig).config.system.build.toplevel.drvPath); mkFailingAssertions = evaluate: cases: map ( @@ -247,7 +259,6 @@ in lineContaining shellValueByPrefix baseModule - mkFixture mkBadFixture mkBadFixtureRaw mkBadProxySuiteFixture diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 9eedce7..8fd04b5 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -56,8 +56,6 @@ let hasRuleSet dnsHasRuleSet dnsServerByTag - mkBadFixtureRaw - mkFailingAssertions ; }; inherit (coreProxyChecks) ruDefaultConfig; diff --git a/nix/checks/repo.nix b/nix/checks/repo.nix index c333022..f196e27 100644 --- a/nix/checks/repo.nix +++ b/nix/checks/repo.nix @@ -122,7 +122,8 @@ printf '%s\n' '["community"]' > tags.json jq -n '{tags:["own-vps","community-de"], sources:{"own-vps":"static","community-de":"sub:community"}, - pinned:"community-de", selection:"urltest"}' > inventory.json + pinned:"community-de", selection:"urltest", + detours:{"community-de":"own-vps"}, excluded:["own-vps"]}' > inventory.json run() { env \ @@ -153,6 +154,9 @@ grep -q 'Pinned: community-de' listing grep -q '\*community-de' listing grep -q 'own-vps *static' listing + # What each one chains through, and what selection leaves alone. + grep -q 'community-de *sub:community, via own-vps$' listing + grep -q 'own-vps *static, never picked$' listing # The old spelling still dispatches. run outbounds | cmp - listing @@ -184,6 +188,14 @@ run proxy outbounds rm spool-one | grep -q 'Removed outbound: spool-one' [ ! -e obd/spool-one.url ] + # --detour leaves the hop next to the entry, and only names an outbound that exists. + ! run proxy outbounds add bad-hop http://example.com:1 --detour nope 2>/dev/null + [ ! -e obd/bad-hop.url ] + run proxy outbounds add chained http://example.com:1 --detour own-vps | grep -q 'Added outbound: chained' + [ "$(cat obd/chained.detour)" = own-vps ] + run proxy outbounds rm chained > /dev/null + [ ! -e obd/chained.detour ] + # JSON, as `link --json` prints it, lands as .json without its own tag; stdin too. run proxy outbounds add from-json '{"type":"trojan","tag":"x","server":"t.test","server_port":443,"password":"p"}' \ | grep -q 'Added outbound: from-json' @@ -631,7 +643,7 @@ and .outbounds[0].detour == null and .outbounds[2].detour == "x1"' <<<"$r" > /dev/null r="$(d '{"outbounds":{"x1":"sb"},"subscriptions":{}}' '{"x1":"static","sb":"static"}' hybrid \ '{"outbounds":[{"tag":"x1"},{"tag":"sb"}],"xray":[{"tag":"x1"}]}')" - jq -e '.errors == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null + jq -e '[.errors[].message] == ["outbound '"'x1'"' runs on XRay and can only chain through another XRay outbound, not '"'sb'"'"]' <<<"$r" > /dev/null # A missing hop and a loop are errors, and nothing is rewritten. r="$(d '{"outbounds":{"a":"b","b":"a","c":"gone"},"subscriptions":{}}' '{"a":"static","b":"static","c":"static"}' sing-box \ '{"outbounds":[{"tag":"a"},{"tag":"b"},{"tag":"c"}],"xray":[]}')" diff --git a/nix/checks/route-mode.nix b/nix/checks/route-mode.nix index 6e96793..e83b558 100644 --- a/nix/checks/route-mode.nix +++ b/nix/checks/route-mode.nix @@ -95,7 +95,8 @@ in assert pkgs.lib.hasInfix "all-bypass)" routeModeStartScript; assert pkgs.lib.hasInfix ".route.rules = (sing_box_preserved_rules + $route_rules)" routeModeBackendJqFilter; - assert pkgs.lib.hasInfix ".dns.rules = []" routeModeBackendJqFilter; + # all-proxy and all-bypass keep proxy.dns.singBox.rules and fake IP. + assert pkgs.lib.hasInfix ".dns.rules = .dns.rules[:0]" routeModeBackendJqFilter; true ) @@ -153,7 +154,7 @@ in shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_SUBS_DIR=" == "/var/lib/proxy-suite/subscriptions.d"; assert pkgs.lib.hasInfix "proxy pin [tag]" minimalProxyCtlScript; - assert pkgs.lib.hasInfix "proxy outbounds add " minimalProxyCtlScript; + assert pkgs.lib.hasInfix "proxy outbounds add " minimalProxyCtlScript; true ) ]; diff --git a/nix/checks/subscriptions-runtime.nix b/nix/checks/subscriptions-runtime.nix index 1bc6d23..e552e28 100644 --- a/nix/checks/subscriptions-runtime.nix +++ b/nix/checks/subscriptions-runtime.nix @@ -78,7 +78,7 @@ in ( assert pkgs.lib.hasInfix ''PROXY_TAG="$PINNED_OUTBOUND"'' subscriptionFirstSelectionStartScript; assert - pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end)'' + pkgs.lib.hasInfix ''map(if .tag == $t then .tag = "proxy" else . end'' subscriptionFirstSelectionStartScript; true ) @@ -147,8 +147,8 @@ in # The fetcher's output must land in the cache, not after a stray newline. ( - assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyStartScript; - assert pkgs.lib.hasInfix ''--tag-prefix "$tag" > "$cache.tmp"'' subscriptionOnlyUpdateScript; + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyStartScript; + assert pkgs.lib.hasInfix ''--tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"'' subscriptionOnlyUpdateScript; true ) diff --git a/nix/checks/tg-ws-proxy/fixtures.nix b/nix/checks/tg-ws-proxy/fixtures.nix index fb0b057..5ad1ba3 100644 --- a/nix/checks/tg-ws-proxy/fixtures.nix +++ b/nix/checks/tg-ws-proxy/fixtures.nix @@ -131,6 +131,8 @@ let services.proxy-suite.tgWsProxy = { enable = true; secretFile = "/run/secrets/tg-ws-proxy"; + # Only read when there is a log file to rotate. + log.file = "/var/log/proxy-suite-tg-ws-proxy/tg-ws-proxy.log"; log.keep = 0; }; } diff --git a/nix/checks/xray-backend-features/fixtures.nix b/nix/checks/xray-backend-features/fixtures.nix index d14a599..c96441e 100644 --- a/nix/checks/xray-backend-features/fixtures.nix +++ b/nix/checks/xray-backend-features/fixtures.nix @@ -16,6 +16,9 @@ let singBoxCfg = null; proxyCfg = null; sshProxyCfg = null; + warpCfg = null; + awgOutbounds = null; + constants = null; hybridEnabled = null; collapseNamedOutbounds = null; selectionMode = null; @@ -136,18 +139,6 @@ let ]; }; } - { - enable = true; - proxy = { - enable = true; - outbounds = [ - { - tag = "primary"; - url = "http://proxy.example.com:8080"; - } - ]; - }; - } { enable = true; proxy = { diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 7f53bae..5cca19d 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -53,7 +53,9 @@ A group without a verb shows its status or list. proxy [status|on|off] local proxy backend proxy outbounds [list] outbounds, where each came from, and the pick - proxy outbounds add add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin) + proxy outbounds add [--detour ] + add an outbound at runtime: a URL, or sing-box/XRay JSON (-: stdin), + chained through another outbound with --detour proxy outbounds rm remove a runtime outbound proxy outbounds test [tag...] [--ping] [--delay] [--download] TCP ping, real delay, download speed (default: ping, delay) @@ -349,6 +351,7 @@ COMPLETE = { "link": "its URL, QR code, JSON or client config", } }, + "proxy outbounds add": {"flags": {"--detour": "chain it through another outbound"}}, "proxy outbounds link": { "args": _outbound_choices, "flags": {"--qr": "print a QR code", "--json": "backend JSON", "--config": "client config for this server"}, @@ -748,7 +751,15 @@ def cmd_outbounds(verb="list", *args): if verb == "list": _outbounds_list() elif verb == "add": - _runtime_entry_add("outbound", *args) + args = list(args) + detour = "" + if "--detour" in args: + i = args.index("--detour") + detour = args[i + 1] if i + 1 < len(args) else "" + del args[i : i + 2] + if not detour: + usage("proxy outbounds add [--detour ]") + _runtime_entry_add("outbound", *args, detour=detour) elif verb in ("rm", "remove", "del"): _runtime_entry_rm("outbound", *args) elif verb == "test": @@ -963,6 +974,8 @@ def _outbounds_list(): inventory = _outbound_inventory() pinned = _s(inventory.get("pinned") or "") sources = inventory.get("sources") or {} + detours = inventory.get("detours") or {} + excluded = set(inventory.get("excluded") or []) current = _outbound_current() reputation = _reputation_by_tag() @@ -980,7 +993,8 @@ def _outbounds_list(): mark = "*" elif not pinned and tag == current: mark = ">" - print(f" {mark}{tag:<34} {rep(tag)}{_s(sources.get(tag) or '-')}") + notes = ([f"via {_s(detours[tag])}"] if tag in detours else []) + (["never picked"] if tag in excluded else []) + print(f" {mark}{tag:<34} {rep(tag)}{', '.join([_s(sources.get(tag) or '-'), *notes])}") # --- sharing ------------------------------------------------------------------ @@ -1160,11 +1174,14 @@ def _check_runtime_tag(kind, tag): die(f"A subscription named '{tag}' is declared in the configuration.") -def _runtime_entry_add(kind, tag="", url="", *_): - what = "" if kind == "outbound" else "" +def _runtime_entry_add(kind, tag="", url="", *_, detour=""): + what = " [--detour ]" if kind == "outbound" else "" if not tag or not url: usage(f"proxy {_runtime_noun(kind)} add {what}") _check_runtime_tag(kind, tag) + # The start script checks the chain again, and leaves the outbound out if it breaks later. + if detour and (detour == tag or detour not in _outbound_tags()): + die(f"Cannot chain through '{detour}': not an outbound. See: proxy-ctl proxy outbounds") if kind == "outbound" and url == "-": url = sys.stdin.read() ext = ".url" @@ -1177,6 +1194,10 @@ def _runtime_entry_add(kind, tag="", url="", *_): path = os.path.join(_runtime_dir(kind), tag + ext) old = os.umask(0o027) try: + # The hop first: the entry is what the start script looks for. + if detour: + with open(os.path.join(_runtime_dir(kind), f"{tag}.detour"), "w", encoding="utf-8") as f: + f.write(f"{detour}\n") with open(path, "w", encoding="utf-8") as f: f.write(f"{url}\n") except OSError: @@ -1195,6 +1216,8 @@ def _runtime_entry_rm(kind, tag="", *_): die(f"No runtime {kind} named '{tag}'. Ones declared in the NixOS configuration are removed there.") try: os.unlink(path) + if kind == "outbound" and os.path.exists(os.path.join(_runtime_dir(kind), f"{tag}.detour")): + os.unlink(os.path.join(_runtime_dir(kind), f"{tag}.detour")) except FileNotFoundError: pass except OSError: diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index d81fa54..e680274 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -24,6 +24,11 @@ def _die(message, status=1): sys.exit(message) +# Clash API calls and systemctl spawns that several readers repeat within one load. +MEMOIZED = ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state") +# proxy_ctl as the CLI has it, before the patching below: its own tests put these back. +CLI_FUNCTIONS = {name: getattr(ctl, name) for name in ("die", *MEMOIZED)} + ctl.die = _die _memo = {} # (reader, args) -> result, cleared at the start of every load @@ -39,8 +44,7 @@ def _per_load(fn): return wrapped -# Clash API calls and systemctl spawns that several readers repeat within one load. -for _name in ("_outbound_current", "_outbound_inventory", "_autoproxy_state", "_autoproxy_next_run", "svc_state"): +for _name in MEMOIZED: setattr(ctl, _name, _per_load(getattr(ctl, _name))) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index 0813a51..790693e 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -5,7 +5,9 @@ import datetime import io import json import os +import shutil import socket +import sys import tempfile import unittest from unittest import mock @@ -13,6 +15,16 @@ from unittest import mock import proxy_ctl as ctl +def setUpModule(): + """proxy_model, once imported into the same run, patches proxy_ctl for the front ends; + these tests want it the way the CLI runs.""" + model = sys.modules.get("proxy_model") + for name, fn in (model.CLI_FUNCTIONS if model else {}).items(): + patcher = mock.patch.object(ctl, name, fn) + patcher.start() + unittest.addModuleCleanup(patcher.stop) + + def run(fn, *args): """(exit status, stdout, stderr) of a proxy-ctl function.""" out, err = io.StringIO(), io.StringIO() @@ -642,6 +654,7 @@ class BadExitTest(EnvTest): class WhereTest(EnvTest): """The route walk has to agree with sing-box and XRay, rule-sets included.""" + @unittest.skipUnless(shutil.which(os.environ.get("SING_BOX", "sing-box")), "sing-box not found; set SING_BOX") def test_sing_box_walk(self): rs = self.write("rs.json", {"version": 1, "rules": [{"domain_suffix": ["youtube.com"]}]}) config = {