feat: outbound groups
This commit is contained in:
35 files changed
+2444
-210
No files matched your search
@@ -21,6 +21,7 @@ let
|
||||
awgRuntimeTunnelBasePort
|
||||
awgRuntimeTunnelSlots
|
||||
systemctl
|
||||
runtimeDir
|
||||
;
|
||||
killSwitchUnit = "proxy-suite-killswitch.service";
|
||||
# Profiles behind a loopback SOCKS hop, in a tunnel unit rather than awg-quick.
|
||||
@@ -646,6 +647,12 @@ let
|
||||
exec ${pkgs.coreutils}/bin/sleep infinity
|
||||
fi
|
||||
${mkHandshakeHelpers profile}
|
||||
# Tells proxy-suite-outbound-groups at once, so a failover group this outbound is in
|
||||
# moves off it now rather than at its next test.
|
||||
hint() {
|
||||
local health="${runtimeDir}/proxy-suite-outbound-groups/health"
|
||||
[[ -d $health ]] && ${pkgs.coreutils}/bin/touch "$health/$profile_name" 2>/dev/null || true
|
||||
}
|
||||
${lib.optionalString egressProbe ''
|
||||
new_session() {
|
||||
local peers
|
||||
@@ -670,6 +677,7 @@ let
|
||||
stale=0
|
||||
elif (( ++stale >= 2 )); then
|
||||
echo "proxy-suite: AmneziaWG profile '$profile_name' is not rekeying; moving to a new source port" >&2
|
||||
hint
|
||||
new_source_port
|
||||
stale=0
|
||||
${lib.optionalString egressProbe "continue"}
|
||||
@@ -678,7 +686,9 @@ let
|
||||
if (( !probe_egress )) || ${pkgs.curl}/bin/curl -4 -s --noproxy "*" --interface "$interface" -m 5 -o /dev/null \
|
||||
${lib.escapeShellArg cfg.proxy.urlTest.url}; then
|
||||
misses=0
|
||||
elif (( ++misses >= 3 && SECONDS - last_session >= 300 )); then
|
||||
elif (( ++misses == 1 )); then
|
||||
hint
|
||||
elif (( misses >= 3 && SECONDS - last_session >= 300 )); then
|
||||
echo "proxy-suite: AmneziaWG profile '$profile_name' carries no IPv4 past its peer; starting a new session" >&2
|
||||
new_session
|
||||
misses=0
|
||||
|
||||
@@ -95,16 +95,63 @@ let
|
||||
authEnabled = auth.username != null && (auth.password != null || auth.passwordFile != null);
|
||||
};
|
||||
|
||||
warpCfg = cfg.warp // {
|
||||
# Without a configFile, proxy-suite-warp registers with wgcf into its state dir.
|
||||
autoRegister = cfg.warp.enable && cfg.warp.configFile == null;
|
||||
profilePath =
|
||||
if cfg.warp.configFile != null then cfg.warp.configFile else "${stateDir}/warp/wgcf-profile.conf";
|
||||
# Loopback SOCKS listener of proxy-suite-warp-tunnel, which the "warp" outbound dials.
|
||||
tunnelPort = 18538;
|
||||
# Its "direct-in" listener, which tells a blocked WARP from a dead uplink.
|
||||
directPort = 18539;
|
||||
};
|
||||
# WARP devices: one "warp" unless warp.devices or warp.instances name more. The first keeps
|
||||
# what a single device had (its registration unit, state dir and ports), so a registration
|
||||
# made before carries over.
|
||||
warpDeviceNames =
|
||||
if cfg.warp.instances != null then
|
||||
map (i: "warp-${toString i}") (lib.range 1 cfg.warp.instances)
|
||||
else if cfg.warp.devices != { } then
|
||||
builtins.attrNames cfg.warp.devices
|
||||
else
|
||||
[ "warp" ];
|
||||
warpDevices = lib.imap0 (
|
||||
index: tag:
|
||||
let
|
||||
device =
|
||||
cfg.warp.devices.${tag} or {
|
||||
configFile = null;
|
||||
endpoint = null;
|
||||
};
|
||||
first = index == 0;
|
||||
configFile =
|
||||
if device.configFile != null then
|
||||
device.configFile
|
||||
else if first then
|
||||
cfg.warp.configFile
|
||||
else
|
||||
null;
|
||||
stateSubdir = if first then "warp" else "warp/${tag}";
|
||||
in
|
||||
{
|
||||
inherit
|
||||
tag
|
||||
first
|
||||
configFile
|
||||
stateSubdir
|
||||
;
|
||||
endpoint = if device.endpoint != null then device.endpoint else cfg.warp.endpoint;
|
||||
# Without a configFile, its registration unit registers with wgcf into its state dir.
|
||||
autoRegister = cfg.warp.enable && configFile == null;
|
||||
profilePath =
|
||||
if configFile != null then configFile else "${stateDir}/${stateSubdir}/wgcf-profile.conf";
|
||||
registerUnit = if first then "proxy-suite-warp" else "proxy-suite-warp-register-${tag}";
|
||||
tunnelUnit = if first then "proxy-suite-warp-tunnel" else "proxy-suite-warp-tunnel-${tag}";
|
||||
# Loopback SOCKS listener of the sing-box tunnel, which the outbound dials, and its
|
||||
# "direct-in" listener, which tells a blocked WARP from a dead uplink.
|
||||
tunnelPort = if first then 18538 else 18900 + 2 * (index - 1);
|
||||
directPort = if first then 18539 else 18901 + 2 * (index - 1);
|
||||
}
|
||||
) warpDeviceNames;
|
||||
warpCfg =
|
||||
cfg.warp
|
||||
// (builtins.head warpDevices)
|
||||
// {
|
||||
devices = warpDevices;
|
||||
autoRegister = builtins.any (d: d.autoRegister) warpDevices;
|
||||
# Two or more: "warp" is a group of them (warp.nix).
|
||||
grouped = builtins.length warpDevices > 1;
|
||||
};
|
||||
warpOutboundTag = "warp";
|
||||
# The sing-box tunnel; "userspace" and "interface" come in through the AmneziaWG profile list.
|
||||
warpOutboundEnabled = warpCfg.enable && warpCfg.asOutbound == "singBox";
|
||||
@@ -399,11 +446,15 @@ let
|
||||
effectiveOutboundTags =
|
||||
outboundTags
|
||||
++ lib.optional sshProxyOutboundEnabled sshProxyOutboundTag
|
||||
++ lib.optional warpOutboundEnabled warpOutboundTag
|
||||
++ lib.optionals warpOutboundEnabled (map (d: d.tag) warpDevices)
|
||||
++ lib.optional torOutboundEnabled torOutboundTag
|
||||
++ map (j: j.tag) whitelistBypassJoiners
|
||||
++ map (ob: ob.tag) awgOutbounds;
|
||||
subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
|
||||
groupTags = builtins.attrNames proxyCfg.groups;
|
||||
# proxy-suite-outbound-groups moves failover groups, and "failover" selection, along. Runtime
|
||||
# groups can be failover too, so it runs with every Clash API; with nothing to watch it idles.
|
||||
outboundGroupsWatch = proxyEnabled && clashApiEnabled;
|
||||
|
||||
hasStaticOutbounds = proxyCfg.outbounds != [ ];
|
||||
hasSubscriptions = proxyCfg.subscriptions != [ ];
|
||||
@@ -620,7 +671,7 @@ let
|
||||
invalidRoutingTargets = lib.unique (
|
||||
map (rule: rule.outbound) (
|
||||
builtins.filter (
|
||||
rule: !builtins.elem rule.outbound (builtinTags ++ effectiveOutboundTags)
|
||||
rule: !builtins.elem rule.outbound (builtinTags ++ effectiveOutboundTags ++ groupTags)
|
||||
) proxyCfg.routing.rules
|
||||
)
|
||||
);
|
||||
@@ -662,6 +713,7 @@ in
|
||||
sshProxyUnitEnabled
|
||||
warpCfg
|
||||
warpOutboundEnabled
|
||||
warpDeviceNames
|
||||
torCfg
|
||||
torOutboundTag
|
||||
torOutboundEnabled
|
||||
@@ -707,6 +759,8 @@ in
|
||||
outboundTags
|
||||
effectiveOutboundTags
|
||||
subscriptionTags
|
||||
groupTags
|
||||
outboundGroupsWatch
|
||||
hasSubscriptions
|
||||
hasAvailableOutbounds
|
||||
collapseNamedOutbounds
|
||||
|
||||
@@ -53,18 +53,116 @@ in
|
||||
"first"
|
||||
"selector"
|
||||
"urltest"
|
||||
"failover"
|
||||
];
|
||||
default = "first";
|
||||
description = ''
|
||||
How to pick an outbound:
|
||||
How to pick an outbound among the top-level ones: groups and outbounds in no group.
|
||||
- "first": the pinned one, or else the first available.
|
||||
- "selector": pick by hand.
|
||||
- "urltest": the fastest, unless one is pinned.
|
||||
- "failover": the first one that works, in `priority` order; moves on within seconds
|
||||
of a failure and comes back once the earlier one works again. sing-box and hybrid only.
|
||||
|
||||
`proxy-ctl proxy pin` works in every mode and survives restarts. On sing-box, "selector"
|
||||
and "urltest" switch without restarting the backend.
|
||||
`proxy-ctl proxy pin` works in every mode and survives restarts. On sing-box, "selector",
|
||||
"urltest" and "failover" switch without restarting the backend.
|
||||
'';
|
||||
example = "urltest";
|
||||
example = "failover";
|
||||
};
|
||||
|
||||
groups = mkOption {
|
||||
type = types.attrsOf (
|
||||
types.submodule {
|
||||
options = {
|
||||
outbounds = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Member tags, in order: the failover order. Any outbound or group tag.";
|
||||
example = [
|
||||
"warp-1"
|
||||
"warp-2"
|
||||
];
|
||||
};
|
||||
subscriptions = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Subscriptions whose every entry is a member, as the subscription holds them at start.";
|
||||
example = [ "community-list" ];
|
||||
};
|
||||
match = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = "Glob patterns (`*`, `?`) over outbound tags; every match is a member.";
|
||||
example = [ "de-*" ];
|
||||
};
|
||||
strategy = mkOption {
|
||||
type = types.enum [
|
||||
"failover"
|
||||
"urltest"
|
||||
"selector"
|
||||
];
|
||||
default = "failover";
|
||||
description = ''
|
||||
How the group picks a member:
|
||||
- "failover": the first member that works, in order; moves on within seconds of a
|
||||
failure.
|
||||
- "urltest": the fastest; `proxy.urlTest.tolerance` keeps it from switching over
|
||||
small differences.
|
||||
- "selector": the first member, or the one picked by hand.
|
||||
'';
|
||||
};
|
||||
failback = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
With "failover": go back to an earlier member once it has worked three checks in a
|
||||
row. Off: stay on the member it moved to until that one fails.
|
||||
'';
|
||||
};
|
||||
interval = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
How often members are tested (Go duration). `null`: `proxy.urlTest.interval` for
|
||||
"urltest", 30s for "failover". Health checks of their own, such as the AmneziaWG
|
||||
watchdog's, trigger a test at once.
|
||||
'';
|
||||
example = "15s";
|
||||
};
|
||||
};
|
||||
}
|
||||
);
|
||||
default = { };
|
||||
description = ''
|
||||
Outbound groups: one tag standing for several outbounds, which picks among them. A group
|
||||
works wherever an outbound tag does: routing rules, `detour`, pins, other groups. Its
|
||||
members are no longer picked on their own at the top level, only through the group.
|
||||
sing-box and hybrid only.
|
||||
'';
|
||||
example = lib.literalExpression ''
|
||||
{
|
||||
warp-pool.outbounds = [ "warp-1" "warp-2" ];
|
||||
eu = {
|
||||
subscriptions = [ "community-list" ];
|
||||
match = [ "de-*" ];
|
||||
strategy = "urltest";
|
||||
};
|
||||
}
|
||||
'';
|
||||
};
|
||||
|
||||
priority = mkOption {
|
||||
type = types.attrsOf types.int;
|
||||
default = { };
|
||||
description = ''
|
||||
Order of outbounds and groups, lower first: which one "first" and "failover" take, and the
|
||||
order of group members pulled in by `subscriptions` or `match`. Tags not listed come after,
|
||||
in their usual order. `proxy-ctl proxy priority` changes it at runtime.
|
||||
'';
|
||||
example = {
|
||||
warp-pool = 10;
|
||||
de-vps = 20;
|
||||
};
|
||||
};
|
||||
|
||||
selectionExclude = mkOption {
|
||||
|
||||
@@ -83,6 +83,64 @@ in
|
||||
example = "prefer_ipv4";
|
||||
};
|
||||
|
||||
devices = mkOption {
|
||||
type = types.attrsOf (
|
||||
types.submodule {
|
||||
options = {
|
||||
configFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = "This device's WireGuard profile, as `warp.configFile`. `null`: registered with wgcf.";
|
||||
example = "/run/secrets/warp-b.conf";
|
||||
};
|
||||
endpoint = endpoint "This device's endpoint, as `warp.endpoint` (which it defaults to).";
|
||||
};
|
||||
}
|
||||
);
|
||||
default = { };
|
||||
description = ''
|
||||
Several WARP devices, each registered on its own and each an outbound with its tag. With
|
||||
two or more, the tag "warp" names a group of them (`warp.group`), so rules, pins and
|
||||
chains naming "warp" fail over between them. A device cannot be named "warp" then.
|
||||
With "interface", a tag holds at most 11 characters (its interface is awg-<tag>).
|
||||
|
||||
Empty: one device, "warp", as `configFile` and `endpoint` above say.
|
||||
'';
|
||||
example = lib.literalExpression ''
|
||||
{
|
||||
warp-a = { };
|
||||
warp-b.endpoint = "162.159.193.10:500";
|
||||
}
|
||||
'';
|
||||
};
|
||||
|
||||
instances = mkOption {
|
||||
type = types.nullOr types.ints.positive;
|
||||
default = null;
|
||||
description = ''
|
||||
Shorthand for `devices`: this many WARP devices, warp-1 to warp-N, each registered with
|
||||
wgcf. warp-1 keeps the registration a single "warp" device made. Not with `devices`.
|
||||
'';
|
||||
example = 2;
|
||||
};
|
||||
|
||||
group = {
|
||||
strategy = mkOption {
|
||||
type = types.enum [
|
||||
"failover"
|
||||
"urltest"
|
||||
"selector"
|
||||
];
|
||||
default = "failover";
|
||||
description = "How the \"warp\" group of several devices picks one; see `proxy.groups`.";
|
||||
};
|
||||
failback = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = "With \"failover\": go back to an earlier device once it works again.";
|
||||
};
|
||||
};
|
||||
|
||||
asAmneziaWg = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
# Outbound groups, resolved at start: subscription entries and runtime outbounds only exist then.
|
||||
#
|
||||
# Input: {tags: [outbound tags, in build order], sources: {tag: source label}}.
|
||||
# Args: $groups {name: {outbounds, subscriptions, match, strategy, failback, interval}},
|
||||
# $priority {tag: n}, $disabled [tags], $pins {group: member}, $url, $interval, $tolerance,
|
||||
# $watched: whether proxy-suite-outbound-groups drives this instance's failover groups through
|
||||
# its Clash API. Without it (the TUN instances) a failover group is sing-box's own urltest.
|
||||
#
|
||||
# Output: {groups: {name: {strategy, failback, interval, members, pinned}}, outbounds: [the
|
||||
# sing-box group outbounds], top: [what the top level picks among, in order], warnings, errors}.
|
||||
# Errors mean the config cannot be built (a group inside itself); warnings are dropped members
|
||||
# and pins.
|
||||
|
||||
def glob_regex: "^" + (gsub("(?<c>[.+^$()\\[\\]{}|\\\\])"; "\\\(.c)") | gsub("\\*"; ".*") | gsub("\\?"; ".")) + "$";
|
||||
|
||||
(.tags) as $tags
|
||||
| (.sources // {}) as $sources
|
||||
| ($groups | keys_unsorted) as $names
|
||||
| ($tags | to_entries | map({key: .value, value: .key}) | from_entries) as $position
|
||||
|
||||
# Members as configured: the explicit list in its order, then the rest by priority, then build
|
||||
# order. A member that names nothing running is dropped with a warning: a subscription entry or
|
||||
# a runtime outbound may be gone, and that must not stop the proxy.
|
||||
| (reduce $names[] as $g ({members: {}, warnings: []};
|
||||
($groups[$g]) as $cfg
|
||||
| [($cfg.outbounds // [])[] | select(. != $g)] as $explicit
|
||||
| ($explicit | map(select(. as $t | ($tags | index([$t])) == null and ($names | index([$t])) == null))) as $missing
|
||||
| ([$tags[] | . as $t
|
||||
| select(($cfg.subscriptions // []) | any(. as $s | $sources[$t] == ("sub:" + $s)))]
|
||||
+ [($tags + $names)[] | . as $t | select($t != $g)
|
||||
| select(($cfg.match // []) | any(. as $p | $t | test($p | glob_regex)))]) as $pulled
|
||||
| ($pulled | unique | map(select(. as $t | $explicit | index([$t]) | not))
|
||||
| sort_by([$priority[.] // 1000000000, $position[.] // 1000000000, .])) as $rest
|
||||
| .members[$g] = ([$explicit[] | select(. as $t | $missing | index([$t]) | not)] + $rest)
|
||||
| .warnings += [$missing[] | "group '\($g)': member '\(.)' is not available; leaving it out"]
|
||||
)) as $resolved
|
||||
| $resolved.members as $members
|
||||
|
||||
# A group inside itself, however deep, has no member to end on.
|
||||
| def reach($g; $seen):
|
||||
[$members[$g][] | select(. as $m | $names | index([$m]))] as $sub
|
||||
| $sub + [$sub[] | . as $m | select($seen | index([$m]) | not) | reach($m; $seen + [$m])[]];
|
||||
[$names[] as $g | select(reach($g; [$g]) | index([$g])) | $g] as $loops
|
||||
|
||||
# Where a group sits when nothing sets its priority: where its first member would have.
|
||||
| def spot($g; $seen):
|
||||
[$members[$g][] | . as $m | if ($names | index([$m])) and ($seen | index([$m]) | not) then spot($m; $seen + [$m])
|
||||
else $position[.] end | select(. != null)] | min;
|
||||
($names | map({key: ., value: (spot(.; [.]) // 1000000000)}) | from_entries) as $spots
|
||||
|
||||
| ([$members[]] | add // [] | unique) as $grouped
|
||||
| ([$tags[], $names[]] | map(select(. as $t | $grouped | index([$t]) | not))
|
||||
| sort_by([$priority[.] // 1000000000, ($position[.] // $spots[.] // 1000000000)])) as $top
|
||||
|
||||
| (reduce $names[] as $g ({groups: {}, outbounds: [], warnings: []};
|
||||
($groups[$g]) as $cfg
|
||||
| ($members[$g]) as $all
|
||||
| [$all[] | select(. as $t | $disabled | index([$t]) | not)] as $usable
|
||||
| ($pins[$g] // "") as $pin
|
||||
| (if $pin == "" then ""
|
||||
elif ($all | index([$pin])) == null then "unknown"
|
||||
elif ($disabled | index([$pin])) then "disabled"
|
||||
else $pin end) as $pinned
|
||||
| .warnings += (if $pinned == "unknown" then ["group '\($g)': pinned member '\($pin)' is not in it; picking automatically"]
|
||||
elif $pinned == "disabled" then ["group '\($g)': pinned member '\($pin)' is disabled; picking automatically"]
|
||||
else [] end)
|
||||
| (if $pinned == "unknown" or $pinned == "disabled" then "" else $pinned end) as $pinned
|
||||
# With nothing to pick, the group blocks rather than disappear: rules naming it must not
|
||||
# fall through to direct.
|
||||
| .warnings += (if $usable == [] then ["group '\($g)' has no available member; it blocks until one is"] else [] end)
|
||||
| (if $all == [] then ["block"] else $all end) as $all
|
||||
| (if $usable == [] then ["block"] else $usable end) as $usable
|
||||
| .groups[$g] = {strategy: $cfg.strategy, failback: ($cfg.failback != false),
|
||||
interval: ($cfg.interval // (if $cfg.strategy == "urltest" then $interval else "30s" end)),
|
||||
members: $all, pinned: $pinned, runtime: ($cfg.runtime // false)}
|
||||
| .outbounds += [
|
||||
if ($cfg.strategy == "urltest" or ($cfg.strategy == "failover" and ($watched | not))) and $pinned == "" then
|
||||
{type: "urltest", tag: $g, outbounds: $usable, url: $url,
|
||||
interval: ($cfg.interval // $interval), tolerance: $tolerance}
|
||||
else
|
||||
# A pin holds any strategy, as the top-level pin does: a selector the Clash API switches.
|
||||
{type: "selector", tag: $g, outbounds: $all,
|
||||
default: (if $pinned != "" then $pinned else $usable[0] end)}
|
||||
+ (if $cfg.strategy == "failover" then {interrupt_exist_connections: true} else {} end)
|
||||
end]
|
||||
)) as $built
|
||||
|
||||
| {groups: $built.groups,
|
||||
# Inner groups first: sing-box wants an outbound defined before a group names it.
|
||||
outbounds: ($built.outbounds | sort_by(.tag as $t | [$names[] | select(reach(.; [.]) | index([$t]))] | -length)),
|
||||
top: $top,
|
||||
warnings: ($resolved.warnings + $built.warnings),
|
||||
errors: [$loops[] | "group '\(.)' contains itself"]}
|
||||
@@ -70,10 +70,12 @@ let
|
||||
builtins.attrValues constants.xrayDnsBridgePorts
|
||||
++ [ constants.outboundTestPort ]
|
||||
++ lib.optionals hybridEnabled (builtins.attrValues constants.xraySidecarPorts)
|
||||
++ lib.optionals derived.warpOutboundEnabled [
|
||||
derived.warpCfg.tunnelPort
|
||||
derived.warpCfg.directPort
|
||||
]
|
||||
++ lib.optionals derived.warpOutboundEnabled (
|
||||
lib.concatMap (d: [
|
||||
d.tunnelPort
|
||||
d.directPort
|
||||
]) derived.warpCfg.devices
|
||||
)
|
||||
++ lib.concatMap (ob: [
|
||||
ob.tunnelPort
|
||||
ob.directPort
|
||||
@@ -185,6 +187,15 @@ let
|
||||
(mkAssertion (!(cfg.warp.enable && cfg.warp.asOutbound != null && cfg.warp.asAmneziaWg))
|
||||
"proxy-suite: warp.asOutbound and warp.asAmneziaWg share one WARP key and would knock each other off; enable one"
|
||||
)
|
||||
(mkAssertion (
|
||||
!(cfg.warp.instances != null && cfg.warp.devices != { })
|
||||
) "proxy-suite: warp.instances is a shorthand for warp.devices; set one of them")
|
||||
(mkAssertion (!(derived.warpCfg.grouped && builtins.elem "warp" derived.warpDeviceNames))
|
||||
"proxy-suite: with several WARP devices, \"warp\" names their group; call the device something else"
|
||||
)
|
||||
(mkAssertion (
|
||||
!(cfg.warp.enable && derived.warpCfg.grouped && cfg.warp.asAmneziaWg)
|
||||
) "proxy-suite: warp.asAmneziaWg is one global profile, so it takes a single WARP device")
|
||||
# inbounds.routing.serverSource: a dummy interface, and an address per user in each range.
|
||||
(
|
||||
let
|
||||
@@ -281,6 +292,41 @@ let
|
||||
(mkAssertion (
|
||||
!(pureXrayEnabled && proxyCfg.selection == "selector")
|
||||
) "proxy-suite: proxy.selection = \"selector\" requires proxy.backend = \"sing-box\" or \"hybrid\"")
|
||||
(mkAssertion (
|
||||
!(pureXrayEnabled && proxyCfg.selection == "failover")
|
||||
) "proxy-suite: proxy.selection = \"failover\" requires proxy.backend = \"sing-box\" or \"hybrid\"")
|
||||
(mkAssertion (
|
||||
!(pureXrayEnabled && proxyCfg.groups != { })
|
||||
) "proxy-suite: proxy.groups requires proxy.backend = \"sing-box\" or \"hybrid\"")
|
||||
(
|
||||
let
|
||||
clashing = builtins.filter (
|
||||
g: builtins.elem g (builtinTags ++ effectiveOutboundTags ++ subscriptionTags)
|
||||
) derived.groupTags;
|
||||
in
|
||||
mkAssertion (!proxyEnabled || clashing == [ ])
|
||||
"proxy-suite: proxy.groups names must differ from outbound and subscription tags and from proxy, direct, block: ${lib.concatStringsSep ", " clashing}"
|
||||
)
|
||||
(
|
||||
let
|
||||
bad = builtins.filter (g: builtins.match "[A-Za-z0-9][A-Za-z0-9._-]*" g == null) derived.groupTags;
|
||||
in
|
||||
mkAssertion (bad == [ ])
|
||||
"proxy-suite: proxy.groups names may hold only letters, digits, '.', '_' and '-', starting with a letter or digit: ${lib.concatStringsSep ", " bad}"
|
||||
)
|
||||
(
|
||||
let
|
||||
empty = builtins.filter (
|
||||
g:
|
||||
let
|
||||
grp = proxyCfg.groups.${g};
|
||||
in
|
||||
grp.outbounds == [ ] && grp.subscriptions == [ ] && grp.match == [ ]
|
||||
) derived.groupTags;
|
||||
in
|
||||
mkAssertion (empty == [ ])
|
||||
"proxy-suite: proxy.groups need members in outbounds, subscriptions or match: ${lib.concatStringsSep ", " empty}"
|
||||
)
|
||||
(mkAssertion
|
||||
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
|
||||
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.backend = \"xray\"; use udp/tcp DNS for XRay"
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
|
||||
let
|
||||
curl = "${pkgs.curl}/bin/curl";
|
||||
# As the start script reads them (script-blocks/outbounds.nix).
|
||||
groupPinsDir = "${dirOf pinnedOutboundFile}/group-pins";
|
||||
|
||||
restartActiveBlock = lib.concatMapStrings (svc: ''
|
||||
if ${systemctl} is-active --quiet ${svc}; then
|
||||
@@ -77,6 +79,70 @@ let
|
||||
set -euo pipefail
|
||||
tag="''${1:-}"
|
||||
|
||||
# group/member pins inside a group, group/ unpins it (`proxy-ctl proxy pin --in`).
|
||||
case "$tag" in
|
||||
*/*)
|
||||
group="''${tag%%/*}"
|
||||
member="''${tag#*/}"
|
||||
case "$group/$member" in
|
||||
/* | */*/* | . | .. | ./* | ../* | */. | */..)
|
||||
echo "proxy-suite: not a group and member: $tag" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
if [ -r "${outboundInventoryFile}" ] \
|
||||
&& ! ${jq} -e --arg g "$group" '.groups // {} | has($g)' "${outboundInventoryFile}" >/dev/null; then
|
||||
echo "proxy-suite: unknown group '$group'" >&2
|
||||
exit 1
|
||||
fi
|
||||
STRATEGY=$(${jq} -r --arg g "$group" '.groups[$g].strategy // ""' "${outboundInventoryFile}" 2>/dev/null || true)
|
||||
if [ -z "$member" ]; then
|
||||
rm -f "${groupPinsDir}/$group"
|
||||
# A failover group is picked again by the watcher, a selector stays where it is; a
|
||||
# urltest group only becomes one again with a restart.
|
||||
if [ "$STRATEGY" = urltest ]; then
|
||||
${restartActiveConfigConsumersBlock}
|
||||
elif [ -f "${outboundInventoryFile}" ]; then
|
||||
INVENTORY_TMP=$(mktemp "${outboundInventoryFile}.XXXXXX")
|
||||
${jq} --arg g "$group" '.groups[$g].pinned = ""' "${outboundInventoryFile}" > "$INVENTORY_TMP"
|
||||
chmod 644 "$INVENTORY_TMP"
|
||||
mv -f "$INVENTORY_TMP" "${outboundInventoryFile}"
|
||||
fi
|
||||
${restartActiveBlock tunConsumers}
|
||||
exit 0
|
||||
fi
|
||||
if [ -r "${outboundInventoryFile}" ] \
|
||||
&& ! ${jq} -e --arg g "$group" --arg t "$member" '.groups[$g].members | index([$t]) != null' "${outboundInventoryFile}" >/dev/null; then
|
||||
echo "proxy-suite: '$member' is not in group '$group'" >&2
|
||||
exit 1
|
||||
fi
|
||||
if [ -e "${runtimeOutboundsDir}/$member.disabled" ]; then
|
||||
echo "proxy-suite: outbound '$member' is disabled; enable it first: proxy-ctl proxy outbounds enable $member" >&2
|
||||
exit 1
|
||||
fi
|
||||
mkdir -p "${groupPinsDir}"
|
||||
printf '%s\n' "$member" > "${groupPinsDir}/$group"
|
||||
CLASH_SECRET_FILE="$(dirname "${outboundInventoryFile}")/clash-secret"
|
||||
CLASH_SECRET=""
|
||||
[ ! -r "$CLASH_SECRET_FILE" ] || CLASH_SECRET=$(${pkgs.coreutils}/bin/tr -d '\r\n' < "$CLASH_SECRET_FILE")
|
||||
if [ "$STRATEGY" != urltest ] && ${curl} -sf -X PUT "${clashApi}/proxies/$group" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H @<(printf 'Authorization: Bearer %s\n' "$CLASH_SECRET") \
|
||||
-d "$(${jq} -cn --arg name "$member" '{name:$name}')" >/dev/null 2>&1; then
|
||||
if [ -f "${outboundInventoryFile}" ]; then
|
||||
INVENTORY_TMP=$(mktemp "${outboundInventoryFile}.XXXXXX")
|
||||
${jq} --arg g "$group" --arg t "$member" '.groups[$g].pinned = $t' "${outboundInventoryFile}" > "$INVENTORY_TMP"
|
||||
chmod 644 "$INVENTORY_TMP"
|
||||
mv -f "$INVENTORY_TMP" "${outboundInventoryFile}"
|
||||
fi
|
||||
${restartActiveBlock tunConsumers}
|
||||
exit 0
|
||||
fi
|
||||
${restartActiveConfigConsumersBlock}
|
||||
exit 0
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -z "$tag" ]; then
|
||||
rm -f "${pinnedOutboundFile}"
|
||||
else
|
||||
|
||||
@@ -78,6 +78,15 @@ in
|
||||
ROUTE_MODE_STATE_FILE = routeModeStateFile;
|
||||
DEFAULT_ROUTE_MODE = if proxyCfg.routing.default == "proxy" then "blacklist" else "whitelist";
|
||||
AWG_PROFILES_FILE = toString amneziaWgProfileNamesFile;
|
||||
# The WARP devices behind outbounds, each with the unit that carries it.
|
||||
WARP_DEVICES = builtins.toJSON (
|
||||
lib.optionals (ctx.warpCfg.enable && ctx.warpCfg.asOutbound != null) (
|
||||
map (d: {
|
||||
inherit (d) tag;
|
||||
unit = if ctx.warpCfg.asOutbound == "singBox" then d.tunnelUnit else "proxy-suite-awg-${d.tag}";
|
||||
}) ctx.warpCfg.devices
|
||||
)
|
||||
);
|
||||
# Profiles and outbounds added with `awg add` and `proxy outbounds add`.
|
||||
AWG_RUNTIME_GLOBAL = flag awgRuntimeGlobal;
|
||||
AWG_RUNTIME_OUTBOUNDS = flag awgRuntimeOutbounds;
|
||||
|
||||
@@ -78,9 +78,41 @@ let
|
||||
inherit userControlAllows;
|
||||
}
|
||||
);
|
||||
# `proxy-ctl proxy groups watch`: failover groups and "failover" selection, through the Clash API.
|
||||
outboundGroupsUnit = lib.mkIf derived.outboundGroupsWatch {
|
||||
services.proxy-suite.internal.services.proxy-suite-outbound-groups = {
|
||||
description = "proxy-suite - move failover groups off outbounds that stop working";
|
||||
after = [ "proxy-suite-socks.service" ];
|
||||
bindsTo = [ "proxy-suite-socks.service" ];
|
||||
wantedBy = [ "proxy-suite-socks.service" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${control.proxyCtl}/bin/proxy-ctl proxy groups watch";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
# health/ takes hints from watchdogs; groups-state.json is for the front ends.
|
||||
RuntimeDirectory = "proxy-suite-outbound-groups";
|
||||
RuntimeDirectoryMode = "0755";
|
||||
NoNewPrivileges = true;
|
||||
PrivateTmp = true;
|
||||
ProtectSystem = "strict";
|
||||
ProtectHome = true;
|
||||
ProtectClock = true;
|
||||
ProtectControlGroups = true;
|
||||
ProtectHostname = true;
|
||||
ProtectKernelLogs = true;
|
||||
ProtectKernelModules = true;
|
||||
ProtectKernelTunables = true;
|
||||
RestrictRealtime = true;
|
||||
RestrictSUIDSGID = true;
|
||||
LockPersonality = true;
|
||||
CapabilityBoundingSet = [ "" ];
|
||||
};
|
||||
};
|
||||
};
|
||||
in
|
||||
lib.mkMerge [
|
||||
autoProxyUnits
|
||||
outboundGroupsUnit
|
||||
{
|
||||
services.proxy-suite.internal = {
|
||||
# The GUI's pkexec needs its setuid wrapper.
|
||||
|
||||
@@ -31,6 +31,12 @@
|
||||
let
|
||||
sshProxyTag = "ssh-proxy";
|
||||
torOutboundEnabled = torCfg != null && torCfg.enable && torCfg.asOutbound;
|
||||
groupsJq = builtins.path {
|
||||
name = "proxy-suite-outbound-groups";
|
||||
path = ../../outbound-groups.jq;
|
||||
};
|
||||
# `proxy-ctl proxy pin <tag> --in <group>`: one file per group, next to the top-level pin.
|
||||
groupPinsDir = "${dirOf pinnedOutboundFile}/group-pins";
|
||||
|
||||
# sing-box domain strategies in XRay's names (UseIPv4v6 = prefer IPv4).
|
||||
xrayDomainStrategies = {
|
||||
@@ -549,7 +555,7 @@ let
|
||||
# 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 = ''
|
||||
tagsBlock = ''
|
||||
OUTBOUND_TAGS_JSON=$(${jq} -c '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
|
||||
# `proxy-ctl proxy outbounds disable` leaves <tag>.disabled next to the runtime entries:
|
||||
@@ -564,13 +570,101 @@ let
|
||||
done
|
||||
fi
|
||||
DISABLED_TAGS_JSON=$(${jq} -c --argjson tags "$OUTBOUND_TAGS_JSON" 'map(select(. as $t | $tags | index([$t]))) | unique' <<< "$DISABLED_TAGS_JSON")
|
||||
'';
|
||||
|
||||
# proxy.groups and those `proxy-ctl proxy groups add` left as <tag>.group next to the runtime
|
||||
# outbounds (a declared one wins), resolved against the outbounds this start has: members
|
||||
# from subscriptions and patterns only exist now. The group outbounds join the rest; what
|
||||
# the top level picks among is ungrouped outbounds and outermost groups, by priority.
|
||||
groupsBlock =
|
||||
let
|
||||
declared = lib.mapAttrs (_: g: {
|
||||
inherit (g)
|
||||
outbounds
|
||||
subscriptions
|
||||
match
|
||||
strategy
|
||||
failback
|
||||
interval
|
||||
;
|
||||
}) proxyCfg.groups;
|
||||
in
|
||||
''
|
||||
GROUPS_CONFIG_JSON=${lib.escapeShellArg (builtins.toJSON declared)}
|
||||
PRIORITY_JSON=${lib.escapeShellArg (builtins.toJSON proxyCfg.priority)}
|
||||
GROUP_PINS_JSON='{}'
|
||||
${lib.optionalString (!pureXrayEnabled) ''
|
||||
if [ -d "${runtimeOutboundsDir}" ]; then
|
||||
for GROUP_FILE in "${runtimeOutboundsDir}"/*.group; do
|
||||
[ -e "$GROUP_FILE" ] || continue
|
||||
GROUP_NAME="''${GROUP_FILE##*/}"
|
||||
GROUP_NAME="''${GROUP_NAME%.group}"
|
||||
if ${jq} -e --arg g "$GROUP_NAME" 'has($g)' <<< "$GROUPS_CONFIG_JSON" >/dev/null; then
|
||||
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': proxy.groups declares it" >&2
|
||||
continue
|
||||
fi
|
||||
if ! GROUP_JSON=$(_proxy_suite_read_source "$GROUP_FILE" | ${jq} -ce '
|
||||
{outbounds: (.outbounds // []), subscriptions: (.subscriptions // []), match: (.match // []),
|
||||
strategy: (.strategy // "failover"), failback: (.failback != false), interval: (.interval // null),
|
||||
runtime: true}
|
||||
| select(.strategy | IN("failover", "urltest", "selector"))
|
||||
| select([.outbounds, .subscriptions, .match] | all(type == "array" and all(type == "string")))'); then
|
||||
echo "proxy-suite: warning: ignoring runtime group '$GROUP_NAME': not a valid group" >&2
|
||||
continue
|
||||
fi
|
||||
GROUPS_CONFIG_JSON=$(${jq} -c --arg g "$GROUP_NAME" --argjson v "$GROUP_JSON" '.[$g] = $v' <<< "$GROUPS_CONFIG_JSON")
|
||||
done
|
||||
if [ -f "${runtimeOutboundsDir}/priority.json" ]; then
|
||||
if RUNTIME_PRIORITY_JSON=$(_proxy_suite_read_source "${runtimeOutboundsDir}/priority.json" \
|
||||
| ${jq} -ce 'select(type == "object" and all(.[]; type == "number")) | map_values(floor)'); then
|
||||
PRIORITY_JSON=$(${jq} -c --argjson r "$RUNTIME_PRIORITY_JSON" '. + $r' <<< "$PRIORITY_JSON")
|
||||
else
|
||||
echo "proxy-suite: warning: ignoring ${runtimeOutboundsDir}/priority.json: not {tag: number}" >&2
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
if [ -d "${groupPinsDir}" ]; then
|
||||
for GROUP_PIN_FILE in "${groupPinsDir}"/*; do
|
||||
[ -f "$GROUP_PIN_FILE" ] || continue
|
||||
GROUP_PINS_JSON=$(${jq} -c --arg g "''${GROUP_PIN_FILE##*/}" \
|
||||
--arg t "$(tr -d '\r\n[:space:]' < "$GROUP_PIN_FILE" 2>/dev/null || true)" '.[$g] = $t' <<< "$GROUP_PINS_JSON")
|
||||
done
|
||||
fi
|
||||
''}
|
||||
# A runtime outbound may have taken a group's name: the outbound stays.
|
||||
for GROUP_NAME in $(${jq} -r --argjson tags "$OUTBOUND_TAGS_JSON" 'keys[] | select(. as $g | $tags | index([$g]))' <<< "$GROUPS_CONFIG_JSON"); do
|
||||
echo "proxy-suite: warning: ignoring group '$GROUP_NAME': an outbound has that tag" >&2
|
||||
GROUPS_CONFIG_JSON=$(${jq} -c --arg g "$GROUP_NAME" 'del(.[$g])' <<< "$GROUPS_CONFIG_JSON")
|
||||
done
|
||||
GROUPS_RESULT=$(${jq} -nc --argjson tags "$OUTBOUND_TAGS_JSON" --argjson sources "''${OUTBOUND_SOURCES_JSON:-{\}}" \
|
||||
'{tags: $tags, sources: $sources}' \
|
||||
| ${jq} -c -f ${groupsJq} \
|
||||
--argjson groups "$GROUPS_CONFIG_JSON" \
|
||||
--argjson priority "$PRIORITY_JSON" \
|
||||
--argjson disabled "$DISABLED_TAGS_JSON" \
|
||||
--argjson pins "$GROUP_PINS_JSON" \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
|
||||
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||
--argjson watched "''${GROUPS_WATCHED:-true}")
|
||||
${jq} -r '.warnings[] | "proxy-suite: warning: " + .' <<< "$GROUPS_RESULT" >&2
|
||||
if ${jq} -e '.errors != []' <<< "$GROUPS_RESULT" >/dev/null; then
|
||||
${jq} -r '.errors[] | "proxy-suite: " + .' <<< "$GROUPS_RESULT" >&2
|
||||
exit 1
|
||||
fi
|
||||
GROUP_TAGS_JSON=$(${jq} -c '.groups | keys_unsorted' <<< "$GROUPS_RESULT")
|
||||
GROUPS_INFO_JSON=$(${jq} -c '.groups' <<< "$GROUPS_RESULT")
|
||||
TOP_TAGS_JSON=$(${jq} -c '.top' <<< "$GROUPS_RESULT")
|
||||
OUTBOUNDS_JSON=$(${jq} -c --argjson g "$(${jq} -c '.outbounds' <<< "$GROUPS_RESULT")" '. + $g' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
pinBlock = ''
|
||||
PINNED_OUTBOUND=""
|
||||
if [ -r "${pinnedOutboundFile}" ]; then
|
||||
PINNED_OUTBOUND="$(tr -d '\r\n[:space:]' < "${pinnedOutboundFile}" 2>/dev/null || true)"
|
||||
fi
|
||||
if [ -n "$PINNED_OUTBOUND" ] \
|
||||
&& ! ${jq} -e --arg t "$PINNED_OUTBOUND" 'index($t) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
|
||||
&& ! ${jq} -e --arg t "$PINNED_OUTBOUND" --argjson groups "$GROUP_TAGS_JSON" '. + $groups | index([$t]) != null' <<< "$OUTBOUND_TAGS_JSON" >/dev/null; then
|
||||
echo "proxy-suite: warning: pinned outbound '$PINNED_OUTBOUND' is not available; picking automatically" >&2
|
||||
PINNED_OUTBOUND=""
|
||||
fi
|
||||
@@ -587,7 +681,7 @@ let
|
||||
selectableBlock = ''
|
||||
SELECTABLE_TAGS_JSON=$(${jq} -c --argjson ex ${lib.escapeShellArg (builtins.toJSON proxyCfg.selectionExclude)} \
|
||||
--argjson disabled "$DISABLED_TAGS_JSON" \
|
||||
'${lib.optionalString torOutboundEnabled "(if length > 1 then [\"tor\"] else [] end) as $tor | "}map(select(. as $t | ($ex + $disabled${lib.optionalString torOutboundEnabled " + $tor"}) | index([$t]) | not))' <<< "$OUTBOUND_TAGS_JSON")
|
||||
'${lib.optionalString torOutboundEnabled "(if length > 1 then [\"tor\"] else [] end) as $tor | "}map(select(. as $t | ($ex + $disabled${lib.optionalString torOutboundEnabled " + $tor"}) | index([$t]) | not))' <<< "$TOP_TAGS_JSON")
|
||||
if [ -z "$PINNED_OUTBOUND" ] && [ "$(${jq} 'length' <<< "$SELECTABLE_TAGS_JSON")" -eq 0 ]; then
|
||||
echo "proxy-suite: every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one (proxy-ctl proxy outbounds enable), or exclude fewer" >&2
|
||||
exit 1
|
||||
@@ -606,10 +700,15 @@ let
|
||||
--slurpfile xobs <(printf '%s' "${if hybridEnabled then "$XRAY_OUTBOUNDS_JSON" else "[]"}") \
|
||||
--argjson selectable "$SELECTABLE_TAGS_JSON" \
|
||||
--argjson disabled "$DISABLED_TAGS_JSON" \
|
||||
--argjson groups "$GROUPS_INFO_JSON" \
|
||||
--argjson top "$TOP_TAGS_JSON" \
|
||||
--argjson priority "$PRIORITY_JSON" \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
'{tags: $tags, sources: $sources, pinned: $pinned, selection: $selection,
|
||||
detours: ([($xobs[0] + $obs[0])[] | (.detour // .streamSettings.sockopt.dialerProxy?) as $h
|
||||
| select($h != null) | {key: .tag, value: $h}] | from_entries),
|
||||
excluded: ($tags - $selectable), disabled: $disabled}' \
|
||||
excluded: ($top - $selectable), disabled: $disabled,
|
||||
groups: $groups, top: $top, priority: $priority, url: $url}' \
|
||||
> "$RUNTIME_DIR/outbounds.json"
|
||||
chmod 644 "$RUNTIME_DIR/outbounds.json"
|
||||
'';
|
||||
@@ -627,7 +726,9 @@ let
|
||||
|
||||
sshProxyBlock = lib.optionalString sshProxyCfg.asOutbound (mkSshProxyOutboundBlock routingMark);
|
||||
warpBlock = lib.optionalString (warpCfg.enable && warpCfg.asOutbound == "singBox") (
|
||||
mkTunnelOutboundBlock "proxy-suite-warp-tunnel" "warp" "warp" warpCfg.tunnelPort
|
||||
lib.concatMapStrings (
|
||||
d: mkTunnelOutboundBlock d.tunnelUnit "warp" d.tag d.tunnelPort
|
||||
) warpCfg.devices
|
||||
);
|
||||
torBlock = lib.optionalString torOutboundEnabled (
|
||||
mkTunnelOutboundBlock "proxy-suite-tor" "tor" "tor" torCfg.socksPort
|
||||
@@ -665,6 +766,30 @@ let
|
||||
''OUTBOUNDS_JSON=$(${jq} --arg t "$PROXY_TAG" '[{type:"selector",tag:"proxy",outbounds:[$t],default:$t}] + .' <<< "$OUTBOUNDS_JSON")''
|
||||
}
|
||||
''
|
||||
else if selectionMode == "failover" then
|
||||
''
|
||||
# Every tag, so a pin reaches any of them live; proxy-suite-outbound-groups moves
|
||||
# it along the selectable ones, cutting what the failed one still carried.
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
DEFAULT_TAG="$PINNED_OUTBOUND"
|
||||
if [ -z "$DEFAULT_TAG" ]; then
|
||||
DEFAULT_TAG=$(${jq} -r '.[0]' <<< "$SELECTABLE_TAGS_JSON")
|
||||
fi
|
||||
if [ -z "$PINNED_OUTBOUND" ] && [ "''${GROUPS_WATCHED:-true}" != true ]; then
|
||||
# No Clash API here for the watcher to drive: sing-box's own urltest instead.
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$SELECTABLE_TAGS_JSON" \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:"30s",tolerance:$tolerance}')
|
||||
else
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--arg default "$DEFAULT_TAG" \
|
||||
'{type:"selector",tag:"proxy",outbounds:$tags,default:$default,interrupt_exist_connections:true}')
|
||||
fi
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else if selectionMode == "selector" then
|
||||
''
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
@@ -717,6 +842,8 @@ let
|
||||
+ awgBlocks
|
||||
+ detourBlock
|
||||
+ requireOutboundsBlock
|
||||
+ tagsBlock
|
||||
+ groupsBlock
|
||||
+ pinBlock
|
||||
+ selectableBlock
|
||||
+ inventoryBlock
|
||||
@@ -725,6 +852,6 @@ let
|
||||
in
|
||||
{
|
||||
inherit mkOutboundScript rawOutboundJson;
|
||||
# For the checks: which outbounds a pin and selection may take.
|
||||
selectionBlocks = pinBlock + selectableBlock + inventoryBlock;
|
||||
# For the checks: groups, and which outbounds a pin and selection may take.
|
||||
selectionBlocks = tagsBlock + groupsBlock + pinBlock + selectableBlock + inventoryBlock;
|
||||
}
|
||||
@@ -216,6 +216,8 @@ let
|
||||
|
||||
${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"}
|
||||
|
||||
|
||||
@@ -89,69 +89,91 @@ let
|
||||
"userspace"
|
||||
"interface"
|
||||
];
|
||||
deviceTags = map (d: d.tag) w.devices;
|
||||
in
|
||||
{
|
||||
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
|
||||
# One AmneziaWG profile per device, named after it.
|
||||
services.proxy-suite.amneziaWg.profiles = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) (
|
||||
lib.listToAttrs (
|
||||
map (
|
||||
d:
|
||||
lib.nameValuePair d.tag {
|
||||
configFile = d.profilePath;
|
||||
inherit (d) endpoint;
|
||||
inherit (w) domainStrategy;
|
||||
asOutbound = lib.mkIf viaAmneziaWg w.asOutbound;
|
||||
autostart = lib.mkIf w.autostart true;
|
||||
}
|
||||
) w.devices
|
||||
)
|
||||
);
|
||||
|
||||
# Several devices: "warp" picks among them, so whatever names "warp" fails over.
|
||||
services.proxy-suite.proxy.groups = lib.mkIf (w.grouped && w.asOutbound != null) {
|
||||
warp = {
|
||||
configFile = w.profilePath;
|
||||
inherit (w) endpoint domainStrategy;
|
||||
asOutbound = lib.mkIf viaAmneziaWg w.asOutbound;
|
||||
autostart = lib.mkIf w.autostart true;
|
||||
outbounds = lib.mkDefault deviceTags;
|
||||
strategy = lib.mkDefault w.group.strategy;
|
||||
failback = lib.mkDefault w.group.failback;
|
||||
};
|
||||
};
|
||||
|
||||
services.proxy-suite.internal.services = lib.mkMerge [
|
||||
(lib.mkIf (w.asOutbound == "singBox") {
|
||||
proxy-suite-warp-tunnel = mkTunnel {
|
||||
description = "proxy-suite - Cloudflare WARP tunnel behind the warp outbound";
|
||||
unit = "proxy-suite-warp-tunnel";
|
||||
tag = "warp";
|
||||
profile = ''
|
||||
profile=${lib.escapeShellArg w.profilePath}
|
||||
if [ ! -s "$profile" ]; then
|
||||
echo "proxy-suite: waiting for the WARP profile at $profile" >&2
|
||||
until [ -s "$profile" ]; do sleep 5; done
|
||||
fi
|
||||
'';
|
||||
inherit (w)
|
||||
tunnelPort
|
||||
directPort
|
||||
endpoint
|
||||
domainStrategy
|
||||
;
|
||||
};
|
||||
})
|
||||
services.proxy-suite.internal.services = lib.mkMerge (
|
||||
map (
|
||||
d:
|
||||
lib.mkMerge [
|
||||
(lib.mkIf (w.asOutbound == "singBox") {
|
||||
${d.tunnelUnit} = mkTunnel {
|
||||
description = "proxy-suite - Cloudflare WARP tunnel behind the ${d.tag} outbound";
|
||||
unit = d.tunnelUnit;
|
||||
inherit (d) tag;
|
||||
profile = ''
|
||||
profile=${lib.escapeShellArg d.profilePath}
|
||||
if [ ! -s "$profile" ]; then
|
||||
echo "proxy-suite: waiting for the WARP profile at $profile" >&2
|
||||
until [ -s "$profile" ]; do sleep 5; done
|
||||
fi
|
||||
'';
|
||||
inherit (d)
|
||||
tunnelPort
|
||||
directPort
|
||||
endpoint
|
||||
;
|
||||
inherit (w) domainStrategy;
|
||||
};
|
||||
})
|
||||
|
||||
(lib.mkIf w.autoRegister {
|
||||
proxy-suite-warp = {
|
||||
description = "proxy-suite - register a Cloudflare WARP device with wgcf";
|
||||
after = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
path = [ pkgs.wgcf ];
|
||||
# Retried until it registers. Not a oneshot: a slow or failed registration must not
|
||||
# hold up or fail a switch.
|
||||
startLimitIntervalSec = 0;
|
||||
serviceConfig = unprivilegedServiceConfig [ ] // {
|
||||
Type = "simple";
|
||||
RemainAfterExit = true;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 30;
|
||||
StateDirectory = "proxy-suite/warp";
|
||||
StateDirectoryMode = "0700";
|
||||
WorkingDirectory = "${derived.constants.stateDir}/warp";
|
||||
UMask = "0077";
|
||||
LoadCredential = lib.optional (
|
||||
cfg.proxy.enable && withProxyAuth
|
||||
) "proxy-password:${passwordSource}";
|
||||
ExecStart = registerScript;
|
||||
};
|
||||
};
|
||||
(lib.mkIf d.autoRegister {
|
||||
${d.registerUnit} = {
|
||||
description = "proxy-suite - register the Cloudflare WARP device ${d.tag} with wgcf";
|
||||
after = [ "network-online.target" ] ++ lib.optional cfg.proxy.enable "proxy-suite-socks.service";
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
path = [ pkgs.wgcf ];
|
||||
# Retried until it registers. Not a oneshot: a slow or failed registration must not
|
||||
# hold up or fail a switch.
|
||||
startLimitIntervalSec = 0;
|
||||
serviceConfig = unprivilegedServiceConfig [ ] // {
|
||||
Type = "simple";
|
||||
RemainAfterExit = true;
|
||||
Restart = "on-failure";
|
||||
RestartSec = 30;
|
||||
StateDirectory = "proxy-suite/${d.stateSubdir}";
|
||||
StateDirectoryMode = "0700";
|
||||
WorkingDirectory = "${derived.constants.stateDir}/${d.stateSubdir}";
|
||||
UMask = "0077";
|
||||
LoadCredential = lib.optional (
|
||||
cfg.proxy.enable && withProxyAuth
|
||||
) "proxy-password:${passwordSource}";
|
||||
ExecStart = registerScript;
|
||||
};
|
||||
};
|
||||
|
||||
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
|
||||
proxy-suite-awg-warp = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
|
||||
wants = [ "proxy-suite-warp.service" ];
|
||||
};
|
||||
})
|
||||
];
|
||||
# Only pulls registration in: a simple unit gives the profile no ordering guarantee.
|
||||
"proxy-suite-awg-${d.tag}" = lib.mkIf (w.asAmneziaWg || viaAmneziaWg) {
|
||||
wants = [ "${d.registerUnit}.service" ];
|
||||
};
|
||||
})
|
||||
]
|
||||
) w.devices
|
||||
);
|
||||
}
|
||||
@@ -10,6 +10,7 @@
|
||||
|
||||
let
|
||||
inherit (derived.constants) serviceUser runAsServiceUser ifPrivileged;
|
||||
hintDir = "${derived.constants.runtimeDir}/proxy-suite-outbound-groups/health";
|
||||
scriptsDir = import ./lib/scripts-dir.nix { inherit lib; };
|
||||
|
||||
# sing-box's "local" server has no upstream on hosts behind systemd-resolved, so the tunnel
|
||||
@@ -68,6 +69,10 @@ let
|
||||
fi
|
||||
''}
|
||||
uplink_down=0
|
||||
# proxy-suite-outbound-groups hears of the first miss: a failover group moves off it now.
|
||||
if (( healthy && failures == 0 )) && [[ -d ${hintDir} ]]; then
|
||||
${pkgs.coreutils}/bin/touch ${hintDir}/${lib.escapeShellArg tag} 2>/dev/null || true
|
||||
fi
|
||||
if (( healthy ? ++failures >= 3 : SECONDS - since >= 15 )); then
|
||||
echo "proxy-suite: ${tag} is not answering; restarting the tunnel on a new source port" >&2
|
||||
kill "$tunnel"
|
||||
|
||||
Reference in new issue
Block a user