refactor: overhaul of options and features

Includes, but not limited to:
- zapret2 support
- declarative inbounds
- proxy-ctl revamp
- automatic proxy learning
This commit is contained in:
FUFSoB committed 2026-09-13 22:37:45 +05:00
1 parent b892384527
commit fdb2b08790
144 files changed
+13198 -14066

No files matched your search

+8 -3
View File
@@ -36,6 +36,7 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
userControlCfg
selectionMode
builtinTags
@@ -43,13 +44,13 @@ let
subscriptionTags
invalidRoutingTargets
collapseNamedOutbounds
hasSubscriptions
sshProxyCfg
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsCfg
proxyInboundsEnabled
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
;
@@ -96,7 +97,6 @@ let
userControlCfg
selectionMode
collapseNamedOutbounds
hasSubscriptions
constants
;
inherit
@@ -120,6 +120,7 @@ let
inherit
proxyInboundsCfg
proxyInboundsNeedLocalProxy
proxyInboundsGuardPrivate
proxyInboundViaOutbounds
userControlEnabled
builders
@@ -161,12 +162,16 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretCfg
zapretEngine
constants
selectionMode
userControlCfg
;
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
inherit (scripts) routeModeStateFile;
inherit proxyInboundsEnabled;
inherit (scripts) proxyInboundsLinksFile;
inherit (scripts) proxyInboundsLinksFile proxyInboundsSubscriptionsFile;
proxyInboundsSubscriptionsBaseUrl = proxyInboundsCfg.subscriptions.baseUrl;
inherit amneziaWgProfileNamesFile;
inherit (perAppRouting)
perAppRoutingProfilesFile
@@ -1,16 +1,22 @@
# Subscription refresh and route-mode control scripts.
# Subscription refresh, route-mode and outbound control scripts.
{
lib,
pkgs,
proxyCfg,
clashApi,
routeModeStateFile,
priorityOutboundFile,
outboundInventoryFile,
subscriptionCacheDir,
subscriptionCacheHelpersBlock,
mkSubscriptionFetchBlock,
runtimeSubscriptionsFetchBlock,
jq,
}:
let
systemctl = "${pkgs.systemd}/bin/systemctl";
curl = "${pkgs.curl}/bin/curl";
restartActiveConfigConsumersBlock =
lib.concatMapStrings
@@ -32,6 +38,7 @@ let
FAILED=0
${subscriptionCacheHelpersBlock}
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
${runtimeSubscriptionsFetchBlock}
if [ "$FAILED" -eq 0 ]; then
${restartActiveConfigConsumersBlock}
@@ -69,10 +76,77 @@ let
${restartActiveConfigConsumersBlock}
'';
# Pins the outbound the proxy prefers, or "auto" to hand the choice back to the
# configured selection. The pin is persisted either way; a live Clash API switch
# only saves the restart.
setPriorityOutboundScript = pkgs.writeShellScript "proxy-suite-set-priority-outbound" ''
set -euo pipefail
tag="''${1:-}"
if [ -z "$tag" ]; then
echo "proxy-suite: usage: proxy-suite-set-priority-outbound <tag|auto>" >&2
exit 1
fi
if [ "$tag" = "auto" ]; then
rm -f "${priorityOutboundFile}"
else
# The inventory only exists once the proxy has run. Without it there is
# nothing to check against, so accept the tag and let the start script warn
# if it turns out to name nothing.
if [ -r "${outboundInventoryFile}" ] \
&& ! ${jq} -e --arg t "$tag" '.tags | index($t) != null' "${outboundInventoryFile}" >/dev/null; then
echo "proxy-suite: unknown outbound '$tag'" >&2
exit 1
fi
mkdir -p "$(dirname "${priorityOutboundFile}")"
printf '%s\n' "$tag" > "${priorityOutboundFile}"
# Live switch when the running config exposes a selector; the persisted pin
# is what keeps it after the next restart.
if ${curl} -sf -X PUT "${clashApi}/proxies/proxy" \
-H "Content-Type: application/json" \
-d "$(${jq} -cn --arg name "$tag" '{name:$name}')" >/dev/null 2>&1; then
exit 0
fi
fi
${restartActiveConfigConsumersBlock}
'';
# Applies whatever is now in the runtime spool directories. A removed runtime
# subscription leaves a root-owned cache behind that the group cannot unlink,
# so the cache dir is reconciled against the sources here.
reloadOutboundsScript = pkgs.writeShellScript "proxy-suite-reload-outbounds" ''
set -euo pipefail
${subscriptionCacheHelpersBlock}
KEEP="|${
lib.concatMapStrings (sub: "${sub.tag}|") proxyCfg.subscriptions
}"
while IFS=$'\t' read -r TAG _; do
[ -n "$TAG" ] || continue
KEEP="$KEEP$TAG|"
done < <(_proxy_suite_runtime_subscriptions)
for CACHE in "$SUB_CACHE_DIR"/*.json; do
[ -e "$CACHE" ] || continue
TAG="''${CACHE##*/}"
TAG="''${TAG%.json}"
case "$KEEP" in
*"|$TAG|"*) ;;
*) rm -f "$CACHE" ;;
esac
done
${restartActiveConfigConsumersBlock}
'';
in
{
inherit
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
}
+22 -1
View File
@@ -7,7 +7,10 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretCfg,
zapretEngine,
constants,
selectionMode,
userControlCfg,
subscriptionTagsFile,
subscriptionCacheDir,
perAppRoutingProfilesFile,
@@ -17,6 +20,8 @@
amneziaWgProfileNamesFile,
proxyInboundsEnabled,
proxyInboundsLinksFile,
proxyInboundsSubscriptionsFile,
proxyInboundsSubscriptionsBaseUrl,
}:
{
proxyCtl = packages.mkProxyCtl {
@@ -31,13 +36,29 @@
routeModeStateFile
amneziaWgProfileNamesFile
;
defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist";
defaultRouteMode = if (proxyCfg.routing.default == "proxy") 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";
perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0";
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
zapretAutoEnabled = if zapretEngine == "zapret2" then "1" else "0";
zapretStateDir = constants.zapret2StateDir;
priorityOutboundFile = constants.priorityOutboundFile;
outboundInventoryFile = constants.outboundInventoryFile;
runtimeOutboundsDir = constants.runtimeOutboundsDir;
runtimeSubscriptionsDir = constants.runtimeSubscriptionsDir;
userControlGroup = userControlCfg.group;
inboundsEnabled = if proxyInboundsEnabled then "1" else "0";
inboundsLinksFile = proxyInboundsLinksFile;
inboundsStatsFile = constants.inboundStatsFile;
inboundsSubscriptionsFile = proxyInboundsSubscriptionsFile;
inboundsSubscriptionsBaseUrl =
if proxyInboundsSubscriptionsBaseUrl == null then "" else proxyInboundsSubscriptionsBaseUrl;
autoProxyEnabled = if proxyCfg.autoProxy.enable then "1" else "0";
autoProxyStateDir = constants.autoProxyStateDir;
localProxyUrl = "http://${
if proxyCfg.listener.address == "0.0.0.0" then "127.0.0.1" else proxyCfg.listener.address
}:${toString proxyCfg.listener.port}";
};
}
+101 -66
View File
@@ -63,7 +63,6 @@ let
userControlCfg
userControlEnabled
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
@@ -106,7 +105,6 @@ let
perAppRoutingTun
perAppRoutingTproxy
perAppZapretEnabled
hasSubscriptions
sshProxyOutboundEnabled
sshProxyUnitEnabled
proxyInboundsEnabled
@@ -115,6 +113,7 @@ let
perAppRouting
routingScripts
;
inherit (cfg) geodata;
};
inherit (serviceUnits)
localProxyAuthEnabled
@@ -122,72 +121,108 @@ let
userServiceEntries
timerEntries
;
in
{
environment.systemPackages = [ control.proxyCtl ];
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.proxyInbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
# autoProxy shells out to the built proxy-ctl, which only exists in this
# scope, so its units are merged in here rather than alongside the other
# feature modules in ../default.nix.
autoProxyUnits = lib.mkIf cfg.proxy.autoProxy.enable (
import ../autoproxy.nix {
inherit lib pkgs cfg;
inherit (control) proxyCtl;
inherit (constants) autoProxyStateDir;
}
);
in
lib.mkMerge [
autoProxyUnits
{
environment.systemPackages = [ control.proxyCtl ];
systemd.user.services = mkNamedUnits userServiceEntries;
# nftables must be on for transparent routing backends. Global TUN uses
# SingBox auto_redirect programs an `inet sing-box` nftables table.
networking.nftables.enable = lib.mkIf (
globalTun.enable
|| globalTproxy.enable
|| perAppRoutingTun.enable
|| perAppRoutingTproxy.enable
|| perAppZapretEnabled
) (lib.mkDefault true);
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
inherit
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
# Inbound listeners are reached from outside, so their ports have to be open.
networking.firewall = lib.mkIf (proxyInboundsEnabled && cfg.inbounds.openFirewall) {
allowedTCPPorts = proxyInboundFirewallPorts;
allowedUDPPorts = proxyInboundFirewallUdpPorts;
};
systemd.services = mkNamedUnits systemServiceEntries;
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
"${userControlCfg.group}" = { };
};
systemd.timers = mkNamedUnits timerEntries;
}
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (
lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${userControlCfg.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${polkit.userControlPolkitRules}
return null;
});
''
);
# Spool dirs for outbounds and subscriptions added at runtime. Setgid so the
# files proxy-ctl drops here inherit the group; without userControl only root
# writes them. tmpfiles rather than the start scripts, so the group can add an
# outbound before the proxy has ever run.
systemd.tmpfiles.rules = lib.mkIf (cfg.enable && proxyEnabled) (
map
(
dir:
"d ${dir} ${
if userControlEnabled then "2770 root ${userControlCfg.group}" else "0700 root root"
} -"
)
[
constants.runtimeOutboundsDir
constants.runtimeSubscriptionsDir
]
);
systemd.user.services = mkNamedUnits userServiceEntries;
assertions = import ../service-assertions.nix {
inherit lib cfg derived;
tgWsProxyCfg = cfg.tgWsProxy;
inherit
builtinTags
outboundTags
effectiveOutboundTags
subscriptionTags
invalidRoutingTargets
;
inherit (perAppRouting)
effectivePerAppRoutingProfileNames
hasProxychainsProfiles
hasTunProfiles
hasTproxyProfiles
hasZapretProfiles
;
};
warnings = lib.optional (proxyEnabled && !derived.hasAvailableOutbounds) (
"proxy-suite: no outbounds or subscriptions are declared; the proxy will not start"
+ " until one is added with `proxy-ctl proxy outbounds add`"
);
systemd.services = mkNamedUnits systemServiceEntries;
systemd.timers = mkNamedUnits timerEntries;
}
]
@@ -44,7 +44,7 @@ let
) defaultPerAppRoutingProfiles;
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
localProxyAuth = proxyCfg.auth;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -65,7 +65,7 @@ let
tcp_connect_time_out 8000
[ProxyList]
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
socks5 ${proxyCfg.listener.address} ${toString proxyCfg.listener.port}
'';
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
+3 -3
View File
@@ -6,15 +6,15 @@
}:
let
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
userControlEnabled = userControlCfg.allow != [ ];
userControlPolkitRules =
lib.optionalString userControlCfg.perApp.enable ''
lib.optionalString (builtins.elem "perApp" userControlCfg.allow) ''
if (unit.indexOf("proxy-suite-per-app-") === 0) {
return polkit.Result.YES;
}
''
+ lib.optionalString userControlCfg.global.enable ''
+ lib.optionalString (builtins.elem "global" userControlCfg.allow) ''
if ((unit.indexOf("proxy-suite-") === 0 &&
unit.indexOf("proxy-suite-per-app-") !== 0) ||
unit === "zapret-discord-youtube.service") {
@@ -1,8 +1,5 @@
# Startup script for the server-side inbound service.
#
# Much smaller than the client start script: no route-mode, no TUN/TProxy, no
# hybrid sidecar. It renders the listeners (reading their secrets), merges them
# into the build-time template, and hands the result to XRay.
# Start script of the inbound service: renders the listeners with their secrets into the
# template and runs XRay.
{
lib,
pkgs,
@@ -23,16 +20,16 @@
proxyInboundsFile,
proxyInboundsSpecFile,
builders,
constants,
}:
let
runtimeDir = "/run/proxy-suite-inbounds";
linksFile = "${runtimeDir}/links.json";
# This service's own package, not the client backend's.
subscriptionsFile = "${runtimeDir}/subscriptions.json";
subsCfg = proxyInboundsCfg.subscriptions;
xray = "${proxyInboundsCfg.package}/bin/xray";
# Only the local proxy needs credentials injected; the listeners' own secrets
# are resolved by build-inbound.py.
needsLocalProxyAuth = proxyInboundsNeedLocalProxy && localProxyAuthEnabled;
serverAddressBlock =
@@ -43,17 +40,15 @@ let
${builders.mkDefaultUplinkIPv4Source {
ip = "${pkgs.iproute2}/bin/ip";
awk = "${pkgs.gawk}/bin/awk";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set proxyInbounds.serverAddress";
errorMessage = "proxy-suite: could not determine this host's uplink address for inbound share links; set inbounds.serverAddress";
}}
SERVER_ADDRESS="$uplink_addr"
''
else
''SERVER_ADDRESS=""'';
# Outbounds a listener pins itself to with `via = "<tag>"`. Rendered here, at
# start time, so a urlFile's contents stay out of the Nix store. Subscriptions
# are deliberately not duplicated into this service: their cache is refreshed
# for the client backend only, and `via = "proxy"` already reaches them.
# Outbounds pinned with `via = "<tag>"`, rendered at start so urlFile contents stay
# out of the store.
mkViaOutboundBlock =
ob:
let
@@ -86,8 +81,6 @@ let
viaOutboundsBlock = lib.concatMapStrings mkViaOutboundBlock proxyInboundViaOutbounds;
# Share links carry the listener credentials, so they are no more public than
# the config itself.
writeLinksBlock = lib.optionalString proxyInboundsCfg.shareLinks ''
${jq} -c '.links' <<< "$RENDERED" > "${linksFile}"
${lib.optionalString userControlEnabled ''
@@ -96,6 +89,28 @@ let
chmod ${if userControlEnabled then "640" else "600"} "${linksFile}"
'';
# One file per user for the web server, plus a token index for proxy-ctl. Filled aside
# and swapped in whole; a missing group leaves them root-only.
writeSubscriptionsBlock = lib.optionalString (proxyInboundsCfg.shareLinks && subsCfg.enable) ''
SUB_DIR="${runtimeDir}/subscriptions"
rm -rf "$SUB_DIR.new"
mkdir -m 0750 "$SUB_DIR.new"
${jq} -r '.subscriptions[] | "\(.token)\t\(.body)"' <<< "$RENDERED" |
while IFS=$'\t' read -r token body; do
printf '%s' "$body" > "$SUB_DIR.new/$token"
done
chmod -R u=rwX,g=rX,o= "$SUB_DIR.new"
${pkgs.coreutils}/bin/chgrp -R ${lib.escapeShellArg subsCfg.group} "$SUB_DIR.new" ||
echo "proxy-suite: group ${subsCfg.group} cannot be given the subscriptions; they stay root-only" >&2
rm -rf "$SUB_DIR"
mv "$SUB_DIR.new" "$SUB_DIR"
${jq} -c '[.subscriptions[] | {user, token}]' <<< "$RENDERED" > "${subscriptionsFile}"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${subscriptionsFile}"
''}
chmod ${if userControlEnabled then "640" else "600"} "${subscriptionsFile}"
'';
startInbounds = pkgs.writeShellScript "proxy-suite-start-inbounds" ''
set -euo pipefail
umask 077
@@ -133,10 +148,42 @@ let
chmod 600 "$RUNTIME_DIR/config.json"
${writeLinksBlock}
${writeSubscriptionsBlock}
exec ${xray} run -c "$RUNTIME_DIR/config.json"
'';
# Adds XRay's per-user counters to the daily totals, read and reset in one call.
# ponytail: a restart of the inbounds loses what was counted since the last run, at
# most one timer interval; collect from ExecStop if that matters.
collectInboundStats = pkgs.writeShellScript "proxy-suite-inbound-stats" ''
set -euo pipefail
file=${lib.escapeShellArg constants.inboundStatsFile}
if ! reading=$(${xray} api statsquery --server=127.0.0.1:${toString constants.inboundStatsApiPort} \
-pattern 'user>>>' -reset 2> /dev/null); then
echo "the inbounds' stats API is not answering; nothing collected"
exit 0
fi
[ -n "$reading" ] || reading='{}'
[ -s "$file" ] || echo '{}' > "$file"
tmp=$(${pkgs.coreutils}/bin/mktemp "$file.XXXXXX")
${jq} --argjson q "$reading" \
--arg day "$(${pkgs.coreutils}/bin/date +%F)" \
--argjson now "$(${pkgs.coreutils}/bin/date +%s)" \
-f ${../inbound-stats-add.jq} "$file" > "$tmp"
${lib.optionalString userControlEnabled ''
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$tmp" ||
echo "proxy-suite: group ${userControlCfg.group} cannot read the stats; they stay root-only" >&2
''}
chmod ${if userControlEnabled then "640" else "600"} "$tmp"
mv -f "$tmp" "$file"
'';
in
{
inherit startInbounds linksFile;
inherit
startInbounds
collectInboundStats
linksFile
subscriptionsFile
;
}
@@ -117,7 +117,7 @@ in
# SingBox normally removes these on graceful shutdown, but stale
# auto_route/auto_redirect state leaves the host routing through a dead TUN
# interface after `proxy-ctl tun off` or an unclean service stop.
# interface after `proxy-ctl proxy tun off` or an unclean service stop.
${builders.mkNftDeleteTable { inherit nft; family = "inet"; table = "sing-box"; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-4"; table = tunAutoRouteTableIndex; }}
${builders.mkIpRuleDeleteByTable { inherit ip; family = "-6"; table = tunAutoRouteTableIndex; }}
@@ -1,6 +1,8 @@
{
lib,
pureXrayEnabled,
selectionMode,
proxyInboundsGuardPrivate,
}:
if pureXrayEnabled then
@@ -95,4 +97,21 @@ else
| .dns.final = $dns_final
| if $clear_dns_rules then .dns.rules = [] else . end
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
# explicit rules win. All [] when off.
| .inbounds += $probe_inbounds
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
''
+ lib.optionalString proxyInboundsGuardPrivate ''
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Last, so only traffic falling through to a direct final is resolved. Local mixed-
# in clients lose names that resolve private.
| if (.route.final // "direct") == "direct" then
.route.rules += [
{inbound: ["mixed-in"], action: "resolve"},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}
]
else . end
''
@@ -1,4 +1,3 @@
# Outbound construction script fragments for backend startup scripts.
{
lib,
pkgs,
@@ -12,18 +11,21 @@
backend,
backendArg,
xraySidecarRoutingMark,
priorityOutboundFile,
runtimeOutboundsDir,
jq,
python3,
parserScriptsPythonPath,
buildOutboundPy,
mkSubscriptionBlock,
mkSubscriptionLoadHelperBlock,
runtimeSubscriptionsBlock,
}:
let
sshProxyTag = "ssh-proxy";
# sing-box domain-strategy names mapped onto XRay's sockopt.domainStrategy.
# XRay's "UseIPv4v6" means "IPv4 first, fall back to IPv6", i.e. prefer_ipv4.
# sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4).
xrayDomainStrategies = {
prefer_ipv4 = "UseIPv4v6";
prefer_ipv6 = "UseIPv6v4";
@@ -54,6 +56,114 @@ let
in
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
# Every outbound that comes from a URL goes through these, whether it was
# declared in Nix or dropped into outbounds.d at runtime.
mkUrlOutboundHelpersBlock =
routingMark:
let
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
parse = backendFlag: markFlag: ''
printf '%s' "$2" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} \
${backendFlag} --tag "$1"${markFlag}
'';
addBlock =
if hybridEnabled then
''
case "$pref" in
xray)
ob=$(_proxy_suite_parse_xray_url "$tag" "$url") || return 1
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
;;
sing-box)
ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url") || return 1
_proxy_suite_add_sing_box_ob "$ob"
;;
*)
if ob=$(_proxy_suite_parse_sing_box_url "$tag" "$url" 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$ob"
elif ob=$(_proxy_suite_parse_xray_url "$tag" "$url"); then
_proxy_suite_add_xray_sidecar_ob "$ob" "$tag"
else
echo "proxy-suite: outbound '$tag' cannot be parsed by SingBox or XRay" >&2
if [ -s "$RUNTIME_DIR/sing-box-parser.err" ]; then
cat "$RUNTIME_DIR/sing-box-parser.err" >&2
fi
return 1
fi
;;
esac
''
else
''
ob=$(_proxy_suite_parse_url "$tag" "$url") || return 1
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
in
''
OUTBOUND_SOURCES_JSON='{}'
_proxy_suite_record_tag_source() {
OUTBOUND_SOURCES_JSON=$(${jq} --arg t "$1" --arg s "$2" '.[$t] = $s' <<< "$OUTBOUND_SOURCES_JSON")
}
# $1 source label, $2 array length before the add, $3 after. Subscriptions
# append an unknown number of outbounds, so they label them by range.
_proxy_suite_record_outbound_source() {
[ "$3" -gt "$2" ] || return 0
OUTBOUND_SOURCES_JSON=$(${jq} \
--argjson sources "$OUTBOUND_SOURCES_JSON" --arg s "$1" \
--argjson b "$2" --argjson a "$3" \
'reduce .[$b:$a][].tag as $t ($sources; .[$t] = $s)' <<< "$OUTBOUNDS_JSON")
}
${
if hybridEnabled then
''
_proxy_suite_parse_sing_box_url() {
${parse "--backend sing-box" markArg}
}
_proxy_suite_parse_xray_url() {
${parse "--backend xray" " --routing-mark ${toString xraySidecarRoutingMark}"}
}
''
else
''
_proxy_suite_parse_url() {
${parse backendArg markArg}
}
''
}
# $1 tag, $2 URL, $3 source label, $4 backend preference (auto|sing-box|xray).
# Returns non-zero when the URL cannot be parsed; the caller decides whether
# that is fatal.
_proxy_suite_add_url_outbound() {
local tag="$1" url="$2" source="$3" pref="''${4:-auto}" ob
${addBlock}
_proxy_suite_record_tag_source "$tag" "$source"
}
# Every runtime outbound, as "<tag>\t<url file>" lines. proxy-ctl refuses
# the reserved names, but the spool is group-writable, so check again here:
# a second outbound tagged "proxy" would quietly shadow the real one.
_proxy_suite_runtime_outbounds() {
local f tag
[ -d "${runtimeOutboundsDir}" ] || return 0
for f in "${runtimeOutboundsDir}"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
case "$tag" in
proxy | direct | block)
echo "proxy-suite: warning: ignoring runtime outbound '$tag': reserved name" >&2
continue
;;
esac
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
mkOutboundBlock =
ob: routingMark: tag:
let
@@ -74,6 +184,7 @@ let
# outbound: ${tag} (static ${backend} json)
OB_JSON=$(cat "${jsonFile}")
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
@@ -82,11 +193,7 @@ let
in
''
# outbound: ${tag}
URL=$(cat "${urlSource}")
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
})
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static || exit 1
'';
singBoxRawOutboundJson =
@@ -117,6 +224,7 @@ let
# outbound: ${tag} (hybrid XRay json sidecar)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else if ob.singBoxJson != null || ob.json != null then
let
@@ -127,66 +235,27 @@ let
# outbound: ${tag} (hybrid SingBox json)
OB_JSON=$(cat "${jsonFile}")
_proxy_suite_add_sing_box_ob "$OB_JSON"
_proxy_suite_record_tag_source ${lib.escapeShellArg tag} static
''
else
let
urlSource =
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
singBoxCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
}
'';
xrayCommand = ''
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark}
'';
in
if ob.backend == "xray" then
''
# outbound: ${tag} (hybrid forced XRay sidecar)
URL=$(cat "${urlSource}")
OB_JSON=$(${xrayCommand})
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
''
else if ob.backend == "sing-box" then
''
# outbound: ${tag} (hybrid forced SingBox)
URL=$(cat "${urlSource}")
OB_JSON=$(${singBoxCommand})
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${tag} (hybrid auto)
URL=$(cat "${urlSource}")
if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then
_proxy_suite_add_sing_box_ob "$OB_JSON"
else
SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)"
if OB_JSON=$(${xrayCommand}); then
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
else
echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2
if [ -n "$SING_BOX_PARSE_ERROR" ]; then
printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2
fi
exit 1
fi
fi
'';
''
# outbound: ${tag} (hybrid ${ob.backend})
_proxy_suite_add_url_outbound ${lib.escapeShellArg tag} "$(cat "${urlSource}")" static ${ob.backend} || exit 1
'';
mkSshProxyOutboundBlock =
routingMark:
let
# sing-box dials SSH itself, so there is no OpenSSH unit and no local
# SOCKS5 hop. It resolves destinations natively, which is why this shape
# takes no domainStrategy.
singBoxOutbound = {
type = "ssh";
tag = sshProxyTag;
server = sshProxyCfg.host;
server_port = sshProxyCfg.sshPort;
user = sshProxyCfg.user;
server = sshProxyCfg.server.host;
server_port = sshProxyCfg.server.port;
user = sshProxyCfg.server.user;
}
// lib.optionalAttrs (sshProxyCfg.identityFile != null) {
private_key_path = sshProxyCfg.identityFile;
@@ -197,9 +266,7 @@ let
// lib.optionalAttrs (routingMark != null) {
routing_mark = routingMark;
};
# XRay has no SSH outbound, so it proxies through the listener the
# OpenSSH unit creates. sockopt.domainStrategy is what makes XRay resolve
# destinations here instead of handing the domain to the remote sshd.
# XRay has no SSH outbound: it goes through the OpenSSH unit's listener.
xraySockopt =
lib.optionalAttrs (routingMark != null) { mark = routingMark; }
// lib.optionalAttrs (sshProxyCfg.domainStrategy != null) {
@@ -209,8 +276,8 @@ let
protocol = "socks";
tag = sshProxyTag;
settings = {
address = sshProxyCfg.listenAddress;
port = sshProxyCfg.listenPort;
address = sshProxyCfg.listener.address;
port = sshProxyCfg.listener.port;
};
}
// lib.optionalAttrs (xraySockopt != { }) {
@@ -220,13 +287,12 @@ let
outboundJson = builtins.toJSON outbound;
jsonFile = pkgs.writeText "proxy-suite-ob-ssh-proxy-${backend}.json" outboundJson;
# Host keys come from a known-hosts file at start time so the file stays
# out of the Nix store. ssh-keygen -F also resolves hashed entries.
# Read at start so the known-hosts file stays out of the store.
knownHostsTarget =
if sshProxyCfg.sshPort == 22 then
sshProxyCfg.host
if sshProxyCfg.server.port == 22 then
sshProxyCfg.server.host
else
"[${sshProxyCfg.host}]:${toString sshProxyCfg.sshPort}";
"[${sshProxyCfg.server.host}]:${toString sshProxyCfg.server.port}";
hostKeyFileBlock =
lib.optionalString (!pureXrayEnabled && sshProxyCfg.hostKeyFile != null)
''
@@ -240,38 +306,71 @@ let
OB_JSON=$(${jq} --argjson hk "$SSH_HOST_KEYS" '.host_key = $hk' <<< "$OB_JSON")
'';
in
if hybridEnabled then
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
_proxy_suite_add_sing_box_ob "$OB_JSON"
''
else
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
'';
''
# outbound: ${sshProxyTag} (${if pureXrayEnabled then "OpenSSH SOCKS5 listener" else "native SSH"})
OB_JSON=$(cat "${jsonFile}")
${hostKeyFileBlock}
${
if hybridEnabled then
''_proxy_suite_add_sing_box_ob "$OB_JSON"''
else
''OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")''
}
_proxy_suite_record_tag_source ${sshProxyTag} ssh
'';
mkBackendOutboundBlock = if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock;
runtimeOutboundsBlock = ''
# outbounds added at runtime
while IFS=$'\t' read -r RUNTIME_OB_TAG RUNTIME_OB_SRC; do
[ -n "$RUNTIME_OB_TAG" ] || continue
_proxy_suite_add_url_outbound "$RUNTIME_OB_TAG" "$(cat "$RUNTIME_OB_SRC")" runtime \
|| echo "proxy-suite: warning: ignoring runtime outbound '$RUNTIME_OB_TAG'" >&2
done < <(_proxy_suite_runtime_outbounds)
'';
requireOutboundsBlock = ''
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2
echo "proxy-suite: no proxy outbounds are available; declare one, or add one with 'proxy-ctl proxy outbounds add'" >&2
exit 1
fi
'';
# The pin names a user-facing tag, so it is resolved before the wrapper block
# renames anything. A pin that no longer matches any outbound - a subscription
# entry that went away, say - is dropped rather than left to break the config.
pinBlock = ''
OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON")
PRIORITY_OUTBOUND=""
if [ -r "${priorityOutboundFile}" ]; then
PRIORITY_OUTBOUND="$(tr -d '\r\n[:space:]' < "${priorityOutboundFile}" 2>/dev/null || true)"
fi
if [ -n "$PRIORITY_OUTBOUND" ] \
&& ! ${jq} -e --arg t "$PRIORITY_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
echo "proxy-suite: warning: pinned outbound '$PRIORITY_OUTBOUND' is not available; picking automatically" >&2
PRIORITY_OUTBOUND=""
fi
'';
# proxy-ctl reads this unprivileged: tags, where each came from, and the pin.
inventoryBlock = ''
${jq} -n \
--argjson tags "$OUTBOUND_TAGS_JSON" \
--argjson sources "$OUTBOUND_SOURCES_JSON" \
--arg pinned "$PRIORITY_OUTBOUND" \
--arg selection ${lib.escapeShellArg selectionMode} \
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection}' \
> "$RUNTIME_DIR/outbounds.json"
chmod 644 "$RUNTIME_DIR/outbounds.json"
'';
mkOutboundScript =
routingMark:
let
outboundBlocks =
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
mkBackendOutboundBlock (builtins.head proxyCfg.outbounds) routingMark "proxy"
else
lib.concatMapStrings (ob: mkBackendOutboundBlock ob routingMark ob.tag) proxyCfg.outbounds;
outboundBlocks = lib.concatMapStrings (
ob: mkBackendOutboundBlock ob routingMark ob.tag
) proxyCfg.outbounds;
subscriptionBlocks = lib.concatMapStrings (
sub: mkSubscriptionBlock sub routingMark
@@ -283,43 +382,74 @@ let
if pureXrayEnabled && selectionMode == "urltest" then
''
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
# XRay has no selector: a pin degrades the balancer to the one outbound,
# which is the same path a single-outbound config already takes.
if [ -n "$PRIORITY_OUTBOUND" ]; then
XRAY_SINGLE_PROXY_TAG="proxy-suite-ob-$PRIORITY_OUTBOUND"
elif [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
fi
''
else if collapseNamedOutbounds then
lib.optionalString
(proxyCfg.outbounds == [ ] && (proxyCfg.subscriptions != [ ] || sshProxyCfg.asOutbound))
''
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
if [ -n "$FIRST_TAG" ]; then
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
fi
''
''
PROXY_TAG="$PRIORITY_OUTBOUND"
if [ -z "$PROXY_TAG" ]; then
PROXY_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" \
'map(if .tag == $t then .tag = "proxy" else . end)' <<< "$OUTBOUNDS_JSON")
''
else if selectionMode == "selector" then
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
FIRST=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
DEFAULT_TAG="$PRIORITY_OUTBOUND"
if [ -z "$DEFAULT_TAG" ]; then
DEFAULT_TAG=$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")
fi
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$FIRST" \
--arg default "$DEFAULT_TAG" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
''
else
''
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
if [ -n "$PRIORITY_OUTBOUND" ]; then
# A pin beats latency ranking: the same outbounds, behind a selector
# the Clash API can also switch live.
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg default "$PRIORITY_OUTBOUND" \
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default}')
else
WRAPPER=$(${jq} -n \
--argjson tags "$TAGS" \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
fi
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
'';
# Real exits for autoProxy, taken after the wrapper may have renamed one to
# "proxy".
exitTagsBlock = ''
EXIT_TAGS_JSON=$(${jq} -c '[.[] | select(.type != "selector" and .type != "urltest") | .tag]' <<< "$OUTBOUNDS_JSON")
'';
in
outboundBlocks + subscriptionBlocks + sshProxyBlock + requireOutboundsBlock + wrapperBlock;
mkUrlOutboundHelpersBlock routingMark
+ mkSubscriptionLoadHelperBlock routingMark
+ outboundBlocks
+ subscriptionBlocks
+ runtimeSubscriptionsBlock
+ runtimeOutboundsBlock
+ sshProxyBlock
+ requireOutboundsBlock
+ pinBlock
+ inventoryBlock
+ wrapperBlock
+ exitTagsBlock;
in
{
inherit mkOutboundScript rawOutboundJson;
@@ -1,12 +1,16 @@
# Subscription cache and outbound-loading script fragments.
#
# Everything is emitted as shell functions taking a tag and a file holding the
# subscription URL, so a subscription declared in Nix and one added at runtime
# under `subscriptions.d/` go through exactly the same code.
{
lib,
pkgs,
proxyCfg,
hasSubscriptions,
hybridEnabled,
mainBackend,
backend,
runtimeSubscriptionsDir,
jq,
python3,
parserScriptsPythonPath,
@@ -19,8 +23,6 @@ let
subscriptionBackendArg = "--backend ${subscriptionBackend}";
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
mkSubscriptionUrlSource =
sub:
if sub.urlFile != null then
@@ -28,20 +30,12 @@ let
else
pkgs.writeText "proxy-suite-sub-url-${sub.tag}" sub.url;
mkSubscriptionFetchCommand =
sub:
let
urlSource = mkSubscriptionUrlSource sub;
in
# Both call sites append their own `> "$CACHE_FILE.tmp"`, so this must not
# end in a newline: that would close the pipeline and turn the redirect
# into a separate command that just truncates the cache to zero bytes.
lib.removeSuffix "\n" ''
printf '%s' "$(cat "${urlSource}")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
'';
# Defined in every script that touches a cache: the start scripts and the
# update unit.
subscriptionCacheHelpersBlock = ''
SUB_CACHE_DIR="${subscriptionCacheDir}"
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
@@ -71,77 +65,122 @@ let
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(cat "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" > "$cache.tmp"; then
_proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"
return
fi
rm -f "$cache.tmp"
echo "proxy-suite: failed to update subscription '$tag'" >&2
return 1
}
# Every runtime subscription, as "<tag>\t<url file>" lines.
_proxy_suite_runtime_subscriptions() {
local f tag
[ -d "$RUNTIME_SUBS_DIR" ] || return 0
for f in "$RUNTIME_SUBS_DIR"/*.url; do
[ -e "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
mkSubscriptionBlock =
sub: routingMark:
# Merging a cache into OUTBOUNDS_JSON needs the routing mark, which differs per
# start script, so this one is emitted separately from the cache helpers.
mkSubscriptionLoadHelperBlock =
routingMark:
let
cacheFile = mkSubscriptionCacheFile sub;
markFilter = routingMarkJq routingMark;
in
''
# subscription: ${sub.tag}
CACHE_DIR="${subscriptionCacheDir}"
CACHE_FILE="${cacheFile}"
_proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag}
if [ ! -f "$CACHE_FILE" ]; then
mkdir -p "$CACHE_DIR"
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
_proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true
else
rm -f "$CACHE_FILE.tmp"
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
fi
fi
${
subVar = if hybridEnabled then "SUB_SING_BOX_JSON" else "SUB_JSON";
# Plain string concatenation: "$" next to an interpolation is exactly the
# spot where an indented string's escaping bites.
markBlock = lib.optionalString (routingMark != null) (
subVar + "=$(${jq} 'map(.${markFilter})' <<< \"$" + subVar + "\")\n"
);
mergeBlock =
if hybridEnabled then
''
if [ -f "$CACHE_FILE" ]; then
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$CACHE_FILE")
fi
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
while IFS= read -r SUB_XRAY_OB; do
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
done < <(${jq} -c '.xray[]' "$cache")
''
else
''
if [ -f "$CACHE_FILE" ]; then
SUB_JSON=$(cat "$CACHE_FILE")
${
lib.optionalString (routingMark != null) ''
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
''
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
fi
''
SUB_JSON=$(cat "$cache")
${markBlock}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
'';
in
''
# $1 tag, $2 file holding the subscription URL. Fetches on a cold cache and
# merges whatever is cached; a subscription that cannot be fetched is a
# warning, never a failed start.
_proxy_suite_load_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" before after
_proxy_suite_drop_invalid_subscription_cache "$cache" "$tag"
if [ ! -f "$cache" ]; then
_proxy_suite_fetch_subscription "$tag" "$src" \
|| echo "proxy-suite: warning: could not fetch subscription '$tag'" >&2
fi
[ -f "$cache" ] || return 0
before=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
${mergeBlock}
after=$(${jq} 'length' <<< "$OUTBOUNDS_JSON")
_proxy_suite_record_outbound_source "sub:$tag" "$before" "$after"
}
'';
mkSubscriptionBlock =
sub: _routingMark:
''
# subscription: ${sub.tag}
_proxy_suite_load_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}
'';
runtimeSubscriptionsBlock = ''
# subscriptions added at runtime
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
_proxy_suite_load_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"
done < <(_proxy_suite_runtime_subscriptions)
'';
mkSubscriptionFetchBlock =
sub:
let
cacheFile = mkSubscriptionCacheFile sub;
in
''
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then
echo "Updated subscription: ${sub.tag}"
else
FAILED=1
fi
if _proxy_suite_fetch_subscription ${lib.escapeShellArg sub.tag} ${
lib.escapeShellArg (mkSubscriptionUrlSource sub)
}; then
echo "Updated subscription: ${sub.tag}"
else
rm -f "${cacheFile}.tmp"
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
FAILED=1
fi
'';
runtimeSubscriptionsFetchBlock = ''
while IFS=$'\t' read -r RUNTIME_SUB_TAG RUNTIME_SUB_SRC; do
[ -n "$RUNTIME_SUB_TAG" ] || continue
if _proxy_suite_fetch_subscription "$RUNTIME_SUB_TAG" "$RUNTIME_SUB_SRC"; then
echo "Updated subscription: $RUNTIME_SUB_TAG"
else
FAILED=1
fi
done < <(_proxy_suite_runtime_subscriptions)
'';
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
);
@@ -150,8 +189,11 @@ in
inherit
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
}
+44 -6
View File
@@ -13,7 +13,6 @@
userControlCfg,
selectionMode,
collapseNamedOutbounds,
hasSubscriptions,
constants,
jq,
python3,
@@ -28,6 +27,7 @@
routeModeRulesFile,
proxyInboundsCfg,
proxyInboundsNeedLocalProxy,
proxyInboundsGuardPrivate,
proxyInboundViaOutbounds,
userControlEnabled,
buildInboundPy,
@@ -42,7 +42,7 @@ let
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
backendArg = "--backend ${mainBackend}";
backendBin = if pureXrayEnabled then xray else singBox;
localProxyAuth = proxyCfg.auth;
localProxyAuth = proxyCfg.listener.auth;
localProxyAuthEnabled =
localProxyAuth.username != null
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
@@ -54,6 +54,13 @@ let
else
null;
routeModeStateFile = "/run/proxy-suite/route-mode";
inherit (constants)
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
;
clashApi = "http://127.0.0.1:${toString singBoxCfg.clashApiPort}";
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
xraySidecarRoutingMark = globalTproxy.proxyMark;
@@ -72,10 +79,10 @@ let
lib
pkgs
proxyCfg
hasSubscriptions
hybridEnabled
mainBackend
backend
runtimeSubscriptionsDir
jq
python3
parserScriptsPythonPath
@@ -86,8 +93,11 @@ let
inherit (subscriptionScripts)
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionLoadHelperBlock
mkSubscriptionBlock
runtimeSubscriptionsBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
subscriptionTagsFile
;
@@ -105,11 +115,15 @@ let
backend
backendArg
xraySidecarRoutingMark
priorityOutboundFile
runtimeOutboundsDir
jq
python3
parserScriptsPythonPath
buildOutboundPy
mkSubscriptionBlock
mkSubscriptionLoadHelperBlock
runtimeSubscriptionsBlock
;
};
inherit (outboundScripts) mkOutboundScript;
@@ -125,8 +139,10 @@ let
backendJqFilter = import ./script-blocks/backend-jq-filter.nix {
inherit
lib
pureXrayEnabled
selectionMode
proxyInboundsGuardPrivate
;
};
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" backendJqFilter;
@@ -186,38 +202,60 @@ let
proxyInboundsFile
proxyInboundsSpecFile
builders
constants
;
};
inherit (proxyInboundsScripts) startInbounds;
inherit (proxyInboundsScripts) startInbounds collectInboundStats;
proxyInboundsLinksFile = proxyInboundsScripts.linksFile;
proxyInboundsSubscriptionsFile = proxyInboundsScripts.subscriptionsFile;
controlScripts = import ./control-scripts.nix {
inherit
lib
pkgs
proxyCfg
clashApi
routeModeStateFile
priorityOutboundFile
outboundInventoryFile
subscriptionCacheDir
subscriptionCacheHelpersBlock
mkSubscriptionFetchBlock
runtimeSubscriptionsFetchBlock
jq
;
};
inherit (controlScripts)
subscriptionUpdateScript
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
;
in
{
inherit startSocks startTun startPerAppTun startInbounds;
inherit
startSocks
startTun
startPerAppTun
startInbounds
collectInboundStats
;
inherit
proxyInboundsLinksFile
proxyInboundsSubscriptionsFile
routeModeStateFile
setRouteModeScript
setPriorityOutboundScript
reloadOutboundsScript
subscriptionUpdateScript
hasSubscriptions
subscriptionTagsFile
subscriptionCacheDir
runtimeProxychainsConfig
priorityOutboundFile
runtimeOutboundsDir
runtimeSubscriptionsDir
outboundInventoryFile
clashApi
;
}
+52 -2
View File
@@ -32,10 +32,13 @@
let
inherit (constants)
autoProxyStateDir
xrayDnsBridgePorts
xraySidecarBasePorts
;
autoProxyRender = import ../autoproxy-render.nix { inherit pkgs; };
routeModeBlacklistTail =
if pureXrayEnabled then
''
@@ -119,8 +122,8 @@ let
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listenAddress} \
${lib.escapeShellArg (toString proxyCfg.port)} \
${lib.escapeShellArg proxyCfg.listener.address} \
${lib.escapeShellArg (toString proxyCfg.listener.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
@@ -139,6 +142,7 @@ let
xrayTunDnsRuntime ? false,
xraySidecarBasePort ? xraySidecarBasePorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
}:
pkgs.writeShellScript name ''
set -euo pipefail
@@ -190,8 +194,52 @@ let
${mkOutboundScript routingMark}
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
# autoProxy: a loopback listener and a learned rule-set per exit, generated here
# because subscription tags only exist at runtime.
PROBE_INBOUNDS_JSON='[]'
PROBE_PIN_RULES_JSON='[]'
AUTOPROXY_RULE_SETS_JSON='[]'
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
install -d -m 0750 "$AUTOPROXY_DIR"
[ -s "$AUTOPROXY_DIR/state.json" ] || echo '{"domains":{},"hosts":{},"exits":{},"backlog":{}}' > "$AUTOPROXY_DIR/state.json"
# direct is always exit 0; state is keyed by tag, so shifting indices are
# harmless.
PROBE_EXITS_JSON=$(${jq} -c \
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
--arg dir "$AUTOPROXY_DIR" '
(["direct"] + map(select(. != "direct")))[0:$max]
| to_entries
| map({i: .key, tag: .value, port: ($base + .key),
rule_set: ("autoproxy-" + (.key | tostring)),
path: ($dir + "/rs-" + (.key | tostring) + ".json")})
' <<< "$EXIT_TAGS_JSON")
printf '%s\n' "$PROBE_EXITS_JSON" > "$RUNTIME_DIR/probe-exits.json"
# proxy-ctl reads it unprivileged; it holds tags and loopback ports only.
chmod 644 "$RUNTIME_DIR/probe-exits.json"
${autoProxyRender} "$RUNTIME_DIR/probe-exits.json" "$AUTOPROXY_DIR/state.json"
PROBE_INBOUNDS_JSON=$(${jq} -c 'map({type: "mixed", tag: ("probe-in-" + (.i | tostring)),
listen: "127.0.0.1", listen_port: .port})' <<< "$PROBE_EXITS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c 'map({inbound: ["probe-in-" + (.i | tostring)],
outbound: .tag})' <<< "$PROBE_EXITS_JSON")
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c 'map({type: "local", format: "source",
tag: .rule_set, path: .path})' <<< "$PROBE_EXITS_JSON")
# all-bypass means everything direct; learned exits must not override it.
if [ "$ROUTE_MODE" != all-bypass ]; then
AUTOPROXY_RULES_JSON=$(${jq} -c 'map({rule_set: [.rule_set], outbound: .tag})' <<< "$PROBE_EXITS_JSON")
fi
''}
${jq} \
--argjson obs "$OUTBOUNDS_JSON" \
--argjson probe_inbounds "$PROBE_INBOUNDS_JSON" \
--argjson probe_pin_rules "$PROBE_PIN_RULES_JSON" \
--argjson autoproxy_rule_sets "$AUTOPROXY_RULE_SETS_JSON" \
--argjson autoproxy_rules "$AUTOPROXY_RULES_JSON" \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
@@ -259,6 +307,8 @@ let
enableLocalProxyAuth = localProxyAuthEnabled;
xraySidecarBasePort = xraySidecarBasePorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
};
startTun = mkStartScript {
+66 -13
View File
@@ -11,7 +11,6 @@
perAppRoutingTun,
perAppRoutingTproxy,
perAppZapretEnabled,
hasSubscriptions,
sshProxyOutboundEnabled,
sshProxyUnitEnabled,
proxyInboundsEnabled,
@@ -19,6 +18,7 @@
scripts,
perAppRouting,
routingScripts,
geodata,
}:
let
@@ -45,6 +45,7 @@ let
perAppZapret = "proxy-suite-per-app-zapret";
subscriptionUpdate = "proxy-suite-subscription-update";
inbounds = "proxy-suite-inbounds";
inboundStats = "proxy-suite-inbound-stats";
};
backendDescription =
@@ -56,8 +57,13 @@ let
"sing-box";
localProxyAuthEnabled =
proxyCfg.auth.username != null
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
proxyCfg.listener.auth.username != null
&& (proxyCfg.listener.auth.password != null || proxyCfg.listener.auth.passwordFile != null);
# XRay finds geoip.dat/geosite.dat through this; sing-box ignores it.
xrayAssetEnv = lib.optionalAttrs (geodata.xray.assets != null) {
Environment = [ "XRAY_LOCATION_ASSET=${geodata.xray.assets}/share/v2ray" ];
};
systemServiceEntries = [
{
@@ -65,8 +71,7 @@ let
name = serviceNames.socks;
value = mkRestartingService {
description = "${backendDescription} proxy client (SOCKS + TProxy-ready)";
# Only the XRay backend proxies through the OpenSSH unit's listener;
# SingBox dials SSH inside its own process and needs no ordering.
# Only XRay goes through the OpenSSH unit's listener.
after = [
"network-online.target"
]
@@ -79,6 +84,7 @@ let
execStart = scripts.startSocks;
runtimeDirectory = serviceNames.socks;
stateDirectory = "proxy-suite";
extraServiceConfig = xrayAssetEnv;
};
}
{
@@ -89,9 +95,8 @@ let
after = [
"network-online.target"
]
# Relayed traffic leaves through the client stack's SOCKS listener, so
# start after it. Not `requires`: the listeners should keep serving
# direct-routed traffic even if the client stack is down.
# After the client stack, but not `requires`: direct listeners keep serving
# without it.
++ lib.optional proxyInboundsNeedLocalProxy "${serviceNames.socks}.service";
wants = [
"network-online.target"
@@ -100,6 +105,19 @@ let
wantedBy = [ "multi-user.target" ];
execStart = scripts.startInbounds;
runtimeDirectory = serviceNames.inbounds;
extraServiceConfig = xrayAssetEnv;
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = mkOneshotService {
description = "proxy-suite - add up per-user traffic through the inbounds";
after = [ "${serviceNames.inbounds}.service" ];
execStart = scripts.collectInboundStats;
stateDirectory = "proxy-suite";
# Run by a timer: a unit left "active" would never be started again.
extraServiceConfig.RemainAfterExit = false;
};
}
{
@@ -111,7 +129,7 @@ let
"network.target"
"${serviceNames.socks}.service"
];
wantedBy = lib.optionals globalTproxy.autostart [ "multi-user.target" ];
wantedBy = lib.optionals (proxyCfg.autostart == "tproxy") [ "multi-user.target" ];
requires = [ "${serviceNames.socks}.service" ];
conflicts = [
"${serviceNames.tun}.service"
@@ -128,7 +146,7 @@ let
description = "${backendDescription} TUN proxy client";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
wantedBy = lib.optionals (proxyCfg.autostart == "tun") [ "multi-user.target" ];
conflicts = [ "${serviceNames.tproxy}.service" ];
execStartPre = tunCleanupScript;
execStart = scripts.startTun;
@@ -202,7 +220,8 @@ let
};
}
{
enable = proxyEnabled && hasSubscriptions;
# Not gated on hasSubscriptions: runtime subscriptions need refreshing too.
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = mkOneshotService {
description = "Refresh proxy-suite subscription caches";
@@ -221,6 +240,26 @@ let
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-select@";
value = mkOneshotService {
description = "Pin the proxy-suite priority outbound to %i";
execStart = "${scripts.setPriorityOutboundScript} %i";
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
{
enable = proxyEnabled;
name = "proxy-suite-outbound-reload";
value = mkOneshotService {
description = "Apply proxy-suite outbounds and subscriptions added at runtime";
execStart = scripts.reloadOutboundsScript;
stateDirectory = "proxy-suite";
extraServiceConfig.RemainAfterExit = false;
};
}
];
userServiceEntries = [
@@ -243,17 +282,31 @@ let
timerEntries = [
{
enable = proxyEnabled && hasSubscriptions;
enable = proxyEnabled;
name = serviceNames.subscriptionUpdate;
value = {
description = "Periodic proxy-suite subscription refresh";
wantedBy = [ "timers.target" ];
timerConfig = {
OnBootSec = "5m";
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
};
};
}
{
enable = proxyInboundsEnabled;
name = serviceNames.inboundStats;
value = {
description = "proxy-suite per-user inbound traffic collection";
wantedBy = [ "timers.target" ];
timerConfig = {
# OnActiveSec, not OnBootSec: see the autoProxy timer.
OnActiveSec = "5m";
OnUnitActiveSec = "5m";
};
};
}
];
in
{