From 584c8ba0a07938f95ec20f275720dac1fb503261 Mon Sep 17 00:00:00 2001 From: fufsob Date: Sat, 10 Oct 2026 13:41:12 +0000 Subject: [PATCH] feat: runtime routing --- README.md | 12 + docs/options/userControl.md | 2 +- docs/usage/control.md | 3 +- docs/usage/routing.md | 67 ++- modules/proxy-suite/config.nix | 7 +- modules/proxy-suite/derived.nix | 5 + modules/proxy-suite/options/user-control.nix | 2 +- modules/proxy-suite/rules.nix | 56 +++ modules/proxy-suite/rules/sing-box.nix | 32 +- modules/proxy-suite/service/control.nix | 8 + modules/proxy-suite/service/default.nix | 9 + modules/proxy-suite/service/polkit.nix | 1 + .../backend-filter-private-guard.template.jq | 12 +- .../backend-filter-sing-box.template.jq | 18 +- .../backend-filter-xray.template.jq | 2 +- .../script-blocks/backend-jq-filter.nix | 42 +- .../service/script-blocks/routing-compose.jq | 24 + .../service/script-blocks/routing-convert.jq | 67 +++ .../service/script-blocks/routing-render.jq | 52 ++ .../service/script-blocks/routing-runtime.nix | 184 +++++++ modules/proxy-suite/service/scripts.nix | 3 + modules/proxy-suite/service/start-scripts.nix | 80 ++- modules/proxy-suite/service/units.nix | 15 + nix/checks/module-suite.nix | 11 + nix/checks/runtime-routing.nix | 169 +++++++ .../runtime-routing/compose.template.sh | 188 +++++++ pkgs/proxy-ctl/proxy_ctl.py | 471 +++++++++++++++++- pkgs/proxy-ctl/proxy_gui.py | 61 ++- pkgs/proxy-ctl/proxy_model.py | 107 +++- pkgs/proxy-ctl/proxy_tui.py | 73 ++- pkgs/proxy-ctl/test_proxy_ctl.py | 161 ++++++ pkgs/proxy-ctl/test_proxy_gui.py | 17 + pkgs/proxy-ctl/test_proxy_model.py | 47 +- pkgs/proxy-ctl/test_proxy_tui.py | 30 +- 34 files changed, 1926 insertions(+), 112 deletions(-) create mode 100644 modules/proxy-suite/service/script-blocks/routing-compose.jq create mode 100644 modules/proxy-suite/service/script-blocks/routing-convert.jq create mode 100644 modules/proxy-suite/service/script-blocks/routing-render.jq create mode 100644 modules/proxy-suite/service/script-blocks/routing-runtime.nix create mode 100644 nix/checks/runtime-routing.nix create mode 100644 nix/checks/runtime-routing/compose.template.sh diff --git a/README.md b/README.md index 240b7de..c33aee2 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,18 @@ Changes and secrets need root or the userControl group. lower goes first; up/down renumbers the top level proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] show or override the routing mode + proxy rules [list] routing rules, the configuration's and runtime ones, + in the order they are checked + proxy rules add [--name ] [--priority ] + send domains, addresses, geosite:x, geoip:x or ruleset:x + to proxy, direct, block or an outbound; no --name: the + rule named after the target, extended (priority 50: + ahead of the configuration's, at 100 to 500) + proxy rules matches add|rm + proxy rules target + proxy rules priority |up|down + lower goes first; up/down moves past the next row + proxy rules disable|enable|rm proxy subs [list|update] subscriptions; update refetches them proxy subs add [tag] add a subscription (no tag: named after its host; -: stdin) proxy subs rm remove a runtime subscription diff --git a/docs/options/userControl.md b/docs/options/userControl.md index cba6312..57cfb42 100644 --- a/docs/options/userControl.md +++ b/docs/options/userControl.md @@ -65,7 +65,7 @@ What the group may do\. Empty allows everything\. - “services”: start, stop and restart services, and ` tor newnym `\. - “perApp”: ` proxy-ctl apps run `\. - - “routing”: ` proxy pin `, ` proxy unpin ` and ` proxy mode `\. + - “routing”: ` proxy pin `, ` proxy unpin `, ` proxy mode ` and ` proxy rules `\. - “outbounds”: add, remove, enable and disable outbounds and subscriptions\. - “secrets”: read share links, subscription URLs and running configs\. - “autoProxy”: see and change what autoProxy learned\. diff --git a/docs/usage/control.md b/docs/usage/control.md index 31d4a38..88ba7a7 100644 --- a/docs/usage/control.md +++ b/docs/usage/control.md @@ -36,7 +36,7 @@ Members of the group get the listed scopes. An empty `scopes` list grants all of | Scope | Allows | |---|---| | `services` | turning services on, off and restarting them | -| `routing` | `proxy pin`, `proxy unpin`, `proxy mode` | +| `routing` | `proxy pin`, `proxy unpin`, `proxy mode`, `proxy rules` | | `outbounds` | adding, removing, enabling and disabling outbounds and subscriptions, AmneziaWG outbounds included | | `amneziaWg` | `awg add` and `awg rm`: global AmneziaWG profiles, which take over the host's routes and DNS | | `perApp` | `apps run` with `tun`, `tproxy` and `zapret` profiles | @@ -89,6 +89,7 @@ connections (`proxy-ctl where`) need `secrets`. Nothing else in the API is open | `proxy outbounds disable` | until `enable`; works on outbounds from Nix too | | `inbounds users add`, `inbounds add`, `inbounds bind` | until removed; kept across reboots | | `proxy pin` | until `unpin`; kept across reboots | +| `proxy rules add` | until removed with `rules rm`; kept across reboots | | `proxy mode` | until the next reboot | | `… on` / `… off` | until the next reboot; boot state comes from the config | diff --git a/docs/usage/routing.md b/docs/usage/routing.md index bec2feb..fa0efa8 100644 --- a/docs/usage/routing.md +++ b/docs/usage/routing.md @@ -5,12 +5,21 @@ applies to the local proxy, TUN, TProxy and per-app routing alike. ## How a destination is routed -1. `proxy.routing.rules`, in order. The first match wins, and a rule can name a specific - outbound. -2. The lists: `proxy.domains` and `proxy.ips` first, then `block`, then `direct`, then - `proxy.geosites`, `proxy.geoips` and `proxy.ruleSets`. A name in both a block and a direct - list (an ad domain under `category-ru`, say) is blocked. -3. Anything left goes to `proxy.routing.default`: `"proxy"` (the default) or `"direct"`. +The first match wins, checked in this order. Each step has a priority number, and the +rules you add at runtime (below) go in among them: + +| Priority | What is checked | +|---|---| +| 100 | `proxy.routing.rules`, in order, after each outbound's own `routing`. A rule can name a specific outbound. | +| 200 | `proxy.domains` and `proxy.ips` | +| 300 | `block` | +| 400 | `direct`, then private addresses | +| 500 | `proxy.geosites`, `proxy.geoips` and `proxy.ruleSets` | +| after | what autoProxy and zapret2 learned | +| last | `proxy.routing.default`: `"proxy"` (the default) or `"direct"` | + +A name in both a block and a direct list (an ad domain under `category-ru`, say) is blocked. +Apps run with `apps run --via` skip all of this. Russian sites and IPs go direct unless you set `routing.directRu = false`. @@ -81,6 +90,48 @@ services.proxy-suite = { They need the sing-box or hybrid backend. +## Add rules at runtime + +`proxy-ctl proxy rules` adds rules without a rebuild. They are kept across reboots: + +```sh +proxy-ctl proxy rules add direct bank.example 10.0.0.0/8 # these go direct +proxy-ctl proxy rules add proxy geosite:netflix # this through the proxy +proxy-ctl proxy rules add us-vps hulu.com --name streaming # through one outbound or group +proxy-ctl proxy rules add block ads.example --priority 350 # after the config's block list +proxy-ctl proxy rules # every rule, in the order checked +``` + +A rule matches domains (subdomains included), addresses and CIDRs, `geosite:NAME`, +`geoip:NAME` and `ruleset:NAME` (a rule set from `routing.ruleSets`). It sends them to +`proxy`, `direct`, `block`, or any outbound or group, ones added at runtime included. + +Without `--name`, the rule is named after its target, so `rules add direct …` keeps adding to +the same rule. A new rule gets priority 50, ahead of everything in the config. Give it +another number with `--priority`, or move it later: + +```sh +proxy-ctl proxy rules priority streaming 450 # after the direct lists +proxy-ctl proxy rules priority streaming up # one row up, past a rule or a config step +proxy-ctl proxy rules matches direct rm 10.0.0.0/8 +proxy-ctl proxy rules target streaming de-vps +proxy-ctl proxy rules disable streaming # keep it, but stop applying it +proxy-ctl proxy rules rm streaming +``` + +On equal priority, a runtime rule goes first. Route modes treat runtime rules like the +config's: `all-proxy` drops the ones that go direct, and `all-bypass` keeps only blocks. + +A change applies at once. On sing-box and hybrid, adding or removing a rule's domains and +addresses does not restart anything. Other changes, and every change on XRay, restart the +proxy, which drops open connections. A rule whose outbound is gone is left out until the +outbound is back, and `proxy rules` says why. + +The Routing tab in the TUI and the app lists the same rules, the config's included. It adds +(`n`), edits (`a`, `x`, `t`), moves (`+`, `-`, `y`), disables (`e`) and removes (`d`) them. The +route mode is a selector above the table (`m`). Pasting a bare domain onto the tab sends it +through the proxy. + ## Commands ```sh @@ -90,11 +141,13 @@ proxy-ctl proxy mode blacklist # proxy unless a rule says otherwise proxy-ctl proxy mode all-proxy # everything through the proxy, except blocks proxy-ctl proxy mode all-bypass # everything direct, except blocks proxy-ctl proxy mode default # back to routing.default +proxy-ctl proxy rules # every routing rule, in the order checked proxy-ctl proxy auto # what autoProxy routed, and where proxy-ctl proxy rulesets update # refetch rule sets now ``` -A route mode set with `proxy-ctl` lasts until the next reboot. +A route mode set with `proxy-ctl` lasts until the next reboot. Rules added with +`proxy rules` last until removed. ## Good to know diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 6f367db..2ec7486 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -205,8 +205,13 @@ let }; selectedTemplates = if derived.pureXrayEnabled then xrayTemplates else singBoxTemplates; + # The start script composes the route from these buckets (and the runtime rules); proxy-ctl + # reads the sections, the configuration's part of `proxy rules list`. routeModeRules = - if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules; + (if derived.pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules) + // { + sections = rules.routingSections; + }; tproxyFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON selectedTemplates.tproxy); tunFile = pkgs.writeText "proxy-suite-core" (builtins.toJSON selectedTemplates.tun); diff --git a/modules/proxy-suite/derived.nix b/modules/proxy-suite/derived.nix index 275d185..17d45b0 100644 --- a/modules/proxy-suite/derived.nix +++ b/modules/proxy-suite/derived.nix @@ -1066,6 +1066,11 @@ let runtimeInboundsLock = "${runtimeDir}/proxy-suite-inbounds-runtime.lock"; # Per-app profiles added with `proxy-ctl apps add`: .json, next to the declared ones. runtimeAppsDir = "${stateDir}/apps.d"; + # Routing rules added with `proxy-ctl proxy rules`: rules.json, written by the routing + # scope's groups. Root renders it into routingRulesDir (routing-runtime.nix), which the + # backends read: rules.json checked, and a rule set per rule that sing-box reloads. + runtimeRoutingDir = "${stateDir}/routing.d"; + routingRulesDir = "${stateDir}/routing"; # Shell function for the scripts that read those spools as root. $1 a file: in a spool, # a regular file only, and never through a symlink, which would hand over any file root # can read (a share link or an error message then shows it), nor a FIFO, which would diff --git a/modules/proxy-suite/options/user-control.nix b/modules/proxy-suite/options/user-control.nix index ccea2ef..1a51e49 100644 --- a/modules/proxy-suite/options/user-control.nix +++ b/modules/proxy-suite/options/user-control.nix @@ -22,7 +22,7 @@ in What the group may do. Empty allows everything. - "services": start, stop and restart services, and `tor newnym`. - "perApp": `proxy-ctl apps run`. - - "routing": `proxy pin`, `proxy unpin` and `proxy mode`. + - "routing": `proxy pin`, `proxy unpin`, `proxy mode` and `proxy rules`. - "outbounds": add, remove, enable and disable outbounds and subscriptions. - "secrets": read share links, subscription URLs and running configs. - "autoProxy": see and change what autoProxy learned. diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 83e119c..b3dac89 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -109,6 +109,61 @@ let routingRules = singBoxRoutingRules; routeModeRules = singBoxRouteModeRules; + # The configuration's sections in match order, each at a fixed priority that runtime + # routing rules (`proxy-ctl proxy rules`) sort among; `proxy rules list` and the Routing tab + # show them. Tags as the user wrote them, not as the backend spells them. + matchFields = rule: { + domains = rule.domains or [ ]; + ips = rule.ips or [ ]; + geosites = rule.geosites or [ ]; + geoips = rule.geoips or [ ]; + ruleSets = rule.ruleSets or [ ]; + }; + routingSections = [ + { + id = "rules"; + priority = 100; + label = "routing.rules"; + entries = + lib.concatMap ( + ob: + let + m = matchFields ob.routing; + in + lib.optional (lib.any (v: v != [ ]) (builtins.attrValues m)) (m // { target = ob.tag; }) + ) proxyCfg.outbounds + ++ map (rule: matchFields rule // { target = rule.outbound; }) r.rules; + } + { + id = "proxy"; + priority = 200; + label = "routing.proxy: domains and ips"; + entries = [ + (matchFields { inherit (r.proxy) domains ips; } // { target = "proxy"; }) + ]; + } + { + id = "block"; + priority = 300; + label = "routing.block"; + entries = [ (matchFields r.block // { target = "block"; }) ]; + } + { + id = "direct"; + priority = 400; + label = "routing.direct, private addresses"; + entries = [ (matchFields (direct // { inherit (r.direct) ruleSets; }) // { target = "direct"; }) ]; + } + { + id = "proxyGeo"; + priority = 500; + label = "routing.proxy: geosites, geoips and rule sets"; + entries = [ + (matchFields { inherit (r.proxy) geosites geoips ruleSets; } // { target = "proxy"; }) + ]; + } + ]; + in { inherit @@ -124,5 +179,6 @@ in xrayRouteModeRules routeModeRules routingRules + routingSections ; } diff --git a/modules/proxy-suite/rules/sing-box.nix b/modules/proxy-suite/rules/sing-box.nix index 5e05d73..c7ad4aa 100644 --- a/modules/proxy-suite/rules/sing-box.nix +++ b/modules/proxy-suite/rules/sing-box.nix @@ -99,6 +99,9 @@ let customRouteRules = map (rule: { category = customRuleCategory rule.outbound; entries = mkCustomRuleEntries rule; + # Its share of the DNS mirror below, so a start script that reorders the sections + # (runtime routing rules) reorders their lookups with them. + dns = customDnsRules rule; }) customRules; proxyPrimaryRules = lib.flatten [ @@ -172,18 +175,23 @@ let 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 ( - rule.ruleSets or [ ] - ) + customDnsRules = + rule: + lib.optionals (customRuleCategory rule.outbound != "block") ( + mkDnsRules (dnsServerFor (customRuleCategory rule.outbound)) rule.domains rule.geosites ( + rule.ruleSets or [ ] ) - ) customRules - ++ mkDnsRules "remote" r.proxy.domains [ ] [ ] - ++ mkDnsRules "local" direct.domains direct.geosites r.direct.ruleSets - ++ mkDnsRules "remote" [ ] r.proxy.geosites r.proxy.ruleSets; + ); + dnsSections = { + proxyPrimary = mkDnsRules "remote" r.proxy.domains [ ] [ ]; + direct = mkDnsRules "local" direct.domains direct.geosites r.direct.ruleSets; + proxyGeo = mkDnsRules "remote" [ ] r.proxy.geosites r.proxy.ruleSets; + }; + singBoxDnsRules = + lib.concatMap (item: item.dns) customRouteRules + ++ dnsSections.proxyPrimary + ++ dnsSections.direct + ++ dnsSections.proxyGeo; singBoxRouteModeRules = { common = commonRules; @@ -193,6 +201,8 @@ let safetyDirect = safetyDirectRules; block = blockRules; proxyGeo = proxyGeoRules; + # The DNS mirror by section, in singBoxDnsRules' order (custom's is in each rule). + dns = dnsSections; }; in { diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index 1cbf86c..2c85688 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -30,6 +30,7 @@ let perAppViaRuntime proxySuiteScriptsDir ruleSets + routeModeRulesFile pkgs ; inherit (ctx.scripts) @@ -93,6 +94,13 @@ in PROXYCHAINS_CONFIG = toString proxychainsConfigFile; PROXYCHAINS_QUIET_ARG = lib.removeSuffix " " proxychainsQuietArg; ROUTE_MODE_STATE_FILE = routeModeStateFile; + # The configuration's routing in sections, each at its priority ("sections"), and the + # rules `proxy rules` adds: its spool, and what root rendered of it. + ROUTING_RULES_FILE = toString routeModeRulesFile; + RUNTIME_ROUTING_DIR = constants.runtimeRoutingDir; + ROUTING_RULES_DIR = constants.routingRulesDir; + GEODATA_GEOSITE_DIR = "${cfg.geodata.singBox.geosite}/share/sing-box/rule-set"; + GEODATA_GEOIP_DIR = "${cfg.geodata.singBox.geoip}/share/sing-box/rule-set"; DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist"; AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile; # The WARP devices behind outbounds, each with the unit that carries it. diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index d50d373..92b9916 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -95,6 +95,10 @@ let path = constants.runtimeAppsDir; scope = "perApp"; } + ++ lib.optional proxyEnabled { + path = constants.runtimeRoutingDir; + scope = "routing"; + } ++ lib.optional derived.zapretCutoffEnabled { path = "${constants.zapret2CutoffDir}/requests"; scope = "zapret"; @@ -367,6 +371,11 @@ lib.mkMerge [ constants.runtimeSubscriptionsDir ] )) + # Routing rules added at runtime (`proxy rules`): the routing scope's. Nothing secret + # in them, but root renders what is there into every backend's route. + (lib.mkIf (cfg.enable && proxyEnabled) [ + "d ${constants.runtimeRoutingDir} ${spoolDirMode "routing"} -" + ]) # inbounds.runtime: the users' and listeners' files hold their secrets, so the dir is # as closed as outbounds.d, and group-writable only with the inbounds scope. (lib.mkIf (cfg.enable && derived.proxyInboundsRuntimeEnabled) ( diff --git a/modules/proxy-suite/service/polkit.nix b/modules/proxy-suite/service/polkit.nix index bfc81f6..13ce053 100644 --- a/modules/proxy-suite/service/polkit.nix +++ b/modules/proxy-suite/service/polkit.nix @@ -22,6 +22,7 @@ let "proxy-suite-outbound-pin@" = "routing"; "proxy-suite-outbound-unpin." = "routing"; "proxy-suite-route-mode@" = "routing"; + "proxy-suite-routing-apply." = "routing"; "proxy-suite-outbound-reload." = "outbounds"; "proxy-suite-subscription-update." = "outbounds"; # Tunnels of the AmneziaWG outbounds added at runtime; a global profile's own unit diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq index 6c5100b..782cda5 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-private-guard.template.jq @@ -1,6 +1,7 @@ # inbounds.routing.blockPrivate (or, without it, this host's loopback), enforced here because # the listener passes names unresolved. -# Just before the first direct rule (or last, for a direct final), so names that the +# Just before the first direct rule of the configuration (or last, for a direct final), and +# scoped to each runtime direct rule above that (insert_guard), so names that the # proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local # mixed-in clients lose names that resolve private. Rules for other inbounds do not count: # autoProxy's direct probe pin would put the guard first, resolving every name, .onion too. @@ -11,11 +12,4 @@ {inbound: ["mixed-in"]@rejectMatch@, action: "reject"}] + (($ARGS.named.host_addresses // []) as $own | if $own == [] or @hostPortsAllOpen@ then [] else [{inbound: ["mixed-in"], ip_cidr: $own@hostPortMatch@, action: "reject"}] end) as $guard -| (.route.rules - | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) - | index(true)) as $first_direct -| if $first_direct != null then - .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] - elif (.route.final // "direct") == "direct" then - .route.rules += $guard - else . end +| insert_guard($guard) diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq index 42004d1..69f8d53 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-sing-box.template.jq @@ -20,7 +20,23 @@ $route_rules[0] as $route_rules | $probe_inbounds[0] as $probe_inbounds | if $clear_dns_rules then .dns.rules = .dns.rules[:@userDnsRuleCount@] + [.dns.rules[@userDnsRuleCount@:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])] - else . end + else + # The DNS mirror composed with the route (routing-compose.jq), runtime rules' lookups + # among the configuration's: in place of the configuration's own, which follows the + # user's rules and the .onion ones. + (($ARGS.named.route_dns // [null])[0]) as $route_dns + | if $route_dns == null then . else + (.dns.rules // []) as $r + | ([$r[@userDnsRuleCount@:][] | .domain_suffix? == ["onion"]] | index(false) + // ($r[@userDnsRuleCount@:] | length)) as $onion + | (@userDnsRuleCount@ + $onion) as $at + | .dns.rules = $r[:$at] + $route_dns + $r[$at + ($ARGS.named.static_dns_count // 0):] + end + end + # The runtime rules' own rule sets, and geodata the configuration does not name. + | ([.route.rule_set[]?.tag]) as $have + | .route.rule_set = ((.route.rule_set // []) + + [(($ARGS.named.user_rule_sets // [[]])[0])[] | select(.tag as $t | $have | index([$t]) | not)]) else . end # autoProxy rules, after the route-mode replace so no mode drops them: pins first # (they only match their own listener), learned rules last before final, so diff --git a/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq index 0d508f0..3cbfabf 100644 --- a/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq +++ b/modules/proxy-suite/service/script-blocks/backend-filter-xray.template.jq @@ -14,7 +14,7 @@ def xray_rewrite_proxy_rule($single_tag): def xray_preserved_rules: [.routing.rules[] | select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote" - or . == "inbounds-private-guard" or . == "inbounds-host-guard")]; + or . == "dns-remote-bridge" or . == "inbounds-private-guard" or . == "inbounds-host-guard")]; def xray_final_rule($tag; $single_tag): if $tag == "proxy" and "@selectionMode@" == "urltest" then {type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag) 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 4ffb72e..8dbde88 100644 --- a/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix +++ b/modules/proxy-suite/service/script-blocks/backend-jq-filter.nix @@ -19,6 +19,38 @@ let fillTemplate = import ../../lib/fill-template.nix; + # A guard for mixed-in's names goes just before the first direct rule that applies to + # mixed-in, or last for a direct final. A runtime routing rule (routing-convert.jq: its first + # rule set is user:) does not count: one sending a name direct at the top would take the + # guard, and its lookup, above every proxy rule. Each such rule above the guard gets the guard + # to itself instead, only for what it matches. + insertGuardDefs = '' + | def runtime_rule: ((.rule_set? // [])[0] // "") | type == "string" and startswith("user:"); + def direct_for_mixed: (.outbound? // "") == "direct" + and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null; + # An "and" takes the rule set as one more condition; anything else, "or" included, is + # wrapped whole. + def scoped($sets): + if .type? == "logical" and .mode? == "and" then .rules += [{rule_set: $sets}] + else {type: "logical", mode: "and", + rules: [del(.action, .strategy, .server), {rule_set: $sets}]} + + ({action, strategy, server} | with_entries(select(.value != null))) + end; + def first_direct: .route.rules | map(direct_for_mixed and (runtime_rule | not)) | index(true); + def insert_guard($guard): + (first_direct // (.route.rules | length)) as $limit + | .route.rules = [.route.rules | to_entries[] | .key as $i | .value + | if $i < $limit and direct_for_mixed and runtime_rule + then (. as $rule | $guard[] | scoped($rule.rule_set)), . + else . end] + | first_direct as $first_direct + | if $first_direct != null then + .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] + elif (.route.final // "direct") == "direct" then + .route.rules += $guard + else . end; + . + ''; # XRay's port list: "80,1000-2000". closedPorts = map ( r: if r.from == r.to then toString r.from else "${toString r.from}-${toString r.to}" @@ -33,6 +65,7 @@ else (fillTemplate ./backend-filter-sing-box.template.jq { userDnsRuleCount = toString (builtins.length userDnsRules); }) + + lib.optionalString (listenerExposed || proxyInboundsGuardPrivate) insertGuardDefs # An outbound on such an interface resolves through it (awg-dns-), as a declared one # does; only its server cannot be in the build-time config. + lib.optionalString (awgRuntimeDnsServer != null) '' @@ -58,14 +91,7 @@ else {type: "logical", mode: "and", rules: [{inbound: ["mixed-in"], ip_cidr: ${builtins.toJSON proxyInboundsLoopback}}, $remote], action: "reject"}] as $guard - | (.route.rules - | map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null) - | index(true)) as $first_direct - | if $first_direct != null then - .route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:] - elif (.route.final // "direct") == "direct" then - .route.rules += $guard - else . end + | insert_guard($guard) '' # No sniffing on mixed-in, where the inbounds' clients arrive: an SNI the rules send direct # would take their connection direct to any address. Their names still route as names. diff --git a/modules/proxy-suite/service/script-blocks/routing-compose.jq b/modules/proxy-suite/service/script-blocks/routing-compose.jq new file mode 100644 index 0000000..125b78d --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/routing-compose.jq @@ -0,0 +1,24 @@ +# The route for a mode, from the configuration's rule buckets (routeModeRulesFile) and the +# runtime rules' sections (routing-convert.jq): every section at its priority, a runtime one +# ahead of the configuration's at the same number, the common rules first. $mode drops what it +# leaves to the final outbound: all-proxy every direct list, all-bypass all but the blocks. +# Out: the route rules, the DNS mirror in the same order, and how long the configuration's +# own mirror is (the stretch of dns.rules this replaces). +def keep: if $mode == "all-proxy" then .cat != "direct" + elif $mode == "all-bypass" then .cat == "block" or .cat == "safety" + else true end; + +.common as $common +| ([.custom[] | {prio: 100, cat: .category, rules: .entries, dns: (.dns // [])}] + + [{prio: 200, cat: "proxy", rules: .proxyPrimary, dns: (.dns.proxyPrimary // [])}, + {prio: 300, cat: "block", rules: .block, dns: []}, + {prio: 400, cat: "direct", rules: .direct, dns: (.dns.direct // [])}, + {prio: 400, cat: "safety", rules: .safetyDirect, dns: []}, + {prio: 500, cat: "proxy", rules: .proxyGeo, dns: (.dns.proxyGeo // [])}]) as $static +# sort_by is stable: runtime sections, already in their order, first among equals. +| ($runtime[0] + $static | sort_by(.prio) | map(select(keep))) as $sections +| { + rules: ($common + ([$sections[].rules[]])), + dns: [$sections[].dns[]], + staticDnsCount: ([$static[].dns | length] | add // 0) + } diff --git a/modules/proxy-suite/service/script-blocks/routing-convert.jq b/modules/proxy-suite/service/script-blocks/routing-convert.jq new file mode 100644 index 0000000..f8cc9d9 --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/routing-convert.jq @@ -0,0 +1,67 @@ +# The rendered runtime routing rules (routing-render.jq) as the backend's: one section each, +# at the rule's priority, for routing-compose.jq to sort among the configuration's. +# A rule the backend would refuse (an outbound that is gone, a rule set this configuration does +# not declare) is left out and said why, so it never fails the whole start. +# +# $backend: sing-box or xray. $tags (slurped): every outbound tag the config will have. +# $rule_sets: the declared routing.ruleSets. $missing_geo (slurped): geosite-X/geoip-X with no +# .srs. $dir: where the +# rendered rule sets are. $geosite_dir/$geoip_dir: sing-box's geodata. $urltest: pure XRay's +# urltest, which prefixes every outbound and balances "proxy". +def builtin: . == "proxy" or . == "direct" or . == "block"; +def category: if . == "direct" then "direct" elif . == "block" then "block" else "proxy" end; +def backend_tag: if $backend == "xray" and $urltest and (builtin | not) then "proxy-suite-ob-" + . else . end; +def xray_target: if . == "proxy" and $urltest then {balancerTag: "proxy"} else {outboundTag: backend_tag} end; +def local_set($tag; $path; $format): {type: "local", format: $format, tag: $tag, path: $path}; +def why: + if (.target | builtin | not) and ((.target | backend_tag) as $t | $tags[0] | index([$t]) | not) then + "no outbound or group named \(.target)" + elif $backend == "xray" and .ruleSets != [] then + "rule sets need the sing-box or hybrid backend" + elif (.ruleSets - $rule_sets) != [] then + "no rule set named \((.ruleSets - $rule_sets) | join(", ")) in routing.ruleSets" + elif ([.geosites[] | "geosite-" + .] + [.geoips[] | "geoip-" + .] | any(. as $g | $missing_geo[0] | index([$g]))) then + "no such geosite or geoip: \([.geosites[] | "geosite-" + .] + [.geoips[] | "geoip-" + .] | map(select(. as $g | $missing_geo[0] | index([$g]))) | join(", "))" + else null end; + +[.[] | select(.disabled | not)] as $rules +| [$rules[] | why as $why | select($why != null) | {name, why: $why}] as $skipped +| [$rules[] | select(why == null)] as $ok +| { + skipped: $skipped, + sections: [$ok[] | . as $r | { + prio: .priority, + cat: (.target | category), + name: .name, + rules: ( + if $backend == "xray" then + # XRay takes a ruleTag once. + ({type: "field"} + (.target | xray_target)) as $base + | ([.domains[] | "domain:" + .] + [.geosites[] | "geosite:" + .]) as $domain + | (.ips + [.geoips[] | "geoip:" + .]) as $ip + | (if $domain != [] then [$base + {ruleTag: ("user:" + $r.name), domain: $domain}] else [] end) + + (if $ip != [] then [$base + {ruleTag: ("user:" + $r.name + ":ip"), ip: $ip}] else [] end) + else + # Always, its own rule set first even while empty: matches added later reach sing-box + # by the file alone, no restart. The guards find a runtime rule by that first tag. + [{rule_set: (["user:" + .name] + [.geosites[] | "geosite-" + .] + [.geoips[] | "geoip-" + .] + + [.ruleSets[] | "ruleset-" + .]), + outbound: .target}] + end), + # As the configuration's lookups follow its routing (rules/sing-box.nix): names only. + dns: ( + if $backend == "xray" or .target == "block" then [] + else [{rule_set: (["user-dns:" + .name] + [.geosites[] | "geosite-" + .] + + [.ruleSets[] | "ruleset-" + . + "-dns"]), + server: (if .target == "direct" then "local" else "remote" end)}] + end) + }], + rule_sets: ( + if $backend == "xray" then [] + else + [$ok[] | local_set("user:" + .name; $dir + "/rs/" + .name + ".json"; "source"), + local_set("user-dns:" + .name; $dir + "/dns/" + .name + ".json"; "source")] + + ([$ok[].geosites[]] | unique | map(local_set("geosite-" + .; $geosite_dir + "/geosite-" + . + ".srs"; "binary"))) + + ([$ok[].geoips[]] | unique | map(local_set("geoip-" + .; $geoip_dir + "/geoip-" + . + ".srs"; "binary"))) + end) + } diff --git a/modules/proxy-suite/service/script-blocks/routing-render.jq b/modules/proxy-suite/service/script-blocks/routing-render.jq new file mode 100644 index 0000000..95df13b --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/routing-render.jq @@ -0,0 +1,52 @@ +# routing.d/rules.json, as userControl's group wrote it (slurped: one document, else none), to +# the rules root applies: each field checked, anything else dropped, a name once. Sorted in +# match order (priority, then name). +def strs: if type == "array" then [.[] | strings] else [] end; +def domain: ascii_downcase | ltrimstr(".") | select(test("^[a-z0-9_-]+(\\.[a-z0-9_-]+)*$") and length <= 253); +# Addresses as Go's netip parses them, which both backends do: one the backend refuses would +# fail its whole start. No leading zeros, no zone. +def v4: test("^(0|[1-9][0-9]{0,2})(\\.(0|[1-9][0-9]{0,2})){3}$") and all(split(".")[]; tonumber <= 255); +def v6_groups: + split("::") as $parts + | ($parts | length) as $n + | [$parts[] | select(. != "") | split(":")[]] as $groups + | $n <= 2 and ($groups | all(test("^[0-9a-f]{1,4}$"))) + and (if $n == 2 then ($groups | length) <= 7 else ($groups | length) == 8 end); +# An IPv4 tail (::ffff:192.0.2.1) counts as two groups. +def v6: + test("^[0-9a-f:.]+$") and test(":") + and (if test("\\.") then + [match("^(.*:)([0-9.]+)$").captures[].string] as $m + | ($m | length) == 2 and ($m[1] | v4) and ($m[0] + "0:0" | v6_groups) + else v6_groups end); +def prefix($max): test("^(0|[1-9][0-9]{0,2})$") and tonumber <= $max; +# A bare address is its own /32 or /128. +def cidr: + ascii_downcase | split("/") as $s + | ($s | length) as $n + | if $n > 2 then empty + elif ($s[0] | v4) then (if $n == 1 then $s[0] + "/32" elif ($s[1] | prefix(32)) then . else empty end) + elif ($s[0] | v6) then (if $n == 1 then $s[0] + "/128" elif ($s[1] | prefix(128)) then . else empty end) + else empty end; +# geosite-NAME.srs, geosite:NAME: "geolocation-!cn" and "google@cn" among them, never a path. +def geo: select(test("^[A-Za-z0-9!@._-]{1,64}$") and (startswith(".") | not)); +def tag: select(test("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")); + +(if length == 1 then .[0] else null end) +| [(.rules? // []) | if type == "array" then .[] else empty end + | objects + | select((.name | type) == "string" and (.name | test("^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$"))) + | select((.target | type) == "string" and (.target | length) >= 1 and (.target | length) <= 128 and (.target | test("[[:cntrl:]]") | not)) + | { + name, + target, + priority: (if (.priority | type) == "number" then (.priority | floor | if . < -1000000 then -1000000 elif . > 1000000 then 1000000 else . end) else 50 end), + disabled: (.disabled == true), + domains: ([.domains | strs[] | domain] | unique), + ips: ([.ips | strs[] | cidr] | unique), + geosites: ([.geosites | strs[] | geo] | unique), + geoips: ([.geoips | strs[] | geo] | unique), + ruleSets: ([.ruleSets | strs[] | tag] | unique) + }] +| reduce .[] as $r ([]; if any(.[]; .name == $r.name) then . else . + [$r] end) +| sort_by(.priority, .name) diff --git a/modules/proxy-suite/service/script-blocks/routing-runtime.nix b/modules/proxy-suite/service/script-blocks/routing-runtime.nix new file mode 100644 index 0000000..761f9ad --- /dev/null +++ b/modules/proxy-suite/service/script-blocks/routing-runtime.nix @@ -0,0 +1,184 @@ +# Routing rules added at runtime (`proxy-ctl proxy rules`): rendered from the routing scope's +# spool, then composed into each backend's route by the start scripts. +# +# routing.d/rules.json is the groups'; root renders it into routingRulesDir: rules.json +# checked (routing-render.jq), per rule rs/.json (its domains and addresses) and +# dns/.json (its domains alone) as sing-box source rule sets, and `structure`, what of +# them changes the config itself. A change to a rule's domains or addresses alone reaches a +# running sing-box through its rule set files, which it reloads; anything else, and any change +# on XRay, which has no rule sets, restarts the backends. +{ ctx }: + +let + inherit (ctx) + lib + pkgs + cfg + jq + constants + pureXrayEnabled + ; + inherit (constants) runtimeRoutingDir routingRulesDir; + coreutils = "${pkgs.coreutils}/bin"; + + renderJq = ./routing-render.jq; + convertJq = ./routing-convert.jq; + composeJq = ./routing-compose.jq; + + # Where sing-box finds geodata the configuration does not name; also how a geosite or geoip + # gets checked before XRay is handed one (the two come from the same lists). + geositeDir = "${cfg.geodata.singBox.geosite}/share/sing-box/rule-set"; + geoipDir = "${cfg.geodata.singBox.geoip}/share/sing-box/rule-set"; + + # Root, over a spool the groups write: read through no symlink, 4 MiB at most, and checked + # field by field. Under a lock: every backend's start script renders too. --sweep also + # removes the rule sets of rules that are gone, which apply does once the backends that + # watched them have restarted. The spool and output directories as arguments: for the checks. + render = pkgs.writeShellScript "proxy-suite-core" '' + set -euo pipefail + SWEEP=false + if [ "''${1:-}" = --sweep ]; then + SWEEP=true + shift + fi + SPOOL=''${1:-${lib.escapeShellArg runtimeRoutingDir}} + OUT=''${2:-${lib.escapeShellArg routingRulesDir}} + umask 022 + ${coreutils}/mkdir -p "$OUT/rs" "$OUT/dns" + ${coreutils}/chmod 0755 "$OUT" "$OUT/rs" "$OUT/dns" + exec 9> "$OUT/.lock" + ${pkgs.util-linux}/bin/flock 9 + + SRC='{}' + if [ -f "$SPOOL/rules.json" ] && [ ! -L "$SPOOL/rules.json" ]; then + SRC=$(${coreutils}/dd if="$SPOOL/rules.json" iflag=nofollow,nonblock,fullblock bs=4M count=1 status=none 2>/dev/null) || SRC='{}' + fi + # Slurped: an empty file, or several documents, is no rules rather than no output. + if ! RULES=$(${jq} -c -s -f ${renderJq} <<< "$SRC" 2>/dev/null); then + echo "proxy-suite: $SPOOL/rules.json is not valid JSON; no runtime routing rules apply" >&2 + RULES='[]' + fi + + # Renamed in, and only when it changed: sing-box reloads a rule set on every new file. + _put() { + cat > "$1.tmp" + ${coreutils}/chmod 644 "$1.tmp" + if ${pkgs.diffutils}/bin/cmp -s "$1.tmp" "$1"; then + rm -f "$1.tmp" + else + mv -f "$1.tmp" "$1" + fi + } + printf '%s\n' "$RULES" | _put "$OUT/rules.json" + KEEP=" " + while IFS=$'\t' read -r NAME SET DNS; do + printf '%s\n' "$SET" | _put "$OUT/rs/$NAME.json" + printf '%s\n' "$DNS" | _put "$OUT/dns/$NAME.json" + KEEP="$KEEP$NAME.json " + done < <(${jq} -r '.[] + | [.name, + ({version: 1, rules: ([if .domains != [] then {domain_suffix: .domains} else empty end] + + [if .ips != [] then {ip_cidr: .ips} else empty end])} | tojson), + ({version: 1, rules: [if .domains != [] then {domain_suffix: .domains} else empty end]} | tojson)] + | @tsv' <<< "$RULES") + if [ "$SWEEP" = true ]; then + for F in "$OUT"/rs/*.json "$OUT"/dns/*.json; do + [ -e "$F" ] || continue + case "$KEEP" in + *" ''${F##*/} "*) ;; + *) rm -f "$F" ;; + esac + done + fi + ${jq} -c '${ + if pureXrayEnabled then + "map(select(.disabled | not))" + else + "map(select(.disabled | not) | del(.domains, .ips))" + }' <<< "$RULES" | _put "$OUT/structure" + ''; + + # The backends whose config holds the rules, with their runtime directories. + consumers = [ + { + unit = "proxy-suite-socks"; + dir = "${constants.runtimeDir}/proxy-suite-socks"; + } + { + unit = "proxy-suite-tun"; + dir = "${constants.runtimeDir}/proxy-suite-tun"; + } + { + unit = "proxy-suite-per-app-tun"; + dir = "${constants.runtimeDir}/proxy-suite-per-app-tun"; + } + ]; + + # proxy-suite-routing-apply, after every `proxy rules` change: a backend restarts only when + # its config would change, the structure it started from (startBlock) no longer the one now. + apply = pkgs.writeShellScript "proxy-suite-core" '' + set -euo pipefail + ${render} + ${lib.concatMapStrings (c: '' + if ${constants.systemctl} is-active --quiet ${c.unit} \ + && ! ${pkgs.diffutils}/bin/cmp -s ${lib.escapeShellArg "${routingRulesDir}/structure"} ${lib.escapeShellArg "${c.dir}/routing-structure"}; then + ${constants.systemctl} restart ${c.unit} + fi + '') consumers} + ${render} --sweep + ''; + + # In a start script, after the outbounds: sets RUNTIME_SECTIONS_JSON (routing-compose.jq's + # $runtime) and USER_RULE_SETS_JSON, and writes $RUNTIME_DIR/routing-structure and + # routing-skipped.json, the rules left out and why (for proxy-ctl, which anyone may read). + startBlock = configFile: '' + RUNTIME_SECTIONS_JSON='[]' + USER_RULE_SETS_JSON='[]' + RUNTIME_ROUTING_SKIPPED='[]' + ${render} + cp ${lib.escapeShellArg "${routingRulesDir}/structure"} "$RUNTIME_DIR/routing-structure" + chmod 644 "$RUNTIME_DIR/routing-structure" + RUNTIME_ROUTING_JSON=$(cat ${lib.escapeShellArg "${routingRulesDir}/rules.json"}) + if ${jq} -e 'any(.[]; .disabled | not)' <<< "$RUNTIME_ROUTING_JSON" >/dev/null; then + MISSING_GEO_JSON=$(${jq} -r '[.[] | select(.disabled | not) + | (.geosites[] | "geosite-" + .), (.geoips[] | "geoip-" + .)] | unique[]' <<< "$RUNTIME_ROUTING_JSON" \ + | while IFS= read -r GEO; do + case "$GEO" in + geosite-*) [ -e ${lib.escapeShellArg geositeDir}/"$GEO.srs" ] || printf '%s\n' "$GEO" ;; + *) [ -e ${lib.escapeShellArg geoipDir}/"$GEO.srs" ] || printf '%s\n' "$GEO" ;; + esac + done | ${jq} -R . | ${jq} -cs .) + # Slurped: a large subscription's tags outgrow one argument. + ROUTING_TAGS_JSON=$(${jq} -c --slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \ + --slurpfile groups <(printf '%s' "''${GROUP_TAGS_JSON:-[]}") \ + '[($obs[0][]?, .outbounds[]?) | .tag? | strings] + $groups[0] | unique' ${configFile}) + CONVERTED=$(${jq} -c \ + --arg backend ${if pureXrayEnabled then "xray" else "sing-box"} \ + --slurpfile tags <(printf '%s' "$ROUTING_TAGS_JSON") \ + --argjson rule_sets ${lib.escapeShellArg (builtins.toJSON (map (rs: rs.name) ctx.ruleSets))} \ + --slurpfile missing_geo <(printf '%s' "$MISSING_GEO_JSON") \ + --arg dir ${lib.escapeShellArg routingRulesDir} \ + --arg geosite_dir ${lib.escapeShellArg geositeDir} \ + --arg geoip_dir ${lib.escapeShellArg geoipDir} \ + --argjson urltest ${lib.boolToString (pureXrayEnabled && ctx.selectionMode == "urltest")} \ + -f ${convertJq} <<< "$RUNTIME_ROUTING_JSON") + RUNTIME_SECTIONS_JSON=$(${jq} -c '.sections' <<< "$CONVERTED") + USER_RULE_SETS_JSON=$(${jq} -c '.rule_sets' <<< "$CONVERTED") + RUNTIME_ROUTING_SKIPPED=$(${jq} -c '.skipped' <<< "$CONVERTED") + ${jq} -r '.[] | "proxy-suite: routing rule \(.name) left out: \(.why)"' <<< "$RUNTIME_ROUTING_SKIPPED" >&2 + fi + printf '%s\n' "$RUNTIME_ROUTING_SKIPPED" > "$RUNTIME_DIR/routing-skipped.json.tmp" + chmod 644 "$RUNTIME_DIR/routing-skipped.json.tmp" + mv -f "$RUNTIME_DIR/routing-skipped.json.tmp" "$RUNTIME_DIR/routing-skipped.json" + ''; +in +{ + inherit + render + apply + startBlock + composeJq + geositeDir + geoipDir + ; +} diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 817e16e..4b19268 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -187,6 +187,8 @@ let backendJqFilterFile = pkgs.writeText "proxy-suite-core" backendJqFilter; startScripts = import ./start-scripts.nix { ctx = sctx; }; + routingRuntime = import ./script-blocks/routing-runtime.nix { ctx = sctx; }; + applyRoutingScript = routingRuntime.apply; inherit (startScripts) startSocks startTun startPerAppTun; proxyInboundsScripts = import ./proxy-inbounds-scripts.nix { ctx = sctx; }; @@ -240,6 +242,7 @@ in proxyInboundsSubscriptionsFile routeModeStateFile setRouteModeScript + applyRoutingScript pinOutboundScript reloadOutboundsScript subscriptionUpdateScript diff --git a/modules/proxy-suite/service/start-scripts.nix b/modules/proxy-suite/service/start-scripts.nix index 76f1650..b7ff659 100644 --- a/modules/proxy-suite/service/start-scripts.nix +++ b/modules/proxy-suite/service/start-scripts.nix @@ -49,6 +49,7 @@ let inherit (constants) serviceUser ifPrivileged; }; autoProxyMigrate = import ../autoproxy-migrate.nix { inherit pkgs; }; + routingRuntime = import ./script-blocks/routing-runtime.nix { inherit ctx; }; # Who reads the probe listeners' login (`proxy outbounds test`, `proxy auto probe`). # Local proxy auth with userControl off keeps its group as before. probeLoginMainGroup = @@ -62,35 +63,18 @@ let userControlGroup = lib.escapeShellArg userControlCfg.group; chgrp = "${pkgs.coreutils}/bin/chgrp"; - # Every route mode is the same four assignments over one jq program on the rule buckets. + # What a route mode decides beyond which rule buckets it keeps (routing-compose.jq): the + # final outbound, and the DNS server for names no rule takes. routeModeArms = [ { mode = "blacklist"; final = "proxy"; dns = "remote"; - rules = '' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .block - + .direct - + .safetyDirect - + .proxyGeo - ''; } { mode = "whitelist"; final = "direct"; dns = "local"; - rules = '' - .common - + (.custom | map(.entries) | add // []) - + .proxyPrimary - + .block - + .direct - + .safetyDirect - + .proxyGeo - ''; } { # Only the proxy and block lists are kept: everything else follows the final action. @@ -98,31 +82,18 @@ let final = "proxy"; dns = "remote"; clearDns = true; - rules = '' - .common - + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) - + .proxyPrimary - + .block - + .safetyDirect - + .proxyGeo - ''; } { mode = "all-bypass"; final = "direct"; dns = "local"; clearDns = true; - rules = '' - .common - + (.custom | map(select(.category == "block") | .entries) | add // []) - + .block - + .safetyDirect - ''; } ]; + # The configured routing.default as a mode: runtime rules compose the route without an + # override, and the result is the configuration's own order with theirs among it. + defaultRouteMode = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist"; - # Written out line by line: the block lands inside a `case`, where the indentation of an - # interpolated multi-line value would otherwise be lost. mkRouteModeArm = arm: lib.concatStringsSep "\n" ( @@ -133,14 +104,7 @@ let " ROUTE_MODE_ACTIVE=true" ] ++ lib.optional (arm.clearDns or false) " CLEAR_DNS_RULES=true" - ++ [ " ROUTE_RULES_JSON=$(${jq} -c '" ] - ++ map (line: if line == "" then "" else " ${line}") ( - lib.splitString "\n" (lib.removeSuffix "\n" arm.rules) - ) - ++ [ - " ' \"${routeModeRulesFile}\")" - " ;;" - ] + ++ [ " ;;" ] ); routeModeCaseBlock = '' @@ -154,6 +118,27 @@ let esac ''; + # The route, once a mode or a runtime rule calls for one: the buckets and runtime sections + # in priority order, and the DNS mirror composed alike. + composeRouteBlock = '' + if [ "$ROUTE_MODE_ACTIVE" != true ] && [ "$RUNTIME_SECTIONS_JSON" != '[]' ]; then + case ${defaultRouteMode} in${ + lib.concatMapStrings (arm: "\n" + mkRouteModeArm arm) ( + lib.filter (arm: arm.mode == defaultRouteMode) routeModeArms + ) + } + esac + fi + if [ "$ROUTE_MODE_ACTIVE" = true ]; then + COMPOSED_ROUTE_JSON=$(${jq} -c --arg mode "''${ROUTE_MODE:-${defaultRouteMode}}" \ + --slurpfile runtime <(printf '%s' "$RUNTIME_SECTIONS_JSON") \ + -f ${routingRuntime.composeJq} "${routeModeRulesFile}") + ROUTE_RULES_JSON=$(${jq} -c '.rules' <<< "$COMPOSED_ROUTE_JSON") + ROUTE_DNS_JSON=$(${jq} -c '.dns' <<< "$COMPOSED_ROUTE_JSON") + STATIC_DNS_COUNT=$(${jq} '.staticDnsCount' <<< "$COMPOSED_ROUTE_JSON") + fi + ''; + writeProxychainsConfigBlock = '' # proxychains reads its config by words: a password with whitespace in it would come out # as another field, or another line. None then, and proxy-ctl says why. @@ -219,6 +204,8 @@ let ROUTE_FINAL="" DNS_FINAL="" ROUTE_RULES_JSON='[]' + ROUTE_DNS_JSON=null + STATIC_DNS_COUNT=0 ROUTE_MODE_ACTIVE=false CLEAR_DNS_RULES=false ${hybridRuntimeHelpersBlock routingMark xraySidecarPort xrayDnsBridgePort} @@ -245,6 +232,10 @@ let ${mkOutboundScript routingMark} ${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"} + # Routing rules added at runtime, which name outbounds: after them. + ${routingRuntime.startBlock configFile} + ${composeRouteBlock} + # autoProxy: a loopback listener and a learned rule-set per exit, generated here # because subscription tags only exist at runtime. PROBE_INBOUNDS_JSON='[]' @@ -459,6 +450,9 @@ let } \ --argjson route_enabled "$ROUTE_MODE_ACTIVE" \ --slurpfile route_rules <(printf '%s' "$ROUTE_RULES_JSON") \ + --slurpfile route_dns <(printf '%s' "$ROUTE_DNS_JSON") \ + --argjson static_dns_count "$STATIC_DNS_COUNT" \ + --slurpfile user_rule_sets <(printf '%s' "$USER_RULE_SETS_JSON") \ --arg route_final "$ROUTE_FINAL" \ --arg dns_final "$DNS_FINAL" \ --argjson clear_dns_rules "$CLEAR_DNS_RULES" \ diff --git a/modules/proxy-suite/service/units.nix b/modules/proxy-suite/service/units.nix index 3e054c4..42513ce 100644 --- a/modules/proxy-suite/service/units.nix +++ b/modules/proxy-suite/service/units.nix @@ -782,6 +782,21 @@ let }; }; } + { + enable = proxyEnabled; + name = "proxy-suite-routing-apply"; + value = mkOneshotService { + description = "Apply proxy-suite routing rules added at runtime"; + execStart = scripts.applyRoutingScript; + # Root, over the spool the routing scope writes: it renders the rules into the state + # directory and restarts the backends whose config they change. + stateDirectory = "proxy-suite"; + extraServiceConfig = { + RemainAfterExit = false; + } + // spoolReaderSandbox [ ]; + }; + } { enable = proxyEnabled; name = "proxy-suite-outbound-pin@"; diff --git a/nix/checks/module-suite.nix b/nix/checks/module-suite.nix index 6dcded0..768e1ae 100644 --- a/nix/checks/module-suite.nix +++ b/nix/checks/module-suite.nix @@ -80,6 +80,15 @@ let ; }; + runtimeRoutingChecks = import ./runtime-routing.nix { + inherit + checkLib + pkgs + minimalProxyCtlWrapper + minimalProxyCtlScript + ; + }; + subscriptionChecks = import ./subscriptions.nix { inherit checkLib; inherit @@ -344,6 +353,7 @@ let ++ guiChecks.assertions ++ subscriptionChecks.assertions ++ routeModeChecks.assertions + ++ runtimeRoutingChecks.assertions ++ optionTypeChecks.assertions ++ perAppRoutingChecks.assertions ++ perAppRoutingAwgChecks.assertions @@ -356,6 +366,7 @@ in amneziawg-unit-scripts = amneziaWgChecks.unitScripts; xray-jq-filter-runtime = xrayBackendChecks.runtime; tor-guard-runtime = torChecks.runtime; + runtime-routing = runtimeRoutingChecks.runtime; per-app-zapret-runtime = perAppRoutingChecks.runtime; zapret-hostlist-rules = zapretChecks.rules; zapret2-config = zapret2Checks.runtime; diff --git a/nix/checks/runtime-routing.nix b/nix/checks/runtime-routing.nix new file mode 100644 index 0000000..0c7a8a2 --- /dev/null +++ b/nix/checks/runtime-routing.nix @@ -0,0 +1,169 @@ +# Routing rules added at runtime (`proxy-ctl proxy rules`): the units, spool and environment +# they need, the configuration's sections proxy-ctl lists, and (runtime) the rules composed into +# real configs, which the backends then accept. +{ + checkLib, + pkgs, + minimalProxyCtlWrapper, + minimalProxyCtlScript, +}: + +let + inherit (checkLib) + ok + evalProxySuite + baseModule + mkRouteModeRules + shellValueByPrefix + startScript + unitScript + ; + inherit (pkgs) lib; + fillTemplate = import ../../modules/proxy-suite/lib/fill-template.nix; + + routing = { + rules = [ + { + outbound = "primary"; + domains = [ "custom.example" ]; + } + ]; + proxy.domains = [ "proxied.example" ]; + block.domains = [ "blocked.example" ]; + }; + fixture = + backend: + evalProxySuite [ + baseModule + { + services.proxy-suite = { + proxy = { + backend = lib.mkForce backend; + inherit routing; + }; + userControl = { + enable = true; + scopes = [ "routing" ]; + }; + }; + } + ]; + singBoxFixture = fixture "sing-box"; + xrayFixture = fixture "xray"; + services = singBoxFixture.config.systemd.services; + execStart = f: f.config.systemd.services.proxy-suite-socks.serviceConfig.ExecStart; + socksScript = startScript singBoxFixture; + applyScript = unitScript singBoxFixture "proxy-suite-routing-apply"; + buckets = mkRouteModeRules singBoxFixture; + polkitRules = singBoxFixture.config.security.polkit.extraConfig; + sections = (checkLib.mkRouting singBoxFixture).routingSections; + + # The inbounds' guard, alone: where it lands around runtime direct rules. + guardFilter = pkgs.writeText "proxy-suite-runtime-routing-guard.jq" ( + import ../../modules/proxy-suite/service/script-blocks/backend-jq-filter.nix { + inherit lib; + pureXrayEnabled = false; + selectionMode = "first"; + proxyInboundsGuardPrivate = true; + } + ); + + runtime = + pkgs.runCommand "proxy-suite-runtime-routing-check" + { + nativeBuildInputs = [ + pkgs.jq + pkgs.gnugrep + ]; + } + ( + fillTemplate ./runtime-routing/compose.template.sh { + singBoxStart = execStart singBoxFixture; + xrayStart = execStart xrayFixture; + singBox = "${singBoxFixture.config.services.proxy-suite.proxy.singBox.package}/bin/sing-box"; + xray = "${xrayFixture.config.services.proxy-suite.proxy.xray.package}/bin/xray"; + xrayAssets = "${xrayFixture.config.services.proxy-suite.geodata.xray.assets}/share/v2ray"; + inherit guardFilter; + } + ); +in +{ + inherit runtime; + assertions = [ + # proxy-ctl reads the configuration's sections, the spool and the rendered copy, and checks + # geosites against the geodata the backend would load. + ( + assert + shellValueByPrefix minimalProxyCtlWrapper "export RUNTIME_ROUTING_DIR=" + == "/var/lib/proxy-suite/routing.d"; + assert + shellValueByPrefix minimalProxyCtlWrapper "export ROUTING_RULES_DIR=" + == "/var/lib/proxy-suite/routing"; + assert lib.hasPrefix "/nix/store/" ( + shellValueByPrefix minimalProxyCtlWrapper "export ROUTING_RULES_FILE=" + ); + assert lib.hasSuffix "/share/sing-box/rule-set" ( + shellValueByPrefix minimalProxyCtlWrapper "export GEODATA_GEOSITE_DIR=" + ); + assert lib.hasInfix "proxy rules add " minimalProxyCtlScript; + true + ) + + # The sections, at the priorities runtime rules sort among, with the tags as written. + (ok ( + map (s: s.id) sections == [ + "rules" + "proxy" + "block" + "direct" + "proxyGeo" + ] + && + map (s: s.priority) sections == [ + 100 + 200 + 300 + 400 + 500 + ] + && (builtins.head (builtins.head sections).entries).target == "primary" + && (builtins.head (builtins.elemAt sections 2).entries).domains == [ "blocked.example" ] + )) + + # The DNS mirror by section adds up to the configuration's own, in its order. + (ok ( + lib.concatMap (c: c.dns) buckets.custom + ++ buckets.dns.proxyPrimary + ++ buckets.dns.direct + ++ buckets.dns.proxyGeo == (checkLib.mkRouting singBoxFixture).singBoxDnsRules + )) + + # The apply unit: root, over the routing scope's spool, which polkit lets that scope start. + ( + let + apply = services.proxy-suite-routing-apply.serviceConfig; + in + assert apply.RemainAfterExit == false; + assert apply.ProtectSystem == "strict"; + assert apply.StateDirectory == "proxy-suite"; + assert lib.hasInfix "systemctl restart proxy-suite-socks" ( + builtins.replaceStrings [ "\n" ] [ " " ] applyScript + ); + assert lib.hasInfix "/run/proxy-suite-tun/routing-structure" applyScript; + assert lib.hasInfix "proxy-suite-routing-apply" polkitRules; + assert builtins.elem "d /var/lib/proxy-suite/routing.d 2770 root proxy-suite -" + singBoxFixture.config.systemd.tmpfiles.rules; + true + ) + + # Every start renders the spool and composes the route, the runtime rules among the + # configuration's, before the filter. + ( + assert lib.hasInfix "routing-convert.jq" socksScript; + assert lib.hasInfix "routing-compose.jq" socksScript; + assert lib.hasInfix "--slurpfile user_rule_sets" socksScript; + assert lib.hasInfix ''"$RUNTIME_DIR/routing-structure"'' socksScript; + true + ) + ]; +} diff --git a/nix/checks/runtime-routing/compose.template.sh b/nix/checks/runtime-routing/compose.template.sh new file mode 100644 index 0000000..72331cd --- /dev/null +++ b/nix/checks/runtime-routing/compose.template.sh @@ -0,0 +1,188 @@ +# Runtime routing rules through the real generated programs: the start script's convert and +# compose steps, then the backend filter, over a spool with good and bad entries; the result +# through the backend's own check. Paths are read out of the start script, as it runs them. +set -eu +export HOME=$PWD + +# $1 start script: the store paths it hands jq. +paths() { + START=$1 + FILTER=$(grep -o 'BACKEND_JQ_FILTER=[^ ]*' "$START" | head -n 1 | cut -d= -f2) + CONFIG=$(grep -o '"/nix/store/[a-z0-9]*-proxy-suite-core" > "$RUNTIME_DIR/config.json"' "$START" | grep -o '/nix/store/[a-z0-9]*-proxy-suite-core') + BUCKETS=$(grep -o 'routing-compose.jq "/nix/store/[^"]*' "$START" | grep -o '/nix/store/.*') + CONVERT=$(grep -o '/nix/store/[^ ]*routing-convert.jq' "$START" | head -n 1) + COMPOSE=$(grep -o '/nix/store/[^ ]*routing-compose.jq' "$START" | head -n 1) + GEOSITE_DIR=$(grep -o -- '--arg geosite_dir [^ ]*' "$START" | head -n 1 | cut -d' ' -f3) + GEOIP_DIR=$(grep -o -- '--arg geoip_dir [^ ]*' "$START" | head -n 1 | cut -d' ' -f3) + URLTEST=$(grep -o -- '--argjson urltest [a-z]*' "$START" | head -n 1 | cut -d' ' -f3) + BACKEND=$(grep -o -- '--arg backend [a-z-]*' "$START" | head -n 1 | cut -d' ' -f3) + for v in FILTER CONFIG BUCKETS CONVERT COMPOSE GEOSITE_DIR GEOIP_DIR URLTEST BACKEND; do + if [ -z "$(eval "printf %s \"\$$v\"")" ]; then + echo "no $v in $START" >&2 + exit 1 + fi + done +} + +# The spool as a member might leave it: a name twice, a path for a name, junk in the lists. +cat > spool.json <<'JSON' +{"rules": [ + {"name": "bank", "target": "direct", "priority": 50, "domains": [".Bank.Example", "bad domain"], + "ips": ["192.0.2.1", "nope"], "geosites": ["category-gov-ru", "../x"]}, + {"name": "bank", "target": "proxy"}, + {"name": "../evil", "target": "proxy"}, + {"name": "ads", "target": "block", "priority": 10, "domains": ["ads2.example"]}, + {"name": "work", "target": "primary", "priority": 450, "domains": ["work.example"], + "ips": ["198.51.100.0/24", "999.1.1.1", "198.51.100.1/33", "010.0.0.1", "1::2::3"]}, + {"name": "gone", "target": "removed-outbound", "domains": ["x.example"]}, + {"name": "nogeo", "target": "proxy", "geosites": ["no-such-list"]}, + {"name": "empty", "target": "proxy", "priority": 250}, + {"name": "off", "target": "proxy", "disabled": true, "domains": ["off.example"]} +]} +JSON +# The render script root runs, as the start script calls it, into ./routing. +RENDER=$(grep -A1 "^RUNTIME_ROUTING_SKIPPED='\[\]'" @singBoxStart@ | tail -n 1) +mkdir spool +cp spool.json spool/rules.json +mkdir -p routing/rs +echo '{}' > routing/rs/old.json +"$RENDER" "$PWD/spool" "$PWD/routing" +cp routing/rules.json rendered.json +jq -e ' + map(.name) == ["ads", "bank", "gone", "nogeo", "off", "empty", "work"] + and (.[] | select(.name == "bank") | .domains == ["bank.example"] and .ips == ["192.0.2.1/32"] + and .geosites == ["category-gov-ru"] and .target == "direct") +' rendered.json > /dev/null +# A rule set per rule, domains and addresses for routing, domains alone for lookups; an address +# the backends would refuse (and with it the whole start) is dropped. +jq -e '.rules == [{domain_suffix: ["work.example"]}, {ip_cidr: ["198.51.100.0/24"]}]' routing/rs/work.json > /dev/null +jq -e '.rules == [{domain_suffix: ["work.example"]}]' routing/dns/work.json > /dev/null +jq -e '.rules == []' routing/rs/empty.json > /dev/null +# What restarts the backends: everything but the domains and addresses of enabled rules. +jq -e --slurpfile r rendered.json '. == ($r[0] | map(select(.disabled | not) | del(.domains, .ips)))' routing/structure > /dev/null +# A rule gone: its rule set stays until apply sweeps, once the backends restarted. +[ -e routing/rs/old.json ] +"$RENDER" --sweep "$PWD/spool" "$PWD/routing" +[ ! -e routing/rs/old.json ] && [ -e routing/rs/work.json ] +# Only a change is renamed in: sing-box reloads a rule set on every new file. +before=$(stat -c %i routing/rs/work.json) +"$RENDER" "$PWD/spool" "$PWD/routing" +[ "$(stat -c %i routing/rs/work.json)" = "$before" ] +# A member's symlink, what is not JSON, an empty file or two documents are no rule at all, and +# no failure. +mkdir bad-link bad-json bad-empty bad-two +ln -s "$PWD/spool/rules.json" bad-link/rules.json +echo 'not json' > bad-json/rules.json +: > bad-empty/rules.json +cat spool.json spool.json > bad-two/rules.json +for spool in bad-link bad-json bad-empty bad-two; do + "$RENDER" "$PWD/$spool" "$PWD/out-$spool" + jq -e '. == []' "out-$spool/rules.json" > /dev/null +done + +# $1 start script, $2 mode ("": none), $3 the outbounds the start script would add, $4 out. +compose() { + paths "$1" + MODE=$2 OBS=$3 OUT=$4 + MISSING=$(jq -r '[.[] | select(.disabled | not) | (.geosites[] | "geosite-" + .), (.geoips[] | "geoip-" + .)] | unique[]' rendered.json \ + | while read -r geo; do + case "$geo" in + geosite-*) [ -e "$GEOSITE_DIR/$geo.srs" ] || printf '%s\n' "$geo" ;; + *) [ -e "$GEOIP_DIR/$geo.srs" ] || printf '%s\n' "$geo" ;; + esac + done | jq -R . | jq -cs .) + TAGS=$(jq -c --argjson obs "$OBS" '[($obs[]?, .outbounds[]?) | .tag? | strings] | unique' "$CONFIG") + jq -c --arg backend "$BACKEND" --slurpfile tags <(echo "$TAGS") --argjson rule_sets '[]' \ + --slurpfile missing_geo <(echo "$MISSING") --arg dir "$PWD/routing" --arg geosite_dir "$GEOSITE_DIR" \ + --arg geoip_dir "$GEOIP_DIR" --argjson urltest "$URLTEST" -f "$CONVERT" rendered.json > converted.json + jq -c --arg mode "${MODE:-blacklist}" --slurpfile runtime <(jq -c .sections converted.json) -f "$COMPOSE" "$BUCKETS" > composed.json + FINAL=proxy DNS_FINAL=remote CLEAR=false + case "$MODE" in + whitelist) FINAL=direct DNS_FINAL=local ;; + all-proxy) CLEAR=true ;; + all-bypass) FINAL=direct DNS_FINAL=local CLEAR=true ;; + esac + jq --slurpfile obs <(echo "$OBS") --slurpfile probe_inbounds <(echo '[]') --slurpfile probe_pin_rules <(echo '[]') \ + --slurpfile autoproxy_rule_sets <(echo '[]') --slurpfile autoproxy_rules <(echo '[]') \ + --argjson auth_enabled false --arg user "" --arg password "" \ + --argjson route_enabled "${ENABLED:-true}" --slurpfile route_rules <(jq -c .rules composed.json) \ + --slurpfile route_dns <(jq -c .dns composed.json) --argjson static_dns_count "$(jq .staticDnsCount composed.json)" \ + --slurpfile user_rule_sets <(jq -c .rule_sets converted.json) \ + --arg route_final "$FINAL" --arg dns_final "$DNS_FINAL" --argjson clear_dns_rules "$CLEAR" \ + --arg xray_loglevel "" --arg xray_single_proxy_tag "" --slurpfile xray_selectable <(echo '[]') \ + --argjson xray_tun_dns_runtime false --argjson host_addresses '[]' \ + -f "$FILTER" "$CONFIG" > "$OUT" +} + +# --- sing-box -------------------------------------------------------------------------------- +SB_OBS='[{"type":"selector","tag":"proxy","outbounds":["primary"]},{"type":"http","tag":"primary","server":"proxy.example.com","server_port":8080}]' +compose @singBoxStart@ "" "$SB_OBS" none.json +# Left out, and why: an outbound that is gone, a geosite this host does not have. +jq -e 'map(.name) == ["gone", "nogeo"] and (.[0].why | test("removed-outbound"))' <(jq -c .skipped converted.json) > /dev/null +jq -e ' + [.route.rules[] | (.rule_set[0]? // .domain_suffix[0]? // .action // (.ip_is_private | tostring))] as $order + | def at($x): $order | index($x); + # Runtime ads (10) and bank (50) ahead of the configuration'"'"'s rules (100), empty (250) after + # its proxy lists (200), work (450) after the direct ones (400); disabled off nowhere. + at("user:ads") < at("user:bank") and at("user:bank") < at("custom.example") + and at("proxied.example") < at("user:empty") and at("user:empty") < at("blocked.example") + and at("true") < at("user:work") and at("user:off") == null and at("user:gone") == null + # The rule sets, each once: geodata the configuration has too is not declared twice. + and ([.route.rule_set[].tag] | length == (unique | length)) + and ([.route.rule_set[] | select(.tag == "user:bank" or .tag == "user-dns:bank")] | length == 2) + and any(.route.rule_set[]; .tag == "geosite-category-gov-ru") + # Lookups follow: bank locally, ahead of the configuration'"'"'s; a block rule none. + and ([.dns.rules[] | .rule_set[0]? // .domain_suffix[0]?] as $dns + | ($dns | index("user-dns:bank")) < ($dns | index("custom.example")) + and ($dns | index("user-dns:ads")) == null and ($dns | index("user-dns:work")) != null) + and (.dns.rules[] | select(.rule_set[0]? == "user-dns:bank") | .server) == "local" +' none.json > /dev/null +@singBox@ check -c none.json +# Composed with no runtime rule, the route is the configuration's own, lookups too. +cp rendered.json full.json +echo '[]' > rendered.json +compose @singBoxStart@ "" "$SB_OBS" composed-default.json +ENABLED=false compose @singBoxStart@ "" "$SB_OBS" static.json +jq -e --slurpfile static static.json '.route == $static[0].route and .dns == $static[0].dns' composed-default.json > /dev/null +cp full.json rendered.json +for mode in whitelist all-proxy all-bypass; do + compose @singBoxStart@ "$mode" "$SB_OBS" "$mode.json" + @singBox@ check -c "$mode.json" +done +# all-proxy keeps no direct list, all-bypass nothing but the blocks. +jq -e '[.route.rules[].rule_set[0]?] | index("user:bank") == null and index("user:work") != null' all-proxy.json > /dev/null +jq -e '[.route.rules[].rule_set[0]?] | index("user:ads") != null and index("user:work") == null' all-bypass.json > /dev/null + +# --- xray ------------------------------------------------------------------------------------ +jq 'map(.ruleSets = [])' full.json > rendered.json +compose @xrayStart@ "" '[{"protocol":"freedom","tag":"primary"}]' xray.json +jq -e ' + [.routing.rules[].ruleTag] as $tags + | ($tags | index("user:bank")) < ($tags | index("user:work")) + and ($tags | index("user:work:ip")) == ($tags | index("user:work")) + 1 + and ($tags | index("dns-remote-bridge")) != null +' xray.json > /dev/null +XRAY_LOCATION_ASSET=@xrayAssets@ @xray@ run -test -c xray.json + +# --- the inbounds' guard --------------------------------------------------------------------- +# A runtime direct rule above the configuration's gets a guard of its own, for what it matches; +# the guard proper stays before the configuration's first direct rule. +echo '{"inbounds":[],"outbounds":[],"dns":{"rules":[]},"route":{"final":"proxy","rules":[ + {"action":"sniff"},{"rule_set":["user:bank"],"outbound":"direct"}, + {"domain_suffix":["proxied.example"],"outbound":"proxy"},{"domain_suffix":["ru"],"outbound":"direct"}]}}' | + jq --slurpfile obs <(echo '[]') --argjson auth_enabled false --arg user "" --arg password "" \ + --argjson route_enabled false --slurpfile route_rules <(echo '[]') \ + --arg route_final proxy --arg dns_final remote --argjson clear_dns_rules false \ + --slurpfile probe_inbounds <(echo '[]') --slurpfile autoproxy_rule_sets <(echo '[]') \ + --slurpfile autoproxy_rules <(echo '[]') --slurpfile probe_pin_rules <(echo '[]') \ + -f @guardFilter@ > guard.json +jq -e ' + .route.rules as $r + | ($r | map(.type? == "logical" and .action == "resolve" and .rules[-1].rule_set == ["user:bank"]) | index(true)) as $scoped + | ($r | map(.rule_set? == ["user:bank"]) | index(true)) as $bank + | ($r | map(.inbound? == ["mixed-in"] and .action == "resolve") | index(true)) as $guard + | ($r | map(.domain_suffix? == ["proxied.example"]) | index(true)) as $proxied + | ($r | map(.domain_suffix? == ["ru"]) | index(true)) as $ru + | $scoped < $bank and $proxied < $guard and $guard < $ru +' guard.json > /dev/null +touch "$out" diff --git a/pkgs/proxy-ctl/proxy_ctl.py b/pkgs/proxy-ctl/proxy_ctl.py index 7f79c15..fd955e9 100644 --- a/pkgs/proxy-ctl/proxy_ctl.py +++ b/pkgs/proxy-ctl/proxy_ctl.py @@ -13,6 +13,7 @@ import http.client import importlib import ipaddress import json +import math import os import re import shutil @@ -96,6 +97,18 @@ Changes and secrets need root or the userControl group. lower goes first; up/down renumbers the top level proxy mode [default|whitelist|blacklist|all-proxy|all-bypass] show or override the routing mode + proxy rules [list] routing rules, the configuration's and runtime ones, + in the order they are checked + proxy rules add [--name ] [--priority ] + send domains, addresses, geosite:x, geoip:x or ruleset:x + to proxy, direct, block or an outbound; no --name: the + rule named after the target, extended (priority 50: + ahead of the configuration's, at 100 to 500) + proxy rules matches add|rm + proxy rules target + proxy rules priority |up|down + lower goes first; up/down moves past the next row + proxy rules disable|enable|rm proxy subs [list|update] subscriptions; update refetches them proxy subs add [tag] add a subscription (no tag: named after its host; -: stdin) proxy subs rm remove a runtime subscription @@ -755,6 +768,7 @@ COMPLETE = { "groups": "outbound groups", "priority": "the order the top level picks in", "mode": "show or override the routing mode", + "rules": "routing rules added at runtime", "subs": "subscription caches", "rulesets": "routing rule sets", "tun": "global TUN mode", @@ -841,6 +855,26 @@ COMPLETE = { } }, "proxy rulesets": {"words": {"list": "when each rule set was fetched", "update": "fetch the rule sets now"}}, + "proxy rules": { + "words": { + "list": "the routing rules in the order they are checked", + "add": "add a rule, or extend one: ", + "matches": "add or remove a rule's domains, addresses and lists", + "target": "where a rule sends what it matches", + "priority": "where a rule is checked: a number, up or down", + "disable": "keep a rule without applying it", + "enable": "apply a disabled rule again", + "rm": "remove a rule", + } + }, + "proxy rules add": { + "args": lambda: {**_names(RULE_TARGETS), **_outbound_choices(), **_group_choices()}, + "flags": {"--name": "the rule's name (default: the target)", "--priority": "where it is checked (default 50)"}, + }, + **{ + f"proxy rules {verb}": {"args": lambda: {r["name"]: f"-> {r['target']}" for r in _runtime_rules()}} + for verb in ("matches", "target", "priority", "disable", "enable", "rm") + }, "proxy subs link": {"args": lambda: _names(_sub_tags() + _runtime_tags("subscription")), "flags": {"--qr": "print a QR code"}}, "proxy subs rm": {"args": lambda: _names(_runtime_tags("subscription"))}, "proxy tun": {"words": TOGGLE}, @@ -1353,6 +1387,8 @@ def cmd_proxy(verb="status", *args): cmd_subscription(*args) elif verb == "rulesets": cmd_rulesets(*args) + elif verb == "rules": + cmd_rules(*args) elif verb in ("tun", "tproxy"): action = _flip(f"proxy-suite-{verb}", *args[:1]) _toggle(f"proxy-suite-{verb}", f"proxy {verb}", action) @@ -1367,7 +1403,7 @@ def cmd_proxy(verb="status", *args): elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"): cmd_proxy_auto(verb, *args) else: - usage("proxy [status|on|off|toggle|restart|outbounds|groups|priority|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]") + usage("proxy [status|on|off|toggle|restart|outbounds|groups|priority|pin|unpin|mode|rules|subs|rulesets|tun|tproxy|auto|config]") def cmd_outbounds(verb="list", *args): @@ -3201,6 +3237,433 @@ def cmd_rulesets(verb="list", *_): usage("proxy rulesets [list|update]") +# --- proxy rules: routing rules added at runtime ------------------------------ +# +# rules.json in the routing spool (RUNTIME_ROUTING_DIR), which userControl's groups with the +# routing scope write: {"rules": [{name, target, priority, disabled, domains, ips, geosites, +# geoips, ruleSets}]}. proxy-suite-routing-apply renders it for the backends (routing-render.jq +# keeps what it can check) and restarts those whose config it changes; a rule's domains and +# addresses alone reach a running sing-box without one. A rule's priority places it among the +# configuration's sections ("sections" in ROUTING_RULES_FILE, 100 to 500): lower goes first, +# and a runtime rule goes first among equals. + +ROUTING_APPLY_UNIT = "proxy-suite-routing-apply" +RULE_DEFAULT_PRIORITY = 50 +RULE_PRIORITY_LIMIT = 1_000_000 +RULE_MATCH_KINDS = ("domains", "ips", "geosites", "geoips", "ruleSets") +# What a match spells, as `rules add` takes it and `rules list` prints it back. +RULE_MATCH_PREFIXES = {"geosite:": "geosites", "geoip:": "geoips", "ruleset:": "ruleSets"} +RULE_MATCH_SPELLING = {"domains": "", "ips": "", "geosites": "geosite:", "geoips": "geoip:", "ruleSets": "ruleset:"} +RULE_DOMAIN = re.compile(r"[a-z0-9_-]+(\.[a-z0-9_-]+)*") +RULE_GEO = re.compile(r"[A-Za-z0-9!@._-]{1,64}") +RULE_TARGETS = ("proxy", "direct", "block") +# As much as routing-render.jq reads of the spool. +RULES_MAX_BYTES = 4 * 1024 * 1024 + + +def _rules_path(): + return os.path.join(env("RUNTIME_ROUTING_DIR", f"{state_dir()}/routing.d"), "rules.json") + + +def _rules_rendered_path(): + return os.path.join(env("ROUTING_RULES_DIR", f"{state_dir()}/routing"), "rules.json") + + +def _rule_target_ok(target): + # As routing-render.jq: no control character ([[:cntrl:]]). + return 1 <= len(target) <= 128 and not re.search(r"[\x00-\x1f\x7f-\x9f]", target) + + +def _rule_normal(rule): + """One rule with every field there and of its type, or None for what is not a rule: what + routing-render.jq keeps, so the list shows what root applies.""" + if not isinstance(rule, dict) or not isinstance(rule.get("name"), str) or not isinstance(rule.get("target"), str): + return None + if not _rule_name_ok(rule["name"]) or not _rule_target_ok(rule["target"]): + return None + priority = rule.get("priority") + # JSON as Python reads it has Infinity and NaN too. + if isinstance(priority, (int, float)) and not isinstance(priority, bool) and not math.isnan(priority): + priority = max(-RULE_PRIORITY_LIMIT, min(RULE_PRIORITY_LIMIT, priority)) + priority = math.floor(priority) + else: + priority = RULE_DEFAULT_PRIORITY + out = { + "name": rule["name"], + "target": rule["target"], + "priority": priority, + "disabled": rule.get("disabled") is True, + } + for kind in RULE_MATCH_KINDS: + values = rule.get(kind) + out[kind] = [v for v in values if isinstance(v, str)] if isinstance(values, list) else [] + return out + + +def _rules_sorted(rules): + return sorted(rules, key=lambda r: (r["priority"], r["name"])) + + +def _runtime_rules(writing=False): + """The runtime rules, in match order: as saved, or, where the spool is the routing scope's + alone, as root last applied them. writing: the spool or nothing.""" + path = _rules_path() + try: + data = json.loads(read_shared_text(path, RULES_MAX_BYTES)) + rules = data.get("rules") if isinstance(data, dict) else None + except FileNotFoundError: + rules = [] + except PermissionError: + if writing: + denied(path, "change") + rules = read_json_or(_rules_rendered_path(), []) + except (OSError, ValueError): + if writing: + die(f"{path} is not valid; fix or remove it first.") + rules = [] + # A name once, the first, as root reads it. + seen = {} + for rule in map(_rule_normal, rules if isinstance(rules, list) else []): + if rule and rule["name"] not in seen: + seen[rule["name"]] = rule + return _rules_sorted(seen.values()) + + +def _rules_save(rules): + path = _rules_path() + text = json.dumps({"rules": _rules_sorted(rules)}, indent=2, ensure_ascii=False) + "\n" + try: + _spool_write(path, text) + except OSError: + denied(path, "write") + + +def _routing_apply(): + if systemctl("start", f"{ROUTING_APPLY_UNIT}.service")[0]: + die(f"Saved, but applying it failed - see: proxy-ctl logs {ROUTING_APPLY_UNIT}") + + +def _routing_sections(): + """The configuration's routing, a section per priority: [{id, priority, label, entries}].""" + sections = read_json_or(env("ROUTING_RULES_FILE"), {}).get("sections") + return [s for s in sections if isinstance(s, dict) and isinstance(s.get("priority"), int)] if isinstance(sections, list) else [] + + +def _routing_skipped(): + """{rule: why} for the rules the running proxy left out.""" + skipped = read_json_or(_runtime_file("routing-skipped.json"), []) + return {_s(x.get("name")): _s(x.get("why")) for x in skipped if isinstance(x, dict)} + + +def _rule_matches(rule, limit=None): + words = [f"{RULE_MATCH_SPELLING[kind]}{v}" for kind in RULE_MATCH_KINDS for v in rule.get(kind) or []] + if limit is not None and len(words) > limit: + return ", ".join(words[:limit]) + f" and {len(words) - limit} more" + return ", ".join(words) + + +def _section_empty(section): + # The direct section always holds the private ranges. + return section.get("id") != "direct" and not any( + e.get(kind) for e in section.get("entries") or [] if isinstance(e, dict) for kind in RULE_MATCH_KINDS + ) + + +def _routing_rows(): + """The routing in match order: the configuration's sections and the runtime rules, as rows + of {key, priority, name, target, matches, source, notes, runtime, disabled}.""" + skipped = _routing_skipped() + rows = [] + for rule in _runtime_rules(): + notes = "disabled" if rule["disabled"] else (f"left out: {skipped[rule['name']]}" if rule["name"] in skipped else "") + rows.append( + { + "key": f"rule:{rule['name']}", + "priority": rule["priority"], + "name": rule["name"], + "target": rule["target"], + "matches": _rule_matches(rule, 6) or "nothing yet", + "source": "runtime", + "notes": notes, + "runtime": True, + "disabled": rule["disabled"], + "order": 0, + } + ) + for section in _routing_sections(): + if _section_empty(section): + continue + entries = [e for e in section.get("entries") or [] if isinstance(e, dict)] + for n, entry in enumerate(entries): + matches = _rule_matches(entry, 6) + if not matches and section.get("id") != "direct": + continue + if section.get("id") == "direct": + matches = ", ".join(x for x in (matches, "private addresses") if x) + rows.append( + { + "key": f"config:{_s(section.get('id'))}:{n}", + "priority": section["priority"], + "name": _s(section.get("label") or section.get("id")), + "target": _s(entry.get("target") or ""), + "matches": matches, + "source": "config", + "notes": "", + "runtime": False, + "disabled": False, + "order": 1, + } + ) + # Stable: runtime rules in their order, then sections in theirs, at each priority. + rows.sort(key=lambda r: (r["priority"], r["order"])) + for r in rows: + del r["order"] + return rows + + +def _rule_name_ok(name): + return bool(RUNTIME_TAG.fullmatch(name)) and len(name) <= 64 + + +def _rule_match(word): + """(kind, value) of one match as typed: a domain (or a URL), an address or a CIDR, + geosite:NAME, geoip:NAME or ruleset:NAME.""" + for prefix, kind in RULE_MATCH_PREFIXES.items(): + if word.lower().startswith(prefix): + name = word[len(prefix) :] + if kind == "ruleSets": + declared = [_s(rs.get("name")) for rs in read_json_or(env("RULE_SETS_FILE"), []) if isinstance(rs, dict)] + if name not in declared: + die(f"No rule set named '{name}' in routing.ruleSets" + (f" (there are: {', '.join(declared)})." if declared else ".")) + return kind, name + if not RULE_GEO.fullmatch(name) or name.startswith("."): + die(f"Not a {prefix[:-1]} name: {name}") + directory = env("GEODATA_GEOSITE_DIR" if kind == "geosites" else "GEODATA_GEOIP_DIR") + if directory and os.path.isdir(directory) and not os.path.exists(os.path.join(directory, f"{prefix[:-1]}-{name}.srs")): + die(f"No {prefix[:-1]} named '{name}' in this host's geodata.") + return kind, name + try: + return "ips", str(ipaddress.ip_network(word, strict=False)) + except ValueError: + pass + host = word.split("://", 1)[1].split("/", 1)[0].rsplit("@", 1)[-1] if "://" in word else word + host = host.lower().lstrip(".") + if "://" in word: + host = re.sub(r":\d+$", "", host) + if RULE_DOMAIN.fullmatch(host) and len(host) <= 253: + return "domains", host + die(f"Not a domain, an address, or geosite:, geoip: or ruleset: something: {word}") + + +def _rule_check_target(target): + if target in RULE_TARGETS: + return + if not _rule_target_ok(target): + die(f"Not an outbound: {target!r}") + tags = set(_outbound_tags()) | set(_outbound_groups()) + if not tags: + print(f"Cannot check '{target}' until the proxy has run; a rule naming no outbound is left out.", file=sys.stderr) + elif target not in tags: + die(f"Unknown outbound or group: {target} (or proxy, direct, block)") + + +def _rule_find(rules, name): + for rule in rules: + if rule["name"] == name: + return rule + die(f"No runtime routing rule named '{name}'. See: proxy-ctl proxy rules") + + +def _rule_parse_priority(value): + if not re.fullmatch(r"-?[0-9]+", value or "") or abs(int(value)) > RULE_PRIORITY_LIMIT: + die(f"A priority is a whole number, -{RULE_PRIORITY_LIMIT} to {RULE_PRIORITY_LIMIT}: {value}") + return int(value) + + +def _rules_edit(change): + """change(rules) under the spool's lock, saved and applied. It returns what to print.""" + path = _rules_path() + with _file_lock(path): + rules = _runtime_rules(writing=True) + message = change(rules) + _rules_save(rules) + _routing_apply() + print(message) + + +def _rules_move(rules, name, direction): + """Moves a rule one row up or down in the match order, past a runtime rule or a section of + the configuration, then numbers the runtime rules where it landed, 10 apart where they fit.""" + rows = [("rule", r["name"], r["priority"]) for r in rules] + rows += [("section", s.get("id"), s["priority"]) for s in _routing_sections() if not _section_empty(s)] + rows.sort(key=lambda r: (r[2], 0 if r[0] == "rule" else 1)) + order = [r[:2] for r in rows] + i = order.index(("rule", name)) + j = i - 1 if direction == "up" else i + 1 + if not 0 <= j < len(order): + return f"{name} is already {'first' if direction == 'up' else 'last'}." + order[i], order[j] = order[j], order[i] + priority = {r[:2]: r[2] for r in rows} + k = order.index(("rule", name)) + # The run of runtime rules it is in now, and the sections around it. + lo = k + while lo > 0 and order[lo - 1][0] == "rule": + lo -= 1 + hi = k + while hi + 1 < len(order) and order[hi + 1][0] == "rule": + hi += 1 + below = priority[order[lo - 1]] if lo > 0 else None + above = priority[order[hi + 1]] if hi + 1 < len(order) else None + run = order[lo : hi + 1] + # After a section: above its number. Before one: at most its number (runtime first). + if below is None and above is None: + numbers = [10 * (n + 1) for n in range(len(run))] + elif below is None: + numbers = [above - 10 * (len(run) - n) for n in range(len(run))] + elif above is None: + numbers = [below + 10 * (n + 1) for n in range(len(run))] + else: + step = min(10, (above - below) // len(run)) + if step < 1: + die(f"No room for {len(run)} rules between priorities {below} and {above}; set them by hand.") + numbers = [below + step * (n + 1) for n in range(len(run))] + by_name = {r["name"]: r for r in rules} + for (_, rule_name), number in zip(run, numbers, strict=True): + by_name[rule_name]["priority"] = number + return f"{name}: moved {direction}, priority {by_name[name]['priority']}" + + +def _rules_list(): + rows = _routing_rows() + if not rows: + print("No routing rules: everything goes to the final outbound.") + return + print("In the order they are checked; lower priority first, a runtime rule first among equals:") + width = max(len(r["name"]) for r in rows) + for r in rows: + notes = f" ({r['notes']})" if r["notes"] else "" + print(f" {r['priority']:>7} {r['name']:<{width}} {r['source']:<7} -> {r['target']}: {r['matches']}{notes}") + print(f"Then the final outbound ({_route_mode_label(_route_mode_current())}).") + + +def cmd_rules(verb="list", *args): + if not svc_exists("proxy-suite-socks"): + die("proxy is not enabled in this configuration.") + if verb == "list": + _rules_list() + elif verb == "add": + _rules_add(*args) + elif verb == "matches" and len(args) >= 3 and args[1] in ("add", "rm"): + _rules_matches(*args) + elif verb == "target" and len(args) == 2: + _rule_check_target(args[1]) + + def change(rules): + _rule_find(rules, args[0])["target"] = args[1] + return f"{args[0]}: -> {args[1]}" + + _rules_edit(change) + elif verb == "priority" and len(args) == 2: + name, value = args + + def change(rules): + rule = _rule_find(rules, name) + if value in ("up", "down"): + return _rules_move(rules, name, value) + rule["priority"] = _rule_parse_priority(value) + return f"{name}: priority {rule['priority']}" + + _rules_edit(change) + elif verb in ("disable", "enable") and len(args) == 1: + + def change(rules): + _rule_find(rules, args[0])["disabled"] = verb == "disable" + return f"{args[0]}: {verb}d" + + _rules_edit(change) + elif verb == "rm" and len(args) == 1: + + def change(rules): + rules.remove(_rule_find(rules, args[0])) + return f"Removed routing rule: {args[0]}" + + _rules_edit(change) + else: + usage( + "proxy rules [list] | add [--name ] [--priority ]" + " | matches add|rm | target " + " | priority |up|down | disable|enable | rm " + ) + + +def _rules_add(*args): + name, priority, words = None, None, [] + rest = list(args) + while rest: + word = rest.pop(0) + if word in ("--name", "--priority"): + if not rest: + usage(f"proxy rules add [{word} ]") + if word == "--name": + name = rest.pop(0) + else: + priority = _rule_parse_priority(rest.pop(0)) + else: + words.append(word) + if len(words) < 2: + usage("proxy rules add [--name ] [--priority ]") + target, matches = words[0], [_rule_match(w) for w in words[1:]] + _rule_check_target(target) + name = name or target + if not _rule_name_ok(name): + die(f"'{name}' cannot name a rule: letters, digits, dot, dash and underscore only; give one with --name.") + + def change(rules): + rule = next((r for r in rules if r["name"] == name), None) + if rule is None: + rule = {"name": name, "target": target, "priority": RULE_DEFAULT_PRIORITY if priority is None else priority, "disabled": False} + rule.update({kind: [] for kind in RULE_MATCH_KINDS}) + rules.append(rule) + verb = "Added" + elif rule["target"] != target: + die(f"Rule '{name}' sends to {rule['target']}, not {target}: name another with --name, or change it with: proxy-ctl proxy rules target {name} {target}") + else: + verb = "Extended" + if priority is not None: + rule["priority"] = priority + added = _rule_add_matches(rule, matches) + return f"{verb} routing rule {name} (priority {rule['priority']}) -> {target}: {', '.join(added) or 'nothing new'}" + + _rules_edit(change) + + +def _rule_add_matches(rule, matches): + added = [] + for kind, value in matches: + if value not in rule[kind]: + rule[kind].append(value) + added.append(f"{RULE_MATCH_SPELLING[kind]}{value}") + return added + + +def _rules_matches(name, op, *words): + matches = [_rule_match(w) for w in words] + + def change(rules): + rule = _rule_find(rules, name) + if op == "add": + done = _rule_add_matches(rule, matches) + else: + done = [] + for kind, value in matches: + if value in rule[kind]: + rule[kind].remove(value) + done.append(f"{RULE_MATCH_SPELLING[kind]}{value}") + return f"{name}: {'added' if op == 'add' else 'removed'} {', '.join(done) or 'nothing'}" + + _rules_edit(change) + + # --- proxy auto: reachability probe ------------------------------------------- # # Fetches a URL through one exit after another (direct first) and finds one @@ -4366,7 +4829,11 @@ def _where_sing_box(config, domain): hit = hit or next((f"domain_keyword {k}" for k in rule.get("domain_keyword") or [] if k in domain), "") hit = hit or next((f"domain_regex {r}" for r in rule.get("domain_regex") or [] if re.search(r, domain)), "") hit = hit or next( - (f"rule-set {t}" for t in rule.get("rule_set") or [] if _where_rule_set_match(rule_sets.get(t, {}), domain)), + ( + f"runtime rule {t.removeprefix('user:')}" if t.startswith("user:") else f"rule-set {t}" + for t in rule.get("rule_set") or [] + if _where_rule_set_match(rule_sets.get(t, {}), domain) + ), "", ) if hit: diff --git a/pkgs/proxy-ctl/proxy_gui.py b/pkgs/proxy-ctl/proxy_gui.py index 5ad48a0..48dc823 100644 --- a/pkgs/proxy-ctl/proxy_gui.py +++ b/pkgs/proxy-ctl/proxy_gui.py @@ -93,6 +93,7 @@ CSS = """ .status-chip.ok .chip-label, .status-chip.warn .chip-label, .status-chip.bad .chip-label { opacity: 0.8; } .summary { padding: 8px 14px 0 14px; } +.selector-bar { padding: 8px 14px 0 14px; } .filter-bar { padding: 8px 12px; } .row-count { font-feature-settings: "tnum"; } @@ -309,6 +310,20 @@ class Page(Gtk.Box): self.summary = Gtk.Label(xalign=0, wrap=True, selectable=True, visible=False, css_classes=["summary", "dim-label"]) + # The tab's one choice apart from its rows (Routing: the mode), above everything else, so + # it is there whatever the rows are. + self.selector_values = [] + self.selector_setting = False + self.selector_drop = None + if tab.selector: + self.selector_drop = Gtk.DropDown(model=Gtk.StringList(), valign=Gtk.Align.CENTER, tooltip_text=f"Shortcut: {display_key(tab.selector.key)}") + self.selector_drop.connect("notify::selected", self.on_selector_changed) + label = Gtk.Label(label=tab.selector.label, css_classes=["heading"], mnemonic_widget=self.selector_drop) + self.selector_bar = Gtk.Box(spacing=12, css_classes=["selector-bar"], visible=False) + self.selector_bar.append(label) + self.selector_bar.append(self.selector_drop) + self.append(self.selector_bar) + self.search = Gtk.SearchEntry(placeholder_text="Filter: words in any column, or column:value", hexpand=True) self.search.connect("search-changed", lambda _: self.refill()) self.search.connect("stop-search", self.on_stop_search) @@ -420,6 +435,7 @@ class Page(Gtk.Box): ("o", lambda *_: self.win.show_last_output()), ("r", lambda *_: self.win.app.reload(fresh_root=True)), ("Menu|F10", lambda *_: self.open_menu(None)), + *([(accelerator(self.tab.selector.key), lambda *_: self.open_selector())] if self.tab.selector else []), ): if trigger not in self.triggers(): controller.add_shortcut(Gtk.Shortcut(trigger=Gtk.ShortcutTrigger.parse_string(trigger), action=Gtk.CallbackAction.new(self.keyed(trigger, callback)))) @@ -464,10 +480,44 @@ class Page(Gtk.Box): # --- filling ------------------------------------------------------------------------ - def fill(self, rows, summary): + def fill(self, rows, summary, selector=None): self.rows, self.summary_text, self.loaded = rows, summary, True + self.fill_selector(selector) self.refill() + def fill_selector(self, state): + """The selector as read: its options and the current one, set without running anything.""" + if self.selector_drop is None: + return + self.selector_bar.set_visible(state is not None) + if state is None: + return + options, current = state + values = [v for v, _ in options] + self.selector_setting = True + try: + if values != self.selector_values: + self.selector_values = values + self.selector_drop.set_model(Gtk.StringList.new([label for _, label in options])) + if current in values and self.selector_drop.get_selected() != values.index(current): + self.selector_drop.set_selected(values.index(current)) + finally: + self.selector_setting = False + + def on_selector_changed(self, drop, _): + index = drop.get_selected() + if self.selector_setting or not 0 <= index < len(self.selector_values): + return + argv = model.selector_argv(self.tab, self.selector_values[index]) + if argv: + self.win.app.run_argv("run", argv, self.win) + + def open_selector(self): + if self.selector_drop is None or not self.selector_bar.get_visible(): + return False + self.selector_drop.grab_focus() + return self.selector_drop.activate() + def refill(self): rows, summary = self.rows, self.summary_text if text := self.search.get_text().strip(): @@ -929,7 +979,7 @@ class Window(Adw.ApplicationWindow): chip.append(Gtk.Label(label=value, css_classes=["chip-value"], ellipsize=Pango.EllipsizeMode.END)) self.status.append(chip) - def fill(self, states, visible, status, tab_id, rows, summary, stale=False): + def fill(self, states, visible, status, tab_id, rows, summary, stale=False, selector=None): # A read that came back empty after a good one keeps what is on screen: every tab # and row blinking out and back is worse than a banner saying the read failed. if stale: @@ -943,7 +993,7 @@ class Window(Adw.ApplicationWindow): if visible != self.shown(): self.show_tabs(visible) if tab_id in self.pages and tab_id in visible: - self.pages[tab_id].fill(rows, summary) + self.pages[tab_id].fill(rows, summary, selector) # --- acting ---------------------------------------------------------------------------------- @@ -1072,6 +1122,8 @@ class Window(Adw.ApplicationWindow): section = Adw.ShortcutsSection(title=page.tab.title) for key, label in model.key_labels(actions): section.add(Adw.ShortcutsItem(title=cap(label), accelerator=accelerator(key))) + if page.tab.selector: + section.add(Adw.ShortcutsItem(title=f"Choose the {page.tab.selector.label.lower()}", accelerator=accelerator(page.tab.selector.key))) dialog.add(section) section = Adw.ShortcutsSection(title="Everywhere") for accel, title in GLOBAL_SHORTCUTS: @@ -1263,6 +1315,7 @@ class ProxySuiteGui(Adw.Application): result["visible"] = model.available_tabs(states) result["status"] = model._safe(model.status_items, states, fallback=[("", "Status unavailable", "bad")]) result["tab"] = (tab.id, *self.load_tab(tab, states, elevated, fresh_root)) + result["selector"] = model.selector_state(tab) return result def load_tab(self, tab, states, elevated, fresh_root=False): @@ -1317,7 +1370,7 @@ class ProxySuiteGui(Adw.Application): self.tray.update(model.icon_name(overall), tooltip, tree, attention=bool(failed)) self.notify_failures(snap) if "tab" in result and self.window: - self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale) + self.window.fill(self.states, result["visible"], result["status"], *result["tab"], stale=stale, selector=result.get("selector")) if self.pending: fresh, self.pending, self.pending_fresh = self.pending_fresh, False, False self.reload(fresh_root=fresh) diff --git a/pkgs/proxy-ctl/proxy_model.py b/pkgs/proxy-ctl/proxy_model.py index 8cb34f7..26f1038 100644 --- a/pkgs/proxy-ctl/proxy_model.py +++ b/pkgs/proxy-ctl/proxy_model.py @@ -72,6 +72,17 @@ class Action: stdin: Callable = None # (selected row or None, prompt text) -> text proxy-ctl reads on stdin, or None +@dataclass +class Selector: + """One choice a tab makes apart from its rows (the Routing tab's mode), drawn above the table.""" + + label: str + options: Callable # () -> [(value, label)] + current: Callable # () -> the value chosen now + argv: Callable # value -> proxy-ctl argv that chooses it + key: str = "m" # opens the choice + + @dataclass class Tab: id: str @@ -82,6 +93,7 @@ class Tab: summary: Callable = None # () -> text above the table, read with every load actions: list = field(default_factory=list) tree: bool = False # rows carry "ancestors" (row keys) and "group": the order means something, so no sorting + selector: Selector = None def ROW(_): @@ -248,12 +260,21 @@ def service_rows(states): ] -def route_rows(_): - current = ctl._route_mode_current() - return [ - {"key": m, "active": "●" if m == current else "", "mode": ctl._route_mode_label(m)} - for m in ("default", *ctl.ROUTE_MODES) - ] +def route_mode_options(): + """The route modes as the Routing tab's selector and the tray offer them: (mode, label).""" + return [(m, ctl._route_mode_label(m)) for m in ("default", *ctl.ROUTE_MODES)] + + +def routing_rows(_): + return ctl._routing_rows() + + +def routing_summary(): + return ( + f"Configured default: {ctl._route_mode_default()}; an override lasts until you switch back to default. " + "Checked top to bottom: a lower # first, a runtime rule first among equals, then the final outbound. " + "On sing-box, a rule's domains and addresses change without a restart." + ) def outbound_rows(_): @@ -655,6 +676,10 @@ def _rule_sets(): return bool(ctl.read_json_or(ctl.env("RULE_SETS_FILE"), [])) +def _runtime_rule(row): + return bool(row.get("runtime")) + + def _zapret_toggle(row, _, states): return ["zapret", "off" if states.get("proxy-suite-zapret") == "active" else "on"] @@ -748,11 +773,40 @@ TABS = [ "routing", "Routing", _socks, - [("active", ""), ("key", "Mode"), ("mode", "Meaning")], - route_rows, - summary=lambda: f"Configured default: {ctl._route_mode_default()}. An override lasts until you switch back to default.", + [("priority", "#"), ("name", "Rule"), ("source", "Source"), ("target", "Target"), ("matches", "Matches"), ("notes", "Notes")], + routing_rows, + summary=routing_summary, + tree=True, + selector=Selector( + "Mode", + route_mode_options, + # Looked up at each read: tests and the front ends patch proxy_ctl's. + lambda: ctl._route_mode_current(), + lambda mode: ["proxy", "mode", mode], + ), actions=[ - Action("space", "switch to this mode", lambda r, *_: ["proxy", "mode", r["key"]], when=lambda r: not r["active"]), + Action( + "n", + "add a rule…", + lambda r, t, _: ["proxy", "rules", "add", *shlex.split(t)], + prompt=" [--name n] [--priority n]" + " - e.g. direct bank.example 10.0.0.0/8", + ), + Action("a", "add domains or addresses to it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "add", *t.split()], when=_runtime_rule, prompt=""), + Action("x", "remove domains or addresses from it…", lambda r, t, _: ["proxy", "rules", "matches", r["name"], "rm", *t.split()], when=_runtime_rule, prompt=""), + Action("t", "send it elsewhere…", lambda r, t, _: ["proxy", "rules", "target", r["name"], t.strip()], when=_runtime_rule, prompt=""), + Action( + "y", + "set its priority…", + lambda r, t, _: ["proxy", "rules", "priority", r["name"], t.strip()], + when=_runtime_rule, + prompt=" - lower goes first; the configuration's sections are at 100 to 500", + ), + Action("plus", "move it up", lambda r, *_: ["proxy", "rules", "priority", r["name"], "up"], when=_runtime_rule), + Action("minus", "move it down", lambda r, *_: ["proxy", "rules", "priority", r["name"], "down"], when=_runtime_rule), + Action("e", "disable it", lambda r, *_: ["proxy", "rules", "disable", r["name"]], when=lambda r: _runtime_rule(r) and not r["disabled"]), + Action("e", "enable it again", lambda r, *_: ["proxy", "rules", "enable", r["name"]], when=lambda r: _runtime_rule(r) and r["disabled"]), + Action("d", "remove it", lambda r, *_: ["proxy", "rules", "rm", r["name"]], when=_runtime_rule, confirm=True), Action("i", "rule sets and when each was fetched", lambda r, *_: ["proxy", "rulesets", "list"], mode="dialog", offered=_rule_sets), Action("u", "fetch the rule sets now", lambda r, *_: ["proxy", "rulesets", "update"], mode="dialog", offered=_rule_sets), ], @@ -1017,7 +1071,7 @@ WHERE = Action("w", "How is a domain routed", lambda r, t, _: ["where", t], prom PROXY_SCHEMES = ("vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic", "socks5", "socks5h", "socks4", "socks4a") HOST = re.compile(r"(?!-)[A-Za-z0-9-]{1,63}(? ComposeResult: + values = [v for v, _ in self.options] + with Vertical(classes="dialog menu"): + yield Label(printable(self.heading), classes="dialog-title", markup=False) + choices = Choices(*(Option(f"{'●' if v == self.current else '○'} {label}", id=str(i)) for i, (v, label) in enumerate(self.options))) + if self.current in values: + choices.highlighted = values.index(self.current) + yield choices + yield hint("↑↓ or click to choose", ("esc close", "dismiss")) + + def on_option_list_option_selected(self, event): + self.dismiss(self.options[int(event.option.id)][0]) + + class Output(Dialog): BINDINGS = [Binding("escape,q", "dismiss", "close"), Binding("c", "copy", "copy"), Binding("exclamation_mark", "retry_root", "retry as root")] @@ -344,9 +368,23 @@ class Table(DataTable): def _pane(tab): """A pane whose bindings are its tab's action keys, live while its table has focus.""" bindings = [Binding(a.key, f"app.act({i})") for i, a in enumerate(tab.actions)] + if tab.selector: + bindings.append(Binding(tab.selector.key, "app.choose")) return type(f"{tab.id.title()}Pane", (TabPane,), {"BINDINGS": bindings}) +def selector_markup(tab, state): + """The selector's line, each option a link that chooses it.""" + options, current = state + parts = [ + f"[b]{escape(label)}[/]" if value == current else f"[@click=app.choose({json.dumps(value)})]{escape(label)}[/]" + for value, label in options + ] + return f"[b ansi_cyan]{escape(model.display_key(tab.selector.key))}[/] {escape(tab.selector.label)}: " + " · ".join( + f"{'●' if value == current else '○'} {part}" for (value, _), part in zip(options, parts, strict=True) + ) + + WIDE, TALL = 130, 40 # from here on the detail panel shows beside, or below, the table @@ -379,6 +417,8 @@ class MainScreen(Screen): with TabbedContent(id="tabs"): for tab in self.tabs.values(): with _pane(tab)(tab.title, id=tab.id): + if tab.selector: + yield Static(id=f"{tab.id}-selector", classes="selector") yield Static(id=f"{tab.id}-summary", classes="summary") with Container(classes="body"): table = Table(id=f"{tab.id}-table", cursor_type="row") @@ -412,6 +452,7 @@ class ProxyTui(App): #tabs ContentSwitcher { height: 1fr; } #tabs TabPane { height: 1fr; padding: 0; } .summary { display: none; height: auto; padding: 0 1; text-style: dim; } + .selector { display: none; height: auto; padding: 0 1; } DataTable { background: $background; } #tabs DataTable { height: 1fr; } DataTable > .datatable--header { background: $background; color: $accent; text-style: bold; } @@ -447,6 +488,7 @@ class ProxyTui(App): self.sorts = {} # tab id -> (column, descending) self.collapsed = {} # tree tab id -> keys of the groups folded away self.loaded = {} # tab id -> the last load, refilled at once when sorting or filtering changes + self.selectors = {} # tab id -> its selector's (options, current) as last read self.status = [] self.typed = {} # prompt title -> what was last typed there self.feedback_timer = None @@ -536,6 +578,7 @@ class ProxyTui(App): visible = model.available_tabs(states) status = _safe(status_text, states, fallback=["status unavailable"]) rows, summary = model.load_tab(self.tabs[tab_id], states) + self.selectors[tab_id] = model.selector_state(self.tabs[tab_id]) except Exception as e: # A dead worker would leave the tab as it was, for good; the next refresh tries again. log_trace(f"load {tab_id}") @@ -586,6 +629,11 @@ class ProxyTui(App): widget = self.main.query_one(f"#{tab_id}-summary", Static) _update(widget, Text(printable(summary))) widget.display = bool(summary) + if self.tabs[tab_id].selector: + state = self.selectors.get(tab_id) + widget = self.main.query_one(f"#{tab_id}-selector", Static) + _update(widget, selector_markup(self.tabs[tab_id], state) if state else "") + widget.display = bool(state) self.rows[tab_id] = {r["key"]: r for r in rows} tab, table = self.tabs[tab_id], self.table(tab_id) keys = [r["key"] for r in rows] @@ -672,10 +720,28 @@ class ProxyTui(App): def action_where(self): self.perform(model.WHERE, None) + def action_choose(self, value=None): + """The tab's selector: value from a click on its line, else picked from a list.""" + tab = self.tabs[self.active_tab()] + state = self.selectors.get(tab.id) + if not tab.selector or not state: + self.feedback("Nothing to choose here right now.") + return + + def chosen(value): + argv = value is not None and model.selector_argv(tab, value) + if argv: + self.run_argv("run", argv) + + if value is None: + self.push_screen(Pick(tab.selector.label, *state), chosen) + else: + chosen(value) + def on_data_table_header_selected(self, event): tab_id, name = self.active_tab(), event.column_key.value if self.tabs[tab_id].tree: - self.feedback("This list keeps its order: it is the order groups and the top level pick in.") + self.feedback("This list keeps its order: the order it is picked or checked in.") return sort = self.sorts.pop(tab_id, None) if not sort or sort[0] != name: @@ -717,7 +783,10 @@ class ProxyTui(App): def action_help(self): tab = self.tabs[self.active_tab()] text = Text() - for heading, keys in ((tab.title, model.key_labels(a for a in tab.actions if model.offered(a))), ("Everywhere", GLOBAL_KEYS)): + own = model.key_labels(a for a in tab.actions if model.offered(a)) + if tab.selector: + own.append((tab.selector.key, f"choose the {tab.selector.label.lower()}")) + for heading, keys in ((tab.title, own), ("Everywhere", GLOBAL_KEYS)): text.append(f"{heading}\n", style="bold") for key, label in keys: text.append(f" {model.display_key(key):<9}", style=ACCENT) diff --git a/pkgs/proxy-ctl/test_proxy_ctl.py b/pkgs/proxy-ctl/test_proxy_ctl.py index b722c91..105ff7f 100644 --- a/pkgs/proxy-ctl/test_proxy_ctl.py +++ b/pkgs/proxy-ctl/test_proxy_ctl.py @@ -2508,6 +2508,10 @@ class WhereTest(EnvTest): } } self.assertEqual(ctl._where_sing_box(config, "rr1.youtube.com"), ("warp", "rule-set yt")) + # A runtime routing rule's own rule set reads as the rule. + config["route"]["rule_set"][0]["tag"] = "user:videos" + config["route"]["rules"][-1]["rule_set"] = ["user:videos"] + self.assertEqual(ctl._where_sing_box(config, "rr1.youtube.com"), ("warp", "runtime rule videos")) self.assertEqual(ctl._where_sing_box(config, "a.example.org")[0], "proxy") # A leading dot is subdomains only; nothing else matches, so the final outbound. self.assertEqual(ctl._where_sing_box(config, "example.org")[0], "direct") @@ -2533,6 +2537,163 @@ class WhereTest(EnvTest): ) +class RoutingRulesTest(EnvTest): + """proxy rules: the spool proxy-ctl writes, and where each rule lands among the configuration's.""" + + SECTIONS = [ + {"id": "rules", "priority": 100, "label": "routing.rules", "entries": [{"target": "de", "domains": ["c.example"]}]}, + {"id": "proxy", "priority": 200, "label": "routing.proxy: domains and ips", "entries": [{"target": "proxy", "domains": []}]}, + {"id": "block", "priority": 300, "label": "routing.block", "entries": [{"target": "block", "domains": ["ads.example"]}]}, + {"id": "direct", "priority": 400, "label": "routing.direct, private addresses", "entries": [{"target": "direct"}]}, + ] + + def setUp(self): + super().setUp() + os.makedirs(self.path("routing.d")) + geosites = self.path("geo") + os.makedirs(geosites) + open(os.path.join(geosites, "geosite-netflix.srs"), "w").close() + os.environ.update( + RUNTIME_ROUTING_DIR=self.path("routing.d"), + ROUTING_RULES_DIR=self.path("routing"), + ROUTING_RULES_FILE=self.write("buckets.json", {"common": [], "sections": self.SECTIONS}), + OUTBOUND_INVENTORY_FILE=self.write("socks/outbounds.json", {"tags": ["de", "proxy"], "groups": {"fast": {}}}), + RULE_SETS_FILE=self.write("rulesets.json", [{"name": "blocked", "path": "/x"}]), + GEODATA_GEOSITE_DIR=geosites, + ROUTE_MODE_STATE_FILE=self.path("no-mode"), + ) + self.applied = 0 + + def systemctl(*args, **_): + self.applied += args[:2] == ("start", "proxy-suite-routing-apply.service") + return 0, "" + + self.patch("systemctl", systemctl) + self.patch("svc_exists", lambda unit: True) + + def rules(self): + with open(self.path("routing.d/rules.json")) as f: + return {r["name"]: r for r in json.load(f)["rules"]} + + def test_matches_as_typed(self): + m = ctl._rule_match + self.assertEqual(m("Bank.Example"), ("domains", "bank.example")) + self.assertEqual(m(".bank.example"), ("domains", "bank.example")) + self.assertEqual(m("https://user@WWW.Bank.example:8443/login"), ("domains", "www.bank.example")) + self.assertEqual(m("10.1.2.3"), ("ips", "10.1.2.3/32")) + self.assertEqual(m("10.1.2.3/8"), ("ips", "10.0.0.0/8")) + self.assertEqual(m("2001:db8::1"), ("ips", "2001:db8::1/128")) + self.assertEqual(m("geosite:netflix"), ("geosites", "netflix")) + self.assertEqual(m("geoip:ru"), ("geoips", "ru")) # no geoip dir here: not checked + self.assertEqual(m("ruleset:blocked"), ("ruleSets", "blocked")) + for bad in ("geosite:nope", "geosite:../x", "ruleset:other", "a b", "$(id)", "x/y"): + with self.subTest(bad=bad): + self.assertEqual(run(ctl._rule_match, bad)[0], 1) + + def test_add_extends_the_rule_named_after_its_target(self): + ok(ctl.cmd_rules, "add", "direct", "bank.example", "10.0.0.0/8") + ok(ctl.cmd_rules, "add", "direct", "bank2.example", "bank.example") + ok(ctl.cmd_rules, "add", "fast", "geosite:netflix", "--name", "video", "--priority", "250") + rules = self.rules() + self.assertEqual(rules["direct"]["domains"], ["bank.example", "bank2.example"]) + self.assertEqual((rules["direct"]["priority"], rules["direct"]["ips"]), (50, ["10.0.0.0/8"])) + self.assertEqual((rules["video"]["target"], rules["video"]["priority"], rules["video"]["geosites"]), ("fast", 250, ["netflix"])) + self.assertEqual(self.applied, 3) + # Another target under the same name is a mistake, not a silent move. + status, _, err = run(ctl.cmd_rules, "add", "proxy", "x.example", "--name", "direct") + self.assertEqual(status, 1) + self.assertIn("rules target direct proxy", err) + self.assertEqual(run(ctl.cmd_rules, "add", "nowhere", "x.example")[0], 1) + self.assertEqual(run(ctl.cmd_rules, "add", "proxy", "x.example", "--name", "../x")[0], 1) + self.assertEqual(self.applied, 3) + + def test_edits(self): + ok(ctl.cmd_rules, "add", "direct", "a.example", "b.example") + ok(ctl.cmd_rules, "matches", "direct", "rm", "a.example") + ok(ctl.cmd_rules, "matches", "direct", "add", "1.1.1.1") + ok(ctl.cmd_rules, "target", "direct", "de") + ok(ctl.cmd_rules, "disable", "direct") + ok(ctl.cmd_rules, "priority", "direct", "450") + rule = self.rules()["direct"] + self.assertEqual((rule["domains"], rule["ips"], rule["target"], rule["disabled"], rule["priority"]), (["b.example"], ["1.1.1.1/32"], "de", True, 450)) + ok(ctl.cmd_rules, "enable", "direct") + self.assertFalse(self.rules()["direct"]["disabled"]) + self.assertEqual(run(ctl.cmd_rules, "priority", "direct", "1.5")[0], 1) + self.assertEqual(run(ctl.cmd_rules, "rm", "nope")[0], 1) + ok(ctl.cmd_rules, "rm", "direct") + self.assertEqual(self.rules(), {}) + + def test_up_and_down_step_past_the_configuration(self): + ok(ctl.cmd_rules, "add", "direct", "a.example") + ok(ctl.cmd_rules, "add", "proxy", "b.example") + order = lambda: [r["name"] for r in ctl._routing_rows()] # noqa: E731 + # Empty sections are no rows: proxy (200) is not there to step past. + self.assertEqual(order(), ["direct", "proxy", "routing.rules", "routing.block", "routing.direct, private addresses"]) + ok(ctl.cmd_rules, "priority", "proxy", "down") + self.assertEqual(order(), ["direct", "routing.rules", "proxy", "routing.block", "routing.direct, private addresses"]) + self.assertEqual(self.rules()["proxy"]["priority"], 110) + ok(ctl.cmd_rules, "priority", "direct", "down") + # Both after routing.rules now, the one moved first: numbered 10 apart there. + self.assertEqual(order()[:3], ["routing.rules", "direct", "proxy"]) + self.assertEqual({n: r["priority"] for n, r in self.rules().items()}, {"direct": 110, "proxy": 120}) + ok(ctl.cmd_rules, "priority", "direct", "down") + self.assertEqual(order()[:3], ["routing.rules", "proxy", "direct"]) + ok(ctl.cmd_rules, "priority", "direct", "down") + ok(ctl.cmd_rules, "priority", "direct", "down") + self.assertEqual(order()[-1], "direct") + self.assertIn("already last", ok(ctl.cmd_rules, "priority", "direct", "down")) + # Before a section a rule may share its number (runtime first among equals). + ok(ctl.cmd_rules, "priority", "proxy", "100") + self.assertEqual(order()[:2], ["proxy", "routing.rules"]) + + def test_list_and_rows(self): + ok(ctl.cmd_rules, "add", "direct", "a.example", "geosite:netflix") + self.write("socks/routing-skipped.json", [{"name": "direct", "why": "no such geosite"}]) + rows = {r["key"]: r for r in ctl._routing_rows()} + self.assertEqual(rows["rule:direct"]["matches"], "a.example, geosite:netflix") + self.assertEqual(rows["rule:direct"]["notes"], "left out: no such geosite") + self.assertEqual((rows["config:block:0"]["source"], rows["config:block:0"]["runtime"]), ("config", False)) + self.assertEqual(rows["config:direct:0"]["matches"], "private addresses") + out = ok(ctl.cmd_rules) + self.assertIn("routing.block", out) + self.assertIn("-> direct: a.example, geosite:netflix", out) + + def test_a_spool_edited_by_hand_reads_as_root_applies_it(self): + """What routing-render.jq drops is no row, and nothing in the file stops the list.""" + with open(self.path("routing.d/rules.json"), "w") as f: + f.write( + '{"rules": [{"name": "inf", "target": "proxy", "priority": Infinity},' + ' {"name": "nan", "target": "proxy", "priority": NaN},' + ' {"name": "far", "target": "proxy", "priority": -5e9},' + ' {"name": "half", "target": "proxy", "priority": -2.5},' + ' {"name": "half", "target": "direct"},' + ' {"name": "../x", "target": "proxy"},' + ' {"name": "ctl", "target": "a\\u0007b"}]}' + ) + rules = {r["name"]: (r["priority"], r["target"]) for r in ctl._runtime_rules()} + self.assertEqual(rules, {"inf": (1_000_000, "proxy"), "nan": (50, "proxy"), "far": (-1_000_000, "proxy"), "half": (-3, "proxy")}) + self.assertIn("inf", ok(ctl.cmd_rules)) + self.assertIn("priority 7", ok(ctl.cmd_rules, "priority", "half", "007")) + + @unittest.skipIf(os.geteuid() == 0, "root reads anything") + def test_a_stranger_sees_what_root_applied(self): + """The spool is the routing scope's; anyone else reads the rendered copy.""" + ok(ctl.cmd_rules, "add", "direct", "a.example") + self.write("routing/rules.json", [{"name": "applied", "target": "proxy", "priority": 5, "domains": ["b.example"]}]) + os.chmod(self.path("routing.d/rules.json"), 0) + self.assertEqual([r["name"] for r in ctl._runtime_rules()], ["applied"]) + status, _, err = run(ctl.cmd_rules, "add", "direct", "c.example") + self.assertEqual(status, 1) + self.assertIn("Cannot change", err) + + def test_completion(self): + ok(ctl.cmd_rules, "add", "direct", "a.example") + self.assertIn("matches", ctl._complete_tree("proxy", "rules")) + self.assertEqual(ctl._complete_tree("proxy", "rules", "rm"), {"direct": "-> direct"}) + targets = ctl._complete_tree("proxy", "rules", "add") + self.assertTrue({"proxy", "direct", "block", "de", "fast", "--name"} <= set(targets)) + + class StatusSnapshotTest(EnvTest): def setUp(self): super().setUp() diff --git a/pkgs/proxy-ctl/test_proxy_gui.py b/pkgs/proxy-ctl/test_proxy_gui.py index 4f2c53e..a0f8e08 100644 --- a/pkgs/proxy-ctl/test_proxy_gui.py +++ b/pkgs/proxy-ctl/test_proxy_gui.py @@ -154,6 +154,23 @@ class GuiTest(unittest.TestCase): then() self.assertEqual(ran, [(["proxy", "subs", "add", "-"], "https://evil.test/s")]) + def test_selector_runs_only_a_new_choice(self): + """The Routing page's mode drop-down: picking runs proxy-ctl; filling it from a read does not.""" + routing = next(t for t in model.TABS if t.id == "routing") + ran = [] + win = types.SimpleNamespace(app=types.SimpleNamespace(run_argv=lambda mode, argv, win: ran.append((mode, argv)))) + page = types.SimpleNamespace(tab=routing, win=win, selector_setting=False, selector_values=["default", *ctl.ROUTE_MODES]) + drop = lambda index: types.SimpleNamespace(get_selected=lambda: index) # noqa: E731 + with mock.patch.object(ctl, "_route_mode_current", lambda: "default"): + gui.Page.on_selector_changed(page, drop(2), None) + self.assertEqual(ran, [("run", ["proxy", "mode", "blacklist"])]) + gui.Page.on_selector_changed(page, drop(0), None) # the current one + gui.Page.on_selector_changed(page, drop(Gtk.INVALID_LIST_POSITION), None) + page.selector_setting = True # set from a read + gui.Page.on_selector_changed(page, drop(1), None) + self.assertEqual(len(ran), 1) + self.assertTrue(gui.accelerator(routing.selector.key)) + def test_every_tray_icon_is_drawn(self): here = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") with tempfile.TemporaryDirectory() as out: diff --git a/pkgs/proxy-ctl/test_proxy_model.py b/pkgs/proxy-ctl/test_proxy_model.py index fb0859b..60ef745 100644 --- a/pkgs/proxy-ctl/test_proxy_model.py +++ b/pkgs/proxy-ctl/test_proxy_model.py @@ -238,6 +238,7 @@ class ModelTest(unittest.TestCase): ], "zapret": [{"kind": k} for k in ("learned", "pinned", "excluded")], "autoproxy": [{"kind": k} for k in ("routed", "queued")], + "routing": [{"runtime": rt, "disabled": d} for rt in (False, True) for d in (False, True)], } for tab in model.TABS: by_key = {} @@ -271,18 +272,60 @@ class ModelTest(unittest.TestCase): zapret = next(t for t in model.TABS if t.id == "zapret") env = {} with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)): - self.assertEqual([a.key for a in model.applicable(routing, None)], []) + self.assertEqual([a.key for a in model.applicable(routing, None)], ["n"]) self.assertEqual([a.key for a in model.applicable(zapret, None)], ["space", "ctrl+r"]) with tempfile.NamedTemporaryFile("w", suffix=".json") as f: json.dump([{"name": "ru", "path": "/nonexistent"}], f) f.flush() env.update(RULE_SETS_FILE=f.name, ZAPRET_AUTO_ENABLED="1", ZAPRET_CUTOFF_ENABLED="1") - self.assertEqual([a.argv(None, "", {}) for a in model.applicable(routing, None)], [["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]]) + self.assertEqual( + [a.argv(None, "", {}) for a in model.applicable(routing, None) if a.key != "n"], + [["proxy", "rulesets", "list"], ["proxy", "rulesets", "update"]], + ) self.assertEqual([a.key for a in model.applicable(zapret, None)], ["n", "X", "F", "P", "space", "ctrl+r"]) actions = {a.key: a for a in zapret.actions} self.assertEqual(actions["n"].argv(None, "example.com", {}), ["zapret", "auto", "add", "example.com"]) self.assertEqual(actions["X"].argv(None, "example.com", {}), ["zapret", "auto", "exclude", "example.com"]) + def test_routing_tab(self): + """Rules in match order, actions on the runtime ones only, and the mode as a selector.""" + tab = next(t for t in model.TABS if t.id == "routing") + with tempfile.TemporaryDirectory() as tmp: + spool = os.path.join(tmp, "routing.d") + os.makedirs(spool) + with open(os.path.join(spool, "rules.json"), "w") as f: + json.dump({"rules": [{"name": "work", "target": "de", "priority": 150, "domains": ["work.example"]}, + {"name": "off", "target": "direct", "priority": 10, "disabled": True}]}, f) + buckets = os.path.join(tmp, "buckets.json") + with open(buckets, "w") as f: + json.dump({"sections": [{"id": "rules", "priority": 100, "label": "routing.rules", "entries": [{"target": "de", "domains": ["c.example"]}]}]}, f) + env = {"RUNTIME_ROUTING_DIR": spool, "ROUTING_RULES_FILE": buckets, "OUTBOUND_INVENTORY_FILE": os.path.join(tmp, "none.json")} + with mock.patch.object(ctl, "env", lambda name, default="": env.get(name, default)): + rows, _ = model.load_tab(tab, {}) + self.assertEqual([r["key"] for r in rows], ["rule:off", "config:rules:0", "rule:work"]) + off, config, work = rows + self.assertEqual(off["notes"], "disabled") + by = lambda row: {a.key: a for a in model.applicable(tab, row)} # noqa: E731 + self.assertEqual(set(by(config)), {"n"}) # the configuration's: nothing to change here + self.assertEqual(by(off)["e"].argv(off, "", {}), ["proxy", "rules", "enable", "off"]) + self.assertEqual(by(work)["e"].argv(work, "", {}), ["proxy", "rules", "disable", "work"]) + self.assertEqual(by(work)["plus"].argv(work, "", {}), ["proxy", "rules", "priority", "work", "up"]) + self.assertEqual(by(work)["a"].argv(work, "a.example 1.1.1.1", {}), ["proxy", "rules", "matches", "work", "add", "a.example", "1.1.1.1"]) + self.assertEqual(by(work)["t"].argv(work, " proxy ", {}), ["proxy", "rules", "target", "work", "proxy"]) + self.assertTrue(by(work)["d"].confirm) + self.assertEqual(by(None)["n"].argv(None, "direct bank.example --name bank", {}), ["proxy", "rules", "add", "direct", "bank.example", "--name", "bank"]) + # The mode: a selector over the table, not rows in it. + options, current = model.selector_state(tab) + self.assertEqual([v for v, _ in options], ["default", *ctl.ROUTE_MODES]) + self.assertEqual(current, "default") + self.assertIsNone(model.selector_argv(tab, "default")) # already + self.assertIsNone(model.selector_argv(tab, "nope")) + self.assertEqual(model.selector_argv(tab, "all-proxy"), ["proxy", "mode", "all-proxy"]) + self.assertTrue(model.selector_line(tab).startswith("Mode: ● Default")) + self.assertIsNone(model.selector_state(next(t for t in model.TABS if t.id == "services"))) + # A bare host pasted onto the tab goes through the proxy. + self.assertEqual(model.paste_argv("routing", "blocked.example")[0], ["proxy", "rules", "add", "proxy", "blocked.example"]) + def test_tray_menu(self): states = { "proxy-suite-socks": "active", diff --git a/pkgs/proxy-ctl/test_proxy_tui.py b/pkgs/proxy-ctl/test_proxy_tui.py index 038db3a..9749655 100644 --- a/pkgs/proxy-ctl/test_proxy_tui.py +++ b/pkgs/proxy-ctl/test_proxy_tui.py @@ -4,6 +4,8 @@ import asyncio import contextlib import io +import json +import os import signal import tempfile import unittest @@ -285,19 +287,37 @@ class TuiTest(unittest.TestCase): # Declared: nothing removes it here. self.assertNotIn("d", app.screen.active_bindings) - # On to Routing. + # On to Routing: a runtime rule ahead of nothing the configuration has. + os.makedirs(f"{self.env['STATE_DIR']}/routing.d") + with open(f"{self.env['STATE_DIR']}/routing.d/rules.json", "w") as f: + json.dump({"rules": [{"name": "bank", "target": "direct", "domains": ["bank.example"]}]}, f) await pilot.press("right") await self.settle(app, pilot) self.assertEqual((app.active_tab(), app.focused.id), ("routing", "routing-table")) + self.assertIn("● [b]Default", str(app.main.query_one("#routing-selector").content)) # Enter opens the row's actions; arrows and enter pick one. - await pilot.press("down", "enter") - await pilot.pause() - self.assertIsInstance(app.screen, tui.Menu) - self.assertEqual(self.menu_labels(app), ["switch to this mode"]) await pilot.press("enter") await pilot.pause() + self.assertIsInstance(app.screen, tui.Menu) + self.assertEqual(self.menu_labels(app)[:2], ["add a rule…", "add domains or addresses to it…"]) + await pilot.press("escape") + await pilot.pause() + await pilot.press("minus") + self.assertEqual(self.ran.pop(), ["proxy", "rules", "priority", "bank", "down"]) + + # m: the mode, picked from a list that starts at the current one. + await pilot.press("m") + await pilot.pause() + self.assertIsInstance(app.screen, tui.Pick) + await pilot.press("down", "enter") + await pilot.pause() self.assertEqual(self.ran.pop(), ["proxy", "mode", "whitelist"]) + # Or a click on one in the line above the table. + app.action_choose("all-bypass") + self.assertEqual(self.ran.pop(), ["proxy", "mode", "all-bypass"]) + app.action_choose("default") # already: nothing runs + self.assertEqual(self.ran, []) # Outbounds: letter shortcuts; p pins, and on the pinned row unpins; nothing removes a declared one. await pilot.press("right")