feat: outbound groups
This commit is contained in:
35 files changed
+2444
-210
No files matched your search
@@ -157,8 +157,19 @@ Changes and secrets need root or the userControl group.
|
||||
test ping, delay, download speed (default: ping, delay)
|
||||
proxy outbounds link <tag> [--qr|--json|--config]
|
||||
its link, QR code, JSON, or client config
|
||||
proxy pin [tag] always use this outbound (no tag: pick from a menu)
|
||||
proxy unpin go back to automatic selection
|
||||
proxy pin [tag] [--in <group>] always use this outbound (no tag: pick from a menu);
|
||||
--in: hold a group on one of its members
|
||||
proxy unpin [--in <group>] go back to automatic selection
|
||||
proxy groups [list] outbound groups, their members, and what each uses
|
||||
proxy groups add <tag> [member...] [--sub <sub>]... [--match <pattern>]...
|
||||
[--strategy failover|urltest|selector] [--no-failback] [--interval <d>]
|
||||
add a group (failover by default)
|
||||
proxy groups rm <tag> remove a group added with groups add
|
||||
proxy groups members <tag> add|rm <member...>
|
||||
proxy groups strategy <tag> failover|urltest|selector
|
||||
proxy priority [list] the top level in the order it is picked in
|
||||
proxy priority <tag> <n>|up|down|--clear
|
||||
lower goes first; up/down renumbers the top level
|
||||
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
|
||||
show or override the routing mode
|
||||
proxy subs [list|update] subscriptions; update refetches them
|
||||
@@ -197,7 +208,7 @@ Changes and secrets need root or the userControl group.
|
||||
stays on until turned off here or with the tunnel
|
||||
|
||||
ssh [status|on|off] SSH tunnel
|
||||
warp [status|on|off] WARP tunnel
|
||||
warp [status|on|off] [device] WARP tunnel (every device, or the one named)
|
||||
tor [status|on|off] Tor
|
||||
tor newnym new circuits for new connections
|
||||
tg [status|on|off] Telegram proxy
|
||||
|
||||
@@ -180,6 +180,7 @@ services.proxy-suite = {
|
||||
strategy = null;
|
||||
};
|
||||
enable = false;
|
||||
groups = { };
|
||||
ipv6 = config.networking.enableIPv6;
|
||||
listener = {
|
||||
address = "127.0.0.1";
|
||||
@@ -191,6 +192,7 @@ services.proxy-suite = {
|
||||
port = 1080;
|
||||
};
|
||||
outbounds = [ ];
|
||||
priority = { };
|
||||
routing = {
|
||||
block = {
|
||||
domains = [ ];
|
||||
@@ -335,10 +337,16 @@ services.proxy-suite = {
|
||||
asOutbound = null;
|
||||
autostart = false;
|
||||
configFile = null;
|
||||
devices = { };
|
||||
domainStrategy = if config.networking.enableIPv6 then "prefer_ipv6" else "prefer_ipv4";
|
||||
enable = false;
|
||||
endpoint = null;
|
||||
generatorUrl = null;
|
||||
group = {
|
||||
failback = true;
|
||||
strategy = "failover";
|
||||
};
|
||||
instances = null;
|
||||
};
|
||||
whitelistBypass = {
|
||||
creators = { };
|
||||
|
||||
+112
-5
@@ -36,6 +36,14 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [rules](#services-proxy-suite-proxy-dns-singbox-rules)
|
||||
- [servers](#services-proxy-suite-proxy-dns-singbox-servers)
|
||||
- [strategy](#services-proxy-suite-proxy-dns-strategy)
|
||||
- [groups](#services-proxy-suite-proxy-groups)
|
||||
- `<name>`
|
||||
- [failback](#services-proxy-suite-proxy-groups-name-failback)
|
||||
- [interval](#services-proxy-suite-proxy-groups-name-interval)
|
||||
- [match](#services-proxy-suite-proxy-groups-name-match)
|
||||
- [outbounds](#services-proxy-suite-proxy-groups-name-outbounds)
|
||||
- [strategy](#services-proxy-suite-proxy-groups-name-strategy)
|
||||
- [subscriptions](#services-proxy-suite-proxy-groups-name-subscriptions)
|
||||
- [ipv6](#services-proxy-suite-proxy-ipv6)
|
||||
- listener
|
||||
- [address](#services-proxy-suite-proxy-listener-address)
|
||||
@@ -59,6 +67,7 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [url](#services-proxy-suite-proxy-outbounds-url)
|
||||
- [urlFile](#services-proxy-suite-proxy-outbounds-urlfile)
|
||||
- [xrayJson](#services-proxy-suite-proxy-outbounds-xrayjson)
|
||||
- [priority](#services-proxy-suite-proxy-priority)
|
||||
- routing
|
||||
- block
|
||||
- [domains](#services-proxy-suite-proxy-routing-block-domains)
|
||||
@@ -352,6 +361,91 @@ Which IP versions to resolve\. Use ` ipv4_only ` if the uplink has no IPv6\. sin
|
||||
**Default:** `null`\
|
||||
**Example:** `"ipv4_only"`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups"></a>
|
||||
## services\.proxy-suite\.proxy\.groups
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** attribute set of (submodule)\
|
||||
**Default:** `{ }`\
|
||||
**Example:**
|
||||
|
||||
```nix
|
||||
{
|
||||
warp-pool.outbounds = [ "warp-1" "warp-2" ];
|
||||
eu = {
|
||||
subscriptions = [ "community-list" ];
|
||||
match = [ "de-*" ];
|
||||
strategy = "urltest";
|
||||
};
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-failback"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.failback
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-interval"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.interval
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"15s"`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-match"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.match
|
||||
|
||||
Glob patterns (` * `, ` ? `) over outbound tags; every match is a member\.
|
||||
|
||||
**Type:** list of string\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "de-*" ]`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-outbounds"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.outbounds
|
||||
|
||||
Member tags, in order: the failover order\. Any outbound or group tag\.
|
||||
|
||||
**Type:** list of string\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "warp-1" "warp-2" ]`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-strategy"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.strategy
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** one of “failover”, “urltest”, “selector”\
|
||||
**Default:** `"failover"`
|
||||
|
||||
<a id="services-proxy-suite-proxy-groups-name-subscriptions"></a>
|
||||
## services\.proxy-suite\.proxy\.groups\.\<name>\.subscriptions
|
||||
|
||||
Subscriptions whose every entry is a member, as the subscription holds them at start\.
|
||||
|
||||
**Type:** list of string\
|
||||
**Default:** `[ ]`\
|
||||
**Example:** `[ "community-list" ]`
|
||||
|
||||
<a id="services-proxy-suite-proxy-ipv6"></a>
|
||||
## services\.proxy-suite\.proxy\.ipv6
|
||||
|
||||
@@ -541,6 +635,17 @@ Raw XRay outbound JSON, instead of ` url ` (XRay backend)\. Its tag is replaced\
|
||||
**Default:** `null`\
|
||||
**Example:** `{ protocol = "vless"; settings = { address = "example.com"; }; }`
|
||||
|
||||
<a id="services-proxy-suite-proxy-priority"></a>
|
||||
## services\.proxy-suite\.proxy\.priority
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** attribute set of signed integer\
|
||||
**Default:** `{ }`\
|
||||
**Example:** `{ de-vps = 20; warp-pool = 10; }`
|
||||
|
||||
<a id="services-proxy-suite-proxy-routing-block-domains"></a>
|
||||
## services\.proxy-suite\.proxy\.routing\.block\.domains
|
||||
|
||||
@@ -819,18 +924,20 @@ Rule sets from ` proxy.routing.ruleSets ` that this rule matches (sing-box and h
|
||||
<a id="services-proxy-suite-proxy-selection"></a>
|
||||
## services\.proxy-suite\.proxy\.selection
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** one of “first”, “selector”, “urltest”\
|
||||
**Type:** one of “first”, “selector”, “urltest”, “failover”\
|
||||
**Default:** `"first"`\
|
||||
**Example:** `"urltest"`
|
||||
**Example:** `"failover"`
|
||||
|
||||
<a id="services-proxy-suite-proxy-selectionexclude"></a>
|
||||
## services\.proxy-suite\.proxy\.selectionExclude
|
||||
|
||||
@@ -12,9 +12,17 @@ Part of the [proxy-suite options reference](./index.md).
|
||||
- [asOutbound](#services-proxy-suite-warp-asoutbound)
|
||||
- [autostart](#services-proxy-suite-warp-autostart)
|
||||
- [configFile](#services-proxy-suite-warp-configfile)
|
||||
- [devices](#services-proxy-suite-warp-devices)
|
||||
- `<name>`
|
||||
- [configFile](#services-proxy-suite-warp-devices-name-configfile)
|
||||
- [endpoint](#services-proxy-suite-warp-devices-name-endpoint)
|
||||
- [domainStrategy](#services-proxy-suite-warp-domainstrategy)
|
||||
- [endpoint](#services-proxy-suite-warp-endpoint)
|
||||
- [generatorUrl](#services-proxy-suite-warp-generatorurl)
|
||||
- group
|
||||
- [failback](#services-proxy-suite-warp-group-failback)
|
||||
- [strategy](#services-proxy-suite-warp-group-strategy)
|
||||
- [instances](#services-proxy-suite-warp-instances)
|
||||
|
||||
<a id="services-proxy-suite-warp-enable"></a>
|
||||
## services\.proxy-suite\.warp\.enable
|
||||
@@ -68,6 +76,38 @@ through the local proxy if enabled\. WARP does not work until that succeeds\.
|
||||
**Default:** `null`\
|
||||
**Example:** `"/run/secrets/wgcf-profile.conf"`
|
||||
|
||||
<a id="services-proxy-suite-warp-devices"></a>
|
||||
## services\.proxy-suite\.warp\.devices
|
||||
|
||||
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\.
|
||||
|
||||
**Type:** attribute set of (submodule)\
|
||||
**Default:** `{ }`\
|
||||
**Example:** `{ warp-a = { }; warp-b.endpoint = "162.159.193.10:500"; } `
|
||||
|
||||
<a id="services-proxy-suite-warp-devices-name-configfile"></a>
|
||||
## services\.proxy-suite\.warp\.devices\.\<name>\.configFile
|
||||
|
||||
This device’s WireGuard profile, as ` warp.configFile `\. ` null `: registered with wgcf\.
|
||||
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"/run/secrets/warp-b.conf"`
|
||||
|
||||
<a id="services-proxy-suite-warp-devices-name-endpoint"></a>
|
||||
## services\.proxy-suite\.warp\.devices\.\<name>\.endpoint
|
||||
|
||||
This device’s endpoint, as ` warp.endpoint ` (which it defaults to)\.
|
||||
|
||||
**Type:** null or string matching the pattern (\\\[\[0-9A-Fa-f:\.]+]|\[^]:\[]+):\[0-9]+\
|
||||
**Default:** `null`\
|
||||
**Example:** `"162.159.192.1:500"`
|
||||
|
||||
<a id="services-proxy-suite-warp-domainstrategy"></a>
|
||||
## services\.proxy-suite\.warp\.domainStrategy
|
||||
|
||||
@@ -101,3 +141,29 @@ Its operator sees your private key\.
|
||||
**Type:** null or string\
|
||||
**Default:** `null`\
|
||||
**Example:** `"https://valokda-amnezia.vercel.app/api/warp?mode=awg2"`
|
||||
|
||||
<a id="services-proxy-suite-warp-group-failback"></a>
|
||||
## services\.proxy-suite\.warp\.group\.failback
|
||||
|
||||
With “failover”: go back to an earlier device once it works again\.
|
||||
|
||||
**Type:** boolean\
|
||||
**Default:** `true`
|
||||
|
||||
<a id="services-proxy-suite-warp-group-strategy"></a>
|
||||
## services\.proxy-suite\.warp\.group\.strategy
|
||||
|
||||
How the “warp” group of several devices picks one; see ` proxy.groups `\.
|
||||
|
||||
**Type:** one of “failover”, “urltest”, “selector”\
|
||||
**Default:** `"failover"`
|
||||
|
||||
<a id="services-proxy-suite-warp-instances"></a>
|
||||
## services\.proxy-suite\.warp\.instances
|
||||
|
||||
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 `\.
|
||||
|
||||
**Type:** null or (positive integer, meaning >0)\
|
||||
**Default:** `null`\
|
||||
**Example:** `2`
|
||||
@@ -0,0 +1,14 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
proxy = {
|
||||
enable = true;
|
||||
outbounds = [
|
||||
{ tag = "de-vps"; urlFile = "/run/secrets/de-vps-url"; }
|
||||
{ tag = "nl-vps"; urlFile = "/run/secrets/nl-vps-url"; }
|
||||
];
|
||||
groups.eu.outbounds = [ "de-vps" "nl-vps" ]; # de-vps first, nl-vps when it fails
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite.proxy = {
|
||||
enable = true;
|
||||
subscriptions = [ { tag = "provider"; urlFile = "/run/secrets/provider-sub"; } ];
|
||||
groups.fast = {
|
||||
subscriptions = [ "provider" ]; # every entry the subscription holds
|
||||
match = [ "de-*" ]; # and every outbound whose tag matches
|
||||
strategy = "urltest";
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite.proxy = {
|
||||
enable = true;
|
||||
selection = "failover";
|
||||
priority = { eu = 10; warp = 20; };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
proxy.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
instances = 2; # warp-1 (keeps an existing registration) and warp-2
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{ config, lib, pkgs, ... }:
|
||||
{
|
||||
services.proxy-suite.warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
devices = {
|
||||
warp-a = { };
|
||||
warp-b.endpoint = "162.159.193.10:500";
|
||||
};
|
||||
group.strategy = "failover";
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
# Group outbounds and fail over
|
||||
|
||||
A group is one tag standing for several outbounds. Whatever names the group (a routing rule,
|
||||
a chain, a pin, the top-level pick) uses whichever member the group picks. The usual reason
|
||||
is failover: when one exit stops carrying traffic, move to the next within seconds instead of
|
||||
waiting for someone to notice.
|
||||
|
||||
## A failover group
|
||||
|
||||
```nix
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
proxy = {
|
||||
enable = true;
|
||||
outbounds = [
|
||||
{ tag = "de-vps"; urlFile = "/run/secrets/de-vps-url"; }
|
||||
{ tag = "nl-vps"; urlFile = "/run/secrets/nl-vps-url"; }
|
||||
];
|
||||
groups.eu.outbounds = [ "de-vps" "nl-vps" ]; # de-vps first, nl-vps when it fails
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
The members leave the top level: the top level now picks between `eu` and whatever is in no
|
||||
group. Members can be any outbound, including subscription entries, WARP, Tor and AmneziaWG,
|
||||
and other groups.
|
||||
|
||||
Each group has a `strategy`:
|
||||
|
||||
| Strategy | Picks |
|
||||
|---|---|
|
||||
| `failover` (default) | The first member that works, in order. With `failback` (on by default) it goes back to an earlier member once that has worked three checks in a row. |
|
||||
| `urltest` | The fastest member, switching only when another is faster by `proxy.urlTest.tolerance`. |
|
||||
| `selector` | The first member, or the one you pick. |
|
||||
|
||||
Failover is driven by `proxy-suite-outbound-groups`, which tests the members every `interval`
|
||||
(30 s by default) and switches through sing-box's Clash API. A member is down after two
|
||||
failed tests in a row. Watchdogs that already watch a tunnel (the AmneziaWG watchdog, the
|
||||
sing-box WARP tunnel) tell it at the first sign of trouble, so their outbounds are dropped
|
||||
within seconds. Connections still open on the dropped member are cut, so clients reconnect
|
||||
through the next one.
|
||||
|
||||
Groups need the sing-box or hybrid backend. The TUN instances of sing-box have no Clash API,
|
||||
so there a failover group works as `urltest`.
|
||||
|
||||
## Members from subscriptions and patterns
|
||||
|
||||
```nix
|
||||
services.proxy-suite.proxy = {
|
||||
enable = true;
|
||||
subscriptions = [ { tag = "provider"; urlFile = "/run/secrets/provider-sub"; } ];
|
||||
groups.fast = {
|
||||
subscriptions = [ "provider" ]; # every entry the subscription holds
|
||||
match = [ "de-*" ]; # and every outbound whose tag matches
|
||||
strategy = "urltest";
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Listed `outbounds` come first, in their order; members pulled in by `subscriptions` or `match`
|
||||
follow, ordered by `proxy.priority`.
|
||||
|
||||
## Failover at the top level, and priority
|
||||
|
||||
`proxy.selection = "failover"` treats the top level like a failover group. Its order comes
|
||||
from `proxy.priority`, lower first; anything not listed follows in its usual order:
|
||||
|
||||
```nix
|
||||
services.proxy-suite.proxy = {
|
||||
enable = true;
|
||||
selection = "failover";
|
||||
priority = { eu = 10; warp = 20; };
|
||||
};
|
||||
```
|
||||
|
||||
## Several WARP devices
|
||||
|
||||
One WARP device is one key and one session. With several, `warp` becomes a failover group of
|
||||
them, so rules and pins that name `warp` keep working and fail over:
|
||||
|
||||
```nix
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
proxy.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
instances = 2; # warp-1 (keeps an existing registration) and warp-2
|
||||
};
|
||||
};
|
||||
```
|
||||
|
||||
Name them yourself, each with its own endpoint, through `warp.devices`:
|
||||
|
||||
```nix
|
||||
services.proxy-suite.warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
devices = {
|
||||
warp-a = { };
|
||||
warp-b.endpoint = "162.159.193.10:500";
|
||||
};
|
||||
group.strategy = "failover";
|
||||
};
|
||||
```
|
||||
|
||||
Devices whose outages come at the same time (the path to Cloudflare, say) do not help each
|
||||
other; a different endpoint for each, or a member that is not WARP, does.
|
||||
|
||||
## At runtime
|
||||
|
||||
```sh
|
||||
proxy-ctl proxy outbounds # the tree: groups, members, what each uses
|
||||
proxy-ctl proxy groups add eu de-vps nl-vps # a failover group
|
||||
proxy-ctl proxy groups add fast --sub provider --strategy urltest
|
||||
proxy-ctl proxy groups members eu add pl-vps
|
||||
proxy-ctl proxy pin nl-vps --in eu # hold eu on nl-vps
|
||||
proxy-ctl proxy unpin --in eu
|
||||
proxy-ctl proxy priority eu 5 # or: eu up, eu down, eu --clear
|
||||
proxy-ctl warp restart warp-2
|
||||
```
|
||||
|
||||
Groups added at runtime can be changed and removed there; declared ones change in Nix. In
|
||||
the TUI and the GUI, the Outbounds tab shows the same tree: `space` folds a group, `p` on a
|
||||
member pins it inside its group, `g` adds a group, and `+` and `-` move a top-level entry.
|
||||
|
||||
## See also
|
||||
|
||||
- [`proxy.groups`](../options/proxy.md#services-proxy-suite-proxy-groups)
|
||||
- [`proxy.priority`](../options/proxy.md#services-proxy-suite-proxy-priority)
|
||||
- [`warp.devices`](../options/warp.md#services-proxy-suite-warp-devices)
|
||||
- [Chain proxies and add exits](./chains.md)
|
||||
@@ -17,6 +17,7 @@ examples follow below.
|
||||
| [Control it day to day](./control.md) | Switching things without editing Nix or typing sudo |
|
||||
| [Use an AmneziaWG config](./amneziawg.md) | You have an AmneziaWG `.conf` or an Amnezia `vpn://` export |
|
||||
| [Chain proxies and add exits](./chains.md) | WARP, Tor, SSH, or reaching a server through another one |
|
||||
| [Group outbounds and fail over](./groups.md) | Several exits for one job, moving off one that stops working |
|
||||
| [Other Linux and Android](./other-hosts.md) | You are not on NixOS |
|
||||
| [Get past mobile whitelists](./whitelist-bypass.md) | Mobile internet lets only whitelisted services through |
|
||||
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -89,7 +89,7 @@ in
|
||||
]);
|
||||
in
|
||||
assert pkgs.lib.hasInfix ''--argjson ex '["primary"]' '' script;
|
||||
assert pkgs.lib.hasInfix "excluded: ($tags - $selectable)" script;
|
||||
assert pkgs.lib.hasInfix "excluded: ($top - $selectable)" script;
|
||||
true
|
||||
)
|
||||
|
||||
|
||||
@@ -197,6 +197,16 @@ let
|
||||
;
|
||||
};
|
||||
|
||||
outboundGroupsChecks = import ./outbound-groups.nix {
|
||||
inherit
|
||||
pkgs
|
||||
checkLib
|
||||
evalProxySuite
|
||||
baseModule
|
||||
rejects
|
||||
;
|
||||
};
|
||||
|
||||
amneziaWgChecks = import ./amnezia-wg.nix {
|
||||
inherit checkLib;
|
||||
inherit
|
||||
@@ -317,6 +327,7 @@ let
|
||||
++ xrayBackendChecks.assertions
|
||||
++ outboundValidationChecks.assertions
|
||||
++ chainingDnsChecks.assertions
|
||||
++ outboundGroupsChecks.assertions
|
||||
++ amneziaWgChecks.assertions
|
||||
++ amneziaWgOutboundChecks.assertions
|
||||
++ zapretChecks.assertions
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
# proxy.groups and "failover" selection, as the module evaluates them. The start-time
|
||||
# resolution itself is the outbound-disabled check (repo.nix); the watcher is proxy-ctl's.
|
||||
{
|
||||
pkgs,
|
||||
checkLib,
|
||||
evalProxySuite,
|
||||
baseModule,
|
||||
rejects,
|
||||
}:
|
||||
|
||||
let
|
||||
inherit (checkLib) startScript;
|
||||
|
||||
grouped = evalProxySuite [
|
||||
baseModule
|
||||
{
|
||||
services.proxy-suite.proxy = {
|
||||
selection = "failover";
|
||||
outbounds = [
|
||||
{
|
||||
tag = "second";
|
||||
url = "http://second.example.com:8080";
|
||||
}
|
||||
];
|
||||
groups.pool.outbounds = [
|
||||
"primary"
|
||||
"second"
|
||||
];
|
||||
priority.pool = 1;
|
||||
# A rule may name a group like any outbound.
|
||||
routing.rules = [
|
||||
{
|
||||
outbound = "pool";
|
||||
domains = [ "example.org" ];
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
script = startScript grouped;
|
||||
in
|
||||
{
|
||||
assertions = [
|
||||
# The watcher runs beside the socks backend, and the start script resolves the groups.
|
||||
(
|
||||
let
|
||||
unit = grouped.config.systemd.services.proxy-suite-outbound-groups;
|
||||
in
|
||||
assert builtins.elem "proxy-suite-socks.service" unit.bindsTo;
|
||||
assert pkgs.lib.hasInfix "proxy groups watch" unit.serviceConfig.ExecStart;
|
||||
assert pkgs.lib.hasInfix ''"outbounds":["primary","second"]'' script;
|
||||
assert pkgs.lib.hasInfix "interrupt_exist_connections:true" script;
|
||||
true
|
||||
)
|
||||
|
||||
# Pure XRay has neither groups nor failover selection, nor the watcher.
|
||||
(rejects "proxy.groups requires proxy.backend" [
|
||||
{
|
||||
services.proxy-suite.proxy = {
|
||||
backend = pkgs.lib.mkForce "xray";
|
||||
groups.pool.outbounds = [ "primary" ];
|
||||
};
|
||||
}
|
||||
])
|
||||
(rejects "proxy.selection = \"failover\" requires" [
|
||||
{
|
||||
services.proxy-suite.proxy = {
|
||||
backend = pkgs.lib.mkForce "xray";
|
||||
selection = "failover";
|
||||
};
|
||||
}
|
||||
])
|
||||
(
|
||||
let
|
||||
xray = evalProxySuite [
|
||||
baseModule
|
||||
{ services.proxy-suite.proxy.backend = pkgs.lib.mkForce "xray"; }
|
||||
];
|
||||
in
|
||||
assert !(xray.config.systemd.services ? proxy-suite-outbound-groups);
|
||||
true
|
||||
)
|
||||
|
||||
# A group takes a name of its own, and has members.
|
||||
(rejects "proxy.groups names must differ" [
|
||||
{ services.proxy-suite.proxy.groups.primary.outbounds = [ "primary" ]; }
|
||||
])
|
||||
(rejects "proxy.groups names must differ" [
|
||||
{ services.proxy-suite.proxy.groups.direct.outbounds = [ "primary" ]; }
|
||||
])
|
||||
(rejects "proxy.groups need members" [
|
||||
{ services.proxy-suite.proxy.groups.empty = { }; }
|
||||
])
|
||||
(rejects "proxy.groups names may hold only" [
|
||||
{ services.proxy-suite.proxy.groups."a/b".outbounds = [ "primary" ]; }
|
||||
])
|
||||
];
|
||||
}
|
||||
+90
-36
@@ -846,46 +846,100 @@ in
|
||||
# `proxy-ctl proxy outbounds disable` markers, as the start script reads them.
|
||||
outbound-disabled =
|
||||
let
|
||||
inherit
|
||||
(import ../../modules/proxy-suite/service/script-blocks/outbounds.nix {
|
||||
lib = pkgs.lib;
|
||||
inherit pkgs;
|
||||
jq = "${pkgs.jq}/bin/jq";
|
||||
proxyCfg.selectionExclude = [ "ex" ];
|
||||
selectionMode = "urltest";
|
||||
hybridEnabled = false;
|
||||
# Relative: the build directory.
|
||||
pinnedOutboundFile = "pinned";
|
||||
runtimeOutboundsDir = "obd";
|
||||
singBoxCfg = null;
|
||||
sshProxyCfg = null;
|
||||
warpCfg = null;
|
||||
torCfg = null;
|
||||
whitelistBypassJoiners = [ ];
|
||||
awgOutbounds = null;
|
||||
constants = null;
|
||||
pureXrayEnabled = null;
|
||||
collapseNamedOutbounds = null;
|
||||
backend = null;
|
||||
backendArg = null;
|
||||
xraySidecarRoutingMark = null;
|
||||
python3 = null;
|
||||
parserScriptsPythonPath = null;
|
||||
buildOutboundPy = null;
|
||||
mkSubscriptionBlock = null;
|
||||
mkSubscriptionLoadHelperBlock = null;
|
||||
runtimeSubscriptionsBlock = null;
|
||||
})
|
||||
selectionBlocks
|
||||
;
|
||||
selection = pkgs.writeShellScript "outbound-selection" ''
|
||||
set -euo pipefail
|
||||
${selectionBlocks}
|
||||
'';
|
||||
mkSelection =
|
||||
groups:
|
||||
let
|
||||
inherit
|
||||
(import ../../modules/proxy-suite/service/script-blocks/outbounds.nix {
|
||||
lib = pkgs.lib;
|
||||
inherit pkgs;
|
||||
jq = "${pkgs.jq}/bin/jq";
|
||||
proxyCfg = {
|
||||
selectionExclude = [ "ex" ];
|
||||
inherit groups;
|
||||
priority = { };
|
||||
urlTest = {
|
||||
url = "https://t";
|
||||
interval = "3m";
|
||||
};
|
||||
};
|
||||
selectionMode = "urltest";
|
||||
hybridEnabled = false;
|
||||
# Relative: the build directory.
|
||||
pinnedOutboundFile = "pinned";
|
||||
runtimeOutboundsDir = "obd";
|
||||
singBoxCfg.urlTest.tolerance = 50;
|
||||
sshProxyCfg = null;
|
||||
warpCfg = null;
|
||||
torCfg = null;
|
||||
whitelistBypassJoiners = [ ];
|
||||
awgOutbounds = null;
|
||||
constants = null;
|
||||
pureXrayEnabled = false;
|
||||
collapseNamedOutbounds = null;
|
||||
backend = null;
|
||||
backendArg = null;
|
||||
xraySidecarRoutingMark = null;
|
||||
python3 = null;
|
||||
parserScriptsPythonPath = null;
|
||||
buildOutboundPy = null;
|
||||
mkSubscriptionBlock = null;
|
||||
mkSubscriptionLoadHelperBlock = null;
|
||||
runtimeSubscriptionsBlock = null;
|
||||
})
|
||||
selectionBlocks
|
||||
;
|
||||
in
|
||||
pkgs.writeShellScript "outbound-selection" ''
|
||||
set -euo pipefail
|
||||
${selectionBlocks}
|
||||
'';
|
||||
selection = mkSelection { };
|
||||
# Resolved at start as the runtime ones are; `g` holds b and a, in that order.
|
||||
grouped = mkSelection {
|
||||
g = {
|
||||
outbounds = [
|
||||
"b"
|
||||
"a"
|
||||
];
|
||||
subscriptions = [ ];
|
||||
match = [ ];
|
||||
strategy = "failover";
|
||||
failback = true;
|
||||
interval = null;
|
||||
};
|
||||
};
|
||||
in
|
||||
pkgs.runCommand "proxy-suite-outbound-disabled-check" { nativeBuildInputs = [ pkgs.jq ]; } ''
|
||||
mkdir obd
|
||||
export RUNTIME_DIR="$PWD" OUTBOUND_SOURCES_JSON='{}'
|
||||
# No group here: `g` names members that are not running, so it blocks, with a warning.
|
||||
export OUTBOUNDS_JSON='[{"tag":"x"}]'
|
||||
${grouped} 2> err
|
||||
grep -q "group 'g': member 'b' is not available" err
|
||||
grep -q "group 'g' has no available member" err
|
||||
jq -e '.top == ["x", "g"] and .groups.g.members == ["block"]' outbounds.json > /dev/null
|
||||
|
||||
# With its members: they leave the top level, the group takes their place and order.
|
||||
export OUTBOUNDS_JSON='[{"tag":"x"},{"tag":"a"},{"tag":"b"}]'
|
||||
${grouped}
|
||||
jq -e '.top == ["x", "g"] and .groups.g.members == ["b", "a"] and .groups.g.strategy == "failover"' outbounds.json > /dev/null
|
||||
# A group pin, a runtime group, and a runtime priority putting it first.
|
||||
mkdir group-pins
|
||||
echo a > group-pins/g
|
||||
echo '{"outbounds": ["x"], "strategy": "urltest"}' > obd/h.group
|
||||
echo '{"h": 1}' > obd/priority.json
|
||||
_proxy_suite_read_source() { cat -- "$1"; }
|
||||
export -f _proxy_suite_read_source
|
||||
${grouped}
|
||||
jq -e '.top == ["h", "g"] and .groups.g.pinned == "a" and .groups.h.runtime and .priority.h == 1' outbounds.json > /dev/null
|
||||
# A group inside itself stops the start.
|
||||
echo '{"outbounds": ["h3"]}' > obd/h2.group
|
||||
echo '{"outbounds": ["h2"]}' > obd/h3.group
|
||||
! ${grouped} 2> err
|
||||
grep -q "group 'h2' contains itself" err
|
||||
rm -r obd/h.group obd/h2.group obd/h3.group obd/priority.json group-pins
|
||||
|
||||
export OUTBOUNDS_JSON='[{"tag":"a"},{"tag":"b"},{"tag":"ex"}]'
|
||||
|
||||
# A marker takes its outbound out of selection and drops a pin on it; stale markers do nothing.
|
||||
|
||||
@@ -105,6 +105,27 @@ let
|
||||
};
|
||||
};
|
||||
|
||||
# Several devices: one registration and one profile each, and "warp" is their group.
|
||||
instances = mkProxySuite {
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
proxy.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
instances = 2;
|
||||
};
|
||||
};
|
||||
instancesCfg = instances.config.services.proxy-suite;
|
||||
devices = mkFixture "sing-box" {
|
||||
asOutbound = "singBox";
|
||||
devices = {
|
||||
a = { };
|
||||
b.endpoint = "162.159.193.10:500";
|
||||
};
|
||||
};
|
||||
devicesStart = startOf devices;
|
||||
|
||||
invalidAssertions = mkFailingAssertions mkBadProxySuiteFixture [
|
||||
# An IPv6 endpoint without brackets.
|
||||
{
|
||||
@@ -117,6 +138,42 @@ let
|
||||
};
|
||||
proxy.enable = true;
|
||||
}
|
||||
# instances is devices' shorthand, not an addition.
|
||||
{
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
proxy.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
instances = 2;
|
||||
devices.extra = { };
|
||||
};
|
||||
}
|
||||
# With two devices, "warp" is their group's name.
|
||||
{
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
proxy.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asOutbound = "interface";
|
||||
devices = {
|
||||
warp = { };
|
||||
other = { };
|
||||
};
|
||||
};
|
||||
}
|
||||
# One global profile, one key.
|
||||
{
|
||||
enable = true;
|
||||
amneziaWg.enable = true;
|
||||
warp = {
|
||||
enable = true;
|
||||
asAmneziaWg = true;
|
||||
instances = 2;
|
||||
};
|
||||
}
|
||||
# Enabled but used for nothing.
|
||||
{
|
||||
enable = true;
|
||||
@@ -313,6 +370,45 @@ in
|
||||
&& amneziaWg.config.services.proxy-suite.amneziaWg.profiles.warp.endpoint == null;
|
||||
true
|
||||
)
|
||||
(
|
||||
assert
|
||||
builtins.attrNames (
|
||||
pkgs.lib.filterAttrs (n: _: pkgs.lib.hasPrefix "warp" n) instancesCfg.amneziaWg.profiles
|
||||
) == [
|
||||
"warp-1"
|
||||
"warp-2"
|
||||
];
|
||||
# warp-1 keeps the state dir a single device had; warp-2 gets one of its own.
|
||||
assert pkgs.lib.hasSuffix "/warp/wgcf-profile.conf"
|
||||
instancesCfg.amneziaWg.profiles.warp-1.configFile;
|
||||
assert pkgs.lib.hasSuffix "/warp/warp-2/wgcf-profile.conf"
|
||||
instancesCfg.amneziaWg.profiles.warp-2.configFile;
|
||||
assert instances.config.systemd.services ? proxy-suite-warp;
|
||||
assert
|
||||
instances.config.systemd.services.proxy-suite-warp-register-warp-2.serviceConfig.StateDirectory
|
||||
== "proxy-suite/warp/warp-2";
|
||||
assert builtins.elem "proxy-suite-warp-register-warp-2.service"
|
||||
instances.config.systemd.services.proxy-suite-awg-warp-2.wants;
|
||||
assert
|
||||
instancesCfg.proxy.groups.warp.outbounds == [
|
||||
"warp-1"
|
||||
"warp-2"
|
||||
];
|
||||
assert instancesCfg.proxy.groups.warp.strategy == "failover";
|
||||
true
|
||||
)
|
||||
# sing-box tunnels: the first on the usual ports, the next on its own, with its endpoint.
|
||||
(
|
||||
assert hasInfix ''"server":"127.0.0.1","server_port":18538,"tag":"a","type":"socks"'' devicesStart;
|
||||
assert hasInfix ''"server":"127.0.0.1","server_port":18900,"tag":"b","type":"socks"'' devicesStart;
|
||||
assert hasInfix "--endpoint 162.159.193.10:500" (
|
||||
generated.readDerivation devices.config.systemd.services.proxy-suite-warp-tunnel-b.serviceConfig.ExecStart
|
||||
);
|
||||
# a has the configFile, so only b registers.
|
||||
assert !(devices.config.systemd.services ? proxy-suite-warp);
|
||||
assert devices.config.systemd.services ? proxy-suite-warp-register-b;
|
||||
true
|
||||
)
|
||||
]
|
||||
++ invalidAssertions;
|
||||
}
|
||||
+697
-44
@@ -77,8 +77,19 @@ Changes and secrets need root or the userControl group.
|
||||
test ping, delay, download speed (default: ping, delay)
|
||||
proxy outbounds link <tag> [--qr|--json|--config]
|
||||
its link, QR code, JSON, or client config
|
||||
proxy pin [tag] always use this outbound (no tag: pick from a menu)
|
||||
proxy unpin go back to automatic selection
|
||||
proxy pin [tag] [--in <group>] always use this outbound (no tag: pick from a menu);
|
||||
--in: hold a group on one of its members
|
||||
proxy unpin [--in <group>] go back to automatic selection
|
||||
proxy groups [list] outbound groups, their members, and what each uses
|
||||
proxy groups add <tag> [member...] [--sub <sub>]... [--match <pattern>]...
|
||||
[--strategy failover|urltest|selector] [--no-failback] [--interval <d>]
|
||||
add a group (failover by default)
|
||||
proxy groups rm <tag> remove a group added with groups add
|
||||
proxy groups members <tag> add|rm <member...>
|
||||
proxy groups strategy <tag> failover|urltest|selector
|
||||
proxy priority [list] the top level in the order it is picked in
|
||||
proxy priority <tag> <n>|up|down|--clear
|
||||
lower goes first; up/down renumbers the top level
|
||||
proxy mode [default|whitelist|blacklist|all-proxy|all-bypass]
|
||||
show or override the routing mode
|
||||
proxy subs [list|update] subscriptions; update refetches them
|
||||
@@ -117,7 +128,7 @@ Changes and secrets need root or the userControl group.
|
||||
stays on until turned off here or with the tunnel
|
||||
|
||||
ssh [status|on|off] SSH tunnel
|
||||
warp [status|on|off] WARP tunnel
|
||||
warp [status|on|off] [device] WARP tunnel (every device, or the one named)
|
||||
tor [status|on|off] Tor
|
||||
tor newnym new circuits for new connections
|
||||
tg [status|on|off] Telegram proxy
|
||||
@@ -394,15 +405,46 @@ def _toggle(unit, name, verb="status", *_):
|
||||
usage(f"{name} [status|on|off|toggle|restart]")
|
||||
|
||||
|
||||
def _warp_unit():
|
||||
"""The unit behind the warp outbound: its sing-box tunnel, or an outbound AmneziaWG profile.
|
||||
def _warp_devices():
|
||||
"""[(tag, unit)] of the WARP devices behind outbounds: their sing-box tunnels or AmneziaWG profiles.
|
||||
|
||||
A global "warp" profile belongs to `awg on warp`, not here.
|
||||
"""
|
||||
try:
|
||||
devices = json.loads(env("WARP_DEVICES", "[]"))
|
||||
except ValueError:
|
||||
devices = []
|
||||
listed = [(_s(d["tag"]), _s(d["unit"])) for d in devices if isinstance(d, dict) and d.get("tag") and d.get("unit")]
|
||||
if listed:
|
||||
return listed
|
||||
# A wrapper from before WARP_DEVICES: the one device there was.
|
||||
awg = _awg_service("warp")
|
||||
if "warp" not in _awg_profiles() and svc_exists(awg):
|
||||
return awg
|
||||
return "proxy-suite-warp-tunnel"
|
||||
return [("warp", awg)]
|
||||
return [("warp", "proxy-suite-warp-tunnel")]
|
||||
|
||||
|
||||
def cmd_warp(*args):
|
||||
"""warp [status|on|off|toggle|restart] [device]: every device, or the one named."""
|
||||
devices = _warp_devices()
|
||||
tags = [t for t, _ in devices]
|
||||
args = list(args)
|
||||
if args and args[-1] in tags and args[-1] not in ("status", "on", "off", "toggle", "restart"):
|
||||
tag = args.pop()
|
||||
devices = [(t, u) for t, u in devices if t == tag]
|
||||
if len(args) > 1:
|
||||
usage(f"warp [status|on|off|toggle|restart] [{'|'.join(tags)}]")
|
||||
if len(devices) == 1:
|
||||
_toggle(devices[0][1], "warp", *args)
|
||||
return
|
||||
verb = args[0] if args else "status"
|
||||
for tag, unit in devices:
|
||||
if verb == "status":
|
||||
state = systemctl("is-active", unit, capture=True, quiet=True)[1].strip() or "inactive"
|
||||
print(f"{tag:<16} {state}")
|
||||
else:
|
||||
print(f"{tag}:", flush=True)
|
||||
_toggle(unit, tag, verb)
|
||||
|
||||
|
||||
def _tor_control(*commands):
|
||||
@@ -546,6 +588,10 @@ def _outbound_choices():
|
||||
return {tag: _s(sources.get(tag) or "") for tag in _outbound_tags()}
|
||||
|
||||
|
||||
def _group_choices():
|
||||
return {g: f"group: {_s(i.get('strategy') or 'failover')}" for g, i in _outbound_groups().items()}
|
||||
|
||||
|
||||
def _inbound_link_choices():
|
||||
links = read_json(env("INBOUNDS_LINKS_FILE"))
|
||||
return dict(sorted((_s(x["tag"]), f"{_s(x.get('type', ''))} {_s(x.get('port', ''))}".strip()) for x in links))
|
||||
@@ -590,6 +636,8 @@ COMPLETE = {
|
||||
"outbounds": "outbounds, where each came from, and the pick",
|
||||
"pin": "always use this outbound",
|
||||
"unpin": "let the configured selection pick again",
|
||||
"groups": "outbound groups",
|
||||
"priority": "the order the top level picks in",
|
||||
"mode": "show or override the routing mode",
|
||||
"subs": "subscription caches",
|
||||
"rulesets": "routing rule sets",
|
||||
@@ -631,7 +679,35 @@ COMPLETE = {
|
||||
"--download": "timed download through each outbound",
|
||||
},
|
||||
},
|
||||
"proxy pin": {"args": lambda: {t: d for t, d in _outbound_choices().items() if t not in _outbound_disabled()}},
|
||||
"proxy pin": {
|
||||
"args": lambda: {t: d for t, d in {**_outbound_choices(), **_group_choices()}.items() if t not in _outbound_disabled()},
|
||||
"flags": {"--in": "hold a group on one of its members"},
|
||||
},
|
||||
"proxy unpin": {"flags": {"--in": "let a group pick again"}},
|
||||
"proxy groups": {
|
||||
"words": {
|
||||
"list": "groups, their members, and what each uses",
|
||||
"add": "add a group: <tag> [member...]",
|
||||
"rm": "remove a group added with groups add",
|
||||
"members": "add or remove a group's members",
|
||||
"strategy": "how a group picks: failover, urltest or selector",
|
||||
}
|
||||
},
|
||||
"proxy groups add": {
|
||||
"args": lambda: {**_outbound_choices(), **_group_choices()},
|
||||
"repeat": True,
|
||||
"flags": {
|
||||
"--sub": "every entry of a subscription",
|
||||
"--match": "every outbound whose tag matches a pattern",
|
||||
"--strategy": "failover, urltest or selector",
|
||||
"--no-failback": "stay on a member until it fails",
|
||||
"--interval": "how often members are tested",
|
||||
},
|
||||
},
|
||||
"proxy groups rm": {"args": lambda: {g: "" for g, i in _outbound_groups().items() if i.get("runtime")}},
|
||||
"proxy groups members": {"args": lambda: {g: "" for g, i in _outbound_groups().items() if i.get("runtime")}},
|
||||
"proxy groups strategy": {"args": lambda: {g: "" for g, i in _outbound_groups().items() if i.get("runtime")}},
|
||||
"proxy priority": {"args": lambda: {"list": "the top level in order", **{_s(t): "" for t in _outbound_inventory().get("top") or []}}},
|
||||
"proxy mode": {"args": lambda: {"default": f"config default ({_route_mode_default()})", **ROUTE_MODE_LABELS}},
|
||||
"proxy subs": {
|
||||
"words": {
|
||||
@@ -703,7 +779,7 @@ COMPLETE = {
|
||||
"awg toggle": {"args": lambda: _names(_awg_profiles())},
|
||||
"awg restart": {"args": lambda: _names(_awg_profiles())},
|
||||
"ssh": {"words": TOGGLE},
|
||||
"warp": {"words": TOGGLE},
|
||||
"warp": {"words": TOGGLE, "args": lambda: {t: u for t, u in _warp_devices()} if len(_warp_devices()) > 1 else {}},
|
||||
"killswitch": {"words": TOGGLE},
|
||||
"tor": {"words": {**TOGGLE, "newnym": "new circuits for new connections"}},
|
||||
"tg": {"words": TOGGLE},
|
||||
@@ -785,6 +861,12 @@ def _complete_tree(*words):
|
||||
return _outbound_choices()
|
||||
if rest[-1:] == ["--by"]:
|
||||
return _names(STATS_KINDS)
|
||||
if rest[-1:] == ["--in"]:
|
||||
return _group_choices()
|
||||
if rest[-1:] == ["--strategy"]:
|
||||
return _names(GROUP_STRATEGIES)
|
||||
if rest[-1:] == ["--sub"]:
|
||||
return _names(_sub_tags())
|
||||
candidates = {}
|
||||
if node.get("repeat") or not [w for w in rest if not w.startswith("-")]:
|
||||
candidates.update(node.get("words", {}))
|
||||
@@ -859,8 +941,12 @@ BUSY_STATES = ("activating", "deactivating", "reloading")
|
||||
|
||||
def _snapshot_units():
|
||||
profiles = _awg_profiles()
|
||||
# WARP as an AmneziaWG outbound has no profile to toggle, but it is a unit that can fail (_warp_unit).
|
||||
warp = [] if "warp" in profiles else [_awg_service("warp")]
|
||||
# WARP devices have no profile to toggle, but their units can fail (_warp_devices). A wrapper
|
||||
# from before WARP_DEVICES: the AmneziaWG unit of the one device there was, if it runs.
|
||||
if env("WARP_DEVICES"):
|
||||
warp = [u for _, u in _warp_devices() if u not in ALL_SERVICES and u not in map(_awg_service, profiles)]
|
||||
else:
|
||||
warp = [] if "warp" in profiles else [_awg_service("warp")]
|
||||
return [*ALL_SERVICES, SUBSCRIPTION_UPDATE, *map(_awg_service, profiles), *warp, *map(_wl_unit, _wl())]
|
||||
|
||||
|
||||
@@ -1080,7 +1166,11 @@ def cmd_proxy(verb="status", *args):
|
||||
elif verb == "pin":
|
||||
cmd_pin(*args)
|
||||
elif verb == "unpin":
|
||||
cmd_unpin()
|
||||
cmd_unpin(*args)
|
||||
elif verb == "groups":
|
||||
cmd_groups(*args)
|
||||
elif verb == "priority":
|
||||
cmd_priority(*args)
|
||||
elif verb == "mode":
|
||||
cmd_route_mode(*args)
|
||||
elif verb == "subs":
|
||||
@@ -1098,7 +1188,7 @@ def cmd_proxy(verb="status", *args):
|
||||
elif verb in ("probe", "learn", "forget", "relearn", "queue", "learned"):
|
||||
cmd_proxy_auto(verb, *args)
|
||||
else:
|
||||
usage("proxy [status|on|off|toggle|restart|outbounds|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
|
||||
usage("proxy [status|on|off|toggle|restart|outbounds|groups|priority|pin|unpin|mode|subs|rulesets|tun|tproxy|auto|config]")
|
||||
|
||||
|
||||
def cmd_outbounds(verb="list", *args):
|
||||
@@ -1363,6 +1453,25 @@ def cmd_outbounds_test(*args):
|
||||
print(note, file=sys.stderr)
|
||||
|
||||
|
||||
def _outbound_tree(inventory):
|
||||
"""[(depth, tag, parent group or "")] in display order: the top level, each group's members under it.
|
||||
|
||||
An inventory from before groups has no "top": every tag is top level then.
|
||||
"""
|
||||
groups = inventory.get("groups") or {}
|
||||
rows = []
|
||||
|
||||
def walk(tag, depth, parent, path):
|
||||
rows.append((depth, tag, parent))
|
||||
if tag in groups and tag not in path:
|
||||
for member in groups[tag].get("members") or []:
|
||||
walk(_s(member), depth + 1, tag, (*path, tag))
|
||||
|
||||
for tag in inventory.get("top") or inventory.get("tags") or []:
|
||||
walk(_s(tag), 0, "", ())
|
||||
return rows
|
||||
|
||||
|
||||
def _outbounds_list():
|
||||
_require_outbound_inventory()
|
||||
inventory = _outbound_inventory()
|
||||
@@ -1371,7 +1480,11 @@ def _outbounds_list():
|
||||
detours = inventory.get("detours") or {}
|
||||
excluded = set(inventory.get("excluded") or [])
|
||||
disabled = set(_outbound_disabled())
|
||||
groups = inventory.get("groups") or {}
|
||||
# One Clash API read for every group's pick, only when there are groups.
|
||||
nows = _group_nows() if groups else {}
|
||||
current = _outbound_current()
|
||||
down = {t for t, m in (_group_state().get("members") or {}).items() if isinstance(m, dict) and m.get("up") is False}
|
||||
reputation = _reputation_by_tag()
|
||||
|
||||
print(f"Selection: {_s(inventory.get('selection') or 'first')}")
|
||||
@@ -1382,17 +1495,34 @@ def _outbounds_list():
|
||||
# The reputation column only once the autoProxy prober has checked some exit.
|
||||
rep = (lambda tag: f"{reputation.get(tag, '-'):<16} ") if reputation else (lambda tag: "")
|
||||
print(f" {'TAG':<34} {'REPUTATION':<16} SOURCE" if reputation else f" {'TAG':<34} SOURCE")
|
||||
for tag in _outbound_tags():
|
||||
for depth, tag, parent in _outbound_tree(inventory):
|
||||
if parent:
|
||||
info = groups.get(parent) or {}
|
||||
chosen, live = _s(info.get("pinned") or ""), nows.get(parent, "")
|
||||
else:
|
||||
chosen, live = pinned, current
|
||||
mark = " "
|
||||
if tag == pinned:
|
||||
if tag == chosen:
|
||||
mark = "*"
|
||||
elif not pinned and tag == current:
|
||||
elif not chosen and tag == live:
|
||||
mark = ">"
|
||||
elif tag in disabled:
|
||||
mark = "-"
|
||||
notes = [f"via {_s(detours[tag])}"] if tag in detours else []
|
||||
notes += ["disabled"] if tag in disabled else ["never picked"] if tag in excluded else []
|
||||
print(f" {mark}{tag:<34} {rep(tag)}{', '.join([_s(sources.get(tag) or '-'), *notes])}")
|
||||
if tag in groups:
|
||||
info = groups[tag]
|
||||
source = f"group: {_s(info.get('strategy') or 'failover')}"
|
||||
notes = [f"pinned {_s(info['pinned'])}"] if info.get("pinned") else [f"using {nows[tag]}"] if nows.get(tag) else []
|
||||
else:
|
||||
source = _s(sources.get(tag) or "-")
|
||||
notes = [f"via {_s(detours[tag])}"] if tag in detours else []
|
||||
if tag in disabled:
|
||||
notes.append("disabled")
|
||||
elif tag in down:
|
||||
notes.append("down")
|
||||
elif not parent and tag in excluded:
|
||||
notes.append("never picked")
|
||||
name = " " * depth + tag
|
||||
print(f" {mark}{name:<34} {rep(tag)}{', '.join([source, *notes])}")
|
||||
|
||||
|
||||
# --- sharing ------------------------------------------------------------------
|
||||
@@ -1489,39 +1619,559 @@ def _config_export(*args, only=None):
|
||||
print(f"warning: {warning}", file=sys.stderr)
|
||||
|
||||
|
||||
def cmd_pin(tag="", *_):
|
||||
if not tag:
|
||||
if not (os.isatty(0) and os.isatty(1)):
|
||||
usage("proxy pin <tag>")
|
||||
_require_outbound_inventory()
|
||||
pinned = _s(_outbound_inventory().get("pinned") or "") or "(none)"
|
||||
status, tag = _run(
|
||||
["fzf", "--prompt=pin> ", "--height=40%", "--reverse", f"--header=pinned: {pinned}"],
|
||||
capture=True,
|
||||
stdin="".join(f"{t}\n" for t in _outbound_tags() if t not in _outbound_disabled()),
|
||||
)
|
||||
tag = tag.strip("\n")
|
||||
# Dismissed.
|
||||
if status or not tag:
|
||||
return
|
||||
# The inventory too: the marker sits in a dir only root and the group can look into.
|
||||
if os.path.exists(_outbound_disabled_marker(tag)) or tag in _outbound_disabled():
|
||||
die(f"Outbound '{tag}' is disabled; enable it first: proxy-ctl proxy outbounds enable {tag}")
|
||||
status, escaped = _run(["systemd-escape", "--", tag], capture=True)
|
||||
def _pin_args(args, verb):
|
||||
"""(tag, group) from `pin [tag] [--in <group>]` or `unpin [--in <group>]`."""
|
||||
args = list(args)
|
||||
group = ""
|
||||
if "--in" in args:
|
||||
i = args.index("--in")
|
||||
group = args[i + 1] if i + 1 < len(args) else ""
|
||||
del args[i : i + 2]
|
||||
if not group:
|
||||
usage(f"proxy {verb} {'[tag] ' if verb == 'pin' else ''}--in <group>")
|
||||
if group not in _outbound_groups():
|
||||
die(f"Unknown group: {group}")
|
||||
for arg in args:
|
||||
if arg.startswith("-"):
|
||||
die(f"Unknown option: {arg}")
|
||||
if verb == "unpin" and args:
|
||||
usage("proxy unpin [--in <group>]")
|
||||
if len(args) > 1:
|
||||
usage("proxy pin [tag] [--in <group>]")
|
||||
return (args[0] if args else ""), group
|
||||
|
||||
|
||||
def _pick_pin(choices, header):
|
||||
status, tag = _run(
|
||||
["fzf", "--prompt=pin> ", "--height=40%", "--reverse", f"--header={header}"],
|
||||
capture=True,
|
||||
stdin="".join(f"{t}\n" for t in choices),
|
||||
)
|
||||
tag = tag.strip("\n")
|
||||
# Dismissed.
|
||||
return "" if status else tag
|
||||
|
||||
|
||||
def _start_pin_unit(instance):
|
||||
status, escaped = _run(["systemd-escape", "--", instance], capture=True)
|
||||
if status:
|
||||
sys.exit(status)
|
||||
unit = "proxy-suite-outbound-pin@" + escaped.rstrip("\n")
|
||||
if systemctl("start", f"{unit}.service")[0]:
|
||||
die(f"Failed - see: proxy-ctl logs {unit}")
|
||||
|
||||
|
||||
def cmd_pin(*args):
|
||||
tag, group = _pin_args(args, "pin")
|
||||
if not tag:
|
||||
if not (os.isatty(0) and os.isatty(1)):
|
||||
usage("proxy pin <tag> [--in <group>]")
|
||||
_require_outbound_inventory()
|
||||
disabled = _outbound_disabled()
|
||||
if group:
|
||||
info = _outbound_groups()[group]
|
||||
choices = [m for m in info.get("members") or [] if m not in disabled and m != "block"]
|
||||
header = f"{group} pinned: {_s(info.get('pinned') or '') or '(none)'}"
|
||||
else:
|
||||
choices = [t for t in _outbound_tags() + list(_outbound_groups()) if t not in disabled]
|
||||
header = f"pinned: {_s(_outbound_inventory().get('pinned') or '') or '(none)'}"
|
||||
tag = _pick_pin(choices, header)
|
||||
if not tag:
|
||||
return
|
||||
# The inventory too: the marker sits in a dir only root and the group can look into.
|
||||
if os.path.exists(_outbound_disabled_marker(tag)) or tag in _outbound_disabled():
|
||||
die(f"Outbound '{tag}' is disabled; enable it first: proxy-ctl proxy outbounds enable {tag}")
|
||||
if group:
|
||||
if tag not in (_outbound_groups()[group].get("members") or []):
|
||||
die(f"'{tag}' is not in group '{group}'. See: proxy-ctl proxy groups")
|
||||
_start_pin_unit(f"{group}/{tag}")
|
||||
print(f"Pinned in {group}: {tag}")
|
||||
return
|
||||
_start_pin_unit(tag)
|
||||
print(f"Pinned: {tag}")
|
||||
|
||||
|
||||
def cmd_unpin(*_):
|
||||
def cmd_unpin(*args):
|
||||
_, group = _pin_args(args, "unpin")
|
||||
if group:
|
||||
_start_pin_unit(f"{group}/")
|
||||
print(f"Unpinned in {group}: it picks again.")
|
||||
return
|
||||
if systemctl("start", "proxy-suite-outbound-unpin.service")[0]:
|
||||
die("Failed - see: proxy-ctl logs proxy-suite-outbound-unpin")
|
||||
print("Unpinned: the configured selection picks again.")
|
||||
|
||||
|
||||
# --- outbound groups ----------------------------------------------------------
|
||||
#
|
||||
# proxy.groups and runtime <tag>.group files (in the runtime outbound dir) are resolved by the
|
||||
# start script, which lists them in the inventory: strategy, members in order, and the pin.
|
||||
# proxy-suite-outbound-groups runs `proxy groups watch` for the failover ones.
|
||||
|
||||
GROUP_STRATEGIES = ("failover", "urltest", "selector")
|
||||
# A member is down after this many failed tests in a row, or after one that follows a hint.
|
||||
GROUP_MISSES_DOWN = 2
|
||||
# A member that was down is up again after this many passes in a row.
|
||||
GROUP_PASSES_UP = 3
|
||||
GROUP_TEST_TIMEOUT_MS = 5000
|
||||
|
||||
|
||||
def _outbound_groups():
|
||||
"""{group: {strategy, failback, interval, members, pinned, runtime}}, as the running backend took them."""
|
||||
groups = _outbound_inventory().get("groups") or {}
|
||||
return groups if isinstance(groups, dict) else {}
|
||||
|
||||
|
||||
def _groups_dir():
|
||||
"""proxy-suite-outbound-groups' runtime dir: health/ for hints, groups-state.json for the front ends."""
|
||||
return os.path.join(runtime_dir(), "proxy-suite-outbound-groups")
|
||||
|
||||
|
||||
def _group_state():
|
||||
"""What the watcher last saw: {"groups": {group: {"now"}}, "members": {tag: {"up", "since"}}}."""
|
||||
state = read_json_or(os.path.join(_groups_dir(), "groups-state.json"), {})
|
||||
return state if isinstance(state, dict) else {}
|
||||
|
||||
|
||||
def _group_nows():
|
||||
"""{group: the member it uses now} for every sing-box group, the top-level "proxy" included."""
|
||||
status, body = _clash("GET", "/proxies", timeout=5)
|
||||
proxies = body.get("proxies") if status == 200 and isinstance(body, dict) else None
|
||||
if not isinstance(proxies, dict):
|
||||
return {}
|
||||
return {_s(name): _s(p["now"]) for name, p in proxies.items() if isinstance(p, dict) and p.get("now")}
|
||||
|
||||
|
||||
def _duration(text, fallback=30.0):
|
||||
"""Seconds in a Go duration ("30s", "3m", "1h30m")."""
|
||||
total = 0.0
|
||||
for number, unit in re.findall(r"(\d+(?:\.\d+)?)(ms|s|m|h)", str(text or "")):
|
||||
total += float(number) * {"ms": 0.001, "s": 1, "m": 60, "h": 3600}[unit]
|
||||
return total or fallback
|
||||
|
||||
|
||||
class GroupWatch:
|
||||
"""Moves failover groups, and "failover" selection, to the first member that works.
|
||||
|
||||
Every group is tested on its interval; a hint (a file a watchdog touches in health/, named
|
||||
after the outbound it saw fail) tests that outbound at once. A member is down after
|
||||
GROUP_MISSES_DOWN failed tests in a row, or one failed test right after a hint; one that was
|
||||
down is up again after GROUP_PASSES_UP passes. With failback the group goes back to an
|
||||
earlier member once it is up; without, it stays until its member goes down. Pinned groups
|
||||
are left alone. urltest groups are sing-box's to move; a hint only makes them test now.
|
||||
"""
|
||||
|
||||
def __init__(self, clash=None, clock=time.monotonic, wall=time.time):
|
||||
self.clash = clash or _clash
|
||||
self.clock = clock
|
||||
self.wall = wall
|
||||
self.health = {} # tag -> {"up", "misses", "passes", "since"}
|
||||
self.due = {} # group -> clock time of its next test
|
||||
self.seen_hints = {} # tag -> hint file mtime already acted on
|
||||
|
||||
@staticmethod
|
||||
def watched(inventory):
|
||||
"""{group: info} to watch, with "proxy" standing for the top level when its selection is failover."""
|
||||
groups = {g: dict(v) for g, v in (inventory.get("groups") or {}).items() if isinstance(v, dict)}
|
||||
if inventory.get("selection") == "failover":
|
||||
skip = set(inventory.get("excluded") or []) | set(inventory.get("disabled") or [])
|
||||
groups["proxy"] = {
|
||||
"strategy": "failover",
|
||||
"failback": True,
|
||||
"interval": "30s",
|
||||
"members": [t for t in inventory.get("top") or [] if t not in skip],
|
||||
"pinned": _s(inventory.get("pinned") or ""),
|
||||
}
|
||||
return groups
|
||||
|
||||
@staticmethod
|
||||
def inner_first(groups):
|
||||
"""Group names with every group they contain before them."""
|
||||
order = []
|
||||
|
||||
def visit(name, path):
|
||||
if name in order or name in path:
|
||||
return
|
||||
for member in groups[name].get("members") or []:
|
||||
if member in groups:
|
||||
visit(member, path + [name])
|
||||
order.append(name)
|
||||
|
||||
for name in groups:
|
||||
visit(name, [])
|
||||
return order
|
||||
|
||||
def test(self, tag, url):
|
||||
query = urllib.parse.urlencode({"url": url, "timeout": GROUP_TEST_TIMEOUT_MS})
|
||||
status, body = self.clash("GET", f"/proxies/{urllib.parse.quote(tag, safe='')}/delay?{query}", timeout=GROUP_TEST_TIMEOUT_MS / 1000 + 3)
|
||||
return status == 200 and isinstance(body, dict) and "delay" in body
|
||||
|
||||
def record(self, tag, ok, hinted=False):
|
||||
h = self.health.setdefault(tag, {"up": True, "misses": 0, "passes": 0, "since": self.wall()})
|
||||
if ok:
|
||||
h["misses"], h["passes"] = 0, h["passes"] + 1
|
||||
if not h["up"] and h["passes"] >= GROUP_PASSES_UP:
|
||||
h["up"], h["since"] = True, self.wall()
|
||||
else:
|
||||
h["passes"], h["misses"] = 0, h["misses"] + 1
|
||||
if h["up"] and (hinted or h["misses"] >= GROUP_MISSES_DOWN):
|
||||
h["up"], h["since"] = False, self.wall()
|
||||
|
||||
def up(self, tag):
|
||||
return self.health.get(tag, {}).get("up", True)
|
||||
|
||||
def pick(self, info, now, disabled):
|
||||
"""The member the group should use, or None to leave it where it is."""
|
||||
if info.get("pinned"):
|
||||
return None
|
||||
members = [m for m in info.get("members") or [] if m != "block" and m not in disabled]
|
||||
working = [m for m in members if self.up(m)]
|
||||
if not working:
|
||||
return None # nothing works: moving would only flap
|
||||
if not info.get("failback", True) and now in working:
|
||||
return None
|
||||
return working[0] if working[0] != now else None
|
||||
|
||||
def hints(self):
|
||||
"""Tags whose hint file changed since the last look."""
|
||||
directory = os.path.join(_groups_dir(), "health")
|
||||
fresh = []
|
||||
try:
|
||||
names = os.listdir(directory)
|
||||
except OSError:
|
||||
return fresh
|
||||
for name in names:
|
||||
try:
|
||||
mtime = os.stat(os.path.join(directory, name)).st_mtime
|
||||
except OSError:
|
||||
continue
|
||||
if self.seen_hints.get(name) != mtime:
|
||||
if name in self.seen_hints:
|
||||
fresh.append(name)
|
||||
self.seen_hints[name] = mtime
|
||||
return fresh
|
||||
|
||||
def step(self, inventory, hinted=()):
|
||||
"""One pass: test what is due or hinted, move what should move. The switches made, as (group, member)."""
|
||||
groups = self.watched(inventory)
|
||||
if not groups:
|
||||
return []
|
||||
url = _s(inventory.get("url") or "https://www.gstatic.com/generate_204")
|
||||
disabled = set(inventory.get("disabled") or [])
|
||||
now_clock = self.clock()
|
||||
hinted = set(hinted)
|
||||
results = {}
|
||||
# A hinted tag is tested at once, and so is everything around it.
|
||||
for tag in hinted:
|
||||
if tag not in results:
|
||||
results[tag] = self.test(tag, url)
|
||||
self.record(tag, results[tag], hinted=True)
|
||||
switches = []
|
||||
nows = None
|
||||
for name in self.inner_first(groups):
|
||||
info = groups[name]
|
||||
members = [m for m in info.get("members") or [] if m != "block"]
|
||||
touched = bool(hinted & set(members))
|
||||
if info.get("strategy") == "urltest":
|
||||
if touched:
|
||||
query = urllib.parse.urlencode({"url": url, "timeout": GROUP_TEST_TIMEOUT_MS})
|
||||
self.clash("GET", f"/group/{urllib.parse.quote(name, safe='')}/delay?{query}", timeout=GROUP_TEST_TIMEOUT_MS / 1000 + 3)
|
||||
continue
|
||||
if info.get("strategy") != "failover":
|
||||
continue
|
||||
if not touched and self.due.get(name, 0) > now_clock:
|
||||
continue
|
||||
self.due[name] = now_clock + _duration(info.get("interval"))
|
||||
for tag in members:
|
||||
if tag in disabled:
|
||||
continue
|
||||
if tag not in results:
|
||||
results[tag] = self.test(tag, url)
|
||||
self.record(tag, results[tag])
|
||||
if nows is None:
|
||||
nows = _group_nows()
|
||||
target = self.pick(info, nows.get(name, ""), disabled)
|
||||
if target is None:
|
||||
continue
|
||||
status, _ = self.clash("PUT", f"/proxies/{urllib.parse.quote(name, safe='')}", {"name": target})
|
||||
if 200 <= status < 300:
|
||||
print(f"{name}: {nows.get(name) or '-'} -> {target}", file=sys.stderr)
|
||||
nows[name] = target
|
||||
switches.append((name, target))
|
||||
return switches
|
||||
|
||||
def state(self, nows):
|
||||
return {
|
||||
"updated": self.wall(),
|
||||
"groups": {g: {"now": n} for g, n in nows.items()},
|
||||
"members": {t: {"up": h["up"], "since": h["since"]} for t, h in self.health.items()},
|
||||
}
|
||||
|
||||
def write_state(self):
|
||||
path = os.path.join(_groups_dir(), "groups-state.json")
|
||||
try:
|
||||
fd, tmp = tempfile.mkstemp(dir=_groups_dir(), prefix=".groups-state.")
|
||||
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
||||
json.dump(self.state(_group_nows()), f)
|
||||
os.chmod(tmp, 0o644)
|
||||
os.replace(tmp, path)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def run(self):
|
||||
health = os.path.join(_groups_dir(), "health")
|
||||
os.makedirs(health, exist_ok=True)
|
||||
# Watchdogs run as other users (the WARP tunnel as the service user). A hint only makes
|
||||
# this test sooner, so anyone may leave one; nobody may list or remove another's.
|
||||
os.chmod(health, 0o1733)
|
||||
self.hints() # what is there already is no news
|
||||
last_state = 0.0
|
||||
while True:
|
||||
inventory = _outbound_inventory()
|
||||
fresh = self.hints()
|
||||
if inventory:
|
||||
self.step(inventory, fresh)
|
||||
if fresh or self.clock() - last_state >= 10:
|
||||
self.write_state()
|
||||
last_state = self.clock()
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def _group_file(tag):
|
||||
return os.path.join(_runtime_dir("outbound"), f"{tag}.group")
|
||||
|
||||
|
||||
def _read_group_file(tag):
|
||||
try:
|
||||
with open(_group_file(tag), encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except FileNotFoundError:
|
||||
die(f"'{tag}' is not a group added with proxy-ctl; declared groups change in the configuration.")
|
||||
except (OSError, ValueError):
|
||||
denied(_group_file(tag))
|
||||
return data if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def _write_group_file(tag, data):
|
||||
path = _group_file(tag)
|
||||
old = os.umask(0o027)
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2)
|
||||
f.write("\n")
|
||||
except OSError:
|
||||
denied(path, "write")
|
||||
finally:
|
||||
os.umask(old)
|
||||
|
||||
|
||||
def _group_contains(groups, outer, tag, seen=()):
|
||||
"""Whether group outer holds tag, however deep."""
|
||||
for member in (groups.get(outer) or {}).get("members") or []:
|
||||
if member == tag or (member in groups and member not in seen and _group_contains(groups, member, tag, (*seen, outer))):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _group_check_members(tag, members):
|
||||
groups = _outbound_groups()
|
||||
for member in members:
|
||||
if member == tag or (member in groups and _group_contains(groups, member, tag)):
|
||||
die(f"'{member}' contains '{tag}': a group cannot hold itself.")
|
||||
if member not in _outbound_tags() and member not in groups:
|
||||
print(f"warning: '{member}' is not an outbound or group right now; the group leaves it out until it is.", file=sys.stderr)
|
||||
|
||||
|
||||
def _group_options(args, shape):
|
||||
"""(positional, {strategy, failback, interval, subscriptions, match}) from group add flags."""
|
||||
rest, opts = [], {"subscriptions": [], "match": []}
|
||||
it = iter(args)
|
||||
for arg in it:
|
||||
if arg == "--strategy":
|
||||
opts["strategy"] = next(it, "")
|
||||
if opts["strategy"] not in GROUP_STRATEGIES:
|
||||
die(f"--strategy is one of: {', '.join(GROUP_STRATEGIES)}")
|
||||
elif arg == "--no-failback":
|
||||
opts["failback"] = False
|
||||
elif arg == "--interval":
|
||||
opts["interval"] = next(it, "")
|
||||
if not re.fullmatch(r"(\d+(\.\d+)?(ms|s|m|h))+", opts["interval"]):
|
||||
die("--interval is a Go duration: 30s, 1m, 1m30s.")
|
||||
elif arg == "--sub":
|
||||
opts["subscriptions"].append(next(it, ""))
|
||||
elif arg == "--match":
|
||||
opts["match"].append(next(it, ""))
|
||||
elif arg.startswith("-"):
|
||||
die(f"Unknown option: {arg}")
|
||||
else:
|
||||
rest.append(arg)
|
||||
if "" in opts["subscriptions"] + opts["match"]:
|
||||
usage(shape)
|
||||
return rest, opts
|
||||
|
||||
|
||||
GROUP_ADD_SHAPE = "proxy groups add <tag> [member...] [--sub <subscription>]... [--match <pattern>]... [--strategy failover|urltest|selector] [--no-failback] [--interval <duration>]"
|
||||
|
||||
|
||||
def _groups_list():
|
||||
_require_outbound_inventory()
|
||||
groups = _outbound_groups()
|
||||
if not groups:
|
||||
print("No groups. Add one: proxy-ctl proxy groups add <tag> <member...>")
|
||||
return
|
||||
nows = _group_nows()
|
||||
members_state = _group_state().get("members") or {}
|
||||
disabled = set(_outbound_disabled())
|
||||
for name, info in groups.items():
|
||||
strategy = _s(info.get("strategy") or "failover")
|
||||
notes = [strategy]
|
||||
if strategy == "failover" and info.get("failback") is False:
|
||||
notes.append("no failback")
|
||||
if info.get("pinned"):
|
||||
notes.append(f"pinned: {_s(info['pinned'])}")
|
||||
elif nows.get(name):
|
||||
notes.append(f"using {nows[name]}")
|
||||
if info.get("runtime"):
|
||||
notes.append("runtime")
|
||||
print(f"{name} ({', '.join(notes)})")
|
||||
for member in info.get("members") or []:
|
||||
mark = "*" if member == info.get("pinned") else ">" if member == nows.get(name) else " "
|
||||
state = []
|
||||
if member in disabled:
|
||||
state.append("disabled")
|
||||
elif (members_state.get(member) or {}).get("up") is False:
|
||||
state.append("down")
|
||||
print(f" {mark} {member}{' (' + ', '.join(state) + ')' if state else ''}")
|
||||
|
||||
|
||||
def cmd_groups(verb="list", *args):
|
||||
if verb == "list":
|
||||
_groups_list()
|
||||
elif verb == "watch":
|
||||
# proxy-suite-outbound-groups' ExecStart.
|
||||
GroupWatch().run()
|
||||
elif verb == "add":
|
||||
rest, opts = _group_options(args, GROUP_ADD_SHAPE)
|
||||
if not rest:
|
||||
usage(GROUP_ADD_SHAPE)
|
||||
tag, members = rest[0], rest[1:]
|
||||
_check_runtime_tag("outbound", tag)
|
||||
if tag in _outbound_groups() or os.path.exists(_group_file(tag)):
|
||||
die(f"A group named '{tag}' already exists.")
|
||||
if not members and not opts["subscriptions"] and not opts["match"]:
|
||||
die("A group needs members, a --sub or a --match.")
|
||||
_group_check_members(tag, members)
|
||||
_write_group_file(tag, {"outbounds": members, **opts})
|
||||
_runtime_reload()
|
||||
print(f"Added group: {tag}")
|
||||
elif verb == "rm":
|
||||
if len(args) != 1:
|
||||
usage("proxy groups rm <tag>")
|
||||
tag = args[0]
|
||||
_read_group_file(tag)
|
||||
try:
|
||||
os.unlink(_group_file(tag))
|
||||
except OSError:
|
||||
denied(_group_file(tag), "remove")
|
||||
_runtime_reload()
|
||||
print(f"Removed group: {tag}")
|
||||
elif verb == "members":
|
||||
if len(args) < 3 or args[1] not in ("add", "rm"):
|
||||
usage("proxy groups members <tag> add|rm <member...>")
|
||||
tag, action, names = args[0], args[1], list(args[2:])
|
||||
data = _read_group_file(tag)
|
||||
members = [m for m in data.get("outbounds") or [] if isinstance(m, str)]
|
||||
if action == "add":
|
||||
_group_check_members(tag, names)
|
||||
members += [n for n in names if n not in members]
|
||||
else:
|
||||
missing = [n for n in names if n not in members]
|
||||
if missing:
|
||||
die(f"Not listed in '{tag}': {', '.join(missing)}")
|
||||
members = [m for m in members if m not in names]
|
||||
if not members and not data.get("subscriptions") and not data.get("match"):
|
||||
die(f"That would leave '{tag}' empty; remove the group instead: proxy-ctl proxy groups rm {tag}")
|
||||
data["outbounds"] = members
|
||||
_write_group_file(tag, data)
|
||||
_runtime_reload()
|
||||
print(f"{tag}: {', '.join(members) or '(members from --sub/--match only)'}")
|
||||
elif verb == "strategy":
|
||||
if len(args) != 2 or args[1] not in GROUP_STRATEGIES:
|
||||
usage(f"proxy groups strategy <tag> {'|'.join(GROUP_STRATEGIES)}")
|
||||
tag, strategy = args
|
||||
data = _read_group_file(tag)
|
||||
data["strategy"] = strategy
|
||||
_write_group_file(tag, data)
|
||||
_runtime_reload()
|
||||
print(f"{tag}: {strategy}")
|
||||
else:
|
||||
usage("proxy groups [list|add|rm|members|strategy]")
|
||||
|
||||
|
||||
# --- priority -----------------------------------------------------------------
|
||||
#
|
||||
# proxy.priority, and runtime overrides in priority.json in the runtime outbound dir: lower
|
||||
# goes first, for the top level and for group members pulled in by --sub or --match.
|
||||
|
||||
|
||||
def _priority_file():
|
||||
return os.path.join(_runtime_dir("outbound"), "priority.json")
|
||||
|
||||
|
||||
def _runtime_priority():
|
||||
data = read_json_or(_priority_file(), {})
|
||||
return {k: v for k, v in data.items() if isinstance(v, int)} if isinstance(data, dict) else {}
|
||||
|
||||
|
||||
def cmd_priority(*args):
|
||||
if not args or args[0] == "list":
|
||||
_require_outbound_inventory()
|
||||
inventory = _outbound_inventory()
|
||||
priority = inventory.get("priority") or {}
|
||||
print("Top level, in order:")
|
||||
# An inventory from before groups has no "top": every tag is top level then.
|
||||
for tag in inventory.get("top") or inventory.get("tags") or []:
|
||||
rank = priority.get(tag)
|
||||
print(f" {'-' if rank is None else rank:>6} {tag}")
|
||||
return
|
||||
if len(args) != 2:
|
||||
usage("proxy priority [list] | <tag> <number>|up|down|--clear")
|
||||
tag, value = args
|
||||
if tag not in _outbound_tags() and tag not in _outbound_groups():
|
||||
die(f"Unknown outbound or group: {tag}")
|
||||
data = _runtime_priority()
|
||||
if value == "--clear":
|
||||
data.pop(tag, None)
|
||||
elif value in ("up", "down"):
|
||||
# Every top-level entry numbered in the new order, 10 apart: room to slot one in by hand.
|
||||
top = [_s(t) for t in _outbound_inventory().get("top") or []]
|
||||
if tag not in top:
|
||||
die(f"'{tag}' is not at the top level; a group orders its members itself.")
|
||||
i = top.index(tag)
|
||||
j = i - 1 if value == "up" else i + 1
|
||||
if not 0 <= j < len(top):
|
||||
print(f"{tag} is already {'first' if value == 'up' else 'last'}.")
|
||||
return
|
||||
top[i], top[j] = top[j], top[i]
|
||||
data.update({t: 10 * (n + 1) for n, t in enumerate(top)})
|
||||
elif re.fullmatch(r"-?\d+", value):
|
||||
data[tag] = int(value)
|
||||
else:
|
||||
usage("proxy priority <tag> <number>|up|down|--clear")
|
||||
path = _priority_file()
|
||||
old = os.umask(0o027)
|
||||
try:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, indent=2, sort_keys=True)
|
||||
f.write("\n")
|
||||
except OSError:
|
||||
denied(path, "write")
|
||||
finally:
|
||||
os.umask(old)
|
||||
_runtime_reload()
|
||||
print(f"{tag}: {'default order' if value == '--clear' else 'moved ' + value if value in ('up', 'down') else value}")
|
||||
|
||||
|
||||
# --- runtime outbounds and subscriptions --------------------------------------
|
||||
#
|
||||
# One entry per file in a spool directory the userControl group may write: <tag>.url,
|
||||
@@ -1585,6 +2235,8 @@ def _check_runtime_tag(kind, tag):
|
||||
if kind == "outbound":
|
||||
if tag in _outbound_tags():
|
||||
die(f"An outbound named '{tag}' already exists.")
|
||||
if tag in _outbound_groups() or os.path.exists(os.path.join(_runtime_dir(kind), f"{tag}.group")):
|
||||
die(f"A group named '{tag}' already exists.")
|
||||
elif tag in _sub_tags():
|
||||
die(f"A subscription named '{tag}' is declared in the configuration.")
|
||||
|
||||
@@ -3164,10 +3816,11 @@ def _awg_add(*args):
|
||||
name, source = args
|
||||
else:
|
||||
usage(shape)
|
||||
# "warp" names WARP's own AmneziaWG unit (_warp_unit).
|
||||
taken = {*_awg_profiles(), "warp"}
|
||||
if name == "warp":
|
||||
die("'warp' is reserved for WARP; pick another name.")
|
||||
# "warp" and the WARP devices name WARP's own AmneziaWG units (_warp_devices).
|
||||
reserved = {"warp", *(t for t, _ in _warp_devices())}
|
||||
taken = {*_awg_profiles(), *reserved}
|
||||
if name in reserved:
|
||||
die(f"'{name}' is reserved for WARP; pick another name.")
|
||||
if name:
|
||||
if not AWG_NAME.fullmatch(name):
|
||||
die(f"Invalid profile name '{name}': up to 32 letters, digits, dashes and underscores, starting with a letter or digit.")
|
||||
@@ -3989,7 +4642,7 @@ COMMANDS = {
|
||||
"awg": cmd_awg,
|
||||
"killswitch": lambda *args: _toggle(KILL_SWITCH, "killswitch", *args),
|
||||
"ssh": lambda *args: _toggle("proxy-suite-ssh-proxy", "ssh", *args),
|
||||
"warp": lambda *args: _toggle(_warp_unit(), "warp", *args),
|
||||
"warp": cmd_warp,
|
||||
"tor": cmd_tor,
|
||||
"tg": lambda *args: _toggle("proxy-suite-tg-ws-proxy", "tg", *args),
|
||||
"wl": cmd_wl,
|
||||
|
||||
@@ -298,6 +298,7 @@ class Page(Gtk.Box):
|
||||
super().__init__(orientation=Gtk.Orientation.VERTICAL)
|
||||
self.win, self.tab = win, tab
|
||||
self.rows = [] # the last load, unfiltered
|
||||
self.collapsed = set() # a tree tab's groups folded away, by row key
|
||||
self.summary_text = ""
|
||||
self.detail_shape = None
|
||||
self.loaded = False # whether a load has landed here: before that the tab is not empty, it is unread
|
||||
@@ -328,7 +329,9 @@ class Page(Gtk.Box):
|
||||
column.set_expand(i == len(tab.columns) - 1)
|
||||
sorter = Gtk.CustomSorter.new(lambda a, b, name: self.compare(a, b, name), name)
|
||||
self.sorters.append(sorter)
|
||||
column.set_sorter(sorter)
|
||||
# A tree keeps its order: it is the order its groups pick in.
|
||||
if not tab.tree:
|
||||
column.set_sorter(sorter)
|
||||
self.view.append_column(column)
|
||||
self.view.connect("activate", lambda view, pos: self.open_menu(None))
|
||||
|
||||
@@ -467,6 +470,8 @@ class Page(Gtk.Box):
|
||||
rows = model.filter_rows(rows, self.tab.columns, text)
|
||||
self.count.set_text(f"{len(rows)} of {len(self.rows)}")
|
||||
else:
|
||||
if self.tab.tree:
|
||||
rows = model.fold_rows(rows, self.collapsed)
|
||||
self.count.set_text(f"{len(rows)} row{'' if len(rows) == 1 else 's'}")
|
||||
self.summary.set_text(summary)
|
||||
keys = [r["key"] for r in rows]
|
||||
@@ -985,6 +990,13 @@ class Window(Adw.ApplicationWindow):
|
||||
return True
|
||||
|
||||
def perform(self, action, row):
|
||||
if action.mode == "fold":
|
||||
page = self.page()
|
||||
if page is not None and row is not None:
|
||||
page.collapsed.symmetric_difference_update({row["key"]})
|
||||
page.refill()
|
||||
return
|
||||
|
||||
def with_text(text=""):
|
||||
try:
|
||||
argv = action.argv(row, text, self.app.states)
|
||||
|
||||
+127
-33
@@ -78,6 +78,7 @@ class Tab:
|
||||
rows: Callable # unit states -> [row dict with a unique "key"]
|
||||
summary: Callable = None # () -> text above the table, read with every load
|
||||
actions: list = field(default_factory=list)
|
||||
tree: bool = False # rows carry "ancestors" (row keys) and "group": the order means something, so no sorting
|
||||
|
||||
|
||||
def ROW(_):
|
||||
@@ -235,27 +236,58 @@ def outbound_rows(_):
|
||||
detours = inventory.get("detours") or {}
|
||||
excluded = set(inventory.get("excluded") or [])
|
||||
disabled = set(ctl._outbound_disabled())
|
||||
groups = inventory.get("groups") or {}
|
||||
# One Clash API read for every group's pick, only when there are groups.
|
||||
nows = ctl._group_nows() if groups else {}
|
||||
current = ctl._outbound_current()
|
||||
down = {t for t, m in (ctl._group_state().get("members") or {}).items() if isinstance(m, dict) and m.get("up") is False}
|
||||
reputation = ctl._reputation_by_tag()
|
||||
# outbounds.d is root-only; the inventory says "runtime" for what the backend loaded from it.
|
||||
runtime = set(ctl._runtime_tags("outbound")) | {t for t, s in sources.items() if s == "runtime"}
|
||||
return [
|
||||
{
|
||||
"key": t,
|
||||
"mark": "★" if t == pinned else "▸" if t == current else "✕" if t in disabled else "",
|
||||
"tag": t,
|
||||
"reputation": reputation.get(t, "-"),
|
||||
"source": "runtime" if t in runtime else ctl._s(sources.get(t) or "-"),
|
||||
# As `proxy-ctl proxy outbounds` prints them.
|
||||
"notes": ", ".join(
|
||||
([f"via {ctl._s(detours[t])}"] if t in detours else [])
|
||||
+ (["disabled"] if t in disabled else ["never picked"] if t in excluded else [])
|
||||
),
|
||||
"runtime": t in runtime,
|
||||
"disabled": t in disabled,
|
||||
}
|
||||
for t in ctl._outbound_tags()
|
||||
]
|
||||
rows, path = [], []
|
||||
# As `proxy-ctl proxy outbounds` prints them: a group's members under it, in its order.
|
||||
for depth, t, parent in ctl._outbound_tree(inventory):
|
||||
path = path[:depth]
|
||||
key = "/".join([*path, t])
|
||||
chosen, live = (ctl._s(groups[parent].get("pinned") or ""), nows.get(parent, "")) if parent else (pinned, current)
|
||||
group = groups.get(t)
|
||||
if group is not None:
|
||||
source = f"group: {ctl._s(group.get('strategy') or 'failover')}"
|
||||
notes = [f"pinned {ctl._s(group['pinned'])}"] if group.get("pinned") else [f"using {nows[t]}"] if nows.get(t) else []
|
||||
else:
|
||||
source = "runtime" if t in runtime else ctl._s(sources.get(t) or "-")
|
||||
notes = [f"via {ctl._s(detours[t])}"] if t in detours else []
|
||||
notes += ["disabled"] if t in disabled else ["down"] if t in down else ["never picked"] if not parent and t in excluded else []
|
||||
rows.append(
|
||||
{
|
||||
"key": key,
|
||||
"ancestors": ["/".join(path[: i + 1]) for i in range(len(path))],
|
||||
"depth": depth,
|
||||
"parent": parent,
|
||||
"group": group is not None,
|
||||
"mark": "★" if t == chosen else "▸" if t == live else "✕" if t in disabled else "",
|
||||
"tag": t,
|
||||
"name": " " * depth + t,
|
||||
"reputation": "-" if group is not None else reputation.get(t, "-"),
|
||||
"source": source,
|
||||
"notes": ", ".join(notes),
|
||||
"runtime": t in runtime or bool(group and group.get("runtime")),
|
||||
"parent_runtime": bool(parent and (groups.get(parent) or {}).get("runtime")),
|
||||
"disabled": t in disabled,
|
||||
}
|
||||
)
|
||||
path = [*path, t]
|
||||
return rows
|
||||
|
||||
|
||||
def _in_group(row):
|
||||
"""A pin on a group member holds its group, not the top level."""
|
||||
return ["--in", row["parent"]] if row.get("parent") else []
|
||||
|
||||
|
||||
def _exit(row):
|
||||
"""An outbound rather than a group: what tests, links and chains take."""
|
||||
return row is not None and not row.get("group") and row.get("tag") != "block"
|
||||
|
||||
|
||||
def outbound_summary():
|
||||
@@ -481,7 +513,25 @@ def filter_rows(rows, columns, text):
|
||||
return value in str(row.get(names[column], "")).lower()
|
||||
return any(term.lower() in str(row.get(name, "")).lower() for name, _ in columns)
|
||||
|
||||
return [r for r in rows if all(matches(r, t) for t in text.split())]
|
||||
kept = [r for r in rows if all(matches(r, t) for t in text.split())]
|
||||
# In a tree, a match keeps the rows above it, so it still reads as where it sits.
|
||||
wanted = {k for r in kept for k in r.get("ancestors") or []}
|
||||
if not wanted:
|
||||
return kept
|
||||
keys = {r["key"] for r in kept} | wanted
|
||||
return [r for r in rows if r["key"] in keys]
|
||||
|
||||
|
||||
def fold_rows(rows, collapsed):
|
||||
"""A tree tab's rows without those under a collapsed group, each group's name showing whether it is."""
|
||||
out = []
|
||||
for r in rows:
|
||||
if any(k in collapsed for k in r.get("ancestors") or []):
|
||||
continue
|
||||
if r.get("group"):
|
||||
r = {**r, "name": " " * r.get("depth", 0) + ("▸ " if r["key"] in collapsed else "▾ ") + r["tag"]}
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def _natural(value):
|
||||
@@ -644,19 +694,26 @@ TABS = [
|
||||
"outbounds",
|
||||
"Outbounds",
|
||||
_socks,
|
||||
[("mark", ""), ("tag", "Tag"), ("reputation", "Reputation"), ("source", "Source"), ("notes", "Notes")],
|
||||
[("mark", ""), ("name", "Tag"), ("reputation", "Reputation"), ("source", "Source"), ("notes", "Notes")],
|
||||
outbound_rows,
|
||||
summary=outbound_summary,
|
||||
tree=True,
|
||||
actions=[
|
||||
Action("p", "pin it", lambda r, *_: ["proxy", "pin", r["tag"]], when=lambda r: r["mark"] != "★" and not r["disabled"]),
|
||||
Action("p", "unpin it", lambda r, *_: ["proxy", "unpin"], when=lambda r: r["mark"] == "★"),
|
||||
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("ctrl+t", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=ROW, mode="dialog"),
|
||||
Action("space", "fold / unfold the group", lambda r, *_: [], when=lambda r: r["group"], mode="fold"),
|
||||
Action(
|
||||
"p",
|
||||
"pin it",
|
||||
lambda r, *_: ["proxy", "pin", r["tag"], *_in_group(r)],
|
||||
when=lambda r: r["mark"] != "★" and not r["disabled"] and r["tag"] != "block",
|
||||
),
|
||||
Action("p", "unpin it", lambda r, *_: ["proxy", "unpin", *_in_group(r)], when=lambda r: r["mark"] == "★"),
|
||||
Action("t", "test it", lambda r, *_: ["proxy", "outbounds", "test", r["tag"]], when=_exit, mode="dialog"),
|
||||
Action("ctrl+t", "test its download speed", lambda r, *_: ["proxy", "outbounds", "test", r["tag"], "--download"], when=_exit, mode="dialog"),
|
||||
Action(
|
||||
"P",
|
||||
"probe a domain through it…",
|
||||
lambda r, t, _: ["proxy", "auto", "probe", t, "--via", ctl._backend_tag(r["tag"])],
|
||||
when=_enabled("AUTOPROXY_ENABLED"),
|
||||
when=lambda r: _exit(r) and _enabled("AUTOPROXY_ENABLED")(r),
|
||||
prompt="<domain>[/path]",
|
||||
mode="dialog",
|
||||
),
|
||||
@@ -668,35 +725,72 @@ TABS = [
|
||||
prompt="[tag] <url, JSON or vpn://> - e.g. de-1 vless://… or just vless://…",
|
||||
stdin=lambda r, t: _add_stdin(t),
|
||||
),
|
||||
Action(
|
||||
"g",
|
||||
"add a group…",
|
||||
lambda r, t, _: ["proxy", "groups", "add", *shlex.split(t)],
|
||||
prompt="<tag> <member…> [--sub <subscription>] [--match <pattern>] [--strategy failover|urltest|selector]",
|
||||
),
|
||||
Action(
|
||||
"m",
|
||||
"add members to the group…",
|
||||
lambda r, t, _: ["proxy", "groups", "members", r["tag"], "add", *t.split()],
|
||||
when=lambda r: r["group"] and r["runtime"],
|
||||
prompt="<member…>",
|
||||
),
|
||||
Action(
|
||||
"M",
|
||||
"take it out of the group",
|
||||
lambda r, *_: ["proxy", "groups", "members", r["parent"], "rm", r["tag"]],
|
||||
when=lambda r: r["parent_runtime"],
|
||||
confirm=True,
|
||||
),
|
||||
Action(
|
||||
"S",
|
||||
"change the group's strategy…",
|
||||
lambda r, t, _: ["proxy", "groups", "strategy", r["tag"], t.strip()],
|
||||
when=lambda r: r["group"] and r["runtime"],
|
||||
prompt="failover, urltest or selector",
|
||||
),
|
||||
Action(
|
||||
"y",
|
||||
"set its priority…",
|
||||
lambda r, t, _: ["proxy", "priority", r["tag"], t.strip() or "--clear"],
|
||||
when=lambda r: not r["parent"],
|
||||
prompt="<number> - lower goes first; empty: back to the default order",
|
||||
),
|
||||
Action("plus", "move it up", lambda r, *_: ["proxy", "priority", r["tag"], "up"], when=lambda r: not r["parent"]),
|
||||
Action("minus", "move it down", lambda r, *_: ["proxy", "priority", r["tag"], "down"], when=lambda r: not r["parent"]),
|
||||
Action(
|
||||
"h",
|
||||
"add an outbound chained through this one…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "add", *_add_args(t), "--detour", r["tag"]],
|
||||
when=ROW,
|
||||
when=_exit,
|
||||
prompt="[tag] <url or JSON> - e.g. de-1 vless://… or just vless://…",
|
||||
),
|
||||
Action(
|
||||
"H",
|
||||
"chain it through another outbound…",
|
||||
lambda r, t, _: ["proxy", "outbounds", "chain", r["tag"], *t.split()],
|
||||
when=ROW,
|
||||
when=_exit,
|
||||
prompt="<hop tag> [new tag] - a copy of this one dialing through the hop",
|
||||
),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"], confirm=True),
|
||||
Action("d", "remove it", lambda r, *_: ["proxy", "outbounds", "rm", r["tag"]], when=lambda r: r["runtime"] and not r["group"], confirm=True),
|
||||
Action("d", "remove the group", lambda r, *_: ["proxy", "groups", "rm", r["tag"]], when=lambda r: r["runtime"] and r["group"], confirm=True),
|
||||
Action(
|
||||
"x",
|
||||
"disable it",
|
||||
lambda r, *_: ["proxy", "outbounds", "disable", r["tag"]],
|
||||
when=lambda r: not r["disabled"],
|
||||
when=lambda r: _exit(r) and not r["disabled"],
|
||||
confirm=True,
|
||||
),
|
||||
Action("x", "enable it again", lambda r, *_: ["proxy", "outbounds", "enable", r["tag"]], when=lambda r: r["disabled"]),
|
||||
# Credentials: proxy-ctl refuses these without root or the group, and the dialog says so.
|
||||
Action("s", "share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="dialog"),
|
||||
Action("c", "copy share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=ROW, mode="copy"),
|
||||
Action("Q", "share link as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=ROW, mode="dialog"),
|
||||
Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=ROW, mode="dialog"),
|
||||
Action("k", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=ROW, mode="dialog"),
|
||||
Action("s", "share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=_exit, mode="dialog"),
|
||||
Action("c", "copy share link", lambda r, *_: ["proxy", "outbounds", "link", r["tag"]], when=_exit, mode="copy"),
|
||||
Action("Q", "share link as QR", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--qr"], when=_exit, mode="dialog"),
|
||||
Action("J", "its JSON", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--json"], when=_exit, mode="dialog"),
|
||||
Action("k", "client config for it alone", lambda r, *_: ["proxy", "outbounds", "link", r["tag"], "--config"], when=_exit, mode="dialog"),
|
||||
Action("K", "client config with every outbound and rule", lambda r, *_: ["proxy", "config"], mode="dialog"),
|
||||
Action("V", "the config as it runs here", lambda r, *_: ["proxy", "config", "--raw"], mode="dialog"),
|
||||
],
|
||||
|
||||
@@ -428,6 +428,7 @@ class ProxyTui(App):
|
||||
self.rows = {} # tab id -> {row key: row}
|
||||
self.filters = {} # tab id -> text
|
||||
self.sorts = {} # tab id -> (column, descending)
|
||||
self.collapsed = {} # tree tab id -> keys of the groups folded away
|
||||
self.loaded = {} # tab id -> the last load, refilled at once when sorting or filtering changes
|
||||
self.status = []
|
||||
self.typed = {} # prompt title -> what was last typed there
|
||||
@@ -561,6 +562,8 @@ class ProxyTui(App):
|
||||
if text := self.filters.get(tab_id):
|
||||
rows = filter_rows(rows, self.tabs[tab_id].columns, text)
|
||||
summary = f"filter: {text} ({len(rows)} rows) · esc clears" + (f"\n{summary}" if summary else "")
|
||||
elif self.tabs[tab_id].tree:
|
||||
rows = model.fold_rows(rows, self.collapsed.get(tab_id, set()))
|
||||
if sort := self.sorts.get(tab_id):
|
||||
rows = sorted(rows, key=lambda r: _natural(r.get(sort[0])), reverse=sort[1])
|
||||
widget = self.main.query_one(f"#{tab_id}-summary", Static)
|
||||
@@ -652,6 +655,9 @@ class ProxyTui(App):
|
||||
|
||||
def on_data_table_header_selected(self, event):
|
||||
tab_id, name = self.active_tab(), event.column_key.value
|
||||
if self.tabs[tab_id].tree:
|
||||
self.feedback("This list keeps its order: it is the order groups and the top level pick in.")
|
||||
return
|
||||
sort = self.sorts.pop(tab_id, None)
|
||||
if not sort or sort[0] != name:
|
||||
self.sorts[tab_id] = (name, False)
|
||||
@@ -702,6 +708,12 @@ class ProxyTui(App):
|
||||
self.push_screen(Output("Keys", text))
|
||||
|
||||
def perform(self, action, row):
|
||||
if action.mode == "fold":
|
||||
folded = self.collapsed.setdefault(self.active_tab(), set())
|
||||
folded.symmetric_difference_update({row["key"]})
|
||||
self.refill(self.active_tab())
|
||||
return
|
||||
|
||||
def with_text(text=""):
|
||||
try:
|
||||
argv = action.argv(row, text, self.states)
|
||||
|
||||
@@ -11,6 +11,7 @@ import sys
|
||||
import tempfile
|
||||
import threading
|
||||
import unittest
|
||||
import urllib.parse
|
||||
from unittest import mock
|
||||
|
||||
import proxy_ctl as ctl
|
||||
@@ -107,6 +108,150 @@ class ClashApiTest(EnvTest):
|
||||
self.assertEqual(ctl._outbound_current(), "")
|
||||
|
||||
|
||||
class WarpDevicesTest(EnvTest):
|
||||
def test_every_device_or_the_one_named(self):
|
||||
os.environ["WARP_DEVICES"] = json.dumps([{"tag": "warp-1", "unit": "proxy-suite-awg-warp-1"}, {"tag": "warp-2", "unit": "proxy-suite-awg-warp-2"}])
|
||||
calls = []
|
||||
self.patch("svc_exists", lambda unit: True)
|
||||
self.patch("systemctl", lambda *a, **kw: calls.append(a) or (0, "active\n"))
|
||||
status, out, _ = run(ctl.cmd_warp)
|
||||
self.assertEqual(status, 0)
|
||||
self.assertEqual(out.split(), ["warp-1", "active", "warp-2", "active"])
|
||||
calls.clear()
|
||||
run(ctl.cmd_warp, "restart", "warp-2")
|
||||
self.assertEqual(calls, [("restart", "proxy-suite-awg-warp-2")])
|
||||
calls.clear()
|
||||
run(ctl.cmd_warp, "off")
|
||||
self.assertEqual(calls, [("stop", "proxy-suite-awg-warp-1"), ("stop", "proxy-suite-awg-warp-2")])
|
||||
# Both are WARP's: `awg add` leaves their names alone.
|
||||
self.patch("_awg_profiles", lambda: [])
|
||||
os.environ["AWG_RUNTIME_GLOBAL"] = "1"
|
||||
self.assertIn("reserved for WARP", run(ctl.cmd_awg, "add", "warp-2", "vpn://x")[2])
|
||||
|
||||
|
||||
class GroupWatchTest(EnvTest):
|
||||
"""Failover groups, through a Clash API that answers from a table."""
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
os.environ["RUNTIME_DIR"] = self.dir
|
||||
self.working = {"warp-1": True, "warp-2": True, "de": True}
|
||||
self.nows = {"warp": "warp-1", "proxy": "warp"}
|
||||
self.calls = []
|
||||
self.clock = [0.0]
|
||||
self.patch("_group_nows", lambda: dict(self.nows))
|
||||
self.watch = ctl.GroupWatch(clash=self.clash, clock=lambda: self.clock[0], wall=lambda: 1000.0)
|
||||
self.inventory = {
|
||||
"url": "https://t",
|
||||
"selection": "first",
|
||||
"disabled": [],
|
||||
"groups": {"warp": {"strategy": "failover", "failback": True, "interval": "30s", "members": ["warp-1", "warp-2"], "pinned": ""}},
|
||||
}
|
||||
|
||||
def clash(self, method, path, body=None, timeout=10):
|
||||
self.calls.append((method, path))
|
||||
if method == "GET" and path.startswith("/proxies/") and "/delay" in path:
|
||||
tag = urllib.parse.unquote(path.split("/")[2])
|
||||
return (200, {"delay": 50}) if self.working.get(tag, True) else (504, None)
|
||||
if method == "PUT":
|
||||
self.nows[urllib.parse.unquote(path.split("/")[2])] = body["name"]
|
||||
return 204, None
|
||||
return 200, {}
|
||||
|
||||
def step(self, seconds=30, hinted=()):
|
||||
self.clock[0] += seconds
|
||||
return self.watch.step(self.inventory, hinted)
|
||||
|
||||
def test_moves_after_two_misses_and_comes_back_after_three_passes(self):
|
||||
self.assertEqual(self.step(0), [])
|
||||
self.working["warp-1"] = False
|
||||
self.assertEqual(self.step(), []) # one miss is not an outage
|
||||
self.assertEqual(self.step(), [("warp", "warp-2")])
|
||||
self.working["warp-1"] = True
|
||||
self.assertEqual(self.step(), [])
|
||||
self.assertEqual(self.step(), [])
|
||||
self.assertEqual(self.step(), [("warp", "warp-1")])
|
||||
|
||||
def test_a_hint_moves_at_once(self):
|
||||
self.step(0)
|
||||
self.working["warp-1"] = False
|
||||
# Not due yet, but a watchdog saw it fail.
|
||||
self.assertEqual(self.step(1, hinted=["warp-1"]), [("warp", "warp-2")])
|
||||
# A hint about a member that still works changes nothing.
|
||||
self.assertEqual(self.step(1, hinted=["warp-2"]), [])
|
||||
|
||||
def test_without_failback_it_stays(self):
|
||||
self.inventory["groups"]["warp"]["failback"] = False
|
||||
self.step(0)
|
||||
self.working["warp-1"] = False
|
||||
self.step(1, hinted=["warp-1"])
|
||||
self.working["warp-1"] = True
|
||||
for _ in range(4):
|
||||
self.assertEqual(self.step(), [])
|
||||
self.assertEqual(self.nows["warp"], "warp-2")
|
||||
|
||||
def test_pins_and_dead_ends_stay_put(self):
|
||||
self.inventory["groups"]["warp"]["pinned"] = "warp-1"
|
||||
self.working["warp-1"] = False
|
||||
self.step(0, hinted=["warp-1"])
|
||||
self.assertEqual(self.nows["warp"], "warp-1")
|
||||
self.inventory["groups"]["warp"]["pinned"] = ""
|
||||
self.working["warp-2"] = False
|
||||
self.step(1, hinted=["warp-2"])
|
||||
self.assertEqual(self.nows["warp"], "warp-1") # nothing works: no flapping
|
||||
|
||||
def test_failover_selection_and_nested_groups(self):
|
||||
self.inventory.update(selection="failover", top=["warp", "de", "tor"], excluded=["tor"])
|
||||
self.assertEqual(list(ctl.GroupWatch.watched(self.inventory)), ["warp", "proxy"])
|
||||
self.assertEqual(ctl.GroupWatch.inner_first({"proxy": {"members": ["warp", "de"]}, "warp": {"members": ["warp-1"]}}), ["warp", "proxy"])
|
||||
self.working["warp"] = False
|
||||
self.step(0, hinted=["warp"])
|
||||
self.assertEqual(self.nows["proxy"], "de")
|
||||
|
||||
def test_urltest_groups_are_only_asked_to_test_again(self):
|
||||
self.inventory["groups"]["warp"]["strategy"] = "urltest"
|
||||
self.step(0)
|
||||
self.assertEqual(self.calls, [])
|
||||
self.step(1, hinted=["warp-1"])
|
||||
self.assertTrue(any(p.startswith("/group/warp/delay") for _, p in self.calls))
|
||||
self.assertFalse(any(m == "PUT" for m, _ in self.calls))
|
||||
|
||||
def test_hint_files(self):
|
||||
health = self.path("proxy-suite-outbound-groups/health")
|
||||
os.makedirs(health)
|
||||
self.assertEqual(self.watch.hints(), [])
|
||||
open(os.path.join(health, "warp-1"), "w").close()
|
||||
self.assertEqual(self.watch.hints(), []) # first sight: there already
|
||||
os.utime(os.path.join(health, "warp-1"), (5, 5))
|
||||
self.assertEqual(self.watch.hints(), ["warp-1"])
|
||||
self.assertEqual(self.watch.hints(), [])
|
||||
|
||||
def test_group_files_and_priority(self):
|
||||
os.environ["RUNTIME_OUTBOUNDS_DIR"] = self.path("obd")
|
||||
os.makedirs(self.path("obd"))
|
||||
inventory = {"tags": ["a", "b", "c"], "top": ["g", "c"], "groups": {"g": {"members": ["a", "b"], "runtime": True}}}
|
||||
self.patch("_outbound_inventory", lambda: inventory)
|
||||
self.patch("_runtime_reload", lambda: None)
|
||||
|
||||
def saved(name):
|
||||
with open(self.path(f"obd/{name}")) as f:
|
||||
return json.load(f)
|
||||
|
||||
run(ctl.cmd_groups, "add", "h", "c", "--strategy", "urltest", "--no-failback")
|
||||
self.assertEqual(saved("h.group"), {"outbounds": ["c"], "subscriptions": [], "match": [], "strategy": "urltest", "failback": False})
|
||||
self.assertIn("cannot hold itself", run(ctl.cmd_groups, "add", "x", "x")[2])
|
||||
# h holds g (as the start script would list it): g cannot take h in.
|
||||
inventory["groups"]["h"] = {"members": ["g"]}
|
||||
self.write("obd/g.group", {"outbounds": ["a", "b"]})
|
||||
self.assertIn("contains 'g'", run(ctl.cmd_groups, "members", "g", "add", "h")[2])
|
||||
# A group's name is taken for outbounds too.
|
||||
self.assertIn("A group named 'g' already exists", run(ctl._check_runtime_tag, "outbound", "g")[2])
|
||||
run(ctl.cmd_priority, "c", "up")
|
||||
self.assertEqual(saved("priority.json"), {"c": 10, "g": 20})
|
||||
run(ctl.cmd_priority, "c", "--clear")
|
||||
self.assertEqual(saved("priority.json"), {"g": 20})
|
||||
|
||||
|
||||
# The verdict table, fed tuples measured on a real censored network.
|
||||
class ProbeVerdictTest(unittest.TestCase):
|
||||
def expect(self, want, direct, via):
|
||||
|
||||
@@ -197,7 +197,13 @@ class ModelTest(unittest.TestCase):
|
||||
def test_a_shared_key_is_a_toggle(self):
|
||||
"""Actions on one key take turns: each needs a row, and no row gets two of them."""
|
||||
rows = {
|
||||
"outbounds": [{"mark": m, "disabled": d} for m in ("", "★") for d in (False, True)],
|
||||
"outbounds": [
|
||||
{"mark": m, "disabled": d, "tag": "a", "group": g, "runtime": rt, "parent": "", "parent_runtime": False}
|
||||
for m in ("", "★")
|
||||
for d in (False, True)
|
||||
for g in (False, True)
|
||||
for rt in (False, True)
|
||||
],
|
||||
"zapret": [{"kind": k} for k in ("learned", "pinned", "excluded")],
|
||||
"autoproxy": [{"kind": k} for k in ("routed", "queued")],
|
||||
}
|
||||
@@ -372,7 +378,7 @@ class ModelTest(unittest.TestCase):
|
||||
self.assertEqual([(r["tag"], r["mark"], r["notes"]) for r in rows], [("a", "▸", "via b"), ("b", "★", "never picked")])
|
||||
self.assertIn("Pinned: b", summary)
|
||||
with mock.patch.object(ctl, "env", lambda name, default="": ""):
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["p", "t", "ctrl+t", "T", "n", "h", "H", "x", "s", "c", "Q", "J", "k", "K", "V"])
|
||||
self.assertEqual([a.key for a in model.applicable(tab, rows[1])], ["p", "t", "ctrl+t", "T", "n", "g", "y", "plus", "minus", "h", "H", "x", "s", "c", "Q", "J", "k", "K", "V"])
|
||||
chain = next(a for a in tab.actions if a.key == "h")
|
||||
self.assertEqual(chain.argv(rows[1], 'c {"type": "socks"}', {}), ["proxy", "outbounds", "add", "c", '{"type": "socks"}', "--detour", "b"])
|
||||
# Probe exits go by the backend's tag.
|
||||
@@ -388,6 +394,52 @@ class ModelTest(unittest.TestCase):
|
||||
rows, _ = model.load_tab(tab, {})
|
||||
self.assertEqual([(r["source"], r["runtime"]) for r in rows], [("runtime", True), ("-", False)])
|
||||
|
||||
def test_outbound_groups_tree(self):
|
||||
"""Members sit under their group, pins inside a group go --in it, and a group folds away."""
|
||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||
inventory = {
|
||||
"tags": ["tor", "warp-1", "warp-2"],
|
||||
"top": ["warp", "tor"],
|
||||
"pinned": "",
|
||||
"excluded": ["tor"],
|
||||
"groups": {"warp": {"strategy": "failover", "members": ["warp-1", "warp-2"], "pinned": "", "runtime": True}},
|
||||
}
|
||||
with (
|
||||
mock.patch.object(ctl, "_outbound_current", lambda: "warp"),
|
||||
mock.patch.object(ctl, "_group_nows", lambda: {"proxy": "warp", "warp": "warp-2"}),
|
||||
mock.patch.object(ctl, "_group_state", lambda: {"members": {"warp-1": {"up": False}}}),
|
||||
mock.patch.object(ctl, "_reputation_by_tag", lambda: {}),
|
||||
mock.patch.object(ctl, "_runtime_tags", lambda kind: []),
|
||||
mock.patch.object(ctl, "_outbound_inventory", lambda: inventory),
|
||||
mock.patch.object(ctl, "env", lambda name, default="": ""),
|
||||
):
|
||||
rows, _ = model.load_tab(tab, {})
|
||||
self.assertEqual(
|
||||
[(r["key"], r["name"], r["mark"], r["source"], r["notes"]) for r in rows],
|
||||
[
|
||||
("warp", "warp", "▸", "group: failover", "using warp-2"),
|
||||
("warp/warp-1", " warp-1", "", "-", "down"),
|
||||
("warp/warp-2", " warp-2", "▸", "-", ""),
|
||||
("tor", "tor", "", "-", "never picked"),
|
||||
],
|
||||
)
|
||||
member = rows[1]
|
||||
pin = next(a for a in model.applicable(tab, member) if a.key == "p")
|
||||
self.assertEqual(pin.argv(member, "", {}), ["proxy", "pin", "warp-1", "--in", "warp"])
|
||||
keys = [a.key for a in model.applicable(tab, member)]
|
||||
self.assertIn("M", keys) # its group was added at runtime: it can be taken out
|
||||
self.assertNotIn("plus", keys) # a group orders its own members
|
||||
group_keys = [a.key for a in model.applicable(tab, rows[0])]
|
||||
for key in ("space", "m", "S", "d", "plus"):
|
||||
self.assertIn(key, group_keys)
|
||||
for key in ("t", "s", "x", "h"):
|
||||
self.assertNotIn(key, group_keys) # an outbound's, not a group's
|
||||
folded = model.fold_rows(rows, {"warp"})
|
||||
self.assertEqual([r["name"] for r in folded], ["▸ warp", "tor"])
|
||||
self.assertEqual([r["name"] for r in model.fold_rows(rows, set())][0], "▾ warp")
|
||||
# A match keeps the group it sits in.
|
||||
self.assertEqual([r["key"] for r in model.filter_rows(rows, tab.columns, "warp-2")], ["warp", "warp/warp-2"])
|
||||
|
||||
def test_disabled_outbound(self):
|
||||
"""Disabled: marked, never offered a pin, and enabled again rather than disabled twice."""
|
||||
tab = next(t for t in model.TABS if t.id == "outbounds")
|
||||
|
||||
Reference in new issue
Block a user