17 Commits
Author SHA1 Message Date
FUFSoB d3c68f7a9a some simplifications and improvements 2026-04-15 13:43:18 +05:00
FUFSoB fe41f56cc5 update system tray 2026-04-15 13:07:42 +05:00
FUFSoB eeea6c161d move userControl to root options 2026-04-15 11:07:46 +05:00
FUFSoB 8d4779481c allow using all privileged proxy-ctl command for group proxy-suite 2026-04-14 22:57:41 +05:00
FUFSoB de33512c88 update docs on per-app 2026-04-14 22:51:31 +05:00
FUFSoB 435c908663 per-app zapret 2026-04-14 22:50:27 +05:00
FUFSoB c3f4088458 per-app tproxy 2026-04-14 18:40:03 +05:00
FUFSoB 14557eba82 per-app tun 2026-04-14 18:17:27 +05:00
FUFSoB 181f3355c1 proxychains integration, proxy-ctl wrap 2026-04-14 14:49:32 +05:00
FUFSoB e6c7b1a817 Fix README 2026-04-14 10:59:16 +05:00
FUFSoB 981745bafb more docs improvements 2026-04-13 18:39:08 +05:00
FUFSoB 215958b367 make dns configurable 2026-04-13 17:26:48 +05:00
FUFSoB 5f45041e4c small readme clarification 2026-04-13 17:11:35 +05:00
FUFSoB 2ba1167d69 make default tg-ws-proxy host local-only 2026-04-13 17:03:51 +05:00
FUFSoB b8496a5737 add tproxy/tun autostart option 2026-04-13 16:58:33 +05:00
FUFSoB aac8e8d17d refined docs 2026-04-13 16:48:40 +05:00
FUFSoB 1eebbfdc21 update tg-ws-proxy package 2026-04-12 20:24:52 +05:00
25 changed files with 8351 additions and 935 deletions

No files matched your search

+13 -485
View File
@@ -1,25 +1,26 @@
# proxy-suite-flake
Declarative proxy stack for NixOS. One flake, one module, done.
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.
The goal is to replace GUI clients like v2rayN, throne and their ilk – you configure your proxies in Nix, rebuild, and they just work as systemd services.
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.
---
## 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
- **TUN mode** – full tunnel via a virtual network interface; useful when TProxy doesn't cover something
- **Transparent proxy (TProxy)** – redirect all system traffic through sing-box 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
- **`proxy-ctl`** – control script for managing services, switching outbounds, and following logs
- **DPI bypass** via zapret – handles YouTube, Discord, and other sites that are blocked by packet inspection rather than IP
- **Telegram proxy** – local MTProto WebSocket proxy using tg-ws-proxy
- **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
---
@@ -36,496 +37,23 @@ No need to add zapret separately – it comes along as a transitive input.
Add the module to your NixOS configuration:
```nix
imports = [ inputs.proxy-suite.nixosModules.default ];
modules = [ inputs.proxy-suite.nixosModules.default ];
```
---
## Basic configuration
Enable the service with all defaults:
```nix
services.proxy-suite = {
enable = true;
singBox = {
outbounds = [
{
tag = "vps";
# Runtime secret – not in the nix store.
# Works with sops-nix, agenix, or anything that gives you a file path.
urlFile = config.sops.secrets.proxy_url.path;
}
];
routing = {
# Default: send RU geosite/geoip traffic direct.
enableRuDirect = true;
direct.domains = [ "reddit.com" ];
};
routing.proxy.geosites = [ "google" ];
};
zapret = {
enable = true;
# Default: mirror zapret domain lists into sing-box direct routing.
syncDirectRouting = true;
# Upstream zapret IP ranges are much broader, so keep them opt-in.
syncDirectRoutingUpstreamIps = false;
# User-defined ipsetAll/ipsetExclude still map into sing-box by default.
syncDirectRoutingUserIps = true;
};
};
```
After `nixos-rebuild switch`, you have a SOCKS proxy at `localhost:1080`.
If you intentionally want to expose it on another interface, set:
```nix
services.proxy-suite.singBox.listenAddress = "0.0.0.0";
```
To also start transparent proxying:
```bash
systemctl start proxy-suite-tproxy
```
TProxy installs its own nftables interception rules and can coexist with the NixOS firewall.
By default, `zapret` and `tgWsProxy` stay disabled until you enable them explicitly.
---
## Outbound formats
## Options
Each outbound needs exactly one of `urlFile`, `url`, or `json`.
To see options and documentation, check out the [options reference](./docs/options.md).
### urlFile (recommended for real credentials)
```nix
outbounds = [{
tag = "vps";
urlFile = config.sops.secrets.my_vps_url.path;
}];
```
The URL is read at service start time. Never touches the nix store.
### url (convenient, not secret)
```nix
outbounds = [{
tag = "vps";
url = "hy2://yourpassword@your-server.com:443?sni=your-server.com";
}];
```
The URL string ends up in `/nix/store`. Fine for non-sensitive configs or testing.
### json (full sing-box outbound attrset)
```nix
outbounds = [{
tag = "vps";
json = {
type = "vless";
server = "your-server.com";
server_port = 443;
uuid = "your-uuid";
tls = {
enabled = true;
server_name = "your-server.com";
reality = {
enabled = true;
public_key = "your-public-key";
short_id = "abc123";
};
};
};
}];
```
Embedded at build time. Good when you generate the config programmatically.
---
## Multiple outbounds
```nix
singBox = {
outbounds = [
{ tag = "de"; urlFile = config.sops.secrets.vps_de.path; }
{ tag = "nl"; urlFile = config.sops.secrets.vps_nl.path; }
];
# Auto-select the fastest (checks every 3 minutes)
selection = "urltest";
# Or expose a Clash-compatible API for manual switching:
# selection = "selector";
# clashApiPort = 9090; # then use a Clash controller UI
};
```
---
## Subscription URLs
A subscription URL is an HTTP endpoint that returns a base64-encoded newline-separated list of proxy URIs — the standard format used by v2rayN, Clash, and similar clients. All supported proxy schemes (VLESS, VMess, Trojan, Shadowsocks, Hysteria2, TUIC, SOCKS5, HTTP…) can appear in the same subscription.
```nix
singBox = {
subscriptions = [
{
tag = "community";
url = "https://example.com/sub/your-token";
}
];
# urltest is strongly recommended for subscriptions: sing-box probes all proxies
# concurrently and routes through the fastest working one. With selection = "first"
# a single dead server in position 0 breaks everything.
selection = "urltest";
subscriptionUpdateInterval = "6h"; # refresh every 6 hours (default: 1d)
# Optional: test against a URL that is actually blocked in your region.
# Only proxies that bypass the block will win — not just any reachable server.
# Defaults to https://www.gstatic.com/generate_204 (reachability check only).
urlTest.url = "https://telegram.org/";
};
```
Use `urlFile` instead of `url` to keep the subscription URL out of the nix store:
```nix
subscriptions = [{
tag = "private";
urlFile = config.sops.secrets.sub_url.path;
}];
```
### How it works
**First start:** the service fetches the subscription URL live and writes the parsed outbounds to `/var/lib/proxy-suite/subscriptions/<tag>.json`.
**Subsequent starts:** the cache file is used directly — no network access on restart.
**Periodic refresh:** a systemd timer (`proxy-suite-subscription-update`) fires on boot (after 5 minutes) and then every `subscriptionUpdateInterval`. On success it updates the cache files and restarts `proxy-suite-socks` (and `proxy-suite-tun` if it is active).
### urltest startup behavior
When `selection = "urltest"`, sing-box starts probing all proxies **concurrently** the moment the service comes up. Until the first test result arrives (typically within a few seconds), traffic uses the first proxy in the list. As tests complete, sing-box progressively switches to faster winners. Dead proxies are skipped as their tests time out.
**Practical consequence:** the first few requests after a (re)start may go through a slow or unreachable proxy. This resolves quickly — usually within 5–20 seconds — without any manual action.
To minimize this window, set `urlTest.url` to a URL that must actually be reachable through a working proxy (e.g. a blocked site in your region). This way the first working test result corresponds to a proxy that genuinely serves your traffic, not just any reachable server.
### Tag generation
Each proxy URI in the subscription gets a sing-box outbound tag derived from its `#remark` fragment:
```
<subscription-tag>-<slugified-remark>
```
For example, a subscription with `tag = "sub"` and a proxy remarked `Server DE #1` becomes `sub-Server-DE--1`. URIs without a remark get `sub-0`, `sub-1`, etc. Duplicate tags are suffixed with `-2`, `-3`, and so on.
### Routing domains through subscription proxies
Routing rules that point to `"proxy"` automatically use whatever subscription proxy is currently active. With `selection = "urltest"`, the fastest subscription proxy handles those domains. With `selection = "selector"`, the manually chosen one does.
```nix
singBox = {
subscriptions = [{ tag = "community"; url = "https://example.com/sub/token"; }];
selection = "urltest";
# These domains go through whichever community proxy wins the latency test.
routing.proxy.domains = [ "telegram.org" "twitter.com" ];
};
```
You **cannot** route specific domains to "a named group of proxies from subscription X" — subscription tags are generated at runtime and are unknown at Nix eval time. If you need to pin a domain to a specific proxy, use `selection = "selector"`, switch to that proxy via `proxy-ctl select <tag>`, and all routing rules pointing to `"proxy"` will follow.
### Mixing subscriptions with static outbounds
Subscriptions and static outbound declarations can coexist. Subscription outbounds are appended after static ones, so with `selection = "selector"` or `"urltest"` all of them are available:
```nix
singBox = {
outbounds = [
{ tag = "own-vps"; urlFile = config.sops.secrets.vps.path; }
];
subscriptions = [
{ tag = "backup"; url = "https://example.com/sub/token"; }
];
selection = "urltest";
};
```
### `selection = "first"` with subscriptions
With `selection = "first"` and static outbounds, the first static outbound is used (as usual). With `selection = "first"` and **subscriptions only**, the first proxy from the first subscription is used as `proxy`.
---
## Per-outbound routing
By default all proxied traffic goes to whatever the active outbound is (the selector, urltest winner, or single "first" outbound). You can override this per-outbound or with explicit rules to send specific traffic to a specific server.
Global direct routing also has two built-in behaviors:
- `singBox.routing.enableRuDirect = true` sends `geosite-category-ru` and `geoip-ru` direct by default.
- If `zapret.enable = true`, then `zapret.syncDirectRouting = true` mirrors zapret's upstream domain hostlists into sing-box direct rules. `zapret.syncDirectRoutingUpstreamIps = false` by default, so upstream zapret IP ranges are not mirrored unless you opt in, while `zapret.syncDirectRoutingUserIps = true` keeps user `ipsetAll`/`ipsetExclude` mirrored by default.
**Attached to an outbound:**
```nix
outbounds = [
{
tag = "de";
urlFile = config.sops.secrets.vps_de.path;
# Only meaningful with selection = "selector" or "urltest"
routing.geosites = [ "netflix" ];
routing.geoips = [ "us" ];
routing.domains = [ "hulu.com" "peacocktv.com" ];
}
{
tag = "nl";
urlFile = config.sops.secrets.vps_nl.path;
routing.domains = [ "discord.com" "discordapp.com" ];
}
];
```
**Explicit rules list** – also works for `direct` and `block`, in any selection mode:
```nix
singBox.routing.rules = [
# Block ad networks before anything else
{ outbound = "block"; geosites = [ "category-ads-all" ]; }
# Internal traffic goes direct
{ outbound = "direct"; domains = [ "corp.internal" ]; ips = [ "10.0.0.0/8" ]; }
# Route US ips and Netflix to a specific server
{ outbound = "de"; geoips = [ "us" ]; geosites = [ "netflix" ]; }
];
```
Rules from `outbound.routing` and `routing.rules` are evaluated **before** the global `routing.proxy` / `routing.direct` / `routing.block` lists, so they always take priority.
Within a single rule, `domains`, `ips`, `geosites`, and `geoips` are treated as independent matches. In practice that means one rule with multiple fields behaves like OR, not AND.
In `first` selection mode, per-outbound tags are resolved to `"proxy"` automatically (there's only one proxy outbound in that mode, so routing to a specific tag doesn't make sense).
---
## proxy-ctl
A control script is installed into your system packages automatically. Run it as root or with the right polkit permissions.
```
proxy-ctl status show status of all proxy-suite services
proxy-ctl tproxy on|off enable/disable TProxy transparent mode
proxy-ctl tun on|off enable/disable TUN mode
proxy-ctl restart restart proxy-suite-socks, and proxy-suite-tun if it is active
proxy-ctl logs [service] follow logs (default: proxy-suite-socks)
proxy-ctl outbounds list outbounds and current selection (needs Clash API)
proxy-ctl select <tag> switch to a specific outbound (selector mode)
proxy-ctl subscription list show subscriptions, cache age, and proxy count
proxy-ctl subscription update force-refresh all subscription caches and restart
```
`outbounds` works with `selection = "selector"` or `"urltest"`. `select` requires `selection = "selector"` and talks to the Clash-compatible REST API embedded in sing-box.
`subscription list` and `subscription update` are only meaningful when `singBox.subscriptions` is non-empty.
---
## Protocol URL formats
| Protocol | Example URL |
| --------------- | ------------------------------------------------------------------------------------------------ |
| VLESS + Reality | `vless://uuid@host:443?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=abc&flow=xtls-rprx-vision` |
| VLESS + TLS | `vless://uuid@host:443?security=tls&sni=SNI&type=ws&path=/path` |
| VMess | `vmess://BASE64_JSON` (standard V2 link format) |
| Trojan | `trojan://password@host:443?sni=SNI&fp=chrome` |
| Shadowsocks | `ss://BASE64(method:password)@host:port` or `ss://method:password@host:port` |
| Hysteria2 | `hy2://password@host:443?sni=SNI` |
| TUIC v5 | `tuic://uuid:password@host:443?sni=SNI&congestion_control=bbr` |
| SOCKS5 | `socks5://user:pass@host:1080` or `socks5://host:1080` |
| SOCKS4 | `socks4://host:1080` |
| HTTP proxy | `http://user:pass@host:8080` |
| HTTPS proxy | `https://host:8080` (HTTP CONNECT over TLS) |
---
## Zapret
zapret handles DPI-based blocking by mangling packets at the netfilter level. It's separate from the proxy, but by default this module also mirrors zapret-covered domains into sing-box direct routing so the proxy does not fight zapret for the same traffic.
```nix
zapret = {
enable = true;
configName = "general(ALT)";
syncDirectRouting = true; # default: sync upstream domain lists
syncDirectRoutingUpstreamIps = false; # default: do not sync upstream IP ranges
syncDirectRoutingUserIps = true; # default: do sync user ipsetAll/ipsetExclude
# Extra domains beyond zapret's built-in list
listGeneral = [ "pixiv.net" "pximg.net" ];
};
```
When `syncDirectRouting = true`, the module always reuses zapret's upstream `hostlists/list-general.txt` and `list-google.txt`, adds your `listGeneral`, and subtracts both upstream and user domain exclusions before generating sing-box direct rules. If `zapret.includeExtraUpstreamLists = true`, it also includes upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` in both zapret handling and sing-box direct sync.
Custom `zapret.hostlistRules` domains also join this direct-domain sync by default. Set `enableDirectSync = false` on a custom hostlist if you want zapret to handle it but do not want sing-box direct-routing rules generated from it.
The generated zapret config can also auto-activate upstream `list-instagram.txt`, `list-soundcloud.txt`, and `list-twitter.txt` when the selected upstream preset does not already reference them. They are attached using the active config's `general` rule family so those hostlists are actually handled by zapret instead of just existing on disk. This is disabled by default; set `zapret.includeExtraUpstreamLists = true;` to opt in.
When `syncDirectRoutingUpstreamIps = true`, the module also mirrors zapret's upstream `ipset-all.txt`. This is disabled by default because the upstream IP set is intentionally broad.
When `syncDirectRoutingUserIps = true`, the module mirrors your `ipsetAll` and `ipsetExclude` values into sing-box direct routing even if upstream IP sync stays disabled. This is enabled by default.
If zapret corrupts traffic for some subnet (e.g. a VM behind a libvirt bridge):
```nix
zapret.cidrExemption = {
enable = true;
cidrs = [ "192.168.123.0/24" ]; # your VM's bridge network(s)
};
```
You can also define custom zapret hostlists with per-list rules:
```nix
zapret.hostlistRules = [
{
name = "googlevideo";
domains = [ "googlevideo.com" "ggpht.com" ];
preset = "google";
}
{
name = "example";
domains = [ "example.com" "example.de" ];
nfqwsArgs = [
"--filter-tcp=443 --dpi-desync=fake,multisplit"
];
}
{
name = "social-extra";
domains = [ "x.example" ];
preset = "twitter";
nfqwsArgs = [
"--filter-udp=443 --dpi-desync=fake --dpi-desync-repeats=6"
];
}
];
```
Each entry generates `hostlists/list-<name>.txt`. `preset` clones the active zapret config's matching family rules for that hostlist, while `nfqwsArgs` appends custom NFQWS rule fragments. The module injects the generated `--hostlist=...`, standard zapret exclude files, and trailing `--new` automatically.
---
## Telegram proxy
Runs a WebSocket MTProto relay. Useful for sharing with others on mobile or for clients that need a dedicated Telegram proxy.
```nix
tgWsProxy = {
enable = true;
# Generate a secret: openssl rand -hex 16
secretFile = config.sops.secrets.tg_ws_proxy_secret.path;
port = 1076;
host = "0.0.0.0"; # configurable bind address
};
```
`secretFile` is the recommended form because it keeps the secret out of the nix store. The legacy inline `secret = "...";` form still works for testing.
---
## Services
| Service | Auto-starts | Description |
| --------------------------------- | ------------------ | ------------------------------------------------ |
| `proxy-suite-socks` | yes | SOCKS5/HTTP proxy, always running |
| `proxy-suite-tproxy` | no | TProxy transparent mode (start manually) |
| `proxy-suite-tun` | no | TUN mode (start manually, conflicts with tproxy) |
| `proxy-suite-tg-ws-proxy` | yes (if enabled) | Telegram proxy |
| `proxy-suite-zapret-vm-exempt` | yes (if enabled) | VM subnet exemption |
| `proxy-suite-subscription-update` | timer (if sub set) | Refresh subscription caches and restart |
TProxy and TUN are mutually exclusive. Start one, the other refuses to start.
---
## Secret management
This module doesn't care how you manage secrets. Anything that gives you a file path works:
**sops-nix:**
```nix
sops.secrets.proxy_url.sopsFile = ./secrets/proxy.yaml;
services.proxy-suite.singBox.outbounds = [{
tag = "vps";
urlFile = config.sops.secrets.proxy_url.path;
}];
```
**agenix:**
```nix
age.secrets.proxy_url.file = ./secrets/proxy_url.age;
services.proxy-suite.singBox.outbounds = [{
tag = "vps";
urlFile = config.age.secrets.proxy_url.path;
}];
```
**Plain file (not recommended but works):**
```nix
# Create /run/proxy-url with your URL, ensure it's readable by root
urlFile = "/run/proxy-url";
```
---
## System tray
Optional tray indicator for desktop environments. Shows proxy status and provides quick toggles.
```nix
services.proxy-suite = {
tray = {
enable = true;
autostart = true; # Install XDG autostart for all graphical users (default)
pollInterval = 5; # Status refresh interval in seconds
};
};
```
Features:
- **Status icon**: `network-vpn` (active), `network-vpn-acquiring` (partial), `network-vpn-disconnected` (stopped)
- **Quick controls window**: Opens on secondary activation and on hosts that emit StatusNotifier `Activate` on left-click (including niri)
- **Enable/Disable Proxy**: Toggles `proxy-suite-socks`; disabling proxy also stops active TProxy/TUN first
- **Toggle TProxy/TUN**: Only shown if the service is enabled in your config
- **Close window**: Hides the floating controls window without exiting the tray
- **Update Subscriptions**: Triggers `proxy-suite-subscription-update` to re-fetch all subscription caches; only shown when subscriptions are configured
- **Restart services**: Restarts `proxy-suite-socks`, and `proxy-suite-tun` if it is active
- **Polkit authentication**: Prompts for password when toggling services
When enabled, the tray app is installed system-wide and autostarts for all graphical users via XDG autostart unless you set `tray.autostart = false;`.
The tray uses libayatana-appindicator and requires StatusNotifier/AppIndicator support. KDE generally works out of the box; GNOME may need shell support or an extension that exposes AppIndicators.
To enable TProxy/TUN toggles in the tray, you need to enable the services in your config:
```nix
services.proxy-suite.singBox = {
tproxy.enable = true; # Show TProxy toggle
tun.enable = true; # Show TUN toggle
};
```
Options are autogenerated from [options.nix](./modules/proxy-suite/options.nix) using `nix run .#update-options-doc`.
+4762
View File
File diff suppressed because it is too large. Load diff
+45 -3
View File
@@ -23,6 +23,9 @@
forAll = nixpkgs.lib.genAttrs systems;
pkgsFor = system: import nixpkgs { inherit system; };
proxySuiteModule = import ./modules/proxy-suite { inherit zapret; };
mkOptionsDoc = import ./nix/options-doc.nix {
inherit nixpkgs pkgsFor proxySuiteModule;
};
in
{
# Main module – bakes in the zapret flake so consumers don't need it as a separate input.
@@ -36,9 +39,47 @@
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = final; };
};
packages = forAll (system: {
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { pkgs = pkgsFor system; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { pkgs = pkgsFor system; };
packages = forAll (
system:
let
pkgs = pkgsFor system;
in
{
tg-ws-proxy = import ./pkgs/tg-ws-proxy.nix { inherit pkgs; };
proxy-suite-tray = import ./pkgs/proxy-suite-tray.nix { inherit pkgs; };
optionsDoc = mkOptionsDoc system;
update-options-doc = pkgs.writeShellApplication {
name = "update-options-doc";
runtimeInputs = [
pkgs.coreutils
pkgs.git
pkgs.nix
];
text = ''
set -euo pipefail
repo_root="$(git rev-parse --show-toplevel 2>/dev/null || true)"
if [[ -z "''${repo_root}" || ! -f "''${repo_root}/flake.nix" ]]; then
echo "run this helper from inside the proxy-suite-flake repository" >&2
exit 1
fi
output_path="$(nix build --no-link --print-out-paths "''${repo_root}#optionsDoc")"
target_path="''${repo_root}/docs/options.md"
install -Dm644 "''${output_path}" "''${target_path}"
echo "updated ''${target_path}"
'';
};
}
);
apps = forAll (system: {
update-options-doc = {
type = "app";
program = "${self.packages.${system}.update-options-doc}/bin/update-options-doc";
};
});
checks = forAll (
@@ -50,6 +91,7 @@
proxySuiteModule
zapret
;
generatedOptionsDoc = mkOptionsDoc system;
}
);
};
+78 -43
View File
@@ -9,8 +9,38 @@
let
sb = cfg.singBox;
art = cfg.appRouting.backends.tun;
direct = rules.direct;
mkDnsServer =
tag: upstream: detour:
{
inherit tag;
type = upstream.type;
server = upstream.address;
server_port = upstream.port;
}
// lib.optionalAttrs (detour != null) { inherit detour; };
mkDnsConfig =
{ localDetour ? null }:
{
servers = [
(mkDnsServer "remote" sb.dns.remote "proxy")
(mkDnsServer "local" sb.dns.local localDetour)
];
rules =
lib.optional (builtins.elem "google" sb.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if sb.proxyByDefault then "remote" else "local";
};
clashApiBlock = lib.optionalAttrs (sb.selection != "first") {
experimental = {
clash_api = {
@@ -19,50 +49,30 @@ let
};
};
dnsConfig = {
servers = [
{
tag = "remote";
type = "udp";
server = "1.1.1.1";
detour = "proxy";
}
{
tag = "local";
type = "udp";
server = "1.1.1.1";
# In TUN mode, routing DNS through direct can conflict with auto_redirect.
# In TProxy/mixed mode, direct is fine for local traffic.
detour = "direct";
}
];
rules =
lib.optional (builtins.elem "google" sb.routing.proxy.geosites) {
rule_set = [ "geosite-google" ];
server = "remote";
}
++ lib.optional (direct.geosites != [ ]) {
rule_set = map (s: "geosite-${s}") direct.geosites;
server = "local";
};
final = if sb.proxyByDefault then "remote" else "local";
};
dnsConfigTun = dnsConfig // {
servers = map (s: if s.tag == "local" then s // { detour = "proxy"; } else s) dnsConfig.servers;
};
mkConfig =
{
enableMixed ? false,
enableTProxy ? false,
enableTun ? false,
tunInterface ? sb.tun.interface,
tunAddress ? sb.tun.address,
tunMtu ? sb.tun.mtu,
tunAutoRoute ? true,
tunAutoRedirect ? true,
tunStrictRoute ? true,
forceLocalDnsViaProxy ? false,
useOutboundRoutingMark ? false,
enableClashApi ? true,
}:
{
log.level = "warn";
dns = if enableTun then dnsConfigTun else dnsConfig;
# 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 {
localDetour = if forceLocalDnsViaProxy then "proxy" else null;
};
inbounds =
lib.optional enableMixed {
@@ -80,12 +90,12 @@ let
++ lib.optional enableTun {
type = "tun";
tag = "tun-in";
interface_name = sb.tun.interface;
address = [ sb.tun.address ];
mtu = sb.tun.mtu;
auto_route = true;
auto_redirect = true;
strict_route = true;
interface_name = tunInterface;
address = [ tunAddress ];
mtu = tunMtu;
auto_route = tunAutoRoute;
auto_redirect = tunAutoRedirect;
strict_route = tunStrictRoute;
stack = "mixed";
};
@@ -110,24 +120,49 @@ let
rules = rules.routingRules;
final = if sb.proxyByDefault then "proxy" else "direct";
}
// lib.optionalAttrs enableTun { auto_detect_interface = true; };
// lib.optionalAttrs (enableTun && tunAutoRoute) { auto_detect_interface = true; };
}
// clashApiBlock;
// lib.optionalAttrs enableClashApi clashApiBlock;
tproxyTemplate = mkConfig {
enableMixed = true;
enableTProxy = true;
useOutboundRoutingMark = true;
enableClashApi = true;
};
tunTemplate = mkConfig {
enableTun = true;
tunInterface = sb.tun.interface;
tunAddress = sb.tun.address;
tunMtu = sb.tun.mtu;
tunAutoRoute = true;
tunAutoRedirect = true;
tunStrictRoute = true;
forceLocalDnsViaProxy = true;
enableClashApi = false;
};
appTunTemplate = mkConfig {
enableTun = true;
tunInterface = art.interface;
tunAddress = art.address;
tunMtu = art.mtu;
tunAutoRoute = false;
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 = sb.tproxy.enable;
enableClashApi = false;
};
tproxyFile = pkgs.writeText "proxy-suite-tproxy-template.json" (builtins.toJSON tproxyTemplate);
tunFile = pkgs.writeText "proxy-suite-tun-template.json" (builtins.toJSON tunTemplate);
appTunFile = pkgs.writeText "proxy-suite-app-tun-template.json" (builtins.toJSON appTunTemplate);
in
{
inherit tproxyFile tunFile;
inherit tproxyFile tunFile appTunFile;
}
+4 -6
View File
@@ -11,13 +11,11 @@
let
cfg = config.services.proxy-suite;
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
in
{
imports = [
./options.nix
# Always import the zapret module so its options are available,
# but we only activate services when cfg.zapret.enable = true.
zapret.nixosModules.default
];
config = lib.mkIf cfg.enable (
@@ -40,7 +38,6 @@ in
rules
;
};
nftr = import ./nftables.nix { inherit lib pkgs cfg; };
in
import ./service.nix {
inherit
@@ -49,8 +46,8 @@ in
pkgs
cfg
;
inherit (configs) tproxyFile tunFile;
inherit (nftr) nftablesRulesFile ip nft;
inherit (configs) tproxyFile tunFile appTunFile;
inherit (nftr) nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
}
))
@@ -62,6 +59,7 @@ in
cfg
zapret
;
inherit (nftr) appZapretRulesFile nft;
}
))
+74 -10
View File
@@ -7,13 +7,12 @@
let
sb = cfg.singBox;
art = cfg.appRouting.backends.tun;
artp = cfg.appRouting.backends.tproxy;
arz = cfg.appRouting.backends.zapret;
localSubnetLines = lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') sb.tproxy.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
# Shared across all three nftables rule files that do IPv4 routing.
reservedIpBlock = ''
define RESERVED_IP = {
10.0.0.0/8,
100.64.0.0/10,
@@ -25,7 +24,18 @@ let
240.0.0.0/4,
255.255.255.255/32
}
'';
mkLocalSubnetLines = subnets: lib.concatMapStrings (cidr: ''
ip daddr ${cidr} tcp dport != 53 return
ip daddr ${cidr} udp dport != 53 return
'') subnets;
tproxyLocalSubnetLines = mkLocalSubnetLines sb.tproxy.localSubnets;
appTproxyLocalSubnetLines = mkLocalSubnetLines artp.localSubnets;
nftablesRulesFile = pkgs.writeText "proxy-suite-tproxy.nft" ''
${reservedIpBlock}
table ip singbox {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
@@ -33,25 +43,79 @@ let
# Packets re-entering via loopback after output marking should not
# be skipped just because the host has an RFC1918 source address.
iifname != "lo" ip saddr $RESERVED_IP return
${localSubnetLines}
${tproxyLocalSubnetLines}
ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort} meta mark set ${toString sb.fwmark}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${localSubnetLines}
${tproxyLocalSubnetLines}
meta mark ${toString sb.proxyMark} return
ip protocol tcp meta mark set ${toString sb.fwmark}
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"}${lib.optionalString artp.enable " meta mark ${toString artp.fwmark} return\n"} ip protocol tcp meta mark set ${toString sb.fwmark}
ip protocol udp meta mark set ${toString sb.fwmark}
}
}
'';
appTproxyRulesFile = pkgs.writeText "proxy-suite-app-tproxy.nft" ''
${reservedIpBlock}
table ip proxy_suite_app_tproxy {
chain prerouting {
type filter hook prerouting priority mangle; policy accept;
ip daddr $RESERVED_IP return
iifname != "lo" ip saddr $RESERVED_IP return
${appTproxyLocalSubnetLines}
ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
meta mark ${toString artp.fwmark} ip protocol tcp tproxy to 127.0.0.1:${toString sb.tproxyPort}
meta mark ${toString artp.fwmark} ip protocol udp tproxy to 127.0.0.1:${toString sb.tproxyPort}
}
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${appTproxyLocalSubnetLines}
meta mark ${toString sb.proxyMark} return
${lib.optionalString art.enable " meta mark ${toString art.fwmark} return\n"} ct mark ${toString artp.fwmark} meta mark set ${toString artp.fwmark}
meta mark ${toString artp.fwmark} return
}
}
'';
appZapretRulesFile = pkgs.writeText "proxy-suite-app-zapret.nft" ''
table inet proxy_suite_app_zapret_mark {
chain prerouting {
type filter hook prerouting priority -103; policy accept;
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
}
chain output {
type route hook output priority -103; policy accept;
ct mark and ${toString arz.filterMark} == ${toString arz.filterMark} meta mark set meta mark or ${toString arz.filterMark}
meta mark and ${toString arz.filterMark} == ${toString arz.filterMark} return
}
}
'';
appTunChainFile = pkgs.writeText "proxy-suite-app-tun-chain.nft" ''
${reservedIpBlock}
table inet proxy_suite_app_tun {
chain output {
type route hook output priority mangle; policy accept;
ip daddr $RESERVED_IP return
${lib.concatMapStrings (cidr: ''
ip daddr ${cidr} return
'') art.localSubnets}
ct mark ${toString art.fwmark} meta mark set ${toString art.fwmark}
meta mark ${toString art.fwmark} return
}
}
'';
ip = "${pkgs.iproute2}/bin/ip";
nft = "${pkgs.nftables}/bin/nft";
in
{
inherit nftablesRulesFile ip nft;
inherit nftablesRulesFile appTproxyRulesFile appZapretRulesFile appTunChainFile ip nft;
}
File diff suppressed because it is too large. Load diff
+708 -15
View File
@@ -6,7 +6,11 @@
cfg,
tproxyFile,
tunFile,
appTunFile,
nftablesRulesFile,
appTproxyRulesFile,
appZapretRulesFile,
appTunChainFile,
ip,
nft,
}:
@@ -14,6 +18,25 @@
let
sb = cfg.singBox;
t = cfg.tgWsProxy;
ar = cfg.appRouting;
uc = cfg.userControl;
art = ar.backends.tun;
artp = ar.backends.tproxy;
arz = ar.backends.zapret;
userControlEnabled = uc.global.enable || uc.perApp.enable;
userControlPolkitRules =
lib.optionalString uc.perApp.enable ''
if (unit.indexOf("proxy-suite-app-") === 0) {
return polkit.Result.YES;
}
''
+ lib.optionalString uc.global.enable ''
if ((unit.indexOf("proxy-suite-") === 0 &&
unit.indexOf("proxy-suite-app-") !== 0) ||
unit === "zapret-discord-youtube.service") {
return polkit.Result.YES;
}
'';
builtinTags = [
"proxy"
"direct"
@@ -29,6 +52,17 @@ let
jq = "${pkgs.jq}/bin/jq";
python3 = "${pkgs.python3}/bin/python3";
singBox = "${pkgs.sing-box}/bin/sing-box";
proxychains4 = "${pkgs.proxychains-ng}/bin/proxychains4";
systemdRun = "${pkgs.systemd}/bin/systemd-run";
systemctl = "${pkgs.systemd}/bin/systemctl";
journalctl = "${pkgs.systemd}/bin/journalctl";
idBin = "${pkgs.coreutils}/bin/id";
grepBin = "${pkgs.gnugrep}/bin/grep";
awk = "${pkgs.gawk}/bin/awk";
sleepBin = "${pkgs.coreutils}/bin/sleep";
headBin = "${pkgs.coreutils}/bin/head";
seqBin = "${pkgs.coreutils}/bin/seq";
findBin = "${pkgs.findutils}/bin/find";
fetchSubscriptionPy = ../../scripts/fetch-subscription.py;
@@ -190,6 +224,15 @@ let
routingMark = null;
};
startAppTun = mkStartScript {
name = "proxy-suite-start-app-tun";
runtimeDir = "/run/proxy-suite-app-tun";
configFile = appTunFile;
# Only needed when TProxy mode is enabled; otherwise avoid tagging app TUN
# proxy outbounds with a host-global mark.
routingMark = if sb.tproxy.enable then sb.proxyMark else null;
};
clashApi = "http://127.0.0.1:${toString sb.clashApiPort}";
selection = sb.selection;
@@ -236,18 +279,234 @@ let
# Subscription tags embedded at build time for proxy-ctl.
subscriptionTagsList = lib.concatStringsSep " " (map (sub: lib.escapeShellArg sub.tag) sb.subscriptions);
hasSubscriptions = sb.subscriptions != [ ];
appRoutingProfileNames = map (profile: profile.name) ar.profiles;
defaultAppRoutingProfiles = lib.optionals ar.createDefaultProfiles [
{
name = "proxychains";
route = "proxychains";
}
] ++ lib.optionals art.enable [
{
name = "tun";
route = "tun";
}
] ++ lib.optionals artp.enable [
{
name = "tproxy";
route = "tproxy";
}
] ++ lib.optionals (arz.enable && cfg.zapret.enable) [
{
name = "zapret";
route = "zapret";
}
];
effectiveAppRoutingProfiles =
ar.profiles
++ builtins.filter (profile: !(builtins.elem profile.name appRoutingProfileNames)) defaultAppRoutingProfiles;
effectiveAppRoutingProfileNames = map (profile: profile.name) effectiveAppRoutingProfiles;
appRoutingProfilesFile = pkgs.writeText "proxy-suite-app-routing-profiles.json" (
builtins.toJSON effectiveAppRoutingProfiles
);
proxychainsConfigFile = pkgs.writeText "proxy-suite-proxychains.conf" ''
strict_chain
${lib.optionalString ar.proxychains.quiet "quiet_mode"}
${lib.optionalString ar.proxychains.proxyDns "proxy_dns"}
tcp_read_time_out 15000
tcp_connect_time_out 8000
[ProxyList]
socks5 ${sb.listenAddress} ${toString sb.port}
'';
proxychainsQuietArg = lib.optionalString ar.proxychains.quiet "-q ";
hasProxychainsProfiles = builtins.any (profile: profile.route == "proxychains") effectiveAppRoutingProfiles;
hasTunProfiles = builtins.any (profile: profile.route == "tun") effectiveAppRoutingProfiles;
hasTproxyProfiles = builtins.any (profile: profile.route == "tproxy") effectiveAppRoutingProfiles;
hasZapretProfiles = builtins.any (profile: profile.route == "zapret") effectiveAppRoutingProfiles;
appTunSliceName = "proxy-suite-app-tun.slice";
appTproxySliceName = "proxy-suite-app-tproxy.slice";
appZapretSliceName = "proxy-suite-app-zapret.slice";
appTunWaitForInterface = pkgs.writeShellScript "proxy-suite-app-tun-wait-for-interface" ''
set -euo pipefail
for _ in $(${seqBin} 1 50); do
if ${ip} link show dev ${lib.escapeShellArg art.interface} >/dev/null 2>&1; then
exit 0
fi
${sleepBin} 0.1
done
echo "proxy-suite: app TUN interface ${art.interface} did not appear in time" >&2
exit 1
'';
appTunUpScript = pkgs.writeShellScript "proxy-suite-app-tun-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
${nft} -f ${appTunChainFile}
${appTunWaitForInterface}
${ip} route replace default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable}
${ip} rule add fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true
'';
appTunDownScript = pkgs.writeShellScript "proxy-suite-app-tun-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_tun 2>/dev/null || true
${ip} route del default dev ${lib.escapeShellArg art.interface} table ${toString art.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString art.fwmark} table ${toString art.routeTable} 2>/dev/null || true
'';
# Generate a "start" script that adds a per-user cgroup nftables mark rule.
mkUserRuleStart =
{
name,
nftFamily,
nftTable,
nftChain,
sliceName,
sliceLabel,
markRule,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-start" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
mark_comment="$rule_comment_prefix-mark"
cgroup_root="/sys/fs/cgroup/user.slice/user-$uid.slice/user@$uid.service"
if ! [ -d "$cgroup_root" ]; then
echo "proxy-suite: user cgroup root does not exist for uid $uid: $cgroup_root" >&2
exit 1
fi
cgroup_dir=$(${findBin} "$cgroup_root" -type d -name ${lib.escapeShellArg sliceName} | ${headBin} -n1 || true)
if [ -z "$cgroup_dir" ]; then
echo "proxy-suite: ${sliceLabel} slice cgroup does not exist for uid $uid under $cgroup_root" >&2
exit 1
fi
cgroup_path=''${cgroup_dir#/sys/fs/cgroup/}
cgroup_level=$(printf '%s' "$cgroup_path" | ${awk} -F/ '{ print NF }')
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
printf '%s\n' \
"add rule ${nftFamily} ${nftTable} ${nftChain} socket cgroupv2 level $cgroup_level \"$cgroup_path\" ${markRule} comment \"$mark_comment\"" \
| ${nft} -f -
'';
# Generate a "stop" script that removes all per-user cgroup nftables mark rules.
mkUserRuleStop =
{
name,
nftFamily,
nftTable,
nftChain,
}:
pkgs.writeShellScript "proxy-suite-${name}-user-stop" ''
set -euo pipefail
uid="$1"
rule_comment_prefix="proxy-suite-${name}-user-$uid"
handles=$(${nft} -a list chain ${nftFamily} ${nftTable} ${nftChain} 2>/dev/null \
| ${grepBin} -F "comment \"$rule_comment_prefix" \
| ${awk} '{ print $NF }' || true)
if [ -n "$handles" ]; then
while IFS= read -r handle; do
[ -n "$handle" ] || continue
${nft} delete rule ${nftFamily} ${nftTable} ${nftChain} handle "$handle" || true
done <<< "$handles"
fi
'';
appTunUserRuleStart = mkUserRuleStart {
name = "app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_app_tun";
nftChain = "output";
sliceName = appTunSliceName;
sliceLabel = "app TUN";
markRule = "meta mark set ${toString art.fwmark} ct mark set ${toString art.fwmark}";
};
appTunUserRuleStop = mkUserRuleStop {
name = "app-tun";
nftFamily = "inet";
nftTable = "proxy_suite_app_tun";
nftChain = "output";
};
appTproxyUserRuleStart = mkUserRuleStart {
name = "app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_app_tproxy";
nftChain = "output";
sliceName = appTproxySliceName;
sliceLabel = "app TProxy";
markRule = "meta mark set ${toString artp.fwmark} ct mark set ${toString artp.fwmark}";
};
appTproxyUserRuleStop = mkUserRuleStop {
name = "app-tproxy";
nftFamily = "ip";
nftTable = "proxy_suite_app_tproxy";
nftChain = "output";
};
appZapretUserRuleStart = mkUserRuleStart {
name = "app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_app_zapret_mark";
nftChain = "output";
sliceName = appZapretSliceName;
sliceLabel = "app zapret";
markRule = "meta mark set meta mark or ${toString arz.filterMark} ct mark set ct mark or ${toString arz.filterMark}";
};
appZapretUserRuleStop = mkUserRuleStop {
name = "app-zapret";
nftFamily = "inet";
nftTable = "proxy_suite_app_zapret_mark";
nftChain = "output";
};
appTproxyUpScript = pkgs.writeShellScript "proxy-suite-app-tproxy-up" ''
set -euo pipefail
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
${nft} -f ${appTproxyRulesFile}
${ip} route replace local default dev lo table ${toString artp.routeTable}
${ip} rule add fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true
'';
appTproxyDownScript = pkgs.writeShellScript "proxy-suite-app-tproxy-down" ''
set -euo pipefail
${nft} delete table ip proxy_suite_app_tproxy 2>/dev/null || true
${ip} route del local default dev lo table ${toString artp.routeTable} 2>/dev/null || true
${ip} rule del fwmark ${toString artp.fwmark} table ${toString artp.routeTable} 2>/dev/null || true
'';
proxyCtl = pkgs.writeShellApplication {
name = "proxy-ctl";
runtimeInputs = with pkgs; [
coreutils
curl
gawk
gnugrep
jq
proxychains-ng
systemd
];
text = ''
# Embedded at build time from module config
CLASH_API="${clashApi}"
SELECTION="${selection}"
SUB_TAGS=(${subscriptionTagsList})
APP_ROUTING_ENABLED="${if ar.enable then "1" else "0"}"
APP_ROUTING_PROXYCHAINS_ENABLED="${if ar.proxychains.enable then "1" else "0"}"
APP_ROUTING_TUN_ENABLED="${if art.enable then "1" else "0"}"
APP_ROUTING_TPROXY_ENABLED="${if artp.enable then "1" else "0"}"
APP_ROUTING_ZAPRET_ENABLED="${if (arz.enable && cfg.zapret.enable) then "1" else "0"}"
APP_ROUTING_PROFILES_FILE="${appRoutingProfilesFile}"
PROXYCHAINS_CONFIG="${proxychainsConfigFile}"
APP_TUN_SLICE_BASE="proxy-suite-app-tun"
APP_TPROXY_SLICE_BASE="proxy-suite-app-tproxy"
APP_ZAPRET_SLICE_BASE="proxy-suite-app-zapret"
ALL_SERVICES=(
proxy-suite-socks
@@ -262,13 +521,17 @@ let
echo "Usage: proxy-ctl <command> [args]"
echo ""
echo "Commands:"
echo " status show status of all proxy-suite services"
echo " status [--tray] show status of all proxy-suite services"
echo " proxy on|off enable/disable the core SOCKS proxy"
echo " tproxy on|off enable/disable TProxy transparent mode"
echo " tun on|off enable/disable TUN mode"
echo " restart restart proxy-suite-socks and proxy-suite-tun if active"
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)"
echo " outbounds list outbounds and current selection"
echo " select <tag> switch to a specific outbound (selector mode)"
echo " apps list configured per-app routing profiles"
echo " wrap <profile> -- <cmd> run a command via an appRouting profile"
echo " subscription list show subscriptions, cache age, and proxy count"
echo " subscription update force-refresh all subscription caches and restart"
exit 1
@@ -284,15 +547,126 @@ let
printf " %-44s %s\n" "$svc" "$state"
}
_bool() {
if "$@"; then
printf true
else
printf false
fi
}
_svc_exists() {
systemctl cat "$1" &>/dev/null
}
_svc_active() {
systemctl is-active --quiet "$1"
}
_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)"
printf 'subscription_update_available=%s\n' "$(_bool _svc_exists proxy-suite-subscription-update)"
}
_ensure_app_routing() {
if [ "$APP_ROUTING_ENABLED" != "1" ]; then
echo "appRouting is not enabled in services.proxy-suite.appRouting."
exit 1
fi
}
_profile_route() {
local profile="$1"
${jq} -r --arg name "$profile" '.[] | select(.name == $name) | .route' "$APP_ROUTING_PROFILES_FILE"
}
_scope_running() {
${systemctl} --user list-units --type=scope --state=running --plain --no-legend "$1-*" \
| ${grepBin} -q .
}
_any_user_active() {
${systemctl} list-units --type=service --state=active --plain --no-legend "$1*.service" \
| ${grepBin} -q .
}
_check_no_global_proxy() {
if ${systemctl} is-active --quiet proxy-suite-tun.service; then
echo "Global proxy-suite-tun.service is active. Stop it before using route=$1 profiles."
exit 1
fi
if ${systemctl} is-active --quiet proxy-suite-tproxy.service; then
echo "Global proxy-suite-tproxy.service is active. Stop it before using route=$1 profiles."
exit 1
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"
shift 4
if [ "$enabled" != "1" ]; then
echo "$disabled_msg"
exit 1
fi
local uid; uid="$(${idBin} -u)"
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
${systemdRun} --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
fi
exit "$status"
}
cmd="''${1:-status}"
shift || true
case "$cmd" in
status)
echo "proxy-suite services:"
for svc in "''${ALL_SERVICES[@]}"; do
_svc_status "$svc"
done
if [ "''${1:-}" = "--tray" ]; then
_status_tray
else
echo "proxy-suite services:"
for svc in "''${ALL_SERVICES[@]}"; do
_svc_status "$svc"
done
fi
;;
proxy)
case "''${1:-on}" in
on)
systemctl start proxy-suite-socks
;;
off)
systemctl stop proxy-suite-tproxy || true
systemctl stop proxy-suite-tun || true
systemctl stop proxy-suite-socks
;;
*)
echo "Usage: proxy-ctl proxy on|off"; exit 1 ;;
esac
;;
tproxy)
@@ -311,11 +685,25 @@ let
esac
;;
zapret)
case "''${1:-on}" in
on) systemctl start zapret-discord-youtube ;;
off) systemctl stop zapret-discord-youtube ;;
*) echo "Usage: proxy-ctl zapret on|off"; exit 1 ;;
esac
;;
restart)
systemctl restart proxy-suite-socks
if systemctl is-active --quiet proxy-suite-tproxy; then
systemctl restart proxy-suite-tproxy
fi
if systemctl is-active --quiet proxy-suite-tun; then
systemctl restart proxy-suite-tun
fi
if systemctl is-active --quiet zapret-discord-youtube; then
systemctl restart zapret-discord-youtube
fi
;;
logs)
@@ -357,6 +745,73 @@ let
fi
;;
apps)
_ensure_app_routing
if [ "$(${jq} 'length' "$APP_ROUTING_PROFILES_FILE")" -eq 0 ]; then
echo "No appRouting profiles configured."
else
printf " %-24s %s\n" "PROFILE" "ROUTE"
${jq} -r '.[] | " " + (.name | tostring) + "\t" + (.route | tostring)' \
"$APP_ROUTING_PROFILES_FILE" \
| while IFS=$'\t' read -r profile route; do
printf "%-26s %s\n" "$profile" "$route"
done
fi
;;
wrap)
profile="''${1:?Usage: proxy-ctl wrap <profile> -- <command> [args...]}"
shift || true
if [ "''${1:-}" = "--" ]; then
shift
fi
if [ "$#" -eq 0 ]; then
echo "Usage: proxy-ctl wrap <profile> -- <command> [args...]"
exit 1
fi
_ensure_app_routing
route="$(_profile_route "$profile")"
if [ -z "$route" ] || [ "$route" = "null" ]; then
echo "Unknown appRouting profile: $profile"
exit 1
fi
case "$route" in
direct)
exec "$@"
;;
proxychains)
if [ "$APP_ROUTING_PROXYCHAINS_ENABLED" != "1" ]; then
echo "Profile '$profile' uses route=proxychains, but appRouting.proxychains.enable is false."
exit 1
fi
exec ${proxychains4} ${proxychainsQuietArg}-f "$PROXYCHAINS_CONFIG" "$@"
;;
tun)
_wrap_slice "$APP_TUN_SLICE_BASE" "$APP_ROUTING_TUN_ENABLED" \
"Profile '$profile' uses route=tun, but appRouting.backends.tun.enable is false." \
"proxy-suite-app-tun.service" "$@"
;;
tproxy)
_check_no_global_proxy tproxy
_wrap_slice "$APP_TPROXY_SLICE_BASE" "$APP_ROUTING_TPROXY_ENABLED" \
"Profile '$profile' uses route=tproxy, but appRouting.backends.tproxy.enable is false." \
"proxy-suite-app-tproxy.service" "$@"
;;
zapret)
_check_no_global_proxy zapret
_wrap_slice "$APP_ZAPRET_SLICE_BASE" "$APP_ROUTING_ZAPRET_ENABLED" \
"Profile '$profile' uses route=zapret, but the app-zapret backend or zapret service is not enabled." \
"proxy-suite-app-zapret.service" "$@"
;;
*)
echo "Route backend '$route' is not implemented in this build."
exit 1
;;
esac
;;
subscription)
subcmd="''${1:-list}"
shift || true
@@ -396,12 +851,59 @@ let
'';
};
mkAnchorService = sliceName: desc: {
description = desc;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
Slice = sliceName;
ExecStart = "${pkgs.coreutils}/bin/true";
ExecStop = "${pkgs.coreutils}/bin/true";
};
};
in
{
environment.systemPackages = [ proxyCtl ];
# nftables must be on for TProxy to work.
networking.nftables.enable = lib.mkIf sb.tproxy.enable (lib.mkDefault true);
networking.nftables.enable = lib.mkIf (sb.tproxy.enable || art.enable || artp.enable || arz.enable) (lib.mkDefault true);
users.groups = lib.mkIf (cfg.enable && userControlEnabled) {
"${uc.group}" = { };
};
security.polkit.enable = lib.mkIf (cfg.enable && userControlEnabled) true;
security.polkit.extraConfig = lib.mkIf (cfg.enable && userControlEnabled) (lib.mkAfter ''
polkit.addRule(function(action, subject) {
if (!subject.isInGroup("${uc.group}")) {
return null;
}
if (action.id !== "org.freedesktop.systemd1.manage-units") {
return null;
}
var unit = action.lookup("unit");
${userControlPolkitRules}
return null;
});
'');
systemd.user.services =
lib.optionalAttrs art.enable {
proxy-suite-app-tun-anchor =
mkAnchorService appTunSliceName "Anchor service for proxy-suite app TUN slice";
}
// lib.optionalAttrs artp.enable {
proxy-suite-app-tproxy-anchor =
mkAnchorService appTproxySliceName "Anchor service for proxy-suite app TProxy slice";
}
// lib.optionalAttrs (arz.enable && cfg.zapret.enable) {
proxy-suite-app-zapret-anchor =
mkAnchorService appZapretSliceName "Anchor service for proxy-suite app zapret slice";
};
assertions = [
{
@@ -420,6 +922,126 @@ in
assertion = invalidRoutingTargets == [ ];
message = "proxy-suite: routing.rules reference unknown outbound tag(s): ${lib.concatStringsSep ", " invalidRoutingTargets}";
}
{
assertion = !(sb.tproxy.enable && sb.tproxy.autostart && sb.tun.enable && sb.tun.autostart);
message = "proxy-suite: singBox.tproxy.autostart and singBox.tun.autostart cannot both be enabled at the same time";
}
{
assertion = ar.enable || ar.profiles == [ ];
message = "proxy-suite: appRouting.profiles requires appRouting.enable = true";
}
{
assertion = !ar.proxychains.enable || ar.enable;
message = "proxy-suite: appRouting.proxychains.enable requires appRouting.enable = true";
}
{
assertion = builtins.length effectiveAppRoutingProfileNames == builtins.length (lib.unique effectiveAppRoutingProfileNames);
message = "proxy-suite: appRouting profile names must be unique";
}
{
assertion = !hasProxychainsProfiles || ar.proxychains.enable;
message = "proxy-suite: route=proxychains in appRouting.profiles requires appRouting.proxychains.enable = true";
}
{
assertion = !art.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tun.enable requires appRouting.enable = true";
}
{
assertion = !(hasTunProfiles && !art.enable);
message = "proxy-suite: route=tun in appRouting profiles requires appRouting.backends.tun.enable = true";
}
{
assertion = !artp.enable || ar.enable;
message = "proxy-suite: appRouting.backends.tproxy.enable requires appRouting.enable = true";
}
{
assertion = !(hasTproxyProfiles && !artp.enable);
message = "proxy-suite: route=tproxy in appRouting profiles requires appRouting.backends.tproxy.enable = true";
}
{
assertion = !arz.enable || ar.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires appRouting.enable = true";
}
{
assertion = !arz.enable || cfg.zapret.enable;
message = "proxy-suite: appRouting.backends.zapret.enable requires zapret.enable = true";
}
{
assertion = !(hasZapretProfiles && (!arz.enable || !cfg.zapret.enable));
message = "proxy-suite: route=zapret in appRouting profiles requires appRouting.backends.zapret.enable = true and zapret.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.fwmark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tun.fwmark must differ from singBox.proxyMark when singBox.tproxy.enable = true";
}
{
assertion = !(art.enable && sb.tproxy.enable && art.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable must differ from singBox.routeTable when singBox.tproxy.enable = true";
}
{
assertion = !(artp.enable && artp.fwmark == sb.fwmark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.fwmark";
}
{
assertion = !(artp.enable && artp.fwmark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must differ from singBox.proxyMark";
}
{
assertion = !(artp.enable && artp.routeTable == sb.routeTable);
message = "proxy-suite: appRouting.backends.tproxy.routeTable must differ from singBox.routeTable";
}
{
assertion = !(art.enable && artp.enable && art.fwmark == artp.fwmark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.tproxy.fwmark must differ";
}
{
assertion = !(art.enable && artp.enable && art.routeTable == artp.routeTable);
message = "proxy-suite: appRouting.backends.tun.routeTable and appRouting.backends.tproxy.routeTable must differ";
}
{
assertion = !(arz.enable && arz.filterMark == sb.fwmark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.fwmark";
}
{
assertion = !(arz.enable && arz.filterMark == sb.proxyMark);
message = "proxy-suite: appRouting.backends.zapret.filterMark must differ from singBox.proxyMark";
}
{
assertion = !(art.enable && arz.enable && art.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tun.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(artp.enable && arz.enable && artp.fwmark == arz.filterMark);
message = "proxy-suite: appRouting.backends.tproxy.fwmark and appRouting.backends.zapret.filterMark must differ";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 536870912 1073741824 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem sb.proxyMark [ 67108864 134217728 ]);
message = "proxy-suite: singBox.proxyMark must not use app-zapret internal desync mark bits";
}
{
assertion = !(art.enable && arz.enable && builtins.elem art.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tun.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(artp.enable && arz.enable && builtins.elem artp.fwmark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.tproxy.fwmark must not use app-zapret internal desync mark bits";
}
{
assertion = !(arz.enable && builtins.elem arz.filterMark [ 67108864 134217728 ]);
message = "proxy-suite: appRouting.backends.zapret.filterMark must not use app-zapret internal desync mark bits";
}
{
assertion =
!t.enable
@@ -460,7 +1082,6 @@ in
]) sb.subscriptions;
systemd.services = {
# Always-on: SOCKS5/HTTP mixed inbound, also ready for TProxy interception.
proxy-suite-socks = {
description = "sing-box proxy client (SOCKS + TProxy-ready)";
after = [ "network.target" ];
@@ -475,17 +1096,18 @@ in
};
}
// lib.optionalAttrs sb.tproxy.enable {
# Opt-in transparent proxy. Start/stop with:
# systemctl start proxy-suite-tproxy
# systemctl stop proxy-suite-tproxy
proxy-suite-tproxy = {
description = "sing-box TProxy – nftables rules and policy routing";
after = [
"network.target"
"proxy-suite-socks.service"
];
wantedBy = lib.optionals sb.tproxy.autostart [ "multi-user.target" ];
requires = [ "proxy-suite-socks.service" ];
conflicts = [ "proxy-suite-tun.service" ];
conflicts = [
"proxy-suite-tun.service"
"proxy-suite-app-tproxy.service"
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
@@ -504,12 +1126,10 @@ in
};
}
// lib.optionalAttrs sb.tun.enable {
# Opt-in TUN mode (full tunnel, no nftables needed). Start/stop with:
# systemctl start proxy-suite-tun
# systemctl stop proxy-suite-tun
proxy-suite-tun = {
description = "sing-box TUN proxy client";
after = [ "network-online.target" ];
wantedBy = lib.optionals sb.tun.autostart [ "multi-user.target" ];
wants = [ "network-online.target" ];
conflicts = [ "proxy-suite-tproxy.service" ];
serviceConfig = {
@@ -521,6 +1141,79 @@ in
};
};
}
// lib.optionalAttrs art.enable {
proxy-suite-app-tun = {
description = "sing-box app-routing TUN backend";
after = [ "network-online.target" ];
wants = [ "network-online.target" ];
serviceConfig = {
ExecStart = "${startAppTun}";
ExecStartPost = "${appTunUpScript}";
ExecStopPost = "${appTunDownScript}";
Restart = "on-failure";
RestartSec = 5;
RuntimeDirectory = "proxy-suite-app-tun";
StateDirectory = "proxy-suite";
};
};
"proxy-suite-app-tun-user@" = {
description = "Enable proxy-suite app TUN marking for user %i";
requires = [ "proxy-suite-app-tun.service" ];
after = [ "proxy-suite-app-tun.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTunUserRuleStart} %i";
ExecStop = "${appTunUserRuleStop} %i";
};
};
}
// lib.optionalAttrs artp.enable {
proxy-suite-app-tproxy = {
description = "proxy-suite app-routing TProxy backend";
after = [
"network.target"
"proxy-suite-socks.service"
];
requires = [ "proxy-suite-socks.service" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTproxyUpScript}";
ExecStop = "${appTproxyDownScript}";
};
};
"proxy-suite-app-tproxy-user@" = {
description = "Enable proxy-suite app TProxy marking for user %i";
requires = [ "proxy-suite-app-tproxy.service" ];
after = [ "proxy-suite-app-tproxy.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appTproxyUserRuleStart} %i";
ExecStop = "${appTproxyUserRuleStop} %i";
};
};
}
// lib.optionalAttrs (arz.enable && cfg.zapret.enable) {
"proxy-suite-app-zapret-user@" = {
description = "Enable proxy-suite app zapret marking for user %i";
requires = [ "proxy-suite-app-zapret.service" ];
after = [ "proxy-suite-app-zapret.service" ];
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
ExecStart = "${appZapretUserRuleStart} %i";
ExecStop = "${appZapretUserRuleStop} %i";
};
};
}
// lib.optionalAttrs hasSubscriptions {
proxy-suite-subscription-update = {
description = "Refresh proxy-suite subscription caches";
+176 -41
View File
@@ -4,10 +4,13 @@
pkgs,
cfg,
zapret,
appZapretRulesFile,
nft,
}:
let
z = cfg.zapret;
arz = cfg.appRouting.backends.zapret;
iptables = "${pkgs.iptables}/bin/iptables";
@@ -15,6 +18,7 @@ let
inherit (pkgs)
iptables
ipset
nftables
coreutils
gawk
curl
@@ -31,7 +35,7 @@ let
hostlistRuleNames = map (rule: rule.name) z.hostlistRules;
upstreamZapretPackage =
baseZapretPackage =
let
upstreamPackages = zapret.packages.${pkgs.stdenv.hostPlatform.system};
in
@@ -87,8 +91,33 @@ let
};
patchConfigScript = "${pkgs.python3}/bin/python3 ${patchConfigScriptSrc}";
customZapretPackage =
pkgs.runCommand "proxy-suite-zapret-${selectedConfigName}"
mkGlobalBypassScript =
filterMark:
pkgs.writeText "proxy-suite-zapret-global-bypass.sh" ''
zapret_custom_firewall_nft() {
nft insert rule inet $ZAPRET_NFT_TABLE postrouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE postnat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prerouting mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
nft insert rule inet $ZAPRET_NFT_TABLE prenat mark and ${filterMark} != 0 return comment "proxy-suite app-zapret bypass"
}
'';
mkDerivedZapretPackage =
{
packageName,
pidDir,
configName ? z.configName,
gameFilter ? z.gameFilter,
forceDisableFilterMark ? false,
filterMark ? null,
qnum ? null,
modeFilter ? null,
desyncMark ? null,
desyncMarkPostnat ? null,
nftTable ? null,
customScript ? null,
}:
pkgs.runCommand packageName
{
nativeBuildInputs = with pkgs; [
coreutils
@@ -100,25 +129,32 @@ let
set -euo pipefail
mkdir -p "$out"
cp -a ${upstreamZapretPackage}/. "$out/"
cp -a ${baseZapretPackage}/. "$out/"
chmod -R u+w "$out/opt/zapret" "$out/bin"
find "$out/opt/zapret/configs" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
find "$out/opt/zapret/hostlists" -type f -exec ${pkgs.gnused}/bin/sed -i \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
{} \;
if [ -f "$out/opt/zapret/configs/${z.configName}" ]; then
cp "$out/opt/zapret/configs/${z.configName}" "$out/opt/zapret/config"
if [ -f "$out/opt/zapret/configs/${configName}" ]; then
cp "$out/opt/zapret/configs/${configName}" "$out/opt/zapret/config"
else
echo "proxy-suite: zapret config '${z.configName}' not found in upstream package" >&2
echo "proxy-suite: zapret config '${configName}' not found in curated package" >&2
ls -la "$out/opt/zapret/configs" >&2 || true
exit 1
fi
${pkgs.gnused}/bin/sed -i \
-e 's|${upstreamZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
-e 's|${baseZapretPackage}/opt/zapret|'"$out"'/opt/zapret|g' \
"$out/opt/zapret/config"
${pkgs.gnused}/bin/sed -i \
-e 's|^PIDDIR=.*$|PIDDIR=${pidDir}|' \
"$out/opt/zapret/init.d/sysv/functions"
append_list_file() {
local target="$1"
local extra_file="$2"
@@ -129,6 +165,16 @@ let
mv "$tmp" "$out/opt/zapret/hostlists/$target"
}
set_config_var() {
local key="$1"
local value="$2"
if grep -Eq "^[#[:space:]]*$key=" "$out/opt/zapret/config"; then
${pkgs.gnused}/bin/sed -Ei "s|^[#[:space:]]*$key=.*$|$key=$value|" "$out/opt/zapret/config"
else
printf '\n%s=%s\n' "$key" "$value" >> "$out/opt/zapret/config"
fi
}
${lib.optionalString (listGeneralFile != null) ''
append_list_file list-general-user.txt ${listGeneralFile}
''}
@@ -146,8 +192,8 @@ let
''}
rm -f "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (z.gameFilter != "null") ''
echo "${z.gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
${lib.optionalString (gameFilter != "null") ''
echo "${gameFilter}" > "$out/opt/zapret/hostlists/.game_filter.enabled"
''}
${lib.concatMapStrings (
@@ -163,8 +209,92 @@ let
) z.hostlistRules}
${patchConfigScript} --config "$out/opt/zapret/config" --spec ${hostlistRuleSpec}
${lib.optionalString forceDisableFilterMark ''
set_config_var FILTER_MARK ""
''}
${lib.optionalString (filterMark != null) ''
filter_mark_hex=$(printf '0x%x' ${toString filterMark})
set_config_var FILTER_MARK "$filter_mark_hex"
''}
${lib.optionalString (qnum != null) ''
set_config_var QNUM ${toString qnum}
''}
${lib.optionalString (modeFilter != null) ''
set_config_var MODE_FILTER ${modeFilter}
''}
${lib.optionalString (desyncMark != null) ''
desync_mark_hex=$(printf '0x%x' ${toString desyncMark})
set_config_var DESYNC_MARK "$desync_mark_hex"
''}
${lib.optionalString (desyncMarkPostnat != null) ''
desync_mark_postnat_hex=$(printf '0x%x' ${toString desyncMarkPostnat})
set_config_var DESYNC_MARK_POSTNAT "$desync_mark_postnat_hex"
''}
${lib.optionalString (nftTable != null) ''
set_config_var ZAPRET_NFT_TABLE ${nftTable}
''}
${lib.optionalString (customScript != null) ''
mkdir -p "$out/opt/zapret/init.d/sysv/custom.d"
cp ${customScript} "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
chmod +x "$out/opt/zapret/init.d/sysv/custom.d/50-proxy-suite-custom.sh"
''}
'';
globalZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-zapret";
gameFilter = z.gameFilter;
forceDisableFilterMark = true;
customScript = if arz.enable then mkGlobalBypassScript (toString arz.filterMark) else null;
};
appZapretPackage = mkDerivedZapretPackage {
packageName = "proxy-suite-app-zapret-${selectedConfigName}";
pidDir = "/run/proxy-suite-app-zapret";
gameFilter = "all";
filterMark = arz.filterMark;
qnum = arz.qnum;
modeFilter = "none";
desyncMark = 134217728;
desyncMarkPostnat = 67108864;
nftTable = "proxy_suite_app_zapret";
};
zapretCommonPreStart = package: ''
${package}/opt/zapret/init.d/sysv/zapret stop || true
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
${pkgs.ipset}/bin/ipset create nozapret hash:net
fi
'';
globalZapretEnv = [
"ZAPRET_BASE=${globalZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
appZapretEnv = [
"ZAPRET_BASE=${appZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
appZapretMarkUpScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-up" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
${nft} -f ${appZapretRulesFile}
'';
appZapretMarkDownScript = pkgs.writeShellScript "proxy-suite-app-zapret-mark-down" ''
set -euo pipefail
${nft} delete table inet proxy_suite_app_zapret_mark 2>/dev/null || true
'';
exemptStart = lib.concatMapStrings (cidr: ''
${iptables} -t mangle -I FORWARD 1 -d ${cidr} -j RETURN
${iptables} -t mangle -I POSTROUTING 1 -s ${cidr} -j RETURN
@@ -191,39 +321,44 @@ in
}
];
services.zapret-discord-youtube = {
enable = true;
configName = z.configName;
gameFilter = z.gameFilter;
listGeneral = z.listGeneral;
listExclude = z.listExclude;
ipsetAll = z.ipsetAll;
ipsetExclude = z.ipsetExclude;
};
environment.systemPackages = lib.mkBefore [ customZapretPackage ];
environment.systemPackages =
lib.mkBefore (
[ globalZapretPackage ] ++ lib.optionals arz.enable [ appZapretPackage ]
);
systemd.services.zapret-discord-youtube = {
preStart = lib.mkForce ''
${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop || true
${lib.getExe' pkgs.kmod "modprobe"} xt_NFQUEUE 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_connbytes 2>/dev/null || true
${lib.getExe' pkgs.kmod "modprobe"} xt_multiport 2>/dev/null || true
if ! ${pkgs.ipset}/bin/ipset list nozapret >/dev/null 2>&1; then
${pkgs.ipset}/bin/ipset create nozapret hash:net
fi
'';
description = "zapret DPI bypass";
after = [ "network.target" ];
wantedBy = [ "multi-user.target" ];
preStart = zapretCommonPreStart globalZapretPackage;
serviceConfig = {
ExecStart = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecReload = lib.mkForce "${customZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = lib.mkForce [
"ZAPRET_BASE=${customZapretPackage}/opt/zapret"
"PATH=${lib.makeBinPath runtimeDeps}"
];
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "proxy-suite-zapret";
ExecStart = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecReload = "${globalZapretPackage}/opt/zapret/init.d/sysv/zapret restart";
Environment = globalZapretEnv;
};
};
systemd.services.proxy-suite-app-zapret = lib.mkIf arz.enable {
description = "proxy-suite app-routing zapret backend";
after = [ "network.target" ];
conflicts = [
"proxy-suite-tproxy.service"
"proxy-suite-tun.service"
];
preStart = zapretCommonPreStart appZapretPackage;
serviceConfig = {
Type = "oneshot";
RemainAfterExit = true;
RuntimeDirectory = "proxy-suite-app-zapret";
ExecStartPre = "${appZapretMarkUpScript}";
ExecStart = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret start";
ExecStop = "${appZapretPackage}/opt/zapret/init.d/sysv/zapret stop";
ExecStopPost = "${appZapretMarkDownScript}";
Environment = appZapretEnv;
};
};
+1012 -3
View File
File diff suppressed because it is too large. Load diff
+234
View File
@@ -0,0 +1,234 @@
{
nixpkgs,
pkgsFor,
proxySuiteModule,
}:
system:
let
pkgs = pkgsFor system;
lib = pkgs.lib;
eval = import "${nixpkgs}/nixos/lib/eval-config.nix" {
inherit system;
modules = [
proxySuiteModule
{
system.stateVersion = lib.trivial.release;
}
];
};
filterGeneratedOptions = lib.filterAttrs (name: _: name != "_module");
mkGeneratedExampleValue =
option:
if (option ? _type) && option._type == "option" then
if option ? example then
option.example
else if (option ? type) && ((option.type.name or null) == "submodule") then
lib.mapAttrs (_: mkGeneratedExampleValue) (filterGeneratedOptions (option.type.getSubOptions [ ]))
else if option ? default then
option.default
else
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)
);
repoRoot = toString ../.;
repoUrl = "https://github.com/FUFSoB/proxy-suite-flake/blob/main";
transformDeclaration =
decl:
let
declStr = toString decl;
subpath = lib.removePrefix "/" (lib.removePrefix repoRoot declStr);
in
if lib.hasPrefix repoRoot declStr then
{
url = "${repoUrl}/${subpath}";
name = subpath;
}
else
decl;
optionDocs = pkgs.nixosOptionsDoc {
options = {
services = {
"proxy-suite" = eval.options.services.proxy-suite;
};
};
documentType = "none";
variablelistId = "proxy-suite-options";
optionIdPrefix = "proxy-suite-opt-";
transformOptions = opt: opt // { declarations = map transformDeclaration opt.declarations; };
};
in
pkgs.runCommand "proxy-suite-options.md" { } ''
preamble="$TMPDIR/preamble.md"
sections="$TMPDIR/sections.md"
sections_with_anchors="$TMPDIR/sections-with-anchors.md"
section_index="$TMPDIR/sections-index.tsv"
toc="$TMPDIR/toc.md"
cat >"$preamble" <<'EOF'
# proxy-suite options
This file is generated from the `services.proxy-suite` option descriptions in [`modules/proxy-suite/options.nix`](modules/proxy-suite/options.nix).
Update module option docs there instead of editing this file by hand.
## Table of contents
EOF
cat >"$sections" <<'EOF'
## Complete default config
```nix
services.proxy-suite = ${defaultConfigText};
```
## Complete example config
This is generated by filling in all the options with example values (or defaults if no example is provided). This is not meant to be a recommended config, just a comprehensive example of how to set all the options.
```nix
services.proxy-suite = ${exampleConfigText};
```
EOF
cat ${optionDocs.optionsCommonMark} >>"$sections"
: >"$section_index"
: >"$sections_with_anchors"
awk -v section_index="$section_index" -v out="$sections_with_anchors" '
function slugify(text, slug) {
slug = text
gsub(/\\/, "", slug)
slug = tolower(slug)
gsub(/[^a-z0-9]+/, "-", slug)
sub(/^-+/, "", slug)
sub(/-+$/, "", slug)
return slug
}
/^## / {
title = substr($0, 4)
base = slugify(title)
count = seen[base]
seen[base]++
slug = count == 0 ? base : base "-" count
print title "\t" slug >> section_index
print "<a id=\"" slug "\"></a>" >> out
}
{
print >> out
}
' "$sections"
: >"$toc"
awk -F '\t' -v toc="$toc" '
function addChild(parent, child, key) {
key = parent SUBSEP child
if (!(key in seenChild)) {
seenChild[key] = 1
childCount[parent]++
childOrder[parent, childCount[parent]] = child
}
}
function indent(depth, i, prefix) {
prefix = ""
for (i = 0; i < depth; i++) {
prefix = prefix " "
}
return prefix
}
function displayLabel(label) {
if (label == "*") {
return "item"
}
return label
}
function printNode(path, label, depth, i, child, childPath, text) {
text = displayLabel(label)
if (path in slugByPath) {
text = "[" text "](#" slugByPath[path] ")"
}
print indent(depth) "- " text >> toc
for (i = 1; i <= childCount[path]; i++) {
child = childOrder[path, i]
childPath = path "." child
printNode(childPath, child, depth + 1)
}
}
{
title = $1
slug = $2
normalized = title
gsub(/\\/, "", normalized)
if (normalized ~ /^Complete /) {
sampleCount++
sampleTitle[sampleCount] = title
sampleSlug[sampleCount] = slug
next
}
if (index(normalized, "services.proxy-suite") == 1) {
optionRootSeen = 1
slugByPath[normalized] = slug
count = split(normalized, parts, /\./)
if (count < 3) {
next
}
parent = "services.proxy-suite"
for (i = 3; i <= count; i++) {
child = parts[i]
addChild(parent, child)
parent = parent "." child
}
next
}
otherCount++
otherTitle[otherCount] = title
otherSlug[otherCount] = slug
}
END {
if (sampleCount > 0) {
print "- Config samples" >> toc
for (i = 1; i <= sampleCount; i++) {
print " - [" sampleTitle[i] "](#" sampleSlug[i] ")" >> toc
}
}
if (optionRootSeen) {
print "- services.proxy-suite" >> toc
for (i = 1; i <= childCount["services.proxy-suite"]; i++) {
child = childOrder["services.proxy-suite", i]
printNode("services.proxy-suite." child, child, 1)
}
}
for (i = 1; i <= otherCount; i++) {
print "- [" otherTitle[i] "](#" otherSlug[i] ")" >> toc
}
}
' "$section_index"
cat "$preamble" >"$out"
cat "$toc" >>"$out"
printf '\n' >>"$out"
cat "$sections_with_anchors" >>"$out"
''
+18
View File
@@ -27,6 +27,24 @@ pkgs.stdenv.mkDerivation {
installPhase = ''
mkdir -p $out/bin
cp proxy-suite-tray $out/bin/
# Install custom icons in hicolor theme
if [ -d icons ]; then
mkdir -p $out/share/icons/hicolor/scalable/apps
mkdir -p $out/share/icons/hicolor/symbolic/apps
cp icons/proxy-suite-disabled.svg \
icons/proxy-suite-zapret.svg \
icons/proxy-suite-proxy.svg \
icons/proxy-suite-active.svg \
icons/proxy-suite-tunnel.svg \
$out/share/icons/hicolor/scalable/apps/
cp icons/proxy-suite-disabled-symbolic.svg \
icons/proxy-suite-zapret-symbolic.svg \
icons/proxy-suite-proxy-symbolic.svg \
icons/proxy-suite-active-symbolic.svg \
icons/proxy-suite-tunnel-symbolic.svg \
$out/share/icons/hicolor/symbolic/apps/
fi
'';
meta = {
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<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="currentColor"/>
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
stroke="white" stroke-width="1.4" fill="none"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 354 B

@@ -0,0 +1,8 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Green shield: proxy + zapret both enabled -->
<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="#4CAF50" stroke="#2E7D32" stroke-width="0.8"/>
<path d="M 9 13 L 11.5 15.5 L 15.5 9.5"
stroke="#FFFFFF" stroke-width="1.4" fill="none"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 440 B

@@ -0,0 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<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="currentColor"/>
<line x1="9" y1="9.5" x2="15" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
<line x1="15" y1="9.5" x2="9" y2="15.5" stroke="white" stroke-width="1.4" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 403 B

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Red shield: everything disabled -->
<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="#F44336" stroke="#B71C1C" stroke-width="0.8"/>
<line x1="9" y1="9.5" x2="15" y2="15.5"
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
<line x1="15" y1="9.5" x2="9" y2="15.5"
stroke="#FFFFFF" stroke-width="1.4" stroke-linecap="round"/>
</svg>

After

Width:  |  Height:  |  Size: 497 B

@@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<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="currentColor"/>
<circle cx="12" cy="12.5" r="2.5" fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 252 B

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Orange shield: only proxy (SOCKS) enabled -->
<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="#FF9800" stroke="#E65100" stroke-width="0.8"/>
<!-- Dot in center -->
<circle cx="12" cy="12.5" r="2.5" fill="#FFFFFF"/>
</svg>

After

Width:  |  Height:  |  Size: 363 B

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<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="currentColor"/>
<path d="M 12 15.5 L 12 9.5 M 9.5 12 L 12 9.5 L 14.5 12"
stroke="white" stroke-width="1.4" fill="none"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 371 B

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Gold 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"/>
<!-- 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"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 497 B

@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<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="currentColor"/>
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
stroke="white" stroke-width="1.4" fill="none"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 352 B

@@ -0,0 +1,9 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
<!-- Blue shield: only zapret enabled -->
<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="#2196F3" stroke="#0D47A1" stroke-width="0.8"/>
<!-- Z letter for Zapret -->
<path d="M 9 9 L 15 9 L 9 15 L 15 15"
stroke="#FFFFFF" stroke-width="1.4" fill="none"
stroke-linecap="round" stroke-linejoin="round"/>
</svg>

After

Width:  |  Height:  |  Size: 460 B

+378 -126
View File
@@ -8,25 +8,45 @@
#ifndef POLL_INTERVAL
#define POLL_INTERVAL 5
#endif
#ifndef SYSTEMCTL_BIN
#define SYSTEMCTL_BIN "/run/current-system/sw/bin/systemctl"
#endif
#ifndef PKEXEC_BIN
#define PKEXEC_BIN "/run/current-system/sw/bin/pkexec"
#ifndef PROXY_CTL_BIN
#define PROXY_CTL_BIN "/run/current-system/sw/bin/proxy-ctl"
#endif
static AppIndicator *indicator;
static GtkWidget *menu;
static GtkWidget *status_item;
static GtkWidget *traffic_status_item;
static GtkWidget *zapret_status_item;
static GtkWidget *proxy_item;
static GtkWidget *tproxy_item;
static GtkWidget *tun_item;
static GtkWidget *zapret_item;
static GtkWidget *open_controls_item;
static GtkWidget *controls_window;
static GtkWidget *controls_status_label;
static GtkWidget *controls_summary_label;
static GtkWidget *controls_core_status_label;
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;
typedef struct {
gboolean loaded;
gboolean socks_available;
gboolean tproxy_available;
gboolean tun_available;
gboolean zapret_available;
gboolean subscription_update_available;
gboolean socks;
gboolean tproxy;
gboolean tun;
gboolean zapret;
} ServiceState;
static ServiceState initial_state;
static gboolean command_succeeds(gchar **argv) {
GError *error = NULL;
@@ -113,58 +133,29 @@ static GDBusMessage *on_session_bus_message(
return message;
}
static gboolean service_exists(const char *name) {
gchar *load_state = NULL;
gboolean exists = FALSE;
static gboolean run_proxy_ctl1(const char *arg1) {
gchar *argv[] = {
(gchar *) SYSTEMCTL_BIN,
(gchar *) "show",
(gchar *) "--value",
(gchar *) "--property=LoadState",
NULL,
(gchar *) PROXY_CTL_BIN,
(gchar *) arg1,
NULL
};
argv[4] = g_strdup_printf("%s.service", name);
if (command_stdout(argv, &load_state)) {
g_strstrip(load_state);
exists = load_state[0] != '\0' && strcmp(load_state, "not-found") != 0;
}
g_free(argv[4]);
g_free(load_state);
return exists;
return command_succeeds(argv);
}
static gboolean service_active(const char *name) {
static gboolean run_proxy_ctl2(const char *arg1, const char *arg2) {
gchar *argv[] = {
(gchar *) SYSTEMCTL_BIN,
(gchar *) "is-active",
(gchar *) "--quiet",
NULL,
(gchar *) PROXY_CTL_BIN,
(gchar *) arg1,
(gchar *) arg2,
NULL
};
argv[3] = g_strdup_printf("%s.service", name);
gboolean active = command_succeeds(argv);
g_free(argv[3]);
return active;
return command_succeeds(argv);
}
static gboolean run_privileged(const char *action, const char *service) {
char cmd[512];
snprintf(
cmd,
sizeof(cmd),
"%s %s %s %s.service",
PKEXEC_BIN,
SYSTEMCTL_BIN,
action,
service
);
return system(cmd) == 0;
static gboolean parse_proxy_ctl_bool(const char *value) {
return value && strcmp(value, "true") == 0;
}
static const char *pick_icon_name(
@@ -186,136 +177,336 @@ static const char *pick_icon_name(
return fallback;
}
static void update_status(void) {
gboolean socks = service_active("proxy-suite-socks");
gboolean tproxy = service_active("proxy-suite-tproxy");
gboolean tun = service_active("proxy-suite-tun");
static ServiceState get_service_state(void) {
ServiceState state = { 0 };
gchar *stdout_text = NULL;
gchar *argv[] = {
(gchar *) PROXY_CTL_BIN,
(gchar *) "status",
(gchar *) "--tray",
NULL
};
if (!command_stdout(argv, &stdout_text)) {
return state;
}
state.loaded = TRUE;
gchar **lines = g_strsplit(stdout_text, "\n", -1);
for (gchar **line = lines; line && *line; ++line) {
if ((*line)[0] == '\0') {
continue;
}
gchar **parts = g_strsplit(*line, "=", 2);
if (!parts[0] || !parts[1]) {
g_strfreev(parts);
continue;
}
if (strcmp(parts[0], "socks_available") == 0) {
state.socks_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "socks_active") == 0) {
state.socks = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tproxy_available") == 0) {
state.tproxy_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tproxy_active") == 0) {
state.tproxy = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tun_available") == 0) {
state.tun_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "tun_active") == 0) {
state.tun = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "zapret_available") == 0) {
state.zapret_available = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "zapret_active") == 0) {
state.zapret = parse_proxy_ctl_bool(parts[1]);
} else if (strcmp(parts[0], "subscription_update_available") == 0) {
state.subscription_update_available = parse_proxy_ctl_bool(parts[1]);
}
g_strfreev(parts);
}
g_strfreev(lines);
g_free(stdout_text);
return state;
}
static const char *traffic_mode_label(const ServiceState *state) {
if (state->tun) {
return "TUN tunnel enabled";
}
if (state->tproxy) {
return "TProxy interception enabled";
}
return "System-wide routing disabled";
}
static const char *indicator_label_text(const ServiceState *state) {
if (state->socks && (state->tproxy || state->tun) && state->zapret) {
return "Proxy + traffic + zapret";
}
if (state->socks && (state->tproxy || state->tun)) {
return "Proxy + traffic";
}
if (state->socks && state->zapret) {
return "Proxy + zapret";
}
if (state->socks) {
return "Proxy only";
}
if (state->zapret) {
return "Zapret only";
}
return "Inactive";
}
static void update_status(void) {
ServiceState state = get_service_state();
/* Gold: TUN/TProxy active (highest priority) */
static const char *const tunnel_icons[] = {
"proxy-suite-tunnel",
"proxy-suite-tunnel-symbolic",
"network-vpn",
"network-vpn-symbolic"
};
/* Green: proxy + zapret, no tunnel */
static const char *const active_icons[] = {
"proxy-suite-active",
"proxy-suite-active-symbolic",
"network-vpn",
"network-vpn-symbolic"
};
static const char *const partial_icons[] = {
/* Orange: proxy only */
static const char *const proxy_icons[] = {
"proxy-suite-proxy",
"proxy-suite-proxy-symbolic",
"network-vpn-acquiring",
"network-vpn",
"network-vpn-acquiring-symbolic",
"network-vpn",
"network-vpn-symbolic"
};
static const char *const disconnected_icons[] = {
/* Blue: zapret only */
static const char *const zapret_icons[] = {
"proxy-suite-zapret",
"proxy-suite-zapret-symbolic",
"network-vpn-acquiring",
"network-vpn-acquiring-symbolic",
"network-vpn",
"network-vpn-symbolic"
};
/* Red: everything disabled */
static const char *const disabled_icons[] = {
"proxy-suite-disabled",
"proxy-suite-disabled-symbolic",
"network-vpn-disconnected",
"network-offline",
"network-error",
"process-stop",
"dialog-error",
"network-vpn-disconnected-symbolic",
"network-offline-symbolic",
"network-error-symbolic",
"process-stop-symbolic",
"dialog-error-symbolic"
};
if (socks) {
if (tproxy || tun) {
app_indicator_set_icon(
indicator,
pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn")
);
} else {
app_indicator_set_icon(
indicator,
pick_icon_name(partial_icons, G_N_ELEMENTS(partial_icons), "network-vpn-acquiring")
);
if (!state.loaded) {
app_indicator_set_icon(
indicator,
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected")
);
app_indicator_set_label(indicator, "Status unavailable", "");
if (status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), "[Status] proxy-ctl status unavailable");
}
if (traffic_status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(traffic_status_item), "[Traffic] Mode: Unknown");
}
if (zapret_status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(zapret_status_item), "[Zapret] zapret-discord-youtube: Unknown");
}
if (controls_summary_label) {
gtk_label_set_text(GTK_LABEL(controls_summary_label), "[Status] proxy-ctl status unavailable");
}
if (controls_core_status_label) {
gtk_label_set_text(GTK_LABEL(controls_core_status_label), "[Core] SOCKS proxy: Unknown");
}
if (controls_traffic_status_label) {
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), "[Traffic] Mode: Unknown");
}
if (controls_zapret_status_label) {
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), "[Zapret] zapret-discord-youtube: Unknown");
}
return;
}
const char *traffic = traffic_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",
state.socks ? "Proxy ready" : "Proxy down",
traffic,
zapret
);
gchar *core_text = g_strdup_printf(
"[Core] SOCKS proxy: %s",
state.socks ? "Running" : "Stopped"
);
gchar *traffic_text = g_strdup_printf("[Traffic] Mode: %s", traffic);
gchar *zapret_text = g_strdup_printf(
"[Zapret] zapret-discord-youtube: %s",
zapret
);
if (state.tproxy || state.tun) {
app_indicator_set_icon(
indicator,
pick_icon_name(tunnel_icons, G_N_ELEMENTS(tunnel_icons), "network-vpn")
);
} else if (state.socks && state.zapret) {
app_indicator_set_icon(
indicator,
pick_icon_name(active_icons, G_N_ELEMENTS(active_icons), "network-vpn")
);
} else if (state.socks) {
app_indicator_set_icon(
indicator,
pick_icon_name(proxy_icons, G_N_ELEMENTS(proxy_icons), "network-vpn-acquiring")
);
} else if (state.zapret) {
app_indicator_set_icon(
indicator,
pick_icon_name(zapret_icons, G_N_ELEMENTS(zapret_icons), "network-vpn-acquiring")
);
} else {
app_indicator_set_icon(
indicator,
pick_icon_name(disconnected_icons, G_N_ELEMENTS(disconnected_icons), "network-vpn-disconnected")
pick_icon_name(disabled_icons, G_N_ELEMENTS(disabled_icons), "network-vpn-disconnected")
);
}
app_indicator_set_label(indicator, summary, "");
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item),
socks ? "SOCKS Proxy: Running" : "SOCKS Proxy: Stopped");
if (controls_status_label) {
gtk_label_set_text(GTK_LABEL(controls_status_label),
socks ? "SOCKS Proxy: Running" : "SOCKS Proxy: Stopped");
if (status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(status_item), summary_text);
}
if (traffic_status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(traffic_status_item), traffic_text);
}
if (zapret_status_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(zapret_status_item), zapret_text);
}
if (controls_summary_label) {
gtk_label_set_text(GTK_LABEL(controls_summary_label), summary_text);
}
if (controls_core_status_label) {
gtk_label_set_text(GTK_LABEL(controls_core_status_label), core_text);
}
if (controls_traffic_status_label) {
gtk_label_set_text(GTK_LABEL(controls_traffic_status_label), traffic_text);
}
if (controls_zapret_status_label) {
gtk_label_set_text(GTK_LABEL(controls_zapret_status_label), zapret_text);
}
if (proxy_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(proxy_item),
socks ? "Disable Proxy" : "Enable Proxy");
state.socks ? "[Core] Stop SOCKS Proxy" : "[Core] Start SOCKS Proxy");
}
if (controls_proxy_button) {
gtk_button_set_label(GTK_BUTTON(controls_proxy_button),
socks ? "Disable Proxy" : "Enable Proxy");
state.socks ? "Stop SOCKS Proxy" : "Start SOCKS Proxy");
}
if (tproxy_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(tproxy_item),
tproxy ? "Disable TProxy" : "Enable TProxy");
state.tproxy ? "[Traffic] Stop TProxy Mode" : "[Traffic] Start TProxy Mode");
}
if (controls_tproxy_button) {
gtk_button_set_label(GTK_BUTTON(controls_tproxy_button),
tproxy ? "Disable TProxy" : "Enable TProxy");
state.tproxy ? "Stop TProxy Mode" : "Start TProxy Mode");
}
if (tun_item) {
gtk_menu_item_set_label(GTK_MENU_ITEM(tun_item),
tun ? "Disable TUN" : "Enable TUN");
state.tun ? "[Traffic] Stop TUN Mode" : "[Traffic] Start TUN Mode");
}
if (controls_tun_button) {
gtk_button_set_label(GTK_BUTTON(controls_tun_button),
tun ? "Disable TUN" : "Enable TUN");
state.tun ? "Stop TUN Mode" : "Start TUN Mode");
}
if (zapret_item) {
gtk_menu_item_set_label(
GTK_MENU_ITEM(zapret_item),
state.zapret ? "[Zapret] Stop zapret-discord-youtube" : "[Zapret] Start zapret-discord-youtube"
);
}
if (controls_zapret_button) {
gtk_button_set_label(
GTK_BUTTON(controls_zapret_button),
state.zapret ? "Stop zapret-discord-youtube" : "Start zapret-discord-youtube"
);
}
g_free(summary_text);
g_free(core_text);
g_free(traffic_text);
g_free(zapret_text);
}
static void on_proxy_toggle(GtkWidget *item, gpointer data) {
(void)item; (void)data;
if (service_active("proxy-suite-socks")) {
if (service_active("proxy-suite-tproxy")) {
run_privileged("stop", "proxy-suite-tproxy");
}
if (service_active("proxy-suite-tun")) {
run_privileged("stop", "proxy-suite-tun");
}
run_privileged("stop", "proxy-suite-socks");
ServiceState state = get_service_state();
if (state.socks) {
run_proxy_ctl2("proxy", "off");
} else {
run_privileged("start", "proxy-suite-socks");
run_proxy_ctl2("proxy", "on");
}
update_status();
}
static void on_tproxy_toggle(GtkWidget *item, gpointer data) {
(void)item; (void)data;
if (service_active("proxy-suite-tproxy")) {
run_privileged("stop", "proxy-suite-tproxy");
ServiceState state = get_service_state();
if (state.tproxy) {
run_proxy_ctl2("tproxy", "off");
} else {
run_privileged("start", "proxy-suite-tproxy");
run_proxy_ctl2("tproxy", "on");
}
update_status();
}
static void on_tun_toggle(GtkWidget *item, gpointer data) {
(void)item; (void)data;
if (service_active("proxy-suite-tun")) {
run_privileged("stop", "proxy-suite-tun");
ServiceState state = get_service_state();
if (state.tun) {
run_proxy_ctl2("tun", "off");
} else {
run_privileged("start", "proxy-suite-tun");
run_proxy_ctl2("tun", "on");
}
update_status();
}
static void on_zapret_toggle(GtkWidget *item, gpointer data) {
(void)item; (void)data;
ServiceState state = get_service_state();
if (state.zapret) {
run_proxy_ctl2("zapret", "off");
} else {
run_proxy_ctl2("zapret", "on");
}
update_status();
}
static void on_restart(GtkWidget *item, gpointer data) {
(void)item; (void)data;
gboolean tun_was_active = service_active("proxy-suite-tun");
if (run_privileged("restart", "proxy-suite-socks") && tun_was_active) {
run_privileged("restart", "proxy-suite-tun");
}
run_proxy_ctl1("restart");
update_status();
}
static void on_subscription_update(GtkWidget *item, gpointer data) {
(void)item; (void)data;
run_privileged("start", "proxy-suite-subscription-update");
run_proxy_ctl2("subscription", "update");
}
static void on_open_controls(GtkWidget *item, gpointer data) {
@@ -349,43 +540,85 @@ static void build_controls_window(void) {
GtkWidget *box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
gtk_container_add(GTK_CONTAINER(controls_window), box);
controls_status_label = gtk_label_new("SOCKS Proxy: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(box), controls_status_label, FALSE, FALSE, 0);
controls_summary_label = gtk_label_new("[Status] Loading service state...");
gtk_label_set_xalign(GTK_LABEL(controls_summary_label), 0.0f);
gtk_box_pack_start(GTK_BOX(box), controls_summary_label, FALSE, FALSE, 0);
controls_proxy_button = gtk_button_new_with_label("Enable Proxy");
GtkWidget *core_frame = gtk_frame_new("[Core] Proxy");
GtkWidget *core_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width(GTK_CONTAINER(core_box), 6);
gtk_container_add(GTK_CONTAINER(core_frame), core_box);
gtk_box_pack_start(GTK_BOX(box), core_frame, FALSE, FALSE, 0);
controls_core_status_label = gtk_label_new("[Core] SOCKS proxy: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_core_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(core_box), controls_core_status_label, FALSE, FALSE, 0);
controls_proxy_button = gtk_button_new_with_label("Start SOCKS Proxy");
g_signal_connect(controls_proxy_button, "clicked", G_CALLBACK(on_proxy_toggle), NULL);
gtk_box_pack_start(GTK_BOX(box), controls_proxy_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(core_box), controls_proxy_button, FALSE, FALSE, 0);
if (service_exists("proxy-suite-tproxy")) {
controls_tproxy_button = gtk_button_new_with_label("Enable TProxy");
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);
gtk_container_add(GTK_CONTAINER(traffic_frame), traffic_box);
gtk_box_pack_start(GTK_BOX(box), traffic_frame, FALSE, FALSE, 0);
controls_traffic_status_label = gtk_label_new("[Traffic] Mode: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_traffic_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_traffic_status_label, FALSE, FALSE, 0);
if (initial_state.tproxy_available) {
controls_tproxy_button = gtk_button_new_with_label("Start TProxy Mode");
g_signal_connect(controls_tproxy_button, "clicked", G_CALLBACK(on_tproxy_toggle), NULL);
gtk_box_pack_start(GTK_BOX(box), controls_tproxy_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tproxy_button, FALSE, FALSE, 0);
}
if (service_exists("proxy-suite-tun")) {
controls_tun_button = gtk_button_new_with_label("Enable TUN");
if (initial_state.tun_available) {
controls_tun_button = gtk_button_new_with_label("Start TUN Mode");
g_signal_connect(controls_tun_button, "clicked", G_CALLBACK(on_tun_toggle), NULL);
gtk_box_pack_start(GTK_BOX(box), controls_tun_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(traffic_box), controls_tun_button, FALSE, FALSE, 0);
}
if (service_exists("proxy-suite-subscription-update")) {
if (initial_state.zapret_available) {
GtkWidget *zapret_frame = gtk_frame_new("[Zapret] DPI bypass");
GtkWidget *zapret_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width(GTK_CONTAINER(zapret_box), 6);
gtk_container_add(GTK_CONTAINER(zapret_frame), zapret_box);
gtk_box_pack_start(GTK_BOX(box), zapret_frame, FALSE, FALSE, 0);
controls_zapret_status_label = gtk_label_new("[Zapret] zapret-discord-youtube: Unknown");
gtk_label_set_xalign(GTK_LABEL(controls_zapret_status_label), 0.0f);
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_status_label, FALSE, FALSE, 0);
controls_zapret_button = gtk_button_new_with_label("Start zapret-discord-youtube");
g_signal_connect(controls_zapret_button, "clicked", G_CALLBACK(on_zapret_toggle), NULL);
gtk_box_pack_start(GTK_BOX(zapret_box), controls_zapret_button, FALSE, FALSE, 0);
}
GtkWidget *tools_frame = gtk_frame_new("[Tools] Maintenance");
GtkWidget *tools_box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
gtk_container_set_border_width(GTK_CONTAINER(tools_box), 6);
gtk_container_add(GTK_CONTAINER(tools_frame), tools_box);
gtk_box_pack_start(GTK_BOX(box), tools_frame, FALSE, FALSE, 0);
if (initial_state.subscription_update_available) {
GtkWidget *sub_update_button = gtk_button_new_with_label("Update Subscriptions");
g_signal_connect(sub_update_button, "clicked", G_CALLBACK(on_subscription_update), NULL);
gtk_box_pack_start(GTK_BOX(box), sub_update_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tools_box), sub_update_button, FALSE, FALSE, 0);
}
GtkWidget *restart_button = gtk_button_new_with_label("Restart Services");
GtkWidget *restart_button = gtk_button_new_with_label("Restart Active Services");
g_signal_connect(restart_button, "clicked", G_CALLBACK(on_restart), NULL);
gtk_box_pack_start(GTK_BOX(box), restart_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tools_box), restart_button, FALSE, FALSE, 0);
GtkWidget *close_button = gtk_button_new_with_label("Close Window");
g_signal_connect(close_button, "clicked", G_CALLBACK(on_close_controls), NULL);
gtk_box_pack_start(GTK_BOX(box), close_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tools_box), close_button, FALSE, FALSE, 0);
GtkWidget *quit_button = gtk_button_new_with_label("Exit Tray");
g_signal_connect(quit_button, "clicked", G_CALLBACK(on_quit), NULL);
gtk_box_pack_start(GTK_BOX(box), quit_button, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(tools_box), quit_button, FALSE, FALSE, 0);
gtk_widget_show_all(controls_window);
gtk_widget_hide(controls_window);
@@ -394,13 +627,21 @@ static void build_controls_window(void) {
static void build_menu(void) {
menu = gtk_menu_new();
status_item = gtk_menu_item_new_with_label("SOCKS Proxy: Unknown");
status_item = gtk_menu_item_new_with_label("[Status] Loading service state...");
gtk_widget_set_sensitive(status_item, FALSE);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), status_item);
traffic_status_item = gtk_menu_item_new_with_label("[Traffic] Mode: Unknown");
gtk_widget_set_sensitive(traffic_status_item, FALSE);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), traffic_status_item);
zapret_status_item = gtk_menu_item_new_with_label("[Zapret] zapret-discord-youtube: Unknown");
gtk_widget_set_sensitive(zapret_status_item, FALSE);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_status_item);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
proxy_item = gtk_menu_item_new_with_label("Enable Proxy");
proxy_item = gtk_menu_item_new_with_label("[Core] Start SOCKS Proxy");
g_signal_connect(proxy_item, "activate", G_CALLBACK(on_proxy_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), proxy_item);
@@ -410,19 +651,29 @@ static void build_menu(void) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
if (service_exists("proxy-suite-tproxy")) {
tproxy_item = gtk_menu_item_new_with_label("Enable TProxy");
if (initial_state.tproxy_available) {
tproxy_item = gtk_menu_item_new_with_label("[Traffic] Start TProxy Mode");
g_signal_connect(tproxy_item, "activate", G_CALLBACK(on_tproxy_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tproxy_item);
}
if (service_exists("proxy-suite-tun")) {
tun_item = gtk_menu_item_new_with_label("Enable TUN");
if (initial_state.tun_available) {
tun_item = gtk_menu_item_new_with_label("[Traffic] Start TUN Mode");
g_signal_connect(tun_item, "activate", G_CALLBACK(on_tun_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), tun_item);
}
if (service_exists("proxy-suite-subscription-update")) {
if (initial_state.zapret_available) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
zapret_item = gtk_menu_item_new_with_label("[Zapret] Start zapret-discord-youtube");
g_signal_connect(zapret_item, "activate", G_CALLBACK(on_zapret_toggle), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), zapret_item);
}
if (initial_state.subscription_update_available) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
GtkWidget *sub_update_item = gtk_menu_item_new_with_label("Update Subscriptions");
g_signal_connect(sub_update_item, "activate", G_CALLBACK(on_subscription_update), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), sub_update_item);
@@ -430,7 +681,7 @@ static void build_menu(void) {
gtk_menu_shell_append(GTK_MENU_SHELL(menu), gtk_separator_menu_item_new());
GtkWidget *restart_item = gtk_menu_item_new_with_label("Restart Services");
GtkWidget *restart_item = gtk_menu_item_new_with_label("[Tools] Restart Active Services");
g_signal_connect(restart_item, "activate", G_CALLBACK(on_restart), NULL);
gtk_menu_shell_append(GTK_MENU_SHELL(menu), restart_item);
@@ -465,11 +716,12 @@ int main(int argc, char *argv[]) {
indicator = app_indicator_new(
"proxy-suite-tray",
"network-vpn-disconnected",
"proxy-suite-disabled",
APP_INDICATOR_CATEGORY_SYSTEM_SERVICES
);
app_indicator_set_status(indicator, APP_INDICATOR_STATUS_ACTIVE);
initial_state = get_service_state();
build_menu();
build_controls_window();
app_indicator_set_menu(indicator, GTK_MENU(menu));
+2 -2
View File
@@ -4,8 +4,8 @@ let
src = pkgs.fetchFromGitHub {
owner = "Flowseal";
repo = "tg-ws-proxy";
rev = "fe4e0e82344d8e8ca5e54b7752cafa934fb763ab";
hash = "sha256-tXDfYE1qFYTAWTu7pse/jcovDmX/F42SCGOzsUBmljs=";
rev = "v1.6.1";
hash = "sha256-7dFHrD8lrxzQsjGanCWao5zEIIx+swcKRKo+mI/fMlQ=";
};
pythonEnv = pkgs.python3.withPackages (
+86 -117
View File
@@ -20,18 +20,55 @@ def _qs(query: str) -> dict:
return dict(urllib.parse.parse_qsl(query))
def _parse_url_parts(url: str, scheme: str) -> tuple[str, str, str, dict]:
"""Strip scheme+fragment, return (userinfo, host, port_str, params).
userinfo is "" when no '@' is present."""
rest = url[len(f"{scheme}://"):]
rest, _, _ = rest.partition("#")
if "@" in rest:
userinfo, _, rest = rest.partition("@")
else:
userinfo = ""
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
return userinfo, host, port, _qs(query)
def _mk_transport(
transport_type: str,
path: str = "/",
host_header: str = "",
service_name: str = "",
) -> "dict | None":
"""Build a sing-box transport dict for ws/grpc/h2. Returns None for tcp."""
if transport_type == "ws":
return {
"type": "ws",
"path": urllib.parse.unquote(path),
"headers": {"Host": host_header},
}
elif transport_type == "grpc":
return {
"type": "grpc",
"service_name": urllib.parse.unquote(service_name),
}
elif transport_type == "h2":
return {
"type": "http",
"host": [host_header],
"path": urllib.parse.unquote(path),
}
return None
def parse_vless(url: str, tag: str) -> dict:
"""
vless://UUID@HOST:PORT?security=reality&pbk=KEY&fp=chrome&sni=SNI&sid=SID&flow=FLOW&type=tcp
vless://UUID@HOST:PORT?security=tls&sni=SNI&fp=chrome&type=ws&path=/path&host=HOST
"""
rest = url[len("vless://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
userinfo, host, port, params = _parse_url_parts(url, "vless")
security = params.get("security", "none")
transport = params.get("type", "tcp")
ob: dict = {
"type": "vless",
@@ -42,9 +79,6 @@ def parse_vless(url: str, tag: str) -> dict:
"packet_encoding": "xudp",
}
security = params.get("security", "none")
transport = params.get("type", "tcp")
if security == "reality":
ob["tls"] = {
"enabled": True,
@@ -66,23 +100,14 @@ def parse_vless(url: str, tag: str) -> dict:
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
elif transport == "h2":
ob["transport"] = {
"type": "http",
"host": [params.get("host", host)],
"path": urllib.parse.unquote(params.get("path", "/")),
}
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
flow = urllib.parse.unquote(params.get("flow", ""))
if flow:
@@ -129,23 +154,15 @@ def parse_vmess(url: str, tag: str) -> dict:
path = str(data.get("path") or "/")
h_host = str(data.get("host") or host)
if net == "ws":
ob["transport"] = {
"type": "ws",
"path": path,
"headers": {"Host": h_host},
}
elif net == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": path.lstrip("/"),
}
elif net in ("h2", "http"):
ob["transport"] = {
"type": "http",
"host": [h_host],
"path": path,
}
# vmess grpc uses path as service_name; other transports use path/h_host directly
tr = _mk_transport(
net if net != "http" else "h2",
path=path,
host_header=h_host,
service_name=path.lstrip("/"),
)
if tr is not None:
ob["transport"] = tr
return ob
@@ -154,15 +171,7 @@ def parse_trojan(url: str, tag: str) -> dict:
"""
trojan://PASSWORD@HOST:PORT?sni=SNI&fp=chrome&security=tls&type=tcp|ws|grpc&path=...
"""
rest = url[len("trojan://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
password = urllib.parse.unquote(userinfo)
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
userinfo, host, port, params = _parse_url_parts(url, "trojan")
transport = params.get("type", "tcp")
ob: dict = {
@@ -170,7 +179,7 @@ def parse_trojan(url: str, tag: str) -> dict:
"tag": tag,
"server": host,
"server_port": int(port),
"password": password,
"password": urllib.parse.unquote(userinfo),
"tls": {
"enabled": True,
"server_name": params.get("sni", host),
@@ -182,17 +191,14 @@ def parse_trojan(url: str, tag: str) -> dict:
if params.get("alpn"):
ob["tls"]["alpn"] = params["alpn"].split(",")
if transport == "ws":
ob["transport"] = {
"type": "ws",
"path": urllib.parse.unquote(params.get("path", "/")),
"headers": {"Host": params.get("host", host)},
}
elif transport == "grpc":
ob["transport"] = {
"type": "grpc",
"service_name": urllib.parse.unquote(params.get("serviceName", "")),
}
tr = _mk_transport(
transport,
path=params.get("path", "/"),
host_header=params.get("host", host),
service_name=params.get("serviceName", ""),
)
if tr is not None:
ob["transport"] = tr
return ob
@@ -236,13 +242,7 @@ def parse_hysteria2(url: str, tag: str) -> dict:
hy2://... (same, shorter alias)
"""
scheme = "hysteria2" if url.startswith("hysteria2://") else "hy2"
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
userinfo, host, port, params = _parse_url_parts(url, scheme)
ob: dict = {
"type": "hysteria2",
@@ -267,18 +267,9 @@ def parse_tuic(url: str, tag: str) -> dict:
"""
tuic://UUID:PASSWORD@HOST:PORT?congestion_control=bbr&udp_relay_mode=native&alpn=h3&sni=SNI
"""
rest = url[len("tuic://"):]
rest, _, _ = rest.partition("#")
userinfo, _, rest = rest.partition("@")
userinfo, host, port, params = _parse_url_parts(url, "tuic")
uuid, _, password = userinfo.partition(":")
hostpart, _, query = rest.partition("?")
host, _, port = hostpart.rpartition(":")
params = _qs(query)
alpn_raw = params.get("alpn", "h3")
alpn = [a for a in alpn_raw.split(",") if a]
alpn = [a for a in params.get("alpn", "h3").split(",") if a]
return {
"type": "tuic",
@@ -306,25 +297,13 @@ def parse_socks(url: str, tag: str) -> dict:
"""
scheme = url.split("://")[0].lower()
version = "4" if scheme.startswith("socks4") else "5"
userinfo, host, port, _ = _parse_url_parts(url, scheme)
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
ob: dict = {
"type": "socks",
"tag": tag,
"version": version,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob: dict = {"type": "socks", "tag": tag, "version": version}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)
@@ -337,23 +316,13 @@ def parse_http_proxy(url: str, tag: str) -> dict:
https://[user:pass@]host:port[#remark] – HTTP CONNECT proxy over TLS
"""
scheme = url.split("://")[0].lower()
rest = url[len(scheme) + 3:]
rest, _, _ = rest.partition("#")
userinfo, host, port, _ = _parse_url_parts(url, scheme)
ob: dict = {
"type": "http",
"tag": tag,
}
if "@" in rest:
userinfo, _, rest = rest.partition("@")
if ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
hostpart = rest.split("?")[0]
host, _, port = hostpart.rpartition(":")
ob: dict = {"type": "http", "tag": tag}
if userinfo and ":" in userinfo:
username, _, password = userinfo.partition(":")
ob["username"] = urllib.parse.unquote(username)
ob["password"] = urllib.parse.unquote(password)
ob["server"] = host
ob["server_port"] = int(port)