Author SHA1 Message Date
faumarayandClaude Opus 5.5 fe291fab2b windows: component archives download on a slow line
Windows release / build (push) Successful in 1h9m39s
Windows release / publish (push) Successful in 50s
A component's archive (sing-box's is 15 MB) had a minute for the
whole transfer, which a slow line misses (CI run #9 timed out on it).
Now a minute without a byte fails it, the whole has no limit, and a
transfer cut short is taken up where it stopped (an HTTP range), eight
times at most; the pinned hash checks the result as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 19:13:34 +03:00
faumarayandClaude Opus 5.5 7cdd33f05e windows: the release notes for 0.2.0-pre.1, the downloads first
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:23:44 +03:00
faumarayandClaude Opus 5.5 36532bcf47 windows: no app logs beside the README's screenshots
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:22:58 +03:00
faumarayandClaude Opus 5.5 e71f6bf5aa windows: screenshots of every page, in the README
tools/screenshots.sh's demo shows zapret2 with z2k, autoProxy,
AmneziaWG and whitelist-bypass; nothing in it warns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:22:46 +03:00
faumarayandClaude Opus 5.5 514ffb97ca windows: zapret2's verdicts route the proxy; options kept to what they are
As upstream's direct-sync: from zapret2's lists and the detector's
verdicts, two rule-sets sing-box reloads, rebuilt every ten seconds and
before it starts: what zapret2 cannot fix (every strategy failed for a
site, or an address leaves connections unanswered) through the proxy
(zapret2.proxyFallback), after the explicit rules and autoProxy's; what
it fixes direct, so it sees it (directSync), unless learned from
transfers cut short. all-bypass and all-proxy as upstream.

The options file winws2 reads (one a line) refuses an option holding a
control character, which would read as more options than it is; and
zapret2.ports.extraTcp/extraUdp, which join its options as written, are
ports or ranges within 1-65535 (validated, and filtered again).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:16:48 +03:00
faumarayandClaude Opus 5.5 9eed225ccc windows: zapret2 with z2k's strategies and upstream's Lua layers
The zapret2-extras component (tools/build-zapret2-extras.sh): z2k at
upstream's pinned commit, its strategies made by its own generator as
upstream's z2k-profiles.template.sh runs it, with tokens where upstream
fills in the configuration at build time; its Lua, lists and fakes; and
upstream's own Lua: the extended detector (detect.lua), the per-site key
by public suffix, the fail stamp, every-change persistence and the
strategy log.

winws2 now runs, as upstream's nfqws2 does, with z2k's Lua for its
strategies, then the layers: each site's working strategy kept across
restarts (z2k's state layer), strategies keyed by site, and with
autoHostlist.extendedDetection the detector learning in place of
nfqws2's own (its last TLS profile, the stall watch where the learned
sites are). Lua arguments name paths as Cygwin does (no colon); what
winws2 writes stays under the Low-integrity folder. The server's TLS
handshake and alert records reach the detectors through a WinDivert
filter part: WinDivert has no per-flow packet window to hand them over
by. Options go to winws2 in a file (@file): z2k's alone are 55 KB, past
a Windows command line.

Both sources, with every layer, verified by winws2's --dry-run under
Wine (tools/winws-dry-run.sh). The DPI page picks the strategies and
switches the detection. proxyFallback and the cutoff probe are said to
be not on Windows yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 18:10:57 +03:00
faumarayandClaude Opus 5.5 0a7d8d99c0 windows: the AmneziaWG tunnel in the release, checked under Wine
package.sh builds the amneziawg component (awg-tunnel.exe, Wintun);
the setup test adds a system-wide profile and checks its tunnel service
registered (Wine's sc has no qc: its registry key), started (the tunnel
runs as a service up to Wintun, which Wine lacks; its log read back),
and removed with its profile. README and notes say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:39:27 +03:00
faumarayandClaude Opus 5.5 5cf3a237e6 windows: AmneziaWG as a system-wide VPN
Each profile without asOutbound is a tunnel service of its own,
AmneziaWGTunnel$<interface>, as amneziawg-windows's client installs one:
amneziawg-go on Wintun, its routes and DNS, and for one peer that takes
everything its firewall blocking what would leave outside the tunnel.
It runs awg-tunnel.exe, amneziawg-windows built from its pinned commit
with a main of ours (its Run(), its log in a file) instead of its
tunnel.dll, beside Wintun's signed DLL (tools/build-amneziawg.sh).

The service writes each profile's .conf below its state root, registers
the tunnel (unrestricted service SID, which its firewall exempts it by),
starts the autostart ones with itself, and removes the tunnels of
profiles gone, and all of them on uninstall. proxy-ctl awg
list|on|off|log, and the app's AmneziaWG page: profiles (a system-wide
one switched on and off, its log), one added from a vpn:// link or a
.conf, or removed.

tools/lib.sh: clone_commit, and fetch_pinned, which fetches in pieces a
download that stalls (some networks cut TLS after about 16 KB, as
wintun.net's here).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:23:11 +03:00
faumarayandClaude Opus 5.5 95ec15e14a windows: autoProxy routes slow sites, and has a page in the app
As upstream's sampler and slow judge: every minute, eleven Clash API
snapshots a second apart; a site whose best direct transfer never beat
slowBelowKiBps three times is owed an exit, and gets the first, in probe
order, that answers it as well as direct does (probe --via); routed
slow, it moves on after crawling twice there, and with no exit left it
stays direct for a TTL. Here the Clash API is always on, so it works
whatever the selection.

The app's autoProxy page: on or off, a site probed or learned, the sites
routed (forget one or all), the exits (bad ones marked), the exclusions
and the slowness threshold. tools/screenshots.sh takes every page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:47:45 +03:00
faumarayandClaude Opus 5.5 694e176353 windows: autoProxy keeps to its exclusions, and its listing to its scope
proxy.autoProxy.exclude is never probed or routed: learn and probe
requests for an excluded host are refused, and a site learned whole
(example.com) routes no excluded name under it (intranet.example.com):
the learned rule skips them.

Without the secrets scope, proxy-ctl proxy auto lists the sites routed
and counts: the hosts probed, those left to zapret and the sites behind
each strike are browsing history, as the logs are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:36:00 +03:00
faumarayandClaude Opus 5.5 5a89b8d11d windows: autoProxy
As upstream's prober: the sites apps reach directly (the Clash API's
direct connections here; upstream's inbound access log) are probed
through each exit, direct first, every interval and at once for
proxy-ctl proxy auto learn. One blocked directly but reached through an
exit is routed through it: its exit's local rule-set, which sing-box
reloads. Upstream's judgement, ported and tested: block pages, the walk
over paths and exits, one exit per network first, strikes against exits
that refuse, a new egress discarding what was learned, rechecks once per
TTL. Blocks zapret can fix stay direct.

The config gains a loopback probe listener per exit (with the hop login,
pinned behind the loopback guard) and the learned rules after the user's.
proxy-ctl proxy auto list|probe|learn|forget|clear over new API requests
(autoProxy scope). Slow sites (slowBelowKiBps) are not routed yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 16:31:29 +03:00
faumarayandClaude Opus 5.5 69e70d6f74 windows: CI gives the SSH test's sshd its privilege separation
The job runs as root in the runner's container, where sshd separates
privileges and needs /var/empty (root's, not writable by others) and the
sshd user; the image lacks the directory, so the test's sshd exited and
an_ssh_tunnel failed. A step makes both. The test now waits for its sshd
and, should it exit, says why.

Checked as root in docker.gitea.com/runner-images:ubuntu-24.04: the
end-to-end tests pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 15:35:49 +03:00
faumarayandClaude Opus 5.5 8d9705cd3a windows: uninstall.cmd leaves the install folder before removing it
Opened from Explorer, its window's working directory is the install
folder, which Windows then cannot remove while the window waits at its
pause: the files went, the folder stayed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:47:45 +03:00
faumarayandClaude Opus 5.5 ae58bd1f12 windows: a setup program, and an uninstall entry in Settings > Apps
ProxySuite-<version>-windows-x64-setup.exe (NSIS, English and Russian):
it unpacks the release into its temporary folder and runs the release's
own proxy-suite-service.exe install from there, as install.cmd does from
the zip (unpacked straight into Program Files, an upgrade would find its
files in use). It refuses 32-bit Windows and anything before 10 1903, and
offers Windows' OpenSSH Client, unchecked, for the SSH tunnel.

install now writes the entry in Settings > Apps (uninstall.cmd; quietly,
the service's uninstall), and uninstall removes it, with WinDivert's
driver service when it is the suite's own.

The release workflow publishes the setup beside the zip. The app's
icon and GPUI's manifest share one resource (llvm-rc for both); the
build scripts' clones retry, and are kept for the next build.
Tested under Wine: tools/wine-setup-test.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:45:09 +03:00
faumarayandClaude Opus 5.5 ae31e499ca windows: the app's whitelist-bypass page, and its icon
A page for whitelist-bypass: on or off; joiners with their state and the
call link to join; creators with theirs, their call link to copy, a new
call, and their login (a cookies export picked from disk, or DION's and
Bitrix's email and password); adding and removing either.

The app carries an icon now (tools/make-icon.py draws it; llvm-rc makes
it the exe's resource 1, where GPUI, Explorer and the Start Menu take it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:21:49 +03:00
faumarayandClaude Opus 5.5 b6e54f963d windows: whitelist-bypass names its files only after plain names
The names were checked only while whitelist-bypass was on, but proxy-ctl
wl names files after them either way: a configuration saved with it off
could name a creator 'C:\...\x' (on Windows a join with an absolute
path replaces the directory) and have the service write or delete a file
of that name as SYSTEM. They are checked on or off now, and every state
file goes through one helper that checks the name again.

Names (of rule sets, groups, profiles, devices, ...) can no longer be
Windows devices either (CON, NUL, COM1, ...): a file named so is the
device.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:05:22 +03:00
faumarayandClaude Opus 5.5 610e36a28b windows: whitelist-bypass
Creators and joiners, built from upstream's tag with upstream's patches
(links and passwords from the environment, never argv), run by the
service as whitelist-bypass.nix runs them: joiners while the proxy runs,
as its outbounds, creators while the suite is on, their logins kept in
a working copy they refresh. proxy-ctl wl list|link|auth|join|new|restart
over new API requests (whitelistBypass scope).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:01:10 +03:00
faumarayandClaude Opus 5.5 1f4fcf540d windows: the programs carry their C runtime
Statically linked (+crt-static): no vcruntime140.dll, so no Visual C++
Redistributable to install first. LNK4099 (the runtime's own PDBs) ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:01:10 +03:00
69 changed files with 6007 additions and 126 deletions

No files matched your search

+20 -6
View File
@@ -1,8 +1,8 @@
name: Windows release name: Windows release
# The Windows port (windows/). On a tag windows-v<version> it builds the release zip and # The Windows port (windows/). On a tag windows-v<version> it builds the setup program and the
# publishes it as a Gitea release, with the notes in windows/release-notes/<version>.md. Run # release zip and publishes them as a Gitea release, with the notes in
# by hand, it only builds: the zip is the run's artifact. # windows/release-notes/<version>.md. Run by hand, it only builds: they are the run's artifact.
# #
# Two jobs, as upstream's dependency updates: the one that runs fetched code (crates, # Two jobs, as upstream's dependency updates: the one that runs fetched code (crates,
# components, wheels, the Nix closure) holds no token that can write. Only the publishing job # components, wheels, the Nix closure) holds no token that can write. Only the publishing job
@@ -75,7 +75,19 @@ jobs:
working-directory: windows working-directory: windows
run: nix develop --command rustup toolchain install run: nix develop --command rustup toolchain install
# The default members: everything the zip carries, not the app (GPUI) yet. # The SSH tunnel's end-to-end test runs an sshd of its own. As root (the job's user in the
# runner's container) sshd separates privileges: it needs its empty, root-owned directory
# and its unprivileged user, which the image does not have.
- name: Test prerequisites
run: |
set -euo pipefail
if [ "$(id -u)" = 0 ]; then
install -d -m 0755 -o root -g root /var/empty
id sshd >/dev/null 2>&1 || useradd --system --no-create-home --home-dir /var/empty --shell /usr/sbin/nologin sshd
fi
# The default members: the service, proxy-ctl, the client and core (the app's crate is
# built by Package).
- name: Test - name: Test
working-directory: windows working-directory: windows
run: nix develop --command cargo test --locked run: nix develop --command cargo test --locked
@@ -90,7 +102,9 @@ jobs:
set -euo pipefail set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
mkdir -p ../release mkdir -p ../release
cp "dist/ProxySuite-$version-windows-x64.zip" "dist/ProxySuite-$version-windows-x64.zip.sha256" ../release/ for f in "ProxySuite-$version-windows-x64-setup.exe" "ProxySuite-$version-windows-x64.zip"; do
cp "dist/$f" "dist/$f.sha256" ../release/
done
if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi
- name: Upload - name: Upload
@@ -150,7 +164,7 @@ jobs:
*) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;; *) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;;
esac esac
for f in release/*.zip release/*.sha256; do for f in release/*.exe release/*.zip release/*.sha256; do
name=$(basename "$f") name=$(basename "$f")
for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
api -X DELETE "$API/releases/$id/assets/$old" >/dev/null api -X DELETE "$API/releases/$id/assets/$old" >/dev/null
+15
View File
@@ -0,0 +1,15 @@
# The Windows programs carry their C runtime: vcruntime140.dll is not on every Windows (the
# Visual C++ Redistributable brings it), and nothing else should have to be installed first.
# (LNK4099: the static runtime's objects name Microsoft's own PDBs, which are not shipped; it
# is about their debug info only.)
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=/ignore:4099"]
# GPUI's build compiles its manifest with embed-resource, which would take the dev shell's RC
# (MinGW's windres, for the C cross-compiler) and make a COFF object of it; with llvm-rc it makes
# a .res, which the linker merges with the app's icon (crates/ps-gui/build.rs). Two resource
# objects it refuses. (A target/ from before this keeps GPUI's object: cargo clean -p gpui-pre.)
# Building on Windows without llvm-rc: set RC_x86_64_pc_windows_msvc=rc.exe in the environment,
# which this does not override.
[env]
RC_x86_64_pc_windows_msvc = "llvm-rc"
+2
View File
@@ -1,2 +1,4 @@
target/ target/
dist/ dist/
# The app logs tools/gui-shot.sh writes beside each shot.
docs/screenshots/*.log
+38
View File
@@ -4992,6 +4992,7 @@ dependencies = [
"indexmap", "indexmap",
"ipnet", "ipnet",
"percent-encoding", "percent-encoding",
"psl",
"regex", "regex",
"serde", "serde",
"serde_json", "serde_json",
@@ -5007,6 +5008,7 @@ dependencies = [
"ps-client", "ps-client",
"ps-core", "ps-core",
"ps-ipc", "ps-ipc",
"rpassword",
"serde_json", "serde_json",
"tokio", "tokio",
] ]
@@ -5064,6 +5066,21 @@ dependencies = [
"zip", "zip",
] ]
[[package]]
name = "psl"
version = "2.1.245"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46cce9bc841c0eeb395275a775d11e3cc91b904e6ab370a9a42369e111b3038e"
dependencies = [
"psl-types",
]
[[package]]
name = "psl-types"
version = "2.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac"
[[package]] [[package]]
name = "pulp" name = "pulp"
version = "0.22.3" version = "0.22.3"
@@ -5623,6 +5640,27 @@ dependencies = [
"memchr", "memchr",
] ]
[[package]]
name = "rpassword"
version = "7.5.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da316a15f47e3d053de9cb2c439650bd8fa4aaeb9365f2e5f27f492ff73c196"
dependencies = [
"libc",
"rtoolbox",
"windows-sys 0.61.2",
]
[[package]]
name = "rtoolbox"
version = "0.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a1efe12a1469752d0e6ff5ebec0b6ef4924cc5c4c71046b0ec730040535819d"
dependencies = [
"libc",
"windows-sys 0.61.2",
]
[[package]] [[package]]
name = "rust-embed" name = "rust-embed"
version = "8.13.0" version = "8.13.0"
+1
View File
@@ -22,6 +22,7 @@ ipnet = "2"
indexmap = { version = "2", features = ["serde"] } indexmap = { version = "2", features = ["serde"] }
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] } tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
clap = { version = "4.6", features = ["derive"] } clap = { version = "4.6", features = ["derive"] }
rpassword = "7"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] } reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
windows-service = "0.8" windows-service = "0.8"
+67 -18
View File
@@ -21,22 +21,35 @@ tray icon) or with `proxy-ctl`, as upstream's is.
| Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend) | | Local proxy | SOCKS5/HTTP on `127.0.0.1:1080` through sing-box (or the hybrid sing-box + XRay backend) |
| Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** | | Outbounds | links (vless/REALITY/TLS, vmess, trojan, shadowsocks, hysteria2, tuic, anytls, naive, socks, http), raw JSON, subscriptions, groups (failover, urltest, selector), chains, pins, route modes, routing rules by site, address, geodata, rule set or **program** |
| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) | | zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) |
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies and nfqws2's own learning of blocked sites | | zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies or [z2k](https://github.com/necronicle/z2k)'s (made by z2k's own generator, per category: YouTube, Discord, QUIC, the RKN list), and upstream's Lua around them: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the extended detector, which also learns sites blocked only some of the time and requests that never get an answer. The server's TLS replies reach the detectors through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen on Windows, as WinDivert cannot hand over a flow's first packets alone. By its detector's verdicts the proxy routes too: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`) |
| tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python | | tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python |
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy | | Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
| AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too | | AmneziaWG | `amneziaWg` profiles, from a `.conf`, an AmneziaVPN `vpn://` link or settings. Without `asOutbound`, a **system-wide VPN**: amneziawg-windows's tunnel (amneziawg-go on Wintun, built from its source) as a Windows service of its own, with its routes, DNS and, for one peer that takes everything, its firewall blocking what leaves outside the tunnel; on and off in the app or `proxy-ctl awg on|off`. As outbounds: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
| WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` | | WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` |
| autoProxy | `proxy.autoProxy`: the sites apps reach directly are probed through each exit in turn (direct first); one blocked directly but reached through an exit is routed through it, as upstream's prober decides (block pages, one exit per network first, strikes against exits that refuse). Blocks zapret can fix stay direct. A site that crawls directly (`slowBelowKiBps`) moves to the first exit that carries it as well as direct does. Its page in the app, or `proxy-ctl proxy auto`, shows, probes, learns and forgets |
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) | | SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** | | TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy | | The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
Not in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service, whitelist-bypass, Not in this release, still to come: Tor's onion service,
the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe. Their options are accepted (they are upstream's), but the
detection and z2k strategies. Their options are accepted (they are upstream's), but the
service says, in its status and in the app, that it does not run them yet. service says, in its status and in the app, that it does not run them yet.
Needs 64-bit Windows 10 (1903 or later) or 11. Needs 64-bit Windows 10 (1903 or later) or 11.
## Screenshots
Taken on Linux against the service with a demo configuration (`tools/screenshots.sh`), so the
DPI bypass, which runs on Windows only, shows as inactive.
| | |
|---|---|
| ![Overview](docs/screenshots/overview.png) | ![DPI bypass](docs/screenshots/dpi-bypass.png) |
| ![Outbounds](docs/screenshots/outbounds.png) | ![autoProxy](docs/screenshots/autoproxy.png) |
| ![AmneziaWG](docs/screenshots/amneziawg.png) | ![Whitelist bypass](docs/screenshots/whitelist-bypass.png) |
| ![Telegram proxy](docs/screenshots/telegram.png) | ![Settings](docs/screenshots/settings.png) |
## What has been verified ## What has been verified
| Part | How | | Part | How |
@@ -51,10 +64,14 @@ Needs 64-bit Windows 10 (1903 or later) or 11.
| SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) | | SSH tunnel | end to end on Linux: an sshd of the test's own, a page through the `ssh -D` listener and through sing-box's SSH outbound, each logging in with the service's copy of the key (`an_ssh_tunnel`) |
| Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) | | Tor | its Windows `tor.exe` (under Wine) accepts the torrc the service writes, bridges and transports included; on Linux the service runs Tor with it and Tor starts bootstrapping (where Tor's relays are blocked, it needs bridges) |
| AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) | | AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) |
| autoProxy | its judgement (upstream's verdicts, walk, exit order, strikes, state) by unit tests; the config with its probe listeners and learned rule-sets accepted by `sing-box check`; on Linux with a local exit: probes through direct and the exit, a learn request, a site an app reached directly queued from the Clash API and probed at the next run, the state and the rule-set files written; a download held to 40 KiB/s seen crawling and moved to the exit. A site blocked here and reached through an exit needs a remote exit, so none was routed that way |
| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made |
| AmneziaWG system-wide | under Wine's service manager (`tools/wine-setup-test.sh`): a profile added registers its tunnel service (program, configuration, dependencies), `proxy-ctl awg on` starts it, and the tunnel runs as a service up to creating the Wintun adapter, which Wine cannot; its log is read back; the service goes with its profile. Traffic through it needs real Windows |
| WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) | | WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) |
| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) | | zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) |
| The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) | | The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) |
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; under Wine it starts and gets as far as drawing text | | The setup program | under Wine (`tools/wine-setup-test.sh`): a silent install puts every file of the release into Program Files and the entry into Settings → Apps, the service runs and answers; the same setup again over the running install upgrades it; the entry's uninstall removes the service, the files and the entry. Its pages (and the Russian ones) not looked at |
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; its icon and manifest in its resources, no C runtime DLL among its imports; under Wine it starts and gets as far as drawing text |
**Not verified: anything that needs real Windows.** Traffic through sing-box on Windows (Wine **Not verified: anything that needs real Windows.** Traffic through sing-box on Windows (Wine
lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows
@@ -64,16 +81,27 @@ there), its tray icon, the system proxy and the Start Menu entry.
## Install ## Install
1. Unzip `ProxySuite-<version>-windows-x64.zip` anywhere. 1. Download `ProxySuite-<version>-windows-x64-setup.exe` and run it. It asks for
2. Run `install.cmd` (it asks for administrator rights). It copies the program to administrator rights; SmartScreen may warn of an unknown publisher (the programs are not
`C:\Program Files\ProxySuite`, registers the **ProxySuite** service (starts at boot), adds signed yet): **More info** → **Run anyway**.
`proxy-ctl` to PATH, starts it, and opens the app; the app starts at every sign-in, in the 2. It installs everything into `C:\Program Files\ProxySuite`, registers the **ProxySuite**
tray (its shield is green while things work, amber when one failed, grey when all is off). service (starts at boot), adds `proxy-ctl` to PATH, starts it, and opens the app; the app
starts at every sign-in, in the tray (its shield is green while things work, amber when one
failed, grey when all is off). One option, unchecked: Windows' **OpenSSH Client**, for the
SSH tunnel only, where it was removed from Windows (Windows 10 1809 and later have it).
3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal: 3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal:
`proxy-ctl status`. `proxy-ctl status`.
To upgrade, unzip the new release and run its `install.cmd`. To remove, run `uninstall.cmd`; Nothing has to be installed first: the C runtime is linked into the programs, and WinDivert,
the configuration and state stay in `%ProgramData%\ProxySuite` until you delete it. wintun, Python, Tor and the rest come with it, as components. For a silent install:
`ProxySuite-<version>-windows-x64-setup.exe /S`.
To upgrade, run the new setup: the settings stay. To remove: **Settings → Apps → Proxy Suite →
Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in
`%ProgramData%\ProxySuite` until you delete it.
Without the setup program: unzip `ProxySuite-<version>-windows-x64.zip` anywhere and run
`install.cmd` (it asks for administrator rights): the same install, from the same files.
Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a
packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first: packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first:
@@ -110,6 +138,24 @@ proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
proxy-ctl config set config.json proxy-ctl config set config.json
proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret
# whitelist-bypass: a joiner here (set "whitelistBypass": { "enable": true,
# "joiners": { "wl": { "platform": "wbstream" } } }), its creator's link from the other end:
proxy-ctl wl join wl "https://..."
proxy-ctl proxy pin wl
# A creator: its login (a cookies export; DION and Bitrix ask for an email and password), its call:
proxy-ctl wl auth laptop cookies.json
proxy-ctl wl link laptop
# AmneziaWG as a system-wide VPN (a profile without asOutbound):
proxy-ctl awg # profiles and their state
proxy-ctl awg on home # start it; off stops it
proxy-ctl awg log home # its tunnel's log
# autoProxy (set "proxy": { "autoProxy": { "enable": true } }):
proxy-ctl proxy auto # what it routed, and where
proxy-ctl proxy auto probe example.com # how a site answers through each exit
proxy-ctl proxy auto learn example.com # probe it now, route it if it needs it
proxy-ctl logs -f # everything, following proxy-ctl logs -f # everything, following
proxy-ctl --help proxy-ctl --help
``` ```
@@ -169,8 +215,9 @@ On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`),
```sh ```sh
cargo test # everything but the app; sing-box and xray from the shell cargo test # everything but the app; sing-box and xray from the shell
python3 -I tools/parity/links.py # link parsing against upstream's Python python3 -I tools/parity/links.py # link parsing against upstream's Python
tools/package.sh # the release zip, in dist/ tools/package.sh # the setup program and the zip, in dist/
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-*-setup.exe dist/ProxySuite-*-x64
``` ```
The app on Linux, against the service on Linux: The app on Linux, against the service on Linux:
@@ -185,10 +232,12 @@ Its Windows build compiles GPUI's shaders with Microsoft's `fxc.exe` under Wine
(`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build (`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build
machine), through a small patch to GPUI's Windows backend (`vendor/gpui-pre-windows`). machine), through a small patch to GPUI's Windows backend (`vendor/gpui-pre-windows`).
The Windows programs are cross-compiled with `cargo xwin` (MSVC target), with the toolchain The Windows programs are cross-compiled with `cargo xwin` (MSVC target, the C runtime linked
in `rust-toolchain.toml`. Design notes: [`DESIGN.md`](DESIGN.md). in: `.cargo/config.toml`), with the toolchain in `rust-toolchain.toml`. The setup program is
NSIS's (`tools/installer.nsi`, `makensis` from the shell): it unpacks the release and runs its
`proxy-suite-service.exe install`, as `install.cmd` does. Design notes: [`DESIGN.md`](DESIGN.md).
Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version` Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version`
in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The
workflow tests, packages and publishes the zip and its `.sha256` with the `RELEASE_TOKEN` workflow tests, packages and publishes the setup program and the zip, each with its `.sha256`, with the `RELEASE_TOKEN`
secret (a token with `write:repository`). Run by hand, it only builds. secret (a token with `write:repository`). Run by hand, it only builds.
+21
View File
@@ -125,6 +125,27 @@
"homepage": "https://github.com/artem-russkikh/wireproxy-awg", "homepage": "https://github.com/artem-russkikh/wireproxy-awg",
"bundled": true, "bundled": true,
"sources": [] "sources": []
},
"zapret2-extras": {
"version": "2026.10.27+z2k.7beb975",
"license": "MIT (z2k, proxy-suite's Lua); MPL-2.0 (the public suffix list)",
"homepage": "https://github.com/necronicle/z2k",
"bundled": true,
"sources": []
},
"amneziawg": {
"version": "0-unstable-2026-08-14+e90531d",
"license": "MIT",
"homepage": "https://github.com/amnezia-vpn/amneziawg-windows",
"bundled": true,
"sources": []
},
"whitelist-bypass": {
"version": "0.4.4",
"license": "MIT",
"homepage": "https://github.com/kulikov0/whitelist-bypass",
"bundled": true,
"sources": []
} }
} }
} }
+98
View File
@@ -235,6 +235,73 @@ pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
*cur = value; *cur = value;
} }
/// whitelist-bypass's platforms, as its options name them.
pub const WL_PLATFORMS: [&str; 5] = ["wbstream", "telemost", "dion", "bitrix", "vk"];
/// A whitelist-bypass joiner or creator (`role`: "joiners" or "creators") on `platform`. A name
/// is one of either: `proxy-ctl wl` takes them by name alone.
pub fn add_wl(c: &mut Value, role: &str, name: &str, platform: &str) -> Result<()> {
if !matches!(role, "joiners" | "creators") {
bail!("a whitelist-bypass role is joiners or creators");
}
if !ps_core::config::path_name_ok(name) {
bail!("a name takes letters, digits, '.', '_' and '-', and no leading dot");
}
if !WL_PLATFORMS.contains(&platform) {
bail!("no platform '{platform}': {}", WL_PLATFORMS.join(", "));
}
if role == "joiners" && platform == "vk" {
bail!("VK has no joiner, only creators");
}
let wl = &c["whitelistBypass"];
if wl["joiners"].get(name).is_some() || wl["creators"].get(name).is_some() {
bail!("'{name}' is taken");
}
set_path(c, &["whitelistBypass", role, name], json!({ "platform": platform }));
Ok(())
}
pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
match c.get_mut("whitelistBypass").and_then(|w| w.get_mut(role)).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
Some(_) => Ok(()),
None => bail!("no whitelist-bypass {} '{name}'", role.trim_end_matches('s')),
}
}
/// An AmneziaWG profile from an AmneziaVPN `vpn://` link or a `.conf`'s text: `kind` "vpn"
/// (system-wide), "userspace" or "singBox" (an outbound of the proxy).
pub fn add_awg_profile(c: &mut Value, name: &str, text: &str, kind: &str) -> Result<()> {
if !ps_core::config::path_name_ok(name) || name.len() > 32 {
bail!("a profile name takes up to 32 letters, digits, '.', '_' and '-', and no leading dot");
}
let text = text.trim();
let mut profile = if text.starts_with("vpn://") {
json!({ "vpn": text })
} else if text.contains("[Interface]") {
json!({ "config": text })
} else {
bail!("paste an AmneziaVPN vpn:// link or a .conf (with its [Interface])");
};
match kind {
"vpn" => {}
"userspace" | "singBox" => profile["asOutbound"] = kind.into(),
_ => bail!("a profile is a system-wide VPN or an outbound (userspace, singBox)"),
}
if c["amneziaWg"]["profiles"].get(name).is_some() {
bail!("there is a profile '{name}' already");
}
set_path(c, &["amneziaWg", "profiles", name], profile);
set_path(c, &["amneziaWg", "enable"], true.into());
Ok(())
}
pub fn remove_awg_profile(c: &mut Value, name: &str) -> Result<()> {
match c.get_mut("amneziaWg").and_then(|w| w.get_mut("profiles")).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
Some(_) => Ok(()),
None => bail!("no AmneziaWG profile '{name}'"),
}
}
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube` /// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
/// beside its release's lists, for `zapret2` beside its strategies' own. /// beside its release's lists, for `zapret2` beside its strategies' own.
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> { pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
@@ -259,6 +326,37 @@ pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn amneziawg_profiles_come_from_links_or_confs() {
let mut c = json!({});
add_awg_profile(&mut c, "home", "vpn://AAAA", "vpn").unwrap();
add_awg_profile(&mut c, "exit", "[Interface]\nPrivateKey = x\n", "userspace").unwrap();
assert_eq!(c["amneziaWg"]["profiles"]["home"], json!({ "vpn": "vpn://AAAA" }));
assert_eq!(c["amneziaWg"]["profiles"]["exit"]["asOutbound"], "userspace");
assert_eq!(c["amneziaWg"]["enable"], true);
assert!(add_awg_profile(&mut c, "home", "vpn://B", "vpn").is_err());
assert!(add_awg_profile(&mut c, "x", "hello", "vpn").is_err());
assert!(add_awg_profile(&mut c, "a/b", "vpn://B", "vpn").is_err());
remove_awg_profile(&mut c, "home").unwrap();
assert!(remove_awg_profile(&mut c, "home").is_err());
}
#[test]
fn whitelist_bypass_entries_are_added_once_and_removed() {
let mut c = json!({});
add_wl(&mut c, "joiners", "wl", "wbstream").unwrap();
add_wl(&mut c, "creators", "laptop", "vk").unwrap();
assert_eq!(c["whitelistBypass"]["joiners"]["wl"], json!({ "platform": "wbstream" }));
assert!(add_wl(&mut c, "creators", "wl", "dion").is_err(), "a name is one of either");
assert!(add_wl(&mut c, "joiners", "phone", "vk").is_err(), "VK has no joiner");
assert!(add_wl(&mut c, "joiners", "phone", "zoom").is_err());
assert!(add_wl(&mut c, "joiners", "../x", "wbstream").is_err());
assert!(add_wl(&mut c, "joiners", "CON", "wbstream").is_err());
remove_wl(&mut c, "joiners", "wl").unwrap();
assert!(remove_wl(&mut c, "joiners", "wl").is_err());
assert_eq!(c["whitelistBypass"]["creators"]["laptop"]["platform"], "vk");
}
#[test] #[test]
fn outbounds_are_added_once_and_removed() { fn outbounds_are_added_once_and_removed() {
let mut c = json!({}); let mut c = json!({});
+1
View File
@@ -15,5 +15,6 @@ thiserror.workspace = true
percent-encoding.workspace = true percent-encoding.workspace = true
ipnet.workspace = true ipnet.workspace = true
indexmap.workspace = true indexmap.workspace = true
psl = "2"
[dev-dependencies] [dev-dependencies]
@@ -1,21 +1,47 @@
//! For tools/winws-dry-run.sh: winws2's arguments as the service builds them, one per line. //! For tools/winws-dry-run.sh: winws2's arguments as the service builds them, one per line.
//! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>` //! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>
//! [<extras dir> <extras dir as Windows sees it> <extras dir as Cygwin sees it> keenetic|z2k]`
use ps_core::config::Zapret2; use ps_core::config::{StrategySource, Zapret2};
use ps_core::zapret2::{Paths, args, keenetic}; use ps_core::zapret2::{Extras, Paths, args, keenetic, z2k};
fn main() { fn main() {
let a: Vec<String> = std::env::args().collect(); let a: Vec<String> = std::env::args().collect();
let conf = std::fs::read_to_string(std::path::Path::new(&a[1]).join("keenetic").join("nfqws2.conf")).unwrap(); let conf = std::fs::read_to_string(std::path::Path::new(&a[1]).join("keenetic").join("nfqws2.conf")).unwrap();
let (comp, state) = (&a[2], &a[3]); let (comp, state) = (&a[2], &a[3]);
let source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap(); let mut z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
let mut source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap();
let mut extras = None;
if let [_, _, _, _, dir, win, cyg, kind] = &a[..] {
let read = |f: &str| std::fs::read_to_string(std::path::Path::new(dir).join("z2k").join(f)).unwrap();
if kind == "z2k" {
z.strategy_source = StrategySource::Z2k;
source = z2k(
&read("profiles.plain"),
&read("profiles.learn"),
&read("blobs"),
&read("ports"),
&format!("{cyg}z2k"),
&format!("{cyg}z2k/root"),
&format!("{cyg}z2k/files/lua/"),
)
.unwrap();
}
let state_cyg = format!("/cygdrive/{}", state.replace(':', "").replace('\\', "/").to_lowercase());
extras = Some(Extras {
lua: format!("{win}lua\\"),
z2k_lua: format!("{win}z2k\\files\\lua\\"),
auto_lua: format!("{state_cyg}learned/zapret-hosts-auto.txt"),
exclude_lua: vec![format!("{state_cyg}zapret-hosts-user-exclude.txt")],
});
}
let paths = Paths { let paths = Paths {
lua: format!("{comp}lua\\"), lua: format!("{comp}lua\\"),
user: format!("{state}zapret-hosts-user.txt"), user: format!("{state}zapret-hosts-user.txt"),
exclude: format!("{state}zapret-hosts-user-exclude.txt"), exclude: format!("{state}zapret-hosts-user-exclude.txt"),
auto: format!("{state}learned\\zapret-hosts-auto.txt"), auto: format!("{state}learned\\zapret-hosts-auto.txt"),
extras,
}; };
let z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
for arg in args(&z, &source, &paths, false).unwrap() { for arg in args(&z, &source, &paths, false).unwrap() {
println!("{arg}"); println!("{arg}");
} }
+865
View File
@@ -0,0 +1,865 @@
//! autoProxy's judgement, as upstream decides it: what one fetch through an exit says
//! (proxy_ctl.py's `proxy auto probe`), the walk over the exits for a destination, the order
//! they are walked in (autoproxy-rounds.jq), the strikes against exits a destination refused
//! (autoproxy-strike.jq), what is remembered (autoproxy-run.template.sh, autoproxy-edit.jq)
//! and the rule-sets sing-box takes it from (autoproxy-render.template.sh).
//!
//! The fetches themselves are the service's; this is the deciding, so it is tested here.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::LazyLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::links::subscription::{nearness, url_parts};
/// The exit that is this host: always the first.
pub const DIRECT: &str = "direct";
/// The paths a destination is probed at: the page, then robots.txt, which some sites serve
/// where their front page refuses a client that is not a browser.
pub const PATHS: [&str; 2] = ["/", "/robots.txt"];
/// One fetch through one exit, at the first hop that is not a same-site redirect.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fetch {
/// The answer's status; none when no answer came (TLS or the connection failed first).
pub status: Option<u16>,
/// The PROBE_BLOCK_PAGES name a refusal's page matched, "" for none.
#[serde(default)]
pub block: String,
/// A redirect's Location.
#[serde(default)]
pub location: String,
/// Bytes read of the body (at most what was read to judge it).
#[serde(default)]
pub bytes: u64,
/// Why no answer came.
#[serde(default)]
pub error: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Judgement {
/// Content.
Ok,
/// Failed before the origin spoke: the censor's doing, zapret's job.
Dead,
/// The site's security layer refused this address: an exit past it helps.
Wall,
/// The origin answered and refused: another exit can fix it.
Blocked,
}
/// Block pages, by name: (kind, pattern over a refusal's headers and the first 8 KiB of its
/// body). "address": the address itself was refused, so an exit that gets past it reaches the
/// site; "geo": its country was, which is an ordinary refusal.
static BLOCK_PAGES: LazyLock<Vec<(&str, &str, Regex)>> = LazyLock::new(|| {
[
("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."),
("cloudfront-geo", "geo", r"(?i)configured to block access from your country"),
("cloudflare", "address", r#"(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b"#),
("cloudflare-geo", "geo", r#"(?i)cf-error-code">1009<|error code: 1009\b"#),
("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"),
("imperva", "address", r"(?i)Incapsula incident ID"),
("datadome", "address", r"(?im)^x-datadome:"),
]
.into_iter()
.map(|(name, kind, re)| (name, kind, Regex::new(re).expect("a valid pattern")))
.collect()
});
static BLOCK_REDIRECT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)unavailable|not-available|blocked|geo|region|restricted").unwrap());
static HOST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$").unwrap());
/// A host name autoProxy probes or routes: letters, digits, dots, '_' and '-', with a TLD.
pub fn host_ok(host: &str) -> bool {
host.len() <= 253 && HOST.is_match(host)
}
/// The name of the block page a refusal (`status` 4xx or 5xx) shows, "" for none. `head` is
/// its headers as received, `body` its first bytes.
pub fn block_page(status: u16, head: &str, body: &[u8]) -> String {
if !(400..600).contains(&status) {
return String::new();
}
let body: String = body.iter().take(8192).map(|&b| b as char).collect();
let text = format!("{head}\n\n{body}\n\n");
BLOCK_PAGES.iter().find(|(_, _, re)| re.is_match(&text)).map(|(name, _, _)| (*name).to_owned()).unwrap_or_default()
}
/// The last two labels: a redirect is followed only within them.
pub fn site(url: &str) -> String {
let host = url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_default();
let labels: Vec<&str> = host.split('.').collect();
labels[labels.len().saturating_sub(2)..].join(".")
}
/// Whether a Location names this host or its LAN (localhost, or an address literal in any of
/// the forms curl takes): never followed.
pub fn local_target(url: &str) -> bool {
match url_parts::split(url) {
Ok(u) => nearness(u.hostname.as_deref()) > 0,
Err(_) => true,
}
}
/// Whether a redirect's target says the content is refused (a "not available" page).
pub fn redirect_is_block(location: &str) -> bool {
BLOCK_REDIRECT.is_match(location)
}
fn http_ok(f: &Fetch) -> bool {
match f.status {
Some(s) if (200..300).contains(&s) || s == 401 || s == 404 => true,
Some(s) if (300..400).contains(&s) => !redirect_is_block(&f.location),
_ => false,
}
}
pub fn judge(f: &Fetch) -> Judgement {
if f.status.is_none() {
return Judgement::Dead;
}
if http_ok(f) {
return Judgement::Ok;
}
let address = BLOCK_PAGES.iter().any(|(name, kind, _)| *name == f.block && *kind == "address");
if address { Judgement::Wall } else { Judgement::Blocked }
}
/// Content; or, where direct hit a wall, any answer from the origin past it.
pub fn reaches(direct: Judgement, j: Judgement) -> bool {
j == Judgement::Ok || (direct == Judgement::Wall && j == Judgement::Blocked)
}
/// "ok": direct gets it. "destination": an exit reaches what direct does not, past a refusal:
/// route through it. "censor": direct dies on the way while an exit reaches it, which zapret
/// is for: it stays direct. "both-fail" and "unreachable": no exit helps.
pub fn verdict(direct: &Fetch, via: &Fetch) -> &'static str {
let d = judge(direct);
if d == Judgement::Ok {
return "ok";
}
if reaches(d, judge(via)) {
return if d == Judgement::Dead { "censor" } else { "destination" };
}
if d == Judgement::Dead { "unreachable" } else { "both-fail" }
}
pub fn verdict_text(verdict: &str, exit: Option<&str>) -> String {
match verdict {
"ok" => "reachable directly - nothing to do".into(),
"destination" => format!("destination-side block - route via {}", exit.unwrap_or("proxy")),
"censor" => "censor-side block - zapret's territory, not proxied".into(),
"both-fail" => "fails through every egress - not an egress problem".into(),
"unreachable" => "no egress reaches it at all".into(),
_ => "inconclusive".into(),
}
}
pub fn describe(f: &Fetch) -> String {
let Some(status) = f.status else {
return if f.error.is_empty() { "no answer".into() } else { format!("no answer ({})", f.error) };
};
let mut text = format!("{status}, {} bytes", f.bytes);
if !f.block.is_empty() {
text.push_str(&format!(", {} page", f.block));
}
if !f.location.is_empty() {
text.push_str(&format!(" -> {}", f.location));
}
text
}
/// One request of a walk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
pub tag: String,
pub path: String,
pub fetch: Fetch,
pub judgement: Judgement,
}
/// What a probe found: the verdict, the exit that reached it (none for "ok" and the failures),
/// the path it was judged on, and every request made.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Probe {
pub domain: String,
pub verdict: String,
pub exit: Option<String>,
pub path: String,
pub rows: Vec<Row>,
}
/// Walks the exits (`exits[0]` is direct) and stops at the first that reaches `domain`: gets
/// content, or gets past a wall direct hit. `keep_going` still tries the rest, keeping that
/// first one. `fetch(tag, path)` is one request through one exit.
pub async fn walk<F, Fut>(domain: &str, exits: &[String], paths: &[&str], keep_going: bool, mut fetch: F) -> Probe
where
F: FnMut(String, String) -> Fut,
Fut: Future<Output = Fetch>,
{
let mut p = Probe { domain: domain.to_owned(), ..Default::default() };
let Some((direct_tag, others)) = exits.split_first() else {
p.verdict = "error".into();
return p;
};
let mut first_direct: Option<Fetch> = None;
for path in paths {
let direct = fetch(direct_tag.clone(), (*path).to_owned()).await;
let dj = judge(&direct);
p.rows.push(Row { tag: direct_tag.clone(), path: (*path).to_owned(), fetch: direct.clone(), judgement: dj });
first_direct.get_or_insert_with(|| direct.clone());
if dj == Judgement::Ok && p.verdict.is_empty() {
p.verdict = "ok".into();
p.path = (*path).to_owned();
if !keep_going {
return p;
}
}
for tag in others {
let via = fetch(tag.clone(), (*path).to_owned()).await;
let j = judge(&via);
p.rows.push(Row { tag: tag.clone(), path: (*path).to_owned(), fetch: via.clone(), judgement: j });
if reaches(dj, j) && p.verdict.is_empty() {
p.verdict = verdict(&direct, &via).into();
p.exit = Some(tag.clone());
p.path = (*path).to_owned();
if !keep_going {
return p;
}
}
}
}
if p.verdict.is_empty() {
let dead = first_direct.as_ref().is_none_or(|f| judge(f) == Judgement::Dead);
p.verdict = if dead { "unreachable" } else { "both-fail" }.into();
p.path = paths.first().map(|s| (*s).to_owned()).unwrap_or_default();
}
p
}
/// `--via`: can `via` carry what direct reaches? It must get content on some path and fail on
/// none where direct succeeds. Verdict "ok" or "blocked".
pub async fn stand_in<F, Fut>(domain: &str, via: &str, paths: &[&str], mut fetch: F) -> Probe
where
F: FnMut(String, String) -> Fut,
Fut: Future<Output = Fetch>,
{
let mut p = Probe {
domain: domain.to_owned(),
verdict: "ok".into(),
exit: Some(via.to_owned()),
path: paths.first().map(|s| (*s).to_owned()).unwrap_or_default(),
rows: Vec::new(),
};
let mut got = false;
for path in paths {
let direct = fetch(DIRECT.to_owned(), (*path).to_owned()).await;
let through = fetch(via.to_owned(), (*path).to_owned()).await;
let (dj, vj) = (judge(&direct), judge(&through));
p.rows.push(Row { tag: DIRECT.into(), path: (*path).to_owned(), fetch: direct, judgement: dj });
p.rows.push(Row { tag: via.to_owned(), path: (*path).to_owned(), fetch: through, judgement: vj });
got |= vj == Judgement::Ok;
if dj == Judgement::Ok && vj != Judgement::Ok {
p.verdict = "blocked".into();
}
}
if !got {
p.verdict = "blocked".into();
}
p
}
/// The registrable domain of `host` (its site: example.co.uk, foo.workers.dev), by the public
/// suffix list with its private section; none for a public suffix itself, or a bare label.
pub fn registrable(host: &str) -> Option<String> {
let host = host.trim_end_matches('.').to_ascii_lowercase();
if !host.contains('.') {
return None;
}
let domain = psl::domain_str(&host)?;
Some(domain.to_owned())
}
// --- the state -----------------------------------------------------------------------------
/// A destination routed through an exit: probed blocked directly ("destination"), or
/// crawling directly ("slow").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Route {
pub verdict: String,
pub exit: String,
pub host: String,
#[serde(default)]
pub path: String,
pub at: u64,
/// "slow": times it crawled on its exit since it last did not; two move it on.
#[serde(default, skip_serializing_if = "is_zero")]
pub bad: u32,
/// "slow": the exits tried, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tried: Vec<String>,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
/// What the transfer sampler saw: a host's best connection through an exit, crawling
/// (`slow`) or not, and its fastest second.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation {
pub domain: String,
pub host: String,
pub exit: String,
pub slow: bool,
pub peak: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowHits {
pub n: u32,
pub first: u64,
}
/// A site owed an exit for crawling directly, and the exits tried for it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowWant {
pub host: String,
#[serde(default)]
pub tried: Vec<String>,
}
/// What the last probe of a host found.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HostVerdict {
pub domain: String,
pub verdict: String,
#[serde(default)]
pub exit: Option<String>,
pub at: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Strike {
pub why: String,
pub at: u64,
}
/// An exit: where it leaves from (its network, by AS), and the destinations that refused it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ExitInfo {
pub ip: Option<String>,
pub asn: Option<String>,
pub at: u64,
pub strikes: BTreeMap<String, Strike>,
pub bad: bool,
pub bad_by: Vec<String>,
}
/// A host dialled directly, not yet probed: how often, and since when.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Queued {
pub domain: String,
pub hits: u64,
pub first: u64,
}
/// state.json.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct State {
/// This host's public address the verdicts are about.
pub egress: Option<String>,
/// Registrable domain -> the exit it is routed through.
pub domains: BTreeMap<String, Route>,
pub hosts: BTreeMap<String, HostVerdict>,
pub exits: BTreeMap<String, ExitInfo>,
pub backlog: BTreeMap<String, Queued>,
pub last_run: u64,
/// Hosts seen crawling directly, within a day.
pub slow_hits: BTreeMap<String, SlowHits>,
/// Sites owed an exit for crawling, by registrable domain.
pub slow_want: BTreeMap<String, SlowWant>,
/// Sites no exit carried better, left direct until then.
pub slow_skip: BTreeMap<String, u64>,
}
/// Most entries the backlog keeps: every distinct name dialled is one.
const BACKLOG_MAX: usize = 5000;
impl State {
/// `domain` refused `tags` at `now` (`why`: "wall:<page>", "refused" or "slow"), and every
/// strike older than `ttl` goes. A domain counts once per exit; two make an exit bad.
pub fn strike(&mut self, tags: &[String], domain: &str, why: &str, now: u64, ttl: u64) {
for t in tags {
self.exits.entry(t.clone()).or_default().strikes.insert(domain.to_owned(), Strike { why: why.to_owned(), at: now });
}
for e in self.exits.values_mut() {
e.strikes.retain(|_, s| s.at + ttl > now);
rebad(e);
}
}
/// `domain` back to direct, every verdict and strike about it gone.
pub fn forget(&mut self, domain: &str) {
self.domains.remove(domain);
self.hosts.retain(|_, h| h.domain != domain);
self.backlog.retain(|_, q| q.domain != domain);
self.slow_want.remove(domain);
self.slow_skip.remove(domain);
for e in self.exits.values_mut() {
if e.strikes.remove(domain).is_some() {
rebad(e);
}
}
}
/// Everything learned forgotten; what each exit is, the backlog and the egress stay.
pub fn clear(&mut self) {
self.domains.clear();
self.hosts.clear();
self.slow_want.clear();
self.slow_skip.clear();
for e in self.exits.values_mut() {
e.strikes.clear();
rebad(e);
}
}
/// A new public address: every verdict was about the old one.
pub fn new_egress(&mut self, egress: &str) {
*self = State { egress: Some(egress.to_owned()), backlog: std::mem::take(&mut self.backlog), last_run: self.last_run, ..Default::default() };
}
/// What probing `host` (of `domain`) found. A route applies to the whole domain (blocks
/// are drawn around sites); a verdict to the host. Exits refused on the path the winner
/// reached are struck: by a block page, or by the origin where the winner got content.
pub fn record(&mut self, domain: &str, host: &str, p: &Probe, now: u64, ttl: u64) {
if p.verdict == "destination"
&& let Some(exit) = &p.exit
{
self.domains.insert(
domain.to_owned(),
Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now, bad: 0, tried: Vec::new() },
);
}
let exit = if p.verdict == "destination" { p.exit.clone() } else { None };
self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now });
self.backlog.remove(host);
let Some(winner) = &p.exit else { return };
let won = p.rows.iter().find(|r| &r.tag == winner && r.path == p.path).map(|r| r.judgement);
let mut struck: BTreeMap<String, String> = BTreeMap::new();
for r in p.rows.iter().filter(|r| r.path == p.path && r.tag != DIRECT && &r.tag != winner) {
let why = match r.judgement {
Judgement::Wall => format!("wall:{}", r.fetch.block),
Judgement::Blocked if won == Some(Judgement::Ok) => "refused".into(),
_ => continue,
};
struck.entry(r.tag.clone()).or_insert(why);
}
for (tag, why) in struck {
self.strike(&[tag], domain, &why, now, ttl);
}
}
/// Hosts dialled directly since the last run (`counts`: host -> (domain, hits)) into the
/// backlog, skipping those a route covers or a verdict within the TTL judged; entries past
/// the TTL, or covered since, go; the most dialled 5000 stay.
pub fn queue(&mut self, counts: &BTreeMap<String, (String, u64)>, now: u64, ttl: u64) {
self.last_run = now;
self.hosts.retain(|_, h| h.at + ttl > now);
for (host, (domain, hits)) in counts {
if self.domains.contains_key(domain) || self.hosts.get(host).is_some_and(|h| h.at + ttl > now) {
continue;
}
let q = self.backlog.entry(host.clone()).or_insert(Queued { domain: domain.clone(), hits: 0, first: now });
q.hits += hits;
}
let domains = &self.domains;
self.backlog.retain(|_, q| q.first + ttl > now && !domains.contains_key(&q.domain));
if self.backlog.len() > BACKLOG_MAX {
let mut v: Vec<(String, Queued)> = std::mem::take(&mut self.backlog).into_iter().collect();
v.sort_by_key(|a| std::cmp::Reverse(a.1.hits));
v.truncate(BACKLOG_MAX);
self.backlog = v.into_iter().collect();
}
}
/// The backlog to probe, most dialled first: (domain, host).
pub fn backlog_order(&self, now: u64, ttl: u64) -> Vec<(String, String)> {
let mut v: Vec<(&String, &Queued)> = self
.backlog
.iter()
.filter(|(h, q)| !self.domains.contains_key(&q.domain) && self.hosts.get(*h).is_none_or(|v| v.at + ttl <= now))
.collect();
v.sort_by(|a, b| b.1.hits.cmp(&a.1.hits).then_with(|| a.0.cmp(b.0)));
v.into_iter().map(|(h, q)| (q.domain.clone(), h.clone())).collect()
}
/// Routes to probe again, once per TTL: (domain, host, exit).
pub fn due(&self, now: u64, ttl: u64) -> Vec<(String, String, String)> {
self.domains
.iter()
.filter(|(_, r)| r.verdict == "destination" && now.saturating_sub(r.at) >= ttl)
.map(|(d, r)| (d.clone(), r.host.clone(), r.exit.clone()))
.collect()
}
}
impl State {
/// What the sampler saw, folded in (autoproxy-slow-judge.jq). `hits` crawls on direct
/// within a day make a site owed an exit (`slow_want`); once routed it is judged on that
/// exit alone: a fast transfer keeps it, two slow ones move it to the next. Never moved:
/// censor verdicts (zapret's) and sites skipped for a while.
pub fn judge_slow(&mut self, obs: &[Observation], now: u64, hits: u32) {
self.slow_hits.retain(|_, h| h.first + 86400 > now);
for x in obs {
if let Some(r) = self.domains.get_mut(&x.domain)
&& r.verdict == "slow"
{
if x.exit != r.exit {
} else if x.slow {
r.bad += 1;
} else {
r.bad = 0;
r.at = now;
}
continue;
}
let skip = self.domains.contains_key(&x.domain)
|| x.exit != DIRECT
|| !x.slow
|| self.slow_want.contains_key(&x.domain)
|| self.slow_skip.get(&x.domain).is_some_and(|u| *u > now)
|| self.hosts.get(&x.host).is_some_and(|h| h.verdict == "censor");
if skip {
continue;
}
let h = self.slow_hits.entry(x.host.clone()).or_insert(SlowHits { n: 0, first: now });
h.n += 1;
if h.n >= hits {
self.slow_hits.remove(&x.host);
self.slow_want.insert(x.domain.clone(), SlowWant { host: x.host.clone(), tried: Vec::new() });
}
}
let moved: Vec<(String, Route)> =
self.domains.iter().filter(|(_, r)| r.verdict == "slow" && r.bad >= 2).map(|(d, r)| (d.clone(), r.clone())).collect();
for (d, r) in moved {
self.domains.remove(&d);
let tried = if r.tried.is_empty() { vec![r.exit.clone()] } else { r.tried.clone() };
self.slow_want.insert(d, SlowWant { host: r.host, tried });
}
self.slow_skip.retain(|_, until| *until > now);
if self.slow_hits.len() > 5000 {
let mut v: Vec<(String, SlowHits)> = std::mem::take(&mut self.slow_hits).into_iter().collect();
v.sort_by_key(|(_, h)| std::cmp::Reverse(h.n));
v.truncate(5000);
self.slow_hits = v.into_iter().collect();
}
while self.slow_want.len() > 500 {
let last = self.slow_want.keys().next_back().cloned().unwrap();
self.slow_want.remove(&last);
}
}
/// A crawling site's next exit found: routed through it.
pub fn route_slow(&mut self, domain: &str, host: &str, exit: &str, tried: Vec<String>, now: u64) {
self.domains.insert(
domain.to_owned(),
Route { verdict: "slow".into(), exit: exit.to_owned(), host: host.to_owned(), path: String::new(), at: now, bad: 0, tried },
);
self.slow_want.remove(domain);
}
/// No exit carries a crawling site better: left direct for `ttl`.
pub fn skip_slow(&mut self, domain: &str, now: u64, ttl: u64) {
self.slow_skip.insert(domain.to_owned(), now + ttl);
self.slow_want.remove(domain);
}
}
/// From Clash API `/connections` snapshots a second apart: per host and exit that moved at
/// least `min` bytes, its best connection's fastest second, and whether it never beat `below`
/// in any second (paced streams burst, so they read fast). Probe and test listeners skipped;
/// `chains[0]` is the exit that carried it. (autoproxy-slow-sample.jq)
pub fn sample_transfers(snapshots: &[Value], min: u64, below: u64) -> Vec<(String, String, bool, u64)> {
// id -> (host, exit, [download per snapshot])
let mut seen: BTreeMap<String, (String, String, Vec<Option<u64>>)> = BTreeMap::new();
for (i, snap) in snapshots.iter().enumerate() {
for c in snap["connections"].as_array().into_iter().flatten() {
let kind = c["metadata"]["type"].as_str().unwrap_or("");
if kind.contains("/probe-in-") || kind.ends_with("/proxy-suite-test-in") {
continue;
}
let Some(id) = c["id"].as_str() else { continue };
let host = c["metadata"]["host"].as_str().unwrap_or("").to_owned();
let exit = c["chains"][0].as_str().unwrap_or("").to_owned();
let e = seen.entry(id.to_owned()).or_insert_with(|| (host, exit, vec![None; snapshots.len()]));
e.2[i] = c["download"].as_u64();
}
}
let mut best: BTreeMap<(String, String), (u64, u64)> = BTreeMap::new();
for (host, exit, d) in seen.into_values() {
let deltas: Vec<u64> = d.windows(2).filter_map(|w| Some(w[1]?.saturating_sub(w[0]?))).collect();
let (total, peak) = (deltas.iter().sum::<u64>(), deltas.iter().copied().max().unwrap_or(0));
if host.is_empty() || exit.is_empty() || deltas.is_empty() || total < min {
continue;
}
let b = best.entry((host, exit)).or_insert((0, 0));
if peak >= b.0 {
*b = (peak, total);
}
}
best.into_iter().map(|((host, exit), (peak, _))| (host, exit, peak < below, peak)).collect()
}
fn rebad(e: &mut ExitInfo) {
e.bad = e.strikes.len() >= 2;
let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect();
s.sort_by_key(|(_, v)| v.at);
e.bad_by = s.into_iter().map(|(d, v)| format!("{d} {}", v.why)).collect();
}
/// The probe order of the exits after direct: round 1, one exit per network (AS); round 2,
/// walked only when round 1 all refused, the rest; bad exits never take a network's round-1
/// place and go last. Also the whole order.
pub fn rounds(exits: &[String], state: &State) -> (Vec<String>, Vec<String>, Vec<String>) {
let info = |t: &str| state.exits.get(t);
let bad = |t: &str| info(t).is_some_and(|e| e.bad);
let mut ordered: Vec<String> = exits.iter().filter(|t| t.as_str() != DIRECT && !bad(t)).cloned().collect();
ordered.extend(exits.iter().filter(|t| t.as_str() != DIRECT && bad(t)).cloned());
let (mut r1, mut r2) = (Vec::new(), Vec::new());
let mut seen = BTreeSet::new();
for t in &ordered {
let asn = info(t).and_then(|e| e.asn.clone()).unwrap_or_default();
if bad(t) {
r2.push(t.clone());
} else if asn.is_empty() || seen.insert(asn) {
r1.push(t.clone());
} else {
r2.push(t.clone());
}
}
(r1, r2, ordered)
}
/// The sing-box rule-set (source format) of the domains routed through `exit`.
pub fn rule_set(state: &State, exit: &str) -> Value {
let domains: Vec<&String> = state.domains.iter().filter(|(_, r)| r.exit == exit).map(|(d, _)| d).collect();
if domains.is_empty() {
json!({ "version": 1, "rules": [] })
} else {
json!({ "version": 1, "rules": [{ "domain_suffix": domains }] })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ok() -> Fetch {
Fetch { status: Some(200), bytes: 1000, ..Default::default() }
}
fn dead() -> Fetch {
Fetch { status: None, error: "reset".into(), ..Default::default() }
}
fn refused() -> Fetch {
Fetch { status: Some(403), ..Default::default() }
}
fn wall() -> Fetch {
Fetch { status: Some(403), block: "cloudflare".into(), ..Default::default() }
}
/// Runs a future that never waits (the fetches here answer at once).
fn now<F: Future>(f: F) -> F::Output {
let mut f = std::pin::pin!(f);
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
match f.as_mut().poll(&mut cx) {
std::task::Poll::Ready(v) => v,
std::task::Poll::Pending => panic!("a test fetch waited"),
}
}
fn exits(tags: &[&str]) -> Vec<String> {
tags.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn judgements_follow_upstream() {
assert_eq!(judge(&ok()), Judgement::Ok);
assert_eq!(judge(&Fetch { status: Some(404), ..Default::default() }), Judgement::Ok);
assert_eq!(judge(&Fetch { status: Some(302), location: "https://x.example/why-not-available".into(), ..Default::default() }), Judgement::Blocked);
assert_eq!(judge(&Fetch { status: Some(301), location: "https://www.x.example/".into(), ..Default::default() }), Judgement::Ok);
assert_eq!(judge(&dead()), Judgement::Dead);
assert_eq!(judge(&wall()), Judgement::Wall);
assert_eq!(judge(&Fetch { status: Some(403), block: "cloudflare-geo".into(), ..Default::default() }), Judgement::Blocked);
assert_eq!(verdict(&refused(), &ok()), "destination");
assert_eq!(verdict(&dead(), &ok()), "censor");
assert_eq!(verdict(&wall(), &refused()), "destination");
assert_eq!(verdict(&dead(), &dead()), "unreachable");
assert_eq!(verdict(&refused(), &refused()), "both-fail");
}
#[test]
fn block_pages_are_recognised() {
assert_eq!(block_page(403, "HTTP/1.1 403\r\nserver: cloudflare\r\ncf-mitigated: challenge\r\n", b""), "cloudflare");
assert_eq!(block_page(403, "", b"<span class=\"cf-error-code\">1009</span>"), "cloudflare-geo");
assert_eq!(block_page(403, "Server: CloudFront\r\n", b"<h1>Request blocked.</h1>"), "aws-waf");
assert_eq!(block_page(200, "x-datadome: 1\r\n", b""), "");
}
#[test]
fn a_walk_stops_at_the_first_exit_that_reaches() {
let answers = |tag: &str, _path: &str| match tag {
"direct" => refused(),
"a" => refused(),
_ => ok(),
};
let p = now(walk("x.example", &exits(&["direct", "a", "b", "c"]), &PATHS, false, |t: String, p: String| std::future::ready(answers(&t, &p))));
assert_eq!(p.verdict, "destination");
assert_eq!(p.exit.as_deref(), Some("b"));
assert_eq!(p.rows.len(), 3, "c is never asked");
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(ok())));
assert_eq!((p.verdict.as_str(), p.rows.len()), ("ok", 1));
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(dead())));
assert_eq!((p.verdict.as_str(), p.rows.len()), ("unreachable", 4));
}
#[test]
fn robots_txt_can_decide_what_the_page_did_not() {
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |t: String, path: String| std::future::ready(match (t.as_str(), path.as_str()) {
("direct", _) => refused(),
("a", "/") => refused(),
_ => ok(),
})));
assert_eq!((p.verdict.as_str(), p.exit.as_deref(), p.path.as_str()), ("destination", Some("a"), "/robots.txt"));
}
#[test]
fn a_stand_in_must_carry_everything_direct_gets() {
let p = now(stand_in("x.example", "a", &PATHS, |t: String, path: String| std::future::ready(if t == "a" && path == "/robots.txt" { refused() } else { ok() })));
assert_eq!(p.verdict, "blocked");
let p = now(stand_in("x.example", "a", &PATHS, |_: String, _: String| std::future::ready(ok())));
assert_eq!(p.verdict, "ok");
}
#[test]
fn recording_routes_the_domain_and_strikes_who_refused() {
let mut s = State::default();
let p = now(walk("www.x.example", &exits(&["direct", "a", "b"]), &PATHS, false, |t: String, _: String| std::future::ready(match t.as_str() {
"a" => wall(),
"b" => ok(),
_ => refused(),
})));
s.record("x.example", "www.x.example", &p, 100, 1000);
assert_eq!(s.domains["x.example"].exit, "b");
assert_eq!(s.exits["a"].strikes["x.example"].why, "wall:cloudflare");
assert!(!s.exits["a"].bad);
s.strike(&exits(&["a"]), "y.example", "refused", 200, 1000);
assert!(s.exits["a"].bad, "two domains make an exit bad");
assert_eq!(s.exits["a"].bad_by, ["x.example wall:cloudflare", "y.example refused"]);
s.strike(&[], "", "", 1150, 1000);
assert!(!s.exits["a"].bad, "a strike past the TTL stops counting");
s.forget("x.example");
assert!(s.domains.is_empty() && s.hosts.is_empty());
assert_eq!(rule_set(&s, "b"), json!({ "version": 1, "rules": [] }));
}
#[test]
fn rounds_take_one_exit_per_network_first_and_bad_ones_last() {
let mut s = State::default();
for (t, asn) in [("a", "AS1"), ("b", "AS1"), ("c", "AS2")] {
s.exits.insert(t.into(), ExitInfo { asn: Some(asn.into()), ..Default::default() });
}
s.exits.insert("d".into(), ExitInfo { bad: true, ..Default::default() });
let (r1, r2, ordered) = rounds(&exits(&["direct", "d", "a", "b", "c", "e"]), &s);
assert_eq!(r1, ["a", "c", "e"]);
assert_eq!(r2, ["b", "d"]);
assert_eq!(ordered, ["a", "b", "c", "e", "d"]);
}
#[test]
fn the_backlog_skips_what_is_known_and_keeps_counting() {
let mut s = State::default();
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0, bad: 0, tried: Vec::new() });
let counts: BTreeMap<String, (String, u64)> = [
("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)),
("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)),
("api.other.example".to_owned(), ("other.example".to_owned(), 7)),
]
.into();
s.queue(&counts, 10, 1000);
s.queue(&counts, 20, 1000);
assert_eq!(s.backlog.len(), 2);
assert_eq!(s.backlog["cdn.new.example"].hits, 4);
assert_eq!(s.backlog_order(20, 1000)[0], ("other.example".to_owned(), "api.other.example".to_owned()));
s.new_egress("203.0.113.9");
assert!(s.domains.is_empty());
assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address");
}
fn obs(d: &str, exit: &str, slow: bool) -> Observation {
Observation { domain: d.into(), host: format!("www.{d}"), exit: exit.into(), slow, peak: 1 }
}
#[test]
fn crawling_three_times_owes_a_site_an_exit_and_two_more_move_it_on() {
let mut s = State::default();
s.judge_slow(&[obs("slow.example", "direct", true), obs("fast.example", "direct", false)], 10, 3);
s.judge_slow(&[obs("slow.example", "direct", true)], 20, 3);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "direct", true)], 30, 3);
assert_eq!(s.slow_want["slow.example"].host, "www.slow.example");
s.route_slow("slow.example", "www.slow.example", "nl", vec!["nl".into()], 40);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "nl", true)], 50, 3);
s.judge_slow(&[obs("slow.example", "nl", false)], 60, 3);
assert_eq!(s.domains["slow.example"].bad, 0, "a fast transfer keeps it");
s.judge_slow(&[obs("slow.example", "nl", true)], 70, 3);
s.judge_slow(&[obs("slow.example", "nl", true)], 80, 3);
assert!(!s.domains.contains_key("slow.example"));
assert_eq!(s.slow_want["slow.example"].tried, ["nl"]);
s.skip_slow("slow.example", 90, 1000);
s.judge_slow(&[obs("slow.example", "direct", true)], 100, 1);
assert!(s.slow_want.is_empty(), "skipped for a while");
}
#[test]
fn transfers_are_judged_by_their_fastest_second() {
let snap = |down: &[(&str, &str, &str, u64)]| {
json!({ "connections": down.iter().map(|(id, host, exit, d)| json!({
"id": id, "download": d, "chains": [exit], "metadata": { "host": host, "type": "mixed/mixed-in" },
})).collect::<Vec<_>>() })
};
let snaps = [
snap(&[("1", "a.example", "direct", 0), ("2", "b.example", "direct", 0)]),
snap(&[("1", "a.example", "direct", 100_000), ("2", "b.example", "direct", 400_000)]),
snap(&[("1", "a.example", "direct", 200_000), ("2", "b.example", "direct", 400_100)]),
snap(&[("1", "a.example", "direct", 300_000), ("2", "b.example", "direct", 400_200)]),
];
let out = sample_transfers(&snaps, 250_000, 150 * 1024);
assert_eq!(out, [("a.example".to_owned(), "direct".to_owned(), true, 100_000), ("b.example".to_owned(), "direct".to_owned(), false, 400_000)]);
}
#[test]
fn sites_and_local_targets() {
assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk"));
assert_eq!(registrable("foo.workers.dev").as_deref(), Some("foo.workers.dev"));
assert_eq!(registrable("co.uk"), None);
assert_eq!(site("https://accounts.spotify.com/why"), "spotify.com");
assert!(local_target("http://127.1/"));
assert!(local_target("https://192.168.0.1/admin"));
assert!(local_target("http://localhost:8080/"));
assert!(!local_target("https://example.com/"));
assert!(host_ok("www.example.com") && !host_ok("127.0.0.1") && !host_ok("example") && !host_ok("a b.com"));
}
}
+1 -1
View File
@@ -21,7 +21,7 @@ pub use misc::*;
pub use privilege::privileged_changes; pub use privilege::privileged_changes;
pub use proxy::*; pub use proxy::*;
pub use tunnels::*; pub use tunnels::*;
pub use validate::{Issue, Severity, validate}; pub use validate::{Issue, Severity, path_name_ok, validate};
pub use zapret::*; pub use zapret::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
+69 -23
View File
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset}; use super::{Backend, Config, GroupStrategy, Selection, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
use crate::derived::{self, BUILTIN_TAGS}; use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -50,11 +50,20 @@ fn tag_pattern_ok(tag: &str) -> bool {
/// A name that becomes part of a file path, a Windows service name or an adapter name: /// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters. /// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub(crate) fn path_name_ok(name: &str) -> bool { pub fn path_name_ok(name: &str) -> bool {
!name.is_empty() !name.is_empty()
&& name.len() <= 64 && name.len() <= 64
&& !name.starts_with('.') && !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-')) && name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
&& !windows_device(name)
}
/// CON, NUL, COM1 and the rest: on Windows a file named so (whatever its extension) is the
/// device.
fn windows_device(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
} }
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path /// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
@@ -113,12 +122,9 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel"); v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel");
} }
for (on, path, what) in [ for (on, path, what) in [
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"), (cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"), (cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"), (cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
] { ] {
if on { if on {
v.warn(path, format!("{what} {IGNORED}")); v.warn(path, format!("{what} {IGNORED}"));
@@ -131,13 +137,8 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
if z.enable && z.engine == ZapretEngine::DiscordYoutube && z.discord_youtube.include_extra_upstream_lists { if z.enable && z.engine == ZapretEngine::DiscordYoutube && z.discord_youtube.include_extra_upstream_lists {
v.warn("zapret.zapret-discord-youtube.includeExtraUpstreamLists", "Flowseal's Windows release has no instagram, soundcloud or twitter list: ignored"); v.warn("zapret.zapret-discord-youtube.includeExtraUpstreamLists", "Flowseal's Windows release has no instagram, soundcloud or twitter list: ignored");
} }
if z.enable && z.engine == ZapretEngine::Zapret2 { if z.enable && z.engine == ZapretEngine::Zapret2 && z.zapret2.cutoff.enable {
if z.zapret2.strategy_source == StrategySource::Z2k && z.zapret2.profiles.is_none() { v.warn("zapret.zapret2.cutoff.enable", "the 16 KB cutoff probe is not on Windows yet");
v.warn("zapret.zapret2.strategySource", "z2k's strategies are not on Windows yet: zapret2 does not start with them (nfqws2-keenetic's, or your own profiles, do)");
}
if z.zapret2.auto_hostlist.extended_detection {
v.warn("zapret.zapret2.autoHostlist.extendedDetection", "the extended detection is not on Windows yet: nfqws2's own learning is used");
}
} }
if z.enable && cfg.proxy.tun.enable { if z.enable && cfg.proxy.tun.enable {
v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other"); v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other");
@@ -306,9 +307,8 @@ fn proxy(cfg: &Config, v: &mut Issues) {
if p.auto_proxy.enable && !sing_box { if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend"); 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 { // Upstream samples transfers through the Clash API, which "first" selection leaves off
v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\""); // there; here it is always on, so slow sites are routed whatever the selection.
}
if p.dns.fake_ip.enable && !sing_box { if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend"); v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
} }
@@ -478,13 +478,14 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
} }
let wl = &cfg.whitelist_bypass; let wl = &cfg.whitelist_bypass;
// Checked on or off: `proxy-ctl wl` names files after them either way.
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if wl.enable { if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true"); v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
for (name, j) in &wl.joiners { for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk { if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here"); v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
@@ -498,6 +499,26 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
fn zapret(cfg: &Config, v: &mut Issues) { fn zapret(cfg: &Config, v: &mut Issues) {
let z = &cfg.zapret; let z = &cfg.zapret;
// They join winws2's options as written.
let p = &z.zapret2.ports;
for (path, values) in [("zapret.zapret2.ports.extraTcp", &p.extra_tcp), ("zapret.zapret2.ports.extraUdp", &p.extra_udp)] {
for value in values {
let text = match value {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
};
if !crate::zapret2::port_spec_ok(text.trim()) {
v.error(path, format!("'{text}' is not a port or a range (N, or N-M, within 1-65535)"));
}
}
}
for (path, list) in [("zapret.zapret2.ports.tcp", &p.tcp), ("zapret.zapret2.ports.udp", &p.udp)] {
if let Some(list) = list
&& !list.split(',').all(|x| crate::zapret2::port_spec_ok(x.trim().replace(':', "-").as_str()))
{
v.error(path, "ports and ranges, comma-separated (N, or N-M, within 1-65535)");
}
}
if !z.enable { if !z.enable {
return; return;
} }
@@ -757,6 +778,33 @@ mod tests {
use super::*; use super::*;
use crate::config::{Group, Outbound, RoutingRule}; use crate::config::{Group, Outbound, RoutingRule};
#[test]
fn names_are_plain_file_names_and_never_devices() {
for ok in ["laptop", "wl", "a.b_c-1", "COM", "console", "lpt10", "nul-ish"] {
assert!(path_name_ok(ok), "{ok}");
}
for bad in ["", ".hidden", "a/b", r"a\b", "C:x", "..", "CON", "con.txt", "Nul", "PRN", "aux.json", "COM1", "lpt9.link"] {
assert!(!path_name_ok(bad), "{bad}");
}
}
#[test]
fn zapret2_extra_ports_are_ports() {
let mut cfg = Config::default();
cfg.zapret.zapret2.ports.extra_tcp = vec![serde_json::json!(8443), serde_json::json!("50000-50099"), serde_json::json!("443\n--lua-init=@x.lua")];
cfg.zapret.zapret2.ports.udp = Some("443,590:600".into());
let errs = errors(&cfg);
assert_eq!(errs.iter().filter(|e| e.starts_with("zapret.zapret2.ports")).count(), 1, "{errs:?}");
assert!(crate::zapret2::port_spec_ok("1-65535") && !crate::zapret2::port_spec_ok("0") && !crate::zapret2::port_spec_ok("9-1") && !crate::zapret2::port_spec_ok("443 x"));
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
cfg.whitelist_bypass.creators.insert(r"C:\Windows\x".into(), serde_json::from_value(serde_json::json!({ "platform": "wbstream" })).unwrap());
assert!(errors(&cfg).iter().any(|e| e.starts_with("whitelistBypass.")), "{:?}", errors(&cfg));
}
fn errors(cfg: &Config) -> Vec<String> { fn errors(cfg: &Config) -> Vec<String> {
validate(cfg) validate(cfg)
.into_iter() .into_iter()
@@ -815,12 +863,10 @@ mod tests {
assert!(quiet.is_empty(), "{quiet:?}"); assert!(quiet.is_empty(), "{quiet:?}");
let mut cfg = Config::default(); let mut cfg = Config::default();
cfg.kill_switch.enable = true; cfg.kill_switch.enable = true;
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert("vpn".into(), Default::default());
cfg.zapret.enable = true; cfg.zapret.enable = true;
cfg.proxy.tun.enable = true; cfg.proxy.tun.enable = true;
let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect(); let paths: Vec<String> = validate(&cfg).into_iter().filter(|i| i.severity == Severity::Warning && i.message.contains("Windows yet")).map(|i| i.path).collect();
for want in ["killSwitch.enable", "amneziaWg.profiles", "proxy.tun.enable"] { for want in ["killSwitch.enable", "proxy.tun.enable"] {
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}"); assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
} }
} }
+1
View File
@@ -4,6 +4,7 @@
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here //! 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. //! touches the network, the file system or processes; the service does that.
pub mod autoproxy;
pub mod awg; pub mod awg;
pub mod components; pub mod components;
pub mod config; pub mod config;
@@ -0,0 +1,105 @@
//! autoProxy in sing-box's config, as upstream's start script adds it: a loopback listener
//! per exit (direct first) that the prober fetches through, pinned to that exit; and per exit
//! a local rule-set of the domains learned blocked directly, routed through it after every
//! rule of the user's. sing-box reloads a rule-set file when it changes, so what the prober
//! learns takes effect without a restart.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::outbounds::Inventory;
use super::{Input, RouteMode};
use crate::autoproxy::DIRECT;
/// One exit the prober fetches through.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProbeExit {
pub tag: String,
/// Its loopback listener.
pub port: u16,
/// Its rule-set's tag and file (none for direct: nothing is routed there).
pub rule_set: Option<String>,
pub path: Option<String>,
}
fn inbound(i: usize) -> String {
format!("probe-in-{i}")
}
/// direct, then the exits that are not disabled, `maxExits` in all. The state is kept by tag,
/// so an index that shifts is harmless.
pub fn probe_exits(input: &Input, inv: &Inventory) -> Vec<ProbeExit> {
let a = &input.cfg.proxy.auto_proxy;
let Some(dir) = input.env.autoproxy_rules_dir.as_deref().filter(|_| a.enable) else {
return Vec::new();
};
let dir = dir.trim_end_matches(['/', '\\']);
let sep = if input.env.windows { '\\' } else { '/' };
std::iter::once(DIRECT.to_owned())
.chain(inv.exits.iter().filter(|t| t.as_str() != DIRECT && !inv.disabled.contains(t)).cloned())
.take(a.max_exits.max(1) as usize)
.enumerate()
.map(|(i, tag)| ProbeExit {
port: a.probe_base_port.saturating_add(i as u16),
rule_set: (i > 0).then(|| format!("autoproxy-{i}")),
path: (i > 0).then(|| format!("{dir}{sep}rs-{i}.json")),
tag,
})
.collect()
}
/// Adds the listeners (with the hop login: they reach every exit), their pins at `pin_at`
/// (after the loopback guard, ahead of every rule that picks an outbound), the rule-sets, and
/// the learned rules after the rest, unless the mode sends everything direct. What an exit
/// carries is looked up through the proxy too, as every proxied name is.
#[allow(clippy::too_many_arguments)]
pub(super) fn apply(
input: &Input,
exits: &[ProbeExit],
inbounds: &mut Vec<Value>,
rules: &mut Vec<Value>,
pin_at: usize,
rule_sets: &mut Vec<Value>,
dns_rules: &mut Vec<Value>,
mode: RouteMode,
) {
if exits.is_empty() {
return;
}
for (i, e) in exits.iter().enumerate() {
let mut l = json!({ "type": "mixed", "tag": inbound(i), "listen": "127.0.0.1", "listen_port": e.port });
if let Some((user, password)) = &input.env.hop_login {
l["users"] = json!([{ "username": user, "password": password }]);
}
inbounds.push(l);
}
// The direct probe resolves as a direct dial would, and never reaches this host's LAN: the
// hosts probed are ones apps dialled, or anyone with the autoProxy scope asked for.
let mut pins = vec![
json!({ "inbound": [inbound(0)], "action": "resolve", "server": "local" }),
json!({ "inbound": [inbound(0)], "ip_is_private": true, "action": "reject" }),
];
pins.extend(exits.iter().enumerate().map(|(i, e)| json!({ "inbound": [inbound(i)], "outbound": e.tag })));
let at = pin_at.min(rules.len());
rules.splice(at..at, pins);
// autoProxy.exclude is never routed by it: a site learned whole (example.com) must not take
// an excluded name under it (intranet.example.com) along.
let exclude: Vec<String> = input.cfg.proxy.auto_proxy.exclude.iter().map(|x| x.trim_start_matches('.').to_ascii_lowercase()).filter(|x| !x.is_empty()).collect();
for e in exits {
let (Some(tag), Some(path)) = (&e.rule_set, &e.path) else { continue };
rule_sets.push(json!({ "type": "local", "format": "source", "tag": tag, "path": path }));
if mode != RouteMode::AllBypass {
rules.push(if exclude.is_empty() {
json!({ "rule_set": [tag], "outbound": e.tag })
} else {
json!({
"type": "logical", "mode": "and",
"rules": [{ "rule_set": [tag] }, { "domain_suffix": exclude, "invert": true }],
"outbound": e.tag,
})
});
}
dns_rules.push(json!({ "rule_set": [tag], "server": "remote" }));
}
}
+13 -2
View File
@@ -2,6 +2,7 @@
//! what it has fetched. Upstream builds these in its start scripts (bash and jq over the //! what it has fetched. Upstream builds these in its start scripts (bash and jq over the
//! Nix templates); here it is one pure function the service calls before every (re)start. //! Nix templates); here it is one pure function the service calls before every (re)start.
mod autoproxy;
pub mod groups; pub mod groups;
mod outbounds; mod outbounds;
mod routing; mod routing;
@@ -15,6 +16,7 @@ use serde_json::Value;
use crate::config::{Config, RouteMatch, RuleSetFormat}; use crate::config::{Config, RouteMatch, RuleSetFormat};
pub use autoproxy::ProbeExit;
pub use outbounds::Inventory; pub use outbounds::Inventory;
pub use routing::{WantedRuleSet, wanted_rule_sets}; pub use routing::{WantedRuleSet, wanted_rule_sets};
@@ -101,6 +103,12 @@ pub struct Env {
pub sidecar_secret: String, pub sidecar_secret: String,
/// Running on Windows: the TUN takes Windows' fields only. /// Running on Windows: the TUN takes Windows' fields only.
pub windows: bool, pub windows: bool,
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
pub autoproxy_rules_dir: Option<String>,
/// zapret2's rule-sets (ps_core::zapret2::routing): what it fixes, sent direct
/// (`zapret.directSync`), and what it cannot, for the proxy (`zapret2.proxyFallback`).
pub zapret2_direct_rule_set: Option<String>,
pub zapret2_proxy_rule_set: Option<String>,
} }
pub struct Input<'a> { pub struct Input<'a> {
@@ -123,6 +131,8 @@ pub struct Rendered {
/// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid". /// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid".
pub xray: Option<Value>, pub xray: Option<Value>,
pub inventory: Inventory, pub inventory: Inventory,
/// autoProxy's exits and their probe listeners; empty when it is off.
pub probe_exits: Vec<ProbeExit>,
pub warnings: Vec<String>, pub warnings: Vec<String>,
} }
@@ -143,8 +153,9 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
let assembly = outbounds::assemble(input, &mut warnings)?; let assembly = outbounds::assemble(input, &mut warnings)?;
match input.cfg.proxy.backend { match input.cfg.proxy.backend {
crate::config::Backend::SingBox | crate::config::Backend::Hybrid => { crate::config::Backend::SingBox | crate::config::Backend::Hybrid => {
let (config, sidecar) = sing_box::config(input, &assembly, &mut warnings)?; let probe_exits = autoproxy::probe_exits(input, &assembly.inventory);
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, warnings }) let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings })
} }
crate::config::Backend::Xray => Err(RenderError( crate::config::Backend::Xray => Err(RenderError(
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(), "the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
+6 -1
View File
@@ -177,6 +177,10 @@ pub(super) fn per_app_inbound(name: &str) -> String {
/// Every route and DNS rule, in order, and the final outbound and resolver. /// Every route and DNS rule, in order, and the final outbound and resolver.
pub(super) struct Route { pub(super) struct Route {
pub rules: Vec<Value>, pub rules: Vec<Value>,
/// Where rules pinned to an inbound go: after the loopback guard, ahead of every rule that
/// picks an outbound.
pub pin_at: usize,
pub mode: RouteMode,
pub dns_rules: Vec<Value>, pub dns_rules: Vec<Value>,
pub final_outbound: &'static str, pub final_outbound: &'static str,
pub dns_final: &'static str, pub dns_final: &'static str,
@@ -204,6 +208,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo
let _ = hop_ports; let _ = hop_ports;
common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" })); common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" }));
common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" })); common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" }));
let pin_at = common.len();
common.extend(always_rules(input, known, warnings)); common.extend(always_rules(input, known, warnings));
// The custom rules: each outbound's own routing, then routing.rules, at their priority. // The custom rules: each outbound's own routing, then routing.rules, at their priority.
@@ -321,7 +326,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo
dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" })); dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" }));
} }
Route { rules, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) } Route { rules, pin_at, mode, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) }
} }
fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section { fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section {
+22 -3
View File
@@ -3,6 +3,7 @@
use serde_json::{Map, Value, json}; use serde_json::{Map, Value, json};
use super::autoproxy::{self, ProbeExit};
use super::outbounds::Assembly; use super::outbounds::Assembly;
use super::routing::{self, per_app_inbound}; use super::routing::{self, per_app_inbound};
use super::{Input, RenderError}; use super::{Input, RenderError};
@@ -64,7 +65,7 @@ fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
Ok(Some(json!([{ "username": user, "password": password }]))) Ok(Some(json!([{ "username": user, "password": password }])))
} }
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> { pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> {
let cfg = input.cfg; let cfg = input.cfg;
let p = &cfg.proxy; let p = &cfg.proxy;
let env = input.env; let env = input.env;
@@ -142,6 +143,24 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
test_members.extend(asm.inventory.exits.iter().map(|t| Value::from(t.clone()))); test_members.extend(asm.inventory.exits.iter().map(|t| Value::from(t.clone())));
outbounds.push(json!({ "type": "selector", "tag": "proxy-suite-test", "outbounds": test_members, "default": "block" })); outbounds.push(json!({ "type": "selector", "tag": "proxy-suite-test", "outbounds": test_members, "default": "block" }));
let mut rules = route.rules; let mut rules = route.rules;
let mut rule_sets = route.rule_set;
let mut dns_rules = route.dns_rules;
autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode);
// zapret2's: what it cannot fix through the proxy, after the explicit rules and autoProxy's,
// ahead of the hosts it does fix, which go direct so it sees them. all-bypass sends
// everything direct, and all-proxy keeps no direct lists.
if let Some(path) = &env.zapret2_proxy_rule_set
&& route.mode != super::RouteMode::AllBypass
{
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
}
if let Some(path) = &env.zapret2_direct_rule_set
&& !matches!(route.mode, super::RouteMode::AllBypass | super::RouteMode::AllProxy)
{
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-hosts", "path": path }));
rules.push(json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
}
let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1); let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1);
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" })); rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
if hybrid { if hybrid {
@@ -156,7 +175,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
servers.push(json!({ "type": "fakeip", "tag": "fakeip", "inet4_range": p.dns.fake_ip.inet4_range })); servers.push(json!({ "type": "fakeip", "tag": "fakeip", "inet4_range": p.dns.fake_ip.inet4_range }));
} }
servers.extend(p.dns.sing_box.servers.iter().map(|s| Value::Object(s.clone()))); servers.extend(p.dns.sing_box.servers.iter().map(|s| Value::Object(s.clone())));
let mut dns = json!({ "servers": servers, "rules": route.dns_rules, "final": route.dns_final }); let mut dns = json!({ "servers": servers, "rules": dns_rules, "final": route.dns_final });
if let Some(s) = p.dns.strategy { if let Some(s) = p.dns.strategy {
dns["strategy"] = s.as_str().into(); dns["strategy"] = s.as_str().into();
} }
@@ -166,7 +185,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
let mut route_obj = json!({ let mut route_obj = json!({
"default_domain_resolver": "local", "default_domain_resolver": "local",
"rule_set": route.rule_set, "rule_set": rule_sets,
"rules": rules, "rules": rules,
"final": route.final_outbound, "final": route.final_outbound,
}); });
+403 -26
View File
@@ -1,14 +1,16 @@
//! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2 //! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2
//! (NFQUEUE). The strategy source is nfqws2-keenetic, read and patched as upstream's //! (NFQUEUE): nfqws2-keenetic's, read and patched as upstream's `zapret2/sources.nix` does, or
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow //! z2k's, made by its own generator (tools/build-zapret2-extras.sh); the profiles, markers,
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`. //! circular defaults, ports and Lua layers follow upstream's `zapret2/runtime.nix`, and the
//! routing by the detector's verdicts its `direct-sync.template.sh`.
//! //!
//! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take //! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once //! the place of the queue's rules, a filter part hands the detectors the server's TLS
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's //! records in place of the queue's packet windows, and there are no marks. winws2 drops to
//! own `--writable` insists on making the directory, which must already hold the list). //! Low integrity once it runs, so what it writes lives in a directory the service labels Low
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`, //! for it (winws2's own `--writable` insists on making the directory).
//! `extendedDetection`) and z2k come later.
use std::collections::BTreeMap;
use crate::config::{StrategySource, Zapret2}; use crate::config::{StrategySource, Zapret2};
@@ -34,14 +36,59 @@ fn patch(what: &str, from: &str, to: &str, text: &str) -> Result<String, String>
} }
} }
/// nfqws2-keenetic's strategies, as upstream's sources.nix takes them. /// A strategy source, as upstream's sources.nix takes it: nfqws2-keenetic's or z2k's.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq, Default)]
pub struct Source { pub struct Source {
/// In nfqws2's order: UDP, QUIC, TCP. Hostlist markers still in. /// In nfqws2's order. Hostlist markers (and z2k's tokens) still in.
pub profiles: Vec<String>, pub profiles: Vec<String>,
/// z2k: its profiles with the extended detector learning in its last place.
pub learn_profiles: Option<Vec<String>>,
pub blob_args: Vec<String>, pub blob_args: Vec<String>,
pub tcp_ports: String, pub tcp_ports: String,
pub udp_ports: String, pub udp_ports: String,
/// Lua its strategies need, loaded after zapret2's own (z2k's detectors).
pub lua_init: Vec<String>,
/// winws2 options it runs with.
pub daemon_args: Vec<String>,
/// z2k's: its profiles carry @HSUF@, @ESUF@ and the learner's tokens.
pub z2k: bool,
}
/// z2k's Lua, in its S99zapret2 order (upstream's sources.nix): z2k-range-rand resolves the
/// ranges its strategies write; without it each fake goes once.
pub const Z2K_LUA: [&str; 6] = ["z2k-alert", "z2k-quic-silence", "z2k-tcp16", "z2k-fooling-ext", "z2k-range-rand", "z2k-modern-core"];
/// z2k's strategies, as its generator made them (tools/build-zapret2-extras.sh): `plain` and
/// `learn` its two profile sets, `blobs` its fake payloads, `ports` its NFQWS2_PORTS_*;
/// `z2k_dir` where its files are and `root_dir` the tree its generator wrote, as winws2 reads
/// them, and `lua` its `files/lua/` likewise (with a trailing separator).
pub fn z2k(plain: &str, learn: &str, blobs: &str, ports: &str, z2k_dir: &str, root_dir: &str, lua: &str) -> Result<Source, String> {
let fill = |t: &str| t.replace("@ROOT@", root_dir).replace("@Z2K@", z2k_dir);
let split = |t: &str| -> Vec<String> { fill(t).split(" --new ").map(|p| p.trim().to_owned()).filter(|p| !p.is_empty()).collect() };
let (plain, learn) = (split(plain), split(learn));
if plain.is_empty() || !plain.iter().any(|p| p.contains("--lua-desync=circular")) {
return Err("z2k's generated profiles are empty: is the zapret2-extras component installed?".into());
}
let port = |name: &str| -> Result<String, String> {
ports
.lines()
.find_map(|l| l.strip_prefix(&format!("{name}=")))
.map(|v| v.trim().to_owned())
.filter(|v| !v.is_empty())
.ok_or_else(|| format!("z2k's ports: no {name}"))
};
Ok(Source {
profiles: plain,
learn_profiles: Some(learn),
blob_args: words(&fill(blobs)).into_iter().map(str::to_owned).collect(),
tcp_ports: port("NFQWS2_PORTS_TCP")?,
udp_ports: port("NFQWS2_PORTS_UDP")?.replace(':', "-"),
lua_init: Z2K_LUA.iter().map(|n| format!("{lua}{n}.lua")).collect(),
// As its S99zapret2 runs nfqws2: a connection without SNI takes the name last seen
// on that address, so it still meets its site's profile and strategy.
daemon_args: vec!["--ipcache-hostname=1".into()],
z2k: true,
})
} }
/// `conf`: its `etc/nfqws2/nfqws2.conf`; `dir`: where its `etc/nfqws2/` is (as winws2 will /// `conf`: its `etc/nfqws2/nfqws2.conf`; `dir`: where its `etc/nfqws2/` is (as winws2 will
@@ -94,6 +141,7 @@ pub fn keenetic(conf: &str, dir: &str) -> Result<Source, String> {
blob_args, blob_args,
tcp_ports: bare("TCP_PORTS")?.trim().to_owned(), tcp_ports: bare("TCP_PORTS")?.trim().to_owned(),
udp_ports: bare("UDP_PORTS")?.trim().replace(':', "-"), udp_ports: bare("UDP_PORTS")?.trim().replace(':', "-"),
..Default::default()
}) })
} }
@@ -108,6 +156,22 @@ pub struct Paths {
pub exclude: String, pub exclude: String,
/// `zapret-hosts-auto.txt`, in a directory labelled Low integrity. /// `zapret-hosts-auto.txt`, in a directory labelled Low integrity.
pub auto: String, pub auto: String,
/// The zapret2-extras component, when installed: upstream's Lua layers and z2k's.
pub extras: Option<Extras>,
}
/// Where the zapret2-extras component's files are, as winws2 reads them.
#[derive(Debug, Clone)]
pub struct Extras {
/// proxy-suite's own Lua (detect.lua, …), with a trailing separator.
pub lua: String,
/// z2k's `files/lua/`, with a trailing separator: its state layer persists strategies
/// whichever the source.
pub z2k_lua: String,
/// The auto list and the lists the learner never learns from, as Lua arguments take
/// paths: without a colon, so Cygwin's `/cygdrive/c/…` on Windows.
pub auto_lua: String,
pub exclude_lua: Vec<String>,
} }
/// A hostlist entry as nfqws2 takes one: a name (`^` for an exact match), nothing that could /// A hostlist entry as nfqws2 takes one: a name (`^` for an exact match), nothing that could
@@ -119,8 +183,9 @@ pub fn host_entry_ok(entry: &str) -> bool {
&& entry.chars().enumerate().all(|(i, c)| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '*') || (c == '^' && i == 0)) && entry.chars().enumerate().all(|(i, c)| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '*') || (c == '^' && i == 0))
} }
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target). /// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target),
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) { /// and the configuration's own sites and exclusions, which join every profile that takes a list.
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String, String) {
let a = &z.auto_hostlist; let a = &z.auto_hostlist;
let base = format!("--hostlist={} --hostlist-exclude={}", p.user, p.exclude); let base = format!("--hostlist={} --hostlist-exclude={}", p.user, p.exclude);
let (with_auto, no_auto) = if a.enable { let (with_auto, no_auto) = if a.enable {
@@ -156,7 +221,57 @@ fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) {
if !excluded.is_empty() { if !excluded.is_empty() {
statics.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(","))); statics.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(",")));
} }
(with_auto + &statics, no_auto + &statics) (with_auto, no_auto, statics)
}
/// The extended detector's arguments (upstream's learnArgs and stallWatch), when it learns.
fn detector(z: &Zapret2, x: &Extras) -> (String, String) {
let a = &z.auto_hostlist;
let mut learn = vec![
format!("auto={}", x.auto_lua),
format!("exclude={}", x.exclude_lua.join(",")),
format!("fails={}", a.fail_threshold),
format!("time={}", a.fail_time),
format!("inseq={}", a.incoming_maxseq),
format!("retrans={}", a.retrans_threshold),
// How many of the server's packets it watches (upstream's NFQUEUE window).
"win=32".into(),
];
let excluded: Vec<&str> = z.exclude_domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
if !excluded.is_empty() {
learn.push(format!("exclude_domains={}", excluded.join(",")));
}
if z.strategy_log {
learn.push("log".into());
}
let mut watch = vec![format!("fails={}", a.fail_threshold), format!("time={}", a.fail_time), "win=32".into()];
if z.strategy_log {
watch.push("log".into());
}
(
learn.join(":"),
format!("--in-range=-s65536 --payload=all --lua-desync=ps_watch:{} --in-range=x --payload=all", watch.join(":")),
)
}
/// A WinDivert filter part for the server's packets that begin a TLS handshake or alert
/// record, on `ports`: what the detectors judge a site by (its ServerHello, a refusal), where
/// nfqws2 is handed a flow's first packets by a queue window WinDivert has no means for.
fn tls_reply_filter(ports: &str) -> Option<String> {
let conds: Vec<String> = ports
.split(',')
.filter_map(|p| match p.split_once('-') {
Some((a, b)) => Some(format!("(tcp.SrcPort >= {} and tcp.SrcPort <= {})", a.trim().parse::<u16>().ok()?, b.trim().parse::<u16>().ok()?)),
None => Some(format!("tcp.SrcPort == {}", p.trim().parse::<u16>().ok()?)),
})
.collect();
if conds.is_empty() {
return None;
}
Some(format!(
"inbound and tcp.PayloadLength >= 6 and (tcp.Payload[0] == 0x16 or tcp.Payload[0] == 0x15) and tcp.Payload[1] == 0x03 and ({})",
conds.join(" or ")
))
} }
/// Detector settings a circular instance leaves unset come from autoHostlist. /// Detector settings a circular instance leaves unset come from autoHostlist.
@@ -184,13 +299,25 @@ fn circular_fill(z: &Zapret2, token: &str) -> String {
t t
} }
/// A port or a range as winws2 takes one: `N` or `N-M`, within 1-65535.
pub fn port_spec_ok(spec: &str) -> bool {
let num = |s: &str| !s.is_empty() && s.len() <= 5 && s.chars().all(|c| c.is_ascii_digit()) && s.parse::<u32>().is_ok_and(|n| (1..=65535).contains(&n));
match spec.split_once('-') {
Some((a, b)) => num(a) && num(b) && a.parse::<u32>().ok() <= b.parse::<u32>().ok(),
None => num(spec),
}
}
/// `ports.extraTcp`/`extraUdp` as winws2's list: numbers and ranges alone (validated already;
/// anything else dropped here too, as it joins winws2's options).
fn port_list(values: &[serde_json::Value]) -> String { fn port_list(values: &[serde_json::Value]) -> String {
values values
.iter() .iter()
.map(|v| match v { .map(|v| match v {
serde_json::Value::String(s) => s.clone(), serde_json::Value::String(s) => s.trim().to_owned(),
other => other.to_string(), other => other.to_string(),
}) })
.filter(|s| port_spec_ok(s))
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(",") .join(",")
} }
@@ -230,29 +357,91 @@ pub(crate) fn merge_ports(lists: &[&str]) -> String {
/// winws2's whole command line. /// winws2's whole command line.
pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Result<Vec<String>, String> { pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Result<Vec<String>, String> {
if z.strategy_source != StrategySource::Nfqws2Keenetic && z.profiles.is_none() { if z.strategy_source == StrategySource::Z2k && z.profiles.is_none() && !source.z2k {
return Err("only the nfqws2-keenetic strategies are there on Windows yet (zapret.zapret2.strategySource)".into()); return Err("z2k's strategies need the zapret2-extras component (proxy-ctl components)".into());
} }
let (with_auto, no_auto) = hostlist_args(z, p); let (with_auto, no_auto, statics) = hostlist_args(z, p);
let render = |profile: &str| { // The extended detector learns in place of nfqws2's own learning: with the source's own
// strategies only, and the component installed.
let learning = p.extras.as_ref().filter(|_| z.auto_hostlist.enable && z.auto_hostlist.extended_detection && z.profiles.is_none());
let (learn_args, stall_watch) = learning.map(|x| detector(z, x)).unwrap_or_default();
let exclude_suffix = {
let mut e = format!("--hostlist-exclude={}", p.exclude);
let excluded: Vec<&str> = z.exclude_domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
if !excluded.is_empty() {
e.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(",")));
}
e
};
let render = |profile: &str| -> String {
if source.z2k && z.profiles.is_none() {
// z2k's profiles name the lists themselves; the markers take only ours, and the
// configuration's sites go where its generator left @HSUF@.
return profile
.replace("<HOSTLIST_NOAUTO>", &no_auto)
.replace("<HOSTLIST>", &with_auto)
.replace("@HSUF@", statics.trim())
.replace("@ESUF@", &exclude_suffix)
.replace("@STALLWATCH@", &stall_watch)
.replace(":win=32@LEARNEXTRA@", &learn_args.split(":win=32").nth(1).map(|rest| format!(":win=32{rest}")).unwrap_or_else(|| ":win=32".into()))
.replace("@AUTO@", learning.map_or("", |x| x.auto_lua.as_str()))
.replace("@EXCLUDE@", &learning.map(|x| x.exclude_lua.join(",")).unwrap_or_default())
.replace("@FAILS@", &z.auto_hostlist.fail_threshold.to_string())
.replace("@TIME@", &z.auto_hostlist.fail_time.to_string())
.replace("@INSEQ@", &z.auto_hostlist.incoming_maxseq.to_string())
.replace("@RETRANS@", &z.auto_hostlist.retrans_threshold.to_string());
}
// nfqws2-keenetic: with the extended detector, its learning profile only reads the
// auto list (upstream's sourceProfiles).
let profile = if learning.is_some() { profile.replace("<HOSTLIST>", "<HOSTLIST_NOAUTO>") } else { profile.to_owned() };
profile profile
.replace("<HOSTLIST_NOAUTO>", &no_auto) .replace("<HOSTLIST_NOAUTO>", &(no_auto.clone() + &statics))
.replace("<HOSTLIST>", &with_auto) .replace("<HOSTLIST>", &(with_auto.clone() + &statics))
.replace("<STALLWATCH> ", "") .replace("<STALLWATCH> ", &if stall_watch.is_empty() { String::new() } else { format!("{stall_watch} ") })
.replace("<STALLWATCH>", "") .replace("<STALLWATCH>", &stall_watch)
}; };
let profiles: Vec<String> = match &z.profiles { let mut profiles: Vec<String> = match (&z.profiles, &source.learn_profiles) {
Some(own) => own.iter().map(|x| render(x)).collect(), (Some(own), _) => own.iter().map(|x| render(x)).collect(),
None => source.profiles.iter().map(|x| render(x)).collect(), (None, Some(learn)) if learning.is_some() => learn.iter().map(|x| render(x)).collect(),
(None, _) => source.profiles.iter().map(|x| render(x)).collect(),
}; };
// After every source profile, so it only takes what none of them did: ps_learn, the TLS
// sites in no list (z2k's places its own).
if learning.is_some() && !source.z2k {
profiles.push(format!(
"--filter-tcp=443 --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:{learn_args}"
));
}
let mut opt: Vec<String> = Vec::new(); let mut opt: Vec<String> = Vec::new();
if debug_packets { if debug_packets {
opt.push("--debug=1".into()); opt.push("--debug=1".into());
} }
if z.profiles.is_none() {
opt.extend(source.daemon_args.iter().cloned());
}
for lua in ["zapret-lib.lua", "zapret-antidpi.lua", "zapret-auto.lua"] { for lua in ["zapret-lib.lua", "zapret-antidpi.lua", "zapret-auto.lua"] {
opt.push(format!("--lua-init=@{}{lua}", p.lua)); opt.push(format!("--lua-init=@{}{lua}", p.lua));
} }
if z.profiles.is_none() {
opt.extend(source.lua_init.iter().map(|f| format!("--lua-init=@{f}")));
}
// Upstream's layers, in its order: the per-site key, the fail stamp, z2k's state layer
// (each site's strategy kept across restarts) and its every-change writes, the detector
// (after z2k-alert.lua, whose detector it wraps), the strategy log.
if let Some(x) = &p.extras {
let mut layers = vec![
format!("{}public-suffix-hostkey.lua", x.lua),
format!("{}fail-stamp.lua", x.lua),
format!("{}z2k-state-persist.lua", x.z2k_lua),
format!("{}persist-every.lua", x.lua),
format!("{}detect.lua", x.lua),
];
if z.strategy_log {
layers.push(format!("{}strategy-log.lua", x.lua));
}
opt.extend(layers.into_iter().map(|f| format!("--lua-init=@{f}")));
}
for (name, file) in &z.blobs { for (name, file) in &z.blobs {
opt.push(format!("--blob={name}:@{file}")); opt.push(format!("--blob={name}:@{file}"));
} }
@@ -313,6 +502,9 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
let (wf_tcp, wf_udp) = (merge_ports(&tcp_all), merge_ports(&udp_all)); let (wf_tcp, wf_udp) = (merge_ports(&tcp_all), merge_ports(&udp_all));
if !wf_tcp.is_empty() { if !wf_tcp.is_empty() {
opt.push(format!("--wf-tcp-out={wf_tcp}")); opt.push(format!("--wf-tcp-out={wf_tcp}"));
if let Some(part) = tls_reply_filter(&wf_tcp) {
opt.push(format!("--wf-raw-part={part}"));
}
} }
if !wf_udp.is_empty() { if !wf_udp.is_empty() {
opt.push(format!("--wf-udp-out={wf_udp}")); opt.push(format!("--wf-udp-out={wf_udp}"));
@@ -326,6 +518,119 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
Ok(opt) Ok(opt)
} }
// --- what the proxy does with zapret2's verdicts (upstream's direct-sync.template.sh) -------
/// An entry a rule-set can take: an IPv4 or IPv6 address, or a name of two labels at least
/// (a bare "com" would send the whole TLD past the proxy). The zapret scope writes the lists.
fn host_valid(h: &str) -> bool {
if let Ok(ip) = h.parse::<std::net::IpAddr>() {
return ip.is_ipv4() || !h.contains('%');
}
let label_ok = |l: &str| {
!l.is_empty()
&& l.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
&& !l.starts_with('-')
&& !l.ends_with('-')
};
h.len() <= 253 && h.contains('.') && h.split('.').all(label_ok) && !h.chars().all(|c| c.is_ascii_digit() || c == '.')
}
/// nfqws hostlists: one host a line, `#` comments, `^` for the name alone.
fn hosts(text: &str) -> Vec<String> {
text.lines()
.map(|l| l.trim().to_ascii_lowercase())
.map(|l| l.trim_start_matches('^').to_owned())
.filter(|l| !l.is_empty() && !l.starts_with('#') && host_valid(l))
.collect()
}
/// detect.lua's verdicts ("kind<TAB>name<TAB>proto<TAB>..."), the last per name and proto:
/// (name, proto) -> kind.
fn verdicts(text: &str) -> BTreeMap<(String, String), String> {
let mut out = BTreeMap::new();
for line in text.lines() {
let f: Vec<&str> = line.split('\t').collect();
if f.len() < 3 || !host_valid(f[1]) {
continue;
}
out.insert((f[1].to_owned(), f[2].to_owned()), f[0].to_owned());
}
out
}
fn named(v: &BTreeMap<(String, String), String>, kind: &str, proto: &str) -> Vec<String> {
v.iter().filter(|((_, p), k)| k.as_str() == kind && p == proto).map(|((n, _), _)| n.clone()).collect()
}
/// A name and a site key cover each other either way round: www.notion.so and notion.so.
fn covers(a: &str, b: &str) -> bool {
a == b || a.ends_with(&format!(".{b}")) || b.ends_with(&format!(".{a}"))
}
fn is_ip(h: &str) -> bool {
h.parse::<std::net::IpAddr>().is_ok()
}
fn cidr(ips: &[String]) -> Vec<String> {
ips.iter().map(|ip| if ip.contains(':') { format!("{ip}/128") } else { format!("{ip}/32") }).collect()
}
/// The two rule-sets the proxy routes by, from zapret2's lists and its detector's verdicts:
/// `direct`, the hosts zapret2 handles, sent direct so it sees them (the pinned ones, and the
/// learned ones once a strategy got through for them, unless learned from transfers cut short);
/// `proxy`, what it cannot fix, for the proxy to carry (sites every strategy failed for, all
/// of a site's TCP or only its QUIC, and addresses that leave connections unanswered).
/// `auto` is the learned list, none when learning is off.
pub fn routing(user: &str, auto: Option<&str>, excluded: &str, verdicts_text: &str) -> (serde_json::Value, serde_json::Value) {
use serde_json::json;
let v = verdicts(verdicts_text);
let works = named(&v, "works", "tcp");
// Learned from a transfer cut short: success is judged on the first 4 KB, which the
// cutoff lets through, so "works" proves nothing for it.
let stalls = named(&v, "stalls", "cutoff");
let excluded = hosts(excluded);
let mut direct: Vec<String> = hosts(user);
direct.extend(
hosts(auto.unwrap_or(""))
.into_iter()
.filter(|h| works.iter().any(|w| covers(h, w)) && !stalls.iter().any(|s| covers(h, s))),
);
direct.sort();
direct.dedup();
direct.retain(|h| !excluded.contains(h));
let (ips, names): (Vec<String>, Vec<String>) = direct.into_iter().partition(|h| is_ip(h));
let mut rules = Vec::new();
if !names.is_empty() {
rules.push(json!({ "domain_suffix": names }));
}
if !ips.is_empty() {
rules.push(json!({ "ip_cidr": cidr(&ips) }));
}
let direct = json!({ "version": 1, "rules": rules });
// A site keyed by its address (no name seen) goes by address.
let tcp = named(&v, "unfixable", "tcp");
let udp = named(&v, "unfixable", "udp");
let (tcp_ips, tcp_names): (Vec<String>, Vec<String>) = tcp.into_iter().partition(|h| is_ip(h));
let (udp_ips, udp_names): (Vec<String>, Vec<String>) = udp.into_iter().partition(|h| is_ip(h));
let mut blocked = named(&v, "blocked", "ip");
blocked.extend(tcp_ips);
let mut rules = Vec::new();
if !tcp_names.is_empty() {
rules.push(json!({ "domain_suffix": tcp_names }));
}
if !udp_names.is_empty() {
rules.push(json!({ "network": ["udp"], "port": [443], "domain_suffix": udp_names }));
}
if !udp_ips.is_empty() {
rules.push(json!({ "network": ["udp"], "port": [443], "ip_cidr": cidr(&udp_ips) }));
}
if !blocked.is_empty() {
rules.push(json!({ "ip_cidr": cidr(&blocked) }));
}
(direct, json!({ "version": 1, "rules": rules }))
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
@@ -364,9 +669,81 @@ UDP_PORTS=443,590:600
user: r"C:\s\user.txt".into(), user: r"C:\s\user.txt".into(),
exclude: r"C:\s\exclude.txt".into(), exclude: r"C:\s\exclude.txt".into(),
auto: r"C:\s\learned\auto.txt".into(), auto: r"C:\s\learned\auto.txt".into(),
extras: None,
} }
} }
fn extras() -> Extras {
Extras {
lua: r"C:\x\lua\".into(),
z2k_lua: r"C:\x\z2k\files\lua\".into(),
auto_lua: "/cygdrive/c/s/learned/auto.txt".into(),
exclude_lua: vec!["/cygdrive/c/s/exclude.txt".into()],
}
}
#[test]
fn verdicts_route_what_zapret2_fixes_direct_and_the_rest_by_the_proxy() {
let user = "^pinned.example\n# a comment\ncom\n203.0.113.5\nbad entry\n";
let auto = "learned.example\nnotyet.example\ncut.example\nleft.example\n";
let verdicts = "works\tlearned.example\ttcp\t\t1\nworks\tcut.example\ttcp\t\t1\nstalls\tcut.example\tcutoff\t\t2\n\
works\tleft.example\ttcp\t\t1\nunfixable\tdead.example\ttcp\t\t3\nunfixable\tquic.example\tudp\t\t3\n\
blocked\t198.51.100.7\tip\t\t4\nunfixable\tgone.example\ttcp\t\t3\nretry\tgone.example\ttcp\t\t5\n";
let (direct, proxy) = routing(user, Some(auto), "left.example\n", verdicts);
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["learned.example", "pinned.example"]));
assert_eq!(direct["rules"][1]["ip_cidr"], serde_json::json!(["203.0.113.5/32"]));
assert_eq!(proxy["rules"][0]["domain_suffix"], serde_json::json!(["dead.example"]), "gone.example's last verdict clears it");
assert_eq!(proxy["rules"][1], serde_json::json!({ "network": ["udp"], "port": [443], "domain_suffix": ["quic.example"] }));
assert_eq!(proxy["rules"][2]["ip_cidr"], serde_json::json!(["198.51.100.7/32"]));
// Learning off: the pinned ones alone.
let (direct, _) = routing(user, None, "", verdicts);
assert_eq!(direct["rules"][0]["domain_suffix"], serde_json::json!(["pinned.example"]));
}
#[test]
fn the_extended_detector_learns_in_place_of_nfqws2() {
let z = Zapret2 { strategy_log: true, ..Default::default() };
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
let p = Paths { extras: Some(extras()), ..paths() };
let a = args(&z, &s, &p, false).unwrap();
let inits: Vec<&String> = a.iter().filter(|x| x.starts_with("--lua-init=")).collect();
assert_eq!(inits.len(), 3 + 6, "zapret's, then upstream's layers: {inits:?}");
assert_eq!(inits[3], r"--lua-init=@C:\x\lua\public-suffix-hostkey.lua");
assert_eq!(inits[5], r"--lua-init=@C:\x\z2k\files\lua\z2k-state-persist.lua");
assert!(inits[7].ends_with("detect.lua") && inits[8].ends_with("strategy-log.lua"));
let learn = a.iter().find(|x| x.starts_with("--lua-desync=ps_learn:")).expect("a learning profile");
assert!(learn.starts_with("--lua-desync=ps_learn:auto=/cygdrive/c/s/learned/auto.txt:exclude=/cygdrive/c/s/exclude.txt:fails="), "{learn}");
assert!(learn.ends_with(":win=32:log"));
assert!(a.iter().any(|x| x.starts_with("--lua-desync=ps_watch:")), "the stall watch, where <STALLWATCH> was");
assert!(!a.iter().any(|x| x.starts_with("--hostlist-auto=")), "nfqws2's own learning is off");
let raw = a.iter().find(|x| x.starts_with("--wf-raw-part=")).expect("the TLS replies' filter");
assert!(raw.contains("tcp.Payload[0] == 0x16") && raw.contains("tcp.SrcPort == 443"), "{raw}");
}
#[test]
fn z2k_fills_its_tokens() {
let plain = "--filter-tcp=443 --hostlist-exclude=@ROOT@/lists/whitelist.txt @ESUF@ --lua-desync=circular:fails=3 --new --filter-tcp=443 --filter-l7=tls <HOSTLIST> @HSUF@";
let learn = "--filter-tcp=443 @STALLWATCH@ --lua-desync=circular:fails=3 --new --filter-tcp=443 --lua-desync=ps_learn:auto=@AUTO@:exclude=@ROOT@/lists/whitelist.txt,@EXCLUDE@:fails=@FAILS@:time=@TIME@:inseq=@INSEQ@:retrans=@RETRANS@:win=32@LEARNEXTRA@";
let s = z2k(plain, learn, "--blob=a:@@Z2K@/files/fake/a.bin", "NFQWS2_PORTS_TCP=80,443\nNFQWS2_PORTS_UDP=443\n", "/cygdrive/c/x/z2k", "/cygdrive/c/x/z2k/root", "/cygdrive/c/x/z2k/files/lua/").unwrap();
assert_eq!(s.blob_args, ["--blob=a:@/cygdrive/c/x/z2k/files/fake/a.bin"]);
assert!(s.lua_init[0].ends_with("z2k-alert.lua") && s.daemon_args == ["--ipcache-hostname=1"]);
let mut z = Zapret2 { strategy_source: StrategySource::Z2k, ..Default::default() };
z.domains = vec!["mine.example".into()];
// Without the detector: the plain set, our lists where the markers are.
z.auto_hostlist.extended_detection = false;
let a = args(&z, &s, &Paths { extras: Some(extras()), ..paths() }, false).unwrap().join(" ");
assert!(a.contains("--hostlist-exclude=/cygdrive/c/x/z2k/root/lists/whitelist.txt --hostlist-exclude=C:\\s\\exclude.txt"), "{a}");
assert!(a.contains("--hostlist-auto=C:\\s\\learned\\auto.txt") && a.contains("--hostlist-domains=mine.example"), "{a}");
assert!(a.contains("--lua-init=@/cygdrive/c/x/z2k/files/lua/z2k-alert.lua"));
// With it: the learning set, every token filled.
z.auto_hostlist.extended_detection = true;
let a = args(&z, &s, &Paths { extras: Some(extras()), ..paths() }, false).unwrap().join(" ");
assert!(!a.contains('@') || !a.contains("@AUTO@"), "{a}");
assert!(a.contains("ps_learn:auto=/cygdrive/c/s/learned/auto.txt:exclude=/cygdrive/c/x/z2k/root/lists/whitelist.txt,/cygdrive/c/s/exclude.txt:fails=3"), "{a}");
assert!(a.contains("--lua-desync=ps_watch:"), "{a}");
assert!(!a.contains("@STALLWATCH@") && !a.contains("@LEARNEXTRA@") && !a.contains("@HSUF@") && !a.contains("@ESUF@"), "{a}");
}
#[test] #[test]
fn keenetic_is_read_and_patched_as_upstream_does() { fn keenetic_is_read_and_patched_as_upstream_does() {
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap(); let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
+85
View File
@@ -230,3 +230,88 @@ fn no_outbounds_is_an_error() {
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err(); let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("no proxy outbounds")); assert!(err.0.contains("no proxy outbounds"));
} }
#[test]
fn auto_proxy_adds_probe_listeners_and_learned_rules() {
let dir = scratch("autoproxy");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["blocked.example"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let mut state = State::default();
let render_with = |state: &State| {
render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap()
};
let r = render_with(&state);
// direct, then the first exit: maxExits 2.
assert_eq!(r.probe_exits.iter().map(|x| (x.tag.as_str(), x.port)).collect::<Vec<_>>(), [("direct", 18540), ("nl", 18541)]);
let sb = r.sing_box.unwrap();
let probe_in: Vec<&Value> = sb["inbounds"].as_array().unwrap().iter().filter(|i| i["tag"].as_str().unwrap().starts_with("probe-in-")).collect();
assert_eq!(probe_in.len(), 2);
assert_eq!(probe_in[1]["users"], json!([{ "username": "hop", "password": "hop-pass" }]));
let rules = sb["route"]["rules"].as_array().unwrap();
let guard = rules.iter().position(|r| r["domain"] == json!(["localhost"])).unwrap();
let pin = rules.iter().position(|r| r["inbound"] == json!(["probe-in-1"])).unwrap();
assert!(pin > guard, "the probes stay behind the loopback guard");
assert_eq!(rules.last().unwrap(), &json!({ "rule_set": ["autoproxy-1"], "outbound": "nl" }));
assert!(sb["dns"]["rules"].as_array().unwrap().contains(&json!({ "rule_set": ["autoproxy-1"], "server": "remote" })));
check_sing_box(&sb, &dir);
// all-bypass: everything direct, learned routes too.
state.route_mode = Some(RouteMode::AllBypass);
let sb = render_with(&state).sing_box.unwrap();
assert!(!sb["route"]["rules"].as_array().unwrap().iter().any(|r| r["rule_set"] == json!(["autoproxy-1"]) && r.get("outbound").is_some()));
}
#[test]
fn auto_proxy_never_routes_what_it_excludes() {
let dir = scratch("autoproxy-exclude");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
cfg.proxy.auto_proxy.exclude = vec!["intranet.example.com".into()];
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["example.com"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(
sb["route"]["rules"].as_array().unwrap().last().unwrap(),
&json!({ "type": "logical", "mode": "and", "rules": [{ "rule_set": ["autoproxy-1"] }, { "domain_suffix": ["intranet.example.com"], "invert": true }], "outbound": "nl" })
);
check_sing_box(&sb, &dir);
}
#[test]
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
let dir = scratch("zapret2-sync");
let (direct, proxy) = (dir.join("direct.json"), dir.join("proxy.json"));
std::fs::write(&direct, r#"{"version":1,"rules":[{"domain_suffix":["fixed.example"]}]}"#).unwrap();
std::fs::write(&proxy, r#"{"version":1,"rules":[{"domain_suffix":["unfixable.example"]}]}"#).unwrap();
let cfg = base();
let mut e = env(&dir);
e.windows = false;
e.zapret2_direct_rule_set = Some(direct.to_string_lossy().into());
e.zapret2_proxy_rule_set = Some(proxy.to_string_lossy().into());
let render_with = |state: &State| render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap().sing_box.unwrap();
let sb = render_with(&State::default());
let rules = sb["route"]["rules"].as_array().unwrap();
let n = rules.len();
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
assert_eq!(rules[n - 1], json!({ "rule_set": ["zapret-hosts"], "outbound": "direct" }));
check_sing_box(&sb, &dir);
// all-proxy keeps no direct lists; all-bypass sends everything direct.
let mut state = State { route_mode: Some(RouteMode::AllProxy), ..Default::default() };
let tags = |sb: &Value| sb["route"]["rules"].as_array().unwrap().iter().filter_map(|r| r["rule_set"][0].as_str().map(str::to_owned)).collect::<Vec<_>>();
assert_eq!(tags(&render_with(&state)), ["zapret-unfixable"]);
state.route_mode = Some(RouteMode::AllBypass);
assert!(tags(&render_with(&state)).is_empty());
}
+1
View File
@@ -17,6 +17,7 @@ anyhow.workspace = true
serde_json.workspace = true serde_json.workspace = true
tokio.workspace = true tokio.workspace = true
clap.workspace = true clap.workspace = true
rpassword.workspace = true
[dev-dependencies] [dev-dependencies]
serde_json.workspace = true serde_json.workspace = true
+302 -2
View File
@@ -54,6 +54,16 @@ enum Cmd {
#[command(subcommand)] #[command(subcommand)]
verb: TgVerb, verb: TgVerb,
}, },
/// AmneziaWG profiles: the system-wide ones started and stopped.
Awg {
#[command(subcommand)]
verb: Option<AwgVerb>,
},
/// whitelist-bypass creators and joiners.
Wl {
#[command(subcommand)]
verb: Option<WlVerb>,
},
/// The backend programs: what is installed, and installing them (administrator). /// The backend programs: what is installed, and installing them (administrator).
Components { Components {
#[command(subcommand)] #[command(subcommand)]
@@ -67,6 +77,39 @@ enum TgVerb {
Link, Link,
} }
#[derive(Subcommand)]
enum AwgVerb {
/// Profiles and their state.
List,
/// Start a system-wide profile's tunnel.
On { profile: String },
/// Stop it.
Off { profile: String },
/// Its tunnel's log.
Log {
profile: String,
#[arg(short = 'n', long, default_value_t = 50)]
lines: usize,
},
}
#[derive(Subcommand)]
enum WlVerb {
/// Creators and joiners, and their state.
List,
/// The call a creator made, for its joiner.
Link { creator: String },
/// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for
/// an email and password without one.
Auth { creator: String, file: Option<String> },
/// The call link a joiner joins (or - for stdin).
Join { joiner: String, link: String },
/// Start a new call, if the platform closed the old one.
New { creator: String },
/// Restart all of them, or the one named.
Restart { name: Option<String> },
}
#[derive(Subcommand)] #[derive(Subcommand)]
enum ZapretVerb { enum ZapretVerb {
Status, Status,
@@ -148,6 +191,39 @@ enum ProxyVerb {
}, },
/// The config the backend runs. /// The config the backend runs.
Config, Config,
/// autoProxy: what it routed and where; probing, learning, forgetting.
Auto {
#[command(subcommand)]
verb: Option<AutoVerb>,
},
}
#[derive(Subcommand)]
enum AutoVerb {
/// The routes learned, the exits, what waits.
List,
/// Probe a site (host, or host/path) through the exits, as autoProxy does.
Probe {
target: String,
/// Only these exits (comma-separated), in this order.
#[arg(long, value_delimiter = ',')]
exits: Option<Vec<String>>,
/// Whether this exit carries what direct reaches.
#[arg(long)]
via: Option<String>,
/// Try every exit, not only up to the first that reaches it.
#[arg(long)]
keep_going: bool,
},
/// Probe these hosts now, and route them if they need it.
Learn {
#[arg(required = true)]
hosts: Vec<String>,
},
/// Forget a domain's route: it is probed again when next dialled.
Forget { domain: String },
/// Forget everything learned.
Clear,
} }
#[derive(Subcommand)] #[derive(Subcommand)]
@@ -245,9 +321,13 @@ fn read_arg(value: &str) -> Result<String> {
} }
} }
/// A file's text, or stdin's for -.
fn read_arg_file(file: &str) -> Result<String> {
if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) }
}
fn read_file_arg(file: &str) -> Result<Value> { fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? }; serde_json::from_str(&read_arg_file(file)?).with_context(|| format!("{file} is not JSON"))
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
} }
async fn status(ctl: &Ctl) -> Result<()> { async fn status(ctl: &Ctl) -> Result<()> {
@@ -497,6 +577,79 @@ async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
} }
}, },
ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?), ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?),
ProxyVerb::Auto { verb } => auto(ctl, verb).await?,
}
Ok(())
}
async fn auto(ctl: &Ctl, verb: Option<AutoVerb>) -> Result<()> {
match verb.unwrap_or(AutoVerb::List) {
AutoVerb::List => {
let r = ctl.call(Request::AutoList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let state = match (r["enabled"] == true, r["running"] == true) {
(false, _) => "off (proxy.autoProxy.enable)",
(true, false) => "on, waiting for the local proxy",
(true, true) => "running",
};
println!("autoProxy: {state}");
if let Some(e) = r["egress"].as_str() {
println!(" egress {e}");
}
let domains = r["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
println!(" nothing routed yet");
} else {
println!(" {:<32} {:<20} PROBED AS", "DOMAIN", "EXIT");
for d in &domains {
println!(" {:<32} {:<20} {}", d["domain"].as_str().unwrap_or(""), d["exit"].as_str().unwrap_or(""), d["host"].as_str().unwrap_or("-"));
}
}
for e in r["exits"].as_array().into_iter().flatten().filter(|e| e["bad"] == true) {
let by: Vec<&str> = e["badBy"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let why = if by.is_empty() { format!("{} strike(s)", e["strikes"]) } else { by.join(", ") };
println!(" bad exit {} (probed last): {why}", e["tag"].as_str().unwrap_or(""));
}
let censored = r["censored"].as_array().map_or_else(|| r["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
println!(" {} host(s) judged, {censored} left to zapret, {} waiting to be probed", r["hostsJudged"], r["backlog"]);
}
AutoVerb::Probe { target, exits, via, keep_going } => {
let r = ctl.call(Request::AutoProbe { target, exits, via: via.clone(), keep_going }).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
println!(" domain {}", r["domain"].as_str().unwrap_or(""));
let chosen = (r["exit"].as_str().unwrap_or(""), r["path"].as_str().unwrap_or(""));
println!(" exits");
for row in r["rows"].as_array().into_iter().flatten() {
let (tag, path) = (row["tag"].as_str().unwrap_or(""), row["path"].as_str().unwrap_or(""));
let f: ps_core::autoproxy::Fetch = serde_json::from_value(row["fetch"].clone()).unwrap_or_default();
let mark = if (tag, path) == chosen { " <- chosen" } else { "" };
println!(" {tag:<18} {path:<12} {:<44} {}{mark}", ps_core::autoproxy::describe(&f), row["judgement"].as_str().unwrap_or(""));
}
let verdict = r["verdict"].as_str().unwrap_or("");
match via {
Some(v) if verdict == "ok" => println!(" verdict {v} answers it as well as direct does - it can carry it"),
Some(v) => println!(" verdict {v} answers it worse than direct does"),
None => println!(" verdict {}", ps_core::autoproxy::verdict_text(verdict, r["exit"].as_str())),
}
}
AutoVerb::Learn { hosts } => {
let r = ctl.call(Request::AutoLearn { hosts }).await?;
println!("{} host(s) queued; the prober runs now (proxy-ctl logs proxy-suite-autoproxy)", r["queued"]);
}
AutoVerb::Forget { domain } => {
ctl.call(Request::AutoForget { domain: Some(domain.clone()) }).await?;
println!("forgot {domain}");
}
AutoVerb::Clear => {
ctl.call(Request::AutoForget { domain: None }).await?;
println!("forgot everything learned");
}
} }
Ok(()) Ok(())
} }
@@ -549,6 +702,151 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
Ok(()) Ok(())
} }
async fn awg(ctl: &Ctl, verb: Option<AwgVerb>) -> Result<()> {
match verb.unwrap_or(AwgVerb::List) {
AwgVerb::List => {
let r = ctl.call(Request::AwgList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let profiles = r["profiles"].as_array().cloned().unwrap_or_default();
if profiles.is_empty() {
println!("No AmneziaWG profiles configured.");
return Ok(());
}
if r["enabled"] != true {
println!("AmneziaWG is off (amneziaWg.enable).");
}
println!(" {:<24} {:<12} {:<12} INTERFACE", "PROFILE", "KIND", "STATUS");
for p in profiles {
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => "system VPN",
"userspace" => "outbound",
"singBox" => "outbound (WG)",
k => k,
};
println!(" {:<24} {:<12} {:<12} {}", p["name"].as_str().unwrap_or(""), kind, p["state"].as_str().unwrap_or(""), p["interface"].as_str().unwrap_or("-"));
}
}
AwgVerb::On { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: true }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Off { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: false }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Log { profile, lines } => {
let r = ctl.call(Request::AwgLog { name: profile, lines }).await?;
for l in r["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {
println!("{l}");
}
}
}
Ok(())
}
/// A login for the DION and Bitrix creators, which log in on their own from it.
fn password_login(platform: &str, name: &str) -> Result<String> {
let fields: &[&str] = match platform {
"dion" => &["email", "password"],
"bitrix" => &["email", "password", "portal"],
_ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} <file>"),
};
let mut login = serde_json::Map::new();
for field in fields {
let value = if *field == "password" {
rpassword::prompt_password("Password: ")?
} else {
eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]);
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
line.trim().to_owned()
};
let value = match *field {
"portal" => {
let portal = value.trim_end_matches('/');
if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") }
}
_ => value,
};
login.insert((*field).to_owned(), Value::String(value));
}
Ok(Value::Object(login).to_string())
}
async fn wl(ctl: &Ctl, verb: Option<WlVerb>) -> Result<()> {
let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"));
match verb.unwrap_or(WlVerb::List) {
WlVerb::List => {
let r = ctl.call(Request::WlList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let list = r.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!("No whitelist-bypass creators or joiners configured.");
return Ok(());
}
println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM");
for w in list {
let f = |k: &str| w[k].as_str().unwrap_or("").to_owned();
println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state"));
}
}
WlVerb::Link { creator } => {
let r = ctl.call(Request::WlLink { name: creator }).await?;
println!("{}", r["link"].as_str().unwrap_or(""));
}
WlVerb::Auth { creator, file } => {
let login = match file {
Some(f) => {
let text = read_arg_file(&f)?;
serde_json::from_str::<Value>(&text).context("not a cookies export, not valid JSON")?;
text
}
None => {
let list = ctl.call(Request::WlList).await?;
let platform = list
.as_array()
.into_iter()
.flatten()
.find(|w| w["name"] == creator.as_str() && w["role"] == "creator")
.and_then(|w| w["platform"].as_str().map(str::to_owned))
.with_context(|| format!("no whitelist-bypass creator '{creator}'"))?;
password_login(&platform, &creator)?
}
};
say(&ctl.call(Request::WlAuth { name: creator, login }).await?);
}
WlVerb::Join { joiner, link } => {
let link = read_arg(&link)?;
say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?);
}
WlVerb::New { creator } => {
say(&ctl.call(Request::WlNew { name: creator.clone() }).await?);
println!("Its joiner needs the new call: proxy-ctl wl link {creator}");
}
WlVerb::Restart { name } => {
let list = ctl.call(Request::WlList).await?;
let units: Vec<String> = list
.as_array()
.into_iter()
.flatten()
.filter(|w| name.as_deref().is_none_or(|n| w["name"] == n))
.map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or("")))
.collect();
if units.is_empty() {
bail!("no such whitelist-bypass creator or joiner");
}
ctl.call(Request::Restart { units }).await?;
}
}
Ok(())
}
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> { async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
match verb.unwrap_or(ComponentsVerb::List) { match verb.unwrap_or(ComponentsVerb::List) {
ComponentsVerb::List => { ComponentsVerb::List => {
@@ -601,6 +899,8 @@ async fn real_main() -> Result<()> {
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?, Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Zapret { verb } => zapret(&ctl, verb).await?, Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
Cmd::Components { verb } => components(&ctl, verb).await?, Cmd::Components { verb } => components(&ctl, verb).await?,
Cmd::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Awg { verb } => awg(&ctl, verb).await?,
Cmd::Tg { verb: TgVerb::Link } => { Cmd::Tg { verb: TgVerb::Link } => {
let r = ctl.call(Request::TgLinks).await?; let r = ctl.call(Request::TgLinks).await?;
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) { for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
+9 -1
View File
@@ -230,7 +230,15 @@ fn an_ssh_tunnel() {
), ),
) )
.unwrap(); .unwrap();
let _sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap()); let mut sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap());
// One that cannot start says why, here (as root it needs its privilege separation: the
// directory /var/empty and the user sshd).
wait_for("sshd", Duration::from_secs(10), || {
if let Ok(Some(status)) = sshd.0.try_wait() {
panic!("sshd exited ({status}):\n{}", std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default());
}
std::net::TcpStream::connect(("127.0.0.1", ssh_port)).is_ok()
});
let state = dir.join("state"); let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap(); std::fs::create_dir_all(&state).unwrap();
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

+34
View File
@@ -0,0 +1,34 @@
//! The Windows build carries the app's icon as its resource 1, where GPUI loads its windows'
//! icon from (and Explorer, the Start Menu and Settings > Apps show it). The resource compiler
//! is LLVM's (`llvm-rc`, in the dev shell), or `rc.exe` on Windows; `PS_GUI_RC` names another.
//! (Not `RC`: the dev shell sets that to MinGW's windres, which takes other arguments.) Without
//! one the app builds with Windows' default icon, and says so; tools/package.sh refuses that.
use std::path::PathBuf;
use std::process::Command;
fn main() {
let icon = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("assets/proxy-suite.ico");
println!("cargo:rerun-if-changed={}", icon.display());
println!("cargo:rerun-if-env-changed=PS_GUI_RC");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let rc = out.join("app.rc");
let res = out.join("app.res");
// The resource script's strings are C strings: backslashes doubled.
std::fs::write(&rc, format!("1 ICON \"{}\"\n", icon.display().to_string().replace('\\', "\\\\"))).unwrap();
let compiler = std::env::var("PS_GUI_RC").unwrap_or_else(|_| if cfg!(windows) { "rc.exe".into() } else { "llvm-rc".into() });
let mut command = Command::new(&compiler);
command.arg("/nologo");
if compiler.contains("llvm-rc") {
// Nothing to preprocess, so no C compiler needed for it.
command.arg("/no-preprocess");
}
match command.arg("/fo").arg(&res).arg(&rc).status() {
Ok(s) if s.success() => println!("cargo:rustc-link-arg-bins={}", res.display()),
Ok(s) => println!("cargo:warning=the app's icon: {compiler} failed ({s}); building without it"),
Err(e) => println!("cargo:warning=the app's icon: no {compiler} ({e}); building without it"),
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ use std::borrow::Cow;
use gpui_kit::*; use gpui_kit::*;
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power]); gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock]);
pub struct AppAssets; pub struct AppAssets;
+206
View File
@@ -0,0 +1,206 @@
//! AmneziaWG: its profiles, system-wide VPNs (started and stopped here, their tunnel's log) or
//! outbounds of the proxy; one added from an AmneziaVPN vpn:// link or a .conf, or removed.
use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const KINDS: [(&str, &str); 3] = [("vpn", "System-wide VPN"), ("userspace", "Outbound (AmneziaWG)"), ("singBox", "Outbound (plain WireGuard)")];
pub struct AmneziaWgPage {
model: Entity<Model>,
name: Entity<InputState>,
text: Entity<TextareaState>,
kind: usize,
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// A profile's tunnel log, while shown.
logs: BTreeMap<String, Result<Vec<String>, String>>,
_subscriptions: Vec<Subscription>,
}
impl AmneziaWgPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("home"));
let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder("vpn://… from AmneziaVPN, or a .conf: [Interface] …"));
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
this.load(cx);
}
})];
let mut this = Self { model, name, text, kind: 0, list: Ok(Value::Null), loaded_at: None, logs: BTreeMap::new(), _subscriptions: subscriptions };
this.load(cx);
this
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AwgList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
let what = format!("{name}: {}", if on { "tunnel up" } else { "tunnel down" });
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn toggle_log(&mut self, name: String, cx: &mut Context<Self>) {
if self.logs.remove(&name).is_some() {
cx.notify();
return;
}
let job = self.model.read(cx).bridge().call(Request::AwgLog { name: name.clone(), lines: 30 });
cx.spawn(async move |this, cx| {
let r = job.await.map(|v| v["lines"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()).map_err(|e| format!("{e:#}"));
this.update(cx, |this, cx| {
this.logs.insert(name, r);
cx.notify();
})
.ok();
})
.detach();
}
fn add(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let name = self.name.read(cx).value().trim().to_owned();
let text = self.text.read(cx).value().to_string();
let kind = KINDS[self.kind].0;
// Checked here first, for a message at once.
if let Err(e) = edits::add_awg_profile(&mut serde_json::json!({}), &name, &text, kind) {
window.push_notification(Notification::error(format!("{e:#}")), cx);
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
self.text.update(cx, |s, cx| s.set_value("", window, cx));
let what = format!("AmneziaWG profile '{name}' added");
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_awg_profile(c, &name, &text, kind), cx));
}
fn remove(&mut self, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(format!("AmneziaWG profile '{name}' removed"), move |c| edits::remove_awg_profile(c, &name), cx));
}
}
impl Render for AmneziaWgPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let body = page("AmneziaWG", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let on = m.config()["amneziaWg"]["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("awg-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "AmneziaWG is on" } else { "AmneziaWG is off" },
move |c| {
edits::set_path(c, &["amneziaWg", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint(
"WireGuard with AmneziaVPN's obfuscation. A system-wide profile is a VPN of its own (a network adapter, its routes and DNS); with one peer that takes everything, it also blocks what would leave outside the tunnel. An outbound profile is one more exit for the proxy, with nothing else changed.",
cx,
));
let mut profiles = card("Profiles", Some(Button::new("awg-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))).into_any_element()), cx);
match &self.list {
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let list = l["profiles"].as_array().cloned().unwrap_or_default();
if list.is_empty() {
profiles = profiles.child(hint("None yet: add one below.", cx));
}
for (i, p) in list.iter().enumerate() {
let name = p["name"].as_str().unwrap_or("").to_owned();
let vpn = p["kind"] == "vpn";
let state = p["state"].as_str().unwrap_or("").to_owned();
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => Tag::info().child("system VPN"),
"userspace" => Tag::secondary().child("outbound"),
_ => Tag::secondary().child("outbound (WireGuard)"),
};
let mut line = div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(kind)
.child(if state == "windows-only" { Tag::secondary().child("Windows only") } else { state_tag(&state) })
.child(div().flex_1());
if vpn {
let (n1, n2) = (name.clone(), name.clone());
let running = matches!(state.as_str(), "active" | "activating");
line = line
.child(Button::new(("awg-log", i)).small().ghost().label("Log").on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
.child(
Switch::new(("awg-on", i))
.checked(running)
.disabled(!on)
.on_change(cx.listener(move |this, v: &bool, _, cx| this.set(n2.clone(), *v, cx))),
);
}
let n3 = name.clone();
line = line.child(Button::new(("awg-remove", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove(n3.clone(), cx))));
let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line);
match self.logs.get(&name) {
Some(Ok(lines)) => {
let text = if lines.is_empty() { "(no log yet)".to_owned() } else { lines.join("\n") };
row = row.child(div().text_xs().font_family("monospace").text_color(cx.theme().muted_foreground).child(text));
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
None => {}
}
profiles = profiles.child(row);
}
}
}
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| label)).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
this.kind = *ix;
cx.notify();
}));
let add = card("Add a profile", Some(Button::new("awg-add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (also the adapter's)")).child(Input::new(&self.name)))
.child(kinds)
.child(Textarea::new(&self.text))
.child(hint("The link or .conf stays in the service's configuration, which only you and administrators read. Starting at sign-in (autostart), the endpoint and the rest are in Settings, under amneziaWg.profiles.", cx));
body.child(about).child(profiles).child(add)
}
}
+338
View File
@@ -0,0 +1,338 @@
//! autoProxy: on or off; a site probed through each exit, or learned now; the sites it routed
//! and through what, each forgotten on its own; the exits, bad ones marked; what it never
//! touches, and how slow a site must be to be moved.
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::{Value, json};
use super::widgets::{card, hint, page};
use crate::model::Model;
pub struct AutoProxyPage {
model: Entity<Model>,
site: Entity<InputState>,
exclude: Entity<TextareaState>,
slow: Entity<InputState>,
/// What the service listed last, or why it could not.
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// The last probe: its answer, or that it runs.
probe: Option<Result<Value, String>>,
probing: bool,
/// The exclusions and threshold the inputs were last filled from (see the DPI page).
shown: (String, String),
_subscriptions: Vec<Subscription>,
}
impl AutoProxyPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let site = cx.new(|cx| InputState::new(window, cx).placeholder("example.com"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder("intranet.example — one per line"));
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
this.sync(window, cx);
// The listing with the service's own refresh, every few seconds at most.
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(5)) {
this.load(cx);
}
})];
let mut this = Self {
model,
site,
exclude,
slow,
list: Ok(Value::Null),
loaded_at: None,
probe: None,
probing: false,
shown: Default::default(),
_subscriptions: subscriptions,
};
this.sync(window, cx);
this.load(cx);
this
}
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let a = self.model.read(cx).config()["proxy"]["autoProxy"].clone();
let exclude = a["exclude"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n");
let slow = a["slowBelowKiBps"].as_u64().map(|n| n.to_string()).unwrap_or_default();
let fresh = (exclude, slow);
if fresh != self.shown {
if self.exclude.read(cx).value() == self.shown.0.as_str() {
let v = fresh.0.clone();
self.exclude.update(cx, |s, cx| s.set_value(v, window, cx));
}
if self.slow.read(cx).value() == self.shown.1.as_str() {
let v = fresh.1.clone();
self.slow.update(cx, |s, cx| s.set_value(v, window, cx));
}
self.shown = fresh;
}
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AutoList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let site = self.site.read(cx).value().trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_owned();
if site.is_empty() {
window.push_notification(Notification::error("Type a site first: example.com"), cx);
return None;
}
Some(site)
}
fn probe(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(target) = self.site(window, cx) else { return };
self.probing = true;
self.probe = None;
cx.notify();
let job = self.model.read(cx).bridge().call(Request::AutoProbe { target, exits: None, via: None, keep_going: true });
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.probing = false;
this.probe = Some(r.map_err(|e| format!("{e:#}")));
cx.notify();
})
.ok();
})
.detach();
}
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(site) = self.site(window, cx) else { return };
let site = site.split('/').next().unwrap_or("").to_owned();
self.model.update(cx, |m, cx| m.request(format!("{site}: probed now, routed if it needs it"), Request::AutoLearn { hosts: vec![site] }, cx));
}
fn forget(&mut self, domain: Option<String>, cx: &mut Context<Self>) {
let what = domain.as_ref().map_or("Everything learned is forgotten".to_owned(), |d| format!("{d} is forgotten"));
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
let slow_text = self.slow.read(cx).value().trim().to_owned();
let Ok(slow) = (if slow_text.is_empty() { Ok(0) } else { slow_text.parse::<u32>() }) else {
window.push_notification(Notification::error(format!("“{slow_text}” is not a speed in KiB/s (0 turns it off)")), cx);
return;
};
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
self.model.update(cx, |m, cx| {
m.edit(
"autoProxy saved",
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "exclude"], json!(exclude));
edits::set_path(c, &["proxy", "autoProxy", "slowBelowKiBps"], json!(slow));
Ok(())
},
cx,
)
});
}
}
fn row(cx: &App) -> Div {
div().h_flex().gap_3().items_center().py_2().border_t_1().border_color(cx.theme().border)
}
impl Render for AutoProxyPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let a = m.config()["proxy"]["autoProxy"].clone();
let body = page("autoProxy", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let list = self.list.clone();
let on = a["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("ap-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "autoProxy is on" } else { "autoProxy is off" },
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
let state = match (on, running) {
(false, _) => Tag::secondary().child("off"),
(true, false) => Tag::warning().child("waiting for the local proxy"),
(true, true) => Tag::success().child("running"),
};
let about = card("autoProxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state))
.child(hint(
"It probes the sites your apps reach directly through each exit, direct first. A site blocked directly but reached through an exit is routed through it; one that crawls directly can move to an exit that carries it faster. Blocks zapret can fix stay direct.",
cx,
));
let probing = self.probing;
let mut try_card = card("Probe or learn a site", None, cx)
.child(hint("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", cx))
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(&self.site)))
.child(
Button::new("ap-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { "Probing…" } else { "Probe" })
.disabled(probing || !running)
.on_click(cx.listener(|this, _, window, cx| this.probe(window, cx))),
)
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label("Learn").disabled(!running).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
);
match &self.probe {
Some(Ok(p)) => {
let verdict = p["verdict"].as_str().unwrap_or("");
let text = match verdict {
"ok" => "Reachable directly: nothing to do".to_owned(),
"destination" => format!("Blocked directly: routed through {}", p["exit"].as_str().unwrap_or("an exit")),
"censor" => "Cut on the way: zapret's to fix, left direct".to_owned(),
"both-fail" => "Fails through every exit: not a block".to_owned(),
"unreachable" => "No exit reaches it at all".to_owned(),
v => v.to_owned(),
};
try_card = try_card.child(div().font_medium().child(text));
for r in p["rows"].as_array().into_iter().flatten() {
let f = &r["fetch"];
let what = match f["status"].as_u64() {
Some(s) => format!("{s}, {} bytes{}", f["bytes"], f["block"].as_str().filter(|b| !b.is_empty()).map(|b| format!(", {b} page")).unwrap_or_default()),
None => format!("no answer ({})", f["error"].as_str().unwrap_or("")),
};
let judgement = r["judgement"].as_str().unwrap_or("");
let tag = match judgement {
"ok" => Tag::success(),
"dead" => Tag::danger(),
_ => Tag::warning(),
};
try_card = try_card.child(
row(cx)
.text_sm()
.child(div().w(px(150.)).truncate().child(r["tag"].as_str().unwrap_or("").to_owned()))
.child(div().w(px(100.)).text_color(cx.theme().muted_foreground).child(r["path"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().child(what))
.child(tag.child(judgement.to_owned())),
);
}
}
Some(Err(e)) => try_card = try_card.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
None => {}
}
let mut routed = card(
"Routed sites",
Some(
div()
.h_flex()
.gap_2()
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label("Forget all").on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.into_any_element(),
),
cx,
);
match &list {
Err(e) => routed = routed.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let domains = l["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
routed = routed.child(hint("Nothing routed yet.", cx));
}
for (i, d) in domains.iter().enumerate() {
let domain = d["domain"].as_str().unwrap_or("").to_owned();
let why = if d["verdict"] == "slow" { Tag::warning().child("slow") } else { Tag::danger().child("blocked") };
let forget = domain.clone();
routed = routed.child(
row(cx)
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
.child(why)
.child(div().w(px(160.)).truncate().text_sm().child(format!("via {}", d["exit"].as_str().unwrap_or(""))))
.child(Button::new(("ap-forget", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.forget(Some(forget.clone()), cx)))),
);
}
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
routed = routed.child(hint(
format!(
"{} site(s) judged; {censored} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
l["hostsJudged"].as_u64().unwrap_or(0),
l["backlog"].as_u64().unwrap_or(0),
l["slowWaiting"].as_u64().unwrap_or(0)
),
cx,
));
}
}
let mut exits = card("Exits", None, cx).child(hint("Probed one per network first. One that two sites refused is bad, and probed last.", cx));
if let Ok(l) = &list {
for e in l["exits"].as_array().into_iter().flatten() {
let bad = e["bad"] == true;
exits = exits.child(
row(cx)
.child(div().w(px(180.)).truncate().font_medium().child(e["tag"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().text_sm().text_color(cx.theme().muted_foreground).child(format!(
"{} {}",
e["ip"].as_str().unwrap_or(""),
e["asn"].as_str().unwrap_or("")
)))
.child(if bad { Tag::danger().child("bad") } else { Tag::success().child("ok") }),
);
}
}
let options = card("Options", Some(Button::new("ap-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
.child(
div()
.h_flex()
.gap_4()
.items_start()
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Never probe or route (with their subdomains)")).child(Textarea::new(&self.exclude)))
.child(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child("Move sites slower than (KiB/s, 0: never)")).child(Input::new(&self.slow))),
)
.child(hint("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", cx));
body.child(about).child(try_card).child(routed).child(exits).child(options)
}
}
+28 -1
View File
@@ -15,6 +15,7 @@ use super::widgets::{card, hint, page, state_tag};
use crate::model::Model; use crate::model::Model;
const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")]; const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")];
const SOURCES: [(&str, &str); 2] = [("nfqws2-keenetic", "nfqws2-keenetic"), ("z2k", "z2k (per category: YouTube, Discord, QUIC, the RKN list)")];
const GAME_FILTERS: [(&str, &str); 4] = [("null", "Off"), ("all", "TCP and UDP"), ("tcp", "TCP only"), ("udp", "UDP only")]; const GAME_FILTERS: [(&str, &str); 4] = [("null", "Off"), ("all", "TCP and UDP"), ("tcp", "TCP only"), ("udp", "UDP only")];
/// Preset names as the service matches them: without spaces, any case. /// Preset names as the service matches them: without spaces, any case.
@@ -180,7 +181,7 @@ impl Render for DpiPage {
.child(engines) .child(engines)
.child(hint( .child(hint(
if engine == "zapret2" { if engine == "zapret2" {
"zapret2 (winws2) with nfqws2-keenetic's strategies; it learns which sites are blocked as it goes." "zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts."
} else { } else {
"Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists." "Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists."
}, },
@@ -189,9 +190,35 @@ impl Render for DpiPage {
); );
if engine == "zapret2" { if engine == "zapret2" {
let model = self.model.clone();
let source = config["zapret"]["zapret2"]["strategySource"].as_str().unwrap_or("nfqws2-keenetic");
let sources = RadioGroup::horizontal("strategy-source")
.children(SOURCES.map(|(_, label)| label))
.selected_index(SOURCES.iter().position(|(v, _)| *v == source))
.on_change(move |ix, _, cx| {
let (value, label) = SOURCES[*ix];
model.update(cx, |m, cx| {
m.edit(
format!("Strategies: {label}"),
move |c| {
edits::set_path(c, &["zapret", "zapret2", "strategySource"], value.into());
Ok(())
},
cx,
)
})
});
body = body.child( body = body.child(
card("zapret2", None, cx) card("zapret2", None, cx)
.child(div().text_sm().child("Strategies"))
.child(sources)
.child(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config)) .child(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config))
.child(self.option_switch(
"extended-detection",
"Extended detection: also sites blocked only some of the time, and requests that never get an answer",
&["zapret", "zapret2", "autoHostlist", "extendedDetection"],
&config,
))
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config)) .child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)), .child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
); );
+41 -2
View File
@@ -1,6 +1,8 @@
//! The window: a sidebar of pages, the page shown, and what came of each change as a //! The window: a sidebar of pages, the page shown, and what came of each change as a
//! notification. //! notification.
mod amneziawg;
mod autoproxy;
mod components; mod components;
mod dpi; mod dpi;
mod logs; mod logs;
@@ -8,6 +10,7 @@ mod outbounds;
mod overview; mod overview;
mod settings; mod settings;
mod telegram; mod telegram;
mod whitelist;
mod widgets; mod widgets;
use gpui_kit::component::notification::Notification; use gpui_kit::component::notification::Notification;
@@ -23,21 +26,38 @@ pub enum Page {
Overview, Overview,
Dpi, Dpi,
Telegram, Telegram,
Whitelist,
Outbounds, Outbounds,
AutoProxy,
AmneziaWg,
Logs, Logs,
Settings, Settings,
Components, Components,
} }
impl Page { impl Page {
const ALL: [Page; 7] = [Page::Overview, Page::Dpi, Page::Telegram, Page::Outbounds, Page::Logs, Page::Settings, Page::Components]; const ALL: [Page; 10] = [
Page::Overview,
Page::Dpi,
Page::Telegram,
Page::Whitelist,
Page::Outbounds,
Page::AutoProxy,
Page::AmneziaWg,
Page::Logs,
Page::Settings,
Page::Components,
];
fn title(self) -> &'static str { fn title(self) -> &'static str {
match self { match self {
Page::Overview => "Overview", Page::Overview => "Overview",
Page::Dpi => "DPI bypass", Page::Dpi => "DPI bypass",
Page::Telegram => "Telegram proxy", Page::Telegram => "Telegram proxy",
Page::Whitelist => "Whitelist bypass",
Page::Outbounds => "Outbounds", Page::Outbounds => "Outbounds",
Page::AutoProxy => "autoProxy",
Page::AmneziaWg => "AmneziaWG",
Page::Logs => "Logs", Page::Logs => "Logs",
Page::Settings => "Settings", Page::Settings => "Settings",
Page::Components => "Components", Page::Components => "Components",
@@ -49,7 +69,10 @@ impl Page {
Page::Overview => IconName::LayoutDashboard, Page::Overview => IconName::LayoutDashboard,
Page::Dpi => IconName::Shield, Page::Dpi => IconName::Shield,
Page::Telegram => IconName::Send, Page::Telegram => IconName::Send,
Page::Whitelist => IconName::Video,
Page::Outbounds => IconName::Globe, Page::Outbounds => IconName::Globe,
Page::AutoProxy => IconName::Route,
Page::AmneziaWg => IconName::Lock,
Page::Logs => IconName::SquareTerminal, Page::Logs => IconName::SquareTerminal,
Page::Settings => IconName::Settings, Page::Settings => IconName::Settings,
Page::Components => IconName::Package, Page::Components => IconName::Package,
@@ -63,6 +86,10 @@ pub struct AppView {
dpi: Entity<dpi::DpiPage>, dpi: Entity<dpi::DpiPage>,
telegram: Entity<telegram::TelegramPage>, telegram: Entity<telegram::TelegramPage>,
outbounds: Entity<outbounds::OutboundsPage>, outbounds: Entity<outbounds::OutboundsPage>,
/// Made when first shown.
whitelist: Option<Entity<whitelist::WhitelistPage>>,
autoproxy: Option<Entity<autoproxy::AutoProxyPage>>,
amneziawg: Option<Entity<amneziawg::AmneziaWgPage>>,
/// Made when first shown: following the logs starts then. /// Made when first shown: following the logs starts then.
logs: Option<Entity<logs::LogsPage>>, logs: Option<Entity<logs::LogsPage>>,
/// Made when first shown, as it loads the configuration into its editor then. /// Made when first shown, as it loads the configuration into its editor then.
@@ -86,7 +113,7 @@ impl AppView {
let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx)); let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx));
let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx)); let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx));
let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx)); let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx));
Self { model, page: Page::Overview, dpi, telegram, outbounds, logs: None, settings: None, components: None, _subscriptions: subscriptions } Self { model, page: Page::Overview, dpi, telegram, outbounds, whitelist: None, autoproxy: None, amneziawg: None, logs: None, settings: None, components: None, _subscriptions: subscriptions }
} }
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement { fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
@@ -114,7 +141,19 @@ impl Render for AppView {
Page::Overview => overview::render(&self.model, window, cx).into_any_element(), Page::Overview => overview::render(&self.model, window, cx).into_any_element(),
Page::Dpi => self.dpi.clone().into_any_element(), Page::Dpi => self.dpi.clone().into_any_element(),
Page::Telegram => self.telegram.clone().into_any_element(), Page::Telegram => self.telegram.clone().into_any_element(),
Page::Whitelist => {
let model = self.model.clone();
self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element()
}
Page::Outbounds => self.outbounds.clone().into_any_element(), Page::Outbounds => self.outbounds.clone().into_any_element(),
Page::AmneziaWg => {
let model = self.model.clone();
self.amneziawg.get_or_insert_with(|| cx.new(|cx| amneziawg::AmneziaWgPage::new(model, window, cx))).clone().into_any_element()
}
Page::AutoProxy => {
let model = self.model.clone();
self.autoproxy.get_or_insert_with(|| cx.new(|cx| autoproxy::AutoProxyPage::new(model, window, cx))).clone().into_any_element()
}
Page::Logs => { Page::Logs => {
let model = self.model.clone(); let model = self.model.clone();
self.logs.get_or_insert_with(|| cx.new(|cx| logs::LogsPage::new(model, cx))).clone().into_any_element() self.logs.get_or_insert_with(|| cx.new(|cx| logs::LogsPage::new(model, cx))).clone().into_any_element()
+318
View File
@@ -0,0 +1,318 @@
//! whitelist-bypass: its joiners (outbounds of the proxy, through a video call) and creators
//! (the calls' other ends), their state; a joiner's call link given, a creator's shown, its
//! login given (a cookies export, or DION's and Bitrix's email and password); which there are.
use std::collections::BTreeMap;
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const PLATFORMS: [(&str, &str); 5] = [("wbstream", "WB Stream"), ("telemost", "Telemost"), ("dion", "DION"), ("bitrix", "Bitrix24"), ("vk", "VK (creators only)")];
/// A creator's login by email and password, for the platforms that take one.
struct PasswordLogin {
email: Entity<InputState>,
password: Entity<InputState>,
/// Bitrix only: the portal's address.
portal: Option<Entity<InputState>>,
}
pub struct WhitelistPage {
model: Entity<Model>,
name: Entity<InputState>,
platform: usize,
/// Each joiner's link input, by name.
joins: BTreeMap<String, Entity<InputState>>,
/// DION's and Bitrix's creators' login inputs, by name.
logins: BTreeMap<String, PasswordLogin>,
/// Each creator's call link, or why there is none, once asked for.
links: BTreeMap<String, Result<String, String>>,
_subscriptions: Vec<Subscription>,
}
impl WhitelistPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("laptop"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
let mut this = Self { model, name, platform: 0, joins: BTreeMap::new(), logins: BTreeMap::new(), links: BTreeMap::new(), _subscriptions: subscriptions };
this.sync(window, cx);
this
}
/// Inputs for the creators and joiners there are now.
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let w = self.model.read(cx).config()["whitelistBypass"].clone();
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
self.joins.retain(|n, _| joiners.contains(n));
for n in joiners {
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder("the creator's call link")));
}
let creators: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
self.logins.retain(|n, _| creators.iter().any(|(c, p)| c == n && matches!(p.as_str(), "dion" | "bitrix")));
for (n, platform) in creators {
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
let login = PasswordLogin {
email: cx.new(|cx| InputState::new(window, cx).placeholder("email")),
password: cx.new(|cx| InputState::new(window, cx).placeholder("password").masked(true)),
portal: (platform == "bitrix").then(|| cx.new(|cx| InputState::new(window, cx).placeholder("portal.bitrix24.ru"))),
};
self.logins.insert(n, login);
}
}
}
fn add(&mut self, role: &'static str, window: &mut Window, cx: &mut Context<Self>) {
let name = self.name.read(cx).value().trim().to_owned();
let platform = PLATFORMS[self.platform].0;
// Checked here first, for a message at once.
if let Err(e) = edits::add_wl(&mut Value::Null, role, &name, platform) {
window.push_notification(Notification::error(format!("{e:#}")), cx);
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
let what = format!("{} '{name}' added", if role == "joiners" { "Joiner" } else { "Creator" });
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_wl(c, role, &name, platform), cx));
}
fn join(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(input) = self.joins.get(&name) else { return };
let link = input.read(cx).value().trim().to_owned();
if link.is_empty() {
window.push_notification(Notification::error("Paste the link the creator's side gave (its proxy-ctl wl link)"), cx);
return;
}
input.update(cx, |s, cx| s.set_value("", window, cx));
self.model.update(cx, |m, cx| m.request(format!("'{name}' joins the call"), Request::WlJoin { name, link }, cx));
}
fn link(&mut self, name: String, cx: &mut Context<Self>) {
let job = self.model.read(cx).bridge().call(Request::WlLink { name: name.clone() });
cx.spawn(async move |this, cx| {
let r = job.await.map(|v| v["link"].as_str().unwrap_or("").to_owned()).map_err(|e| format!("{e:#}"));
this.update(cx, |this, cx| {
this.links.insert(name, r);
cx.notify();
})
.ok();
})
.detach();
}
/// A cookies export, chosen: read here, as the signed-in user, and handed to the service.
fn cookies(&mut self, name: String, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some("Log in".into()) });
let model = self.model.clone();
cx.spawn(async move |_, cx| {
let Ok(Ok(Some(paths))) = paths.await else { return };
let Some(path) = paths.into_iter().next() else { return };
let login = std::fs::read_to_string(&path);
model.update(cx, |m, cx| match login {
Ok(login) => m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx),
Err(e) => m.track(format!("Reading {}", path.display()), async move { Err(e.into()) }, cx),
});
})
.detach();
}
fn password_login(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(l) = self.logins.get(&name) else { return };
let mut login = serde_json::Map::new();
login.insert("email".into(), l.email.read(cx).value().trim().into());
login.insert("password".into(), l.password.read(cx).value().to_string().into());
if let Some(p) = &l.portal {
let portal = p.read(cx).value().trim().trim_end_matches('/').to_owned();
login.insert("portal".into(), if portal.contains("://") { portal } else { format!("https://{portal}") }.into());
}
if login.values().any(|v| v.as_str().is_none_or(str::is_empty) || v == "https://") {
window.push_notification(Notification::error("Fill in every field"), cx);
return;
}
l.password.update(cx, |s, cx| s.set_value("", window, cx));
let login = Value::Object(login).to_string();
self.model.update(cx, |m, cx| m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx));
}
fn remove(&mut self, role: &'static str, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(format!("'{name}' removed"), move |c| edits::remove_wl(c, role, &name), cx));
}
}
/// A unit's state from the service's status, "off" when whitelist-bypass is.
fn unit_state(status: &Value, unit: &str, on: bool) -> String {
if !on {
return "off".into();
}
status["units"].as_array().into_iter().flatten().find(|u| u["name"] == unit).and_then(|u| u["state"].as_str()).unwrap_or("waiting").to_owned()
}
fn platform_label(p: &str) -> &str {
PLATFORMS.iter().find(|(id, _)| *id == p).map_or(p, |(_, label)| label.trim_end_matches(" (creators only)"))
}
impl Render for WhitelistPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let w = m.config()["whitelistBypass"].clone();
let status = m.status().clone();
let body = page("Whitelist bypass", cx);
if m.config().is_null() {
return body.child(hint("Waiting for the service…", cx));
}
let on = w["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("wl-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "Whitelist bypass is on" } else { "Whitelist bypass is off" },
move |c| {
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let about = card("whitelist-bypass", Some(enable.into_any_element()), cx).child(hint(
"For networks that let only a whitelist through, video calls among it: a joiner here tunnels the proxy's traffic through a call that a creator, on a machine with normal internet, holds open. Pin the joiner's outbound (Outbounds) to send traffic through it.",
cx,
));
let mut joiners = card("Joiners", None, cx).child(hint("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives.", cx));
let joiner_list: Vec<(String, String)> =
w["joiners"].as_object().map(|o| o.iter().map(|(n, j)| (n.clone(), j["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if joiner_list.is_empty() {
joiners = joiners.child(hint("None yet: add one below.", cx));
}
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
let Some(input) = self.joins.get(&name) else { continue };
let state = unit_state(&status, &format!("proxy-suite-wb-joiner-{name}"), on);
let (n1, n2) = (name.clone(), name.clone());
joiners = joiners.child(
div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-remove-joiner", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("joiners", n1.clone(), cx)))),
)
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(input)))
.child(Button::new(("wl-join", i)).small().primary().label("Join").on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
),
);
}
let mut creators = card("Creators", None, cx).child(hint(
"On the machine with normal internet. Each logs in to its platform (a cookies export from the desktop Creator app or a browser; DION and Bitrix take an email and password), starts a call and keeps it: give its link to the joiner.",
cx,
));
let creator_list: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if creator_list.is_empty() {
creators = creators.child(hint("None here.", cx));
}
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
let (n1, n2, n3, n4, n5) = (name.clone(), name.clone(), name.clone(), name.clone(), name.clone());
let mut row = div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-link", i)).small().icon(IconName::Link).label("Call link").on_click(cx.listener(move |this, _, _, cx| this.link(n1.clone(), cx))))
.child(Button::new(("wl-new", i)).small().icon(IconName::RefreshCw).label("New call").on_click(cx.listener(move |this, _, _, cx| {
this.links.remove(&n2);
let name = n2.clone();
this.model.update(cx, |m, cx| m.request(format!("'{name}' starts a new call"), Request::WlNew { name }, cx));
})))
.child(Button::new(("wl-cookies", i)).small().icon(IconName::FileUp).label("Cookies file…").on_click(cx.listener(move |this, _, _, cx| this.cookies(n3.clone(), cx))))
.child(Button::new(("wl-remove-creator", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("creators", n4.clone(), cx)))),
);
match self.links.get(&name) {
Some(Ok(link)) => {
let copy = link.clone();
row = row.child(
div()
.h_flex()
.gap_2()
.items_center()
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link.clone()))
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label("Copy").on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
window.push_notification(Notification::success("Copied"), cx);
})),
);
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
None => {}
}
if let Some(l) = self.logins.get(&name) {
let mut fields = div().h_flex().gap_2().child(div().flex_1().min_w_0().child(Input::new(&l.email))).child(div().flex_1().min_w_0().child(Input::new(&l.password)));
if let Some(p) = &l.portal {
fields = fields.child(div().flex_1().min_w_0().child(Input::new(p)));
}
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label("Log in").on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
}
creators = creators.child(row);
}
let platforms = RadioGroup::horizontal("wl-platform")
.children(PLATFORMS.map(|(_, label)| label))
.selected_index(Some(self.platform))
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.platform = *ix;
cx.notify();
}));
let add = card("Add", None, cx)
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (letters, digits, '.', '_', '-')")).child(Input::new(&self.name)))
.child(platforms)
.child(
div()
.h_flex()
.gap_2()
.child(Button::new("wl-add-joiner").small().icon(IconName::Plus).label("Add a joiner").on_click(cx.listener(|this, _, window, cx| this.add("joiners", window, cx))))
.child(Button::new("wl-add-creator").small().icon(IconName::Plus).label("Add a creator").on_click(cx.listener(|this, _, window, cx| this.add("creators", window, cx)))),
)
.child(hint("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass.", cx));
body.child(about).child(joiners).child(creators).child(add)
}
}
+37
View File
@@ -65,6 +65,43 @@ pub enum Request {
TgLinks, TgLinks,
/// Fetch and install components (all wanted, or the named ones). /// Fetch and install components (all wanted, or the named ones).
ComponentsInstall { names: Vec<String> }, ComponentsInstall { names: Vec<String> },
/// whitelist-bypass's creators and joiners, and their state.
WlList,
/// The call a creator made and keeps rejoining.
WlLink { name: String },
/// A creator's login: a cookies export, or (DION, Bitrix) the JSON of its email, password
/// and portal.
WlAuth { name: String, login: String },
/// The call link a joiner joins.
WlJoin { name: String, link: String },
/// Drops the call a creator rejoins: it makes a new one.
WlNew { name: String },
/// autoProxy: the routes it learned, its exits, what waits.
AutoList,
/// Probes a destination (a host, or host/path) through the exits as the prober does:
/// through `exits` (all, without), or whether `via` carries what direct reaches.
AutoProbe {
target: String,
#[serde(default)]
exits: Option<Vec<String>>,
#[serde(default)]
via: Option<String>,
#[serde(default)]
keep_going: bool,
},
/// Hosts to probe now.
AutoLearn { hosts: Vec<String> },
/// Forgets a domain's route and verdicts; without one, everything learned.
AutoForget {
#[serde(default)]
domain: Option<String>,
},
/// AmneziaWG's profiles: system-wide ones with their tunnel's state, outbounds by kind.
AwgList,
/// Starts or stops a system-wide profile's tunnel.
AwgSet { name: String, on: bool },
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
AwgLog { name: String, lines: usize },
} }
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+197
View File
@@ -135,10 +135,30 @@ fn scope_of(req: &Request) -> Option<Scope> {
// Backend logs name the sites visited (at info), and errors may quote what was dialled. // Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets), Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
Request::AwgLog { .. } => Some(Scope::Secrets),
_ => None, _ => None,
} }
} }
/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what
/// was just left for it.
async fn wl_restart(s: &mut service::Service, unit: &str) -> Response {
let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since);
let before = started(s);
if let Err(e) = s.apply_wl().await {
return Response::err(format!("{e:#}"));
}
// Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is).
let after = started(s);
if after.is_some() && after == before {
s.sup.restart(unit);
}
Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() }))
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool { fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok() allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
} }
@@ -476,6 +496,183 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
} }
} }
Request::WlList => {
let s = shared.lock().await;
let wl = &s.cfg().whitelist_bypass;
let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" };
let mut list: Vec<Value> = wl
.creators
.iter()
.map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) }))
.collect();
list.extend(wl.joiners.iter().map(|(name, j)| {
json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) })
}));
Response::ok(json!(list))
}
Request::WlLink { name } => {
let s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
match crate::wl::last_link(s.paths(), &name) {
Some(link) => Response::ok(json!({ "link": link })),
None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)),
}
}
Request::WlAuth { name, login } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON");
}
let file = match crate::wl::state_file(s.paths(), &name, ".cookies.json") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::WlJoin { name, link } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.joiners.contains_key(&name) {
return Response::err(format!("no whitelist-bypass joiner '{name}'"));
}
let link = link.trim();
let link = match crate::wl::clean_link(link) {
Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"),
};
let file = match crate::wl::state_file(s.paths(), &name, ".join") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await
}
Request::WlNew { name } => {
let mut s = shared.lock().await;
let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
};
if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
}
let file = match crate::wl::state_file(s.paths(), &name, ".link") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Response::err(format!("removing {}: {e}", file.display()));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::AutoList => {
let s = shared.lock().await;
let exits = crate::autoproxy::exits(&s);
Response::ok(crate::autoproxy::listing(s.paths(), exits.as_ref(), &s.cfg().proxy.auto_proxy, has_secrets(s.cfg(), peer)))
}
Request::AutoProbe { target, exits, via, keep_going } => {
let Some(probe_exits) = crate::autoproxy::exits(&*shared.lock().await) else {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
};
// The network, outside the lock.
match probe_exits.probe(&target, exits.as_deref(), via.as_deref(), keep_going).await {
Ok(p) => Response::ok(serde_json::to_value(&p).unwrap()),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::AutoLearn { hosts } => {
let s = shared.lock().await;
if crate::autoproxy::exits(&s).is_none() {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
}
let bad: Vec<&String> = hosts.iter().filter(|h| !ps_core::autoproxy::host_ok(h.trim())).collect();
if !bad.is_empty() {
return Response::err(format!("not host names: {}", bad.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")));
}
let opts = &s.cfg().proxy.auto_proxy;
let skipped: Vec<&String> = hosts.iter().filter(|h| crate::autoproxy::excluded(opts, &h.trim().to_ascii_lowercase())).collect();
if !skipped.is_empty() {
return Response::err(format!(
"in proxy.autoProxy.exclude, never probed: {}",
skipped.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")
));
}
let queued = {
let mut r = s.ap.requests.lock().unwrap();
// Bounded: every request is a probe.
let room = 10_000usize.saturating_sub(r.len());
r.extend(hosts.iter().take(room).map(|h| h.trim().to_owned()));
hosts.len().min(room)
};
s.ap.wake.notify_one();
Response::ok(json!({ "queued": queued }))
}
Request::AutoForget { domain } => match crate::autoproxy::edit(shared, domain.as_deref()).await {
Ok(()) => Response::ok(json!({ "forgot": domain.unwrap_or_else(|| "everything".into()) })),
Err(e) => Response::err(format!("{e:#}")),
},
Request::AwgList => {
let s = shared.lock().await;
let cfg = s.cfg();
let vpns = crate::awgvpn::profiles(cfg);
let list: Vec<Value> = cfg
.amnezia_wg
.profiles
.iter()
.map(|(name, p)| match vpns.iter().find(|v| &v.name == name) {
Some(v) => json!({ "name": name, "kind": "vpn", "interface": v.iface, "autostart": v.autostart, "state": crate::awgvpn::state(&v.iface) }),
None => json!({
"name": name,
"kind": match p.as_outbound { Some(ps_core::config::AwgOutboundKind::SingBox) => "singBox", Some(_) => "userspace", None => "vpn" },
"state": if cfg.amnezia_wg.enable { "outbound" } else { "off" },
}),
})
.collect();
Response::ok(json!({ "enabled": cfg.amnezia_wg.enable, "profiles": list }))
}
Request::AwgSet { name, on } => {
let s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}' (is amneziaWg.enable on, and the profile without asOutbound?)"));
};
// The SCM's calls wait for the tunnel: not in the async runtime's threads.
let iface = vpn.iface.clone();
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
match r {
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
Ok(Err(e)) => Response::err(format!("{e:#}")),
Err(e) => Response::err(e.to_string()),
}
}
Request::AwgLog { name, lines } => {
let s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}'"));
};
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
}
Request::ComponentsInstall { names } => { Request::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin { if !peer.admin {
+725
View File
@@ -0,0 +1,725 @@
//! autoProxy's prober, as upstream's autoproxy-run.template.sh runs it: every `interval`, and
//! at once for `proxy-ctl proxy auto learn`, it probes the hosts apps dialled directly (and
//! those asked for) through each exit in turn, remembers the first exit that reaches what
//! direct does not, and publishes it as that exit's rule-set, which sing-box reloads.
//!
//! Upstream learns the hosts from its server inbounds' access log; on a desktop they are the
//! local proxy's own direct connections, which the Clash API lists (`sample`). The judging is
//! ps_core::autoproxy's.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use ps_core::autoproxy::{self as ap, Fetch, PATHS, Probe, State};
use ps_core::config::AutoProxy as Options;
use ps_core::render::ProbeExit;
use serde_json::{Value, json};
use crate::paths::{Paths, write_atomic};
use crate::service::{SOCKS_UNIT, Shared};
use crate::units::UnitState;
/// Where the prober's lines go: `proxy-ctl logs proxy-suite-autoproxy`.
pub const UNIT: &str = "proxy-suite-autoproxy";
const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) proxy-suite-probe";
/// What the service and the prober share.
#[derive(Default)]
pub struct AutoProxy {
/// Runs and edits take turns on the state.
pub lock: tokio::sync::Mutex<()>,
/// Hosts asked for, probed at the next run, which asking wakes.
pub requests: std::sync::Mutex<Vec<String>>,
/// Hosts apps dialled directly since the last run, with how often.
pub dialled: std::sync::Mutex<BTreeMap<String, u64>>,
/// What the transfer sampler saw since the last run: host, exit, crawling, fastest second.
pub samples: std::sync::Mutex<Vec<(String, String, bool, u64)>>,
pub wake: tokio::sync::Notify,
}
pub fn dir(paths: &Paths) -> PathBuf {
paths.root.join("autoproxy")
}
pub fn rules_dir(paths: &Paths) -> PathBuf {
dir(paths).join("rules")
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
/// The state, or a fresh one; an unreadable one is set aside as state.json.broken.
pub fn load(paths: &Paths) -> State {
let file = dir(paths).join("state.json");
match std::fs::read(&file) {
Ok(bytes) => match serde_json::from_slice(&bytes) {
Ok(s) => s,
Err(e) => {
tracing::warn!("{} is unreadable ({e}); set aside, starting fresh", file.display());
let _ = std::fs::rename(&file, file.with_extension("json.broken"));
State::default()
}
},
Err(_) => State::default(),
}
}
pub fn save(paths: &Paths, state: &State) -> Result<()> {
let d = dir(paths);
std::fs::create_dir_all(&d)?;
write_atomic(&d.join("state.json"), &serde_json::to_vec_pretty(state)?)?;
Ok(())
}
/// Every exit's rule-set file from the state: before sing-box starts (it refuses a missing
/// one), and after each route learned (it reloads a file replaced).
pub fn publish(exits: &[ProbeExit], state: &State) -> Result<()> {
for e in exits {
let Some(path) = &e.path else { continue };
let path = Path::new(path);
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
let body = serde_json::to_vec(&ap::rule_set(state, &e.tag))?;
if std::fs::read(path).is_ok_and(|old| old == body) {
continue;
}
write_atomic(path, &body).with_context(|| format!("writing {}", path.display()))?;
}
Ok(())
}
/// The probe listeners and their login, while the proxy and autoProxy run.
#[derive(Clone)]
pub struct Exits {
pub list: Vec<ProbeExit>,
pub login: (String, String),
/// autoProxy.exclude: never probed.
pub opts: Options,
}
impl Exits {
fn port(&self, tag: &str) -> Option<u16> {
self.list.iter().find(|e| e.tag == tag).map(|e| e.port)
}
fn tags(&self) -> Vec<String> {
self.list.iter().map(|e| e.tag.clone()).collect()
}
/// `domain` at `path` through `tag`'s listener.
pub async fn fetch(&self, tag: &str, domain: &str, path: &str) -> Fetch {
match self.port(tag) {
Some(port) => fetch(port, &self.login, domain, path).await,
None => Fetch { error: format!("no exit {tag}"), ..Default::default() },
}
}
/// Whether the direct listener answers at all: a probe through a listener that is not
/// there would judge every site unreachable.
async fn up(&self) -> bool {
let Some(e) = self.list.first() else { return false };
tokio::time::timeout(Duration::from_secs(3), tokio::net::TcpStream::connect(("127.0.0.1", e.port))).await.is_ok_and(|r| r.is_ok())
}
/// A probe of `domain` (a host, or host/path), as `proxy-ctl proxy auto probe` asks it:
/// through `wanted` (all, without), or whether `via` carries what direct reaches.
pub async fn probe(&self, target: &str, wanted: Option<&[String]>, via: Option<&str>, keep_going: bool) -> Result<Probe> {
let target = target.split("://").last().unwrap_or(target);
let (domain, paths): (&str, Vec<String>) = match target.split_once('/') {
Some((d, p)) => (d, vec![format!("/{p}")]),
None => (target, PATHS.iter().map(|p| (*p).to_owned()).collect()),
};
if !ap::host_ok(domain) {
bail!("'{domain}' is not a host name");
}
if excluded(&self.opts, &domain.to_ascii_lowercase()) {
bail!("{domain} is in proxy.autoProxy.exclude: never probed");
}
if !self.up().await {
bail!("the probe listeners are not up: is the local proxy running?");
}
let paths: Vec<&str> = paths.iter().map(String::as_str).collect();
let fetch = |tag: String, path: String| async move { self.fetch(&tag, domain, &path).await };
if let Some(via) = via {
if via == ap::DIRECT || self.port(via).is_none() {
bail!("no exit named {via} other than direct");
}
return Ok(ap::stand_in(domain, via, &paths, fetch).await);
}
let mut exits = vec![ap::DIRECT.to_owned()];
match wanted {
Some(w) => exits.extend(w.iter().filter(|t| t.as_str() != ap::DIRECT && self.port(t).is_some()).cloned()),
None => exits.extend(self.list.iter().skip(1).map(|e| e.tag.clone())),
}
Ok(ap::walk(domain, &exits, &paths, keep_going, fetch).await)
}
}
/// One request through a probe listener: the first hop that is not a same-site redirect
/// (a block can sit at the end of a chain: spotify.com -> www -> open -> why-not-available).
async fn fetch(port: u16, login: &(String, String), domain: &str, path: &str) -> Fetch {
let client = reqwest::Client::builder()
.proxy(match reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)) {
Ok(p) => p,
Err(e) => return Fetch { error: e.to_string(), ..Default::default() },
})
.redirect(reqwest::redirect::Policy::none())
.user_agent(USER_AGENT)
.connect_timeout(Duration::from_secs(8))
.timeout(Duration::from_secs(15))
.build();
let client = match client {
Ok(c) => c,
Err(e) => return Fetch { error: e.to_string(), ..Default::default() },
};
let mut url = format!("https://{domain}{path}");
let site = ap::site(&url);
let mut result = Fetch::default();
for _ in 0..6 {
result = match client.get(&url).send().await {
Err(e) => return Fetch { error: short_error(&e), ..Default::default() },
Ok(mut resp) => {
let status = resp.status().as_u16();
let head: String = resp.headers().iter().map(|(k, v)| format!("{k}: {}\r\n", String::from_utf8_lossy(v.as_bytes()))).collect();
let location = resp
.headers()
.get(reqwest::header::LOCATION)
.and_then(|l| l.to_str().ok())
.and_then(|l| resp.url().join(l).ok())
.map(|u| u.to_string())
.unwrap_or_default();
// Enough to judge a refusal by (its first 8 KiB) and to count what came.
let mut body = Vec::new();
while body.len() < 64 * 1024 {
match resp.chunk().await {
Ok(Some(c)) => body.extend_from_slice(&c),
_ => break,
}
}
Fetch { status: Some(status), block: ap::block_page(status, &head, &body), location, bytes: body.len() as u64, error: String::new() }
}
};
let redirect = result.status.is_some_and(|s| (300..400).contains(&s));
if !redirect || ap::redirect_is_block(&result.location) || result.location.is_empty() {
break;
}
if ap::site(&result.location) != site || ap::local_target(&result.location) || !result.location.starts_with("http") {
break;
}
url = result.location.clone();
}
result
}
fn short_error(e: &reqwest::Error) -> String {
if e.is_timeout() {
"timed out".into()
} else if e.is_connect() {
"could not connect".into()
} else {
let mut s = e.to_string();
let mut src = std::error::Error::source(e);
while let Some(inner) = src {
s = inner.to_string();
src = inner.source();
}
s.chars().take(120).collect()
}
}
/// A plain GET through a probe listener, for the egress address and an exit's network.
async fn get_text(port: u16, login: &(String, String), url: &str) -> Option<String> {
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)).ok()?)
.user_agent(USER_AGENT)
.timeout(Duration::from_secs(10))
.build()
.ok()?;
let resp = client.get(url).send().await.ok()?;
if !resp.status().is_success() {
return None;
}
let text = resp.text().await.ok()?;
(text.len() < 64 * 1024).then_some(text)
}
/// The probe listeners, when autoProxy runs with the local proxy.
pub fn exits(s: &crate::service::Service) -> Option<Exits> {
let cfg = s.cfg();
if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || s.sup.state_of(SOCKS_UNIT) != UnitState::Active {
return None;
}
let list = s.last.as_ref()?.probe_exits.clone();
(!list.is_empty()).then(|| Exits {
list,
login: (s.store.secrets.hop_user.clone(), s.store.secrets.hop_password.clone()),
opts: cfg.proxy.auto_proxy.clone(),
})
}
pub fn excluded(opts: &Options, host: &str) -> bool {
opts.exclude.iter().any(|x| {
let x = x.trim_start_matches('.').to_ascii_lowercase();
host == x || host.ends_with(&format!(".{x}"))
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// Everything: rechecks, the backlog, the requests.
Full,
/// `proxy-ctl proxy auto learn`'s hosts only.
Requests,
}
/// One run. Each verdict is saved as it comes: a run cut short keeps what it learned.
pub async fn run(shared: &Shared, mode: Mode) {
let (exits, opts, paths, disabled, auto) = {
let s = shared.lock().await;
let Some(exits) = exits(&s) else { return };
let disabled = s.last.as_ref().map(|r| r.inventory.disabled.clone()).unwrap_or_default();
(exits, s.cfg().proxy.auto_proxy.clone(), s.paths().clone(), disabled, s.ap.clone())
};
let _turn = auto.lock.lock().await;
let note = async |line: String| shared.lock().await.sup.note(UNIT, line);
if !exits.up().await {
note("no probe listeners: is the local proxy running?".into()).await;
return;
}
let ttl = u64::from(opts.ttl_days) * 86400;
let now = now();
let mut state = load(&paths);
let save_and = async |state: &State, publish_too: bool| {
if let Err(e) = save(&paths, state) {
tracing::warn!("autoProxy's state: {e:#}");
}
if publish_too && let Err(e) = publish(&exits.list, state) {
tracing::warn!("autoProxy's rule-sets: {e:#}");
}
};
// Routes through an exit disabled since: probed again without it.
let gone: Vec<(String, String)> = state.domains.iter().filter(|(_, r)| disabled.contains(&r.exit)).map(|(d, r)| (d.clone(), r.exit.clone())).collect();
for (d, exit) in &gone {
state.forget(d);
note(format!("forgot {d}: its exit {exit} is disabled")).await;
}
// Verdicts are about this host's address: a new one discards them. An error page or a
// captive portal must not pass for one.
let direct_port = exits.list[0].port;
if let Some(egress) = get_text(direct_port, &exits.login, "https://api.ipify.org").await.map(|t| t.trim().to_owned())
&& !egress.is_empty()
&& egress.chars().all(|c| c.is_ascii_hexdigit() || c == '.' || c == ':')
&& state.egress.as_deref() != Some(egress.as_str())
{
if state.egress.is_some() {
note(format!("egress is now {egress}; discarding everything learned for the old address")).await;
}
state.new_egress(&egress);
}
// Which network (AS) each exit leaves from, once per TTL.
for e in &exits.list {
if now.saturating_sub(state.exits.get(&e.tag).map_or(0, |x| x.at)) < ttl {
continue;
}
let Some(info) = get_text(e.port, &exits.login, "https://ipinfo.io/json").await.and_then(|t| serde_json::from_str::<Value>(&t).ok()) else {
continue;
};
let Some(ip) = info["ip"].as_str() else { continue };
let x = state.exits.entry(e.tag.clone()).or_default();
x.ip = Some(ip.to_owned());
x.asn = info["org"].as_str().and_then(|o| o.split_whitespace().next()).map(str::to_owned);
x.at = now;
}
state.strike(&[], "", "", now, ttl);
let (r1, r2, _) = ap::rounds(&exits.tags(), &state);
save_and(&state, !gone.is_empty()).await;
// Walks round 1; round 2 only when it all refused, round 1's refusals kept.
let exits = &exits;
let walk = async |host: &str| -> Probe {
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await };
let first: Vec<String> = std::iter::once(ap::DIRECT.to_owned()).chain(r1.iter().cloned()).collect();
let p = ap::walk(host, &first, &PATHS, false, fetch).await;
if matches!(p.verdict.as_str(), "both-fail" | "unreachable") && !r2.is_empty() {
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await };
let second: Vec<String> = std::iter::once(ap::DIRECT.to_owned()).chain(r2.iter().cloned()).collect();
let mut q = ap::walk(host, &second, &PATHS, false, fetch).await;
let mut rows = p.rows;
rows.append(&mut q.rows);
q.rows = rows;
return q;
}
p
};
let mut requeue: Vec<(String, String)> = Vec::new();
if mode == Mode::Full {
// Remembered routes, once per TTL.
for (dom, host, exit) in state.due(now, ttl) {
let h = host.as_str();
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, h, &path).await };
let p = ap::walk(&host, &[ap::DIRECT.to_owned(), exit.clone()], &PATHS, false, fetch).await;
if p.verdict == "destination" && p.exit.as_deref() == Some(exit.as_str()) {
if let Some(r) = state.domains.get_mut(&dom) {
r.at = now;
}
} else if p.verdict == "ok" {
note(format!("recheck {dom}: reachable directly now, dropping {exit}")).await;
state.domains.remove(&dom);
state.record(&dom, &host, &p, now, ttl);
save_and(&state, true).await;
} else {
note(format!("recheck {dom}: {exit} no longer works ({}), walking again", p.verdict)).await;
state.domains.remove(&dom);
save_and(&state, true).await;
requeue.push((dom, host));
}
}
// What apps dialled directly since the last run, per host.
let dialled = std::mem::take(&mut *auto.dialled.lock().unwrap());
let counts: BTreeMap<String, (String, u64)> = dialled
.into_iter()
.filter(|(h, _)| ap::host_ok(h) && !excluded(&opts, h))
.filter_map(|(h, n)| ap::registrable(&h).map(|d| (h, (d, n))))
.collect();
state.queue(&counts, now, ttl);
save_and(&state, false).await;
// What the sampler saw crawl: each such site gets the next exit, in probe order, that
// answers it as well as direct does; none left, it stays direct for a TTL.
let samples = std::mem::take(&mut *auto.samples.lock().unwrap());
if opts.slow_below_kibps > 0 && !samples.is_empty() {
let obs: Vec<ap::Observation> = samples
.into_iter()
.filter(|(h, ..)| ap::host_ok(h) && !excluded(&opts, h))
.filter_map(|(host, exit, slow, peak)| ap::registrable(&host).map(|domain| ap::Observation { domain, host, exit, slow, peak }))
.collect();
let before = state.domains.clone();
state.judge_slow(&obs, now, 3);
let (_, _, ordered) = ap::rounds(&exits.tags(), &state);
let wanted: Vec<(String, ap::SlowWant)> = state.slow_want.iter().take(20).map(|(d, w)| (d.clone(), w.clone())).collect();
for (dom, want) in wanted {
let mut tried = want.tried.clone();
let was = tried.last().cloned();
// It crawled twice on the exit it was routed through.
if let Some(was) = &was {
state.strike(std::slice::from_ref(was), &dom, "slow", now, ttl);
}
let mut via = None;
for tag in &ordered {
if tried.contains(tag) {
continue;
}
tried.push(tag.clone());
let host = want.host.as_str();
let fetch = |t: String, path: String| async move { exits.fetch(&t, host, &path).await };
let p = ap::stand_in(host, tag, &PATHS, fetch).await;
if p.verdict == "ok" {
via = Some(tag.clone());
break;
}
// Refused what direct gets: by a block page, or by the origin.
let rows: Vec<&ap::Row> = p.rows.iter().filter(|r| &r.tag == tag).collect();
let why = rows
.iter()
.find(|r| r.judgement == ap::Judgement::Wall)
.map(|r| format!("wall:{}", r.fetch.block))
.or_else(|| rows.iter().any(|r| r.judgement == ap::Judgement::Blocked).then(|| "refused".to_owned()));
if let Some(why) = why {
state.strike(std::slice::from_ref(tag), &dom, &why, now, ttl);
}
}
let how = was.as_deref().map_or("directly".to_owned(), |w| format!("via {w}"));
match via {
Some(v) => {
note(format!("slow {dom}: crawls {how}, routed via {v}")).await;
state.route_slow(&dom, &want.host, &v, tried, now);
}
None => {
note(format!("slow {dom}: crawls {how}, and no other exit reaches it; left direct")).await;
state.skip_slow(&dom, now, ttl);
}
}
}
save_and(&state, state.domains != before).await;
}
}
// Probe: the requests, then broken routes, then the backlog.
let mut asked: Vec<(String, String)> = Vec::new();
{
let mut requests = auto.requests.lock().unwrap();
let mut seen = BTreeSet::new();
let taken: Vec<String> = std::mem::take(&mut *requests);
for h in taken {
let h = h.trim().to_ascii_lowercase();
if !ap::host_ok(&h) || excluded(&opts, &h) || !seen.insert(h.clone()) {
continue;
}
if let Some(d) = ap::registrable(&h) {
asked.push((d, h));
}
}
let max = opts.probes_per_run as usize;
if asked.len() > max {
requests.extend(asked.split_off(max).into_iter().map(|(_, h)| h));
}
}
let left = auto.requests.lock().unwrap().len();
if left > 0 {
note(format!("{left} requested host(s) past probesPerRun wait for the next run")).await;
}
let backlog = if mode == Mode::Full { state.backlog_order(now, ttl) } else { Vec::new() };
let mut seen: HashSet<String> = HashSet::new();
let mut routed: HashSet<String> = HashSet::new();
let started = Instant::now();
let mut probed = 0usize;
let rows = asked.iter().map(|r| (r, true)).chain(requeue.iter().chain(backlog.iter()).map(|r| (r, false)));
for ((dom, host), was_asked) in rows {
if !was_asked && probed >= opts.probes_per_run as usize {
break;
}
// A run of tarpits must not go on for good: what is left waits for the next.
if started.elapsed() > Duration::from_secs(2 * 3600) {
note("a run ends after two hours; the rest wait for the next".into()).await;
break;
}
if !seen.insert(host.clone()) || routed.contains(dom) {
continue;
}
if !was_asked {
probed += 1;
}
if !exits.up().await {
note("the probe listeners went away; the run ends".into()).await;
break;
}
let p = walk(host).await;
state.record(dom, host, &p, now, ttl);
let destination = p.verdict == "destination";
if destination {
routed.insert(dom.clone());
}
save_and(&state, destination).await;
let how = match (&p.verdict[..], &p.exit) {
("destination", Some(x)) => format!("destination via {x}"),
("censor", Some(x)) => format!("censor ({x} reaches it; left to zapret)"),
(v, _) => v.to_owned(),
};
note(format!("probe {host} -> {how}")).await;
}
if mode == Mode::Full || !asked.is_empty() {
note(format!("probed {} requested and {probed} queued host(s); {} still waiting", asked.len(), state.backlog.len())).await;
}
save_and(&state, true).await;
}
/// The prober's schedule: a first run ten minutes after start (as upstream's timer; sooner with
/// a shorter `interval`), then every `interval`; a learn request wakes it for the requests alone.
pub async fn runner(shared: Shared) {
let (auto, every) = {
let s = shared.lock().await;
(s.ap.clone(), interval(&s.cfg().proxy.auto_proxy))
};
let mut next = Instant::now() + every.min(Duration::from_secs(600));
loop {
tokio::select! {
_ = tokio::time::sleep_until(next.into()) => {
run(&shared, Mode::Full).await;
next = Instant::now() + interval(&shared.lock().await.cfg().proxy.auto_proxy);
}
_ = auto.wake.notified() => run(&shared, Mode::Requests).await,
}
}
}
/// `interval`, a minute at least.
fn interval(opts: &Options) -> Duration {
ps_core::duration::parse(&opts.interval).unwrap_or(Duration::from_secs(600)).max(Duration::from_secs(60))
}
/// The hosts the local proxy's clients dial directly, from the Clash API's connections, every
/// ten seconds while autoProxy runs: what the prober's backlog is made of.
pub async fn sample(shared: Shared) {
let mut seen: HashSet<String> = HashSet::new();
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
let (clash, auto) = {
let s = shared.lock().await;
let cfg = s.cfg();
if exits(&s).is_none() {
continue;
}
(crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone())
};
let Ok(v) = clash.connections().await else { continue };
let mut dialled = auto.dialled.lock().unwrap();
for c in v["connections"].as_array().into_iter().flatten() {
let Some(id) = c["id"].as_str() else { continue };
if !seen.insert(id.to_owned()) {
continue;
}
let m = &c["metadata"];
let inbound = m["type"].as_str().unwrap_or("");
if inbound.contains("probe-in-") || inbound.contains("proxy-suite-test-in") {
continue;
}
// Only what went direct: the rest is routed already.
let chains: Vec<&str> = c["chains"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if chains != [ap::DIRECT] {
continue;
}
let port = m["destinationPort"].as_str().map(str::to_owned).or_else(|| m["destinationPort"].as_u64().map(|p| p.to_string()));
if !matches!(port.as_deref(), Some("443" | "80")) {
continue;
}
let host = m["host"].as_str().unwrap_or("").to_ascii_lowercase();
if ap::host_ok(&host) {
*dialled.entry(host).or_insert(0) += 1;
}
}
if seen.len() > 50_000 {
seen.clear();
}
// Bounded between runs, as the backlog is.
if dialled.len() > 20_000 {
let mut v: Vec<(String, u64)> = std::mem::take(&mut *dialled).into_iter().collect();
v.sort_by_key(|a| std::cmp::Reverse(a.1));
v.truncate(10_000);
*dialled = v.into_iter().collect();
}
}
}
/// Live transfers every minute while slow sites are routed (`slowBelowKiBps`): eleven Clash
/// API snapshots a second apart, the transfers that moved enough kept for the next run, as
/// upstream's sampler timer does.
pub async fn sample_slow(shared: Shared) {
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
let (clash, auto, below) = {
let s = shared.lock().await;
let cfg = s.cfg();
let below = cfg.proxy.auto_proxy.slow_below_kibps;
if below == 0 || exits(&s).is_none() {
continue;
}
(crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone(), below)
};
let mut snapshots = Vec::with_capacity(11);
for i in 0..11 {
if i > 0 {
tokio::time::sleep(Duration::from_secs(1)).await;
}
snapshots.push(clash.connections().await.unwrap_or(Value::Null));
}
let seen = ap::sample_transfers(&snapshots, 300 * 1024, u64::from(below) * 1024);
let mut samples = auto.samples.lock().unwrap();
samples.extend(seen);
let over = samples.len().saturating_sub(10_000);
samples.drain(..over);
}
}
/// What `proxy-ctl proxy auto` lists. Without `detail` (the secrets scope) the sites routed
/// and the counts only: the hosts probed, those left to zapret and the sites behind each
/// strike are browsing history, as the logs are.
pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options, detail: bool) -> Value {
let s = load(paths);
let domains: Vec<Value> = s
.domains
.iter()
.map(|(d, r)| {
let mut v = json!({ "domain": d, "exit": r.exit, "verdict": r.verdict, "at": r.at });
if detail {
v["host"] = r.host.clone().into();
}
v
})
.collect();
let exit_list: Vec<Value> = s
.exits
.iter()
.map(|(t, e)| {
let mut v = json!({ "tag": t, "ip": e.ip, "asn": e.asn, "bad": e.bad, "strikes": e.strikes.len() });
if detail {
v["badBy"] = json!(e.bad_by);
}
v
})
.collect();
let censored: Vec<&String> = s.hosts.iter().filter(|(_, h)| h.verdict == "censor").map(|(h, _)| h).collect();
let censored = if detail { json!(censored) } else { json!(censored.len()) };
json!({
"enabled": opts.enable,
"running": exits.is_some(),
"egress": s.egress,
"lastRun": s.last_run,
"domains": domains,
"exits": exit_list,
"probeExits": exits.map(|e| e.tags()).unwrap_or_default(),
"hostsJudged": s.hosts.len(),
"censored": censored,
"backlog": s.backlog.len(),
"slowWaiting": s.slow_want.len(),
})
}
/// `forget <domain>` or `clear`, under the prober's lock, published at once.
pub async fn edit(shared: &Shared, forget: Option<&str>) -> Result<()> {
let (paths, auto, list) = {
let s = shared.lock().await;
(s.paths().clone(), s.ap.clone(), s.last.as_ref().map(|r| r.probe_exits.clone()).unwrap_or_default())
};
let _turn = auto.lock.lock().await;
let mut state = load(&paths);
match forget {
Some(d) => {
if !ap::host_ok(d) {
bail!("'{d}' is not a domain");
}
state.forget(&d.to_ascii_lowercase());
}
None => state.clear(),
}
save(&paths, &state)?;
publish(&list, &state)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exclusions_take_subdomains() {
let opts = Options { exclude: vec!["internal.example".into()], ..Default::default() };
assert!(excluded(&opts, "internal.example"));
assert!(excluded(&opts, "a.internal.example"));
assert!(!excluded(&opts, "notinternal.example"));
}
#[test]
fn published_rule_sets_follow_the_state() {
let d = std::env::temp_dir().join(format!("ps-ap-{}", std::process::id()));
let path = d.join("rs-1.json");
let exits = [
ProbeExit { tag: "direct".into(), port: 1, rule_set: None, path: None },
ProbeExit { tag: "nl".into(), port: 2, rule_set: Some("autoproxy-1".into()), path: Some(path.to_string_lossy().into()) },
];
let mut s = State::default();
s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1, bad: 0, tried: Vec::new() });
publish(&exits, &s).unwrap();
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v, json!({ "version": 1, "rules": [{ "domain_suffix": ["x.example"] }] }));
let _ = std::fs::remove_dir_all(&d);
}
}
+322
View File
@@ -0,0 +1,322 @@
//! AmneziaWG as a system-wide VPN: each profile with no `asOutbound` is a tunnel service of
//! its own, `AmneziaWGTunnel$<interface name>`, as amneziawg-windows's client installs one:
//! amneziawg-go on Wintun, routes and DNS from the configuration, and, for a single peer that
//! takes everything (0.0.0.0/0, ::/0), its firewall blocking what would leave outside the
//! tunnel. It runs `awg-tunnel.exe` (tools/build-amneziawg.sh) with the profile's `.conf`,
//! written below the protected state root, and logs beside it.
//!
//! The service writes the configuration and registers the tunnel; `proxy-ctl awg on|off` and
//! the app start and stop it; `autostart` starts it with the service. Windows only: on Linux
//! (development) the profiles are listed and say so.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::Config;
use crate::paths::{Paths, write_atomic};
/// The tunnel services' names: amneziawg-windows's own.
#[cfg_attr(not(windows), allow(dead_code))]
pub const SERVICE_PREFIX: &str = "AmneziaWGTunnel$";
/// Where the service's notes about the tunnels go: `proxy-ctl logs proxy-suite-awg-vpn`.
pub const UNIT: &str = "proxy-suite-awg-vpn";
/// A system-wide profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vpn {
pub name: String,
/// The adapter's and the service's name.
pub iface: String,
pub autostart: bool,
}
/// The profiles that are system-wide VPNs, while AmneziaWG is on.
pub fn profiles(cfg: &Config) -> Vec<Vpn> {
if !cfg.enable || !cfg.amnezia_wg.enable {
return Vec::new();
}
cfg.amnezia_wg
.profiles
.iter()
.filter(|(_, p)| p.as_outbound.is_none())
.map(|(name, p)| Vpn { name: name.clone(), iface: p.interface_name.clone().unwrap_or_else(|| name.clone()), autostart: p.autostart })
.collect()
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn service_name(iface: &str) -> String {
format!("{SERVICE_PREFIX}{iface}")
}
/// The tunnels' configurations: each `<interface>.conf` there is a tunnel this suite
/// registered, which is how it finds its own to remove.
fn dir(paths: &Paths) -> PathBuf {
paths.root.join("awg-vpn")
}
/// The tunnels registered, by interface name.
fn registered(paths: &Paths) -> Vec<String> {
std::fs::read_dir(dir(paths))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".conf").map(str::to_owned))
.collect()
}
/// A tunnel unregistered: its service, configuration and log gone.
fn forget(paths: &Paths, iface: &str) -> Result<()> {
#[cfg(windows)]
scm::remove(iface, &paths.bin())?;
let _ = std::fs::remove_file(conf_path(paths, iface));
let _ = std::fs::remove_file(log_path(paths, iface));
Ok(())
}
pub fn conf_path(paths: &Paths, iface: &str) -> PathBuf {
dir(paths).join(format!("{iface}.conf"))
}
/// The tunnel's log: awg-tunnel.exe writes it anew at each start.
pub fn log_path(paths: &Paths, iface: &str) -> PathBuf {
dir(paths).join(format!("{iface}.conf.log"))
}
/// The profile's `.conf`, as the tunnel reads it: it holds the private key, so only below
/// the protected state root.
pub fn write_conf(cfg: &Config, paths: &Paths, vpn: &Vpn) -> Result<PathBuf> {
let p = &cfg.amnezia_wg.profiles[&vpn.name];
let read = |f: &str| std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"));
let text = ps_core::awg::prepare(p, &read).map_err(|e| anyhow::anyhow!("AmneziaWG profile '{}': {e}", vpn.name))?;
let file = conf_path(paths, &vpn.iface);
std::fs::create_dir_all(dir(paths))?;
if std::fs::read_to_string(&file).ok().as_deref() != Some(text.as_str()) {
write_atomic(&file, text.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(file)
}
/// The last lines of a tunnel's log.
pub fn log_tail(paths: &Paths, iface: &str, lines: usize) -> Vec<String> {
let text = std::fs::read_to_string(log_path(paths, iface)).unwrap_or_default();
let all: Vec<&str> = text.lines().collect();
all[all.len().saturating_sub(lines)..].iter().map(|l| (*l).to_owned()).collect()
}
#[cfg(windows)]
mod scm {
use std::ffi::OsString;
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result};
use windows_service::service::{
ServiceAccess, ServiceDependency, ServiceErrorControl, ServiceInfo, ServiceSidType, ServiceStartType, ServiceState, ServiceType,
};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
fn manager() -> Result<ServiceManager> {
ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE | ServiceManagerAccess::ENUMERATE_SERVICE)
.context("opening the Service Control Manager")
}
const ACCESS: ServiceAccess = ServiceAccess::QUERY_STATUS
.union(ServiceAccess::QUERY_CONFIG)
.union(ServiceAccess::START)
.union(ServiceAccess::STOP)
.union(ServiceAccess::CHANGE_CONFIG)
.union(ServiceAccess::DELETE);
/// The tunnel's service, created or brought in line with `program` and `conf`.
pub fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
let m = manager()?;
let info = ServiceInfo {
name: OsString::from(super::service_name(iface)),
display_name: OsString::from(format!("AmneziaWG tunnel: {iface} (Proxy Suite)")),
service_type: ServiceType::OWN_PROCESS,
start_type: ServiceStartType::OnDemand,
error_control: ServiceErrorControl::Normal,
executable_path: program.to_path_buf(),
launch_arguments: vec![conf.as_os_str().to_owned(), OsString::from(iface)],
// As amneziawg-windows's client: the network stack first.
dependencies: vec![ServiceDependency::Service(OsString::from("Nsi")), ServiceDependency::Service(OsString::from("TcpIp"))],
account_name: None,
account_password: None,
};
let service = match m.open_service(super::service_name(iface), ACCESS) {
Ok(s) => {
let current = s.query_config()?;
let wanted_args = format!("\"{}\" \"{}\" \"{iface}\"", program.display(), conf.display());
if current.executable_path.to_string_lossy() != wanted_args {
s.change_config(&info)?;
}
s
}
Err(_) => m.create_service(&info, ACCESS).context("creating the tunnel service")?,
};
// Its firewall lets the tunnel's own traffic out by the service's SID, which a service
// has in its token only with this.
service.set_config_service_sid_info(ServiceSidType::Unrestricted)?;
Ok(())
}
pub fn start(iface: &str) -> Result<()> {
let s = manager()?.open_service(super::service_name(iface), ACCESS).context("the tunnel is not registered")?;
if s.query_status()?.current_state == ServiceState::Stopped {
s.start::<&str>(&[]).context("starting the tunnel")?;
}
Ok(())
}
pub fn stop(iface: &str) -> Result<()> {
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
if s.query_status()?.current_state != ServiceState::Stopped {
let _ = s.stop();
for _ in 0..40 {
if s.query_status()?.current_state == ServiceState::Stopped {
break;
}
std::thread::sleep(Duration::from_millis(250));
}
}
Ok(())
}
pub fn state(iface: &str) -> String {
let Ok(m) = manager() else { return "unknown".into() };
let Ok(s) = m.open_service(super::service_name(iface), ServiceAccess::QUERY_STATUS) else { return "inactive".into() };
match s.query_status().map(|st| st.current_state) {
Ok(ServiceState::Running) => "active",
Ok(ServiceState::StartPending) => "activating",
Ok(ServiceState::StopPending) => "deactivating",
Ok(_) => "inactive",
Err(_) => "unknown",
}
.into()
}
/// Stopped and deleted, if it runs this suite's program (under `bin`): a tunnel of
/// amneziawg-windows's own client by the same name is left alone.
pub fn remove(iface: &str, bin: &Path) -> Result<()> {
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
let bin = bin.to_string_lossy().to_lowercase();
if !s.query_config().is_ok_and(|c| c.executable_path.to_string_lossy().to_lowercase().contains(&bin)) {
return Ok(());
}
stop(iface)?;
s.delete()?;
Ok(())
}
}
/// Registers every system-wide profile's tunnel (its `.conf` written), removes the tunnels
/// of profiles gone, and starts the `autostart` ones when `boot`. Errors per profile are
/// returned as lines, the rest done.
pub fn apply(cfg: &Config, paths: &Paths, program: Option<&Path>, boot: bool) -> Vec<String> {
let wanted = profiles(cfg);
let mut notes = Vec::new();
let keep: Vec<&str> = wanted.iter().map(|v| v.iface.as_str()).collect();
for iface in registered(paths) {
if !keep.contains(&iface.as_str()) {
match forget(paths, &iface) {
Ok(()) => notes.push(format!("AmneziaWG tunnel {iface} removed: its profile is gone, or AmneziaWG is off")),
Err(e) => notes.push(format!("AmneziaWG tunnel {iface}: {e:#}")),
}
}
}
if wanted.is_empty() {
return notes;
}
let Some(program) = program else {
notes.push("AmneziaWG's tunnel (component amneziawg) is not installed: the system-wide profiles cannot start".into());
return notes;
};
for vpn in &wanted {
let r = write_conf(cfg, paths, vpn).and_then(|conf| register(&vpn.iface, program, &conf));
match r {
Ok(()) if boot && vpn.autostart => {
if let Err(e) = start(&vpn.iface) {
notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name));
}
}
Ok(()) => {}
Err(e) => notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name)),
}
}
notes
}
#[cfg(windows)]
fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
scm::register(iface, program, conf)
}
#[cfg(not(windows))]
fn register(_iface: &str, _program: &Path, _conf: &Path) -> Result<()> {
Ok(())
}
#[cfg(windows)]
pub fn start(iface: &str) -> Result<()> {
scm::start(iface)
}
#[cfg(not(windows))]
pub fn start(_iface: &str) -> Result<()> {
anyhow::bail!("AmneziaWG as a system-wide VPN runs on Windows only")
}
#[cfg(windows)]
pub fn stop(iface: &str) -> Result<()> {
scm::stop(iface)
}
#[cfg(not(windows))]
pub fn stop(_iface: &str) -> Result<()> {
Ok(())
}
#[cfg(windows)]
pub fn state(iface: &str) -> String {
scm::state(iface)
}
#[cfg(not(windows))]
pub fn state(_iface: &str) -> String {
"windows-only".into()
}
/// Every tunnel this suite registered, stopped and deleted: on uninstall.
#[cfg_attr(not(windows), allow(dead_code))]
pub fn remove_all(paths: &Paths) {
for iface in registered(paths) {
let _ = forget(paths, &iface);
}
}
#[cfg(test)]
mod tests {
use super::*;
use ps_core::config::{AwgOutboundKind, AwgProfile};
#[test]
fn only_profiles_without_an_outbound_are_vpns() {
let mut cfg = Config::default();
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert("home".into(), AwgProfile { autostart: true, ..Default::default() });
cfg.amnezia_wg.profiles.insert("office".into(), AwgProfile { interface_name: Some("awg-office".into()), ..Default::default() });
cfg.amnezia_wg.profiles.insert("exit".into(), AwgProfile { as_outbound: Some(AwgOutboundKind::Userspace), ..Default::default() });
let v = profiles(&cfg);
assert_eq!(v.iter().map(|v| (v.name.as_str(), v.iface.as_str(), v.autostart)).collect::<Vec<_>>(), [("home", "home", true), ("office", "awg-office", false)]);
assert_eq!(service_name("home"), "AmneziaWGTunnel$home");
cfg.amnezia_wg.enable = false;
assert!(profiles(&cfg).is_empty());
}
}
+5
View File
@@ -44,6 +44,11 @@ impl Clash {
Ok(body) Ok(body)
} }
/// The connections open now, with where each goes and through what.
pub async fn connections(&self) -> Result<Value> {
self.get("/connections").await
}
/// Every proxy (outbound or group) with what a selector holds now. /// Every proxy (outbound or group) with what a selector holds now.
pub async fn proxies(&self) -> Result<Value> { pub async fn proxies(&self) -> Result<Value> {
self.get("/proxies").await.map(|v| v["proxies"].clone()) self.get("/proxies").await.map(|v| v["proxies"].clone())
+58 -1
View File
@@ -16,6 +16,12 @@ pub enum Route {
} }
fn client(route: &Route) -> Result<reqwest::Client> { fn client(route: &Route) -> Result<reqwest::Client> {
client_with(route, Some(Duration::from_secs(60)))
}
/// `total`: the whole transfer's limit; none for an archive, which a stall (a minute without a
/// byte) ends instead.
fn client_with(route: &Route, total: Option<Duration>) -> Result<reqwest::Client> {
let policy = reqwest::redirect::Policy::custom(|attempt| { let policy = reqwest::redirect::Policy::custom(|attempt| {
let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default(); let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default();
let to = attempt.url().as_str().to_owned(); let to = attempt.url().as_str().to_owned();
@@ -34,7 +40,10 @@ fn client(route: &Route) -> Result<reqwest::Client> {
.user_agent(USER_AGENT) .user_agent(USER_AGENT)
.redirect(policy) .redirect(policy)
.connect_timeout(Duration::from_secs(15)) .connect_timeout(Duration::from_secs(15))
.timeout(Duration::from_secs(60)); .read_timeout(Duration::from_secs(60));
if let Some(total) = total {
b = b.timeout(total);
}
b = match route { b = match route {
Route::Direct => b.no_proxy(), Route::Direct => b.no_proxy(),
Route::Proxy { port, login } => { Route::Proxy { port, login } => {
@@ -69,6 +78,54 @@ pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
Ok(body) Ok(body)
} }
/// A large download (a component's archive), at most `limit` bytes: no limit on the whole
/// transfer, which a slow line needs, but a minute without a byte fails it, and a transfer cut
/// short is taken up where it stopped (an HTTP range), eight times at most.
pub async fn get_large(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
let scheme = url_parts::split(url).map(|u| u.scheme).unwrap_or_default();
if scheme != "http" && scheme != "https" {
bail!("the URL must be http:// or https://");
}
let http = client_with(route, None)?;
let mut body: Vec<u8> = Vec::new();
let mut last = String::new();
for _ in 0..8 {
let mut req = http.get(url);
if !body.is_empty() {
req = req.header(reqwest::header::RANGE, format!("bytes={}-", body.len()));
}
let mut resp = match req.send().await {
Ok(r) => r,
Err(e) => {
last = describe(&e);
continue;
}
};
match resp.status().as_u16() {
206 if !body.is_empty() => {}
// The whole of it again: the server takes no range.
200 => body.clear(),
s => bail!("the server answered {s}"),
}
loop {
match resp.chunk().await {
Ok(Some(chunk)) => {
body.extend_from_slice(&chunk);
if body.len() > limit {
bail!("the answer is larger than {limit} bytes");
}
}
Ok(None) => return Ok(body),
Err(e) => {
last = describe(&e);
break;
}
}
}
}
bail!("{last} (after eight tries)")
}
/// `body` posted as JSON to `url` with `headers`, and the JSON answer. /// `body` posted as JSON to `url` with `headers`, and the JSON answer.
pub async fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)], route: &Route) -> Result<serde_json::Value> { pub async fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)], route: &Route) -> Result<serde_json::Value> {
let mut req = client(route)?.post(url).json(body); let mut req = client(route)?.post(url).json(body);
+1 -1
View File
@@ -27,7 +27,7 @@ pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Res
} }
let mut last = None; let mut last = None;
for route in routes { for route in routes {
match fetch::get(&src.url, route, 512 * 1024 * 1024).await { match fetch::get_large(&src.url, route, 512 * 1024 * 1024).await {
Ok(data) => { Ok(data) => {
if let Some(want) = &src.sha256 { if let Some(want) = &src.sha256 {
let got = hex(&data); let got = hex(&data);
+7
View File
@@ -4,7 +4,9 @@
//! it); `--console` runs it in the foreground, which is also how it runs off Windows. //! it); `--console` runs it in the foreground, which is also how it runs off Windows.
mod api; mod api;
mod autoproxy;
mod awg; mod awg;
mod awgvpn;
mod clash; mod clash;
mod components; mod components;
mod fetch; mod fetch;
@@ -21,6 +23,7 @@ mod units;
mod warp; mod warp;
#[cfg(windows)] #[cfg(windows)]
mod winsvc; mod winsvc;
mod wl;
mod zapret; mod zapret;
use std::path::PathBuf; use std::path::PathBuf;
@@ -102,6 +105,10 @@ pub async fn run(
tracing::warn!("not starting the proxy yet: {e}"); tracing::warn!("not starting the proxy yet: {e}");
} }
tokio::spawn(api::serve(server, shared.clone())); tokio::spawn(api::serve(server, shared.clone()));
tokio::spawn(autoproxy::runner(shared.clone()));
tokio::spawn(autoproxy::sample(shared.clone()));
tokio::spawn(autoproxy::sample_slow(shared.clone()));
tokio::spawn(zapret::sync_loop(shared.clone()));
// First fetches: what the configuration needs and has not got yet. // First fetches: what the configuration needs and has not got yet.
{ {
let shared = shared.clone(); let shared = shared.clone();
+95 -2
View File
@@ -1,6 +1,6 @@
//! The service's state and what it does with it: render, write, check, (re)start, fetch. //! The service's state and what it does with it: render, write, check, (re)start, fetch.
use std::collections::BTreeMap; use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
use std::time::{Duration, SystemTime}; use std::time::{Duration, SystemTime};
@@ -37,6 +37,13 @@ pub struct Service {
pub last_error: Option<String>, pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>, pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool, tcp_timestamps_on: bool,
/// What whitelist-bypass's units waited for at the last apply, said when it first did.
wl_waiting: BTreeSet<String>,
/// autoProxy's requests and the hosts its prober learns from (crate::autoproxy).
pub ap: Arc<crate::autoproxy::AutoProxy>,
/// Whether the system-wide AmneziaWG tunnels were registered since the service started:
/// the first time, the `autostart` ones start too.
awg_vpn_started: bool,
} }
fn digest(data: &[u8]) -> String { fn digest(data: &[u8]) -> String {
@@ -59,6 +66,9 @@ impl Service {
last_error: None, last_error: None,
last_fetch: BTreeMap::new(), last_fetch: BTreeMap::new(),
tcp_timestamps_on: false, tcp_timestamps_on: false,
wl_waiting: BTreeSet::new(),
ap: Arc::default(),
awg_vpn_started: false,
store, store,
}) })
} }
@@ -99,6 +109,17 @@ impl Service {
{ {
direct.push(p.to_string_lossy().into_owned()); direct.push(p.to_string_lossy().into_owned());
} }
// The joiners' calls, and the creators' unless they go through the proxy.
if cfg.whitelist_bypass.enable {
let wl = &cfg.whitelist_bypass;
let joiners = wl.joiners.values().map(|j| format!("headless-{}-joiner", j.platform.as_str()));
let creators = wl.creators.values().filter(|c| c.upstream == ps_core::config::Upstream::Direct).map(|c| format!("headless-{}-creator", c.platform.as_str()));
for name in joiners.chain(creators).collect::<BTreeSet<_>>() {
if let Some(p) = self.comps.find("whitelist-bypass", &name) {
direct.push(p.to_string_lossy().into_owned());
}
}
}
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy"). // Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
if cfg.tor.enable if cfg.tor.enable
&& cfg.tor.upstream == ps_core::config::Upstream::Direct && cfg.tor.upstream == ps_core::config::Upstream::Direct
@@ -122,6 +143,9 @@ impl Service {
ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()), ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()),
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() }, ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
windows: cfg!(windows), windows: cfg!(windows),
autoproxy_rules_dir: cfg.proxy.auto_proxy.enable.then(|| crate::autoproxy::rules_dir(paths).to_string_lossy().into_owned()),
zapret2_direct_rule_set: crate::zapret::rule_set_paths(cfg, paths).0,
zapret2_proxy_rule_set: crate::zapret::rule_set_paths(cfg, paths).1,
} }
} }
@@ -163,8 +187,71 @@ impl Service {
if let Err(e) = &awg { if let Err(e) = &awg {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}")); self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
} }
self.apply_awg_vpn();
let wl = self.apply_wl().await;
if let Err(e) = &wl {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
}
let proxy = self.apply_proxy().await; let proxy = self.apply_proxy().await;
zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy) zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
}
/// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with
/// their profiles, the `autostart` ones started with the service.
fn apply_awg_vpn(&mut self) {
let cfg = self.cfg().clone();
let boot = !self.awg_vpn_started;
self.awg_vpn_started = true;
if !cfg!(windows) {
if !crate::awgvpn::profiles(&cfg).is_empty() {
self.sup.note(crate::awgvpn::UNIT, "proxy-suite: AmneziaWG as a system-wide VPN runs on Windows only; not registered");
}
return;
}
let program = self.comps.program("amneziawg", "awg-tunnel").ok();
for note in crate::awgvpn::apply(&cfg, self.paths(), program.as_deref(), boot) {
self.sup.note(crate::awgvpn::UNIT, format!("proxy-suite: {note}"));
}
}
/// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it
/// is on; the ones no longer wanted stopped, and what the rest wait for said once.
pub async fn apply_wl(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let mut wanted_cfg = cfg.clone();
let on = cfg.enable && cfg.whitelist_bypass.enable;
if !self.proxy_wanted() {
wanted_cfg.whitelist_bypass.joiners.clear();
}
let (units, waiting) = if on {
let auth = &cfg.proxy.listener.auth;
let password = match (&auth.password, &auth.password_file) {
(Some(p), _) => Some(p.clone()),
(None, Some(f)) => Some(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.lines().next().unwrap_or("").to_owned()),
(None, None) => None,
};
let login = auth.username.clone().zip(password);
let hop = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let program = |name: &str| self.comps.program("whitelist-bypass", name);
crate::wl::units(&wanted_cfg, self.paths(), &program, (&hop.0, &hop.1), login)
} else {
(Vec::new(), Vec::new())
};
let waiting: BTreeSet<String> = waiting.into_iter().collect();
for w in waiting.difference(&self.wl_waiting) {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {w}"));
}
self.wl_waiting = waiting;
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if (name.starts_with(crate::wl::JOINER_PREFIX) || name.starts_with(crate::wl::CREATOR_PREFIX)) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
} }
/// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while /// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while
@@ -299,6 +386,12 @@ impl Service {
for w in &rendered.warnings { for w in &rendered.warnings {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}")); self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
} }
// sing-box refuses a local rule-set file that is not there: autoProxy's and zapret2's,
// written first.
if !rendered.probe_exits.is_empty() {
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
}
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
let backend = self.cfg().proxy.backend; let backend = self.cfg().proxy.backend;
let main_program = match backend { let main_program = match backend {
+100
View File
@@ -144,6 +144,9 @@ pub fn install() -> Result<()> {
Ok(false) => {} Ok(false) => {}
Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"), Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"),
} }
if let Err(e) = apps::add(&to) {
println!("warning: the entry in Settings → Apps: {e:#}");
}
println!("Open a new terminal and try: proxy-ctl status"); println!("Open a new terminal and try: proxy-ctl status");
Ok(()) Ok(())
} }
@@ -163,8 +166,11 @@ pub fn uninstall() -> Result<()> {
} else { } else {
println!("{DISPLAY} was not installed."); println!("{DISPLAY} was not installed.");
} }
remove_windivert(&manager);
crate::awgvpn::remove_all(&crate::paths::Paths::platform_default());
let dir = install_dir(); let dir = install_dir();
desktop::remove(); desktop::remove();
apps::remove();
let _ = path::remove(&dir); let _ = path::remove(&dir);
if dir.exists() { if dir.exists() {
// This program may be one of the files: they go a moment after it exits. Raw, as cmd // This program may be one of the files: they go a moment after it exits. Raw, as cmd
@@ -185,6 +191,100 @@ pub fn uninstall() -> Result<()> {
Ok(()) Ok(())
} }
/// The WinDivert driver zapret loaded from this suite's components, if it is still registered
/// (WinDivert removes its own service as it loads, but one stopped hard can stay): stopped and
/// deleted, as Flowseal's service.bat removes it. One from elsewhere is left alone.
fn remove_windivert(manager: &ServiceManager) {
let ours = crate::paths::Paths::platform_default().root.to_string_lossy().to_lowercase();
for name in ["WinDivert", "WinDivert14"] {
let Ok(service) = manager.open_service(name, ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) else {
continue;
};
let Ok(config) = service.query_config() else { continue };
if config.executable_path.to_string_lossy().to_lowercase().contains(&ours) {
let _ = service.stop();
if service.delete().is_ok() {
println!("WinDivert's driver ({name}) is removed.");
}
}
}
}
/// The entry in Settings → Apps (and Control Panel's Programs and Features): its Uninstall runs
/// uninstall.cmd, which asks for administrator rights; `QuietUninstallString` (winget, scripts
/// that run elevated) the service's own `uninstall`.
mod apps {
use std::path::Path;
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteTreeW,
RegSetValueExW,
};
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn size_kib(dir: &Path) -> u64 {
fn walk(dir: &Path) -> u64 {
std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| match e.file_type() {
Ok(t) if t.is_dir() => walk(&e.path()),
Ok(t) if t.is_file() => e.metadata().map_or(0, |m| m.len()),
_ => 0,
}).sum()
}
walk(dir) / 1024
}
pub fn add(dir: &Path) -> Result<()> {
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
let d = dir.display();
let text = [
("DisplayName", super::DISPLAY.to_owned()),
("DisplayVersion", env!("CARGO_PKG_VERSION").to_owned()),
("Publisher", "Proxy Suite".to_owned()),
("URLInfoAbout", "https://git.faumaray.com/faumaray/proxy-suite-flake".to_owned()),
("InstallLocation", d.to_string()),
("DisplayIcon", format!("{d}\\proxy-suite.exe")),
// cmd's /c takes the whole line in one more pair of quotes.
("UninstallString", format!("\"{system}\\System32\\cmd.exe\" /c \"\"{d}\\uninstall.cmd\"\"")),
("QuietUninstallString", format!("\"{d}\\proxy-suite-service.exe\" uninstall")),
];
let numbers = [("NoModify", 1u32), ("NoRepair", 1), ("EstimatedSize", size_kib(dir).min(u32::MAX as u64) as u32)];
// SAFETY: NUL-terminated names and data, lengths as given; the key is closed below.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegCreateKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, std::ptr::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, std::ptr::null(), &mut key, std::ptr::null_mut()) != ERROR_SUCCESS {
bail!("cannot create the uninstall key");
}
let mut failed = false;
for (name, value) in &text {
let data = wide(value);
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) != ERROR_SUCCESS;
}
for (name, value) in &numbers {
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_DWORD, (value as *const u32).cast(), 4) != ERROR_SUCCESS;
}
RegCloseKey(key);
if failed {
bail!("cannot write the uninstall key");
}
}
Ok(())
}
pub fn remove() {
// SAFETY: a NUL-terminated name.
unsafe {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr());
}
}
}
/// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray; /// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray;
/// closed before its files are replaced or removed. /// closed before its files are replaced or removed.
mod desktop { mod desktop {
+221
View File
@@ -0,0 +1,221 @@
//! whitelist-bypass, as upstream's whitelist-bypass.nix runs it: joiners, each a SOCKS listener
//! on loopback (with the hop login) behind its outbound, tunnelled through a video call; and
//! creators, the free ends of those calls. Links, logins and passwords reach them through the
//! environment (the build makes those the flags' defaults), never their command lines.
//!
//! A joiner waits for its call's link (`proxy-ctl wl join`, or `linkFile`); a creator for a login
//! (`proxy-ctl wl auth`, or `cookiesFile`), which it keeps refreshing in its own working copy.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, Upstream, WlCreator, WlResources};
use ps_core::derived::ports;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const JOINER_PREFIX: &str = "proxy-suite-wb-joiner-";
pub const CREATOR_PREFIX: &str = "proxy-suite-wb-creator-";
/// What `proxy-ctl wl` leaves for the units: links (`<name>.join`), logins
/// (`<name>.cookies.json`), and the creators' calls (`<name>.link`, last line the current).
pub fn state_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass")
}
/// The creators' working logins, which they rewrite as they refresh them.
fn sessions_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass-sessions")
}
/// `name`'s file in `dir`: a plain name there, checked here again whatever let it through (on
/// Windows, joining an absolute path replaces the directory).
fn named(dir: &Path, name: &str, suffix: &str) -> Result<PathBuf> {
if !ps_core::config::path_name_ok(name) {
bail!("'{name}' is not a creator or joiner name");
}
Ok(dir.join(format!("{name}{suffix}")))
}
/// `name`'s file in the state directory: `.join`, `.cookies.json` or `.link`.
pub fn state_file(paths: &Paths, name: &str, suffix: &str) -> Result<PathBuf> {
named(&state_dir(paths), name, suffix)
}
fn resources(r: WlResources) -> &'static str {
match r {
WlResources::Moderate => "moderate",
WlResources::Default => "default",
WlResources::Unlimited => "unlimited",
}
}
/// A link as the units take it: whitespace gone, one line.
pub fn clean_link(text: &str) -> Result<String> {
let link: String = text.chars().filter(|c| !c.is_whitespace()).collect();
if link.is_empty() {
bail!("an empty link");
}
if link.len() > 4096 || link.chars().any(char::is_control) {
bail!("that is not a call link");
}
Ok(link)
}
/// The units, and what each that cannot run yet waits for. `program` finds one of the
/// component's programs by name.
pub fn units(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
hop: (&str, &str),
proxy_login: Option<(String, String)>,
) -> (Vec<UnitSpec>, Vec<String>) {
let w = &cfg.whitelist_bypass;
let mut units = Vec::new();
let mut waiting = Vec::new();
for (i, (tag, j)) in w.joiners.iter().enumerate() {
let port = ports::WL_JOINER_BASE + i as u16;
// The link `wl join` gave wins over linkFile.
let link = state_file(paths, tag, ".join")
.and_then(|f| Ok(std::fs::read_to_string(f)?))
.ok()
.or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()))
.and_then(|t| clean_link(&t).ok());
let Some(link) = link else {
waiting.push(format!("whitelist-bypass joiner '{tag}' waits for its call's link: proxy-ctl wl join {tag} <link>"));
continue;
};
let program = match program(&format!("headless-{}-joiner", j.platform.as_str())) {
Ok(p) => p,
Err(e) => {
waiting.push(format!("whitelist-bypass joiner '{tag}': {e:#}"));
continue;
}
};
let args = vec!["--socks-port".into(), port.to_string(), "--socks-user".into(), hop.0.to_owned()];
units.push(UnitSpec {
name: format!("{JOINER_PREFIX}{tag}"),
program,
generation: format!("{args:?}{link}"),
args,
env: vec![("WB_LINK".into(), link), ("WB_SOCKS_PASS".into(), hop.1.to_owned())],
cwd: None,
});
}
for (name, c) in &w.creators {
match creator(cfg, paths, program, name, c, proxy_login.clone()) {
Ok(Some(unit)) => units.push(unit),
Ok(None) => waiting.push(format!("whitelist-bypass creator '{name}' waits for a login: proxy-ctl wl auth {name} <cookies.json>")),
Err(e) => waiting.push(format!("whitelist-bypass creator '{name}': {e:#}")),
}
}
(units, waiting)
}
/// The call a creator made and keeps rejoining: the last line it wrote.
pub fn last_link(paths: &Paths, name: &str) -> Option<String> {
let text = std::fs::read_to_string(state_file(paths, name, ".link").ok()?).ok()?;
text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned)
}
/// Writes a file only the service reads: a link, a login.
pub fn write_private(file: &Path, data: &[u8]) -> Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
write_atomic(file, data).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn creator(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
name: &str,
c: &WlCreator,
proxy_login: Option<(String, String)>,
) -> Result<Option<UnitSpec>> {
let program = program(&format!("headless-{}-creator", c.platform.as_str()))?;
let sessions = sessions_dir(paths);
std::fs::create_dir_all(state_dir(paths))?;
std::fs::create_dir_all(&sessions)?;
let given = state_file(paths, name, ".cookies.json")?;
let cookies = named(&sessions, name, ".cookies.json")?;
// A login `wl auth` left replaces the working copy, then goes.
if given.is_file() {
write_private(&cookies, &std::fs::read(&given)?)?;
std::fs::remove_file(&given)?;
} else if !cookies.is_file()
&& let Some(f) = &c.cookies_file
{
write_private(&cookies, &std::fs::read(f).with_context(|| format!("reading {f}"))?)?;
}
if !cookies.is_file() {
return Ok(None);
}
let links = state_file(paths, name, ".link")?;
// linkFile's call, or the last one it made (empty: it makes one).
let link = match &c.link_file {
Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?,
None => last_link(paths, name).unwrap_or_default(),
};
let mut args: Vec<String> = vec![
"--cookies".into(),
cookies.display().to_string(),
"--write-file".into(),
links.display().to_string(),
"--resources".into(),
resources(c.resources).into(),
];
let mut env = vec![("WB_LINK".to_owned(), link)];
if c.upstream == Upstream::Proxy {
// From the parsed address, as Tor's: the listener's own, or loopback for a wildcard.
let l = &cfg.proxy.listener;
let host = match l.address.parse::<std::net::IpAddr>().context("proxy.listener.address is not an IP address")? {
ip if ip.is_unspecified() => "127.0.0.1".to_owned(),
std::net::IpAddr::V6(v6) => format!("[{v6}]"),
v4 => v4.to_string(),
};
args.extend(["--upstream-socks".into(), format!("{host}:{}", l.port)]);
if let Some((user, password)) = proxy_login {
args.extend(["--upstream-user".into(), user]);
env.push(("WB_UPSTREAM_PASS".into(), password));
}
}
Ok(Some(UnitSpec {
name: format!("{CREATOR_PREFIX}{name}"),
program,
generation: format!("{args:?}{}", env[0].1),
args,
env,
cwd: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_are_one_clean_line() {
assert_eq!(clean_link(" https://stream.wb.ru/room/abc \n").unwrap(), "https://stream.wb.ru/room/abc");
assert!(clean_link(" \n").is_err());
assert!(clean_link("a\u{7}b").is_err());
}
#[test]
fn files_are_only_plain_names_in_the_state_directory() {
let paths = Paths::new("state");
assert_eq!(state_file(&paths, "laptop", ".link").unwrap(), std::path::Path::new("state/whitelist-bypass/laptop.link"));
for bad in [r"C:\Windows\System32\x", "/etc/x", "../x", "..", "a/b", r"a\b", "CON", "nul", "COM1", ""] {
assert!(state_file(&paths, bad, ".link").is_err(), "{bad}");
}
}
}
+178 -8
View File
@@ -146,19 +146,43 @@ pub async fn enable_tcp_timestamps() -> Result<()> {
Ok(()) Ok(())
} }
/// The unit for zapret2: winws2 with nfqws2-keenetic's strategies (ps_core::zapret2), its /// The unit for zapret2: winws2 with nfqws2-keenetic's or z2k's strategies
/// lists in the service's `zapret2\\` directory, the learned one where winws2 can still write /// (ps_core::zapret2), upstream's Lua layers from the zapret2-extras component when it is
/// once it runs at Low integrity. /// installed, its lists in the service's `zapret2\\` directory, and what winws2 writes (the
/// learned list, each site's strategy, the detector's verdicts) where it can still write once
/// it runs at Low integrity.
pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> { pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
use ps_core::config::StrategySource;
use ps_core::zapret2; use ps_core::zapret2;
let z = &cfg.zapret.zapret2; let z = &cfg.zapret.zapret2;
let component = paths.bin().join("zapret2"); let component = paths.bin().join("zapret2");
let conf = std::fs::read_to_string(component.join("keenetic").join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?; let extras_dir = paths.bin().join("zapret2-extras");
let source = zapret2::keenetic(&conf, &with_sep(&component.join("keenetic"))).map_err(anyhow::Error::msg)?; let extras_there = extras_dir.join("lua").join("detect.lua").is_file();
let keenetic_dir = component.join("keenetic");
let source = if z.strategy_source == StrategySource::Z2k && extras_there {
let z2k = extras_dir.join("z2k");
let read = |name: &str| std::fs::read_to_string(z2k.join(name)).with_context(|| format!("reading z2k's {name}"));
zapret2::z2k(
&read("profiles.plain")?,
&read("profiles.learn")?,
&read("blobs")?,
&read("ports")?,
&lua_path(&z2k),
&lua_path(&z2k.join("root")),
&with_sep_lua(&z2k.join("files").join("lua")),
)
.map_err(anyhow::Error::msg)?
} else {
let conf = std::fs::read_to_string(keenetic_dir.join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?;
zapret2::keenetic(&conf, &with_sep(&keenetic_dir)).map_err(anyhow::Error::msg)?
};
let state = paths.root.join("zapret2"); let state = paths.root.join("zapret2");
let learned = state.join("learned"); let learned = state.join("learned");
std::fs::create_dir_all(&learned)?; let circular = learned.join("circular");
let fallback = learned.join("run");
std::fs::create_dir_all(&circular)?;
std::fs::create_dir_all(&fallback)?;
#[cfg(windows)] #[cfg(windows)]
low_integrity(&learned)?; low_integrity(&learned)?;
let user = state.join("zapret-hosts-user.txt"); let user = state.join("zapret-hosts-user.txt");
@@ -170,23 +194,151 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
std::fs::write(f, b"")?; std::fs::write(f, b"")?;
} }
} }
let extras = extras_there.then(|| {
// Never learned by the detector, as the source's own learning never learned them.
let mut exclude_lua = Vec::new();
if !source.z2k {
exclude_lua.push(lua_path(&keenetic_dir.join("lists").join("exclude.list")));
}
exclude_lua.push(lua_path(&exclude));
zapret2::Extras {
lua: with_sep(&extras_dir.join("lua")),
z2k_lua: with_sep(&extras_dir.join("z2k").join("files").join("lua")),
auto_lua: lua_path(&auto),
exclude_lua,
}
});
let p = zapret2::Paths { let p = zapret2::Paths {
lua: with_sep(&component.join("lua")), lua: with_sep(&component.join("lua")),
user: user.to_string_lossy().into_owned(), user: user.to_string_lossy().into_owned(),
exclude: exclude.to_string_lossy().into_owned(), exclude: exclude.to_string_lossy().into_owned(),
auto: auto.to_string_lossy().into_owned(), auto: auto.to_string_lossy().into_owned(),
extras,
}; };
let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?; let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?;
// Read inside winws2 by z2k's state layer, the detector and the per-site key.
let mut env = Vec::new();
if extras_there {
env.push(("Z2K_STATE_DIR_OVERRIDE".to_owned(), lua_path(&circular)));
env.push(("Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE".to_owned(), lua_path(&fallback)));
env.push(("PROXY_SUITE_ZAPRET2_VERDICTS".to_owned(), lua_path(&learned.join("verdicts.tsv"))));
env.push(("PROXY_SUITE_PUBLIC_SUFFIXES".to_owned(), lua_path(&extras_dir.join("public_suffixes.txt"))));
}
let generation = { let generation = {
use sha2::{Digest, Sha256}; use sha2::{Digest, Sha256};
let mut h = Sha256::new(); let mut h = Sha256::new();
for a in &argv { for a in argv.iter().chain(env.iter().map(|(_, v)| v)) {
h.update(a.as_bytes()); h.update(a.as_bytes());
h.update(b"\n"); h.update(b"\n");
} }
h.finalize().iter().map(|b| format!("{b:02x}")).collect() h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}; };
Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(component), generation }) // In a file winws2 reads (`@file`, its only argument): z2k's strategies alone run past
// the 32767 characters a Windows command line holds.
let file = paths.run().join("winws2.conf");
write_atomic(&file, options_file(&argv)?.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
Ok(UnitSpec { name: UNIT.into(), program, args: vec![format!("@{}", file.display())], env, cwd: Some(component), generation })
}
/// winws2's options as its `@file` takes them: one a line, quoted when it holds a space. One
/// holding a line break would be read as more options than it is: refused.
pub fn options_file(argv: &[String]) -> Result<String> {
let mut out = String::new();
for a in argv {
if a.contains(char::is_control) {
bail!("a winws2 option holds a control character: {:?}", a.chars().take(80).collect::<String>());
}
if a.contains(char::is_whitespace) || a.contains('"') {
out.push('"');
out.push_str(&a.replace('\\', "\\\\").replace('"', "\\\""));
out.push('"');
} else {
out.push_str(a);
}
out.push('\n');
}
Ok(out)
}
/// zapret2's rule-sets for the proxy (ps_core::zapret2::routing), when it runs: what it fixes,
/// sent direct (`zapret.directSync`), and what it cannot, for the proxy
/// (`zapret2.proxyFallback`).
pub fn rule_set_paths(cfg: &Config, paths: &Paths) -> (Option<String>, Option<String>) {
let on = cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2;
let dir = paths.root.join("zapret2-direct");
let file = |name: &str| dir.join(name).to_string_lossy().into_owned();
(
(on && cfg.zapret.direct_sync.enable).then(|| file("direct.json")),
(on && cfg.zapret.zapret2.proxy_fallback).then(|| file("proxy.json")),
)
}
/// The rule-sets rebuilt from zapret2's lists and its detector's verdicts, each written only
/// when it changed (sing-box reloads a rule-set file replaced). Whether either did.
pub fn sync_rule_sets(cfg: &Config, paths: &Paths) -> Result<bool> {
let (direct, proxy) = rule_set_paths(cfg, paths);
if direct.is_none() && proxy.is_none() {
return Ok(false);
}
let state = paths.root.join("zapret2");
let read = |p: PathBuf| std::fs::read_to_string(p).unwrap_or_default();
let auto = cfg.zapret.zapret2.auto_hostlist.enable.then(|| read(state.join("learned").join("zapret-hosts-auto.txt")));
let (d, p) = ps_core::zapret2::routing(
&read(state.join("zapret-hosts-user.txt")),
auto.as_deref(),
&read(state.join("zapret-hosts-user-exclude.txt")),
&read(state.join("learned").join("verdicts.tsv")),
);
let mut changed = false;
for (path, set) in [(direct, d), (proxy, p)] {
let Some(path) = path else { continue };
let path = PathBuf::from(path);
let body = serde_json::to_vec(&set)?;
if std::fs::read(&path).ok().as_deref() != Some(body.as_slice()) {
std::fs::create_dir_all(path.parent().unwrap())?;
write_atomic(&path, &body)?;
changed = true;
}
}
Ok(changed)
}
/// The rule-sets kept in step with what zapret2 learns, every ten seconds.
pub async fn sync_loop(shared: crate::service::Shared) {
loop {
tokio::time::sleep(std::time::Duration::from_secs(10)).await;
let s = shared.lock().await;
if let Err(e) = sync_rule_sets(s.cfg(), s.paths()) {
tracing::warn!("zapret2's rule-sets: {e:#}");
}
}
}
/// A path as winws2's Lua takes it in a colon-separated argument, or opens it from the
/// environment: Cygwin's `/cygdrive/c/…` on Windows (winws2 is a Cygwin program), as it is
/// elsewhere.
fn lua_path(p: &Path) -> String {
let s = p.to_string_lossy().into_owned();
if cfg!(windows) { cygwin(&s) } else { s }
}
fn with_sep_lua(p: &Path) -> String {
let mut s = lua_path(p);
if !s.ends_with('/') && !s.ends_with('\\') {
s.push(if cfg!(windows) { '/' } else { std::path::MAIN_SEPARATOR });
}
s
}
/// `C:\\a\\b` as Cygwin names it: `/cygdrive/c/a/b`.
fn cygwin(path: &str) -> String {
let path = path.trim_start_matches(r"\\?\");
match path.as_bytes() {
[d, b':', rest @ ..] if d.is_ascii_alphabetic() => {
format!("/cygdrive/{}{}", (*d as char).to_ascii_lowercase(), String::from_utf8_lossy(rest).replace('\\', "/"))
}
_ => path.replace('\\', "/"),
}
} }
/// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2, /// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2,
@@ -220,3 +372,21 @@ fn low_integrity(dir: &Path) -> Result<()> {
} }
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn options_go_one_a_line_quoted_when_spaced() {
let argv: Vec<String> = ["--filter-tcp=443", "--wf-raw-part=inbound and tcp.Payload[0] == 0x16", r#"--x="a""#].map(String::from).into();
assert_eq!(options_file(&argv).unwrap(), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
assert!(options_file(&["--filter-tcp=443\n--lua-init=@x.lua".to_owned()]).is_err());
}
#[test]
fn cygwin_names_drives_and_separators() {
assert_eq!(cygwin(r"C:\ProgramData\ProxySuite\zapret2\learned"), "/cygdrive/c/ProgramData/ProxySuite/zapret2/learned");
assert_eq!(cygwin(r"\\?\D:\x"), "/cygdrive/d/x");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

+2
View File
@@ -56,6 +56,8 @@
openssh openssh
# wireproxy-awg and whitelist-bypass, built from source (Go cross-compiles). # wireproxy-awg and whitelist-bypass, built from source (Go cross-compiles).
go go
# The setup program (tools/installer.nsi).
nsis
]; ];
buildInputs = guiLibs; buildInputs = guiLibs;
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs; LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs;
+32 -10
View File
@@ -1,35 +1,57 @@
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`. Proxy Suite for Windows, now with a desktop app and a setup program. Since 0.1.0-pre.2 it also gained zapret2 with z2k's strategies and upstream's extended detector, autoProxy, AmneziaWG as a system-wide VPN and as outbounds, WARP, Tor, the SSH tunnel and whitelist-bypass.
**Not yet run on real Windows.** It was built and tested on Linux, and under Wine where Wine can (it cannot draw the app's text: its DirectWrite does not match fonts). See "What has been verified" in the README, and please report what happens on yours. **Not yet run on real Windows.** It was built and tested on Linux, and under Wine where Wine can (it cannot draw the app's text: its DirectWrite does not match fonts). See "What has been verified" in the README, and please report what happens on yours.
### Downloads
- **`ProxySuite-0.2.0-pre.1-windows-x64-setup.exe`**: the setup program (recommended). It installs everything into Program Files, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Silent: `/S`.
- **`ProxySuite-0.2.0-pre.1-windows-x64.zip`**: the same files, unpacked anywhere; `install.cmd` installs them (as an administrator), `uninstall.cmd` removes them.
Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of an unknown publisher, as the programs are not signed yet (**More info** → **Run anyway**). Nothing has to be installed first: the programs carry their C runtime. Needs 64-bit Windows 10 (1903 or later) or 11.
### zapret2
- **z2k's strategies** (`strategySource = "z2k"`), made by z2k's own generator, per category (YouTube, Discord, QUIC, the RKN list), besides nfqws2-keenetic's.
- **Upstream's Lua around either source**: each site's working strategy kept across restarts, strategies keyed by site (the public suffix list), and the **extended detector** (`autoHostlist.extendedDetection`), which also learns sites blocked only some of the time and requests that never get an answer.
- **By the detector's verdicts the proxy routes too**: what zapret2 cannot fix goes through the proxy (`proxyFallback`), what it fixes goes direct so it sees it (`directSync`).
- On Windows the detectors get the server's TLS replies through a WinDivert filter part; a download stalling mid-way (the 16 KB cutoff) is not seen, as WinDivert cannot hand over a flow's first packets alone.
### autoProxy
Sites apps reach directly are probed through each exit, direct first; one blocked directly but reached through an exit is routed through it, as upstream decides (block pages, one exit per network first, strikes against exits that refuse). A site that crawls directly moves to an exit that carries it as well (`slowBelowKiBps`). Blocks zapret can fix stay direct. On its page in the app, or `proxy-ctl proxy auto` (list, probe, learn, forget, clear).
### AmneziaWG
- **As a system-wide VPN**: a profile without `asOutbound` is a tunnel of its own (amneziawg-windows's, built from its source, on Wintun), with its routes, DNS and, for one peer that takes everything, a kill switch; on and off on the app's AmneziaWG page or with `proxy-ctl awg on|off`, at boot with `autostart`.
- **As outbounds**: `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
- Profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings, added in the app.
### The app ### The app
- **Overview:** the local proxy, the DPI bypass and the Telegram proxy, their states and switches; what the service warns of. - **Overview:** the local proxy, the DPI bypass and the Telegram proxy, their states and switches; what the service warns of.
- **DPI bypass:** zapret with Flowseal's presets (the preset, game traffic) or zapret2 (learning, IPv6); your own sites to handle or leave alone. - **DPI bypass:** zapret with Flowseal's presets (the preset, game traffic) or zapret2 (its strategies, learning, the extended detection, IPv6, the strategy log); your own sites to handle or leave alone.
- **Telegram proxy:** on or off, its tg:// links to open in Telegram or copy to a phone, other devices allowed or not, port and fake-TLS domain. - **Telegram proxy:** on or off, its tg:// links to open in Telegram or copy to a phone, other devices allowed or not, port and fake-TLS domain.
- **Whitelist bypass:** joiners and creators, added or removed; a joiner's call link given, a creator's call link copied, its login given (a cookies file, or DION's and Bitrix's email and password).
- **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions. - **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions.
- **autoProxy:** on or off; probe a site through each exit, or learn it now; the sites it routed (forget each, or all); the exits, bad ones marked; what it never touches and how slow is slow.
- **AmneziaWG:** profiles, a system-wide one switched on and off with its tunnel's log, one added from a `vpn://` link or a `.conf`, or removed.
- **Logs:** every service's, live. - **Logs:** every service's, live.
- **Settings:** every option, as JSON, checked by the service before it is saved. - **Settings:** every option, as JSON, checked by the service before it is saved.
- **Components:** what is installed, at which version. - **Components:** what is installed, at which version.
- **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy. - **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy.
- **System proxy:** the app can point Windows' proxy setting (browsers, most programs) at the local proxy while it runs, and puts yours back after. - **System proxy:** the app can point Windows' proxy setting (browsers, most programs) at the local proxy while it runs, and puts yours back after.
- It has an icon (window, taskbar, Start Menu, Settings → Apps), starts at every sign-in in the tray, and is in the Start Menu.
`install.cmd` puts it in the Start Menu and starts it at every sign-in, in the tray. Screenshots are in the README.
### Also ### Also
- zapret's `hostlistRules`: a group of sites with its own strategy, copied from a preset (or another one, `configName`) or given as `nfqwsArgs`, ahead of the preset's own; every preset with them checked by Flowseal's `winws.exe`. - zapret's `hostlistRules`: a group of sites with its own strategy, copied from a preset (or another one, `configName`) or given as `nfqwsArgs`, ahead of the preset's own; every preset with them checked by Flowseal's `winws.exe`.
- The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809). - The SSH tunnel (`sshProxy`): Windows' own OpenSSH as a SOCKS listener for other programs, and, with `asOutbound`, an outbound of the proxy. Needs Windows' "OpenSSH Client" (there by default since Windows 10 1809; the setup program offers it).
- Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy. - Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy.
- AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
- WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`. - WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`.
- What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it. - whitelist-bypass (`whitelistBypass`): its creators and joiners, built from upstream's source; a joiner is an outbound of the proxy through a video call (WB Stream, Telemost, DION, Bitrix), a creator the call's other end. `proxy-ctl wl join|auth|link|new`.
- What is not on Windows yet is no longer accepted silently: the service warns while it is configured, and the app shows it.
- The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`). - The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`).
- Uninstalling removes WinDivert's driver service and the AmneziaWG tunnels too, when they are the suite's.
- Built and published by Gitea Actions. - Built and published by Gitea Actions.
### Install
Download `ProxySuite-0.2.0-pre.1-windows-x64.zip`; its SHA-256 is in the `.sha256` file next to it. Unzip, run `install.cmd` as administrator, then open **Proxy Suite** from the Start Menu. Needs 64-bit Windows 10 (1903 or later) or 11.
### Not yet ### Not yet
AmneziaWG as a system-wide VPN, Tor's onion service, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. Tor's onion service, the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe.
### Note ### Note
Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`. Unlike upstream, the signed-in user may change every setting by default (`userControl`), except the ones that could run programs or read files as SYSTEM: those always need an administrator. On a shared computer, restrict `userControl.scopes`.
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
# AmneziaWG as a system-wide VPN: amneziawg-windows's tunnel (amneziawg-go on Wintun, its
# firewall that blocks what leaves outside a full tunnel, its DNS and routes), built from its
# pinned commit as awg-tunnel.exe rather than its tunnel.dll: the same Run() a tunnel service
# makes, with a main that takes the config's path and the tunnel's name, and its log in a
# file beside the config (not its ring log). Wintun's signed driver DLL from wintun.net,
# pinned as amneziawg-windows's own build pins it.
#
# tools/build-amneziawg.sh OUT_DIR (needs git, go, curl, unzip)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
COMMIT=e90531d15802cb976773f3b63443bc281f738ca3
VERSION=0-unstable-2026-08-14+e90531d
WINTUN_URL=https://www.wintun.net/builds/wintun-0.14.1.zip
WINTUN_SHA256=07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_commit https://github.com/amnezia-vpn/amneziawg-windows "$COMMIT" "$WORK/src"
cd "$WORK/src"
# Its exports (tunnel.dll's, through cgo) out; a main of ours in.
rm main.go
grep -q 'err = ringlogger.InitGlobalLogger("TUN")' service.go || { echo "service.go changed: no ring logger to replace"; exit 1; }
sed -i 's|err = ringlogger.InitGlobalLogger("TUN")|err = nil|' service.go
sed -i '/"github.com\/amnezia-vpn\/amneziawg-windows\/v3\/ringlogger"/d' service.go
cat > proxysuite_main.go <<'GO'
/* SPDX-License-Identifier: MIT
*
* Proxy Suite's AmneziaWG tunnel service: run by the Service Control Manager as
* `awg-tunnel <config path> <tunnel name>`, as amneziawg-windows's tunnel.dll is from its
* client's service. Its log goes to <config path>.log, written anew at each start.
*/
package main
import (
"fmt"
"log"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: awg-tunnel <config> <tunnel name> (as a Windows service)")
os.Exit(2)
}
confPath, name := os.Args[1], os.Args[2]
if f, err := os.OpenFile(confPath+".log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600); err == nil {
log.SetOutput(f)
}
text, err := os.ReadFile(confPath)
if err != nil {
log.Printf("reading %s: %v", confPath, err)
os.Exit(1)
}
if err := Run(string(text), name); err != nil {
log.Printf("the tunnel service: %v", err)
os.Exit(1)
}
}
GO
export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=windows GOARCH=amd64
go build -trimpath -ldflags "-s -w" -o "$WORK/awg-tunnel.exe" .
rm -rf "$OUT" && mkdir -p "$OUT"
cp "$WORK/awg-tunnel.exe" "$OUT/"
# Its license is the MIT text in its README.
sed -n '/^```text/,/^```/p' README.md | sed '1d;$d' >"$OUT/LICENSE"
grep -q 'Permission is hereby granted' "$OUT/LICENSE" || { echo "README.md: no license text"; exit 1; }
fetch_pinned "$WINTUN_URL" "$WINTUN_SHA256" "$WORK/wintun.zip"
unzip -q -o "$WORK/wintun.zip" -d "$WORK/wintun"
cp "$WORK/wintun/wintun/bin/amd64/wintun.dll" "$OUT/"
cp "$WORK/wintun/wintun/LICENSE.txt" "$OUT/wintun-LICENSE.txt"
echo "$VERSION" >"$OUT/.version"
echo "amneziawg $VERSION (windows) in $OUT"
+2 -1
View File
@@ -5,6 +5,7 @@
# #
# tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip) # tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip)
set -euo pipefail set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}") OUT=$(realpath -m "${1:?output directory}")
cd "$(dirname "$0")" cd "$(dirname "$0")"
PY_VERSION=3.12.10 PY_VERSION=3.12.10
@@ -25,7 +26,7 @@ pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_am
mkdir -p "$OUT/python/Lib/site-packages" mkdir -p "$OUT/python/Lib/site-packages"
for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done
git -c advice.detachedHead=false clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src" clone_tag https://github.com/Flowseal/tg-ws-proxy "$TG_TAG" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; } [ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; }
cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/" cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/"
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# whitelist-bypass's headless ends for Windows (creators and joiners: a tunnel through the media
# servers of video calls), built from upstream's tag as upstream's pkgs/whitelist-bypass.nix
# builds them: the call link, the local proxy's password and a joiner's SOCKS password read
# from the environment by default, never the command line (any local user reads that).
#
# tools/build-whitelist-bypass.sh OUT_DIR [GOOS] (needs git, go, sed; GOOS: windows)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows}
VERSION=0.4.4
COMMIT=7c19a7ec40900940fe0c43ea1db7768ee632393d
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_tag https://github.com/kulikov0/whitelist-bypass "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src"
# upstream's postPatch: flag.String("NAME", "", …) defaults to os.Getenv("VAR").
env_default() {
local file="headless/$1/main.go"
grep -q "flag.String(\"$2\", \"\"," "$file" || { echo "$file has no flag $2 to patch"; exit 1; }
sed -i "s|flag.String(\"$2\", \"\",|flag.String(\"$2\", os.Getenv(\"$3\"),|" "$file"
}
for p in vk telemost wbstream dion bitrix; do env_default "$p" upstream-pass WB_UPSTREAM_PASS; done
for p in bitrix dion dion-joiner wbstream wbstream-joiner; do env_default "$p" room WB_LINK; done
for p in telemost-joiner wbstream-joiner dion-joiner bitrix-joiner; do env_default "$p" socks-pass WB_SOCKS_PASS; done
env_default bitrix-joiner link WB_LINK
env_default telemost tm-link WB_LINK
env_default telemost-joiner tm-link WB_LINK
env_default vk vk-link WB_LINK
export GOTOOLCHAIN=local CGO_ENABLED=0 GOOS GOARCH=amd64
ext=
[ "$GOOS" = windows ] && ext=.exe
rm -rf "$OUT" && mkdir -p "$OUT"
# Upstream's names (build-headless.sh): headless-<platform>-creator and -joiner.
for p in vk telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-creator$ext" "./headless/$p"
done
for p in telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-joiner$ext" "./headless/$p-joiner"
done
cp LICENSE "$OUT/"
echo "$VERSION" >"$OUT/.version"
echo "whitelist-bypass $VERSION ($GOOS) in $OUT"
+2 -1
View File
@@ -6,6 +6,7 @@
# #
# tools/build-wireproxy-awg.sh OUT_DIR [GOOS] (needs git, go, patch; GOOS: windows) # tools/build-wireproxy-awg.sh OUT_DIR [GOOS] (needs git, go, patch; GOOS: windows)
set -euo pipefail set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}") OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows} GOOS=${2:-windows}
cd "$(dirname "$0")" cd "$(dirname "$0")"
@@ -15,7 +16,7 @@ PATCHES=$(realpath ../../pkgs/patches)
WORK=$(mktemp -d) WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT trap 'rm -rf "$WORK"' EXIT
git -c advice.detachedHead=false clone -q --depth 1 --branch "v$VERSION" https://github.com/artem-russkikh/wireproxy-awg "$WORK/src" clone_tag https://github.com/artem-russkikh/wireproxy-awg "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; } [ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src" cd "$WORK/src"
patch -s -p1 <"$PATCHES/wireproxy-awg-fwmark.patch" patch -s -p1 <"$PATCHES/wireproxy-awg-fwmark.patch"
+195
View File
@@ -0,0 +1,195 @@
#!/usr/bin/env bash
# zapret2's layers beyond the strategies, as upstream's runtime.nix loads them into nfqws2
# (winws2 here: the same engine, the same Lua): z2k's Lua (a site's working strategy kept
# across restarts, and its own detectors) and its lists and fake payloads; proxy-suite's own
# Lua (the extended detector, the per-site key by public suffix, the fail stamp, the
# strategy log); and z2k's strategies, made by z2k's own generator, as upstream's
# z2k-profiles.template.sh runs it at build time.
#
# What upstream fills in from the configuration at build time is left as a token here and
# filled in by the service (ps_core::zapret2): @HSUF@ and @ESUF@ (the user's sites and
# exclusions), @AUTO@ @EXCLUDE@ @FAILS@ @TIME@ @INSEQ@ @RETRANS@ @LEARNEXTRA@ (the
# learner's arguments), @STALLWATCH@; and the paths, @Z2K@ (z2k's files) and @ROOT@ (the
# tree its generator wrote), which winws2 reads where the component is installed.
#
# tools/build-zapret2-extras.sh OUT_DIR (needs git, bash, gawk, python3, nix)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
HERE=$(realpath "$(dirname "$0")")
UPSTREAM=$(realpath "$HERE/../../modules/proxy-suite/zapret2")
Z2K_COMMIT=7beb9754d65a2cafd9c1d26d382bcb61d453d5b3
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_commit https://github.com/necronicle/z2k "$Z2K_COMMIT" "$WORK/z2k"
Z=$WORK/z2k
rm -rf "$OUT" && mkdir -p "$OUT/z2k/files" "$OUT/lua"
# --- z2k's files the strategies and Lua read --------------------------------------------
cp -r "$Z/files/lua" "$Z/files/lists" "$OUT/z2k/files/"
[ -d "$Z/files/fake" ] && cp -r "$Z/files/fake" "$OUT/z2k/files/"
cp "$Z/LICENSE" "$OUT/z2k/LICENSE"
# Its QUIC silence detector, as upstream's sources.nix patches it: rkn_quic's flows too, and
# a flow answered past udp_in replies only.
q=$OUT/z2k/files/lua/z2k-quic-silence.lua
grep -qF 'local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true }' "$q" || { echo "z2k-quic-silence.lua changed"; exit 1; }
sed -i 's/local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true }/local Z2K_QUIC_POOLS = { yt_quic = true, gv_quic = true, rkn_quic = true }/' "$q"
python3 -I - "$q" <<'PY'
import sys
p = sys.argv[1]
s = open(p).read()
old = " if not desync.outgoing then\n crec.z2k_quic_answered = true\n"
new = " if not desync.outgoing then\n if (pos_get(desync, 'n') or 0) > (tonumber(desync.arg.udp_in) or 1) then crec.z2k_quic_answered = true end\n"
if old not in s:
sys.exit("z2k-quic-silence.lua: the answer check changed")
open(p, "w").write(s.replace(old, new))
PY
# --- proxy-suite's own Lua --------------------------------------------------------------
cp "$UPSTREAM/detect.lua" "$UPSTREAM/persist-every.lua" "$UPSTREAM/strategy-log.lua" "$OUT/lua/"
# The suffix list's path from the environment: it is where the component is installed.
grep -q '"@suffixes@"' "$UPSTREAM/public-suffix-hostkey.lua" || { echo "public-suffix-hostkey.lua changed"; exit 1; }
sed 's|"@suffixes@"|os.getenv("PROXY_SUITE_PUBLIC_SUFFIXES")|' "$UPSTREAM/public-suffix-hostkey.lua" >"$OUT/lua/public-suffix-hostkey.lua"
cat >"$OUT/lua/fail-stamp.lua" <<'LUA'
-- The state layer undoes a rotation when the host succeeded within 30 s, unless a failure
-- came later; only z2k's own detector stamps that failure. Without the stamp any success on
-- a busy host (all of googlevideo.com) undoes every rotation. (upstream's runtime.nix)
local count = automate_failure_counter
function automate_failure_counter(hrec, crec, fails, maxtime)
if not (crec and crec.failure) then
hrec.z2k_last_fail_ts = type(clock_getfloattime) == "function" and clock_getfloattime() or os.time()
end
return count(hrec, crec, fails, maxtime)
end
LUA
psl=$(nix build --no-link --print-out-paths --inputs-from "$HERE/.." nixpkgs#publicsuffix-list | head -1)
python3 -I "$UPSTREAM/public-suffixes.py" "$psl/share/publicsuffix/public_suffix_list.dat" >"$OUT/public_suffixes.txt"
# --- z2k's strategies, by its generator ---------------------------------------------------
root=$WORK/root
mkdir -p "$root/lists" "$root/lua" "$WORK/conf"
cp -r "$Z/files/lists/extra_strats" "$root/"
chmod -R u+w "$root"
cp "$root/extra_strats/TCP/RKN/Discord.txt" "$root/extra_strats/TCP_Discord.txt"
cp "$Z/files/lists/cf_extra_check_ips.txt" "$root/lists/"
: >"$root/lists/discovered-domains.txt"
mkdir -p "$root/state"
echo 1 >"$root/state/tcp16.flag"
ln -s "$Z"/files/lua/*.lua "$root/lua/"
(
export ZAPRET2_DIR="$root" CONFIG_DIR="$WORK/conf" LISTS_DIR="$root/lists"
cd "$Z"
bash -c '
. lib/utils.sh && . lib/config.sh && . lib/strategies.sh && . lib/config_official.sh || exit 1
print_info() { echo "$*" >&2; }
print_success() { echo "$*" >&2; }
print_warning() { echo "$*" >&2; }
print_error() { echo "$*" >&2; }
create_base_config >&2 &&
generate_strategies_conf strats_new2.txt "$STRATEGIES_CONF" >&2 &&
generate_quic_strategies_conf quic_strats.ini "$QUIC_STRATEGIES_CONF" >&2 &&
create_default_strategy_files >&2 &&
generate_nfqws2_opt_from_strategies
'
) >"$WORK/generated" 2>"$WORK/generator.log" || { tail -20 "$WORK/generator.log"; exit 1; }
sed -n '/^NFQWS2_OPT="/,/^"$/p' "$WORK/generated" | sed '1s/^NFQWS2_OPT="//; $d' | tr '\n' ' ' >"$WORK/raw"
grep -q -- '--lua-desync=circular' "$WORK/raw" || { echo "z2k generator produced no profiles"; exit 1; }
# As upstream's z2k-profiles.template.sh: its learned-host list becomes ours, its whitelist
# takes our exclusions, circular's pinned detector args go (autoHostlist fills them), and
# learning is a last profile of its own; with the extended detector, ps_learn's.
profiles() {
local learn=$1 watch=$2
awk -v disc="--hostlist=$root/lists/discovered-domains.txt" \
-v wl="--hostlist-exclude=$root/lists/whitelist.txt" \
-v yt="--hostlist-exclude=$root/extra_strats/TCP/YT/List.txt --hostlist-exclude=$root/extra_strats/TCP/YT_GV/List.txt" \
-v hsuf=" @HSUF@" -v esuf=" @ESUF@" \
-v learn="$learn" -v wlfile="$root/lists/whitelist.txt" -v watch="$watch" '
{
for (i = 1; i <= NF; i++) {
t = $i
if (t == "--new") {
prof++
} else if (t ~ /^--filter-tcp=/ && !(prof in ports)) {
ports[prof] = substr(t, 14)
}
pre = ""
if (t ~ /^--(in-range|out-range|payload|lua-desync)=/) {
if (watch != "" && seen && prof == learner && !watched++) pre = watch " "
filtered[prof] = 1
}
if (t == disc) {
t = "<HOSTLIST_NOAUTO>" hsuf
if (!seen++) {
t = t " " yt
learner = prof
if (prof in filtered) { print "z2k general TLS profile: hostlist after its instances" > "/dev/stderr"; exit 1 }
}
} else if (t == wl) {
t = t esuf
} else if (t ~ /^--lua-desync=circular:/) {
n = split(substr(t, 23), p, ":")
t = "--lua-desync=circular"
for (j = 1; j <= n; j++)
if (p[j] !~ /^(retrans|maxseq|inseq)=/ && p[j] != "reset") t = t ":" p[j]
}
printf "%s%s%s", (i > 1 ? " " : ""), pre, t
}
}
END {
if (!seen || !(learner in ports)) { print "z2k general TLS profile not found" > "/dev/stderr"; exit 1 }
if (watch != "" && !watched) { print "z2k general TLS profile has no instances" > "/dev/stderr"; exit 1 }
if (learn == "")
printf " --new --filter-tcp=%s --filter-l7=tls %s%s <HOSTLIST>%s", ports[learner], wl, esuf, hsuf
else {
sub(/:exclude=/, ":exclude=" wlfile ",", learn)
printf " --new --filter-tcp=%s --filter-l7=tls --in-range=-s65536 --out-range=-s32768 --payload=all --lua-desync=ps_learn:%s", ports[learner], learn
}
}' "$WORK/raw" >"$WORK/body"
# rkn_quic: z2k's YouTube QUIC profile over the sites rkn_tcp handles, right after it.
awk -v yt="--hostlist=$root/extra_strats/UDP/YT/List.txt" \
-v rkn="--hostlist=$root/extra_strats/TCP/RKN/List.txt --hostlist=$root/extra_strats/TCP_Discord.txt <HOSTLIST_NOAUTO> @HSUF@" '
{
n = split($0, p, / --new /)
for (i = 1; i <= n; i++) {
printf "%s%s", (i > 1 ? " --new " : ""), p[i]
if (p[i] ~ /key=yt_quic:/ && (k = index(p[i], yt))) {
q = substr(p[i], 1, k - 1) rkn substr(p[i], k + length(yt))
gsub(/key=yt_quic:/, "key=rkn_quic:", q)
if (!sub(/:udp_in=1:/, ":udp_in=4:", q)) { print "z2k YouTube QUIC udp_in=1 not found" > "/dev/stderr"; exit 1 }
printf " --new %s", q
found++
}
}
}
END { if (found != 1) { print "z2k YouTube QUIC profile not found" > "/dev/stderr"; exit 1 } }' "$WORK/body"
}
profiles "" "" >"$WORK/profiles.plain"
profiles "auto=@AUTO@:exclude=@EXCLUDE@:fails=@FAILS@:time=@TIME@:inseq=@INSEQ@:retrans=@RETRANS@:win=32@LEARNEXTRA@" "@STALLWATCH@" >"$WORK/profiles.learn"
awk -v z="$Z" '
match($0, /^([A-Z0-9_]+_BLOB)="\$ZAPRET_BASE\/([^"]+)"/, m) { file[m[1]] = m[2] }
match($0, /--blob=([a-z0-9_]+):@\$([A-Z0-9_]+_BLOB)/, m) { printf "--blob=%s:@%s/%s ", m[1], z, file[m[2]] }
' "$Z/files/S99zapret2.new" >"$WORK/blobs"
grep -q -- '--blob=' "$WORK/blobs" || { echo "z2k blob registrations not found"; exit 1; }
# The paths as tokens; the tree the generator wrote, shipped.
for f in profiles.plain profiles.learn blobs; do
sed -e "s|$root|@ROOT@|g" -e "s|$Z|@Z2K@|g" "$WORK/$f" >"$OUT/z2k/$f"
if grep -q "$WORK" "$OUT/z2k/$f"; then echo "$f still names the build's directory"; exit 1; fi
done
# The blobs it names, from z2k's tree, wherever they are in it.
for b in $(grep -o '@Z2K@/[^ ]*' "$OUT/z2k/blobs" | sed 's|@Z2K@/||'); do
mkdir -p "$OUT/z2k/$(dirname "$b")" && cp "$Z/$b" "$OUT/z2k/$b"
done
cp -rL "$root" "$OUT/z2k/root"
rm -rf "$OUT/z2k/root/lua"
# Its ports, from its generator's configuration.
gen=$(cat "$Z/lib/config_official.sh")
for name in NFQWS2_PORTS_TCP NFQWS2_PORTS_UDP; do
printf '%s=%s\n' "$name" "$(sed -n "s/^$name=\"\\(.*\\)\"/\\1/p" "$Z/lib/config_official.sh" | head -1)"
done >"$OUT/z2k/ports"
grep -q '^NFQWS2_PORTS_TCP=.\+' "$OUT/z2k/ports" || { echo "z2k's ports not found"; exit 1; }
echo "$Z2K_COMMIT" >"$OUT/z2k/.commit"
echo "2026.10.27+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
echo "zapret2-extras $(cat "$OUT/.version") in $OUT"
+2 -1
View File
@@ -6,7 +6,7 @@
# #
# Before the shot, SHOT_STEPS does what it lists, in order, each followed by a moment for the # Before the shot, SHOT_STEPS does what it lists, in order, each followed by a moment for the
# app to answer: "click:X,Y" (screen points), "type:TEXT" (no spaces), "key:NAME" (xdotool's # app to answer: "click:X,Y" (screen points), "type:TEXT" (no spaces), "key:NAME" (xdotool's
# names, e.g. ctrl+a), "wait:SECONDS". # names, e.g. ctrl+a), "scroll:X,Y" (ten steps down, there), "wait:SECONDS".
set -euo pipefail set -euo pipefail
OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift
WAIT=6 WAIT=6
@@ -36,6 +36,7 @@ x() { DISPLAY=":$n" "$XDOTOOL/bin/xdotool" "$@"; }
for step in ${SHOT_STEPS:-}; do for step in ${SHOT_STEPS:-}; do
case $step in case $step in
click:*) p=${step#click:}; x mousemove "${p%,*}" "${p#*,}" click 1 ;; click:*) p=${step#click:}; x mousemove "${p%,*}" "${p#*,}" click 1 ;;
scroll:*) p=${step#scroll:}; x mousemove "${p%,*}" "${p#*,}" click --repeat 10 5 ;;
type:*) x type --delay 40 "${step#type:}" ;; type:*) x type --delay 40 "${step#type:}" ;;
key:*) x key "${step#key:}" ;; key:*) x key "${step#key:}" ;;
wait:*) sleep "${step#wait:}" ;; wait:*) sleep "${step#wait:}" ;;
+126
View File
@@ -0,0 +1,126 @@
; Proxy Suite's setup program. It unpacks the release into its temporary folder and runs the
; release's own `proxy-suite-service.exe install` from there, as install.cmd does from the zip:
; that stops what runs, copies the release into Program Files, registers the service, PATH, the
; Start Menu entry, the app at sign-in and the entry in Settings > Apps, and starts it all.
; Unpacked straight into Program Files instead, an upgrade would find its files in use.
; The uninstaller is that entry's: uninstall.cmd, which the release carries.
;
; makensis -INPUTCHARSET UTF8 -DVERSION=0.2.0-pre.1 -DVERSION4=0.2.0.0 -DRELEASE=<release dir>
; -DICON=crates/ps-gui/assets/proxy-suite.ico -DOUT=<setup.exe> tools/installer.nsi
;
; Everything the programs need is in the release: the C runtime is linked in, WinDivert, wintun,
; Python and the rest are components. Windows' OpenSSH Client (the SSH tunnel) is Windows' own:
; offered, unchecked, for a Windows that had it removed.
Unicode true
ManifestDPIAware true
RequestExecutionLevel admin
; Solid, with a dictionary that keeps the build's memory modest: the release is ~600 MB of
; programs, many alike (whitelist-bypass's nine).
SetCompressor /SOLID /FINAL lzma
SetCompressorDictSize 32
!include MUI2.nsh
!include LogicLib.nsh
!include x64.nsh
!include WinVer.nsh
Name "Proxy Suite"
OutFile "${OUT}"
InstallDir "$PROGRAMFILES64\ProxySuite"
BrandingText "Proxy Suite ${VERSION}"
ShowInstDetails show
VIProductVersion "${VERSION4}"
VIAddVersionKey /LANG=0 "ProductName" "Proxy Suite"
VIAddVersionKey /LANG=0 "ProductVersion" "${VERSION}"
VIAddVersionKey /LANG=0 "FileVersion" "${VERSION}"
VIAddVersionKey /LANG=0 "FileDescription" "Proxy Suite setup"
VIAddVersionKey /LANG=0 "LegalCopyright" "MIT License"
!define MUI_ICON "${ICON}"
!define MUI_ABORTWARNING
!define MUI_FINISHPAGE_TITLE "$(FinishTitle)"
!define MUI_FINISHPAGE_TEXT "$(FinishText)"
!define MUI_FINISHPAGE_NOAUTOCLOSE
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE "${RELEASE}/LICENSE"
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
; The first is the default; Windows' own language picks among them.
!insertmacro MUI_LANGUAGE "English"
!insertmacro MUI_LANGUAGE "Russian"
LangString NeedX64 ${LANG_ENGLISH} "Proxy Suite needs 64-bit Windows."
LangString NeedX64 ${LANG_RUSSIAN} "Для Proxy Suite нужна 64-битная Windows."
LangString NeedBuild ${LANG_ENGLISH} "Proxy Suite needs Windows 10 version 1903 or later, or Windows 11."
LangString NeedBuild ${LANG_RUSSIAN} "Для Proxy Suite нужна Windows 10 версии 1903 или новее либо Windows 11."
LangString Failed ${LANG_ENGLISH} "Setup did not finish: the details are in the list above. Nothing that was installed before is lost."
LangString Failed ${LANG_RUSSIAN} "Установка не завершена: подробности в списке выше. Установленное ранее не потеряно."
LangString MainName ${LANG_ENGLISH} "Proxy Suite"
LangString MainName ${LANG_RUSSIAN} "Proxy Suite"
LangString MainDesc ${LANG_ENGLISH} "The service, the app, proxy-ctl and every component (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass), into Program Files. Settings already made are kept."
LangString MainDesc ${LANG_RUSSIAN} "Служба, приложение, proxy-ctl и все компоненты (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass) в Program Files. Сделанные ранее настройки сохраняются."
LangString SshName ${LANG_ENGLISH} "Windows OpenSSH Client"
LangString SshName ${LANG_RUSSIAN} "Клиент OpenSSH Windows"
LangString SshDesc ${LANG_ENGLISH} "For the SSH tunnel only. Windows 10 1809 and later have it already; this adds it from Windows Update where it was removed."
LangString SshDesc ${LANG_RUSSIAN} "Нужен только для SSH-туннеля. В Windows 10 1809 и новее он уже есть; здесь он добавляется из Центра обновления, если его удалили."
LangString SshThere ${LANG_ENGLISH} "The OpenSSH Client is there already."
LangString SshThere ${LANG_RUSSIAN} "Клиент OpenSSH уже установлен."
LangString SshFailed ${LANG_ENGLISH} "The OpenSSH Client could not be added (is Windows Update reachable?). Everything else works without it; add it later in Settings > System > Optional features."
LangString SshFailed ${LANG_RUSSIAN} "Не удалось добавить клиент OpenSSH (доступен ли Центр обновления?). Всё остальное работает без него; его можно добавить позже: Параметры > Система > Дополнительные компоненты."
LangString FinishTitle ${LANG_ENGLISH} "Proxy Suite is installed"
LangString FinishTitle ${LANG_RUSSIAN} "Proxy Suite установлен"
LangString FinishText ${LANG_ENGLISH} "Its service runs, and the app is in the tray (the shield) and the Start Menu; it starts at every sign-in.$\r$\n$\r$\nIn a new terminal: proxy-ctl status.$\r$\n$\r$\nTo remove it: Settings > Apps > Proxy Suite."
LangString FinishText ${LANG_RUSSIAN} "Служба запущена, приложение в трее (щит) и в меню «Пуск»; оно запускается при каждом входе в систему.$\r$\n$\r$\nВ новом терминале: proxy-ctl status.$\r$\n$\r$\nУдаление: Параметры > Приложения > Proxy Suite."
Function .onInit
${IfNot} ${RunningX64}
MessageBox MB_ICONSTOP "$(NeedX64)" /SD IDOK
Abort
${EndIf}
${IfNot} ${AtLeastBuild} 18362
MessageBox MB_ICONSTOP "$(NeedBuild)" /SD IDOK
Abort
${EndIf}
InitPluginsDir
FunctionEnd
Section "$(MainName)" SecMain
SectionIn RO
SetOutPath "$PLUGINSDIR\release"
File /r "${RELEASE}/*"
DetailPrint "proxy-suite-service install"
nsExec::ExecToLog '"$PLUGINSDIR\release\proxy-suite-service.exe" install'
Pop $0
; Out of the folder, so that it goes with $PLUGINSDIR when setup ends.
SetOutPath "$TEMP"
${If} $0 != 0
DetailPrint "$(Failed)"
MessageBox MB_ICONSTOP "$(Failed)" /SD IDOK
SetErrorLevel 2
Abort
${EndIf}
SectionEnd
Section /o "$(SshName)" SecSsh
; This setup runs as a 32-bit program: Sysnative is the real System32.
${If} ${FileExists} "$WINDIR\Sysnative\OpenSSH\ssh.exe"
DetailPrint "$(SshThere)"
${Else}
nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -Command "Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 | Out-Null; if (-not (Test-Path $$env:SystemRoot\System32\OpenSSH\ssh.exe)) { exit 1 }"'
Pop $0
${If} $0 != 0
DetailPrint "$(SshFailed)"
MessageBox MB_ICONEXCLAMATION "$(SshFailed)" /SD IDOK
${EndIf}
${EndIf}
SectionEnd
!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
!insertmacro MUI_DESCRIPTION_TEXT ${SecMain} "$(MainDesc)"
!insertmacro MUI_DESCRIPTION_TEXT ${SecSsh} "$(SshDesc)"
!insertmacro MUI_FUNCTION_DESCRIPTION_END
+90
View File
@@ -0,0 +1,90 @@
# Shared by tools/build-*.sh (sourced).
# clone_tag URL TAG DIR: a shallow clone of TAG into DIR, tried three times: a transfer that
# stalls (GitHub's sometimes do) is given up after a minute, a connection that hangs by curl's
# own timeout; a slow one is waited for. With SRC_CACHE set, a clone made is kept there and
# the next build copies it rather than fetching it again (the scripts check its commit either
# way).
clone_tag() {
local url=$1 tag=$2 dir=$3 try cached=""
if [ -n "${SRC_CACHE:-}" ]; then
cached="$SRC_CACHE/$(basename "$url")@$tag"
if [ -d "$cached/.git" ]; then
# Its files as its commit has them, whatever happened to the copy since.
rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0
fi
fi
for try in 1 2 3; do
rm -rf "$dir"
if git -c advice.detachedHead=false -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 \
clone -q --depth 1 --branch "$tag" "$url" "$dir"; then
if [ -n "$cached" ]; then
mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached"
fi
return 0
fi
echo "cloning $url ($tag) failed, try $try of 3" >&2
sleep 5
done
return 1
}
# clone_commit URL COMMIT DIR: COMMIT alone, for a project without release tags; cached and
# tried again as clone_tag is.
clone_commit() {
local url=$1 commit=$2 dir=$3 try cached=""
if [ -n "${SRC_CACHE:-}" ]; then
cached="$SRC_CACHE/$(basename "$url")@$commit"
if [ -d "$cached/.git" ]; then
rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0
fi
fi
for try in 1 2 3; do
rm -rf "$dir" && mkdir -p "$dir"
if git -C "$dir" init -q && git -C "$dir" remote add origin "$url" &&
git -C "$dir" -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 fetch -q --depth 1 origin "$commit" &&
git -C "$dir" -c advice.detachedHead=false checkout -q FETCH_HEAD; then
if [ -n "$cached" ]; then
mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached"
fi
return 0
fi
echo "fetching $url ($commit) failed, try $try of 3" >&2
sleep 5
done
return 1
}
# fetch_pinned URL SHA256 FILE: a download, checked by its hash; kept in SRC_CACHE.
fetch_pinned() {
local url=$1 sha=$2 out=$3 cached=""
if [ -n "${SRC_CACHE:-}" ]; then
cached="$SRC_CACHE/$sha"
if [ -f "$cached" ] && echo "$sha $cached" | sha256sum -c --quiet 2>/dev/null; then
cp "$cached" "$out" && return 0
fi
fi
# Whole, unless it stalls: some networks cut TLS to some hosts after about 16 KB (as
# zapret2's cutoff option knows). Then in ranges below that, each on a connection of its own.
if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 15 --max-time 900 --retry 2 -o "$out" "$url"; then
echo "$url stalled; fetching it in pieces" >&2
local size from=0 step=12000 tries=0
size=$(curl -fsSIL --connect-timeout 30 --max-time 60 "$url" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }')
[[ "$size" =~ ^[0-9]+$ ]] && [ "$size" -gt 0 ] || { echo "$url: no size to fetch it in pieces by" >&2; return 1; }
: >"$out"
while [ "$from" -lt "$size" ]; do
if curl -fsSL --connect-timeout 30 --max-time 60 -r "$from-$((from + step - 1))" "$url" >>"$out.piece" 2>/dev/null &&
[ "$(stat -c %s "$out.piece")" -gt 0 ]; then
cat "$out.piece" >>"$out"
from=$(stat -c %s "$out")
tries=0
else
tries=$((tries + 1))
[ "$tries" -lt 5 ] || { rm -f "$out.piece"; echo "$url: a piece failed five times" >&2; return 1; }
fi
rm -f "$out.piece"
done
fi
echo "$sha $out" | sha256sum -c --quiet || { echo "$url: not the pinned file" >&2; return 1; }
if [ -n "$cached" ]; then mkdir -p "$SRC_CACHE" && cp "$out" "$cached"; fi
}
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""The app's icon, crates/ps-gui/assets/proxy-suite.ico: a shield with a check mark (the tray's
shield, in the app's blue), drawn here at every size Windows asks for, antialiased, with no
image library. The .ico it writes is committed; run this again only to change it.
python3 -I tools/make-icon.py
"""
import math
import pathlib
import struct
import zlib
BLUE = (37, 99, 235)
WHITE = (255, 255, 255)
SIZES = [16, 20, 24, 32, 40, 48, 64, 256]
SAMPLES = 4 # per axis, per pixel
def cubic(p0, p1, p2, p3, steps=24):
out = []
for i in range(1, steps + 1):
t = i / steps
u = 1 - t
out.append(tuple(u**3 * a + 3 * u * u * t * b + 3 * u * t * t * c + t**3 * d for a, b, c, d in zip(p0, p1, p2, p3)))
return out
# Lucide's shield, on its 24-unit grid, as a polygon.
SHIELD = [(12.0, 2.2)]
SHIELD += cubic((12.0, 2.2), (14.6, 4.4), (17.2, 5.1), (19.8, 5.1))
SHIELD += [(19.8, 13.0)]
SHIELD += cubic((19.8, 13.0), (19.8, 18.2), (16.4, 20.6), (12.0, 22.0))
SHIELD += cubic((12.0, 22.0), (7.6, 20.6), (4.2, 18.2), (4.2, 13.0))
SHIELD += [(4.2, 5.1)]
SHIELD += cubic((4.2, 5.1), (6.8, 5.1), (9.4, 4.4), (12.0, 2.2))
CHECK = [(8.3, 12.3), (11.0, 15.0), (15.9, 9.6)]
CHECK_HALF_WIDTH = 1.15
def inside(poly, x, y):
hit = False
for (x1, y1), (x2, y2) in zip(poly, poly[1:] + poly[:1]):
if (y1 > y) != (y2 > y) and x < x1 + (y - y1) * (x2 - x1) / (y2 - y1):
hit = not hit
return hit
def near_check(x, y):
for (x1, y1), (x2, y2) in zip(CHECK, CHECK[1:]):
dx, dy = x2 - x1, y2 - y1
t = max(0.0, min(1.0, ((x - x1) * dx + (y - y1) * dy) / (dx * dx + dy * dy)))
if math.hypot(x - (x1 + t * dx), y - (y1 + t * dy)) <= CHECK_HALF_WIDTH:
return True
return False
def render(size):
"""RGBA rows, top first."""
rows = []
scale = 24 / size
for py in range(size):
row = bytearray()
for px in range(size):
shield = check = 0
for sy in range(SAMPLES):
for sx in range(SAMPLES):
x = (px + (sx + 0.5) / SAMPLES) * scale
y = (py + (sy + 0.5) / SAMPLES) * scale
if inside(SHIELD, x, y):
shield += 1
check += near_check(x, y)
n = SAMPLES * SAMPLES
alpha = shield / n
if shield:
w = check / shield
colour = [round(b * (1 - w) + f * w) for b, f in zip(BLUE, WHITE)]
else:
colour = [0, 0, 0]
row += bytes(colour + [round(alpha * 255)])
rows.append(bytes(row))
return rows
def png(size, rows):
def chunk(kind, data):
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
raw = b"".join(b"\x00" + r for r in rows)
ihdr = struct.pack(">IIBBBBB", size, size, 8, 6, 0, 0, 0)
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(raw, 9)) + chunk(b"IEND", b"")
def main():
images = [png(s, render(s)) for s in SIZES]
header = struct.pack("<HHH", 0, 1, len(images))
offset = 6 + 16 * len(images)
entries = b""
for s, data in zip(SIZES, images):
entries += struct.pack("<BBBBHHII", s % 256, s % 256, 0, 0, 1, 32, len(data), offset)
offset += len(data)
out = pathlib.Path(__file__).resolve().parent.parent / "crates/ps-gui/assets/proxy-suite.ico"
out.parent.mkdir(exist_ok=True)
out.write_bytes(header + entries + b"".join(images))
print(f"{out}: {out.stat().st_size} bytes, sizes {SIZES}")
if __name__ == "__main__":
main()
+27 -7
View File
@@ -1,22 +1,28 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# The release: ProxySuite-<version>-windows-x64.zip in dist/, with the programs (the service, # The release, in dist/: ProxySuite-<version>-windows-x64-setup.exe, the setup program, and
# proxy-ctl, the app), every component (fetched and verified), the install scripts, the README # ProxySuite-<version>-windows-x64.zip, the same unpacked with install.cmd. Both hold the
# and the licenses. # programs (the service, proxy-ctl, the app), every component (fetched and verified), the
# install scripts, the README and the licenses.
# #
# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go; nix # nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go, makensis;
# for the app's shader compiler, tools/fxc-wine.sh) # nix for the app's shader compiler, tools/fxc-wine.sh)
set -euo pipefail set -euo pipefail
cd "$(dirname "$0")/.." cd "$(dirname "$0")/.."
VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
NAME=ProxySuite-$VERSION-windows-x64 NAME=ProxySuite-$VERSION-windows-x64
DIST=dist/$NAME DIST=dist/$NAME
CACHE=${CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/proxy-suite-windows} CACHE=${CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/proxy-suite-windows}
# The sources tools/build-*.sh clone, kept for the next build.
export SRC_CACHE=$CACHE/src
rm -rf "$DIST" "dist/$NAME.zip" rm -rf "$DIST" "dist/$NAME.zip"
mkdir -p "$DIST/components" mkdir -p "$DIST/components"
echo "== components" echo "== components"
tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy" tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy"
tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows
tools/build-whitelist-bypass.sh "$DIST/components/whitelist-bypass" windows
tools/build-amneziawg.sh "$DIST/components/amneziawg"
tools/build-zapret2-extras.sh "$DIST/components/zapret2-extras"
cargo build -q --release -p ps-service cargo build -q --release -p ps-service
target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE" target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE"
rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging
@@ -29,6 +35,8 @@ GPUI_FXC_PATH="$PWD/tools/fxc-wine.sh" cargo xwin build -q --release -p ps-gui -
for exe in proxy-suite-service proxy-ctl proxy-suite; do for exe in proxy-suite-service proxy-ctl proxy-suite; do
cp "target/x86_64-pc-windows-msvc/release/$exe.exe" "$DIST/" cp "target/x86_64-pc-windows-msvc/release/$exe.exe" "$DIST/"
done done
# Its build only warns without its icon (cargo -q shows no warning): the release has it.
llvm-readobj --coff-resources "$DIST/proxy-suite.exe" | grep 'Type: ICON' >/dev/null || { echo "proxy-suite.exe has no icon"; exit 1; }
cp ../LICENSE README.md "$DIST/" cp ../LICENSE README.md "$DIST/"
cp tools/install.cmd tools/uninstall.cmd "$DIST/" cp tools/install.cmd tools/uninstall.cmd "$DIST/"
@@ -51,7 +59,12 @@ echo "== THIRD-PARTY.md"
echo "- **cygwin1.dll** (zapret, zapret2): LGPL-3.0, https://cygwin.com" echo "- **cygwin1.dll** (zapret, zapret2): LGPL-3.0, https://cygwin.com"
echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic" echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic"
echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net" echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net"
echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch): MIT, https://github.com/amnezia-vpn/amneziawg-go" echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch, and inside amneziawg's awg-tunnel.exe): MIT, https://github.com/amnezia-vpn/amneziawg-go"
echo "- **z2k** (zapret2-extras: its strategies, made by its own generator, its Lua and lists): MIT, https://github.com/necronicle/z2k"
echo "- **The public suffix list** (zapret2-extras' public_suffixes.txt, derived): MPL-2.0, https://publicsuffix.org"
echo "- **proxy-suite's zapret2 Lua** (zapret2-extras' lua/: the extended detector and the layers around z2k's state): MIT, this repository's modules/proxy-suite/zapret2"
echo "- **Wintun** (amneziawg's wintun.dll, as WireGuard LLC builds and signs it): its prebuilt-binaries license, components/amneziawg/wintun-LICENSE.txt"
echo "- **Go modules** (inside wireproxy-awg and whitelist-bypass, e.g. Pion's WebRTC): as each project's go.mod pins them, under their own licenses (MIT, BSD-3-Clause, Apache-2.0)"
echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs" echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs"
echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org" echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org"
echo "- **The programs themselves** (proxy-suite-service, proxy-ctl, proxy-suite) are built from" echo "- **The programs themselves** (proxy-suite-service, proxy-ctl, proxy-suite) are built from"
@@ -71,4 +84,11 @@ echo "== THIRD-PARTY.md"
echo "== zip" echo "== zip"
(cd dist && zip -qr "$NAME.zip" "$NAME") (cd dist && zip -qr "$NAME.zip" "$NAME")
(cd dist && sha256sum "$NAME.zip" | tee "$NAME.zip.sha256") (cd dist && sha256sum "$NAME.zip" | tee "$NAME.zip.sha256")
du -h "dist/$NAME.zip"
echo "== setup"
# Windows' file version takes four numbers: 0.2.0-pre.1 is 0.2.0.0.
VERSION4=$(sed 's/-.*//' <<<"$VERSION").0
rm -f "dist/$NAME-setup.exe"
makensis -V2 -INPUTCHARSET UTF8 -DVERSION="$VERSION" -DVERSION4="$VERSION4" -DRELEASE="$PWD/$DIST" -DICON="$PWD/crates/ps-gui/assets/proxy-suite.ico" -DOUT="$PWD/dist/$NAME-setup.exe" tools/installer.nsi
(cd dist && sha256sum "$NAME-setup.exe" | tee "$NAME-setup.exe.sha256")
du -h "dist/$NAME.zip" "dist/$NAME-setup.exe"
+77
View File
@@ -0,0 +1,77 @@
#!/usr/bin/env bash
# Screenshots of every page of the app, for the README: the service on Linux with a demo
# configuration (a local Shadowsocks exit, zapret's presets from a built release, autoProxy,
# whitelist-bypass, the Telegram proxy), the app on a virtual display (tools/gui-shot.sh).
# In the dev shell, after tools/package.sh:
#
# tools/screenshots.sh [OUT_DIR] (OUT_DIR: docs/screenshots)
set -euo pipefail
cd "$(dirname "$0")/.."
OUT=$(realpath -m "${1:-docs/screenshots}")
mkdir -p "$OUT"
WORK=$(mktemp -d)
STATE=$WORK/state
SOCK=${XDG_RUNTIME_DIR:-/tmp}/proxy-suite-shots.sock
rm -f "$SOCK"
mkdir -p "$STATE/bin"
port() { python3 -c 'import socket;s=socket.socket();s.bind(("127.0.0.1",0));print(s.getsockname()[1])'; }
SS=$(port) PROXY=$(port) CLASH=$(port) TEST=$(port)
KEY=a2tra2tra2tra2tra2traw==
cat >"$WORK/server.json" <<JSON
{ "log": { "level": "warn" },
"inbounds": [{ "type": "shadowsocks", "listen": "127.0.0.1", "listen_port": $SS, "method": "2022-blake3-aes-128-gcm", "password": "$KEY" }],
"dns": { "servers": [{ "type": "https", "tag": "local", "server": "1.1.1.1" }] },
"outbounds": [{ "type": "direct" }], "route": { "default_domain_resolver": "local" } }
JSON
sing-box run -c "$WORK/server.json" >/dev/null 2>&1 &
SERVER=$!
SS_URL="ss://2022-blake3-aes-128-gcm:${KEY//=/%3D}@127.0.0.1:$SS"
cat >"$STATE/config.json" <<JSON
{ "proxy": { "enable": true, "listener": { "port": $PROXY },
"singBox": { "clashApiPort": $CLASH, "testPort": $TEST },
"selection": "urltest",
"routing": { "directRu": false,
"rules": [{ "name": "streaming", "outbound": "Netherlands", "domains": ["youtube.com", "googlevideo.com"] }] },
"autoProxy": { "enable": true, "slowBelowKiBps": 0 },
"outbounds": [{ "tag": "Netherlands", "url": "$SS_URL#Netherlands" },
{ "tag": "Germany", "url": "$SS_URL#Germany" },
{ "tag": "Finland", "url": "$SS_URL#Finland" }] },
"zapret": { "enable": true, "engine": "zapret2",
"zapret2": { "strategySource": "z2k", "strategyLog": true, "cutoff": { "enable": false } },
"zapret-discord-youtube": { "configName": "general (ALT9)", "gameFilter": "all" } },
"tgWsProxy": { "enable": false },
"amneziaWg": { "enable": true, "profiles": {
"home": { "autostart": true, "config": "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 40\nJmax = 70\nS1 = 12\nS2 = 34\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n" },
"office": { "asOutbound": "userspace", "config": "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 40\nJmax = 70\nS1 = 12\nS2 = 34\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n" } } },
"whitelistBypass": { "enable": true,
"joiners": { "wl": { "platform": "wbstream" } },
"creators": { "office": { "platform": "bitrix" } } } }
JSON
release=$(ls -d dist/ProxySuite-*-windows-x64/components 2>/dev/null | tail -1 || true)
[ -n "$release" ] && cp -r "$release/zapret" "$STATE/bin/" 2>/dev/null || true
cargo build -q -p ps-service -p ps-gui
target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" >"$WORK/service.log" 2>&1 &
SERVICE=$!
trap 'kill $SERVICE $SERVER 2>/dev/null || true; rm -rf "$WORK"' EXIT
for _ in $(seq 60); do target/debug/proxy-ctl --socket "$SOCK" status 2>/dev/null | grep -q 'proxy: active' && break; sleep 0.5; done
# Something for the Logs and Outbounds pages to show: delays, a few lines.
target/debug/proxy-ctl --socket "$SOCK" proxy outbounds test >/dev/null 2>&1 || true
# Sidebar entries, top to bottom (points on a 1280x820 screen).
shot() {
local name=$1 y=$2 extra=${3:-}
SHOT_STEPS="click:197,$y wait:2 $extra" tools/gui-shot.sh "$OUT/$name.png" 8 -- --socket "$SOCK" >/dev/null
# gui-shot keeps the app's log beside the shot: not for the README.
rm -f "$OUT/$name.log"
echo "$OUT/$name.png"
}
shot overview 162
shot dpi-bypass 198
shot telegram 234
shot whitelist-bypass 270
shot outbounds 306
shot autoproxy 342
shot amneziawg 378
shot logs 414
shot settings 450
shot components 486
+3 -2
View File
@@ -5,5 +5,6 @@ net session >nul 2>&1 || (
powershell -NoProfile -Command "Start-Process -Verb RunAs -FilePath '%~f0'" powershell -NoProfile -Command "Start-Process -Verb RunAs -FilePath '%~f0'"
exit /b exit /b
) )
:: One line: cmd reads a batch file line by line, and this one is deleted meanwhile. :: One line: cmd reads a batch file line by line, and this one is deleted meanwhile. Out of
"%~dp0proxy-suite-service.exe" uninstall & pause & exit /b :: the folder first: opened from Explorer, this window would hold it (and keep it there).
cd /d "%SystemRoot%" & "%~dp0proxy-suite-service.exe" uninstall & pause & exit /b
+105
View File
@@ -0,0 +1,105 @@
#!/usr/bin/env bash
# The setup program under Wine: a silent install into Program Files (every file, the
# components' manifests among them), the entry in Settings > Apps, the service registered and
# answering over its pipe; the same setup again over the running install (an upgrade); then the
# entry's quiet uninstall, after which the service, the files and the entry are gone.
#
# nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-<version>-windows-x64-setup.exe [RELEASE_DIR]
#
# RELEASE_DIR (the unpacked release the setup was made of): its files are compared with the
# installed ones.
set -euo pipefail
SETUP=$(realpath "${1:?the setup program}")
REL=${2:+$(realpath "$2")}
WORK=$(mktemp -d)
export WINEPREFIX=${WINEPREFIX:-$WORK/prefix} WINEDEBUG=-all
trap 'wineserver -k 2>/dev/null || true; rm -rf "$WORK"' EXIT
wineboot -i >/dev/null 2>&1 || true
for key in Tcpip Tcpip6; do
wine reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\$key\\Parameters\\Interfaces" /f >/dev/null 2>&1
done
PF="$WINEPREFIX/drive_c/Program Files/ProxySuite"
KEY='HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite'
fail() { echo "FAIL: $*"; exit 1; }
state() { local st; st=$(wine sc query ProxySuite 2>/dev/null || true); st=${st//$'\r'/}; grep STATE <<<"$st" | grep -o '[A-Z_]*$' || echo NONE; }
# Wine's manager often fails the first start right after a create (wine-install-test.sh says
# more); a second start works.
running() {
local s last=""
for _ in $(seq 60); do
s=$(state)
[ "$s" = "$last" ] || echo " $s"
last=$s
[ "$s" = RUNNING ] && return 0
[ "$s" = STOPPED ] && { wine sc start ProxySuite >/dev/null 2>&1 || true; }
sleep 3
done
return 1
}
echo "== setup /S"
wine "$SETUP" /S && rc=0 || rc=$?
echo " exit code $rc"
[ "$rc" = 0 ] || fail "setup exited with $rc"
[ -f "$PF/proxy-suite-service.exe" ] || fail "nothing in Program Files"
ls "$PF" | sed 's/^/ /'
if [ -n "$REL" ]; then
# Every file of the release, dotfiles too (the components' .files.json and .version).
missing=$(cd "$REL" && find . -type f | while read -r f; do [ -f "$PF/$f" ] || echo "$f"; done)
[ -z "$missing" ] || fail "not installed: $missing"
echo " every file of the release is there ($(cd "$REL" && find . -type f | wc -l))"
fi
ls "$PF"/components/*/.files.json >/dev/null || fail "no component manifests"
echo "== Settings > Apps"
entry=$(wine reg query "$KEY" 2>/dev/null | tr -d '\r') || fail "no uninstall entry"
sed 's/^/ /' <<<"$entry"
for v in DisplayName DisplayVersion UninstallString QuietUninstallString InstallLocation EstimatedSize; do
grep -q "$v" <<<"$entry" || fail "the entry has no $v"
done
echo "== the service"
running || fail "the service is $(state)"
for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done
wine "$PF/proxy-ctl.exe" components | tr -d '\r' | sed 's/^/ /' || fail "no answer over the pipe"
echo "== an AmneziaWG system-wide profile: its tunnel service registered, then removed"
CONF='[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 10.8.0.2/32\nDNS = 1.1.1.1\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.7:51820\n'
printf '{ "amneziaWg": { "enable": true, "profiles": { "home": { "config": "%s" } } } }' "$CONF" >"$WORK/awg.json"
wine "$PF/proxy-ctl.exe" config set "Z:$WORK/awg.json" | tr -d '\r' | sed 's/^/ /'
sleep 3
# Wine's sc has no qc: the service's registry key says the same.
qc=$(wine reg query 'HKLM\System\CurrentControlSet\Services\AmneziaWGTunnel$home' 2>/dev/null | tr -d '\r' || true)
grep -q 'awg-tunnel.exe' <<<"$qc" || fail "no tunnel service registered: $(wine "$PF/proxy-ctl.exe" logs proxy-suite-awg-vpn -n 20 | tr -d '\r')"
grep -iE 'ImagePath|ServiceSidType|DependOnService' <<<"$qc" | sed 's/^ */ /'
wine "$PF/proxy-ctl.exe" awg | tr -d '\r' | sed 's/^/ /'
# Wine has no Wintun driver: the tunnel itself cannot come up here, only be asked to.
wine "$PF/proxy-ctl.exe" awg on home 2>&1 | tr -d '\r' | sed 's/^/ on: /' || true
sleep 3
wine "$PF/proxy-ctl.exe" awg log home -n 5 2>&1 | tr -d '\r' | sed 's/^/ log: /' || true
printf '{}' >"$WORK/none.json"
wine "$PF/proxy-ctl.exe" config set "Z:$WORK/none.json" >/dev/null
sleep 3
wine reg query 'HKLM\System\CurrentControlSet\Services\AmneziaWGTunnel$home' >/dev/null 2>&1 && fail "the tunnel service outlived its profile"
echo " registered, and removed with its profile"
echo "== setup /S again, over the running install"
wine "$SETUP" /S && rc=0 || rc=$?
[ "$rc" = 0 ] || fail "the upgrade exited with $rc"
running || fail "after the upgrade the service is $(state)"
for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done
wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 || fail "no answer after the upgrade"
echo " upgraded, running, answering"
echo "== the entry's quiet uninstall"
quiet=$(wine reg query "$KEY" /v QuietUninstallString | tr -d '\r' | sed -n 's/.*REG_SZ *//p')
echo " $quiet"
# Its command line, as Windows would run it: the quoted program, then its argument.
prog=${quiet#\"}; prog=${prog%%\"*}
wine "$prog" uninstall
sleep 6
[ "$(state)" = NONE ] || fail "the service is still there: $(state)"
wine reg query "$KEY" >/dev/null 2>&1 && fail "the entry is still there"
[ ! -e "$PF" ] || fail "Program Files\\ProxySuite is still there: $(ls "$PF")"
echo "OK: installed, upgraded and removed by the setup program and its entry"
+23
View File
@@ -59,4 +59,27 @@ if out=$(cd "$Z2" && wine ./winws2.exe --dry-run "${args[@]}" 2>&1) && grep -q "
else else
fail=$((fail + 1)); echo "FAIL: zapret2"; grep -v -i cygwin <<<"$out" | tail -4 fail=$((fail + 1)); echo "FAIL: zapret2"; grep -v -i cygwin <<<"$out" | tail -4
fi fi
# With the zapret2-extras component: upstream's Lua layers loaded and the extended detector
# learning, for nfqws2-keenetic's strategies and for z2k's, with the environment the service
# gives winws2.
X="$STAGE/zapret2-extras"
if [ -d "$X" ]; then
cyg() { echo "/cygdrive/z$(realpath "$1")"; }
mkdir -p "$WORK/z2/learned/circular" "$WORK/z2/learned/run"
for kind in keenetic z2k; do
# Through an options file (@file), as the service starts winws2: z2k's run past the
# 32767 characters of a Windows command line. One a line, quoted when it holds a space.
{ echo --dry-run; target/debug/examples/zapret2_args "$Z2" "$(win "$Z2")" "$(win "$WORK/z2")" "$X" "$(win "$X")" "$(cyg "$X")/" "$kind"; } |
python3 -I -c 'import sys
for a in sys.stdin.read().splitlines():
print(("\"" + a.replace("\\", "\\\\").replace("\"", "\\\"") + "\"") if (" " in a or "\"" in a) else a)' >"$WORK/winws2.conf"
if out=$(cd "$Z2" && Z2K_STATE_DIR_OVERRIDE="$(cyg "$WORK/z2/learned/circular")" Z2K_AUTOCIRCULAR_FALLBACK_OVERRIDE="$(cyg "$WORK/z2/learned/run")" \
PROXY_SUITE_ZAPRET2_VERDICTS="$(cyg "$WORK/z2/learned")/verdicts.tsv" PROXY_SUITE_PUBLIC_SUFFIXES="$(cyg "$X")/public_suffixes.txt" \
WINEDEBUG=-all wine ./winws2.exe "@$(win "$WORK")winws2.conf" 2>&1) && grep -q "parameters verified" <<<"$out"; then
echo "zapret2 ($kind, extended detection, upstream's Lua layers): verified by winws2.exe, $(grep -c -- '--lua-init' "$WORK/winws2.conf") Lua files, $(wc -l <"$WORK/winws2.conf") options"
else
fail=$((fail + 1)); echo "FAIL: zapret2 ($kind with the extras)"; grep -v -i cygwin <<<"$out" | tail -6
fi
done
fi
[ "$fail" = 0 ] [ "$fail" = 0 ]