refactor: move out large code blocks out of nix

This commit is contained in:
fufsob authored and FUFSoB committed 2026-10-04 11:54:04 +05:00
1 parent e8ace6523d
commit af5b3ff27a
47 files changed
+2220 -2070

No files matched your search

@@ -0,0 +1,15 @@
# inbounds.routing.blockPrivate, enforced here because the listener passes names unresolved.
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
| [{inbound: ["mixed-in"], action: "resolve"@resolveStrategy@},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
@@ -0,0 +1,29 @@
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then
.dns.rules = .dns.rules[:@userDnsRuleCount@]
+ [.dns.rules[@userDnsRuleCount@:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])]
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
# The loopback probe and test listeners reach every exit: with listener.auth, the
# same login, or any local user would get past it through them.
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users)
= [{username:$user,password:$password}]
else . end
| .route.rule_set = ((.route.rule_set // []) + $autoproxy_rule_sets)
| .route.rules = ($probe_pin_rules + .route.rules + $autoproxy_rules)
@@ -0,0 +1,79 @@
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
# "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit.
if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "@selectionMode@" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
# Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy.
def xray_server_names:
[.outbounds[].settings
| (.vnext[]?.address, .servers[]?.address, .address?)
| strings | select(test("^[0-9.]+$|:|^localhost$") | not)]
| unique;
# A copy of "local" answering only for them: routed direct by its tag, so looking up a
# proxy server never waits on that proxy.
def xray_pin_server_names:
xray_server_names as $names
| if $names == [] then .
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
end;
.outbounds = ($obs[0] + .outbounds)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| .dns.servers = xray_dns_server_order($dns_final)
| xray_pin_server_names
| if $xray_tun_dns_runtime then
# Without a domainStrategy a dial resolves through the system resolver, whose upstream
# queries the TUN answers with fake IPs and TProxy sends through the proxy being
# dialed. XRay's own DNS client skips fakedns.
.outbounds |= map(
if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then .
else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end)
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
# The balancer's prefix would take in proxy.selectionExclude and disabled outbounds
# too: name the rest instead. Disabling is a runtime decision, so always.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| if $ARGS.named.xray_selectable == null then . else
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
@@ -7,138 +7,19 @@
userDnsRules ? [ ],
}:
let
fillTemplate = import ../../lib/fill-template.nix;
in
if pureXrayEnabled then
''
def xray_proxy_rule_target($single_tag):
if $single_tag != "" then
{outboundTag:$single_tag}
else
{balancerTag:"proxy"}
end;
def xray_rewrite_proxy_rule($single_tag):
# "proxy" is a balancer in urltest and no outbound at all in "first": either way, the one exit.
if $single_tag != "" and ((.balancerTag? // .outboundTag? // "") == "proxy") then
.outboundTag = $single_tag | del(.balancerTag)
else
.
end;
def xray_preserved_rules:
[.routing.rules[]
| select((.ruleTag? // "") | . == "dns-hijack" or . == "dns-upstream-direct" or . == "dns-upstream-remote")];
def xray_final_rule($tag; $single_tag):
if $tag == "proxy" and "${selectionMode}" == "urltest" then
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
else
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
end;
def xray_dns_server_order($dns_final):
if $dns_final == "" then
.dns.servers
else
([.dns.servers[] | select((.tag? // "") == "fakedns")]
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
end;
# Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy.
def xray_server_names:
[.outbounds[].settings
| (.vnext[]?.address, .servers[]?.address, .address?)
| strings | select(test("^[0-9.]+$|:|^localhost$") | not)]
| unique;
# A copy of "local" answering only for them: routed direct by its tag, so looking up a
# proxy server never waits on that proxy.
def xray_pin_server_names:
xray_server_names as $names
| if $names == [] then .
else .dns.servers += [.dns.servers[] | select((.tag? // "") == "local")
| . + {domains: ($names | map("full:" + .)), skipFallback: true}]
end;
.outbounds = ($obs[0] + .outbounds)
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
| if $auth_enabled then
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
else . end
| .dns.servers = xray_dns_server_order($dns_final)
| xray_pin_server_names
| if $xray_tun_dns_runtime then
# Without a domainStrategy a dial resolves through the system resolver, whose upstream
# queries the TUN answers with fake IPs and TProxy sends through the proxy being
# dialed. XRay's own DNS client skips fakedns.
.outbounds |= map(
if .protocol == "blackhole" or .protocol == "dns" or .protocol == "loopback" then .
else .streamSettings.sockopt.domainStrategy //= "UseIPv4v6" end)
else . end
| if $route_enabled then
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
else . end
# The balancer's prefix would take in proxy.selectionExclude and disabled outbounds
# too: name the rest instead. Disabling is a runtime decision, so always.
# ponytail: selectors are prefixes still, so "de" also takes in an excluded "de-hop";
# rename one of them if that matters.
| if $ARGS.named.xray_selectable == null then . else
($ARGS.named.xray_selectable | map("proxy-suite-ob-" + .)) as $candidates
| if .routing.balancers then .routing.balancers |= map(.selector = $candidates) else . end
| if .observatory then .observatory.subjectSelector = $candidates else . end
end
| if $xray_single_proxy_tag == "" then
.
else
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
| del(.routing.balancers)
| del(.observatory)
end
''
(fillTemplate ./backend-filter-xray.template.jq { inherit selectionMode; })
else
''
def sing_box_preserved_rules:
[.route.rules[]
| select(((.action? // "") == "hijack-dns")
and (((.inbound? // []) | index("xray-dns-in")) != null))];
.outbounds = ($obs[0] + .outbounds)
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
else . end
| if $route_enabled then
.route.rules = (sing_box_preserved_rules + $route_rules)
| .route.final = $route_final
| .dns.final = $dns_final
| if $clear_dns_rules then
.dns.rules = .dns.rules[:${toString (builtins.length userDnsRules)}]
+ [.dns.rules[${toString (builtins.length userDnsRules)}:][] | select(.server? == "fakeip" or .domain_suffix? == ["onion"])]
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
# The loopback probe and test listeners reach every exit: with listener.auth, the
# same login, or any local user would get past it through them.
| if $auth_enabled then
(.inbounds[] | select(.type == "mixed" and (.tag == "proxy-suite-test-in" or (.tag | startswith("probe-in-")))) | .users)
= [{username:$user,password:$password}]
else . end
| .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.
# Just before the first direct rule (or last, for a direct final), so names that the
# proxy rules above take stay unresolved and none reaches a direct dial unchecked. Local
# mixed-in clients lose names that resolve private. Rules for other inbounds do not count:
# autoProxy's direct probe pin would put the guard first, resolving every name, .onion too.
| [{inbound: ["mixed-in"], action: "resolve"${
lib.optionalString (
(fillTemplate ./backend-filter-sing-box.template.jq {
userDnsRuleCount = toString (builtins.length userDnsRules);
})
+ lib.optionalString proxyInboundsGuardPrivate (
fillTemplate ./backend-filter-private-guard.template.jq {
resolveStrategy = lib.optionalString (
proxyInboundsGuardStrategy != null
) ", strategy: \"${proxyInboundsGuardStrategy}\""
}},
{inbound: ["mixed-in"], ip_is_private: true, action: "reject"}] as $guard
| (.route.rules
| map((.outbound? // "") == "direct" and ((.inbound? // ["mixed-in"]) | index(["mixed-in"])) != null)
| index(true)) as $first_direct
| if $first_direct != null then
.route.rules = .route.rules[:$first_direct] + $guard + .route.rules[$first_direct:]
elif (.route.final // "direct") == "direct" then
.route.rules += $guard
else . end
''
) ", strategy: \"${proxyInboundsGuardStrategy}\"";
}
)
@@ -1,6 +1,7 @@
{ ctx }:
let
fillTemplate = import ../../lib/fill-template.nix;
inherit (ctx)
lib
jq
@@ -11,107 +12,17 @@ in
routingMark: xraySidecarPort: xrayDnsBridgePort:
lib.optionalString hybridEnabled ''
XRAY_OUTBOUNDS_JSON='[]'
XRAY_CLIENTS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_PORT=${toString xraySidecarPort}
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
# Client ids: this run's random prefix plus a counter, so every sidecar outbound has its
# own and no other local user can guess one.
XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid)
XRAY_SIDECAR_NEXT_ID=0
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(${jq} --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
lib.optionalString hybridEnabled (
fillTemplate ./hybrid-runtime-helpers.template.sh {
sidecarPort = toString xraySidecarPort;
dnsBridgePort = toString xrayDnsBridgePort;
inherit jq;
sidecarMark = if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark;
setSidecarMark = lib.optionalString (
xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark";
hopRoutingMark = lib.optionalString (
routingMark != null
) " + {routing_mark: ${toString routingMark}}";
}
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
# client on the sidecar's one loopback VLESS inbound, routed to it by its email, and
# stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream
# (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by.
_proxy_suite_add_xray_sidecar_obs() {
local batch
batch=$(${jq} -c \
--argjson next "$XRAY_SIDECAR_NEXT_ID" \
--rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \
--argjson port "$XRAY_SIDECAR_PORT" \
--argjson mark ${
if xraySidecarRoutingMark == null then "null" else toString xraySidecarRoutingMark
} '
def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add;
to_entries | map(
($secret[:24] + ($next + .key | hex12)) as $id
| .value.tag as $tag
| {outbound: (.value
${lib.optionalString (
xraySidecarRoutingMark != null
) "| .streamSettings.sockopt.mark = $mark"}
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
client: {id: $id, email: $tag},
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id,
packet_encoding: "xudp"}${
lib.optionalString (routingMark != null) " + {routing_mark: ${toString routingMark}}"
})})
| {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)}
' <<< "$1")
XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(${jq} '.outbounds | length' <<< "$batch")))
# Through a file, not --argjson: a big subscription's batch outgrows the kernel's
# 128 KiB limit on one argument.
XRAY_OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
XRAY_CLIENTS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON")
XRAY_ROUTE_RULES_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON")
OUTBOUNDS_JSON=$(${jq} -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON")
}
# $1 one XRay outbound, $2 its tag.
_proxy_suite_add_xray_sidecar_ob() {
_proxy_suite_add_xray_sidecar_obs "$(${jq} -c --arg tag "$2" '[.tag = $tag]' <<< "$1")"
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
${jq} -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson port "$XRAY_SIDECAR_PORT" \
--slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \
--slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \
--slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \
'
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: [
{
tag: "sidecar-in",
listen: "127.0.0.1",
port: $port,
protocol: "vless",
settings: {clients: $clients[0], decryption: "none"}
}
],
outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
''
)
@@ -0,0 +1,96 @@
XRAY_OUTBOUNDS_JSON='[]'
XRAY_CLIENTS_JSON='[]'
XRAY_ROUTE_RULES_JSON='[]'
XRAY_SIDECAR_PORT=@sidecarPort@
XRAY_SIDECAR_DNS_PORT=@dnsBridgePort@
# Client ids: this run's random prefix plus a counter, so every sidecar outbound has its
# own and no other local user can guess one.
XRAY_SIDECAR_SECRET=$(cat /proc/sys/kernel/random/uuid)
XRAY_SIDECAR_NEXT_ID=0
_proxy_suite_add_sing_box_ob() {
local ob="$1"
OUTBOUNDS_JSON=$(@jq@ --slurpfile ob <(printf '%s' "$ob") '. + $ob' <<< "$OUTBOUNDS_JSON")
}
# $1 a JSON array of XRay outbounds, each tagged. One jq pass for the lot: each gets a
# client on the sidecar's one loopback VLESS inbound, routed to it by its email, and
# stands in sing-box as a hop to it. VLESS rather than SOCKS: UDP rides the stream
# (XUDP) with the client id, where SOCKS UDP datagrams carry no user to route by.
_proxy_suite_add_xray_sidecar_obs() {
local batch
batch=$(@jq@ -c \
--argjson next "$XRAY_SIDECAR_NEXT_ID" \
--rawfile secret <(printf '%s' "$XRAY_SIDECAR_SECRET") \
--argjson port "$XRAY_SIDECAR_PORT" \
--argjson mark @sidecarMark@ '
def hex12: [range(11; -1; -1) as $i | (. / pow(16; $i) | floor) % 16 | "0123456789abcdef"[.:. + 1]] | add;
to_entries | map(
($secret[:24] + ($next + .key | hex12)) as $id
| .value.tag as $tag
| {outbound: (.value
@setSidecarMark@
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")),
client: {id: $id, email: $tag},
rule: {type: "field", inboundTag: ["sidecar-in"], user: [$tag], outboundTag: $tag},
hop: ({type: "vless", tag: $tag, server: "127.0.0.1", server_port: $port, uuid: $id,
packet_encoding: "xudp"}@hopRoutingMark@)})
| {outbounds: map(.outbound), clients: map(.client), rules: map(.rule), hops: map(.hop)}
' <<< "$1")
XRAY_SIDECAR_NEXT_ID=$((XRAY_SIDECAR_NEXT_ID + $(@jq@ '.outbounds | length' <<< "$batch")))
# Through a file, not --argjson: a big subscription's batch outgrows the kernel's
# 128 KiB limit on one argument.
XRAY_OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].outbounds' <<< "$XRAY_OUTBOUNDS_JSON")
XRAY_CLIENTS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].clients' <<< "$XRAY_CLIENTS_JSON")
XRAY_ROUTE_RULES_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].rules' <<< "$XRAY_ROUTE_RULES_JSON")
OUTBOUNDS_JSON=$(@jq@ -c --slurpfile b <(printf '%s' "$batch") '. + $b[0].hops' <<< "$OUTBOUNDS_JSON")
}
# $1 one XRay outbound, $2 its tag.
_proxy_suite_add_xray_sidecar_ob() {
_proxy_suite_add_xray_sidecar_obs "$(@jq@ -c --arg tag "$2" '[.tag = $tag]' <<< "$1")"
}
_proxy_suite_write_xray_sidecar_config() {
if [ "$(@jq@ 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
return 0
fi
@jq@ -n \
--arg loglevel "$XRAY_LOGLEVEL" \
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
--argjson port "$XRAY_SIDECAR_PORT" \
--slurpfile clients <(printf '%s' "$XRAY_CLIENTS_JSON") \
--slurpfile outbounds <(printf '%s' "$XRAY_OUTBOUNDS_JSON") \
--slurpfile route_rules <(printf '%s' "$XRAY_ROUTE_RULES_JSON") \
'
{
log: {
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
access: "none"
},
dns: {
servers: [
{
address: "127.0.0.1",
port: $dns_port,
queryStrategy: "UseIP",
skipFallBack: true
}
]
},
inbounds: [
{
tag: "sidecar-in",
listen: "127.0.0.1",
port: $port,
protocol: "vless",
settings: {clients: $clients[0], decryption: "none"}
}
],
outbounds: ($outbounds[0] + [{protocol:"freedom",tag:"direct"}]),
routing: {
domainStrategy: "AsIs",
rules: ($route_rules[0] + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
}
}' > "$RUNTIME_DIR/xray-sidecar.json"
}
@@ -0,0 +1,67 @@
@readSourceFunction@
SUB_CACHE_DIR="@cacheDir@"
RUNTIME_SUBS_DIR="@runtimeSubscriptionsDir@"
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && @jq@ -e @validCacheFilter@ "$1" >/dev/null 2>&1
}
# Set when a fetch leaves a cache different from before, so the update unit restarts the
# proxy only for a change: a restart cuts every connection through it.
SUB_CACHE_CHANGED=0
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
if [ -f "$target" ] && @diffutils@/bin/cmp -s "$tmp" "$target"; then
rm -f "$tmp"
else
mv "$tmp" "$target"
SUB_CACHE_CHANGED=1
fi
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="@pythonPath@" @python3@ @fetchSubscriptionPy@ \
@backendArg@ --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
return 0
fi
rm -f "$links.tmp"
return 1
fi
rm -f "$cache.tmp" "$links.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
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="${f##*/}"
tag="${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
@@ -6,6 +6,7 @@
{ ctx }:
let
fillTemplate = import ../../lib/fill-template.nix;
inherit (ctx)
lib
pkgs
@@ -30,82 +31,21 @@ let
# Defined in every script that touches a cache: the start scripts and the
# update unit.
subscriptionCacheHelpersBlock = ''
${constants.readSourceFunction pkgs}
SUB_CACHE_DIR="${subscriptionCacheDir}"
RUNTIME_SUBS_DIR="${runtimeSubscriptionsDir}"
_proxy_suite_valid_subscription_cache() {
[ -s "$1" ] && ${jq} -e ${
lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
)
} "$1" >/dev/null 2>&1
}
# Set when a fetch leaves a cache different from before, so the update unit restarts the
# proxy only for a change: a restart cuts every connection through it.
SUB_CACHE_CHANGED=0
_proxy_suite_commit_subscription_cache() {
local tmp="$1" target="$2" tag="$3"
if _proxy_suite_valid_subscription_cache "$tmp"; then
if [ -f "$target" ] && ${pkgs.diffutils}/bin/cmp -s "$tmp" "$target"; then
rm -f "$tmp"
else
mv "$tmp" "$target"
SUB_CACHE_CHANGED=1
fi
return 0
fi
rm -f "$tmp"
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
return 1
}
_proxy_suite_drop_invalid_subscription_cache() {
local target="$1" tag="$2"
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
rm -f "$target"
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
fi
}
# $1 tag, $2 file holding the subscription URL. Writes the cache atomically,
# and next to it <tag>.links: each entry's original URI, for proxy-ctl to share.
_proxy_suite_fetch_subscription() {
local tag="$1" src="$2" cache="$SUB_CACHE_DIR/$1.json" links="$SUB_CACHE_DIR/$1.links"
mkdir -p "$SUB_CACHE_DIR"
if printf '%s' "$(_proxy_suite_read_source "$src")" \
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} \
${subscriptionBackendArg} --tag-prefix "$tag" --links-out "$links.tmp" > "$cache.tmp"; then
if _proxy_suite_commit_subscription_cache "$cache.tmp" "$cache" "$tag"; then
mv "$links.tmp" "$links"
return 0
fi
rm -f "$links.tmp"
return 1
fi
rm -f "$cache.tmp" "$links.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
[ -f "$f" ] && [ ! -L "$f" ] || continue
tag="''${f##*/}"
tag="''${tag%.url}"
printf '%s\t%s\n' "$tag" "$f"
done
}
'';
subscriptionCacheHelpersBlock = fillTemplate ./subscription-cache-helpers.template.sh {
readSourceFunction = constants.readSourceFunction pkgs;
cacheDir = subscriptionCacheDir;
inherit runtimeSubscriptionsDir jq;
validCacheFilter = lib.escapeShellArg (
if hybridEnabled then
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
else
''type == "array"''
);
diffutils = pkgs.diffutils;
pythonPath = parserScriptsPythonPath;
inherit python3 fetchSubscriptionPy;
backendArg = subscriptionBackendArg;
};
# 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.