Compare commits
No files matched your search
@@ -1,2 +1,4 @@
|
|||||||
target/
|
target/
|
||||||
dist/
|
dist/
|
||||||
|
# The app logs tools/gui-shot.sh writes beside each shot.
|
||||||
|
docs/screenshots/*.log
|
||||||
@@ -4974,7 +4974,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-client"
|
name = "ps-client"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"ps-core",
|
"ps-core",
|
||||||
@@ -4985,7 +4985,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-core"
|
name = "ps-core"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
"flate2",
|
"flate2",
|
||||||
@@ -5001,7 +5001,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-ctl"
|
name = "ps-ctl"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"clap",
|
"clap",
|
||||||
@@ -5015,7 +5015,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-gui"
|
name = "ps-gui"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"async-channel",
|
"async-channel",
|
||||||
@@ -5023,6 +5023,7 @@ dependencies = [
|
|||||||
"gpui-tray",
|
"gpui-tray",
|
||||||
"ps-client",
|
"ps-client",
|
||||||
"ps-ipc",
|
"ps-ipc",
|
||||||
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"tokio",
|
"tokio",
|
||||||
"windows-sys 0.61.2",
|
"windows-sys 0.61.2",
|
||||||
@@ -5030,7 +5031,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-ipc"
|
name = "ps-ipc"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
@@ -5041,7 +5042,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "ps-service"
|
name = "ps-service"
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anyhow",
|
"anyhow",
|
||||||
"base64 0.22.1",
|
"base64 0.22.1",
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-cl
|
|||||||
default-members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl"]
|
default-members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl"]
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.2.0-pre.1"
|
version = "0.3.0-pre.1"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
license = "MIT"
|
license = "MIT"
|
||||||
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
|
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
|
||||||
|
|||||||
@@ -6,9 +6,10 @@ by a Windows service instead of NixOS and systemd, controlled from its desktop a
|
|||||||
tray icon) or with `proxy-ctl`, as upstream's is.
|
tray icon) or with `proxy-ctl`, as upstream's is.
|
||||||
|
|
||||||
> [!WARNING]
|
> [!WARNING]
|
||||||
> **Pre-release.** Built and tested on Linux and under Wine, **never yet run on real Windows.**
|
> **Pre-release.** Built and tested on Linux and under Wine; on real Windows so far only the
|
||||||
> Read [what has been verified](#what-has-been-verified) before relying on it, and please
|
> setup program, zapret, zapret2 and tg-ws-proxy have been tried (they work). Read
|
||||||
> report what happens on yours.
|
> [what has been verified](#what-has-been-verified) before relying on it, and please report
|
||||||
|
> what happens on yours.
|
||||||
|
|
||||||
> [!IMPORTANT]
|
> [!IMPORTANT]
|
||||||
> For study and research only, as upstream: learning how proxies, tunnels and traffic
|
> For study and research only, as upstream: learning how proxies, tunnels and traffic
|
||||||
@@ -18,10 +19,10 @@ 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, or XRay alone: `proxy.backend = "xray"`, without the TUN, groups, rule sets, autoProxy, latency tests, per-app and program rules, which need sing-box) |
|
||||||
| 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`). The **16 KB cutoff probe** (`zapret2.cutoff`, on by default): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes; z2k's probe (`z2k-detect`, built from its source) finds them daily or when the line's network changes, and with z2k's strategies a name that gets through for each, which z2k puts into a fake hello; the networks no name fixes go through the proxy, by address. Its connections leave from ports winws2 is told to leave alone. `proxy-ctl zapret cutoff [probe]`, or the DPI bypass page |
|
||||||
| 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, 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 |
|
| 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 |
|
||||||
@@ -29,26 +30,46 @@ tray icon) or with `proxy-ctl`, as upstream's is.
|
|||||||
| 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 |
|
| 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 |
|
| 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`, alongside zapret too — **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; 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 |
|
| Kill switch | `killSwitch`: while the TUN or a system-wide AmneziaWG profile is on, what would leave past it is blocked (Windows Filtering Platform filters, in the service's session); LAN, DHCP, NTP and the tunnel's own programs stay open. `proxy-ctl killswitch [on\|off]`, or the Overview |
|
||||||
|
| 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; in English or Russian (as Windows is set, or chosen); a light and a dark theme (or as Windows is set); a newer release installed from its Overview |
|
||||||
|
|
||||||
Not in this release, still to come: Tor's onion service,
|
Not ported: server inbounds (this PC serving other devices) and Tor's onion service, which
|
||||||
the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and z2k
|
serves them. Their options are accepted (they are upstream's), but the
|
||||||
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.
|
||||||
|
|
||||||
|
| | |
|
||||||
|
|---|---|
|
||||||
|
|  |  |
|
||||||
|
|  |  |
|
||||||
|
|  |  |
|
||||||
|
|  |  |
|
||||||
|
|  |  |
|
||||||
|
|  |  |
|
||||||
|
|
||||||
## What has been verified
|
## What has been verified
|
||||||
|
|
||||||
| Part | How |
|
| Part | How |
|
||||||
|---|---|
|
|---|---|
|
||||||
|
| **On real Windows** (0.2.0-pre.1) | the setup program installs it; zapret, zapret2 and tg-ws-proxy work |
|
||||||
| Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results |
|
| Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results |
|
||||||
| sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` |
|
| sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` |
|
||||||
|
| The XRay-only backend | its config (listener login, DNS order and pinned server names, route modes, urltest balancer and pin, chains, helper hops, zapret's direct lists) accepted by `xray run -test` and asserted as upstream's filter vectors are; end to end on Linux: the service running xray with the release's own `geoip.dat`/`geosite.dat`, a page fetched through its listener and a Shadowsocks outbound (urltest, then pinned), a wrong password refused, the latency test refused as upstream refuses it |
|
||||||
|
| The kill switch | its plan (what stays open: local networks, the tunnels' addresses, their programs, NTP; when it holds and when it is lifted) by unit tests; the Windows Filtering Platform filters built and compiled for Windows. Not run: Wine has no Windows Filtering Platform, so whether the filters block and let through as meant needs real Windows |
|
||||||
|
| zapret beside the TUN | the filter part that leaves the TUN's packets out (IPv4 and IPv6), alone, with the cutoff probe's and around Flowseal's own filter as `--wf-raw` takes it, compiled by WinDivert's own `WinDivertHelperCompileFilter` (under Wine); zapret2's arguments with it checked by `winws2 --dry-run`. Traffic through both needs real Windows |
|
||||||
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
|
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
|
||||||
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
|
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
|
||||||
| zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) |
|
| zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) |
|
||||||
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine |
|
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine, the cutoff probe's filter part included |
|
||||||
|
| 16 KB cutoff probe | on this test machine's line, which does cut TLS at 16 KB to some networks: the service ran z2k-detect (its Linux build, the same patched source), which found 25 networks cut off and a name for each; its connections left from the probe's ports only; 157 distinct local ports of the probe's range were seen in use during its run; the maps, the line's network and the rule-set written, shown by `proxy-ctl zapret cutoff` and the app. The Windows build runs under Wine (it found the same networks, from the range's ports); winws2 leaving its connections alone needs real Windows (its filter, with the exclusion, saved by `winws2 --wf-save`) |
|
||||||
|
| Updates from the app | on Linux against a local stand-in for the releases API: a newer release found (and none for a pre-release's user beyond its channel, by unit tests), its setup program fetched and matched to its SHA-256, a wrong checksum refused, the app's states (found, fetching, installing) shown. Not verified: the setup run as SYSTEM by the service, and the app started again in the user's session afterwards, which need real Windows (the first chance is the update from 0.3.0-pre.1 to the release after it) |
|
||||||
| tg-ws-proxy | runs and listens under Wine |
|
| tg-ws-proxy | runs and listens under Wine |
|
||||||
| 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) |
|
||||||
@@ -62,11 +83,10 @@ Needs 64-bit Windows 10 (1903 or later) or 11.
|
|||||||
| 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 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 |
|
| 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 yet: the rest of what needs real Windows.** Traffic through sing-box on Windows
|
||||||
lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows
|
(Wine lacks an API it needs), the TUN adapter, AmneziaWG's system-wide tunnels, autoProxy,
|
||||||
service under the Service Control Manager, `install`/`uninstall`, the system PATH change, and
|
whitelist-bypass, the SSH tunnel, Tor and WARP there, uninstalling, and the app's pages beyond
|
||||||
**the app drawing on Windows** (Wine's DirectWrite cannot match fonts, so no text is drawn
|
what the zapret and Telegram ones need, its tray icon, the system proxy and the Start Menu entry.
|
||||||
there), its tray icon, the system proxy and the Start Menu entry.
|
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
@@ -85,7 +105,13 @@ Nothing has to be installed first: the C runtime is linked into the programs, an
|
|||||||
wintun, Python, Tor and the rest come with it, as components. For a silent install:
|
wintun, Python, Tor and the rest come with it, as components. For a silent install:
|
||||||
`ProxySuite-<version>-windows-x64-setup.exe /S`.
|
`ProxySuite-<version>-windows-x64-setup.exe /S`.
|
||||||
|
|
||||||
To upgrade, run the new setup: the settings stay. To remove: **Settings → Apps → Proxy Suite →
|
To upgrade, run the new setup, or install it from the app: its Overview says when a newer
|
||||||
|
release is out (it looks when it starts, and daily; Settings → This app turns that off), and
|
||||||
|
**Install** has the service fetch the setup program from this project's releases, check its
|
||||||
|
SHA-256 against the one published beside it, and run it silently: the service and the app close
|
||||||
|
for a moment and start again, new. `proxy-ctl update` and `proxy-ctl update install` do the
|
||||||
|
same. A pre-release is offered newer pre-releases and releases; a release only releases. The
|
||||||
|
settings stay either way. To remove: **Settings → Apps → Proxy Suite →
|
||||||
Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in
|
Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in
|
||||||
`%ProgramData%\ProxySuite` until you delete it.
|
`%ProgramData%\ProxySuite` until you delete it.
|
||||||
|
|
||||||
@@ -121,6 +147,7 @@ proxy-ctl zapret game-filter all
|
|||||||
# zapret2 instead:
|
# zapret2 instead:
|
||||||
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
|
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
|
||||||
proxy-ctl config set config.json
|
proxy-ctl config set config.json
|
||||||
|
proxy-ctl zapret cutoff # the networks this line cuts off after 16 KB (probe: now)
|
||||||
|
|
||||||
# Telegram's WebSocket proxy:
|
# Telegram's WebSocket proxy:
|
||||||
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
|
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
|
||||||
@@ -176,15 +203,16 @@ Whatever the scopes, these always need an administrator: anything that makes the
|
|||||||
a program, pass arguments to one, or read or write a file of the caller's choosing — every
|
a program, pass arguments to one, or read or write a file of the caller's choosing — every
|
||||||
`*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`,
|
`*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`,
|
||||||
`nfqwsArgs`, zapret2's `profiles` and `blobs`, `allowConfigHooks`, and `userControl` itself —
|
`nfqwsArgs`, zapret2's `profiles` and `blobs`, `allowConfigHooks`, and `userControl` itself —
|
||||||
and installing components. Secrets (links, passwords) are hidden from callers without the
|
and installing components. Installing an update takes the `services` scope only: it runs no
|
||||||
|
program but this project's own setup, from its own releases, checked, and only a newer one. Secrets (links, passwords) are hidden from callers without the
|
||||||
`secrets` scope, and survive a round trip through `config get`/`config set` unchanged.
|
`secrets` scope, and survive a round trip through `config get`/`config set` unchanged.
|
||||||
|
|
||||||
## Caveats
|
## Caveats
|
||||||
|
|
||||||
- **TUN and zapret together**: upstream keeps zapret's packets off the TUN interface, which
|
- **TUN and zapret together**: zapret (winws or winws2) leaves the TUN's own packets alone,
|
||||||
this release does not do yet. Use one or the other.
|
by its address in WinDivert's filter, and handles the connections sing-box makes on the way
|
||||||
- zapret2 learns with nfqws2's own detector, not upstream's extended one; z2k's strategies are
|
out of the real adapter, direct ones included. Checked by WinDivert's own filter compiler;
|
||||||
not there yet.
|
traffic through both needs real Windows.
|
||||||
- The global TUN restarts the local proxy when it is turned on or off (one sing-box does both).
|
- The global TUN restarts the local proxy when it is turned on or off (one sing-box does both).
|
||||||
- The system proxy is set by the app, for the user it runs as, while it runs: quitting the app
|
- The system proxy is set by the app, for the user it runs as, while it runs: quitting the app
|
||||||
puts the user's own setting back.
|
puts the user's own setting back.
|
||||||
|
|||||||
@@ -126,6 +126,13 @@
|
|||||||
"bundled": true,
|
"bundled": true,
|
||||||
"sources": []
|
"sources": []
|
||||||
},
|
},
|
||||||
|
"zapret2-extras": {
|
||||||
|
"version": "2026.10.28+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": {
|
"amneziawg": {
|
||||||
"version": "0-unstable-2026-08-14+e90531d",
|
"version": "0-unstable-2026-08-14+e90531d",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
|
|||||||
@@ -127,3 +127,29 @@ impl Client {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A Unix time as `YYYY-MM-DD HH:MM UTC`.
|
||||||
|
pub fn utc(ts: u64) -> String {
|
||||||
|
let (days, secs) = ((ts / 86400) as i64, ts % 86400);
|
||||||
|
// Howard Hinnant's civil_from_days.
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z - era * 146_097;
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let d = doy - (153 * mp + 2) / 5 + 1;
|
||||||
|
let m = if mp < 10 { mp + 3 } else { mp - 9 };
|
||||||
|
let y = yoe + era * 400 + i64::from(m <= 2);
|
||||||
|
format!("{y:04}-{m:02}-{d:02} {:02}:{:02} UTC", secs / 3600, secs % 3600 / 60)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod time_tests {
|
||||||
|
#[test]
|
||||||
|
fn unix_times_read_as_dates() {
|
||||||
|
assert_eq!(super::utc(0), "1970-01-01 00:00 UTC");
|
||||||
|
assert_eq!(super::utc(951_782_400), "2000-02-29 00:00 UTC");
|
||||||
|
assert_eq!(super::utc(1_793_190_240), "2026-10-28 12:24 UTC");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,49 @@
|
|||||||
//! 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,
|
||||||
|
// Beside sing-box's TUN, as its defaults are: checked by winws2 with the rest.
|
||||||
|
keep_off: ps_core::zapret::tun_exclusion("172.19.0.1/30", Some("fd66:19::1/64")),
|
||||||
};
|
};
|
||||||
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}");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,8 +9,9 @@ use serde::{Deserialize, Serialize};
|
|||||||
pub struct KillSwitch {
|
pub struct KillSwitch {
|
||||||
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
|
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
|
||||||
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
|
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
|
||||||
/// and after it fails. Windows Filtering Platform filters do it, so it holds even while
|
/// and after it fails. Windows Filtering Platform filters in the service's own session do
|
||||||
/// the service itself is stopped, until `proxy-ctl killswitch off`.
|
/// it: they go with the service. `proxy-ctl killswitch off`, or turning the tunnel off,
|
||||||
|
/// lifts it until a tunnel is turned on again.
|
||||||
pub enable: bool,
|
pub enable: bool,
|
||||||
pub direct_fallbacks: bool,
|
pub direct_fallbacks: bool,
|
||||||
pub allowed_subnets: Vec<String>,
|
pub allowed_subnets: Vec<String>,
|
||||||
|
|||||||
@@ -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)]
|
||||||
@@ -119,7 +119,7 @@ pub fn validate(cfg: &Config) -> Vec<Issue> {
|
|||||||
fn not_ported(cfg: &Config, v: &mut Issues) {
|
fn not_ported(cfg: &Config, v: &mut Issues) {
|
||||||
const IGNORED: &str = "is not on Windows yet: this release ignores it";
|
const IGNORED: &str = "is not on Windows yet: this release ignores it";
|
||||||
if cfg.kill_switch.enable {
|
if cfg.kill_switch.enable {
|
||||||
v.warn("killSwitch.enable", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel");
|
v.warn("killSwitch.enable", "on Windows the kill switch holds while the service runs, not from boot as upstream's: stopping the service lifts it");
|
||||||
}
|
}
|
||||||
for (on, path, what) in [
|
for (on, path, what) in [
|
||||||
(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"),
|
||||||
@@ -130,24 +130,10 @@ fn not_ported(cfg: &Config, v: &mut Issues) {
|
|||||||
v.warn(path, format!("{what} {IGNORED}"));
|
v.warn(path, format!("{what} {IGNORED}"));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
|
|
||||||
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
|
|
||||||
}
|
|
||||||
let z = &cfg.zapret;
|
let z = &cfg.zapret;
|
||||||
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.zapret2.strategy_source == StrategySource::Z2k && z.zapret2.profiles.is_none() {
|
|
||||||
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 {
|
|
||||||
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");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn proxy(cfg: &Config, v: &mut Issues) {
|
fn proxy(cfg: &Config, v: &mut Issues) {
|
||||||
@@ -317,6 +303,9 @@ fn proxy(cfg: &Config, v: &mut Issues) {
|
|||||||
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");
|
||||||
}
|
}
|
||||||
|
if p.enable && p.backend == Backend::Xray {
|
||||||
|
xray_backend(cfg, v);
|
||||||
|
}
|
||||||
if p.enable && !derived::has_available_outbounds(cfg) {
|
if p.enable && !derived::has_available_outbounds(cfg) {
|
||||||
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
|
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
|
||||||
}
|
}
|
||||||
@@ -344,6 +333,43 @@ fn proxy(cfg: &Config, v: &mut Issues) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What upstream asserts unavailable with `proxy.backend = "xray"`, and the transparent modes
|
||||||
|
/// this port has no XRay counterpart for. (Rule sets, groups, "failover", autoProxy, fake IP,
|
||||||
|
/// program rules, per-app routing and sing-box JSON are refused with the other backend checks.)
|
||||||
|
fn xray_backend(cfg: &Config, v: &mut Issues) {
|
||||||
|
const NEEDS: &str = "needs the sing-box or hybrid backend";
|
||||||
|
let p = &cfg.proxy;
|
||||||
|
if p.selection == Selection::Selector {
|
||||||
|
v.error("proxy.selection", format!("\"selector\" selection {NEEDS}"));
|
||||||
|
}
|
||||||
|
if p.dns.local.transport == super::DnsTransport::Tls || p.dns.remote.transport == super::DnsTransport::Tls {
|
||||||
|
v.error("proxy.dns", "DoT (type \"tls\") is not supported with the xray backend; use udp or tcp DNS");
|
||||||
|
}
|
||||||
|
if p.dns.strategy.is_some() {
|
||||||
|
v.error("proxy.dns.strategy", format!("dns.strategy {NEEDS}"));
|
||||||
|
}
|
||||||
|
if p.dns.client_subnet.is_some() {
|
||||||
|
v.error("proxy.dns.clientSubnet", format!("dns.clientSubnet {NEEDS}"));
|
||||||
|
}
|
||||||
|
if !p.dns.sing_box.servers.is_empty() || !p.dns.sing_box.rules.is_empty() {
|
||||||
|
v.error("proxy.dns.singBox", format!("dns.singBox.servers and rules {NEEDS}"));
|
||||||
|
}
|
||||||
|
if cfg.debug.connection_log.enable {
|
||||||
|
v.error("debug.connectionLog.enable", format!("the connection log {NEEDS}"));
|
||||||
|
}
|
||||||
|
if p.tun.enable {
|
||||||
|
v.error("proxy.tun.enable", "the TUN with the xray backend is not on Windows yet; use sing-box or hybrid for it");
|
||||||
|
}
|
||||||
|
if matches!(cfg.warp.as_outbound, Some(crate::config::WarpOutboundKind::SingBox)) && cfg.warp.enable {
|
||||||
|
v.error("warp.asOutbound", "a sing-box WARP endpoint needs the sing-box or hybrid backend; use \"userspace\"");
|
||||||
|
}
|
||||||
|
for (name, prof) in &cfg.amnezia_wg.profiles {
|
||||||
|
if cfg.amnezia_wg.enable && matches!(prof.as_outbound, Some(crate::config::AwgOutboundKind::SingBox)) {
|
||||||
|
v.error(format!("amneziaWg.profiles.{name}.asOutbound"), "a sing-box AmneziaWG endpoint needs the sing-box or hybrid backend; use \"userspace\"");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn tunnels(cfg: &Config, v: &mut Issues) {
|
fn tunnels(cfg: &Config, v: &mut Issues) {
|
||||||
let proxy_on = cfg.proxy.enable;
|
let proxy_on = cfg.proxy.enable;
|
||||||
|
|
||||||
@@ -504,6 +530,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;
|
||||||
}
|
}
|
||||||
@@ -773,6 +819,16 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[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]
|
#[test]
|
||||||
fn whitelist_bypass_names_are_checked_while_it_is_off() {
|
fn whitelist_bypass_names_are_checked_while_it_is_off() {
|
||||||
let mut cfg = Config::default();
|
let mut cfg = Config::default();
|
||||||
@@ -841,9 +897,9 @@ mod tests {
|
|||||||
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", "proxy.tun.enable"] {
|
// Both are ported: the kill switch says how it differs, the TUN beside zapret nothing.
|
||||||
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
|
assert!(paths.is_empty(), "{paths:?}");
|
||||||
}
|
assert!(validate(&cfg).iter().any(|i| i.path == "killSwitch.enable" && i.message.contains("not from boot")));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ pub mod groups;
|
|||||||
mod outbounds;
|
mod outbounds;
|
||||||
mod routing;
|
mod routing;
|
||||||
mod sing_box;
|
mod sing_box;
|
||||||
|
mod xray;
|
||||||
|
/// The TUN's IPv6 address (its IPv4 one is configured).
|
||||||
|
pub use sing_box::TUN_IPV6_ADDRESS;
|
||||||
|
|
||||||
use std::collections::{BTreeMap, HashMap};
|
use std::collections::{BTreeMap, HashMap};
|
||||||
use std::fmt;
|
use std::fmt;
|
||||||
@@ -105,6 +108,13 @@ pub struct Env {
|
|||||||
pub windows: bool,
|
pub windows: bool,
|
||||||
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
|
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
|
||||||
pub autoproxy_rules_dir: Option<String>,
|
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>,
|
||||||
|
/// The networks the 16 KB cutoff probe found cut and no name fixes, for the proxy
|
||||||
|
/// (`zapret2.cutoff.proxyFallback`, ps_core::zapret2::cutoff_rules).
|
||||||
|
pub zapret2_cutoff_rule_set: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Input<'a> {
|
pub struct Input<'a> {
|
||||||
@@ -153,9 +163,10 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
|
|||||||
let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut 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 })
|
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings })
|
||||||
}
|
}
|
||||||
crate::config::Backend::Xray => Err(RenderError(
|
crate::config::Backend::Xray => {
|
||||||
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
|
let config = xray::config(input, &assembly, &mut warnings)?;
|
||||||
)),
|
Ok(Rendered { sing_box: None, xray: Some(config), inventory: assembly.inventory, probe_exits: Vec::new(), warnings })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,6 +54,8 @@ pub(super) struct Assembly {
|
|||||||
/// The hybrid sidecar's XRay outbounds.
|
/// The hybrid sidecar's XRay outbounds.
|
||||||
pub xray: Vec<Value>,
|
pub xray: Vec<Value>,
|
||||||
pub inventory: Inventory,
|
pub inventory: Inventory,
|
||||||
|
/// What selection may pick on its own (the XRay backend builds its "proxy" from it).
|
||||||
|
pub selectable: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
struct Builder<'a> {
|
struct Builder<'a> {
|
||||||
@@ -136,6 +138,14 @@ impl Builder<'_> {
|
|||||||
|
|
||||||
/// A loopback SOCKS hop to a helper the service runs.
|
/// A loopback SOCKS hop to a helper the service runs.
|
||||||
fn hop(&self, tag: &str, port: u16, login: bool) -> Value {
|
fn hop(&self, tag: &str, port: u16, login: bool) -> Value {
|
||||||
|
if self.backend == Backend::Xray {
|
||||||
|
let mut ob = json!({ "protocol": "socks", "tag": tag, "settings": { "address": "127.0.0.1", "port": port } });
|
||||||
|
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
|
||||||
|
ob["settings"]["user"] = user.clone().into();
|
||||||
|
ob["settings"]["pass"] = pass.clone().into();
|
||||||
|
}
|
||||||
|
return ob;
|
||||||
|
}
|
||||||
let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port });
|
let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port });
|
||||||
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
|
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
|
||||||
ob["username"] = user.clone().into();
|
ob["username"] = user.clone().into();
|
||||||
@@ -276,6 +286,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
}
|
}
|
||||||
ExtraKind::Warp { device } => match device.kind {
|
ExtraKind::Warp { device } => match device.kind {
|
||||||
crate::config::WarpOutboundKind::SingBox => {
|
crate::config::WarpOutboundKind::SingBox => {
|
||||||
|
if p.backend == Backend::Xray {
|
||||||
|
warnings.push(format!("WARP device '{}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out", device.tag));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(profile) = input.env.warp_profiles.get(&device.tag) else {
|
let Some(profile) = input.env.warp_profiles.get(&device.tag) else {
|
||||||
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
|
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
|
||||||
continue;
|
continue;
|
||||||
@@ -296,6 +310,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
},
|
},
|
||||||
ExtraKind::Awg { profile, kind, port } => match kind {
|
ExtraKind::Awg { profile, kind, port } => match kind {
|
||||||
crate::config::AwgOutboundKind::SingBox => {
|
crate::config::AwgOutboundKind::SingBox => {
|
||||||
|
if p.backend == Backend::Xray {
|
||||||
|
warnings.push(format!("AmneziaWG outbound '{profile}': a sing-box endpoint needs the sing-box or hybrid backend (use \"userspace\"); leaving it out"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let Some(conf) = input.env.awg_profiles.get(&profile) else {
|
let Some(conf) = input.env.awg_profiles.get(&profile) else {
|
||||||
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
|
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
|
||||||
continue;
|
continue;
|
||||||
@@ -341,7 +359,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
// Groups, against the outbounds this start has. A group whose name an outbound took, or
|
// Groups, against the outbounds this start has. A group whose name an outbound took, or
|
||||||
// that contains itself, is left out.
|
// that contains itself, is left out.
|
||||||
let mut group_cfg = p.groups.clone();
|
let mut group_cfg = p.groups.clone();
|
||||||
if let Some(warp) = warp_group(cfg) {
|
// Groups need sing-box (validated); the XRay backend has none, nor a "warp" group.
|
||||||
|
if p.backend == Backend::Xray {
|
||||||
|
group_cfg.clear();
|
||||||
|
} else if let Some(warp) = warp_group(cfg) {
|
||||||
group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp);
|
group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp);
|
||||||
}
|
}
|
||||||
group_cfg.retain(|name, _| {
|
group_cfg.retain(|name, _| {
|
||||||
@@ -424,11 +445,12 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest.
|
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest. The
|
||||||
|
// XRay backend builds its own from `selectable` and the pin.
|
||||||
let mut every: Vec<String> = b.order.clone();
|
let mut every: Vec<String> = b.order.clone();
|
||||||
every.extend(resolved.groups.keys().cloned());
|
every.extend(resolved.groups.keys().cloned());
|
||||||
let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() };
|
let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() };
|
||||||
let wrapper = match p.selection {
|
let wrapper = if p.backend == Backend::Xray { Value::Null } else { match p.selection {
|
||||||
Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }),
|
Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }),
|
||||||
Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
|
Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
|
||||||
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
|
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
|
||||||
@@ -446,8 +468,8 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
|
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
|
||||||
"interval": p.url_test.interval, "tolerance": p.url_test.tolerance,
|
"interval": p.url_test.interval, "tolerance": p.url_test.tolerance,
|
||||||
}),
|
}),
|
||||||
};
|
} };
|
||||||
let mut outbounds = vec![wrapper];
|
let mut outbounds = if wrapper.is_null() { Vec::new() } else { vec![wrapper] };
|
||||||
outbounds.append(&mut b.outbounds);
|
outbounds.append(&mut b.outbounds);
|
||||||
outbounds.extend(resolved.outbounds.iter().cloned());
|
outbounds.extend(resolved.outbounds.iter().cloned());
|
||||||
|
|
||||||
@@ -472,7 +494,7 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
|
|||||||
.map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned())))
|
.map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned())))
|
||||||
.collect(),
|
.collect(),
|
||||||
};
|
};
|
||||||
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory })
|
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory, selectable })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// With two or more WARP devices, "warp" names a group of them.
|
/// With two or more WARP devices, "warp" names a group of them.
|
||||||
|
|||||||
@@ -142,8 +142,11 @@ pub(super) fn direct_match(input: &Input) -> RouteMatch {
|
|||||||
fn always_rules(input: &Input, known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Vec<Value> {
|
fn always_rules(input: &Input, known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Vec<Value> {
|
||||||
let cfg = input.cfg;
|
let cfg = input.cfg;
|
||||||
let mut rules = Vec::new();
|
let mut rules = Vec::new();
|
||||||
if !input.env.direct_processes.is_empty() {
|
// Only what the TUN takes: sing-box looks a connection's program up on every inbound once a
|
||||||
rules.push(json!({ "process_path": input.env.direct_processes, "outbound": "direct" }));
|
// rule names one, and what the service sends through the local listener on purpose must
|
||||||
|
// keep going through the proxy.
|
||||||
|
if input.tun && !input.env.direct_processes.is_empty() {
|
||||||
|
rules.push(json!({ "inbound": ["tun-in"], "process_path": input.env.direct_processes, "outbound": "direct" }));
|
||||||
}
|
}
|
||||||
if cfg.per_app_routing.enable {
|
if cfg.per_app_routing.enable {
|
||||||
for prof in &cfg.per_app_routing.profiles {
|
for prof in &cfg.per_app_routing.profiles {
|
||||||
|
|||||||
@@ -52,7 +52,7 @@ fn hop_ports(input: &Input) -> Vec<u16> {
|
|||||||
out
|
out
|
||||||
}
|
}
|
||||||
|
|
||||||
fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
|
pub(super) fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
|
||||||
let auth = &input.cfg.proxy.listener.auth;
|
let auth = &input.cfg.proxy.listener.auth;
|
||||||
let Some(user) = &auth.username else { return Ok(None) };
|
let Some(user) = &auth.username else { return Ok(None) };
|
||||||
let password = match (&auth.password, &auth.password_file) {
|
let password = match (&auth.password, &auth.password_file) {
|
||||||
@@ -146,6 +146,29 @@ pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], w
|
|||||||
let mut rule_sets = route.rule_set;
|
let mut rule_sets = route.rule_set;
|
||||||
let mut dns_rules = route.dns_rules;
|
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);
|
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" }));
|
||||||
|
}
|
||||||
|
// The networks that cut TLS after 16 KB, which no name fixes: by address, so only for
|
||||||
|
// what the proxy sees by address (the TUN, per-app routing), as upstream's.
|
||||||
|
if let Some(path) = &env.zapret2_cutoff_rule_set
|
||||||
|
&& route.mode != super::RouteMode::AllBypass
|
||||||
|
{
|
||||||
|
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-cutoff", "path": path }));
|
||||||
|
rules.push(json!({ "rule_set": ["zapret-cutoff"], "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 {
|
||||||
|
|||||||
@@ -0,0 +1,334 @@
|
|||||||
|
//! The XRay-only backend's whole config: upstream's `config-templates/xray.nix` (its `tproxy`
|
||||||
|
//! variant, without TProxy), `rules/xray.nix` and the start-time `backend-filter-xray.template.jq`.
|
||||||
|
//! The transparent modes (TProxy, TUN, per-app TUN) have no counterpart here.
|
||||||
|
|
||||||
|
use std::collections::BTreeSet;
|
||||||
|
|
||||||
|
use serde_json::{Map, Value, json};
|
||||||
|
|
||||||
|
use super::outbounds::Assembly;
|
||||||
|
use super::routing::{LOOPBACK, direct_match};
|
||||||
|
use super::sing_box::{apply_xmux, listener_users, xray_log_level};
|
||||||
|
use super::{Input, RenderError, RouteMode};
|
||||||
|
use crate::config::{DnsTransport, DnsUpstream, RouteDefault, RouteMatch, Selection};
|
||||||
|
use crate::derived;
|
||||||
|
|
||||||
|
/// `urltest` renames every outbound so the balancer's selector can be a prefix.
|
||||||
|
const PREFIX: &str = "proxy-suite-ob-";
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
enum Category {
|
||||||
|
Proxy,
|
||||||
|
Direct,
|
||||||
|
Block,
|
||||||
|
/// Private addresses and the Telegram relay's: direct, but kept in every mode.
|
||||||
|
Safety,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn category(target: &str) -> Category {
|
||||||
|
match target {
|
||||||
|
"direct" => Category::Direct,
|
||||||
|
"block" => Category::Block,
|
||||||
|
_ => Category::Proxy,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Section {
|
||||||
|
priority: i64,
|
||||||
|
category: Category,
|
||||||
|
rules: Vec<Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where a rule's outbound is in this config.
|
||||||
|
struct Targets {
|
||||||
|
prefixed: bool,
|
||||||
|
/// The one outbound "proxy" stands for (a pin, "first", or a balancer of one), renamed.
|
||||||
|
single: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Targets {
|
||||||
|
/// `{type, ruleTag, <fields>}` and its target: "proxy" is the balancer or the one exit.
|
||||||
|
fn rule(&self, rule_tag: &str, fields: Value, outbound: &str) -> Value {
|
||||||
|
let mut rule = json!({ "type": "field", "ruleTag": rule_tag });
|
||||||
|
if let Value::Object(f) = fields {
|
||||||
|
rule.as_object_mut().unwrap().extend(f);
|
||||||
|
}
|
||||||
|
match outbound {
|
||||||
|
"proxy" => match &self.single {
|
||||||
|
Some(tag) => rule["outboundTag"] = tag.clone().into(),
|
||||||
|
None => rule["balancerTag"] = "proxy".into(),
|
||||||
|
},
|
||||||
|
"direct" | "block" => rule["outboundTag"] = outbound.into(),
|
||||||
|
tag if self.prefixed => rule["outboundTag"] = format!("{PREFIX}{tag}").into(),
|
||||||
|
tag => rule["outboundTag"] = tag.into(),
|
||||||
|
}
|
||||||
|
rule
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One rule per kind of match, as upstream's `mkXrayCustomRuleEntries` (a rule matches any
|
||||||
|
/// of them): `<prefix>-domain`, `-ip`, `-geosite`, `-geoip`.
|
||||||
|
fn match_rules(&self, rule_tag: &dyn Fn(&str) -> String, outbound: &str, m: &RouteMatch) -> Vec<Value> {
|
||||||
|
let mut rules = Vec::new();
|
||||||
|
if !m.domains.is_empty() {
|
||||||
|
let domains: Vec<String> = m.domains.iter().map(|d| format!("domain:{d}")).collect();
|
||||||
|
rules.push(self.rule(&rule_tag("domain"), json!({ "domain": domains }), outbound));
|
||||||
|
}
|
||||||
|
if !m.ips.is_empty() {
|
||||||
|
rules.push(self.rule(&rule_tag("ip"), json!({ "ip": m.ips }), outbound));
|
||||||
|
}
|
||||||
|
if !m.geosites.is_empty() {
|
||||||
|
let sites: Vec<String> = m.geosites.iter().map(|s| format!("geosite:{s}")).collect();
|
||||||
|
rules.push(self.rule(&rule_tag("geosite"), json!({ "domain": sites }), outbound));
|
||||||
|
}
|
||||||
|
if !m.geoips.is_empty() {
|
||||||
|
let ips: Vec<String> = m.geoips.iter().map(|s| format!("geoip:{s}")).collect();
|
||||||
|
rules.push(self.rule(&rule_tag("geoip"), json!({ "ip": ips }), outbound));
|
||||||
|
}
|
||||||
|
rules
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dns_server(tag: &str, upstream: &DnsUpstream) -> Result<Value, RenderError> {
|
||||||
|
let address = match upstream.transport {
|
||||||
|
DnsTransport::Udp => upstream.address.clone(),
|
||||||
|
DnsTransport::Tcp => format!("tcp://{}", upstream.address),
|
||||||
|
DnsTransport::Tls => return Err(RenderError("proxy.dns.*.type = \"tls\" is not supported with the xray backend; use udp or tcp DNS".into())),
|
||||||
|
};
|
||||||
|
Ok(json!({ "address": address, "tag": tag, "port": upstream.port, "queryStrategy": "UseIP" }))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Names of proxy servers, which XRay's DNS resolves once a dial has a domainStrategy
|
||||||
|
/// (the jq's `xray_server_names`).
|
||||||
|
fn server_names(outbounds: &[Value]) -> BTreeSet<String> {
|
||||||
|
let mut names = BTreeSet::new();
|
||||||
|
for ob in outbounds {
|
||||||
|
let settings = &ob["settings"];
|
||||||
|
let addresses = settings["vnext"]
|
||||||
|
.as_array()
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.chain(settings["servers"].as_array().into_iter().flatten())
|
||||||
|
.map(|s| &s["address"])
|
||||||
|
.chain(std::iter::once(&settings["address"]));
|
||||||
|
for a in addresses.filter_map(Value::as_str) {
|
||||||
|
let numeric = a.chars().all(|c| c.is_ascii_digit() || c == '.');
|
||||||
|
if !numeric && !a.contains(':') && a != "localhost" {
|
||||||
|
names.insert(a.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<Value, RenderError> {
|
||||||
|
if input.tun {
|
||||||
|
return Err(RenderError("the TUN with the xray backend is not on Windows yet".into()));
|
||||||
|
}
|
||||||
|
let cfg = input.cfg;
|
||||||
|
let p = &cfg.proxy;
|
||||||
|
let r = &p.routing;
|
||||||
|
|
||||||
|
// "proxy": a balancer over every selectable outbound on urltest, else the one exit. XRay has
|
||||||
|
// no selector: a pin leaves the balancer with one outbound, which is the path "first" takes.
|
||||||
|
let urltest = p.selection == Selection::Urltest;
|
||||||
|
let pinned = &asm.inventory.pinned;
|
||||||
|
let single_raw = if !pinned.is_empty() {
|
||||||
|
Some(pinned.clone())
|
||||||
|
} else if urltest {
|
||||||
|
(asm.selectable.len() == 1).then(|| asm.selectable[0].clone())
|
||||||
|
} else {
|
||||||
|
asm.selectable.first().cloned()
|
||||||
|
};
|
||||||
|
let targets = Targets {
|
||||||
|
prefixed: urltest,
|
||||||
|
single: single_raw.map(|t| if urltest { format!("{PREFIX}{t}") } else { t }),
|
||||||
|
};
|
||||||
|
let balanced = urltest && targets.single.is_none();
|
||||||
|
|
||||||
|
// Outbounds: the exits, then the builtin ones.
|
||||||
|
let mut outbounds: Vec<Value> = Vec::new();
|
||||||
|
for ob in &asm.outbounds {
|
||||||
|
let mut ob = ob.clone();
|
||||||
|
apply_xmux(input, &mut ob);
|
||||||
|
if urltest {
|
||||||
|
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
|
||||||
|
ob["tag"] = format!("{PREFIX}{tag}").into();
|
||||||
|
if let Some(hop) = ob.pointer("/streamSettings/sockopt/dialerProxy").and_then(Value::as_str) {
|
||||||
|
ob["streamSettings"]["sockopt"]["dialerProxy"] = format!("{PREFIX}{hop}").into();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outbounds.push(ob);
|
||||||
|
}
|
||||||
|
let names = server_names(&outbounds);
|
||||||
|
|
||||||
|
// No loopback by any name for what goes direct, besides the resolvers on it: the loopback
|
||||||
|
// hops, the helpers' listeners and whatever else listens there are nothing to dial.
|
||||||
|
let loopback_dns_ports: BTreeSet<u16> = [&p.dns.local, &p.dns.remote]
|
||||||
|
.into_iter()
|
||||||
|
.filter(|u| u.address.starts_with("127.") || u.address == "::1" || u.address == "localhost")
|
||||||
|
.map(|u| u.port)
|
||||||
|
.collect();
|
||||||
|
let mut final_rules = Vec::new();
|
||||||
|
if !loopback_dns_ports.is_empty() {
|
||||||
|
let ports: Vec<String> = loopback_dns_ports.iter().map(u16::to_string).collect();
|
||||||
|
final_rules.push(json!({ "action": "allow", "ip": LOOPBACK, "port": ports.join(",") }));
|
||||||
|
}
|
||||||
|
final_rules.push(json!({ "action": "block", "ip": LOOPBACK, "blockDelay": 0 }));
|
||||||
|
outbounds.push(json!({ "protocol": "freedom", "tag": "direct", "settings": { "finalRules": final_rules } }));
|
||||||
|
outbounds.push(json!({ "protocol": "blackhole", "tag": "block", "settings": {} }));
|
||||||
|
|
||||||
|
// No rule takes packets to dns-out here (those are TProxy's and the TUN's), but it is the
|
||||||
|
// template's: .onion is told there is no such name, other record types go on.
|
||||||
|
let mut dns_rules = Vec::new();
|
||||||
|
if derived::tor_route_onion(cfg) {
|
||||||
|
dns_rules.push(json!({ "action": "return", "rCode": 3, "domain": ["domain:onion"] }));
|
||||||
|
}
|
||||||
|
dns_rules.push(json!({ "action": "direct", "qType": "2-27,29-65535" }));
|
||||||
|
outbounds.push(json!({ "protocol": "dns", "tag": "dns-out", "settings": { "userLevel": 0, "rules": dns_rules } }));
|
||||||
|
|
||||||
|
// The mode: the configured default, or proxy-ctl's override.
|
||||||
|
let mode = input.state.route_mode.unwrap_or(match r.default {
|
||||||
|
RouteDefault::Proxy => RouteMode::Blacklist,
|
||||||
|
RouteDefault::Direct => RouteMode::Whitelist,
|
||||||
|
});
|
||||||
|
let (final_outbound, remote_first) = match mode {
|
||||||
|
RouteMode::Blacklist | RouteMode::AllProxy => ("proxy", true),
|
||||||
|
RouteMode::Whitelist | RouteMode::AllBypass => ("direct", false),
|
||||||
|
};
|
||||||
|
|
||||||
|
// DNS: the preferred server first (the backend filter's `xray_dns_server_order`), proxy
|
||||||
|
// servers' names pinned to a copy of "local".
|
||||||
|
let remote = dns_server("remote", &p.dns.remote)?;
|
||||||
|
let local = dns_server("local", &p.dns.local)?;
|
||||||
|
let mut servers = if remote_first { vec![remote, local.clone()] } else { vec![local.clone(), remote] };
|
||||||
|
if !names.is_empty() {
|
||||||
|
let mut pinned_local = local;
|
||||||
|
pinned_local["domains"] = names.iter().map(|n| format!("full:{n}")).collect::<Vec<_>>().into();
|
||||||
|
pinned_local["skipFallback"] = true.into();
|
||||||
|
servers.push(pinned_local);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rules. What XRay's DNS asks for goes by the server's tag: "local" direct, "remote" through
|
||||||
|
// the proxy.
|
||||||
|
let mut rules = vec![
|
||||||
|
targets.rule("dns-upstream-direct", json!({ "inboundTag": ["local"], "network": "tcp,udp" }), "direct"),
|
||||||
|
targets.rule("dns-upstream-remote", json!({ "inboundTag": ["remote"], "network": "tcp,udp" }), "proxy"),
|
||||||
|
];
|
||||||
|
// Nothing reaches this host's loopback through the proxy, by address or by name. Upstream
|
||||||
|
// guards the transparent inbounds only (its firewall keeps the rest from other users);
|
||||||
|
// Windows has no such firewall here, so the local listener too.
|
||||||
|
let onion = derived::tor_route_onion(cfg) && asm.inventory.tags.iter().any(|t| t == derived::TOR_OUTBOUND_TAG);
|
||||||
|
let mut common = vec![
|
||||||
|
targets.rule("guard-loopback-ip", json!({ "inboundTag": ["mixed-in"], "ip": LOOPBACK }), "block"),
|
||||||
|
targets.rule("guard-loopback-domain", json!({ "inboundTag": ["mixed-in"], "domain": ["domain:localhost"] }), "block"),
|
||||||
|
];
|
||||||
|
if onion {
|
||||||
|
common.push(targets.rule("tor-onion", json!({ "domain": ["domain:onion"] }), derived::TOR_OUTBOUND_TAG));
|
||||||
|
}
|
||||||
|
rules.extend(common);
|
||||||
|
|
||||||
|
let known = |t: &str| asm.inventory.tags.iter().any(|x| x == t);
|
||||||
|
let mut sections = Vec::new();
|
||||||
|
let custom_tag = |outbound: &str| {
|
||||||
|
let c = match category(outbound) {
|
||||||
|
Category::Direct => "direct",
|
||||||
|
Category::Block => "block",
|
||||||
|
_ => "proxy",
|
||||||
|
};
|
||||||
|
let c = c.to_owned();
|
||||||
|
move |kind: &str| format!("custom-{c}-{kind}")
|
||||||
|
};
|
||||||
|
for ob in &p.outbounds {
|
||||||
|
if ob.routing.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let outbound = if known(&ob.tag) {
|
||||||
|
ob.tag.as_str()
|
||||||
|
} else {
|
||||||
|
warnings.push(format!("outbound '{}' is not running: what its routing sends to it is blocked until it is", ob.tag));
|
||||||
|
"block"
|
||||||
|
};
|
||||||
|
let tag = custom_tag(outbound);
|
||||||
|
sections.push(Section { priority: 100, category: category(outbound), rules: targets.match_rules(&tag, outbound, &ob.routing) });
|
||||||
|
}
|
||||||
|
for (i, rule) in r.rules.iter().enumerate() {
|
||||||
|
if rule.disabled {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let name = rule.name.clone().unwrap_or_else(|| format!("#{i}"));
|
||||||
|
let outbound = if derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) || known(&rule.outbound) {
|
||||||
|
rule.outbound.as_str()
|
||||||
|
} else {
|
||||||
|
warnings.push(format!("routing rule {name}: no outbound named '{}' is running; what it matches is blocked until it is", rule.outbound));
|
||||||
|
"block"
|
||||||
|
};
|
||||||
|
let tag = custom_tag(outbound);
|
||||||
|
sections.push(Section {
|
||||||
|
priority: rule.priority.unwrap_or(100),
|
||||||
|
category: category(outbound),
|
||||||
|
rules: targets.match_rules(&tag, outbound, &rule.matches),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let direct = direct_match(input);
|
||||||
|
let fixed = |prefix: &'static str| move |kind: &str| format!("{prefix}-{kind}");
|
||||||
|
let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() };
|
||||||
|
let proxy_geo = RouteMatch { geosites: r.proxy.geosites.clone(), geoips: r.proxy.geoips.clone(), ..Default::default() };
|
||||||
|
sections.push(Section { priority: 200, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_primary) });
|
||||||
|
// Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too).
|
||||||
|
sections.push(Section { priority: 300, category: Category::Block, rules: targets.match_rules(&fixed("block"), "block", &r.block) });
|
||||||
|
sections.push(Section { priority: 400, category: Category::Direct, rules: targets.match_rules(&fixed("direct"), "direct", &direct) });
|
||||||
|
let mut safety = vec![targets.rule("direct-private", json!({ "ip": ["geoip:private"] }), "direct")];
|
||||||
|
let tg = &cfg.tg_ws_proxy;
|
||||||
|
if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() {
|
||||||
|
let ips: BTreeSet<&String> = tg.dc_ips.values().collect();
|
||||||
|
safety.push(targets.rule("direct-tg-relay", json!({ "ip": ips }), "direct"));
|
||||||
|
}
|
||||||
|
sections.push(Section { priority: 400, category: Category::Safety, rules: safety });
|
||||||
|
// Geosite and geoip lists last: they are the heaviest to match.
|
||||||
|
sections.push(Section { priority: 500, category: Category::Proxy, rules: targets.match_rules(&fixed("proxy"), "proxy", &proxy_geo) });
|
||||||
|
|
||||||
|
let keep = |c: Category| match mode {
|
||||||
|
RouteMode::AllProxy => c != Category::Direct,
|
||||||
|
RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety),
|
||||||
|
_ => true,
|
||||||
|
};
|
||||||
|
// A stable sort: among equals, the list's own order.
|
||||||
|
sections.sort_by_key(|s| s.priority);
|
||||||
|
rules.extend(sections.into_iter().filter(|s| keep(s.category)).flat_map(|s| s.rules));
|
||||||
|
rules.push(targets.rule("final-default", json!({ "network": "tcp,udp" }), final_outbound));
|
||||||
|
|
||||||
|
let mut routing = json!({ "domainStrategy": "IPIfNonMatch", "domainMatcher": "hybrid", "rules": rules });
|
||||||
|
let mut config = Map::new();
|
||||||
|
if balanced {
|
||||||
|
// Only what selection may pick: not proxy.selectionExclude, nor what is disabled.
|
||||||
|
let candidates: Vec<String> = asm.selectable.iter().map(|t| format!("{PREFIX}{t}")).collect();
|
||||||
|
routing["balancers"] = json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]);
|
||||||
|
config.insert(
|
||||||
|
"observatory".into(),
|
||||||
|
json!({ "subjectSelector": candidates, "probeUrl": p.url_test.url, "probeInterval": p.url_test.interval }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// The listener: sniffing puts a name in place of the address a client connected to, so the
|
||||||
|
// domain rules see it.
|
||||||
|
let mut settings = json!({ "auth": "noauth", "udp": true, "ip": p.listener.address });
|
||||||
|
if let Some(users) = listener_users(input)? {
|
||||||
|
let accounts: Vec<Value> =
|
||||||
|
users.as_array().into_iter().flatten().map(|u| json!({ "user": u["username"], "pass": u["password"] })).collect();
|
||||||
|
settings["auth"] = "password".into();
|
||||||
|
settings["accounts"] = accounts.into();
|
||||||
|
}
|
||||||
|
let mixed = json!({
|
||||||
|
"tag": "mixed-in", "protocol": "socks", "listen": p.listener.address, "port": p.listener.port,
|
||||||
|
"settings": settings,
|
||||||
|
"sniffing": { "enabled": true, "destOverride": ["http", "tls", "quic"] },
|
||||||
|
});
|
||||||
|
|
||||||
|
config.insert("log".into(), json!({ "loglevel": xray_log_level(input), "access": "none" }));
|
||||||
|
config.insert("dns".into(), json!({ "queryStrategy": "UseIP", "servers": servers }));
|
||||||
|
config.insert("inbounds".into(), json!([mixed]));
|
||||||
|
config.insert("outbounds".into(), Value::Array(outbounds));
|
||||||
|
config.insert("routing".into(), routing);
|
||||||
|
Ok(Value::Object(config))
|
||||||
|
}
|
||||||
@@ -497,6 +497,68 @@ pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclu
|
|||||||
(dedup(domains), dedup(ips))
|
(dedup(domains), dedup(ips))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// --- zapret beside the TUN ---------------------------------------------------------------
|
||||||
|
|
||||||
|
/// A WinDivert filter part that leaves out the packets of sing-box's TUN: what the apps send
|
||||||
|
/// into it carries its address as the source, what sing-box hands back as the destination.
|
||||||
|
/// zapret changing them would break them before sing-box reads them; it still sees the
|
||||||
|
/// connections sing-box makes (direct ones included) on the way out of the real adapter.
|
||||||
|
/// `v4`, `v6`: the TUN's addresses (CIDR); None for an address that does not read.
|
||||||
|
pub fn tun_exclusion(v4: &str, v6: Option<&str>) -> Option<String> {
|
||||||
|
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
// WinDivert negates a single test only, never a group: each "not from or to the TUN" is
|
||||||
|
// spelled out (a packet is inbound when it is not outbound).
|
||||||
|
let mut parts = Vec::new();
|
||||||
|
let (ip, len) = v4.split_once('/')?;
|
||||||
|
let (ip, len): (Ipv4Addr, u32) = (ip.parse().ok()?, len.parse().ok().filter(|l| *l <= 32)?);
|
||||||
|
let mask = if len == 0 { 0 } else { u32::MAX << (32 - len) };
|
||||||
|
let (lo, hi) = (Ipv4Addr::from(u32::from(ip) & mask), Ipv4Addr::from(u32::from(ip) | !mask));
|
||||||
|
parts.push(format!("(not ip or inbound or ip.SrcAddr < {lo} or ip.SrcAddr > {hi})"));
|
||||||
|
parts.push(format!("(not ip or outbound or ip.DstAddr < {lo} or ip.DstAddr > {hi})"));
|
||||||
|
if let Some(v6) = v6 {
|
||||||
|
let (ip, len) = v6.split_once('/')?;
|
||||||
|
let (ip, len): (Ipv6Addr, u32) = (ip.parse().ok()?, len.parse().ok().filter(|l| *l <= 128)?);
|
||||||
|
let mask = if len == 0 { 0 } else { u128::MAX << (128 - len) };
|
||||||
|
let (lo, hi) = (Ipv6Addr::from(u128::from(ip) & mask), Ipv6Addr::from(u128::from(ip) | !mask));
|
||||||
|
parts.push(format!("(not ipv6 or inbound or ipv6.SrcAddr < {lo} or ipv6.SrcAddr > {hi})"));
|
||||||
|
parts.push(format!("(not ipv6 or outbound or ipv6.DstAddr < {lo} or ipv6.DstAddr > {hi})"));
|
||||||
|
}
|
||||||
|
Some(parts.join(" and "))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// winws's arguments with its whole filter given instead (`--wf-raw=@file`, which replaces
|
||||||
|
/// the port options and the filter parts): for Flowseal's winws, which takes no part ANDed
|
||||||
|
/// with the rest. `file` holds what `--wf-save` printed for `argv`, with what is ANDed to it.
|
||||||
|
pub fn with_raw_filter(argv: &[String], file: &str) -> Vec<String> {
|
||||||
|
let mut out: Vec<String> = argv.iter().filter(|a| !["--wf-tcp=", "--wf-udp=", "--wf-raw-part=", "--wf-raw="].iter().any(|p| a.starts_with(p))).cloned().collect();
|
||||||
|
// The filter options go before the profiles (`--new`), as the presets give them.
|
||||||
|
let at = out.iter().position(|a| a == "--new" || !a.starts_with("--wf-") && !a.starts_with("--debug")).unwrap_or(out.len());
|
||||||
|
out.insert(at, format!("--wf-raw=@{file}"));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tun_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_tuns_packets_are_left_out() {
|
||||||
|
let f = tun_exclusion("172.19.0.1/30", Some("fd66:19::1/64")).unwrap();
|
||||||
|
assert!(f.starts_with("(not ip or inbound or ip.SrcAddr < 172.19.0.0 or ip.SrcAddr > 172.19.0.3) and "), "{f}");
|
||||||
|
assert!(f.ends_with("(not ipv6 or outbound or ipv6.DstAddr < fd66:19:: or ipv6.DstAddr > fd66:19::ffff:ffff:ffff:ffff)"), "{f}");
|
||||||
|
assert!(!f.contains("not ("), "WinDivert negates no group: {f}");
|
||||||
|
assert_eq!(tun_exclusion("172.19.0.1", None), None);
|
||||||
|
assert!(!tun_exclusion("10.0.0.1/8", None).unwrap().contains("ipv6"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_raw_filter_replaces_the_ports_and_parts() {
|
||||||
|
let argv: Vec<String> = ["--debug=1", "--wf-tcp=80,443", "--wf-udp=443", "--wf-raw-part=x", "--filter-tcp=80", "--dpi-desync=fake", "--new", "--filter-udp=443"].map(String::from).to_vec();
|
||||||
|
assert_eq!(with_raw_filter(&argv, "C:\\f.txt"), ["--debug=1", "--wf-raw=@C:\\f.txt", "--filter-tcp=80", "--dpi-desync=fake", "--new", "--filter-udp=443"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|||||||
@@ -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,25 @@ 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>,
|
||||||
|
/// A WinDivert filter part ANDed with the rest, besides the cutoff probe's: the TUN's
|
||||||
|
/// packets left out (ps_core::zapret::tun_exclusion).
|
||||||
|
pub keep_off: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 +186,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 +224,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 +302,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 +360,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 +505,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}"));
|
||||||
@@ -322,10 +517,218 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
|
|||||||
if !z.ipv6 {
|
if !z.ipv6 {
|
||||||
opt.push("--wf-l3=ipv4".into());
|
opt.push("--wf-l3=ipv4".into());
|
||||||
}
|
}
|
||||||
|
// The cutoff probe measures the line itself: its connections pass winws2 untouched. (One
|
||||||
|
// such filter only: a profile's own goes first.)
|
||||||
|
let ands: Vec<String> = z.cutoff.enable.then(cutoff_filter).into_iter().chain(p.keep_off.clone()).collect();
|
||||||
|
if !ands.is_empty() && !body.iter().any(|a| a.starts_with("--wf-raw-filter")) {
|
||||||
|
let all = if ands.len() == 1 { ands[0].clone() } else { ands.iter().map(|a| format!("({a})")).collect::<Vec<_>>().join(" and ") };
|
||||||
|
opt.push(format!("--wf-raw-filter={all}"));
|
||||||
|
}
|
||||||
opt.extend(body);
|
opt.extend(body);
|
||||||
Ok(opt)
|
Ok(opt)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// --- the 16 KB cutoff probe (upstream's zapret2/cutoff.nix) ---------------------------------
|
||||||
|
|
||||||
|
/// The local ports the cutoff probe (z2k-detect) connects from, which winws2 leaves alone, as
|
||||||
|
/// upstream's nft rule keeps zapret2 off the probe's cgroup. Below Windows' dynamic range
|
||||||
|
/// (49152-65535), so no other program's connection is given one of them unasked.
|
||||||
|
pub const CUTOFF_PORTS: (u16, u16) = (44000, 47999);
|
||||||
|
|
||||||
|
/// winws2's filter part (`--wf-raw-filter`, ANDed with the rest) that leaves out the probe's
|
||||||
|
/// connections: TCP from or to a local port in [`CUTOFF_PORTS`].
|
||||||
|
pub fn cutoff_filter() -> String {
|
||||||
|
let (lo, hi) = CUTOFF_PORTS;
|
||||||
|
format!("not tcp or (outbound and (tcp.SrcPort < {lo} or tcp.SrcPort > {hi})) or (inbound and (tcp.DstPort < {lo} or tcp.DstPort > {hi}))")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The networks (AS numbers) a probe found cut off, from its `asn.txt`: a row is one when its
|
||||||
|
/// first field is all digits (upstream's awk; `#` lines are comments).
|
||||||
|
pub fn cut_networks(asn: &str) -> Vec<String> {
|
||||||
|
let mut out: Vec<String> = asn.lines().filter_map(|l| l.split('\t').next()).map(str::trim).filter(|a| is_asn(a)).map(str::to_owned).collect();
|
||||||
|
out.dedup();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The name that gets through, by network, from its `sni.txt` (`asn<TAB>name`).
|
||||||
|
pub fn network_names(sni: &str) -> BTreeMap<String, String> {
|
||||||
|
sni.lines()
|
||||||
|
.filter_map(|l| {
|
||||||
|
let mut f = l.split('\t');
|
||||||
|
let (a, n) = (f.next()?.trim(), f.next().unwrap_or("").trim());
|
||||||
|
is_asn(a).then(|| (a.to_owned(), n.to_owned()))
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_asn(a: &str) -> bool {
|
||||||
|
!a.is_empty() && a.len() <= 10 && a.bytes().all(|b| b.is_ascii_digit())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cidr_ok(p: &str) -> bool {
|
||||||
|
let Some((ip, len)) = p.split_once('/') else { return false };
|
||||||
|
match (ip.parse::<std::net::IpAddr>(), len.parse::<u8>()) {
|
||||||
|
(Ok(std::net::IpAddr::V4(_)), Ok(l)) => l <= 32,
|
||||||
|
(Ok(std::net::IpAddr::V6(_)), Ok(l)) => l <= 128,
|
||||||
|
_ => false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rule-set for the proxy (`cutoff.proxyFallback`, upstream's `proxyRules`): the prefixes,
|
||||||
|
/// from z2k's `tcp16_nets.txt` (`asn<TAB>prefix`), of every cut-off network no name fixes.
|
||||||
|
pub fn cutoff_rules(asn: &str, sni: &str, nets: &str) -> serde_json::Value {
|
||||||
|
let cut: std::collections::BTreeSet<String> = cut_networks(asn).into_iter().collect();
|
||||||
|
let named = network_names(sni);
|
||||||
|
let cidrs: Vec<&str> = nets
|
||||||
|
.lines()
|
||||||
|
.filter_map(|l| {
|
||||||
|
let mut f = l.split('\t');
|
||||||
|
let (a, p) = (f.next()?.trim(), f.next()?.trim());
|
||||||
|
(cut.contains(a) && !named.contains_key(a) && cidr_ok(p)).then_some(p)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let rules = if cidrs.is_empty() { serde_json::json!([]) } else { serde_json::json!([{ "ip_cidr": cidrs }]) };
|
||||||
|
serde_json::json!({ "version": 1, "rules": rules })
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- 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)]
|
||||||
|
mod cutoff_tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_probes_maps_read_as_upstreams_awk_reads_them() {
|
||||||
|
let asn = "# cut off on this line\n24940\n16509\n\nAS13335\n";
|
||||||
|
assert_eq!(cut_networks(asn), ["24940", "16509"]);
|
||||||
|
let sni = "# names\n# per network\n24940\t300.ya.ru\nx\ty\n";
|
||||||
|
assert_eq!(network_names(sni), BTreeMap::from([("24940".to_owned(), "300.ya.ru".to_owned())]));
|
||||||
|
let nets = "24940\t91.98.0.0/16\n16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n16509\tnot-a-prefix\n13335\t104.16.0.0/16\n";
|
||||||
|
// Hetzner has a name (z2k puts it in); Amazon none: its prefixes go to the proxy.
|
||||||
|
assert_eq!(cutoff_rules(asn, sni, nets), serde_json::json!({ "version": 1, "rules": [{ "ip_cidr": ["3.5.0.0/16", "2600:1f00::/32"] }] }));
|
||||||
|
assert_eq!(cutoff_rules("", sni, nets), serde_json::json!({ "version": 1, "rules": [] }));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_probes_ports_are_left_out_of_winws2s_filter() {
|
||||||
|
let f = cutoff_filter();
|
||||||
|
assert!(f.contains("tcp.SrcPort < 44000 or tcp.SrcPort > 47999"), "{f}");
|
||||||
|
assert!(f.starts_with("not tcp or "));
|
||||||
|
assert!(CUTOFF_PORTS.1 < 49152, "inside Windows' dynamic port range");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -364,9 +767,82 @@ 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,
|
||||||
|
keep_off: 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();
|
||||||
|
|||||||
@@ -289,3 +289,335 @@ fn auto_proxy_never_routes_what_it_excludes() {
|
|||||||
);
|
);
|
||||||
check_sing_box(&sb, &dir);
|
check_sing_box(&sb, &dir);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
|
||||||
|
let dir = scratch("zapret2-sync");
|
||||||
|
let (direct, proxy, cutoff) = (dir.join("direct.json"), dir.join("proxy.json"), dir.join("cutoff.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 cut = ps_core::zapret2::cutoff_rules("16509\n", "", "16509\t3.5.0.0/16\n16509\t2600:1f00::/32\n");
|
||||||
|
std::fs::write(&cutoff, serde_json::to_vec(&cut).unwrap()).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());
|
||||||
|
e.zapret2_cutoff_rule_set = Some(cutoff.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 - 3], json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
|
||||||
|
assert_eq!(rules[n - 2], json!({ "rule_set": ["zapret-cutoff"], "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", "zapret-cutoff"]);
|
||||||
|
state.route_mode = Some(RouteMode::AllBypass);
|
||||||
|
assert!(tags(&render_with(&state)).is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn helper_programs_go_direct_only_from_the_tun() {
|
||||||
|
let dir = scratch("direct-programs");
|
||||||
|
let mut cfg = base();
|
||||||
|
cfg.proxy.tun.enable = true;
|
||||||
|
let e = env(&dir);
|
||||||
|
let rules = |tun: bool| {
|
||||||
|
let sb = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun }).unwrap().sing_box.unwrap();
|
||||||
|
sb["route"]["rules"].as_array().unwrap().iter().filter(|r| r.get("process_path").is_some() && r["outbound"] == "direct").cloned().collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
// Through the local listener a helper (the service's own fetches) goes where the rules say.
|
||||||
|
assert!(rules(false).is_empty());
|
||||||
|
let under_tun = rules(true);
|
||||||
|
assert_eq!(under_tun.len(), 1);
|
||||||
|
assert_eq!(under_tun[0]["inbound"], json!(["tun-in"]));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The xray backend's config, rendered and checked by `xray run -test`.
|
||||||
|
fn render_xray(cfg: &Config, state: &State, dir: &Path) -> (Value, Vec<String>) {
|
||||||
|
let mut cfg = cfg.clone();
|
||||||
|
cfg.proxy.backend = Backend::Xray;
|
||||||
|
let r = render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &env(dir), read_file: &no_files, tun: false }).unwrap();
|
||||||
|
assert!(r.sing_box.is_none() && r.probe_exits.is_empty());
|
||||||
|
let x = r.xray.unwrap();
|
||||||
|
check_xray(&x, dir);
|
||||||
|
(x, r.warnings)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xray_rules(x: &Value) -> &Vec<Value> {
|
||||||
|
x["routing"]["rules"].as_array().unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xray_rule<'a>(x: &'a Value, tag: &str) -> Option<&'a Value> {
|
||||||
|
xray_rules(x).iter().find(|r| r["ruleTag"] == tag)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xray_tags(x: &Value) -> Vec<&str> {
|
||||||
|
x["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xray_dns_tags(x: &Value) -> Vec<&str> {
|
||||||
|
x["dns"]["servers"].as_array().unwrap().iter().map(|s| s["tag"].as_str().unwrap()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn xray_base() -> Config {
|
||||||
|
let mut cfg = base();
|
||||||
|
cfg.proxy.outbounds[0] = outbound("nl", "trojan://pw@nl.example.com:443?sni=nl.example.com");
|
||||||
|
cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_route_modes_change_the_final_the_lists_and_the_dns_order() {
|
||||||
|
let dir = scratch("xray-modes");
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
|
||||||
|
cfg.proxy.routing.direct.geoips = vec!["cn".into()];
|
||||||
|
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
|
||||||
|
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
|
||||||
|
cfg.proxy.routing.proxy.geosites = vec!["netflix".into()];
|
||||||
|
for (mode, final_ob, has_direct, remote_first) in [
|
||||||
|
(None, "nl", true, true),
|
||||||
|
(Some(RouteMode::Whitelist), "direct", true, false),
|
||||||
|
(Some(RouteMode::AllProxy), "nl", false, true),
|
||||||
|
(Some(RouteMode::AllBypass), "direct", false, false),
|
||||||
|
] {
|
||||||
|
let state = State { route_mode: mode, ..Default::default() };
|
||||||
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], final_ob, "{mode:?}");
|
||||||
|
assert_eq!(xray_rule(&x, "direct-domain").is_some(), has_direct, "{mode:?}");
|
||||||
|
assert_eq!(xray_rule(&x, "direct-geoip").is_some(), has_direct, "{mode:?}");
|
||||||
|
// Block and the private-address safety stay in every mode.
|
||||||
|
assert_eq!(xray_rule(&x, "block-domain").unwrap()["outboundTag"], "block", "{mode:?}");
|
||||||
|
assert!(xray_rule(&x, "direct-private").is_some(), "{mode:?}");
|
||||||
|
let proxied = mode != Some(RouteMode::AllBypass);
|
||||||
|
assert_eq!(xray_rule(&x, "proxy-domain").is_some(), proxied, "{mode:?}");
|
||||||
|
assert_eq!(xray_rule(&x, "proxy-geosite").is_some(), proxied, "{mode:?}");
|
||||||
|
// The DNS server the mode prefers comes first.
|
||||||
|
assert_eq!(xray_dns_tags(&x)[0], if remote_first { "remote" } else { "local" }, "{mode:?}");
|
||||||
|
}
|
||||||
|
// The order of the lists: block ahead of direct, the geo lists of the proxy last.
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
let pos = |tag: &str| xray_rules(&x).iter().position(|r| r["ruleTag"] == tag).unwrap();
|
||||||
|
assert!(pos("proxy-domain") < pos("block-domain") && pos("block-domain") < pos("direct-domain"));
|
||||||
|
assert!(pos("direct-private") < pos("proxy-geosite") && pos("proxy-geosite") < pos("final-default"));
|
||||||
|
assert_eq!(xray_rule(&x, "proxy-geosite").unwrap()["domain"], json!(["geosite:netflix"]));
|
||||||
|
assert_eq!(xray_rule(&x, "direct-domain").unwrap()["domain"], json!(["domain:direct.example"]));
|
||||||
|
assert_eq!(x["routing"]["domainStrategy"], "IPIfNonMatch");
|
||||||
|
assert_eq!(x["routing"]["domainMatcher"], "hybrid");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_dns_follows_routing_default_and_pins_the_proxy_servers() {
|
||||||
|
let dir = scratch("xray-dns");
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
cfg.proxy.dns.remote = DnsUpstream { transport: DnsTransport::Tcp, address: "9.9.9.9".into(), port: 5353 };
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
// proxy: remote first; the copy of "local" that answers for the servers' names last.
|
||||||
|
assert_eq!(xray_dns_tags(&x), ["remote", "local", "local"]);
|
||||||
|
let servers = x["dns"]["servers"].as_array().unwrap();
|
||||||
|
assert_eq!(servers[0]["address"], "tcp://9.9.9.9");
|
||||||
|
assert_eq!(servers[0]["port"], 5353);
|
||||||
|
assert_eq!(servers[2]["domains"], json!(["full:de.example.com", "full:nl.example.com"]));
|
||||||
|
assert_eq!(servers[2]["skipFallback"], true);
|
||||||
|
assert!(servers[1].get("domains").is_none());
|
||||||
|
// The server's own queries: local direct, remote through the proxy.
|
||||||
|
assert_eq!(xray_rule(&x, "dns-upstream-direct").unwrap()["outboundTag"], "direct");
|
||||||
|
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["outboundTag"], "nl");
|
||||||
|
cfg.proxy.routing.default = RouteDefault::Direct;
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert_eq!(xray_dns_tags(&x), ["local", "remote", "local"]);
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "direct");
|
||||||
|
// DoT has no XRay counterpart.
|
||||||
|
cfg.proxy.backend = Backend::Xray;
|
||||||
|
cfg.proxy.dns.local.transport = DnsTransport::Tls;
|
||||||
|
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("tls"), "{err}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_urltest_balances_and_a_pin_leaves_one_exit() {
|
||||||
|
let dir = scratch("xray-urltest");
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
cfg.proxy.selection = Selection::Urltest;
|
||||||
|
cfg.proxy.url_test.url = "https://probe.example/204".into();
|
||||||
|
cfg.proxy.url_test.interval = "90s".into();
|
||||||
|
cfg.proxy.outbounds.push(outbound("ru", "trojan://pw@ru.example.com:443?sni=ru.example.com"));
|
||||||
|
cfg.proxy.outbounds[2].routing.domains = vec!["ru.example".into()];
|
||||||
|
cfg.proxy.selection_exclude = vec!["ru".into()];
|
||||||
|
cfg.proxy.routing.proxy.domains = vec!["proxy.example".into()];
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert_eq!(xray_tags(&x)[..3], ["proxy-suite-ob-nl", "proxy-suite-ob-de", "proxy-suite-ob-ru"]);
|
||||||
|
// The balancer takes what selection may pick, not the excluded outbound.
|
||||||
|
let candidates = json!(["proxy-suite-ob-nl", "proxy-suite-ob-de"]);
|
||||||
|
assert_eq!(x["routing"]["balancers"], json!([{ "tag": "proxy", "selector": candidates, "strategy": { "type": "leastPing" } }]));
|
||||||
|
assert_eq!(x["observatory"], json!({ "subjectSelector": candidates, "probeUrl": "https://probe.example/204", "probeInterval": "90s" }));
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["balancerTag"], "proxy");
|
||||||
|
assert_eq!(xray_rule(&x, "proxy-domain").unwrap()["balancerTag"], "proxy");
|
||||||
|
assert_eq!(xray_rule(&x, "dns-upstream-remote").unwrap()["balancerTag"], "proxy");
|
||||||
|
// An outbound's own routing names it, renamed with the rest.
|
||||||
|
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
|
||||||
|
|
||||||
|
// A pin: no balancer, no observatory, every "proxy" rule on the one exit.
|
||||||
|
let state = State { pin: Some("de".into()), ..Default::default() };
|
||||||
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
||||||
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
||||||
|
for tag in ["final-default", "proxy-domain", "dns-upstream-remote"] {
|
||||||
|
let r = xray_rule(&x, tag).unwrap();
|
||||||
|
assert_eq!(r["outboundTag"], "proxy-suite-ob-de", "{tag}");
|
||||||
|
assert!(r.get("balancerTag").is_none(), "{tag}");
|
||||||
|
}
|
||||||
|
assert_eq!(xray_rule(&x, "custom-proxy-domain").unwrap()["outboundTag"], "proxy-suite-ob-ru");
|
||||||
|
|
||||||
|
// One selectable outbound is a pin of its own.
|
||||||
|
cfg.proxy.selection_exclude = vec!["ru".into(), "de".into()];
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "proxy-suite-ob-nl");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_first_selection_takes_the_first_outbound_or_the_pin() {
|
||||||
|
let dir = scratch("xray-first");
|
||||||
|
let cfg = xray_base();
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert_eq!(xray_tags(&x), ["nl", "de", "direct", "block", "dns-out"]);
|
||||||
|
assert!(x["routing"].get("balancers").is_none() && x.get("observatory").is_none());
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "nl");
|
||||||
|
let state = State { pin: Some("de".into()), ..Default::default() };
|
||||||
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap()["outboundTag"], "de");
|
||||||
|
// Every tag stays, so a rule naming another outbound still reaches it.
|
||||||
|
let mut cfg = cfg;
|
||||||
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "nl".into(), matches: RouteMatch { ips: vec!["203.0.113.0/24".into()], geoips: vec!["us".into()], ..Default::default() }, ..Default::default() });
|
||||||
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "direct".into(), matches: RouteMatch { domains: vec!["lan.example".into()], ..Default::default() }, ..Default::default() });
|
||||||
|
let (x, _) = render_xray(&cfg, &state, &dir);
|
||||||
|
assert_eq!(xray_rule(&x, "custom-proxy-ip").unwrap()["outboundTag"], "nl");
|
||||||
|
assert_eq!(xray_rule(&x, "custom-proxy-geoip").unwrap()["ip"], json!(["geoip:us"]));
|
||||||
|
assert_eq!(xray_rule(&x, "custom-direct-domain").unwrap()["outboundTag"], "direct");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_listener_takes_a_login_and_guards_loopback() {
|
||||||
|
let dir = scratch("xray-listener");
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
let inbound = &x["inbounds"][0];
|
||||||
|
assert_eq!(inbound["tag"], "mixed-in");
|
||||||
|
assert_eq!(inbound["protocol"], "socks");
|
||||||
|
assert_eq!(inbound["listen"], "127.0.0.1");
|
||||||
|
assert_eq!(inbound["port"], 1080);
|
||||||
|
assert_eq!(inbound["settings"]["auth"], "noauth");
|
||||||
|
assert_eq!(inbound["settings"]["udp"], true);
|
||||||
|
assert_eq!(x["inbounds"].as_array().unwrap().len(), 1);
|
||||||
|
cfg.proxy.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
|
||||||
|
let (x, _) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert_eq!(x["inbounds"][0]["settings"]["auth"], "password");
|
||||||
|
assert_eq!(x["inbounds"][0]["settings"]["accounts"], json!([{ "user": "me", "pass": "pw" }]));
|
||||||
|
// Nothing reaches this host's loopback: by address or name through the listener, or from a
|
||||||
|
// name the direct outbound resolves.
|
||||||
|
assert_eq!(xray_rule(&x, "guard-loopback-ip").unwrap()["outboundTag"], "block");
|
||||||
|
assert_eq!(xray_rule(&x, "guard-loopback-domain").unwrap()["domain"], json!(["domain:localhost"]));
|
||||||
|
let direct = x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "direct").unwrap();
|
||||||
|
assert_eq!(direct["settings"]["finalRules"].as_array().unwrap().last().unwrap()["action"], "block");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_chains_and_helpers_are_xray_outbounds() {
|
||||||
|
let dir = scratch("xray-chain");
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
cfg.proxy.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
|
||||||
|
cfg.proxy.outbounds.push(Outbound { tag: "raw".into(), xray_json: Some(serde_json::from_value(json!({ "protocol": "freedom", "settings": {} })).unwrap()), ..Default::default() });
|
||||||
|
cfg.tor.enable = true;
|
||||||
|
cfg.tor.as_outbound = true;
|
||||||
|
cfg.warp.enable = true;
|
||||||
|
cfg.warp.as_outbound = Some(WarpOutboundKind::Userspace);
|
||||||
|
cfg.ssh_proxy.enable = true;
|
||||||
|
cfg.ssh_proxy.as_outbound = true;
|
||||||
|
cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 };
|
||||||
|
cfg.whitelist_bypass.enable = true;
|
||||||
|
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
|
||||||
|
cfg.proxy.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
|
||||||
|
for urltest in [false, true] {
|
||||||
|
cfg.proxy.selection = if urltest { Selection::Urltest } else { Selection::First };
|
||||||
|
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
let prefix = if urltest { "proxy-suite-ob-" } else { "" };
|
||||||
|
let ob = |tag: &str| x["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == format!("{prefix}{tag}")).unwrap_or_else(|| panic!("no {tag}: {:?}", xray_tags(&x)));
|
||||||
|
assert_eq!(ob("chained")["streamSettings"]["sockopt"]["dialerProxy"], format!("{prefix}nl"));
|
||||||
|
// The helpers' loopback SOCKS listeners, with the hop login where the service set one.
|
||||||
|
let tor = ob("tor");
|
||||||
|
assert_eq!(tor["protocol"], "socks");
|
||||||
|
assert_eq!(tor["settings"]["address"], "127.0.0.1");
|
||||||
|
assert!(tor["settings"].get("user").is_none());
|
||||||
|
assert!(ob("ssh-proxy")["settings"].get("user").is_none());
|
||||||
|
assert_eq!(ob("warp")["settings"]["user"], "hop");
|
||||||
|
assert_eq!(ob("warp")["settings"]["pass"], "hop-pass");
|
||||||
|
assert_eq!(ob("wl")["settings"]["user"], "hop");
|
||||||
|
assert_eq!(ob("raw")["protocol"], "freedom");
|
||||||
|
// Tor is for what is routed to it: not selected on its own.
|
||||||
|
assert_eq!(xray_rule(&x, "final-default").unwrap().get("balancerTag").is_some(), urltest);
|
||||||
|
if urltest {
|
||||||
|
let selector = x["routing"]["balancers"][0]["selector"].as_array().unwrap();
|
||||||
|
assert!(!selector.contains(&json!("proxy-suite-ob-tor")), "{selector:?}");
|
||||||
|
}
|
||||||
|
assert_eq!(xray_rule(&x, "tor-onion").unwrap()["outboundTag"], format!("{prefix}tor"));
|
||||||
|
assert_eq!(xray_rule(&x, "custom-block-domain").unwrap()["outboundTag"], "block");
|
||||||
|
assert!(warnings.iter().any(|w| w.contains("'gone'")), "{warnings:?}");
|
||||||
|
}
|
||||||
|
// Endpoints are sing-box's: left out, with a word.
|
||||||
|
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
|
||||||
|
let (x, warnings) = render_xray(&cfg, &State::default(), &dir);
|
||||||
|
assert!(!xray_tags(&x).contains(&"warp"));
|
||||||
|
assert!(warnings.iter().any(|w| w.contains("WARP")), "{warnings:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_zapret_direct_lists_go_direct() {
|
||||||
|
let dir = scratch("xray-zapret");
|
||||||
|
let cfg = xray_base();
|
||||||
|
let mut e = env(&dir);
|
||||||
|
e.zapret_direct = RouteMatch { domains: vec!["blocked.example".into()], ips: vec!["198.51.100.0/24".into()], ..Default::default() };
|
||||||
|
// zapret2's runtime rule-sets are sing-box's: pure XRay has no equivalent.
|
||||||
|
e.zapret2_direct_rule_set = Some("zapret.json".into());
|
||||||
|
let mut cfg = cfg;
|
||||||
|
cfg.proxy.backend = Backend::Xray;
|
||||||
|
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
|
||||||
|
let x = r.xray.unwrap();
|
||||||
|
check_xray(&x, &dir);
|
||||||
|
let domains = xray_rule(&x, "direct-domain").unwrap();
|
||||||
|
assert_eq!(domains["outboundTag"], "direct");
|
||||||
|
assert!(domains["domain"].as_array().unwrap().contains(&json!("domain:blocked.example")));
|
||||||
|
assert!(xray_rule(&x, "direct-ip").unwrap()["ip"].as_array().unwrap().contains(&json!("198.51.100.0/24")));
|
||||||
|
assert!(!x.to_string().contains("zapret.json"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xray_backend_refuses_what_it_cannot_do() {
|
||||||
|
let mut cfg = xray_base();
|
||||||
|
cfg.proxy.backend = Backend::Xray;
|
||||||
|
let refused = |cfg: &Config| -> Vec<String> {
|
||||||
|
ps_core::config::validate(cfg).into_iter().filter(|i| i.severity == Severity::Error).map(|i| i.path).collect()
|
||||||
|
};
|
||||||
|
assert!(refused(&cfg).is_empty(), "{:?}", refused(&cfg));
|
||||||
|
let mut c = cfg.clone();
|
||||||
|
c.proxy.selection = Selection::Selector;
|
||||||
|
assert!(refused(&c).contains(&"proxy.selection".to_owned()));
|
||||||
|
let mut c = cfg.clone();
|
||||||
|
c.proxy.tun.enable = true;
|
||||||
|
assert!(refused(&c).contains(&"proxy.tun.enable".to_owned()));
|
||||||
|
let mut c = cfg.clone();
|
||||||
|
c.proxy.dns.remote.transport = DnsTransport::Tls;
|
||||||
|
assert!(refused(&c).contains(&"proxy.dns".to_owned()));
|
||||||
|
let mut c = cfg.clone();
|
||||||
|
c.proxy.dns.strategy = Some(DomainStrategy::Ipv4Only);
|
||||||
|
assert!(refused(&c).contains(&"proxy.dns.strategy".to_owned()));
|
||||||
|
let mut c = cfg.clone();
|
||||||
|
c.debug.connection_log.enable = true;
|
||||||
|
assert!(refused(&c).contains(&"debug.connectionLog.enable".to_owned()));
|
||||||
|
// The TUN is refused at render too, whatever the validation was told.
|
||||||
|
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&scratch("xray-tun")), read_file: &no_files, tun: true });
|
||||||
|
assert!(r.unwrap_err().0.contains("TUN"));
|
||||||
|
}
|
||||||
@@ -69,6 +69,33 @@ enum Cmd {
|
|||||||
#[command(subcommand)]
|
#[command(subcommand)]
|
||||||
verb: Option<ComponentsVerb>,
|
verb: Option<ComponentsVerb>,
|
||||||
},
|
},
|
||||||
|
/// The kill switch: what it holds back, or lift it (off) until a tunnel is turned on, or
|
||||||
|
/// hold it again (on).
|
||||||
|
Killswitch {
|
||||||
|
#[command(subcommand)]
|
||||||
|
verb: Option<KillswitchVerb>,
|
||||||
|
},
|
||||||
|
/// Proxy Suite itself: whether a newer release is out, and installing it.
|
||||||
|
Update {
|
||||||
|
#[command(subcommand)]
|
||||||
|
verb: Option<UpdateVerb>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum KillswitchVerb {
|
||||||
|
Status,
|
||||||
|
On,
|
||||||
|
Off,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum UpdateVerb {
|
||||||
|
/// This version, and a newer release if there is one.
|
||||||
|
Check,
|
||||||
|
/// Fetch the newest release's setup program, check it and run it: the service and the app
|
||||||
|
/// stop for a moment and start again, new.
|
||||||
|
Install,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -121,6 +148,19 @@ enum ZapretVerb {
|
|||||||
Preset { name: String },
|
Preset { name: String },
|
||||||
/// Which game traffic to handle: all, tcp, udp or null.
|
/// Which game traffic to handle: all, tcp, udp or null.
|
||||||
GameFilter { filter: String },
|
GameFilter { filter: String },
|
||||||
|
/// zapret2's 16 KB cutoff probe: the networks this line cuts off, and the names that get
|
||||||
|
/// through (status), or probe the line now (probe).
|
||||||
|
Cutoff {
|
||||||
|
#[command(subcommand)]
|
||||||
|
verb: Option<CutoffVerb>,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Subcommand)]
|
||||||
|
enum CutoffVerb {
|
||||||
|
Status,
|
||||||
|
/// Probe the line now: a few minutes, thousands of short direct connections.
|
||||||
|
Probe,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Subcommand)]
|
#[derive(Subcommand)]
|
||||||
@@ -654,8 +694,60 @@ async fn auto(ctl: &Ctl, verb: Option<AutoVerb>) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The cutoff probe's findings, as upstream's `proxy-ctl zapret cutoff` prints them.
|
||||||
|
fn print_cutoff(r: &Value) {
|
||||||
|
if let Some(n) = r["note"].as_str().filter(|n| !n.is_empty()) {
|
||||||
|
println!("Note: {n}");
|
||||||
|
}
|
||||||
|
let Some(ts) = r["probed"].as_u64() else {
|
||||||
|
println!("Not probed yet.");
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
println!("Probed: {} from {}", ps_client::utc(ts), r["egress"].as_str().unwrap_or("?"));
|
||||||
|
let nets = r["networks"].as_array().cloned().unwrap_or_default();
|
||||||
|
if nets.is_empty() {
|
||||||
|
println!("Cutoff: none on this line");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
println!("Cutoff: {} network(s)", nets.len());
|
||||||
|
let fallback = if r["proxyFallback"] == true { "no name - proxy fallback" } else { "no name" };
|
||||||
|
for n in nets {
|
||||||
|
println!(" AS{:<8} {}", n["asn"].as_str().unwrap_or("?"), n["name"].as_str().unwrap_or(fallback));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cutoff(ctl: &Ctl, verb: Option<CutoffVerb>) -> Result<()> {
|
||||||
|
let probe = matches!(verb, Some(CutoffVerb::Probe));
|
||||||
|
let mut r = ctl.call(Request::ZapretCutoff { probe }).await?;
|
||||||
|
if probe {
|
||||||
|
if !ctl.json {
|
||||||
|
println!("Probing this line; this takes a few minutes...");
|
||||||
|
}
|
||||||
|
// Until the round it asked for has begun and ended.
|
||||||
|
let mut began = false;
|
||||||
|
for _ in 0..1800 {
|
||||||
|
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
|
||||||
|
r = ctl.call(Request::ZapretCutoff { probe: false }).await?;
|
||||||
|
let probing = r["probing"] == true;
|
||||||
|
began |= probing;
|
||||||
|
if began && !probing || !began && r["note"].as_str().is_some_and(|n| !n.is_empty() && !n.starts_with("probed")) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ctl.json {
|
||||||
|
ctl.print(&r);
|
||||||
|
} else if r["enabled"] != true {
|
||||||
|
println!("The cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable.");
|
||||||
|
} else {
|
||||||
|
print_cutoff(&r);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
||||||
match verb.unwrap_or(ZapretVerb::Status) {
|
match verb.unwrap_or(ZapretVerb::Status) {
|
||||||
|
ZapretVerb::Cutoff { verb } => return cutoff(ctl, verb).await,
|
||||||
ZapretVerb::Status => {
|
ZapretVerb::Status => {
|
||||||
let s = ctl.call(Request::Status).await?;
|
let s = ctl.call(Request::Status).await?;
|
||||||
let z = &s["zapret"];
|
let z = &s["zapret"];
|
||||||
@@ -702,6 +794,31 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update(ctl: &Ctl, verb: Option<UpdateVerb>) -> Result<()> {
|
||||||
|
match verb.unwrap_or(UpdateVerb::Check) {
|
||||||
|
UpdateVerb::Check => {
|
||||||
|
let r = ctl.call(Request::UpdateCheck).await?;
|
||||||
|
if ctl.json {
|
||||||
|
ctl.print(&r);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let current = r["current"].as_str().unwrap_or("?");
|
||||||
|
match r["available"].as_object() {
|
||||||
|
Some(a) => {
|
||||||
|
println!("Proxy Suite {current}; {} is out: {}", a["version"].as_str().unwrap_or("?"), a["page"].as_str().unwrap_or(""));
|
||||||
|
println!("Install it with: proxy-ctl update install");
|
||||||
|
}
|
||||||
|
None => println!("Proxy Suite {current} is the newest release."),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
UpdateVerb::Install => {
|
||||||
|
let r = ctl.call(Request::UpdateInstall).await?;
|
||||||
|
println!("Installing Proxy Suite {}: the service stops for a moment and starts again.", r["version"].as_str().unwrap_or("?"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
async fn awg(ctl: &Ctl, verb: Option<AwgVerb>) -> Result<()> {
|
async fn awg(ctl: &Ctl, verb: Option<AwgVerb>) -> Result<()> {
|
||||||
match verb.unwrap_or(AwgVerb::List) {
|
match verb.unwrap_or(AwgVerb::List) {
|
||||||
AwgVerb::List => {
|
AwgVerb::List => {
|
||||||
@@ -901,6 +1018,28 @@ async fn real_main() -> Result<()> {
|
|||||||
Cmd::Components { verb } => components(&ctl, verb).await?,
|
Cmd::Components { verb } => components(&ctl, verb).await?,
|
||||||
Cmd::Wl { verb } => wl(&ctl, verb).await?,
|
Cmd::Wl { verb } => wl(&ctl, verb).await?,
|
||||||
Cmd::Awg { verb } => awg(&ctl, verb).await?,
|
Cmd::Awg { verb } => awg(&ctl, verb).await?,
|
||||||
|
Cmd::Update { verb } => update(&ctl, verb).await?,
|
||||||
|
Cmd::Killswitch { verb } => {
|
||||||
|
let on = match verb.unwrap_or(KillswitchVerb::Status) {
|
||||||
|
KillswitchVerb::Status => None,
|
||||||
|
KillswitchVerb::On => Some(true),
|
||||||
|
KillswitchVerb::Off => Some(false),
|
||||||
|
};
|
||||||
|
let r = ctl.call(Request::KillSwitch { on }).await?;
|
||||||
|
if ctl.json {
|
||||||
|
ctl.print(&r);
|
||||||
|
} else if r["enabled"] != true {
|
||||||
|
println!("The kill switch is off (killSwitch.enable).");
|
||||||
|
} else if r["failed"] == true {
|
||||||
|
println!("The kill switch should hold, but its filters are not in place: see the service's log (proxy-ctl logs).");
|
||||||
|
} else if r["holding"] == true {
|
||||||
|
println!("The kill switch holds: what would leave past the tunnel is blocked.");
|
||||||
|
} else if r["lifted"] == true {
|
||||||
|
println!("The kill switch is lifted until a tunnel is turned on (proxy-ctl killswitch on holds it again).");
|
||||||
|
} else {
|
||||||
|
println!("The kill switch holds nothing back: no global tunnel is on.");
|
||||||
|
}
|
||||||
|
}
|
||||||
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) {
|
||||||
|
|||||||
@@ -15,9 +15,18 @@ gpui-tray = { version = "0.3", default-features = false, features = ["gpui-kit",
|
|||||||
ps-client.workspace = true
|
ps-client.workspace = true
|
||||||
ps-ipc.workspace = true
|
ps-ipc.workspace = true
|
||||||
anyhow.workspace = true
|
anyhow.workspace = true
|
||||||
|
serde.workspace = true
|
||||||
serde_json.workspace = true
|
serde_json.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
async-channel = "2"
|
async-channel = "2"
|
||||||
|
|
||||||
[target.'cfg(windows)'.dependencies]
|
[target.'cfg(windows)'.dependencies]
|
||||||
windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Registry", "Win32_Networking_WinInet"] }
|
windows-sys = { workspace = true, features = [
|
||||||
|
"Win32_Foundation",
|
||||||
|
"Win32_System_Registry",
|
||||||
|
"Win32_Networking_WinInet",
|
||||||
|
"Win32_Graphics_Dwm",
|
||||||
|
"Win32_System_Threading",
|
||||||
|
"Win32_UI_WindowsAndMessaging",
|
||||||
|
"Win32_Globalization",
|
||||||
|
] }
|
||||||
@@ -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, Video, FileUp, Route, Lock]);
|
gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock, ExternalLink, Sun, Moon]);
|
||||||
|
|
||||||
pub struct AppAssets;
|
pub struct AppAssets;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,86 @@
|
|||||||
|
//! The app's words in the user's language: English, as the code writes them, or Russian. Each
|
||||||
|
//! page keeps its Russian beside its English (its `RU` table); `tr` and `trf` look a text up,
|
||||||
|
//! and a text without a translation stays English. What the service says (its warnings and
|
||||||
|
//! errors) stays English, as `proxy-ctl` does.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::fmt::Display;
|
||||||
|
use std::sync::LazyLock;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
static RUSSIAN: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// Every page's table, and the app's own.
|
||||||
|
static TABLE: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
|
||||||
|
let tables: [&[(&str, &str)]; 15] = [
|
||||||
|
RU,
|
||||||
|
crate::model::RU,
|
||||||
|
crate::shell::RU,
|
||||||
|
crate::ui::RU,
|
||||||
|
crate::ui::widgets::RU,
|
||||||
|
crate::ui::overview::RU,
|
||||||
|
crate::ui::dpi::RU,
|
||||||
|
crate::ui::telegram::RU,
|
||||||
|
crate::ui::whitelist::RU,
|
||||||
|
crate::ui::outbounds::RU,
|
||||||
|
crate::ui::autoproxy::RU,
|
||||||
|
crate::ui::amneziawg::RU,
|
||||||
|
crate::ui::logs::RU,
|
||||||
|
crate::ui::settings::RU,
|
||||||
|
crate::ui::components::RU,
|
||||||
|
];
|
||||||
|
tables.iter().flat_map(|t| t.iter().copied()).collect()
|
||||||
|
});
|
||||||
|
|
||||||
|
pub fn set_russian(on: bool) {
|
||||||
|
RUSSIAN.store(on, Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn russian() -> bool {
|
||||||
|
RUSSIAN.load(Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether Windows' own language (the user's display language) is Russian; elsewhere, the
|
||||||
|
/// locale's.
|
||||||
|
pub fn system_russian() -> bool {
|
||||||
|
#[cfg(windows)]
|
||||||
|
{
|
||||||
|
// SAFETY: no arguments.
|
||||||
|
let id = unsafe { windows_sys::Win32::Globalization::GetUserDefaultUILanguage() };
|
||||||
|
// The primary language: LANG_RUSSIAN.
|
||||||
|
id & 0x3ff == 0x19
|
||||||
|
}
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
{
|
||||||
|
["LC_ALL", "LC_MESSAGES", "LANG"].iter().find_map(|v| std::env::var(v).ok().filter(|s| !s.is_empty())).is_some_and(|s| s.starts_with("ru"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `en` in the user's language.
|
||||||
|
pub fn tr(en: &'static str) -> &'static str {
|
||||||
|
if !russian() {
|
||||||
|
return en;
|
||||||
|
}
|
||||||
|
TABLE.get(en).copied().unwrap_or(en)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `en` in the user's language, each `{}` in it taking the next of `args`.
|
||||||
|
pub fn trf(en: &'static str, args: &[&dyn Display]) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut args = args.iter();
|
||||||
|
let mut parts = tr(en).split("{}");
|
||||||
|
if let Some(first) = parts.next() {
|
||||||
|
out.push_str(first);
|
||||||
|
}
|
||||||
|
for part in parts {
|
||||||
|
match args.next() {
|
||||||
|
Some(a) => out.push_str(&a.to_string()),
|
||||||
|
None => out.push_str("{}"),
|
||||||
|
}
|
||||||
|
out.push_str(part);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The app's own words, outside the pages.
|
||||||
|
pub const RU: &[(&str, &str)] = &[];
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
//! proxy-suite: the desktop app. A client of the service, as proxy-ctl is: it shows what the
|
//! proxy-suite: the desktop app. A client of the service, as proxy-ctl is: it shows what the
|
||||||
//! service runs and sends it each change, which the service checks and applies. The app keeps
|
//! service runs and sends it each change, which the service checks and applies. The app keeps
|
||||||
//! nothing of its own.
|
//! only its own look, and whether it looks for updates (prefs.rs).
|
||||||
//!
|
//!
|
||||||
//! proxy-suite [--socket ADDRESS] [--hidden] (the service's pipe or socket, as proxy-ctl takes
|
//! proxy-suite [--socket ADDRESS] [--hidden] (the service's pipe or socket, as proxy-ctl takes
|
||||||
//! it; --hidden starts in the tray)
|
//! it; --hidden starts in the tray)
|
||||||
@@ -9,7 +9,9 @@
|
|||||||
|
|
||||||
mod assets;
|
mod assets;
|
||||||
mod bridge;
|
mod bridge;
|
||||||
|
mod i18n;
|
||||||
mod model;
|
mod model;
|
||||||
|
mod prefs;
|
||||||
mod shell;
|
mod shell;
|
||||||
mod sysproxy;
|
mod sysproxy;
|
||||||
mod ui;
|
mod ui;
|
||||||
@@ -46,6 +48,11 @@ fn main() {
|
|||||||
// The window closing does not end the app: the tray does (shell.rs).
|
// The window closing does not end the app: the tray does (shell.rs).
|
||||||
gpui_kit::application().with_assets(assets::AppAssets).with_quit_mode(QuitMode::Explicit).run(move |cx| {
|
gpui_kit::application().with_assets(assets::AppAssets).with_quit_mode(QuitMode::Explicit).run(move |cx| {
|
||||||
gpui_kit::init(cx);
|
gpui_kit::init(cx);
|
||||||
|
let prefs = prefs::load();
|
||||||
|
i18n::set_russian(prefs.language.russian());
|
||||||
|
cx.set_global(prefs);
|
||||||
|
prefs::tune_dark(cx);
|
||||||
|
prefs::apply_theme(None, cx);
|
||||||
let model = cx.new(|cx| model::Model::new(bridge, cx));
|
let model = cx.new(|cx| model::Model::new(bridge, cx));
|
||||||
shell::start(model, !args.hidden, cx);
|
shell::start(model, !args.hidden, cx);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! What the app knows of the service, refreshed while it runs, and the changes it asks of it.
|
//! What the app knows of the service, refreshed while it runs, and the changes it asks of it.
|
||||||
//! Views read it and call its methods; it tells them what came of each change ([`Outcome`]).
|
//! Views read it and call its methods; it tells them what came of each change ([`Outcome`]).
|
||||||
|
|
||||||
use std::time::Duration;
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
use anyhow::{Result, bail};
|
use anyhow::{Result, bail};
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
@@ -10,6 +10,7 @@ use ps_ipc::Request;
|
|||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use crate::bridge::Bridge;
|
use crate::bridge::Bridge;
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
|
|
||||||
/// What a change came to.
|
/// What a change came to.
|
||||||
pub enum Outcome {
|
pub enum Outcome {
|
||||||
@@ -17,6 +18,20 @@ pub enum Outcome {
|
|||||||
Failed(SharedString),
|
Failed(SharedString),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether a newer release of Proxy Suite is out, as the service last found.
|
||||||
|
#[derive(Clone, PartialEq)]
|
||||||
|
pub enum Update {
|
||||||
|
/// Not looked for (yet, or the preference says not to).
|
||||||
|
Unknown,
|
||||||
|
Checking,
|
||||||
|
Newest,
|
||||||
|
Available { version: SharedString, page: SharedString },
|
||||||
|
/// Its setup program being fetched and checked (`started`: and then run, which closes
|
||||||
|
/// this app and opens the new one), since `at`.
|
||||||
|
Installing { version: SharedString, started: bool, at: Instant },
|
||||||
|
Failed(SharedString),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
pub enum Connection {
|
pub enum Connection {
|
||||||
Connecting,
|
Connecting,
|
||||||
@@ -36,12 +51,21 @@ pub struct Model {
|
|||||||
tg_links: Vec<SharedString>,
|
tg_links: Vec<SharedString>,
|
||||||
/// Changes sent and not yet answered.
|
/// Changes sent and not yet answered.
|
||||||
pending: usize,
|
pending: usize,
|
||||||
|
update: Update,
|
||||||
|
/// The version the service runs, from its last update check.
|
||||||
|
version: SharedString,
|
||||||
|
/// When updates were last looked for.
|
||||||
|
update_checked: Option<Instant>,
|
||||||
_poll: Task<()>,
|
_poll: Task<()>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EventEmitter<Outcome> for Model {}
|
impl EventEmitter<Outcome> for Model {}
|
||||||
|
|
||||||
const POLL: Duration = Duration::from_secs(2);
|
const POLL: Duration = Duration::from_secs(2);
|
||||||
|
/// How often a running app looks for updates again (when the preference has it look).
|
||||||
|
const UPDATE_CHECK: Duration = Duration::from_secs(24 * 3600);
|
||||||
|
/// How long the setup has to close this app once it runs.
|
||||||
|
const SETUP_WAIT: Duration = Duration::from_secs(5 * 60);
|
||||||
|
|
||||||
impl Model {
|
impl Model {
|
||||||
pub fn new(bridge: Bridge, cx: &mut Context<Self>) -> Self {
|
pub fn new(bridge: Bridge, cx: &mut Context<Self>) -> Self {
|
||||||
@@ -58,6 +82,16 @@ impl Model {
|
|||||||
if let Some(Ok(o)) = outbounds {
|
if let Some(Ok(o)) = outbounds {
|
||||||
m.outbounds = o;
|
m.outbounds = o;
|
||||||
}
|
}
|
||||||
|
// A setup that ran and left this app running did not replace it.
|
||||||
|
if let Update::Installing { version, started: true, at } = &m.update
|
||||||
|
&& at.elapsed() >= SETUP_WAIT
|
||||||
|
{
|
||||||
|
m.update = Update::Failed(trf("the setup of {} did not finish (the service's log, on the Logs page, may say why)", &[version]).into());
|
||||||
|
}
|
||||||
|
let due = m.update_checked.is_none_or(|t| t.elapsed() >= UPDATE_CHECK);
|
||||||
|
if m.connection == Connection::Up && due && cx.global::<crate::prefs::Prefs>().check_updates {
|
||||||
|
m.check_update(cx);
|
||||||
|
}
|
||||||
cx.notify();
|
cx.notify();
|
||||||
});
|
});
|
||||||
if alive.is_err() {
|
if alive.is_err() {
|
||||||
@@ -76,6 +110,9 @@ impl Model {
|
|||||||
presets: Vec::new(),
|
presets: Vec::new(),
|
||||||
tg_links: Vec::new(),
|
tg_links: Vec::new(),
|
||||||
pending: 0,
|
pending: 0,
|
||||||
|
update: Update::Unknown,
|
||||||
|
version: env!("CARGO_PKG_VERSION").into(),
|
||||||
|
update_checked: None,
|
||||||
_poll: poll,
|
_poll: poll,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -128,6 +165,74 @@ impl Model {
|
|||||||
self.pending > 0
|
self.pending > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn update(&self) -> &Update {
|
||||||
|
&self.update
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn version(&self) -> &SharedString {
|
||||||
|
&self.version
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asks the service whether a newer release is out.
|
||||||
|
pub fn check_update(&mut self, cx: &mut Context<Self>) {
|
||||||
|
if matches!(self.update, Update::Checking | Update::Installing { .. }) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.update = Update::Checking;
|
||||||
|
self.update_checked = Some(Instant::now());
|
||||||
|
cx.notify();
|
||||||
|
let job = self.bridge.call(Request::UpdateCheck);
|
||||||
|
cx.spawn(async move |this, cx| {
|
||||||
|
let r = job.await;
|
||||||
|
this.update(cx, |m, cx| {
|
||||||
|
m.update = match r {
|
||||||
|
Ok(r) => {
|
||||||
|
if let Some(v) = r["current"].as_str() {
|
||||||
|
m.version = v.to_owned().into();
|
||||||
|
}
|
||||||
|
match r["available"].as_object() {
|
||||||
|
Some(a) => Update::Available {
|
||||||
|
version: a.get("version").and_then(Value::as_str).unwrap_or("?").to_owned().into(),
|
||||||
|
page: a.get("page").and_then(Value::as_str).unwrap_or_default().to_owned().into(),
|
||||||
|
},
|
||||||
|
None => Update::Newest,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => Update::Failed(format!("{e:#}").into()),
|
||||||
|
};
|
||||||
|
cx.notify();
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Has the service fetch the newest release and run its setup, which replaces the service
|
||||||
|
/// and this app, and opens the new one.
|
||||||
|
pub fn install_update(&mut self, cx: &mut Context<Self>) {
|
||||||
|
let Update::Available { version, .. } = &self.update else { return };
|
||||||
|
let version = version.clone();
|
||||||
|
self.update = Update::Installing { version: version.clone(), started: false, at: Instant::now() };
|
||||||
|
cx.notify();
|
||||||
|
let job = self.bridge.call(Request::UpdateInstall);
|
||||||
|
cx.spawn(async move |this, cx| {
|
||||||
|
let r = job.await;
|
||||||
|
this.update(cx, |m, cx| {
|
||||||
|
match r {
|
||||||
|
Ok(_) => m.update = Update::Installing { version, started: true, at: Instant::now() },
|
||||||
|
Err(e) => {
|
||||||
|
let e: SharedString = format!("{e:#}").into();
|
||||||
|
cx.emit(Outcome::Failed(trf("Updating to {}: {}", &[&version, &e]).into()));
|
||||||
|
m.update = Update::Failed(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cx.notify();
|
||||||
|
})
|
||||||
|
.ok();
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}
|
||||||
|
|
||||||
/// Status and outbounds now, rather than at the next round.
|
/// Status and outbounds now, rather than at the next round.
|
||||||
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
pub fn refresh(&mut self, cx: &mut Context<Self>) {
|
||||||
let status = self.bridge.call(Request::Status);
|
let status = self.bridge.call(Request::Status);
|
||||||
@@ -218,7 +323,7 @@ impl Model {
|
|||||||
what,
|
what,
|
||||||
async move {
|
async move {
|
||||||
if let Some(e) = job.await?.apply_error {
|
if let Some(e) = job.await?.apply_error {
|
||||||
bail!("saved, but not applied: {e}");
|
bail!(trf("saved, but not applied: {}", &[&e]));
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
},
|
||||||
@@ -243,7 +348,7 @@ impl Model {
|
|||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
if let Some(e) = saved.apply_error {
|
if let Some(e) = saved.apply_error {
|
||||||
bail!("saved, but not applied: {e}");
|
bail!(trf("saved, but not applied: {}", &[&e]));
|
||||||
}
|
}
|
||||||
bridge.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
|
bridge.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
|
||||||
} else {
|
} else {
|
||||||
@@ -251,6 +356,15 @@ impl Model {
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
};
|
};
|
||||||
self.track(if on { "The proxy is on" } else { "The proxy is off" }, job, cx);
|
self.track(tr(if on { "The proxy is on" } else { "The proxy is off" }), job, cx);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The changes' words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("the setup of {} did not finish (the service's log, on the Logs page, may say why)", "установка {} не завершилась (причину может подсказать журнал службы на странице «Журналы»)"),
|
||||||
|
("Updating to {}: {}", "Обновление до {}: {}"),
|
||||||
|
("saved, but not applied: {}", "сохранено, но не применено: {}"),
|
||||||
|
("The proxy is on", "Локальный прокси включён"),
|
||||||
|
("The proxy is off", "Локальный прокси выключен"),
|
||||||
|
];
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
//! The app's own preferences, each user's: its language and look, and whether it looks for
|
||||||
|
//! updates. All else is the service's configuration.
|
||||||
|
//!
|
||||||
|
//! In `%APPDATA%\ProxySuite\app.json` (elsewhere `$XDG_CONFIG_HOME/proxy-suite/app.json`).
|
||||||
|
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use gpui_kit::component::{Theme, ThemeMode};
|
||||||
|
use gpui_kit::*;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "lowercase")]
|
||||||
|
pub enum ThemeChoice {
|
||||||
|
/// Windows' own: light or dark as apps are set to be (Settings → Personalization → Colors).
|
||||||
|
#[default]
|
||||||
|
System,
|
||||||
|
Light,
|
||||||
|
Dark,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThemeChoice {
|
||||||
|
pub const ALL: [(ThemeChoice, &'static str); 3] = [(ThemeChoice::System, "As Windows"), (ThemeChoice::Light, "Light"), (ThemeChoice::Dark, "Dark")];
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub enum Language {
|
||||||
|
/// Windows' own display language: Russian when it is, else English.
|
||||||
|
#[default]
|
||||||
|
#[serde(rename = "system")]
|
||||||
|
System,
|
||||||
|
#[serde(rename = "en")]
|
||||||
|
English,
|
||||||
|
#[serde(rename = "ru")]
|
||||||
|
Russian,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Language {
|
||||||
|
/// Each named in its own language.
|
||||||
|
pub const ALL: [(Language, &'static str); 3] = [(Language::System, "As Windows"), (Language::English, "English"), (Language::Russian, "Русский")];
|
||||||
|
|
||||||
|
pub fn russian(self) -> bool {
|
||||||
|
match self {
|
||||||
|
Language::System => crate::i18n::system_russian(),
|
||||||
|
Language::English => false,
|
||||||
|
Language::Russian => true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase", default)]
|
||||||
|
pub struct Prefs {
|
||||||
|
pub language: Language,
|
||||||
|
pub theme: ThemeChoice,
|
||||||
|
/// At start and daily, ask the service whether a newer release is out.
|
||||||
|
pub check_updates: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Prefs {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { language: Language::System, theme: ThemeChoice::System, check_updates: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Global for Prefs {}
|
||||||
|
|
||||||
|
fn path() -> Option<PathBuf> {
|
||||||
|
if cfg!(windows) {
|
||||||
|
std::env::var_os("APPDATA").map(|d| PathBuf::from(d).join("ProxySuite").join("app.json"))
|
||||||
|
} else {
|
||||||
|
let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
|
||||||
|
Some(base.join("proxy-suite").join("app.json"))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The saved preferences, or the defaults where there are none (or they do not read).
|
||||||
|
pub fn load() -> Prefs {
|
||||||
|
path().and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Prefs {
|
||||||
|
fn save(&self) {
|
||||||
|
let Some(path) = path() else { return };
|
||||||
|
if let Some(dir) = path.parent() {
|
||||||
|
let _ = std::fs::create_dir_all(dir);
|
||||||
|
}
|
||||||
|
if let Err(e) = std::fs::write(&path, serde_json::to_vec_pretty(self).unwrap_or_default()) {
|
||||||
|
eprintln!("proxy-suite: saving {}: {e}", path.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Changes the preferences, saves them, and shows what changed.
|
||||||
|
pub fn change(cx: &mut App, edit: impl FnOnce(&mut Prefs)) {
|
||||||
|
let before = cx.global::<Prefs>().clone();
|
||||||
|
edit(cx.global_mut::<Prefs>());
|
||||||
|
let now = cx.global::<Prefs>().clone();
|
||||||
|
now.save();
|
||||||
|
if now.theme != before.theme {
|
||||||
|
apply_theme(None, cx);
|
||||||
|
}
|
||||||
|
if now.language.russian() != before.language.russian() {
|
||||||
|
crate::i18n::set_russian(now.language.russian());
|
||||||
|
// What the pages made once (placeholders, lists) is made again, in the new words.
|
||||||
|
crate::shell::reopen_window(cx);
|
||||||
|
}
|
||||||
|
cx.refresh_windows();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Controls that are off all but vanish on the dark theme's near-black page: its switch, a
|
||||||
|
/// near-black thumb on a #404040 track, gets a lighter track (the thumb stays dark: it is the
|
||||||
|
/// on switch's too, on a white track); unchecked radio buttons and checkboxes, and text
|
||||||
|
/// fields, a lighter edge than #2f2f2f.
|
||||||
|
pub fn tune_dark(cx: &mut App) {
|
||||||
|
let theme = Theme::global_mut(cx);
|
||||||
|
let mut dark = (*theme.dark_theme).clone();
|
||||||
|
dark.colors.switch = Some("#737373".into());
|
||||||
|
dark.colors.input = Some("#525252".into());
|
||||||
|
theme.dark_theme = Rc::new(dark);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The theme the preference picks: Windows' appearance (the window's, when there is one), or
|
||||||
|
/// the one chosen.
|
||||||
|
pub fn apply_theme(window: Option<&mut Window>, cx: &mut App) {
|
||||||
|
match cx.global::<Prefs>().theme {
|
||||||
|
ThemeChoice::System => Theme::sync_system_appearance(window, cx),
|
||||||
|
ThemeChoice::Light => Theme::change(ThemeMode::Light, window, cx),
|
||||||
|
ThemeChoice::Dark => Theme::change(ThemeMode::Dark, window, cx),
|
||||||
|
}
|
||||||
|
#[cfg(windows)]
|
||||||
|
title_bars(Theme::global(cx).is_dark());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Windows draws the window's title bar, light or dark as Windows' own appearance is (GPUI sets
|
||||||
|
/// it so): as the theme chosen instead. The app's windows are its main thread's.
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn title_bars(dark: bool) {
|
||||||
|
use windows_sys::Win32::Foundation::{HWND, LPARAM};
|
||||||
|
use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_IMMERSIVE_DARK_MODE, DwmSetWindowAttribute};
|
||||||
|
use windows_sys::Win32::System::Threading::GetCurrentThreadId;
|
||||||
|
use windows_sys::Win32::UI::WindowsAndMessaging::EnumThreadWindows;
|
||||||
|
|
||||||
|
unsafe extern "system" fn each(hwnd: HWND, dark: LPARAM) -> windows_sys::core::BOOL {
|
||||||
|
let value: windows_sys::core::BOOL = (dark != 0).into();
|
||||||
|
// SAFETY: a window of this thread, and a BOOL as long as said.
|
||||||
|
unsafe { DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE as u32, (&value as *const windows_sys::core::BOOL).cast(), 4) };
|
||||||
|
1
|
||||||
|
}
|
||||||
|
// SAFETY: the callback only reads its arguments.
|
||||||
|
unsafe { EnumThreadWindows(GetCurrentThreadId(), Some(each), dark as LPARAM) };
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
//! are, with switches in its menu; quitting. Closing the window leaves the app in the tray; with
|
//! are, with switches in its menu; quitting. Closing the window leaves the app in the tray; with
|
||||||
//! no tray (a desktop without one), closing it quits.
|
//! no tray (a desktop without one), closing it quits.
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
use gpui_tray::{Icon, Tray};
|
use gpui_tray::{Icon, Tray};
|
||||||
use ps_client::edits;
|
use ps_client::edits;
|
||||||
@@ -15,7 +16,8 @@ actions!(proxy_suite, [OpenWindow, ToggleProxy, ToggleDpi, ToggleTelegram, Quit]
|
|||||||
|
|
||||||
struct Shell {
|
struct Shell {
|
||||||
model: Entity<Model>,
|
model: Entity<Model>,
|
||||||
window: Option<WindowHandle<AppView>>,
|
/// The window (gpui-kit's root holds the view: no handle typed by it) and its view.
|
||||||
|
window: Option<(AnyWindowHandle, Entity<AppView>)>,
|
||||||
tray: Option<Tray>,
|
tray: Option<Tray>,
|
||||||
/// The icon's colour and the tooltip now: the tray is only touched when they change (a
|
/// The icon's colour and the tooltip now: the tray is only touched when they change (a
|
||||||
/// menu rebuilt while open would close).
|
/// menu rebuilt while open would close).
|
||||||
@@ -24,13 +26,15 @@ struct Shell {
|
|||||||
system_proxy: SystemProxy,
|
system_proxy: SystemProxy,
|
||||||
/// The system proxy's last failure, said once.
|
/// The system proxy's last failure, said once.
|
||||||
system_proxy_error: Option<String>,
|
system_proxy_error: Option<String>,
|
||||||
|
/// The window is closing to open again (the language changed): not a reason to quit.
|
||||||
|
reopening: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Global for Shell {}
|
impl Global for Shell {}
|
||||||
|
|
||||||
pub fn start(model: Entity<Model>, open: bool, cx: &mut App) {
|
pub fn start(model: Entity<Model>, open: bool, cx: &mut App) {
|
||||||
cx.on_action(open_window).on_action(toggle_proxy).on_action(toggle_dpi).on_action(toggle_telegram).on_action(quit);
|
cx.on_action(open_window).on_action(toggle_proxy).on_action(toggle_dpi).on_action(toggle_telegram).on_action(quit);
|
||||||
cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "", tooltip: String::new(), system_proxy: SystemProxy::default(), system_proxy_error: None });
|
cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "", tooltip: String::new(), system_proxy: SystemProxy::default(), system_proxy_error: None, reopening: false });
|
||||||
|
|
||||||
let mut builder = Tray::builder().tooltip("Proxy Suite").on_activate(OpenWindow).menu(menu);
|
let mut builder = Tray::builder().tooltip("Proxy Suite").on_activate(OpenWindow).menu(menu);
|
||||||
if let Some(icon) = icon("#6b7280", cx) {
|
if let Some(icon) = icon("#6b7280", cx) {
|
||||||
@@ -42,7 +46,7 @@ pub fn start(model: Entity<Model>, open: bool, cx: &mut App) {
|
|||||||
Err(e) => eprintln!("proxy-suite: no tray icon ({e}); closing the window quits"),
|
Err(e) => eprintln!("proxy-suite: no tray icon ({e}); closing the window quits"),
|
||||||
}
|
}
|
||||||
cx.on_window_closed(|cx, _| {
|
cx.on_window_closed(|cx, _| {
|
||||||
if cx.global::<Shell>().tray.is_none() && cx.windows().is_empty() {
|
if cx.global::<Shell>().tray.is_none() && cx.windows().is_empty() && !cx.global::<Shell>().reopening {
|
||||||
cx.quit();
|
cx.quit();
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -120,10 +124,10 @@ fn refresh(cx: &mut App) {
|
|||||||
}
|
}
|
||||||
let (s, up) = status(cx);
|
let (s, up) = status(cx);
|
||||||
let tip = if up {
|
let tip = if up {
|
||||||
let on = |v: &Value| if *v == true { "on" } else { "off" };
|
let on = |v: &Value| if *v == true { tr("on") } else { tr("off") };
|
||||||
format!("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", on(&s["proxy"]["on"]), on(&s["zapret"]["enabled"]), on(&s["tgWsProxy"]["enabled"]))
|
trf("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", &[&on(&s["proxy"]["on"]), &on(&s["zapret"]["enabled"]), &on(&s["tgWsProxy"]["enabled"])])
|
||||||
} else {
|
} else {
|
||||||
"Proxy Suite — the service is not running".into()
|
tr("Proxy Suite — the service is not running").into()
|
||||||
};
|
};
|
||||||
// The tooltip says what the menu's checks do: the same news.
|
// The tooltip says what the menu's checks do: the same news.
|
||||||
if tip != cx.global::<Shell>().tooltip {
|
if tip != cx.global::<Shell>().tooltip {
|
||||||
@@ -136,18 +140,44 @@ fn refresh(cx: &mut App) {
|
|||||||
fn menu(cx: &mut App) -> Vec<MenuItem> {
|
fn menu(cx: &mut App) -> Vec<MenuItem> {
|
||||||
let (s, up) = status(cx);
|
let (s, up) = status(cx);
|
||||||
vec![
|
vec![
|
||||||
MenuItem::action("Open Proxy Suite", OpenWindow),
|
MenuItem::action(tr("Open Proxy Suite"), OpenWindow),
|
||||||
MenuItem::separator(),
|
MenuItem::separator(),
|
||||||
MenuItem::action("Local proxy", ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
|
MenuItem::action(tr("Local proxy"), ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
|
||||||
MenuItem::action("DPI bypass", ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
|
MenuItem::action(tr("DPI bypass"), ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
|
||||||
MenuItem::action("Telegram proxy", ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
|
MenuItem::action(tr("Telegram proxy"), ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
|
||||||
MenuItem::separator(),
|
MenuItem::separator(),
|
||||||
MenuItem::action("Quit", Quit),
|
MenuItem::action(tr("Quit"), Quit),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The window, if open, closed and opened again on the same page: what its pages made once
|
||||||
|
/// (lists, placeholders) is made again, in the language just chosen. The tray's menu and
|
||||||
|
/// tooltip follow too.
|
||||||
|
pub fn reopen_window(cx: &mut App) {
|
||||||
|
cx.global_mut::<Shell>().tooltip.clear();
|
||||||
|
cx.defer(|cx| {
|
||||||
|
refresh(cx);
|
||||||
|
let Some((window, view)) = cx.global::<Shell>().window.clone() else { return };
|
||||||
|
let page = view.read(cx).page();
|
||||||
|
cx.global_mut::<Shell>().reopening = true;
|
||||||
|
let closed = window.update(cx, |_, window, _| window.remove_window()).is_ok();
|
||||||
|
cx.global_mut::<Shell>().window = None;
|
||||||
|
if closed {
|
||||||
|
cx.defer(move |cx| {
|
||||||
|
open_window(&OpenWindow, cx);
|
||||||
|
if let Some((_, view)) = cx.global::<Shell>().window.clone() {
|
||||||
|
view.update(cx, |v, cx| v.show(page, cx));
|
||||||
|
}
|
||||||
|
cx.global_mut::<Shell>().reopening = false;
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
cx.global_mut::<Shell>().reopening = false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
fn open_window(_: &OpenWindow, cx: &mut App) {
|
fn open_window(_: &OpenWindow, cx: &mut App) {
|
||||||
if let Some(window) = cx.global::<Shell>().window
|
if let Some((window, _)) = cx.global::<Shell>().window
|
||||||
&& window.update(cx, |_, window, _| window.activate_window()).is_ok()
|
&& window.update(cx, |_, window, _| window.activate_window()).is_ok()
|
||||||
{
|
{
|
||||||
return;
|
return;
|
||||||
@@ -161,7 +191,7 @@ fn open_window(_: &OpenWindow, cx: &mut App) {
|
|||||||
..Default::default()
|
..Default::default()
|
||||||
};
|
};
|
||||||
match gpui_kit::open_window(options, cx, |window, cx| cx.new(|cx| AppView::new(model, window, cx))) {
|
match gpui_kit::open_window(options, cx, |window, cx| cx.new(|cx| AppView::new(model, window, cx))) {
|
||||||
Ok((window, _)) => cx.global_mut::<Shell>().window = window.downcast(),
|
Ok((window, view)) => cx.global_mut::<Shell>().window = Some((window, view)),
|
||||||
Err(e) => eprintln!("proxy-suite: opening the window: {e}"),
|
Err(e) => eprintln!("proxy-suite: opening the window: {e}"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -177,7 +207,7 @@ fn toggle_dpi(_: &ToggleDpi, cx: &mut App) {
|
|||||||
let on = model.read(cx).status()["zapret"]["enabled"] != true;
|
let on = model.read(cx).status()["zapret"]["enabled"] != true;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
|
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_zapret_enabled(c, on);
|
edits::set_zapret_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -192,7 +222,7 @@ fn toggle_telegram(_: &ToggleTelegram, cx: &mut App) {
|
|||||||
let on = model.read(cx).status()["tgWsProxy"]["enabled"] != true;
|
let on = model.read(cx).status()["tgWsProxy"]["enabled"] != true;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
|
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_tg_ws_proxy_enabled(c, on);
|
edits::set_tg_ws_proxy_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -209,3 +239,18 @@ fn quit(_: &Quit, cx: &mut App) {
|
|||||||
}
|
}
|
||||||
cx.quit();
|
cx.quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tray's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("on", "вкл."),
|
||||||
|
("off", "выкл."),
|
||||||
|
("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", "Proxy Suite — прокси: {}, обход DPI: {}, прокси для Telegram: {}"),
|
||||||
|
("Proxy Suite — the service is not running", "Proxy Suite — служба не запущена"),
|
||||||
|
("Open Proxy Suite", "Открыть Proxy Suite"),
|
||||||
|
("Local proxy", "Локальный прокси"),
|
||||||
|
("Quit", "Выйти"),
|
||||||
|
("The DPI bypass is on", "Обход DPI включён"),
|
||||||
|
("The DPI bypass is off", "Обход DPI выключен"),
|
||||||
|
("The Telegram proxy is on", "Прокси для Telegram включён"),
|
||||||
|
("The Telegram proxy is off", "Прокси для Telegram выключен"),
|
||||||
|
];
|
||||||
@@ -12,11 +12,13 @@ use gpui_kit::component::radio::RadioGroup;
|
|||||||
use gpui_kit::component::switch::Switch;
|
use gpui_kit::component::switch::Switch;
|
||||||
use gpui_kit::component::tag::Tag;
|
use gpui_kit::component::tag::Tag;
|
||||||
use gpui_kit::component::*;
|
use gpui_kit::component::*;
|
||||||
|
use gpui_kit::prelude::FluentBuilder as _;
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
use ps_client::edits;
|
use ps_client::edits;
|
||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use super::widgets::{card, hint, page, state_tag};
|
use super::widgets::{card, hint, page, state_tag};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
|
||||||
@@ -37,7 +39,7 @@ pub struct AmneziaWgPage {
|
|||||||
impl AmneziaWgPage {
|
impl AmneziaWgPage {
|
||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
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 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 text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder(tr("vpn://… from AmneziaVPN, or a .conf: [Interface] …")));
|
||||||
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
|
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
|
||||||
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
|
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
|
||||||
this.load(cx);
|
this.load(cx);
|
||||||
@@ -63,7 +65,7 @@ impl AmneziaWgPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
|
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
|
||||||
let what = format!("{name}: {}", if on { "tunnel up" } else { "tunnel down" });
|
let what = if on { trf("{}: tunnel up", &[&name]) } else { trf("{}: tunnel down", &[&name]) };
|
||||||
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
|
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
@@ -102,12 +104,12 @@ impl AmneziaWgPage {
|
|||||||
}
|
}
|
||||||
self.name.update(cx, |s, cx| s.set_value("", window, cx));
|
self.name.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
self.text.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");
|
let what = trf("AmneziaWG profile '{}' added", &[&name]);
|
||||||
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_awg_profile(c, &name, &text, kind), cx));
|
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>) {
|
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));
|
self.model.update(cx, |m, cx| m.edit(trf("AmneziaWG profile '{}' removed", &[&name]), move |c| edits::remove_awg_profile(c, &name), cx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,7 +118,7 @@ impl Render for AmneziaWgPage {
|
|||||||
let m = self.model.read(cx);
|
let m = self.model.read(cx);
|
||||||
let body = page("AmneziaWG", cx);
|
let body = page("AmneziaWG", cx);
|
||||||
if m.config().is_null() {
|
if m.config().is_null() {
|
||||||
return body.child(hint("Waiting for the service…", cx));
|
return body.child(hint(tr("Waiting for the service…"), cx));
|
||||||
}
|
}
|
||||||
let on = m.config()["amneziaWg"]["enable"] == true;
|
let on = m.config()["amneziaWg"]["enable"] == true;
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
@@ -124,7 +126,7 @@ impl Render for AmneziaWgPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "AmneziaWG is on" } else { "AmneziaWG is off" },
|
if on { tr("AmneziaWG is on") } else { tr("AmneziaWG is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["amneziaWg", "enable"], on.into());
|
edits::set_path(c, &["amneziaWg", "enable"], on.into());
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -134,26 +136,26 @@ impl Render for AmneziaWgPage {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint(
|
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.",
|
tr("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,
|
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);
|
let mut profiles = card(tr("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 {
|
match &self.list {
|
||||||
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
|
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
|
||||||
Ok(l) => {
|
Ok(l) => {
|
||||||
let list = l["profiles"].as_array().cloned().unwrap_or_default();
|
let list = l["profiles"].as_array().cloned().unwrap_or_default();
|
||||||
if list.is_empty() {
|
if list.is_empty() {
|
||||||
profiles = profiles.child(hint("None yet: add one below.", cx));
|
profiles = profiles.child(hint(tr("None yet: add one below."), cx));
|
||||||
}
|
}
|
||||||
for (i, p) in list.iter().enumerate() {
|
for (i, p) in list.iter().enumerate() {
|
||||||
let name = p["name"].as_str().unwrap_or("").to_owned();
|
let name = p["name"].as_str().unwrap_or("").to_owned();
|
||||||
let vpn = p["kind"] == "vpn";
|
let vpn = p["kind"] == "vpn";
|
||||||
let state = p["state"].as_str().unwrap_or("").to_owned();
|
let state = p["state"].as_str().unwrap_or("").to_owned();
|
||||||
let kind = match p["kind"].as_str().unwrap_or("") {
|
let kind = match p["kind"].as_str().unwrap_or("") {
|
||||||
"vpn" => Tag::info().child("system VPN"),
|
"vpn" => Tag::info().child(tr("system VPN")),
|
||||||
"userspace" => Tag::secondary().child("outbound"),
|
"userspace" => Tag::secondary().child(tr("outbound")),
|
||||||
_ => Tag::secondary().child("outbound (WireGuard)"),
|
_ => Tag::secondary().child(tr("outbound (WireGuard)")),
|
||||||
};
|
};
|
||||||
let mut line = div()
|
let mut line = div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
@@ -161,13 +163,14 @@ impl Render for AmneziaWgPage {
|
|||||||
.items_center()
|
.items_center()
|
||||||
.child(div().font_medium().child(name.clone()))
|
.child(div().font_medium().child(name.clone()))
|
||||||
.child(kind)
|
.child(kind)
|
||||||
.child(if state == "windows-only" { Tag::secondary().child("Windows only") } else { state_tag(&state) })
|
// An outbound's state is "outbound" while AmneziaWG is on: its kind says so.
|
||||||
|
.when(state != "outbound", |d| d.child(if state == "windows-only" { Tag::secondary().child(tr("Windows only")) } else { state_tag(&state) }))
|
||||||
.child(div().flex_1());
|
.child(div().flex_1());
|
||||||
if vpn {
|
if vpn {
|
||||||
let (n1, n2) = (name.clone(), name.clone());
|
let (n1, n2) = (name.clone(), name.clone());
|
||||||
let running = matches!(state.as_str(), "active" | "activating");
|
let running = matches!(state.as_str(), "active" | "activating");
|
||||||
line = line
|
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(Button::new(("awg-log", i)).small().ghost().label(tr("Log")).on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
|
||||||
.child(
|
.child(
|
||||||
Switch::new(("awg-on", i))
|
Switch::new(("awg-on", i))
|
||||||
.checked(running)
|
.checked(running)
|
||||||
@@ -180,7 +183,7 @@ impl Render for AmneziaWgPage {
|
|||||||
let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line);
|
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) {
|
match self.logs.get(&name) {
|
||||||
Some(Ok(lines)) => {
|
Some(Ok(lines)) => {
|
||||||
let text = if lines.is_empty() { "(no log yet)".to_owned() } else { lines.join("\n") };
|
let text = if lines.is_empty() { tr("(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));
|
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)),
|
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
|
||||||
@@ -191,16 +194,44 @@ impl Render for AmneziaWgPage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| label)).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
|
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| tr(label))).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
|
||||||
this.kind = *ix;
|
this.kind = *ix;
|
||||||
cx.notify();
|
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)
|
let add = card(tr("Add a profile"), Some(Button::new("awg-add").small().primary().icon(IconName::Plus).label(tr("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(div().v_flex().gap_1().child(div().text_sm().child(tr("Name (also the adapter's)"))).child(Input::new(&self.name)))
|
||||||
.child(kinds)
|
.child(kinds)
|
||||||
.child(Textarea::new(&self.text))
|
.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));
|
.child(hint(tr("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)
|
body.child(about).child(profiles).child(add)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("vpn://… from AmneziaVPN, or a .conf: [Interface] …", "vpn://… из AmneziaVPN или .conf: [Interface] …"),
|
||||||
|
("{}: tunnel up", "{}: туннель запущен"),
|
||||||
|
("{}: tunnel down", "{}: туннель остановлен"),
|
||||||
|
("AmneziaWG profile '{}' added", "Профиль AmneziaWG «{}» добавлен"),
|
||||||
|
("AmneziaWG profile '{}' removed", "Профиль AmneziaWG «{}» удалён"),
|
||||||
|
("Waiting for the service…", "Ожидание службы…"),
|
||||||
|
("AmneziaWG is on", "AmneziaWG включён"),
|
||||||
|
("AmneziaWG is off", "AmneziaWG выключен"),
|
||||||
|
("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.", "WireGuard с обфускацией AmneziaVPN. Профиль для всей системы — это отдельный VPN (сетевой адаптер, его маршруты и DNS); если единственный узел (peer) забирает весь трафик, он также блокирует всё, что пошло бы мимо туннеля. Профиль-выход — ещё один выход для прокси, остальное не меняется."),
|
||||||
|
("Profiles", "Профили"),
|
||||||
|
("None yet: add one below.", "Пока нет: добавьте ниже."),
|
||||||
|
("system VPN", "VPN для всей системы"),
|
||||||
|
("outbound", "выход прокси"),
|
||||||
|
("outbound (WireGuard)", "выход прокси (WireGuard)"),
|
||||||
|
("Windows only", "Только Windows"),
|
||||||
|
("Log", "Журнал"),
|
||||||
|
("(no log yet)", "(журнала пока нет)"),
|
||||||
|
("System-wide VPN", "VPN для всей системы"),
|
||||||
|
("Outbound (AmneziaWG)", "Выход (AmneziaWG)"),
|
||||||
|
("Outbound (plain WireGuard)", "Выход (обычный WireGuard)"),
|
||||||
|
("Add a profile", "Добавить профиль"),
|
||||||
|
("Add", "Добавить"),
|
||||||
|
("Name (also the adapter's)", "Имя (также имя адаптера)"),
|
||||||
|
("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.", "Ссылка или .conf остаётся в конфигурации службы, которую читаете только вы и администраторы. Запуск при входе в систему (автозапуск), конечная точка (endpoint) и остальное — в «Настройках», в разделе amneziaWg.profiles."),
|
||||||
|
];
|
||||||
@@ -16,7 +16,8 @@ use ps_client::edits;
|
|||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
use super::widgets::{card, hint, page};
|
use super::widgets::{card, hint, page, Inactive as _};
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
|
||||||
pub struct AutoProxyPage {
|
pub struct AutoProxyPage {
|
||||||
@@ -38,7 +39,7 @@ pub struct AutoProxyPage {
|
|||||||
impl AutoProxyPage {
|
impl AutoProxyPage {
|
||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
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 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 exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder(tr("intranet.example — one per line")));
|
||||||
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
|
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
|
||||||
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
|
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
|
||||||
this.sync(window, cx);
|
this.sync(window, cx);
|
||||||
@@ -99,7 +100,7 @@ impl AutoProxyPage {
|
|||||||
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
|
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();
|
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() {
|
if site.is_empty() {
|
||||||
window.push_notification(Notification::error("Type a site first: example.com"), cx);
|
window.push_notification(Notification::error(tr("Type a site first: example.com")), cx);
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
Some(site)
|
Some(site)
|
||||||
@@ -126,11 +127,11 @@ impl AutoProxyPage {
|
|||||||
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let Some(site) = self.site(window, cx) else { return };
|
let Some(site) = self.site(window, cx) else { return };
|
||||||
let site = site.split('/').next().unwrap_or("").to_owned();
|
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));
|
self.model.update(cx, |m, cx| m.request(trf("{}: probed now, routed if it needs it", &[&site]), Request::AutoLearn { hosts: vec![site] }, cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn forget(&mut self, domain: Option<String>, cx: &mut Context<Self>) {
|
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 what = domain.as_ref().map_or(tr("Everything learned is forgotten").to_owned(), |d| trf("{} is forgotten", &[d]));
|
||||||
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
|
let job = self.model.read(cx).bridge().call(Request::AutoForget { domain });
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
@@ -145,7 +146,7 @@ impl AutoProxyPage {
|
|||||||
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
|
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 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 {
|
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);
|
window.push_notification(Notification::error(trf("“{}” is not a speed in KiB/s (0 turns it off)", &[&slow_text])), cx);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
|
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
|
||||||
@@ -173,7 +174,7 @@ impl Render for AutoProxyPage {
|
|||||||
let a = m.config()["proxy"]["autoProxy"].clone();
|
let a = m.config()["proxy"]["autoProxy"].clone();
|
||||||
let body = page("autoProxy", cx);
|
let body = page("autoProxy", cx);
|
||||||
if m.config().is_null() {
|
if m.config().is_null() {
|
||||||
return body.child(hint("Waiting for the service…", cx));
|
return body.child(hint(tr("Waiting for the service…"), cx));
|
||||||
}
|
}
|
||||||
let list = self.list.clone();
|
let list = self.list.clone();
|
||||||
let on = a["enable"] == true;
|
let on = a["enable"] == true;
|
||||||
@@ -183,7 +184,7 @@ impl Render for AutoProxyPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "autoProxy is on" } else { "autoProxy is off" },
|
if on { tr("autoProxy is on") } else { tr("autoProxy is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
|
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -194,20 +195,20 @@ impl Render for AutoProxyPage {
|
|||||||
});
|
});
|
||||||
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
|
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
|
||||||
let state = match (on, running) {
|
let state = match (on, running) {
|
||||||
(false, _) => Tag::secondary().child("off"),
|
(false, _) => Tag::secondary().child(tr("off")),
|
||||||
(true, false) => Tag::warning().child("waiting for the local proxy"),
|
(true, false) => Tag::warning().child(tr("waiting for the local proxy")),
|
||||||
(true, true) => Tag::success().child("running"),
|
(true, true) => Tag::success().child(tr("running")),
|
||||||
};
|
};
|
||||||
let about = card("autoProxy", Some(enable.into_any_element()), cx)
|
let about = card("autoProxy", Some(enable.into_any_element()), cx)
|
||||||
.child(div().h_flex().child(state))
|
.child(div().h_flex().child(state))
|
||||||
.child(hint(
|
.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.",
|
tr("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,
|
cx,
|
||||||
));
|
));
|
||||||
|
|
||||||
let probing = self.probing;
|
let probing = self.probing;
|
||||||
let mut try_card = card("Probe or learn a site", None, cx)
|
let mut try_card = card(tr("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(hint(tr("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it."), cx))
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
@@ -217,29 +218,29 @@ impl Render for AutoProxyPage {
|
|||||||
Button::new("ap-probe")
|
Button::new("ap-probe")
|
||||||
.small()
|
.small()
|
||||||
.icon(IconName::Gauge)
|
.icon(IconName::Gauge)
|
||||||
.label(if probing { "Probing…" } else { "Probe" })
|
.label(if probing { tr("Probing…") } else { tr("Probe") })
|
||||||
.disabled(probing || !running)
|
.inactive(probing || !running, cx)
|
||||||
.on_click(cx.listener(|this, _, window, cx| this.probe(window, cx))),
|
.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)))),
|
.child(Button::new("ap-learn").small().primary().icon(IconName::Plus).label(tr("Learn")).inactive(!running, cx).on_click(cx.listener(|this, _, window, cx| this.learn(window, cx)))),
|
||||||
);
|
);
|
||||||
match &self.probe {
|
match &self.probe {
|
||||||
Some(Ok(p)) => {
|
Some(Ok(p)) => {
|
||||||
let verdict = p["verdict"].as_str().unwrap_or("");
|
let verdict = p["verdict"].as_str().unwrap_or("");
|
||||||
let text = match verdict {
|
let text = match verdict {
|
||||||
"ok" => "Reachable directly: nothing to do".to_owned(),
|
"ok" => tr("Reachable directly: nothing to do").to_owned(),
|
||||||
"destination" => format!("Blocked directly: routed through {}", p["exit"].as_str().unwrap_or("an exit")),
|
"destination" => trf("Blocked directly: routed through {}", &[&p["exit"].as_str().unwrap_or(tr("an exit"))]),
|
||||||
"censor" => "Cut on the way: zapret's to fix, left direct".to_owned(),
|
"censor" => tr("Cut on the way: zapret's to fix, left direct").to_owned(),
|
||||||
"both-fail" => "Fails through every exit: not a block".to_owned(),
|
"both-fail" => tr("Fails through every exit: not a block").to_owned(),
|
||||||
"unreachable" => "No exit reaches it at all".to_owned(),
|
"unreachable" => tr("No exit reaches it at all").to_owned(),
|
||||||
v => v.to_owned(),
|
v => v.to_owned(),
|
||||||
};
|
};
|
||||||
try_card = try_card.child(div().font_medium().child(text));
|
try_card = try_card.child(div().font_medium().child(text));
|
||||||
for r in p["rows"].as_array().into_iter().flatten() {
|
for r in p["rows"].as_array().into_iter().flatten() {
|
||||||
let f = &r["fetch"];
|
let f = &r["fetch"];
|
||||||
let what = match f["status"].as_u64() {
|
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()),
|
Some(s) => trf("{}, {} bytes{}", &[&s, &f["bytes"], &f["block"].as_str().filter(|b| !b.is_empty()).map(|b| trf(", {} page", &[&b])).unwrap_or_default()]),
|
||||||
None => format!("no answer ({})", f["error"].as_str().unwrap_or("")),
|
None => trf("no answer ({})", &[&f["error"].as_str().unwrap_or("")]),
|
||||||
};
|
};
|
||||||
let judgement = r["judgement"].as_str().unwrap_or("");
|
let judgement = r["judgement"].as_str().unwrap_or("");
|
||||||
let tag = match judgement {
|
let tag = match judgement {
|
||||||
@@ -262,13 +263,13 @@ impl Render for AutoProxyPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let mut routed = card(
|
let mut routed = card(
|
||||||
"Routed sites",
|
tr("Routed sites"),
|
||||||
Some(
|
Some(
|
||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
|
.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))))
|
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label(tr("Forget all")).on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
|
||||||
.into_any_element(),
|
.into_any_element(),
|
||||||
),
|
),
|
||||||
cx,
|
cx,
|
||||||
@@ -278,34 +279,32 @@ impl Render for AutoProxyPage {
|
|||||||
Ok(l) => {
|
Ok(l) => {
|
||||||
let domains = l["domains"].as_array().cloned().unwrap_or_default();
|
let domains = l["domains"].as_array().cloned().unwrap_or_default();
|
||||||
if domains.is_empty() {
|
if domains.is_empty() {
|
||||||
routed = routed.child(hint("Nothing routed yet.", cx));
|
routed = routed.child(hint(tr("Nothing routed yet."), cx));
|
||||||
}
|
}
|
||||||
for (i, d) in domains.iter().enumerate() {
|
for (i, d) in domains.iter().enumerate() {
|
||||||
let domain = d["domain"].as_str().unwrap_or("").to_owned();
|
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 why = if d["verdict"] == "slow" { Tag::warning().child(tr("slow")) } else { Tag::danger().child(tr("blocked")) };
|
||||||
let forget = domain.clone();
|
let forget = domain.clone();
|
||||||
routed = routed.child(
|
routed = routed.child(
|
||||||
row(cx)
|
row(cx)
|
||||||
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
|
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
|
||||||
.child(why)
|
.child(why)
|
||||||
.child(div().w(px(160.)).truncate().text_sm().child(format!("via {}", d["exit"].as_str().unwrap_or(""))))
|
.child(div().w(px(160.)).truncate().text_sm().child(trf("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)))),
|
.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);
|
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
|
||||||
routed = routed.child(hint(
|
routed = routed.child(hint(
|
||||||
format!(
|
trf(
|
||||||
"{} site(s) judged; {censored} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
|
"{} site(s) judged; {} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
|
||||||
l["hostsJudged"].as_u64().unwrap_or(0),
|
&[&l["hostsJudged"].as_u64().unwrap_or(0), &censored, &l["backlog"].as_u64().unwrap_or(0), &l["slowWaiting"].as_u64().unwrap_or(0)],
|
||||||
l["backlog"].as_u64().unwrap_or(0),
|
|
||||||
l["slowWaiting"].as_u64().unwrap_or(0)
|
|
||||||
),
|
),
|
||||||
cx,
|
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));
|
let mut exits = card(tr("Exits"), None, cx).child(hint(tr("Probed one per network first. One that two sites refused is bad, and probed last."), cx));
|
||||||
if let Ok(l) = &list {
|
if let Ok(l) = &list {
|
||||||
for e in l["exits"].as_array().into_iter().flatten() {
|
for e in l["exits"].as_array().into_iter().flatten() {
|
||||||
let bad = e["bad"] == true;
|
let bad = e["bad"] == true;
|
||||||
@@ -317,22 +316,69 @@ impl Render for AutoProxyPage {
|
|||||||
e["ip"].as_str().unwrap_or(""),
|
e["ip"].as_str().unwrap_or(""),
|
||||||
e["asn"].as_str().unwrap_or("")
|
e["asn"].as_str().unwrap_or("")
|
||||||
)))
|
)))
|
||||||
.child(if bad { Tag::danger().child("bad") } else { Tag::success().child("ok") }),
|
.child(if bad { Tag::danger().child(tr("bad")) } else { Tag::success().child(tr("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)
|
let options = card(tr("Options"), Some(Button::new("ap-save").small().label(tr("Save")).on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()), cx)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_4()
|
.gap_4()
|
||||||
.items_start()
|
.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().flex_1().child(div().text_sm().child(tr("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(div().v_flex().gap_1().w(px(220.)).child(div().text_sm().child(tr("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));
|
.child(hint(tr("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy."), cx));
|
||||||
|
|
||||||
body.child(about).child(try_card).child(routed).child(exits).child(options)
|
body.child(about).child(try_card).child(routed).child(exits).child(options)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("intranet.example — one per line", "intranet.example — по одному в строке"),
|
||||||
|
("Type a site first: example.com", "Сначала введите сайт: example.com"),
|
||||||
|
("{}: probed now, routed if it needs it", "{}: проверен сейчас, будет направлен, если нужно"),
|
||||||
|
("Everything learned is forgotten", "Всё изученное забыто"),
|
||||||
|
("{} is forgotten", "{}: забыт"),
|
||||||
|
("“{}” is not a speed in KiB/s (0 turns it off)", "«{}» — не скорость в КиБ/с (0 отключает)"),
|
||||||
|
("Waiting for the service…", "Ожидание службы…"),
|
||||||
|
("autoProxy is on", "autoProxy включён"),
|
||||||
|
("autoProxy is off", "autoProxy выключен"),
|
||||||
|
("off", "выкл."),
|
||||||
|
("waiting for the local proxy", "ждёт локальный прокси"),
|
||||||
|
("running", "работает"),
|
||||||
|
("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.", "Проверяет сайты, к которым ваши приложения обращаются напрямую, через каждый выход, начиная с прямого. Сайт, заблокированный напрямую, но доступный через выход, направляется через него; сайт, который напрямую открывается медленно, можно перенести на выход, где он быстрее. Блокировки, которые под силу zapret, остаются напрямую."),
|
||||||
|
("Probe or learn a site", "Проверить или изучить сайт"),
|
||||||
|
("Probe: how it answers through each exit, nothing changed. Learn: probe it now and route it if it needs it.", "Проверить: как сайт отвечает через каждый выход, ничего не меняется. Изучить: проверить сейчас и направить через выход, если нужно."),
|
||||||
|
("Probing…", "Проверка…"),
|
||||||
|
("Probe", "Проверить"),
|
||||||
|
("Learn", "Изучить"),
|
||||||
|
("Reachable directly: nothing to do", "Доступен напрямую: делать ничего не нужно"),
|
||||||
|
("Blocked directly: routed through {}", "Заблокирован напрямую: направлен через {}"),
|
||||||
|
("an exit", "выход"),
|
||||||
|
("Cut on the way: zapret's to fix, left direct", "Обрывается по пути: это для zapret, оставлен напрямую"),
|
||||||
|
("Fails through every exit: not a block", "Не открывается ни через один выход: это не блокировка"),
|
||||||
|
("No exit reaches it at all", "Ни один выход до него не доходит"),
|
||||||
|
("{}, {} bytes{}", "{}, байт: {}{}"),
|
||||||
|
(", {} page", ", страница: {}"),
|
||||||
|
("no answer ({})", "нет ответа ({})"),
|
||||||
|
("Routed sites", "Направленные сайты"),
|
||||||
|
("Forget all", "Забыть все"),
|
||||||
|
("Nothing routed yet.", "Пока ничего не направлено."),
|
||||||
|
("slow", "медленный"),
|
||||||
|
("blocked", "заблокирован"),
|
||||||
|
("via {}", "через {}"),
|
||||||
|
("{} site(s) judged; {} left to zapret; {} waiting to be probed; {} crawling, to be moved.", "Оценено сайтов: {}; оставлено zapret: {}; ждут проверки: {}; медленных, будут перенесены: {}."),
|
||||||
|
("Exits", "Выходы"),
|
||||||
|
("Probed one per network first. One that two sites refused is bad, and probed last.", "Сначала проверяется по одному выходу из каждой сети. Выход, от которого отказались два сайта, считается плохим и проверяется последним."),
|
||||||
|
("bad", "плохой"),
|
||||||
|
("ok", "в порядке"),
|
||||||
|
("Options", "Параметры"),
|
||||||
|
("Save", "Сохранить"),
|
||||||
|
("Never probe or route (with their subdomains)", "Никогда не проверять и не направлять (вместе с поддоменами)"),
|
||||||
|
("Move sites slower than (KiB/s, 0: never)", "Переносить сайты медленнее (КиБ/с, 0: никогда)"),
|
||||||
|
("Everything else (interval, exits, ports) is in Settings, under proxy.autoProxy.", "Всё остальное (интервал, выходы, порты) — в настройках, в разделе proxy.autoProxy."),
|
||||||
|
];
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Components: the programs the service runs, the version each should be and the one
|
//! Components: the programs the service runs, the version each should be and the one
|
||||||
//! installed; fetching them again (an administrator's call, which the service enforces).
|
//! installed; fetching them again (an administrator's call, which the service enforces).
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::button::Button;
|
use gpui_kit::component::button::Button;
|
||||||
use gpui_kit::component::tag::Tag;
|
use gpui_kit::component::tag::Tag;
|
||||||
@@ -9,7 +10,7 @@ use gpui_kit::*;
|
|||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::widgets::{card, hint, page};
|
use super::widgets::{card, hint, page, Inactive as _};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
|
||||||
pub struct ComponentsPage {
|
pub struct ComponentsPage {
|
||||||
@@ -41,7 +42,7 @@ impl ComponentsPage {
|
|||||||
fn install(&mut self, names: Vec<String>, cx: &mut Context<Self>) {
|
fn install(&mut self, names: Vec<String>, cx: &mut Context<Self>) {
|
||||||
self.installing = true;
|
self.installing = true;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
let what = if names.is_empty() { "Components installed".to_owned() } else { format!("{} installed", names.join(", ")) };
|
let what = if names.is_empty() { tr("Components installed").to_owned() } else { trf("{} installed", &[&names.join(", ")]) };
|
||||||
let job = self.model.read(cx).bridge().call(Request::ComponentsInstall { names });
|
let job = self.model.read(cx).bridge().call(Request::ComponentsInstall { names });
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
@@ -66,17 +67,17 @@ impl Render for ComponentsPage {
|
|||||||
let actions = div()
|
let actions = div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(Button::new("comp-reload").small().icon(IconName::RefreshCw).label("Reload").on_click(cx.listener(|this, _, _, cx| this.load(cx))))
|
.child(Button::new("comp-reload").small().icon(IconName::RefreshCw).label(tr("Reload")).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
|
||||||
.child(
|
.child(
|
||||||
Button::new("comp-install")
|
Button::new("comp-install")
|
||||||
.small()
|
.small()
|
||||||
.icon(IconName::Download)
|
.icon(IconName::Download)
|
||||||
.label(if self.installing { "Installing…" } else { "Fetch all again" })
|
.label(if self.installing { tr("Installing…") } else { tr("Fetch all again") })
|
||||||
.disabled(self.installing)
|
.inactive(self.installing, cx)
|
||||||
.on_click(cx.listener(|this, _, _, cx| this.install(Vec::new(), cx))),
|
.on_click(cx.listener(|this, _, _, cx| this.install(Vec::new(), cx))),
|
||||||
);
|
);
|
||||||
let mut list = card("Programs", Some(actions.into_any_element()), cx).child(hint(
|
let mut list = card(tr("Programs"), Some(actions.into_any_element()), cx).child(hint(
|
||||||
"Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal.",
|
tr("Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal."),
|
||||||
cx,
|
cx,
|
||||||
));
|
));
|
||||||
match &self.list {
|
match &self.list {
|
||||||
@@ -86,9 +87,9 @@ impl Render for ComponentsPage {
|
|||||||
let want = c["version"].as_str().unwrap_or("");
|
let want = c["version"].as_str().unwrap_or("");
|
||||||
let have = c["installed"].as_str();
|
let have = c["installed"].as_str();
|
||||||
let state = match have {
|
let state = match have {
|
||||||
Some(v) if v == want => Tag::success().child("installed"),
|
Some(v) if v == want => Tag::success().child(tr("installed")),
|
||||||
Some(v) => Tag::warning().child(format!("{v} installed")),
|
Some(v) => Tag::warning().child(trf("{} installed", &[&v])),
|
||||||
None => Tag::danger().child("missing"),
|
None => Tag::danger().child(tr("missing")),
|
||||||
};
|
};
|
||||||
list = list.child(
|
list = list.child(
|
||||||
div()
|
div()
|
||||||
@@ -106,6 +107,20 @@ impl Render for ComponentsPage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
page("Components", cx).child(list)
|
page(tr("Components"), cx).child(list)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("Components installed", "Компоненты установлены"),
|
||||||
|
("{} installed", "Установлено: {}"),
|
||||||
|
("Reload", "Перечитать"),
|
||||||
|
("Installing…", "Устанавливается…"),
|
||||||
|
("Fetch all again", "Загрузить все заново"),
|
||||||
|
("Programs", "Программы"),
|
||||||
|
("Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal.", "Каждая программа закреплена по версии и хешу и проверяется перед запуском. Для повторной загрузки нужен администратор: запустите приложение от его имени или выполните proxy-ctl components install в терминале администратора."),
|
||||||
|
("installed", "установлена"),
|
||||||
|
("missing", "отсутствует"),
|
||||||
|
("Components", "Компоненты"),
|
||||||
|
];
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies; and the
|
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies and its 16 KB
|
||||||
//! sites it handles beside the lists it comes with.
|
//! cutoff probe; and the sites it handles beside the lists it comes with.
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::button::Button;
|
use gpui_kit::component::button::Button;
|
||||||
use gpui_kit::component::input::{Textarea, TextareaState};
|
use gpui_kit::component::input::{Textarea, TextareaState};
|
||||||
use gpui_kit::component::radio::RadioGroup;
|
use gpui_kit::component::radio::RadioGroup;
|
||||||
@@ -9,12 +12,15 @@ use gpui_kit::component::switch::Switch;
|
|||||||
use gpui_kit::component::*;
|
use gpui_kit::component::*;
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
use ps_client::edits;
|
use ps_client::edits;
|
||||||
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::widgets::{card, hint, page, state_tag};
|
use super::widgets::{Inactive as _, card, hint, page, state_tag};
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
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.
|
||||||
@@ -36,14 +42,17 @@ pub struct DpiPage {
|
|||||||
/// The engine and lists the text areas were last filled from: news from the service
|
/// The engine and lists the text areas were last filled from: news from the service
|
||||||
/// replaces what the user has not changed, never what they have.
|
/// replaces what the user has not changed, never what they have.
|
||||||
shown: (String, String, String),
|
shown: (String, String, String),
|
||||||
|
/// The cutoff probe's findings (`zapret-cutoff`), followed while it probes.
|
||||||
|
cutoff: Value,
|
||||||
|
_cutoff_poll: Option<Task<()>>,
|
||||||
_subscriptions: Vec<Subscription>,
|
_subscriptions: Vec<Subscription>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DpiPage {
|
impl DpiPage {
|
||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let preset = cx.new(|cx| SelectState::new(Vec::<SharedString>::new(), None, window, cx).searchable(true));
|
let preset = cx.new(|cx| SelectState::new(Vec::<SharedString>::new(), None, window, cx).searchable(true));
|
||||||
let domains = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder("example.com — one per line"));
|
let domains = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder(tr("example.com — one per line")));
|
||||||
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder("bank.example — one per line"));
|
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder(tr("bank.example — one per line")));
|
||||||
let subscriptions = vec![
|
let subscriptions = vec![
|
||||||
cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx)),
|
cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx)),
|
||||||
cx.subscribe_in(&preset, window, |this, _, event: &SelectEvent<Vec<SharedString>>, _, cx| {
|
cx.subscribe_in(&preset, window, |this, _, event: &SelectEvent<Vec<SharedString>>, _, cx| {
|
||||||
@@ -51,7 +60,7 @@ impl DpiPage {
|
|||||||
let name = name.to_string();
|
let name = name.to_string();
|
||||||
this.model.update(cx, |m, cx| {
|
this.model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
format!("Preset: {name}"),
|
trf("Preset: {}", &[&name]),
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_zapret_preset(c, &name);
|
edits::set_zapret_preset(c, &name);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -62,11 +71,100 @@ impl DpiPage {
|
|||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
let mut this = Self { model, preset, presets: Vec::new(), domains, exclude, shown: Default::default(), _subscriptions: subscriptions };
|
let mut this = Self { model, preset, presets: Vec::new(), domains, exclude, shown: Default::default(), cutoff: Value::Null, _cutoff_poll: None, _subscriptions: subscriptions };
|
||||||
this.sync(window, cx);
|
this.sync(window, cx);
|
||||||
|
this.follow_cutoff(false, cx);
|
||||||
this
|
this
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The cutoff probe's findings, now and (`probe`: after starting it) every two seconds while
|
||||||
|
/// it probes.
|
||||||
|
fn follow_cutoff(&mut self, probe: bool, cx: &mut Context<Self>) {
|
||||||
|
let bridge = self.model.read(cx).bridge().clone();
|
||||||
|
let model = self.model.clone();
|
||||||
|
self._cutoff_poll = Some(cx.spawn(async move |this, cx| {
|
||||||
|
let mut probe = probe;
|
||||||
|
loop {
|
||||||
|
let r = bridge.call(Request::ZapretCutoff { probe }).await;
|
||||||
|
let failed = probe && r.is_err();
|
||||||
|
probe = false;
|
||||||
|
let probing = r.as_ref().is_ok_and(|v| v["probing"] == true);
|
||||||
|
let alive = this.update(cx, |this, cx| {
|
||||||
|
match r {
|
||||||
|
Ok(v) => this.cutoff = v,
|
||||||
|
Err(e) if failed => model.update(cx, |_, cx| cx.emit(crate::model::Outcome::Failed(trf("The cutoff probe: {}", &[&format!("{e:#}")]).into()))),
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
cx.notify();
|
||||||
|
});
|
||||||
|
if alive.is_err() || !probing {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cx.background_executor().timer(Duration::from_secs(2)).await;
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// zapret2's 16 KB cutoff probe: on or off, what it found, probe now.
|
||||||
|
fn cutoff_card(&self, config: &Value, cx: &mut Context<Self>) -> Div {
|
||||||
|
let c = &self.cutoff;
|
||||||
|
let on = config["zapret"]["zapret2"]["cutoff"]["enable"] == true;
|
||||||
|
let probing = c["probing"] == true;
|
||||||
|
let probe = Button::new("cutoff-probe")
|
||||||
|
.small()
|
||||||
|
.icon(IconName::Gauge)
|
||||||
|
.label(if probing { tr("Probing…") } else { tr("Probe now") })
|
||||||
|
.inactive(probing || !on, cx)
|
||||||
|
.on_click(cx.listener(|this, _, _, cx| this.follow_cutoff(true, cx)));
|
||||||
|
let mut card = card(tr("16 KB cutoff"), Some(probe.into_any_element()), cx)
|
||||||
|
.child(hint(
|
||||||
|
tr("Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections."),
|
||||||
|
cx,
|
||||||
|
))
|
||||||
|
.child(self.option_switch("cutoff-on", tr("Probe this line"), &["zapret", "zapret2", "cutoff", "enable"], config))
|
||||||
|
.child(self.option_switch(
|
||||||
|
"cutoff-fallback",
|
||||||
|
tr("Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)"),
|
||||||
|
&["zapret", "zapret2", "cutoff", "proxyFallback"],
|
||||||
|
config,
|
||||||
|
));
|
||||||
|
if !on || c.is_null() {
|
||||||
|
return card;
|
||||||
|
}
|
||||||
|
if c["installed"] != true {
|
||||||
|
return card.child(hint(tr("z2k-detect, the probe, is not installed (the zapret2-extras component)."), cx));
|
||||||
|
}
|
||||||
|
if let Some(n) = c["note"].as_str().filter(|n| !n.is_empty() && (probing || !n.starts_with("probed"))) {
|
||||||
|
card = card.child(hint(n.to_owned(), cx));
|
||||||
|
}
|
||||||
|
let Some(ts) = c["probed"].as_u64() else {
|
||||||
|
return card.child(hint(tr("Not probed yet: the first probe runs five minutes after the service starts."), cx));
|
||||||
|
};
|
||||||
|
let nets = c["networks"].as_array().cloned().unwrap_or_default();
|
||||||
|
let named = nets.iter().filter(|n| n["name"].is_string()).count();
|
||||||
|
let summary = match nets.len() {
|
||||||
|
0 => trf("Probed {} from {}: no network is cut off on this line.", &[&ps_client::utc(ts), &c["egress"].as_str().unwrap_or("?")]),
|
||||||
|
n => trf("Probed {} from {}: {} network(s) cut off, {} with a name that gets through.", &[&ps_client::utc(ts), &c["egress"].as_str().unwrap_or("?"), &n, &named]),
|
||||||
|
};
|
||||||
|
card = card.child(div().text_sm().child(summary));
|
||||||
|
let fallback = if c["proxyFallback"] == true { tr("through the proxy") } else { tr("no name") };
|
||||||
|
const SHOWN: usize = 8;
|
||||||
|
for n in nets.iter().take(SHOWN) {
|
||||||
|
card = card.child(
|
||||||
|
div()
|
||||||
|
.h_flex()
|
||||||
|
.gap_2()
|
||||||
|
.text_sm()
|
||||||
|
.child(div().w(px(110.)).font_family("monospace").text_color(cx.theme().muted_foreground).child(format!("AS{}", n["asn"].as_str().unwrap_or("?"))))
|
||||||
|
.child(n["name"].as_str().unwrap_or(fallback).to_owned()),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if nets.len() > SHOWN {
|
||||||
|
card = card.child(hint(trf("and {} more (proxy-ctl zapret cutoff).", &[&(nets.len() - SHOWN)]), cx));
|
||||||
|
}
|
||||||
|
card
|
||||||
|
}
|
||||||
|
|
||||||
fn engine(config: &Value) -> String {
|
fn engine(config: &Value) -> String {
|
||||||
config["zapret"]["engine"].as_str().unwrap_or("zapret-discord-youtube").to_owned()
|
config["zapret"]["engine"].as_str().unwrap_or("zapret-discord-youtube").to_owned()
|
||||||
}
|
}
|
||||||
@@ -115,7 +213,7 @@ impl DpiPage {
|
|||||||
self.shown.1 = domains_text;
|
self.shown.1 = domains_text;
|
||||||
self.shown.2 = exclude_text;
|
self.shown.2 = exclude_text;
|
||||||
let engine = Self::engine(self.model.read(cx).config());
|
let engine = Self::engine(self.model.read(cx).config());
|
||||||
self.model.update(cx, |m, cx| m.edit("Sites saved", move |c| edits::set_zapret_sites(c, &engine, &domains, &exclude), cx));
|
self.model.update(cx, |m, cx| m.edit(tr("Sites saved"), move |c| edits::set_zapret_sites(c, &engine, &domains, &exclude), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A switch for one option of the configuration, by its path.
|
/// A switch for one option of the configuration, by its path.
|
||||||
@@ -129,7 +227,7 @@ impl DpiPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
format!("{label}: {}", if on { "on" } else { "off" }),
|
format!("{label}: {}", tr(if on { "on" } else { "off" })),
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, path, on.into());
|
edits::set_path(c, path, on.into());
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -147,9 +245,9 @@ impl Render for DpiPage {
|
|||||||
let status = m.status()["zapret"].clone();
|
let status = m.status()["zapret"].clone();
|
||||||
let config = m.config().clone();
|
let config = m.config().clone();
|
||||||
let engine = Self::engine(&config);
|
let engine = Self::engine(&config);
|
||||||
let body = page("DPI bypass", cx);
|
let body = page(tr("DPI bypass"), cx);
|
||||||
if config.is_null() {
|
if config.is_null() {
|
||||||
return body.child(hint("Waiting for the service…", cx));
|
return body.child(hint(tr("Waiting for the service…"), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
@@ -157,7 +255,7 @@ impl Render for DpiPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
|
tr(if on { "The DPI bypass is on" } else { "The DPI bypass is off" }),
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_zapret_enabled(c, on);
|
edits::set_zapret_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -168,11 +266,11 @@ impl Render for DpiPage {
|
|||||||
});
|
});
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
let engines = RadioGroup::horizontal("engine")
|
let engines = RadioGroup::horizontal("engine")
|
||||||
.children(ENGINES.map(|(_, label)| label))
|
.children(ENGINES.map(|(_, label)| tr(label)))
|
||||||
.selected_index(ENGINES.iter().position(|(e, _)| *e == engine))
|
.selected_index(ENGINES.iter().position(|(e, _)| *e == engine))
|
||||||
.on_change(move |ix, _, cx| {
|
.on_change(move |ix, _, cx| {
|
||||||
let (engine, label) = ENGINES[*ix];
|
let (engine, label) = ENGINES[*ix];
|
||||||
model.update(cx, |m, cx| m.edit(format!("Engine: {label}"), move |c| edits::set_zapret_engine(c, engine), cx));
|
model.update(cx, |m, cx| m.edit(trf("Engine: {}", &[&tr(label)]), move |c| edits::set_zapret_engine(c, engine), cx));
|
||||||
});
|
});
|
||||||
let mut body = body.child(
|
let mut body = body.child(
|
||||||
card("zapret", Some(enable.into_any_element()), cx)
|
card("zapret", Some(enable.into_any_element()), cx)
|
||||||
@@ -180,38 +278,65 @@ 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."
|
tr("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."
|
tr("Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists.")
|
||||||
},
|
},
|
||||||
cx,
|
cx,
|
||||||
)),
|
)),
|
||||||
);
|
);
|
||||||
|
|
||||||
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)| tr(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(
|
||||||
|
trf("Strategies: {}", &[&tr(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(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config))
|
.child(div().text_sm().child(tr("Strategies")))
|
||||||
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
|
.child(sources)
|
||||||
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
|
.child(self.option_switch("autohostlist", tr("Learn which sites are blocked"), &["zapret", "zapret2", "autoHostlist", "enable"], &config))
|
||||||
|
.child(self.option_switch(
|
||||||
|
"extended-detection",
|
||||||
|
tr("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", tr("IPv6 too"), &["zapret", "zapret2", "ipv6"], &config))
|
||||||
|
.child(self.option_switch("strategy-log", tr("Log the strategy each site gets"), &["zapret", "zapret2", "strategyLog"], &config)),
|
||||||
);
|
);
|
||||||
|
body = body.child(self.cutoff_card(&config, cx));
|
||||||
} else {
|
} else {
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
|
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
|
||||||
body = body
|
body = body
|
||||||
.child(
|
.child(
|
||||||
card("Preset", None, cx)
|
card(tr("Preset"), None, cx)
|
||||||
.child(hint("One of the release's strategies. If a site still does not open, try the next one.", cx))
|
.child(hint(tr("One of the release's strategies. If a site still does not open, try the next one."), cx))
|
||||||
.child(Select::new(&self.preset).placeholder("Choose a preset").menu_max_h(px(320.))),
|
.child(Select::new(&self.preset).placeholder(tr("Choose a preset")).menu_max_h(px(320.))),
|
||||||
)
|
)
|
||||||
.child(
|
.child(
|
||||||
card("Game traffic", None, cx).child(hint("Also handle game traffic, on ports above 1023.", cx)).child(
|
card(tr("Game traffic"), None, cx).child(hint(tr("Also handle game traffic, on ports above 1023."), cx)).child(
|
||||||
RadioGroup::horizontal("game-filter")
|
RadioGroup::horizontal("game-filter")
|
||||||
.children(GAME_FILTERS.map(|(_, label)| label))
|
.children(GAME_FILTERS.map(|(_, label)| tr(label)))
|
||||||
.selected_index(GAME_FILTERS.iter().position(|(v, _)| *v == filter))
|
.selected_index(GAME_FILTERS.iter().position(|(v, _)| *v == filter))
|
||||||
.on_change(move |ix, _, cx| {
|
.on_change(move |ix, _, cx| {
|
||||||
let (value, label) = GAME_FILTERS[*ix];
|
let (value, label) = GAME_FILTERS[*ix];
|
||||||
model.update(cx, |m, cx| m.edit(format!("Game traffic: {label}"), move |c| edits::set_game_filter(c, value), cx));
|
model.update(cx, |m, cx| m.edit(trf("Game traffic: {}", &[&tr(label)]), move |c| edits::set_game_filter(c, value), cx));
|
||||||
}),
|
}),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -219,20 +344,76 @@ impl Render for DpiPage {
|
|||||||
|
|
||||||
body.child(
|
body.child(
|
||||||
card(
|
card(
|
||||||
"Your sites",
|
tr("Your sites"),
|
||||||
Some(Button::new("save-sites").small().label("Save").on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
|
Some(Button::new("save-sites").small().label(tr("Save")).on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
|
||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.child(hint("Sites to handle besides the engine's own lists, and sites to leave alone.", cx))
|
.child(hint(tr("Sites to handle besides the engine's own lists, and sites to leave alone."), cx))
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_4()
|
.gap_4()
|
||||||
.items_start()
|
.items_start()
|
||||||
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Also handle")).child(Textarea::new(&self.domains)))
|
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Also handle"))).child(Textarea::new(&self.domains)))
|
||||||
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Leave alone")).child(Textarea::new(&self.exclude))),
|
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Leave alone"))).child(Textarea::new(&self.exclude))),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.child(card("Windows", None, cx).child(self.option_switch("tcp-timestamps", "TCP timestamps (some strategies need them)", &["zapret", "tcpTimestamps"], &config)))
|
.child(card("Windows", None, cx).child(self.option_switch("tcp-timestamps", tr("TCP timestamps (some strategies need them)"), &["zapret", "tcpTimestamps"], &config)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("Flowseal's presets (zapret)", "Пресеты Flowseal (zapret)"),
|
||||||
|
("z2k (per category: YouTube, Discord, QUIC, the RKN list)", "z2k (по категориям: YouTube, Discord, QUIC, список RKN)"),
|
||||||
|
("Off", "Выкл."),
|
||||||
|
("TCP and UDP", "TCP и UDP"),
|
||||||
|
("TCP only", "Только TCP"),
|
||||||
|
("UDP only", "Только UDP"),
|
||||||
|
("example.com — one per line", "example.com — по одному в строке"),
|
||||||
|
("bank.example — one per line", "bank.example — по одному в строке"),
|
||||||
|
("Preset: {}", "Пресет: {}"),
|
||||||
|
("The cutoff probe: {}", "Проверка обрыва на 16 КБ: {}"),
|
||||||
|
("Probing…", "Проверка…"),
|
||||||
|
("Probe now", "Проверить сейчас"),
|
||||||
|
("16 KB cutoff", "Обрыв на 16 КБ"),
|
||||||
|
("Some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. A probe finds them daily (and when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello. Each probe makes thousands of short direct connections.",
|
||||||
|
"Некоторые линии обрывают TLS к определённым сетям хостинга примерно после 16 КБ, и никакая стратегия этого не исправляет. Проверка находит такие сети раз в сутки (и при смене сети линии) и, со стратегиями z2k, для каждой подбирает имя, которое проходит; z2k вставляет его в поддельный hello. Каждая проверка устанавливает тысячи коротких прямых соединений."),
|
||||||
|
("Probe this line", "Проверять эту линию"),
|
||||||
|
("Send what no name fixes through the proxy (it sees addresses: the TUN, per-app routing)", "Отправлять через прокси то, что не удаётся исправить подбором имени (он видит адреса: TUN, маршрутизация по приложениям)"),
|
||||||
|
("z2k-detect, the probe, is not installed (the zapret2-extras component).", "z2k-detect, средство проверки, не установлен (компонент zapret2-extras)."),
|
||||||
|
("Not probed yet: the first probe runs five minutes after the service starts.", "Ещё не проверялось: первая проверка выполняется через пять минут после запуска службы."),
|
||||||
|
("Probed {} from {}: no network is cut off on this line.", "Проверено {} с {}: на этой линии нет сетей с обрывом."),
|
||||||
|
("Probed {} from {}: {} network(s) cut off, {} with a name that gets through.", "Проверено {} с {}: сетей с обрывом — {}, из них с именем, которое проходит, — {}."),
|
||||||
|
("through the proxy", "через прокси"),
|
||||||
|
("no name", "нет имени"),
|
||||||
|
("and {} more (proxy-ctl zapret cutoff).", "и ещё {} (proxy-ctl zapret cutoff)."),
|
||||||
|
("Sites saved", "Сайты сохранены"),
|
||||||
|
("DPI bypass", "Обход DPI"),
|
||||||
|
("Waiting for the service…", "Ожидание службы…"),
|
||||||
|
("The DPI bypass is on", "Обход DPI включён"),
|
||||||
|
("The DPI bypass is off", "Обход DPI выключен"),
|
||||||
|
("Engine: {}", "Движок: {}"),
|
||||||
|
("zapret2 (winws2): it learns which sites are blocked as it goes, rotates each one's strategy until one works, and keeps it across restarts.",
|
||||||
|
"zapret2 (winws2): по ходу работы узнаёт, какие сайты заблокированы, перебирает для каждого стратегии, пока одна не сработает, и сохраняет её между перезапусками."),
|
||||||
|
("Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists.",
|
||||||
|
"zapret-discord-youtube от Flowseal: winws с одним из его пресетов — для YouTube, Discord и сайтов из его списков."),
|
||||||
|
("Strategies: {}", "Стратегии: {}"),
|
||||||
|
("Strategies", "Стратегии"),
|
||||||
|
("Learn which sites are blocked", "Узнавать, какие сайты заблокированы"),
|
||||||
|
("Extended detection: also sites blocked only some of the time, and requests that never get an answer", "Расширенное обнаружение: также сайты, заблокированные лишь время от времени, и запросы, на которые так и не приходит ответ"),
|
||||||
|
("IPv6 too", "Также IPv6"),
|
||||||
|
("Log the strategy each site gets", "Записывать в журнал стратегию каждого сайта"),
|
||||||
|
("Preset", "Пресет"),
|
||||||
|
("One of the release's strategies. If a site still does not open, try the next one.", "Одна из стратегий выпуска. Если сайт всё равно не открывается, попробуйте следующую."),
|
||||||
|
("Choose a preset", "Выберите пресет"),
|
||||||
|
("Game traffic", "Игровой трафик"),
|
||||||
|
("Also handle game traffic, on ports above 1023.", "Обрабатывать также игровой трафик на портах выше 1023."),
|
||||||
|
("Game traffic: {}", "Игровой трафик: {}"),
|
||||||
|
("Your sites", "Ваши сайты"),
|
||||||
|
("Save", "Сохранить"),
|
||||||
|
("Sites to handle besides the engine's own lists, and sites to leave alone.", "Сайты, которые нужно обрабатывать помимо списков самого движка, и сайты, которые нужно не трогать."),
|
||||||
|
("Also handle", "Обрабатывать также"),
|
||||||
|
("Leave alone", "Не трогать"),
|
||||||
|
("TCP timestamps (some strategies need them)", "Метки времени TCP (нужны некоторым стратегиям)"),
|
||||||
|
];
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
//! Logs: every unit's, as they come, the last few thousand lines kept; one unit's on its own.
|
//! Logs: every unit's, as they come, the last few thousand lines kept; one unit's on its own.
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use std::collections::VecDeque;
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
use gpui_kit::component::button::Button;
|
use gpui_kit::component::button::Button;
|
||||||
@@ -102,7 +103,7 @@ impl LogsPage {
|
|||||||
impl Render for LogsPage {
|
impl Render for LogsPage {
|
||||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let shown = self.shown();
|
let shown = self.shown();
|
||||||
let mut choices: Vec<SharedString> = vec!["All".into()];
|
let mut choices: Vec<SharedString> = vec![tr("All").into()];
|
||||||
choices.extend(self.units.iter().map(|u| SharedString::from(short(u).to_owned())));
|
choices.extend(self.units.iter().map(|u| SharedString::from(short(u).to_owned())));
|
||||||
let selected = match &self.only {
|
let selected = match &self.only {
|
||||||
None => 0,
|
None => 0,
|
||||||
@@ -113,11 +114,11 @@ impl Render for LogsPage {
|
|||||||
this.only = if *ix == 0 { None } else { this.units.get(*ix - 1).cloned() };
|
this.only = if *ix == 0 { None } else { this.units.get(*ix - 1).cloned() };
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}));
|
}));
|
||||||
let follow = Switch::new("log-follow").label("Follow").checked(self.follow).on_change(cx.listener(|this, on: &bool, _, cx| {
|
let follow = Switch::new("log-follow").label(tr("Follow")).checked(self.follow).on_change(cx.listener(|this, on: &bool, _, cx| {
|
||||||
this.follow = *on;
|
this.follow = *on;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}));
|
}));
|
||||||
let clear = Button::new("log-clear").small().label("Clear").on_click(cx.listener(|this, _, _, cx| {
|
let clear = Button::new("log-clear").small().label(tr("Clear")).on_click(cx.listener(|this, _, _, cx| {
|
||||||
this.lines.clear();
|
this.lines.clear();
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}));
|
}));
|
||||||
@@ -143,10 +144,19 @@ impl Render for LogsPage {
|
|||||||
.track_scroll(&self.scroll)
|
.track_scroll(&self.scroll)
|
||||||
.h(px(460.));
|
.h(px(460.));
|
||||||
|
|
||||||
let mut body = card("Logs", Some(div().h_flex().gap_3().items_center().child(follow).child(clear).into_any_element()), cx).child(filter);
|
let mut body = card(tr("Logs"), Some(div().h_flex().gap_3().items_center().child(follow).child(clear).into_any_element()), cx).child(filter);
|
||||||
if let Some(why) = &self.lost {
|
if let Some(why) = &self.lost {
|
||||||
body = body.child(hint(format!("Not receiving logs: {why}"), cx));
|
body = body.child(hint(trf("Not receiving logs: {}", &[&why]), cx));
|
||||||
}
|
}
|
||||||
page("Logs", cx).child(body.child(div().p_2().rounded_md().bg(cx.theme().muted).child(lines)))
|
page(tr("Logs"), cx).child(body.child(div().p_2().rounded_md().bg(cx.theme().muted).child(lines)))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("All", "Все"),
|
||||||
|
("Follow", "Следить"),
|
||||||
|
("Clear", "Очистить"),
|
||||||
|
("Logs", "Журналы"),
|
||||||
|
("Not receiving logs: {}", "Журналы не поступают: {}"),
|
||||||
|
];
|
||||||
@@ -1,18 +1,20 @@
|
|||||||
//! 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;
|
pub(crate) mod amneziawg;
|
||||||
mod autoproxy;
|
pub(crate) mod autoproxy;
|
||||||
mod components;
|
pub(crate) mod components;
|
||||||
mod dpi;
|
pub(crate) mod dpi;
|
||||||
mod logs;
|
pub(crate) mod logs;
|
||||||
mod outbounds;
|
pub(crate) mod outbounds;
|
||||||
mod overview;
|
pub(crate) mod overview;
|
||||||
mod settings;
|
pub(crate) mod settings;
|
||||||
mod telegram;
|
pub(crate) mod telegram;
|
||||||
mod whitelist;
|
pub(crate) mod whitelist;
|
||||||
mod widgets;
|
pub(crate) mod widgets;
|
||||||
|
|
||||||
|
use crate::i18n::tr;
|
||||||
|
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||||
use gpui_kit::component::notification::Notification;
|
use gpui_kit::component::notification::Notification;
|
||||||
use gpui_kit::component::sidebar::{Sidebar, SidebarFooter, SidebarGroup, SidebarHeader, SidebarMenu, SidebarMenuItem};
|
use gpui_kit::component::sidebar::{Sidebar, SidebarFooter, SidebarGroup, SidebarHeader, SidebarMenu, SidebarMenuItem};
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
@@ -102,6 +104,16 @@ impl AppView {
|
|||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let subscriptions = vec![
|
let subscriptions = vec![
|
||||||
cx.observe(&model, |_, _, cx| cx.notify()),
|
cx.observe(&model, |_, _, cx| cx.notify()),
|
||||||
|
// As Windows' appearance changes: the theme, when it follows it; the title bar, which
|
||||||
|
// GPUI sets to Windows' own just after this, a moment later.
|
||||||
|
cx.observe_window_appearance(window, |_, window, cx| {
|
||||||
|
crate::prefs::apply_theme(Some(window), cx);
|
||||||
|
cx.spawn_in(window, async move |_, cx| {
|
||||||
|
cx.background_executor().timer(std::time::Duration::from_millis(300)).await;
|
||||||
|
cx.update(|window, cx| crate::prefs::apply_theme(Some(window), cx)).ok();
|
||||||
|
})
|
||||||
|
.detach();
|
||||||
|
}),
|
||||||
cx.subscribe_in(&model, window, |_, _, outcome: &Outcome, window, cx| {
|
cx.subscribe_in(&model, window, |_, _, outcome: &Outcome, window, cx| {
|
||||||
let note = match outcome {
|
let note = match outcome {
|
||||||
Outcome::Done(m) => Notification::success(m.clone()),
|
Outcome::Done(m) => Notification::success(m.clone()),
|
||||||
@@ -110,28 +122,51 @@ impl AppView {
|
|||||||
window.push_notification(note, cx);
|
window.push_notification(note, cx);
|
||||||
}),
|
}),
|
||||||
];
|
];
|
||||||
|
// The window's appearance is the one to follow (the app's, before a window, may not be).
|
||||||
|
crate::prefs::apply_theme(Some(window), cx);
|
||||||
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, whitelist: None, autoproxy: None, amneziawg: None, 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 }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn page(&self) -> Page {
|
||||||
|
self.page
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn show(&mut self, page: Page, cx: &mut Context<Self>) {
|
||||||
|
self.page = page;
|
||||||
|
cx.notify();
|
||||||
|
}
|
||||||
|
|
||||||
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let items = Page::ALL.map(|page| {
|
let items = Page::ALL.map(|page| {
|
||||||
SidebarMenuItem::new(page.title()).icon(page.icon()).active(self.page == page).on_click(cx.listener(move |this, _, _, cx| {
|
SidebarMenuItem::new(tr(page.title())).icon(page.icon()).active(self.page == page).on_click(cx.listener(move |this, _, _, cx| {
|
||||||
this.page = page;
|
this.page = page;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}))
|
}))
|
||||||
});
|
});
|
||||||
let m = self.model.read(cx);
|
let m = self.model.read(cx);
|
||||||
let (colour, state) = match m.connection() {
|
let (colour, state) = match m.connection() {
|
||||||
Connection::Up if m.busy() => (cx.theme().warning, "Applying…"),
|
Connection::Up if m.busy() => (cx.theme().warning, tr("Applying…")),
|
||||||
Connection::Up => (cx.theme().success, "Connected to the service"),
|
Connection::Up => (cx.theme().success, tr("Connected to the service")),
|
||||||
Connection::Connecting => (cx.theme().muted_foreground, "Connecting…"),
|
Connection::Connecting => (cx.theme().muted_foreground, tr("Connecting…")),
|
||||||
Connection::Down(_) => (cx.theme().danger, "The service is not running"),
|
Connection::Down(_) => (cx.theme().danger, tr("The service is not running")),
|
||||||
};
|
};
|
||||||
let footer = SidebarFooter::new().child(div().h_flex().gap_2().items_center().text_xs().text_color(cx.theme().muted_foreground).child(div().size_2().rounded_full().bg(colour)).child(state));
|
let footer = SidebarFooter::new().child(div().h_flex().gap_2().items_center().text_xs().text_color(cx.theme().muted_foreground).child(div().size_2().rounded_full().bg(colour)).child(state));
|
||||||
Sidebar::new("pages").header(SidebarHeader::new().child(widgets::brand(cx))).child(SidebarGroup::new("Proxy Suite").child(SidebarMenu::new().children(items))).footer(footer)
|
// Light or dark at a click; Settings → This app has "as Windows" too.
|
||||||
|
let dark = cx.theme().is_dark();
|
||||||
|
let theme = Button::new("theme-toggle")
|
||||||
|
.ghost()
|
||||||
|
.xsmall()
|
||||||
|
.icon(if dark { IconName::Sun } else { IconName::Moon })
|
||||||
|
.tooltip(if dark { tr("Light theme") } else { tr("Dark theme") })
|
||||||
|
.on_click(move |_, _, cx| {
|
||||||
|
let choice = if dark { crate::prefs::ThemeChoice::Light } else { crate::prefs::ThemeChoice::Dark };
|
||||||
|
crate::prefs::change(cx, |p| p.theme = choice);
|
||||||
|
});
|
||||||
|
let header = SidebarHeader::new().child(div().h_flex().w_full().justify_between().items_center().child(widgets::brand(cx)).child(theme));
|
||||||
|
Sidebar::new("pages").header(header).child(SidebarGroup::new("Proxy Suite").child(SidebarMenu::new().children(items))).footer(footer)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -176,3 +211,21 @@ impl Render for AppView {
|
|||||||
.child(div().id("page").flex_1().min_w_0().h_full().overflow_y_scroll().child(page))
|
.child(div().id("page").flex_1().min_w_0().h_full().overflow_y_scroll().child(page))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The window's words (the pages' names), in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("Overview", "Обзор"),
|
||||||
|
("DPI bypass", "Обход DPI"),
|
||||||
|
("Telegram proxy", "Прокси для Telegram"),
|
||||||
|
("Whitelist bypass", "Обход белых списков"),
|
||||||
|
("Outbounds", "Выходы"),
|
||||||
|
("Logs", "Журналы"),
|
||||||
|
("Settings", "Настройки"),
|
||||||
|
("Components", "Компоненты"),
|
||||||
|
("Applying…", "Применяется…"),
|
||||||
|
("Connected to the service", "Служба на связи"),
|
||||||
|
("Connecting…", "Подключение…"),
|
||||||
|
("The service is not running", "Служба не запущена"),
|
||||||
|
("Light theme", "Светлая тема"),
|
||||||
|
("Dark theme", "Тёмная тема"),
|
||||||
|
];
|
||||||
@@ -16,7 +16,8 @@ use ps_client::edits::{self, OutboundSource};
|
|||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::widgets::{card, hint, page};
|
use super::widgets::{card, hint, page, Inactive as _};
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
|
||||||
const MODES: [(&str, &str); 5] = [
|
const MODES: [(&str, &str); 5] = [
|
||||||
@@ -40,8 +41,8 @@ pub struct OutboundsPage {
|
|||||||
|
|
||||||
impl OutboundsPage {
|
impl OutboundsPage {
|
||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let link = cx.new(|cx| InputState::new(window, cx).placeholder("vless://…, ss://…, trojan://…, hysteria2://… or JSON"));
|
let link = cx.new(|cx| InputState::new(window, cx).placeholder(tr("vless://…, ss://…, trojan://…, hysteria2://… or JSON")));
|
||||||
let tag = cx.new(|cx| InputState::new(window, cx).placeholder("from the link"));
|
let tag = cx.new(|cx| InputState::new(window, cx).placeholder(tr("from the link")));
|
||||||
let sub_url = cx.new(|cx| InputState::new(window, cx).placeholder("https://provider.example/sub/…"));
|
let sub_url = cx.new(|cx| InputState::new(window, cx).placeholder("https://provider.example/sub/…"));
|
||||||
let subscriptions = vec![cx.observe(&model, |_, _, cx| cx.notify())];
|
let subscriptions = vec![cx.observe(&model, |_, _, cx| cx.notify())];
|
||||||
Self { model, link, tag, sub_url, delays: HashMap::new(), testing: false, _subscriptions: subscriptions }
|
Self { model, link, tag, sub_url, delays: HashMap::new(), testing: false, _subscriptions: subscriptions }
|
||||||
@@ -55,7 +56,7 @@ impl OutboundsPage {
|
|||||||
let source = match OutboundSource::parse(&text) {
|
let source = match OutboundSource::parse(&text) {
|
||||||
Ok(s) => s,
|
Ok(s) => s,
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
window.push_notification(Notification::error(format!("Not an outbound: {e:#}")).autohide(false), cx);
|
window.push_notification(Notification::error(trf("Not an outbound: {}", &[&format!("{e:#}")])).autohide(false), cx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -63,7 +64,7 @@ impl OutboundsPage {
|
|||||||
let tag = if typed.is_empty() { edits::link_tag(&text) } else { typed };
|
let tag = if typed.is_empty() { edits::link_tag(&text) } else { typed };
|
||||||
self.link.update(cx, |s, cx| s.set_value("", window, cx));
|
self.link.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
self.tag.update(cx, |s, cx| s.set_value("", window, cx));
|
self.tag.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
let what = format!("Added {tag}");
|
let what = trf("Added {}", &[&tag]);
|
||||||
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_outbound(c, &tag, &source, None), cx));
|
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_outbound(c, &tag, &source, None), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,7 +75,7 @@ impl OutboundsPage {
|
|||||||
}
|
}
|
||||||
let tag = edits::subscription_tag(&url);
|
let tag = edits::subscription_tag(&url);
|
||||||
self.sub_url.update(cx, |s, cx| s.set_value("", window, cx));
|
self.sub_url.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
self.model.update(cx, |m, cx| m.edit(format!("Subscription {tag} added; fetching it"), move |c| edits::add_subscription(c, &tag, &url), cx));
|
self.model.update(cx, |m, cx| m.edit(trf("Subscription {} added; fetching it", &[&tag]), move |c| edits::add_subscription(c, &tag, &url), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test(&mut self, tags: Vec<String>, cx: &mut Context<Self>) {
|
fn test(&mut self, tags: Vec<String>, cx: &mut Context<Self>) {
|
||||||
@@ -89,7 +90,7 @@ impl OutboundsPage {
|
|||||||
Ok(list) => {
|
Ok(list) => {
|
||||||
for t in list.as_array().into_iter().flatten() {
|
for t in list.as_array().into_iter().flatten() {
|
||||||
let tag = t["tag"].as_str().unwrap_or("").to_owned();
|
let tag = t["tag"].as_str().unwrap_or("").to_owned();
|
||||||
let delay = t["delay"].as_u64().ok_or_else(|| t["error"].as_str().unwrap_or("failed").to_owned());
|
let delay = t["delay"].as_u64().ok_or_else(|| t["error"].as_str().unwrap_or(tr("no reason given")).to_owned());
|
||||||
this.delays.insert(tag, delay);
|
this.delays.insert(tag, delay);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -115,11 +116,11 @@ impl OutboundsPage {
|
|||||||
notes.push(r.to_owned());
|
notes.push(r.to_owned());
|
||||||
}
|
}
|
||||||
if let Some(h) = inv["detours"][tag].as_str() {
|
if let Some(h) = inv["detours"][tag].as_str() {
|
||||||
notes.push(format!("through {h}"));
|
notes.push(trf("through {}", &[&h]));
|
||||||
}
|
}
|
||||||
let delay = match self.delays.get(tag) {
|
let delay = match self.delays.get(tag) {
|
||||||
Some(Ok(ms)) => Tag::success().child(format!("{ms} ms")).into_any_element(),
|
Some(Ok(ms)) => Tag::success().child(format!("{ms} ms")).into_any_element(),
|
||||||
Some(Err(e)) => div().max_w(px(220.)).truncate().text_xs().text_color(cx.theme().danger).child(format!("failed: {e}")).into_any_element(),
|
Some(Err(e)) => div().max_w(px(220.)).truncate().text_xs().text_color(cx.theme().danger).child(trf("failed: {}", &[&e])).into_any_element(),
|
||||||
None => div().into_any_element(),
|
None => div().into_any_element(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -137,25 +138,25 @@ impl OutboundsPage {
|
|||||||
.v_flex()
|
.v_flex()
|
||||||
.flex_1()
|
.flex_1()
|
||||||
.min_w_0()
|
.min_w_0()
|
||||||
.child(div().h_flex().gap_2().items_center().child(div().font_medium().truncate().child(tag.to_owned())).when(pinned, |d| d.child(Tag::primary().child("pinned"))).when(disabled, |d| d.child(Tag::secondary().child("disabled"))))
|
.child(div().h_flex().gap_2().items_center().child(div().font_medium().truncate().child(tag.to_owned())).when(pinned, |d| d.child(Tag::primary().child(tr("pinned")))).when(disabled, |d| d.child(Tag::secondary().child(tr("disabled")))))
|
||||||
.child(div().text_xs().text_color(cx.theme().muted_foreground).child(notes.join(" · "))),
|
.child(div().text_xs().text_color(cx.theme().muted_foreground).child(notes.join(" · "))),
|
||||||
)
|
)
|
||||||
.child(delay)
|
.child(delay)
|
||||||
.child(Button::new(("test", ix)).small().ghost().icon(IconName::Gauge).tooltip("Test its delay").on_click(cx.listener(move |this, _, _, cx| this.test(vec![t_test.clone()], cx))))
|
.child(Button::new(("test", ix)).small().ghost().icon(IconName::Gauge).tooltip(tr("Test its delay")).on_click(cx.listener(move |this, _, _, cx| this.test(vec![t_test.clone()], cx))))
|
||||||
.child(Button::new(("pin", ix)).small().ghost().icon(if pinned { IconName::PinOff } else { IconName::Pin }).tooltip(if pinned { "Back to automatic selection" } else { "Always use this one" }).on_click(move |_, _, cx| {
|
.child(Button::new(("pin", ix)).small().ghost().icon(if pinned { IconName::PinOff } else { IconName::Pin }).tooltip(if pinned { tr("Back to automatic selection") } else { tr("Always use this one") }).on_click(move |_, _, cx| {
|
||||||
let req = Request::Pin { tag: if pinned { None } else { Some(t_pin.clone()) }, group: None };
|
let req = Request::Pin { tag: if pinned { None } else { Some(t_pin.clone()) }, group: None };
|
||||||
let what = if pinned { "Back to automatic selection".to_owned() } else { format!("Pinned to {t_pin}") };
|
let what = if pinned { tr("Back to automatic selection").to_owned() } else { trf("Pinned to {}", &[&t_pin]) };
|
||||||
model_pin.update(cx, |m, cx| m.request(what, req, cx));
|
model_pin.update(cx, |m, cx| m.request(what, req, cx));
|
||||||
}))
|
}))
|
||||||
.child(Button::new(("disable", ix)).small().ghost().icon(IconName::Power).tooltip(if disabled { "Use it again" } else { "Leave it out" }).on_click(move |_, _, cx| {
|
.child(Button::new(("disable", ix)).small().ghost().icon(IconName::Power).tooltip(if disabled { tr("Use it again") } else { tr("Leave it out") }).on_click(move |_, _, cx| {
|
||||||
let what = format!("{t_dis} {}", if disabled { "is back" } else { "is left out" });
|
let what = if disabled { trf("{} is back", &[&t_dis]) } else { trf("{} is left out", &[&t_dis]) };
|
||||||
let req = Request::Disable { tag: t_dis.clone(), disabled: !disabled };
|
let req = Request::Disable { tag: t_dis.clone(), disabled: !disabled };
|
||||||
model_dis.update(cx, |m, cx| m.request(what, req, cx));
|
model_dis.update(cx, |m, cx| m.request(what, req, cx));
|
||||||
}))
|
}))
|
||||||
.when(own, |d| {
|
.when(own, |d| {
|
||||||
d.child(Button::new(("remove", ix)).small().ghost().icon(IconName::Trash).tooltip("Remove it").on_click(move |_, _, cx| {
|
d.child(Button::new(("remove", ix)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| {
|
||||||
let tag = t_rm.clone();
|
let tag = t_rm.clone();
|
||||||
model_rm.update(cx, |m, cx| m.edit(format!("Removed {tag}"), move |c| edits::remove_outbound(c, &tag), cx));
|
model_rm.update(cx, |m, cx| m.edit(trf("Removed {}", &[&tag]), move |c| edits::remove_outbound(c, &tag), cx));
|
||||||
}))
|
}))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -169,44 +170,44 @@ impl Render for OutboundsPage {
|
|||||||
let subs: Vec<String> = m.config()["proxy"]["subscriptions"].as_array().into_iter().flatten().filter_map(|s| s["tag"].as_str().map(str::to_owned)).collect();
|
let subs: Vec<String> = m.config()["proxy"]["subscriptions"].as_array().into_iter().flatten().filter_map(|s| s["tag"].as_str().map(str::to_owned)).collect();
|
||||||
let tags: Vec<String> = inv["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
let tags: Vec<String> = inv["tags"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();
|
||||||
|
|
||||||
let add = card("Add an outbound", Some(Button::new("add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
|
let add = card(tr("Add an outbound"), Some(Button::new("add").small().primary().icon(IconName::Plus).label(tr("Add")).on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
|
||||||
.child(hint("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration.", cx))
|
.child(hint(tr("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration."), cx))
|
||||||
.child(div().h_flex().gap_3().child(div().flex_1().min_w_0().child(Input::new(&self.link))).child(div().w(px(180.)).child(Input::new(&self.tag))));
|
.child(div().h_flex().gap_3().child(div().flex_1().min_w_0().child(Input::new(&self.link))).child(div().w(px(180.)).child(Input::new(&self.tag))));
|
||||||
|
|
||||||
let mut list = card(
|
let mut list = card(
|
||||||
format!("Outbounds ({})", tags.len()),
|
trf("Outbounds ({})", &[&tags.len()]),
|
||||||
Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { "Testing…" } else { "Test all" }).disabled(self.testing || tags.is_empty()).on_click(cx.listener(|this, _, _, cx| this.test(Vec::new(), cx))).into_any_element()),
|
Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { tr("Testing…") } else { tr("Test all") }).inactive(self.testing || tags.is_empty(), cx).on_click(cx.listener(|this, _, _, cx| this.test(Vec::new(), cx))).into_any_element()),
|
||||||
cx,
|
cx,
|
||||||
);
|
);
|
||||||
if let Some(Err(e)) = self.delays.get("") {
|
if let Some(Err(e)) = self.delays.get("") {
|
||||||
list = list.child(div().text_sm().text_color(cx.theme().danger).child(format!("Testing failed: {e}")));
|
list = list.child(div().text_sm().text_color(cx.theme().danger).child(trf("Testing failed: {}", &[&e])));
|
||||||
}
|
}
|
||||||
if tags.is_empty() {
|
if tags.is_empty() {
|
||||||
list = list.child(hint("None yet: add a link above, or a subscription below.", cx));
|
list = list.child(hint(tr("None yet: add a link above, or a subscription below."), cx));
|
||||||
}
|
}
|
||||||
for (i, tag) in tags.iter().enumerate() {
|
for (i, tag) in tags.iter().enumerate() {
|
||||||
list = list.child(self.row(tag, &inv, i, cx));
|
list = list.child(self.row(tag, &inv, i, cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
let modes = card("Routing mode", None, cx).child(hint("Overrides the routing rules until changed back; “As configured” follows them.", cx)).child(
|
let modes = card(tr("Routing mode"), None, cx).child(hint(tr("Overrides the routing rules until changed back; “As configured” follows them."), cx)).child(
|
||||||
RadioGroup::vertical("mode").children(MODES.map(|(_, label)| label)).selected_index(MODES.iter().position(|(v, _)| *v == mode)).on_change(move |ix, _, cx| {
|
RadioGroup::vertical("mode").children(MODES.map(|(_, label)| tr(label))).selected_index(MODES.iter().position(|(v, _)| *v == mode)).on_change(move |ix, _, cx| {
|
||||||
let (value, label) = MODES[*ix];
|
let (value, label) = MODES[*ix];
|
||||||
let req = Request::Mode { mode: if value == "default" { None } else { Some(value.into()) } };
|
let req = Request::Mode { mode: if value == "default" { None } else { Some(value.into()) } };
|
||||||
model.update(cx, |m, cx| m.request(format!("Mode: {label}"), req, cx));
|
model.update(cx, |m, cx| m.request(trf("Mode: {}", &[&tr(label)]), req, cx));
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
let mut subscriptions = card(
|
let mut subscriptions = card(
|
||||||
"Subscriptions",
|
tr("Subscriptions"),
|
||||||
Some(
|
Some(
|
||||||
Button::new("subs-update")
|
Button::new("subs-update")
|
||||||
.small()
|
.small()
|
||||||
.icon(IconName::RefreshCw)
|
.icon(IconName::RefreshCw)
|
||||||
.label("Update all")
|
.label(tr("Update all"))
|
||||||
.disabled(subs.is_empty())
|
.inactive(subs.is_empty(), cx)
|
||||||
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request("Subscriptions updated", Request::SubsUpdate { tag: None }, cx)))
|
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request(tr("Subscriptions updated"), Request::SubsUpdate { tag: None }, cx)))
|
||||||
.into_any_element(),
|
.into_any_element(),
|
||||||
),
|
),
|
||||||
cx,
|
cx,
|
||||||
@@ -216,7 +217,7 @@ impl Render for OutboundsPage {
|
|||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_3()
|
.gap_3()
|
||||||
.child(div().flex_1().min_w_0().child(Input::new(&self.sub_url)))
|
.child(div().flex_1().min_w_0().child(Input::new(&self.sub_url)))
|
||||||
.child(Button::new("sub-add").small().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add_subscription(window, cx)))),
|
.child(Button::new("sub-add").small().icon(IconName::Plus).label(tr("Add")).on_click(cx.listener(|this, _, window, cx| this.add_subscription(window, cx)))),
|
||||||
);
|
);
|
||||||
for (i, tag) in subs.into_iter().enumerate() {
|
for (i, tag) in subs.into_iter().enumerate() {
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
@@ -229,13 +230,58 @@ impl Render for OutboundsPage {
|
|||||||
.border_t_1()
|
.border_t_1()
|
||||||
.border_color(cx.theme().border)
|
.border_color(cx.theme().border)
|
||||||
.child(div().flex_1().child(tag))
|
.child(div().flex_1().child(tag))
|
||||||
.child(Button::new(("sub-rm", i)).small().ghost().icon(IconName::Trash).tooltip("Remove it").on_click(move |_, _, cx| {
|
.child(Button::new(("sub-rm", i)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| {
|
||||||
let tag = t.clone();
|
let tag = t.clone();
|
||||||
model.update(cx, |m, cx| m.edit(format!("Removed subscription {tag}"), move |c| edits::remove_subscription(c, &tag), cx));
|
model.update(cx, |m, cx| m.edit(trf("Removed subscription {}", &[&tag]), move |c| edits::remove_subscription(c, &tag), cx));
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
page("Outbounds", cx).child(add).child(list).child(modes).child(subscriptions)
|
page(tr("Outbounds"), cx).child(add).child(list).child(modes).child(subscriptions)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("As configured", "Как настроено"),
|
||||||
|
("Proxy only listed sites", "Прокси только для сайтов из списка"),
|
||||||
|
("Proxy all but listed sites", "Прокси для всех, кроме сайтов из списка"),
|
||||||
|
("Proxy everything", "Прокси для всего"),
|
||||||
|
("Proxy nothing", "Без прокси"),
|
||||||
|
("vless://…, ss://…, trojan://…, hysteria2://… or JSON", "vless://…, ss://…, trojan://…, hysteria2://… или JSON"),
|
||||||
|
("from the link", "из ссылки"),
|
||||||
|
("Not an outbound: {}", "Это не выход: {}"),
|
||||||
|
("Added {}", "Добавлен выход: {}"),
|
||||||
|
("Subscription {} added; fetching it", "Подписка {} добавлена, загружаем её"),
|
||||||
|
("no reason given", "причина неизвестна"),
|
||||||
|
("through {}", "через {}"),
|
||||||
|
("failed: {}", "не удалось: {}"),
|
||||||
|
("pinned", "закреплён"),
|
||||||
|
("disabled", "исключён"),
|
||||||
|
("Test its delay", "Проверить задержку"),
|
||||||
|
("Back to automatic selection", "Вернуть автоматический выбор"),
|
||||||
|
("Always use this one", "Всегда использовать этот"),
|
||||||
|
("Pinned to {}", "Закреплён: {}"),
|
||||||
|
("Use it again", "Использовать снова"),
|
||||||
|
("Leave it out", "Исключить"),
|
||||||
|
("{} is back", "{}: снова используется"),
|
||||||
|
("{} is left out", "{}: исключён"),
|
||||||
|
("Remove it", "Удалить"),
|
||||||
|
("Removed {}", "Удалён: {}"),
|
||||||
|
("Add an outbound", "Добавить выход"),
|
||||||
|
("Add", "Добавить"),
|
||||||
|
("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration.", "Ссылка от вашего провайдера или выход sing-box либо XRay в виде JSON. Ссылки остаются на этом компьютере, в конфигурации службы."),
|
||||||
|
("Outbounds ({})", "Выходы ({})"),
|
||||||
|
("Testing…", "Проверка…"),
|
||||||
|
("Test all", "Проверить все"),
|
||||||
|
("Testing failed: {}", "Проверка не удалась: {}"),
|
||||||
|
("None yet: add a link above, or a subscription below.", "Пока пусто: добавьте ссылку выше или подписку ниже."),
|
||||||
|
("Routing mode", "Режим маршрутизации"),
|
||||||
|
("Overrides the routing rules until changed back; “As configured” follows them.", "Заменяет правила маршрутизации, пока не вернёте прежний режим; «Как настроено» следует правилам."),
|
||||||
|
("Mode: {}", "Режим: {}"),
|
||||||
|
("Subscriptions", "Подписки"),
|
||||||
|
("Update all", "Обновить все"),
|
||||||
|
("Subscriptions updated", "Подписки обновлены"),
|
||||||
|
("Removed subscription {}", "Подписка удалена: {}"),
|
||||||
|
("Outbounds", "Выходы"),
|
||||||
|
];
|
||||||
@@ -1,7 +1,10 @@
|
|||||||
//! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state
|
//! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state
|
||||||
//! and a switch; what the service warns of.
|
//! and a switch; what the service warns of; Proxy Suite's version, and a newer one to install.
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::alert::Alert;
|
use gpui_kit::component::alert::Alert;
|
||||||
|
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||||
use gpui_kit::component::switch::Switch;
|
use gpui_kit::component::switch::Switch;
|
||||||
use gpui_kit::component::*;
|
use gpui_kit::component::*;
|
||||||
use gpui_kit::prelude::FluentBuilder as _;
|
use gpui_kit::prelude::FluentBuilder as _;
|
||||||
@@ -10,8 +13,8 @@ use ps_client::edits;
|
|||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::AppView;
|
use super::AppView;
|
||||||
use super::widgets::{card, fact, hint, page, state_tag};
|
use super::widgets::{card, fact, hint, page, state_tag, Inactive as _};
|
||||||
use crate::model::{Connection, Model};
|
use crate::model::{Connection, Model, Update};
|
||||||
|
|
||||||
fn text(v: &Value) -> SharedString {
|
fn text(v: &Value) -> SharedString {
|
||||||
match v {
|
match v {
|
||||||
@@ -25,23 +28,23 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
let m = model.read(cx);
|
let m = model.read(cx);
|
||||||
let s = m.status().clone();
|
let s = m.status().clone();
|
||||||
let connection = m.connection().clone();
|
let connection = m.connection().clone();
|
||||||
let mut body = page("Overview", cx);
|
let mut body = page(tr("Overview"), cx);
|
||||||
|
|
||||||
match &connection {
|
match &connection {
|
||||||
Connection::Down(why) => {
|
Connection::Down(why) => {
|
||||||
body = body.child(Alert::error("service-down", why.clone()).title("Not connected")).child(hint(
|
body = body.child(Alert::error("service-down", why.clone()).title(tr("Not connected"))).child(hint(
|
||||||
"The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite.",
|
tr("The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite."),
|
||||||
cx,
|
cx,
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
Connection::Connecting => body = body.child(Alert::info("connecting", "Connecting to the Proxy Suite service…")),
|
Connection::Connecting => body = body.child(Alert::info("connecting", tr("Connecting to the Proxy Suite service…"))),
|
||||||
Connection::Up => {}
|
Connection::Up => {}
|
||||||
}
|
}
|
||||||
if connection != Connection::Up {
|
if connection != Connection::Up {
|
||||||
return body;
|
return body;
|
||||||
}
|
}
|
||||||
if let Some(e) = s["error"].as_str() {
|
if let Some(e) = s["error"].as_str() {
|
||||||
body = body.child(Alert::error("service-error", e.to_owned()).title("The configuration did not apply"));
|
body = body.child(Alert::error("service-error", e.to_owned()).title(tr("The configuration did not apply")));
|
||||||
}
|
}
|
||||||
for (i, w) in s["warnings"].as_array().into_iter().flatten().enumerate() {
|
for (i, w) in s["warnings"].as_array().into_iter().flatten().enumerate() {
|
||||||
body = body.child(Alert::warning(("warning", i), text(w)));
|
body = body.child(Alert::warning(("warning", i), text(w)));
|
||||||
@@ -51,7 +54,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
let proxy_on = p["on"] == true;
|
let proxy_on = p["on"] == true;
|
||||||
let model_p = model.clone();
|
let model_p = model.clone();
|
||||||
let proxy = card(
|
let proxy = card(
|
||||||
"Local proxy",
|
tr("Local proxy"),
|
||||||
Some(
|
Some(
|
||||||
Switch::new("proxy-on")
|
Switch::new("proxy-on")
|
||||||
.checked(proxy_on)
|
.checked(proxy_on)
|
||||||
@@ -60,19 +63,39 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
),
|
),
|
||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.child(div().h_flex().gap_2().child(state_tag(p["state"].as_str().unwrap_or("unknown"))).when(p["tun"] == true, |d| d.child(tag::Tag::info().child("global TUN"))))
|
.child(div().h_flex().gap_2().child(state_tag(p["state"].as_str().unwrap_or("unknown"))).when(p["tun"] == true, |d| d.child(tag::Tag::info().child(tr("global TUN")))))
|
||||||
.child(fact("Listening on", text(&p["listener"]), cx))
|
.child(fact(tr("Listening on"), text(&p["listener"]), cx))
|
||||||
.child(fact("Backend", text(&p["backend"]), cx))
|
.child(fact(tr("Backend"), text(&p["backend"]), cx))
|
||||||
.child(fact("Mode", p["mode"].as_str().unwrap_or("default").to_owned(), cx))
|
.child(fact(tr("Mode"), p["mode"].as_str().unwrap_or("default").to_owned(), cx))
|
||||||
.child(fact("Outbound", p["pinned"].as_str().map(|t| format!("{t} (pinned)")).unwrap_or_else(|| format!("{} selection", p["selection"].as_str().unwrap_or("?"))), cx))
|
.child(fact(tr("Outbound"), p["pinned"].as_str().map(|t| trf("{} (pinned)", &[&t])).unwrap_or_else(|| trf("{} selection", &[&p["selection"].as_str().unwrap_or("?")])), cx))
|
||||||
|
.when(s["killSwitch"]["enabled"] == true, |d| {
|
||||||
|
let k = &s["killSwitch"];
|
||||||
|
let (state, action, on) = if k["failed"] == true {
|
||||||
|
(tr("not in place: its filters failed (the Logs say why)"), tr("Lift"), false)
|
||||||
|
} else if k["holding"] == true {
|
||||||
|
(tr("holding: what would leave past the tunnel is blocked"), tr("Lift"), false)
|
||||||
|
} else if k["lifted"] == true {
|
||||||
|
(tr("lifted until a tunnel is turned on"), tr("Hold again"), true)
|
||||||
|
} else {
|
||||||
|
(tr("nothing to hold: no global tunnel is on"), "", true)
|
||||||
|
};
|
||||||
|
let model = model.clone();
|
||||||
|
d.child(
|
||||||
|
div().h_flex().gap_2().items_center().child(fact(tr("Kill switch"), state, cx)).when(!action.is_empty(), |d| {
|
||||||
|
d.child(Button::new("killswitch").xsmall().label(action).on_click(move |_, _, cx| {
|
||||||
|
model.update(cx, |m, cx| m.request(if on { tr("The kill switch holds again") } else { tr("The kill switch is lifted") }, ps_ipc::Request::KillSwitch { on: Some(on) }, cx))
|
||||||
|
}))
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
})
|
||||||
.child({
|
.child({
|
||||||
let model = model.clone();
|
let model = model.clone();
|
||||||
let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
|
let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
|
||||||
Switch::new("system-proxy").label("Use it as the system proxy (browsers and most programs follow it)").checked(on).on_change(move |on, _, cx| {
|
Switch::new("system-proxy").label(tr("Use it as the system proxy (browsers and most programs follow it)")).checked(on).on_change(move |on, _, cx| {
|
||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The system proxy follows the local proxy" } else { "The system proxy is left alone" },
|
if on { tr("The system proxy follows the local proxy") } else { tr("The system proxy is left alone") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["proxy", "systemProxy", "enable"], on.into());
|
edits::set_path(c, &["proxy", "systemProxy", "enable"], on.into());
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -86,7 +109,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
let z = &s["zapret"];
|
let z = &s["zapret"];
|
||||||
let model_z = model.clone();
|
let model_z = model.clone();
|
||||||
let dpi = card(
|
let dpi = card(
|
||||||
"DPI bypass",
|
tr("DPI bypass"),
|
||||||
Some(
|
Some(
|
||||||
Switch::new("zapret-on")
|
Switch::new("zapret-on")
|
||||||
.checked(z["enabled"] == true)
|
.checked(z["enabled"] == true)
|
||||||
@@ -94,7 +117,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model_z.update(cx, |m, cx| {
|
model_z.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The DPI bypass is on" } else { "The DPI bypass is off" },
|
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_zapret_enabled(c, on);
|
edits::set_zapret_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -108,13 +131,13 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.child(div().h_flex().child(state_tag(z["state"].as_str().unwrap_or("unknown"))))
|
.child(div().h_flex().child(state_tag(z["state"].as_str().unwrap_or("unknown"))))
|
||||||
.child(fact("Engine", text(&z["engine"]), cx))
|
.child(fact(tr("Engine"), text(&z["engine"]), cx))
|
||||||
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact("Preset", text(&z["preset"]), cx)));
|
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact(tr("Preset"), text(&z["preset"]), cx)));
|
||||||
|
|
||||||
let t = &s["tgWsProxy"];
|
let t = &s["tgWsProxy"];
|
||||||
let model_t = model.clone();
|
let model_t = model.clone();
|
||||||
let telegram = card(
|
let telegram = card(
|
||||||
"Telegram proxy",
|
tr("Telegram proxy"),
|
||||||
Some(
|
Some(
|
||||||
Switch::new("tg-on")
|
Switch::new("tg-on")
|
||||||
.checked(t["enabled"] == true)
|
.checked(t["enabled"] == true)
|
||||||
@@ -122,7 +145,7 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model_t.update(cx, |m, cx| {
|
model_t.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
|
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_tg_ws_proxy_enabled(c, on);
|
edits::set_tg_ws_proxy_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -136,7 +159,92 @@ pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>)
|
|||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.child(div().h_flex().child(state_tag(t["state"].as_str().unwrap_or("unknown"))))
|
.child(div().h_flex().child(state_tag(t["state"].as_str().unwrap_or("unknown"))))
|
||||||
.child(fact("Listening on", text(&t["listener"]), cx));
|
.child(fact(tr("Listening on"), text(&t["listener"]), cx));
|
||||||
|
|
||||||
body.child(proxy).child(div().h_flex().gap_4().items_start().child(dpi.flex_1()).child(telegram.flex_1()))
|
body.child(proxy).child(div().h_flex().gap_4().items_start().child(dpi.flex_1()).child(telegram.flex_1())).child(updates(model, cx))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The version, and the newest release when it is newer: installed from here by the service.
|
||||||
|
fn updates(model: &Entity<Model>, cx: &mut Context<AppView>) -> Div {
|
||||||
|
let m = model.read(cx);
|
||||||
|
let update = m.update().clone();
|
||||||
|
let busy = matches!(update, Update::Checking | Update::Installing { .. });
|
||||||
|
let check = {
|
||||||
|
let model = model.clone();
|
||||||
|
Button::new("update-check")
|
||||||
|
.small()
|
||||||
|
.ghost()
|
||||||
|
.icon(IconName::RefreshCw)
|
||||||
|
.label(tr("Check for updates"))
|
||||||
|
.inactive(busy, cx)
|
||||||
|
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.check_update(cx)))
|
||||||
|
};
|
||||||
|
let card = card(trf("Proxy Suite {}", &[&m.version()]), Some(check.into_any_element()), cx);
|
||||||
|
let explain = tr("The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay.");
|
||||||
|
match update {
|
||||||
|
Update::Unknown if !cx.global::<crate::prefs::Prefs>().check_updates => card.child(hint(tr("Updates are not looked for by themselves (Settings → This app)."), cx)),
|
||||||
|
Update::Unknown => card.child(hint(tr("Updates are looked for when the app starts, and daily."), cx)),
|
||||||
|
Update::Checking => card.child(hint(tr("Looking for a newer release…"), cx)),
|
||||||
|
Update::Newest => card.child(hint(tr("This is the newest release."), cx)),
|
||||||
|
Update::Failed(e) => card.child(div().text_sm().text_color(cx.theme().danger).child(trf("Could not look for updates: {}", &[&e]))),
|
||||||
|
Update::Available { version, page } => {
|
||||||
|
let install = {
|
||||||
|
let model = model.clone();
|
||||||
|
Button::new("update-install")
|
||||||
|
.small()
|
||||||
|
.primary()
|
||||||
|
.icon(IconName::Download)
|
||||||
|
.label(trf("Install {}", &[&version]))
|
||||||
|
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.install_update(cx)))
|
||||||
|
};
|
||||||
|
let notes = Button::new("update-notes").small().ghost().icon(IconName::ExternalLink).label(tr("What's new")).on_click(move |_, _, cx| cx.open_url(&page));
|
||||||
|
card.child(div().h_flex().gap_3().items_center().child(div().text_sm().font_semibold().child(trf("{} is out.", &[&version]))).child(install).child(notes)).child(hint(explain, cx))
|
||||||
|
}
|
||||||
|
Update::Installing { version, started: false, .. } => card.child(Alert::info("update-fetching", trf("Fetching {} and checking it…", &[&version]))),
|
||||||
|
Update::Installing { version, started: true, .. } => {
|
||||||
|
card.child(Alert::info("update-running", trf("Installing {}: this app closes, and opens again in a moment.", &[&version])))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("Not connected", "Нет связи со службой"),
|
||||||
|
("The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite.", "Всё работает в службе, а это приложение лишь управляет ею. Установите её с помощью install.cmd из выпуска или запустите от имени администратора: sc start ProxySuite."),
|
||||||
|
("Connecting to the Proxy Suite service…", "Подключение к службе Proxy Suite…"),
|
||||||
|
("The configuration did not apply", "Конфигурация не применилась"),
|
||||||
|
("global TUN", "глобальный TUN"),
|
||||||
|
("Listening on", "Слушает на"),
|
||||||
|
("Backend", "Бэкенд"),
|
||||||
|
("Mode", "Режим"),
|
||||||
|
("Outbound", "Выход"),
|
||||||
|
("{} (pinned)", "{} (закреплён)"),
|
||||||
|
("{} selection", "выбор: {}"),
|
||||||
|
("Use it as the system proxy (browsers and most programs follow it)", "Использовать как системный прокси (ему следуют браузеры и большинство программ)"),
|
||||||
|
("Kill switch", "Kill switch"),
|
||||||
|
("holding: what would leave past the tunnel is blocked", "действует: всё, что пошло бы мимо туннеля, блокируется"),
|
||||||
|
("lifted until a tunnel is turned on", "снят до включения туннеля"),
|
||||||
|
("nothing to hold: no global tunnel is on", "не нужен: ни один общий туннель не включён"),
|
||||||
|
("Lift", "Снять"),
|
||||||
|
("not in place: its filters failed (the Logs say why)", "не действует: фильтры не установлены (причина — в «Журналах»)"),
|
||||||
|
("Hold again", "Включить снова"),
|
||||||
|
("The kill switch holds again", "Kill switch снова действует"),
|
||||||
|
("The kill switch is lifted", "Kill switch снят"),
|
||||||
|
("The system proxy follows the local proxy", "Системный прокси следует за локальным прокси"),
|
||||||
|
("The system proxy is left alone", "Системный прокси не затрагивается"),
|
||||||
|
("Engine", "Движок"),
|
||||||
|
("Preset", "Пресет"),
|
||||||
|
("Check for updates", "Проверить обновления"),
|
||||||
|
("Proxy Suite {}", "Proxy Suite {}"),
|
||||||
|
("The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay.", "Служба загружает установщик из выпусков проекта, проверяет его SHA-256 и запускает: служба и это приложение на мгновение закроются и запустятся снова, уже новые. Настройки сохранятся."),
|
||||||
|
("Updates are not looked for by themselves (Settings → This app).", "Обновления сами не ищутся (Настройки → Это приложение)."),
|
||||||
|
("Updates are looked for when the app starts, and daily.", "Обновления ищутся при запуске приложения и раз в сутки."),
|
||||||
|
("Looking for a newer release…", "Поиск более нового выпуска…"),
|
||||||
|
("This is the newest release.", "Это самый новый выпуск."),
|
||||||
|
("Could not look for updates: {}", "Не удалось проверить обновления: {}"),
|
||||||
|
("Install {}", "Установить {}"),
|
||||||
|
("What's new", "Что нового"),
|
||||||
|
("{} is out.", "Вышла версия {}."),
|
||||||
|
("Fetching {} and checking it…", "Загрузка {} и проверка…"),
|
||||||
|
("Installing {}: this app closes, and opens again in a moment.", "Установка {}: приложение закроется и через мгновение откроется снова."),
|
||||||
|
];
|
||||||
@@ -1,10 +1,12 @@
|
|||||||
//! Settings: the whole configuration, upstream's option tree as JSON, edited here and checked
|
//! Settings: this app's own (its look, updates), and the whole configuration, upstream's option
|
||||||
//! by the service before it takes it. Every option the other pages show is here too, and the
|
//! tree as JSON, edited here and checked by the service before it takes it. Every option the
|
||||||
//! ones they do not.
|
//! other pages show is here too, and the ones they do not.
|
||||||
|
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||||
use gpui_kit::component::input::{Editor, EditorState, InputEvent};
|
use gpui_kit::component::input::{Editor, EditorState, InputEvent};
|
||||||
|
use gpui_kit::component::radio::RadioGroup;
|
||||||
|
use gpui_kit::component::switch::Switch;
|
||||||
use gpui_kit::component::*;
|
use gpui_kit::component::*;
|
||||||
use gpui_kit::prelude::FluentBuilder as _;
|
use gpui_kit::prelude::FluentBuilder as _;
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
@@ -12,8 +14,10 @@ use ps_client::Issue;
|
|||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
use super::widgets::{card, hint, page};
|
use super::widgets::{card, hint, page, Inactive as _};
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
use crate::prefs::{self, Language, Prefs, ThemeChoice};
|
||||||
|
|
||||||
/// What the service shows in place of a secret the caller may not read; saved back as it is,
|
/// What the service shows in place of a secret the caller may not read; saved back as it is,
|
||||||
/// the secret keeps its value.
|
/// the secret keeps its value.
|
||||||
@@ -51,7 +55,7 @@ impl SettingsPage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
self.verdict = Verdict::Working("Loading…");
|
self.verdict = Verdict::Working(tr("Loading…"));
|
||||||
cx.notify();
|
cx.notify();
|
||||||
let job = self.model.read(cx).bridge().call(Request::ConfigGet);
|
let job = self.model.read(cx).bridge().call(Request::ConfigGet);
|
||||||
cx.spawn_in(window, async move |this, cx| {
|
cx.spawn_in(window, async move |this, cx| {
|
||||||
@@ -75,7 +79,7 @@ impl SettingsPage {
|
|||||||
|
|
||||||
/// The editor's text as JSON, or where it is not.
|
/// The editor's text as JSON, or where it is not.
|
||||||
fn parsed(&self, cx: &App) -> Result<Value, String> {
|
fn parsed(&self, cx: &App) -> Result<Value, String> {
|
||||||
serde_json::from_str(&self.editor.read(cx).value()).map_err(|e| format!("Not valid JSON: {e}"))
|
serde_json::from_str(&self.editor.read(cx).value()).map_err(|e| trf("Not valid JSON: {}", &[&e]))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn validate(&mut self, cx: &mut Context<Self>) {
|
fn validate(&mut self, cx: &mut Context<Self>) {
|
||||||
@@ -86,7 +90,7 @@ impl SettingsPage {
|
|||||||
return cx.notify();
|
return cx.notify();
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
self.verdict = Verdict::Working("Checking…");
|
self.verdict = Verdict::Working(tr("Checking…"));
|
||||||
cx.notify();
|
cx.notify();
|
||||||
let job = self.model.read(cx).bridge().call(Request::ConfigValidate { config });
|
let job = self.model.read(cx).bridge().call(Request::ConfigValidate { config });
|
||||||
cx.spawn(async move |this, cx| {
|
cx.spawn(async move |this, cx| {
|
||||||
@@ -112,7 +116,7 @@ impl SettingsPage {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
let base = self.loaded.as_ref().map(|(_, r)| *r);
|
let base = self.loaded.as_ref().map(|(_, r)| *r);
|
||||||
self.verdict = Verdict::Working("Saving…");
|
self.verdict = Verdict::Working(tr("Saving…"));
|
||||||
cx.notify();
|
cx.notify();
|
||||||
let job = self.model.read(cx).bridge().call(Request::ConfigSet { config, base });
|
let job = self.model.read(cx).bridge().call(Request::ConfigSet { config, base });
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
@@ -127,7 +131,7 @@ impl SettingsPage {
|
|||||||
Verdict::Saved { revision, issues: ps_client::issues(&r), apply_error: r["error"].as_str().map(str::to_owned) }
|
Verdict::Saved { revision, issues: ps_client::issues(&r), apply_error: r["error"].as_str().map(str::to_owned) }
|
||||||
}
|
}
|
||||||
Err(e) if e.to_string().contains("changed since revision") => {
|
Err(e) if e.to_string().contains("changed since revision") => {
|
||||||
Verdict::Failed("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).".into())
|
Verdict::Failed(tr("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).").into())
|
||||||
}
|
}
|
||||||
Err(e) => Verdict::Failed(format!("{e:#}")),
|
Err(e) => Verdict::Failed(format!("{e:#}")),
|
||||||
};
|
};
|
||||||
@@ -152,6 +156,38 @@ fn issue_list(issues: &[Issue], cx: &App) -> Div {
|
|||||||
list
|
list
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The app's own preferences, this user's: not the service's configuration.
|
||||||
|
fn this_app(cx: &App) -> Div {
|
||||||
|
let p = cx.global::<Prefs>().clone();
|
||||||
|
let theme = RadioGroup::horizontal("app-theme")
|
||||||
|
.children(ThemeChoice::ALL.map(|(_, label)| tr(label)))
|
||||||
|
.selected_index(ThemeChoice::ALL.iter().position(|(t, _)| *t == p.theme))
|
||||||
|
.on_change(|ix, _, cx| {
|
||||||
|
let choice = ThemeChoice::ALL[*ix].0;
|
||||||
|
prefs::change(cx, |p| p.theme = choice);
|
||||||
|
});
|
||||||
|
let language = RadioGroup::horizontal("app-language")
|
||||||
|
.children(Language::ALL.map(|(_, label)| tr(label)))
|
||||||
|
.selected_index(Language::ALL.iter().position(|(l, _)| *l == p.language))
|
||||||
|
.on_change(|ix, _, cx| {
|
||||||
|
let language = Language::ALL[*ix].0;
|
||||||
|
prefs::change(cx, |p| p.language = language);
|
||||||
|
});
|
||||||
|
let updates = Switch::new("app-check-updates")
|
||||||
|
.label(tr("Look for a newer release when the app starts, and daily"))
|
||||||
|
.checked(p.check_updates)
|
||||||
|
.on_change(|on, _, cx| {
|
||||||
|
let on = *on;
|
||||||
|
prefs::change(cx, |p| p.check_updates = on);
|
||||||
|
});
|
||||||
|
let row = |label: &'static str, control: AnyElement| div().h_flex().gap_4().items_center().child(div().text_sm().w(px(110.)).text_color(cx.theme().muted_foreground).child(label)).child(control);
|
||||||
|
card(tr("This app"), None, cx)
|
||||||
|
.child(row(tr("Language"), language.into_any_element()))
|
||||||
|
.child(row(tr("Theme"), theme.into_any_element()))
|
||||||
|
.child(updates)
|
||||||
|
.child(hint(tr("Yours alone, kept with your Windows account; the service's configuration is below."), cx))
|
||||||
|
}
|
||||||
|
|
||||||
impl Render for SettingsPage {
|
impl Render for SettingsPage {
|
||||||
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
|
||||||
let text = self.editor.read(cx).value();
|
let text = self.editor.read(cx).value();
|
||||||
@@ -161,30 +197,57 @@ impl Render for SettingsPage {
|
|||||||
let actions = div()
|
let actions = div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(Button::new("cfg-reload").small().ghost().icon(IconName::RefreshCw).label("Reload").on_click(cx.listener(|this, _, window, cx| this.reload(window, cx))))
|
.child(Button::new("cfg-reload").small().ghost().icon(IconName::RefreshCw).label(tr("Reload")).on_click(cx.listener(|this, _, window, cx| this.reload(window, cx))))
|
||||||
.child(Button::new("cfg-validate").small().label("Check").on_click(cx.listener(|this, _, _, cx| this.validate(cx))))
|
.child(Button::new("cfg-validate").small().label(tr("Check")).on_click(cx.listener(|this, _, _, cx| this.validate(cx))))
|
||||||
.child(Button::new("cfg-save").small().primary().icon(IconName::Save).label("Save").disabled(!changed).on_click(cx.listener(|this, _, _, cx| this.save(cx))));
|
.child(Button::new("cfg-save").small().primary().icon(IconName::Save).label(tr("Save")).inactive(!changed, cx).on_click(cx.listener(|this, _, _, cx| this.save(cx))));
|
||||||
|
|
||||||
let verdict = match &self.verdict {
|
let verdict = match &self.verdict {
|
||||||
Verdict::None => div(),
|
Verdict::None => div(),
|
||||||
Verdict::Working(what) => hint(*what, cx),
|
Verdict::Working(what) => hint(*what, cx),
|
||||||
Verdict::Failed(e) => div().text_sm().text_color(cx.theme().danger).child(e.clone()),
|
Verdict::Failed(e) => div().text_sm().text_color(cx.theme().danger).child(e.clone()),
|
||||||
Verdict::Issues(issues) if issues.is_empty() => div().text_sm().text_color(cx.theme().success).child("It is valid."),
|
Verdict::Issues(issues) if issues.is_empty() => div().text_sm().text_color(cx.theme().success).child(tr("It is valid.")),
|
||||||
Verdict::Issues(issues) => issue_list(issues, cx),
|
Verdict::Issues(issues) => issue_list(issues, cx),
|
||||||
Verdict::Saved { revision, issues, apply_error } => div()
|
Verdict::Saved { revision, issues, apply_error } => div()
|
||||||
.v_flex()
|
.v_flex()
|
||||||
.gap_1()
|
.gap_1()
|
||||||
.child(div().text_sm().text_color(cx.theme().success).child(format!("Saved as revision {revision}.")))
|
.child(div().text_sm().text_color(cx.theme().success).child(trf("Saved as revision {}.", &[&revision])))
|
||||||
.when_some(apply_error.clone(), |d, e| d.child(div().text_sm().text_color(cx.theme().danger).child(format!("Saved, but not applied: {e}"))))
|
.when_some(apply_error.clone(), |d, e| d.child(div().text_sm().text_color(cx.theme().danger).child(trf("Saved, but not applied: {}", &[&e]))))
|
||||||
.child(issue_list(issues, cx)),
|
.child(issue_list(issues, cx)),
|
||||||
};
|
};
|
||||||
|
|
||||||
page("Settings", cx).child(
|
page(tr("Settings"), cx).child(this_app(cx)).child(
|
||||||
card("Configuration", Some(actions.into_any_element()), cx)
|
card(tr("Configuration"), Some(actions.into_any_element()), cx)
|
||||||
.child(hint("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator.", cx))
|
.child(hint(tr("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator."), cx))
|
||||||
.when(redacted, |d| d.child(hint("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values.", cx)))
|
.when(redacted, |d| d.child(hint(tr("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values."), cx)))
|
||||||
.child(div().h(px(480.)).border_1().border_color(cx.theme().border).rounded_md().child(Editor::new(&self.editor).h_full()))
|
.child(div().h(px(480.)).border_1().border_color(cx.theme().border).rounded_md().child(Editor::new(&self.editor).h_full()))
|
||||||
.child(verdict),
|
.child(verdict),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("Loading…", "Загрузка…"),
|
||||||
|
("Checking…", "Проверка…"),
|
||||||
|
("Saving…", "Сохранение…"),
|
||||||
|
("Not valid JSON: {}", "Некорректный JSON: {}"),
|
||||||
|
("The configuration was changed elsewhere since it was loaded. Reload to see it (your edits here are then lost; copy them first).", "Конфигурация была изменена в другом месте после загрузки. Перечитайте её, чтобы увидеть изменения (ваши правки здесь при этом пропадут; сначала скопируйте их)."),
|
||||||
|
("As Windows", "Как в Windows"),
|
||||||
|
("Light", "Светлая"),
|
||||||
|
("Dark", "Тёмная"),
|
||||||
|
("Look for a newer release when the app starts, and daily", "Искать новый выпуск при запуске приложения и раз в сутки"),
|
||||||
|
("This app", "Это приложение"),
|
||||||
|
("Language", "Язык"),
|
||||||
|
("Theme", "Тема"),
|
||||||
|
("Yours alone, kept with your Windows account; the service's configuration is below.", "Только ваши, хранятся в вашей учётной записи Windows; конфигурация службы ниже."),
|
||||||
|
("Reload", "Перечитать"),
|
||||||
|
("Check", "Проверить"),
|
||||||
|
("Save", "Сохранить"),
|
||||||
|
("It is valid.", "Конфигурация корректна."),
|
||||||
|
("Saved as revision {}.", "Сохранено как ревизия {}."),
|
||||||
|
("Saved, but not applied: {}", "Сохранено, но не применено: {}"),
|
||||||
|
("Settings", "Настройки"),
|
||||||
|
("Configuration", "Конфигурация"),
|
||||||
|
("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator.", "Параметры upstream (services.proxy-suite…) в виде JSON, как их выводит proxy-ctl config get. Служба проверяет их, прежде чем принять; параметры, запускающие программы или читающие файлы, требуют прав администратора."),
|
||||||
|
("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values.", "Значения вида •••redacted••• — секреты, которые вам здесь читать нельзя; если оставить их как есть, они сохранят свои значения."),
|
||||||
|
];
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
//! The Telegram proxy (Flowseal's tg-ws-proxy): on or off, the links to open in Telegram, and
|
//! The Telegram proxy (Flowseal's tg-ws-proxy): on or off, the links to open in Telegram, and
|
||||||
//! where it listens.
|
//! where it listens.
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
use gpui_kit::component::button::{Button, ButtonVariants as _};
|
||||||
use gpui_kit::component::input::{Input, InputState};
|
use gpui_kit::component::input::{Input, InputState};
|
||||||
@@ -26,7 +27,7 @@ pub struct TelegramPage {
|
|||||||
impl TelegramPage {
|
impl TelegramPage {
|
||||||
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
|
||||||
let port = cx.new(|cx| InputState::new(window, cx).placeholder("1443"));
|
let port = cx.new(|cx| InputState::new(window, cx).placeholder("1443"));
|
||||||
let fake_tls = cx.new(|cx| InputState::new(window, cx).placeholder("none"));
|
let fake_tls = cx.new(|cx| InputState::new(window, cx).placeholder(tr("none")));
|
||||||
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
|
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
|
||||||
let mut this = Self { model, port, fake_tls, shown: Default::default(), _subscriptions: subscriptions };
|
let mut this = Self { model, port, fake_tls, shown: Default::default(), _subscriptions: subscriptions };
|
||||||
this.sync(window, cx);
|
this.sync(window, cx);
|
||||||
@@ -55,14 +56,14 @@ impl TelegramPage {
|
|||||||
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
|
||||||
let port_text = self.port.read(cx).value().trim().to_owned();
|
let port_text = self.port.read(cx).value().trim().to_owned();
|
||||||
let Ok(port) = port_text.parse::<u16>() else {
|
let Ok(port) = port_text.parse::<u16>() else {
|
||||||
window.push_notification(Notification::error(format!("“{port_text}” is not a port (1–65535)")), cx);
|
window.push_notification(Notification::error(trf("“{}” is not a port (1–65535)", &[&port_text])), cx);
|
||||||
return;
|
return;
|
||||||
};
|
};
|
||||||
let domain = self.fake_tls.read(cx).value().trim().to_owned();
|
let domain = self.fake_tls.read(cx).value().trim().to_owned();
|
||||||
self.shown = (self.port.read(cx).value().to_string(), self.fake_tls.read(cx).value().to_string());
|
self.shown = (self.port.read(cx).value().to_string(), self.fake_tls.read(cx).value().to_string());
|
||||||
self.model.update(cx, |m, cx| {
|
self.model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
"Telegram proxy saved",
|
tr("Telegram proxy saved"),
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["tgWsProxy", "listener", "port"], port.into());
|
edits::set_path(c, &["tgWsProxy", "listener", "port"], port.into());
|
||||||
edits::set_path(c, &["tgWsProxy", "fakeTlsDomain"], if domain.is_empty() { Value::Null } else { domain.clone().into() });
|
edits::set_path(c, &["tgWsProxy", "fakeTlsDomain"], if domain.is_empty() { Value::Null } else { domain.clone().into() });
|
||||||
@@ -80,9 +81,9 @@ impl Render for TelegramPage {
|
|||||||
let status = m.status()["tgWsProxy"].clone();
|
let status = m.status()["tgWsProxy"].clone();
|
||||||
let t = m.config()["tgWsProxy"].clone();
|
let t = m.config()["tgWsProxy"].clone();
|
||||||
let links = m.tg_links().to_vec();
|
let links = m.tg_links().to_vec();
|
||||||
let body = page("Telegram proxy", cx);
|
let body = page(tr("Telegram proxy"), cx);
|
||||||
if t.is_null() {
|
if t.is_null() {
|
||||||
return body.child(hint("Waiting for the service…", cx));
|
return body.child(hint(tr("Waiting for the service…"), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
@@ -90,7 +91,7 @@ impl Render for TelegramPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
|
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_tg_ws_proxy_enabled(c, on);
|
edits::set_tg_ws_proxy_enabled(c, on);
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -100,9 +101,9 @@ impl Render for TelegramPage {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut link_card = card("Links", None, cx).child(hint("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy.", cx));
|
let mut link_card = card(tr("Links"), None, cx).child(hint(tr("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy."), cx));
|
||||||
if links.is_empty() {
|
if links.is_empty() {
|
||||||
link_card = link_card.child(hint("No links: reading them needs the secrets scope (userControl).", cx));
|
link_card = link_card.child(hint(tr("No links: reading them needs the secrets scope (userControl)."), cx));
|
||||||
}
|
}
|
||||||
for (i, link) in links.into_iter().enumerate() {
|
for (i, link) in links.into_iter().enumerate() {
|
||||||
let (copy, open) = (link.clone(), link.clone());
|
let (copy, open) = (link.clone(), link.clone());
|
||||||
@@ -112,21 +113,21 @@ impl Render for TelegramPage {
|
|||||||
.gap_2()
|
.gap_2()
|
||||||
.items_center()
|
.items_center()
|
||||||
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link))
|
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link))
|
||||||
.child(Button::new(("copy-link", i)).small().icon(IconName::Copy).label("Copy").on_click(move |_, window, cx| {
|
.child(Button::new(("copy-link", i)).small().icon(IconName::Copy).label(tr("Copy")).on_click(move |_, window, cx| {
|
||||||
cx.write_to_clipboard(ClipboardItem::new_string(copy.to_string()));
|
cx.write_to_clipboard(ClipboardItem::new_string(copy.to_string()));
|
||||||
window.push_notification(Notification::success("Copied"), cx);
|
window.push_notification(Notification::success(tr("Copied")), cx);
|
||||||
}))
|
}))
|
||||||
.child(Button::new(("open-link", i)).small().primary().icon(IconName::Send).label("Open in Telegram").on_click(move |_, _, cx| cx.open_url(&open))),
|
.child(Button::new(("open-link", i)).small().primary().icon(IconName::Send).label(tr("Open in Telegram")).on_click(move |_, _, cx| cx.open_url(&open))),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let shared = t["listener"]["address"] == "0.0.0.0";
|
let shared = t["listener"]["address"] == "0.0.0.0";
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
let lan = Switch::new("tg-lan").label("Let other devices on this network connect (phones, other computers)").checked(shared).on_change(move |on, _, cx| {
|
let lan = Switch::new("tg-lan").label(tr("Let other devices on this network connect (phones, other computers)")).checked(shared).on_change(move |on, _, cx| {
|
||||||
let address = if *on { "0.0.0.0" } else { "127.0.0.1" };
|
let address = if *on { "0.0.0.0" } else { "127.0.0.1" };
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if address == "0.0.0.0" { "Other devices may connect" } else { "Only this computer may connect" },
|
if address == "0.0.0.0" { tr("Other devices may connect") } else { tr("Only this computer may connect") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["tgWsProxy", "listener", "address"], json!(address));
|
edits::set_path(c, &["tgWsProxy", "listener", "address"], json!(address));
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -139,13 +140,13 @@ impl Render for TelegramPage {
|
|||||||
body.child(
|
body.child(
|
||||||
card("tg-ws-proxy", Some(enable.into_any_element()), cx)
|
card("tg-ws-proxy", Some(enable.into_any_element()), cx)
|
||||||
.child(div().h_flex().child(state_tag(status["state"].as_str().unwrap_or("unknown"))))
|
.child(div().h_flex().child(state_tag(status["state"].as_str().unwrap_or("unknown"))))
|
||||||
.child(hint("Telegram over WebSocket to its own servers, for networks that block its usual connections.", cx)),
|
.child(hint(tr("Telegram over WebSocket to its own servers, for networks that block its usual connections."), cx)),
|
||||||
)
|
)
|
||||||
.child(link_card)
|
.child(link_card)
|
||||||
.child(
|
.child(
|
||||||
card(
|
card(
|
||||||
"Listening",
|
tr("Listening"),
|
||||||
Some(Button::new("tg-save").small().label("Save").on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()),
|
Some(Button::new("tg-save").small().label(tr("Save")).on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()),
|
||||||
cx,
|
cx,
|
||||||
)
|
)
|
||||||
.child(lan)
|
.child(lan)
|
||||||
@@ -153,9 +154,33 @@ impl Render for TelegramPage {
|
|||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_4()
|
.gap_4()
|
||||||
.child(div().v_flex().gap_1().w(px(160.)).child(div().text_sm().child("Port")).child(Input::new(&self.port)))
|
.child(div().v_flex().gap_1().w(px(160.)).child(div().text_sm().child(tr("Port"))).child(Input::new(&self.port)))
|
||||||
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Fake-TLS domain (ee links)")).child(Input::new(&self.fake_tls))),
|
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child(tr("Fake-TLS domain (ee links)"))).child(Input::new(&self.fake_tls))),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("none", "нет"),
|
||||||
|
("“{}” is not a port (1–65535)", "«{}» — не порт (1–65535)"),
|
||||||
|
("Telegram proxy saved", "Прокси для Telegram сохранён"),
|
||||||
|
("Waiting for the service…", "Ожидание службы…"),
|
||||||
|
("The Telegram proxy is on", "Прокси для Telegram включён"),
|
||||||
|
("The Telegram proxy is off", "Прокси для Telegram выключен"),
|
||||||
|
("Links", "Ссылки"),
|
||||||
|
("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy.", "Откройте ссылку в Telegram или скопируйте её на телефон: Telegram будет подключаться через этот прокси."),
|
||||||
|
("No links: reading them needs the secrets scope (userControl).", "Ссылок нет: чтобы их прочитать, нужна область секретов (userControl)."),
|
||||||
|
("Copy", "Копировать"),
|
||||||
|
("Copied", "Скопировано"),
|
||||||
|
("Open in Telegram", "Открыть в Telegram"),
|
||||||
|
("Let other devices on this network connect (phones, other computers)", "Разрешить подключаться другим устройствам этой сети (телефонам, другим компьютерам)"),
|
||||||
|
("Other devices may connect", "Другим устройствам подключаться можно"),
|
||||||
|
("Only this computer may connect", "Подключаться может только этот компьютер"),
|
||||||
|
("Telegram over WebSocket to its own servers, for networks that block its usual connections.", "Telegram через WebSocket к его собственным серверам — для сетей, где обычные подключения заблокированы."),
|
||||||
|
("Listening", "Прослушивание"),
|
||||||
|
("Save", "Сохранить"),
|
||||||
|
("Port", "Порт"),
|
||||||
|
("Fake-TLS domain (ee links)", "Домен Fake-TLS (ссылки ee)"),
|
||||||
|
];
|
||||||
@@ -16,6 +16,7 @@ use ps_client::edits;
|
|||||||
use ps_ipc::Request;
|
use ps_ipc::Request;
|
||||||
use serde_json::Value;
|
use serde_json::Value;
|
||||||
|
|
||||||
|
use crate::i18n::{tr, trf};
|
||||||
use super::widgets::{card, hint, page, state_tag};
|
use super::widgets::{card, hint, page, state_tag};
|
||||||
use crate::model::Model;
|
use crate::model::Model;
|
||||||
|
|
||||||
@@ -57,7 +58,7 @@ impl WhitelistPage {
|
|||||||
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
|
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
|
||||||
self.joins.retain(|n, _| joiners.contains(n));
|
self.joins.retain(|n, _| joiners.contains(n));
|
||||||
for n in joiners {
|
for n in joiners {
|
||||||
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder("the creator's call link")));
|
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder(tr("the creator's call link"))));
|
||||||
}
|
}
|
||||||
let creators: Vec<(String, String)> =
|
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();
|
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();
|
||||||
@@ -65,8 +66,8 @@ impl WhitelistPage {
|
|||||||
for (n, platform) in creators {
|
for (n, platform) in creators {
|
||||||
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
|
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
|
||||||
let login = PasswordLogin {
|
let login = PasswordLogin {
|
||||||
email: cx.new(|cx| InputState::new(window, cx).placeholder("email")),
|
email: cx.new(|cx| InputState::new(window, cx).placeholder(tr("email"))),
|
||||||
password: cx.new(|cx| InputState::new(window, cx).placeholder("password").masked(true)),
|
password: cx.new(|cx| InputState::new(window, cx).placeholder(tr("password")).masked(true)),
|
||||||
portal: (platform == "bitrix").then(|| cx.new(|cx| InputState::new(window, cx).placeholder("portal.bitrix24.ru"))),
|
portal: (platform == "bitrix").then(|| cx.new(|cx| InputState::new(window, cx).placeholder("portal.bitrix24.ru"))),
|
||||||
};
|
};
|
||||||
self.logins.insert(n, login);
|
self.logins.insert(n, login);
|
||||||
@@ -83,7 +84,7 @@ impl WhitelistPage {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
self.name.update(cx, |s, cx| s.set_value("", window, cx));
|
self.name.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
let what = format!("{} '{name}' added", if role == "joiners" { "Joiner" } else { "Creator" });
|
let what = if role == "joiners" { trf("Joiner '{}' added", &[&name]) } else { trf("Creator '{}' added", &[&name]) };
|
||||||
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_wl(c, role, &name, platform), cx));
|
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_wl(c, role, &name, platform), cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,11 +92,11 @@ impl WhitelistPage {
|
|||||||
let Some(input) = self.joins.get(&name) else { return };
|
let Some(input) = self.joins.get(&name) else { return };
|
||||||
let link = input.read(cx).value().trim().to_owned();
|
let link = input.read(cx).value().trim().to_owned();
|
||||||
if link.is_empty() {
|
if link.is_empty() {
|
||||||
window.push_notification(Notification::error("Paste the link the creator's side gave (its proxy-ctl wl link)"), cx);
|
window.push_notification(Notification::error(tr("Paste the link the creator's side gave (its proxy-ctl wl link)")), cx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
input.update(cx, |s, cx| s.set_value("", window, cx));
|
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));
|
self.model.update(cx, |m, cx| m.request(trf("'{}' joins the call", &[&name]), Request::WlJoin { name, link }, cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn link(&mut self, name: String, cx: &mut Context<Self>) {
|
fn link(&mut self, name: String, cx: &mut Context<Self>) {
|
||||||
@@ -113,15 +114,15 @@ impl WhitelistPage {
|
|||||||
|
|
||||||
/// A cookies export, chosen: read here, as the signed-in user, and handed to the service.
|
/// 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>) {
|
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 paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some(tr("Log in").into()) });
|
||||||
let model = self.model.clone();
|
let model = self.model.clone();
|
||||||
cx.spawn(async move |_, cx| {
|
cx.spawn(async move |_, cx| {
|
||||||
let Ok(Ok(Some(paths))) = paths.await else { return };
|
let Ok(Ok(Some(paths))) = paths.await else { return };
|
||||||
let Some(path) = paths.into_iter().next() else { return };
|
let Some(path) = paths.into_iter().next() else { return };
|
||||||
let login = std::fs::read_to_string(&path);
|
let login = std::fs::read_to_string(&path);
|
||||||
model.update(cx, |m, cx| match login {
|
model.update(cx, |m, cx| match login {
|
||||||
Ok(login) => m.request(format!("'{name}' has its login"), Request::WlAuth { name, login }, cx),
|
Ok(login) => m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx),
|
||||||
Err(e) => m.track(format!("Reading {}", path.display()), async move { Err(e.into()) }, cx),
|
Err(e) => m.track(trf("Reading {}", &[&path.display()]), async move { Err(e.into()) }, cx),
|
||||||
});
|
});
|
||||||
})
|
})
|
||||||
.detach();
|
.detach();
|
||||||
@@ -137,16 +138,16 @@ impl WhitelistPage {
|
|||||||
login.insert("portal".into(), if portal.contains("://") { portal } else { format!("https://{portal}") }.into());
|
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://") {
|
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);
|
window.push_notification(Notification::error(tr("Fill in every field")), cx);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
l.password.update(cx, |s, cx| s.set_value("", window, cx));
|
l.password.update(cx, |s, cx| s.set_value("", window, cx));
|
||||||
let login = Value::Object(login).to_string();
|
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));
|
self.model.update(cx, |m, cx| m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx));
|
||||||
}
|
}
|
||||||
|
|
||||||
fn remove(&mut self, role: &'static str, name: String, cx: &mut Context<Self>) {
|
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));
|
self.model.update(cx, |m, cx| m.edit(trf("'{}' removed", &[&name]), move |c| edits::remove_wl(c, role, &name), cx));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -167,9 +168,9 @@ impl Render for WhitelistPage {
|
|||||||
let m = self.model.read(cx);
|
let m = self.model.read(cx);
|
||||||
let w = m.config()["whitelistBypass"].clone();
|
let w = m.config()["whitelistBypass"].clone();
|
||||||
let status = m.status().clone();
|
let status = m.status().clone();
|
||||||
let body = page("Whitelist bypass", cx);
|
let body = page(tr("Whitelist bypass"), cx);
|
||||||
if m.config().is_null() {
|
if m.config().is_null() {
|
||||||
return body.child(hint("Waiting for the service…", cx));
|
return body.child(hint(tr("Waiting for the service…"), cx));
|
||||||
}
|
}
|
||||||
let on = w["enable"] == true;
|
let on = w["enable"] == true;
|
||||||
|
|
||||||
@@ -178,7 +179,7 @@ impl Render for WhitelistPage {
|
|||||||
let on = *on;
|
let on = *on;
|
||||||
model.update(cx, |m, cx| {
|
model.update(cx, |m, cx| {
|
||||||
m.edit(
|
m.edit(
|
||||||
if on { "Whitelist bypass is on" } else { "Whitelist bypass is off" },
|
if on { tr("Whitelist bypass is on") } else { tr("Whitelist bypass is off") },
|
||||||
move |c| {
|
move |c| {
|
||||||
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
|
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -188,15 +189,15 @@ impl Render for WhitelistPage {
|
|||||||
})
|
})
|
||||||
});
|
});
|
||||||
let about = card("whitelist-bypass", Some(enable.into_any_element()), cx).child(hint(
|
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.",
|
tr("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,
|
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 mut joiners = card(tr("Joiners"), None, cx).child(hint(tr("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)> =
|
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();
|
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() {
|
if joiner_list.is_empty() {
|
||||||
joiners = joiners.child(hint("None yet: add one below.", cx));
|
joiners = joiners.child(hint(tr("None yet: add one below."), cx));
|
||||||
}
|
}
|
||||||
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
|
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
|
||||||
let Some(input) = self.joins.get(&name) else { continue };
|
let Some(input) = self.joins.get(&name) else { continue };
|
||||||
@@ -225,19 +226,19 @@ impl Render for WhitelistPage {
|
|||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_2()
|
.gap_2()
|
||||||
.child(div().flex_1().min_w_0().child(Input::new(input)))
|
.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)))),
|
.child(Button::new(("wl-join", i)).small().primary().label(tr("Join")).on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut creators = card("Creators", None, cx).child(hint(
|
let mut creators = card(tr("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.",
|
tr("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,
|
cx,
|
||||||
));
|
));
|
||||||
let creator_list: Vec<(String, String)> =
|
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();
|
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() {
|
if creator_list.is_empty() {
|
||||||
creators = creators.child(hint("None here.", cx));
|
creators = creators.child(hint(tr("None here."), cx));
|
||||||
}
|
}
|
||||||
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
|
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
|
||||||
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
|
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
|
||||||
@@ -257,13 +258,13 @@ impl Render for WhitelistPage {
|
|||||||
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
|
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
|
||||||
.child(state_tag(&state))
|
.child(state_tag(&state))
|
||||||
.child(div().flex_1())
|
.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-link", i)).small().icon(IconName::Link).label(tr("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| {
|
.child(Button::new(("wl-new", i)).small().icon(IconName::RefreshCw).label(tr("New call")).on_click(cx.listener(move |this, _, _, cx| {
|
||||||
this.links.remove(&n2);
|
this.links.remove(&n2);
|
||||||
let name = n2.clone();
|
let name = n2.clone();
|
||||||
this.model.update(cx, |m, cx| m.request(format!("'{name}' starts a new call"), Request::WlNew { name }, cx));
|
this.model.update(cx, |m, cx| m.request(trf("'{}' starts a new call", &[&name]), 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-cookies", i)).small().icon(IconName::FileUp).label(tr("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)))),
|
.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) {
|
match self.links.get(&name) {
|
||||||
@@ -275,9 +276,9 @@ impl Render for WhitelistPage {
|
|||||||
.gap_2()
|
.gap_2()
|
||||||
.items_center()
|
.items_center()
|
||||||
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link.clone()))
|
.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| {
|
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label(tr("Copy")).on_click(move |_, window, cx| {
|
||||||
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
|
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
|
||||||
window.push_notification(Notification::success("Copied"), cx);
|
window.push_notification(Notification::success(tr("Copied")), cx);
|
||||||
})),
|
})),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -289,30 +290,70 @@ impl Render for WhitelistPage {
|
|||||||
if let Some(p) = &l.portal {
|
if let Some(p) = &l.portal {
|
||||||
fields = fields.child(div().flex_1().min_w_0().child(Input::new(p)));
|
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)))));
|
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label(tr("Log in")).on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
|
||||||
}
|
}
|
||||||
creators = creators.child(row);
|
creators = creators.child(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
let platforms = RadioGroup::horizontal("wl-platform")
|
let platforms = RadioGroup::horizontal("wl-platform")
|
||||||
.children(PLATFORMS.map(|(_, label)| label))
|
.children(PLATFORMS.map(|(_, label)| tr(label)))
|
||||||
.selected_index(Some(self.platform))
|
.selected_index(Some(self.platform))
|
||||||
.on_change(cx.listener(|this, ix: &usize, _, cx| {
|
.on_change(cx.listener(|this, ix: &usize, _, cx| {
|
||||||
this.platform = *ix;
|
this.platform = *ix;
|
||||||
cx.notify();
|
cx.notify();
|
||||||
}));
|
}));
|
||||||
let add = card("Add", None, cx)
|
let add = card(tr("Add"), None, cx)
|
||||||
.child(div().v_flex().gap_1().child(div().text_sm().child("Name (letters, digits, '.', '_', '-')")).child(Input::new(&self.name)))
|
.child(div().v_flex().gap_1().child(div().text_sm().child(tr("Name (letters, digits, '.', '_', '-')"))).child(Input::new(&self.name)))
|
||||||
.child(platforms)
|
.child(platforms)
|
||||||
.child(
|
.child(
|
||||||
div()
|
div()
|
||||||
.h_flex()
|
.h_flex()
|
||||||
.gap_2()
|
.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-joiner").small().icon(IconName::Plus).label(tr("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(Button::new("wl-add-creator").small().icon(IconName::Plus).label(tr("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));
|
.child(hint(tr("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass."), cx));
|
||||||
|
|
||||||
body.child(about).child(joiners).child(creators).child(add)
|
body.child(about).child(joiners).child(creators).child(add)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// This page's words, in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("the creator's call link", "ссылка на звонок от создателя"),
|
||||||
|
("email", "эл. почта"),
|
||||||
|
("password", "пароль"),
|
||||||
|
("Joiner '{}' added", "Участник «{}» добавлен"),
|
||||||
|
("Creator '{}' added", "Создатель «{}» добавлен"),
|
||||||
|
("Paste the link the creator's side gave (its proxy-ctl wl link)", "Вставьте ссылку от стороны создателя (её ссылка из proxy-ctl wl link)"),
|
||||||
|
("'{}' joins the call", "«{}» подключается к звонку"),
|
||||||
|
("Log in", "Войти"),
|
||||||
|
("'{}' has its login", "Для «{}» заданы данные для входа"),
|
||||||
|
("Reading {}", "Чтение {}"),
|
||||||
|
("Fill in every field", "Заполните все поля"),
|
||||||
|
("'{}' removed", "Удалено: «{}»"),
|
||||||
|
("Whitelist bypass", "Обход белых списков"),
|
||||||
|
("Waiting for the service…", "Ожидание службы…"),
|
||||||
|
("Whitelist bypass is on", "Обход белых списков включён"),
|
||||||
|
("Whitelist bypass is off", "Обход белых списков выключен"),
|
||||||
|
("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.", "Для сетей, пропускающих только белый список, в котором есть видеозвонки: участник здесь пускает трафик прокси через звонок, который держит открытым создатель на машине с обычным интернетом. Закрепите выход участника (раздел «Выходы»), чтобы направить трафик через него."),
|
||||||
|
("Joiners", "Участники"),
|
||||||
|
("Each is an outbound of the proxy, named as here. It joins the call whose link its creator gives.", "Каждый участник — выход прокси с тем же именем. Он подключается к звонку по ссылке, которую даёт его создатель."),
|
||||||
|
("None yet: add one below.", "Пока нет: добавьте ниже."),
|
||||||
|
("Join", "Подключиться"),
|
||||||
|
("Creators", "Создатели"),
|
||||||
|
("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.", "На машине с обычным интернетом. Каждый создатель входит на свою платформу (экспорт cookies из настольного приложения Creator или из браузера; DION и Bitrix принимают эл. почту и пароль), запускает звонок и держит его: передайте его ссылку участнику."),
|
||||||
|
("None here.", "Пока нет."),
|
||||||
|
("Call link", "Ссылка на звонок"),
|
||||||
|
("New call", "Новый звонок"),
|
||||||
|
("'{}' starts a new call", "«{}» начинает новый звонок"),
|
||||||
|
("Cookies file…", "Файл cookies…"),
|
||||||
|
("Copy", "Копировать"),
|
||||||
|
("Copied", "Скопировано"),
|
||||||
|
("Add", "Добавить"),
|
||||||
|
("Name (letters, digits, '.', '_', '-')", "Имя (буквы, цифры, «.», «_», «-»)"),
|
||||||
|
("Add a joiner", "Добавить участника"),
|
||||||
|
("Add a creator", "Добавить создателя"),
|
||||||
|
("Their other options (linkFile, cookiesFile, upstream, resources) are in Settings, under whitelistBypass.", "Остальные их параметры (linkFile, cookiesFile, upstream, resources) — в «Настройках», в разделе whitelistBypass."),
|
||||||
|
("VK (creators only)", "VK (только создатели)"),
|
||||||
|
];
|
||||||
@@ -1,6 +1,10 @@
|
|||||||
//! Pieces the pages share: the page frame, cards, a unit's state as a tag.
|
//! Pieces the pages share: the page frame, cards, a unit's state as a tag.
|
||||||
|
|
||||||
|
use gpui_kit::component::button::Button;
|
||||||
use gpui_kit::component::tag::Tag;
|
use gpui_kit::component::tag::Tag;
|
||||||
|
use gpui_kit::prelude::FluentBuilder as _;
|
||||||
|
|
||||||
|
use crate::i18n::tr;
|
||||||
use gpui_kit::assets::IconName;
|
use gpui_kit::assets::IconName;
|
||||||
use gpui_kit::component::*;
|
use gpui_kit::component::*;
|
||||||
use gpui_kit::*;
|
use gpui_kit::*;
|
||||||
@@ -28,7 +32,7 @@ pub fn card(title: impl Into<SharedString>, action: Option<AnyElement>, cx: &App
|
|||||||
.child(div().h_flex().justify_between().items_center().child(div().font_semibold().child(title.into())).children(action))
|
.child(div().h_flex().justify_between().items_center().child(div().font_semibold().child(title.into())).children(action))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A unit's state, as the service says it, coloured by what it means.
|
/// A unit's state, as the service says it, coloured by what it means, in the user's words.
|
||||||
pub fn state_tag(state: &str) -> Tag {
|
pub fn state_tag(state: &str) -> Tag {
|
||||||
let tag = match state {
|
let tag = match state {
|
||||||
"active" => Tag::success(),
|
"active" => Tag::success(),
|
||||||
@@ -36,7 +40,16 @@ pub fn state_tag(state: &str) -> Tag {
|
|||||||
"failed" => Tag::danger(),
|
"failed" => Tag::danger(),
|
||||||
_ => Tag::secondary(),
|
_ => Tag::secondary(),
|
||||||
};
|
};
|
||||||
tag.child(state.to_owned())
|
tag.child(state_word(state))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The service's word for a state, in the user's language.
|
||||||
|
pub fn state_word(state: &str) -> SharedString {
|
||||||
|
const KNOWN: [&str; 11] = ["active", "inactive", "activating", "deactivating", "reloading", "failed", "unknown", "off", "on", "outbound", "waiting"];
|
||||||
|
match KNOWN.iter().find(|k| **k == state) {
|
||||||
|
Some(k) => tr(k).into(),
|
||||||
|
None => state.to_owned().into(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A quieter line of explanation.
|
/// A quieter line of explanation.
|
||||||
@@ -48,3 +61,32 @@ pub fn hint(text: impl Into<SharedString>, cx: &App) -> Div {
|
|||||||
pub fn fact(label: &'static str, value: impl Into<SharedString>, cx: &App) -> Div {
|
pub fn fact(label: &'static str, value: impl Into<SharedString>, cx: &App) -> Div {
|
||||||
div().h_flex().gap_2().text_sm().child(div().w(px(110.)).text_color(cx.theme().muted_foreground).child(label)).child(value.into())
|
div().h_flex().gap_2().text_sm().child(div().w(px(110.)).text_color(cx.theme().muted_foreground).child(label)).child(value.into())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A button that cannot be pressed now. gpui-component draws a disabled button's text at half
|
||||||
|
/// the muted colour, which the dark theme all but hides: here at the muted colour itself (a
|
||||||
|
/// button's own style is laid over its disabled state's), still plainly dimmer than an active
|
||||||
|
/// button's.
|
||||||
|
pub trait Inactive: Sized {
|
||||||
|
fn inactive(self, disabled: bool, cx: &App) -> Self;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Inactive for Button {
|
||||||
|
fn inactive(self, disabled: bool, cx: &App) -> Self {
|
||||||
|
self.disabled(disabled).when(disabled, |b| b.text_color(cx.theme().muted_foreground))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shared pieces' words (units' states), in Russian (i18n).
|
||||||
|
pub const RU: &[(&str, &str)] = &[
|
||||||
|
("active", "работает"),
|
||||||
|
("inactive", "остановлено"),
|
||||||
|
("activating", "запускается"),
|
||||||
|
("deactivating", "останавливается"),
|
||||||
|
("reloading", "перезапускается"),
|
||||||
|
("failed", "сбой"),
|
||||||
|
("unknown", "неизвестно"),
|
||||||
|
("off", "выкл."),
|
||||||
|
("on", "вкл."),
|
||||||
|
("outbound", "выход прокси"),
|
||||||
|
("waiting", "ожидает"),
|
||||||
|
];
|
||||||
@@ -102,6 +102,23 @@ pub enum Request {
|
|||||||
AwgSet { name: String, on: bool },
|
AwgSet { name: String, on: bool },
|
||||||
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
|
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
|
||||||
AwgLog { name: String, lines: usize },
|
AwgLog { name: String, lines: usize },
|
||||||
|
/// The 16 KB cutoff probe: the networks this line cuts, and the names that get through;
|
||||||
|
/// `probe` runs it now.
|
||||||
|
ZapretCutoff {
|
||||||
|
#[serde(default)]
|
||||||
|
probe: bool,
|
||||||
|
},
|
||||||
|
/// The kill switch: lift it (`on: false`, until a tunnel is turned on), hold it again
|
||||||
|
/// (`true`), or (none) what it does.
|
||||||
|
KillSwitch {
|
||||||
|
#[serde(default)]
|
||||||
|
on: Option<bool>,
|
||||||
|
},
|
||||||
|
/// This version, and the newest release if it is newer.
|
||||||
|
UpdateCheck,
|
||||||
|
/// Fetches the newest release's setup program, checks it, and runs it: the service stops,
|
||||||
|
/// is replaced, and starts again, and the app with it. Services scope.
|
||||||
|
UpdateInstall,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ windows-sys = { workspace = true, features = [
|
|||||||
"Win32_UI_WindowsAndMessaging",
|
"Win32_UI_WindowsAndMessaging",
|
||||||
"Win32_System_Threading",
|
"Win32_System_Threading",
|
||||||
"Win32_Networking_WinInet",
|
"Win32_Networking_WinInet",
|
||||||
|
"Win32_System_RemoteDesktop",
|
||||||
|
"Win32_System_Environment",
|
||||||
|
"Win32_NetworkManagement_WindowsFilteringPlatform",
|
||||||
|
"Win32_System_Rpc",
|
||||||
] }
|
] }
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[target.'cfg(target_os = "linux")'.dependencies]
|
||||||
|
|||||||
@@ -134,11 +134,14 @@ fn scope_of(req: &Request) -> Option<Scope> {
|
|||||||
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
|
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
|
||||||
// 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),
|
// An update runs only the project's own setup program, checked: no more than a restart.
|
||||||
|
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } | Request::UpdateInstall => Some(Scope::Services),
|
||||||
Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass),
|
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::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
|
||||||
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
|
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
|
||||||
Request::AwgLog { .. } => Some(Scope::Secrets),
|
Request::AwgLog { .. } => Some(Scope::Secrets),
|
||||||
|
Request::ZapretCutoff { .. } => Some(Scope::Zapret),
|
||||||
|
Request::KillSwitch { on: Some(_) } => Some(Scope::Services),
|
||||||
_ => None,
|
_ => None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -398,6 +401,8 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
|||||||
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
|
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
|
||||||
}
|
}
|
||||||
s.tun = true;
|
s.tun = true;
|
||||||
|
// A tunnel turned on: the kill switch holds again.
|
||||||
|
s.killswitch_lifted = false;
|
||||||
}
|
}
|
||||||
s.proxy_on = true;
|
s.proxy_on = true;
|
||||||
applied(s.apply().await)
|
applied(s.apply().await)
|
||||||
@@ -435,6 +440,9 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Request::Test { tags } => {
|
Request::Test { tags } => {
|
||||||
|
if shared.lock().await.cfg().proxy.backend == ps_core::config::Backend::Xray {
|
||||||
|
return Response::err("latency tests need the sing-box or hybrid backend");
|
||||||
|
}
|
||||||
let (clash, tags, url) = {
|
let (clash, tags, url) = {
|
||||||
let s = shared.lock().await;
|
let s = shared.lock().await;
|
||||||
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
|
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
|
||||||
@@ -651,13 +659,27 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Request::AwgSet { name, on } => {
|
Request::AwgSet { name, on } => {
|
||||||
let s = shared.lock().await;
|
let mut s = shared.lock().await;
|
||||||
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
|
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?)"));
|
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.
|
// The SCM's calls wait for the tunnel: not in the async runtime's threads.
|
||||||
let iface = vpn.iface.clone();
|
let iface = vpn.iface.clone();
|
||||||
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
|
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
|
||||||
|
// The kill switch holds to the profiles wanted on: turned off, this one leaves its
|
||||||
|
// plan (the TUN's, and other profiles', stay); turned on, it joins, and a kill switch
|
||||||
|
// lifted holds again.
|
||||||
|
if matches!(r, Ok(Ok(()))) {
|
||||||
|
if on {
|
||||||
|
s.awg_wanted.insert(vpn.iface.clone());
|
||||||
|
s.killswitch_lifted = false;
|
||||||
|
} else {
|
||||||
|
s.awg_wanted.remove(&vpn.iface);
|
||||||
|
}
|
||||||
|
if let Err(e) = s.apply_killswitch() {
|
||||||
|
s.sup.note(crate::service::SOCKS_UNIT, format!("proxy-suite: the kill switch: {e:#}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
match r {
|
match r {
|
||||||
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
|
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
|
||||||
Ok(Err(e)) => Response::err(format!("{e:#}")),
|
Ok(Err(e)) => Response::err(format!("{e:#}")),
|
||||||
@@ -673,6 +695,47 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
|
|||||||
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
|
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Request::KillSwitch { on } => {
|
||||||
|
let mut s = shared.lock().await;
|
||||||
|
if let Some(on) = on {
|
||||||
|
s.killswitch_lifted = !on;
|
||||||
|
if let Err(e) = s.apply_killswitch() {
|
||||||
|
return Response::err(format!("{e:#}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Response::ok(s.status()["killSwitch"].clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
Request::ZapretCutoff { probe } => {
|
||||||
|
let s = shared.lock().await;
|
||||||
|
if probe {
|
||||||
|
if !crate::cutoff::enabled(s.cfg()) {
|
||||||
|
return Response::err("the cutoff probe needs zapret.engine = \"zapret2\" with zapret2.cutoff.enable");
|
||||||
|
}
|
||||||
|
crate::cutoff::request_probe();
|
||||||
|
}
|
||||||
|
Response::ok(crate::cutoff::status(s.cfg(), s.paths()))
|
||||||
|
}
|
||||||
|
|
||||||
|
Request::UpdateCheck => {
|
||||||
|
let routes = shared.lock().await.fetch_routes(true);
|
||||||
|
match crate::update::check(&routes).await {
|
||||||
|
Ok(r) => Response::ok(json!({ "current": env!("CARGO_PKG_VERSION"), "available": r.map(|r| r.to_json()) })),
|
||||||
|
Err(e) => Response::err(format!("{e:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Request::UpdateInstall => {
|
||||||
|
let (routes, dir) = {
|
||||||
|
let s = shared.lock().await;
|
||||||
|
(s.fetch_routes(true), s.paths().updates())
|
||||||
|
};
|
||||||
|
match crate::update::install(&routes, &dir).await {
|
||||||
|
Ok(r) => Response::ok(r.to_json()),
|
||||||
|
Err(e) => Response::err(format!("{e:#}")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
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 {
|
||||||
|
|||||||
@@ -251,7 +251,8 @@ async fn get_text(port: u16, login: &(String, String), url: &str) -> Option<Stri
|
|||||||
/// The probe listeners, when autoProxy runs with the local proxy.
|
/// The probe listeners, when autoProxy runs with the local proxy.
|
||||||
pub fn exits(s: &crate::service::Service) -> Option<Exits> {
|
pub fn exits(s: &crate::service::Service) -> Option<Exits> {
|
||||||
let cfg = s.cfg();
|
let cfg = s.cfg();
|
||||||
if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || s.sup.state_of(SOCKS_UNIT) != UnitState::Active {
|
// No Clash API on the xray backend (validated away too).
|
||||||
|
if !(cfg.enable && cfg.proxy.enable && cfg.proxy.auto_proxy.enable) || cfg.proxy.backend == ps_core::config::Backend::Xray || s.sup.state_of(SOCKS_UNIT) != UnitState::Active {
|
||||||
return None;
|
return None;
|
||||||
}
|
}
|
||||||
let list = s.last.as_ref()?.probe_exits.clone();
|
let list = s.last.as_ref()?.probe_exits.clone();
|
||||||
|
|||||||
@@ -293,6 +293,21 @@ pub fn state(_iface: &str) -> String {
|
|||||||
"windows-only".into()
|
"windows-only".into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The tunnels this suite registered that run, stopped: their interface names.
|
||||||
|
pub fn stop_running(paths: &Paths) -> Vec<String> {
|
||||||
|
registered(paths)
|
||||||
|
.into_iter()
|
||||||
|
.filter(|iface| state(iface) == "active")
|
||||||
|
.filter(|iface| match stop(iface) {
|
||||||
|
Ok(()) => true,
|
||||||
|
Err(e) => {
|
||||||
|
tracing::warn!("stopping the AmneziaWG tunnel {iface}: {e:#}");
|
||||||
|
false
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
/// Every tunnel this suite registered, stopped and deleted: on uninstall.
|
/// Every tunnel this suite registered, stopped and deleted: on uninstall.
|
||||||
#[cfg_attr(not(windows), allow(dead_code))]
|
#[cfg_attr(not(windows), allow(dead_code))]
|
||||||
pub fn remove_all(paths: &Paths) {
|
pub fn remove_all(paths: &Paths) {
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
//! The 16 KB cutoff probe (upstream's zapret2/cutoff.nix and cutoff-probe.template.sh). Some
|
||||||
|
//! lines let TLS to certain hosting networks shake hands and then kill the connection at
|
||||||
|
//! 12-34 KB, which no strategy fixes. z2k-detect finds which networks (AS) this line cuts and,
|
||||||
|
//! for z2k's own strategies, a whitelisted name per network that z2k's tcp16 Lua puts into a
|
||||||
|
//! fake ClientHello; the networks no name fixes go to a rule-set the proxy carries.
|
||||||
|
//!
|
||||||
|
//! The probe measures the line itself: its connections leave from
|
||||||
|
//! ps_core::zapret2::CUTOFF_PORTS, which winws2 leaves alone, and directly under the TUN.
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use ps_core::config::{Config, StrategySource, ZapretEngine};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
|
use crate::fetch::{self, Route};
|
||||||
|
use crate::paths::Paths;
|
||||||
|
|
||||||
|
/// A day, as upstream's: the maps belong to the line, probed again when its network changes.
|
||||||
|
const MAX_AGE: u64 = 86400;
|
||||||
|
|
||||||
|
static FORCE: Notify = Notify::const_new();
|
||||||
|
|
||||||
|
/// What the probe is doing, and what the last round said.
|
||||||
|
static NOTE: Mutex<(bool, String)> = Mutex::new((false, String::new()));
|
||||||
|
|
||||||
|
fn note(probing: bool, text: impl Into<String>) {
|
||||||
|
let text = text.into();
|
||||||
|
if !text.is_empty() {
|
||||||
|
tracing::info!("cutoff: {text}");
|
||||||
|
}
|
||||||
|
*NOTE.lock().unwrap_or_else(|e| e.into_inner()) = (probing, text);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn dir(paths: &Paths) -> PathBuf {
|
||||||
|
paths.root.join("zapret2-cutoff")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn enabled(cfg: &Config) -> bool {
|
||||||
|
cfg.enable && cfg.zapret.enable && cfg.zapret.engine == ZapretEngine::Zapret2 && cfg.zapret.zapret2.cutoff.enable
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a name found fixes anything: only z2k's own profiles put it in (z2k-tcp16.lua).
|
||||||
|
/// Elsewhere every cut-off network goes to the proxy, and no name is searched for.
|
||||||
|
pub fn names_apply(cfg: &Config) -> bool {
|
||||||
|
enabled(cfg) && cfg.zapret.zapret2.strategy_source == StrategySource::Z2k && cfg.zapret.zapret2.profiles.is_none()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extras(paths: &Paths) -> PathBuf {
|
||||||
|
paths.bin().join("zapret2-extras")
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn program(paths: &Paths) -> Option<PathBuf> {
|
||||||
|
let p = extras(paths).join(if cfg!(windows) { "z2k-detect.exe" } else { "z2k-detect" });
|
||||||
|
p.is_file().then_some(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lists(paths: &Paths) -> PathBuf {
|
||||||
|
extras(paths).join("z2k").join("files").join("lists")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rule-set the proxy carries, when it is to (`cutoff.proxyFallback`).
|
||||||
|
pub fn rule_set_path(cfg: &Config, paths: &Paths) -> Option<String> {
|
||||||
|
(enabled(cfg) && cfg.zapret.zapret2.cutoff.proxy_fallback).then(|| dir(paths).join("proxy.json").to_string_lossy().into_owned())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read(path: &Path) -> String {
|
||||||
|
std::fs::read_to_string(path).unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What z2k's tcp16 Lua reads inside winws2 (upstream's runtime.nix), with `lua_path` giving
|
||||||
|
/// paths as winws2 opens them; and a digest of the maps, so a new one restarts winws2 (it
|
||||||
|
/// reads them once).
|
||||||
|
pub fn lua_env(cfg: &Config, paths: &Paths, lua_path: impl Fn(&Path) -> String) -> Vec<(String, String)> {
|
||||||
|
if !names_apply(cfg) {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let d = dir(paths);
|
||||||
|
let digest = {
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
let mut h = Sha256::new();
|
||||||
|
h.update(read(&d.join("asn.txt")));
|
||||||
|
h.update(b"\0");
|
||||||
|
h.update(read(&d.join("sni.txt")));
|
||||||
|
h.finalize().iter().take(8).map(|b| format!("{b:02x}")).collect::<String>()
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
("Z2K_TCP16_ASN".into(), lua_path(&d.join("asn.txt"))),
|
||||||
|
("Z2K_TCP16_SNI".into(), lua_path(&d.join("sni.txt"))),
|
||||||
|
("Z2K_SNI_PIN".into(), lua_path(&d.join("pin.txt"))),
|
||||||
|
("Z2K_TCP16_NETS".into(), lua_path(&lists(paths).join("tcp16_nets.txt"))),
|
||||||
|
("PROXY_SUITE_CUTOFF_MAPS".into(), digest),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The rule-set from the maps as they stand, written only when it changed (sing-box reloads a
|
||||||
|
/// rule-set file replaced). Whether it did.
|
||||||
|
pub fn write_rules(cfg: &Config, paths: &Paths) -> Result<bool> {
|
||||||
|
let Some(path) = rule_set_path(cfg, paths) else { return Ok(false) };
|
||||||
|
let d = dir(paths);
|
||||||
|
std::fs::create_dir_all(&d)?;
|
||||||
|
// Names no profile puts in fix nothing: every cut-off network goes to the proxy.
|
||||||
|
let sni = if names_apply(cfg) { read(&d.join("sni.txt")) } else { String::new() };
|
||||||
|
let rules = ps_core::zapret2::cutoff_rules(&read(&d.join("asn.txt")), &sni, &read(&lists(paths).join("tcp16_nets.txt")));
|
||||||
|
let text = serde_json::to_vec(&rules)?;
|
||||||
|
if std::fs::read(&path).is_ok_and(|old| old == text) {
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
|
crate::paths::write_atomic(Path::new(&path), &text).with_context(|| format!("writing {path}"))?;
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The probe's maps and when it ran, for `proxy-ctl zapret cutoff` and the app.
|
||||||
|
pub fn status(cfg: &Config, paths: &Paths) -> Value {
|
||||||
|
let d = dir(paths);
|
||||||
|
let names = ps_core::zapret2::network_names(&read(&d.join("sni.txt")));
|
||||||
|
let networks: Vec<Value> = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt")))
|
||||||
|
.into_iter()
|
||||||
|
.map(|asn| {
|
||||||
|
let name = names.get(&asn).filter(|n| !n.is_empty() && names_apply(cfg));
|
||||||
|
json!({ "asn": asn, "name": name })
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let (probing, note) = NOTE.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
json!({
|
||||||
|
"enabled": enabled(cfg),
|
||||||
|
"installed": program(paths).is_some(),
|
||||||
|
"namesApply": names_apply(cfg),
|
||||||
|
"proxyFallback": cfg.zapret.zapret2.cutoff.proxy_fallback,
|
||||||
|
"probing": probing,
|
||||||
|
"note": note,
|
||||||
|
"probed": read(&d.join("ts")).trim().parse::<u64>().ok(),
|
||||||
|
"egress": Some(read(&d.join("egress")).trim().to_owned()).filter(|e| !e.is_empty()),
|
||||||
|
"networks": networks,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Probe now, whatever the line and the last probe's age. Under way from now on, for whoever
|
||||||
|
/// follows it: every forced round ends with a note that it is not.
|
||||||
|
pub fn request_probe() {
|
||||||
|
note(true, "about to probe the line");
|
||||||
|
FORCE.notify_one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rounds as upstream's timer runs them: 5 minutes after start, then every 10 (cheap unless
|
||||||
|
/// the line's network changed or a day passed), and at once when asked.
|
||||||
|
pub async fn runner(shared: crate::service::Shared) {
|
||||||
|
let mut wait = Duration::from_secs(300);
|
||||||
|
loop {
|
||||||
|
let force = tokio::select! {
|
||||||
|
_ = tokio::time::sleep(wait) => false,
|
||||||
|
_ = FORCE.notified() => true,
|
||||||
|
};
|
||||||
|
wait = Duration::from_secs(600);
|
||||||
|
if let Err(e) = round(&shared, force).await {
|
||||||
|
note(false, format!("{e:#}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The line's network (`AS…`) as one service names it, or none.
|
||||||
|
async fn asn_from(url: &str, pick: impl Fn(&Value) -> Option<String>) -> Option<String> {
|
||||||
|
let body = tokio::time::timeout(Duration::from_secs(10), fetch::get(url, &Route::Direct, 64 * 1024)).await.ok()?.ok()?;
|
||||||
|
let v: Value = serde_json::from_slice(&body).ok()?;
|
||||||
|
pick(&v).filter(|a| a.len() > 2 && a.starts_with("AS") && a[2..].bytes().all(|b| b.is_ascii_digit()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// This line's network: two services must agree, as one alone now and then names another
|
||||||
|
/// (each flip cost a full probe). One answer alone counts for the network already known, or
|
||||||
|
/// when none is. Err with why not to probe.
|
||||||
|
async fn egress(known: &str) -> Result<String, String> {
|
||||||
|
let (ipinfo, ifconfig) = tokio::join!(
|
||||||
|
asn_from("https://ipinfo.io/json", |v| v["org"].as_str().and_then(|o| o.split(' ').next()).map(str::to_owned)),
|
||||||
|
asn_from("https://ifconfig.co/json", |v| v["asn"].as_str().map(str::to_owned)),
|
||||||
|
);
|
||||||
|
match (ipinfo, ifconfig) {
|
||||||
|
(Some(a), Some(b)) if a != b => Err(format!("ipinfo.io says {a}, ifconfig.co says {b}; keeping the last probe")),
|
||||||
|
(Some(a), Some(_)) => Ok(a),
|
||||||
|
(None, None) => Err("no answer about this line's network; not probing".into()),
|
||||||
|
(Some(a), None) | (None, Some(a)) => {
|
||||||
|
if !known.is_empty() && a != known {
|
||||||
|
Err(format!("only one service answered, with {a} for this line's {known}; keeping the last probe"))
|
||||||
|
} else {
|
||||||
|
Ok(a)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// z2k-detect with `args`, from the probe's ports, its output appended to the probe's log:
|
||||||
|
/// its exit code.
|
||||||
|
async fn detect(program: &Path, args: &[&str], dir: &Path) -> Result<i32> {
|
||||||
|
let log = std::fs::OpenOptions::new().create(true).append(true).open(dir.join("probe.log"))?;
|
||||||
|
let (lo, hi) = ps_core::zapret2::CUTOFF_PORTS;
|
||||||
|
let mut cmd = tokio::process::Command::new(program);
|
||||||
|
cmd.args(args)
|
||||||
|
.env("Z2K_TCP16_LOCAL_PORTS", format!("{lo}-{hi}"))
|
||||||
|
.current_dir(dir)
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.stdout(log.try_clone()?)
|
||||||
|
.stderr(log)
|
||||||
|
.kill_on_drop(true);
|
||||||
|
#[cfg(windows)]
|
||||||
|
cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||||
|
let status = cmd.status().await.with_context(|| format!("running {}", program.display()))?;
|
||||||
|
Ok(status.code().unwrap_or(-1))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn round(shared: &crate::service::Shared, force: bool) -> Result<()> {
|
||||||
|
let (cfg, paths) = {
|
||||||
|
let s = shared.lock().await;
|
||||||
|
(s.cfg().clone(), s.paths().clone())
|
||||||
|
};
|
||||||
|
if !enabled(&cfg) {
|
||||||
|
if force {
|
||||||
|
note(false, "the cutoff probe is off (zapret.zapret2.cutoff.enable, with the zapret2 engine)");
|
||||||
|
}
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let Some(program) = program(&paths) else {
|
||||||
|
note(false, "z2k-detect is not installed (the zapret2-extras component)");
|
||||||
|
return Ok(());
|
||||||
|
};
|
||||||
|
let d = dir(&paths);
|
||||||
|
std::fs::create_dir_all(&d)?;
|
||||||
|
let names = names_apply(&cfg);
|
||||||
|
// Names no profile puts in fix nothing: none kept from when one did.
|
||||||
|
if !names && !read(&d.join("sni.txt")).is_empty() {
|
||||||
|
std::fs::write(d.join("sni.txt"), b"")?;
|
||||||
|
}
|
||||||
|
if write_rules(&cfg, &paths)? {
|
||||||
|
tracing::info!("cutoff: the proxy's rule-set follows the maps");
|
||||||
|
}
|
||||||
|
let now = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
|
||||||
|
let last: u64 = read(&d.join("ts")).trim().parse().unwrap_or(0);
|
||||||
|
let known = read(&d.join("egress")).trim().to_owned();
|
||||||
|
let egress = match egress(&known).await {
|
||||||
|
Ok(e) => e,
|
||||||
|
Err(why) => {
|
||||||
|
note(false, why);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if !force && egress == known && now.saturating_sub(last) < MAX_AGE {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let targets = lists(&paths).join("tcp16_targets.txt");
|
||||||
|
let candidates = lists(&paths).join("sni_wl_candidates.txt");
|
||||||
|
// z2k-detect exits 1 for "cut" and for a file it cannot read alike.
|
||||||
|
if !targets.is_file() || !candidates.is_file() {
|
||||||
|
note(false, "z2k's target lists are missing (the zapret2-extras component)");
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
note(true, format!("probing the line from {egress}"));
|
||||||
|
let _ = std::fs::write(d.join("probe.log"), b"");
|
||||||
|
let (asn_new, sni_new) = (d.join("asn.new"), d.join("sni.new"));
|
||||||
|
let _ = std::fs::remove_file(&asn_new);
|
||||||
|
let _ = std::fs::remove_file(&sni_new);
|
||||||
|
let t = targets.to_string_lossy().into_owned();
|
||||||
|
match detect(&program, &["tcp16", "-targets", &t, "-parallel", "50", "-asn-out", "asn.new"], &d).await? {
|
||||||
|
1 => {
|
||||||
|
if names {
|
||||||
|
let c = candidates.to_string_lossy().into_owned();
|
||||||
|
let rc = detect(&program, &["tcp16", "-targets", &t, "-scan", &c, "-per-asn", "-batch", "5", "-parallel", "50", "-sni-out", "sni.new"], &d).await?;
|
||||||
|
// 2: no network took any name; the cut-off networks still stand.
|
||||||
|
if rc != 0 && rc != 2 {
|
||||||
|
let _ = std::fs::remove_file(&asn_new);
|
||||||
|
note(false, format!("the name search failed ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !sni_new.exists() {
|
||||||
|
std::fs::write(&sni_new, b"")?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
0 => {
|
||||||
|
std::fs::write(&asn_new, b"")?;
|
||||||
|
std::fs::write(&sni_new, b"")?;
|
||||||
|
}
|
||||||
|
rc => {
|
||||||
|
let _ = std::fs::remove_file(&asn_new);
|
||||||
|
note(false, format!("the probe did not run ({rc}); keeping the previous maps (its log: {})", d.join("probe.log").display()));
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let changed = read(&asn_new) != read(&d.join("asn.txt")) || read(&sni_new) != read(&d.join("sni.txt"));
|
||||||
|
std::fs::rename(&asn_new, d.join("asn.txt"))?;
|
||||||
|
std::fs::rename(&sni_new, d.join("sni.txt"))?;
|
||||||
|
write_rules(&cfg, &paths)?;
|
||||||
|
std::fs::write(d.join("egress"), format!("{egress}\n"))?;
|
||||||
|
std::fs::write(d.join("ts"), format!("{now}\n"))?;
|
||||||
|
let cut = ps_core::zapret2::cut_networks(&read(&d.join("asn.txt"))).len();
|
||||||
|
let named = ps_core::zapret2::network_names(&read(&d.join("sni.txt"))).len();
|
||||||
|
note(false, format!("probed from {egress}: {cut} network(s) cut off, {named} with a name"));
|
||||||
|
// winws2 reads the maps once: a new one restarts it (the Lua's environment carries their
|
||||||
|
// digest); what it learned stays on disk.
|
||||||
|
if changed && names {
|
||||||
|
if let Err(e) = shared.lock().await.apply().await {
|
||||||
|
tracing::warn!("cutoff: applying the new maps: {e:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
|||||||
@@ -9,7 +9,8 @@ use sha2::{Digest, Sha256};
|
|||||||
|
|
||||||
use crate::fetch;
|
use crate::fetch;
|
||||||
|
|
||||||
fn hex(data: &[u8]) -> String {
|
/// A SHA-256, in lower-case hex.
|
||||||
|
pub(crate) fn hex(data: &[u8]) -> String {
|
||||||
let mut h = Sha256::new();
|
let mut h = Sha256::new();
|
||||||
h.update(data);
|
h.update(data);
|
||||||
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
|
||||||
@@ -27,7 +28,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);
|
||||||
@@ -255,15 +256,20 @@ fn verify_all(dir: &Path) -> Result<()> {
|
|||||||
|
|
||||||
/// Copies each component of `from` (the release's) into `bin` when `bin` lacks it or holds
|
/// Copies each component of `from` (the release's) into `bin` when `bin` lacks it or holds
|
||||||
/// another version: staged, verified file by file, swapped in. What it did, as lines.
|
/// another version: staged, verified file by file, swapped in. What it did, as lines.
|
||||||
|
/// Whether `seed` replaces `name` in `bin`: the release has the version the manifest wants,
|
||||||
|
/// and `bin` another (or none).
|
||||||
|
pub fn seeds(from: &Path, bin: &Path, name: &str) -> bool {
|
||||||
|
let manifest = ps_core::components::manifest();
|
||||||
|
let Some(comp) = manifest.components.get(name) else { return false };
|
||||||
|
installed_version(from, name).as_deref() == Some(comp.version.as_str()) && installed_version(bin, name).as_deref() != Some(comp.version.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
pub fn seed(from: &Path, bin: &Path) -> Vec<String> {
|
pub fn seed(from: &Path, bin: &Path) -> Vec<String> {
|
||||||
let manifest = ps_core::components::manifest();
|
let manifest = ps_core::components::manifest();
|
||||||
let mut notes = Vec::new();
|
let mut notes = Vec::new();
|
||||||
for (name, comp) in &manifest.components {
|
for (name, comp) in &manifest.components {
|
||||||
let src = from.join(name);
|
let src = from.join(name);
|
||||||
if installed_version(from, name).as_deref() != Some(comp.version.as_str()) {
|
if !seeds(from, bin, name) {
|
||||||
continue;
|
|
||||||
}
|
|
||||||
if installed_version(bin, name).as_deref() == Some(comp.version.as_str()) {
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
let staging = bin.join(format!("{name}.staging"));
|
let staging = bin.join(format!("{name}.staging"));
|
||||||
|
|||||||
@@ -0,0 +1,432 @@
|
|||||||
|
//! The kill switch (upstream's `killSwitch`, there in nftables): what would leave past the
|
||||||
|
//! global tunnel (the TUN, or a system-wide AmneziaWG profile) is blocked, while the tunnel runs
|
||||||
|
//! and while it restarts or has failed. LAN, DHCP and NTP stay open, and so do the tunnel's own
|
||||||
|
//! programs. Turning the tunnel off (`proxy-ctl proxy tun off`, `awg off`) or `proxy-ctl
|
||||||
|
//! killswitch off` lifts it until a tunnel is turned on again.
|
||||||
|
//!
|
||||||
|
//! On Windows: Windows Filtering Platform filters in a dynamic session of this service's, so
|
||||||
|
//! they go with the service: stopping it lifts them. (Upstream's holds from boot; that needs
|
||||||
|
//! persistent filters, left for when these have been seen to work.)
|
||||||
|
|
||||||
|
use std::net::IpAddr;
|
||||||
|
use std::path::PathBuf;
|
||||||
|
|
||||||
|
use ps_core::config::Config;
|
||||||
|
|
||||||
|
/// An address range: an address and its prefix length.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Net {
|
||||||
|
pub addr: IpAddr,
|
||||||
|
pub prefix: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Net {
|
||||||
|
pub fn parse(s: &str) -> Option<Net> {
|
||||||
|
let s = s.trim();
|
||||||
|
let (a, p) = s.split_once('/').unwrap_or((s, ""));
|
||||||
|
let addr: IpAddr = a.trim().parse().ok()?;
|
||||||
|
let max = if addr.is_ipv4() { 32 } else { 128 };
|
||||||
|
let prefix = if p.is_empty() { max } else { p.trim().parse().ok().filter(|p| *p <= max)? };
|
||||||
|
Some(Net { addr, prefix })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the kill switch leaves open; everything else that leaves is blocked.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Default)]
|
||||||
|
pub struct Plan {
|
||||||
|
/// Destinations: the local networks, private and reserved ranges, `allowedSubnets`.
|
||||||
|
pub open: Vec<Net>,
|
||||||
|
/// Sources: the tunnels' own addresses, which what goes through them leaves from.
|
||||||
|
pub tunnels: Vec<Net>,
|
||||||
|
/// Programs that reach the network themselves: the tunnel's own (sing-box, its helpers,
|
||||||
|
/// the AmneziaWG tunnel), and the service when `directFallbacks` lets it fetch directly.
|
||||||
|
pub programs: Vec<PathBuf>,
|
||||||
|
/// NTP (UDP 123) to anywhere: `allowTimeSync`.
|
||||||
|
pub time_sync: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ranges upstream's kill switch leaves open besides `allowedSubnets`: this machine, the
|
||||||
|
/// private and reserved networks, link-local, multicast and broadcast (DHCP's among them).
|
||||||
|
const LOCAL: [&str; 13] = [
|
||||||
|
"127.0.0.0/8",
|
||||||
|
"10.0.0.0/8",
|
||||||
|
"100.64.0.0/10",
|
||||||
|
"169.254.0.0/16",
|
||||||
|
"172.16.0.0/12",
|
||||||
|
"192.168.0.0/16",
|
||||||
|
"224.0.0.0/4",
|
||||||
|
"255.255.255.255/32",
|
||||||
|
"::1/128",
|
||||||
|
"fc00::/7",
|
||||||
|
"fe80::/10",
|
||||||
|
"ff00::/8",
|
||||||
|
"0.0.0.0/32",
|
||||||
|
];
|
||||||
|
|
||||||
|
/// What the tunnels are, for the plan: what is wanted on, whatever runs this moment (a tunnel
|
||||||
|
/// that failed or restarts is still held to).
|
||||||
|
pub struct Tunnels {
|
||||||
|
/// The TUN is configured, and wanted on now.
|
||||||
|
pub tun: bool,
|
||||||
|
/// A system-wide AmneziaWG profile is wanted on (turned on, or started at boot).
|
||||||
|
pub awg_on: bool,
|
||||||
|
/// Those profiles' interface addresses (their `Address` lines); none read still holds,
|
||||||
|
/// with nothing let out through them.
|
||||||
|
pub awg: Vec<Net>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the kill switch would leave open now; None when it holds nothing back (off, lifted,
|
||||||
|
/// or no global tunnel to protect).
|
||||||
|
pub fn plan(cfg: &Config, tunnels: &Tunnels, lifted: bool, programs: Vec<PathBuf>) -> Option<Plan> {
|
||||||
|
let k = &cfg.kill_switch;
|
||||||
|
if !cfg.enable || !k.enable || lifted || (!tunnels.tun && !tunnels.awg_on) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut open: Vec<Net> = LOCAL.iter().filter_map(|n| Net::parse(n)).collect();
|
||||||
|
open.extend(k.allowed_subnets.iter().filter_map(|n| Net::parse(n)));
|
||||||
|
let mut tun_nets = Vec::new();
|
||||||
|
if tunnels.tun {
|
||||||
|
tun_nets.extend(Net::parse(&cfg.proxy.tun.address));
|
||||||
|
if cfg.proxy.ipv6 {
|
||||||
|
tun_nets.extend(Net::parse(ps_core::render::TUN_IPV6_ADDRESS));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
tun_nets.extend(tunnels.awg.iter().copied());
|
||||||
|
Some(Plan { open, tunnels: tun_nets, programs, time_sync: k.allow_time_sync })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A system-wide profile's addresses, from its configuration's `Address` lines.
|
||||||
|
pub fn awg_addresses(conf: &str) -> Vec<Net> {
|
||||||
|
conf.lines()
|
||||||
|
.filter_map(|l| {
|
||||||
|
let (k, v) = l.split_once('=')?;
|
||||||
|
k.trim().eq_ignore_ascii_case("address").then_some(v)
|
||||||
|
})
|
||||||
|
.flat_map(|v| v.split(','))
|
||||||
|
.filter_map(Net::parse)
|
||||||
|
.map(|n| Net { prefix: if n.addr.is_ipv4() { 32 } else { 128 }, ..n })
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
pub use wfp::{apply, installed};
|
||||||
|
|
||||||
|
/// Off Windows there is nothing to filter with: the plan is kept, for the status, and said.
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
static APPLIED: std::sync::Mutex<Option<Plan>> = std::sync::Mutex::new(None);
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn apply(plan: Option<&Plan>) -> anyhow::Result<()> {
|
||||||
|
if let Some(p) = plan {
|
||||||
|
tracing::debug!("kill switch (not on this system): {} open ranges, {} tunnel ranges, {} programs", p.open.len(), p.tunnels.len(), p.programs.len());
|
||||||
|
}
|
||||||
|
*APPLIED.lock().unwrap_or_else(|e| e.into_inner()) = plan.cloned();
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plan whose filters are in place.
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
pub fn installed() -> Option<Plan> {
|
||||||
|
APPLIED.lock().unwrap_or_else(|e| e.into_inner()).clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(windows)]
|
||||||
|
mod wfp {
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
|
use anyhow::{Result, bail};
|
||||||
|
use windows_sys::Win32::Foundation::HANDLE;
|
||||||
|
use windows_sys::Win32::NetworkManagement::WindowsFilteringPlatform::*;
|
||||||
|
use windows_sys::core::GUID;
|
||||||
|
|
||||||
|
use super::{IpAddr, Net, Plan};
|
||||||
|
|
||||||
|
/// The session the filters live in: closing it removes them.
|
||||||
|
struct Engine(HANDLE);
|
||||||
|
|
||||||
|
// SAFETY: a WFP engine handle may be used and closed from any thread.
|
||||||
|
unsafe impl Send for Engine {}
|
||||||
|
|
||||||
|
impl Drop for Engine {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
// SAFETY: a handle FwpmEngineOpen0 gave, closed once.
|
||||||
|
unsafe { FwpmEngineClose0(self.0) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plan in place, its session, and which of the two sublayers it took.
|
||||||
|
static ACTIVE: Mutex<Option<(Plan, Engine, usize)>> = Mutex::new(None);
|
||||||
|
|
||||||
|
/// Two keys, taken in turn: a new plan's filters go in under one while the old plan's still
|
||||||
|
/// hold under the other, so nothing leaks between them.
|
||||||
|
const SUBLAYERS: [GUID; 2] = [GUID::from_u128(0x6f0d_4a3e_8f1c_4b2a_9d57_2c1e_8a4b_7f31), GUID::from_u128(0x6f0d_4a3e_8f1c_4b2a_9d57_2c1e_8a4b_7f32)];
|
||||||
|
const RPC_C_AUTHN_WINNT: u32 = 10;
|
||||||
|
|
||||||
|
fn wide(s: &str) -> Vec<u16> {
|
||||||
|
s.encode_utf16().chain(Some(0)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(rc: u32, what: &str) -> Result<()> {
|
||||||
|
if rc != 0 {
|
||||||
|
bail!("{what}: WFP error {rc:#x}");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One condition's value, kept alive (with what it points to) until the filters are added.
|
||||||
|
enum Value {
|
||||||
|
V4(Box<FWP_V4_ADDR_AND_MASK>),
|
||||||
|
V6(Box<FWP_V6_ADDR_AND_MASK>),
|
||||||
|
U8(u8),
|
||||||
|
U16(u16),
|
||||||
|
U32(u32),
|
||||||
|
Blob(*mut FWP_BYTE_BLOB),
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value(v: &Value) -> FWP_CONDITION_VALUE0 {
|
||||||
|
// SAFETY: plain data; the unions take the member the type names.
|
||||||
|
unsafe {
|
||||||
|
let mut c: FWP_CONDITION_VALUE0 = std::mem::zeroed();
|
||||||
|
match v {
|
||||||
|
Value::V4(m) => {
|
||||||
|
c.r#type = FWP_V4_ADDR_MASK;
|
||||||
|
c.Anonymous.v4AddrMask = (&**m as *const FWP_V4_ADDR_AND_MASK).cast_mut();
|
||||||
|
}
|
||||||
|
Value::V6(m) => {
|
||||||
|
c.r#type = FWP_V6_ADDR_MASK;
|
||||||
|
c.Anonymous.v6AddrMask = (&**m as *const FWP_V6_ADDR_AND_MASK).cast_mut();
|
||||||
|
}
|
||||||
|
Value::U8(n) => {
|
||||||
|
c.r#type = FWP_UINT8;
|
||||||
|
c.Anonymous.uint8 = *n;
|
||||||
|
}
|
||||||
|
Value::U16(n) => {
|
||||||
|
c.r#type = FWP_UINT16;
|
||||||
|
c.Anonymous.uint16 = *n;
|
||||||
|
}
|
||||||
|
Value::U32(n) => {
|
||||||
|
c.r#type = FWP_UINT32;
|
||||||
|
c.Anonymous.uint32 = *n;
|
||||||
|
}
|
||||||
|
Value::Blob(b) => {
|
||||||
|
c.r#type = FWP_BYTE_BLOB_TYPE;
|
||||||
|
c.Anonymous.byteBlob = *b;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn net(n: &Net) -> Value {
|
||||||
|
match n.addr {
|
||||||
|
IpAddr::V4(a) => {
|
||||||
|
let mask = if n.prefix == 0 { 0 } else { u32::MAX << (32 - u32::from(n.prefix)) };
|
||||||
|
Value::V4(Box::new(FWP_V4_ADDR_AND_MASK { addr: u32::from(a) & mask, mask }))
|
||||||
|
}
|
||||||
|
IpAddr::V6(a) => Value::V6(Box::new(FWP_V6_ADDR_AND_MASK { addr: a.octets(), prefixLength: n.prefix })),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A filter of `conditions` (field, match, value), all of them to hold.
|
||||||
|
struct Rule {
|
||||||
|
name: &'static str,
|
||||||
|
v6: Option<bool>,
|
||||||
|
conditions: Vec<(GUID, FWP_MATCH_TYPE, Value)>,
|
||||||
|
permit: bool,
|
||||||
|
weight: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn add(engine: HANDLE, rule: &Rule, layer: GUID, sublayer: GUID) -> Result<()> {
|
||||||
|
let mut conds: Vec<FWPM_FILTER_CONDITION0> =
|
||||||
|
rule.conditions.iter().map(|(field, m, v)| FWPM_FILTER_CONDITION0 { fieldKey: *field, matchType: *m, conditionValue: value(v) }).collect();
|
||||||
|
let mut name = wide(&format!("Proxy Suite kill switch: {}", rule.name));
|
||||||
|
// SAFETY: the filter and what it points to live across the call; zeroed fields are
|
||||||
|
// WFP's "none".
|
||||||
|
unsafe {
|
||||||
|
let mut f: FWPM_FILTER0 = std::mem::zeroed();
|
||||||
|
f.displayData.name = name.as_mut_ptr();
|
||||||
|
f.layerKey = layer;
|
||||||
|
f.subLayerKey = sublayer;
|
||||||
|
f.weight.r#type = FWP_UINT8;
|
||||||
|
f.weight.Anonymous.uint8 = rule.weight;
|
||||||
|
f.numFilterConditions = conds.len() as u32;
|
||||||
|
f.filterCondition = if conds.is_empty() { std::ptr::null_mut() } else { conds.as_mut_ptr() };
|
||||||
|
f.action.r#type = if rule.permit { FWP_ACTION_PERMIT } else { FWP_ACTION_BLOCK };
|
||||||
|
let mut id = 0u64;
|
||||||
|
check(FwpmFilterAdd0(engine, &f, std::ptr::null_mut(), &mut id), rule.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The filters for `plan`: permits above, the block beneath, in a sublayer of their own.
|
||||||
|
fn rules(plan: &Plan, apps: &[*mut FWP_BYTE_BLOB]) -> Vec<Rule> {
|
||||||
|
let mut out = vec![Rule {
|
||||||
|
name: "loopback",
|
||||||
|
v6: None,
|
||||||
|
conditions: vec![(FWPM_CONDITION_FLAGS, FWP_MATCH_FLAGS_ALL_SET, Value::U32(FWP_CONDITION_FLAG_IS_LOOPBACK))],
|
||||||
|
permit: true,
|
||||||
|
weight: 15,
|
||||||
|
}];
|
||||||
|
for n in &plan.open {
|
||||||
|
out.push(Rule { name: "local network", v6: Some(n.addr.is_ipv6()), conditions: vec![(FWPM_CONDITION_IP_REMOTE_ADDRESS, FWP_MATCH_EQUAL, net(n))], permit: true, weight: 14 });
|
||||||
|
}
|
||||||
|
for n in &plan.tunnels {
|
||||||
|
out.push(Rule { name: "through the tunnel", v6: Some(n.addr.is_ipv6()), conditions: vec![(FWPM_CONDITION_IP_LOCAL_ADDRESS, FWP_MATCH_EQUAL, net(n))], permit: true, weight: 14 });
|
||||||
|
}
|
||||||
|
for app in apps {
|
||||||
|
out.push(Rule { name: "the tunnel's own program", v6: None, conditions: vec![(FWPM_CONDITION_ALE_APP_ID, FWP_MATCH_EQUAL, Value::Blob(*app))], permit: true, weight: 13 });
|
||||||
|
}
|
||||||
|
if plan.time_sync {
|
||||||
|
out.push(Rule {
|
||||||
|
name: "NTP",
|
||||||
|
v6: None,
|
||||||
|
conditions: vec![(FWPM_CONDITION_IP_PROTOCOL, FWP_MATCH_EQUAL, Value::U8(17)), (FWPM_CONDITION_IP_REMOTE_PORT, FWP_MATCH_EQUAL, Value::U16(123))],
|
||||||
|
permit: true,
|
||||||
|
weight: 12,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.push(Rule { name: "everything else", v6: None, conditions: Vec::new(), permit: false, weight: 0 });
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn install(plan: &Plan, sublayer: GUID) -> Result<Engine> {
|
||||||
|
let mut engine: HANDLE = std::ptr::null_mut();
|
||||||
|
let mut session_name = wide("Proxy Suite kill switch");
|
||||||
|
// SAFETY: zeroed is WFP's "none" for the session's other fields; the name lives across
|
||||||
|
// the call.
|
||||||
|
unsafe {
|
||||||
|
let mut session: FWPM_SESSION0 = std::mem::zeroed();
|
||||||
|
session.displayData.name = session_name.as_mut_ptr();
|
||||||
|
session.flags = FWPM_SESSION_FLAG_DYNAMIC;
|
||||||
|
check(FwpmEngineOpen0(std::ptr::null(), RPC_C_AUTHN_WINNT, std::ptr::null(), &session, &mut engine), "opening the filtering engine")?;
|
||||||
|
}
|
||||||
|
let engine = Engine(engine);
|
||||||
|
let mut apps: Vec<*mut FWP_BYTE_BLOB> = Vec::new();
|
||||||
|
for p in &plan.programs {
|
||||||
|
let mut blob: *mut FWP_BYTE_BLOB = std::ptr::null_mut();
|
||||||
|
let path = wide(&p.to_string_lossy());
|
||||||
|
// SAFETY: a NUL-terminated path; the blob is freed below.
|
||||||
|
if unsafe { FwpmGetAppIdFromFileName0(path.as_ptr(), &mut blob) } == 0 {
|
||||||
|
apps.push(blob);
|
||||||
|
} else {
|
||||||
|
tracing::warn!("kill switch: no application id for {}", p.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result = (|| -> Result<()> {
|
||||||
|
// SAFETY: the engine is open; the transaction is committed or aborted below.
|
||||||
|
unsafe { check(FwpmTransactionBegin0(engine.0, 0), "starting a transaction")? };
|
||||||
|
let added = (|| -> Result<()> {
|
||||||
|
let mut name = wide("Proxy Suite kill switch");
|
||||||
|
// SAFETY: zeroed fields are "none"; the name lives across the call.
|
||||||
|
unsafe {
|
||||||
|
let mut sub: FWPM_SUBLAYER0 = std::mem::zeroed();
|
||||||
|
sub.subLayerKey = sublayer;
|
||||||
|
sub.displayData.name = name.as_mut_ptr();
|
||||||
|
sub.weight = 0xffff;
|
||||||
|
check(FwpmSubLayerAdd0(engine.0, &sub, std::ptr::null_mut()), "adding the sublayer")?;
|
||||||
|
}
|
||||||
|
for rule in rules(plan, &apps) {
|
||||||
|
for (v6, layer) in [(false, FWPM_LAYER_ALE_AUTH_CONNECT_V4), (true, FWPM_LAYER_ALE_AUTH_CONNECT_V6)] {
|
||||||
|
if rule.v6.is_none_or(|r| r == v6) {
|
||||||
|
add(engine.0, &rule, layer, sublayer)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
})();
|
||||||
|
// SAFETY: the transaction begun above.
|
||||||
|
unsafe {
|
||||||
|
match &added {
|
||||||
|
Ok(()) => check(FwpmTransactionCommit0(engine.0), "committing the filters")?,
|
||||||
|
Err(_) => {
|
||||||
|
FwpmTransactionAbort0(engine.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
added
|
||||||
|
})();
|
||||||
|
for mut blob in apps {
|
||||||
|
// SAFETY: each from FwpmGetAppIdFromFileName0, freed once.
|
||||||
|
unsafe { FwpmFreeMemory0((&mut blob as *mut *mut FWP_BYTE_BLOB).cast()) };
|
||||||
|
}
|
||||||
|
result.map(|()| engine)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The plan whose filters are in place.
|
||||||
|
pub fn installed() -> Option<Plan> {
|
||||||
|
ACTIVE.lock().unwrap_or_else(|e| e.into_inner()).as_ref().map(|(p, _, _)| p.clone())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The filters for `plan` in place of the ones there (none: lifted). A plan already in
|
||||||
|
/// place is left as it is; a new one is put in before the old goes, so nothing leaks
|
||||||
|
/// between them. One that cannot be put in leaves the old one holding.
|
||||||
|
pub fn apply(plan: Option<&Plan>) -> Result<()> {
|
||||||
|
let mut active = ACTIVE.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
match plan {
|
||||||
|
None => {
|
||||||
|
if active.take().is_some() {
|
||||||
|
tracing::info!("kill switch: lifted");
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Some(p) if active.as_ref().is_some_and(|(q, _, _)| q == p) => Ok(()),
|
||||||
|
Some(p) => {
|
||||||
|
let next = active.as_ref().map_or(0, |(_, _, i)| 1 - i);
|
||||||
|
let engine = install(p, SUBLAYERS[next])?;
|
||||||
|
tracing::info!("kill switch: holding ({} open ranges, {} tunnel ranges, {} programs)", p.open.len(), p.tunnels.len(), p.programs.len());
|
||||||
|
// The old session closes, and its filters with it, once the new ones hold.
|
||||||
|
*active = Some((p.clone(), engine, next));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use std::net::{Ipv4Addr, Ipv6Addr};
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn cfg() -> Config {
|
||||||
|
let mut c = Config::default();
|
||||||
|
c.enable = true;
|
||||||
|
c.kill_switch.enable = true;
|
||||||
|
c.kill_switch.allowed_subnets = vec!["198.51.100.0/24".into()];
|
||||||
|
c.proxy.enable = true;
|
||||||
|
c.proxy.tun.enable = true;
|
||||||
|
c.proxy.ipv6 = true;
|
||||||
|
c
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn it_holds_only_with_a_tunnel_to_protect_and_not_lifted() {
|
||||||
|
let c = cfg();
|
||||||
|
let tun = Tunnels { tun: true, awg_on: false, awg: Vec::new() };
|
||||||
|
let none = Tunnels { tun: false, awg_on: false, awg: Vec::new() };
|
||||||
|
assert!(plan(&c, &tun, false, Vec::new()).is_some());
|
||||||
|
assert_eq!(plan(&c, &tun, true, Vec::new()), None, "lifted");
|
||||||
|
assert_eq!(plan(&c, &none, false, Vec::new()), None, "no tunnel");
|
||||||
|
let mut off = c.clone();
|
||||||
|
off.kill_switch.enable = false;
|
||||||
|
assert_eq!(plan(&off, &tun, false, Vec::new()), None);
|
||||||
|
let awg = Tunnels { tun: false, awg_on: true, awg: awg_addresses("[Interface]\nAddress = 10.8.0.2/24, fd00:8::2/64\n") };
|
||||||
|
let p = plan(&c, &awg, false, Vec::new()).unwrap();
|
||||||
|
assert_eq!(p.tunnels, [Net::parse("10.8.0.2/32").unwrap(), Net::parse("fd00:8::2/128").unwrap()]);
|
||||||
|
// A profile wanted on whose addresses do not read still holds, letting nothing through it.
|
||||||
|
let unread = Tunnels { tun: false, awg_on: true, awg: Vec::new() };
|
||||||
|
assert!(plan(&c, &unread, false, Vec::new()).is_some_and(|p| p.tunnels.is_empty()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_plan_opens_the_local_networks_and_the_tuns_addresses() {
|
||||||
|
let p = plan(&cfg(), &Tunnels { tun: true, awg_on: false, awg: Vec::new() }, false, vec![PathBuf::from(r"C:\sing-box.exe")]).unwrap();
|
||||||
|
for n in ["192.168.0.0/16", "fe80::/10", "198.51.100.0/24", "255.255.255.255/32"] {
|
||||||
|
assert!(p.open.contains(&Net::parse(n).unwrap()), "{n}");
|
||||||
|
}
|
||||||
|
assert_eq!(p.tunnels, [Net::parse(&Config::default().proxy.tun.address).unwrap(), Net::parse(ps_core::render::TUN_IPV6_ADDRESS).unwrap()]);
|
||||||
|
assert_eq!(p.programs, [PathBuf::from(r"C:\sing-box.exe")]);
|
||||||
|
assert_eq!(Net::parse("10.1.2.3"), Some(Net { addr: IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)), prefix: 32 }));
|
||||||
|
assert_eq!(Net::parse("::1/129"), None);
|
||||||
|
assert_eq!(Net::parse("fd00::/8").unwrap().addr, IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0)));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,10 +9,12 @@ mod awg;
|
|||||||
mod awgvpn;
|
mod awgvpn;
|
||||||
mod clash;
|
mod clash;
|
||||||
mod components;
|
mod components;
|
||||||
|
mod cutoff;
|
||||||
mod fetch;
|
mod fetch;
|
||||||
mod install;
|
mod install;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
mod job;
|
mod job;
|
||||||
|
mod killswitch;
|
||||||
mod paths;
|
mod paths;
|
||||||
mod service;
|
mod service;
|
||||||
mod ssh;
|
mod ssh;
|
||||||
@@ -20,6 +22,7 @@ mod store;
|
|||||||
mod tg;
|
mod tg;
|
||||||
mod tor;
|
mod tor;
|
||||||
mod units;
|
mod units;
|
||||||
|
mod update;
|
||||||
mod warp;
|
mod warp;
|
||||||
#[cfg(windows)]
|
#[cfg(windows)]
|
||||||
mod winsvc;
|
mod winsvc;
|
||||||
@@ -88,9 +91,22 @@ pub async fn run(
|
|||||||
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
|
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
|
||||||
// The components the release carries, next to the program, into bin\ when they are newer.
|
// The components the release carries, next to the program, into bin\ when they are newer.
|
||||||
if let Some(dir) = install::bundled_components_dir() {
|
if let Some(dir) = install::bundled_components_dir() {
|
||||||
|
// What runs from bin\ outside this service holds its files: a system-wide AmneziaWG
|
||||||
|
// tunnel (stopped while its program is replaced, started again after), WinDivert's
|
||||||
|
// driver (left loaded by a zapret stopped hard).
|
||||||
|
let tunnels = if install::seeds(&dir, &paths.bin(), "amneziawg") { awgvpn::stop_running(&paths) } else { Vec::new() };
|
||||||
|
#[cfg(windows)]
|
||||||
|
if ["zapret", "zapret2"].iter().any(|n| install::seeds(&dir, &paths.bin(), n)) {
|
||||||
|
winsvc::release_windivert();
|
||||||
|
}
|
||||||
for note in install::seed(&dir, &paths.bin()) {
|
for note in install::seed(&dir, &paths.bin()) {
|
||||||
tracing::info!("{note}");
|
tracing::info!("{note}");
|
||||||
}
|
}
|
||||||
|
for iface in tunnels {
|
||||||
|
if let Err(e) = awgvpn::start(&iface) {
|
||||||
|
tracing::warn!("the AmneziaWG tunnel {iface} did not start again: {e:#}");
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
let svc = service::Service::new(paths.clone()).with_context(|| format!("opening {}", paths.root.display()))?;
|
let svc = service::Service::new(paths.clone()).with_context(|| format!("opening {}", paths.root.display()))?;
|
||||||
let interactive = svc.cfg().user_control.enable;
|
let interactive = svc.cfg().user_control.enable;
|
||||||
@@ -99,6 +115,7 @@ pub async fn run(
|
|||||||
let addr = address(socket);
|
let addr = address(socket);
|
||||||
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
|
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
|
||||||
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
|
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
|
||||||
|
update::report(&paths.updates());
|
||||||
ready();
|
ready();
|
||||||
|
|
||||||
if let Err(e) = shared.lock().await.apply().await {
|
if let Err(e) = shared.lock().await.apply().await {
|
||||||
@@ -108,6 +125,8 @@ pub async fn run(
|
|||||||
tokio::spawn(autoproxy::runner(shared.clone()));
|
tokio::spawn(autoproxy::runner(shared.clone()));
|
||||||
tokio::spawn(autoproxy::sample(shared.clone()));
|
tokio::spawn(autoproxy::sample(shared.clone()));
|
||||||
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
tokio::spawn(autoproxy::sample_slow(shared.clone()));
|
||||||
|
tokio::spawn(zapret::sync_loop(shared.clone()));
|
||||||
|
tokio::spawn(cutoff::runner(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();
|
||||||
|
|||||||
@@ -58,6 +58,11 @@ impl Paths {
|
|||||||
pub fn run(&self) -> PathBuf {
|
pub fn run(&self) -> PathBuf {
|
||||||
self.root.join("run")
|
self.root.join("run")
|
||||||
}
|
}
|
||||||
|
/// Setup programs the service fetched to update itself.
|
||||||
|
pub fn updates(&self) -> PathBuf {
|
||||||
|
self.root.join("updates")
|
||||||
|
}
|
||||||
|
|
||||||
pub fn logs(&self) -> PathBuf {
|
pub fn logs(&self) -> PathBuf {
|
||||||
self.root.join("logs")
|
self.root.join("logs")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -44,6 +44,12 @@ pub struct Service {
|
|||||||
/// Whether the system-wide AmneziaWG tunnels were registered since the service started:
|
/// Whether the system-wide AmneziaWG tunnels were registered since the service started:
|
||||||
/// the first time, the `autostart` ones start too.
|
/// the first time, the `autostart` ones start too.
|
||||||
awg_vpn_started: bool,
|
awg_vpn_started: bool,
|
||||||
|
/// The kill switch lifted (`proxy-ctl killswitch off`) until a tunnel is turned on again
|
||||||
|
/// (crate::killswitch).
|
||||||
|
pub killswitch_lifted: bool,
|
||||||
|
/// The system-wide AmneziaWG profiles wanted on, by interface: started at boot, or turned
|
||||||
|
/// on since. What the kill switch holds to, whatever their tunnels are doing this moment.
|
||||||
|
pub awg_wanted: BTreeSet<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn digest(data: &[u8]) -> String {
|
fn digest(data: &[u8]) -> String {
|
||||||
@@ -69,6 +75,8 @@ impl Service {
|
|||||||
wl_waiting: BTreeSet::new(),
|
wl_waiting: BTreeSet::new(),
|
||||||
ap: Arc::default(),
|
ap: Arc::default(),
|
||||||
awg_vpn_started: false,
|
awg_vpn_started: false,
|
||||||
|
killswitch_lifted: false,
|
||||||
|
awg_wanted: BTreeSet::new(),
|
||||||
store,
|
store,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -127,6 +135,18 @@ impl Service {
|
|||||||
{
|
{
|
||||||
direct.push(p.to_string_lossy().into_owned());
|
direct.push(p.to_string_lossy().into_owned());
|
||||||
}
|
}
|
||||||
|
// The cutoff probe measures the line: its connections leave directly.
|
||||||
|
if crate::cutoff::enabled(cfg)
|
||||||
|
&& let Some(p) = crate::cutoff::program(paths)
|
||||||
|
{
|
||||||
|
direct.push(p.to_string_lossy().into_owned());
|
||||||
|
}
|
||||||
|
// The service's own: what it fetches directly (fetch::Route::Direct, the line's network
|
||||||
|
// for the probe, a fallback past the proxy) leaves directly; through the proxy it goes
|
||||||
|
// to the local listener, which the TUN does not take.
|
||||||
|
if let Ok(me) = std::env::current_exe() {
|
||||||
|
direct.push(me.to_string_lossy().into_owned());
|
||||||
|
}
|
||||||
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
|
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
|
||||||
Env {
|
Env {
|
||||||
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
|
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
|
||||||
@@ -144,6 +164,9 @@ impl Service {
|
|||||||
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()),
|
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,
|
||||||
|
zapret2_cutoff_rule_set: crate::cutoff::rule_set_path(cfg, paths),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,15 +214,58 @@ impl Service {
|
|||||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
|
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
|
||||||
}
|
}
|
||||||
let proxy = self.apply_proxy().await;
|
let proxy = self.apply_proxy().await;
|
||||||
|
if let Err(e) = self.apply_killswitch() {
|
||||||
|
self.sup.note(SOCKS_UNIT, format!("proxy-suite: the kill switch: {e:#}"));
|
||||||
|
}
|
||||||
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
|
zapret.and(tg).and(ssh).and(tor).and(awg).and(wl).and(proxy)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What the kill switch leaves open now, if it holds anything back.
|
||||||
|
pub fn killswitch_plan(&self) -> Option<crate::killswitch::Plan> {
|
||||||
|
let cfg = self.cfg();
|
||||||
|
let paths = self.paths();
|
||||||
|
let tun = cfg.enable && cfg.proxy.enable && cfg.proxy.tun.enable && self.tun && self.proxy_on;
|
||||||
|
// A system-wide profile counts while it is wanted on, whatever its tunnel is doing.
|
||||||
|
let vpns: Vec<_> = crate::awgvpn::profiles(cfg).into_iter().filter(|v| self.awg_wanted.contains(&v.iface)).collect();
|
||||||
|
let awg = vpns.iter().flat_map(|v| crate::killswitch::awg_addresses(&std::fs::read_to_string(crate::awgvpn::conf_path(paths, &v.iface)).unwrap_or_default())).collect();
|
||||||
|
let me = std::env::current_exe().ok();
|
||||||
|
let mut programs: Vec<std::path::PathBuf> = self
|
||||||
|
.env()
|
||||||
|
.direct_processes
|
||||||
|
.into_iter()
|
||||||
|
.map(std::path::PathBuf::from)
|
||||||
|
// The service's own fetches leave directly only with directFallbacks.
|
||||||
|
.filter(|p| cfg.kill_switch.direct_fallbacks || me.as_ref() != Some(p))
|
||||||
|
.collect();
|
||||||
|
let main = if cfg.proxy.backend == Backend::Xray { self.comps.xray() } else { self.comps.sing_box() };
|
||||||
|
programs.extend(main.ok());
|
||||||
|
if cfg.proxy.backend == Backend::Hybrid {
|
||||||
|
programs.extend(self.comps.xray().ok());
|
||||||
|
}
|
||||||
|
if !vpns.is_empty() {
|
||||||
|
programs.extend(self.comps.find("amneziawg", "awg-tunnel"));
|
||||||
|
}
|
||||||
|
programs.sort();
|
||||||
|
programs.dedup();
|
||||||
|
crate::killswitch::plan(cfg, &crate::killswitch::Tunnels { tun, awg_on: !vpns.is_empty(), awg }, self.killswitch_lifted, programs)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn apply_killswitch(&mut self) -> Result<()> {
|
||||||
|
crate::killswitch::apply(self.killswitch_plan().as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
/// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with
|
/// AmneziaWG's system-wide tunnels: registered (their `.conf` written) or removed with
|
||||||
/// their profiles, the `autostart` ones started with the service.
|
/// their profiles, the `autostart` ones started with the service.
|
||||||
fn apply_awg_vpn(&mut self) {
|
fn apply_awg_vpn(&mut self) {
|
||||||
let cfg = self.cfg().clone();
|
let cfg = self.cfg().clone();
|
||||||
let boot = !self.awg_vpn_started;
|
let boot = !self.awg_vpn_started;
|
||||||
self.awg_vpn_started = true;
|
self.awg_vpn_started = true;
|
||||||
|
// At start: the autostart profiles, and any tunnel already up (turned on before this
|
||||||
|
// service restarted: an update, a crash), are wanted on.
|
||||||
|
if boot {
|
||||||
|
let running = |iface: &str| matches!(crate::awgvpn::state(iface).as_str(), "active" | "activating");
|
||||||
|
self.awg_wanted.extend(crate::awgvpn::profiles(&cfg).into_iter().filter(|v| v.autostart || running(&v.iface)).map(|v| v.iface));
|
||||||
|
}
|
||||||
if !cfg!(windows) {
|
if !cfg!(windows) {
|
||||||
if !crate::awgvpn::profiles(&cfg).is_empty() {
|
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");
|
self.sup.note(crate::awgvpn::UNIT, "proxy-suite: AmneziaWG as a system-wide VPN runs on Windows only; not registered");
|
||||||
@@ -384,10 +450,13 @@ 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, written first.
|
// 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() {
|
if !rendered.probe_exits.is_empty() {
|
||||||
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
|
||||||
}
|
}
|
||||||
|
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
|
||||||
|
crate::cutoff::write_rules(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 {
|
||||||
@@ -400,14 +469,26 @@ impl Service {
|
|||||||
// last good one running.
|
// last good one running.
|
||||||
let candidate = run.join("candidate.json");
|
let candidate = run.join("candidate.json");
|
||||||
write_atomic(&candidate, &main_json)?;
|
write_atomic(&candidate, &main_json)?;
|
||||||
if backend != Backend::Xray {
|
// XRay keeps its geodata beside xray.exe (the component's directory).
|
||||||
let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?;
|
let asset_dir = main_program.parent().map(|d| d.to_string_lossy().into_owned());
|
||||||
if !out.status.success() {
|
let out = if backend == Backend::Xray {
|
||||||
let why = String::from_utf8_lossy(&out.stderr).trim().to_owned();
|
let mut cmd = tokio::process::Command::new(&main_program);
|
||||||
self.last_error = Some(format!("sing-box refused the rendered config: {why}"));
|
cmd.args(["run", "-test", "-c"]).arg(&candidate);
|
||||||
self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}"));
|
if let Some(dir) = &asset_dir {
|
||||||
anyhow::bail!("sing-box refused the rendered config: {why}");
|
cmd.env("XRAY_LOCATION_ASSET", dir);
|
||||||
}
|
}
|
||||||
|
cmd.output().await?
|
||||||
|
} else {
|
||||||
|
tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?
|
||||||
|
};
|
||||||
|
if !out.status.success() {
|
||||||
|
let name = if backend == Backend::Xray { "xray" } else { "sing-box" };
|
||||||
|
// XRay reports on stdout as well.
|
||||||
|
let text = if backend == Backend::Xray { [&out.stdout[..], &out.stderr[..]].concat() } else { out.stderr.clone() };
|
||||||
|
let why = String::from_utf8_lossy(&text).trim().to_owned();
|
||||||
|
self.last_error = Some(format!("{name} refused the rendered config: {why}"));
|
||||||
|
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {name} refused the new config, keeping the old one: {why}"));
|
||||||
|
anyhow::bail!("{name} refused the rendered config: {why}");
|
||||||
}
|
}
|
||||||
if !same_content(&main_path, &main_json) {
|
if !same_content(&main_path, &main_json) {
|
||||||
std::fs::rename(&candidate, &main_path)?;
|
std::fs::rename(&candidate, &main_path)?;
|
||||||
@@ -420,7 +501,7 @@ impl Service {
|
|||||||
name: SOCKS_UNIT.into(),
|
name: SOCKS_UNIT.into(),
|
||||||
program: main_program,
|
program: main_program,
|
||||||
args,
|
args,
|
||||||
env: Vec::new(),
|
env: if backend == Backend::Xray { asset_dir.map(|d| vec![("XRAY_LOCATION_ASSET".to_owned(), d)]).unwrap_or_default() } else { Vec::new() },
|
||||||
cwd: Some(run.clone()),
|
cwd: Some(run.clone()),
|
||||||
generation: digest(&main_json),
|
generation: digest(&main_json),
|
||||||
});
|
});
|
||||||
@@ -475,6 +556,17 @@ impl Service {
|
|||||||
warnings.extend(validate(cfg).into_iter().filter(|i| i.severity == Severity::Warning).map(|i| format!("{}: {}", i.path, i.message)));
|
warnings.extend(validate(cfg).into_iter().filter(|i| i.severity == Severity::Warning).map(|i| format!("{}: {}", i.path, i.message)));
|
||||||
let units: Vec<Value> = self.sup.status().into_iter().map(|u| serde_json::to_value(u).unwrap()).collect();
|
let units: Vec<Value> = self.sup.status().into_iter().map(|u| serde_json::to_value(u).unwrap()).collect();
|
||||||
let socks = self.sup.state_of(SOCKS_UNIT);
|
let socks = self.sup.state_of(SOCKS_UNIT);
|
||||||
|
let kill_switch = {
|
||||||
|
let plan = self.killswitch_plan();
|
||||||
|
let installed = crate::killswitch::installed();
|
||||||
|
// What is in place, not what is meant to be.
|
||||||
|
json!({
|
||||||
|
"enabled": cfg.kill_switch.enable,
|
||||||
|
"holding": plan.is_some() && installed == plan,
|
||||||
|
"failed": plan.is_some() && installed != plan,
|
||||||
|
"lifted": cfg.kill_switch.enable && self.killswitch_lifted,
|
||||||
|
})
|
||||||
|
};
|
||||||
json!({
|
json!({
|
||||||
"units": units,
|
"units": units,
|
||||||
"proxy": {
|
"proxy": {
|
||||||
@@ -488,6 +580,7 @@ impl Service {
|
|||||||
"pinned": self.store.state.pin,
|
"pinned": self.store.state.pin,
|
||||||
"selection": cfg.proxy.selection.as_str(),
|
"selection": cfg.proxy.selection.as_str(),
|
||||||
},
|
},
|
||||||
|
"killSwitch": kill_switch,
|
||||||
"zapret": {
|
"zapret": {
|
||||||
"enabled": cfg.zapret.enable,
|
"enabled": cfg.zapret.enable,
|
||||||
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
|
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
|
||||||
|
|||||||
@@ -0,0 +1,386 @@
|
|||||||
|
//! Updating Proxy Suite itself: the newest release on the project's Gitea, its setup program
|
||||||
|
//! fetched, checked against the SHA-256 published beside it and run silently, as SYSTEM. The
|
||||||
|
//! setup stops this service, puts the new files in place, and starts the service and the app
|
||||||
|
//! (in the signed-in users' sessions) again.
|
||||||
|
|
||||||
|
use std::cmp::Ordering;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use anyhow::{Context, Result, anyhow, bail};
|
||||||
|
use serde_json::{Value, json};
|
||||||
|
|
||||||
|
use crate::fetch::{self, Route};
|
||||||
|
|
||||||
|
/// The project's releases. `PROXY_SUITE_UPDATE_URL` in the service's own environment (which
|
||||||
|
/// only an administrator sets) points it at another listing, for tests.
|
||||||
|
const RELEASES: &str = "https://git.faumaray.com/api/v1/repos/faumaray/proxy-suite-flake/releases?limit=30";
|
||||||
|
/// The Windows port's tags, apart from upstream's `v0.x.0`.
|
||||||
|
const TAG_PREFIX: &str = "windows-v";
|
||||||
|
/// A setup program is ~80 MB.
|
||||||
|
const MAX_SETUP: usize = 512 << 20;
|
||||||
|
|
||||||
|
/// One update at a time: when the one under way began. A setup that never stopped this
|
||||||
|
/// service (it failed early) leaves the way open again after a while.
|
||||||
|
static BUSY: Mutex<Option<Instant>> = Mutex::new(None);
|
||||||
|
const GIVE_UP: Duration = Duration::from_secs(15 * 60);
|
||||||
|
|
||||||
|
fn begin() -> bool {
|
||||||
|
let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
|
if busy.is_some_and(|t| t.elapsed() < GIVE_UP) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
*busy = Some(Instant::now());
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn end() {
|
||||||
|
*BUSY.lock().unwrap_or_else(|e| e.into_inner()) = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn releases_url() -> String {
|
||||||
|
std::env::var("PROXY_SUITE_UPDATE_URL").unwrap_or_else(|_| RELEASES.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A release's version: `major.minor.patch`, with `-pre.N` for a pre-release.
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub struct Version {
|
||||||
|
major: u64,
|
||||||
|
minor: u64,
|
||||||
|
patch: u64,
|
||||||
|
pre: Option<u64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Version {
|
||||||
|
pub fn parse(s: &str) -> Option<Self> {
|
||||||
|
let (core, pre) = match s.split_once('-') {
|
||||||
|
Some((core, pre)) => (core, Some(pre.strip_prefix("pre.")?.parse().ok()?)),
|
||||||
|
None => (s, None),
|
||||||
|
};
|
||||||
|
let mut parts = core.split('.').map(|p| p.parse::<u64>().ok());
|
||||||
|
let v = Version { major: parts.next()??, minor: parts.next()??, patch: parts.next()??, pre };
|
||||||
|
parts.next().is_none().then_some(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn current() -> Self {
|
||||||
|
Self::parse(env!("CARGO_PKG_VERSION")).expect("the package's version reads")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Ord for Version {
|
||||||
|
fn cmp(&self, other: &Self) -> Ordering {
|
||||||
|
(self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch)).then(match (self.pre, other.pre) {
|
||||||
|
(None, None) => Ordering::Equal,
|
||||||
|
// A release is newer than its pre-releases.
|
||||||
|
(None, Some(_)) => Ordering::Greater,
|
||||||
|
(Some(_), None) => Ordering::Less,
|
||||||
|
(Some(a), Some(b)) => a.cmp(&b),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialOrd for Version {
|
||||||
|
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||||
|
Some(self.cmp(other))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for Version {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?;
|
||||||
|
match self.pre {
|
||||||
|
Some(n) => write!(f, "-pre.{n}"),
|
||||||
|
None => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A newer release, with its setup program.
|
||||||
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
|
pub struct Release {
|
||||||
|
pub version: Version,
|
||||||
|
pub page: String,
|
||||||
|
pub notes: String,
|
||||||
|
pub published: String,
|
||||||
|
pub setup: String,
|
||||||
|
pub size: u64,
|
||||||
|
pub checksum: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Release {
|
||||||
|
pub fn to_json(&self) -> Value {
|
||||||
|
json!({
|
||||||
|
"version": self.version.to_string(),
|
||||||
|
"page": self.page,
|
||||||
|
"notes": self.notes,
|
||||||
|
"published": self.published,
|
||||||
|
"size": self.size,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `scheme://host[:port]` of a URL.
|
||||||
|
fn origin(url: &str) -> Option<&str> {
|
||||||
|
let start = url.find("://")? + 3;
|
||||||
|
let end = url[start..].find(['/', '?', '#']).map_or(url.len(), |i| start + i);
|
||||||
|
(end > start).then(|| &url[..end])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest release newer than `current` in a Gitea releases listing. Drafts and other tags
|
||||||
|
/// are left out, pre-releases unless `current` is one (who runs a release stays on releases),
|
||||||
|
/// and a release without its setup program and checksum, or with them on another host than
|
||||||
|
/// the listing's.
|
||||||
|
pub fn newest(list: &Value, current: Version, listing: &str) -> Option<Release> {
|
||||||
|
let home = origin(listing)?;
|
||||||
|
list.as_array()?
|
||||||
|
.iter()
|
||||||
|
.filter_map(|r| {
|
||||||
|
if r["draft"] == true {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let version = Version::parse(r["tag_name"].as_str()?.strip_prefix(TAG_PREFIX)?)?;
|
||||||
|
if version <= current || ((r["prerelease"] == true || version.pre.is_some()) && current.pre.is_none()) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let name = format!("ProxySuite-{version}-windows-x64-setup.exe");
|
||||||
|
let asset = |n: &str| r["assets"].as_array()?.iter().find(|a| a["name"] == n);
|
||||||
|
let url = |a: &Value| a["browser_download_url"].as_str().filter(|u| origin(u) == Some(home)).map(str::to_owned);
|
||||||
|
let setup = asset(&name)?;
|
||||||
|
Some(Release {
|
||||||
|
version,
|
||||||
|
page: r["html_url"].as_str().unwrap_or_default().to_owned(),
|
||||||
|
notes: r["body"].as_str().unwrap_or_default().to_owned(),
|
||||||
|
published: r["published_at"].as_str().unwrap_or_default().to_owned(),
|
||||||
|
setup: url(setup)?,
|
||||||
|
size: setup["size"].as_u64().unwrap_or(0),
|
||||||
|
checksum: url(asset(&format!("{name}.sha256"))?)?,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.max_by_key(|r| r.version)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first route's answer that comes.
|
||||||
|
async fn first<T, F: Future<Output = Result<T>>>(routes: &[Route], each: impl Fn(Route) -> F) -> Result<T> {
|
||||||
|
let mut last = None;
|
||||||
|
for route in routes {
|
||||||
|
match each(route.clone()).await {
|
||||||
|
Ok(v) => return Ok(v),
|
||||||
|
Err(e) => last = Some(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(last.unwrap_or_else(|| anyhow!("no way to reach the network")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The newest release, if there is one newer than this.
|
||||||
|
pub async fn check(routes: &[Route]) -> Result<Option<Release>> {
|
||||||
|
let url = releases_url();
|
||||||
|
let body = first(routes, |r| {
|
||||||
|
let url = url.clone();
|
||||||
|
async move { fetch::get(&url, &r, 4 << 20).await }
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.context("the releases")?;
|
||||||
|
let list: Value = serde_json::from_slice(&body).context("the releases' listing")?;
|
||||||
|
Ok(newest(&list, Version::current(), &url))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The SHA-256 a `.sha256` file holds (`sha256sum`'s line).
|
||||||
|
fn published_sum(text: &[u8]) -> Result<String> {
|
||||||
|
let text = std::str::from_utf8(text).unwrap_or_default();
|
||||||
|
match text.split_whitespace().next() {
|
||||||
|
Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(h.to_ascii_lowercase()),
|
||||||
|
_ => bail!("the published checksum does not read"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The release's setup program in `dir` (older ones gone), once its SHA-256 matches. `dir` is
|
||||||
|
/// under the state root, whose protected DACL (SYSTEM and Administrators only, inherited)
|
||||||
|
/// keeps anyone else from replacing the file between this check and its run as SYSTEM.
|
||||||
|
async fn download(release: &Release, routes: &[Route], dir: &Path) -> Result<PathBuf> {
|
||||||
|
let sum = first(routes, |r| {
|
||||||
|
let url = release.checksum.clone();
|
||||||
|
async move { fetch::get(&url, &r, 4096).await }
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.context("the setup program's checksum")?;
|
||||||
|
let want = published_sum(&sum)?;
|
||||||
|
let body = first(routes, |r| {
|
||||||
|
let url = release.setup.clone();
|
||||||
|
async move { fetch::get_large(&url, &r, MAX_SETUP).await }
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.context("the setup program")?;
|
||||||
|
if crate::install::hex(&body) != want {
|
||||||
|
bail!("the setup program's SHA-256 is not the one published beside it");
|
||||||
|
}
|
||||||
|
std::fs::create_dir_all(dir)?;
|
||||||
|
for e in std::fs::read_dir(dir)?.flatten() {
|
||||||
|
let _ = std::fs::remove_file(e.path());
|
||||||
|
}
|
||||||
|
let path = dir.join(format!("ProxySuite-{}-windows-x64-setup.exe", release.version));
|
||||||
|
crate::paths::write_atomic(&path, &body).with_context(|| format!("writing {}", path.display()))?;
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `install` leaves for the service that the setup starts: the version it went for.
|
||||||
|
const PENDING: &str = "pending";
|
||||||
|
|
||||||
|
/// Fetches the newest release's setup program and runs it, a moment after this returns (so
|
||||||
|
/// the caller hears of it before the setup stops the service).
|
||||||
|
pub async fn install(routes: &[Route], dir: &Path) -> Result<Release> {
|
||||||
|
if !begin() {
|
||||||
|
bail!("an update is under way already");
|
||||||
|
}
|
||||||
|
let r = async {
|
||||||
|
let release = check(routes).await?.ok_or_else(|| anyhow!("this is the newest release ({})", env!("CARGO_PKG_VERSION")))?;
|
||||||
|
tracing::info!("update: fetching {}", release.version);
|
||||||
|
let setup = download(&release, routes, dir).await?;
|
||||||
|
std::fs::write(dir.join(PENDING), release.version.to_string())?;
|
||||||
|
run_later(setup);
|
||||||
|
Ok(release)
|
||||||
|
}
|
||||||
|
.await;
|
||||||
|
if r.is_err() {
|
||||||
|
end();
|
||||||
|
}
|
||||||
|
r
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_later(setup: PathBuf) {
|
||||||
|
tokio::spawn(async move {
|
||||||
|
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||||
|
tracing::info!("update: running {}", setup.display());
|
||||||
|
if let Err(e) = run(&setup) {
|
||||||
|
tracing::error!("update: {e:#}");
|
||||||
|
let _ = std::fs::remove_file(setup.with_file_name(PENDING));
|
||||||
|
end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The setup, silent, on its own: out of any job this process is in, and of its console, as it
|
||||||
|
/// outlives the service it stops.
|
||||||
|
#[cfg(windows)]
|
||||||
|
fn run(setup: &Path) -> Result<()> {
|
||||||
|
use std::os::windows::process::CommandExt;
|
||||||
|
const DETACHED_PROCESS: u32 = 0x8;
|
||||||
|
const CREATE_NEW_PROCESS_GROUP: u32 = 0x200;
|
||||||
|
const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;
|
||||||
|
let spawn = |flags: u32| {
|
||||||
|
std::process::Command::new(setup)
|
||||||
|
.arg("/S")
|
||||||
|
.current_dir(setup.parent().unwrap_or(Path::new(".")))
|
||||||
|
.creation_flags(flags)
|
||||||
|
.stdin(std::process::Stdio::null())
|
||||||
|
.stdout(std::process::Stdio::null())
|
||||||
|
.stderr(std::process::Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
};
|
||||||
|
// A job that allows no breakaway refuses the flag; none to break away from ignores it.
|
||||||
|
spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB)
|
||||||
|
.or_else(|_| spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP))
|
||||||
|
.context("starting the setup program")?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(windows))]
|
||||||
|
fn run(setup: &Path) -> Result<()> {
|
||||||
|
bail!("{} is a Windows setup program; not run here", setup.display())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Said once in the log at start: whether the update `install` went for is the version now
|
||||||
|
/// running.
|
||||||
|
pub fn report(dir: &Path) {
|
||||||
|
let path = dir.join(PENDING);
|
||||||
|
let Ok(wanted) = std::fs::read_to_string(&path) else { return };
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
if wanted.trim() == env!("CARGO_PKG_VERSION") {
|
||||||
|
tracing::info!("updated to {}", env!("CARGO_PKG_VERSION"));
|
||||||
|
// Done with: ~80 MB.
|
||||||
|
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||||
|
let _ = std::fs::remove_file(e.path());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
tracing::warn!("the update to {} did not finish; this is still {}", wanted.trim(), env!("CARGO_PKG_VERSION"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn v(s: &str) -> Version {
|
||||||
|
Version::parse(s).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn versions_order_as_releases() {
|
||||||
|
assert!(v("0.3.0-pre.1") > v("0.2.0-pre.1"));
|
||||||
|
assert!(v("0.3.0-pre.2") > v("0.3.0-pre.1"));
|
||||||
|
assert!(v("0.3.0") > v("0.3.0-pre.9"));
|
||||||
|
assert!(v("0.10.0") > v("0.9.1"));
|
||||||
|
assert_eq!(v("1.2.3-pre.4").to_string(), "1.2.3-pre.4");
|
||||||
|
for bad in ["0.3", "0.3.0.1", "0.3.0-rc.1", "x.1.2", "0.3.0-pre."] {
|
||||||
|
assert_eq!(Version::parse(bad), None, "{bad}");
|
||||||
|
}
|
||||||
|
assert_eq!(Version::current().to_string(), env!("CARGO_PKG_VERSION"));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn release(tag: &str, pre: bool, host: &str) -> Value {
|
||||||
|
let v = tag.trim_start_matches(TAG_PREFIX);
|
||||||
|
let name = format!("ProxySuite-{v}-windows-x64-setup.exe");
|
||||||
|
json!({
|
||||||
|
"tag_name": tag, "prerelease": pre, "draft": false, "body": "notes", "html_url": format!("{host}/r/{tag}"),
|
||||||
|
"assets": [
|
||||||
|
{ "name": name, "size": 5, "browser_download_url": format!("{host}/d/{tag}/{name}") },
|
||||||
|
{ "name": format!("{name}.sha256"), "size": 1, "browser_download_url": format!("{host}/d/{tag}/{name}.sha256") },
|
||||||
|
],
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
const HOME: &str = "https://git.example";
|
||||||
|
const LIST: &str = "https://git.example/api/v1/repos/o/r/releases?limit=30";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_newest_release_with_a_setup_program() {
|
||||||
|
let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.3.0-pre.1", true, HOME), release("v0.9.0", false, HOME)]);
|
||||||
|
let r = newest(&list, v("0.3.0-pre.1"), LIST).unwrap();
|
||||||
|
assert_eq!(r.version, v("0.3.0-pre.2"));
|
||||||
|
assert_eq!(r.setup, "https://git.example/d/windows-v0.3.0-pre.2/ProxySuite-0.3.0-pre.2-windows-x64-setup.exe");
|
||||||
|
assert!(r.checksum.ends_with(".exe.sha256"));
|
||||||
|
// Nothing newer.
|
||||||
|
assert_eq!(newest(&list, v("0.3.0-pre.2"), LIST), None);
|
||||||
|
// Who runs a release is not offered pre-releases, but a newer release.
|
||||||
|
assert_eq!(newest(&list, v("0.2.0"), LIST), None);
|
||||||
|
let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.2.1", false, HOME)]);
|
||||||
|
assert_eq!(newest(&list, v("0.2.0"), LIST).unwrap().version, v("0.2.1"));
|
||||||
|
assert_eq!(newest(&list, v("0.2.0-pre.1"), LIST).unwrap().version, v("0.3.0-pre.2"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn drafts_strangers_and_releases_without_a_setup_are_passed_over() {
|
||||||
|
let mut draft = release("windows-v0.4.0", false, HOME);
|
||||||
|
draft["draft"] = true.into();
|
||||||
|
let elsewhere = release("windows-v0.5.0", false, "https://evil.example");
|
||||||
|
let mut zip_only = release("windows-v0.6.0", false, HOME);
|
||||||
|
zip_only["assets"].as_array_mut().unwrap().remove(0);
|
||||||
|
let mut no_sum = release("windows-v0.7.0", false, HOME);
|
||||||
|
no_sum["assets"].as_array_mut().unwrap().remove(1);
|
||||||
|
let list = json!([draft, elsewhere, zip_only, no_sum, release("windows-v0.3.1", false, HOME)]);
|
||||||
|
assert_eq!(newest(&list, v("0.3.0"), LIST).unwrap().version, v("0.3.1"));
|
||||||
|
// http is another origin than https.
|
||||||
|
let list = json!([release("windows-v0.3.1", false, "http://git.example")]);
|
||||||
|
assert_eq!(newest(&list, v("0.3.0"), LIST), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn origins_and_checksums_read() {
|
||||||
|
assert_eq!(origin("https://h.example:3000/a/b?c"), Some("https://h.example:3000"));
|
||||||
|
assert_eq!(origin("https://h.example?x"), Some("https://h.example"));
|
||||||
|
assert_eq!(origin("https://"), None);
|
||||||
|
let h = "3ff31008aa1d9f4e".repeat(4);
|
||||||
|
assert_eq!(published_sum(format!("{h} ProxySuite-0.2.0-pre.1-windows-x64-setup.exe\n").as_bytes()).unwrap(), h);
|
||||||
|
assert!(published_sum(b"not a sum").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -98,7 +98,12 @@ pub fn install() -> Result<()> {
|
|||||||
}
|
}
|
||||||
if from != to {
|
if from != to {
|
||||||
desktop::close();
|
desktop::close();
|
||||||
copy_release(&from, &to)?;
|
if let Err(e) = copy_release(&from, &to) {
|
||||||
|
// Unattended (an update), no one would start again what was running.
|
||||||
|
let _ = existing.start::<&str>(&[]);
|
||||||
|
desktop::start(&to);
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
existing.change_config(&info)?;
|
existing.change_config(&info)?;
|
||||||
existing
|
existing
|
||||||
@@ -191,6 +196,13 @@ pub fn uninstall() -> Result<()> {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// WinDivert's driver, if this suite's is still loaded: its files are about to be replaced.
|
||||||
|
pub fn release_windivert() {
|
||||||
|
if let Ok(manager) = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT) {
|
||||||
|
remove_windivert(&manager);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The WinDivert driver zapret loaded from this suite's components, if it is still registered
|
/// 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
|
/// (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.
|
/// deleted, as Flowseal's service.bat removes it. One from elsewhere is left alone.
|
||||||
@@ -365,9 +377,102 @@ mod desktop {
|
|||||||
Ok(true)
|
Ok(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The app, as the signed-in user rather than as this elevated installer: Explorer starts it.
|
/// The app, as the signed-in user rather than as this elevated installer: Explorer starts
|
||||||
|
/// it. Run by the service (an update, as SYSTEM, in session 0, which no one sees), it is
|
||||||
|
/// started in each signed-in user's session as that user instead, as at their sign-in.
|
||||||
pub fn start(dir: &Path) {
|
pub fn start(dir: &Path) {
|
||||||
let _ = Command::new("explorer.exe").arg(dir.join("proxy-suite.exe")).spawn();
|
let app = dir.join("proxy-suite.exe");
|
||||||
|
if session::own() == Some(0) {
|
||||||
|
session::start_for_each_user(&app);
|
||||||
|
} else {
|
||||||
|
let _ = Command::new("explorer.exe").arg(&app).spawn();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
mod session {
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
|
||||||
|
use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock};
|
||||||
|
use windows_sys::Win32::System::RemoteDesktop::{
|
||||||
|
ProcessIdToSessionId, WTS_CURRENT_SERVER_HANDLE, WTS_SESSION_INFOW, WTSActive, WTSEnumerateSessionsW, WTSFreeMemory, WTSQueryUserToken,
|
||||||
|
};
|
||||||
|
use windows_sys::Win32::System::Threading::{
|
||||||
|
CREATE_UNICODE_ENVIRONMENT, CreateProcessAsUserW, GetCurrentProcessId, PROCESS_INFORMATION, STARTUPINFOW,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// This process's session.
|
||||||
|
pub fn own() -> Option<u32> {
|
||||||
|
let mut id = 0u32;
|
||||||
|
// SAFETY: an out pointer to a u32.
|
||||||
|
(unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut id) } != 0).then_some(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `app` in every session a user is signed in to and at (a console's, a remote
|
||||||
|
/// desktop's), with that user's token and environment.
|
||||||
|
pub fn start_for_each_user(app: &Path) {
|
||||||
|
let mut list: *mut WTS_SESSION_INFOW = std::ptr::null_mut();
|
||||||
|
let mut count = 0u32;
|
||||||
|
// SAFETY: out pointers; the list is freed below and read within `count`.
|
||||||
|
let sessions: Vec<u32> = unsafe {
|
||||||
|
if WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &mut list, &mut count) == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let ids = std::slice::from_raw_parts(list, count as usize).iter().filter(|s| s.State == WTSActive).map(|s| s.SessionId).collect();
|
||||||
|
WTSFreeMemory(list.cast());
|
||||||
|
ids
|
||||||
|
};
|
||||||
|
for id in sessions {
|
||||||
|
if let Err(e) = start_in(id, app) {
|
||||||
|
println!("warning: the app in session {id}: {e}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn start_in(session: u32, app: &Path) -> std::io::Result<()> {
|
||||||
|
let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::<Vec<u16>>();
|
||||||
|
let mut command = wide(&format!("\"{}\"", app.display()));
|
||||||
|
let dir = wide(&app.parent().unwrap_or(app).display().to_string());
|
||||||
|
let mut desktop = wide("winsta0\\default");
|
||||||
|
// SAFETY: the token and environment are released below; the strings are
|
||||||
|
// NUL-terminated and live across the call; the out structs are zeroed.
|
||||||
|
unsafe {
|
||||||
|
let mut token: HANDLE = std::ptr::null_mut();
|
||||||
|
if WTSQueryUserToken(session, &mut token) == 0 {
|
||||||
|
return Err(std::io::Error::last_os_error());
|
||||||
|
}
|
||||||
|
let mut env: *mut core::ffi::c_void = std::ptr::null_mut();
|
||||||
|
let have_env = CreateEnvironmentBlock(&mut env, token, 0) != 0;
|
||||||
|
let mut si: STARTUPINFOW = std::mem::zeroed();
|
||||||
|
si.cb = std::mem::size_of::<STARTUPINFOW>() as u32;
|
||||||
|
si.lpDesktop = desktop.as_mut_ptr();
|
||||||
|
let mut pi: PROCESS_INFORMATION = std::mem::zeroed();
|
||||||
|
let ok = CreateProcessAsUserW(
|
||||||
|
token,
|
||||||
|
std::ptr::null(),
|
||||||
|
command.as_mut_ptr(),
|
||||||
|
std::ptr::null(),
|
||||||
|
std::ptr::null(),
|
||||||
|
0,
|
||||||
|
CREATE_UNICODE_ENVIRONMENT,
|
||||||
|
if have_env { env } else { std::ptr::null() },
|
||||||
|
dir.as_ptr(),
|
||||||
|
&si,
|
||||||
|
&mut pi,
|
||||||
|
) != 0;
|
||||||
|
let err = std::io::Error::last_os_error();
|
||||||
|
if have_env {
|
||||||
|
DestroyEnvironmentBlock(env);
|
||||||
|
}
|
||||||
|
CloseHandle(token);
|
||||||
|
if !ok {
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
CloseHandle(pi.hProcess);
|
||||||
|
CloseHandle(pi.hThread);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn remove() {
|
pub fn remove() {
|
||||||
|
|||||||
@@ -50,6 +50,12 @@ fn with_sep(p: &Path) -> String {
|
|||||||
/// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the
|
/// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the
|
||||||
/// service's run directory (the release's own, the user's entries added) and the game
|
/// service's run directory (the release's own, the user's entries added) and the game
|
||||||
/// filter. `program` is the verified winws.exe.
|
/// filter. `program` is the verified winws.exe.
|
||||||
|
/// The TUN's packets, left out of WinDivert's filter, when the proxy has a TUN.
|
||||||
|
fn tun_keep_off(cfg: &Config) -> Option<String> {
|
||||||
|
let p = &cfg.proxy;
|
||||||
|
(p.enable && p.tun.enable).then(|| zapret::tun_exclusion(&p.tun.address, p.ipv6.then_some(ps_core::render::TUN_IPV6_ADDRESS))).flatten()
|
||||||
|
}
|
||||||
|
|
||||||
pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
|
pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
|
||||||
let y = &cfg.zapret.discord_youtube;
|
let y = &cfg.zapret.discord_youtube;
|
||||||
let component = paths.bin().join("zapret");
|
let component = paths.bin().join("zapret");
|
||||||
@@ -113,6 +119,26 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
|
|||||||
if cfg.debug.log_level != ps_core::config::LogLevel::Warn {
|
if cfg.debug.log_level != ps_core::config::LogLevel::Warn {
|
||||||
argv.insert(0, "--debug=1".into());
|
argv.insert(0, "--debug=1".into());
|
||||||
}
|
}
|
||||||
|
// Beside the TUN: Flowseal's winws takes no filter part ANDed with the rest, so its whole
|
||||||
|
// filter, as it saves it itself for these arguments, with the TUN's packets left out.
|
||||||
|
let mut filter = String::new();
|
||||||
|
if cfg!(windows)
|
||||||
|
&& let Some(keep_off) = tun_keep_off(cfg)
|
||||||
|
{
|
||||||
|
let saved = paths.run().join("zapret").join("winws-own-filter.txt");
|
||||||
|
let _ = std::fs::remove_file(&saved);
|
||||||
|
let mut cmd = std::process::Command::new(&program);
|
||||||
|
cmd.arg(format!("--wf-save={}", saved.display())).args(&argv).current_dir(&bin_dir);
|
||||||
|
cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||||
|
#[cfg(windows)]
|
||||||
|
std::os::windows::process::CommandExt::creation_flags(&mut cmd, 0x0800_0000); // CREATE_NO_WINDOW
|
||||||
|
let _ = cmd.status();
|
||||||
|
let own = std::fs::read_to_string(&saved).context("winws did not save its filter (--wf-save), to leave the TUN out of it")?;
|
||||||
|
filter = format!("({})\nand\n({keep_off})\n", own.trim());
|
||||||
|
let file = paths.run().join("zapret").join("winws-filter.txt");
|
||||||
|
write_atomic(&file, filter.as_bytes())?;
|
||||||
|
argv = zapret::with_raw_filter(&argv, &file.to_string_lossy());
|
||||||
|
}
|
||||||
// A change of the arguments or of a list winws reads is a restart.
|
// A change of the arguments or of a list winws reads is a restart.
|
||||||
let generation = {
|
let generation = {
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
@@ -121,6 +147,7 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
|
|||||||
h.update(a.as_bytes());
|
h.update(a.as_bytes());
|
||||||
h.update(b"\n");
|
h.update(b"\n");
|
||||||
}
|
}
|
||||||
|
h.update(filter.as_bytes());
|
||||||
for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"].iter().map(|f| f.to_string()).chain(rule_files) {
|
for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"].iter().map(|f| f.to_string()).chain(rule_files) {
|
||||||
h.update(std::fs::read(lists.join(&f)).unwrap_or_default());
|
h.update(std::fs::read(lists.join(&f)).unwrap_or_default());
|
||||||
}
|
}
|
||||||
@@ -146,19 +173,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 +221,156 @@ 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,
|
||||||
|
keep_off: tun_keep_off(cfg),
|
||||||
};
|
};
|
||||||
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"))));
|
||||||
|
// The 16 KB cutoff probe's maps, for z2k's tcp16 name step (z2k's own strategies).
|
||||||
|
if source.z2k {
|
||||||
|
env.extend(crate::cutoff::lua_env(cfg, paths, lua_path));
|
||||||
|
}
|
||||||
|
}
|
||||||
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 +404,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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 98 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 127 KiB After Width: | Height: | Size: 130 KiB |
|
Before Width: | Height: | Size: 84 KiB After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 86 KiB |
|
Before Width: | Height: | Size: 79 KiB After Width: | Height: | Size: 79 KiB |
|
After Width: | Height: | Size: 77 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 85 KiB After Width: | Height: | Size: 77 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 104 KiB |
@@ -1,46 +1,57 @@
|
|||||||
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`; and a setup program.
|
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.
|
||||||
- **AmneziaWG:** profiles (system-wide or outbounds), a system-wide one switched on and off with its tunnel's log, one added from a `vpn://` link or a `.conf`, or removed.
|
|
||||||
- **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.
|
|
||||||
- **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).
|
- **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.
|
||||||
- **Icon:** the app has one now (window, taskbar, Start Menu, Settings → Apps).
|
|
||||||
- **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 a system-wide VPN: a profile without `asOutbound` is a tunnel of its own (amneziawg-windows's, built from its source, on Wintun), its routes, DNS and kill switch for a full tunnel; switched on and off on the app's AmneziaWG page or with `proxy-ctl awg on|off`, started at boot with `autostart`.
|
|
||||||
- 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.
|
|
||||||
- autoProxy (`proxy.autoProxy`): sites apps reach directly are probed through each exit; one blocked directly but reached through an exit is routed through it, as upstream decides. A site that crawls directly moves to an exit that carries it as well (`slowBelowKiBps`). In the app, or `proxy-ctl proxy auto` (list, probe, learn, forget, clear).
|
|
||||||
- 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`.
|
|
||||||
- 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`).
|
||||||
- A setup program (`…-setup.exe`, English and Russian), with an uninstaller in Settings → Apps; `install.cmd` from the zip makes that entry too. Uninstalling removes WinDivert's driver service too, when it is the suite's.
|
- Uninstalling removes WinDivert's driver service and the AmneziaWG tunnels too, when they are the suite's.
|
||||||
- The programs carry their C runtime: no Visual C++ Redistributable needed.
|
|
||||||
- Built and published by Gitea Actions.
|
- Built and published by Gitea Actions.
|
||||||
|
|
||||||
### Install
|
|
||||||
Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256 is in the `.sha256` file next to it); SmartScreen may warn of an unknown publisher, the programs are not signed yet (**More info** → **Run anyway**). It installs everything, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Nothing has to be installed first: the programs carry their C runtime now. Needs 64-bit Windows 10 (1903 or later) or 11.
|
|
||||||
|
|
||||||
The zip is still there, the same files with `install.cmd`.
|
|
||||||
|
|
||||||
### Not yet
|
### Not yet
|
||||||
Tor's onion service, 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`.
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
Proxy Suite for Windows 0.3.0-pre.1: updates from the app, the app in Russian and in a dark theme, zapret2's 16 KB cutoff probe, the XRay-only backend, the TUN beside the DPI bypass, and the kill switch.
|
||||||
|
|
||||||
|
**Partly tried on real Windows:** 0.2.0-pre.1's setup program, zapret, zapret2 and tg-ws-proxy work there. The rest was built and tested on Linux, and under Wine where Wine can. See "What has been verified" in the README, and please report what happens on yours.
|
||||||
|
|
||||||
|
### Downloads
|
||||||
|
- **`ProxySuite-0.3.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.3.0-pre.1-windows-x64.zip`**: the same files, unpacked anywhere; `install.cmd` installs them (as an administrator), `uninstall.cmd` removes them.
|
||||||
|
|
||||||
|
From 0.2.0-pre.1: run the new setup over it; the settings stay. 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**). Needs 64-bit Windows 10 (1903 or later) or 11.
|
||||||
|
|
||||||
|
### New
|
||||||
|
- **Updates from the app**: its Overview says when a newer release is out and installs it. The service fetches the setup program from this project's releases, checks its SHA-256 against the one published beside it and runs it silently; the service and the app close for a moment and start again, new, settings kept. Also `proxy-ctl update` and `proxy-ctl update install`. It looks at start and daily (Settings → This app turns that off). This is the first release that has it: from 0.2.0-pre.1, update by running the new setup.
|
||||||
|
- **zapret2's 16 KB cutoff probe** (`zapret2.cutoff`, on by default, as upstream's): some lines cut TLS to certain hosting networks after about 16 KB, which no strategy fixes. z2k's probe finds those networks daily (or when the line's network changes) and, with z2k's strategies, a name that gets through for each, which z2k puts into a fake hello; what no name fixes goes through the proxy, by address (`cutoff.proxyFallback`). The probe's connections leave from ports winws2 leaves alone. On the DPI bypass page, or `proxy-ctl zapret cutoff [probe]`.
|
||||||
|
- **The app in Russian**: every page, the tray's menu and the notifications, as Windows' display language is (or chosen in Settings → This app). What the service itself says (its warnings and errors) and `proxy-ctl` stay English.
|
||||||
|
- **The XRay-only backend** (`proxy.backend = "xray"`): the local proxy runs on XRay alone, with upstream's config: a SOCKS listener (with a login when set), DNS ordered by the routing mode with the proxy servers' names kept off the proxy, the route modes' lists, `urltest` as a `leastPing` balancer with an observatory (a pin or `first` leaves the one exit), chains, and the helpers (Tor, SSH, WARP, AmneziaWG, whitelist-bypass) as SOCKS hops. What needs sing-box is refused as upstream refuses it (groups, rule sets, autoProxy, latency tests, `selector`/`failover`, DoT, fake IP, the connection log), and so are the TUN and per-app routing, which XRay has no Windows counterpart for yet. The service checks the config with `xray run -test` before it replaces the running one.
|
||||||
|
- **The TUN and the DPI bypass together**: zapret and zapret2 leave the TUN's own packets alone (by its address, in WinDivert's filter) and handle what sing-box sends out of the real adapter, as upstream keeps zapret off the TUN interface.
|
||||||
|
- **The kill switch** (`killSwitch`, off by default): while the global tunnel (the TUN, or a system-wide AmneziaWG profile) is on, what would leave past it is blocked, while it runs, restarts or has failed; LAN, DHCP and NTP stay open, and the tunnel's own programs. Windows Filtering Platform filters do it, in the service's own session: they go with the service (upstream's holds from boot; that comes once these have been seen to work on real Windows). Turning the tunnel off, `proxy-ctl killswitch off` or the Overview's **Lift** lets go until a tunnel is turned on again. Not yet tried on real Windows: please do, and `sc stop ProxySuite` gets the network back if it misbehaves.
|
||||||
|
- **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- The tray's **Open Proxy Suite** opened a second window when one was open, rather than bringing it forward.
|
||||||
|
- An upgrade now stops a running system-wide AmneziaWG tunnel while its program is replaced, and starts it again; WinDivert's driver is let go of before zapret's files are replaced.
|
||||||
|
- A failed copy during an upgrade starts the old service and app again, rather than leaving them stopped.
|
||||||
|
- The helpers' "always direct" rule (the XRay sidecar, wireproxy, Tor, tg-ws-proxy, whitelist-bypass) now applies to what the TUN takes only.
|
||||||
|
|
||||||
|
### Not yet
|
||||||
|
Server inbounds, and Tor's onion service on them. Their options are accepted (they are upstream's), and the service says it does not run them.
|
||||||
|
|
||||||
|
Screenshots are in the README.
|
||||||
@@ -12,7 +12,8 @@
|
|||||||
# learner's arguments), @STALLWATCH@; and the paths, @Z2K@ (z2k's files) and @ROOT@ (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.
|
# 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)
|
# tools/build-zapret2-extras.sh OUT_DIR (needs git, bash, gawk, python3, nix, go;
|
||||||
|
# Z2K_DETECT_GOOS=linux: z2k-detect for here)
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
. "$(dirname "$0")/lib.sh"
|
. "$(dirname "$0")/lib.sh"
|
||||||
OUT=$(realpath -m "${1:?output directory}")
|
OUT=$(realpath -m "${1:?output directory}")
|
||||||
@@ -46,6 +47,70 @@ if old not in s:
|
|||||||
open(p, "w").write(s.replace(old, new))
|
open(p, "w").write(s.replace(old, new))
|
||||||
PY
|
PY
|
||||||
|
|
||||||
|
# --- the 16 KB cutoff probe: z2k-detect, as upstream's pkgs/z2k-detect.nix builds it --------
|
||||||
|
# Its connections leave from the local ports the service names (Z2K_TCP16_LOCAL_PORTS), which
|
||||||
|
# winws2's filter leaves out, as upstream's nft rule keeps zapret2 off the probe's cgroup.
|
||||||
|
t=$Z/z2k-detect/internal/tcp16/tcp16.go
|
||||||
|
grep -qF 'raw, err := d.DialContext(ctx, "tcp", addr)' "$t" || { echo "z2k-detect's tcp16 dial changed"; exit 1; }
|
||||||
|
sed -i 's|raw, err := d.DialContext(ctx, "tcp", addr)|raw, err := dialFrom(ctx, \&d, addr)|' "$t"
|
||||||
|
cat >"$Z/z2k-detect/internal/tcp16/localport.go" <<'GO'
|
||||||
|
package tcp16
|
||||||
|
|
||||||
|
// Proxy Suite for Windows: the probe's connections from a range of local ports
|
||||||
|
// (Z2K_TCP16_LOCAL_PORTS, "lo-hi") that the DPI bypass leaves alone. A port taken
|
||||||
|
// (or in TIME_WAIT) is passed over for the next.
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"net"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"sync/atomic"
|
||||||
|
)
|
||||||
|
|
||||||
|
var portLo, portHi = func() (int, int) {
|
||||||
|
lo, hi, ok := strings.Cut(os.Getenv("Z2K_TCP16_LOCAL_PORTS"), "-")
|
||||||
|
a, e1 := strconv.Atoi(lo)
|
||||||
|
b, e2 := strconv.Atoi(hi)
|
||||||
|
if !ok || e1 != nil || e2 != nil || a < 1 || b > 65535 || a > b {
|
||||||
|
return 0, 0
|
||||||
|
}
|
||||||
|
return a, b
|
||||||
|
}()
|
||||||
|
|
||||||
|
var nextPort atomic.Uint32
|
||||||
|
|
||||||
|
func dialFrom(ctx context.Context, d *net.Dialer, addr string) (net.Conn, error) {
|
||||||
|
if portLo == 0 {
|
||||||
|
return d.DialContext(ctx, "tcp", addr)
|
||||||
|
}
|
||||||
|
n := uint32(portHi - portLo + 1)
|
||||||
|
var err error
|
||||||
|
for i := 0; i < 64; i++ {
|
||||||
|
dd := *d
|
||||||
|
dd.LocalAddr = &net.TCPAddr{Port: portLo + int(nextPort.Add(1)%n)}
|
||||||
|
c, e := dd.DialContext(ctx, "tcp", addr)
|
||||||
|
if e == nil {
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
err = e
|
||||||
|
var se *os.SyscallError
|
||||||
|
if !errors.As(e, &se) || se.Syscall != "bind" {
|
||||||
|
return nil, e
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
GO
|
||||||
|
(
|
||||||
|
cd "$Z/z2k-detect"
|
||||||
|
export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=${Z2K_DETECT_GOOS:-windows} GOARCH=amd64
|
||||||
|
ext=; [ "$GOOS" = windows ] && ext=.exe
|
||||||
|
go build -trimpath -ldflags "-s -w" -o "$OUT/z2k-detect$ext" ./cmd/z2k-detect
|
||||||
|
)
|
||||||
|
|
||||||
# --- proxy-suite's own Lua --------------------------------------------------------------
|
# --- proxy-suite's own Lua --------------------------------------------------------------
|
||||||
cp "$UPSTREAM/detect.lua" "$UPSTREAM/persist-every.lua" "$UPSTREAM/strategy-log.lua" "$OUT/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.
|
# The suffix list's path from the environment: it is where the component is installed.
|
||||||
@@ -191,5 +256,5 @@ for name in NFQWS2_PORTS_TCP NFQWS2_PORTS_UDP; do
|
|||||||
done >"$OUT/z2k/ports"
|
done >"$OUT/z2k/ports"
|
||||||
grep -q '^NFQWS2_PORTS_TCP=.\+' "$OUT/z2k/ports" || { echo "z2k's ports not found"; exit 1; }
|
grep -q '^NFQWS2_PORTS_TCP=.\+' "$OUT/z2k/ports" || { echo "z2k's ports not found"; exit 1; }
|
||||||
echo "$Z2K_COMMIT" >"$OUT/z2k/.commit"
|
echo "$Z2K_COMMIT" >"$OUT/z2k/.commit"
|
||||||
echo "2026.10.27+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
|
echo "2026.10.28+z2k.${Z2K_COMMIT:0:7}" >"$OUT/.version"
|
||||||
echo "zapret2-extras $(cat "$OUT/.version") in $OUT"
|
echo "zapret2-extras $(cat "$OUT/.version") in $OUT"
|
||||||
@@ -16,6 +16,7 @@ FXC_IN_CAB=fil6dfaf6bbf56939fbab75b569ffa0fd41
|
|||||||
DLL_IN_CAB=fil0d3f984977487cd87127d614f654195b
|
DLL_IN_CAB=fil0d3f984977487cd87127d614f654195b
|
||||||
|
|
||||||
here=$(dirname "$(realpath "$0")")
|
here=$(dirname "$(realpath "$0")")
|
||||||
|
. "$here/lib.sh"
|
||||||
pkg() { nix build --no-link --print-out-paths --inputs-from "$here/.." "nixpkgs#$1" | head -1; }
|
pkg() { nix build --no-link --print-out-paths --inputs-from "$here/.." "nixpkgs#$1" | head -1; }
|
||||||
verified() {
|
verified() {
|
||||||
[ -f "$CACHE/fxc.exe" ] && [ -f "$CACHE/d3dcompiler_47.dll" ] &&
|
[ -f "$CACHE/fxc.exe" ] && [ -f "$CACHE/d3dcompiler_47.dll" ] &&
|
||||||
@@ -26,8 +27,8 @@ verified() {
|
|||||||
if ! verified; then
|
if ! verified; then
|
||||||
mkdir -p "$CACHE"
|
mkdir -p "$CACHE"
|
||||||
tmp=$(mktemp -d)
|
tmp=$(mktemp -d)
|
||||||
curl -sSfL -o "$tmp/tools.cab" "$CAB_URL"
|
# Retried, and in pieces if the line stalls (a reset failed a release build once).
|
||||||
echo "$CAB_SHA256 $tmp/tools.cab" | sha256sum -c --quiet
|
fetch_pinned "$CAB_URL" "$CAB_SHA256" "$tmp/tools.cab" >&2
|
||||||
(cd "$tmp" && "$(pkg gcab.bin)/bin/gcab" -x tools.cab "$FXC_IN_CAB" "$DLL_IN_CAB")
|
(cd "$tmp" && "$(pkg gcab.bin)/bin/gcab" -x tools.cab "$FXC_IN_CAB" "$DLL_IN_CAB")
|
||||||
mv "$tmp/$FXC_IN_CAB" "$CACHE/fxc.exe"
|
mv "$tmp/$FXC_IN_CAB" "$CACHE/fxc.exe"
|
||||||
mv "$tmp/$DLL_IN_CAB" "$CACHE/d3dcompiler_47.dll"
|
mv "$tmp/$DLL_IN_CAB" "$CACHE/d3dcompiler_47.dll"
|
||||||
|
|||||||
@@ -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), "scroll:X,Y" (ten steps down, there), "wait:SECONDS".
|
# names, e.g. ctrl+a), "scroll:X,Y[,N]" (N steps down, there; ten), "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,7 +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 ;;
|
scroll:*) IFS=, read -r sx sy sn <<<"${step#scroll:}"; x mousemove "$sx" "$sy" click --repeat "${sn:-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:}" ;;
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ fetch_pinned() {
|
|||||||
fi
|
fi
|
||||||
# Whole, unless it stalls: some networks cut TLS to some hosts after about 16 KB (as
|
# 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.
|
# 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
|
if ! curl -fsSL --connect-timeout 30 --speed-limit 1 --speed-time 15 --max-time 900 --retry 3 --retry-all-errors -o "$out" "$url"; then
|
||||||
echo "$url stalled; fetching it in pieces" >&2
|
echo "$url stalled; fetching it in pieces" >&2
|
||||||
local size from=0 step=12000 tries=0
|
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=$(curl -fsSIL --connect-timeout 30 --max-time 60 "$url" | tr -d '\r' | awk 'tolower($1) == "content-length:" { n = $2 } END { print n }')
|
||||||
|
|||||||
@@ -22,11 +22,21 @@ 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-whitelist-bypass.sh "$DIST/components/whitelist-bypass" windows
|
||||||
tools/build-amneziawg.sh "$DIST/components/amneziawg"
|
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
|
||||||
|
|
||||||
echo "== programs"
|
echo "== programs"
|
||||||
|
# The MSVC CRT and Windows SDK, which cargo-xwin fetches from Microsoft's CDN: this line cuts
|
||||||
|
# some of its connections mid-way now and then (a release build failed on it). Fetched first,
|
||||||
|
# again until it takes; what came whole stays in the cache.
|
||||||
|
for try in 1 2 3 4 5 6; do
|
||||||
|
cargo xwin cache xwin && break
|
||||||
|
[ "$try" -lt 6 ] || { echo "the MSVC CRT could not be fetched" >&2; exit 1; }
|
||||||
|
echo "fetching the MSVC CRT again in $((try * 30)) s" >&2
|
||||||
|
sleep $((try * 30))
|
||||||
|
done
|
||||||
cargo xwin build -q --release -p ps-service -p ps-ctl --target x86_64-pc-windows-msvc
|
cargo xwin build -q --release -p ps-service -p ps-ctl --target x86_64-pc-windows-msvc
|
||||||
# The app on its own, so its crates' features do not change the service's (Cargo unifies them
|
# The app on its own, so its crates' features do not change the service's (Cargo unifies them
|
||||||
# within one build). Its shaders are compiled by Microsoft's fxc.exe under Wine.
|
# within one build). Its shaders are compiled by Microsoft's fxc.exe under Wine.
|
||||||
@@ -59,6 +69,9 @@ echo "== THIRD-PARTY.md"
|
|||||||
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, and inside amneziawg's awg-tunnel.exe): 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 "- **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 "- **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"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@
|
|||||||
# whitelist-bypass, the Telegram proxy), the app on a virtual display (tools/gui-shot.sh).
|
# whitelist-bypass, the Telegram proxy), the app on a virtual display (tools/gui-shot.sh).
|
||||||
# In the dev shell, after tools/package.sh:
|
# In the dev shell, after tools/package.sh:
|
||||||
#
|
#
|
||||||
# tools/screenshots.sh [OUT_DIR] (OUT_DIR: docs/screenshots)
|
# [SHOT_LANGUAGE=ru] tools/screenshots.sh [OUT_DIR] (OUT_DIR: docs/screenshots)
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
cd "$(dirname "$0")/.."
|
cd "$(dirname "$0")/.."
|
||||||
OUT=$(realpath -m "${1:-docs/screenshots}")
|
OUT=$(realpath -m "${1:-docs/screenshots}")
|
||||||
@@ -36,12 +36,13 @@ cat >"$STATE/config.json" <<JSON
|
|||||||
"outbounds": [{ "tag": "Netherlands", "url": "$SS_URL#Netherlands" },
|
"outbounds": [{ "tag": "Netherlands", "url": "$SS_URL#Netherlands" },
|
||||||
{ "tag": "Germany", "url": "$SS_URL#Germany" },
|
{ "tag": "Germany", "url": "$SS_URL#Germany" },
|
||||||
{ "tag": "Finland", "url": "$SS_URL#Finland" }] },
|
{ "tag": "Finland", "url": "$SS_URL#Finland" }] },
|
||||||
"zapret": { "enable": true, "engine": "zapret-discord-youtube",
|
"zapret": { "enable": true, "engine": "zapret2",
|
||||||
|
"zapret2": { "strategySource": "z2k", "strategyLog": true, "cutoff": { "enable": false } },
|
||||||
"zapret-discord-youtube": { "configName": "general (ALT9)", "gameFilter": "all" } },
|
"zapret-discord-youtube": { "configName": "general (ALT9)", "gameFilter": "all" } },
|
||||||
"tgWsProxy": { "enable": false },
|
"tgWsProxy": { "enable": false },
|
||||||
"amneziaWg": { "enable": true, "profiles": {
|
"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" },
|
"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": "singBox", "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,
|
"whitelistBypass": { "enable": true,
|
||||||
"joiners": { "wl": { "platform": "wbstream" } },
|
"joiners": { "wl": { "platform": "wbstream" } },
|
||||||
"creators": { "office": { "platform": "bitrix" } } } }
|
"creators": { "office": { "platform": "bitrix" } } } }
|
||||||
@@ -49,6 +50,13 @@ JSON
|
|||||||
release=$(ls -d dist/ProxySuite-*-windows-x64/components 2>/dev/null | tail -1 || true)
|
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
|
[ -n "$release" ] && cp -r "$release/zapret" "$STATE/bin/" 2>/dev/null || true
|
||||||
cargo build -q -p ps-service -p ps-gui
|
cargo build -q -p ps-service -p ps-gui
|
||||||
|
# The app's own preferences for the shots: the light theme (one dark shot below).
|
||||||
|
mkdir -p "$WORK/prefs/light/proxy-suite" "$WORK/prefs/dark/proxy-suite"
|
||||||
|
# SHOT_LANGUAGE: the app's language (en, ru).
|
||||||
|
lang=${SHOT_LANGUAGE:-en}
|
||||||
|
echo "{\"language\":\"$lang\",\"theme\":\"light\",\"checkUpdates\":false}" >"$WORK/prefs/light/proxy-suite/app.json"
|
||||||
|
echo "{\"language\":\"$lang\",\"theme\":\"dark\",\"checkUpdates\":false}" >"$WORK/prefs/dark/proxy-suite/app.json"
|
||||||
|
export XDG_CONFIG_HOME="$WORK/prefs/light"
|
||||||
target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" >"$WORK/service.log" 2>&1 &
|
target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" >"$WORK/service.log" 2>&1 &
|
||||||
SERVICE=$!
|
SERVICE=$!
|
||||||
trap 'kill $SERVICE $SERVER 2>/dev/null || true; rm -rf "$WORK"' EXIT
|
trap 'kill $SERVICE $SERVER 2>/dev/null || true; rm -rf "$WORK"' EXIT
|
||||||
@@ -60,6 +68,8 @@ target/debug/proxy-ctl --socket "$SOCK" proxy outbounds test >/dev/null 2>&1 ||
|
|||||||
shot() {
|
shot() {
|
||||||
local name=$1 y=$2 extra=${3:-}
|
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
|
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"
|
echo "$OUT/$name.png"
|
||||||
}
|
}
|
||||||
shot overview 162
|
shot overview 162
|
||||||
@@ -72,3 +82,4 @@ shot amneziawg 378
|
|||||||
shot logs 414
|
shot logs 414
|
||||||
shot settings 450
|
shot settings 450
|
||||||
shot components 486
|
shot components 486
|
||||||
|
XDG_CONFIG_HOME="$WORK/prefs/dark" shot overview-dark 162
|
||||||
@@ -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 ]
|
||||||