diff --git a/README.md b/README.md index aed4a96..3f70dd1 100644 --- a/README.md +++ b/README.md @@ -135,6 +135,8 @@ Commands: proxy on|off enable/disable the sing-box proxy stack tproxy on|off enable/disable TProxy transparent mode tun on|off enable/disable TUN mode + route-mode default|whitelist|blacklist|all-proxy|all-bypass|status + set temporary routing override zapret on|off enable/disable zapret-discord-youtube restart restart active global proxy-suite services logs [service] follow service logs (default: proxy-suite-socks) diff --git a/modules/proxy-suite/config.nix b/modules/proxy-suite/config.nix index 0d1f431..b0499b2 100644 --- a/modules/proxy-suite/config.nix +++ b/modules/proxy-suite/config.nix @@ -170,8 +170,11 @@ let perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" ( builtins.toJSON perAppTunTemplate ); + routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" ( + builtins.toJSON rules.routeModeRules + ); in { - inherit tproxyFile tunFile perAppTunFile; + inherit tproxyFile tunFile perAppTunFile routeModeRulesFile; } diff --git a/modules/proxy-suite/default.nix b/modules/proxy-suite/default.nix index 317c53e..f6f1848 100644 --- a/modules/proxy-suite/default.nix +++ b/modules/proxy-suite/default.nix @@ -47,7 +47,7 @@ in packages cfg ; - inherit (configs) tproxyFile tunFile perAppTunFile; + inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile; inherit (nftr) nftablesRulesFile perAppTproxyRulesFile diff --git a/modules/proxy-suite/rules.nix b/modules/proxy-suite/rules.nix index 0535c50..92d0ee2 100644 --- a/modules/proxy-suite/rules.nix +++ b/modules/proxy-suite/rules.nix @@ -101,6 +101,14 @@ let mkDomainRule = mkRule "domain_suffix"; mkIPRule = mkRule "ip_cidr"; mkRulesetRule = mkRule "rule_set"; + customRuleCategory = + outbound: + if outbound == "direct" then + "direct" + else if outbound == "block" then + "block" + else + "proxy"; # In "first" mode the start script renames the first outbound to "proxy", # so any per-outbound routing tag that isn't direct/block/proxy must map @@ -164,7 +172,7 @@ let geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames; geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames; - routingRules = lib.flatten [ + commonRules = [ { network = [ "tcp" @@ -174,42 +182,72 @@ let action = "hijack-dns"; } { action = "sniff"; } + ]; - # Per-outbound and explicit rules come first – they take priority. - (lib.concatMap mkCustomRuleEntries customRules) + customRouteRules = map ( + rule: { + category = customRuleCategory rule.outbound; + entries = mkCustomRuleEntries rule; + } + ) customRules; - # Global proxy lists + proxyPrimaryRules = lib.flatten [ (mkDomainRule "proxy" r.proxy.domains) (mkIPRule "proxy" r.proxy.ips) + ]; - # Global direct lists + directRules = lib.flatten [ (mkDomainRule "direct" direct.domains) (mkIPRule "direct" direct.ips) (mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites)) (mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips)) + ]; + safetyDirectRules = [ { ip_is_private = true; outbound = "direct"; } + ]; - # Block (before proxy geosets so block can override them) + blockRules = lib.flatten [ (mkDomainRule "block" r.block.domains) (mkIPRule "block" r.block.ips) (mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites)) (mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips)) + ]; - # Global proxy geo lists + proxyGeoRules = lib.flatten [ (mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites)) (mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips)) ]; + routingRules = + commonRules + ++ lib.concatMap (item: item.entries) customRouteRules + ++ proxyPrimaryRules + ++ directRules + ++ safetyDirectRules + ++ blockRules + ++ proxyGeoRules; + + routeModeRules = { + common = commonRules; + custom = customRouteRules; + proxyPrimary = proxyPrimaryRules; + direct = directRules; + safetyDirect = safetyDirectRules; + block = blockRules; + proxyGeo = proxyGeoRules; + }; + in { inherit direct geositeRuleSets geoIPRuleSets + routeModeRules routingRules ; } diff --git a/modules/proxy-suite/service/context.nix b/modules/proxy-suite/service/context.nix index 83694ca..d38d67b 100644 --- a/modules/proxy-suite/service/context.nix +++ b/modules/proxy-suite/service/context.nix @@ -7,6 +7,7 @@ tproxyFile, tunFile, perAppTunFile, + routeModeRulesFile, perAppTunChainFile, perAppTproxyRulesFile, perAppZapretRulesFile, @@ -74,7 +75,7 @@ let buildOutboundPy fetchSubscriptionPy ; - inherit tproxyFile tunFile perAppTunFile; + inherit tproxyFile tunFile perAppTunFile routeModeRulesFile; }; perAppRouting = import ./per-app-routing.nix { @@ -112,6 +113,7 @@ let ; zapretEnabled = cfg.zapret.enable; inherit (scripts) subscriptionTagsFile; + inherit (scripts) routeModeStateFile; inherit (perAppRouting) perAppRoutingProfilesFile proxychainsConfigFile diff --git a/modules/proxy-suite/service/control.nix b/modules/proxy-suite/service/control.nix index cd8d759..835bf11 100644 --- a/modules/proxy-suite/service/control.nix +++ b/modules/proxy-suite/service/control.nix @@ -12,6 +12,7 @@ perAppRoutingProfilesFile, proxychainsConfigFile, proxychainsQuietArg, + routeModeStateFile, }: { proxyCtl = packages.mkProxyCtl { @@ -22,7 +23,9 @@ perAppRoutingProfilesFile proxychainsConfigFile proxychainsQuietArg + routeModeStateFile ; + defaultRouteMode = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0"; perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0"; perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0"; diff --git a/modules/proxy-suite/service/default.nix b/modules/proxy-suite/service/default.nix index 8512fa1..95300fc 100644 --- a/modules/proxy-suite/service/default.nix +++ b/modules/proxy-suite/service/default.nix @@ -8,6 +8,7 @@ tproxyFile, tunFile, perAppTunFile, + routeModeRulesFile, nftablesRulesFile, perAppTproxyRulesFile, perAppZapretRulesFile, @@ -26,6 +27,7 @@ let tproxyFile tunFile perAppTunFile + routeModeRulesFile perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile @@ -215,6 +217,15 @@ let stateDirectory = "proxy-suite"; }; } + { + enable = singBoxCfg.enable; + name = "proxy-suite-route-mode@"; + value = mkOneshotService { + description = "Set proxy-suite route mode to %i"; + execStart = "${scripts.setRouteModeScript} %i"; + extraServiceConfig.RemainAfterExit = false; + }; + } ]; userServiceEntries = [ diff --git a/modules/proxy-suite/service/scripts.nix b/modules/proxy-suite/service/scripts.nix index 26a1f3d..c96c670 100644 --- a/modules/proxy-suite/service/scripts.nix +++ b/modules/proxy-suite/service/scripts.nix @@ -18,6 +18,7 @@ tproxyFile, tunFile, perAppTunFile, + routeModeRulesFile, }: let @@ -34,6 +35,7 @@ let else null; subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions"; + routeModeStateFile = "/run/proxy-suite/route-mode"; runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf"; mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json"; @@ -191,6 +193,8 @@ let chmod 640 "${runtimeProxychainsConfig}" ''; + modeBaseline = if singBoxCfg.proxyByDefault then "blacklist" else "whitelist"; + mkStartScript = { name, @@ -202,33 +206,158 @@ let pkgs.writeShellScript name '' set -euo pipefail RUNTIME_DIR="${runtimeDir}" + ROUTE_MODE_STATE_FILE="${routeModeStateFile}" mkdir -p "$RUNTIME_DIR" OUTBOUNDS_JSON='[]' + ROUTE_MODE="" + ROUTE_FINAL="" + DNS_FINAL="" + ROUTE_RULES_JSON="" + CLEAR_DNS_RULES=0 ${lib.optionalString enableLocalProxyAuth '' umask 077 LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")" ${writeProxychainsConfigBlock} ''} + if [ -r "$ROUTE_MODE_STATE_FILE" ]; then + ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)" + fi + case "$ROUTE_MODE" in + blacklist) + ROUTE_FINAL="proxy" + DNS_FINAL="remote" + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + whitelist) + ROUTE_FINAL="direct" + DNS_FINAL="local" + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(.entries) | add // []) + + .proxyPrimary + + .direct + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + all-proxy) + ROUTE_FINAL="proxy" + DNS_FINAL="remote" + CLEAR_DNS_RULES=1 + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // []) + + .proxyPrimary + + .safetyDirect + + .block + + .proxyGeo + ' "${routeModeRulesFile}") + ;; + all-bypass) + ROUTE_FINAL="direct" + DNS_FINAL="local" + CLEAR_DNS_RULES=1 + ROUTE_RULES_JSON=$(${jq} -c ' + .common + + (.custom | map(select(.category == "block") | .entries) | add // []) + + .safetyDirect + + .block + ' "${routeModeRulesFile}") + ;; + *) + ROUTE_MODE="" + ;; + esac + ${mkOutboundScript routingMark} ${ if enableLocalProxyAuth then '' - ${jq} \ - --argjson obs "$OUTBOUNDS_JSON" \ - --arg user ${lib.escapeShellArg localProxyAuth.username} \ - --arg password "$LOCAL_PROXY_PASSWORD" \ - '.outbounds = $obs + .outbounds - | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]' \ - "${configFile}" > "$RUNTIME_DIR/config.json" + if [ -n "$ROUTE_MODE" ]; then + if [ "$CLEAR_DNS_RULES" -eq 1 ]; then + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --arg user ${lib.escapeShellArg localProxyAuth.username} \ + --arg password "$LOCAL_PROXY_PASSWORD" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + '.outbounds = $obs + .outbounds + | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] + | .route.rules = $route_rules + | .route.final = $route_final + | .dns.rules = [] + | .dns.final = $dns_final' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + else + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --arg user ${lib.escapeShellArg localProxyAuth.username} \ + --arg password "$LOCAL_PROXY_PASSWORD" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + '.outbounds = $obs + .outbounds + | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}] + | .route.rules = $route_rules + | .route.final = $route_final + | .dns.final = $dns_final' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + fi + else + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --arg user ${lib.escapeShellArg localProxyAuth.username} \ + --arg password "$LOCAL_PROXY_PASSWORD" \ + '.outbounds = $obs + .outbounds + | (.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + fi chmod 600 "$RUNTIME_DIR/config.json" '' else '' - ${jq} --argjson obs "$OUTBOUNDS_JSON" \ - '.outbounds = $obs + .outbounds' \ - "${configFile}" > "$RUNTIME_DIR/config.json" + if [ -n "$ROUTE_MODE" ]; then + if [ "$CLEAR_DNS_RULES" -eq 1 ]; then + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + '.outbounds = $obs + .outbounds + | .route.rules = $route_rules + | .route.final = $route_final + | .dns.rules = [] + | .dns.final = $dns_final' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + else + ${jq} \ + --argjson obs "$OUTBOUNDS_JSON" \ + --argjson route_rules "$ROUTE_RULES_JSON" \ + --arg route_final "$ROUTE_FINAL" \ + --arg dns_final "$DNS_FINAL" \ + '.outbounds = $obs + .outbounds + | .route.rules = $route_rules + | .route.final = $route_final + | .dns.final = $dns_final' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + fi + else + ${jq} --argjson obs "$OUTBOUNDS_JSON" \ + '.outbounds = $obs + .outbounds' \ + "${configFile}" > "$RUNTIME_DIR/config.json" + fi '' } @@ -305,6 +434,53 @@ let exit "$FAILED" ''; + setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" '' + set -euo pipefail + mode="''${1:-}" + + case "$mode" in + default) + ;; + whitelist) + ;; + blacklist) + ;; + all-proxy) + ;; + all-bypass) + ;; + *) + echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2 + exit 1 + ;; + esac + + mkdir -p "$(dirname "${routeModeStateFile}")" + if [ "$mode" = "default" ]; then + rm -f "${routeModeStateFile}" + else + printf '%s\n' "$mode" > "${routeModeStateFile}" + fi + + SOCKS_WAS_ACTIVE=0 + TUN_WAS_ACTIVE=0 + PER_APP_TUN_WAS_ACTIVE=0 + + systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true + systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true + systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true + + if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then + systemctl restart proxy-suite-socks + fi + if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then + systemctl restart proxy-suite-tun + fi + if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then + systemctl restart proxy-suite-per-app-tun + fi + ''; + subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" ( builtins.toJSON (map (sub: sub.tag) singBoxCfg.subscriptions) ); @@ -312,6 +488,8 @@ in { inherit startSocks startTun startPerAppTun; inherit + routeModeStateFile + setRouteModeScript subscriptionUpdateScript hasSubscriptions subscriptionTagsFile diff --git a/nix/checks.nix b/nix/checks.nix index 5339782..2a819e0 100644 --- a/nix/checks.nix +++ b/nix/checks.nix @@ -10,6 +10,7 @@ let pkgs = import nixpkgs { inherit system; }; parserChecks = import ./checks/parsers.nix { inherit pkgs; }; + suitePkgs = import ../pkgs/default.nix { inherit pkgs; }; readmeDocSource = builtins.readFile ../nix/readme-doc.nix; trayModuleSource = builtins.readFile ../modules/proxy-suite/tray.nix; tgWsProxyModuleSource = builtins.readFile ../modules/proxy-suite/tg-ws-proxy.nix; @@ -44,6 +45,7 @@ let inherit pkgs cfg zapret; }; mkRoutingRules = fixture: (mkRouting fixture).routingRules; + mkRouteModeRules = fixture: (mkRouting fixture).routeModeRules; mkTProxyConfig = fixture: let @@ -184,6 +186,41 @@ let }; minimal = evalProxySuite [ baseModule ]; + _minimalProxyCtl = mkProxyCtlDerived minimal; + minimalProxyCtlWrapper = _minimalProxyCtl.wrapper; + minimalProxyCtlScript = _minimalProxyCtl.script; + + routeModeFixture = evalProxySuite [ + baseModule + { + services.proxy-suite.singBox.routing = { + proxy = { + domains = [ "proxy.example" ]; + geosites = [ "google" ]; + }; + direct.domains = [ "direct.example" ]; + block.domains = [ "block.example" ]; + rules = [ + { + outbound = "direct"; + domains = [ "custom-direct.example" ]; + } + { + outbound = "primary"; + domains = [ "custom-proxy.example" ]; + } + { + outbound = "block"; + domains = [ "custom-block.example" ]; + } + ]; + }; + } + ]; + routeModeStartScript = builtins.readFile ( + routeModeFixture.config.systemd.services."proxy-suite-socks".serviceConfig.ExecStart + ); + routeModeRules = mkRouteModeRules routeModeFixture; tgSecretFile = evalProxySuite [ baseModule @@ -1696,6 +1733,55 @@ let true ) + # -- runtime route mode: proxy-ctl wrapper exports the volatile state file and baseline default -- + ( + assert shellValueByPrefix minimalProxyCtlWrapper "export ROUTE_MODE_STATE_FILE=" == "/run/proxy-suite/route-mode"; + assert shellValueByPrefix minimalProxyCtlWrapper "export DEFAULT_ROUTE_MODE=" == "blacklist"; + true + ) + + # -- runtime route mode: proxy-ctl help/status script exposes default + four explicit modes -- + ( + assert pkgs.lib.hasInfix "route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''printf 'route_mode=%s\n' "$(_route_mode_current)"'' minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''printf 'default_route_mode=%s\n' "$(_route_mode_default)"'' minimalProxyCtlScript; + assert pkgs.lib.hasInfix ''systemctl start "proxy-suite-route-mode@''${action}.service"'' minimalProxyCtlScript; + true + ) + + # -- runtime route mode: socks start script includes all override branches and uses volatile state -- + ( + assert pkgs.lib.hasInfix ''ROUTE_MODE_STATE_FILE="/run/proxy-suite/route-mode"'' routeModeStartScript; + assert pkgs.lib.hasInfix ''all-proxy)'' routeModeStartScript; + assert pkgs.lib.hasInfix ''all-bypass)'' routeModeStartScript; + assert pkgs.lib.hasInfix ''.route.rules = $route_rules'' routeModeStartScript; + assert pkgs.lib.hasInfix ''.dns.rules = []'' routeModeStartScript; + true + ) + + # -- runtime route mode: grouped routing metadata preserves custom rule categories and order -- + ( + assert builtins.length routeModeRules.custom == 3; + assert (builtins.elemAt routeModeRules.custom 0).category == "direct"; + assert (builtins.elemAt routeModeRules.custom 1).category == "proxy"; + assert (builtins.elemAt routeModeRules.custom 2).category == "block"; + true + ) + + # -- runtime route mode: setter unit is present and writes into /run -- + ( + let + setterSvc = routeModeFixture.config.systemd.services."proxy-suite-route-mode@"; + setterScript = builtins.readFile (builtins.head (pkgs.lib.splitString " " setterSvc.serviceConfig.ExecStart)); + in + assert !(setterSvc.serviceConfig ? RuntimeDirectory); + assert pkgs.lib.hasInfix "/run/proxy-suite/route-mode" setterScript; + assert pkgs.lib.hasInfix ''default)'' setterScript; + assert pkgs.lib.hasInfix ''all-proxy)'' setterScript; + assert pkgs.lib.hasInfix ''all-bypass)'' setterScript; + true + ) + # -- subscription: both url + urlFile fails -- ( assert subscriptionBothSources.success == false; @@ -2112,6 +2198,7 @@ let in { proxy-suite-module = builtins.seq validated (pkgs.writeText "proxy-suite-module-check" "ok"); + proxy-suite-tray-build = suitePkgs.proxy-suite-tray; zapret-hostlist-rules = pkgs.runCommand "proxy-suite-zapret-hostlist-rules-check" { } '' grep -F -- '--hostlist="${zapretSyncExtraListsBase}/hostlists/list-twitter.txt"' "${zapretSyncExtraListsBase}/config" diff --git a/nix/readme-doc.nix b/nix/readme-doc.nix index ac1fa09..5d1afb1 100644 --- a/nix/readme-doc.nix +++ b/nix/readme-doc.nix @@ -38,7 +38,7 @@ let packages cfg ; - inherit (configs) tproxyFile tunFile perAppTunFile; + inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile; inherit (nftr) perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile ip nft; }; in diff --git a/pkgs/proxy-ctl-lib.sh b/pkgs/proxy-ctl-lib.sh index 8d08b40..c2b1fbc 100644 --- a/pkgs/proxy-ctl-lib.sh +++ b/pkgs/proxy-ctl-lib.sh @@ -17,6 +17,8 @@ _usage() { echo " proxy on|off enable/disable the sing-box proxy stack" echo " tproxy on|off enable/disable TProxy transparent mode" echo " tun on|off enable/disable TUN mode" + echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" + echo " set temporary routing override" echo " zapret on|off enable/disable zapret-discord-youtube" echo " restart restart active global proxy-suite services" echo " logs [service] follow service logs (default: proxy-suite-socks)" @@ -55,6 +57,57 @@ _svc_active() { systemctl is-active --quiet "$1" } +_route_mode_default() { + printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}" +} + +_route_mode_effective() { + local mode="" + if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then + mode=$(tr -d '\r\n[:space:]' < "${ROUTE_MODE_STATE_FILE}" 2>/dev/null || true) + fi + + case "$mode" in + whitelist|blacklist|all-proxy|all-bypass) + printf '%s' "$mode" + ;; + *) + _route_mode_default + ;; + esac +} + +_route_mode_current() { + if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then + _route_mode_effective + else + printf 'default' + fi +} + +_route_mode_label() { + case "$1" in + default) + printf 'Default (%s)' "$(_route_mode_label "$(_route_mode_default)")" + ;; + whitelist) + printf 'Whitelist (direct by default)' + ;; + blacklist) + printf 'Blacklist (proxy by default)' + ;; + all-proxy) + printf 'All Proxy (override)' + ;; + all-bypass) + printf 'All Bypass (override)' + ;; + *) + printf 'Unknown' + ;; + esac +} + _status_tray() { local pair key svc for pair in \ @@ -68,6 +121,9 @@ _status_tray() { printf '%s_active=%s\n' "$key" "$(_bool _svc_active "$svc")" done printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)" + printf 'route_mode_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)" + printf 'route_mode=%s\n' "$(_route_mode_current)" + printf 'default_route_mode=%s\n' "$(_route_mode_default)" } _ensure_app_routing() { @@ -144,6 +200,11 @@ cmd_status() { for svc in "${ALL_SERVICES[@]}"; do _svc_status "$svc" done + if _svc_exists proxy-suite-socks; then + echo "" + echo "routing:" + echo " active mode $(_route_mode_label "$(_route_mode_current)")" + fi } cmd_proxy() { @@ -183,6 +244,31 @@ cmd_mode_toggle() { cmd_zapret() { cmd_mode_toggle "zapret-discord-youtube" on "${1:-on}" "zapret"; } +cmd_route_mode() { + local action + + if ! _svc_exists proxy-suite-socks; then + echo "Route mode is unavailable because sing-box services are not enabled." + exit 1 + fi + + action="${1:-status}" + + case "$action" in + status) + echo "$(_route_mode_current)" + ;; + default|whitelist|blacklist|all-proxy|all-bypass) + systemctl start "proxy-suite-route-mode@${action}.service" + echo "Switched to: $(_route_mode_label "$action")" + ;; + *) + echo "Usage: proxy-ctl route-mode default|whitelist|blacklist|all-proxy|all-bypass|status" + exit 1 + ;; + esac +} + RESTART_SERVICES=( proxy-suite-tproxy proxy-suite-tun diff --git a/pkgs/proxy-ctl.nix b/pkgs/proxy-ctl.nix index 1343932..cc84712 100644 --- a/pkgs/proxy-ctl.nix +++ b/pkgs/proxy-ctl.nix @@ -15,6 +15,8 @@ perAppRoutingProfilesFile, proxychainsConfigFile, proxychainsQuietArg, + routeModeStateFile, + defaultRouteMode, }: let @@ -49,6 +51,8 @@ pkgs.symlinkJoin { --set PER_APP_ROUTING_ZAPRET_ENABLED ${lib.escapeShellArg perAppRoutingZapretEnabled} \ --set PER_APP_ROUTING_PROFILES_FILE ${lib.escapeShellArg (toString perAppRoutingProfilesFile)} \ --set PROXYCHAINS_CONFIG ${lib.escapeShellArg (toString proxychainsConfigFile)} \ - --set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} + --set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} \ + --set ROUTE_MODE_STATE_FILE ${lib.escapeShellArg routeModeStateFile} \ + --set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode} ''; } diff --git a/pkgs/proxy-ctl.sh b/pkgs/proxy-ctl.sh index 534a7e3..ade2849 100644 --- a/pkgs/proxy-ctl.sh +++ b/pkgs/proxy-ctl.sh @@ -33,6 +33,10 @@ case "$cmd" in cmd_mode_toggle proxy-suite-tun on "${1:-}" ;; + route-mode) + cmd_route_mode "$@" + ;; + zapret) cmd_zapret "$@" ;; diff --git a/pkgs/proxy-suite-tray.nix b/pkgs/proxy-suite-tray.nix index edbf608..8412010 100644 --- a/pkgs/proxy-suite-tray.nix +++ b/pkgs/proxy-suite-tray.nix @@ -21,7 +21,7 @@ pkgs.stdenv.mkDerivation { -DSYSTEMCTL_BIN='"${pkgs.systemd}/bin/systemctl"' \ -DPKEXEC_BIN='"/run/wrappers/bin/pkexec"' \ -DPOLL_INTERVAL=${toString pollInterval} \ - -O2 -Wall + -O2 -Wall -Werror=discarded-qualifiers ''; installPhase = '' diff --git a/pkgs/proxy-suite-tray/main.c b/pkgs/proxy-suite-tray/main.c index 5445a96..9f3d2b2 100644 --- a/pkgs/proxy-suite-tray/main.c +++ b/pkgs/proxy-suite-tray/main.c @@ -16,6 +16,12 @@ static AppIndicator *indicator; static GtkWidget *menu; static GtkWidget *status_item; static GtkWidget *proxy_item; +static GtkWidget *route_mode_item; +static GtkWidget *route_mode_default_item; +static GtkWidget *route_mode_whitelist_item; +static GtkWidget *route_mode_blacklist_item; +static GtkWidget *route_mode_all_proxy_item; +static GtkWidget *route_mode_all_bypass_item; static GtkWidget *tproxy_item; static GtkWidget *tun_item; static GtkWidget *zapret_item; @@ -23,12 +29,25 @@ static GtkWidget *open_controls_item; static GtkWidget *controls_window; static GtkWidget *controls_summary_label; static GtkWidget *controls_core_status_label; +static GtkWidget *controls_route_mode_status_label; +static GtkWidget *controls_route_mode_combo; static GtkWidget *controls_traffic_status_label; static GtkWidget *controls_zapret_status_label; static GtkWidget *controls_proxy_button; static GtkWidget *controls_tproxy_button; static GtkWidget *controls_tun_button; static GtkWidget *controls_zapret_button; +static gboolean updating_route_mode_widgets = FALSE; + +typedef enum +{ + ROUTE_MODE_UNKNOWN = 0, + ROUTE_MODE_DEFAULT, + ROUTE_MODE_WHITELIST, + ROUTE_MODE_BLACKLIST, + ROUTE_MODE_ALL_PROXY, + ROUTE_MODE_ALL_BYPASS +} RouteMode; typedef struct { @@ -38,10 +57,13 @@ typedef struct gboolean tun_available; gboolean zapret_available; gboolean subscription_update_available; + gboolean route_mode_available; gboolean socks; gboolean tproxy; gboolean tun; gboolean zapret; + RouteMode route_mode; + RouteMode default_route_mode; } ServiceState; static ServiceState initial_state; @@ -173,6 +195,35 @@ static gboolean parse_proxy_ctl_bool(const char *value) return value && strcmp(value, "true") == 0; } +static RouteMode parse_route_mode(const char *value) +{ + if (!value) + { + return ROUTE_MODE_UNKNOWN; + } + if (strcmp(value, "default") == 0) + { + return ROUTE_MODE_DEFAULT; + } + if (strcmp(value, "whitelist") == 0) + { + return ROUTE_MODE_WHITELIST; + } + if (strcmp(value, "blacklist") == 0) + { + return ROUTE_MODE_BLACKLIST; + } + if (strcmp(value, "all-proxy") == 0) + { + return ROUTE_MODE_ALL_PROXY; + } + if (strcmp(value, "all-bypass") == 0) + { + return ROUTE_MODE_ALL_BYPASS; + } + return ROUTE_MODE_UNKNOWN; +} + static const char *pick_icon_name( const char *const *candidates, gsize candidates_len, @@ -263,6 +314,18 @@ static ServiceState get_service_state(void) { state.subscription_update_available = parse_proxy_ctl_bool(parts[1]); } + else if (strcmp(parts[0], "route_mode_available") == 0) + { + state.route_mode_available = parse_proxy_ctl_bool(parts[1]); + } + else if (strcmp(parts[0], "route_mode") == 0) + { + state.route_mode = parse_route_mode(parts[1]); + } + else if (strcmp(parts[0], "default_route_mode") == 0) + { + state.default_route_mode = parse_route_mode(parts[1]); + } g_strfreev(parts); } @@ -286,6 +349,84 @@ static const char *traffic_mode_label(const ServiceState *state) return "System-wide routing disabled"; } +static const char *route_mode_label(const ServiceState *state) +{ + switch (state->route_mode) + { + case ROUTE_MODE_DEFAULT: + switch (state->default_route_mode) + { + case ROUTE_MODE_WHITELIST: + return "Default (Whitelist baseline)"; + case ROUTE_MODE_BLACKLIST: + return "Default (Blacklist baseline)"; + default: + return "Default"; + } + case ROUTE_MODE_WHITELIST: + return "Whitelist (direct by default)"; + case ROUTE_MODE_BLACKLIST: + return "Blacklist (proxy by default)"; + case ROUTE_MODE_ALL_PROXY: + return "All Proxy (override)"; + case ROUTE_MODE_ALL_BYPASS: + return "All Bypass (override)"; + default: + return "Unknown"; + } +} + +static gint route_mode_combo_index(RouteMode mode) +{ + switch (mode) + { + case ROUTE_MODE_DEFAULT: + return 0; + case ROUTE_MODE_WHITELIST: + return 1; + case ROUTE_MODE_BLACKLIST: + return 2; + case ROUTE_MODE_ALL_PROXY: + return 3; + case ROUTE_MODE_ALL_BYPASS: + return 4; + default: + return -1; + } +} + +static void sync_route_mode_widgets(RouteMode mode) +{ + updating_route_mode_widgets = TRUE; + + if (route_mode_default_item) + { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_default_item), mode == ROUTE_MODE_DEFAULT); + } + if (route_mode_whitelist_item) + { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_whitelist_item), mode == ROUTE_MODE_WHITELIST); + } + if (route_mode_blacklist_item) + { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_blacklist_item), mode == ROUTE_MODE_BLACKLIST); + } + if (route_mode_all_proxy_item) + { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_proxy_item), mode == ROUTE_MODE_ALL_PROXY); + } + if (route_mode_all_bypass_item) + { + gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_bypass_item), mode == ROUTE_MODE_ALL_BYPASS); + } + if (controls_route_mode_combo) + { + gtk_combo_box_set_active(GTK_COMBO_BOX(controls_route_mode_combo), route_mode_combo_index(mode)); + } + + updating_route_mode_widgets = FALSE; +} + static const char *indicator_label_text(const ServiceState *state) { if (state->socks && (state->tproxy || state->tun) && state->zapret) @@ -378,6 +519,10 @@ static void update_status(void) { gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown"); } + if (controls_route_mode_status_label) + { + gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), "[Routing] Mode: Unknown"); + } if (controls_zapret_status_label) { gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown"); @@ -386,16 +531,19 @@ static void update_status(void) } const char *traffic = traffic_mode_label(&state); + const char *route_mode = route_mode_label(&state); const char *summary = indicator_label_text(&state); const char *zapret = state.zapret ? "Active" : "Stopped"; gchar *summary_text = g_strdup_printf( - "[Status] %s | Traffic: %s | Zapret: %s", + "[Status] %s | Traffic: %s | Routing: %s | Zapret: %s", state.socks ? "Proxy ready" : "Proxy down", traffic, + route_mode, zapret); gchar *core_text = g_strdup_printf( "[Core] SOCKS proxy: %s", state.socks ? "Running" : "Stopped"); + gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic); gchar *zapret_text = g_strdup_printf( "[Zapret] zapret-discord-youtube: %s", @@ -445,6 +593,10 @@ static void update_status(void) { gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text); } + if (controls_route_mode_status_label) + { + gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), route_mode_text); + } if (controls_traffic_status_label) { gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text); @@ -463,6 +615,13 @@ static void update_status(void) gtk_button_set_label(GTK_BUTTON(controls_proxy_button), state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy"); } + if (route_mode_item) + { + gchar *menu_route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode); + gtk_menu_item_set_label(GTK_MENU_ITEM(route_mode_item), menu_route_mode_text); + g_free(menu_route_mode_text); + sync_route_mode_widgets(state.route_mode); + } if (tproxy_item) { @@ -499,6 +658,7 @@ static void update_status(void) g_free(summary_text); g_free(core_text); + g_free(route_mode_text); g_free(traffic_text); g_free(zapret_text); } @@ -535,6 +695,46 @@ static void on_tproxy_toggle(GtkWidget *item, gpointer data) update_status(); } +static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data) +{ + const char *mode; + if (updating_route_mode_widgets || !gtk_check_menu_item_get_active(item)) + { + return; + } + mode = (const char *)data; + if (!mode) + { + return; + } + run_proxy_ctl2("route-mode", mode); + update_status(); +} + +static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data) +{ + (void)data; + const char *mode; + const gchar *active_id; + if (updating_route_mode_widgets) + { + return; + } + active_id = gtk_combo_box_get_active_id(combo); + if (!active_id) + { + return; + } + mode = active_id; + ServiceState state = get_service_state(); + if (!state.route_mode_available) + { + return; + } + run_proxy_ctl2("route-mode", mode); + update_status(); +} + static void on_tun_toggle(GtkWidget *item, gpointer data) { (void)item; @@ -638,6 +838,28 @@ static void build_controls_window(void) g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL); gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0); + if (initial_state.route_mode_available) + { + GtkWidget *routing_frame = gtk_frame_new("[Routing] Mode"); + GtkWidget *routing_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_set_border_width(GTK_CONTAINER(routing_box), 6); + gtk_container_add(GTK_CONTAINER(routing_frame), routing_box); + gtk_box_pack_start(GTK_BOX(box), routing_frame, FALSE, FALSE, 0); + + controls_route_mode_status_label = gtk_label_new("[Routing] Mode: Unknown"); + gtk_label_set_xalign(GTK_LABEL(controls_route_mode_status_label), 0.0f); + gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_status_label, FALSE, FALSE, 0); + + controls_route_mode_combo = gtk_combo_box_text_new(); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "default", "Default (stop overriding)"); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "whitelist", "Whitelist (direct by default)"); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "blacklist", "Blacklist (proxy by default)"); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-proxy", "All Proxy (override)"); + gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-bypass", "All Bypass (override)"); + g_signal_connect(controls_route_mode_combo, "changed", G_CALLBACK(on_route_mode_combo_changed), NULL); + gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_combo, FALSE, FALSE, 0); + } + GtkWidget *traffic_frame = gtk_frame_new("[Traffic] System-wide traffic mode"); GtkWidget *traffic_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); gtk_container_set_border_width(GTK_CONTAINER(traffic_box), 6); @@ -722,6 +944,39 @@ static void build_menu(void) g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL); gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item); + if (initial_state.route_mode_available) + { + route_mode_item = gtk_menu_item_new_with_label("[Routing] Mode: Unknown"); + GtkWidget *route_mode_menu = gtk_menu_new(); + + route_mode_default_item = gtk_radio_menu_item_new_with_label(NULL, "Default (stop overriding)"); + g_signal_connect(route_mode_default_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "default"); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_default_item); + + GSList *route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_default_item)); + route_mode_whitelist_item = gtk_radio_menu_item_new_with_label(route_group, "Whitelist (direct by default)"); + g_signal_connect(route_mode_whitelist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "whitelist"); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_whitelist_item); + + route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_whitelist_item)); + route_mode_blacklist_item = gtk_radio_menu_item_new_with_label(route_group, "Blacklist (proxy by default)"); + g_signal_connect(route_mode_blacklist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "blacklist"); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_blacklist_item); + + route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_blacklist_item)); + route_mode_all_proxy_item = gtk_radio_menu_item_new_with_label(route_group, "All Proxy (override)"); + g_signal_connect(route_mode_all_proxy_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-proxy"); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_proxy_item); + + route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_all_proxy_item)); + route_mode_all_bypass_item = gtk_radio_menu_item_new_with_label(route_group, "All Bypass (override)"); + g_signal_connect(route_mode_all_bypass_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-bypass"); + gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_bypass_item); + + gtk_menu_item_set_submenu(GTK_MENU_ITEM(route_mode_item), route_mode_menu); + gtk_menu_shell_append(GTK_MENU_SHELL(menu), route_mode_item); + } + open_controls_item = gtk_menu_item_new_with_label("Open Controls"); g_signal_connect(open_controls_item, "activate", G_CALLBACK(on_open_controls), NULL); gtk_menu_shell_append(GTK_MENU_SHELL(menu), open_controls_item);