windows: workspace, dev shell and the config model

Start of the native Windows port. windows/ holds a Rust workspace; this
first piece is ps-core's model of the services.proxy-suite option tree,
with upstream's names and defaults, Windows-only additions documented,
validation ported from the module's assertions, and the derived tags and
loopback ports the tunnels add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-10-26 22:28:10 +03:00
1 parent 9d81e975ea
commit c837db1c18
16 files changed
+3506

No files matched your search

+1
View File
@@ -0,0 +1 @@
target/
+221
View File
@@ -0,0 +1,221 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "aho-corasick"
version = "1.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
dependencies = [
"memchr",
]
[[package]]
name = "base64"
version = "0.22.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
[[package]]
name = "equivalent"
version = "1.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
[[package]]
name = "foldhash"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
[[package]]
name = "hashbrown"
version = "0.17.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
[[package]]
name = "indexmap"
version = "2.14.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
dependencies = [
"equivalent",
"hashbrown",
"serde",
"serde_core",
]
[[package]]
name = "ipnet"
version = "2.12.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "memchr"
version = "2.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "percent-encoding"
version = "2.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
"unicode-ident",
]
[[package]]
name = "ps-core"
version = "0.1.0"
dependencies = [
"base64",
"indexmap",
"ipnet",
"percent-encoding",
"regex",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
"proc-macro2",
]
[[package]]
name = "regex"
version = "1.13.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
[[package]]
name = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.154"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
dependencies = [
"foldhash",
"indexmap",
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "3.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "2.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
[[package]]
name = "zmij"
version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+20
View File
@@ -0,0 +1,20 @@
[workspace]
resolver = "2"
members = ["crates/ps-core"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT"
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
[workspace.dependencies]
anyhow = "1"
base64 = "0.22"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
regex = "1"
thiserror = "2"
percent-encoding = "2"
ipnet = "2"
indexmap = { version = "2", features = ["serde"] }
+88
View File
@@ -0,0 +1,88 @@
# Proxy Suite for Windows: design
The Linux tree (`modules/`, `pkgs/`, `scripts/`) stays as upstream has it, so `main` keeps
merging from FUFSoB/proxy-suite-flake. Everything Windows-specific lives under `windows/`.
## Why a rewrite and not a port
Upstream's logic sits in Nix: the module evaluates `services.proxy-suite` into bash + jq start
scripts, systemd units, nftables rules and polkit rules. None of that runs on Windows, and Nix
does not either. What carries over is the *behaviour* (option semantics, link parsing, config
shape, routing order, group/detour resolution, CLI verbs, GUI tabs), not the code. The Python
pieces (`scripts/proxy_url_parsers.py`, `proxy_parsing.py`, …) are the reference
implementation: the Rust port is tested against them differentially.
## Shape
One Rust workspace, four binaries, one library:
| Crate | Binary | Role |
|---|---|---|
| `ps-core` | — | Config model (the `services.proxy-suite` tree as serde types, same names), validation, link and subscription parsing, sing-box / XRay config rendering, zapret strategy rendering, AmneziaWG/WARP config handling, share links. Pure: no I/O beyond what callers hand it. |
| `ps-ipc` | — | The service API: request/response types and the framed-JSON transport (named pipe on Windows, Unix socket elsewhere, so the stack runs on Linux for development). |
| `ps-service` | `proxy-suite-service.exe` | Runs as a Windows service (LocalSystem). Owns the config and state, renders backend configs, supervises the backend processes (a Job Object kills them with it), runs the timers (subscriptions, rule sets, autoProxy), talks to sing-box's Clash API, applies the kill switch, serves the API. `--console` runs it in the foreground. |
| `ps-ctl` | `proxy-ctl.exe` | Upstream's CLI verbs over the API. |
| `ps-gui` | `proxy-suite.exe` | GPUI window and tray icon. Every setting is editable here; it never writes files itself, it sends edits to the service, which validates them. |
### Config and state
- `%ProgramData%\ProxySuite\config.json`: the whole option tree, **with upstream's exact
camelCase names** (`proxy.listener.port`, `zapret.zapret2.autoHostlist.failThreshold` …), so
`docs/options/*.md` stays the reference and differential tests compare like with like. Written only by the service,
after validation, atomically. The GUI and `proxy-ctl config get/set/edit` go through the API.
Upstream's split between *declared* (Nix) and *runtime* additions disappears: everything is
runtime-editable. Secrets (`urlFile`, `passwordFile` …) become plain fields kept in a
separate `secrets.json` readable only by SYSTEM and Administrators (and the API returns them
only to callers with the `secrets` scope).
- `%ProgramData%\ProxySuite\state\`: pins, disabled outbounds, route-mode override, subscription
caches, rule-set downloads, autoProxy results, AWG/WARP registrations, inbound users' traffic.
- `%ProgramData%\ProxySuite\bin\<component>\<version>\`: backend binaries, fetched by the
component manager from pinned release URLs with pinned SHA-256s (see below).
- `%ProgramData%\ProxySuite\logs\`: one rotating log per unit, also tailed over the API.
### Units
The service keeps upstream's unit names so `proxy-ctl status`/`logs` read the same:
| Unit | Windows process | Notes |
|---|---|---|
| `proxy-suite-socks` | `sing-box.exe` (or `xray.exe`) | mixed inbound on `listener`; Clash API on loopback |
| `proxy-suite-tun` | `sing-box.exe` | TUN through wintun, `auto_route`, `strict_route` |
| `proxy-suite-xray-sidecar` | `xray.exe` | hybrid backend's XRay-only outbounds |
| `proxy-suite-zapret` | `winws.exe` / `winws2.exe` | a child with the exact arguments Flowseal's / bol-van's Windows strategies use; never their `service.bat`, which would register a competing `zapret` service. zapret v1 and zapret2 are mutually exclusive, and other WinDivert users (GoodbyeDPI) conflict: validation says so |
| `proxy-suite-awg-<p>` | AmneziaWG tunnel | global VPN profile; amneziawg-windows installs each tunnel as its own Windows service, so this unit kind is a *managed service*, not a child (decided once the AWG research is in) |
| `proxy-suite-awg-ob-<p>` | `wireproxy-awg.exe` | AWG as a SOCKS outbound |
| `proxy-suite-tor` | `tor.exe` (+ lyrebird/snowflake) | outbound tagged `tor` |
| `proxy-suite-ssh-proxy` | `ssh.exe -D` (Windows OpenSSH) | outbound tagged `ssh-proxy` |
| `proxy-suite-tg-ws-proxy` | `tg-ws-proxy.exe` | |
| `proxy-suite-wl-<name>` | whitelist-bypass | creators/joiners |
| `proxy-suite-inbounds` | `xray.exe` | server listeners |
| `proxy-suite-killswitch` | in-service | sing-box `strict_route` first if it holds on Windows; WFP filters as the follow-up |
TProxy, cgroup/netns per-app routing and proxychains have no Windows counterpart. Per-app
routing becomes sing-box `process_name` / `process_path` rules on the TUN, plus a
`proxy-ctl apps run` that sets `HTTP(S)_PROXY`/`ALL_PROXY` for programs that honour them.
The system proxy (WinINet, per user) is set by the GUI for its user, not by the service.
### Who may change things
"Everything editable in the app" means no UAC prompt per edit: the API pipe grants SYSTEM and
Administrators full access and, by default, the interactive user (`S-1-5-4`). `userControl`
maps onto this: `userControl.enable = false` keeps the pipe to Administrators, and
`userControl.scopes` limit what non-admin callers may do, as upstream's do.
### Component manager
Binaries are not vendored into git. `ps-core::components` holds a manifest: name, version,
URL, SHA-256, archive layout, files to keep. The service downloads into `bin\`, verifies, and
switches atomically; the GUI's Components page shows versions and offers updates. Each manifest
entry follows its project's own Windows release (zapret's WinDivert driver and files exactly
as Flowseal / bol-van ship them).
### Testing on the Linux dev box
- `ps-core` unit tests, plus differential tests against upstream's Python parsers.
- Rendered configs are checked with `sing-box check` and `xray run -test` (from nixpkgs).
- `ps-service --console` runs on Linux against Linux sing-box/xray, so the API, supervisor,
timers and CLI are exercised end to end without Windows.
- Windows binaries are cross-compiled (see `README.md` for the toolchain).
+18
View File
@@ -0,0 +1,18 @@
[package]
name = "ps-core"
description = "Proxy Suite for Windows: config model, link parsing and backend config rendering"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
serde.workspace = true
serde_json.workspace = true
regex.workspace = true
thiserror.workspace = true
percent-encoding.workspace = true
ipnet.workspace = true
indexmap.workspace = true
[dev-dependencies]
@@ -0,0 +1,479 @@
//! `inbounds`: server listeners for remote clients, their users, share links,
//! subscriptions, and the manager that keeps the users' policies.
//!
//! Left out from upstream: `runtime` (everything here is runtime-editable), `serverSource`
//! (a Linux dummy interface), `manager.speedLimits` (nftables policing) and the web server
//! groups; the service serves subscriptions itself on `subscriptions.listen`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::{AwgObfuscation, RouteMatch};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Inbounds {
pub enable: bool,
pub server_address: Option<String>,
pub server_aliases: Vec<String>,
pub server_ports: Vec<Value>,
pub access_log: bool,
/// Add Windows Firewall rules for every listener not on loopback.
pub open_firewall: bool,
pub share_links: bool,
pub subscriptions: InboundSubscriptions,
pub routing: InboundRouting,
pub users: BTreeMap<String, InboundUser>,
pub listeners: BTreeMap<String, InboundListener>,
pub manager: Manager,
}
impl Default for Inbounds {
fn default() -> Self {
Self {
enable: false,
server_address: None,
server_aliases: Vec::new(),
server_ports: Vec::new(),
access_log: false,
open_firewall: true,
share_links: true,
subscriptions: InboundSubscriptions::default(),
routing: InboundRouting::default(),
users: BTreeMap::new(),
listeners: BTreeMap::new(),
manager: Manager::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundSubscriptions {
pub enable: bool,
pub base_url: Option<String>,
/// `null`: a key generated on first start and kept in the state directory. `false`: no
/// key (tokens are a hash of the user alone). A string: a file with the key.
pub key_file: Option<Value>,
/// Windows only: address and port the service serves the subscription files on
/// (`host:port`), since there is no web server to hand a directory to. `null`: not
/// served; `proxy-ctl inbounds sub` still prints them.
pub listen: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundRouting {
pub via: String,
pub proxy: RouteMatch,
pub block_ru: bool,
pub block_private: bool,
pub block_torrent: bool,
pub block_ports: Vec<Value>,
pub zapret_direct: bool,
}
impl Default for InboundRouting {
fn default() -> Self {
Self {
via: "proxy".into(),
proxy: RouteMatch::default(),
block_ru: true,
block_private: true,
block_torrent: true,
block_ports: vec![Value::from(25)],
zapret_direct: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundUser {
pub order: Option<u32>,
pub uuid: Option<String>,
pub uuid_file: Option<String>,
pub password: Option<String>,
pub password_file: Option<String>,
pub public_key: Option<String>,
pub private_key_file: Option<String>,
pub preshared_key_file: Option<String>,
pub address: Option<String>,
pub policy: UserPolicy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrafficPeriod {
Daily,
Weekly,
Monthly,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserPolicy {
pub enabled: bool,
/// A date, an ISO time, or a Unix time.
pub expires_at: Option<Value>,
/// Seconds, or a number with m, h, d or w.
pub expires_after: Option<Value>,
/// Bytes, or a number with K, M, G, T.
pub traffic_limit: Option<Value>,
pub traffic_period: Option<TrafficPeriod>,
pub ip_limit: Option<u32>,
}
impl Default for UserPolicy {
fn default() -> Self {
Self {
enabled: true,
expires_at: None,
expires_after: None,
traffic_limit: None,
traffic_period: None,
ip_limit: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InboundType {
Vless,
Vmess,
Trojan,
Hysteria2,
Shadowsocks,
Socks,
Http,
Amneziawg,
}
impl InboundType {
pub fn as_str(self) -> &'static str {
match self {
Self::Vless => "vless",
Self::Vmess => "vmess",
Self::Trojan => "trojan",
Self::Hysteria2 => "hysteria2",
Self::Shadowsocks => "shadowsocks",
Self::Socks => "socks",
Self::Http => "http",
Self::Amneziawg => "amneziawg",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundListener {
#[serde(rename = "type")]
pub kind: Option<InboundType>,
pub port: u16,
pub share_port: Option<u16>,
pub share_address: Option<String>,
pub address: String,
pub accept_proxy_protocol: bool,
pub share_fingerprint: Option<String>,
pub share_variants: Vec<ShareVariant>,
pub via: Option<String>,
pub order: i64,
pub users: Vec<String>,
pub flow: Option<String>,
pub method: String,
pub server_password: Option<String>,
pub server_password_file: Option<String>,
pub transport: InboundTransport,
pub tls: InboundTls,
pub reality: Reality,
pub fallbacks: Vec<Fallback>,
pub xray_json: Option<Map<String, Value>>,
pub json_file: Option<String>,
pub hysteria: Hysteria,
pub amnezia_wg: AwgServer,
}
impl Default for InboundListener {
fn default() -> Self {
Self {
kind: None,
port: 443,
share_port: None,
share_address: None,
address: "::".into(),
accept_proxy_protocol: false,
share_fingerprint: Some("chrome".into()),
share_variants: Vec::new(),
via: None,
order: 1000,
users: Vec::new(),
flow: None,
method: "2022-blake3-aes-128-gcm".into(),
server_password: None,
server_password_file: None,
transport: InboundTransport::default(),
tls: InboundTls::default(),
reality: Reality::default(),
fallbacks: Vec::new(),
xray_json: None,
json_file: None,
hysteria: Hysteria::default(),
amnezia_wg: AwgServer::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ShareVariant {
pub name: String,
pub fingerprint: Option<String>,
pub alpn: Option<Vec<String>>,
pub mode: Option<String>,
pub address: Option<String>,
pub server_name: Option<String>,
pub port_hopping: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundTransport {
#[serde(rename = "type")]
pub kind: String,
pub path: String,
pub host: Option<String>,
pub mode: Option<String>,
pub service_name: String,
pub trusted_x_forwarded_for: Vec<String>,
}
impl Default for InboundTransport {
fn default() -> Self {
Self {
kind: "raw".into(),
path: "/".into(),
host: None,
mode: None,
service_name: String::new(),
trusted_x_forwarded_for: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundTls {
pub enable: bool,
pub certificate_file: Option<String>,
pub key_file: Option<String>,
pub server_name: Option<String>,
pub alpn: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Reality {
pub enable: bool,
pub dest: String,
pub server_names: Vec<String>,
pub private_key_file: Option<String>,
pub private_key: Option<String>,
pub public_key: Option<String>,
pub short_ids: Vec<String>,
pub xver: u8,
}
impl Default for Reality {
fn default() -> Self {
Self {
enable: false,
dest: "www.microsoft.com:443".into(),
server_names: Vec::new(),
private_key_file: None,
private_key: None,
public_key: None,
short_ids: vec![String::new()],
xver: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Fallback {
pub name: Option<String>,
pub alpn: Option<String>,
pub path: Option<String>,
pub dest: Option<Value>,
pub listener: Option<String>,
pub xver: u8,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Hysteria {
pub masquerade: Option<String>,
pub rewrite_host: bool,
pub x_forwarded: bool,
pub salamander: Salamander,
/// Upstream redirects the range with nftables; Windows has no such redirect, so here it
/// only goes into share links for a front that does it.
pub port_hopping: Option<String>,
}
impl Default for Hysteria {
fn default() -> Self {
Self {
masquerade: None,
rewrite_host: true,
x_forwarded: false,
salamander: Salamander::default(),
port_hopping: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Salamander {
pub enable: bool,
pub password: Option<String>,
pub password_file: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AwgServerMode {
#[default]
Proxy,
Lan,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgServer {
pub mode: AwgServerMode,
/// `null`: `awgi-<tag>`.
pub interface_name: Option<String>,
pub subnet: String,
pub subnet6: Option<String>,
pub private_key_file: Option<String>,
pub obfuscation: AwgObfuscation,
pub dns: Vec<String>,
pub mtu: Option<u32>,
pub persistent_keepalive: Option<u32>,
#[serde(rename = "clientAllowedIPs")]
pub client_allowed_ips: Vec<String>,
}
impl Default for AwgServer {
fn default() -> Self {
Self {
mode: AwgServerMode::Proxy,
interface_name: None,
subnet: "10.66.0.0/24".into(),
subnet6: None,
private_key_file: None,
obfuscation: AwgObfuscation::default(),
dns: vec!["1.1.1.1".into(), "1.0.0.1".into()],
mtu: None,
persistent_keepalive: Some(25),
client_allowed_ips: vec!["0.0.0.0/0".into(), "::/0".into()],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Manager {
pub enable: bool,
pub interval: u32,
pub api: ManagerApi,
pub subscriptions: ManagerSubscriptions,
pub delete_expired_after: Option<String>,
pub ip_limit: IpLimit,
pub notify: Notify,
pub webhooks: Vec<Webhook>,
}
impl Default for Manager {
fn default() -> Self {
Self {
enable: false,
interval: 30,
api: ManagerApi::default(),
subscriptions: ManagerSubscriptions::default(),
delete_expired_after: None,
ip_limit: IpLimit::default(),
notify: Notify::default(),
webhooks: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ManagerApi {
pub listen: Option<String>,
pub tokens_file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ManagerSubscriptions {
pub enable: bool,
pub listen: Option<String>,
pub profile_title: String,
pub update_interval: Option<u32>,
pub support_url: Option<String>,
pub web_page_url: Option<String>,
}
impl Default for ManagerSubscriptions {
fn default() -> Self {
Self {
enable: true,
listen: None,
profile_title: "{user}".into(),
update_interval: Some(12),
support_url: None,
web_page_url: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct IpLimit {
pub ban_time: u32,
}
impl Default for IpLimit {
fn default() -> Self {
Self { ban_time: 600 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Notify {
pub traffic_percent: Vec<u32>,
pub expiry_days: Vec<u32>,
}
impl Default for Notify {
fn default() -> Self {
Self { traffic_percent: vec![80, 100], expiry_days: vec![3, 1] }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Webhook {
pub url: String,
pub events: Vec<String>,
pub secret_file: Option<String>,
}
+267
View File
@@ -0,0 +1,267 @@
//! `killSwitch`, `perAppRouting`, `geodata`, `userControl`, `gui` and `debug`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct KillSwitch {
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
/// and after it fails. Windows Filtering Platform filters do it, so it holds even while
/// the service itself is stopped, until `proxy-ctl killswitch off`.
pub enable: bool,
pub direct_fallbacks: bool,
pub allowed_subnets: Vec<String>,
/// Windows only: let the Windows Time service (NTP, UDP 123) past it. Upstream lists the
/// time daemons' users instead.
pub allow_time_sync: bool,
}
impl Default for KillSwitch {
fn default() -> Self {
Self {
enable: false,
direct_fallbacks: true,
allowed_subnets: vec!["192.168.0.0/16".into()],
allow_time_sync: true,
}
}
}
/// Per-app routing, the Windows way: by program, not by cgroup.
///
/// Upstream wraps apps in proxychains or moves them into a cgroup whose packets nftables
/// marks. Windows has neither, but sing-box knows which program owns a connection, so here a
/// profile names programs, and their connections go to its outbound whatever the routing
/// says. `proxy-ctl apps run <profile> -- <cmd>` also starts a command with `HTTP_PROXY`,
/// `HTTPS_PROXY` and `ALL_PROXY` pointing at the profile's own loopback listener, for
/// programs that honour them when no TUN runs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct PerAppRouting {
pub enable: bool,
pub profiles: Vec<PerAppProfile>,
/// Windows only: the first loopback port of the profiles' listeners, one per profile in
/// order.
pub listener_base_port: u16,
}
impl Default for PerAppRouting {
fn default() -> Self {
Self { enable: false, profiles: Vec::new(), listener_base_port: 18800 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct PerAppProfile {
pub name: String,
/// An outbound or group tag, or "proxy", "direct" or "block".
pub outbound: String,
/// Program file names, such as `Telegram.exe`; matched without regard to case.
pub process_names: Vec<String>,
/// Full program paths.
pub process_paths: Vec<String>,
}
impl Default for PerAppProfile {
fn default() -> Self {
Self {
name: String::new(),
outbound: "proxy".into(),
process_names: Vec::new(),
process_paths: Vec::new(),
}
}
}
/// Where geodata comes from. Upstream names Nix packages; here they are download locations,
/// fetched into the state directory and refreshed with `updateInterval`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Geodata {
pub sing_box: GeodataSingBox,
pub xray: GeodataXray,
/// Windows only: how often the downloads are refreshed.
pub update_interval: String,
}
impl Default for Geodata {
fn default() -> Self {
Self {
sing_box: GeodataSingBox::default(),
xray: GeodataXray::default(),
update_interval: "7d".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct GeodataSingBox {
/// Base URL of the `geoip-<name>.srs` rule sets.
pub geoip: String,
/// Base URL of the `geosite-<name>.srs` rule sets.
pub geosite: String,
}
impl Default for GeodataSingBox {
fn default() -> Self {
Self {
geoip: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set".into(),
geosite: "https://raw.githubusercontent.com/SagerNet/sing-geosite/rule-set".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct GeodataXray {
/// Base URL holding `geoip.dat` and `geosite.dat`. `null`: XRay's own, which only has
/// countries.
pub assets: Option<String>,
}
impl Default for GeodataXray {
fn default() -> Self {
Self {
assets: Some(
"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download".into(),
),
}
}
}
/// The scopes `userControl` hands out, as upstream names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Scope {
Services,
PerApp,
Routing,
Outbounds,
Secrets,
AutoProxy,
Zapret,
Stats,
Inbounds,
WhitelistBypass,
AmneziaWg,
/// Windows only: edit the configuration itself (`proxy-ctl config set`, the app's
/// settings pages). Upstream changes it with a rebuild, which needs root.
Config,
}
impl Scope {
pub const ALL: [Scope; 12] = [
Scope::Services,
Scope::PerApp,
Scope::Routing,
Scope::Outbounds,
Scope::Secrets,
Scope::AutoProxy,
Scope::Zapret,
Scope::Stats,
Scope::Inbounds,
Scope::WhitelistBypass,
Scope::AmneziaWg,
Scope::Config,
];
}
/// Who may use the service without being an administrator.
///
/// Upstream's default keeps every change to root; a Windows desktop app whose settings are
/// all edited in its window would prompt for elevation at every click, so here it defaults
/// on for the signed-in (interactive) user.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserControl {
pub enable: bool,
/// A local group whose members get `scopes`. `null`: whoever is signed in at the console
/// or over Remote Desktop (the INTERACTIVE identity).
pub group: Option<String>,
/// Empty allows everything.
pub scopes: Vec<Scope>,
pub groups: BTreeMap<String, UserControlGroup>,
}
impl Default for UserControl {
fn default() -> Self {
Self { enable: true, group: None, scopes: Vec::new(), groups: BTreeMap::new() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserControlGroup {
pub scopes: Vec<Scope>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Gui {
pub autostart: bool,
pub refresh_interval: u32,
}
impl Default for Gui {
fn default() -> Self {
Self { autostart: true, refresh_interval: 3 }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
#[default]
Warn,
Info,
Debug,
Trace,
}
impl LogLevel {
pub fn as_str(self) -> &'static str {
match self {
Self::Warn => "warn",
Self::Info => "info",
Self::Debug => "debug",
Self::Trace => "trace",
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Debug {
pub log_level: LogLevel,
pub connection_log: ConnectionLog,
pub zapret2: DebugZapret2,
pub tg_ws_proxy: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ConnectionLog {
pub enable: bool,
pub hosts: Vec<String>,
pub inbounds: Vec<String>,
pub stall_after: u32,
pub interval: f64,
}
impl Default for ConnectionLog {
fn default() -> Self {
Self { enable: false, hosts: Vec::new(), inbounds: Vec::new(), stall_after: 10, interval: 0.5 }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DebugZapret2 {
pub packets: bool,
pub auto_hostlist: bool,
}
+159
View File
@@ -0,0 +1,159 @@
//! The `services.proxy-suite` option tree, as the Windows port has it.
//!
//! Names, nesting and defaults follow upstream's Nix options (`docs/options/*.md`), so those
//! docs stay the reference and a value means the same thing on both. Options that only mean
//! something on Linux (TProxy, fwmarks, routing tables, kernel and package choices, service
//! users, proxychains) are left out. The few that exist only here say so in their doc comment.
//!
//! Every struct takes `#[serde(default)]`: a config file names only what differs from the
//! defaults, as a Nix config does.
mod inbounds;
mod misc;
mod proxy;
mod tunnels;
mod validate;
mod zapret;
pub use inbounds::*;
pub use misc::*;
pub use proxy::*;
pub use tunnels::*;
pub use validate::{Issue, Severity, validate};
pub use zapret::*;
use serde::{Deserialize, Serialize};
/// The whole configuration: `services.proxy-suite`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Config {
/// The master switch. Upstream defaults it off, since the module is imported everywhere;
/// here the service only runs where it was installed, so it defaults on.
pub enable: bool,
pub proxy: Proxy,
pub kill_switch: KillSwitch,
pub per_app_routing: PerAppRouting,
pub zapret: Zapret,
pub amnezia_wg: AmneziaWg,
pub warp: Warp,
pub tor: Tor,
pub ssh_proxy: SshProxy,
pub tg_ws_proxy: TgWsProxy,
pub whitelist_bypass: WhitelistBypass,
pub inbounds: Inbounds,
pub geodata: Geodata,
pub user_control: UserControl,
pub gui: Gui,
pub debug: Debug,
}
impl Default for Config {
fn default() -> Self {
Self {
enable: true,
proxy: Proxy::default(),
kill_switch: KillSwitch::default(),
per_app_routing: PerAppRouting::default(),
zapret: Zapret::default(),
amnezia_wg: AmneziaWg::default(),
warp: Warp::default(),
tor: Tor::default(),
ssh_proxy: SshProxy::default(),
tg_ws_proxy: TgWsProxy::default(),
whitelist_bypass: WhitelistBypass::default(),
inbounds: Inbounds::default(),
geodata: Geodata::default(),
user_control: UserControl::default(),
gui: Gui::default(),
debug: Debug::default(),
}
}
}
impl Config {
/// Reads a config file's text. Unknown keys are refused, so a typo in a hand-edited file
/// is reported instead of silently meaning the default.
pub fn from_json(text: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(text)
}
pub fn to_json_pretty(&self) -> String {
serde_json::to_string_pretty(self).expect("the config always serializes")
}
}
/// Which address family a name is dialled over first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DomainStrategy {
PreferIpv4,
PreferIpv6,
Ipv4Only,
Ipv6Only,
}
impl DomainStrategy {
pub fn as_str(self) -> &'static str {
match self {
Self::PreferIpv4 => "prefer_ipv4",
Self::PreferIpv6 => "prefer_ipv6",
Self::Ipv4Only => "ipv4_only",
Self::Ipv6Only => "ipv6_only",
}
}
}
/// "direct" or "proxy": how a helper (Tor, a rule-set download, a whitelist-bypass creator)
/// reaches the network.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Upstream {
#[default]
Direct,
Proxy,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_defaults_round_trip() {
let cfg = Config::default();
assert_eq!(Config::from_json(&cfg.to_json_pretty()).unwrap(), cfg);
}
#[test]
fn a_config_names_only_what_differs() {
let cfg = Config::from_json(
r#"{
"proxy": {
"enable": true,
"outbounds": [{ "tag": "nl", "url": "hy2://pw@example.com:443?sni=example.com" }],
"routing": { "rules": [{ "outbound": "nl", "geosites": ["netflix"], "processNames": ["Telegram.exe"] }] },
"groups": { "eu": { "match": ["de-*"], "strategy": "urltest" } }
},
"zapret": { "enable": true, "zapret-discord-youtube": { "configName": "general (ALT9)" } }
}"#,
)
.unwrap();
assert!(cfg.proxy.enable);
assert_eq!(cfg.proxy.listener.port, 1080);
assert_eq!(cfg.proxy.routing.rules[0].matches.geosites, ["netflix"]);
assert_eq!(cfg.proxy.routing.rules[0].process_names, ["Telegram.exe"]);
assert_eq!(cfg.proxy.groups["eu"].strategy, GroupStrategy::Urltest);
assert!(cfg.proxy.groups["eu"].failback);
assert_eq!(cfg.zapret.discord_youtube.config_name, "general (ALT9)");
assert_eq!(cfg.proxy.dns.local.transport, DnsTransport::Tcp);
}
#[test]
fn unknown_keys_are_refused() {
let err = Config::from_json(r#"{ "proxy": { "listner": {} } }"#).unwrap_err();
assert!(err.to_string().contains("listner"), "{err}");
let err = Config::from_json(r#"{ "proxy": { "routing": { "rules": [{ "outbound": "x", "domain": [] }] } } }"#)
.unwrap_err();
assert!(err.to_string().contains("domain"), "{err}");
}
}
+536
View File
@@ -0,0 +1,536 @@
//! `proxy`: the local proxy, its outbounds, subscriptions, selection, routing, DNS and TUN.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::DomainStrategy;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Backend {
#[default]
#[serde(rename = "sing-box")]
SingBox,
#[serde(rename = "xray")]
Xray,
#[serde(rename = "hybrid")]
Hybrid,
}
impl Backend {
pub fn as_str(self) -> &'static str {
match self {
Self::SingBox => "sing-box",
Self::Xray => "xray",
Self::Hybrid => "hybrid",
}
}
/// Whether sing-box runs (alone or in front of XRay).
pub fn runs_sing_box(self) -> bool {
self != Self::Xray
}
}
/// The transparent mode started with the service. Only "tun" exists on Windows: TProxy is
/// a Linux kernel feature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Autostart {
Tun,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Proxy {
pub enable: bool,
pub backend: Backend,
pub autostart: Option<Autostart>,
pub ipv6: bool,
pub listener: ProxyListener,
pub auto_proxy: AutoProxy,
pub sing_box: SingBoxOptions,
pub xray: XrayOptions,
pub outbounds: Vec<Outbound>,
pub subscriptions: Vec<Subscription>,
pub runtime_subscriptions: RuntimeSubscriptions,
pub subscription_update_interval: String,
pub selection: Selection,
pub groups: BTreeMap<String, Group>,
pub priority: BTreeMap<String, i64>,
pub selection_exclude: Vec<String>,
pub url_test: UrlTest,
pub dns: Dns,
pub routing: Routing,
pub tun: Tun,
/// Windows only: point the signed-in user's system proxy (WinINet, which browsers and most
/// apps follow) at `listener` while the local proxy runs.
pub system_proxy: SystemProxy,
}
impl Default for Proxy {
fn default() -> Self {
Self {
enable: false,
backend: Backend::SingBox,
autostart: None,
ipv6: true,
listener: ProxyListener::default(),
auto_proxy: AutoProxy::default(),
sing_box: SingBoxOptions::default(),
xray: XrayOptions::default(),
outbounds: Vec::new(),
subscriptions: Vec::new(),
runtime_subscriptions: RuntimeSubscriptions::default(),
subscription_update_interval: "1d".into(),
selection: Selection::First,
groups: BTreeMap::new(),
priority: BTreeMap::new(),
selection_exclude: Vec::new(),
url_test: UrlTest::default(),
dns: Dns::default(),
routing: Routing::default(),
tun: Tun::default(),
system_proxy: SystemProxy::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ProxyListener {
pub address: String,
pub port: u16,
pub auth: ListenerAuth,
}
impl Default for ProxyListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1080, auth: ListenerAuth::default() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ListenerAuth {
pub username: Option<String>,
pub password: Option<String>,
pub password_file: Option<String>,
}
impl ListenerAuth {
pub fn enabled(&self) -> bool {
self.username.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AutoProxy {
pub enable: bool,
pub interval: String,
pub probes_per_run: u32,
pub max_exits: u32,
pub ttl_days: u32,
#[serde(rename = "slowBelowKiBps")]
pub slow_below_kibps: u32,
pub exclude: Vec<String>,
pub probe_base_port: u16,
}
impl Default for AutoProxy {
fn default() -> Self {
Self {
enable: false,
interval: "10m".into(),
probes_per_run: 200,
max_exits: 12,
ttl_days: 30,
slow_below_kibps: 150,
exclude: Vec::new(),
probe_base_port: 18540,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SingBoxOptions {
pub clash_api_port: u16,
}
impl Default for SingBoxOptions {
fn default() -> Self {
Self { clash_api_port: 9090 }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct XrayOptions {
/// Values are a number or a "low-high" range XRay picks from.
pub xhttp_xmux: Option<BTreeMap<String, Value>>,
}
/// Which engine runs an outbound on the hybrid backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum OutboundBackend {
#[default]
#[serde(rename = "auto")]
Auto,
#[serde(rename = "sing-box")]
SingBox,
#[serde(rename = "xray")]
Xray,
}
/// Domains, addresses, geodata and rule sets: what a rule (or an outbound's own routing)
/// matches.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RouteMatch {
pub domains: Vec<String>,
pub ips: Vec<String>,
pub geosites: Vec<String>,
pub geoips: Vec<String>,
pub rule_sets: Vec<String>,
}
impl RouteMatch {
pub fn is_empty(&self) -> bool {
self.domains.is_empty()
&& self.ips.is_empty()
&& self.geosites.is_empty()
&& self.geoips.is_empty()
&& self.rule_sets.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Outbound {
pub tag: String,
pub url: Option<String>,
pub url_file: Option<String>,
pub detour: Option<String>,
pub sing_box_json: Option<Map<String, Value>>,
pub xray_json: Option<Map<String, Value>>,
pub backend: OutboundBackend,
pub routing: RouteMatch,
/// Windows only, and what upstream's `proxy-ctl proxy outbounds disable` keeps in its
/// state: left out of selection and autoProxy, still usable by name.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub disabled: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Subscription {
pub tag: String,
pub url: Option<String>,
pub url_file: Option<String>,
pub detour: Option<String>,
pub allow_private_servers: bool,
pub allow_insecure: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RuntimeSubscriptions {
pub allow_http: bool,
pub allow_insecure: bool,
pub allow_private_servers: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Selection {
#[default]
First,
Selector,
Urltest,
Failover,
}
impl Selection {
pub fn as_str(self) -> &'static str {
match self {
Self::First => "first",
Self::Selector => "selector",
Self::Urltest => "urltest",
Self::Failover => "failover",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GroupStrategy {
#[default]
Failover,
Urltest,
Selector,
}
impl GroupStrategy {
pub fn as_str(self) -> &'static str {
match self {
Self::Failover => "failover",
Self::Urltest => "urltest",
Self::Selector => "selector",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Group {
pub outbounds: Vec<String>,
pub subscriptions: Vec<String>,
#[serde(rename = "match")]
pub match_: Vec<String>,
pub strategy: GroupStrategy,
pub failback: bool,
pub interval: Option<String>,
}
impl Default for Group {
fn default() -> Self {
Self {
outbounds: Vec::new(),
subscriptions: Vec::new(),
match_: Vec::new(),
strategy: GroupStrategy::Failover,
failback: true,
interval: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UrlTest {
pub url: String,
pub interval: String,
pub tolerance: i64,
}
impl Default for UrlTest {
fn default() -> Self {
Self {
url: "https://www.gstatic.com/generate_204".into(),
interval: "3m".into(),
tolerance: 50,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DnsTransport {
#[default]
Udp,
Tcp,
Tls,
}
impl DnsTransport {
pub fn as_str(self) -> &'static str {
match self {
Self::Udp => "udp",
Self::Tcp => "tcp",
Self::Tls => "tls",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DnsUpstream {
#[serde(rename = "type", default)]
pub transport: DnsTransport,
pub address: String,
#[serde(default = "default_dns_port")]
pub port: u16,
}
fn default_dns_port() -> u16 {
53
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Dns {
/// TCP by default: DPI boxes answer plain UDP queries to well-known resolvers themselves.
pub local: DnsUpstream,
pub remote: DnsUpstream,
pub strategy: Option<DomainStrategy>,
pub client_subnet: Option<String>,
pub fake_ip: FakeIp,
pub sing_box: DnsSingBox,
}
impl Default for Dns {
fn default() -> Self {
Self {
local: DnsUpstream { transport: DnsTransport::Tcp, address: "1.1.1.1".into(), port: 53 },
remote: DnsUpstream { transport: DnsTransport::Udp, address: "1.1.1.1".into(), port: 53 },
strategy: None,
client_subnet: None,
fake_ip: FakeIp::default(),
sing_box: DnsSingBox::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct FakeIp {
pub enable: bool,
pub inet4_range: String,
}
impl Default for FakeIp {
fn default() -> Self {
Self { enable: false, inet4_range: "198.18.0.0/15".into() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DnsSingBox {
pub servers: Vec<Map<String, Value>>,
pub rules: Vec<Map<String, Value>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RouteDefault {
#[default]
Proxy,
Direct,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Routing {
pub default: RouteDefault,
pub direct_ru: bool,
pub proxy: RouteMatch,
pub direct: RouteMatch,
pub block: RouteMatch,
pub rules: Vec<RoutingRule>,
pub rule_sets: BTreeMap<String, RuleSet>,
pub rule_set_update_interval: String,
}
impl Default for Routing {
fn default() -> Self {
Self {
default: RouteDefault::Proxy,
direct_ru: true,
proxy: RouteMatch::default(),
direct: RouteMatch::default(),
block: RouteMatch::default(),
rules: Vec::new(),
rule_sets: BTreeMap::new(),
rule_set_update_interval: "1d".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RoutingRule {
pub outbound: String,
#[serde(flatten)]
pub matches: RouteMatch,
/// Windows only: program file names (`firefox.exe`) whose connections this rule matches.
/// sing-box looks the owning process up, on the TUN and on the local proxy alike.
pub process_names: Vec<String>,
/// Windows only: full program paths, as `process_names` does.
pub process_paths: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleSetFormat {
Binary,
Source,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleSetDetour {
#[default]
Proxy,
Direct,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuleSet {
pub url: String,
#[serde(default)]
pub format: Option<RuleSetFormat>,
#[serde(default)]
pub detour: RuleSetDetour,
}
impl RuleSet {
/// The format, guessed from the URL when unset as upstream does.
pub fn effective_format(&self) -> RuleSetFormat {
self.format.unwrap_or_else(|| {
let path = self.url.split(['?', '#']).next().unwrap_or("");
if path.ends_with(".json") { RuleSetFormat::Source } else { RuleSetFormat::Binary }
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Tun {
pub enable: bool,
/// The adapter's name in Windows' network connections.
pub interface: String,
pub address: String,
pub mtu: u32,
}
impl Default for Tun {
fn default() -> Self {
Self {
enable: false,
interface: "ProxySuite".into(),
address: "172.19.0.1/30".into(),
mtu: 1400,
}
}
}
/// Windows only.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SystemProxy {
pub enable: bool,
/// Hosts that skip the system proxy, in WinINet's syntax. `<local>` covers names without
/// a dot.
pub bypass: Vec<String>,
}
impl Default for SystemProxy {
fn default() -> Self {
Self {
enable: false,
bypass: vec![
"localhost".into(),
"127.*".into(),
"10.*".into(),
"172.16.*".into(),
"192.168.*".into(),
"<local>".into(),
],
}
}
}
@@ -0,0 +1,439 @@
//! The tunnels besides the proxy's own outbounds: `amneziaWg`, `warp`, `tor`, `sshProxy`,
//! `tgWsProxy` and `whitelistBypass`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{DomainStrategy, GroupStrategy, Upstream};
// --- amneziaWg ------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AmneziaWg {
pub enable: bool,
pub profiles: BTreeMap<String, AwgProfile>,
}
/// How a profile is used, when it is not a global VPN.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AwgOutboundKind {
/// Plain WireGuard in sing-box: AmneziaWG obfuscation is dropped, with a warning.
SingBox,
/// wireproxy-awg, a userspace AmneziaWG client with a SOCKS listener the outbound dials.
Userspace,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgProfile {
/// The tunnel's name, which its Windows service (`AmneziaWGTunnel$<name>`) and adapter
/// take. `null`: the profile's name.
pub interface_name: Option<String>,
pub autostart: bool,
pub as_outbound: Option<AwgOutboundKind>,
pub endpoint: Option<String>,
pub domain_strategy: Option<DomainStrategy>,
pub allow_config_hooks: bool,
pub vpn_container: Option<String>,
pub config_file: Option<String>,
/// Windows only: the `.conf` text itself, as pasted into the app.
pub config: Option<String>,
pub vpn_file: Option<String>,
pub vpn: Option<String>,
pub settings: Option<AwgSettings>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgSettings {
pub addresses: Vec<String>,
pub dns: Vec<String>,
pub private_key: Option<String>,
pub private_key_file: Option<String>,
pub listen_port: Option<u16>,
pub mtu: Option<u32>,
pub obfuscation: AwgObfuscation,
pub obfuscation_file: Option<String>,
pub peers: Vec<AwgPeer>,
}
/// A number, or (AWG 3) a "low-high" range or "(off)".
pub type AwgRange = Value;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgObfuscation {
pub jc: Option<u32>,
pub jmin: Option<u32>,
pub jmax: Option<u32>,
pub s1: Option<u32>,
pub s2: Option<u32>,
pub s3: Option<u32>,
pub s4: Option<u32>,
pub h1: Option<AwgRange>,
pub h2: Option<AwgRange>,
pub h3: Option<AwgRange>,
pub h4: Option<AwgRange>,
pub content_padding_addition: Option<AwgRange>,
pub rekey_after_time: Option<AwgRange>,
pub rekey_timeout: Option<AwgRange>,
pub reject_after_time: Option<AwgRange>,
pub keepalive_timeout: Option<AwgRange>,
pub max_handshake_attempts: Option<AwgRange>,
pub i1: Option<String>,
pub i2: Option<String>,
pub i3: Option<String>,
pub i4: Option<String>,
pub i5: Option<String>,
pub header_protection_key: Option<String>,
pub header_protection_key_file: Option<String>,
pub random_trailers: Option<bool>,
pub disable_cookies: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgPeer {
pub public_key: String,
pub preshared_key: Option<String>,
pub preshared_key_file: Option<String>,
#[serde(rename = "allowedIPs")]
pub allowed_ips: Vec<String>,
pub endpoint: Option<String>,
pub persistent_keepalive: Option<AwgRange>,
pub advanced_security: Option<bool>,
}
// --- warp -----------------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarpOutboundKind {
SingBox,
Userspace,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Warp {
pub enable: bool,
pub config_file: Option<String>,
/// Windows only: the WireGuard profile text itself.
pub config: Option<String>,
pub generator_url: Option<String>,
pub endpoint: Option<String>,
pub as_outbound: Option<WarpOutboundKind>,
pub domain_strategy: DomainStrategy,
pub devices: BTreeMap<String, WarpDevice>,
pub instances: Option<u32>,
pub group: WarpGroup,
pub as_amnezia_wg: bool,
pub autostart: bool,
}
impl Default for Warp {
fn default() -> Self {
Self {
enable: false,
config_file: None,
config: None,
generator_url: None,
endpoint: None,
as_outbound: None,
domain_strategy: DomainStrategy::PreferIpv6,
devices: BTreeMap::new(),
instances: None,
group: WarpGroup::default(),
as_amnezia_wg: false,
autostart: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WarpDevice {
pub config_file: Option<String>,
pub config: Option<String>,
pub endpoint: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WarpGroup {
pub strategy: GroupStrategy,
pub failback: bool,
}
impl Default for WarpGroup {
fn default() -> Self {
Self { strategy: GroupStrategy::Failover, failback: true }
}
}
// --- tor ------------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Tor {
pub enable: bool,
pub as_outbound: bool,
pub route_onion: bool,
pub client_only: bool,
pub keep_awake: bool,
pub upstream: Upstream,
pub socks_port: u16,
/// Windows only: Tor's loopback control port (cookie authentication), for `tor newnym`.
/// Upstream uses a Unix socket.
pub control_port: u16,
pub bridges: TorBridges,
pub onion_service: OnionService,
pub extra_config: String,
}
impl Default for Tor {
fn default() -> Self {
Self {
enable: false,
as_outbound: false,
route_onion: true,
client_only: true,
keep_awake: false,
upstream: Upstream::Direct,
socks_port: 18530,
control_port: 18531,
bridges: TorBridges::default(),
onion_service: OnionService::default(),
extra_config: String::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TorBridges {
pub lines: Vec<String>,
pub file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct OnionService {
pub enable: bool,
pub listeners: Option<Vec<String>>,
pub secret_key_file: Option<String>,
}
// --- sshProxy -------------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StrictHostKeyChecking {
#[default]
Yes,
AcceptNew,
No,
}
impl StrictHostKeyChecking {
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::AcceptNew => "accept-new",
Self::No => "no",
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshProxy {
pub enable: bool,
pub server: SshServer,
pub as_outbound: bool,
pub identity_file: Option<String>,
pub host_key: Vec<String>,
pub host_key_file: Option<String>,
pub known_hosts_file: Option<String>,
pub strict_host_key_checking: StrictHostKeyChecking,
pub listener: SshListener,
pub extra_args: Vec<String>,
pub domain_strategy: Option<DomainStrategy>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshServer {
pub user: Option<String>,
pub host: Option<String>,
pub port: u16,
}
impl Default for SshServer {
fn default() -> Self {
Self { user: None, host: None, port: 22 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshListener {
pub address: String,
pub port: u16,
}
impl Default for SshListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1091 }
}
}
// --- tgWsProxy ------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgWsProxy {
pub enable: bool,
pub listener: TgListener,
pub secret: Option<String>,
pub secret_file: Option<String>,
pub dc_ips: BTreeMap<String, String>,
pub fake_tls_domain: Option<String>,
pub cloudflare: TgCloudflare,
pub pool_size: u32,
#[serde(rename = "bufferKiB")]
pub buffer_kib: u32,
pub proxy_protocol: bool,
/// Keep the relay's own connections out of the TUN: on Windows, a rule sending its
/// process direct.
pub bypass_transparent_proxy: bool,
pub log: TgLog,
}
impl Default for TgWsProxy {
fn default() -> Self {
Self {
enable: false,
listener: TgListener::default(),
secret: None,
secret_file: None,
dc_ips: BTreeMap::new(),
fake_tls_domain: None,
cloudflare: TgCloudflare::default(),
pool_size: 4,
buffer_kib: 256,
proxy_protocol: false,
bypass_transparent_proxy: true,
log: TgLog::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgListener {
pub address: String,
pub port: u16,
}
impl Default for TgListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1443 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgCloudflare {
pub domains: Vec<String>,
pub worker_domains: Vec<String>,
pub fallback: bool,
}
impl Default for TgCloudflare {
fn default() -> Self {
Self { domains: Vec::new(), worker_domains: Vec::new(), fallback: true }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgLog {
pub file: Option<String>,
#[serde(rename = "maxSizeMiB")]
pub max_size_mib: f64,
pub keep: u32,
}
impl Default for TgLog {
fn default() -> Self {
Self { file: None, max_size_mib: 5.0, keep: 1 }
}
}
// --- whitelistBypass ------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WlPlatform {
Wbstream,
Telemost,
Dion,
Bitrix,
Vk,
}
impl WlPlatform {
pub fn as_str(self) -> &'static str {
match self {
Self::Wbstream => "wbstream",
Self::Telemost => "telemost",
Self::Dion => "dion",
Self::Bitrix => "bitrix",
Self::Vk => "vk",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WlResources {
#[default]
Moderate,
Default,
Unlimited,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WhitelistBypass {
pub enable: bool,
pub joiners: BTreeMap<String, WlJoiner>,
pub creators: BTreeMap<String, WlCreator>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WlJoiner {
pub platform: WlPlatform,
#[serde(default)]
pub link_file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WlCreator {
pub platform: WlPlatform,
#[serde(default)]
pub cookies_file: Option<String>,
#[serde(default)]
pub link_file: Option<String>,
#[serde(default)]
pub upstream: Upstream,
#[serde(default)]
pub resources: WlResources,
}
@@ -0,0 +1,651 @@
//! Checks a configuration before the service takes it, as upstream's assertions do at
//! evaluation. Errors refuse the configuration; warnings go with it.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::{Backend, Config, GroupStrategy, Selection, ZapretEngine};
use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issue {
pub severity: Severity,
/// The option it is about, as `proxy.outbounds.2.tag`.
pub path: String,
pub message: String,
}
struct Issues(Vec<Issue>);
impl Issues {
fn error(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Error, path: path.into(), message: message.into() });
}
fn warn(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Warning, path: path.into(), message: message.into() });
}
/// `used` needs `dependency`: the shape of most of upstream's assertions.
fn requires(&mut self, used: bool, dependency: bool, path: &str, used_label: &str, dependency_label: &str) {
if used && !dependency {
self.error(path, format!("{used_label} requires {dependency_label}"));
}
}
}
fn tag_pattern_ok(tag: &str) -> bool {
let mut chars = tag.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
fn profile_name_ok(name: &str) -> bool {
let mut chars = name.chars();
matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
fn count_some(values: &[bool]) -> usize {
values.iter().filter(|v| **v).count()
}
/// Every problem with `cfg`, errors first.
pub fn validate(cfg: &Config) -> Vec<Issue> {
let mut v = Issues(Vec::new());
proxy(cfg, &mut v);
tunnels(cfg, &mut v);
zapret(cfg, &mut v);
per_app(cfg, &mut v);
inbounds(cfg, &mut v);
ports(cfg, &mut v);
let mut issues = v.0;
issues.sort_by_key(|i| i.severity != Severity::Error);
issues
}
fn proxy(cfg: &Config, v: &mut Issues) {
let p = &cfg.proxy;
let sing_box = p.backend.runs_sing_box();
let mut seen = BTreeSet::new();
for (i, ob) in p.outbounds.iter().enumerate() {
let path = format!("proxy.outbounds.{i}");
if ob.tag.is_empty() {
v.error(format!("{path}.tag"), "an outbound needs a tag");
} else if BUILTIN_TAGS.contains(&ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("'{}' is a builtin target and cannot be an outbound's tag", ob.tag));
} else if !seen.insert(ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("outbound tag '{}' is used twice", ob.tag));
}
let sources = [ob.url.is_some(), ob.url_file.is_some(), ob.sing_box_json.is_some(), ob.xray_json.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("outbound '{}' sets {} of url, urlFile, singBoxJson and xrayJson; it needs exactly one", ob.tag, count_some(&sources)));
}
if ob.sing_box_json.is_some() && p.backend == Backend::Xray {
v.error(&path, format!("outbound '{}' is sing-box JSON, which the xray backend cannot run", ob.tag));
}
if ob.xray_json.is_some() && p.backend == Backend::SingBox {
v.error(&path, format!("outbound '{}' is XRay JSON, which the sing-box backend cannot run", ob.tag));
}
if !ob.routing.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.routing.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
for name in &ob.routing.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.routing.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
let mut subs = BTreeSet::new();
for (i, sub) in p.subscriptions.iter().enumerate() {
let path = format!("proxy.subscriptions.{i}");
if !tag_pattern_ok(&sub.tag) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' must start with a letter or digit and hold only letters, digits, '.', '_' and '-'", sub.tag));
} else if !subs.insert(sub.tag.as_str()) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' is used twice", sub.tag));
}
if count_some(&[sub.url.is_some(), sub.url_file.is_some()]) != 1 {
v.error(&path, format!("subscription '{}' needs exactly one of url and urlFile", sub.tag));
}
}
let known = |t: &str| derived::is_known_target(cfg, t);
for (i, ob) in p.outbounds.iter().enumerate() {
if let Some(hop) = &ob.detour {
if hop == &ob.tag {
v.error(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' cannot chain through itself", ob.tag));
} else if !known(hop) {
// A subscription entry, perhaps: those only exist once fetched.
v.warn(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' chains through '{hop}', which names no outbound declared here; it must be a subscription entry", ob.tag));
}
}
}
for (i, rule) in p.routing.rules.iter().enumerate() {
let path = format!("proxy.routing.rules.{i}");
if !known(&rule.outbound) {
v.error(format!("{path}.outbound"), format!("routing rule target '{}' is not an outbound, a group, or proxy, direct or block", rule.outbound));
}
if rule.matches.is_empty() && rule.process_names.is_empty() && rule.process_paths.is_empty() {
v.warn(&path, "this rule matches nothing");
}
if !rule.matches.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
if (!rule.process_names.is_empty() || !rule.process_paths.is_empty()) && !sing_box {
v.error(&path, "matching programs needs the sing-box or hybrid backend");
}
for name in &rule.matches.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
for (bucket, m) in [("proxy", &p.routing.proxy), ("direct", &p.routing.direct), ("block", &p.routing.block)] {
for name in &m.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("proxy.routing.{bucket}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
if !p.routing.rule_sets.is_empty() && !sing_box {
v.error("proxy.routing.ruleSets", "rule sets need the sing-box or hybrid backend");
}
for (name, rs) in &p.routing.rule_sets {
if !rs.url.starts_with("https://") || rs.url.len() <= "https://".len() {
v.error(format!("proxy.routing.ruleSets.{name}.url"), "a rule set is fetched over https only");
}
}
if !p.groups.is_empty() && !sing_box {
v.error("proxy.groups", "outbound groups need the sing-box or hybrid backend");
}
for (name, group) in &p.groups {
let path = format!("proxy.groups.{name}");
if BUILTIN_TAGS.contains(&name.as_str()) || p.outbounds.iter().any(|o| &o.tag == name) {
v.error(&path, format!("group '{name}' takes a tag an outbound or builtin already has"));
}
for member in &group.outbounds {
if member == name {
v.error(format!("{path}.outbounds"), format!("group '{name}' cannot contain itself"));
} else if !known(member) {
v.warn(format!("{path}.outbounds"), format!("member '{member}' names no outbound declared here; it is left out unless a subscription brings it"));
}
}
for sub in &group.subscriptions {
if !p.subscriptions.iter().any(|s| &s.tag == sub) {
v.error(format!("{path}.subscriptions"), format!("subscription '{sub}' does not exist"));
}
}
if group.outbounds.is_empty() && group.subscriptions.is_empty() && group.match_.is_empty() {
v.warn(&path, format!("group '{name}' has no members: it blocks"));
}
if group.strategy != GroupStrategy::Failover && !group.failback {
v.warn(format!("{path}.failback"), "failback only applies to the failover strategy");
}
}
if p.selection == Selection::Failover && !sing_box {
v.error("proxy.selection", "\"failover\" selection needs the sing-box or hybrid backend");
}
if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend");
}
if p.auto_proxy.slow_below_kibps > 0 && p.auto_proxy.enable && p.selection == Selection::First {
v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\"");
}
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}
if p.enable && !derived::has_available_outbounds(cfg) {
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
}
v.requires(p.autostart.is_some(), p.tun.enable, "proxy.autostart", "proxy.autostart = \"tun\"", "proxy.tun.enable = true");
v.requires(p.tun.enable, p.enable, "proxy.tun.enable", "proxy.tun.enable", "proxy.enable = true");
v.requires(p.system_proxy.enable, p.enable, "proxy.systemProxy.enable", "proxy.systemProxy.enable", "proxy.enable = true");
let auth = &p.listener.auth;
if auth.username.is_some() && auth.password.is_none() && auth.password_file.is_none() {
v.error("proxy.listener.auth", "a username needs password or passwordFile");
}
if auth.password.is_some() && auth.password_file.is_some() {
v.error("proxy.listener.auth", "set password or passwordFile, not both");
}
if auth.username.is_none() && (auth.password.is_some() || auth.password_file.is_some()) {
v.error("proxy.listener.auth", "a password needs a username");
}
for (label, value) in [("username", &auth.username), ("password", &auth.password)] {
if value.as_deref().is_some_and(|s| s.is_empty() || s.chars().any(char::is_whitespace)) {
v.error(format!("proxy.listener.auth.{label}"), "it must be a single word");
}
}
if p.system_proxy.enable && auth.enabled() {
v.warn("proxy.systemProxy.enable", "the system proxy cannot carry a login: apps that follow it will be asked for one");
}
}
fn tunnels(cfg: &Config, v: &mut Issues) {
let proxy_on = cfg.proxy.enable;
let w = &cfg.warp;
if w.enable {
if w.as_outbound.is_none() && !w.as_amnezia_wg {
v.warn("warp.enable", "WARP is on, but neither asOutbound nor asAmneziaWg uses it");
}
if w.as_outbound.is_some() && w.as_amnezia_wg {
v.error("warp.asAmneziaWg", "asAmneziaWg cannot be used with asOutbound");
}
v.requires(w.as_outbound.is_some(), proxy_on, "warp.asOutbound", "warp.asOutbound", "proxy.enable = true");
v.requires(w.as_amnezia_wg, cfg.amnezia_wg.enable, "warp.asAmneziaWg", "warp.asAmneziaWg", "amneziaWg.enable = true");
v.requires(w.autostart, w.as_amnezia_wg, "warp.autostart", "warp.autostart", "warp.asAmneziaWg = true");
if w.instances.is_some() && !w.devices.is_empty() {
v.error("warp.instances", "instances cannot be used with devices");
}
if w.devices.len() > 1 && w.devices.contains_key(derived::WARP_TAG) {
v.error("warp.devices", "with several devices, \"warp\" names their group and cannot be a device");
}
if w.config_file.is_some() && w.config.is_some() {
v.error("warp.config", "set configFile or config, not both");
}
}
let a = &cfg.amnezia_wg;
if a.enable {
let mut autostarts = Vec::new();
for (name, p) in &a.profiles {
let path = format!("amneziaWg.profiles.{name}");
let sources = [p.config_file.is_some(), p.config.is_some(), p.vpn_file.is_some(), p.vpn.is_some(), p.settings.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("profile '{name}' needs exactly one of configFile, config, vpnFile, vpn and settings"));
}
if p.autostart {
autostarts.push(name.clone());
}
if p.as_outbound.is_some() && p.autostart {
v.warn(format!("{path}.autostart"), "an outbound always runs: autostart only applies to a global profile");
}
v.requires(p.as_outbound.is_some(), proxy_on, &format!("{path}.asOutbound"), &format!("amneziaWg.profiles.{name}.asOutbound"), "proxy.enable = true");
if let Some(iface) = &p.interface_name
&& (iface.is_empty() || iface.len() > 32 || !iface.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.'))) {
v.error(format!("{path}.interfaceName"), "a tunnel name takes letters, digits, '_', '-' and '.' (at most 32)");
}
if let Some(settings) = &p.settings {
if settings.peers.is_empty() {
v.error(format!("{path}.settings.peers"), "a profile needs a peer");
}
if settings.private_key.is_some() == settings.private_key_file.is_some() {
v.error(format!("{path}.settings"), "set exactly one of privateKey and privateKeyFile");
}
}
if BUILTIN_TAGS.contains(&name.as_str()) {
v.error(&path, format!("'{name}' is a builtin target"));
}
}
if w.autostart {
autostarts.push(derived::WARP_TAG.into());
}
if autostarts.len() > 1 {
v.error("amneziaWg.profiles", format!("only one global profile can autostart, not {}", autostarts.join(", ")));
}
if !autostarts.is_empty() && cfg.proxy.autostart.is_some() {
v.error("proxy.autostart", "only one global mode can autostart: a TUN and an AmneziaWG profile both do");
}
}
let t = &cfg.tor;
if t.enable {
v.requires(t.as_outbound, proxy_on, "tor.asOutbound", "tor.asOutbound", "proxy.enable = true");
v.requires(t.onion_service.enable, cfg.inbounds.enable, "tor.onionService.enable", "tor.onionService.enable", "inbounds.enable = true");
if !t.as_outbound && !t.onion_service.enable {
v.warn("tor.enable", "Tor is on, but neither asOutbound nor onionService uses it");
}
if t.socks_port == t.control_port {
v.error("tor.controlPort", "Tor's SOCKS and control ports must differ");
}
}
let s = &cfg.ssh_proxy;
if s.enable {
if s.server.host.is_none() {
v.error("sshProxy.server.host", "the SSH tunnel needs a server");
}
if s.server.user.is_none() {
v.error("sshProxy.server.user", "the SSH tunnel needs a login user");
}
v.requires(s.as_outbound, proxy_on, "sshProxy.asOutbound", "sshProxy.asOutbound", "proxy.enable = true");
if s.strict_host_key_checking == crate::config::StrictHostKeyChecking::Yes
&& s.known_hosts_file.is_none()
&& s.host_key_file.is_none()
&& s.host_key.is_empty()
{
v.error("sshProxy.strictHostKeyChecking", "\"yes\" needs the server's keys: knownHostsFile, hostKeyFile or hostKey");
}
}
let g = &cfg.tg_ws_proxy;
if g.enable {
if g.secret.is_some() && g.secret_file.is_some() {
v.error("tgWsProxy.secret", "set secret or secretFile, not both");
}
if let Some(secret) = &g.secret
&& (secret.len() != 32 || !secret.chars().all(|c| c.is_ascii_hexdigit())) {
v.error("tgWsProxy.secret", "an MTProto secret is 32 hex digits");
}
if g.buffer_kib < 4 {
v.error("tgWsProxy.bufferKiB", "the buffer is at least 4 KiB");
}
}
let wl = &cfg.whitelist_bypass;
if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
}
}
if wl.joiners.is_empty() && wl.creators.is_empty() {
v.warn("whitelistBypass.enable", "whitelist-bypass is on without creators or joiners");
}
}
}
fn zapret(cfg: &Config, v: &mut Issues) {
let z = &cfg.zapret;
if !z.enable {
return;
}
if z.engine == ZapretEngine::DiscordYoutube {
let mut names = BTreeSet::new();
for (i, rule) in z.discord_youtube.hostlist_rules.iter().enumerate() {
let path = format!("zapret.zapret-discord-youtube.hostlistRules.{i}");
if !profile_name_ok(&rule.name) {
v.error(format!("{path}.name"), "a list name takes lowercase letters, digits and '-'");
} else if !names.insert(rule.name.as_str()) {
v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name));
}
if rule.config_name.is_some() && !rule.nfqws_args.is_empty() {
v.error(&path, "configName cannot be used with nfqwsArgs");
}
if rule.preset.is_none() && rule.config_name.is_none() && rule.nfqws_args.is_empty() && rule.default_domains.len() != 1 {
v.error(&path, "without preset, configName or nfqwsArgs, use exactly one of defaultDomains, so its strategy can be inferred");
}
if rule.domains.is_empty() && rule.default_domains.is_empty() && rule.ips.is_empty() && rule.default_ips.is_empty() {
v.warn(&path, format!("list '{}' holds no sites", rule.name));
}
}
}
if z.engine == ZapretEngine::Zapret2 {
let ah = &z.zapret2.auto_hostlist;
for (label, value) in [("failThreshold", ah.fail_threshold), ("failTime", ah.fail_time), ("retransThreshold", ah.retrans_threshold), ("udpOut", ah.udp_out)] {
if value == 0 {
v.error(format!("zapret.zapret2.autoHostlist.{label}"), "it must be greater than zero");
}
}
if z.zapret2.proxy_fallback && !derived::has_available_outbounds(cfg) {
v.warn("zapret.zapret2.proxyFallback", "proxyFallback needs an outbound to fall back to");
}
if z.zapret2.cutoff.enable && z.zapret2.cutoff.proxy_fallback && !derived::sing_box_enabled(cfg) {
v.warn("zapret.zapret2.cutoff.proxyFallback", "the cutoff fallback needs the sing-box backend");
}
}
if z.cidr_exemption.enable && z.cidr_exemption.cidrs.is_empty() {
v.warn("zapret.cidrExemption", "the exemption is on but lists no networks");
}
}
fn per_app(cfg: &Config, v: &mut Issues) {
let pa = &cfg.per_app_routing;
if !pa.enable {
return;
}
v.requires(true, cfg.proxy.enable, "perAppRouting.enable", "perAppRouting", "proxy.enable = true");
if !cfg.proxy.backend.runs_sing_box() {
v.error("perAppRouting.enable", "per-app routing needs the sing-box or hybrid backend");
}
let mut names = BTreeSet::new();
for (i, prof) in pa.profiles.iter().enumerate() {
let path = format!("perAppRouting.profiles.{i}");
if !profile_name_ok(&prof.name) {
v.error(format!("{path}.name"), "a profile name takes lowercase letters, digits and '-'");
} else if !names.insert(prof.name.as_str()) {
v.error(format!("{path}.name"), format!("profile '{}' is defined twice", prof.name));
}
if !derived::is_known_target(cfg, &prof.outbound) {
v.error(format!("{path}.outbound"), format!("'{}' is not an outbound, a group, or proxy, direct or block", prof.outbound));
}
}
if pa.profiles.len() > 200 {
v.error("perAppRouting.profiles", "at most 200 profiles");
}
}
fn inbounds(cfg: &Config, v: &mut Issues) {
let ib = &cfg.inbounds;
if !ib.enable {
return;
}
let via_ok = |via: &str| {
matches!(via, "proxy" | "direct" | "block") || cfg.proxy.outbounds.iter().any(|o| o.tag == via)
};
if !via_ok(&ib.routing.via) {
v.error("inbounds.routing.via", format!("'{}' is not proxy, direct, block or a proxy.outbounds tag", ib.routing.via));
}
v.requires(ib.routing.via == "proxy", cfg.proxy.enable, "inbounds.routing.via", "inbounds.routing.via = \"proxy\"", "proxy.enable = true");
v.requires(ib.subscriptions.enable, ib.share_links, "inbounds.subscriptions.enable", "inbounds.subscriptions", "inbounds.shareLinks = true");
let mut ports: BTreeMap<(u16, bool), &str> = BTreeMap::new();
for (tag, l) in &ib.listeners {
let path = format!("inbounds.listeners.{tag}");
let sources = [l.kind.is_some(), l.xray_json.is_some(), l.json_file.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("listener '{tag}' needs exactly one of type, xrayJson and jsonFile"));
}
for user in &l.users {
if !ib.users.contains_key(user) {
v.error(format!("{path}.users"), format!("listener '{tag}' names user '{user}', which inbounds.users does not define"));
}
}
if let Some(via) = &l.via
&& !via_ok(via) {
v.error(format!("{path}.via"), format!("'{via}' is not proxy, direct, block or a proxy.outbounds tag"));
}
if l.tls.enable && l.reality.enable {
v.error(&path, "tls cannot be used with reality");
}
use crate::config::InboundType as T;
let udp = matches!(l.kind, Some(T::Hysteria2) | Some(T::Amneziawg));
if let Some(other) = ports.insert((l.port, udp), tag) {
v.error(format!("{path}.port"), format!("listeners '{other}' and '{tag}' share port {}", l.port));
}
match l.kind {
Some(T::Hysteria2) if !l.tls.enable => {
v.error(format!("{path}.tls"), "hysteria2 needs tls");
}
Some(T::Trojan) if !l.tls.enable && !l.reality.enable => {
v.error(format!("{path}.tls"), "trojan needs tls or reality");
}
_ => {}
}
if l.reality.enable {
if l.reality.server_names.is_empty() {
v.error(format!("{path}.reality.serverNames"), "REALITY needs at least one server name");
}
if l.reality.private_key.is_some() == l.reality.private_key_file.is_some() {
v.error(format!("{path}.reality"), "set exactly one of privateKey and privateKeyFile");
}
if ib.share_links && l.reality.public_key.is_none() {
v.warn(format!("{path}.reality.publicKey"), "share links need the public key");
}
}
if l.tls.enable && (l.tls.certificate_file.is_none() || l.tls.key_file.is_none()) {
v.error(format!("{path}.tls"), "TLS needs certificateFile and keyFile");
}
if l.flow.is_some() && l.transport.kind != "raw" {
v.error(format!("{path}.flow"), "the vision flow only works on the raw transport");
}
}
let mut orders = BTreeMap::new();
for (name, user) in &ib.users {
if let Some(order) = user.order
&& let Some(other) = orders.insert(order, name) {
v.error(format!("inbounds.users.{name}.order"), format!("users '{other}' and '{name}' share order {order}"));
}
if user.uuid.is_some() && user.uuid_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set uuid or uuidFile, not both");
}
if user.password.is_some() && user.password_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set password or passwordFile, not both");
}
}
if ib.manager.enable && (ib.manager.interval < 5 || ib.manager.interval > 3600) {
v.error("inbounds.manager.interval", "between 5 and 3600 seconds");
}
if ib.manager.api.listen.is_some() && ib.manager.api.tokens_file.is_none() {
v.error("inbounds.manager.api.listen", "a TCP API needs tokensFile");
}
}
/// Loopback listeners must not collide: whichever starts second would die.
fn ports(cfg: &Config, v: &mut Issues) {
let mut taken: BTreeMap<u16, String> = BTreeMap::new();
let mut claim = |port: u16, who: String, v: &mut Issues| {
if let Some(other) = taken.get(&port) {
v.error(who.clone(), format!("port {port} is taken by {other} too"));
} else {
taken.insert(port, who);
}
};
let p = &cfg.proxy;
if p.enable {
claim(p.listener.port, "proxy.listener.port".into(), v);
if p.backend.runs_sing_box() {
claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v);
}
claim(derived::ports::OUTBOUND_TEST, "the outbound test listener".into(), v);
}
if cfg.tor.enable {
claim(cfg.tor.socks_port, "tor.socksPort".into(), v);
claim(cfg.tor.control_port, "tor.controlPort".into(), v);
}
if cfg.ssh_proxy.enable {
claim(cfg.ssh_proxy.listener.port, "sshProxy.listener.port".into(), v);
}
if cfg.tg_ws_proxy.enable {
claim(cfg.tg_ws_proxy.listener.port, "tgWsProxy.listener.port".into(), v);
}
if cfg.per_app_routing.enable {
for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() {
claim(
cfg.per_app_routing.listener_base_port.saturating_add(i as u16),
format!("perAppRouting.profiles.{i} ({})", prof.name),
v,
);
}
}
for ob in derived::extra_outbounds(cfg) {
use derived::ExtraKind as K;
match ob.kind {
K::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => {
claim(port, format!("AmneziaWG outbound '{}'", ob.tag), v)
}
K::WlJoiner { port, .. } => claim(port, format!("whitelist-bypass joiner '{}'", ob.tag), v),
K::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => {
claim(device.port, format!("WARP device '{}'", device.tag), v)
}
_ => {}
}
}
if p.enable && p.auto_proxy.enable {
let base = p.auto_proxy.probe_base_port;
for i in 0..p.auto_proxy.max_exits.min(64) as u16 {
claim(base.saturating_add(i), format!("proxy.autoProxy.probeBasePort (+{i})"), v);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Group, Outbound, RoutingRule};
fn errors(cfg: &Config) -> Vec<String> {
validate(cfg)
.into_iter()
.filter(|i| i.severity == Severity::Error)
.map(|i| format!("{}: {}", i.path, i.message))
.collect()
}
fn outbound(tag: &str) -> Outbound {
Outbound { tag: tag.into(), url: Some("hy2://pw@example.com:443".into()), ..Default::default() }
}
#[test]
fn the_default_config_is_valid() {
assert_eq!(errors(&Config::default()), Vec::<String>::new());
}
#[test]
fn outbound_tags_are_unique_and_not_builtin() {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de"), outbound("de"), outbound("direct")];
let errs = errors(&cfg);
assert!(errs.iter().any(|e| e.contains("'de' is used twice")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("'direct' is a builtin")), "{errs:?}");
}
#[test]
fn an_outbound_needs_exactly_one_source() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![Outbound { tag: "x".into(), ..Default::default() }];
assert!(errors(&cfg)[0].contains("needs exactly one"));
}
#[test]
fn rule_targets_must_exist() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![outbound("de")];
cfg.proxy.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], ..Default::default() });
let rule = |target: &str| RoutingRule {
outbound: target.into(),
matches: crate::config::RouteMatch { domains: vec!["example.com".into()], ..Default::default() },
..Default::default()
};
cfg.proxy.routing.rules = vec![rule("de"), rule("eu"), rule("direct"), rule("nowhere")];
let errs = errors(&cfg);
assert_eq!(errs.len(), 1, "{errs:?}");
assert!(errs[0].contains("'nowhere'"));
}
#[test]
fn colliding_ports_are_refused() {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de")];
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.tor.socks_port = 1080;
assert!(errors(&cfg).iter().any(|e| e.contains("port 1080")));
}
#[test]
fn groups_need_sing_box() {
let mut cfg = Config::default();
cfg.proxy.backend = Backend::Xray;
cfg.proxy.groups.insert("g".into(), Group::default());
assert!(errors(&cfg).iter().any(|e| e.contains("groups need")));
}
}
+270
View File
@@ -0,0 +1,270 @@
//! `zapret`: DPI bypass without a proxy, through WinDivert.
//!
//! zapret-discord-youtube runs Flowseal's Windows release (`winws.exe`) with the strategy of
//! one of its `general*.bat` presets; zapret2 runs `winws2.exe` from bol-van's
//! zapret-win-bundle with Lua strategies. Both intercept with WinDivert, so only one can run.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ZapretEngine {
#[default]
#[serde(rename = "zapret-discord-youtube")]
DiscordYoutube,
#[serde(rename = "zapret2")]
Zapret2,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret {
pub enable: bool,
pub engine: ZapretEngine,
pub direct_sync: DirectSync,
pub cidr_exemption: CidrExemption,
/// Windows only: turn on TCP timestamps (`netsh interface tcp set global
/// timestamps=enabled`), which both Flowseal's and bol-van's installers do: strategies
/// that fool DPI with them need them.
pub tcp_timestamps: bool,
#[serde(rename = "zapret-discord-youtube")]
pub discord_youtube: DiscordYoutube,
pub zapret2: Zapret2,
}
impl Default for Zapret {
fn default() -> Self {
Self {
enable: false,
engine: ZapretEngine::DiscordYoutube,
direct_sync: DirectSync::default(),
cidr_exemption: CidrExemption::default(),
tcp_timestamps: true,
discord_youtube: DiscordYoutube::default(),
zapret2: Zapret2::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DirectSync {
pub enable: bool,
pub upstream_ips: bool,
pub user_ips: bool,
}
impl Default for DirectSync {
fn default() -> Self {
Self { enable: true, upstream_ips: false, user_ips: true }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct CidrExemption {
pub enable: bool,
pub cidrs: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GameFilter {
All,
Tcp,
Udp,
#[default]
Null,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DiscordYoutube {
/// A preset's name as Flowseal's release names its `.bat` (spaces are ignored):
/// "general", "general(ALT)" … "general(ALT13)", "general(FAKE TLS AUTO)" …
pub config_name: String,
pub game_filter: GameFilter,
pub domains: Vec<String>,
pub exclude_domains: Vec<String>,
pub ips: Vec<String>,
pub exclude_ips: Vec<String>,
pub include_extra_upstream_lists: bool,
pub hostlist_rules: Vec<HostlistRule>,
}
impl Default for DiscordYoutube {
fn default() -> Self {
Self {
config_name: "general(ALT)".into(),
game_filter: GameFilter::Null,
domains: Vec::new(),
exclude_domains: Vec::new(),
ips: Vec::new(),
exclude_ips: Vec::new(),
include_extra_upstream_lists: false,
hostlist_rules: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretPreset {
General,
Google,
Instagram,
Soundcloud,
Twitter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretDefaultDomains {
General,
Google,
Discord,
Youtube,
Instagram,
Soundcloud,
Twitter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretDefaultIps {
All,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct HostlistRule {
pub name: String,
pub domains: Vec<String>,
pub default_domains: Vec<ZapretDefaultDomains>,
pub ips: Vec<String>,
pub default_ips: Vec<ZapretDefaultIps>,
pub preset: Option<ZapretPreset>,
pub config_name: Option<String>,
/// Raw winws arguments (nfqws's syntax, which winws shares); `--hostlist` and `--new`
/// are added.
pub nfqws_args: Vec<String>,
pub enable_direct_sync: bool,
}
impl Default for HostlistRule {
fn default() -> Self {
Self {
name: String::new(),
domains: Vec::new(),
default_domains: Vec::new(),
ips: Vec::new(),
default_ips: Vec::new(),
preset: None,
config_name: None,
nfqws_args: Vec::new(),
enable_direct_sync: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum StrategySource {
#[default]
#[serde(rename = "nfqws2-keenetic")]
Nfqws2Keenetic,
#[serde(rename = "z2k")]
Z2k,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret2 {
pub strategy_source: StrategySource,
pub profiles: Option<Vec<String>>,
pub blobs: BTreeMap<String, String>,
pub domains: Vec<String>,
pub exclude_domains: Vec<String>,
pub ports: Zapret2Ports,
pub proxy_fallback: bool,
pub strategy_log: bool,
pub ipv6: bool,
pub auto_hostlist: AutoHostlist,
pub cutoff: Cutoff,
}
impl Default for Zapret2 {
fn default() -> Self {
Self {
strategy_source: StrategySource::Nfqws2Keenetic,
profiles: None,
blobs: BTreeMap::new(),
domains: Vec::new(),
exclude_domains: Vec::new(),
ports: Zapret2Ports::default(),
proxy_fallback: true,
strategy_log: true,
ipv6: false,
auto_hostlist: AutoHostlist::default(),
cutoff: Cutoff::default(),
}
}
}
/// A port, or a "low-high" range.
pub type PortOrRange = Value;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret2Ports {
pub tcp: Option<String>,
pub udp: Option<String>,
pub extra_tcp: Vec<PortOrRange>,
pub extra_udp: Vec<PortOrRange>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AutoHostlist {
pub enable: bool,
pub fail_threshold: u32,
pub fail_time: u32,
pub retrans_threshold: u32,
pub retrans_reset: bool,
pub retrans_maxseq: u32,
pub incoming_maxseq: u32,
pub udp_out: u32,
pub udp_in: u32,
pub extended_detection: bool,
}
impl Default for AutoHostlist {
fn default() -> Self {
Self {
enable: true,
fail_threshold: 3,
fail_time: 300,
retrans_threshold: 3,
retrans_reset: true,
retrans_maxseq: 32768,
incoming_maxseq: 4096,
udp_out: 4,
udp_in: 1,
extended_detection: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Cutoff {
pub enable: bool,
pub proxy_fallback: bool,
}
impl Default for Cutoff {
fn default() -> Self {
Self { enable: true, proxy_fallback: true }
}
}
+262
View File
@@ -0,0 +1,262 @@
//! What the configuration implies beyond its options: the outbounds that tunnels add, the
//! loopback ports everything listens on, which backends run. Upstream's `derived.nix`.
use crate::config::{
AwgOutboundKind, Backend, Config, WarpOutboundKind, WlPlatform,
};
/// Tags no outbound may take: the routing targets every config has.
pub const BUILTIN_TAGS: [&str; 3] = ["proxy", "direct", "block"];
pub const SSH_OUTBOUND_TAG: &str = "ssh-proxy";
pub const TOR_OUTBOUND_TAG: &str = "tor";
pub const WARP_TAG: &str = "warp";
/// Fixed loopback ports, as upstream numbers them where it has them.
pub mod ports {
/// The listener `proxy-ctl proxy outbounds test` dials each outbound through.
pub const OUTBOUND_TEST: u16 = 18537;
/// The global TUN's own Clash API (it is a separate sing-box instance).
pub const TUN_CLASH_API: u16 = 19181;
/// wireproxy-awg listeners of "userspace" AmneziaWG outbounds, one each.
pub const AWG_TUNNEL_BASE: u16 = 18600;
/// whitelist-bypass joiners' SOCKS listeners, one each.
pub const WL_JOINER_BASE: u16 = 18750;
/// wireproxy-awg listeners of "userspace" WARP devices, one each.
pub const WARP_USERSPACE_BASE: u16 = 18900;
/// The hybrid backend's XRay sidecar, which sing-box hands XRay-only outbounds to.
pub const XRAY_SIDECAR_SOCKS: u16 = 33080;
pub const XRAY_SIDECAR_TUN: u16 = 33180;
}
/// An outbound that a tunnel, not `proxy.outbounds`, adds.
#[derive(Debug, Clone, PartialEq)]
pub struct ExtraOutbound {
pub tag: String,
pub kind: ExtraKind,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExtraKind {
/// OpenSSH's `-D` listener (or sing-box's own SSH outbound, which needs a host key).
Ssh,
/// Tor's SOCKS port.
Tor { port: u16 },
/// A WARP device: a WireGuard endpoint in sing-box, or wireproxy-awg on `port`.
Warp { device: WarpDeviceSpec },
/// An AmneziaWG profile used as an outbound.
Awg { profile: String, kind: AwgOutboundKind, port: u16 },
/// A whitelist-bypass joiner's SOCKS listener.
WlJoiner { platform: WlPlatform, port: u16 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct WarpDeviceSpec {
pub tag: String,
/// The first device keeps a single device's state directory, so a registration carries
/// over when more are added.
pub first: bool,
pub kind: WarpOutboundKind,
pub config_file: Option<String>,
pub config: Option<String>,
pub endpoint: Option<String>,
/// The wireproxy-awg listener, for the "userspace" kind.
pub port: u16,
/// Below the state directory: `warp` for the first device, `warp/<tag>` for the rest.
pub state_subdir: String,
}
impl WarpDeviceSpec {
/// Registered on first start: no profile was given.
pub fn auto_register(&self) -> bool {
self.config_file.is_none() && self.config.is_none()
}
}
/// The WARP device tags: "warp", or what `devices` or `instances` name.
pub fn warp_device_names(cfg: &Config) -> Vec<String> {
if let Some(n) = cfg.warp.instances {
(1..=n).map(|i| format!("warp-{i}")).collect()
} else if !cfg.warp.devices.is_empty() {
cfg.warp.devices.keys().cloned().collect()
} else {
vec![WARP_TAG.to_owned()]
}
}
pub fn warp_devices(cfg: &Config) -> Vec<WarpDeviceSpec> {
let Some(kind) = cfg.warp.as_outbound.filter(|_| cfg.warp.enable) else {
return Vec::new();
};
warp_device_names(cfg)
.into_iter()
.enumerate()
.map(|(index, tag)| {
let device = cfg.warp.devices.get(&tag).cloned().unwrap_or_default();
let first = index == 0;
let (config_file, config) = if device.config_file.is_some() || device.config.is_some() {
(device.config_file, device.config)
} else if first {
(cfg.warp.config_file.clone(), cfg.warp.config.clone())
} else {
(None, None)
};
WarpDeviceSpec {
state_subdir: if first { "warp".into() } else { format!("warp/{tag}") },
tag,
first,
kind,
config_file,
config,
endpoint: device.endpoint.or_else(|| cfg.warp.endpoint.clone()),
port: ports::WARP_USERSPACE_BASE + index as u16,
}
})
.collect()
}
/// Whether "warp" names a group of devices rather than a device.
pub fn warp_grouped(cfg: &Config) -> bool {
warp_devices(cfg).len() > 1
}
/// The AmneziaWG profiles that are outbounds, in name order.
pub fn awg_outbounds(cfg: &Config) -> Vec<(String, AwgOutboundKind, u16)> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
cfg.amnezia_wg
.profiles
.iter()
.filter_map(|(name, p)| p.as_outbound.map(|kind| (name.clone(), kind)))
.enumerate()
.map(|(i, (name, kind))| (name, kind, ports::AWG_TUNNEL_BASE + i as u16))
.collect()
}
/// The AmneziaWG profiles that are global VPNs (`proxy-ctl awg on`), in name order.
pub fn awg_global_profiles(cfg: &Config) -> Vec<String> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
let mut names: Vec<String> = cfg
.amnezia_wg
.profiles
.iter()
.filter(|(_, p)| p.as_outbound.is_none())
.map(|(name, _)| name.clone())
.collect();
if cfg.warp.enable && cfg.warp.as_amnezia_wg && !names.iter().any(|n| n == WARP_TAG) {
names.push(WARP_TAG.into());
}
names
}
/// Every outbound the tunnels add, in the order upstream lists them.
pub fn extra_outbounds(cfg: &Config) -> Vec<ExtraOutbound> {
let mut out = Vec::new();
if cfg.ssh_proxy.enable && cfg.ssh_proxy.as_outbound {
out.push(ExtraOutbound { tag: SSH_OUTBOUND_TAG.into(), kind: ExtraKind::Ssh });
}
for device in warp_devices(cfg) {
out.push(ExtraOutbound { tag: device.tag.clone(), kind: ExtraKind::Warp { device } });
}
if cfg.tor.enable && cfg.tor.as_outbound {
out.push(ExtraOutbound {
tag: TOR_OUTBOUND_TAG.into(),
kind: ExtraKind::Tor { port: cfg.tor.socks_port },
});
}
if cfg.whitelist_bypass.enable {
for (i, (tag, joiner)) in cfg.whitelist_bypass.joiners.iter().enumerate() {
out.push(ExtraOutbound {
tag: tag.clone(),
kind: ExtraKind::WlJoiner {
platform: joiner.platform,
port: ports::WL_JOINER_BASE + i as u16,
},
});
}
}
for (profile, kind, port) in awg_outbounds(cfg) {
out.push(ExtraOutbound {
tag: profile.clone(),
kind: ExtraKind::Awg { profile, kind, port },
});
}
out
}
/// The tags known before anything runs: declared outbounds and the tunnels'. Subscription
/// entries only exist once fetched.
pub fn effective_outbound_tags(cfg: &Config) -> Vec<String> {
let mut tags: Vec<String> = cfg.proxy.outbounds.iter().map(|o| o.tag.clone()).collect();
tags.extend(extra_outbounds(cfg).into_iter().map(|o| o.tag));
if warp_grouped(cfg) {
tags.push(WARP_TAG.into());
}
tags
}
pub fn group_tags(cfg: &Config) -> Vec<String> {
cfg.proxy.groups.keys().cloned().collect()
}
/// Whether a routing target names something: a builtin, an outbound or a group.
pub fn is_known_target(cfg: &Config, target: &str) -> bool {
BUILTIN_TAGS.contains(&target)
|| effective_outbound_tags(cfg).iter().any(|t| t == target)
|| cfg.proxy.groups.contains_key(target)
}
/// Whether the proxy has anything to send traffic through, before subscriptions are fetched.
pub fn has_available_outbounds(cfg: &Config) -> bool {
!cfg.proxy.outbounds.is_empty()
|| !cfg.proxy.subscriptions.is_empty()
|| !extra_outbounds(cfg).is_empty()
}
pub fn sing_box_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend.runs_sing_box()
}
pub fn xray_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend != Backend::SingBox
}
pub fn tor_route_onion(cfg: &Config) -> bool {
cfg.tor.enable && cfg.tor.as_outbound && cfg.tor.route_onion && cfg.proxy.enable
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::WarpDevice;
#[test]
fn warp_names_follow_instances_then_devices() {
let mut cfg = Config::default();
assert_eq!(warp_device_names(&cfg), ["warp"]);
cfg.warp.devices.insert("warp-b".into(), WarpDevice::default());
cfg.warp.devices.insert("warp-a".into(), WarpDevice::default());
assert_eq!(warp_device_names(&cfg), ["warp-a", "warp-b"]);
cfg.warp.instances = Some(3);
assert_eq!(warp_device_names(&cfg), ["warp-1", "warp-2", "warp-3"]);
}
#[test]
fn first_warp_device_inherits_the_top_level_profile() {
let mut cfg = Config::default();
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
cfg.warp.config_file = Some(r"C:\secrets\wgcf.conf".into());
cfg.warp.instances = Some(2);
let devices = warp_devices(&cfg);
assert_eq!(devices[0].config_file.as_deref(), Some(r"C:\secrets\wgcf.conf"));
assert!(!devices[0].auto_register());
assert!(devices[1].auto_register());
assert_eq!(devices[1].state_subdir, "warp/warp-2");
assert!(warp_grouped(&cfg));
assert!(effective_outbound_tags(&cfg).contains(&"warp".to_owned()));
}
}
+8
View File
@@ -0,0 +1,8 @@
//! Proxy Suite for Windows: everything that is pure logic.
//!
//! The configuration model (upstream's `services.proxy-suite` options), share-link and
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here
//! touches the network, the file system or processes; the service does that.
pub mod config;
pub mod derived;
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1791594108,
"narHash": "sha256-XK4KceonkwD8LuMAt/vNrz982mXJM5jeHAxMwsUXXAQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "6510408d147d8c5e6d76043e899e9251756f6a75",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+60
View File
@@ -0,0 +1,60 @@
{
description = "Proxy Suite for Windows: development shell";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs =
{ nixpkgs, ... }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
];
forAll = nixpkgs.lib.genAttrs systems;
in
{
devShells = forAll (
system:
let
pkgs = import nixpkgs { inherit system; };
# GPUI also runs on Linux, so the GUI can be tried here before a Windows build.
guiLibs = with pkgs; [
libxkbcommon
wayland
vulkan-loader
libx11
libxcb
libxcursor
libxi
libxrandr
fontconfig
freetype
alsa-lib
];
in
{
default = pkgs.mkShell {
packages = with pkgs; [
rustup
pkg-config
cargo-xwin
clang
lld
llvm
pkgsCross.mingwW64.stdenv.cc
# The backends, to check rendered configs and run the service on Linux.
sing-box
xray
python3
jq
];
buildInputs = guiLibs;
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs;
shellHook = ''
export PATH="$HOME/.cargo/bin:$PATH"
'';
};
}
);
};
}