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

@@ -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
;
}