Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
22ebfa171d | ||
|
|
190ba24ce6 | ||
|
|
1f5e050cb2 | ||
|
|
5b5598d12e | ||
|
|
ce86e5669b | ||
|
|
759bde8b29 | ||
|
|
433a13ccad | ||
|
|
f060c4cd5e | ||
|
|
39ce4d6be2 | ||
|
|
377d974a18 | ||
|
|
32bf2266c0 | ||
|
|
334755fd0e | ||
|
|
6025e463a5 | ||
|
|
110e33bc27 | ||
|
|
86e229ff4c | ||
|
|
70c0454446 | ||
|
|
1198a63f3e | ||
|
|
fc95f71292 | ||
|
|
148f2bf2a2 | ||
|
|
bcc64b3a1b | ||
|
|
43935daeb1 | ||
|
|
b696821d8c | ||
|
|
65e815e6dc |
No files matched your search
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 FUFSoB
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
Declarative proxy stack for NixOS.
|
||||
|
||||
Bundles [sing-box](https://github.com/SagerNet/sing-box), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense.
|
||||
Bundles [sing-box](https://github.com/SagerNet/sing-box), [XRay](https://github.com/XTLS/Xray-core), [zapret-discord-youtube](https://github.com/kartavkun/zapret-discord-youtube), and [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy). Built specifically for dealing with Roskomnadzor (RKN) and the usual Russian ISP nonsense.
|
||||
|
||||
The goal is to replace GUI clients like v2rayN and throne – you configure your proxies in Nix, rebuild, and they just work as systemd services.
|
||||
|
||||
@@ -10,14 +10,15 @@ The goal is to replace GUI clients like v2rayN and throne – you configure your
|
||||
|
||||
## What it gives you
|
||||
|
||||
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` by default – always running, always available to apps
|
||||
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box without configuring each app; start/stop on demand or autostart at boot
|
||||
- **SOCKS5/HTTP proxy** on `127.0.0.1:1080` when `proxy.enable = true`
|
||||
- **Backend choice** – use SingBox or XRay through the same `services.proxy-suite.proxy` option tree
|
||||
- **Transparent proxy (TProxy)** – redirect all system traffic through the active backend without configuring each app; start/stop on demand or autostart at boot
|
||||
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something, with optional boot-time autostart
|
||||
- **Per-app wrapping** – run selected apps through the local proxy with `proxy-ctl wrap <profile> -- <command>`, without enabling global TProxy or TUN
|
||||
- **Subscription URLs** – point at a v2rayN/Clash-format subscription endpoint; the module fetches, decodes, and imports all proxies automatically, with a periodic refresh timer
|
||||
- **Multiple outbounds** with automatic latency-based switching or manual selection
|
||||
- **Per-outbound routing** – route specific domains, IPs, or geo sets to specific servers
|
||||
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, TUIC v5, socks5, socks4, http/https proxy
|
||||
- **Protocol support**: vless (Reality, TLS), vmess, trojan, shadowsocks, hysteria2, socks5, socks4, http/https proxy; SingBox also supports TUIC v5, while XRay supports XHTTP/ECH share links
|
||||
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
|
||||
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites defined by the project
|
||||
- **Telegram proxy** – running local MTProto WebSocket proxy using tg-ws-proxy
|
||||
@@ -46,8 +47,12 @@ Feature-complete starter config:
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
|
||||
singBox = {
|
||||
proxy = {
|
||||
enable = true;
|
||||
singBox.enable = true;
|
||||
# Or use XRay instead:
|
||||
# xray.enable = true;
|
||||
|
||||
port = 1080;
|
||||
|
||||
# Individual proxy example
|
||||
@@ -132,9 +137,11 @@ Usage: proxy-ctl <command> [args]
|
||||
Commands:
|
||||
help show this help message
|
||||
status [--tray] show status of all proxy-suite services
|
||||
proxy on|off enable/disable the sing-box proxy stack
|
||||
proxy on|off enable/disable the proxy backend stack
|
||||
tproxy on|off enable/disable TProxy transparent mode
|
||||
tun on|off enable/disable TUN mode
|
||||
route-mode default|whitelist|blacklist|all-proxy|all-bypass|status
|
||||
set temporary routing override
|
||||
zapret on|off enable/disable zapret-discord-youtube
|
||||
restart restart active global proxy-suite services
|
||||
logs [service] follow service logs (default: proxy-suite-socks)
|
||||
@@ -143,6 +150,6 @@ Commands:
|
||||
apps list configured per-app routing profiles
|
||||
wrap <profile> -- <cmd> run a command via a perAppRouting profile
|
||||
subscription list show subscriptions, cache age, and proxy count
|
||||
subscription update force-refresh all subscription caches and restart active sing-box services
|
||||
subscription update force-refresh all subscription caches and restart active proxy services
|
||||
```
|
||||
<!-- proxy-ctl-help:end -->
|
||||
+1271
-352
File diff suppressed because it is too large.
Load diff
Generated
+9
-9
@@ -20,11 +20,11 @@
|
||||
},
|
||||
"nixpkgs": {
|
||||
"locked": {
|
||||
"lastModified": 1775710090,
|
||||
"narHash": "sha256-ar3rofg+awPB8QXDaFJhJ2jJhu+KqN/PRCXeyuXR76E=",
|
||||
"lastModified": 1779560665,
|
||||
"narHash": "sha256-tpyBcxPpcQb8ukyNF7DoCwfSY3VPsxHoYwj00Cayv5o=",
|
||||
"owner": "NixOS",
|
||||
"repo": "nixpkgs",
|
||||
"rev": "4c1018dae018162ec878d42fec712642d214fdfa",
|
||||
"rev": "64c08a7ca051951c8eae34e3e3cb1e202fe36786",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -64,11 +64,11 @@
|
||||
"zapret-flowseal": "zapret-flowseal"
|
||||
},
|
||||
"locked": {
|
||||
"lastModified": 1775231936,
|
||||
"narHash": "sha256-jvyi6D2Ps0zicpIcn24tacIymQOyUVY6lr6B5RLQkx8=",
|
||||
"lastModified": 1780265315,
|
||||
"narHash": "sha256-akozC33JwGQM1S5R5dS2sG/Wsh9k0AVfHgszBySiY/o=",
|
||||
"owner": "kartavkun",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"rev": "b3e3f854f8d9cf35ddbcbfa7a03cb0a1334dd7eb",
|
||||
"rev": "9d8c3110075117a7d9c0f73395fc3eafa6b76222",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
@@ -80,11 +80,11 @@
|
||||
"zapret-flowseal": {
|
||||
"flake": false,
|
||||
"locked": {
|
||||
"lastModified": 1775228068,
|
||||
"narHash": "sha256-LAbCZRwoGxQcgO1nio33NlxBXIdsTQJxHQxu1RWctIA=",
|
||||
"lastModified": 1780149029,
|
||||
"narHash": "sha256-mXBl6jYku2zXaiSlzzmf1WhhsDYKEvqltLlebxU6kgA=",
|
||||
"owner": "Flowseal",
|
||||
"repo": "zapret-discord-youtube",
|
||||
"rev": "22a9ca3bc067441789c83bd80c00d38e54be51c4",
|
||||
"rev": "7e9b42a00b4c1c3bb5370401b9befcb8565b3ac6",
|
||||
"type": "github"
|
||||
},
|
||||
"original": {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
description = "NixOS proxy suite – sing-box, zapret, tg-ws-proxy";
|
||||
description = "NixOS proxy suite - SingBox, XRay, zapret, tg-ws-proxy";
|
||||
|
||||
inputs = {
|
||||
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||
|
||||
+347
-38
@@ -1,5 +1,5 @@
|
||||
# Build-time sing-box configuration templates.
|
||||
# The proxy outbound(s) are injected at service start time, not here.
|
||||
# Build-time proxy backend configuration templates.
|
||||
# Proxy outbounds are injected at service start time, not here.
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
@@ -10,15 +10,32 @@
|
||||
let
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
inherit (derived)
|
||||
proxyCfg
|
||||
singBoxCfg
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
globalTun
|
||||
globalTproxy
|
||||
clashApiEnabled
|
||||
;
|
||||
perAppTun = derived.perAppRoutingTun;
|
||||
direct = rules.direct;
|
||||
xrayGlobalTunIPv6Address = "fd66:19::1/64";
|
||||
xrayPerAppTunIPv6Address = "fd66:20::1/64";
|
||||
xrayFakeDnsPools = [
|
||||
{
|
||||
ipPool = "198.18.0.0/15";
|
||||
poolSize = 32768;
|
||||
}
|
||||
{
|
||||
ipPool = "fc00::/18";
|
||||
poolSize = 32768;
|
||||
}
|
||||
];
|
||||
stripCidr = cidr: builtins.head (lib.splitString "/" cidr);
|
||||
|
||||
mkDnsServer =
|
||||
mkSingBoxDnsServer =
|
||||
tag: upstream: detour:
|
||||
{
|
||||
inherit tag;
|
||||
@@ -28,17 +45,17 @@ let
|
||||
}
|
||||
// lib.optionalAttrs (detour != null) { inherit detour; };
|
||||
|
||||
mkDnsConfig =
|
||||
mkSingBoxDnsConfig =
|
||||
{
|
||||
localDetour ? null,
|
||||
}:
|
||||
{
|
||||
servers = [
|
||||
(mkDnsServer "remote" singBoxCfg.dns.remote "proxy")
|
||||
(mkDnsServer "local" singBoxCfg.dns.local localDetour)
|
||||
(mkSingBoxDnsServer "remote" proxyCfg.dns.remote "proxy")
|
||||
(mkSingBoxDnsServer "local" proxyCfg.dns.local localDetour)
|
||||
];
|
||||
rules =
|
||||
lib.optional (builtins.elem "google" singBoxCfg.routing.proxy.geosites) {
|
||||
lib.optional (builtins.elem "google" proxyCfg.routing.proxy.geosites) {
|
||||
rule_set = [ "geosite-google" ];
|
||||
server = "remote";
|
||||
}
|
||||
@@ -46,9 +63,18 @@ let
|
||||
rule_set = map (s: "geosite-${s}") direct.geosites;
|
||||
server = "local";
|
||||
};
|
||||
final = if singBoxCfg.proxyByDefault then "remote" else "local";
|
||||
final = if proxyCfg.proxyByDefault then "remote" else "local";
|
||||
};
|
||||
|
||||
xrayDnsBridgeHijackRule = {
|
||||
inbound = [ "xray-dns-in" ];
|
||||
network = [
|
||||
"tcp"
|
||||
"udp"
|
||||
];
|
||||
action = "hijack-dns";
|
||||
};
|
||||
|
||||
clashApiBlock = lib.optionalAttrs clashApiEnabled {
|
||||
experimental = {
|
||||
clash_api = {
|
||||
@@ -57,7 +83,7 @@ let
|
||||
};
|
||||
};
|
||||
|
||||
mkConfig =
|
||||
mkSingBoxConfig =
|
||||
{
|
||||
enableMixed ? false,
|
||||
enableTProxy ? false,
|
||||
@@ -66,28 +92,35 @@ let
|
||||
tunAddress ? globalTun.address,
|
||||
tunMtu ? globalTun.mtu,
|
||||
tunAutoRoute ? true,
|
||||
tunAutoRouteTableIndex ? 2022,
|
||||
tunAutoRouteRuleIndex ? 9000,
|
||||
tunAutoRedirect ? true,
|
||||
tunStrictRoute ? true,
|
||||
forceLocalDnsViaProxy ? false,
|
||||
useOutboundRoutingMark ? false,
|
||||
enableClashApi ? clashApiEnabled,
|
||||
enableXrayDnsBridge ? hybridEnabled,
|
||||
xrayDnsBridgePort ? 18533,
|
||||
}:
|
||||
{
|
||||
log.level = "warn";
|
||||
|
||||
# Keep "local" DNS on the direct path by default, but avoid explicit
|
||||
# detour="direct" because sing-box rejects detouring to an empty
|
||||
# direct outbound. Global TUN can force local DNS through proxy.
|
||||
dns = mkDnsConfig {
|
||||
dns = mkSingBoxDnsConfig {
|
||||
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
|
||||
};
|
||||
|
||||
inbounds =
|
||||
lib.optional enableMixed {
|
||||
lib.optional enableXrayDnsBridge {
|
||||
type = "direct";
|
||||
tag = "xray-dns-in";
|
||||
listen = "127.0.0.1";
|
||||
listen_port = xrayDnsBridgePort;
|
||||
}
|
||||
++ lib.optional enableMixed {
|
||||
type = "mixed";
|
||||
tag = "mixed-in";
|
||||
listen = singBoxCfg.listenAddress;
|
||||
listen_port = singBoxCfg.port;
|
||||
listen = proxyCfg.listenAddress;
|
||||
listen_port = proxyCfg.port;
|
||||
}
|
||||
++ lib.optional enableTProxy {
|
||||
type = "tproxy";
|
||||
@@ -95,19 +128,24 @@ let
|
||||
listen = "127.0.0.1";
|
||||
listen_port = globalTproxy.port;
|
||||
}
|
||||
++ lib.optional enableTun {
|
||||
type = "tun";
|
||||
tag = "tun-in";
|
||||
interface_name = tunInterface;
|
||||
address = [ tunAddress ];
|
||||
mtu = tunMtu;
|
||||
auto_route = tunAutoRoute;
|
||||
auto_redirect = tunAutoRedirect;
|
||||
strict_route = tunStrictRoute;
|
||||
stack = "mixed";
|
||||
};
|
||||
++ lib.optional enableTun (
|
||||
{
|
||||
type = "tun";
|
||||
tag = "tun-in";
|
||||
interface_name = tunInterface;
|
||||
address = [ tunAddress ];
|
||||
mtu = tunMtu;
|
||||
auto_route = tunAutoRoute;
|
||||
auto_redirect = tunAutoRedirect;
|
||||
strict_route = tunStrictRoute;
|
||||
stack = "mixed";
|
||||
}
|
||||
// lib.optionalAttrs tunAutoRoute {
|
||||
iproute2_table_index = tunAutoRouteTableIndex;
|
||||
iproute2_rule_index = tunAutoRouteRuleIndex;
|
||||
}
|
||||
);
|
||||
|
||||
# proxy outbound(s) are prepended at runtime by the start script
|
||||
outbounds = [
|
||||
(
|
||||
{
|
||||
@@ -125,20 +163,252 @@ let
|
||||
route = {
|
||||
default_domain_resolver = "local";
|
||||
rule_set = rules.geositeRuleSets ++ rules.geoIPRuleSets;
|
||||
rules = rules.routingRules;
|
||||
final = if singBoxCfg.proxyByDefault then "proxy" else "direct";
|
||||
rules = lib.optionals enableXrayDnsBridge [ xrayDnsBridgeHijackRule ] ++ rules.singBoxRoutingRules;
|
||||
final = if proxyCfg.proxyByDefault then "proxy" else "direct";
|
||||
}
|
||||
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
|
||||
// lib.optionalAttrs (enableTun && tunAutoRoute) {
|
||||
auto_detect_interface = true;
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs enableClashApi clashApiBlock;
|
||||
|
||||
tproxyTemplate = mkConfig {
|
||||
xrayDnsAddress =
|
||||
upstream: if upstream.type == "tcp" then "tcp://${upstream.address}" else upstream.address;
|
||||
|
||||
mkXrayDnsServer = tag: upstream: {
|
||||
address = xrayDnsAddress upstream;
|
||||
inherit tag;
|
||||
port = upstream.port;
|
||||
queryStrategy = "UseIP";
|
||||
};
|
||||
|
||||
mkXraySniffing =
|
||||
{
|
||||
fakeDnsOnly ? false,
|
||||
}:
|
||||
if fakeDnsOnly then
|
||||
{
|
||||
enabled = true;
|
||||
destOverride = [ "fakedns" ];
|
||||
metadataOnly = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
enabled = true;
|
||||
destOverride = [
|
||||
"http"
|
||||
"tls"
|
||||
"quic"
|
||||
];
|
||||
};
|
||||
|
||||
xraySniffing = mkXraySniffing { };
|
||||
|
||||
mkXrayTunDnsConfig =
|
||||
{
|
||||
preferRemote ? proxyCfg.proxyByDefault,
|
||||
}:
|
||||
let
|
||||
primaryTag = if preferRemote then "remote" else "local";
|
||||
secondaryTag = if preferRemote then "local" else "remote";
|
||||
primaryUpstream = if preferRemote then proxyCfg.dns.remote else proxyCfg.dns.local;
|
||||
secondaryUpstream = if preferRemote then proxyCfg.dns.local else proxyCfg.dns.remote;
|
||||
in
|
||||
{
|
||||
queryStrategy = "UseIP";
|
||||
tag = "dns-in";
|
||||
servers = [
|
||||
{
|
||||
address = "fakedns";
|
||||
tag = "fakedns";
|
||||
}
|
||||
(mkXrayDnsServer primaryTag primaryUpstream)
|
||||
(mkXrayDnsServer secondaryTag secondaryUpstream)
|
||||
];
|
||||
};
|
||||
|
||||
xrayTunDnsHijackRule = {
|
||||
type = "field";
|
||||
inboundTag = [ "tun-in" ];
|
||||
network = "tcp,udp";
|
||||
port = 53;
|
||||
outboundTag = "dns-out";
|
||||
ruleTag = "dns-hijack";
|
||||
};
|
||||
|
||||
xrayTunDnsUpstreamRule = {
|
||||
type = "field";
|
||||
inboundTag = [ "dns-in" ];
|
||||
network = "tcp,udp";
|
||||
outboundTag = "direct";
|
||||
ruleTag = "dns-upstream-direct";
|
||||
};
|
||||
|
||||
xrayFinalRule =
|
||||
tag:
|
||||
{
|
||||
type = "field";
|
||||
network = "tcp,udp";
|
||||
ruleTag = "final-default";
|
||||
}
|
||||
// (
|
||||
if tag == "proxy" && proxyCfg.selection == "urltest" then
|
||||
{ balancerTag = "proxy"; }
|
||||
else
|
||||
{ outboundTag = tag; }
|
||||
);
|
||||
|
||||
xrayRouteRules = rules.xrayRoutingRules ++ [
|
||||
(xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct"))
|
||||
];
|
||||
|
||||
xrayDirectOutbound =
|
||||
useOutboundRoutingMark:
|
||||
{
|
||||
protocol = "freedom";
|
||||
tag = "direct";
|
||||
settings = { };
|
||||
}
|
||||
// lib.optionalAttrs useOutboundRoutingMark {
|
||||
streamSettings.sockopt.mark = globalTproxy.proxyMark;
|
||||
};
|
||||
|
||||
mkXrayConfig =
|
||||
{
|
||||
enableMixed ? false,
|
||||
enableTProxy ? false,
|
||||
enableTun ? false,
|
||||
tunInterface ? globalTun.interface,
|
||||
tunAddress ? globalTun.address,
|
||||
tunIPv6Address ? null,
|
||||
tunMtu ? globalTun.mtu,
|
||||
useOutboundRoutingMark ? false,
|
||||
enableUrlTest ? proxyCfg.selection == "urltest",
|
||||
domainStrategy ? "IPIfNonMatch",
|
||||
enableTunFakeDns ? false,
|
||||
}:
|
||||
let
|
||||
tunDnsServers = [
|
||||
(if proxyCfg.proxyByDefault then proxyCfg.dns.remote.address else proxyCfg.dns.local.address)
|
||||
(if proxyCfg.proxyByDefault then proxyCfg.dns.local.address else proxyCfg.dns.remote.address)
|
||||
];
|
||||
xrayTunSniffing = mkXraySniffing { fakeDnsOnly = enableTunFakeDns; };
|
||||
xrayDnsConfig =
|
||||
if enableTunFakeDns then
|
||||
mkXrayTunDnsConfig { }
|
||||
else
|
||||
{
|
||||
servers = [
|
||||
(mkXrayDnsServer "remote" proxyCfg.dns.remote)
|
||||
(mkXrayDnsServer "local" proxyCfg.dns.local)
|
||||
];
|
||||
};
|
||||
xrayTunOutbounds = lib.optionals enableTunFakeDns [
|
||||
{
|
||||
protocol = "dns";
|
||||
tag = "dns-out";
|
||||
settings = {
|
||||
userLevel = 0;
|
||||
rules = [
|
||||
{
|
||||
action = "direct";
|
||||
qType = "2-27,29-65535";
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
];
|
||||
xrayRoutingRules =
|
||||
lib.optionals enableTunFakeDns [
|
||||
xrayTunDnsUpstreamRule
|
||||
xrayTunDnsHijackRule
|
||||
]
|
||||
++ rules.xrayRoutingRules
|
||||
++ [ (xrayFinalRule (if proxyCfg.proxyByDefault then "proxy" else "direct")) ];
|
||||
in
|
||||
{
|
||||
log.loglevel = "warning";
|
||||
dns = xrayDnsConfig;
|
||||
inbounds =
|
||||
lib.optional enableMixed {
|
||||
tag = "mixed-in";
|
||||
protocol = "socks";
|
||||
listen = proxyCfg.listenAddress;
|
||||
port = proxyCfg.port;
|
||||
settings = {
|
||||
auth = "noauth";
|
||||
udp = true;
|
||||
ip = proxyCfg.listenAddress;
|
||||
};
|
||||
sniffing = xraySniffing;
|
||||
}
|
||||
++ lib.optional enableTProxy {
|
||||
tag = "tproxy-in";
|
||||
protocol = "tunnel";
|
||||
listen = "127.0.0.1";
|
||||
port = globalTproxy.port;
|
||||
settings = {
|
||||
allowedNetwork = "tcp,udp";
|
||||
followRedirect = true;
|
||||
};
|
||||
streamSettings.sockopt.tproxy = "tproxy";
|
||||
sniffing = xraySniffing;
|
||||
}
|
||||
++ lib.optional enableTun {
|
||||
tag = "tun-in";
|
||||
protocol = "tun";
|
||||
settings = {
|
||||
name = tunInterface;
|
||||
mtu = tunMtu;
|
||||
gateway = [ tunAddress ] ++ lib.optionals (tunIPv6Address != null) [ tunIPv6Address ];
|
||||
dns = tunDnsServers;
|
||||
userLevel = 0;
|
||||
autoOutboundsInterface = "auto";
|
||||
};
|
||||
sniffing = xrayTunSniffing;
|
||||
};
|
||||
outbounds = xrayTunOutbounds ++ [
|
||||
(xrayDirectOutbound useOutboundRoutingMark)
|
||||
{
|
||||
protocol = "blackhole";
|
||||
tag = "block";
|
||||
settings = { };
|
||||
}
|
||||
];
|
||||
routing = {
|
||||
domainStrategy = domainStrategy;
|
||||
domainMatcher = "hybrid";
|
||||
rules = xrayRoutingRules;
|
||||
}
|
||||
// lib.optionalAttrs enableUrlTest {
|
||||
balancers = [
|
||||
{
|
||||
tag = "proxy";
|
||||
selector = [ "proxy-suite-ob-" ];
|
||||
strategy = {
|
||||
type = "leastPing";
|
||||
};
|
||||
}
|
||||
];
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs enableUrlTest {
|
||||
observatory = {
|
||||
subjectSelector = [ "proxy-suite-ob-" ];
|
||||
probeUrl = proxyCfg.urlTest.url;
|
||||
probeInterval = proxyCfg.urlTest.interval;
|
||||
};
|
||||
}
|
||||
// lib.optionalAttrs enableTunFakeDns { fakedns = xrayFakeDnsPools; };
|
||||
|
||||
singBoxTproxyTemplate = mkSingBoxConfig {
|
||||
enableMixed = true;
|
||||
enableTProxy = true;
|
||||
useOutboundRoutingMark = true;
|
||||
xrayDnsBridgePort = 18533;
|
||||
};
|
||||
|
||||
tunTemplate = mkConfig {
|
||||
singBoxTunTemplate = mkSingBoxConfig {
|
||||
enableTun = true;
|
||||
tunInterface = globalTun.interface;
|
||||
tunAddress = globalTun.address;
|
||||
@@ -146,11 +416,12 @@ let
|
||||
tunAutoRoute = true;
|
||||
tunAutoRedirect = true;
|
||||
tunStrictRoute = true;
|
||||
forceLocalDnsViaProxy = true;
|
||||
forceLocalDnsViaProxy = false;
|
||||
enableClashApi = false;
|
||||
xrayDnsBridgePort = 18534;
|
||||
};
|
||||
|
||||
perAppTunTemplate = mkConfig {
|
||||
singBoxPerAppTunTemplate = mkSingBoxConfig {
|
||||
enableTun = true;
|
||||
tunInterface = perAppTun.interface;
|
||||
tunAddress = perAppTun.address;
|
||||
@@ -159,19 +430,57 @@ let
|
||||
tunAutoRedirect = false;
|
||||
tunStrictRoute = false;
|
||||
forceLocalDnsViaProxy = false;
|
||||
# App TUN can be used alongside TProxy; mark direct egress so TProxy output
|
||||
# rules do not re-intercept sing-box's own packets.
|
||||
useOutboundRoutingMark = globalTproxy.enable;
|
||||
enableClashApi = false;
|
||||
xrayDnsBridgePort = 18535;
|
||||
};
|
||||
|
||||
xrayTproxyTemplate = mkXrayConfig {
|
||||
enableMixed = true;
|
||||
enableTProxy = true;
|
||||
useOutboundRoutingMark = true;
|
||||
};
|
||||
|
||||
xrayTunTemplate = mkXrayConfig {
|
||||
enableTun = true;
|
||||
tunInterface = globalTun.interface;
|
||||
tunAddress = globalTun.address;
|
||||
tunIPv6Address = xrayGlobalTunIPv6Address;
|
||||
tunMtu = globalTun.mtu;
|
||||
useOutboundRoutingMark = true;
|
||||
enableTunFakeDns = true;
|
||||
};
|
||||
|
||||
xrayPerAppTunTemplate = mkXrayConfig {
|
||||
enableTun = true;
|
||||
tunInterface = perAppTun.interface;
|
||||
tunAddress = perAppTun.address;
|
||||
tunIPv6Address = xrayPerAppTunIPv6Address;
|
||||
tunMtu = perAppTun.mtu;
|
||||
useOutboundRoutingMark = true;
|
||||
enableTunFakeDns = true;
|
||||
};
|
||||
|
||||
tproxyTemplate = if pureXrayEnabled then xrayTproxyTemplate else singBoxTproxyTemplate;
|
||||
tunTemplate = if pureXrayEnabled then xrayTunTemplate else singBoxTunTemplate;
|
||||
perAppTunTemplate = if pureXrayEnabled then xrayPerAppTunTemplate else singBoxPerAppTunTemplate;
|
||||
routeModeRules = if pureXrayEnabled then rules.xrayRouteModeRules else rules.singBoxRouteModeRules;
|
||||
|
||||
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
|
||||
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
|
||||
perAppTunFile = pkgs.writeText "proxy-suite-per-app-tun-template.json" (
|
||||
builtins.toJSON perAppTunTemplate
|
||||
);
|
||||
routeModeRulesFile = pkgs.writeText "proxy-suite-route-mode-rules.json" (
|
||||
builtins.toJSON routeModeRules
|
||||
);
|
||||
|
||||
in
|
||||
{
|
||||
inherit tproxyFile tunFile perAppTunFile;
|
||||
inherit
|
||||
tproxyFile
|
||||
tunFile
|
||||
perAppTunFile
|
||||
routeModeRulesFile
|
||||
;
|
||||
}
|
||||
@@ -47,7 +47,7 @@ in
|
||||
packages
|
||||
cfg
|
||||
;
|
||||
inherit (configs) tproxyFile tunFile perAppTunFile;
|
||||
inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile;
|
||||
inherit (nftr)
|
||||
nftablesRulesFile
|
||||
perAppTproxyRulesFile
|
||||
@@ -58,7 +58,7 @@ in
|
||||
;
|
||||
})
|
||||
|
||||
(lib.mkIf cfg.zapret.enable (
|
||||
(lib.mkIf (cfg.zapret.enable || cfg.zapret.perApp.enable) (
|
||||
import ./zapret.nix {
|
||||
inherit
|
||||
lib
|
||||
|
||||
@@ -4,42 +4,75 @@
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
proxyCfg = cfg.proxy;
|
||||
singBoxCfg = proxyCfg // {
|
||||
enable = proxyCfg.enable && proxyCfg.singBox.enable;
|
||||
package = proxyCfg.singBox.package;
|
||||
clashApiPort = proxyCfg.singBox.clashApiPort;
|
||||
urlTest = proxyCfg.urlTest // {
|
||||
tolerance = proxyCfg.singBox.urlTest.tolerance;
|
||||
};
|
||||
};
|
||||
xrayCfg = proxyCfg.xray;
|
||||
proxyEnabled = proxyCfg.enable;
|
||||
singBoxEnabled = proxyCfg.enable && proxyCfg.singBox.enable;
|
||||
xrayEnabled = proxyCfg.enable && proxyCfg.xray.enable;
|
||||
hybridEnabled = singBoxEnabled && xrayEnabled;
|
||||
pureSingBoxEnabled = singBoxEnabled && !xrayEnabled;
|
||||
pureXrayEnabled = xrayEnabled && !singBoxEnabled;
|
||||
activeBackend =
|
||||
if hybridEnabled then
|
||||
"hybrid"
|
||||
else if pureXrayEnabled then
|
||||
"xray"
|
||||
else if pureSingBoxEnabled then
|
||||
"sing-box"
|
||||
else
|
||||
null;
|
||||
perAppRoutingCfg = cfg.perAppRouting;
|
||||
globalTun = singBoxCfg.tun;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppRoutingTun = singBoxCfg.tun.perApp;
|
||||
perAppRoutingTproxy = singBoxCfg.tproxy.perApp;
|
||||
globalTun = proxyCfg.tun;
|
||||
globalTproxy = proxyCfg.tproxy;
|
||||
perAppRoutingTun = proxyCfg.tun.perApp;
|
||||
perAppRoutingTproxy = proxyCfg.tproxy.perApp;
|
||||
perAppZapretCfg = cfg.zapret.perApp;
|
||||
userControlCfg = cfg.userControl;
|
||||
|
||||
selectionMode = singBoxCfg.selection;
|
||||
selectionMode = proxyCfg.selection;
|
||||
builtinTags = [
|
||||
"proxy"
|
||||
"direct"
|
||||
"block"
|
||||
];
|
||||
outboundTags = map (ob: ob.tag) singBoxCfg.outbounds;
|
||||
subscriptionTags = map (sub: sub.tag) singBoxCfg.subscriptions;
|
||||
outboundTags = map (ob: ob.tag) proxyCfg.outbounds;
|
||||
subscriptionTags = map (sub: sub.tag) proxyCfg.subscriptions;
|
||||
|
||||
hasStaticOutbounds = singBoxCfg.outbounds != [ ];
|
||||
hasSubscriptions = singBoxCfg.subscriptions != [ ];
|
||||
hasStaticOutbounds = proxyCfg.outbounds != [ ];
|
||||
hasSubscriptions = proxyCfg.subscriptions != [ ];
|
||||
collapseNamedOutbounds = selectionMode == "first";
|
||||
clashApiEnabled = selectionMode != "first";
|
||||
perAppZapretEnabled = cfg.zapret.enable && perAppZapretCfg.enable;
|
||||
clashApiEnabled = (singBoxEnabled || hybridEnabled) && selectionMode != "first";
|
||||
perAppZapretEnabled = perAppZapretCfg.enable;
|
||||
userControlEnabled = userControlCfg.global.enable || userControlCfg.perApp.enable;
|
||||
|
||||
invalidRoutingTargets = lib.unique (
|
||||
map (rule: rule.outbound) (
|
||||
builtins.filter (
|
||||
rule: !builtins.elem rule.outbound (builtinTags ++ outboundTags)
|
||||
) singBoxCfg.routing.rules
|
||||
) proxyCfg.routing.rules
|
||||
)
|
||||
);
|
||||
in
|
||||
{
|
||||
inherit
|
||||
proxyCfg
|
||||
singBoxCfg
|
||||
xrayCfg
|
||||
proxyEnabled
|
||||
singBoxEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureSingBoxEnabled
|
||||
pureXrayEnabled
|
||||
activeBackend
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
|
||||
@@ -6,11 +6,16 @@
|
||||
}:
|
||||
|
||||
let
|
||||
singBoxCfg = cfg.singBox;
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
perAppTun = singBoxCfg.tun.perApp;
|
||||
perAppTproxy = singBoxCfg.tproxy.perApp;
|
||||
proxyCfg = cfg.proxy;
|
||||
globalTproxy = proxyCfg.tproxy;
|
||||
perAppTun = proxyCfg.tun.perApp;
|
||||
perAppTproxy = proxyCfg.tproxy.perApp;
|
||||
zapretApp = cfg.zapret.perApp;
|
||||
tgWsProxyCfg = cfg.tgWsProxy;
|
||||
tgWsProxyBypassEnabled = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
|
||||
tgWsProxyBypassMarkLine = lib.optionalString tgWsProxyBypassEnabled ''
|
||||
meta mark ${toString tgWsProxyCfg.routingMark} return
|
||||
'';
|
||||
|
||||
# Shared across all three nftables rule files that do IPv4 routing.
|
||||
reservedIpBlock = ''
|
||||
@@ -55,7 +60,7 @@ let
|
||||
ip daddr $RESERVED_IP return
|
||||
${tproxyLocalSubnetLines}
|
||||
meta mark ${toString globalTproxy.proxyMark} return
|
||||
${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
|
||||
${tgWsProxyBypassMarkLine}${lib.optionalString perAppTun.enable " meta mark ${toString perAppTun.fwmark} return\n"}${lib.optionalString perAppTproxy.enable " meta mark ${toString perAppTproxy.fwmark} return\n"} ip protocol tcp meta mark set ${toString globalTproxy.fwmark}
|
||||
ip protocol udp meta mark set ${toString globalTproxy.fwmark}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
{
|
||||
imports = [
|
||||
./other.nix
|
||||
./legacy-sing-box.nix
|
||||
./sing-box.nix
|
||||
./sing-box-outbounds.nix
|
||||
./sing-box-dns.nix
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
{ lib, config, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkIf mkOption types;
|
||||
cfg = config.services.proxy-suite;
|
||||
legacy = cfg.singBox or { };
|
||||
legacyUsed = legacy != { };
|
||||
|
||||
has = name: builtins.hasAttr name legacy;
|
||||
hasNested = path: lib.hasAttrByPath path legacy;
|
||||
getNested = path: lib.getAttrFromPath path legacy;
|
||||
setIf = condition: value: lib.optionalAttrs condition value;
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox = mkOption {
|
||||
type = types.submodule {
|
||||
freeformType = types.anything;
|
||||
};
|
||||
default = { };
|
||||
visible = false;
|
||||
description = ''
|
||||
Deprecated compatibility tree for the old services.proxy-suite.singBox
|
||||
options. Use services.proxy-suite.proxy instead.
|
||||
'';
|
||||
};
|
||||
|
||||
config = mkIf legacyUsed {
|
||||
warnings = [
|
||||
''
|
||||
services.proxy-suite.singBox is deprecated. Move shared options to
|
||||
services.proxy-suite.proxy and SingBox-specific options to
|
||||
services.proxy-suite.proxy.singBox.
|
||||
''
|
||||
];
|
||||
|
||||
services.proxy-suite.proxy = lib.mkMerge [
|
||||
(setIf (!has "enable") {
|
||||
enable = lib.mkDefault true;
|
||||
singBox.enable = lib.mkDefault true;
|
||||
})
|
||||
(setIf (has "enable") {
|
||||
enable = lib.mkDefault legacy.enable;
|
||||
singBox.enable = lib.mkDefault legacy.enable;
|
||||
})
|
||||
(setIf (has "listenAddress") { listenAddress = lib.mkDefault legacy.listenAddress; })
|
||||
(setIf (has "port") { port = lib.mkDefault legacy.port; })
|
||||
(setIf (has "auth") { auth = lib.mkDefault legacy.auth; })
|
||||
(setIf (has "proxyByDefault") { proxyByDefault = lib.mkDefault legacy.proxyByDefault; })
|
||||
(setIf (has "outbounds") { outbounds = lib.mkDefault legacy.outbounds; })
|
||||
(setIf (has "subscriptions") { subscriptions = lib.mkDefault legacy.subscriptions; })
|
||||
(setIf (has "subscriptionUpdateInterval") {
|
||||
subscriptionUpdateInterval = lib.mkDefault legacy.subscriptionUpdateInterval;
|
||||
})
|
||||
(setIf (has "selection") { selection = lib.mkDefault legacy.selection; })
|
||||
(setIf (has "dns") { dns = lib.mkDefault legacy.dns; })
|
||||
(setIf (has "routing") { routing = lib.mkDefault legacy.routing; })
|
||||
(setIf (has "tun") { tun = lib.mkDefault legacy.tun; })
|
||||
(setIf (has "tproxy") { tproxy = lib.mkDefault legacy.tproxy; })
|
||||
(setIf (hasNested [ "urlTest" "url" ]) {
|
||||
urlTest.url = lib.mkDefault (getNested [ "urlTest" "url" ]);
|
||||
})
|
||||
(setIf (hasNested [ "urlTest" "interval" ]) {
|
||||
urlTest.interval = lib.mkDefault (getNested [ "urlTest" "interval" ]);
|
||||
})
|
||||
(setIf (hasNested [ "urlTest" "tolerance" ]) {
|
||||
singBox.urlTest.tolerance = lib.mkDefault (getNested [ "urlTest" "tolerance" ]);
|
||||
})
|
||||
(setIf (has "package") { singBox.package = lib.mkDefault legacy.package; })
|
||||
(setIf (has "clashApiPort") { singBox.clashApiPort = lib.mkDefault legacy.clashApiPort; })
|
||||
];
|
||||
};
|
||||
}
|
||||
@@ -6,7 +6,7 @@ let
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite = {
|
||||
enable = mkEnableOption "proxy suite (sing-box + zapret + tg-ws-proxy)";
|
||||
enable = mkEnableOption "proxy suite (proxy backend + zapret + tg-ws-proxy)";
|
||||
|
||||
userControl = {
|
||||
group = mkOption {
|
||||
@@ -130,6 +130,155 @@ in
|
||||
"203" = "149.154.167.220";
|
||||
};
|
||||
};
|
||||
|
||||
verbose = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Whether to enable debug logging in tg-ws-proxy.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
logFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
Optional path where tg-ws-proxy writes rotating logs.
|
||||
When unset, tg-ws-proxy logs to stderr only.
|
||||
'';
|
||||
example = "/var/log/tg-ws-proxy.log";
|
||||
};
|
||||
|
||||
logMaxMb = mkOption {
|
||||
type = types.numbers.positive;
|
||||
default = 5.0;
|
||||
description = ''
|
||||
Maximum tg-ws-proxy log file size in MiB before rotation.
|
||||
Only used when tgWsProxy.logFile is set.
|
||||
'';
|
||||
example = 10.0;
|
||||
};
|
||||
|
||||
logBackups = mkOption {
|
||||
type = types.ints.positive;
|
||||
default = 1;
|
||||
description = ''
|
||||
Number of rotated tg-ws-proxy log files to keep.
|
||||
Only used when tgWsProxy.logFile is set.
|
||||
'';
|
||||
example = 3;
|
||||
};
|
||||
|
||||
bufKb = mkOption {
|
||||
type = types.ints.between 4 2147483647;
|
||||
default = 256;
|
||||
description = ''
|
||||
Socket send and receive buffer size for tg-ws-proxy, in KiB.
|
||||
'';
|
||||
example = 512;
|
||||
};
|
||||
|
||||
poolSize = mkOption {
|
||||
type = types.ints.unsigned;
|
||||
default = 4;
|
||||
description = ''
|
||||
WebSocket connection pool size per Telegram DC.
|
||||
Set to 0 to disable connection pooling.
|
||||
'';
|
||||
example = 8;
|
||||
};
|
||||
|
||||
cfProxyDomains = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = ''
|
||||
User-defined Cloudflare-proxied domains used by tg-ws-proxy for
|
||||
WebSocket fallback. Each entry is passed as a separate
|
||||
--cfproxy-domain argument.
|
||||
'';
|
||||
example = [
|
||||
"cdn.example.com"
|
||||
"edge.example.net"
|
||||
];
|
||||
};
|
||||
|
||||
cfProxyWorkerDomains = mkOption {
|
||||
type = types.listOf types.str;
|
||||
default = [ ];
|
||||
description = ''
|
||||
Cloudflare Worker domains used by tg-ws-proxy for WebSocket fallback.
|
||||
These are tried before other fallback methods.
|
||||
'';
|
||||
example = [ "worker.example.com" ];
|
||||
};
|
||||
|
||||
cfProxyFallback = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether to allow tg-ws-proxy to use Cloudflare proxy fallback when
|
||||
direct WebSocket routing is unavailable.
|
||||
'';
|
||||
example = false;
|
||||
};
|
||||
|
||||
fakeTlsDomain = mkOption {
|
||||
type = types.nullOr (types.strMatching ".+");
|
||||
default = null;
|
||||
description = ''
|
||||
Optional SNI domain used to enable tg-ws-proxy Fake TLS masking.
|
||||
When set, tg-ws-proxy emits an ee-secret connection link.
|
||||
'';
|
||||
example = "www.example.com";
|
||||
};
|
||||
|
||||
proxyProtocol = mkOption {
|
||||
type = types.bool;
|
||||
default = false;
|
||||
description = ''
|
||||
Whether tg-ws-proxy should accept a PROXY protocol v1 header from a
|
||||
fronting reverse proxy such as nginx or HAProxy.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
wsKeepalive = mkOption {
|
||||
type = types.numbers.nonnegative;
|
||||
default = 30.0;
|
||||
description = ''
|
||||
Seconds between upstream WebSocket keepalive pings.
|
||||
Set to 0 to disable keepalive pings.
|
||||
'';
|
||||
example = 15.0;
|
||||
};
|
||||
|
||||
bypassTransparentProxy = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether to keep tg-ws-proxy's own relay connections out of proxy-suite
|
||||
transparent routing backends.
|
||||
|
||||
When enabled and global TUN or TProxy mode is configured, the
|
||||
tg-ws-proxy systemd service receives a packet mark and an earlier
|
||||
policy-routing rule back to the main table. This prevents global TUN
|
||||
from routing the local Telegram MTProto relay through the proxy backend again,
|
||||
which can otherwise break tg-ws-proxy after enabling TUN mode.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
routingMark = mkOption {
|
||||
type = types.int;
|
||||
default = 4;
|
||||
description = ''
|
||||
Packet mark used by tgWsProxy.bypassTransparentProxy to bypass
|
||||
proxy-suite transparent routing. Override this only if it collides
|
||||
with another local policy-routing mark on your host.
|
||||
'';
|
||||
example = 4;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -20,10 +20,9 @@ in
|
||||
|
||||
Current curated defaults:
|
||||
- `proxychains`: route = "proxychains"
|
||||
- `tun`: route = "tun" when singBox.tun.perApp.enable = true
|
||||
- `tproxy`: route = "tproxy" when singBox.tproxy.perApp.enable = true
|
||||
- `zapret`: route = "zapret" when zapret.perApp.enable = true and
|
||||
zapret.enable = true
|
||||
- `tun`: route = "tun" when proxy.tun.perApp.enable = true
|
||||
- `tproxy`: route = "tproxy" when proxy.tproxy.perApp.enable = true
|
||||
- `zapret`: route = "zapret" when zapret.perApp.enable = true
|
||||
|
||||
This makes `proxy-ctl wrap proxychains -- <command>` available
|
||||
without defining the profile manually, and similarly exposes
|
||||
@@ -52,11 +51,11 @@ in
|
||||
- "zapret" for per-app-scoped zapret handling through a separate
|
||||
zapret instance without changing the app's network path or exit IP
|
||||
|
||||
proxychains-based wrapping depends on singBox.enable = true and the
|
||||
local proxy-suite mixed proxy listener provided by sing-box. The
|
||||
"tun" route depends on singBox.tun.perApp.enable = true. The "tproxy"
|
||||
route depends on singBox.tproxy.perApp.enable = true. The "zapret"
|
||||
route depends on zapret.perApp.enable = true and zapret.enable = true.
|
||||
proxychains-based wrapping depends on proxy.enable = true and the
|
||||
local proxy-suite proxy listener provided by the active backend. The
|
||||
"tun" route depends on proxy.tun.perApp.enable = true. The "tproxy"
|
||||
route depends on proxy.tproxy.perApp.enable = true. The "zapret"
|
||||
route depends on zapret.perApp.enable = true.
|
||||
|
||||
When createDefaultProfiles = true, curated defaults are added on top
|
||||
of this list unless a user-defined profile already uses the same
|
||||
|
||||
@@ -5,7 +5,7 @@ let
|
||||
t = import ./types.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox.dns = {
|
||||
options.services.proxy-suite.proxy.dns = {
|
||||
local = mkOption {
|
||||
type = t.dnsUpstreamType;
|
||||
default = {
|
||||
@@ -15,7 +15,7 @@ in
|
||||
};
|
||||
description = ''
|
||||
DNS upstream used for the built-in "local" resolver role.
|
||||
This resolver is also used as sing-box route.default_domain_resolver.
|
||||
This resolver is also used as the backend's default domain resolver.
|
||||
|
||||
The module keeps detour policy automatic: in mixed/TProxy mode and
|
||||
per-app-routing TUN mode, "local" stays on the direct path (without an
|
||||
@@ -40,7 +40,7 @@ in
|
||||
DNS upstream used for the built-in "remote" resolver role.
|
||||
|
||||
This resolver always detours through the proxy and becomes the
|
||||
generated dns.final target when singBox.proxyByDefault = true.
|
||||
generated dns.final target when proxy.proxyByDefault = true.
|
||||
'';
|
||||
example = {
|
||||
type = "tls";
|
||||
|
||||
@@ -5,16 +5,18 @@ let
|
||||
t = import ./types.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox = {
|
||||
options.services.proxy-suite.proxy = {
|
||||
outbounds = mkOption {
|
||||
type = types.listOf t.outboundType;
|
||||
default = [ ];
|
||||
description = ''
|
||||
List of static proxy outbounds.
|
||||
Set exactly one of urlFile, url, or json per entry.
|
||||
Set exactly one of urlFile, url, singBoxJson, xrayJson, or the
|
||||
deprecated json field per entry. Backend-specific raw JSON fields are
|
||||
only valid with their matching backend.
|
||||
|
||||
At least one outbound or one subscription is required when
|
||||
singBox.enable = true.
|
||||
proxy.enable = true.
|
||||
'';
|
||||
example = [
|
||||
{
|
||||
@@ -37,12 +39,12 @@ in
|
||||
(standard v2rayN / Clash subscription format) or plain text of the same.
|
||||
|
||||
On first service start, each subscription is fetched live and cached
|
||||
under /var/lib/proxy-suite/subscriptions/<tag>.json. Later restarts
|
||||
under /var/lib/proxy-suite/subscriptions/<backend>/<tag>.json. Later restarts
|
||||
reuse the cache, so ordinary service restarts do not need network access.
|
||||
|
||||
A systemd timer (proxy-suite-subscription-update) refreshes all caches on
|
||||
the interval set by subscriptionUpdateInterval and restarts the running
|
||||
sing-box services after a successful refresh.
|
||||
A systemd timer (proxy-suite-subscription-update) refreshes all caches
|
||||
on the interval set by subscriptionUpdateInterval and restarts the
|
||||
running proxy services after a successful refresh.
|
||||
'';
|
||||
example = [
|
||||
{
|
||||
@@ -64,7 +66,7 @@ in
|
||||
all subscription caches. Accepts any systemd time span string
|
||||
(e.g. "1h", "6h", "1d", "12h").
|
||||
|
||||
Only used when singBox.subscriptions is non-empty. The timer also runs
|
||||
Only used when proxy.subscriptions is non-empty. The timer also runs
|
||||
once shortly after boot.
|
||||
'';
|
||||
example = "6h";
|
||||
@@ -86,11 +88,13 @@ in
|
||||
- "selector": create a Clash-compatible selector outbound tagged
|
||||
"proxy" and keep all configured outbounds available for manual
|
||||
switching via the Clash API.
|
||||
- "urltest": create an automatic latency-testing outbound tagged
|
||||
"proxy" and keep all configured outbounds available so sing-box
|
||||
can periodically probe and switch to a faster one.
|
||||
- "urltest": create automatic latency testing tagged "proxy" and
|
||||
keep all configured outbounds available so the active backend can
|
||||
periodically probe and switch to a faster one.
|
||||
|
||||
clashApiPort is only used with "selector" or "urltest".
|
||||
proxy.singBox.clashApiPort is only used with "selector" or "urltest"
|
||||
on the SingBox backend. "selector" is SingBox-only. "urltest" maps to
|
||||
SingBox urltest or XRay observatory/balancer depending on backend.
|
||||
urlTest.* options are only used with "urltest".
|
||||
Per-outbound tags are only individually meaningful with "selector"
|
||||
or "urltest".
|
||||
@@ -103,7 +107,7 @@ in
|
||||
type = types.str;
|
||||
default = "https://www.gstatic.com/generate_204";
|
||||
description = ''
|
||||
URL that sing-box fetches through each proxy to measure latency.
|
||||
URL that the active backend fetches through each proxy to measure latency.
|
||||
Only used when selection = "urltest".
|
||||
|
||||
Set this to a URL that is actually blocked in your region (e.g.
|
||||
@@ -118,35 +122,12 @@ in
|
||||
type = types.str;
|
||||
default = "3m";
|
||||
description = ''
|
||||
How often sing-box re-tests all outbounds. Accepts a Go duration
|
||||
string (e.g. "1m", "3m", "10m").
|
||||
How often the active backend re-tests all outbounds. Accepts a Go
|
||||
duration string (e.g. "1m", "3m", "10m").
|
||||
Only used when selection = "urltest".
|
||||
'';
|
||||
example = "1m";
|
||||
};
|
||||
|
||||
tolerance = mkOption {
|
||||
type = types.int;
|
||||
default = 50;
|
||||
description = ''
|
||||
Latency tolerance in milliseconds. The current proxy is only replaced
|
||||
when a competing one is faster by more than this value.
|
||||
|
||||
Only used when selection = "urltest".
|
||||
'';
|
||||
example = 100;
|
||||
};
|
||||
};
|
||||
|
||||
clashApiPort = mkOption {
|
||||
type = types.port;
|
||||
default = 9090;
|
||||
description = ''
|
||||
Port for the Clash-compatible REST API exposed by sing-box.
|
||||
Only used when selection is "selector" or "urltest". Ignored in
|
||||
"first" mode because there is no selector-style outbound to control.
|
||||
'';
|
||||
example = 9090;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -5,7 +5,7 @@ let
|
||||
t = import ./types.nix { inherit lib; };
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox.routing = {
|
||||
options.services.proxy-suite.proxy.routing = {
|
||||
enableRuDirect = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
@@ -98,7 +98,7 @@ in
|
||||
The outbound can be a configured outbound tag (useful with selector/urltest),
|
||||
or one of: "proxy" (active proxy), "direct", "block".
|
||||
|
||||
Order is preserved. The first matching rule wins in sing-box.
|
||||
Order is preserved. The first matching rule wins in the active backend.
|
||||
With selection = "first", non-built-in outbound tags are effectively
|
||||
routed to the single active "proxy" outbound.
|
||||
'';
|
||||
|
||||
@@ -4,8 +4,8 @@ let
|
||||
inherit (lib) mkOption mkEnableOption types;
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox.tproxy = {
|
||||
enable = mkEnableOption "global sing-box TProxy mode service";
|
||||
options.services.proxy-suite.proxy.tproxy = {
|
||||
enable = mkEnableOption "global proxy TProxy mode service";
|
||||
|
||||
autostart = mkOption {
|
||||
type = types.bool;
|
||||
@@ -13,7 +13,7 @@ in
|
||||
description = ''
|
||||
Whether to start proxy-suite-tproxy automatically during boot by
|
||||
attaching it to multi-user.target.
|
||||
Cannot be enabled together with singBox.tun.autostart.
|
||||
Cannot be enabled together with proxy.tun.autostart.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
@@ -22,7 +22,7 @@ in
|
||||
type = types.port;
|
||||
default = 1081;
|
||||
description = ''
|
||||
Local listen port for sing-box's TProxy inbound.
|
||||
Local listen port for the proxy backend's TProxy inbound.
|
||||
nftables redirection created by proxy-suite-tproxy sends intercepted
|
||||
TCP/UDP traffic to this port.
|
||||
'';
|
||||
@@ -35,7 +35,7 @@ in
|
||||
description = ''
|
||||
Mark applied to intercepted packets in global TProxy mode.
|
||||
A matching `ip rule` routes this mark to
|
||||
singBox.tproxy.routeTable, which points traffic to
|
||||
proxy.tproxy.routeTable, which points traffic to
|
||||
loopback for local proxy processing.
|
||||
'';
|
||||
example = 1;
|
||||
@@ -45,7 +45,7 @@ in
|
||||
type = types.int;
|
||||
default = 2;
|
||||
description = ''
|
||||
Mark applied to sing-box egress packets in global TProxy mode so
|
||||
Mark applied to backend egress packets in global TProxy mode so
|
||||
they bypass re-interception and do not loop back into the
|
||||
transparent proxy path.
|
||||
'';
|
||||
@@ -58,7 +58,7 @@ in
|
||||
description = ''
|
||||
Policy-routing table number used for global TProxy interception flow.
|
||||
The module installs a local default route in this table and binds it
|
||||
to singBox.tproxy.fwmark.
|
||||
to proxy.tproxy.fwmark.
|
||||
'';
|
||||
example = 100;
|
||||
};
|
||||
@@ -81,7 +81,7 @@ in
|
||||
};
|
||||
|
||||
perApp = {
|
||||
enable = mkEnableOption "per-app-scoped sing-box TProxy backend for perAppRouting profiles";
|
||||
enable = mkEnableOption "per-app-scoped proxy TProxy backend for perAppRouting profiles";
|
||||
|
||||
fwmark = mkOption {
|
||||
type = types.int;
|
||||
|
||||
@@ -36,8 +36,8 @@ let
|
||||
};
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox.tun = {
|
||||
enable = mkEnableOption "global sing-box TUN mode service";
|
||||
options.services.proxy-suite.proxy.tun = {
|
||||
enable = mkEnableOption "global proxy TUN mode service";
|
||||
|
||||
autostart = mkOption {
|
||||
type = types.bool;
|
||||
@@ -45,13 +45,13 @@ in
|
||||
description = ''
|
||||
Whether to start proxy-suite-tun automatically during boot by
|
||||
attaching it to multi-user.target.
|
||||
Cannot be enabled together with singBox.tproxy.autostart.
|
||||
Cannot be enabled together with proxy.tproxy.autostart.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
perApp = {
|
||||
enable = mkEnableOption "per-app-scoped sing-box TUN backend for perAppRouting profiles";
|
||||
enable = mkEnableOption "per-app-scoped proxy TUN backend for perAppRouting profiles";
|
||||
|
||||
fwmark = mkOption {
|
||||
type = types.int;
|
||||
|
||||
@@ -1,18 +1,25 @@
|
||||
# Core sing-box options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix.
|
||||
{ lib, ... }:
|
||||
# Core proxy options. Feature-area options live in sing-box-{outbounds,dns,tun,tproxy,routing}.nix.
|
||||
{ lib, pkgs, ... }:
|
||||
|
||||
let
|
||||
inherit (lib) mkOption mkEnableOption types;
|
||||
inherit (lib)
|
||||
literalExpression
|
||||
mkOption
|
||||
mkEnableOption
|
||||
types
|
||||
;
|
||||
in
|
||||
{
|
||||
options.services.proxy-suite.singBox = {
|
||||
options.services.proxy-suite.proxy = {
|
||||
enable = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
default = false;
|
||||
description = ''
|
||||
Whether to configure and run sing-box services for proxy-suite.
|
||||
When disabled, sing-box services and generated sing-box configs are
|
||||
skipped even if proxy-suite itself is enabled.
|
||||
Whether to configure and run the proxy backend services.
|
||||
This is disabled by default; enable it explicitly and choose at least
|
||||
one backend with proxy.singBox.enable or proxy.xray.enable. Enabling
|
||||
both runs sing-box as the frontend and XRay as a sidecar for outbounds
|
||||
that require XRay.
|
||||
'';
|
||||
};
|
||||
|
||||
@@ -20,8 +27,8 @@ in
|
||||
type = types.str;
|
||||
default = "127.0.0.1";
|
||||
description = ''
|
||||
Address for the SOCKS5/HTTP mixed inbound to bind to.
|
||||
This affects the always-on proxy-suite-socks service.
|
||||
Address for the local SOCKS5/HTTP inbound to bind to.
|
||||
This affects the proxy-suite-socks service.
|
||||
|
||||
Use "0.0.0.0" only if you intentionally want to expose the proxy to
|
||||
other machines on your network.
|
||||
@@ -33,12 +40,56 @@ in
|
||||
type = types.port;
|
||||
default = 1080;
|
||||
description = ''
|
||||
Listen port for the always-on SOCKS5/HTTP mixed inbound provided by
|
||||
proxy-suite-socks.
|
||||
Listen port for the local SOCKS5/HTTP proxy inbound provided by
|
||||
proxy-suite-socks. SingBox exposes SOCKS5 and HTTP on this port.
|
||||
XRay's Socks inbound also accepts SOCKS and HTTP.
|
||||
'';
|
||||
example = 1080;
|
||||
};
|
||||
|
||||
auth = {
|
||||
username = mkOption {
|
||||
type = types.nullOr (types.strMatching "[^[:space:]]+");
|
||||
default = null;
|
||||
description = ''
|
||||
Optional username for the local SOCKS5/HTTP mixed inbound.
|
||||
|
||||
Set this together with exactly one of auth.password or
|
||||
auth.passwordFile to require clients to authenticate before using the
|
||||
local proxy. Leave unset to keep the local proxy unauthenticated.
|
||||
'';
|
||||
example = "proxy-user";
|
||||
};
|
||||
|
||||
password = mkOption {
|
||||
type = types.nullOr (types.strMatching "[^[:space:]]+");
|
||||
default = null;
|
||||
description = ''
|
||||
Optional inline password for the local SOCKS5/HTTP mixed inbound.
|
||||
Convenient for testing, but the password ends up in the Nix store.
|
||||
|
||||
Prefer auth.passwordFile for real deployments.
|
||||
'';
|
||||
example = "change-me";
|
||||
};
|
||||
|
||||
passwordFile = mkOption {
|
||||
type = types.nullOr types.str;
|
||||
default = null;
|
||||
description = ''
|
||||
Runtime path to a file containing the local proxy password.
|
||||
Intended for use with secret managers so the password stays out of
|
||||
the Nix store. The file is read when proxy-suite-socks starts.
|
||||
|
||||
If perAppRouting.proxychains.enable is also used, keep this password
|
||||
as a single non-whitespace token so it can be written to the
|
||||
proxychains-ng config format. The generated proxychains config is
|
||||
readable by members of userControl.group.
|
||||
'';
|
||||
example = "/run/secrets/proxy-suite-local-proxy-password";
|
||||
};
|
||||
};
|
||||
|
||||
proxyByDefault = mkOption {
|
||||
type = types.bool;
|
||||
default = true;
|
||||
@@ -46,10 +97,70 @@ in
|
||||
Whether traffic that does not match any explicit routing rule should
|
||||
go through the proxy or go direct.
|
||||
|
||||
This affects sing-box route.final and dns.final in the generated
|
||||
This affects the generated backend route final and DNS final in the
|
||||
config.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
|
||||
singBox = {
|
||||
enable = mkEnableOption "SingBox proxy backend";
|
||||
|
||||
package = mkOption {
|
||||
type = types.package;
|
||||
default = pkgs.sing-box;
|
||||
defaultText = literalExpression "pkgs.sing-box";
|
||||
example = literalExpression "pkgs.sing-box";
|
||||
description = ''
|
||||
sing-box package used by proxy-suite systemd services.
|
||||
|
||||
Override this to pin or test a specific sing-box build when upstream
|
||||
protocol behavior changes.
|
||||
'';
|
||||
};
|
||||
|
||||
clashApiPort = mkOption {
|
||||
type = types.port;
|
||||
default = 9090;
|
||||
description = ''
|
||||
Port for the Clash-compatible REST API exposed by sing-box.
|
||||
Only used when proxy.selection is "selector" or "urltest". Ignored
|
||||
in "first" mode because there is no selector-style outbound to
|
||||
control.
|
||||
'';
|
||||
example = 9090;
|
||||
};
|
||||
|
||||
urlTest.tolerance = mkOption {
|
||||
type = types.int;
|
||||
default = 50;
|
||||
description = ''
|
||||
Latency tolerance in milliseconds for sing-box urltest. The current
|
||||
proxy is only replaced when a competing one is faster by more than
|
||||
this value.
|
||||
|
||||
Only used when proxy.selection = "urltest" and the SingBox backend
|
||||
is active.
|
||||
'';
|
||||
example = 100;
|
||||
};
|
||||
};
|
||||
|
||||
xray = {
|
||||
enable = mkEnableOption "XRay proxy backend";
|
||||
|
||||
package = mkOption {
|
||||
type = types.package;
|
||||
default = pkgs.xray;
|
||||
defaultText = literalExpression "pkgs.xray";
|
||||
example = literalExpression "pkgs.xray";
|
||||
description = ''
|
||||
XRay package used by proxy-suite systemd services.
|
||||
|
||||
Override this to pin or test a specific XRay build when upstream
|
||||
protocol behavior changes.
|
||||
'';
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -32,7 +32,7 @@ let
|
||||
default = [ ];
|
||||
description = ''
|
||||
sing-geosite rule-set names to match in this routing rule.
|
||||
Each name becomes a sing-box geosite rule-set reference.
|
||||
Each name becomes a backend geosite rule-set reference.
|
||||
'';
|
||||
example = [
|
||||
"netflix"
|
||||
@@ -44,7 +44,7 @@ let
|
||||
default = [ ];
|
||||
description = ''
|
||||
sing-geoip rule-set names to match in this routing rule.
|
||||
Each name becomes a sing-box geoip rule-set reference.
|
||||
Each name becomes a backend geoip rule-set reference.
|
||||
'';
|
||||
example = [
|
||||
"us"
|
||||
@@ -83,7 +83,8 @@ let
|
||||
e.g. "my-sub" -> tags like "my-sub-Server-DE".
|
||||
|
||||
This value is also used as the subscription cache filename stem under
|
||||
/var/lib/proxy-suite/subscriptions/, so it must be a safe identifier.
|
||||
/var/lib/proxy-suite/subscriptions/<backend>/, so it must be a safe
|
||||
identifier.
|
||||
'';
|
||||
example = "community-list";
|
||||
};
|
||||
@@ -125,7 +126,7 @@ let
|
||||
Outbound tag used in routing rules and multi-outbound selection.
|
||||
|
||||
With selection = "selector" or "urltest", each outbound keeps its own
|
||||
tag and can be selected directly. With selection = "first", sing-box
|
||||
tag and can be selected directly. With selection = "first", proxy-suite
|
||||
routes through a single active outbound tagged "proxy", so individual
|
||||
proxy tags are mainly useful for documentation and config structure.
|
||||
'';
|
||||
@@ -158,7 +159,23 @@ let
|
||||
example = "hy2://password@example.com:443?sni=example.com";
|
||||
};
|
||||
|
||||
json = mkOption {
|
||||
backend = mkOption {
|
||||
type = types.enum [
|
||||
"auto"
|
||||
"sing-box"
|
||||
"xray"
|
||||
];
|
||||
default = "auto";
|
||||
description = ''
|
||||
Backend preference for this outbound when both SingBox and XRay are
|
||||
enabled. "auto" uses SingBox when the URL or JSON can be represented
|
||||
there and falls back to XRay for XRay-only transports such as XHTTP
|
||||
or ECH. Ignored by single-backend configurations.
|
||||
'';
|
||||
example = "xray";
|
||||
};
|
||||
|
||||
singBoxJson = mkOption {
|
||||
type = types.nullOr types.attrs;
|
||||
default = null;
|
||||
description = ''
|
||||
@@ -166,9 +183,10 @@ let
|
||||
Embedded directly into the config at build time. The tag field
|
||||
is overridden by the outbound's tag option.
|
||||
|
||||
Set exactly one of urlFile, url, or json for each outbound.
|
||||
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
|
||||
each outbound.
|
||||
Use this when the proxy definition is easier to generate as native Nix
|
||||
than as a single URL string.
|
||||
than as a single URL string. Only valid with the SingBox backend.
|
||||
'';
|
||||
example = {
|
||||
type = "vless";
|
||||
@@ -178,6 +196,37 @@ let
|
||||
};
|
||||
};
|
||||
|
||||
xrayJson = mkOption {
|
||||
type = types.nullOr types.attrs;
|
||||
default = null;
|
||||
description = ''
|
||||
Raw XRay outbound configuration as a Nix attribute set.
|
||||
Embedded directly into the config at build time. The tag field is
|
||||
overridden by the outbound's tag option.
|
||||
|
||||
Set exactly one of urlFile, url, singBoxJson, xrayJson, or json for
|
||||
each outbound. Only valid with the XRay backend.
|
||||
'';
|
||||
example = {
|
||||
protocol = "vless";
|
||||
settings = {
|
||||
address = "example.com";
|
||||
port = 443;
|
||||
id = "...";
|
||||
encryption = "none";
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
json = mkOption {
|
||||
type = types.nullOr types.attrs;
|
||||
default = null;
|
||||
visible = false;
|
||||
description = ''
|
||||
Deprecated alias for singBoxJson. Use singBoxJson instead.
|
||||
'';
|
||||
};
|
||||
|
||||
# Shorthand for attaching routing rules directly to an outbound definition.
|
||||
# Traffic matching these patterns is sent to this specific outbound.
|
||||
# Only meaningful when selection = "selector" or "urltest" (with "first",
|
||||
@@ -196,7 +245,7 @@ let
|
||||
];
|
||||
default = "udp";
|
||||
description = ''
|
||||
sing-box DNS transport type for this upstream resolver.
|
||||
DNS transport type for this upstream resolver.
|
||||
'';
|
||||
example = "tls";
|
||||
};
|
||||
@@ -280,7 +329,7 @@ let
|
||||
type = types.bool;
|
||||
default = true;
|
||||
description = ''
|
||||
Whether this custom hostlist should also be mirrored into sing-box
|
||||
Whether this custom hostlist should also be mirrored into proxy
|
||||
direct domain routing when zapret.syncDirectRouting = true.
|
||||
'';
|
||||
};
|
||||
@@ -317,7 +366,7 @@ let
|
||||
only that app's traffic is policy-routed into the app TUN backend.
|
||||
- "tproxy": launch the command in the dedicated per-app-routing TProxy
|
||||
slice so only that app's traffic is transparently intercepted by
|
||||
the local sing-box TProxy inbound.
|
||||
the local proxy TProxy inbound.
|
||||
- "zapret": launch the command in the dedicated per-app-routing zapret
|
||||
slice so only that app's traffic is handled by the separate
|
||||
per-app-scoped zapret instance.
|
||||
|
||||
@@ -39,7 +39,7 @@ in
|
||||
default = true;
|
||||
description = ''
|
||||
When zapret.enable = true, mirror zapret's upstream domain hostlists
|
||||
into sing-box direct domain routing.
|
||||
into proxy direct domain routing.
|
||||
|
||||
This includes the default zapret domain lists and any custom
|
||||
hostlistRules entries with enableDirectSync = true.
|
||||
@@ -52,7 +52,7 @@ in
|
||||
default = false;
|
||||
description = ''
|
||||
When zapret.enable = true, mirror zapret's upstream ipset ranges
|
||||
(such as ipset-all.txt minus exclusions) into sing-box direct IP routing.
|
||||
(such as ipset-all.txt minus exclusions) into proxy direct IP routing.
|
||||
'';
|
||||
example = false;
|
||||
};
|
||||
@@ -62,7 +62,7 @@ in
|
||||
default = true;
|
||||
description = ''
|
||||
When zapret.enable = true, mirror user-defined zapret.ipsetAll and
|
||||
zapret.ipsetExclude entries into sing-box direct IP routing.
|
||||
zapret.ipsetExclude entries into proxy direct IP routing.
|
||||
'';
|
||||
example = true;
|
||||
};
|
||||
@@ -87,7 +87,7 @@ in
|
||||
description = ''
|
||||
Extra domains to include in zapret's interception list.
|
||||
When syncDirectRouting = true, these domains are also mirrored into
|
||||
sing-box direct routing.
|
||||
proxy direct routing.
|
||||
'';
|
||||
example = [ "youtube.com" ];
|
||||
};
|
||||
@@ -98,7 +98,7 @@ in
|
||||
description = ''
|
||||
Domains to exclude from zapret interception.
|
||||
When syncDirectRouting = true, these exclusions also remove matching
|
||||
domains from the zapret-derived sing-box direct-routing set.
|
||||
domains from the zapret-derived proxy direct-routing set.
|
||||
'';
|
||||
example = [ "music.youtube.com" ];
|
||||
};
|
||||
@@ -108,7 +108,7 @@ in
|
||||
default = [ ];
|
||||
description = ''
|
||||
Extra IPs/CIDRs to add to zapret's ipset.
|
||||
Mirrored into sing-box direct IP routing when
|
||||
Mirrored into proxy direct IP routing when
|
||||
syncDirectRoutingUserIps = true.
|
||||
'';
|
||||
example = [ "203.0.113.0/24" ];
|
||||
@@ -119,7 +119,7 @@ in
|
||||
default = [ ];
|
||||
description = ''
|
||||
IPs/CIDRs to exclude from zapret's ipset.
|
||||
Also excluded from zapret-derived sing-box direct IP routing when
|
||||
Also excluded from zapret-derived proxy direct IP routing when
|
||||
syncDirectRoutingUserIps = true.
|
||||
'';
|
||||
example = [ "203.0.113.10/32" ];
|
||||
@@ -134,7 +134,7 @@ in
|
||||
upstream preset does not already reference them.
|
||||
|
||||
When syncDirectRouting = true, domains from these extra lists are also
|
||||
mirrored into sing-box direct routing.
|
||||
mirrored into proxy direct routing.
|
||||
'';
|
||||
example = false;
|
||||
};
|
||||
|
||||
+203
-21
@@ -8,9 +8,10 @@
|
||||
|
||||
let
|
||||
derived = import ./derived.nix { inherit lib cfg; };
|
||||
r = cfg.singBox.routing;
|
||||
singBoxCfg = derived.singBoxCfg;
|
||||
r = cfg.proxy.routing;
|
||||
proxyCfg = derived.proxyCfg;
|
||||
zapretCfg = cfg.zapret;
|
||||
tgWsProxyCfg = cfg.tgWsProxy;
|
||||
|
||||
trim = lib.strings.trim;
|
||||
hasPrefix = lib.strings.hasPrefix;
|
||||
@@ -101,13 +102,30 @@ let
|
||||
mkDomainRule = mkRule "domain_suffix";
|
||||
mkIPRule = mkRule "ip_cidr";
|
||||
mkRulesetRule = mkRule "rule_set";
|
||||
customRuleCategory =
|
||||
outbound:
|
||||
if outbound == "direct" then
|
||||
"direct"
|
||||
else if outbound == "block" then
|
||||
"block"
|
||||
else
|
||||
"proxy";
|
||||
|
||||
# In "first" mode the start script renames the first outbound to "proxy",
|
||||
# so any per-outbound routing tag that isn't direct/block/proxy must map
|
||||
# to "proxy" instead of the original tag (which won't exist in sing-box).
|
||||
resolveTag =
|
||||
tag:
|
||||
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then "proxy" else tag;
|
||||
if derived.collapseNamedOutbounds && !builtins.elem tag derived.builtinTags then
|
||||
"proxy"
|
||||
else if
|
||||
derived.pureXrayEnabled
|
||||
&& derived.selectionMode == "urltest"
|
||||
&& !builtins.elem tag derived.builtinTags
|
||||
then
|
||||
"proxy-suite-ob-${tag}"
|
||||
else
|
||||
tag;
|
||||
|
||||
# Collect per-outbound routing attached directly to outbound definitions.
|
||||
perOutboundRules = lib.concatMap (
|
||||
@@ -125,7 +143,7 @@ let
|
||||
geoips
|
||||
;
|
||||
}
|
||||
) singBoxCfg.outbounds;
|
||||
) proxyCfg.outbounds;
|
||||
|
||||
# All custom rules in priority order: per-outbound first, then explicit routing.rules.
|
||||
customRules =
|
||||
@@ -154,21 +172,17 @@ let
|
||||
r.proxy.geoips ++ direct.geoips ++ r.block.geoips ++ lib.concatMap (rule: rule.geoips) customRules
|
||||
);
|
||||
|
||||
geositeRuleSets = map (name: {
|
||||
tag = "geosite-${name}";
|
||||
mkRuleSet = kind: pkg: name: {
|
||||
tag = "${kind}-${name}";
|
||||
type = "local";
|
||||
format = "binary";
|
||||
path = "${pkgs.sing-geosite}/share/sing-box/rule-set/geosite-${name}.srs";
|
||||
}) allGeositeNames;
|
||||
path = "${pkg}/share/sing-box/rule-set/${kind}-${name}.srs";
|
||||
};
|
||||
|
||||
geoIPRuleSets = map (name: {
|
||||
tag = "geoip-${name}";
|
||||
type = "local";
|
||||
format = "binary";
|
||||
path = "${pkgs.sing-geoip}/share/sing-box/rule-set/geoip-${name}.srs";
|
||||
}) allGeoIPNames;
|
||||
geositeRuleSets = map (mkRuleSet "geosite" pkgs.sing-geosite) allGeositeNames;
|
||||
geoIPRuleSets = map (mkRuleSet "geoip" pkgs.sing-geoip) allGeoIPNames;
|
||||
|
||||
routingRules = lib.flatten [
|
||||
commonRules = [
|
||||
{
|
||||
network = [
|
||||
"tcp"
|
||||
@@ -178,42 +192,210 @@ let
|
||||
action = "hijack-dns";
|
||||
}
|
||||
{ action = "sniff"; }
|
||||
];
|
||||
|
||||
# Per-outbound and explicit rules come first – they take priority.
|
||||
(lib.concatMap mkCustomRuleEntries customRules)
|
||||
customRouteRules = map (rule: {
|
||||
category = customRuleCategory rule.outbound;
|
||||
entries = mkCustomRuleEntries rule;
|
||||
}) customRules;
|
||||
|
||||
# Global proxy lists
|
||||
proxyPrimaryRules = lib.flatten [
|
||||
(mkDomainRule "proxy" r.proxy.domains)
|
||||
(mkIPRule "proxy" r.proxy.ips)
|
||||
];
|
||||
|
||||
# Global direct lists
|
||||
directRules = lib.flatten [
|
||||
(mkDomainRule "direct" direct.domains)
|
||||
(mkIPRule "direct" direct.ips)
|
||||
(mkRulesetRule "direct" (map (s: "geosite-${s}") direct.geosites))
|
||||
(mkRulesetRule "direct" (map (s: "geoip-${s}") direct.geoips))
|
||||
];
|
||||
|
||||
tgWsProxyRelayDirectRules =
|
||||
lib.optional
|
||||
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
|
||||
{
|
||||
ip_cidr = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps);
|
||||
outbound = "direct";
|
||||
};
|
||||
|
||||
safetyDirectRules = [
|
||||
{
|
||||
ip_is_private = true;
|
||||
outbound = "direct";
|
||||
}
|
||||
]
|
||||
++ tgWsProxyRelayDirectRules;
|
||||
|
||||
# Block (before proxy geosets so block can override them)
|
||||
blockRules = lib.flatten [
|
||||
(mkDomainRule "block" r.block.domains)
|
||||
(mkIPRule "block" r.block.ips)
|
||||
(mkRulesetRule "block" (map (s: "geosite-${s}") r.block.geosites))
|
||||
(mkRulesetRule "block" (map (s: "geoip-${s}") r.block.geoips))
|
||||
];
|
||||
|
||||
# Global proxy geo lists
|
||||
proxyGeoRules = lib.flatten [
|
||||
(mkRulesetRule "proxy" (map (s: "geosite-${s}") r.proxy.geosites))
|
||||
(mkRulesetRule "proxy" (map (s: "geoip-${s}") r.proxy.geoips))
|
||||
];
|
||||
|
||||
singBoxRoutingRules =
|
||||
commonRules
|
||||
++ lib.concatMap (item: item.entries) customRouteRules
|
||||
++ proxyPrimaryRules
|
||||
++ directRules
|
||||
++ safetyDirectRules
|
||||
++ blockRules
|
||||
++ proxyGeoRules;
|
||||
|
||||
singBoxRouteModeRules = {
|
||||
common = commonRules;
|
||||
custom = customRouteRules;
|
||||
proxyPrimary = proxyPrimaryRules;
|
||||
direct = directRules;
|
||||
safetyDirect = safetyDirectRules;
|
||||
block = blockRules;
|
||||
proxyGeo = proxyGeoRules;
|
||||
};
|
||||
|
||||
xrayTarget =
|
||||
tag:
|
||||
if tag == "proxy" && derived.selectionMode == "urltest" then
|
||||
{ balancerTag = "proxy"; }
|
||||
else
|
||||
{ outboundTag = tag; };
|
||||
|
||||
mkXrayRule =
|
||||
ruleTag: fields: tag:
|
||||
(
|
||||
{
|
||||
type = "field";
|
||||
inherit ruleTag;
|
||||
}
|
||||
// fields
|
||||
// (xrayTarget tag)
|
||||
);
|
||||
|
||||
xrayDomainRules =
|
||||
ruleTag: tag: domains:
|
||||
lib.optional (domains != [ ]) (
|
||||
mkXrayRule ruleTag {
|
||||
domain = map (domain: "domain:${domain}") domains;
|
||||
} tag
|
||||
);
|
||||
|
||||
xrayIPRules =
|
||||
ruleTag: tag: ips:
|
||||
lib.optional (ips != [ ]) (
|
||||
mkXrayRule ruleTag {
|
||||
ip = ips;
|
||||
} tag
|
||||
);
|
||||
|
||||
xrayGeositeRules =
|
||||
ruleTag: tag: geosites:
|
||||
lib.optional (geosites != [ ]) (
|
||||
mkXrayRule ruleTag {
|
||||
domain = map (name: "geosite:${name}") geosites;
|
||||
} tag
|
||||
);
|
||||
|
||||
xrayGeoIPRules =
|
||||
ruleTag: tag: geoips:
|
||||
lib.optional (geoips != [ ]) (
|
||||
mkXrayRule ruleTag {
|
||||
ip = map (name: "geoip:${name}") geoips;
|
||||
} tag
|
||||
);
|
||||
|
||||
xrayCustomRuleTag = category: kind: "custom-${category}-${kind}";
|
||||
|
||||
mkXrayCustomRuleEntries =
|
||||
rule:
|
||||
lib.flatten [
|
||||
(xrayDomainRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "domain") rule.outbound
|
||||
rule.domains
|
||||
)
|
||||
(xrayIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "ip") rule.outbound rule.ips)
|
||||
(xrayGeositeRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geosite") rule.outbound
|
||||
rule.geosites
|
||||
)
|
||||
(xrayGeoIPRules (xrayCustomRuleTag (customRuleCategory rule.outbound) "geoip") rule.outbound
|
||||
rule.geoips
|
||||
)
|
||||
];
|
||||
|
||||
xrayCustomRouteRules = map (rule: {
|
||||
category = customRuleCategory rule.outbound;
|
||||
entries = mkXrayCustomRuleEntries rule;
|
||||
}) customRules;
|
||||
|
||||
xrayProxyPrimaryRules = lib.flatten [
|
||||
(xrayDomainRules "proxy-domain" "proxy" r.proxy.domains)
|
||||
(xrayIPRules "proxy-ip" "proxy" r.proxy.ips)
|
||||
];
|
||||
|
||||
xrayDirectRules = lib.flatten [
|
||||
(xrayDomainRules "direct-domain" "direct" direct.domains)
|
||||
(xrayIPRules "direct-ip" "direct" direct.ips)
|
||||
(xrayGeositeRules "direct-geosite" "direct" direct.geosites)
|
||||
(xrayGeoIPRules "direct-geoip" "direct" direct.geoips)
|
||||
];
|
||||
|
||||
xraySafetyDirectRules = [
|
||||
(mkXrayRule "direct-private" { ip = [ "geoip:private" ]; } "direct")
|
||||
]
|
||||
++
|
||||
lib.optional
|
||||
(tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && tgWsProxyCfg.dcIps != { })
|
||||
(
|
||||
mkXrayRule "direct-tg-relay" { ip = lib.unique (builtins.attrValues tgWsProxyCfg.dcIps); } "direct"
|
||||
);
|
||||
|
||||
xrayBlockRules = lib.flatten [
|
||||
(xrayDomainRules "block-domain" "block" r.block.domains)
|
||||
(xrayIPRules "block-ip" "block" r.block.ips)
|
||||
(xrayGeositeRules "block-geosite" "block" r.block.geosites)
|
||||
(xrayGeoIPRules "block-geoip" "block" r.block.geoips)
|
||||
];
|
||||
|
||||
xrayProxyGeoRules = lib.flatten [
|
||||
(xrayGeositeRules "proxy-geosite" "proxy" r.proxy.geosites)
|
||||
(xrayGeoIPRules "proxy-geoip" "proxy" r.proxy.geoips)
|
||||
];
|
||||
|
||||
xrayRoutingRules =
|
||||
lib.concatMap (item: item.entries) xrayCustomRouteRules
|
||||
++ xrayProxyPrimaryRules
|
||||
++ xrayDirectRules
|
||||
++ xraySafetyDirectRules
|
||||
++ xrayProxyGeoRules
|
||||
++ xrayBlockRules;
|
||||
|
||||
xrayRouteModeRules = {
|
||||
common = [ ];
|
||||
custom = xrayCustomRouteRules;
|
||||
proxyPrimary = xrayProxyPrimaryRules;
|
||||
direct = xrayDirectRules;
|
||||
safetyDirect = xraySafetyDirectRules;
|
||||
block = xrayBlockRules;
|
||||
proxyGeo = xrayProxyGeoRules;
|
||||
};
|
||||
|
||||
routingRules = singBoxRoutingRules;
|
||||
routeModeRules = singBoxRouteModeRules;
|
||||
|
||||
in
|
||||
{
|
||||
inherit
|
||||
direct
|
||||
geositeRuleSets
|
||||
geoIPRuleSets
|
||||
singBoxRoutingRules
|
||||
singBoxRouteModeRules
|
||||
xrayRoutingRules
|
||||
xrayRouteModeRules
|
||||
routeModeRules
|
||||
routingRules
|
||||
;
|
||||
}
|
||||
@@ -27,7 +27,13 @@ let
|
||||
;
|
||||
|
||||
inherit (derived)
|
||||
proxyCfg
|
||||
singBoxCfg
|
||||
proxyEnabled
|
||||
singBoxEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
@@ -36,35 +42,53 @@ let
|
||||
perAppZapretCfg
|
||||
;
|
||||
|
||||
globalTunAutoRouteTable = 2022;
|
||||
|
||||
featureAssertions = [
|
||||
(requireAvailable singBoxCfg.enable (
|
||||
singBoxCfg.outbounds != [ ] || singBoxCfg.subscriptions != [ ]
|
||||
) "proxy-suite: at least one outbound or subscription is required when singBox.enable = true")
|
||||
(uniqueValues singBoxCfg.enable outboundTags "proxy-suite: outbound tags must be unique")
|
||||
(uniqueValues singBoxCfg.enable subscriptionTags
|
||||
(requireAvailable proxyCfg.singBox.enable proxyEnabled
|
||||
"proxy-suite: proxy.singBox.enable requires proxy.enable = true"
|
||||
)
|
||||
(requireAvailable proxyCfg.xray.enable proxyEnabled
|
||||
"proxy-suite: proxy.xray.enable requires proxy.enable = true"
|
||||
)
|
||||
(mkAssertion (!proxyEnabled || proxyCfg.singBox.enable || proxyCfg.xray.enable)
|
||||
"proxy-suite: at least one of proxy.singBox.enable or proxy.xray.enable must be true when proxy.enable = true"
|
||||
)
|
||||
(requireAvailable proxyEnabled (
|
||||
proxyCfg.outbounds != [ ] || proxyCfg.subscriptions != [ ]
|
||||
) "proxy-suite: at least one outbound or subscription is required when proxy.enable = true")
|
||||
(uniqueValues proxyEnabled outboundTags "proxy-suite: outbound tags must be unique")
|
||||
(uniqueValues proxyEnabled subscriptionTags
|
||||
"proxy-suite: subscription tags must be unique because they are used as cache keys and outbound tag prefixes"
|
||||
)
|
||||
(mkAssertion (
|
||||
!singBoxCfg.enable || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
|
||||
!proxyEnabled || builtins.all (tag: !builtins.elem tag builtinTags) outboundTags
|
||||
) "proxy-suite: outbound tags must not use reserved names: proxy, direct, block")
|
||||
(mkAssertion (!singBoxCfg.enable || invalidRoutingTargets == [ ])
|
||||
(mkAssertion (!proxyEnabled || invalidRoutingTargets == [ ])
|
||||
"proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}"
|
||||
)
|
||||
(requireEnabled globalTun.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tun.enable requires singBox.enable = true"
|
||||
(mkAssertion (
|
||||
!(pureXrayEnabled && proxyCfg.selection == "selector")
|
||||
) "proxy-suite: proxy.selection = \"selector\" is only available with proxy.singBox.enable = true")
|
||||
(mkAssertion
|
||||
(!(pureXrayEnabled && (proxyCfg.dns.local.type == "tls" || proxyCfg.dns.remote.type == "tls")))
|
||||
"proxy-suite: proxy.dns.*.type = \"tls\" is not supported with proxy.xray.enable = true; use udp/tcp DNS for XRay"
|
||||
)
|
||||
(requireEnabled globalTproxy.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tproxy.enable requires singBox.enable = true"
|
||||
(requireEnabled globalTun.enable proxyEnabled
|
||||
"proxy-suite: proxy.tun.enable requires proxy.enable = true"
|
||||
)
|
||||
(requireEnabled globalTproxy.enable proxyEnabled
|
||||
"proxy-suite: proxy.tproxy.enable requires proxy.enable = true"
|
||||
)
|
||||
(requireEnabled globalTun.autostart globalTun.enable
|
||||
"proxy-suite: singBox.tun.autostart requires singBox.tun.enable = true"
|
||||
"proxy-suite: proxy.tun.autostart requires proxy.tun.enable = true"
|
||||
)
|
||||
(requireEnabled globalTproxy.autostart globalTproxy.enable
|
||||
"proxy-suite: singBox.tproxy.autostart requires singBox.tproxy.enable = true"
|
||||
"proxy-suite: proxy.tproxy.autostart requires proxy.tproxy.enable = true"
|
||||
)
|
||||
(mkAssertion
|
||||
(!(globalTproxy.enable && globalTproxy.autostart && globalTun.enable && globalTun.autostart))
|
||||
"proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time"
|
||||
"proxy-suite: proxy.tproxy.autostart and proxy.tun.autostart cannot both be enabled at the same time"
|
||||
)
|
||||
];
|
||||
|
||||
@@ -75,8 +99,8 @@ let
|
||||
(requireEnabled perAppRoutingCfg.proxychains.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingCfg.proxychains.enable singBoxCfg.enable
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires singBox.enable = true"
|
||||
(requireEnabled perAppRoutingCfg.proxychains.enable proxyEnabled
|
||||
"proxy-suite: perAppRouting.proxychains.enable requires proxy.enable = true"
|
||||
)
|
||||
(uniqueValues true effectivePerAppRoutingProfileNames
|
||||
"proxy-suite: perAppRouting profile names must be unique"
|
||||
@@ -84,117 +108,248 @@ let
|
||||
(requireAvailable hasProxychainsProfiles perAppRoutingCfg.proxychains.enable
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires perAppRouting.proxychains.enable = true"
|
||||
)
|
||||
(requireAvailable hasProxychainsProfiles singBoxCfg.enable
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires singBox.enable = true"
|
||||
(requireAvailable hasProxychainsProfiles proxyEnabled
|
||||
"proxy-suite: route=proxychains in perAppRouting.profiles requires proxy.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTun.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires perAppRouting.enable = true"
|
||||
"proxy-suite: proxy.tun.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTun.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tun.perApp.enable requires singBox.enable = true"
|
||||
(requireEnabled perAppRoutingTun.enable proxyEnabled
|
||||
"proxy-suite: proxy.tun.perApp.enable requires proxy.enable = true"
|
||||
)
|
||||
(requireAvailable hasTunProfiles perAppRoutingTun.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.tun.perApp.enable = true"
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.tun.perApp.enable = true"
|
||||
)
|
||||
(requireAvailable hasTunProfiles singBoxCfg.enable
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires singBox.enable = true"
|
||||
(requireAvailable hasTunProfiles proxyEnabled
|
||||
"proxy-suite: route=tun in perAppRouting.profiles requires proxy.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTproxy.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires perAppRouting.enable = true"
|
||||
"proxy-suite: proxy.tproxy.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppRoutingTproxy.enable singBoxCfg.enable
|
||||
"proxy-suite: singBox.tproxy.perApp.enable requires singBox.enable = true"
|
||||
(requireEnabled perAppRoutingTproxy.enable proxyEnabled
|
||||
"proxy-suite: proxy.tproxy.perApp.enable requires proxy.enable = true"
|
||||
)
|
||||
(requireAvailable hasTproxyProfiles perAppRoutingTproxy.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.tproxy.perApp.enable = true"
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.tproxy.perApp.enable = true"
|
||||
)
|
||||
(requireAvailable hasTproxyProfiles singBoxCfg.enable
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires singBox.enable = true"
|
||||
(requireAvailable hasTproxyProfiles proxyEnabled
|
||||
"proxy-suite: route=tproxy in perAppRouting.profiles requires proxy.enable = true"
|
||||
)
|
||||
(requireEnabled perAppZapretCfg.enable perAppRoutingCfg.enable
|
||||
"proxy-suite: zapret.perApp.enable requires perAppRouting.enable = true"
|
||||
)
|
||||
(requireEnabled perAppZapretCfg.enable cfg.zapret.enable
|
||||
"proxy-suite: zapret.perApp.enable requires zapret.enable = true"
|
||||
)
|
||||
(requireAvailable hasZapretProfiles (perAppZapretCfg.enable && cfg.zapret.enable)
|
||||
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true and zapret.enable = true"
|
||||
(requireAvailable hasZapretProfiles perAppZapretCfg.enable
|
||||
"proxy-suite: route=zapret in perAppRouting.profiles requires zapret.perApp.enable = true"
|
||||
)
|
||||
];
|
||||
|
||||
collisionAssertions = map (item: notEqualWhen item.condition item.left item.right item.message) [
|
||||
{
|
||||
condition = globalTun.enable && perAppRoutingTun.enable;
|
||||
left = globalTun.interface;
|
||||
right = perAppRoutingTun.interface;
|
||||
message = "proxy-suite: proxy.tun.interface and proxy.tun.perApp.interface must differ";
|
||||
}
|
||||
{
|
||||
condition = globalTun.enable && perAppRoutingTun.enable;
|
||||
left = globalTun.address;
|
||||
right = perAppRoutingTun.address;
|
||||
message = "proxy-suite: proxy.tun.address and proxy.tun.perApp.address must differ";
|
||||
}
|
||||
{
|
||||
condition = globalTun.enable && perAppRoutingTun.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = globalTunAutoRouteTable;
|
||||
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from the global TUN auto-route table 2022";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.fwmark when global TProxy is enabled";
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.fwmark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must differ from singBox.tproxy.proxyMark when global TProxy is enabled";
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark must differ from proxy.tproxy.proxyMark when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && globalTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable must differ from singBox.tproxy.routeTable when global TProxy is enabled";
|
||||
message = "proxy-suite: proxy.tun.perApp.routeTable must differ from proxy.tproxy.routeTable when global TProxy is enabled";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.fwmark";
|
||||
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must differ from singBox.tproxy.proxyMark";
|
||||
message = "proxy-suite: proxy.tproxy.perApp.fwmark must differ from proxy.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTproxy.routeTable;
|
||||
right = globalTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.routeTable must differ from singBox.tproxy.routeTable";
|
||||
message = "proxy-suite: proxy.tproxy.perApp.routeTable must differ from proxy.tproxy.routeTable";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppRoutingTproxy.fwmark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and singBox.tproxy.perApp.fwmark must differ";
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark and proxy.tproxy.perApp.fwmark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppRoutingTproxy.enable;
|
||||
left = perAppRoutingTun.routeTable;
|
||||
right = perAppRoutingTproxy.routeTable;
|
||||
message = "proxy-suite: singBox.tun.perApp.routeTable and singBox.tproxy.perApp.routeTable must differ";
|
||||
message = "proxy-suite: proxy.tun.perApp.routeTable and proxy.tproxy.perApp.routeTable must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.fwmark";
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
left = perAppZapretCfg.filterMark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from singBox.tproxy.proxyMark";
|
||||
message = "proxy-suite: zapret.perApp.filterMark must differ from proxy.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTun.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
left = perAppRoutingTproxy.fwmark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
message = "proxy-suite: proxy.tproxy.perApp.fwmark and zapret.perApp.filterMark must differ";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
|
||||
left = tgWsProxyCfg.routingMark;
|
||||
right = globalTproxy.fwmark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.fwmark";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && globalTproxy.enable;
|
||||
left = tgWsProxyCfg.routingMark;
|
||||
right = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.proxyMark";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTun.enable;
|
||||
left = tgWsProxyCfg.routingMark;
|
||||
right = perAppRoutingTun.fwmark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tun.perApp.fwmark";
|
||||
}
|
||||
{
|
||||
condition =
|
||||
tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppRoutingTproxy.enable;
|
||||
left = tgWsProxyCfg.routingMark;
|
||||
right = perAppRoutingTproxy.fwmark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must differ from proxy.tproxy.perApp.fwmark";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
|
||||
left = tgWsProxyCfg.routingMark;
|
||||
right = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must differ from zapret.perApp.filterMark";
|
||||
}
|
||||
];
|
||||
|
||||
perAppZapretDesyncMarks = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
|
||||
positiveNumberAssertions =
|
||||
map (item: mkAssertion (!item.condition || item.value > 0) item.message)
|
||||
[
|
||||
{
|
||||
condition = globalTun.enable;
|
||||
value = globalTun.mtu;
|
||||
message = "proxy-suite: proxy.tun.mtu must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable;
|
||||
value = perAppRoutingTun.mtu;
|
||||
message = "proxy-suite: proxy.tun.perApp.mtu must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = globalTproxy.enable;
|
||||
value = globalTproxy.fwmark;
|
||||
message = "proxy-suite: proxy.tproxy.fwmark must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = globalTproxy.enable;
|
||||
value = globalTproxy.proxyMark;
|
||||
message = "proxy-suite: proxy.tproxy.proxyMark must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = globalTproxy.enable;
|
||||
value = globalTproxy.routeTable;
|
||||
message = "proxy-suite: proxy.tproxy.routeTable must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable;
|
||||
value = perAppRoutingTun.fwmark;
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable;
|
||||
value = perAppRoutingTun.routeTable;
|
||||
message = "proxy-suite: proxy.tun.perApp.routeTable must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
value = perAppRoutingTproxy.fwmark;
|
||||
message = "proxy-suite: proxy.tproxy.perApp.fwmark must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable;
|
||||
value = perAppRoutingTproxy.routeTable;
|
||||
message = "proxy-suite: proxy.tproxy.perApp.routeTable must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.filterMark;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.qnum;
|
||||
message = "proxy-suite: zapret.perApp.qnum must be greater than zero";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy;
|
||||
value = tgWsProxyCfg.routingMark;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must be greater than zero";
|
||||
}
|
||||
];
|
||||
|
||||
localProxyAuthCfg = proxyCfg.auth;
|
||||
localProxyAuthUsed =
|
||||
localProxyAuthCfg.username != null
|
||||
|| localProxyAuthCfg.password != null
|
||||
|| localProxyAuthCfg.passwordFile != null;
|
||||
localProxyAuthAssertions = [
|
||||
(mkAssertion (
|
||||
!proxyEnabled || !localProxyAuthUsed || localProxyAuthCfg.username != null
|
||||
) "proxy-suite: proxy.auth requires username when password or passwordFile is set")
|
||||
(exactlyOneOf (proxyEnabled && localProxyAuthUsed) [
|
||||
localProxyAuthCfg.password
|
||||
localProxyAuthCfg.passwordFile
|
||||
] "proxy-suite: proxy.auth requires exactly one of password or passwordFile")
|
||||
];
|
||||
|
||||
forbiddenValueAssertions =
|
||||
@@ -212,48 +367,39 @@ let
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = globalTproxy.fwmark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: proxy.tproxy.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = globalTproxy.proxyMark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: proxy.tproxy.proxyMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTun.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTun.fwmark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: proxy.tun.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppRoutingTproxy.enable && perAppZapretCfg.enable;
|
||||
value = perAppRoutingTproxy.fwmark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
message = "proxy-suite: singBox.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: proxy.tproxy.perApp.fwmark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = perAppZapretCfg.enable;
|
||||
value = perAppZapretCfg.filterMark;
|
||||
disallowed = [
|
||||
67108864
|
||||
134217728
|
||||
];
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: zapret.perApp.filterMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
{
|
||||
condition = tgWsProxyCfg.enable && tgWsProxyCfg.bypassTransparentProxy && perAppZapretCfg.enable;
|
||||
value = tgWsProxyCfg.routingMark;
|
||||
disallowed = perAppZapretDesyncMarks;
|
||||
message = "proxy-suite: tgWsProxy.routingMark must not use per-app-zapret internal desync mark bits";
|
||||
}
|
||||
];
|
||||
|
||||
secretAssertions = [
|
||||
@@ -264,23 +410,42 @@ let
|
||||
];
|
||||
|
||||
outboundAssertions = lib.concatMap (ob: [
|
||||
(exactlyOneOf singBoxCfg.enable [
|
||||
ob.urlFile
|
||||
ob.url
|
||||
ob.json
|
||||
] "proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, or json")
|
||||
]) singBoxCfg.outbounds;
|
||||
(exactlyOneOf proxyEnabled
|
||||
[
|
||||
ob.urlFile
|
||||
ob.url
|
||||
ob.singBoxJson
|
||||
ob.xrayJson
|
||||
ob.json
|
||||
]
|
||||
"proxy-suite: outbound '${ob.tag}': set exactly one of urlFile, url, singBoxJson, xrayJson, or json"
|
||||
)
|
||||
(mkAssertion (
|
||||
!singBoxEnabled || hybridEnabled || ob.xrayJson == null
|
||||
) "proxy-suite: outbound '${ob.tag}': xrayJson is only available with proxy.xray.enable = true")
|
||||
(mkAssertion (!xrayEnabled || hybridEnabled || (ob.singBoxJson == null && ob.json == null))
|
||||
"proxy-suite: outbound '${ob.tag}': singBoxJson/json are only available with proxy.singBox.enable = true"
|
||||
)
|
||||
(mkAssertion (
|
||||
!(ob.backend == "xray") || xrayEnabled
|
||||
) "proxy-suite: outbound '${ob.tag}': backend = \"xray\" requires proxy.xray.enable = true")
|
||||
(mkAssertion (
|
||||
!(ob.backend == "sing-box") || singBoxEnabled
|
||||
) "proxy-suite: outbound '${ob.tag}': backend = \"sing-box\" requires proxy.singBox.enable = true")
|
||||
]) proxyCfg.outbounds;
|
||||
|
||||
subscriptionAssertions = lib.concatMap (sub: [
|
||||
(exactlyOneOf singBoxCfg.enable [
|
||||
(exactlyOneOf proxyEnabled [
|
||||
sub.urlFile
|
||||
sub.url
|
||||
] "proxy-suite: subscription '${sub.tag}': set exactly one of urlFile or url")
|
||||
]) singBoxCfg.subscriptions;
|
||||
]) proxyCfg.subscriptions;
|
||||
in
|
||||
featureAssertions
|
||||
++ perAppRoutingAssertions
|
||||
++ collisionAssertions
|
||||
++ positiveNumberAssertions
|
||||
++ localProxyAuthAssertions
|
||||
++ forbiddenValueAssertions
|
||||
++ secretAssertions
|
||||
++ outboundAssertions
|
||||
|
||||
@@ -46,6 +46,7 @@ rec {
|
||||
wants ? [ ],
|
||||
requires ? [ ],
|
||||
conflicts ? [ ],
|
||||
execStartPre ? null,
|
||||
execStartPost ? null,
|
||||
execStopPost ? null,
|
||||
extraServiceConfig ? { },
|
||||
@@ -70,6 +71,7 @@ rec {
|
||||
RuntimeDirectory = runtimeDirectory;
|
||||
}
|
||||
// lib.optionalAttrs (stateDirectory != null) { StateDirectory = stateDirectory; }
|
||||
// lib.optionalAttrs (execStartPre != null) { ExecStartPre = execStartPre; }
|
||||
// lib.optionalAttrs (execStartPost != null) { ExecStartPost = execStartPost; }
|
||||
// lib.optionalAttrs (execStopPost != null) { ExecStopPost = execStopPost; }
|
||||
// extraServiceConfig;
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
routeModeRulesFile,
|
||||
perAppTunChainFile,
|
||||
perAppTproxyRulesFile,
|
||||
perAppZapretRulesFile,
|
||||
@@ -18,6 +19,14 @@ let
|
||||
derived = import ../derived.nix { inherit lib cfg; };
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
xrayCfg
|
||||
proxyEnabled
|
||||
singBoxEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
activeBackend
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
@@ -37,7 +46,8 @@ let
|
||||
# Tool paths – defined once here and passed into sub-modules as needed.
|
||||
jq = "${pkgs.jq}/bin/jq";
|
||||
python3 = "${pkgs.python3}/bin/python3";
|
||||
singBox = "${pkgs.sing-box}/bin/sing-box";
|
||||
singBox = "${singBoxCfg.package}/bin/sing-box";
|
||||
xray = "${xrayCfg.package}/bin/xray";
|
||||
grepBin = "${pkgs.gnugrep}/bin/grep";
|
||||
awk = "${pkgs.gawk}/bin/awk";
|
||||
sleepBin = "${pkgs.coreutils}/bin/sleep";
|
||||
@@ -59,6 +69,15 @@ let
|
||||
lib
|
||||
pkgs
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
proxyEnabled
|
||||
singBoxEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
activeBackend
|
||||
perAppRoutingCfg
|
||||
userControlCfg
|
||||
perAppRoutingTun
|
||||
selectionMode
|
||||
collapseNamedOutbounds
|
||||
@@ -68,11 +87,17 @@ let
|
||||
jq
|
||||
python3
|
||||
singBox
|
||||
xray
|
||||
parserScriptsPythonPath
|
||||
buildOutboundPy
|
||||
fetchSubscriptionPy
|
||||
;
|
||||
inherit tproxyFile tunFile perAppTunFile;
|
||||
inherit
|
||||
tproxyFile
|
||||
tunFile
|
||||
perAppTunFile
|
||||
routeModeRulesFile
|
||||
;
|
||||
};
|
||||
|
||||
perAppRouting = import ./per-app-routing.nix {
|
||||
@@ -81,6 +106,8 @@ let
|
||||
pkgs
|
||||
cfg
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
pureXrayEnabled
|
||||
perAppRoutingCfg
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
@@ -102,14 +129,15 @@ let
|
||||
inherit
|
||||
packages
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
perAppRoutingCfg
|
||||
perAppRoutingTun
|
||||
perAppRoutingTproxy
|
||||
perAppZapretCfg
|
||||
selectionMode
|
||||
;
|
||||
zapretEnabled = cfg.zapret.enable;
|
||||
inherit (scripts) subscriptionTagsFile;
|
||||
inherit (scripts) subscriptionTagsFile subscriptionCacheDir;
|
||||
inherit (scripts) routeModeStateFile;
|
||||
inherit (perAppRouting)
|
||||
perAppRoutingProfilesFile
|
||||
proxychainsConfigFile
|
||||
@@ -121,6 +149,14 @@ in
|
||||
inherit
|
||||
derived
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
xrayCfg
|
||||
proxyEnabled
|
||||
singBoxEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
activeBackend
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
|
||||
@@ -2,16 +2,18 @@
|
||||
{
|
||||
packages,
|
||||
singBoxCfg,
|
||||
proxyCfg,
|
||||
perAppRoutingCfg,
|
||||
perAppRoutingTun,
|
||||
perAppRoutingTproxy,
|
||||
perAppZapretCfg,
|
||||
selectionMode,
|
||||
zapretEnabled,
|
||||
subscriptionTagsFile,
|
||||
subscriptionCacheDir,
|
||||
perAppRoutingProfilesFile,
|
||||
proxychainsConfigFile,
|
||||
proxychainsQuietArg,
|
||||
routeModeStateFile,
|
||||
}:
|
||||
{
|
||||
proxyCtl = packages.mkProxyCtl {
|
||||
@@ -19,14 +21,17 @@
|
||||
selection = selectionMode;
|
||||
inherit
|
||||
subscriptionTagsFile
|
||||
subscriptionCacheDir
|
||||
perAppRoutingProfilesFile
|
||||
proxychainsConfigFile
|
||||
proxychainsQuietArg
|
||||
routeModeStateFile
|
||||
;
|
||||
defaultRouteMode = if proxyCfg.proxyByDefault then "blacklist" else "whitelist";
|
||||
perAppRoutingEnabled = if perAppRoutingCfg.enable then "1" else "0";
|
||||
perAppRoutingProxychainsEnabled = if perAppRoutingCfg.proxychains.enable then "1" else "0";
|
||||
perAppRoutingTunEnabled = if perAppRoutingTun.enable then "1" else "0";
|
||||
perAppRoutingTproxyEnabled = if perAppRoutingTproxy.enable then "1" else "0";
|
||||
perAppRoutingZapretEnabled = if (perAppZapretCfg.enable && zapretEnabled) then "1" else "0";
|
||||
perAppRoutingZapretEnabled = if perAppZapretCfg.enable then "1" else "0";
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
# Assembles all sing-box systemd services from the sub-modules.
|
||||
# Assembles proxy-suite systemd services from the sub-modules.
|
||||
{
|
||||
config,
|
||||
lib,
|
||||
@@ -8,6 +8,7 @@
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
routeModeRulesFile,
|
||||
nftablesRulesFile,
|
||||
perAppTproxyRulesFile,
|
||||
perAppZapretRulesFile,
|
||||
@@ -26,6 +27,7 @@ let
|
||||
tproxyFile
|
||||
tunFile
|
||||
perAppTunFile
|
||||
routeModeRulesFile
|
||||
perAppTunChainFile
|
||||
perAppTproxyRulesFile
|
||||
perAppZapretRulesFile
|
||||
@@ -53,6 +55,12 @@ let
|
||||
|
||||
inherit (derived)
|
||||
singBoxCfg
|
||||
proxyCfg
|
||||
proxyEnabled
|
||||
xrayEnabled
|
||||
hybridEnabled
|
||||
pureXrayEnabled
|
||||
activeBackend
|
||||
perAppRoutingCfg
|
||||
globalTun
|
||||
globalTproxy
|
||||
@@ -79,26 +87,167 @@ let
|
||||
subscriptionUpdate = "proxy-suite-subscription-update";
|
||||
};
|
||||
|
||||
localProxyAuthEnabled =
|
||||
proxyCfg.auth.username != null
|
||||
&& (proxyCfg.auth.password != null || proxyCfg.auth.passwordFile != null);
|
||||
|
||||
# Must match the explicit iproute2_* indexes written to the global SingBox TUN
|
||||
# template in config.nix. XRay uses the same table for manual Linux
|
||||
# policy routing because XRay's autoSystemRoutingTable is not Linux-ready.
|
||||
tunAutoRouteTableIndex = 2022;
|
||||
tunAutoRouteRulePriority = 9000;
|
||||
# Keep app-scoped marks ahead of the global XRay TUN catch-all. Without
|
||||
# these priorities, iproute2's default priority lets global TUN capture
|
||||
# packets intended for per-app routing tables.
|
||||
xrayTunPerAppTproxyRulePriority = 8996;
|
||||
xrayTunPerAppTunRulePriority = 8997;
|
||||
xrayGlobalTunIPv6Address = "fd66:19::1/64";
|
||||
xrayGlobalTunIPv6RoutePrefix = "fd66:19::/64";
|
||||
|
||||
xrayTunUpScript = pkgs.writeShellScript "proxy-suite-xray-tun-up" ''
|
||||
set -euo pipefail
|
||||
|
||||
tun_cidr=${lib.escapeShellArg globalTun.address}
|
||||
tun6_cidr=${lib.escapeShellArg xrayGlobalTunIPv6Address}
|
||||
tun6_route_prefix=${lib.escapeShellArg xrayGlobalTunIPv6RoutePrefix}
|
||||
tun_addr=""
|
||||
tun_route_prefix=""
|
||||
uplink_addr=""
|
||||
|
||||
cidr_network() {
|
||||
local cidr="$1"
|
||||
local addr="''${cidr%/*}"
|
||||
local prefix="''${cidr#*/}"
|
||||
local o1 o2 o3 o4 ip mask net
|
||||
|
||||
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
|
||||
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
|
||||
if [ "$prefix" -eq 0 ]; then
|
||||
mask=0
|
||||
else
|
||||
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
|
||||
fi
|
||||
net=$((ip & mask))
|
||||
|
||||
printf '%d.%d.%d.%d/%s' \
|
||||
$(((net >> 24) & 255)) \
|
||||
$(((net >> 16) & 255)) \
|
||||
$(((net >> 8) & 255)) \
|
||||
$((net & 255)) \
|
||||
"$prefix"
|
||||
}
|
||||
|
||||
for _ in $(${pkgs.coreutils}/bin/seq 1 50); do
|
||||
if ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
|
||||
break
|
||||
fi
|
||||
${pkgs.coreutils}/bin/sleep 0.1
|
||||
done
|
||||
|
||||
if ! ${ip} link show dev ${lib.escapeShellArg globalTun.interface} >/dev/null 2>&1; then
|
||||
echo "proxy-suite: XRay TUN interface ${globalTun.interface} did not appear in time" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${pkgs.gawk}/bin/awk '
|
||||
/src/ {
|
||||
for (i = 1; i <= NF; i++) {
|
||||
if ($i == "src" && i + 1 <= NF) {
|
||||
print $(i + 1)
|
||||
exit
|
||||
}
|
||||
}
|
||||
}
|
||||
')"
|
||||
if [ -z "$uplink_addr" ]; then
|
||||
echo "proxy-suite: could not determine the default uplink IPv4 address for XRay TUN" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -4 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del pref ${toString tunAutoRouteRulePriority} 2>/dev/null; do :; done
|
||||
|
||||
tun_addr="''${tun_cidr%%/*}"
|
||||
tun_route_prefix="$(cidr_network "$tun_cidr")"
|
||||
|
||||
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg globalTun.interface}
|
||||
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg globalTun.interface}
|
||||
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg globalTun.interface} src "$tun_addr" table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -4 route replace default dev ${lib.escapeShellArg globalTun.interface} src "$uplink_addr" table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 route replace default dev ${lib.escapeShellArg globalTun.interface} table ${toString tunAutoRouteTableIndex}
|
||||
${lib.optionalString perAppRoutingTproxy.enable ''
|
||||
${ip} -4 rule add pref ${toString xrayTunPerAppTproxyRulePriority} fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
|
||||
''}
|
||||
${lib.optionalString perAppRoutingTun.enable ''
|
||||
${ip} -4 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -6 rule add pref ${toString xrayTunPerAppTunRulePriority} fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable}
|
||||
''}
|
||||
${ip} -4 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||
${ip} -6 rule add pref ${toString tunAutoRouteRulePriority} not fwmark ${toString globalTproxy.proxyMark} table ${toString tunAutoRouteTableIndex}
|
||||
'';
|
||||
|
||||
tproxyUpScript = pkgs.writeShellScript "proxy-suite-tproxy-up" ''
|
||||
set -euo pipefail
|
||||
|
||||
# Start from a clean policy-routing state. `ip rule add` permits duplicate
|
||||
# rules on some iproute2 versions, and a stale rule can keep packets routed
|
||||
# into a dead local table after a failed restart.
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
|
||||
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
|
||||
${nft} -f ${nftablesRulesFile}
|
||||
${ip} route add local default dev lo table ${toString globalTproxy.routeTable}
|
||||
${ip} route replace local default dev lo table ${toString globalTproxy.routeTable}
|
||||
${ip} rule add fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable}
|
||||
'';
|
||||
|
||||
tproxyDownScript = pkgs.writeShellScript "proxy-suite-tproxy-down" ''
|
||||
set +e
|
||||
|
||||
${nft} delete table ip singbox 2>/dev/null || true
|
||||
while ${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null; do :; done
|
||||
${ip} route del local default dev lo table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString globalTproxy.fwmark} table ${toString globalTproxy.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
tunCleanupScript = pkgs.writeShellScript "proxy-suite-tun-cleanup" ''
|
||||
set +e
|
||||
|
||||
# SingBox normally removes these on graceful shutdown, but stale
|
||||
# auto_route/auto_redirect state leaves the host routing through a dead TUN
|
||||
# interface after `proxy-ctl tun off` or an unclean service stop.
|
||||
${nft} delete table inet sing-box 2>/dev/null || true
|
||||
|
||||
while ${ip} -4 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del table ${toString tunAutoRouteTableIndex} 2>/dev/null; do :; done
|
||||
while ${ip} -4 rule del pref ${toString xrayTunPerAppTproxyRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -4 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del pref ${toString xrayTunPerAppTunRulePriority} 2>/dev/null; do :; done
|
||||
${ip} -4 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
|
||||
${ip} -6 route flush table ${toString tunAutoRouteTableIndex} 2>/dev/null || true
|
||||
|
||||
${ip} link del dev ${lib.escapeShellArg globalTun.interface} 2>/dev/null || true
|
||||
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
|
||||
'';
|
||||
|
||||
systemServiceEntries = [
|
||||
{
|
||||
enable = singBoxCfg.enable;
|
||||
enable = proxyEnabled;
|
||||
name = serviceNames.socks;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network.target" ];
|
||||
description = "${
|
||||
if pureXrayEnabled then
|
||||
"XRay"
|
||||
else if hybridEnabled then
|
||||
"sing-box + XRay sidecar"
|
||||
else
|
||||
"sing-box"
|
||||
} proxy client (SOCKS + TProxy-ready)";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
execStart = scripts.startSocks;
|
||||
runtimeDirectory = serviceNames.socks;
|
||||
@@ -106,10 +255,10 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && globalTproxy.enable;
|
||||
enable = proxyEnabled && globalTproxy.enable;
|
||||
name = serviceNames.tproxy;
|
||||
value = mkOneshotService {
|
||||
description = "sing-box TProxy – nftables rules and policy routing";
|
||||
description = "proxy-suite TProxy - nftables rules and policy routing";
|
||||
after = [
|
||||
"network.target"
|
||||
"${serviceNames.socks}.service"
|
||||
@@ -125,26 +274,37 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && globalTun.enable;
|
||||
enable = proxyEnabled && globalTun.enable;
|
||||
name = serviceNames.tun;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box TUN proxy client";
|
||||
description = "${
|
||||
if pureXrayEnabled then
|
||||
"XRay"
|
||||
else if hybridEnabled then
|
||||
"sing-box + XRay sidecar"
|
||||
else
|
||||
"sing-box"
|
||||
} TUN proxy client";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = lib.optionals globalTun.autostart [ "multi-user.target" ];
|
||||
conflicts = [ "${serviceNames.tproxy}.service" ];
|
||||
execStartPre = tunCleanupScript;
|
||||
execStart = scripts.startTun;
|
||||
execStartPost = if pureXrayEnabled then xrayTunUpScript else null;
|
||||
execStopPost = tunCleanupScript;
|
||||
runtimeDirectory = serviceNames.tun;
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTun.enable;
|
||||
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||
name = serviceNames.perAppTun;
|
||||
value = mkRestartingService {
|
||||
description = "sing-box per-app-routing TUN backend";
|
||||
description = "proxy-suite per-app-routing TUN backend";
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
execStartPre = perAppRouting.perAppTunDownScript;
|
||||
execStart = scripts.startPerAppTun;
|
||||
execStartPost = perAppRouting.perAppTunUpScript;
|
||||
execStopPost = perAppRouting.perAppTunDownScript;
|
||||
@@ -153,7 +313,7 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTun.enable;
|
||||
enable = proxyEnabled && perAppRoutingTun.enable;
|
||||
name = "${serviceNames.perAppTun}-user@";
|
||||
value = mkUserRuleService {
|
||||
description = "Enable proxy-suite app TUN marking for user %i";
|
||||
@@ -163,7 +323,7 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTproxy.enable;
|
||||
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||
name = serviceNames.perAppTproxy;
|
||||
value = mkOneshotService {
|
||||
description = "proxy-suite per-app-routing TProxy backend";
|
||||
@@ -181,7 +341,7 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && perAppRoutingTproxy.enable;
|
||||
enable = proxyEnabled && perAppRoutingTproxy.enable;
|
||||
name = "${serviceNames.perAppTproxy}-user@";
|
||||
value = mkUserRuleService {
|
||||
description = "Enable proxy-suite app TProxy marking for user %i";
|
||||
@@ -201,7 +361,7 @@ let
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = singBoxCfg.enable && hasSubscriptions;
|
||||
enable = proxyEnabled && hasSubscriptions;
|
||||
name = serviceNames.subscriptionUpdate;
|
||||
value = mkOneshotService {
|
||||
description = "Refresh proxy-suite subscription caches";
|
||||
@@ -211,6 +371,15 @@ let
|
||||
stateDirectory = "proxy-suite";
|
||||
};
|
||||
}
|
||||
{
|
||||
enable = proxyEnabled;
|
||||
name = "proxy-suite-route-mode@";
|
||||
value = mkOneshotService {
|
||||
description = "Set proxy-suite route mode to %i";
|
||||
execStart = "${scripts.setRouteModeScript} %i";
|
||||
extraServiceConfig.RemainAfterExit = false;
|
||||
};
|
||||
}
|
||||
];
|
||||
|
||||
userServiceEntries = [
|
||||
@@ -233,14 +402,14 @@ let
|
||||
|
||||
timerEntries = [
|
||||
{
|
||||
enable = singBoxCfg.enable && hasSubscriptions;
|
||||
enable = proxyEnabled && hasSubscriptions;
|
||||
name = serviceNames.subscriptionUpdate;
|
||||
value = {
|
||||
description = "Periodic proxy-suite subscription refresh";
|
||||
wantedBy = [ "timers.target" ];
|
||||
timerConfig = {
|
||||
OnBootSec = "5m";
|
||||
OnUnitActiveSec = singBoxCfg.subscriptionUpdateInterval;
|
||||
OnUnitActiveSec = proxyCfg.subscriptionUpdateInterval;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -249,12 +418,17 @@ in
|
||||
{
|
||||
environment.systemPackages = [ control.proxyCtl ];
|
||||
|
||||
# nftables must be on for TProxy to work.
|
||||
# nftables must be on for transparent routing backends. Global TUN uses
|
||||
# SingBox auto_redirect programs an `inet sing-box` nftables table.
|
||||
networking.nftables.enable = lib.mkIf (
|
||||
globalTproxy.enable || perAppRoutingTun.enable || perAppRoutingTproxy.enable || perAppZapretEnabled
|
||||
globalTun.enable
|
||||
|| globalTproxy.enable
|
||||
|| perAppRoutingTun.enable
|
||||
|| perAppRoutingTproxy.enable
|
||||
|| perAppZapretEnabled
|
||||
) (lib.mkDefault true);
|
||||
|
||||
users.groups = lib.mkIf (cfg.enable && userControlEnabled) {
|
||||
users.groups = lib.mkIf (cfg.enable && (userControlEnabled || localProxyAuthEnabled)) {
|
||||
"${userControlCfg.group}" = { };
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
pkgs,
|
||||
cfg,
|
||||
singBoxCfg,
|
||||
proxyCfg,
|
||||
pureXrayEnabled,
|
||||
perAppRoutingCfg,
|
||||
perAppRoutingTun,
|
||||
perAppRoutingTproxy,
|
||||
@@ -49,7 +51,7 @@ let
|
||||
route = "tproxy";
|
||||
}
|
||||
]
|
||||
++ lib.optionals (perAppZapretCfg.enable && cfg.zapret.enable) [
|
||||
++ lib.optionals perAppZapretCfg.enable [
|
||||
{
|
||||
name = "zapret";
|
||||
route = "zapret";
|
||||
@@ -62,21 +64,29 @@ let
|
||||
profile: !(builtins.elem profile.name perAppRoutingProfileNames)
|
||||
) defaultPerAppRoutingProfiles;
|
||||
effectivePerAppRoutingProfileNames = map (profile: profile.name) effectivePerAppRoutingProfiles;
|
||||
localProxyAuth = proxyCfg.auth;
|
||||
localProxyAuthEnabled =
|
||||
localProxyAuth.username != null
|
||||
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
|
||||
|
||||
perAppRoutingProfilesFile = pkgs.writeText "proxy-suite-per-app-routing-profiles.json" (
|
||||
builtins.toJSON effectivePerAppRoutingProfiles
|
||||
);
|
||||
|
||||
proxychainsConfigFile = pkgs.writeText "proxy-suite-proxychains.conf" ''
|
||||
strict_chain
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
|
||||
tcp_read_time_out 15000
|
||||
tcp_connect_time_out 8000
|
||||
proxychainsConfigFile =
|
||||
if localProxyAuthEnabled then
|
||||
"/run/proxy-suite-socks/proxychains.conf"
|
||||
else
|
||||
pkgs.writeText "proxy-suite-proxychains.conf" ''
|
||||
strict_chain
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.quiet "quiet_mode"}
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "proxy_dns"}
|
||||
tcp_read_time_out 15000
|
||||
tcp_connect_time_out 8000
|
||||
|
||||
[ProxyList]
|
||||
socks5 ${singBoxCfg.listenAddress} ${toString singBoxCfg.port}
|
||||
'';
|
||||
[ProxyList]
|
||||
socks5 ${proxyCfg.listenAddress} ${toString proxyCfg.port}
|
||||
'';
|
||||
proxychainsQuietArg = lib.optionalString perAppRoutingCfg.proxychains.quiet "-q ";
|
||||
|
||||
hasProxychainsProfiles = builtins.any (
|
||||
@@ -89,6 +99,8 @@ let
|
||||
hasZapretProfiles = builtins.any (
|
||||
profile: profile.route == "zapret"
|
||||
) effectivePerAppRoutingProfiles;
|
||||
xrayPerAppTunIPv6Address = "fd66:20::1/64";
|
||||
xrayPerAppTunIPv6RoutePrefix = "fd66:20::/64";
|
||||
|
||||
perAppTunWaitForInterface = pkgs.writeShellScript "proxy-suite-per-app-tun-wait-for-interface" ''
|
||||
set -euo pipefail
|
||||
@@ -104,33 +116,103 @@ let
|
||||
|
||||
perAppTunUpScript = pkgs.writeShellScript "proxy-suite-per-app-tun-up" ''
|
||||
set -euo pipefail
|
||||
|
||||
tun_cidr=${lib.escapeShellArg perAppRoutingTun.address}
|
||||
tun6_cidr=${lib.escapeShellArg xrayPerAppTunIPv6Address}
|
||||
tun6_route_prefix=${lib.escapeShellArg xrayPerAppTunIPv6RoutePrefix}
|
||||
tun_addr=""
|
||||
tun_route_prefix=""
|
||||
uplink_addr=""
|
||||
|
||||
cidr_network() {
|
||||
local cidr="$1"
|
||||
local addr="''${cidr%/*}"
|
||||
local prefix="''${cidr#*/}"
|
||||
local o1 o2 o3 o4 ip mask net
|
||||
|
||||
IFS=. read -r o1 o2 o3 o4 <<<"$addr"
|
||||
ip=$(((o1 << 24) | (o2 << 16) | (o3 << 8) | o4))
|
||||
if [ "$prefix" -eq 0 ]; then
|
||||
mask=0
|
||||
else
|
||||
mask=$(((0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF))
|
||||
fi
|
||||
net=$((ip & mask))
|
||||
|
||||
printf '%d.%d.%d.%d/%s' \
|
||||
$(((net >> 24) & 255)) \
|
||||
$(((net >> 16) & 255)) \
|
||||
$(((net >> 8) & 255)) \
|
||||
$((net & 255)) \
|
||||
"$prefix"
|
||||
}
|
||||
|
||||
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${nft} -f ${perAppTunChainFile}
|
||||
${perAppTunWaitForInterface}
|
||||
${ip} route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
uplink_addr="$(${ip} -4 route get 1.1.1.1 2>/dev/null | ${awk} '
|
||||
/src/ {
|
||||
for (i = 1; i <= NF; i++) {
|
||||
if ($i == "src" && i + 1 <= NF) {
|
||||
print $(i + 1)
|
||||
exit
|
||||
}
|
||||
}
|
||||
}
|
||||
')"
|
||||
if [ -z "$uplink_addr" ]; then
|
||||
echo "proxy-suite: could not determine the default uplink IPv4 address for app TUN" >&2
|
||||
exit 1
|
||||
fi
|
||||
tun_addr="''${tun_cidr%%/*}"
|
||||
tun_route_prefix="$(cidr_network "$tun_cidr")"
|
||||
${ip} -4 addr replace "$tun_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
|
||||
${ip} -4 route replace "$tun_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$tun_addr" table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -4 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} src "$uplink_addr" table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -4 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${lib.optionalString pureXrayEnabled ''
|
||||
${ip} -6 addr replace "$tun6_cidr" dev ${lib.escapeShellArg perAppRoutingTun.interface}
|
||||
${ip} -6 route replace "$tun6_route_prefix" dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -6 route replace default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable}
|
||||
${ip} -6 rule add fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
''}
|
||||
'';
|
||||
|
||||
perAppTunDownScript = pkgs.writeShellScript "proxy-suite-per-app-tun-down" ''
|
||||
set -euo pipefail
|
||||
set +e
|
||||
|
||||
# Best-effort cleanup for graceful stops and for unclean previous exits.
|
||||
${nft} delete table inet proxy_suite_per_app_tun 2>/dev/null || true
|
||||
${ip} route del default dev ${lib.escapeShellArg perAppRoutingTun.interface} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
while ${ip} -4 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del fwmark ${toString perAppRoutingTun.fwmark} table ${toString perAppRoutingTun.routeTable} 2>/dev/null; do :; done
|
||||
${ip} -4 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${ip} -6 route flush table ${toString perAppRoutingTun.routeTable} 2>/dev/null || true
|
||||
${ip} link del dev ${lib.escapeShellArg perAppRoutingTun.interface} 2>/dev/null || true
|
||||
${pkgs.systemd}/bin/resolvectl flush-caches 2>/dev/null || true
|
||||
'';
|
||||
|
||||
perAppTproxyUpScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-up" ''
|
||||
set -euo pipefail
|
||||
|
||||
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
|
||||
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
|
||||
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||
|
||||
${nft} -f ${perAppTproxyRulesFile}
|
||||
${ip} route replace local default dev lo table ${toString perAppRoutingTproxy.routeTable}
|
||||
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule add fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable}
|
||||
'';
|
||||
|
||||
perAppTproxyDownScript = pkgs.writeShellScript "proxy-suite-per-app-tproxy-down" ''
|
||||
set -euo pipefail
|
||||
set +e
|
||||
|
||||
${nft} delete table ip proxy_suite_per_app_tproxy 2>/dev/null || true
|
||||
while ${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null; do :; done
|
||||
${ip} route del local default dev lo table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||
${ip} rule del fwmark ${toString perAppRoutingTproxy.fwmark} table ${toString perAppRoutingTproxy.routeTable} 2>/dev/null || true
|
||||
'';
|
||||
|
||||
# Generate a "start" script that adds a per-user cgroup nftables mark rule.
|
||||
|
||||
@@ -1,8 +1,17 @@
|
||||
# Generates the sing-box startup scripts and subscription management scripts.
|
||||
# Generates proxy backend startup scripts and subscription management scripts.
|
||||
{
|
||||
lib,
|
||||
pkgs,
|
||||
singBoxCfg,
|
||||
proxyCfg,
|
||||
proxyEnabled,
|
||||
singBoxEnabled,
|
||||
xrayEnabled,
|
||||
hybridEnabled,
|
||||
pureXrayEnabled,
|
||||
activeBackend,
|
||||
perAppRoutingCfg,
|
||||
userControlCfg,
|
||||
perAppRoutingTun,
|
||||
selectionMode,
|
||||
collapseNamedOutbounds,
|
||||
@@ -10,17 +19,45 @@
|
||||
jq,
|
||||
python3,
|
||||
singBox,
|
||||
xray,
|
||||
parserScriptsPythonPath,
|
||||
buildOutboundPy,
|
||||
fetchSubscriptionPy,
|
||||
tproxyFile,
|
||||
tunFile,
|
||||
perAppTunFile,
|
||||
routeModeRulesFile,
|
||||
}:
|
||||
|
||||
let
|
||||
globalTproxy = singBoxCfg.tproxy;
|
||||
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions";
|
||||
globalTproxy = proxyCfg.tproxy;
|
||||
systemctl = "${pkgs.systemd}/bin/systemctl";
|
||||
backend = if activeBackend == null then "sing-box" else activeBackend;
|
||||
mainBackend = if pureXrayEnabled then "xray" else "sing-box";
|
||||
subscriptionBackend =
|
||||
if hybridEnabled then
|
||||
"hybrid"
|
||||
else
|
||||
mainBackend;
|
||||
backendArg = "--backend ${mainBackend}";
|
||||
subscriptionBackendArg = "--backend ${subscriptionBackend}";
|
||||
backendBin = if pureXrayEnabled then xray else singBox;
|
||||
localProxyAuth = proxyCfg.auth;
|
||||
localProxyAuthEnabled =
|
||||
localProxyAuth.username != null
|
||||
&& (localProxyAuth.password != null || localProxyAuth.passwordFile != null);
|
||||
localProxyAuthPasswordSource =
|
||||
if localProxyAuth.passwordFile != null then
|
||||
localProxyAuth.passwordFile
|
||||
else if localProxyAuth.password != null then
|
||||
pkgs.writeText "proxy-suite-local-proxy-password" localProxyAuth.password
|
||||
else
|
||||
null;
|
||||
subscriptionCacheDir = "/var/lib/proxy-suite/subscriptions/${backend}";
|
||||
routeModeStateFile = "/run/proxy-suite/route-mode";
|
||||
xrayLoglevelFile = "/run/proxy-suite/xray-loglevel";
|
||||
runtimeProxychainsConfig = "/run/proxy-suite-socks/proxychains.conf";
|
||||
xraySidecarRoutingMark = globalTproxy.proxyMark;
|
||||
|
||||
mkSubscriptionCacheFile = sub: "${subscriptionCacheDir}/${sub.tag}.json";
|
||||
|
||||
@@ -38,96 +75,386 @@ let
|
||||
in
|
||||
''
|
||||
printf '%s' "$(cat "${urlSource}")" \
|
||||
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} --tag-prefix ${lib.escapeShellArg sub.tag}
|
||||
| PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${fetchSubscriptionPy} ${subscriptionBackendArg} --tag-prefix ${lib.escapeShellArg sub.tag}
|
||||
'';
|
||||
|
||||
# Build the shell code block for a single outbound entry.
|
||||
# tag overrides ob.tag (used in "first" mode to force tag = "proxy").
|
||||
# routingMark is null or an int; added to outbound JSON if set.
|
||||
subscriptionCacheHelpersBlock = lib.optionalString hasSubscriptions ''
|
||||
_proxy_suite_valid_subscription_cache() {
|
||||
[ -s "$1" ] && ${jq} -e ${
|
||||
lib.escapeShellArg (
|
||||
if hybridEnabled then
|
||||
''type == "object" and (.singBox | type == "array") and (.xray | type == "array")''
|
||||
else
|
||||
''type == "array"''
|
||||
)
|
||||
} "$1" >/dev/null 2>&1
|
||||
}
|
||||
|
||||
_proxy_suite_commit_subscription_cache() {
|
||||
local tmp="$1" target="$2" tag="$3"
|
||||
if _proxy_suite_valid_subscription_cache "$tmp"; then
|
||||
mv "$tmp" "$target"
|
||||
return 0
|
||||
fi
|
||||
rm -f "$tmp"
|
||||
echo "proxy-suite: warning: subscription '$tag' produced an invalid cache; ignoring it" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
_proxy_suite_drop_invalid_subscription_cache() {
|
||||
local target="$1" tag="$2"
|
||||
if [ -f "$target" ] && ! _proxy_suite_valid_subscription_cache "$target"; then
|
||||
rm -f "$target"
|
||||
echo "proxy-suite: warning: removed invalid subscription cache for '$tag'" >&2
|
||||
fi
|
||||
}
|
||||
'';
|
||||
|
||||
routingMarkJq =
|
||||
routingMark:
|
||||
if routingMark == null then
|
||||
""
|
||||
else if pureXrayEnabled then
|
||||
" | .streamSettings.sockopt.mark = ${toString routingMark}"
|
||||
else
|
||||
" | .routing_mark = ${toString routingMark}";
|
||||
|
||||
rawOutboundJson =
|
||||
ob: tag: routingMark:
|
||||
let
|
||||
backendRaw =
|
||||
if pureXrayEnabled then
|
||||
ob.xrayJson
|
||||
else if ob.singBoxJson != null then
|
||||
ob.singBoxJson
|
||||
else
|
||||
ob.json;
|
||||
markAttrs =
|
||||
if routingMark == null then
|
||||
{ }
|
||||
else if pureXrayEnabled then
|
||||
{ streamSettings.sockopt.mark = routingMark; }
|
||||
else
|
||||
{ routing_mark = routingMark; };
|
||||
taggedRaw = backendRaw // {
|
||||
inherit tag;
|
||||
};
|
||||
in
|
||||
if pureXrayEnabled then lib.recursiveUpdate taggedRaw markAttrs else taggedRaw // markAttrs;
|
||||
|
||||
mkOutboundBlock =
|
||||
ob: routingMark: tag:
|
||||
let
|
||||
markArg = lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}";
|
||||
backendRaw =
|
||||
if pureXrayEnabled then
|
||||
ob.xrayJson
|
||||
else if ob.singBoxJson != null then
|
||||
ob.singBoxJson
|
||||
else
|
||||
ob.json;
|
||||
in
|
||||
if ob.json != null then
|
||||
if backendRaw != null then
|
||||
let
|
||||
outboundJson = builtins.toJSON (
|
||||
ob.json // { tag = tag; } // lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; }
|
||||
);
|
||||
outboundJson = builtins.toJSON (rawOutboundJson ob tag routingMark);
|
||||
jsonFile = pkgs.writeText "proxy-suite-ob-${tag}.json" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (static json)
|
||||
# outbound: ${tag} (static ${backend} json)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else
|
||||
let
|
||||
urlSource =
|
||||
if ob.urlFile != null then
|
||||
ob.urlFile
|
||||
else
|
||||
# Literal URL – write to nix store so the script can cat it.
|
||||
# Less secret than urlFile, but convenient for non-sensitive configs.
|
||||
pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag}
|
||||
URL=$(cat "${urlSource}")
|
||||
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --tag ${lib.escapeShellArg tag}${markArg})
|
||||
OB_JSON=$(printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} ${backendArg} --tag ${lib.escapeShellArg tag}${
|
||||
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
|
||||
})
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$OB_JSON" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
|
||||
# Build the shell code block for a single subscription entry.
|
||||
# Fetches subscription into the cache on first run; subsequent starts use the cache.
|
||||
singBoxRawOutboundJson =
|
||||
ob: tag: routingMark:
|
||||
let
|
||||
backendRaw = if ob.singBoxJson != null then ob.singBoxJson else ob.json;
|
||||
markAttrs = lib.optionalAttrs (routingMark != null) { routing_mark = routingMark; };
|
||||
in
|
||||
backendRaw // { inherit tag; } // markAttrs;
|
||||
|
||||
xrayRawOutboundJson =
|
||||
ob: tag:
|
||||
lib.recursiveUpdate (ob.xrayJson // { inherit tag; }) {
|
||||
streamSettings.sockopt = {
|
||||
mark = xraySidecarRoutingMark;
|
||||
domainStrategy = "UseIP";
|
||||
};
|
||||
};
|
||||
|
||||
mkHybridOutboundBlock =
|
||||
ob: routingMark: tag:
|
||||
if ob.xrayJson != null then
|
||||
let
|
||||
outboundJson = builtins.toJSON (xrayRawOutboundJson ob tag);
|
||||
jsonFile = pkgs.writeText "proxy-suite-xray-sidecar-ob-${tag}.json" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (hybrid XRay json sidecar)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
|
||||
''
|
||||
else if ob.singBoxJson != null || ob.json != null then
|
||||
let
|
||||
outboundJson = builtins.toJSON (singBoxRawOutboundJson ob tag routingMark);
|
||||
jsonFile = pkgs.writeText "proxy-suite-sing-box-ob-${tag}.json" outboundJson;
|
||||
in
|
||||
''
|
||||
# outbound: ${tag} (hybrid SingBox json)
|
||||
OB_JSON=$(cat "${jsonFile}")
|
||||
_proxy_suite_add_sing_box_ob "$OB_JSON"
|
||||
''
|
||||
else
|
||||
let
|
||||
urlSource =
|
||||
if ob.urlFile != null then ob.urlFile else pkgs.writeText "proxy-suite-url-${ob.tag}" ob.url;
|
||||
singBoxCommand = ''
|
||||
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend sing-box --tag ${lib.escapeShellArg tag}${
|
||||
lib.optionalString (routingMark != null) " --routing-mark ${toString routingMark}"
|
||||
}
|
||||
'';
|
||||
xrayCommand = ''
|
||||
printf '%s' "$URL" | PYTHONPATH="${parserScriptsPythonPath}" ${python3} ${buildOutboundPy} --backend xray --tag ${lib.escapeShellArg tag} --routing-mark ${toString xraySidecarRoutingMark}
|
||||
'';
|
||||
in
|
||||
if ob.backend == "xray" then
|
||||
''
|
||||
# outbound: ${tag} (hybrid forced XRay sidecar)
|
||||
URL=$(cat "${urlSource}")
|
||||
OB_JSON=$(${xrayCommand})
|
||||
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
|
||||
''
|
||||
else if ob.backend == "sing-box" then
|
||||
''
|
||||
# outbound: ${tag} (hybrid forced SingBox)
|
||||
URL=$(cat "${urlSource}")
|
||||
OB_JSON=$(${singBoxCommand})
|
||||
_proxy_suite_add_sing_box_ob "$OB_JSON"
|
||||
''
|
||||
else
|
||||
''
|
||||
# outbound: ${tag} (hybrid auto)
|
||||
URL=$(cat "${urlSource}")
|
||||
if OB_JSON=$(${singBoxCommand} 2>"$RUNTIME_DIR/sing-box-parser.err"); then
|
||||
_proxy_suite_add_sing_box_ob "$OB_JSON"
|
||||
else
|
||||
SING_BOX_PARSE_ERROR="$(cat "$RUNTIME_DIR/sing-box-parser.err" 2>/dev/null || true)"
|
||||
if OB_JSON=$(${xrayCommand}); then
|
||||
_proxy_suite_add_xray_sidecar_ob "$OB_JSON" ${lib.escapeShellArg tag}
|
||||
else
|
||||
echo "proxy-suite: outbound '${tag}' cannot be parsed by SingBox or XRay" >&2
|
||||
if [ -n "$SING_BOX_PARSE_ERROR" ]; then
|
||||
printf '%s\n' "$SING_BOX_PARSE_ERROR" >&2
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
'';
|
||||
|
||||
mkSubscriptionBlock =
|
||||
sub: routingMark:
|
||||
let
|
||||
cacheFile = mkSubscriptionCacheFile sub;
|
||||
markFilter = routingMarkJq routingMark;
|
||||
in
|
||||
''
|
||||
# subscription: ${sub.tag}
|
||||
CACHE_DIR="${subscriptionCacheDir}"
|
||||
CACHE_FILE="${cacheFile}"
|
||||
_proxy_suite_drop_invalid_subscription_cache "$CACHE_FILE" ${lib.escapeShellArg sub.tag}
|
||||
if [ ! -f "$CACHE_FILE" ]; then
|
||||
mkdir -p "$CACHE_DIR"
|
||||
if ${mkSubscriptionFetchCommand sub} > "$CACHE_FILE.tmp"; then
|
||||
mv "$CACHE_FILE.tmp" "$CACHE_FILE"
|
||||
_proxy_suite_commit_subscription_cache "$CACHE_FILE.tmp" "$CACHE_FILE" ${lib.escapeShellArg sub.tag} || true
|
||||
else
|
||||
rm -f "$CACHE_FILE.tmp"
|
||||
echo "proxy-suite: warning: could not fetch subscription '${sub.tag}'" >&2
|
||||
fi
|
||||
fi
|
||||
if [ -f "$CACHE_FILE" ]; then
|
||||
SUB_JSON=$(cat "$CACHE_FILE")
|
||||
${
|
||||
lib.optionalString (routingMark != null) ''
|
||||
SUB_JSON=$(${jq} --argjson m ${toString routingMark} 'map(. + {routing_mark: $m})' <<< "$SUB_JSON")
|
||||
${
|
||||
if hybridEnabled then
|
||||
''
|
||||
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
fi
|
||||
if [ -f "$CACHE_FILE" ]; then
|
||||
SUB_SING_BOX_JSON=$(${jq} -c '.singBox' "$CACHE_FILE")
|
||||
${
|
||||
lib.optionalString (routingMark != null) ''
|
||||
SUB_SING_BOX_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_SING_BOX_JSON")
|
||||
''
|
||||
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_SING_BOX_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
while IFS= read -r SUB_XRAY_OB; do
|
||||
SUB_XRAY_TAG="$(${jq} -r '.tag' <<< "$SUB_XRAY_OB")"
|
||||
_proxy_suite_add_xray_sidecar_ob "$SUB_XRAY_OB" "$SUB_XRAY_TAG"
|
||||
done < <(${jq} -c '.xray[]' "$CACHE_FILE")
|
||||
fi
|
||||
''
|
||||
else
|
||||
''
|
||||
if [ -f "$CACHE_FILE" ]; then
|
||||
SUB_JSON=$(cat "$CACHE_FILE")
|
||||
${
|
||||
lib.optionalString (routingMark != null) ''
|
||||
SUB_JSON=$(${jq} 'map(.${markFilter})' <<< "$SUB_JSON")
|
||||
''
|
||||
}OUTBOUNDS_JSON=$(${jq} --argjson sub "$SUB_JSON" '. + $sub' <<< "$OUTBOUNDS_JSON")
|
||||
fi
|
||||
''
|
||||
}
|
||||
'';
|
||||
|
||||
xrayUrltestTagFilter = ''
|
||||
OUTBOUNDS_JSON=$(${jq} 'map(.tag = ("proxy-suite-ob-" + .tag))' <<< "$OUTBOUNDS_JSON")
|
||||
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 1 ]; then
|
||||
XRAY_SINGLE_PROXY_TAG="$(${jq} -r '.[0].tag' <<< "$OUTBOUNDS_JSON")"
|
||||
fi
|
||||
'';
|
||||
|
||||
hybridRuntimeHelpersBlock =
|
||||
routingMark: xraySidecarBasePort: xrayDnsBridgePort:
|
||||
lib.optionalString hybridEnabled ''
|
||||
XRAY_OUTBOUNDS_JSON='[]'
|
||||
XRAY_INBOUNDS_JSON='[]'
|
||||
XRAY_ROUTE_RULES_JSON='[]'
|
||||
XRAY_SIDECAR_NEXT_PORT=${toString xraySidecarBasePort}
|
||||
XRAY_SIDECAR_DNS_PORT=${toString xrayDnsBridgePort}
|
||||
|
||||
_proxy_suite_add_sing_box_ob() {
|
||||
local ob="$1"
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
}
|
||||
|
||||
_proxy_suite_next_xray_sidecar_port() {
|
||||
local port="$XRAY_SIDECAR_NEXT_PORT"
|
||||
XRAY_SIDECAR_NEXT_PORT=$((XRAY_SIDECAR_NEXT_PORT + 1))
|
||||
printf '%s\n' "$port"
|
||||
}
|
||||
|
||||
_proxy_suite_add_xray_sidecar_ob() {
|
||||
local ob="$1" tag="$2" port auth inbound_tag sing_ob inbound route_rule
|
||||
port="$(_proxy_suite_next_xray_sidecar_port)"
|
||||
auth="proxy-suite-xray-$port"
|
||||
inbound_tag="$tag-inbound"
|
||||
ob=$(${jq} \
|
||||
--arg tag "$tag" \
|
||||
--argjson mark ${toString xraySidecarRoutingMark} \
|
||||
'.tag = $tag
|
||||
| .streamSettings = (.streamSettings // {})
|
||||
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||
| .streamSettings.sockopt.mark = $mark
|
||||
| .streamSettings.sockopt.domainStrategy = (.streamSettings.sockopt.domainStrategy // "UseIP")' \
|
||||
<<< "$ob")
|
||||
XRAY_OUTBOUNDS_JSON=$(${jq} --argjson ob "$ob" '. + [$ob]' <<< "$XRAY_OUTBOUNDS_JSON")
|
||||
inbound=$(${jq} -n \
|
||||
--arg tag "$inbound_tag" \
|
||||
--arg auth "$auth" \
|
||||
--argjson port "$port" \
|
||||
'{tag:$tag,listen:"127.0.0.1",port:$port,protocol:"socks",settings:{auth:"password",udp:true,accounts:[{user:$auth,pass:$auth}]}}')
|
||||
XRAY_INBOUNDS_JSON=$(${jq} --argjson inbound "$inbound" '. + [$inbound]' <<< "$XRAY_INBOUNDS_JSON")
|
||||
route_rule=$(${jq} -n \
|
||||
--arg inbound "$inbound_tag" \
|
||||
--arg outbound "$tag" \
|
||||
'{type:"field",inboundTag:[$inbound],outboundTag:$outbound}')
|
||||
XRAY_ROUTE_RULES_JSON=$(${jq} --argjson rule "$route_rule" '. + [$rule]' <<< "$XRAY_ROUTE_RULES_JSON")
|
||||
sing_ob=$(${jq} -n \
|
||||
--arg tag "$tag" \
|
||||
--arg auth "$auth" \
|
||||
--argjson port "$port" \
|
||||
'{type:"socks",tag:$tag,server:"127.0.0.1",server_port:$port,version:"5",username:$auth,password:$auth${
|
||||
lib.optionalString (routingMark != null) ",routing_mark:${toString routingMark}"
|
||||
}}')
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson ob "$sing_ob" '. + [$ob]' <<< "$OUTBOUNDS_JSON")
|
||||
}
|
||||
|
||||
_proxy_suite_write_xray_sidecar_config() {
|
||||
if [ "$(${jq} 'length' <<< "$XRAY_OUTBOUNDS_JSON")" -eq 0 ]; then
|
||||
return 0
|
||||
fi
|
||||
${jq} -n \
|
||||
--arg loglevel "$XRAY_LOGLEVEL" \
|
||||
--arg bind_interface "$XRAY_TUN_BIND_INTERFACE" \
|
||||
--argjson dns_port "$XRAY_SIDECAR_DNS_PORT" \
|
||||
--argjson inbounds "$XRAY_INBOUNDS_JSON" \
|
||||
--argjson outbounds "$XRAY_OUTBOUNDS_JSON" \
|
||||
--argjson route_rules "$XRAY_ROUTE_RULES_JSON" \
|
||||
'
|
||||
def bind_xray_sidecar($interface):
|
||||
if $interface == "" then
|
||||
.
|
||||
else
|
||||
.streamSettings = (.streamSettings // {})
|
||||
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||
| if (.streamSettings.sockopt.interface? // "") == "" then
|
||||
.streamSettings.sockopt.interface = $interface
|
||||
else
|
||||
.
|
||||
end
|
||||
end;
|
||||
{
|
||||
log: {
|
||||
loglevel: (if $loglevel == "" then "warning" else $loglevel end),
|
||||
access: "none"
|
||||
},
|
||||
dns: {
|
||||
servers: [
|
||||
{
|
||||
address: "127.0.0.1",
|
||||
port: $dns_port,
|
||||
queryStrategy: "UseIP",
|
||||
skipFallBack: true
|
||||
}
|
||||
]
|
||||
},
|
||||
inbounds: $inbounds,
|
||||
outbounds: (($outbounds | map(bind_xray_sidecar($bind_interface))) + [{protocol:"freedom",tag:"direct"}]),
|
||||
routing: {
|
||||
domainStrategy: "AsIs",
|
||||
rules: ($route_rules + [{type:"field",ip:["127.0.0.1"],port:$dns_port,outboundTag:"direct"}])
|
||||
}
|
||||
}' > "$RUNTIME_DIR/xray-sidecar.json"
|
||||
}
|
||||
'';
|
||||
|
||||
# Shell code that builds all outbounds, then optionally adds a selector/urltest wrapper.
|
||||
mkOutboundScript =
|
||||
routingMark:
|
||||
let
|
||||
outboundBlocks =
|
||||
if collapseNamedOutbounds && singBoxCfg.outbounds != [ ] then
|
||||
# Only the first static outbound, tagged "proxy" so sing-box routes to it.
|
||||
mkOutboundBlock (builtins.head singBoxCfg.outbounds) routingMark "proxy"
|
||||
if collapseNamedOutbounds && proxyCfg.outbounds != [ ] then
|
||||
(if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock)
|
||||
(builtins.head proxyCfg.outbounds)
|
||||
routingMark
|
||||
"proxy"
|
||||
else
|
||||
lib.concatMapStrings (ob: mkOutboundBlock ob routingMark ob.tag) singBoxCfg.outbounds;
|
||||
lib.concatMapStrings (
|
||||
ob: (if hybridEnabled then mkHybridOutboundBlock else mkOutboundBlock) ob routingMark ob.tag
|
||||
) proxyCfg.outbounds;
|
||||
|
||||
subscriptionBlocks = lib.concatMapStrings (
|
||||
sub: mkSubscriptionBlock sub routingMark
|
||||
) singBoxCfg.subscriptions;
|
||||
) proxyCfg.subscriptions;
|
||||
|
||||
requireOutboundsBlock = ''
|
||||
if [ "$(${jq} 'length' <<< "$OUTBOUNDS_JSON")" -eq 0 ]; then
|
||||
echo "proxy-suite: no proxy outbounds are available; check static outbound definitions and subscription caches" >&2
|
||||
exit 1
|
||||
fi
|
||||
'';
|
||||
|
||||
wrapperBlock =
|
||||
if collapseNamedOutbounds then
|
||||
# When there are no static outbounds, subscription outbounds keep their
|
||||
# real tags. Rename the first one to "proxy" so routing rules resolve.
|
||||
lib.optionalString (singBoxCfg.outbounds == [ ] && singBoxCfg.subscriptions != [ ]) ''
|
||||
if pureXrayEnabled && selectionMode == "urltest" then
|
||||
xrayUrltestTagFilter
|
||||
else if collapseNamedOutbounds then
|
||||
lib.optionalString (proxyCfg.outbounds == [ ] && proxyCfg.subscriptions != [ ]) ''
|
||||
FIRST_TAG=$(${jq} -r 'if length > 0 then .[0].tag else "" end' <<< "$OUTBOUNDS_JSON")
|
||||
if [ -n "$FIRST_TAG" ]; then
|
||||
OUTBOUNDS_JSON=$(${jq} --arg t "$FIRST_TAG" \
|
||||
@@ -145,19 +472,219 @@ let
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
''
|
||||
else
|
||||
# urltest
|
||||
''
|
||||
TAGS=$(${jq} '[.[].tag]' <<< "$OUTBOUNDS_JSON")
|
||||
WRAPPER=$(${jq} -n \
|
||||
--argjson tags "$TAGS" \
|
||||
--arg url ${lib.escapeShellArg singBoxCfg.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg singBoxCfg.urlTest.interval} \
|
||||
--arg url ${lib.escapeShellArg proxyCfg.urlTest.url} \
|
||||
--arg interval ${lib.escapeShellArg proxyCfg.urlTest.interval} \
|
||||
--argjson tolerance ${toString singBoxCfg.urlTest.tolerance} \
|
||||
'{type:"urltest",tag:"proxy",outbounds:$tags,url:$url,interval:$interval,tolerance:$tolerance}')
|
||||
OUTBOUNDS_JSON=$(${jq} --argjson w "$WRAPPER" '[$w] + .' <<< "$OUTBOUNDS_JSON")
|
||||
'';
|
||||
in
|
||||
outboundBlocks + subscriptionBlocks + wrapperBlock;
|
||||
outboundBlocks + subscriptionBlocks + requireOutboundsBlock + wrapperBlock;
|
||||
|
||||
writeProxychainsConfigBlock = ''
|
||||
{
|
||||
printf '%s\n' 'strict_chain'
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.quiet "printf '%s\\n' 'quiet_mode'"}
|
||||
${lib.optionalString perAppRoutingCfg.proxychains.proxyDns "printf '%s\\n' 'proxy_dns'"}
|
||||
printf '%s\n' 'tcp_read_time_out 15000'
|
||||
printf '%s\n' 'tcp_connect_time_out 8000'
|
||||
printf '\n%s\n' '[ProxyList]'
|
||||
printf 'socks5 %s %s %s %s\n' \
|
||||
${lib.escapeShellArg proxyCfg.listenAddress} \
|
||||
${lib.escapeShellArg (toString proxyCfg.port)} \
|
||||
${lib.escapeShellArg localProxyAuth.username} \
|
||||
"$LOCAL_PROXY_PASSWORD"
|
||||
} > "${runtimeProxychainsConfig}"
|
||||
${pkgs.coreutils}/bin/chgrp ${lib.escapeShellArg userControlCfg.group} "${runtimeProxychainsConfig}"
|
||||
chmod 640 "${runtimeProxychainsConfig}"
|
||||
'';
|
||||
|
||||
restartActiveConfigConsumersBlock =
|
||||
lib.concatMapStrings
|
||||
(svc: ''
|
||||
if ${systemctl} is-active --quiet ${svc}; then
|
||||
${systemctl} restart ${svc}
|
||||
fi
|
||||
'')
|
||||
[
|
||||
"proxy-suite-socks"
|
||||
"proxy-suite-tun"
|
||||
"proxy-suite-per-app-tun"
|
||||
];
|
||||
|
||||
routeModeBlacklistTail =
|
||||
if pureXrayEnabled then
|
||||
''
|
||||
+ .proxyGeo
|
||||
+ .block
|
||||
''
|
||||
else
|
||||
''
|
||||
+ .block
|
||||
+ .proxyGeo
|
||||
'';
|
||||
|
||||
routeModeCaseBlock = ''
|
||||
if [ -r "$ROUTE_MODE_STATE_FILE" ]; then
|
||||
ROUTE_MODE="$(tr -d '\r\n[:space:]' < "$ROUTE_MODE_STATE_FILE" 2>/dev/null || true)"
|
||||
fi
|
||||
case "$ROUTE_MODE" in
|
||||
blacklist)
|
||||
ROUTE_FINAL="proxy"
|
||||
DNS_FINAL="remote"
|
||||
ROUTE_MODE_ACTIVE=true
|
||||
ROUTE_RULES_JSON=$(${jq} -c '
|
||||
.common
|
||||
+ (.custom | map(.entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .direct
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
' "${routeModeRulesFile}")
|
||||
;;
|
||||
whitelist)
|
||||
ROUTE_FINAL="direct"
|
||||
DNS_FINAL="local"
|
||||
ROUTE_MODE_ACTIVE=true
|
||||
ROUTE_RULES_JSON=$(${jq} -c '
|
||||
.common
|
||||
+ (.custom | map(.entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .direct
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
' "${routeModeRulesFile}")
|
||||
;;
|
||||
all-proxy)
|
||||
ROUTE_FINAL="proxy"
|
||||
DNS_FINAL="remote"
|
||||
ROUTE_MODE_ACTIVE=true
|
||||
CLEAR_DNS_RULES=true
|
||||
ROUTE_RULES_JSON=$(${jq} -c '
|
||||
.common
|
||||
+ (.custom | map(select(.category == "proxy" or .category == "block") | .entries) | add // [])
|
||||
+ .proxyPrimary
|
||||
+ .safetyDirect
|
||||
${routeModeBlacklistTail}
|
||||
' "${routeModeRulesFile}")
|
||||
;;
|
||||
all-bypass)
|
||||
ROUTE_FINAL="direct"
|
||||
DNS_FINAL="local"
|
||||
ROUTE_MODE_ACTIVE=true
|
||||
CLEAR_DNS_RULES=true
|
||||
ROUTE_RULES_JSON=$(${jq} -c '
|
||||
.common
|
||||
+ (.custom | map(select(.category == "block") | .entries) | add // [])
|
||||
+ .safetyDirect
|
||||
+ .block
|
||||
' "${routeModeRulesFile}")
|
||||
;;
|
||||
*)
|
||||
ROUTE_MODE=""
|
||||
;;
|
||||
esac
|
||||
'';
|
||||
|
||||
mkBackendJqFilter =
|
||||
if pureXrayEnabled then
|
||||
''
|
||||
def xray_bind_outbound($interface):
|
||||
if $interface == "" or .protocol == "blackhole" or .protocol == "dns" then
|
||||
.
|
||||
else
|
||||
.streamSettings = (.streamSettings // {})
|
||||
| .streamSettings.sockopt = (.streamSettings.sockopt // {})
|
||||
| if (.streamSettings.sockopt.interface? // "") == "" then
|
||||
.streamSettings.sockopt.interface = $interface
|
||||
else
|
||||
.
|
||||
end
|
||||
end;
|
||||
def xray_proxy_rule_target($single_tag):
|
||||
if $single_tag != "" then
|
||||
{outboundTag:$single_tag}
|
||||
else
|
||||
{balancerTag:"proxy"}
|
||||
end;
|
||||
def xray_rewrite_proxy_rule($single_tag):
|
||||
if $single_tag != "" and (.balancerTag? // "") == "proxy" then
|
||||
.outboundTag = $single_tag | del(.balancerTag)
|
||||
else
|
||||
.
|
||||
end;
|
||||
def xray_preserved_rules:
|
||||
[.routing.rules[]
|
||||
| select(((.ruleTag? // "") == "dns-hijack") or ((.ruleTag? // "") == "dns-upstream-direct"))];
|
||||
def xray_final_rule($tag; $single_tag):
|
||||
if $tag == "proxy" and "${selectionMode}" == "urltest" then
|
||||
{type:"field",network:"tcp,udp",ruleTag:"final-default"} + xray_proxy_rule_target($single_tag)
|
||||
else
|
||||
{type:"field",network:"tcp,udp",ruleTag:"final-default",outboundTag:$tag}
|
||||
end;
|
||||
def xray_dns_server_order($dns_final):
|
||||
if $dns_final == "" then
|
||||
.dns.servers
|
||||
else
|
||||
([.dns.servers[] | select((.tag? // "") == "fakedns")]
|
||||
+ [.dns.servers[] | select((.tag? // "") == $dns_final)]
|
||||
+ [.dns.servers[] | select((.tag? // "") != "fakedns" and (.tag? // "") != $dns_final)])
|
||||
end;
|
||||
def xray_tun_dns_addresses($dns_final; $local_addr; $remote_addr):
|
||||
if $dns_final == "local" then
|
||||
[$local_addr, $remote_addr]
|
||||
elif $dns_final == "remote" then
|
||||
[$remote_addr, $local_addr]
|
||||
else
|
||||
[$remote_addr, $local_addr]
|
||||
end;
|
||||
.outbounds = (($obs + .outbounds) | map(xray_bind_outbound($xray_bind_interface)))
|
||||
| if $xray_loglevel == "" then . else .log.loglevel = $xray_loglevel end
|
||||
| if $auth_enabled then
|
||||
(.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.auth) = "password"
|
||||
| (.inbounds[] | select(.protocol == "socks" and .tag == "mixed-in") | .settings.accounts) = [{user:$user,pass:$password}]
|
||||
else . end
|
||||
| if $xray_tun_dns_runtime then
|
||||
.dns.servers = xray_dns_server_order($dns_final)
|
||||
| if $dns_final == "" then
|
||||
.
|
||||
else
|
||||
(.inbounds[] | select(.protocol == "tun" and .tag == "tun-in") | .settings.dns) = xray_tun_dns_addresses($dns_final; $xray_dns_local_client; $xray_dns_remote_client)
|
||||
end
|
||||
else . end
|
||||
| if $route_enabled then
|
||||
.routing.rules = (xray_preserved_rules + $route_rules + [xray_final_rule($route_final; $xray_single_proxy_tag)])
|
||||
else . end
|
||||
| if $xray_single_proxy_tag == "" then
|
||||
.
|
||||
else
|
||||
.routing.rules |= map(xray_rewrite_proxy_rule($xray_single_proxy_tag))
|
||||
| del(.routing.balancers)
|
||||
| del(.observatory)
|
||||
end
|
||||
''
|
||||
else
|
||||
''
|
||||
def sing_box_preserved_rules:
|
||||
[.route.rules[]
|
||||
| select(((.action? // "") == "hijack-dns")
|
||||
and (((.inbound? // []) | index("xray-dns-in")) != null))];
|
||||
.outbounds = $obs + .outbounds
|
||||
| if $auth_enabled then
|
||||
(.inbounds[] | select(.type == "mixed" and .tag == "mixed-in") | .users) = [{username:$user,password:$password}]
|
||||
else . end
|
||||
| if $route_enabled then
|
||||
.route.rules = (sing_box_preserved_rules + $route_rules)
|
||||
| .route.final = $route_final
|
||||
| .dns.final = $dns_final
|
||||
| if $clear_dns_rules then .dns.rules = [] else . end
|
||||
else . end
|
||||
'';
|
||||
backendJqFilterFile = pkgs.writeText "proxy-suite-${backend}-backend-filter.jq" mkBackendJqFilter;
|
||||
|
||||
mkStartScript =
|
||||
{
|
||||
@@ -165,20 +692,121 @@ let
|
||||
runtimeDir,
|
||||
configFile,
|
||||
routingMark ? null,
|
||||
enableLocalProxyAuth ? false,
|
||||
xrayTunEgressBinding ? false,
|
||||
xrayTunDnsRuntime ? false,
|
||||
xraySidecarBasePort ? 33080,
|
||||
xrayDnsBridgePort ? 18533,
|
||||
}:
|
||||
pkgs.writeShellScript name ''
|
||||
set -euo pipefail
|
||||
RUNTIME_DIR="${runtimeDir}"
|
||||
ROUTE_MODE_STATE_FILE="${routeModeStateFile}"
|
||||
BACKEND_JQ_FILTER=${lib.escapeShellArg backendJqFilterFile}
|
||||
XRAY_LOGLEVEL=""
|
||||
XRAY_TUN_BIND_INTERFACE=""
|
||||
XRAY_SINGLE_PROXY_TAG=""
|
||||
mkdir -p "$RUNTIME_DIR"
|
||||
OUTBOUNDS_JSON='[]'
|
||||
ROUTE_MODE=""
|
||||
ROUTE_FINAL=""
|
||||
DNS_FINAL=""
|
||||
ROUTE_RULES_JSON='[]'
|
||||
ROUTE_MODE_ACTIVE=false
|
||||
CLEAR_DNS_RULES=false
|
||||
${hybridRuntimeHelpersBlock routingMark xraySidecarBasePort xrayDnsBridgePort}
|
||||
${subscriptionCacheHelpersBlock}
|
||||
${lib.optionalString enableLocalProxyAuth ''
|
||||
umask 077
|
||||
LOCAL_PROXY_PASSWORD="$(cat "${localProxyAuthPasswordSource}")"
|
||||
${writeProxychainsConfigBlock}
|
||||
''}
|
||||
${lib.optionalString xrayEnabled ''
|
||||
if [ -r "${xrayLoglevelFile}" ]; then
|
||||
XRAY_LOGLEVEL="$(tr -d '\r\n[:space:]' < "${xrayLoglevelFile}" 2>/dev/null || true)"
|
||||
fi
|
||||
''}
|
||||
${lib.optionalString xrayTunEgressBinding ''
|
||||
XRAY_TUN_BIND_INTERFACE="$(${pkgs.iproute2}/bin/ip -4 route get 1.1.1.1 mark ${toString globalTproxy.proxyMark} 2>/dev/null | ${pkgs.gawk}/bin/awk '
|
||||
/dev/ {
|
||||
for (i = 1; i <= NF; i++) {
|
||||
if ($i == "dev" && i + 1 <= NF) {
|
||||
print $(i + 1)
|
||||
exit
|
||||
}
|
||||
}
|
||||
}
|
||||
')"
|
||||
if [ -z "$XRAY_TUN_BIND_INTERFACE" ]; then
|
||||
echo "proxy-suite: could not determine the default uplink interface for XRay TUN" >&2
|
||||
exit 1
|
||||
fi
|
||||
''}
|
||||
|
||||
${routeModeCaseBlock}
|
||||
|
||||
${mkOutboundScript routingMark}
|
||||
${lib.optionalString hybridEnabled "_proxy_suite_write_xray_sidecar_config"}
|
||||
|
||||
${jq} --argjson obs "$OUTBOUNDS_JSON" \
|
||||
'.outbounds = $obs + .outbounds' \
|
||||
${jq} \
|
||||
--argjson obs "$OUTBOUNDS_JSON" \
|
||||
--argjson auth_enabled ${if enableLocalProxyAuth then "true" else "false"} \
|
||||
--arg user ${if enableLocalProxyAuth then lib.escapeShellArg localProxyAuth.username else "''"} \
|
||||
--arg password ${if enableLocalProxyAuth then "\"$LOCAL_PROXY_PASSWORD\"" else "''"} \
|
||||
--argjson route_enabled "$ROUTE_MODE_ACTIVE" \
|
||||
--argjson route_rules "$ROUTE_RULES_JSON" \
|
||||
--arg route_final "$ROUTE_FINAL" \
|
||||
--arg dns_final "$DNS_FINAL" \
|
||||
--argjson clear_dns_rules "$CLEAR_DNS_RULES" \
|
||||
--arg xray_loglevel "$XRAY_LOGLEVEL" \
|
||||
--arg xray_bind_interface "$XRAY_TUN_BIND_INTERFACE" \
|
||||
--arg xray_single_proxy_tag "$XRAY_SINGLE_PROXY_TAG" \
|
||||
--argjson xray_tun_dns_runtime ${if xrayTunDnsRuntime then "true" else "false"} \
|
||||
--arg xray_dns_local_client ${lib.escapeShellArg proxyCfg.dns.local.address} \
|
||||
--arg xray_dns_remote_client ${lib.escapeShellArg proxyCfg.dns.remote.address} \
|
||||
-f "$BACKEND_JQ_FILTER" \
|
||||
"${configFile}" > "$RUNTIME_DIR/config.json"
|
||||
${lib.optionalString enableLocalProxyAuth ''
|
||||
chmod 600 "$RUNTIME_DIR/config.json"
|
||||
''}
|
||||
|
||||
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||
${
|
||||
if hybridEnabled then
|
||||
''
|
||||
if [ -s "$RUNTIME_DIR/xray-sidecar.json" ]; then
|
||||
XRAY_SIDECAR_PID=""
|
||||
_proxy_suite_cleanup_xray_sidecar() {
|
||||
if [ -n "$XRAY_SIDECAR_PID" ]; then
|
||||
kill "$XRAY_SIDECAR_PID" 2>/dev/null || true
|
||||
wait "$XRAY_SIDECAR_PID" 2>/dev/null || true
|
||||
fi
|
||||
}
|
||||
trap _proxy_suite_cleanup_xray_sidecar EXIT
|
||||
trap 'exit 143' INT TERM
|
||||
|
||||
${xray} run -c "$RUNTIME_DIR/xray-sidecar.json" &
|
||||
XRAY_SIDECAR_PID="$!"
|
||||
${pkgs.coreutils}/bin/sleep 0.2
|
||||
if ! kill -0 "$XRAY_SIDECAR_PID" 2>/dev/null; then
|
||||
XRAY_SIDECAR_STATUS=1
|
||||
wait "$XRAY_SIDECAR_PID" || XRAY_SIDECAR_STATUS="$?"
|
||||
exit "$XRAY_SIDECAR_STATUS"
|
||||
fi
|
||||
|
||||
${singBox} run -c "$RUNTIME_DIR/config.json" &
|
||||
SING_BOX_PID="$!"
|
||||
SING_BOX_STATUS=0
|
||||
wait "$SING_BOX_PID" || SING_BOX_STATUS="$?"
|
||||
exit "$SING_BOX_STATUS"
|
||||
fi
|
||||
|
||||
exec ${singBox} run -c "$RUNTIME_DIR/config.json"
|
||||
''
|
||||
else
|
||||
''
|
||||
exec ${backendBin} run -c "$RUNTIME_DIR/config.json"
|
||||
''
|
||||
}
|
||||
'';
|
||||
|
||||
startSocks = mkStartScript {
|
||||
@@ -186,25 +814,33 @@ let
|
||||
runtimeDir = "/run/proxy-suite-socks";
|
||||
configFile = tproxyFile;
|
||||
routingMark = globalTproxy.proxyMark;
|
||||
enableLocalProxyAuth = localProxyAuthEnabled;
|
||||
xraySidecarBasePort = 33080;
|
||||
xrayDnsBridgePort = 18533;
|
||||
};
|
||||
|
||||
startTun = mkStartScript {
|
||||
name = "proxy-suite-start-tun";
|
||||
runtimeDir = "/run/proxy-suite-tun";
|
||||
configFile = tunFile;
|
||||
routingMark = null;
|
||||
routingMark = if pureXrayEnabled then globalTproxy.proxyMark else null;
|
||||
xrayTunEgressBinding = xrayEnabled;
|
||||
xrayTunDnsRuntime = pureXrayEnabled;
|
||||
xraySidecarBasePort = 33180;
|
||||
xrayDnsBridgePort = 18534;
|
||||
};
|
||||
|
||||
startPerAppTun = mkStartScript {
|
||||
name = "proxy-suite-start-per-app-tun";
|
||||
runtimeDir = "/run/proxy-suite-per-app-tun";
|
||||
configFile = perAppTunFile;
|
||||
# Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN
|
||||
# proxy outbounds with a host-global mark.
|
||||
routingMark = if globalTproxy.enable then globalTproxy.proxyMark else null;
|
||||
routingMark = if xrayEnabled || globalTproxy.enable then globalTproxy.proxyMark else null;
|
||||
xrayTunEgressBinding = xrayEnabled;
|
||||
xrayTunDnsRuntime = pureXrayEnabled;
|
||||
xraySidecarBasePort = 33280;
|
||||
xrayDnsBridgePort = 18535;
|
||||
};
|
||||
|
||||
# Shell code to fetch a single subscription into the cache (used in update service).
|
||||
mkSubscriptionFetchBlock =
|
||||
sub:
|
||||
let
|
||||
@@ -212,8 +848,11 @@ let
|
||||
in
|
||||
''
|
||||
if ${mkSubscriptionFetchCommand sub} > "${cacheFile}.tmp"; then
|
||||
mv "${cacheFile}.tmp" "${cacheFile}"
|
||||
echo "Updated subscription: ${sub.tag}"
|
||||
if _proxy_suite_commit_subscription_cache "${cacheFile}.tmp" "${cacheFile}" ${lib.escapeShellArg sub.tag}; then
|
||||
echo "Updated subscription: ${sub.tag}"
|
||||
else
|
||||
FAILED=1
|
||||
fi
|
||||
else
|
||||
rm -f "${cacheFile}.tmp"
|
||||
echo "proxy-suite: failed to update subscription '${sub.tag}'" >&2
|
||||
@@ -226,35 +865,59 @@ let
|
||||
CACHE_DIR="${subscriptionCacheDir}"
|
||||
mkdir -p "$CACHE_DIR"
|
||||
FAILED=0
|
||||
SOCKS_WAS_ACTIVE=0
|
||||
TUN_WAS_ACTIVE=0
|
||||
PER_APP_TUN_WAS_ACTIVE=0
|
||||
|
||||
systemctl is-active --quiet proxy-suite-socks && SOCKS_WAS_ACTIVE=1 || true
|
||||
systemctl is-active --quiet proxy-suite-tun && TUN_WAS_ACTIVE=1 || true
|
||||
systemctl is-active --quiet proxy-suite-per-app-tun && PER_APP_TUN_WAS_ACTIVE=1 || true
|
||||
|
||||
${lib.concatMapStrings mkSubscriptionFetchBlock singBoxCfg.subscriptions}
|
||||
${subscriptionCacheHelpersBlock}
|
||||
${lib.concatMapStrings mkSubscriptionFetchBlock proxyCfg.subscriptions}
|
||||
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
if [ "$SOCKS_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-socks
|
||||
fi
|
||||
if [ "$TUN_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-tun
|
||||
fi
|
||||
if [ "$PER_APP_TUN_WAS_ACTIVE" -eq 1 ]; then
|
||||
systemctl restart proxy-suite-per-app-tun
|
||||
fi
|
||||
${restartActiveConfigConsumersBlock}
|
||||
fi
|
||||
exit "$FAILED"
|
||||
'';
|
||||
|
||||
setRouteModeScript = pkgs.writeShellScript "proxy-suite-set-route-mode" ''
|
||||
set -euo pipefail
|
||||
mode="''${1:-}"
|
||||
|
||||
case "$mode" in
|
||||
default)
|
||||
;;
|
||||
whitelist)
|
||||
;;
|
||||
blacklist)
|
||||
;;
|
||||
all-proxy)
|
||||
;;
|
||||
all-bypass)
|
||||
;;
|
||||
*)
|
||||
echo "proxy-suite: route mode must be default, whitelist, blacklist, all-proxy, or all-bypass" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
mkdir -p "$(dirname "${routeModeStateFile}")"
|
||||
if [ "$mode" = "default" ]; then
|
||||
rm -f "${routeModeStateFile}"
|
||||
else
|
||||
printf '%s\n' "$mode" > "${routeModeStateFile}"
|
||||
fi
|
||||
|
||||
${restartActiveConfigConsumersBlock}
|
||||
'';
|
||||
|
||||
subscriptionTagsFile = pkgs.writeText "proxy-suite-subscription-tags.json" (
|
||||
builtins.toJSON (map (sub: sub.tag) singBoxCfg.subscriptions)
|
||||
builtins.toJSON (map (sub: sub.tag) proxyCfg.subscriptions)
|
||||
);
|
||||
in
|
||||
{
|
||||
inherit startSocks startTun startPerAppTun;
|
||||
inherit subscriptionUpdateScript hasSubscriptions subscriptionTagsFile;
|
||||
inherit
|
||||
routeModeStateFile
|
||||
setRouteModeScript
|
||||
subscriptionUpdateScript
|
||||
hasSubscriptions
|
||||
subscriptionTagsFile
|
||||
subscriptionCacheDir
|
||||
runtimeProxychainsConfig
|
||||
;
|
||||
}
|
||||
@@ -9,30 +9,81 @@
|
||||
let
|
||||
t = cfg.tgWsProxy;
|
||||
tgPkg = packages.tg-ws-proxy;
|
||||
ip = "${pkgs.iproute2}/bin/ip";
|
||||
|
||||
dcArgs = lib.concatMapStrings (id: " --dc-ip=${id}:${t.dcIps.${id}}") (builtins.attrNames t.dcIps);
|
||||
transparentBypassEnabled =
|
||||
t.bypassTransparentProxy && cfg.proxy.enable && (cfg.proxy.tun.enable || cfg.proxy.tproxy.enable);
|
||||
bypassRulePriority = 8999;
|
||||
|
||||
mkValueArg = name: value: " args+=(${name}=${lib.escapeShellArg value})\n";
|
||||
mkRawValueArg = name: value: " args+=(${name}=${toString value})\n";
|
||||
mkFlagArg = condition: name: lib.optionalString condition " args+=(${name})\n";
|
||||
mkOptionalValueArg =
|
||||
condition: name: value:
|
||||
lib.optionalString condition (mkValueArg name value);
|
||||
mkRepeatedValueArgs = name: values: lib.concatMapStrings (value: mkValueArg name value) values;
|
||||
dcArgs = lib.concatMapStrings (id: mkValueArg "--dc-ip" "${id}:${t.dcIps.${id}}") (
|
||||
builtins.attrNames t.dcIps
|
||||
);
|
||||
startScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-start" ''
|
||||
exec ${tgPkg}/bin/tg-ws-proxy \
|
||||
--port=${toString t.port} \
|
||||
--host=${t.host} \
|
||||
${
|
||||
if t.secretFile != null then
|
||||
"--secret-file=$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret"
|
||||
else
|
||||
"--secret=${t.secret}"
|
||||
}${dcArgs}
|
||||
args=(
|
||||
--port=${toString t.port}
|
||||
--host=${lib.escapeShellArg t.host}
|
||||
)
|
||||
${
|
||||
if t.secretFile != null then
|
||||
''args+=(--secret-file="$CREDENTIALS_DIRECTORY/tg_ws_proxy_secret")''
|
||||
else
|
||||
"args+=(--secret=${lib.escapeShellArg t.secret})"
|
||||
}
|
||||
${dcArgs}${mkFlagArg t.verbose "--verbose"}${
|
||||
mkOptionalValueArg (t.logFile != null) "--log-file" t.logFile
|
||||
}${lib.optionalString (t.logFile != null) (mkRawValueArg "--log-max-mb" t.logMaxMb)}${
|
||||
lib.optionalString (t.logFile != null) (mkRawValueArg "--log-backups" t.logBackups)
|
||||
}${mkRawValueArg "--buf-kb" t.bufKb}${mkRawValueArg "--pool-size" t.poolSize}${mkRepeatedValueArgs "--cfproxy-domain" t.cfProxyDomains}${mkRepeatedValueArgs "--cfproxy-worker-domain" t.cfProxyWorkerDomains}${
|
||||
mkFlagArg (!t.cfProxyFallback) "--no-cfproxy"
|
||||
}${
|
||||
mkOptionalValueArg (t.fakeTlsDomain != null) "--fake-tls-domain" t.fakeTlsDomain
|
||||
}${mkFlagArg t.proxyProtocol "--proxy-protocol"}${mkRawValueArg "--ws-keepalive" t.wsKeepalive}
|
||||
exec ${tgPkg}/bin/tg-ws-proxy "''${args[@]}"
|
||||
'';
|
||||
|
||||
bypassUpScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-up" ''
|
||||
set -euo pipefail
|
||||
|
||||
add_bypass_rule() {
|
||||
local family="$1"
|
||||
while ${ip} "$family" rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
|
||||
${ip} "$family" rule add pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null || true
|
||||
}
|
||||
|
||||
add_bypass_rule -4
|
||||
add_bypass_rule -6
|
||||
'';
|
||||
|
||||
bypassDownScript = pkgs.writeShellScript "proxy-suite-tg-ws-proxy-bypass-down" ''
|
||||
set +e
|
||||
|
||||
while ${ip} -4 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
|
||||
while ${ip} -6 rule del pref ${toString bypassRulePriority} fwmark ${toString t.routingMark} lookup main 2>/dev/null; do :; done
|
||||
'';
|
||||
in
|
||||
{
|
||||
systemd.services.proxy-suite-tg-ws-proxy = {
|
||||
description = "Telegram MTProto WebSocket proxy";
|
||||
after = [ "network.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
serviceConfig = {
|
||||
ExecStart = "${startScript}";
|
||||
LoadCredential = lib.optional (t.secretFile != null) "tg_ws_proxy_secret:${t.secretFile}";
|
||||
Restart = "on-failure";
|
||||
RestartSec = 5;
|
||||
}
|
||||
// lib.optionalAttrs transparentBypassEnabled {
|
||||
ExecStartPre = bypassUpScript;
|
||||
ExecStopPost = bypassDownScript;
|
||||
SocketMark = toString t.routingMark;
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -296,14 +296,22 @@ let
|
||||
${nft} delete table inet proxy_suite_per_app_zapret_mark 2>/dev/null || true
|
||||
'';
|
||||
|
||||
exemptStart = lib.concatMapStrings (cidr: ''
|
||||
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
||||
exemptStart = ''
|
||||
set -euo pipefail
|
||||
''
|
||||
+ lib.concatMapStrings (cidr: ''
|
||||
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
|
||||
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
|
||||
'') zapretCfg.cidrExemption.cidrs;
|
||||
|
||||
exemptStop = lib.concatMapStrings (cidr: ''
|
||||
${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN || true
|
||||
${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN || true
|
||||
exemptStop = ''
|
||||
set +e
|
||||
''
|
||||
+ lib.concatMapStrings (cidr: ''
|
||||
while ${iptables} -t mangle -D FORWARD -d ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||
while ${iptables} -t mangle -D POSTROUTING -s ${cidr} -j RETURN 2>/dev/null; do :; done
|
||||
'') zapretCfg.cidrExemption.cidrs;
|
||||
in
|
||||
{
|
||||
@@ -325,12 +333,14 @@ in
|
||||
];
|
||||
|
||||
environment.systemPackages = lib.mkBefore (
|
||||
[ globalZapretPackage ] ++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
|
||||
lib.optionals zapretCfg.enable [ globalZapretPackage ]
|
||||
++ lib.optionals perAppZapretCfg.enable [ perAppZapretPackage ]
|
||||
);
|
||||
|
||||
systemd.services.zapret-discord-youtube = mkOneshotService {
|
||||
systemd.services.zapret-discord-youtube = lib.mkIf zapretCfg.enable (mkOneshotService {
|
||||
description = "zapret DPI bypass";
|
||||
after = [ "network.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
wantedBy = [ "multi-user.target" ];
|
||||
preStart = zapretCommonPreStart globalZapretPackage;
|
||||
runtimeDirectory = "proxy-suite-zapret";
|
||||
@@ -340,11 +350,12 @@ in
|
||||
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
|
||||
Environment = globalZapretEnv;
|
||||
};
|
||||
};
|
||||
});
|
||||
|
||||
systemd.services.proxy-suite-per-app-zapret = lib.mkIf perAppZapretCfg.enable (mkOneshotService {
|
||||
description = "proxy-suite per-app-routing zapret backend";
|
||||
after = [ "network.target" ];
|
||||
after = [ "network-online.target" ];
|
||||
wants = [ "network-online.target" ];
|
||||
conflicts = [
|
||||
"proxy-suite-tproxy.service"
|
||||
"proxy-suite-tun.service"
|
||||
@@ -359,7 +370,7 @@ in
|
||||
});
|
||||
|
||||
systemd.services.proxy-suite-zapret-vm-exempt =
|
||||
lib.mkIf zapretCfg.cidrExemption.enable
|
||||
lib.mkIf (zapretCfg.enable && zapretCfg.cidrExemption.enable)
|
||||
(mkOneshotService {
|
||||
description = "Exempt CIDRs from zapret NFQUEUE";
|
||||
after = [ "zapret-discord-youtube.service" ];
|
||||
|
||||
+1722
-231
File diff suppressed because it is too large.
Load diff
+60
-8
@@ -19,6 +19,41 @@ let
|
||||
];
|
||||
};
|
||||
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module");
|
||||
singBoxPackagePlaceholder = "__proxy_suite_doc_pkg_sing_box__";
|
||||
xrayPackagePlaceholder = "__proxy_suite_doc_pkg_xray__";
|
||||
sanitizeConfigForDocs =
|
||||
config:
|
||||
builtins.removeAttrs config [ "singBox" ]
|
||||
// {
|
||||
proxy =
|
||||
(config.proxy or { })
|
||||
// {
|
||||
singBox =
|
||||
((config.proxy or { }).singBox or { })
|
||||
// lib.optionalAttrs (((config.proxy or { }).singBox or { }) ? package) {
|
||||
package = singBoxPackagePlaceholder;
|
||||
};
|
||||
xray =
|
||||
((config.proxy or { }).xray or { })
|
||||
// lib.optionalAttrs (((config.proxy or { }).xray or { }) ? package) {
|
||||
package = xrayPackagePlaceholder;
|
||||
};
|
||||
};
|
||||
};
|
||||
renderConfigText =
|
||||
config:
|
||||
lib.replaceStrings
|
||||
[
|
||||
"\"${singBoxPackagePlaceholder}\""
|
||||
"\"${xrayPackagePlaceholder}\""
|
||||
]
|
||||
[
|
||||
"pkgs.sing-box"
|
||||
"pkgs.xray"
|
||||
]
|
||||
(
|
||||
lib.generators.toPretty { } (sanitizeConfigForDocs config)
|
||||
);
|
||||
mkGeneratedExampleValue =
|
||||
option:
|
||||
if (option ? _type) && option._type == "option" then
|
||||
@@ -32,10 +67,10 @@ let
|
||||
throw "Cannot generate example value for option ${lib.showOption option.loc}"
|
||||
else
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions option);
|
||||
defaultConfigText = lib.generators.toPretty { } eval.config.services.proxy-suite;
|
||||
exampleConfigText = lib.generators.toPretty { } (
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite)
|
||||
);
|
||||
defaultConfigText = renderConfigText eval.config.services.proxy-suite;
|
||||
generatedExampleConfig =
|
||||
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions eval.options.services.proxy-suite);
|
||||
exampleConfigText = renderConfigText (builtins.removeAttrs generatedExampleConfig [ "singBox" ]);
|
||||
repoRoot = toString ../.;
|
||||
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
|
||||
transformDeclaration =
|
||||
@@ -227,8 +262,25 @@ pkgs.runCommand "proxy-suite-options.md" { } ''
|
||||
}
|
||||
' "$section_index"
|
||||
|
||||
cat "$preamble" >"$out"
|
||||
cat "$toc" >>"$out"
|
||||
printf '\n' >>"$out"
|
||||
cat "$sections_with_anchors" >>"$out"
|
||||
raw="$TMPDIR/options.md.raw"
|
||||
|
||||
cat "$preamble" >"$raw"
|
||||
cat "$toc" >>"$raw"
|
||||
printf '\n' >>"$raw"
|
||||
cat "$sections_with_anchors" >>"$raw"
|
||||
|
||||
awk '
|
||||
NF {
|
||||
for (i = 0; i < blanks; i++) {
|
||||
print ""
|
||||
}
|
||||
blanks = 0
|
||||
print
|
||||
next
|
||||
}
|
||||
|
||||
{
|
||||
blanks++
|
||||
}
|
||||
' "$raw" >"$out"
|
||||
''
|
||||
@@ -4,11 +4,15 @@
|
||||
services.proxy-suite = {
|
||||
enable = true;
|
||||
|
||||
singBox.outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
proxy = {
|
||||
enable = true;
|
||||
singBox.enable = true;
|
||||
outbounds = [
|
||||
{
|
||||
tag = "primary";
|
||||
url = "http://proxy.example.com:8080";
|
||||
}
|
||||
];
|
||||
};
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -38,7 +38,7 @@ let
|
||||
packages
|
||||
cfg
|
||||
;
|
||||
inherit (configs) tproxyFile tunFile perAppTunFile;
|
||||
inherit (configs) tproxyFile tunFile perAppTunFile routeModeRulesFile;
|
||||
inherit (nftr) perAppTunChainFile perAppTproxyRulesFile perAppZapretRulesFile ip nft;
|
||||
};
|
||||
in
|
||||
|
||||
+165
-32
@@ -14,9 +14,11 @@ _usage() {
|
||||
echo "Commands:"
|
||||
echo " help show this help message"
|
||||
echo " status [--tray] show status of all proxy-suite services"
|
||||
echo " proxy on|off enable/disable the sing-box proxy stack"
|
||||
echo " proxy on|off enable/disable the proxy backend stack"
|
||||
echo " tproxy on|off enable/disable TProxy transparent mode"
|
||||
echo " tun on|off enable/disable TUN mode"
|
||||
echo " route-mode default|whitelist|blacklist|all-proxy|all-bypass|status"
|
||||
echo " set temporary routing override"
|
||||
echo " zapret on|off enable/disable zapret-discord-youtube"
|
||||
echo " restart restart active global proxy-suite services"
|
||||
echo " logs [service] follow service logs (default: proxy-suite-socks)"
|
||||
@@ -25,7 +27,7 @@ _usage() {
|
||||
echo " apps list configured per-app routing profiles"
|
||||
echo " wrap <profile> -- <cmd> run a command via a perAppRouting profile"
|
||||
echo " subscription list show subscriptions, cache age, and proxy count"
|
||||
echo " subscription update force-refresh all subscription caches and restart active sing-box services"
|
||||
echo " subscription update force-refresh all subscription caches and restart active proxy services"
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
@@ -55,16 +57,88 @@ _svc_active() {
|
||||
systemctl is-active --quiet "$1"
|
||||
}
|
||||
|
||||
_require_service() {
|
||||
local svc="$1" message="$2"
|
||||
if ! _svc_exists "$svc"; then
|
||||
echo "$message"
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
_stop_if_exists() {
|
||||
local svc="$1"
|
||||
if _svc_exists "$svc"; then
|
||||
systemctl stop "$svc" || true
|
||||
fi
|
||||
}
|
||||
|
||||
_route_mode_default() {
|
||||
printf '%s' "${DEFAULT_ROUTE_MODE:-blacklist}"
|
||||
}
|
||||
|
||||
_route_mode_effective() {
|
||||
local mode=""
|
||||
if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then
|
||||
mode=$(tr -d '\r\n[:space:]' < "${ROUTE_MODE_STATE_FILE}" 2>/dev/null || true)
|
||||
fi
|
||||
|
||||
case "$mode" in
|
||||
whitelist|blacklist|all-proxy|all-bypass)
|
||||
printf '%s' "$mode"
|
||||
;;
|
||||
*)
|
||||
_route_mode_default
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
_route_mode_current() {
|
||||
if [ -n "${ROUTE_MODE_STATE_FILE:-}" ] && [ -r "${ROUTE_MODE_STATE_FILE}" ]; then
|
||||
_route_mode_effective
|
||||
else
|
||||
printf 'default'
|
||||
fi
|
||||
}
|
||||
|
||||
_route_mode_label() {
|
||||
case "$1" in
|
||||
default)
|
||||
printf 'Default (%s)' "$(_route_mode_label "$(_route_mode_default)")"
|
||||
;;
|
||||
whitelist)
|
||||
printf 'Whitelist (direct by default)'
|
||||
;;
|
||||
blacklist)
|
||||
printf 'Blacklist (proxy by default)'
|
||||
;;
|
||||
all-proxy)
|
||||
printf 'All Proxy (override)'
|
||||
;;
|
||||
all-bypass)
|
||||
printf 'All Bypass (override)'
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown'
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
_status_tray() {
|
||||
printf 'socks_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||
printf 'socks_active=%s\n' "$(_bool _svc_active proxy-suite-socks)"
|
||||
printf 'tproxy_available=%s\n' "$(_bool _svc_exists proxy-suite-tproxy)"
|
||||
printf 'tproxy_active=%s\n' "$(_bool _svc_active proxy-suite-tproxy)"
|
||||
printf 'tun_available=%s\n' "$(_bool _svc_exists proxy-suite-tun)"
|
||||
printf 'tun_active=%s\n' "$(_bool _svc_active proxy-suite-tun)"
|
||||
printf 'zapret_available=%s\n' "$(_bool _svc_exists zapret-discord-youtube)"
|
||||
printf 'zapret_active=%s\n' "$(_bool _svc_active zapret-discord-youtube)"
|
||||
local pair key svc
|
||||
for pair in \
|
||||
socks:proxy-suite-socks \
|
||||
tproxy:proxy-suite-tproxy \
|
||||
tun:proxy-suite-tun \
|
||||
zapret:zapret-discord-youtube; do
|
||||
key="${pair%%:*}"
|
||||
svc="${pair##*:}"
|
||||
printf '%s_available=%s\n' "$key" "$(_bool _svc_exists "$svc")"
|
||||
printf '%s_active=%s\n' "$key" "$(_bool _svc_active "$svc")"
|
||||
done
|
||||
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
|
||||
printf 'route_mode_available=%s\n' "$(_bool _svc_exists proxy-suite-socks)"
|
||||
printf 'route_mode=%s\n' "$(_route_mode_current)"
|
||||
printf 'default_route_mode=%s\n' "$(_route_mode_default)"
|
||||
}
|
||||
|
||||
_ensure_app_routing() {
|
||||
@@ -100,6 +174,18 @@ _check_no_global_proxy() {
|
||||
fi
|
||||
}
|
||||
|
||||
_cleanup_slice_if_idle() {
|
||||
local slice_base="$1" anchor_unit="$2" user_svc="$3" backend_svc="$4"
|
||||
|
||||
if ! _scope_running "$slice_base"; then
|
||||
systemctl stop "$user_svc" || true
|
||||
systemctl --user stop "$anchor_unit" || true
|
||||
if ! _any_user_active "$slice_base-user@"; then
|
||||
systemctl stop "$backend_svc" || true
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
# _wrap_slice <slice_base> <enabled_var> <disabled_msg> <backend_svc> [cmd...]
|
||||
_wrap_slice() {
|
||||
local slice_base="$1" enabled="$2" disabled_msg="$3" backend_svc="$4"
|
||||
@@ -112,22 +198,25 @@ _wrap_slice() {
|
||||
local scope_unit="$slice_base-${profile}-$$"
|
||||
local anchor_unit="$slice_base-anchor.service"
|
||||
local user_svc="$slice_base-user@$uid.service"
|
||||
|
||||
systemctl --user start "$anchor_unit"
|
||||
systemctl start "$backend_svc"
|
||||
systemctl start "$user_svc"
|
||||
|
||||
local status=0
|
||||
systemd-run --user --scope --quiet --collect --same-dir \
|
||||
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||
|
||||
if ! _scope_running "$slice_base"; then
|
||||
systemctl stop "$user_svc" || true
|
||||
systemctl --user stop "$anchor_unit" || true
|
||||
if ! _any_user_active "$slice_base-user@"; then
|
||||
systemctl stop "$backend_svc" || true
|
||||
fi
|
||||
cleanup_slice() {
|
||||
_cleanup_slice_if_idle "$slice_base" "$anchor_unit" "$user_svc" "$backend_svc"
|
||||
}
|
||||
trap cleanup_slice EXIT
|
||||
|
||||
systemctl --user start "$anchor_unit" || status=$?
|
||||
if [ "$status" -eq 0 ]; then
|
||||
systemctl start "$backend_svc" || status=$?
|
||||
fi
|
||||
if [ "$status" -eq 0 ]; then
|
||||
systemctl start "$user_svc" || status=$?
|
||||
fi
|
||||
if [ "$status" -eq 0 ]; then
|
||||
systemd-run --user --scope --quiet --collect --same-dir \
|
||||
--slice="$slice_base" --unit="$scope_unit" "$@" || status=$?
|
||||
fi
|
||||
|
||||
exit "$status"
|
||||
}
|
||||
|
||||
@@ -141,16 +230,23 @@ cmd_status() {
|
||||
for svc in "${ALL_SERVICES[@]}"; do
|
||||
_svc_status "$svc"
|
||||
done
|
||||
if _svc_exists proxy-suite-socks; then
|
||||
echo ""
|
||||
echo "routing:"
|
||||
echo " active mode $(_route_mode_label "$(_route_mode_current)")"
|
||||
fi
|
||||
}
|
||||
|
||||
cmd_proxy() {
|
||||
case "${1:-on}" in
|
||||
on)
|
||||
_require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled."
|
||||
systemctl start proxy-suite-socks
|
||||
;;
|
||||
off)
|
||||
systemctl stop proxy-suite-tproxy || true
|
||||
systemctl stop proxy-suite-tun || true
|
||||
_require_service proxy-suite-socks "SOCKS proxy service is not available because proxy.enable is not enabled."
|
||||
_stop_if_exists proxy-suite-tproxy
|
||||
_stop_if_exists proxy-suite-tun
|
||||
systemctl stop proxy-suite-socks
|
||||
;;
|
||||
*)
|
||||
@@ -164,6 +260,7 @@ cmd_mode_toggle() {
|
||||
local name="$1"
|
||||
local default_action="${2:-on}"
|
||||
local display="${4:-${name#proxy-suite-}}"
|
||||
_require_service "$name" "Service '$name' is not available in this proxy-suite configuration."
|
||||
case "${3:-$default_action}" in
|
||||
on)
|
||||
systemctl start "$name"
|
||||
@@ -180,16 +277,45 @@ cmd_mode_toggle() {
|
||||
|
||||
cmd_zapret() { cmd_mode_toggle "zapret-discord-youtube" on "${1:-on}" "zapret"; }
|
||||
|
||||
cmd_route_mode() {
|
||||
local action
|
||||
|
||||
if ! _svc_exists proxy-suite-socks; then
|
||||
echo "Route mode is unavailable because proxy services are not enabled."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
action="${1:-status}"
|
||||
|
||||
case "$action" in
|
||||
status)
|
||||
echo "$(_route_mode_current)"
|
||||
;;
|
||||
default|whitelist|blacklist|all-proxy|all-bypass)
|
||||
systemctl start "proxy-suite-route-mode@${action}.service"
|
||||
echo "Switched to: $(_route_mode_label "$action")"
|
||||
;;
|
||||
*)
|
||||
echo "Usage: proxy-ctl route-mode default|whitelist|blacklist|all-proxy|all-bypass|status"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
RESTART_SERVICES=(
|
||||
proxy-suite-tproxy
|
||||
proxy-suite-tun
|
||||
proxy-suite-tg-ws-proxy
|
||||
zapret-discord-youtube
|
||||
)
|
||||
|
||||
cmd_restart() {
|
||||
systemctl restart proxy-suite-socks
|
||||
if _svc_exists proxy-suite-socks; then
|
||||
systemctl restart proxy-suite-socks
|
||||
fi
|
||||
|
||||
for svc in "${RESTART_SERVICES[@]}"; do
|
||||
if systemctl is-active --quiet "$svc"; then
|
||||
if _svc_exists "$svc" && _svc_active "$svc"; then
|
||||
systemctl restart "$svc"
|
||||
fi
|
||||
done
|
||||
@@ -248,7 +374,7 @@ cmd_apps() {
|
||||
|
||||
cmd_wrap() {
|
||||
local route
|
||||
profile="${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
|
||||
local profile="${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
|
||||
shift || true
|
||||
if [ "${1:-}" = "--" ]; then
|
||||
shift
|
||||
@@ -274,23 +400,29 @@ cmd_wrap() {
|
||||
echo "Profile '$profile' uses route=proxychains, but perAppRouting.proxychains.enable is false."
|
||||
exit 1
|
||||
fi
|
||||
if [ ! -r "$PROXYCHAINS_CONFIG" ]; then
|
||||
echo "Proxychains config is not readable: $PROXYCHAINS_CONFIG"
|
||||
echo "Make sure proxy-suite-socks.service is running."
|
||||
exit 1
|
||||
fi
|
||||
exec proxychains4 $PROXYCHAINS_QUIET_ARG -f "$PROXYCHAINS_CONFIG" "$@"
|
||||
;;
|
||||
tun)
|
||||
_check_no_global_proxy tun
|
||||
_wrap_slice "proxy-suite-per-app-tun" "$PER_APP_ROUTING_TUN_ENABLED" \
|
||||
"Profile '$profile' uses route=tun, but singBox.tun.perApp.enable is false." \
|
||||
"Profile '$profile' uses route=tun, but proxy.tun.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tun.service" "$@"
|
||||
;;
|
||||
tproxy)
|
||||
_check_no_global_proxy tproxy
|
||||
_wrap_slice "proxy-suite-per-app-tproxy" "$PER_APP_ROUTING_TPROXY_ENABLED" \
|
||||
"Profile '$profile' uses route=tproxy, but singBox.tproxy.perApp.enable is false." \
|
||||
"Profile '$profile' uses route=tproxy, but proxy.tproxy.perApp.enable is false." \
|
||||
"proxy-suite-per-app-tproxy.service" "$@"
|
||||
;;
|
||||
zapret)
|
||||
_check_no_global_proxy zapret
|
||||
_wrap_slice "proxy-suite-per-app-zapret" "$PER_APP_ROUTING_ZAPRET_ENABLED" \
|
||||
"Profile '$profile' uses route=zapret, but zapret.perApp.enable or zapret.enable is false." \
|
||||
"Profile '$profile' uses route=zapret, but zapret.perApp.enable is false." \
|
||||
"proxy-suite-per-app-zapret.service" "$@"
|
||||
;;
|
||||
*)
|
||||
@@ -307,7 +439,7 @@ cmd_subscription() {
|
||||
|
||||
case "$subcmd" in
|
||||
list)
|
||||
CACHE_DIR="/var/lib/proxy-suite/subscriptions"
|
||||
CACHE_DIR="${SUB_CACHE_DIR:-/var/lib/proxy-suite/subscriptions}"
|
||||
if [ ${#SUB_TAGS[@]} -eq 0 ]; then
|
||||
echo "No subscriptions configured."
|
||||
return
|
||||
@@ -327,6 +459,7 @@ cmd_subscription() {
|
||||
done
|
||||
;;
|
||||
update)
|
||||
_require_service proxy-suite-subscription-update "Subscription updates are unavailable because no subscriptions are configured."
|
||||
systemctl start proxy-suite-subscription-update
|
||||
echo "Subscription update triggered. Follow with: proxy-ctl logs proxy-suite-subscription-update"
|
||||
;;
|
||||
|
||||
+7
-1
@@ -7,6 +7,7 @@
|
||||
clashApi,
|
||||
selection,
|
||||
subscriptionTagsFile,
|
||||
subscriptionCacheDir,
|
||||
perAppRoutingEnabled,
|
||||
perAppRoutingProxychainsEnabled,
|
||||
perAppRoutingTunEnabled,
|
||||
@@ -15,6 +16,8 @@
|
||||
perAppRoutingProfilesFile,
|
||||
proxychainsConfigFile,
|
||||
proxychainsQuietArg,
|
||||
routeModeStateFile,
|
||||
defaultRouteMode,
|
||||
}:
|
||||
|
||||
let
|
||||
@@ -42,6 +45,7 @@ pkgs.symlinkJoin {
|
||||
--set CLASH_API ${lib.escapeShellArg clashApi} \
|
||||
--set SELECTION ${lib.escapeShellArg selection} \
|
||||
--set SUB_TAGS_FILE ${lib.escapeShellArg (toString subscriptionTagsFile)} \
|
||||
--set SUB_CACHE_DIR ${lib.escapeShellArg subscriptionCacheDir} \
|
||||
--set PER_APP_ROUTING_ENABLED ${lib.escapeShellArg perAppRoutingEnabled} \
|
||||
--set PER_APP_ROUTING_PROXYCHAINS_ENABLED ${lib.escapeShellArg perAppRoutingProxychainsEnabled} \
|
||||
--set PER_APP_ROUTING_TUN_ENABLED ${lib.escapeShellArg perAppRoutingTunEnabled} \
|
||||
@@ -49,6 +53,8 @@ pkgs.symlinkJoin {
|
||||
--set PER_APP_ROUTING_ZAPRET_ENABLED ${lib.escapeShellArg perAppRoutingZapretEnabled} \
|
||||
--set PER_APP_ROUTING_PROFILES_FILE ${lib.escapeShellArg (toString perAppRoutingProfilesFile)} \
|
||||
--set PROXYCHAINS_CONFIG ${lib.escapeShellArg (toString proxychainsConfigFile)} \
|
||||
--set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)}
|
||||
--set PROXYCHAINS_QUIET_ARG ${lib.escapeShellArg (lib.removeSuffix " " proxychainsQuietArg)} \
|
||||
--set ROUTE_MODE_STATE_FILE ${lib.escapeShellArg routeModeStateFile} \
|
||||
--set DEFAULT_ROUTE_MODE ${lib.escapeShellArg defaultRouteMode}
|
||||
'';
|
||||
}
|
||||
@@ -33,6 +33,10 @@ case "$cmd" in
|
||||
cmd_mode_toggle proxy-suite-tun on "${1:-}"
|
||||
;;
|
||||
|
||||
route-mode)
|
||||
cmd_route_mode "$@"
|
||||
;;
|
||||
|
||||
zapret)
|
||||
cmd_zapret "$@"
|
||||
;;
|
||||
|
||||
@@ -21,7 +21,7 @@ pkgs.stdenv.mkDerivation {
|
||||
-DSYSTEMCTL_BIN='"${pkgs.systemd}/bin/systemctl"' \
|
||||
-DPKEXEC_BIN='"/run/wrappers/bin/pkexec"' \
|
||||
-DPOLL_INTERVAL=${toString pollInterval} \
|
||||
-O2 -Wall
|
||||
-O2 -Wall -Werror=discarded-qualifiers
|
||||
'';
|
||||
|
||||
installPhase = ''
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
|
||||
<!-- Gold shield: TUN/TProxy active -->
|
||||
<!-- Purple shield: TUN/TProxy active -->
|
||||
<path d="M 12 2 L 20 6 L 20 13 C 20 18 12 22 12 22 C 12 22 4 18 4 13 L 4 6 Z"
|
||||
fill="#FFC107" stroke="#F57F17" stroke-width="0.8"/>
|
||||
fill="#9C27B0" stroke="#4A148C" stroke-width="0.8"/>
|
||||
<!-- Up arrow: traffic routed through tunnel -->
|
||||
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
|
||||
stroke="#FFFFFF" stroke-width="1.4" fill="none"
|
||||
|
||||
|
Before Width: | Height: | Size: 497 B After Width: | Height: | Size: 499 B |
@@ -16,6 +16,12 @@ static AppIndicator *indicator;
|
||||
static GtkWidget *menu;
|
||||
static GtkWidget *status_item;
|
||||
static GtkWidget *proxy_item;
|
||||
static GtkWidget *route_mode_item;
|
||||
static GtkWidget *route_mode_default_item;
|
||||
static GtkWidget *route_mode_whitelist_item;
|
||||
static GtkWidget *route_mode_blacklist_item;
|
||||
static GtkWidget *route_mode_all_proxy_item;
|
||||
static GtkWidget *route_mode_all_bypass_item;
|
||||
static GtkWidget *tproxy_item;
|
||||
static GtkWidget *tun_item;
|
||||
static GtkWidget *zapret_item;
|
||||
@@ -23,12 +29,25 @@ static GtkWidget *open_controls_item;
|
||||
static GtkWidget *controls_window;
|
||||
static GtkWidget *controls_summary_label;
|
||||
static GtkWidget *controls_core_status_label;
|
||||
static GtkWidget *controls_route_mode_status_label;
|
||||
static GtkWidget *controls_route_mode_combo;
|
||||
static GtkWidget *controls_traffic_status_label;
|
||||
static GtkWidget *controls_zapret_status_label;
|
||||
static GtkWidget *controls_proxy_button;
|
||||
static GtkWidget *controls_tproxy_button;
|
||||
static GtkWidget *controls_tun_button;
|
||||
static GtkWidget *controls_zapret_button;
|
||||
static gboolean updating_route_mode_widgets = FALSE;
|
||||
|
||||
typedef enum
|
||||
{
|
||||
ROUTE_MODE_UNKNOWN = 0,
|
||||
ROUTE_MODE_DEFAULT,
|
||||
ROUTE_MODE_WHITELIST,
|
||||
ROUTE_MODE_BLACKLIST,
|
||||
ROUTE_MODE_ALL_PROXY,
|
||||
ROUTE_MODE_ALL_BYPASS
|
||||
} RouteMode;
|
||||
|
||||
typedef struct
|
||||
{
|
||||
@@ -38,10 +57,13 @@ typedef struct
|
||||
gboolean tun_available;
|
||||
gboolean zapret_available;
|
||||
gboolean subscription_update_available;
|
||||
gboolean route_mode_available;
|
||||
gboolean socks;
|
||||
gboolean tproxy;
|
||||
gboolean tun;
|
||||
gboolean zapret;
|
||||
RouteMode route_mode;
|
||||
RouteMode default_route_mode;
|
||||
} ServiceState;
|
||||
|
||||
static ServiceState initial_state;
|
||||
@@ -173,6 +195,35 @@ static gboolean parse_proxy_ctl_bool(const char *value)
|
||||
return value && strcmp(value, "true") == 0;
|
||||
}
|
||||
|
||||
static RouteMode parse_route_mode(const char *value)
|
||||
{
|
||||
if (!value)
|
||||
{
|
||||
return ROUTE_MODE_UNKNOWN;
|
||||
}
|
||||
if (strcmp(value, "default") == 0)
|
||||
{
|
||||
return ROUTE_MODE_DEFAULT;
|
||||
}
|
||||
if (strcmp(value, "whitelist") == 0)
|
||||
{
|
||||
return ROUTE_MODE_WHITELIST;
|
||||
}
|
||||
if (strcmp(value, "blacklist") == 0)
|
||||
{
|
||||
return ROUTE_MODE_BLACKLIST;
|
||||
}
|
||||
if (strcmp(value, "all-proxy") == 0)
|
||||
{
|
||||
return ROUTE_MODE_ALL_PROXY;
|
||||
}
|
||||
if (strcmp(value, "all-bypass") == 0)
|
||||
{
|
||||
return ROUTE_MODE_ALL_BYPASS;
|
||||
}
|
||||
return ROUTE_MODE_UNKNOWN;
|
||||
}
|
||||
|
||||
static const char *pick_icon_name(
|
||||
const char *const *candidates,
|
||||
gsize candidates_len,
|
||||
@@ -263,6 +314,18 @@ static ServiceState get_service_state(void)
|
||||
{
|
||||
state.subscription_update_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "route_mode_available") == 0)
|
||||
{
|
||||
state.route_mode_available = parse_proxy_ctl_bool(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "route_mode") == 0)
|
||||
{
|
||||
state.route_mode = parse_route_mode(parts[1]);
|
||||
}
|
||||
else if (strcmp(parts[0], "default_route_mode") == 0)
|
||||
{
|
||||
state.default_route_mode = parse_route_mode(parts[1]);
|
||||
}
|
||||
|
||||
g_strfreev(parts);
|
||||
}
|
||||
@@ -286,6 +349,84 @@ static const char *traffic_mode_label(const ServiceState *state)
|
||||
return "System-wide routing disabled";
|
||||
}
|
||||
|
||||
static const char *route_mode_label(const ServiceState *state)
|
||||
{
|
||||
switch (state->route_mode)
|
||||
{
|
||||
case ROUTE_MODE_DEFAULT:
|
||||
switch (state->default_route_mode)
|
||||
{
|
||||
case ROUTE_MODE_WHITELIST:
|
||||
return "Default (Whitelist baseline)";
|
||||
case ROUTE_MODE_BLACKLIST:
|
||||
return "Default (Blacklist baseline)";
|
||||
default:
|
||||
return "Default";
|
||||
}
|
||||
case ROUTE_MODE_WHITELIST:
|
||||
return "Whitelist (direct by default)";
|
||||
case ROUTE_MODE_BLACKLIST:
|
||||
return "Blacklist (proxy by default)";
|
||||
case ROUTE_MODE_ALL_PROXY:
|
||||
return "All Proxy (override)";
|
||||
case ROUTE_MODE_ALL_BYPASS:
|
||||
return "All Bypass (override)";
|
||||
default:
|
||||
return "Unknown";
|
||||
}
|
||||
}
|
||||
|
||||
static gint route_mode_combo_index(RouteMode mode)
|
||||
{
|
||||
switch (mode)
|
||||
{
|
||||
case ROUTE_MODE_DEFAULT:
|
||||
return 0;
|
||||
case ROUTE_MODE_WHITELIST:
|
||||
return 1;
|
||||
case ROUTE_MODE_BLACKLIST:
|
||||
return 2;
|
||||
case ROUTE_MODE_ALL_PROXY:
|
||||
return 3;
|
||||
case ROUTE_MODE_ALL_BYPASS:
|
||||
return 4;
|
||||
default:
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static void sync_route_mode_widgets(RouteMode mode)
|
||||
{
|
||||
updating_route_mode_widgets = TRUE;
|
||||
|
||||
if (route_mode_default_item)
|
||||
{
|
||||
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_default_item), mode == ROUTE_MODE_DEFAULT);
|
||||
}
|
||||
if (route_mode_whitelist_item)
|
||||
{
|
||||
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_whitelist_item), mode == ROUTE_MODE_WHITELIST);
|
||||
}
|
||||
if (route_mode_blacklist_item)
|
||||
{
|
||||
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_blacklist_item), mode == ROUTE_MODE_BLACKLIST);
|
||||
}
|
||||
if (route_mode_all_proxy_item)
|
||||
{
|
||||
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_proxy_item), mode == ROUTE_MODE_ALL_PROXY);
|
||||
}
|
||||
if (route_mode_all_bypass_item)
|
||||
{
|
||||
gtk_check_menu_item_set_active(GTK_CHECK_MENU_ITEM(route_mode_all_bypass_item), mode == ROUTE_MODE_ALL_BYPASS);
|
||||
}
|
||||
if (controls_route_mode_combo)
|
||||
{
|
||||
gtk_combo_box_set_active(GTK_COMBO_BOX(controls_route_mode_combo), route_mode_combo_index(mode));
|
||||
}
|
||||
|
||||
updating_route_mode_widgets = FALSE;
|
||||
}
|
||||
|
||||
static const char *indicator_label_text(const ServiceState *state)
|
||||
{
|
||||
if (state->socks && (state->tproxy || state->tun) && state->zapret)
|
||||
@@ -314,7 +455,7 @@ static const char *indicator_label_text(const ServiceState *state)
|
||||
static void update_status(void)
|
||||
{
|
||||
ServiceState state = get_service_state();
|
||||
/* Gold: TUN/TProxy active (highest priority) */
|
||||
/* Purple: TUN/TProxy active (highest priority) */
|
||||
static const char *const tunnel_icons[] = {
|
||||
"proxy-suite-tunnel",
|
||||
"proxy-suite-tunnel-symbolic",
|
||||
@@ -378,6 +519,10 @@ static void update_status(void)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown");
|
||||
}
|
||||
if (controls_route_mode_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), "[Routing] Mode: Unknown");
|
||||
}
|
||||
if (controls_zapret_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown");
|
||||
@@ -386,16 +531,19 @@ static void update_status(void)
|
||||
}
|
||||
|
||||
const char *traffic = traffic_mode_label(&state);
|
||||
const char *route_mode = route_mode_label(&state);
|
||||
const char *summary = indicator_label_text(&state);
|
||||
const char *zapret = state.zapret ? "Active" : "Stopped";
|
||||
gchar *summary_text = g_strdup_printf(
|
||||
"[Status] %s | Traffic: %s | Zapret: %s",
|
||||
"[Status] %s | Traffic: %s | Routing: %s | Zapret: %s",
|
||||
state.socks ? "Proxy ready" : "Proxy down",
|
||||
traffic,
|
||||
route_mode,
|
||||
zapret);
|
||||
gchar *core_text = g_strdup_printf(
|
||||
"[Core] SOCKS proxy: %s",
|
||||
state.socks ? "Running" : "Stopped");
|
||||
gchar *route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode);
|
||||
gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic);
|
||||
gchar *zapret_text = g_strdup_printf(
|
||||
"[Zapret] zapret-discord-youtube: %s",
|
||||
@@ -445,6 +593,10 @@ static void update_status(void)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text);
|
||||
}
|
||||
if (controls_route_mode_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_route_mode_status_label), route_mode_text);
|
||||
}
|
||||
if (controls_traffic_status_label)
|
||||
{
|
||||
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text);
|
||||
@@ -463,6 +615,13 @@ static void update_status(void)
|
||||
gtk_button_set_label(GTK_BUTTON(controls_proxy_button),
|
||||
state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy");
|
||||
}
|
||||
if (route_mode_item)
|
||||
{
|
||||
gchar *menu_route_mode_text = g_strdup_printf("[Routing] Mode: %s", route_mode);
|
||||
gtk_menu_item_set_label(GTK_MENU_ITEM(route_mode_item), menu_route_mode_text);
|
||||
g_free(menu_route_mode_text);
|
||||
sync_route_mode_widgets(state.route_mode);
|
||||
}
|
||||
|
||||
if (tproxy_item)
|
||||
{
|
||||
@@ -499,6 +658,7 @@ static void update_status(void)
|
||||
|
||||
g_free(summary_text);
|
||||
g_free(core_text);
|
||||
g_free(route_mode_text);
|
||||
g_free(traffic_text);
|
||||
g_free(zapret_text);
|
||||
}
|
||||
@@ -535,6 +695,46 @@ static void on_tproxy_toggle(GtkWidget *item, gpointer data)
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_route_mode_menu_toggled(GtkCheckMenuItem *item, gpointer data)
|
||||
{
|
||||
const char *mode;
|
||||
if (updating_route_mode_widgets || !gtk_check_menu_item_get_active(item))
|
||||
{
|
||||
return;
|
||||
}
|
||||
mode = (const char *)data;
|
||||
if (!mode)
|
||||
{
|
||||
return;
|
||||
}
|
||||
run_proxy_ctl2("route-mode", mode);
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_route_mode_combo_changed(GtkComboBox *combo, gpointer data)
|
||||
{
|
||||
(void)data;
|
||||
const char *mode;
|
||||
const gchar *active_id;
|
||||
if (updating_route_mode_widgets)
|
||||
{
|
||||
return;
|
||||
}
|
||||
active_id = gtk_combo_box_get_active_id(combo);
|
||||
if (!active_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
mode = active_id;
|
||||
ServiceState state = get_service_state();
|
||||
if (!state.route_mode_available)
|
||||
{
|
||||
return;
|
||||
}
|
||||
run_proxy_ctl2("route-mode", mode);
|
||||
update_status();
|
||||
}
|
||||
|
||||
static void on_tun_toggle(GtkWidget *item, gpointer data)
|
||||
{
|
||||
(void)item;
|
||||
@@ -638,6 +838,28 @@ static void build_controls_window(void)
|
||||
g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0);
|
||||
|
||||
if (initial_state.route_mode_available)
|
||||
{
|
||||
GtkWidget *routing_frame = gtk_frame_new("[Routing] Mode");
|
||||
GtkWidget *routing_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(routing_box), 6);
|
||||
gtk_container_add(GTK_CONTAINER(routing_frame), routing_box);
|
||||
gtk_box_pack_start(GTK_BOX(box), routing_frame, FALSE, FALSE, 0);
|
||||
|
||||
controls_route_mode_status_label = gtk_label_new("[Routing] Mode: Unknown");
|
||||
gtk_label_set_xalign(GTK_LABEL(controls_route_mode_status_label), 0.0f);
|
||||
gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_status_label, FALSE, FALSE, 0);
|
||||
|
||||
controls_route_mode_combo = gtk_combo_box_text_new();
|
||||
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "default", "Default (stop overriding)");
|
||||
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "whitelist", "Whitelist (direct by default)");
|
||||
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "blacklist", "Blacklist (proxy by default)");
|
||||
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-proxy", "All Proxy (override)");
|
||||
gtk_combo_box_text_append(GTK_COMBO_BOX_TEXT(controls_route_mode_combo), "all-bypass", "All Bypass (override)");
|
||||
g_signal_connect(controls_route_mode_combo, "changed", G_CALLBACK(on_route_mode_combo_changed), NULL);
|
||||
gtk_box_pack_start(GTK_BOX(routing_box), controls_route_mode_combo, FALSE, FALSE, 0);
|
||||
}
|
||||
|
||||
GtkWidget *traffic_frame = gtk_frame_new("[Traffic] System-wide traffic mode");
|
||||
GtkWidget *traffic_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
|
||||
gtk_container_set_border_width(GTK_CONTAINER(traffic_box), 6);
|
||||
@@ -722,6 +944,39 @@ static void build_menu(void)
|
||||
g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item);
|
||||
|
||||
if (initial_state.route_mode_available)
|
||||
{
|
||||
route_mode_item = gtk_menu_item_new_with_label("[Routing] Mode: Unknown");
|
||||
GtkWidget *route_mode_menu = gtk_menu_new();
|
||||
|
||||
route_mode_default_item = gtk_radio_menu_item_new_with_label(NULL, "Default (stop overriding)");
|
||||
g_signal_connect(route_mode_default_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "default");
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_default_item);
|
||||
|
||||
GSList *route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_default_item));
|
||||
route_mode_whitelist_item = gtk_radio_menu_item_new_with_label(route_group, "Whitelist (direct by default)");
|
||||
g_signal_connect(route_mode_whitelist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "whitelist");
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_whitelist_item);
|
||||
|
||||
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_whitelist_item));
|
||||
route_mode_blacklist_item = gtk_radio_menu_item_new_with_label(route_group, "Blacklist (proxy by default)");
|
||||
g_signal_connect(route_mode_blacklist_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "blacklist");
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_blacklist_item);
|
||||
|
||||
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_blacklist_item));
|
||||
route_mode_all_proxy_item = gtk_radio_menu_item_new_with_label(route_group, "All Proxy (override)");
|
||||
g_signal_connect(route_mode_all_proxy_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-proxy");
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_proxy_item);
|
||||
|
||||
route_group = gtk_radio_menu_item_get_group(GTK_RADIO_MENU_ITEM(route_mode_all_proxy_item));
|
||||
route_mode_all_bypass_item = gtk_radio_menu_item_new_with_label(route_group, "All Bypass (override)");
|
||||
g_signal_connect(route_mode_all_bypass_item, "toggled", G_CALLBACK(on_route_mode_menu_toggled), (gpointer) "all-bypass");
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(route_mode_menu), route_mode_all_bypass_item);
|
||||
|
||||
gtk_menu_item_set_submenu(GTK_MENU_ITEM(route_mode_item), route_mode_menu);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), route_mode_item);
|
||||
}
|
||||
|
||||
open_controls_item = gtk_menu_item_new_with_label("Open Controls");
|
||||
g_signal_connect(open_controls_item, "activate", G_CALLBACK(on_open_controls), NULL);
|
||||
gtk_menu_shell_append(GTK_MENU_SHELL(menu), open_controls_item);
|
||||
|
||||
@@ -4,8 +4,8 @@ let
|
||||
src = pkgs.fetchFromGitHub {
|
||||
owner = "Flowseal";
|
||||
repo = "tg-ws-proxy";
|
||||
rev = "v1.6.2";
|
||||
hash = "sha256-0X8N5FklFXJY5rHzozIhgNHjrEfhfPeqY6Yqc3l3ETU=";
|
||||
rev = "v1.7.3";
|
||||
hash = "sha256-b9Dmh41PEC3LZDhaSILUDrLApDgP0IiKXn//cvLfm9o=";
|
||||
};
|
||||
|
||||
pythonEnv = pkgs.python3.withPackages (
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a proxy URL from stdin and emit a sing-box outbound JSON object."""
|
||||
"""Read a proxy URL from stdin and emit a backend outbound JSON object."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
@@ -10,15 +10,16 @@ from proxy_parsing import build_outbound
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Convert a proxy URL from stdin into a sing-box outbound JSON object."
|
||||
description="Convert a proxy URL from stdin into a backend outbound JSON object."
|
||||
)
|
||||
ap.add_argument("--tag", required=True)
|
||||
ap.add_argument("--backend", choices=["sing-box", "xray"], default="sing-box")
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
url = sys.stdin.read().strip()
|
||||
try:
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark)
|
||||
outbound = build_outbound(url, args.tag, args.routing_mark, args.backend)
|
||||
except ValueError as exc:
|
||||
print(f"error: {exc}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
Executable
+253
@@ -0,0 +1,253 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
PROXY_CTL="${PROXY_CTL:-proxy-ctl}"
|
||||
SYSTEMCTL="${SYSTEMCTL:-systemctl}"
|
||||
JOURNALCTL="${JOURNALCTL:-journalctl}"
|
||||
IP_BIN="${IP_BIN:-ip}"
|
||||
NFT_BIN="${NFT_BIN:-nft}"
|
||||
CURL_BIN="${CURL_BIN:-curl}"
|
||||
TARGET_URL="${TARGET_URL:-https://whatismyipaddress.com/}"
|
||||
PER_APP_TUN_PROFILE="${PER_APP_TUN_PROFILE:-tun}"
|
||||
PER_APP_TPROXY_PROFILE="${PER_APP_TPROXY_PROFILE:-tproxy}"
|
||||
XRAY_LOGLEVEL_FILE="${XRAY_LOGLEVEL_FILE:-/run/proxy-suite/xray-loglevel}"
|
||||
ROUTE_MODE_FILE="${ROUTE_MODE_FILE:-/run/proxy-suite/route-mode}"
|
||||
|
||||
usage() {
|
||||
cat <<'EOF'
|
||||
Usage: check-xray-tun.sh [output-dir]
|
||||
|
||||
Runs four native XRay regression probes:
|
||||
- global TUN
|
||||
- per-app TUN
|
||||
- global TProxy
|
||||
- per-app TProxy
|
||||
|
||||
The script toggles proxy-suite modes while it runs and writes captures under the
|
||||
chosen output directory.
|
||||
EOF
|
||||
}
|
||||
|
||||
require_cmd() {
|
||||
command -v "$1" >/dev/null 2>&1 || {
|
||||
echo "missing required command: $1" >&2
|
||||
exit 1
|
||||
}
|
||||
}
|
||||
|
||||
capture_cmd() {
|
||||
local output="$1"
|
||||
local status=0
|
||||
shift
|
||||
|
||||
if "$@" >"$output" 2>&1; then
|
||||
return 0
|
||||
else
|
||||
status=$?
|
||||
fi
|
||||
|
||||
{
|
||||
echo
|
||||
echo "[exit=$status] $*"
|
||||
} >>"$output"
|
||||
}
|
||||
|
||||
capture_path() {
|
||||
local source="$1"
|
||||
local target="$2"
|
||||
|
||||
if [ -e "$source" ]; then
|
||||
cp -a "$source" "$target"
|
||||
else
|
||||
printf 'missing: %s\n' "$source" >"$target"
|
||||
fi
|
||||
}
|
||||
|
||||
service_active() {
|
||||
"$SYSTEMCTL" is-active --quiet "$1"
|
||||
}
|
||||
|
||||
set_global_mode() {
|
||||
local mode="$1"
|
||||
|
||||
case "$mode" in
|
||||
tun)
|
||||
"$PROXY_CTL" proxy on
|
||||
"$PROXY_CTL" tproxy off || true
|
||||
"$PROXY_CTL" tun on
|
||||
;;
|
||||
tproxy)
|
||||
"$PROXY_CTL" proxy on
|
||||
"$PROXY_CTL" tun off || true
|
||||
"$PROXY_CTL" tproxy on
|
||||
;;
|
||||
off)
|
||||
"$PROXY_CTL" tun off || true
|
||||
"$PROXY_CTL" tproxy off || true
|
||||
;;
|
||||
*)
|
||||
echo "unsupported global mode: $mode" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
capture_state() {
|
||||
local probe_dir="$1"
|
||||
local since="$2"
|
||||
local config_path="$3"
|
||||
shift 3
|
||||
local services=("$@")
|
||||
|
||||
capture_path "$config_path" "$probe_dir/config.json"
|
||||
capture_path "$ROUTE_MODE_FILE" "$probe_dir/route-mode.txt"
|
||||
capture_path "$XRAY_LOGLEVEL_FILE" "$probe_dir/xray-loglevel.txt"
|
||||
|
||||
capture_cmd "$probe_dir/ip-rule.txt" "$IP_BIN" rule show
|
||||
capture_cmd "$probe_dir/ip-route-all.txt" "$IP_BIN" -4 route show table all
|
||||
capture_cmd "$probe_dir/ip-addr.txt" "$IP_BIN" -4 addr show
|
||||
capture_cmd "$probe_dir/nft-ruleset.txt" "$NFT_BIN" list ruleset
|
||||
|
||||
for svc in "${services[@]}"; do
|
||||
capture_cmd "$probe_dir/journal-${svc}.log" "$JOURNALCTL" -u "$svc" --since "$since" --no-pager
|
||||
done
|
||||
}
|
||||
|
||||
run_global_probe() {
|
||||
local mode="$1"
|
||||
local probe_dir="$OUTPUT_DIR/$mode"
|
||||
local config_path="$2"
|
||||
shift 2
|
||||
local services=("$@")
|
||||
local since=""
|
||||
local curl_status=0
|
||||
|
||||
mkdir -p "$probe_dir"
|
||||
|
||||
set_global_mode "${mode#global-}"
|
||||
sleep 2
|
||||
since="$(date --iso-8601=seconds)"
|
||||
if "$CURL_BIN" -4 -L -sS --max-time 20 -D "$probe_dir/headers.txt" -o "$probe_dir/body.html" "$TARGET_URL" >"$probe_dir/stdout.txt" 2>"$probe_dir/stderr.txt"; then
|
||||
:
|
||||
else
|
||||
curl_status=$?
|
||||
fi
|
||||
printf '%s\n' "$curl_status" >"$probe_dir/curl-exit-code.txt"
|
||||
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
|
||||
set_global_mode off
|
||||
}
|
||||
|
||||
make_wrapped_probe_script() {
|
||||
local probe_dir="$1"
|
||||
local script_path="$probe_dir/run-probe.sh"
|
||||
|
||||
cat >"$script_path" <<EOF
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
status=0
|
||||
if ${CURL_BIN@Q} -4 -L -sS --max-time 20 -D ${probe_dir@Q}/headers.txt -o ${probe_dir@Q}/body.html ${TARGET_URL@Q} >${probe_dir@Q}/stdout.txt 2>${probe_dir@Q}/stderr.txt; then
|
||||
:
|
||||
else
|
||||
status=\$?
|
||||
fi
|
||||
printf '%s\n' "\$status" >${probe_dir@Q}/curl-exit-code.txt
|
||||
sleep 5
|
||||
exit "\$status"
|
||||
EOF
|
||||
chmod 755 "$script_path"
|
||||
printf '%s\n' "$script_path"
|
||||
}
|
||||
|
||||
run_per_app_probe() {
|
||||
local mode="$1"
|
||||
local profile="$2"
|
||||
local config_path="$3"
|
||||
shift 3
|
||||
local services=("$@")
|
||||
local probe_dir="$OUTPUT_DIR/$mode"
|
||||
local probe_script=""
|
||||
local wrapped_pid=""
|
||||
local wrapped_status=0
|
||||
local since=""
|
||||
|
||||
mkdir -p "$probe_dir"
|
||||
set_global_mode off
|
||||
"$PROXY_CTL" proxy on
|
||||
probe_script="$(make_wrapped_probe_script "$probe_dir")"
|
||||
since="$(date --iso-8601=seconds)"
|
||||
"$PROXY_CTL" wrap "$profile" -- "$probe_script" &
|
||||
wrapped_pid=$!
|
||||
sleep 2
|
||||
capture_state "$probe_dir" "$since" "$config_path" "${services[@]}"
|
||||
if wait "$wrapped_pid"; then
|
||||
:
|
||||
else
|
||||
wrapped_status=$?
|
||||
fi
|
||||
printf '%s\n' "$wrapped_status" >"$probe_dir/wrap-exit-code.txt"
|
||||
}
|
||||
|
||||
restore_state() {
|
||||
if [ -n "${ORIG_XRAY_LOGLEVEL+x}" ]; then
|
||||
if [ -n "$ORIG_XRAY_LOGLEVEL" ]; then
|
||||
printf '%s\n' "$ORIG_XRAY_LOGLEVEL" >"$XRAY_LOGLEVEL_FILE"
|
||||
else
|
||||
rm -f "$XRAY_LOGLEVEL_FILE"
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$ORIG_TUN_ACTIVE" = 1 ]; then
|
||||
set_global_mode tun || true
|
||||
elif [ "$ORIG_TPROXY_ACTIVE" = 1 ]; then
|
||||
set_global_mode tproxy || true
|
||||
else
|
||||
set_global_mode off || true
|
||||
if [ "$ORIG_PROXY_ACTIVE" = 0 ]; then
|
||||
"$PROXY_CTL" proxy off || true
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
if [ "${1:-}" = "--help" ] || [ "${1:-}" = "-h" ]; then
|
||||
usage
|
||||
exit 0
|
||||
fi
|
||||
|
||||
require_cmd "$PROXY_CTL"
|
||||
require_cmd "$SYSTEMCTL"
|
||||
require_cmd "$JOURNALCTL"
|
||||
require_cmd "$IP_BIN"
|
||||
require_cmd "$NFT_BIN"
|
||||
require_cmd "$CURL_BIN"
|
||||
|
||||
OUTPUT_DIR="${1:-/tmp/proxy-suite-xray-tun-$(date +%Y%m%d-%H%M%S)}"
|
||||
mkdir -p "$OUTPUT_DIR"
|
||||
|
||||
ORIG_PROXY_ACTIVE=0
|
||||
ORIG_TUN_ACTIVE=0
|
||||
ORIG_TPROXY_ACTIVE=0
|
||||
ORIG_XRAY_LOGLEVEL=""
|
||||
|
||||
if service_active proxy-suite-socks; then
|
||||
ORIG_PROXY_ACTIVE=1
|
||||
fi
|
||||
if service_active proxy-suite-tun; then
|
||||
ORIG_TUN_ACTIVE=1
|
||||
fi
|
||||
if service_active proxy-suite-tproxy; then
|
||||
ORIG_TPROXY_ACTIVE=1
|
||||
fi
|
||||
if [ -r "$XRAY_LOGLEVEL_FILE" ]; then
|
||||
ORIG_XRAY_LOGLEVEL="$(tr -d '\r\n' < "$XRAY_LOGLEVEL_FILE")"
|
||||
fi
|
||||
|
||||
trap restore_state EXIT
|
||||
|
||||
printf 'info\n' >"$XRAY_LOGLEVEL_FILE"
|
||||
|
||||
run_global_probe global-tun /run/proxy-suite-tun/config.json proxy-suite-tun
|
||||
run_per_app_probe per-app-tun "$PER_APP_TUN_PROFILE" /run/proxy-suite-per-app-tun/config.json proxy-suite-per-app-tun
|
||||
run_global_probe global-tproxy /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-tproxy
|
||||
run_per_app_probe per-app-tproxy "$PER_APP_TPROXY_PROFILE" /run/proxy-suite-socks/config.json proxy-suite-socks proxy-suite-per-app-tproxy
|
||||
|
||||
printf '%s\n' "$OUTPUT_DIR"
|
||||
@@ -1,16 +1,16 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read a subscription URL from stdin and emit a JSON array of outbounds."""
|
||||
"""Read a subscription URL from stdin and emit a JSON array of backend outbounds."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
|
||||
from proxy_parsing import decode_subscription, fetch_raw, parse_subscription
|
||||
from proxy_parsing import decode_subscription, fetch_raw, parse_hybrid_subscription, parse_subscription
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description="Fetch a proxy subscription URL from stdin and emit a sing-box outbound JSON array."
|
||||
description="Fetch a proxy subscription URL from stdin and emit a backend outbound JSON array."
|
||||
)
|
||||
ap.add_argument(
|
||||
"--tag-prefix",
|
||||
@@ -18,6 +18,7 @@ def main() -> None:
|
||||
dest="tag_prefix",
|
||||
help="Prefix for outbound tags, e.g. 'my-sub'.",
|
||||
)
|
||||
ap.add_argument("--backend", choices=["sing-box", "xray", "hybrid"], default="sing-box")
|
||||
ap.add_argument("--routing-mark", type=int, default=None, dest="routing_mark")
|
||||
args = ap.parse_args()
|
||||
|
||||
@@ -33,9 +34,14 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
|
||||
lines = decode_subscription(raw)
|
||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark)
|
||||
if args.backend == "hybrid":
|
||||
outbounds = parse_hybrid_subscription(lines, args.tag_prefix, args.routing_mark)
|
||||
has_outbounds = bool(outbounds["singBox"] or outbounds["xray"])
|
||||
else:
|
||||
outbounds = parse_subscription(lines, args.tag_prefix, args.routing_mark, args.backend)
|
||||
has_outbounds = bool(outbounds)
|
||||
|
||||
if not outbounds:
|
||||
if not has_outbounds:
|
||||
print("error: subscription contained no parseable proxy URIs", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
+237
-4
@@ -13,14 +13,202 @@ def detect_scheme(url: str) -> str:
|
||||
return url.split("://", 1)[0].lower()
|
||||
|
||||
|
||||
def build_outbound(url: str, tag: str, routing_mark: int | None = None) -> dict:
|
||||
def _parse_url(url: str, tag: str, backend: str) -> dict:
|
||||
scheme = detect_scheme(url)
|
||||
if scheme not in PARSERS:
|
||||
raise ValueError(f"unsupported scheme '{scheme}'")
|
||||
|
||||
outbound = PARSERS[scheme](url, tag)
|
||||
parser = PARSERS[scheme]
|
||||
try:
|
||||
return parser(url, tag, backend)
|
||||
except TypeError:
|
||||
return parser(url, tag)
|
||||
|
||||
|
||||
def _xray_sockopt(routing_mark: int | None) -> dict:
|
||||
if routing_mark is None:
|
||||
return {}
|
||||
return {"streamSettings": {"sockopt": {"mark": routing_mark}}}
|
||||
|
||||
|
||||
def _xray_tls(tls: dict | None) -> tuple[str, dict]:
|
||||
if not tls or not tls.get("enabled"):
|
||||
return "none", {}
|
||||
|
||||
if tls.get("reality", {}).get("enabled"):
|
||||
reality = tls["reality"]
|
||||
settings = {
|
||||
"serverName": tls.get("server_name", ""),
|
||||
"publicKey": reality["public_key"],
|
||||
"shortId": reality.get("short_id", ""),
|
||||
}
|
||||
utls = tls.get("utls", {})
|
||||
if reality.get("spider_x"):
|
||||
settings["spiderX"] = reality["spider_x"]
|
||||
if utls.get("enabled") and utls.get("fingerprint"):
|
||||
settings["fingerprint"] = utls["fingerprint"]
|
||||
return "reality", {"realitySettings": settings}
|
||||
|
||||
settings = {"serverName": tls.get("server_name", "")}
|
||||
if tls.get("alpn"):
|
||||
settings["alpn"] = tls["alpn"]
|
||||
if tls.get("insecure"):
|
||||
raise ValueError(
|
||||
"XRay no longer supports tlsSettings.allowInsecure; "
|
||||
"remove insecure=1 or use a supported certificate verification option"
|
||||
)
|
||||
if tls.get("ech_config_list"):
|
||||
settings["echConfigList"] = tls["ech_config_list"]
|
||||
utls = tls.get("utls", {})
|
||||
if utls.get("enabled") and utls.get("fingerprint"):
|
||||
settings["fingerprint"] = utls["fingerprint"]
|
||||
return "tls", {"tlsSettings": settings}
|
||||
|
||||
|
||||
def _xray_transport(transport: dict | None) -> tuple[str, dict]:
|
||||
if not transport:
|
||||
return "raw", {}
|
||||
|
||||
t = transport["type"]
|
||||
if t == "ws":
|
||||
return "ws", {"wsSettings": {"path": transport.get("path", "/"), "headers": transport.get("headers", {})}}
|
||||
if t == "grpc":
|
||||
return "grpc", {"grpcSettings": {"serviceName": transport.get("service_name", "")}}
|
||||
if t == "http":
|
||||
return "http", {"httpSettings": {"host": transport.get("host", []), "path": transport.get("path", "/")}}
|
||||
if t == "httpupgrade":
|
||||
return "httpupgrade", {
|
||||
"httpupgradeSettings": {
|
||||
"host": transport.get("host", ""),
|
||||
"path": transport.get("path", "/"),
|
||||
}
|
||||
}
|
||||
if t == "quic":
|
||||
return "quic", {}
|
||||
if t == "xhttp":
|
||||
settings = {"path": transport.get("path", "/")}
|
||||
if transport.get("host"):
|
||||
settings["host"] = transport["host"]
|
||||
if transport.get("mode"):
|
||||
settings["mode"] = transport["mode"]
|
||||
if transport.get("extra") is not None:
|
||||
settings["extra"] = transport["extra"]
|
||||
return "xhttp", {"xhttpSettings": settings}
|
||||
return t, {}
|
||||
|
||||
|
||||
def render_xray_outbound(ob: dict, routing_mark: int | None = None) -> dict:
|
||||
typ = ob["type"]
|
||||
tag = ob["tag"]
|
||||
|
||||
def stream_settings() -> dict:
|
||||
security, sec = _xray_tls(ob.get("tls"))
|
||||
network, net = _xray_transport(ob.get("transport"))
|
||||
stream = {"network": network, "security": security}
|
||||
stream.update(sec)
|
||||
stream.update(net)
|
||||
stream.setdefault("sockopt", {})["domainStrategy"] = "UseIP"
|
||||
if routing_mark is not None:
|
||||
stream.setdefault("sockopt", {})["mark"] = routing_mark
|
||||
return stream
|
||||
|
||||
if typ == "vless":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"id": ob["uuid"],
|
||||
"encryption": "none",
|
||||
}
|
||||
if ob.get("flow"):
|
||||
settings["flow"] = ob["flow"]
|
||||
return {"protocol": "vless", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "vmess":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"id": ob["uuid"],
|
||||
"security": ob.get("security", "auto"),
|
||||
"alterId": ob.get("alter_id", 0),
|
||||
}
|
||||
return {"protocol": "vmess", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "trojan":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"password": ob["password"],
|
||||
}
|
||||
return {"protocol": "trojan", "tag": tag, "settings": settings, "streamSettings": stream_settings()}
|
||||
|
||||
if typ == "shadowsocks":
|
||||
settings = {
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
"method": ob["method"],
|
||||
"password": ob["password"],
|
||||
}
|
||||
return {"protocol": "shadowsocks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||
|
||||
if typ == "hysteria2":
|
||||
stream = stream_settings()
|
||||
stream["network"] = "hysteria"
|
||||
stream["security"] = "tls"
|
||||
stream["hysteriaSettings"] = {"version": 2}
|
||||
settings = {
|
||||
"version": 2,
|
||||
"address": ob["server"],
|
||||
"port": ob["server_port"],
|
||||
}
|
||||
if ob.get("password"):
|
||||
stream["hysteriaSettings"]["auth"] = ob["password"]
|
||||
if ob.get("obfs", {}).get("type") == "salamander":
|
||||
stream.setdefault("finalmask", {}).setdefault("udp", []).append(
|
||||
{
|
||||
"type": "salamander",
|
||||
"settings": {"password": ob["obfs"].get("password", "")},
|
||||
}
|
||||
)
|
||||
return {"protocol": "hysteria", "tag": tag, "settings": settings, "streamSettings": stream}
|
||||
|
||||
if typ == "socks":
|
||||
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||
if ob.get("username"):
|
||||
settings["user"] = ob["username"]
|
||||
settings["pass"] = ob.get("password", "")
|
||||
return {"protocol": "socks", "tag": tag, "settings": settings, **_xray_sockopt(routing_mark)}
|
||||
|
||||
if typ == "http":
|
||||
settings = {"address": ob["server"], "port": ob["server_port"]}
|
||||
if ob.get("username"):
|
||||
settings["user"] = ob["username"]
|
||||
settings["pass"] = ob.get("password", "")
|
||||
outbound = {"protocol": "http", "tag": tag, "settings": settings}
|
||||
if ob.get("tls"):
|
||||
security, sec = _xray_tls(ob.get("tls"))
|
||||
outbound["streamSettings"] = {"security": security, **sec}
|
||||
if routing_mark is not None:
|
||||
outbound["streamSettings"].setdefault("sockopt", {})["mark"] = routing_mark
|
||||
elif routing_mark is not None:
|
||||
outbound.update(_xray_sockopt(routing_mark))
|
||||
return outbound
|
||||
|
||||
raise ValueError(f"unsupported XRay outbound type '{typ}'")
|
||||
|
||||
|
||||
def build_outbound(
|
||||
url: str, tag: str, routing_mark: int | None = None, backend: str = "sing-box"
|
||||
) -> dict:
|
||||
if backend not in {"sing-box", "xray"}:
|
||||
raise ValueError(f"unsupported backend '{backend}'")
|
||||
|
||||
outbound = _parse_url(url, tag, backend)
|
||||
if routing_mark is not None:
|
||||
if backend == "xray":
|
||||
return render_xray_outbound(outbound, routing_mark)
|
||||
outbound["routing_mark"] = routing_mark
|
||||
elif backend == "xray":
|
||||
return render_xray_outbound(outbound)
|
||||
return outbound
|
||||
|
||||
|
||||
@@ -63,7 +251,7 @@ def make_tag(prefix: str, remark: str, index: int) -> str:
|
||||
|
||||
|
||||
def parse_subscription(
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None, backend: str = "sing-box"
|
||||
) -> list[dict]:
|
||||
outbounds = []
|
||||
seen_tags: set[str] = set()
|
||||
@@ -84,7 +272,7 @@ def parse_subscription(
|
||||
tag = f"{base_tag}-{suffix}"
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark)
|
||||
outbound = build_outbound(line, tag, routing_mark, backend)
|
||||
except Exception as exc:
|
||||
print(f"warning: skipping entry {index} ({scheme}): {exc}", file=sys.stderr)
|
||||
continue
|
||||
@@ -93,3 +281,48 @@ def parse_subscription(
|
||||
outbounds.append(outbound)
|
||||
|
||||
return outbounds
|
||||
|
||||
|
||||
def parse_hybrid_subscription(
|
||||
lines: list[str], tag_prefix: str, routing_mark: int | None = None
|
||||
) -> dict[str, list[dict]]:
|
||||
outbounds: dict[str, list[dict]] = {"singBox": [], "xray": []}
|
||||
seen_tags: set[str] = set()
|
||||
|
||||
for index, line in enumerate(lines):
|
||||
scheme = detect_scheme(line)
|
||||
if scheme not in PARSERS:
|
||||
continue
|
||||
|
||||
remark = line.split("#", 1)[1] if "#" in line else ""
|
||||
base_tag = make_tag(tag_prefix, remark, index)
|
||||
tag = base_tag
|
||||
|
||||
if tag in seen_tags:
|
||||
suffix = 2
|
||||
while f"{base_tag}-{suffix}" in seen_tags:
|
||||
suffix += 1
|
||||
tag = f"{base_tag}-{suffix}"
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, "sing-box")
|
||||
outbounds["singBox"].append(outbound)
|
||||
seen_tags.add(tag)
|
||||
continue
|
||||
except Exception as sing_box_exc:
|
||||
sing_box_error = sing_box_exc
|
||||
|
||||
try:
|
||||
outbound = build_outbound(line, tag, routing_mark, "xray")
|
||||
except Exception as xray_exc:
|
||||
print(
|
||||
f"warning: skipping entry {index} ({scheme}): "
|
||||
f"sing-box: {sing_box_error}; xray: {xray_exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
|
||||
outbounds["xray"].append(outbound)
|
||||
seen_tags.add(tag)
|
||||
|
||||
return outbounds
|
||||
+134
-15
@@ -1,49 +1,116 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import base64
|
||||
import binascii
|
||||
import json
|
||||
import urllib.parse
|
||||
|
||||
SUPPORTED_VLESS_TRANSPORTS = {
|
||||
"",
|
||||
"tcp",
|
||||
"ws",
|
||||
"grpc",
|
||||
"h2",
|
||||
"http",
|
||||
"httpupgrade",
|
||||
"quic",
|
||||
}
|
||||
|
||||
SUPPORTED_XRAY_TRANSPORTS = SUPPORTED_VLESS_TRANSPORTS | {
|
||||
"xhttp",
|
||||
"splithttp",
|
||||
}
|
||||
|
||||
|
||||
def _qs(query: str) -> dict:
|
||||
return dict(urllib.parse.parse_qsl(query))
|
||||
return dict(urllib.parse.parse_qsl(query, keep_blank_values=True))
|
||||
|
||||
|
||||
def _split_host_port(hostpart: str) -> tuple[str, str]:
|
||||
host, separator, port = hostpart.rpartition(":")
|
||||
if not separator or not host or not port:
|
||||
raise ValueError("URL must include host and port")
|
||||
if host.startswith("[") and host.endswith("]"):
|
||||
host = host[1:-1]
|
||||
return host, port
|
||||
|
||||
|
||||
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
|
||||
rest = url[len(f"{scheme}://") :]
|
||||
rest, _, _ = rest.partition("#")
|
||||
if "@" in rest:
|
||||
userinfo, _, rest = rest.partition("@")
|
||||
userinfo, _, rest = rest.rpartition("@")
|
||||
else:
|
||||
userinfo = ""
|
||||
hostpart, _, query = rest.partition("?")
|
||||
host, _, port = hostpart.rpartition(":")
|
||||
host, port = _split_host_port(hostpart)
|
||||
return userinfo, host, port, _qs(query)
|
||||
|
||||
|
||||
def _parse_json_param(value: str, name: str) -> dict:
|
||||
try:
|
||||
parsed = json.loads(value)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise ValueError(f"invalid {name} JSON: {exc}") from exc
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError(f"invalid {name} JSON: expected object")
|
||||
return parsed
|
||||
|
||||
|
||||
def _mk_transport(
|
||||
transport_type: str,
|
||||
path: str = "/",
|
||||
host_header: str = "",
|
||||
service_name: str = "",
|
||||
mode: str = "",
|
||||
extra: str = "",
|
||||
x_padding_bytes: str = "",
|
||||
) -> "dict | None":
|
||||
if transport_type == "ws":
|
||||
normalized = transport_type.lower()
|
||||
|
||||
if normalized in ("", "tcp"):
|
||||
return None
|
||||
if normalized == "ws":
|
||||
return {
|
||||
"type": "ws",
|
||||
"path": urllib.parse.unquote(path),
|
||||
"headers": {"Host": host_header},
|
||||
}
|
||||
if transport_type == "grpc":
|
||||
if normalized == "grpc":
|
||||
return {
|
||||
"type": "grpc",
|
||||
"service_name": urllib.parse.unquote(service_name),
|
||||
}
|
||||
if transport_type == "h2":
|
||||
if normalized in ("h2", "http"):
|
||||
return {
|
||||
"type": "http",
|
||||
"host": [host_header],
|
||||
"path": urllib.parse.unquote(path),
|
||||
}
|
||||
if normalized == "httpupgrade":
|
||||
return {
|
||||
"type": "httpupgrade",
|
||||
"host": host_header,
|
||||
"path": urllib.parse.unquote(path),
|
||||
}
|
||||
if normalized == "quic":
|
||||
return {
|
||||
"type": "quic",
|
||||
}
|
||||
if normalized in ("xhttp", "splithttp"):
|
||||
transport = {
|
||||
"type": "xhttp",
|
||||
"path": urllib.parse.unquote(path),
|
||||
}
|
||||
if host_header:
|
||||
transport["host"] = host_header
|
||||
if mode:
|
||||
transport["mode"] = mode
|
||||
if extra:
|
||||
transport["extra"] = _parse_json_param(extra, "xhttp extra")
|
||||
elif x_padding_bytes:
|
||||
transport["extra"] = {"xPaddingBytes": x_padding_bytes}
|
||||
return transport
|
||||
return None
|
||||
|
||||
|
||||
@@ -65,10 +132,26 @@ def _mk_auth(userinfo: str) -> "tuple[str | None, str | None]":
|
||||
return None, None
|
||||
|
||||
|
||||
def parse_vless(url: str, tag: str) -> dict:
|
||||
def parse_vless(url: str, tag: str, backend: str = "sing-box") -> dict:
|
||||
userinfo, host, port, params = _parse_url_parts(url, "vless")
|
||||
security = params.get("security", "none")
|
||||
transport = params.get("type", "tcp")
|
||||
normalized_transport = transport.lower()
|
||||
|
||||
if "ech" in params and backend != "xray":
|
||||
raise ValueError(
|
||||
"unsupported VLESS parameter 'ech': proxy-suite does not translate "
|
||||
"share-link ECH blobs into sing-box TLS config"
|
||||
)
|
||||
|
||||
supported_transports = (
|
||||
SUPPORTED_XRAY_TRANSPORTS if backend == "xray" else SUPPORTED_VLESS_TRANSPORTS
|
||||
)
|
||||
if normalized_transport not in supported_transports:
|
||||
raise ValueError(
|
||||
f"unsupported VLESS transport '{transport}': proxy-suite only maps "
|
||||
f"{backend}-documented transports; use raw JSON or another client/core"
|
||||
)
|
||||
|
||||
ob: dict = {
|
||||
"type": "vless",
|
||||
@@ -86,16 +169,23 @@ def parse_vless(url: str, tag: str) -> dict:
|
||||
"public_key": params["pbk"],
|
||||
"short_id": params.get("sid", ""),
|
||||
}
|
||||
if backend == "xray" and params.get("spx"):
|
||||
ob["tls"]["reality"]["spider_x"] = params["spx"]
|
||||
elif security == "tls":
|
||||
ob["tls"] = _mk_tls(
|
||||
params.get("sni", host), fp=params.get("fp"), alpn=params.get("alpn")
|
||||
)
|
||||
if backend == "xray" and "ech" in params:
|
||||
ob["tls"]["ech_config_list"] = urllib.parse.unquote(params["ech"])
|
||||
|
||||
tr = _mk_transport(
|
||||
transport,
|
||||
normalized_transport,
|
||||
path=params.get("path", "/"),
|
||||
host_header=params.get("host", host),
|
||||
service_name=params.get("serviceName", ""),
|
||||
mode=params.get("mode", ""),
|
||||
extra=params.get("extra", ""),
|
||||
x_padding_bytes=params.get("x_padding_bytes", ""),
|
||||
)
|
||||
if tr is not None:
|
||||
ob["transport"] = tr
|
||||
@@ -109,10 +199,13 @@ def parse_vless(url: str, tag: str) -> dict:
|
||||
|
||||
def parse_vmess(url: str, tag: str) -> dict:
|
||||
b64 = url[len("vmess://") :]
|
||||
b64, _, _ = b64.partition("#")
|
||||
b64, _, _ = b64.partition("?")
|
||||
b64 = urllib.parse.unquote(b64)
|
||||
pad = "=" * (-len(b64) % 4)
|
||||
try:
|
||||
data = json.loads(base64.b64decode(b64 + pad))
|
||||
except Exception:
|
||||
except (binascii.Error, ValueError):
|
||||
data = json.loads(base64.urlsafe_b64decode(b64 + pad))
|
||||
|
||||
host = str(data["add"])
|
||||
@@ -180,18 +273,44 @@ def parse_trojan(url: str, tag: str) -> dict:
|
||||
return ob
|
||||
|
||||
|
||||
def parse_shadowsocks(url: str, tag: str) -> dict:
|
||||
userinfo, host, port, _ = _parse_url_parts(url, "ss")
|
||||
def _decode_ss_userinfo(userinfo: str) -> tuple[str, str]:
|
||||
plain = urllib.parse.unquote(userinfo)
|
||||
if ":" in plain:
|
||||
return tuple(plain.split(":", 1))
|
||||
|
||||
pad = "=" * (-len(userinfo) % 4)
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(userinfo + pad).decode()
|
||||
if ":" not in decoded:
|
||||
raise ValueError
|
||||
method, password = decoded.split(":", 1)
|
||||
except Exception:
|
||||
plain = urllib.parse.unquote(userinfo)
|
||||
method, password = plain.split(":", 1)
|
||||
return tuple(decoded.split(":", 1))
|
||||
except (binascii.Error, UnicodeDecodeError, ValueError) as exc:
|
||||
raise ValueError("invalid shadowsocks userinfo") from exc
|
||||
|
||||
|
||||
def parse_shadowsocks(url: str, tag: str) -> dict:
|
||||
# Support both SIP002 form:
|
||||
# ss://base64(method:password)@host:port#name
|
||||
# and legacy subscriptions that base64-encode the whole endpoint:
|
||||
# ss://base64(method:password@host:port)#name
|
||||
rest = url[len("ss://") :]
|
||||
rest, _, _ = rest.partition("#")
|
||||
endpoint, _, _ = rest.partition("?")
|
||||
|
||||
if "@" in endpoint:
|
||||
userinfo, host, port, _ = _parse_url_parts(url, "ss")
|
||||
else:
|
||||
pad = "=" * (-len(endpoint) % 4)
|
||||
try:
|
||||
decoded = base64.urlsafe_b64decode(endpoint + pad).decode()
|
||||
except (binascii.Error, UnicodeDecodeError) as exc:
|
||||
raise ValueError("invalid shadowsocks URL") from exc
|
||||
userinfo, separator, hostpart = decoded.rpartition("@")
|
||||
if not separator:
|
||||
raise ValueError("invalid legacy shadowsocks URL")
|
||||
host, port = _split_host_port(hostpart)
|
||||
|
||||
method, password = _decode_ss_userinfo(userinfo)
|
||||
|
||||
return {
|
||||
"type": "shadowsocks",
|
||||
|
||||
@@ -11,6 +11,10 @@ def run_parser(url: str):
|
||||
return build_outbound(url, "test-outbound")
|
||||
|
||||
|
||||
def run_xray_parser(url: str):
|
||||
return build_outbound(url, "test-outbound", backend="xray")
|
||||
|
||||
|
||||
class BuildOutboundTests(unittest.TestCase):
|
||||
def test_vless_reality(self):
|
||||
ob = run_parser(
|
||||
@@ -20,6 +24,93 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["server"], "example.com")
|
||||
self.assertEqual(ob["tls"]["reality"]["public_key"], "pubkey")
|
||||
|
||||
def test_vless_reality_germany_main_shape(self):
|
||||
ob = run_parser(
|
||||
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
|
||||
)
|
||||
self.assertEqual(ob["type"], "vless")
|
||||
self.assertEqual(ob["server_port"], 443)
|
||||
self.assertEqual(ob["flow"], "xtls-rprx-vision")
|
||||
self.assertEqual(ob["tls"]["server_name"], "last.fm")
|
||||
self.assertEqual(ob["tls"]["utls"]["fingerprint"], "qq")
|
||||
self.assertEqual(ob["tls"]["reality"]["short_id"], "8a54")
|
||||
self.assertNotIn("spider_x", ob["tls"]["reality"])
|
||||
self.assertNotIn("transport", ob)
|
||||
|
||||
def test_xray_vless_reality_germany_main_shape(self):
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=tcp&security=reality&pbk=pubkey&fp=qq&sni=last.fm&sid=8a54&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
|
||||
)
|
||||
self.assertEqual(ob["protocol"], "vless")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertEqual(ob["settings"]["flow"], "xtls-rprx-vision")
|
||||
self.assertEqual(ob["streamSettings"]["network"], "raw")
|
||||
self.assertEqual(ob["streamSettings"]["sockopt"]["domainStrategy"], "UseIP")
|
||||
self.assertEqual(ob["streamSettings"]["realitySettings"]["serverName"], "last.fm")
|
||||
self.assertEqual(ob["streamSettings"]["realitySettings"]["fingerprint"], "qq")
|
||||
self.assertEqual(
|
||||
ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers"
|
||||
)
|
||||
|
||||
def test_vless_httpupgrade_transport(self):
|
||||
ob = run_parser(
|
||||
"vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade"
|
||||
)
|
||||
self.assertEqual(ob["transport"]["type"], "httpupgrade")
|
||||
self.assertEqual(ob["transport"]["host"], "cdn.example.com")
|
||||
self.assertEqual(ob["transport"]["path"], "/upgrade")
|
||||
|
||||
def test_vless_quic_transport(self):
|
||||
ob = run_parser("vless://uuid@example.com:443?type=quic&security=tls&sni=cdn.example.com")
|
||||
self.assertEqual(ob["transport"]["type"], "quic")
|
||||
|
||||
def test_vless_xhttp_fails_loudly(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported VLESS transport 'xhttp'"):
|
||||
run_parser(
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com"
|
||||
)
|
||||
|
||||
def test_xray_vless_xhttp(self):
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
|
||||
)
|
||||
self.assertEqual(ob["protocol"], "vless")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertEqual(ob["settings"]["id"], "uuid")
|
||||
self.assertEqual(ob["streamSettings"]["network"], "xhttp")
|
||||
self.assertEqual(ob["streamSettings"]["xhttpSettings"]["path"], "/x")
|
||||
|
||||
def test_xray_vless_ech(self):
|
||||
ob = run_xray_parser(
|
||||
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
|
||||
)
|
||||
self.assertEqual(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1")
|
||||
|
||||
def test_xray_socks_uses_current_flat_settings_shape(self):
|
||||
ob = run_xray_parser("socks5://user:pass@example.com:1080")
|
||||
self.assertEqual(ob["protocol"], "socks")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertEqual(ob["settings"]["user"], "user")
|
||||
self.assertNotIn("servers", ob["settings"])
|
||||
|
||||
def test_xray_shadowsocks_uses_current_flat_settings_shape(self):
|
||||
credentials = (
|
||||
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd")
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
ob = run_xray_parser(f"ss://{credentials}@ss.example.com:8388")
|
||||
self.assertEqual(ob["protocol"], "shadowsocks")
|
||||
self.assertEqual(ob["settings"]["address"], "ss.example.com")
|
||||
self.assertEqual(ob["settings"]["method"], "chacha20-ietf-poly1305")
|
||||
self.assertNotIn("servers", ob["settings"])
|
||||
|
||||
def test_vless_ech_fails_loudly(self):
|
||||
with self.assertRaisesRegex(ValueError, "unsupported VLESS parameter 'ech'"):
|
||||
run_parser(
|
||||
"vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=blob"
|
||||
)
|
||||
|
||||
def test_vmess(self):
|
||||
payload = {
|
||||
"add": "vmess.example.com",
|
||||
@@ -39,6 +130,19 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["transport"]["type"], "ws")
|
||||
self.assertEqual(ob["tls"]["server_name"], "cdn.example.com")
|
||||
|
||||
def test_vmess_with_external_remark(self):
|
||||
payload = {
|
||||
"add": "vmess.example.com",
|
||||
"port": "443",
|
||||
"id": "00000000-0000-0000-0000-000000000000",
|
||||
"aid": "0",
|
||||
"scy": "auto",
|
||||
}
|
||||
encoded = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
ob = run_parser(f"vmess://{encoded}#Subscription Remark")
|
||||
self.assertEqual(ob["type"], "vmess")
|
||||
self.assertEqual(ob["server"], "vmess.example.com")
|
||||
|
||||
def test_trojan(self):
|
||||
ob = run_parser("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome")
|
||||
self.assertEqual(ob["type"], "trojan")
|
||||
@@ -55,6 +159,37 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["type"], "shadowsocks")
|
||||
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
||||
|
||||
def test_shadowsocks_legacy_full_base64(self):
|
||||
legacy = (
|
||||
base64.urlsafe_b64encode(
|
||||
b"chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388"
|
||||
)
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
ob = run_parser(f"ss://{legacy}#Legacy Server")
|
||||
self.assertEqual(ob["type"], "shadowsocks")
|
||||
self.assertEqual(ob["server"], "legacy.example.com")
|
||||
self.assertEqual(ob["server_port"], 8388)
|
||||
self.assertEqual(ob["method"], "chacha20-ietf-poly1305")
|
||||
self.assertEqual(ob["password"], "passw0rd")
|
||||
|
||||
def test_shadowsocks_plain_userinfo(self):
|
||||
ob = run_parser("ss://none:plain%20pass@plain.example.com:8388")
|
||||
self.assertEqual(ob["type"], "shadowsocks")
|
||||
self.assertEqual(ob["method"], "none")
|
||||
self.assertEqual(ob["password"], "plain pass")
|
||||
|
||||
def test_shadowsocks_legacy_ipv6_strips_brackets(self):
|
||||
legacy = (
|
||||
base64.urlsafe_b64encode(b"none:pass@[2001:db8::1]:8388")
|
||||
.decode()
|
||||
.rstrip("=")
|
||||
)
|
||||
ob = run_parser(f"ss://{legacy}#Legacy IPv6")
|
||||
self.assertEqual(ob["server"], "2001:db8::1")
|
||||
self.assertEqual(ob["server_port"], 8388)
|
||||
|
||||
def test_hysteria2(self):
|
||||
ob = run_parser(
|
||||
"hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask"
|
||||
@@ -63,6 +198,25 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertTrue(ob["tls"]["insecure"])
|
||||
self.assertEqual(ob["obfs"]["password"], "mask")
|
||||
|
||||
def test_xray_hysteria2(self):
|
||||
ob = run_xray_parser(
|
||||
"hy2://secret@example.com:443?sni=hy.example.com&obfs=salamander&obfs-password=mask"
|
||||
)
|
||||
self.assertEqual(ob["protocol"], "hysteria")
|
||||
self.assertEqual(ob["settings"]["address"], "example.com")
|
||||
self.assertNotIn("password", ob["settings"])
|
||||
self.assertEqual(ob["streamSettings"]["network"], "hysteria")
|
||||
self.assertEqual(ob["streamSettings"]["tlsSettings"]["serverName"], "hy.example.com")
|
||||
self.assertEqual(ob["streamSettings"]["hysteriaSettings"]["auth"], "secret")
|
||||
self.assertEqual(
|
||||
ob["streamSettings"]["finalmask"]["udp"],
|
||||
[{"type": "salamander", "settings": {"password": "mask"}}],
|
||||
)
|
||||
|
||||
def test_xray_hysteria2_insecure_fails_loudly(self):
|
||||
with self.assertRaisesRegex(ValueError, "allowInsecure"):
|
||||
run_xray_parser("hy2://secret@example.com:443?sni=hy.example.com&insecure=1")
|
||||
|
||||
def test_tuic(self):
|
||||
ob = run_parser(
|
||||
"tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29"
|
||||
@@ -76,6 +230,12 @@ class BuildOutboundTests(unittest.TestCase):
|
||||
self.assertEqual(ob["version"], "5")
|
||||
self.assertEqual(ob["username"], "user")
|
||||
|
||||
def test_proxy_userinfo_allows_at_in_password(self):
|
||||
ob = run_parser("socks5://user:p@ss@example.com:1080")
|
||||
self.assertEqual(ob["username"], "user")
|
||||
self.assertEqual(ob["password"], "p@ss")
|
||||
self.assertEqual(ob["server"], "example.com")
|
||||
|
||||
def test_https_proxy(self):
|
||||
ob = run_parser("https://proxy.example.com:8443")
|
||||
self.assertEqual(ob["type"], "http")
|
||||
|
||||
@@ -2,9 +2,11 @@
|
||||
|
||||
import base64
|
||||
import unittest
|
||||
from proxy_parsing import decode_subscription, parse_subscription
|
||||
from proxy_parsing import decode_subscription, parse_hybrid_subscription, parse_subscription
|
||||
|
||||
VLESS_URI = "vless://uuid@example.com:443?security=reality&pbk=pubkey&fp=chrome&sni=cdn.example.com&sid=abcd"
|
||||
VLESS_XHTTP_URI = "vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx"
|
||||
VLESS_ECH_URI = "vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1"
|
||||
SS_URI = "ss://{}@ss.example.com:8388".format(
|
||||
base64.urlsafe_b64encode(b"chacha20-ietf-poly1305:passw0rd").decode().rstrip("=")
|
||||
)
|
||||
@@ -18,10 +20,16 @@ def _make_b64_payload(*uris: str) -> bytes:
|
||||
|
||||
|
||||
def run_fetcher(
|
||||
server_data: bytes, tag_prefix: str = "test", *, routing_mark: int | None = None
|
||||
server_data: bytes,
|
||||
tag_prefix: str = "test",
|
||||
*,
|
||||
routing_mark: int | None = None,
|
||||
backend: str = "sing-box",
|
||||
):
|
||||
lines = decode_subscription(server_data)
|
||||
return parse_subscription(lines, tag_prefix, routing_mark)
|
||||
if backend == "hybrid":
|
||||
return parse_hybrid_subscription(lines, tag_prefix, routing_mark)
|
||||
return parse_subscription(lines, tag_prefix, routing_mark, backend)
|
||||
|
||||
|
||||
class FetchSubscriptionTests(unittest.TestCase):
|
||||
@@ -112,6 +120,23 @@ class FetchSubscriptionTests(unittest.TestCase):
|
||||
obs = run_fetcher(payload)
|
||||
self.assertEqual(len(obs), 2)
|
||||
|
||||
def test_hybrid_subscription_preserves_xray_only_entries(self):
|
||||
payload = _make_b64_payload(VLESS_URI, VLESS_XHTTP_URI, VLESS_ECH_URI)
|
||||
obs = run_fetcher(payload, backend="hybrid")
|
||||
self.assertEqual(len(obs["singBox"]), 1)
|
||||
self.assertEqual(len(obs["xray"]), 2)
|
||||
self.assertEqual(obs["singBox"][0]["type"], "vless")
|
||||
self.assertEqual(obs["xray"][0]["streamSettings"]["network"], "xhttp")
|
||||
self.assertEqual(
|
||||
obs["xray"][1]["streamSettings"]["tlsSettings"]["echConfigList"],
|
||||
"udp://1.1.1.1",
|
||||
)
|
||||
|
||||
def test_hybrid_subscription_all_invalid_returns_empty_backend_lists(self):
|
||||
payload = _make_b64_payload(INVALID_URI, "not-a-uri-at-all")
|
||||
obs = run_fetcher(payload, backend="hybrid")
|
||||
self.assertEqual(obs, {"singBox": [], "xray": []})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user