Files
2026-10-11 11:18:48 +05:00

634 lines
31 KiB
Nix

# Backend startup script derivations.
{ ctx }:
let
inherit (ctx)
lib
pkgs
proxyCfg
perAppRoutingCfg
userControlCfg
userControlAllows
globalTproxy
xrayEnabled
hybridEnabled
pureXrayEnabled
xrayLogLevel
constants
zapretCutoffProxyFallback
zapret2DirectSync
zapret2ProxyFallback
jq
singBox
xray
backendBin
routeModeStateFile
routeModeRulesFile
xrayLoglevelFile
runtimeProxychainsConfig
localProxyAuth
localProxyAuthEnabled
localProxyAuthPasswordSource
backendJqFilterFile
hybridRuntimeHelpersBlock
subscriptionCacheHelpersBlock
mkOutboundScript
tproxyFile
tunFile
perAppTunFile
;
inherit (constants)
autoProxyStateDir
autoProxySpoolDir
outboundTestPort
xrayDnsBridgePorts
xraySidecarPorts
;
autoProxyRender = import ../autoproxy-render.nix {
inherit pkgs;
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 =
(!userControlCfg.enable && localProxyAuthEnabled)
|| userControlAllows "outbounds"
|| userControlAllows "autoProxy";
probeLoginExtraGroups = lib.unique (
ctx.userControlExtraGroupsFor "outbounds" ++ ctx.userControlExtraGroupsFor "autoProxy"
);
runBackend = constants.runAsServiceUser pkgs constants.backendCaps;
userControlGroup = lib.escapeShellArg userControlCfg.group;
chgrp = "${pkgs.coreutils}/bin/chgrp";
# 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";
}
{
mode = "whitelist";
final = "direct";
dns = "local";
}
{
# Only the proxy and block lists are kept: everything else follows the final action.
mode = "all-proxy";
final = "proxy";
dns = "remote";
clearDns = true;
}
{
mode = "all-bypass";
final = "direct";
dns = "local";
clearDns = true;
}
];
# 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";
mkRouteModeArm =
arm:
lib.concatStringsSep "\n" (
[
" ${arm.mode})"
" ROUTE_FINAL=\"${arm.final}\""
" DNS_FINAL=\"${arm.dns}\""
" ROUTE_MODE_ACTIVE=true"
]
++ lib.optional (arm.clearDns or false) " CLEAR_DNS_RULES=true"
++ [ " ;;" ]
);
routeModeCaseBlock = ''
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${lib.concatMapStrings (arm: "\n" + mkRouteModeArm arm) routeModeArms}
*)
ROUTE_MODE=""
;;
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.
case "''${LOCAL_PROXY_PASSWORD:-}" in
*[[:space:]]*)
echo "proxy-suite: listener.auth's password has whitespace, which proxychains cannot take; no proxychains config" >&2
rm -f "${runtimeProxychainsConfig}"
;;
*)
# Private from the start: the chmod below would leave a moment where anyone reads it.
(umask 077 && : > "${runtimeProxychainsConfig}")
{
printf '%s\n' 'strict_chain'
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
printf '%s\n' 'tcp_read_time_out 15000'
printf '%s\n' 'tcp_connect_time_out 8000'
printf '\n%s\n' '[ProxyList]'
printf 'socks5 %s %s %s %s\n' \
${lib.escapeShellArg proxyCfg.listener.address} \
${lib.escapeShellArg (toString proxyCfg.listener.port)} \
${lib.escapeShellArg localProxyAuth.username} \
"$LOCAL_PROXY_PASSWORD"
} > "${runtimeProxychainsConfig}"
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"''}
# Without root the group is the user's own primary one, which may be shared.
chmod ${if constants.privileged then "640" else "600"} "${runtimeProxychainsConfig}"
# It holds the proxy's password: userControl.groups that run apps through proxychains.
${constants.grantFileAcl pkgs ''"${runtimeProxychainsConfig}"''
(ctx.userControlExtraGroupsFor "perApp")
"r"
}
;;
esac
'';
mkStartScript =
{
runtimeDir,
configFile,
routingMark ? null,
enableLocalProxyAuth ? false,
xrayTunDnsRuntime ? false,
xraySidecarPort ? xraySidecarPorts.socks,
xrayDnsBridgePort ? xrayDnsBridgePorts.socks,
enableAutoProxy ? false,
enableOutboundTest ? false,
enableZapretCutoff ? false,
enableZapretDirect ? false,
enableZapretProxy ? false,
excludeServiceUserFromTun ? false,
}:
pkgs.writeShellScript "proxy-suite-core" ''
set -euo pipefail
RUNTIME_DIR="${runtimeDir}"
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
# debug.logLevel; empty keeps each config's own "warning".
XRAY_LOGLEVEL=${lib.escapeShellArg (lib.optionalString (xrayLogLevel != "warning") xrayLogLevel)}
XRAY_SINGLE_PROXY_TAG=""
mkdir -p "$RUNTIME_DIR"
OUTBOUNDS_JSON='[]'
ROUTE_MODE=""
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}
${subscriptionCacheHelpersBlock}
${lib.optionalString enableLocalProxyAuth ''
LOCAL_PROXY_PASSWORD="$(cat ${lib.escapeShellArg localProxyAuthPasswordSource})"
# The umask stays in the subshell: left set, it also narrowed everything
# written below, and autoProxy's state.json is group-readable by design.
(
umask 077
${writeProxychainsConfigBlock}
)
''}
${lib.optionalString xrayEnabled ''
if [ -r "${xrayLoglevelFile}" ]; then
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
fi
''}
${routeModeCaseBlock}
# Only this instance's Clash API is what proxy-suite-outbound-groups drives.
GROUPS_WATCHED=${if enableOutboundTest then "true" else "false"}
${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='[]'
PROBE_PIN_RULES_JSON='[]'
AUTOPROXY_RULE_SETS_JSON='[]'
AUTOPROXY_RULES_JSON='[]'
${lib.optionalString enableAutoProxy ''
AUTOPROXY_DIR=${lib.escapeShellArg autoProxyStateDir}
# Root's alone, 0751: sing-box, running as ${constants.serviceUser}, reaches the
# rules/ inside. An install from before the spool is made so first.
${autoProxyMigrate} "$AUTOPROXY_DIR" ${lib.escapeShellArg autoProxySpoolDir}
[ -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. Disabled outbounds are no exit: the prober drops what was learned
# through them.
PROBE_EXITS_JSON=$(${jq} -c \
--argjson max ${toString proxyCfg.autoProxy.maxExits} \
--argjson base ${toString proxyCfg.autoProxy.probeBasePort} \
--slurpfile disabled <(printf '%s' "''${DISABLED_TAGS_JSON:-[]}") \
--arg dir "$AUTOPROXY_DIR" '
(["direct"] + map(select(. != "direct" and (. as $t | $disabled[0] | index([$t]) | not))))[0:$max]
| to_entries
| map({i: .key, tag: .value, port: ($base + .key),
rule_set: ("autoproxy-" + (.key | tostring)),
path: ($dir + "/rules/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")
# The hosts probed are ones the inbounds' clients dialed: the direct probe gets their
# fence (inbounds.routing.blockPrivate), resolving as a direct dial would.
PROBE_PIN_RULES_JSON=$(${jq} -c --argjson fence ${
lib.escapeShellArg (
builtins.toJSON (
if ctx.proxyInboundsCfg.routing.blockPrivate then
{ ip_is_private = true; }
else
{ ip_cidr = ctx.proxyInboundsLoopback; }
)
)
} '[{inbound: ["probe-in-0"], action: "resolve", server: "local"}, ({inbound: ["probe-in-0"], action: "reject"} + $fence)]
+ 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
''}
${lib.optionalString enableOutboundTest ''
# proxy-ctl proxy outbounds test. Servers for its ping, keyed by the user's tag:
# XRay's urltest wrapper prefixes them all, and a
# hybrid XRay outbound is a sing-box socks hop whose real server is the sidecar's.
# A loopback hop (the WARP tunnel, XRay's SSH listener) has no server worth timing.
ENDPOINTS_TMP="$RUNTIME_DIR/outbound-endpoints.json.tmp"
(umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") '
$sidecar[0] as $sidecar
| def endpoint:
if .server then {server, port: .server_port}
elif .settings.address then {server: .settings.address, port: .settings.port}
elif .settings.vnext then {server: .settings.vnext[0].address, port: .settings.vnext[0].port}
elif .settings.servers then {server: .settings.servers[0].address, port: .settings.servers[0].port}
else null end;
# XRay dials XHTTP over HTTP/3, on UDP, when its ALPN is h3 alone (and not REALITY);
# mKCP is UDP as well. Their servers have no TCP handshake to time either.
def udp: (.type // .protocol) as $t | .streamSettings.network? as $net
| (["hysteria", "hysteria2", "tuic"] | index($t) != null) or .quic? == true
or ($net == "xhttp" and .streamSettings.security? == "tls"
and .streamSettings.tlsSettings.alpn? == ["h3"])
or $net == "kcp" or $net == "mkcp";
($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| [.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-")) as $tag
| ($real[.tag] // .) | select(endpoint != null and (endpoint.server | test("^(127\\.|::1$|localhost$)") | not))
| {key: $tag, value: (endpoint + {network: (if udp then "udp" else "tcp" end)})}]
| from_entries
' <<< "$OUTBOUNDS_JSON" > "$ENDPOINTS_TMP")
# Where each proxy server is: not credentials, but not for every local user either.
${
if userControlCfg.enable || localProxyAuthEnabled then
''
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$ENDPOINTS_TMP"''}
chmod 640 "$ENDPOINTS_TMP"
${constants.grantFileAcl pkgs ''"$ENDPOINTS_TMP"'' ctx.userControlExtraGroups "r"}
''
else
''chmod 600 "$ENDPOINTS_TMP"''
}
mv "$ENDPOINTS_TMP" "$RUNTIME_DIR/outbound-endpoints.json"
# proxy-ctl's share links: the URL each outbound was given, and its backend JSON.
# Credentials: root and the userControl group only.
SHARE_TMP="$RUNTIME_DIR/outbound-share.json.tmp"
(umask 077 && ${jq} -c --slurpfile sidecar <(printf '%s' "''${XRAY_OUTBOUNDS_JSON:-[]}") \
--slurpfile urls <(printf '%s' "$OUTBOUND_URLS_JSON") --slurpfile subs <(printf '%s' "$SUBSCRIPTION_URLS_JSON") '
$sidecar[0] as $sidecar | $urls[0] as $urls | $subs[0] as $subs
| ($sidecar | map({key: .tag, value: .}) | from_entries) as $real
| {outbounds: ([.[] | select(.type != "selector" and .type != "urltest")
| (.tag | ltrimstr("proxy-suite-ob-")) as $tag
| {key: $tag, value: {url: $urls[$tag], outbound: (($real[$tag] // $real[.tag] // .) | .tag = $tag)}}]
| from_entries),
subscriptions: $subs}
' <<< "$OUTBOUNDS_JSON" > "$SHARE_TMP")
${lib.optionalString (userControlAllows "secrets") ''${chgrp} ${userControlGroup} "$SHARE_TMP"''}
chmod ${if userControlAllows "secrets" then "640" else "600"} "$SHARE_TMP"
${constants.grantFileAcl pkgs ''"$SHARE_TMP"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
mv "$SHARE_TMP" "$RUNTIME_DIR/outbound-share.json"
${lib.optionalString (!pureXrayEnabled) ''
# Delay and download: a loopback listener pinned to a selector over every real
# exit, switched one outbound at a time through the Clash API.
# Slurped, not --argjson: one argument holds at most 128 KiB, less than the tags
# of a large subscription.
OUTBOUNDS_JSON=$(${jq} -c --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
'. + [{type: "selector", tag: "proxy-suite-test", outbounds: $tags[0]}]' <<< "$OUTBOUNDS_JSON")
PROBE_INBOUNDS_JSON=$(${jq} -c '. + [{type: "mixed", tag: "proxy-suite-test-in",
listen: "127.0.0.1", listen_port: ${toString outboundTestPort}}]' <<< "$PROBE_INBOUNDS_JSON")
PROBE_PIN_RULES_JSON=$(${jq} -c \
'. + [{inbound: ["proxy-suite-test-in"], outbound: "proxy-suite-test"}]' <<< "$PROBE_PIN_RULES_JSON")
${jq} -n --slurpfile tags <(printf '%s' "$EXIT_TAGS_JSON") \
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} '
{port: ${toString outboundTestPort}, selector: "proxy-suite-test", url: $url,
outbounds: ($tags[0] | map({key: ., value: .}) | from_entries)}
' > "$RUNTIME_DIR/outbound-test.json"
# Tags and a loopback port only.
chmod 644 "$RUNTIME_DIR/outbound-test.json"
''}
''}
${lib.optionalString enableZapretCutoff ''
# zapret2's cutoff probe lists the prefixes of cut-off networks no whitelisted
# name gets through; the proxy carries those. sing-box refuses a missing
# rule-set path and reloads the file when the probe renames a new one in.
if [ "$ROUTE_MODE" != all-bypass ]; then
CUTOFF_RULE_SET=${lib.escapeShellArg "${constants.zapret2CutoffDir}/proxy.json"}
# The cutoff unit owns the directory's mode (the group asks for probes there).
mkdir -p "$(dirname "$CUTOFF_RULE_SET")"
[ -s "$CUTOFF_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$CUTOFF_RULE_SET"
chmod 644 "$CUTOFF_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$CUTOFF_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-cutoff", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-cutoff"], outbound: "proxy"}]' <<< "$AUTOPROXY_RULES_JSON")
fi
''}
${lib.optionalString enableZapretProxy ''
# What zapret2 cannot fix (its strategies all failed for a site, or an address
# leaves connections unanswered) goes through the proxy: after explicit rules,
# autoProxy and the cutoff's networks, ahead of the hosts zapret2 does fix.
if [ "$ROUTE_MODE" != all-bypass ]; then
ZAPRET_PROXY_SET=${lib.escapeShellArg "${constants.zapret2DirectDir}/proxy.json"}
mkdir -p "$(dirname "$ZAPRET_PROXY_SET")"
[ -s "$ZAPRET_PROXY_SET" ] || echo '{"version":1,"rules":[]}' > "$ZAPRET_PROXY_SET"
chmod 644 "$ZAPRET_PROXY_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$ZAPRET_PROXY_SET" \
'. + [{type: "local", format: "source", tag: "zapret-unfixable", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-unfixable"], outbound: "proxy"}]' <<< "$AUTOPROXY_RULES_JSON")
fi
''}
${lib.optionalString enableZapretDirect ''
# directSync for the hosts zapret2 pins and learns at runtime: direct, so zapret2
# sees them. Last, after explicit rules, autoProxy's exits and the cutoff's networks,
# which zapret2 cannot fix. all-proxy and all-bypass keep no direct lists.
case "$ROUTE_MODE" in
all-proxy | all-bypass) ;;
*)
ZAPRET_RULE_SET=${lib.escapeShellArg "${constants.zapret2DirectDir}/direct.json"}
# The sync unit owns the directory's mode: what is in it skips the proxy.
mkdir -p "$(dirname "$ZAPRET_RULE_SET")"
[ -s "$ZAPRET_RULE_SET" ] || echo '{"version":1,"rules":[]}' > "$ZAPRET_RULE_SET"
chmod 644 "$ZAPRET_RULE_SET"
AUTOPROXY_RULE_SETS_JSON=$(${jq} -c --arg p "$ZAPRET_RULE_SET" \
'. + [{type: "local", format: "source", tag: "zapret-hosts", path: $p}]' <<< "$AUTOPROXY_RULE_SETS_JSON")
AUTOPROXY_RULES_JSON=$(${jq} -c '. + [{rule_set: ["zapret-hosts"], outbound: "direct"}]' <<< "$AUTOPROXY_RULES_JSON")
;;
esac
''}
# Every address this host has now, for the inbounds' guard (backend-filter-private-guard):
# dialed from here, a client would reach any port of them past the firewall.
HOST_ADDRESSES_JSON='[]'
${lib.optionalString (ctx.proxyInboundsEnabled && ctx.proxyInboundsNeedLocalProxy) ''
if ! HOST_ADDRESSES_JSON=$(${pkgs.iproute2}/bin/ip -j addr show | ${jq} -c \
'[.[].addr_info[]?.local | strings | if test(":") then . + "/128" else . + "/32" end] | unique'); then
echo "proxy-suite: cannot list this host's addresses; the inbounds' clients reach any port of them" >&2
HOST_ADDRESSES_JSON='[]'
fi
''}
# umask: the file holds credentials until the chmod below; the process
# substitutions keep them out of the argv every local user can read.
(umask 077 && ${jq} \
--slurpfile obs <(printf '%s' "$OUTBOUNDS_JSON") \
--slurpfile probe_inbounds <(printf '%s' "$PROBE_INBOUNDS_JSON") \
--slurpfile probe_pin_rules <(printf '%s' "$PROBE_PIN_RULES_JSON") \
--slurpfile autoproxy_rule_sets <(printf '%s' "$AUTOPROXY_RULE_SETS_JSON") \
--slurpfile autoproxy_rules <(printf '%s' "$AUTOPROXY_RULES_JSON") \
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
${
if enableLocalProxyAuth then
"--rawfile password <(printf '%s' \"$LOCAL_PROXY_PASSWORD\")"
else
"--arg password ''"
} \
--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" \
--arg xray_loglevel "$XRAY_LOGLEVEL" \
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
--slurpfile xray_selectable <(printf '%s' "$SELECTABLE_TAGS_JSON") \
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
--argjson host_addresses "$HOST_ADDRESSES_JSON" \
-f "$BACKEND_JQ_FILTER" \
"${configFile}" > "$RUNTIME_DIR/config.json")
${lib.optionalString excludeServiceUserFromTun ''
# proxy-suite's own daemons (the inbound XRay, replies to its clients included)
# stay out of the TUN; the uid is only known on this host.
SERVICE_UIDS=$(for service_user in ${lib.escapeShellArgs constants.ownTrafficUsers}; do
${pkgs.coreutils}/bin/id -u "$service_user"
done | ${jq} -cs .)
(umask 077 && ${jq} --argjson uids "$SERVICE_UIDS" '(.inbounds[] | select(.type == "tun") | .exclude_uid) = $uids' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
''}
${lib.optionalString (!pureXrayEnabled) ''
# The probe and test listeners reach any exit past the routing rules and the kill
# switch: a login per start, into jq through its environment (argv is public).
if ${jq} -e '[.inbounds[]? | (.tag // "") | select(startswith("probe-in-") or . == "proxy-suite-test-in")] | length > 0' \
"$RUNTIME_DIR/config.json" >/dev/null; then
PROBE_PASSWORD=$(${pkgs.coreutils}/bin/od -An -tx1 -N16 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
(umask 077 && PROBE_PASSWORD="$PROBE_PASSWORD" ${jq} '(.inbounds[]? | select((.tag // "") | startswith("probe-in-") or . == "proxy-suite-test-in"))
+= {users: [{username: "probe", password: $ENV.PROBE_PASSWORD}]}' \
"$RUNTIME_DIR/config.json" > "$RUNTIME_DIR/config.json.next")
mv "$RUNTIME_DIR/config.json.next" "$RUNTIME_DIR/config.json"
(umask 077 && printf 'probe:%s\n' "$PROBE_PASSWORD" > "$RUNTIME_DIR/probe-login.tmp")
unset PROBE_PASSWORD
${
# Only to the groups that test outbounds or probe for autoProxy: to any other the
# login is a way out direct, past the routing rules and the kill switch.
if probeLoginMainGroup then
''
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "$RUNTIME_DIR/probe-login.tmp"''}
chmod ${if constants.privileged then "640" else "600"} "$RUNTIME_DIR/probe-login.tmp"
''
else
''chmod 600 "$RUNTIME_DIR/probe-login.tmp"''
}
${constants.grantFileAcl pkgs ''"$RUNTIME_DIR/probe-login.tmp"'' probeLoginExtraGroups "r"}
mv "$RUNTIME_DIR/probe-login.tmp" "$RUNTIME_DIR/probe-login"
fi
''}
# The Clash API lists every connection and switches outbounds. Loopback alone lets
# every local user at it, and every web page too (sing-box allows any origin): a
# secret per start.
BACKEND_EXTRA_CONFIG=()
if ${jq} -e '.experimental.clash_api? != null' "$RUNTIME_DIR/config.json" >/dev/null; then
CLASH_SECRET=$(${pkgs.coreutils}/bin/od -An -tx1 -N24 /dev/urandom | ${pkgs.coreutils}/bin/tr -d ' \n')
# Not in config.json, which the secrets scope reads (`proxy config --raw`): the
# backend's alone, which sing-box merges in (a second -c).
(umask 077 && ${jq} -n --rawfile s <(printf '%s' "$CLASH_SECRET") '{experimental: {clash_api: {secret: $s}}}' \
> "$RUNTIME_DIR/clash-api.json.tmp")
${constants.ifPrivileged ''${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${constants.serviceUser} "$RUNTIME_DIR/clash-api.json.tmp"''}
chmod 400 "$RUNTIME_DIR/clash-api.json.tmp"
mv "$RUNTIME_DIR/clash-api.json.tmp" "$RUNTIME_DIR/clash-api.json"
BACKEND_EXTRA_CONFIG=(-c "$RUNTIME_DIR/clash-api.json")
# Root's alone where the host is privileged: userControl's groups ask
# proxy-suite-clash-api, which lets them do what their scopes cover. A rootless host
# runs as its one user anyway.
(umask 077 && printf '%s\n' "$CLASH_SECRET" > "$RUNTIME_DIR/clash-secret.tmp")
chmod 600 "$RUNTIME_DIR/clash-secret.tmp"
mv "$RUNTIME_DIR/clash-secret.tmp" "$RUNTIME_DIR/clash-secret"
fi
# Credentials, read by the backend running as ${constants.serviceUser}. With
# userControl its group reads them too; a file has one group, so the daemon
# reads as owner then.
for backend_config in "$RUNTIME_DIR/config.json" "$RUNTIME_DIR/xray-sidecar.json"; do
[ -e "$backend_config" ] || continue
${
if userControlAllows "secrets" then
''
${pkgs.coreutils}/bin/chown ${constants.serviceUser}:${userControlGroup} "$backend_config"
chmod 440 "$backend_config"
''
else
''
${constants.ifPrivileged ''${chgrp} ${constants.serviceUser} "$backend_config"''}
# Without root the group is the user's own primary one, which may be shared
# (users): the owner alone then.
chmod ${if constants.privileged then "640" else "600"} "$backend_config"
''
}
${constants.grantFileAcl pkgs ''"$backend_config"'' (ctx.userControlExtraGroupsFor "secrets") "r"}
done
FAKE_IP_CACHE=$(${jq} -r '.experimental.cache_file.path? // empty' "$RUNTIME_DIR/config.json")
if [ -n "$FAKE_IP_CACHE" ]; then
install -d -m 0700 ${constants.ifPrivileged "-o ${constants.serviceUser} -g ${constants.serviceUser} "}"$(dirname "$FAKE_IP_CACHE")"
fi
${
if hybridEnabled then
''
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
XRAY_SIDECAR_PID=""
_proxy_suite_cleanup_xray_sidecar() {
if [ -n "$XRAY_SIDECAR_PID" ]; then
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
fi
}
trap _proxy_suite_cleanup_xray_sidecar EXIT
trap 'exit 143' INT TERM
${runBackend} ${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
XRAY_SIDECAR_PID="$!"
${pkgs.coreutils}/bin/sleep 0.2
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
XRAY_SIDECAR_STATUS=1
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
exit "$XRAY_SIDECAR_STATUS"
fi
${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}" &
SING_BOX_PID="$!"
# Either one going away breaks the outbounds: exit, and let systemd restart both.
SING_BOX_STATUS=0
wait -n "$XRAY_SIDECAR_PID" "$SING_BOX_PID" || SING_BOX_STATUS="$?"
exit "$(( SING_BOX_STATUS == 0 ? 1 : SING_BOX_STATUS ))"
fi
exec ${runBackend} ${singBox} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}"
''
else
''
exec ${runBackend} ${backendBin} run -c "$RUNTIME_DIR/config.json" "''${BACKEND_EXTRA_CONFIG[@]}"
''
}
'';
startSocks = mkStartScript {
runtimeDir = "${constants.runtimeDir}/proxy-suite-socks";
configFile = tproxyFile;
# Rootless hosts cannot set SO_MARK, and have no TProxy rules to escape anyway.
routingMark = if constants.privileged then globalTproxy.proxyMark else null;
enableLocalProxyAuth = localProxyAuthEnabled;
# TProxy takes the system resolver's own upstream queries too, so a proxy server's name
# has to resolve inside XRay, as under the TUN.
xrayTunDnsRuntime = pureXrayEnabled && globalTproxy.enable;
xraySidecarPort = xraySidecarPorts.socks;
xrayDnsBridgePort = xrayDnsBridgePorts.socks;
# Only the socks unit: relayed traffic reaches it, and the prober needs one home.
enableAutoProxy = proxyCfg.autoProxy.enable && !pureXrayEnabled;
enableZapretCutoff = zapretCutoffProxyFallback && !pureXrayEnabled;
enableZapretDirect = zapret2DirectSync && !pureXrayEnabled;
enableZapretProxy = zapret2ProxyFallback && !pureXrayEnabled;
enableOutboundTest = true;
};
startTun = mkStartScript {
runtimeDir = "${constants.runtimeDir}/proxy-suite-tun";
configFile = tunFile;
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarPort = xraySidecarPorts.tun;
xrayDnsBridgePort = xrayDnsBridgePorts.tun;
# Pure XRay's TUN routes by ip rules instead: see xrayTunUpScript.
excludeServiceUserFromTun = !pureXrayEnabled;
};
startPerAppTun = mkStartScript {
runtimeDir = "${constants.runtimeDir}/proxy-suite-per-app-tun";
configFile = perAppTunFile;
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
xrayTunDnsRuntime = pureXrayEnabled;
xraySidecarPort = xraySidecarPorts.perAppTun;
xrayDnsBridgePort = xrayDnsBridgePorts.perAppTun;
};
in
{
inherit startSocks startTun startPerAppTun;
}