Author SHA1 Message Date
faumarayandClaude Opus 5.5 c36e7038cb windows: the MSVC CRT fetched first in the release build, retried
Windows release / build (push) Successful in 26m41s
Windows release / publish (push) Successful in 1m46s
The 0.3.0-pre.1 build failed on cargo-xwin's download of the MSVC CRT from
Microsoft's CDN (a TLS connection cut mid-way, four times): this line cuts
some of that CDN's connections now and then. package.sh now fetches it with
cargo xwin cache xwin first, up to six times with growing pauses; what came
whole stays cached for the next try.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:41:39 +03:00
faumarayandClaude Opus 5.5 b70085406e windows: server inbounds and Tor's onion service are not to be ported
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:28:04 +03:00
faumarayandClaude Opus 5.5 bd304373e0 windows: the release notes for 0.3.0-pre.1, whole
Windows release / publish (push) Has been cancelled
Windows release / build (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:25:26 +03:00
faumarayandClaude Opus 5.5 29304452f7 windows: the kill switch holds to AmneziaWG tunnels already up when the service starts
From the security review of aa44527: a profile turned on by hand keeps its
tunnel (a Windows service of its own) running across a restart of this
service, but only autostart profiles were wanted on at start: such a
tunnel fell out of the kill switch. Running ones count at start too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:23:39 +03:00
faumarayandClaude Opus 5.5 aa44527082 windows: the kill switch holds to what is wanted on, and says what is in place
From the security review of 32ff264:
- Turning a system-wide AmneziaWG profile off lifted the whole kill switch,
  the TUN's protection too, through a request of the AmneziaWG scope. Now
  the profile only leaves the plan; lifting it all stays killswitch off
  (services scope).
- Which profiles count came from their tunnels' state this moment (one that
  crashed fell out: fail open), and one whose addresses did not read made
  the plan none. Now from intent (started at boot, or turned on), and one
  unread still holds, letting nothing through it.
- holding said what was meant, not what was in place; failed now says
  filters that did not go in.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:21:37 +03:00
faumarayandClaude Opus 5.5 32ff264c81 windows: the kill switch
Upstream's killSwitch, on the Windows Filtering Platform: while the TUN or a
system-wide AmneziaWG profile is on, connections that would leave past it are
blocked at the ALE connect layers, while the tunnel runs, restarts or has
failed. Open: loopback, the private and reserved networks with
allowedSubnets, what leaves from the tunnels' own addresses, the tunnel's own
programs (the backend, its helpers, awg-tunnel; the service with
directFallbacks), NTP with allowTimeSync. Turning a tunnel off, or
proxy-ctl killswitch off / the Overview's Lift, lifts it until a tunnel is
turned on again.

The filters live in a dynamic WFP session of the service's: they go with
it, so stopping the service always gets the network back. Upstream holds
from boot; that needs persistent filters, for once these are seen to work
on real Windows (Wine has no WFP). A changed plan goes in under the other of
two sublayers before the old one goes, so nothing leaks between.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:17:24 +03:00
faumarayandClaude Opus 5.5 ddc1bbe686 windows: fxc's download retried and resumable, as the other pinned downloads
The release build failed on one connection reset fetching the SDK cab that
fxc.exe comes from: fxc-wine.sh now uses lib.sh's fetch_pinned (hash
checked, in pieces when the line stalls), whose whole-file attempt now
retries on any error, a reset included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:07:59 +03:00
faumarayandClaude Opus 5.5 d25e6cbd31 windows: the not-ported test knows the TUN beside zapret is ported
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:06:32 +03:00
faumarayandClaude Opus 5.5 d675fdddb5 windows: the XRay-only backend; zapret beside the TUN
XRay alone (proxy.backend = "xray"), as upstream's xray.nix and its
start-time filter make it: the mixed-in listener with its login, DNS remote
and local ordered by the route mode with the servers' names on local,
IPIfNonMatch routing in upstream's order and modes, zapret's direct lists;
urltest as prefixed tags under a leastPing balancer and observatory, a pin
or first as one exit; chains by dialerProxy; Tor, SSH, WARP, AmneziaWG and
whitelist-bypass as SOCKS hops. What needs sing-box is refused for it, as
upstream asserts (TUN, groups, rule sets, autoProxy, selector/failover,
DoT, dns.strategy and the like). The service checks it with xray run -test
and runs it with its component's geodata (XRAY_LOCATION_ASSET); latency
tests and autoProxy stand aside.

zapret beside the TUN: winws2 gets the TUN's addresses left out in its
--wf-raw-filter (with the cutoff probe's ports); Flowseal's winws, which
takes no ANDed part, gets its own filter as it saves it (--wf-save) with
them left out, through --wf-raw. WinDivert negates single tests only: the
part is spelled positively, and compiled by WinDivert's own parser.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 00:05:21 +03:00
faumarayandClaude Opus 5.5 2dd563ed61 windows: helper programs go direct from the TUN only; the service's fetches too
The rule that sends the helpers' own connections direct (the sidecar,
wireproxy, tg-ws-proxy, Tor, whitelist-bypass, the cutoff probe) now names
the TUN's inbound and is left out without the TUN. sing-box looks a
connection's program up on every inbound once a rule names one, so the
service's fetches through the local listener, sent there to go through the
proxy, went direct once the cutoff probe put the service's program in the
list. Under the TUN the service's direct fetches now always leave directly,
as fetch::Route::Direct means.

README: the updater's verified and unverified parts; the cutoff probe's
port count as measured.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:35:51 +03:00
faumarayandClaude Opus 5.5 e9de863c4b windows: the app in Russian
Every page, the tray's menu and tooltip, and the notifications, as Windows'
display language is (GetUserDefaultUILanguage) or as chosen in Settings >
This app. English stays the key in the code: tr()/trf() (i18n.rs) look it
up in the page's own RU table. What the service says and proxy-ctl stay
English.

Changing the language rebuilds the window on the same page. That needed the
window's handle untyped: gpui-kit's Root holds the view, so the typed handle
was always None, and the tray's Open made a second window rather than
raising the first (fixed too). An AmneziaWG outbound no longer shows its
kind twice. tools/screenshots.sh takes SHOT_LANGUAGE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:28:52 +03:00
faumarayandClaude Opus 5.5 803e18db9d windows: zapret2's 16 KB cutoff probe
Upstream's cutoff.nix and cutoff-probe.template.sh: z2k-detect (built from
z2k's pinned source for Windows, in zapret2-extras) finds the networks this
line cuts after ~16 KB, and with z2k's own strategies a whitelisted name per
network; z2k-tcp16.lua inside winws2 reads the maps (Z2K_TCP16_*, their
digest in the environment so a new map restarts winws2); what no name fixes
goes to the zapret-cutoff rule-set for the proxy (cutoff.proxyFallback).

Upstream keeps zapret2 off the probe with an nft cgroup rule. Here
z2k-detect is patched to dial from a local port range
(Z2K_TCP16_LOCAL_PORTS, 44000-47999, below Windows' dynamic range) and
winws2 gets --wf-raw-filter leaving that range alone; under the TUN the
probe and the service's own lookups of the line's network go direct.

Rounds as upstream's timer: 5 min after start, every 10 min, probing when
the line's network (ipinfo.io and ifconfig.co agreeing) changed or a day
passed. Request::ZapretCutoff, proxy-ctl zapret cutoff [probe], a card on
the DPI page. Verified live on a line that cuts (25 networks, a name for
each), the Windows z2k-detect under Wine, winws2 --dry-run and --wf-save
with the filter. gui-shot's scroll takes a count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:12:43 +03:00
faumarayandClaude Opus 5.5 d33f05c62c windows: the dark theme's off and disabled controls readable; upgrades with tunnels up
Dark theme: a switch that is off has a lighter track (#737373, was #404040
under a near-black thumb), radio buttons, checkboxes and text fields a
lighter edge (#525252); a disabled button's text is the muted colour itself
rather than half of it (widgets::Inactive). The title bar is set again a
moment after Windows' appearance changes, as GPUI resets it to Windows' own.

Upgrades: a running system-wide AmneziaWG tunnel is stopped while the
release's newer amneziawg replaces bin\amneziawg, and started again;
WinDivert's driver is let go of before zapret or zapret2 is replaced. The
fetched setup program goes once the update it brought is running.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 22:39:10 +03:00
faumarayandClaude Opus 5.5 5bd47f7676 windows: updates from the app, and a dark theme
The service looks at the project's releases (windows-v* tags; pre-releases
for a pre-release), fetches the newer setup program, checks its SHA-256
against the one published beside it, and runs it silently, detached, out of
any job: the setup stops the service, replaces it, and starts it again.
Run by the service (session 0), the setup's install starts the app in each
signed-in user's session with their token rather than through Explorer. A
failed copy during an upgrade starts the old service and app again.
Request::UpdateCheck (anyone), UpdateInstall (services scope);
proxy-ctl update [check|install]; the app's Overview card.

The app's own preferences (%APPDATA%\ProxySuite\app.json): the theme
(light, dark, or as Windows, followed as it changes; the title bar too) and
whether to look for updates at start and daily. Settings > This app, and a
sun/moon toggle in the sidebar.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 22:21:27 +03:00
faumarayandClaude Opus 5.5 ed9275250b windows: 0.3.0-pre.1 begun; what works on real Windows so far
The setup program, zapret, zapret2 and tg-ws-proxy, as tried on a real PC.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 22:02:53 +03:00
faumarayandClaude Opus 5.5 fe291fab2b windows: component archives download on a slow line
Windows release / build (push) Successful in 1h9m39s
Windows release / publish (push) Successful in 50s
A component's archive (sing-box's is 15 MB) had a minute for the
whole transfer, which a slow line misses (CI run #9 timed out on it).
Now a minute without a byte fails it, the whole has no limit, and a
transfer cut short is taken up where it stopped (an HTTP range), eight
times at most; the pinned hash checks the result as before.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 13:01:10 +03:00
faumarayandClaude Opus 5.5 2c4cdee7d3 windows: AmneziaWG outbounds, and WARP through wireproxy
- ps_core::awg: upstream's scripts/amneziawg_config.py, ported: a profile
  from a .conf, an AmneziaVPN vpn:// link (qCompress'd JSON or the compact
  .conf form, containers and DNS placeholders as upstream reads them) or
  declarative settings (with obfuscationFile's secrets); AWG 3's MTU
  default, the endpoint override, upstream's checks (no wg-quick hooks
  unless allowed, no control characters, one [Interface]); and the
  wireproxy configuration. Checked against links made by upstream's own
  encoder, output byte for byte.
- wireproxy-awg for Windows, built from upstream's tag (pinned to its
  commit) with upstream's patches, by tools/build-wireproxy-awg.sh; in
  the release as a bundled component. Go joins the dev shell.
- The service runs one per "userspace" AmneziaWG outbound and WARP
  device, on its loopback port with the hop login, its configuration
  below the protected state root; "singBox" profiles reach the renderer.
  wireproxy goes direct under the TUN.
- End to end on Linux (an_amneziawg_tunnel): sing-box as the WireGuard
  server, the service's wireproxy as the client; a page through its
  listener and through the proxy's outbound, named inside the tunnel.
- What is still to come and said: AmneziaWG as a system-wide VPN.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 12:32:43 +03:00
faumarayandClaude Opus 5.5 62adadc207 windows: WARP as a sing-box outbound
- Devices registered as wgcf registers them: an X25519 key made by the
  service, its public half posted to Cloudflare's client API (through the
  local proxy first, as upstream, then directly, then warp.generatorUrl),
  the answer made into wgcf's profile and kept below the protected state
  root; or a profile given (config, configFile). The renderer's endpoint
  for it was there; the service now supplies the profiles.
- Registration runs outside the service's lock, at start, after a change,
  and every ten minutes until it succeeds; the proxy is applied again
  with the new device.
- Checked: a device registered live with Cloudflare, its profile rendered
  as a sing-box WireGuard endpoint and the proxy running with it.
  WARP through AmneziaWG (userspace, interface) is still to come, and said.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:13:29 +03:00
faumarayandClaude Opus 5.5 d9d52c49b6 windows: no unquoted value can add a directive to Tor's torrc
proxy.listener.address went into the torrc unquoted (Socks5Proxy, with
upstream = "proxy"): a newline in it, set by a user who may change the
configuration, would add a directive, ClientTransportPlugin among them,
which runs a program as SYSTEM (found by the commit security review).
The address is written from its parsed IpAddr now; a bridge line with a
control character in it is refused; and the validator holds every
listen address (the proxy's, the SSH tunnel's, tg-ws-proxy's) to an IP
address, which they all are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:06:42 +03:00
faumarayandClaude Opus 5.5 ed2159f7b6 windows: the not-ported test names WARP, now that Tor is there
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:03:09 +03:00
faumarayandClaude Opus 5.5 40221e7981 windows: Tor
- tor: the Tor Project's Expert Bundle for Windows (15.0.26) as a
  component, pinned by the hash of the release whose signature was
  checked against the Tor Browser Developers' key; the installer takes
  gzipped tars now (plain files only: a link could point anywhere).
- The torrc upstream's tor.nix writes: SOCKS for the tor outbound,
  bridges with the bundle's lyrebird (obfs4, webtunnel, meek, snowflake)
  and conjure, the local proxy as upstream (upstream = "proxy") with its
  login, extraConfig. The control port is on loopback with cookie
  authentication (upstream's is a Unix socket only Tor's user opens).
  Values are quoted with control characters escaped: a newline in, say,
  the proxy's login would otherwise start a directive (one that runs a
  program, as SYSTEM).
- Tor's own connections go direct under the TUN unless upstream =
  "proxy". The onion service (for the inbounds) is still to come and is
  said to be.
- Checked: Windows' tor.exe, under Wine, takes a torrc of this shape,
  bridges and escaped values included; on Linux the service runs Tor and
  it bootstraps as far as this network lets it without bridges.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:02:24 +03:00
faumarayandClaude Opus 5.5 82fe4d8e65 windows: the SSH tunnel's host and user cannot be read as ssh options
sshProxy.server.host and .user are ordinary settings the signed-in user
may change, and they reached ssh.exe's command line, which the service
runs as SYSTEM: a host of -oProxyCommand=<program> would have run that
program as SYSTEM (found by the commit security review). The user now
goes as -l's value and the host after "--", so neither can be an
option; the validator holds the host to a host name or IP address, the
user to a login name, and host keys to one line each.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:41:39 +03:00
faumarayandClaude Opus 5.5 fb6c5962d0 windows: zapret's hostlistRules, and the SSH tunnel
- hostlistRules (zapret-discord-youtube): a group of sites with its own
  strategy, as upstream's patch-zapret-config.py makes them: the
  preset's profiles for the rule's family (or another preset's, with
  configName; Discord's voice profile with it), pointed at the rule's own
  list with the standard excludes, or the rule's nfqwsArgs; ahead of the
  preset's own. WinDivert's filter takes the ports they add. Rules with
  enableDirectSync join the direct list. Names of zapret's own lists, and
  the instagram/soundcloud/twitter families (not in Flowseal's Windows
  release), are refused. Every preset with sample rules checked by
  winws.exe --dry-run (tools/winws-dry-run.sh); one without the profile
  a rule copies is refused, as upstream refuses it.
- The SSH tunnel (sshProxy): Windows' own OpenSSH (System32) as ssh -N -D,
  with upstream's options and only the configured key offered
  (IdentitiesOnly: an agent's keys used up the server's tries); the key
  copied below the protected state root, as Windows' OpenSSH wants it and
  sing-box's SSH outbound reads it; the server's keys from hostKey,
  hostKeyFile or knownHostsFile. End to end on Linux against an sshd of
  the test's own: a page through each, two logins with the copied key.
- The dev shell has OpenSSH, for that test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:37:29 +03:00
faumarayandClaude Opus 5.5 88c8b88a49 windows: what is not on Windows yet is said, for as long as it holds
The configuration accepted the kill switch, AmneziaWG, WARP, Tor, the SSH
tunnel, whitelist-bypass, serving inbounds, autoProxy, the xray backend,
zapret's hostlistRules, z2k and zapret2's extended detection, and the
service silently did nothing with them: a kill switch turned on looked
like protection that was not there. The validator now warns for each, and
for TUN with zapret together; the status carries the configuration's
warnings as well as the rendering's, so the app's overview and
proxy-ctl status show them until they no longer hold.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 07:08:14 +03:00
faumarayandClaude Opus 5.5 c0b089dea8 windows: the app leaves a system proxy set by hand alone; a calmer tray
- The check for a system proxy a killed app left on the local proxy ran
  on every refresh while the option was off, so a proxy the user pointed
  at the listener by hand was switched off within two seconds. It now
  runs once, at the start. The registry sits behind a small trait, and
  the state machine has tests.
- The tray's tooltip and menu are only touched when what they say
  changes (a menu rebuilt while open would close).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:24:01 +03:00
faumarayandClaude Opus 5.5 adcd734479 windows: 0.2.0-pre.1: the app in the release, README
- package.sh builds the app (on its own, so its crates' features leave
  the service's build as it was) and puts proxy-suite.exe in the zip;
  THIRD-PARTY.md names GPUI, GPUI Kit and Lucide.
- README: the app, what has been verified of it and how (every page on
  Linux, headless; the Windows build; not drawn on Windows yet), install
  and first run with it, the system proxy, building and trying it.
- Release notes for 0.2.0-pre.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:17:49 +03:00
faumarayandClaude Opus 5.5 6ed7a3b1c6 windows: install puts the app in the Start Menu and starts it at sign-in
- install copies proxy-suite.exe with the rest, closes running copies
  before replacing files, makes an all-users Start Menu shortcut, starts
  the app at every sign-in in the tray (HKLM Run, --hidden), and starts it
  now as the signed-in user (through Explorer, not elevated).
- uninstall closes it, removes the shortcut and the sign-in start, and
  turns off the user's system proxy if the app left it on the local
  proxy (another proxy of theirs is left alone).
- The app does not take its own left-over system proxy for the user's.
- Lints: the last of clippy's, in the app, the service and a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:12:02 +03:00
faumarayandClaude Opus 5.5 757bebbb1d windows: clippy's suggestions in the service and client (collapsible ifs, next_back)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:08:25 +03:00
faumarayandClaude Opus 5.5 7565e62571 windows: the app sets the system proxy; ps-core lint fixes
- The app points the signed-in user's system proxy (WinINet: browsers
  and most programs follow it) at the local proxy while it runs and
  proxy.systemProxy.enable asks; the user's own settings are kept and put
  back when the proxy stops, the service goes, the option is turned off
  or the app quits; one left behind by a killed app is cleared. A switch
  for it on the overview. Elsewhere than Windows it does nothing.
- ps-core: clippy's collapsible ifs, comparisons without owned values, a
  range loop without indexing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:07:02 +03:00
faumarayandClaude Opus 5.5 77becc235c windows: the app's tray, and its Windows build from Linux
- Tray (gpui-tray): a shield coloured by how things are (working, one
  failed, all off, no service), its tooltip saying which; the menu opens
  the window and switches the local proxy, the DPI bypass and the Telegram
  proxy, with their states checked; Quit. Closing the window leaves the
  app in the tray (no tray: it quits); --hidden starts it there.
- The app builds for Windows from Linux: GPUI compiles its HLSL shaders
  with fxc.exe only when the building machine is Windows, so its Windows
  backend is vendored with that one check made on the target instead
  (vendor/gpui-pre-windows/PATCHED.md, tools/vendor-gpui-windows.py), and
  tools/fxc-wine.sh runs Microsoft's fxc.exe under Wine: the compiler from
  the Windows SDK 10.0.26100 installer, pinned by hash, kept on the build
  machine; only the compiled shaders go into the app.
- gui-shot.sh keeps the app off the desktop's session bus.

Under Wine the app starts but cannot draw text (Wine's DirectWrite does
not implement font-set matching), so its Windows rendering is untested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 02:03:18 +03:00
faumarayandClaude Opus 5.5 a7bf347859 windows: the app's Components page; the connection in the sidebar
- Components: each program's pinned version, the one installed (or
  missing), its license and source; fetching them all again, which the
  service allows administrators only, with each failure named.
- The sidebar's foot says whether the service is reachable, and
  "Applying…" while a change is under way; when it is not running, the
  overview says how to start it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:46:58 +03:00
faumarayandClaude Opus 5.5 69759cfbce windows: the app's Settings page: the whole configuration
Upstream's option tree as JSON in a code editor (highlighted, folding),
loaded with its revision; Check asks the service to validate without
taking it; Save sends it against the revision loaded, so a change made
elsewhere meanwhile is refused, not overwritten, and the page says so.
The validator's notes and an apply failure are shown under the editor;
redacted secrets are explained (left as they are, they keep their
values). Every option the other pages do not show is editable here.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:44:55 +03:00
faumarayandClaude Opus 5.5 23c1687118 windows: the app's Logs page; on Linux, units end with the service
- Logs: every unit's as they come (the last 500 first, 5000 kept), one
  unit's on its own, following or held; terminal colours stripped; a
  virtual list, so thousands of lines cost nothing. The follow starts
  when the page is first opened and reconnects by itself.
- Linux (development, tests): the service's children get SIGKILL when it
  dies (PR_SET_PDEATHSIG), as the Job Object does on Windows; a killed
  service no longer leaves sing-box running (the e2e test leaked one per
  run).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:41:12 +03:00
faumarayandClaude Opus 5.5 a839d48e02 windows: the app's Outbounds page
Adding an outbound from a share link or a backend's JSON (checked here
first, by the same parser as proxy-ctl; tagged from the link unless
named); the list with each one's source, backend and detour, pinned or
left out, its delay on request, and remove for the user's own; the
routing mode; subscriptions added, updated and removed.

dev-service.sh: the demo server resolves names over HTTPS (sing-box needs
a resolver for its direct outbound, and plain DNS may be blocked).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:37:02 +03:00
faumarayandClaude Opus 5.5 7dfb3129f4 windows: the app's Telegram proxy page
tg-ws-proxy on or off and its state; its tg:// links, to copy or open in
Telegram (none without the secrets scope, and the page says so); whether
other devices may connect; its port and fake-TLS domain (which adds the
ee link). Long links are cut short rather than widening the page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:33:10 +03:00
faumarayandClaude Opus 5.5 c9ce7a1982 windows: the app's DPI bypass page
zapret on or off and its engine; for Flowseal's presets, the preset (the
release's own list, matched as the service matches names) and game
traffic; for zapret2, learning, IPv6 and the strategy log; the sites to
handle besides the engine's lists and the sites to leave alone; TCP
timestamps. News from the service replaces what the user has not
changed, never what they are typing; a save shows the list as saved.

ps-client: set_path for any one option, set_zapret_sites (tidied,
deduplicated). gui-shot.sh takes ordered steps: click, type, key, wait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:30:25 +03:00
faumarayandClaude Opus 5.5 d3ba00087d windows: the app's skeleton: the service from GPUI, an overview
- bridge: ps-client on a tokio runtime of its own, awaited from GPUI's
  executor; log following as a channel that reconnects.
- model: status polled every 2 s (outbounds every fifth round and on a
  reconnect), the zapret presets and tg links on connecting, and changes
  sent through ps-client's edits; what came of each is a notification,
  the service's own words when it refuses or cannot apply.
- The window: a sidebar of pages; the overview shows the local proxy, the
  DPI bypass and the Telegram proxy with their states and switches, and
  what the service warns of. The other pages come next.
- Icons: the components' own and the few the app adds, not all of Lucide.
- zapret's engines by upstream's names (zapret-discord-youtube, zapret2).
- gui-shot.sh can click before the shot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:25:11 +03:00
faumarayandClaude Opus 5.5 63aede0dc1 windows: the service names zapret's presets and tg-ws-proxy's links
- zapret-presets: the presets of the installed zapret release and the one
  configured; proxy-ctl zapret presets.
- tg-links: tg-ws-proxy's tg:// links (dd, and ee with a fake-TLS
  domain), as it prints them; they carry its secret, so the secrets scope.
  proxy-ctl tg link. No more reading them out of its log.
- tools/dev-service.sh: the service on Linux with a demo outbound, for
  working on the app.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 01:18:59 +03:00
faumarayandClaude Opus 5.5 4ae30dac3c windows: ps-client shared by proxy-ctl and the app; the app's first window
- ps-client: the service's client side, moved out of proxy-ctl: calls,
  configuration edits against the revision read (retried on a concurrent
  change), log following, and the edits themselves as functions on the
  configuration (outbounds, subscriptions, rules, zapret, tg-ws-proxy),
  now unit-tested. proxy-ctl does what it did, through it; a refused log
  follow is now an error instead of nothing.
- ps-gui: proxy-suite, the desktop app on GPUI (gpui-kit 0.8.1); only a
  first window yet. Not in default-members: plain cargo build/test and the
  release workflow's tests leave GPUI out.
- tools/gui-shot.sh: runs the app on Xvfb with Mesa's software Vulkan and
  screenshots it, to check the GUI on Linux without a display.

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

No files matched your search

+21 -6
View File
@@ -1,8 +1,8 @@
name: Windows release
# The Windows port (windows/). On a tag windows-v<version> it builds the release zip and
# publishes it as a Gitea release, with the notes in windows/release-notes/<version>.md. Run
# by hand, it only builds: the zip is the run's artifact.
# The Windows port (windows/). On a tag windows-v<version> it builds the setup program and the
# release zip and publishes them as a Gitea release, with the notes in
# windows/release-notes/<version>.md. Run by hand, it only builds: they are the run's artifact.
#
# Two jobs, as upstream's dependency updates: the one that runs fetched code (crates,
# components, wheels, the Nix closure) holds no token that can write. Only the publishing job
@@ -75,9 +75,22 @@ jobs:
working-directory: windows
run: nix develop --command rustup toolchain install
# The SSH tunnel's end-to-end test runs an sshd of its own. As root (the job's user in the
# runner's container) sshd separates privileges: it needs its empty, root-owned directory
# and its unprivileged user, which the image does not have.
- name: Test prerequisites
run: |
set -euo pipefail
if [ "$(id -u)" = 0 ]; then
install -d -m 0755 -o root -g root /var/empty
id sshd >/dev/null 2>&1 || useradd --system --no-create-home --home-dir /var/empty --shell /usr/sbin/nologin sshd
fi
# The default members: the service, proxy-ctl, the client and core (the app's crate is
# built by Package).
- name: Test
working-directory: windows
run: nix develop --command cargo test --workspace --locked
run: nix develop --command cargo test --locked
- name: Package
working-directory: windows
@@ -89,7 +102,9 @@ jobs:
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
mkdir -p ../release
cp "dist/ProxySuite-$version-windows-x64.zip" "dist/ProxySuite-$version-windows-x64.zip.sha256" ../release/
for f in "ProxySuite-$version-windows-x64-setup.exe" "ProxySuite-$version-windows-x64.zip"; do
cp "dist/$f" "dist/$f.sha256" ../release/
done
if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi
- name: Upload
@@ -149,7 +164,7 @@ jobs:
*) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;;
esac
for f in release/*.zip release/*.sha256; do
for f in release/*.exe release/*.zip release/*.sha256; do
name=$(basename "$f")
for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
api -X DELETE "$API/releases/$id/assets/$old" >/dev/null
+15
View File
@@ -0,0 +1,15 @@
# The Windows programs carry their C runtime: vcruntime140.dll is not on every Windows (the
# Visual C++ Redistributable brings it), and nothing else should have to be installed first.
# (LNK4099: the static runtime's objects name Microsoft's own PDBs, which are not shipped; it
# is about their debug info only.)
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=/ignore:4099"]
# GPUI's build compiles its manifest with embed-resource, which would take the dev shell's RC
# (MinGW's windres, for the C cross-compiler) and make a COFF object of it; with llvm-rc it makes
# a .res, which the linker merges with the app's icon (crates/ps-gui/build.rs). Two resource
# objects it refuses. (A target/ from before this keeps GPUI's object: cargo clean -p gpui-pre.)
# Building on Windows without llvm-rc: set RC_x86_64_pc_windows_msvc=rc.exe in the environment,
# which this does not override.
[env]
RC_x86_64_pc_windows_msvc = "llvm-rc"
+2
View File
@@ -1,2 +1,4 @@
target/
dist/
# The app logs tools/gui-shot.sh writes beside each shot.
docs/screenshots/*.log
+7110 -49
View File
File diff suppressed because it is too large. Load diff
+11 -2
View File
@@ -1,9 +1,11 @@
[workspace]
resolver = "2"
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-ctl"]
members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl", "crates/ps-gui"]
# The app (GPUI) builds only when asked for: `-p ps-gui` or `--workspace`.
default-members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-client", "crates/ps-ctl"]
[workspace.package]
version = "0.1.0-pre.2"
version = "0.3.0-pre.1"
edition = "2024"
license = "MIT"
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
@@ -20,6 +22,7 @@ ipnet = "2"
indexmap = { version = "2", features = ["serde"] }
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
clap = { version = "4.6", features = ["derive"] }
rpassword = "7"
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
windows-service = "0.8"
@@ -31,8 +34,14 @@ sha2 = "0.10"
zip = { version = "2", default-features = false, features = ["deflate"] }
ps-core = { path = "crates/ps-core" }
ps-ipc = { path = "crates/ps-ipc" }
ps-client = { path = "crates/ps-client" }
[profile.release]
lto = "thin"
strip = true
codegen-units = 4
# GPUI's Windows backend, its shader build patched to work when cross-compiling
# (vendor/gpui-pre-windows/PATCHED.md, tools/vendor-gpui-windows.py).
[patch.crates-io]
gpui-pre-windows = { path = "vendor/gpui-pre-windows" }
+138 -33
View File
@@ -2,12 +2,14 @@
A native Windows port of [proxy-suite-flake](https://github.com/FUFSoB/proxy-suite-flake): the
same configuration (upstream's `services.proxy-suite` options, same names and defaults), run
by a Windows service instead of NixOS and systemd, controlled with `proxy-ctl` as upstream's is.
by a Windows service instead of NixOS and systemd, controlled from its desktop app (window and
tray icon) or with `proxy-ctl`, as upstream's is.
> [!WARNING]
> **Pre-release.** Built and tested on Linux and under Wine, **never yet run on real Windows.**
> Read [what has been verified](#what-has-been-verified) before relying on it, and please
> report what happens on yours.
> **Pre-release.** Built and tested on Linux and under Wine; on real Windows so far only the
> setup program, zapret, zapret2 and tg-ws-proxy have been tried (they work). Read
> [what has been verified](#what-has-been-verified) before relying on it, and please report
> what happens on yours.
> [!IMPORTANT]
> For study and research only, as upstream: learning how proxies, tunnels and traffic
@@ -17,43 +19,104 @@ by a Windows service instead of NixOS and systemd, controlled with `proxy-ctl` a
| | |
|---|---|
| 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** |
| 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 |
| 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 |
| 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 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 |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
| 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 |
| WARP | `warp` with `asOutbound = "singBox"` or `"userspace"`: each device registered with Cloudflare as wgcf registers (through the local proxy first, then directly, then `generatorUrl`), or a profile given; a sing-box WireGuard endpoint, several grouped as `warp` |
| autoProxy | `proxy.autoProxy`: the sites apps reach directly are probed through each exit in turn (direct first); one blocked directly but reached through an exit is routed through it, as upstream's prober decides (block pages, one exit per network first, strikes against exits that refuse). Blocks zapret can fix stay direct. A site that crawls directly (`slowBelowKiBps`) moves to the first exit that carries it as well as direct does. Its page in the app, or `proxy-ctl proxy auto`, shows, probes, learns and forgets |
| whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins |
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on`, alongside zapret too — **see the caveats** |
| 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: the desktop app (GPUI, with a tray icon), AmneziaWG,
WARP, Tor, the SSH tunnel, whitelist-bypass, the kill switch, server inbounds, the XRay-only
backend, zapret2's extended detection and z2k strategies.
Not ported: server inbounds (this PC serving other devices) and Tor's onion service, which
serves them. 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.
Needs 64-bit Windows 10 (1903 or later) or 11.
## Screenshots
Taken on Linux against the service with a demo configuration (`tools/screenshots.sh`), so the
DPI bypass, which runs on Windows only, shows as inactive.
| | |
|---|---|
| ![Overview](docs/screenshots/overview.png) | ![DPI bypass](docs/screenshots/dpi-bypass.png) |
| ![Outbounds](docs/screenshots/outbounds.png) | ![autoProxy](docs/screenshots/autoproxy.png) |
| ![AmneziaWG](docs/screenshots/amneziawg.png) | ![Whitelist bypass](docs/screenshots/whitelist-bypass.png) |
| ![Telegram proxy](docs/screenshots/telegram.png) | ![Settings](docs/screenshots/settings.png) |
| ![Overview, dark](docs/screenshots/overview-dark.png) | ![Logs](docs/screenshots/logs.png) |
| ![Overview, in Russian](docs/screenshots/overview-ru.png) | ![Components](docs/screenshots/components.png) |
## What has been verified
| 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 |
| 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 |
| 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`) |
| 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 |
| 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) |
| AmneziaWG | profiles from `.conf`, `vpn://` links and settings converted exactly as upstream's script converts them (its own encoder's links as test vectors); end to end on Linux: sing-box as a WireGuard server, the service running wireproxy-awg, a page through its listener and through the proxy's outbound (`an_amneziawg_tunnel`) |
| autoProxy | its judgement (upstream's verdicts, walk, exit order, strikes, state) by unit tests; the config with its probe listeners and learned rule-sets accepted by `sing-box check`; on Linux with a local exit: probes through direct and the exit, a learn request, a site an app reached directly queued from the Clash API and probed at the next run, the state and the rule-set files written; a download held to 40 KiB/s seen crawling and moved to the exit. A site blocked here and reached through an exit needs a remote exit, so none was routed that way |
| whitelist-bypass | its Windows programs built from upstream's tag with upstream's patches (links and passwords from the environment, never the command line); on Linux the service runs a joiner and a creator with their flags, the link and the login reaching them (`proxy-ctl wl join`, `wl auth`, `wl new`, `wl link`); a real call needs an account on a platform, so none was made |
| AmneziaWG system-wide | under Wine's service manager (`tools/wine-setup-test.sh`): a profile added registers its tunnel service (program, configuration, dependencies), `proxy-ctl awg on` starts it, and the tunnel runs as a service up to creating the Wintun adapter, which Wine cannot; its log is read back; the service goes with its profile. Traffic through it needs real Windows |
| WARP | a device registered live with Cloudflare by the service, its profile rendered as a sing-box endpoint and accepted; traffic through it not (this test machine blocks outgoing UDP) |
| zapret's hostlist rules | every preset with sample rules, checked by `winws.exe --dry-run` (a preset without the profile a rule copies is refused, as upstream refuses it) |
| The app | every page against the service running on Linux, in a window on a virtual display (Xvfb, Mesa's software Vulkan), clicked and typed into by a script, screenshots looked at, and the service's configuration checked after each change (`tools/gui-shot.sh`) |
| The setup program | under Wine (`tools/wine-setup-test.sh`): a silent install puts every file of the release into Program Files and the entry into Settings → Apps, the service runs and answers; the same setup again over the running install upgrades it; the entry's uninstall removes the service, the files and the entry. Its pages (and the Russian ones) not looked at |
| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; its icon and manifest in its resources, no C runtime DLL among its imports; under Wine it starts and gets as far as drawing text |
**Not verified: anything that needs real Windows.** Traffic through sing-box on Windows (Wine
lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows
service under the Service Control Manager, `install`/`uninstall`, the system PATH change.
**Not verified yet: the rest of what needs real Windows.** Traffic through sing-box on Windows
(Wine lacks an API it needs), the TUN adapter, AmneziaWG's system-wide tunnels, autoProxy,
whitelist-bypass, the SSH tunnel, Tor and WARP there, uninstalling, and the app's pages beyond
what the zapret and Telegram ones need, its tray icon, the system proxy and the Start Menu entry.
## Install
1. Unzip `ProxySuite-<version>-windows-x64.zip` anywhere.
2. Run `install.cmd` (it asks for administrator rights). It copies the program to
`C:\Program Files\ProxySuite`, registers the **ProxySuite** service (starts at boot), adds
`proxy-ctl` to PATH and starts it.
3. Open a **new** terminal: `proxy-ctl status`.
1. Download `ProxySuite-<version>-windows-x64-setup.exe` and run it. It asks for
administrator rights; SmartScreen may warn of an unknown publisher (the programs are not
signed yet): **More info** → **Run anyway**.
2. It installs everything into `C:\Program Files\ProxySuite`, registers the **ProxySuite**
service (starts at boot), adds `proxy-ctl` to PATH, starts it, and opens the app; the app
starts at every sign-in, in the tray (its shield is green while things work, amber when one
failed, grey when all is off). One option, unchecked: Windows' **OpenSSH Client**, for the
SSH tunnel only, where it was removed from Windows (Windows 10 1809 and later have it).
3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal:
`proxy-ctl status`.
To upgrade, unzip the new release and run its `install.cmd`. To remove, run `uninstall.cmd`;
the configuration and state stay in `%ProgramData%\ProxySuite` until you delete it.
Nothing has to be installed first: the C runtime is linked into the programs, and WinDivert,
wintun, Python, Tor and the rest come with it, as components. For a silent install:
`ProxySuite-<version>-windows-x64-setup.exe /S`.
To upgrade, run the new setup, 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
`%ProgramData%\ProxySuite` until you delete it.
Without the setup program: unzip `ProxySuite-<version>-windows-x64.zip` anywhere and run
`install.cmd` (it asks for administrator rights): the same install, from the same files.
Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a
packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first:
@@ -62,6 +125,10 @@ service refuses to start zapret while one runs, and says which.
## First run
In the app: **Outbounds** → paste a link → **Add**, then switch the local proxy on in the
**Overview** (and, if wanted, *Use it as the system proxy*). **DPI bypass** switches zapret on
and picks its preset; **Telegram proxy** gives the link to open in Telegram. Or from a terminal:
```powershell
# A proxy:
proxy-ctl proxy outbounds add "vless://...#My Server"
@@ -80,18 +147,38 @@ proxy-ctl zapret game-filter all
# zapret2 instead:
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
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:
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
proxy-ctl config set config.json
proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret
# whitelist-bypass: a joiner here (set "whitelistBypass": { "enable": true,
# "joiners": { "wl": { "platform": "wbstream" } } }), its creator's link from the other end:
proxy-ctl wl join wl "https://..."
proxy-ctl proxy pin wl
# A creator: its login (a cookies export; DION and Bitrix ask for an email and password), its call:
proxy-ctl wl auth laptop cookies.json
proxy-ctl wl link laptop
# AmneziaWG as a system-wide VPN (a profile without asOutbound):
proxy-ctl awg # profiles and their state
proxy-ctl awg on home # start it; off stops it
proxy-ctl awg log home # its tunnel's log
# autoProxy (set "proxy": { "autoProxy": { "enable": true } }):
proxy-ctl proxy auto # what it routed, and where
proxy-ctl proxy auto probe example.com # how a site answers through each exit
proxy-ctl proxy auto learn example.com # probe it now, route it if it needs it
proxy-ctl logs -f # everything, following
proxy-ctl --help
```
## The configuration
The app's **Settings** page edits it whole, and checks it with the service before saving.
`proxy-ctl config get` prints it, `proxy-ctl config set <file>` replaces it (checked first; a
bad one changes nothing), `proxy-ctl config validate <file>` only checks. It is upstream's
option tree as JSON, so [upstream's option reference](../docs/options/index.md) describes it:
@@ -99,7 +186,7 @@ option tree as JSON, so [upstream's option reference](../docs/options/index.md)
Options that only mean something on Linux (TProxy, fwmarks, routing tables, packages) are not
there; the Windows-only ones are documented in `crates/ps-core/src/config/`:
- `proxy.singBox.testPort`; `proxy.systemProxy` (applied by the desktop app, which is not in this release)
- `proxy.singBox.testPort`; `proxy.systemProxy` (applied by the app, for the signed-in user)
- `proxy.routing.rules.*.processNames` / `processPaths` (and `name`, `priority`, `disabled`)
- `perAppRouting.profiles.*`: programs held to an outbound, by name or path
- `zapret.tcpTimestamps`, `geodata` as download locations, `tor.controlPort`
@@ -116,16 +203,19 @@ 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
`*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`,
`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.
## Caveats
- **TUN and zapret together**: upstream keeps zapret's packets off the TUN interface, which
this release does not do yet. Use one or the other.
- zapret2 learns with nfqws2's own detector, not upstream's extended one; z2k's strategies are
not there yet.
- **TUN and zapret together**: zapret (winws or winws2) leaves the TUN's own packets alone,
by its address in WinDivert's filter, and handles the connections sing-box makes on the way
out of the real adapter, direct ones included. Checked by WinDivert's own filter compiler;
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 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.
## Components
@@ -140,16 +230,31 @@ See [`THIRD-PARTY.md`](THIRD-PARTY.md) for their licenses and sources.
On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`), then
```sh
cargo test --workspace # everything, sing-box and xray from the shell
cargo test # everything but the app; sing-box and xray from the shell
python3 -I tools/parity/links.py # link parsing against upstream's Python
tools/package.sh # the release zip, in dist/
tools/package.sh # the setup program and the zip, in dist/
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-*-setup.exe dist/ProxySuite-*-x64
```
The Windows programs are cross-compiled with `cargo xwin` (MSVC target), with the toolchain
in `rust-toolchain.toml`. Design notes: [`DESIGN.md`](DESIGN.md).
The app on Linux, against the service on Linux:
```sh
tools/dev-service.sh # the service, a demo outbound; leave it running
cargo run -p ps-gui -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock"
tools/gui-shot.sh shot.png 8 -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock" # headless
```
Its Windows build compiles GPUI's shaders with Microsoft's `fxc.exe` under Wine
(`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build
machine), through a small patch to GPUI's Windows backend (`vendor/gpui-pre-windows`).
The Windows programs are cross-compiled with `cargo xwin` (MSVC target, the C runtime linked
in: `.cargo/config.toml`), with the toolchain in `rust-toolchain.toml`. The setup program is
NSIS's (`tools/installer.nsi`, `makensis` from the shell): it unpacks the release and runs its
`proxy-suite-service.exe install`, as `install.cmd` does. Design notes: [`DESIGN.md`](DESIGN.md).
Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version`
in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The
workflow tests, packages and publishes the zip and its `.sha256` with the `RELEASE_TOKEN`
workflow tests, packages and publishes the setup program and the zip, each with its `.sha256`, with the `RELEASE_TOKEN`
secret (a token with `write:repository`). Run by hand, it only builds.
+48
View File
@@ -98,6 +98,54 @@
"homepage": "https://github.com/Flowseal/tg-ws-proxy",
"bundled": true,
"sources": []
},
"tor": {
"version": "15.0.26",
"license": "BSD-3-Clause",
"homepage": "https://www.torproject.org",
"sources": [
{
"url": "https://dist.torproject.org/torbrowser/15.0.26/tor-expert-bundle-windows-x86_64-15.0.26.tar.gz",
"sha256": "c1988c701de2f24f7d098d1d6d7f507b58f27740d097f29c246e0524d639b252",
"include": [
"tor/",
"data/geoip",
"data/geoip6",
"docs/"
],
"exclude": [
"tor/tor-gencert.exe"
]
}
]
},
"wireproxy-awg": {
"version": "1.0.18",
"license": "ISC",
"homepage": "https://github.com/artem-russkikh/wireproxy-awg",
"bundled": true,
"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": {
"version": "0-unstable-2026-08-14+e90531d",
"license": "MIT",
"homepage": "https://github.com/amnezia-vpn/amneziawg-windows",
"bundled": true,
"sources": []
},
"whitelist-bypass": {
"version": "0.4.4",
"license": "MIT",
"homepage": "https://github.com/kulikov0/whitelist-bypass",
"bundled": true,
"sources": []
}
}
}
+15
View File
@@ -0,0 +1,15 @@
[package]
name = "ps-client"
description = "Proxy Suite for Windows: the service's client side, for proxy-ctl and the app"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde_json.workspace = true
[dev-dependencies]
tokio.workspace = true
+419
View File
@@ -0,0 +1,419 @@
//! The configuration edits proxy-ctl and the app make, on the configuration as JSON (what
//! `config-get` returns). Each can be made again on a newer configuration, which
//! [`Client::edit`](crate::Client::edit) does when another change came first.
use anyhow::{Result, anyhow, bail};
use serde_json::{Value, json};
/// The list at `path`, made (with the objects above it) when missing.
pub fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
let mut cur = v;
for p in path {
if cur.get(*p).is_none_or(Value::is_null) {
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
}
cur = cur.get_mut(*p).unwrap();
}
cur.as_array_mut().expect("a list")
}
/// A tag for a link without one: its remark, else its host.
pub fn link_tag(link: &str) -> String {
if let Some((_, remark)) = link.split_once('#') {
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
if t != "proxy" {
return t;
}
}
let host = link.split("://").nth(1).unwrap_or("").split(['@']).next_back().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
let t = ps_core::links::subscription::slugify_tag(host);
if t.is_empty() { "outbound".into() } else { t }
}
/// A tag for a subscription without one: its host.
pub fn subscription_tag(url: &str) -> String {
let host = ps_core::links::subscription::url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
ps_core::links::subscription::slugify_tag(&host)
}
/// What an outbound is made from: a share link, or a backend's own JSON for one.
#[derive(Debug, Clone, PartialEq)]
pub enum OutboundSource {
Link(String),
SingBoxJson(Value),
XrayJson(Value),
}
impl OutboundSource {
/// A link, or JSON (XRay's has a `protocol`, sing-box's a `type`). A link is checked
/// here: the service would only say it left the outbound out.
pub fn parse(text: &str) -> Result<Self> {
let text = text.trim();
if text.starts_with('{') {
let json: Value = serde_json::from_str(text).map_err(|e| anyhow!("not JSON: {e}"))?;
return Ok(if json.get("protocol").is_some() { Self::XrayJson(json) } else { Self::SingBoxJson(json) });
}
ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::SingBox)
.or_else(|_| ps_core::links::build_outbound(text, "check", ps_core::links::LinkBackend::Xray))
.map_err(|e| anyhow!("{e}"))?;
Ok(Self::Link(text.to_owned()))
}
}
pub fn add_outbound(c: &mut Value, tag: &str, source: &OutboundSource, detour: Option<&str>) -> Result<()> {
let list = arr(c, &["proxy", "outbounds"]);
if list.iter().any(|o| o["tag"] == tag) {
bail!("an outbound '{tag}' exists");
}
let mut ob = match source {
OutboundSource::Link(link) => json!({ "tag": tag, "url": link }),
OutboundSource::SingBoxJson(j) => json!({ "tag": tag, "singBoxJson": j }),
OutboundSource::XrayJson(j) => json!({ "tag": tag, "xrayJson": j }),
};
if let Some(d) = detour {
ob["detour"] = d.into();
}
list.push(ob);
Ok(())
}
pub fn remove_outbound(c: &mut Value, tag: &str) -> Result<()> {
let list = arr(c, &["proxy", "outbounds"]);
let before = list.len();
list.retain(|o| o["tag"] != tag);
if list.len() == before {
bail!("no outbound '{tag}' in the configuration");
}
Ok(())
}
pub fn add_subscription(c: &mut Value, tag: &str, url: &str) -> Result<()> {
let list = arr(c, &["proxy", "subscriptions"]);
if list.iter().any(|s| s["tag"] == tag) {
bail!("a subscription '{tag}' exists");
}
list.push(json!({ "tag": tag, "url": url }));
Ok(())
}
pub fn remove_subscription(c: &mut Value, tag: &str) -> Result<()> {
let list = arr(c, &["proxy", "subscriptions"]);
let before = list.len();
list.retain(|s| s["tag"] != tag);
if list.len() == before {
bail!("no subscription '{tag}'");
}
Ok(())
}
/// A rule's matches, sorted into their kinds: domains, addresses, `geosite:`, `geoip:`,
/// `ruleset:` and `process:` ones.
pub fn sort_matches(matches: &[String]) -> Value {
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
for x in matches {
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
("geosites", v.to_owned())
} else if let Some(v) = x.strip_prefix("geoip:") {
("geoips", v.to_owned())
} else if let Some(v) = x.strip_prefix("ruleset:") {
("ruleSets", v.to_owned())
} else if let Some(v) = x.strip_prefix("process:") {
("processNames", v.to_owned())
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
("ips", x.clone())
} else {
("domains", x.trim_start_matches('.').to_lowercase())
};
m[key].as_array_mut().unwrap().push(value.into());
}
m
}
/// Sends `matches` to `target`: into the rule called `name` (the target's name without
/// one), extended if it exists, made with priority 50 if not.
pub fn add_rule(c: &mut Value, target: &str, matches: &[String], name: Option<&str>, priority: Option<i64>) -> Result<()> {
if matches.is_empty() {
bail!("a rule needs something to match");
}
let m = sort_matches(matches);
let name = name.unwrap_or(target);
let list = arr(c, &["proxy", "routing", "rules"]);
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name) {
for (k, v) in m.as_object().unwrap() {
let mut merged = rule[k.as_str()].as_array().cloned().unwrap_or_default();
for x in v.as_array().unwrap() {
if !merged.contains(x) {
merged.push(x.clone());
}
}
rule[k.as_str()] = Value::Array(merged);
}
rule["outbound"] = target.into();
if let Some(p) = priority {
rule["priority"] = p.into();
}
} else {
let mut rule = m;
rule["name"] = name.into();
rule["outbound"] = target.into();
rule["priority"] = priority.unwrap_or(50).into();
list.push(rule);
}
Ok(())
}
pub fn remove_rule(c: &mut Value, name: &str) -> Result<()> {
let list = arr(c, &["proxy", "routing", "rules"]);
let before = list.len();
list.retain(|r| r["name"] != name);
if list.len() == before {
bail!("no rule named '{name}'");
}
Ok(())
}
pub fn set_rule_disabled(c: &mut Value, name: &str, disabled: bool) -> Result<()> {
if name.is_empty() {
bail!("a rule name");
}
let list = arr(c, &["proxy", "routing", "rules"]);
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
rule["disabled"] = disabled.into();
Ok(())
}
pub fn set_proxy_enabled(c: &mut Value, on: bool) {
c["proxy"]["enable"] = on.into();
}
pub fn set_tun_enabled(c: &mut Value, on: bool) {
c["proxy"]["tun"]["enable"] = on.into();
}
pub fn set_zapret_enabled(c: &mut Value, on: bool) {
c["zapret"]["enable"] = on.into();
}
/// The DPI bypass's engine, by upstream's names: `zapret-discord-youtube` (Flowseal's
/// presets) or `zapret2`.
pub fn set_zapret_engine(c: &mut Value, engine: &str) -> Result<()> {
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
bail!("the engine is zapret-discord-youtube or zapret2");
}
c["zapret"]["engine"] = engine.into();
Ok(())
}
/// The zapret-discord-youtube preset, e.g. "general (ALT9)".
pub fn set_zapret_preset(c: &mut Value, name: &str) {
c["zapret"]["zapret-discord-youtube"]["configName"] = name.into();
}
/// Which game traffic zapret handles: all, tcp, udp or null.
pub fn set_game_filter(c: &mut Value, filter: &str) -> Result<()> {
if !matches!(filter, "all" | "tcp" | "udp" | "null") {
bail!("the game filter is all, tcp, udp or null");
}
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.into();
Ok(())
}
pub fn set_tg_ws_proxy_enabled(c: &mut Value, on: bool) {
c["tgWsProxy"]["enable"] = on.into();
}
/// Any option by its path, e.g. `["zapret", "zapret2", "ipv6"]`; the objects above it are
/// made when missing.
pub fn set_path(c: &mut Value, path: &[&str], value: Value) {
let mut cur = c;
for p in path {
if !cur.is_object() {
*cur = json!({});
}
cur = &mut cur[*p];
}
*cur = value;
}
/// whitelist-bypass's platforms, as its options name them.
pub const WL_PLATFORMS: [&str; 5] = ["wbstream", "telemost", "dion", "bitrix", "vk"];
/// A whitelist-bypass joiner or creator (`role`: "joiners" or "creators") on `platform`. A name
/// is one of either: `proxy-ctl wl` takes them by name alone.
pub fn add_wl(c: &mut Value, role: &str, name: &str, platform: &str) -> Result<()> {
if !matches!(role, "joiners" | "creators") {
bail!("a whitelist-bypass role is joiners or creators");
}
if !ps_core::config::path_name_ok(name) {
bail!("a name takes letters, digits, '.', '_' and '-', and no leading dot");
}
if !WL_PLATFORMS.contains(&platform) {
bail!("no platform '{platform}': {}", WL_PLATFORMS.join(", "));
}
if role == "joiners" && platform == "vk" {
bail!("VK has no joiner, only creators");
}
let wl = &c["whitelistBypass"];
if wl["joiners"].get(name).is_some() || wl["creators"].get(name).is_some() {
bail!("'{name}' is taken");
}
set_path(c, &["whitelistBypass", role, name], json!({ "platform": platform }));
Ok(())
}
pub fn remove_wl(c: &mut Value, role: &str, name: &str) -> Result<()> {
match c.get_mut("whitelistBypass").and_then(|w| w.get_mut(role)).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
Some(_) => Ok(()),
None => bail!("no whitelist-bypass {} '{name}'", role.trim_end_matches('s')),
}
}
/// An AmneziaWG profile from an AmneziaVPN `vpn://` link or a `.conf`'s text: `kind` "vpn"
/// (system-wide), "userspace" or "singBox" (an outbound of the proxy).
pub fn add_awg_profile(c: &mut Value, name: &str, text: &str, kind: &str) -> Result<()> {
if !ps_core::config::path_name_ok(name) || name.len() > 32 {
bail!("a profile name takes up to 32 letters, digits, '.', '_' and '-', and no leading dot");
}
let text = text.trim();
let mut profile = if text.starts_with("vpn://") {
json!({ "vpn": text })
} else if text.contains("[Interface]") {
json!({ "config": text })
} else {
bail!("paste an AmneziaVPN vpn:// link or a .conf (with its [Interface])");
};
match kind {
"vpn" => {}
"userspace" | "singBox" => profile["asOutbound"] = kind.into(),
_ => bail!("a profile is a system-wide VPN or an outbound (userspace, singBox)"),
}
if c["amneziaWg"]["profiles"].get(name).is_some() {
bail!("there is a profile '{name}' already");
}
set_path(c, &["amneziaWg", "profiles", name], profile);
set_path(c, &["amneziaWg", "enable"], true.into());
Ok(())
}
pub fn remove_awg_profile(c: &mut Value, name: &str) -> Result<()> {
match c.get_mut("amneziaWg").and_then(|w| w.get_mut("profiles")).and_then(Value::as_object_mut).and_then(|o| o.remove(name)) {
Some(_) => Ok(()),
None => bail!("no AmneziaWG profile '{name}'"),
}
}
/// The sites an engine also handles and those it leaves alone: for `zapret-discord-youtube`
/// beside its release's lists, for `zapret2` beside its strategies' own.
pub fn set_zapret_sites(c: &mut Value, engine: &str, domains: &[String], exclude: &[String]) -> Result<()> {
if !matches!(engine, "zapret-discord-youtube" | "zapret2") {
bail!("the engine is zapret-discord-youtube or zapret2");
}
let clean = |list: &[String]| -> Vec<Value> {
let mut out: Vec<Value> = Vec::new();
for d in list.iter().map(|d| d.trim().trim_start_matches('.').to_lowercase()).filter(|d| !d.is_empty()) {
if !out.contains(&Value::from(d.as_str())) {
out.push(d.into());
}
}
out
};
c["zapret"][engine]["domains"] = Value::Array(clean(domains));
c["zapret"][engine]["excludeDomains"] = Value::Array(clean(exclude));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn amneziawg_profiles_come_from_links_or_confs() {
let mut c = json!({});
add_awg_profile(&mut c, "home", "vpn://AAAA", "vpn").unwrap();
add_awg_profile(&mut c, "exit", "[Interface]\nPrivateKey = x\n", "userspace").unwrap();
assert_eq!(c["amneziaWg"]["profiles"]["home"], json!({ "vpn": "vpn://AAAA" }));
assert_eq!(c["amneziaWg"]["profiles"]["exit"]["asOutbound"], "userspace");
assert_eq!(c["amneziaWg"]["enable"], true);
assert!(add_awg_profile(&mut c, "home", "vpn://B", "vpn").is_err());
assert!(add_awg_profile(&mut c, "x", "hello", "vpn").is_err());
assert!(add_awg_profile(&mut c, "a/b", "vpn://B", "vpn").is_err());
remove_awg_profile(&mut c, "home").unwrap();
assert!(remove_awg_profile(&mut c, "home").is_err());
}
#[test]
fn whitelist_bypass_entries_are_added_once_and_removed() {
let mut c = json!({});
add_wl(&mut c, "joiners", "wl", "wbstream").unwrap();
add_wl(&mut c, "creators", "laptop", "vk").unwrap();
assert_eq!(c["whitelistBypass"]["joiners"]["wl"], json!({ "platform": "wbstream" }));
assert!(add_wl(&mut c, "creators", "wl", "dion").is_err(), "a name is one of either");
assert!(add_wl(&mut c, "joiners", "phone", "vk").is_err(), "VK has no joiner");
assert!(add_wl(&mut c, "joiners", "phone", "zoom").is_err());
assert!(add_wl(&mut c, "joiners", "../x", "wbstream").is_err());
assert!(add_wl(&mut c, "joiners", "CON", "wbstream").is_err());
remove_wl(&mut c, "joiners", "wl").unwrap();
assert!(remove_wl(&mut c, "joiners", "wl").is_err());
assert_eq!(c["whitelistBypass"]["creators"]["laptop"]["platform"], "vk");
}
#[test]
fn outbounds_are_added_once_and_removed() {
let mut c = json!({});
let src = OutboundSource::parse("ss://YWVzLTEyOC1nY206cGFzcw@1.2.3.4:8388#My%20Server").unwrap();
add_outbound(&mut c, "nl", &src, Some("hop")).unwrap();
assert_eq!(c["proxy"]["outbounds"][0]["detour"], "hop");
assert!(add_outbound(&mut c, "nl", &src, None).is_err());
remove_outbound(&mut c, "nl").unwrap();
assert!(remove_outbound(&mut c, "nl").is_err());
}
#[test]
fn sources_are_links_or_either_json() {
assert!(matches!(OutboundSource::parse(r#"{"protocol":"vless"}"#).unwrap(), OutboundSource::XrayJson(_)));
assert!(matches!(OutboundSource::parse(r#" {"type":"vless"}"#).unwrap(), OutboundSource::SingBoxJson(_)));
assert!(OutboundSource::parse("not a link").is_err());
}
#[test]
fn tags_come_from_the_remark_or_the_host() {
assert_eq!(link_tag("ss://x@1.2.3.4:8388#My%20Server"), "My-Server");
assert_eq!(link_tag("vless://id@example.com:443?security=tls"), "example-com");
}
#[test]
fn rules_are_extended_by_name() {
let mut c = json!({});
add_rule(&mut c, "direct", &["Example.com".into(), "10.0.0.0/8".into(), "process:steam.exe".into()], None, None).unwrap();
add_rule(&mut c, "direct", &["example.com".into(), "geosite:cn".into()], None, Some(10)).unwrap();
let r = &c["proxy"]["routing"]["rules"][0];
assert_eq!(r["domains"], json!(["example.com"]));
assert_eq!(r["ips"], json!(["10.0.0.0/8"]));
assert_eq!(r["processNames"], json!(["steam.exe"]));
assert_eq!(r["geosites"], json!(["cn"]));
assert_eq!(r["priority"], 10);
set_rule_disabled(&mut c, "direct", true).unwrap();
assert_eq!(c["proxy"]["routing"]["rules"][0]["disabled"], true);
}
#[test]
fn paths_and_site_lists() {
let mut c = json!({ "zapret": null });
set_path(&mut c, &["zapret", "zapret2", "ipv6"], true.into());
assert_eq!(c["zapret"]["zapret2"]["ipv6"], true);
set_zapret_sites(&mut c, "zapret2", &[" .Example.com".into(), "".into(), "example.com".into()], &["bank.example".into()]).unwrap();
assert_eq!(c["zapret"]["zapret2"]["domains"], json!(["example.com"]));
assert_eq!(c["zapret"]["zapret2"]["excludeDomains"], json!(["bank.example"]));
assert!(set_zapret_sites(&mut c, "goodbyedpi", &[], &[]).is_err());
}
#[test]
fn zapret_settings_are_checked() {
let mut c = json!({});
assert!(set_game_filter(&mut c, "everything").is_err());
set_game_filter(&mut c, "udp").unwrap();
assert!(set_zapret_engine(&mut c, "goodbyedpi").is_err());
set_zapret_engine(&mut c, "zapret2").unwrap();
assert_eq!(c["zapret"], json!({ "engine": "zapret2", "zapret-discord-youtube": { "gameFilter": "udp" } }));
}
}
+155
View File
@@ -0,0 +1,155 @@
//! The service's client side, shared by proxy-ctl and the app: requests, configuration
//! edits made against the revision they read, and the edits both make ([`edits`]).
pub mod edits;
use anyhow::{Result, bail};
use ps_ipc::transport::{self, Address};
use ps_ipc::{Request, Response};
use serde_json::Value;
/// What a configuration edit got back: the new revision, the validator's notes, and the
/// error applying it, when it was saved but did not apply.
#[derive(Debug, Clone, Default)]
pub struct Saved {
pub revision: Option<u64>,
pub issues: Vec<Issue>,
pub apply_error: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Issue {
pub severity: String,
pub path: String,
pub message: String,
}
impl std::fmt::Display for Issue {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}: {}: {}", self.severity, self.path, self.message)
}
}
/// The validator's notes in a response's data.
pub fn issues(data: &Value) -> Vec<Issue> {
data["issues"]
.as_array()
.into_iter()
.flatten()
.map(|i| Issue {
severity: i["severity"].as_str().unwrap_or("").to_owned(),
path: i["path"].as_str().unwrap_or("").to_owned(),
message: i["message"].as_str().unwrap_or("").to_owned(),
})
.collect()
}
#[derive(Debug, Clone)]
pub struct Client {
pub addr: Address,
}
impl Client {
pub fn new(addr: Address) -> Self {
Self { addr }
}
/// One request; a refusal is an error carrying the service's words and its notes.
pub async fn call(&self, req: Request) -> Result<Value> {
let resp: Response = transport::call(&self.addr, &req).await?;
if !resp.ok {
let mut msg = resp.error.unwrap_or_else(|| "failed".into());
for i in issues(&resp.data) {
msg.push_str(&format!("\n {i}"));
}
bail!(msg);
}
Ok(resp.data)
}
/// Reads the configuration, lets `edit` change it, and writes it back against the
/// revision read; a concurrent change is read again and `edit` made again.
pub async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
for _ in 0..3 {
let got = self.call(Request::ConfigGet).await?;
let mut config = got["config"].clone();
edit(&mut config)?;
match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await {
Err(e) if e.to_string().contains("changed since revision") => continue,
other => {
let r = other?;
return Ok(Saved {
revision: r["revision"].as_u64(),
issues: issues(&r),
apply_error: r["error"].as_str().map(str::to_owned),
});
}
}
}
bail!("the configuration kept changing; try again")
}
/// Log lines (every unit's without `unit`) as `(unit, line)`, the last `lines` and, with
/// `follow`, each new one, until `each` says stop.
pub async fn logs(&self, unit: Option<String>, lines: usize, follow: bool, mut each: impl FnMut(&str, &str) -> bool) -> Result<()> {
let mut take = |r: Response| {
let one = |l: &Value| (l["unit"].as_str().unwrap_or("").to_owned(), l["line"].as_str().unwrap_or("").to_owned());
match &r.data {
Value::Array(ls) => ls.iter().map(one).all(|(u, l)| each(&u, &l)),
d if d.is_object() => {
let (u, l) = one(d);
each(&u, &l)
}
_ => true,
}
};
let req = Request::Logs { unit, lines, follow };
if follow {
let mut refused = None;
transport::stream(&self.addr, &req, |r| {
if !r.ok {
refused = Some(r.error.unwrap_or_else(|| "failed".into()));
return false;
}
take(r)
})
.await?;
if let Some(e) = refused {
bail!(e);
}
} else {
let r = transport::call(&self.addr, &req).await?;
if !r.ok {
bail!(r.error.unwrap_or_else(|| "failed".into()));
}
take(r);
}
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");
}
}
+2
View File
@@ -7,6 +7,7 @@ license.workspace = true
[dependencies]
base64.workspace = true
flate2 = "1"
serde.workspace = true
serde_json.workspace = true
regex.workspace = true
@@ -14,5 +15,6 @@ thiserror.workspace = true
percent-encoding.workspace = true
ipnet.workspace = true
indexmap.workspace = true
psl = "2"
[dev-dependencies]
@@ -1,21 +1,49 @@
//! 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::zapret2::{Paths, args, keenetic};
use ps_core::config::{StrategySource, Zapret2};
use ps_core::zapret2::{Extras, Paths, args, keenetic, z2k};
fn main() {
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 (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 {
lua: format!("{comp}lua\\"),
user: format!("{state}zapret-hosts-user.txt"),
exclude: format!("{state}zapret-hosts-user-exclude.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() {
println!("{arg}");
}
+36 -7
View File
@@ -1,18 +1,47 @@
//! For tools/winws-dry-run.sh: a preset's winws arguments as the service builds them, one
//! per line. `zapret_args <release dir> <lists dir> <preset> <game filter>`, paths as
//! Windows sees them (with a trailing separator).
//! per line. `zapret_args <release dir> <release dir as Windows sees it> <lists dir as Windows
//! sees it> <preset> <game filter> [<hostlistRules JSON> <lists dir>]`, Windows paths with a
//! trailing separator. With rules, their lists are written into the lists dir.
use ps_core::config::GameFilter;
use ps_core::zapret::{expand, find_preset, preset_args};
use ps_core::config::{GameFilter, HostlistRule};
use ps_core::zapret::{ReleaseLists, expand, find_preset, preset_args, rule, rule_lists, with_rules};
fn main() {
let a: Vec<String> = std::env::args().collect();
let (release, win_root, win_lists, preset, game) = (&a[1], &a[2], &a[3], &a[4], &a[5]);
let release = std::path::Path::new(release);
let files: Vec<String> = std::fs::read_dir(release).unwrap().filter_map(|e| e.ok()?.file_name().into_string().ok()).collect();
let file = find_preset(&files, preset).unwrap();
let text = std::fs::read_to_string(std::path::Path::new(release).join(file)).unwrap();
let game: GameFilter = serde_json::from_value(serde_json::json!(game)).unwrap();
for arg in expand(&preset_args(&text).unwrap(), &format!("{win_root}bin\\"), win_lists, win_root, game) {
let bin = format!("{win_root}bin\\");
let ex = |args: &[String]| expand(args, &bin, win_lists, win_root, game);
let args_of = |name: &str| -> Result<Vec<String>, String> {
let file = find_preset(&files, name)?;
Ok(ex(&preset_args(&std::fs::read_to_string(release.join(file)).unwrap())?))
};
let mut args = args_of(preset).unwrap();
if let (Some(json), Some(lists)) = (a.get(6), a.get(7)) {
let read = |f: &str| std::fs::read_to_string(release.join("lists").join(f)).unwrap_or_default();
let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt"));
let release_lists = ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all };
let raw: Vec<HostlistRule> = serde_json::from_str(&std::fs::read_to_string(json).unwrap()).unwrap();
let rules: Vec<_> = raw.iter().map(|r| rule(r, &release_lists).unwrap()).collect();
for r in &rules {
let (list, ipset) = rule_lists(r);
for (file, entries) in [(list, &r.domains), (ipset, &r.ips)] {
if !entries.is_empty() {
std::fs::write(std::path::Path::new(lists).join(file), format!("{}\n", entries.join("\n"))).unwrap();
}
}
}
args = match with_rules(args, &rules, win_lists, &args_of, &ex) {
Ok(a) => a,
Err(e) => {
eprintln!("{e}");
std::process::exit(2);
}
};
}
for arg in args {
println!("{arg}");
}
}
+865
View File
@@ -0,0 +1,865 @@
//! autoProxy's judgement, as upstream decides it: what one fetch through an exit says
//! (proxy_ctl.py's `proxy auto probe`), the walk over the exits for a destination, the order
//! they are walked in (autoproxy-rounds.jq), the strikes against exits a destination refused
//! (autoproxy-strike.jq), what is remembered (autoproxy-run.template.sh, autoproxy-edit.jq)
//! and the rule-sets sing-box takes it from (autoproxy-render.template.sh).
//!
//! The fetches themselves are the service's; this is the deciding, so it is tested here.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::LazyLock;
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::links::subscription::{nearness, url_parts};
/// The exit that is this host: always the first.
pub const DIRECT: &str = "direct";
/// The paths a destination is probed at: the page, then robots.txt, which some sites serve
/// where their front page refuses a client that is not a browser.
pub const PATHS: [&str; 2] = ["/", "/robots.txt"];
/// One fetch through one exit, at the first hop that is not a same-site redirect.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Fetch {
/// The answer's status; none when no answer came (TLS or the connection failed first).
pub status: Option<u16>,
/// The PROBE_BLOCK_PAGES name a refusal's page matched, "" for none.
#[serde(default)]
pub block: String,
/// A redirect's Location.
#[serde(default)]
pub location: String,
/// Bytes read of the body (at most what was read to judge it).
#[serde(default)]
pub bytes: u64,
/// Why no answer came.
#[serde(default)]
pub error: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Judgement {
/// Content.
Ok,
/// Failed before the origin spoke: the censor's doing, zapret's job.
Dead,
/// The site's security layer refused this address: an exit past it helps.
Wall,
/// The origin answered and refused: another exit can fix it.
Blocked,
}
/// Block pages, by name: (kind, pattern over a refusal's headers and the first 8 KiB of its
/// body). "address": the address itself was refused, so an exit that gets past it reaches the
/// site; "geo": its country was, which is an ordinary refusal.
static BLOCK_PAGES: LazyLock<Vec<(&str, &str, Regex)>> = LazyLock::new(|| {
[
("aws-waf", "address", r"(?ims)^server: cloudfront\b.*Request blocked\."),
("cloudfront-geo", "geo", r"(?i)configured to block access from your country"),
("cloudflare", "address", r#"(?im)^cf-mitigated: challenge|cf-error-code">10(06|07|08|20)<|error code: 10(06|07|08|20)\b"#),
("cloudflare-geo", "geo", r#"(?i)cf-error-code">1009<|error code: 1009\b"#),
("akamai", "address", r"(?ims)^server: AkamaiGHost\b.*Access Denied"),
("imperva", "address", r"(?i)Incapsula incident ID"),
("datadome", "address", r"(?im)^x-datadome:"),
]
.into_iter()
.map(|(name, kind, re)| (name, kind, Regex::new(re).expect("a valid pattern")))
.collect()
});
static BLOCK_REDIRECT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)unavailable|not-available|blocked|geo|region|restricted").unwrap());
static HOST: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[a-zA-Z0-9._-]+\.[a-zA-Z]{2,}$").unwrap());
/// A host name autoProxy probes or routes: letters, digits, dots, '_' and '-', with a TLD.
pub fn host_ok(host: &str) -> bool {
host.len() <= 253 && HOST.is_match(host)
}
/// The name of the block page a refusal (`status` 4xx or 5xx) shows, "" for none. `head` is
/// its headers as received, `body` its first bytes.
pub fn block_page(status: u16, head: &str, body: &[u8]) -> String {
if !(400..600).contains(&status) {
return String::new();
}
let body: String = body.iter().take(8192).map(|&b| b as char).collect();
let text = format!("{head}\n\n{body}\n\n");
BLOCK_PAGES.iter().find(|(_, _, re)| re.is_match(&text)).map(|(name, _, _)| (*name).to_owned()).unwrap_or_default()
}
/// The last two labels: a redirect is followed only within them.
pub fn site(url: &str) -> String {
let host = url_parts::split(url).ok().and_then(|u| u.hostname).unwrap_or_default();
let labels: Vec<&str> = host.split('.').collect();
labels[labels.len().saturating_sub(2)..].join(".")
}
/// Whether a Location names this host or its LAN (localhost, or an address literal in any of
/// the forms curl takes): never followed.
pub fn local_target(url: &str) -> bool {
match url_parts::split(url) {
Ok(u) => nearness(u.hostname.as_deref()) > 0,
Err(_) => true,
}
}
/// Whether a redirect's target says the content is refused (a "not available" page).
pub fn redirect_is_block(location: &str) -> bool {
BLOCK_REDIRECT.is_match(location)
}
fn http_ok(f: &Fetch) -> bool {
match f.status {
Some(s) if (200..300).contains(&s) || s == 401 || s == 404 => true,
Some(s) if (300..400).contains(&s) => !redirect_is_block(&f.location),
_ => false,
}
}
pub fn judge(f: &Fetch) -> Judgement {
if f.status.is_none() {
return Judgement::Dead;
}
if http_ok(f) {
return Judgement::Ok;
}
let address = BLOCK_PAGES.iter().any(|(name, kind, _)| *name == f.block && *kind == "address");
if address { Judgement::Wall } else { Judgement::Blocked }
}
/// Content; or, where direct hit a wall, any answer from the origin past it.
pub fn reaches(direct: Judgement, j: Judgement) -> bool {
j == Judgement::Ok || (direct == Judgement::Wall && j == Judgement::Blocked)
}
/// "ok": direct gets it. "destination": an exit reaches what direct does not, past a refusal:
/// route through it. "censor": direct dies on the way while an exit reaches it, which zapret
/// is for: it stays direct. "both-fail" and "unreachable": no exit helps.
pub fn verdict(direct: &Fetch, via: &Fetch) -> &'static str {
let d = judge(direct);
if d == Judgement::Ok {
return "ok";
}
if reaches(d, judge(via)) {
return if d == Judgement::Dead { "censor" } else { "destination" };
}
if d == Judgement::Dead { "unreachable" } else { "both-fail" }
}
pub fn verdict_text(verdict: &str, exit: Option<&str>) -> String {
match verdict {
"ok" => "reachable directly - nothing to do".into(),
"destination" => format!("destination-side block - route via {}", exit.unwrap_or("proxy")),
"censor" => "censor-side block - zapret's territory, not proxied".into(),
"both-fail" => "fails through every egress - not an egress problem".into(),
"unreachable" => "no egress reaches it at all".into(),
_ => "inconclusive".into(),
}
}
pub fn describe(f: &Fetch) -> String {
let Some(status) = f.status else {
return if f.error.is_empty() { "no answer".into() } else { format!("no answer ({})", f.error) };
};
let mut text = format!("{status}, {} bytes", f.bytes);
if !f.block.is_empty() {
text.push_str(&format!(", {} page", f.block));
}
if !f.location.is_empty() {
text.push_str(&format!(" -> {}", f.location));
}
text
}
/// One request of a walk.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Row {
pub tag: String,
pub path: String,
pub fetch: Fetch,
pub judgement: Judgement,
}
/// What a probe found: the verdict, the exit that reached it (none for "ok" and the failures),
/// the path it was judged on, and every request made.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct Probe {
pub domain: String,
pub verdict: String,
pub exit: Option<String>,
pub path: String,
pub rows: Vec<Row>,
}
/// Walks the exits (`exits[0]` is direct) and stops at the first that reaches `domain`: gets
/// content, or gets past a wall direct hit. `keep_going` still tries the rest, keeping that
/// first one. `fetch(tag, path)` is one request through one exit.
pub async fn walk<F, Fut>(domain: &str, exits: &[String], paths: &[&str], keep_going: bool, mut fetch: F) -> Probe
where
F: FnMut(String, String) -> Fut,
Fut: Future<Output = Fetch>,
{
let mut p = Probe { domain: domain.to_owned(), ..Default::default() };
let Some((direct_tag, others)) = exits.split_first() else {
p.verdict = "error".into();
return p;
};
let mut first_direct: Option<Fetch> = None;
for path in paths {
let direct = fetch(direct_tag.clone(), (*path).to_owned()).await;
let dj = judge(&direct);
p.rows.push(Row { tag: direct_tag.clone(), path: (*path).to_owned(), fetch: direct.clone(), judgement: dj });
first_direct.get_or_insert_with(|| direct.clone());
if dj == Judgement::Ok && p.verdict.is_empty() {
p.verdict = "ok".into();
p.path = (*path).to_owned();
if !keep_going {
return p;
}
}
for tag in others {
let via = fetch(tag.clone(), (*path).to_owned()).await;
let j = judge(&via);
p.rows.push(Row { tag: tag.clone(), path: (*path).to_owned(), fetch: via.clone(), judgement: j });
if reaches(dj, j) && p.verdict.is_empty() {
p.verdict = verdict(&direct, &via).into();
p.exit = Some(tag.clone());
p.path = (*path).to_owned();
if !keep_going {
return p;
}
}
}
}
if p.verdict.is_empty() {
let dead = first_direct.as_ref().is_none_or(|f| judge(f) == Judgement::Dead);
p.verdict = if dead { "unreachable" } else { "both-fail" }.into();
p.path = paths.first().map(|s| (*s).to_owned()).unwrap_or_default();
}
p
}
/// `--via`: can `via` carry what direct reaches? It must get content on some path and fail on
/// none where direct succeeds. Verdict "ok" or "blocked".
pub async fn stand_in<F, Fut>(domain: &str, via: &str, paths: &[&str], mut fetch: F) -> Probe
where
F: FnMut(String, String) -> Fut,
Fut: Future<Output = Fetch>,
{
let mut p = Probe {
domain: domain.to_owned(),
verdict: "ok".into(),
exit: Some(via.to_owned()),
path: paths.first().map(|s| (*s).to_owned()).unwrap_or_default(),
rows: Vec::new(),
};
let mut got = false;
for path in paths {
let direct = fetch(DIRECT.to_owned(), (*path).to_owned()).await;
let through = fetch(via.to_owned(), (*path).to_owned()).await;
let (dj, vj) = (judge(&direct), judge(&through));
p.rows.push(Row { tag: DIRECT.into(), path: (*path).to_owned(), fetch: direct, judgement: dj });
p.rows.push(Row { tag: via.to_owned(), path: (*path).to_owned(), fetch: through, judgement: vj });
got |= vj == Judgement::Ok;
if dj == Judgement::Ok && vj != Judgement::Ok {
p.verdict = "blocked".into();
}
}
if !got {
p.verdict = "blocked".into();
}
p
}
/// The registrable domain of `host` (its site: example.co.uk, foo.workers.dev), by the public
/// suffix list with its private section; none for a public suffix itself, or a bare label.
pub fn registrable(host: &str) -> Option<String> {
let host = host.trim_end_matches('.').to_ascii_lowercase();
if !host.contains('.') {
return None;
}
let domain = psl::domain_str(&host)?;
Some(domain.to_owned())
}
// --- the state -----------------------------------------------------------------------------
/// A destination routed through an exit: probed blocked directly ("destination"), or
/// crawling directly ("slow").
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Route {
pub verdict: String,
pub exit: String,
pub host: String,
#[serde(default)]
pub path: String,
pub at: u64,
/// "slow": times it crawled on its exit since it last did not; two move it on.
#[serde(default, skip_serializing_if = "is_zero")]
pub bad: u32,
/// "slow": the exits tried, in order.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub tried: Vec<String>,
}
fn is_zero(n: &u32) -> bool {
*n == 0
}
/// What the transfer sampler saw: a host's best connection through an exit, crawling
/// (`slow`) or not, and its fastest second.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Observation {
pub domain: String,
pub host: String,
pub exit: String,
pub slow: bool,
pub peak: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowHits {
pub n: u32,
pub first: u64,
}
/// A site owed an exit for crawling directly, and the exits tried for it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SlowWant {
pub host: String,
#[serde(default)]
pub tried: Vec<String>,
}
/// What the last probe of a host found.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct HostVerdict {
pub domain: String,
pub verdict: String,
#[serde(default)]
pub exit: Option<String>,
pub at: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Strike {
pub why: String,
pub at: u64,
}
/// An exit: where it leaves from (its network, by AS), and the destinations that refused it.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct ExitInfo {
pub ip: Option<String>,
pub asn: Option<String>,
pub at: u64,
pub strikes: BTreeMap<String, Strike>,
pub bad: bool,
pub bad_by: Vec<String>,
}
/// A host dialled directly, not yet probed: how often, and since when.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Queued {
pub domain: String,
pub hits: u64,
pub first: u64,
}
/// state.json.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct State {
/// This host's public address the verdicts are about.
pub egress: Option<String>,
/// Registrable domain -> the exit it is routed through.
pub domains: BTreeMap<String, Route>,
pub hosts: BTreeMap<String, HostVerdict>,
pub exits: BTreeMap<String, ExitInfo>,
pub backlog: BTreeMap<String, Queued>,
pub last_run: u64,
/// Hosts seen crawling directly, within a day.
pub slow_hits: BTreeMap<String, SlowHits>,
/// Sites owed an exit for crawling, by registrable domain.
pub slow_want: BTreeMap<String, SlowWant>,
/// Sites no exit carried better, left direct until then.
pub slow_skip: BTreeMap<String, u64>,
}
/// Most entries the backlog keeps: every distinct name dialled is one.
const BACKLOG_MAX: usize = 5000;
impl State {
/// `domain` refused `tags` at `now` (`why`: "wall:<page>", "refused" or "slow"), and every
/// strike older than `ttl` goes. A domain counts once per exit; two make an exit bad.
pub fn strike(&mut self, tags: &[String], domain: &str, why: &str, now: u64, ttl: u64) {
for t in tags {
self.exits.entry(t.clone()).or_default().strikes.insert(domain.to_owned(), Strike { why: why.to_owned(), at: now });
}
for e in self.exits.values_mut() {
e.strikes.retain(|_, s| s.at + ttl > now);
rebad(e);
}
}
/// `domain` back to direct, every verdict and strike about it gone.
pub fn forget(&mut self, domain: &str) {
self.domains.remove(domain);
self.hosts.retain(|_, h| h.domain != domain);
self.backlog.retain(|_, q| q.domain != domain);
self.slow_want.remove(domain);
self.slow_skip.remove(domain);
for e in self.exits.values_mut() {
if e.strikes.remove(domain).is_some() {
rebad(e);
}
}
}
/// Everything learned forgotten; what each exit is, the backlog and the egress stay.
pub fn clear(&mut self) {
self.domains.clear();
self.hosts.clear();
self.slow_want.clear();
self.slow_skip.clear();
for e in self.exits.values_mut() {
e.strikes.clear();
rebad(e);
}
}
/// A new public address: every verdict was about the old one.
pub fn new_egress(&mut self, egress: &str) {
*self = State { egress: Some(egress.to_owned()), backlog: std::mem::take(&mut self.backlog), last_run: self.last_run, ..Default::default() };
}
/// What probing `host` (of `domain`) found. A route applies to the whole domain (blocks
/// are drawn around sites); a verdict to the host. Exits refused on the path the winner
/// reached are struck: by a block page, or by the origin where the winner got content.
pub fn record(&mut self, domain: &str, host: &str, p: &Probe, now: u64, ttl: u64) {
if p.verdict == "destination"
&& let Some(exit) = &p.exit
{
self.domains.insert(
domain.to_owned(),
Route { verdict: p.verdict.clone(), exit: exit.clone(), host: host.to_owned(), path: p.path.clone(), at: now, bad: 0, tried: Vec::new() },
);
}
let exit = if p.verdict == "destination" { p.exit.clone() } else { None };
self.hosts.insert(host.to_owned(), HostVerdict { domain: domain.to_owned(), verdict: p.verdict.clone(), exit, at: now });
self.backlog.remove(host);
let Some(winner) = &p.exit else { return };
let won = p.rows.iter().find(|r| &r.tag == winner && r.path == p.path).map(|r| r.judgement);
let mut struck: BTreeMap<String, String> = BTreeMap::new();
for r in p.rows.iter().filter(|r| r.path == p.path && r.tag != DIRECT && &r.tag != winner) {
let why = match r.judgement {
Judgement::Wall => format!("wall:{}", r.fetch.block),
Judgement::Blocked if won == Some(Judgement::Ok) => "refused".into(),
_ => continue,
};
struck.entry(r.tag.clone()).or_insert(why);
}
for (tag, why) in struck {
self.strike(&[tag], domain, &why, now, ttl);
}
}
/// Hosts dialled directly since the last run (`counts`: host -> (domain, hits)) into the
/// backlog, skipping those a route covers or a verdict within the TTL judged; entries past
/// the TTL, or covered since, go; the most dialled 5000 stay.
pub fn queue(&mut self, counts: &BTreeMap<String, (String, u64)>, now: u64, ttl: u64) {
self.last_run = now;
self.hosts.retain(|_, h| h.at + ttl > now);
for (host, (domain, hits)) in counts {
if self.domains.contains_key(domain) || self.hosts.get(host).is_some_and(|h| h.at + ttl > now) {
continue;
}
let q = self.backlog.entry(host.clone()).or_insert(Queued { domain: domain.clone(), hits: 0, first: now });
q.hits += hits;
}
let domains = &self.domains;
self.backlog.retain(|_, q| q.first + ttl > now && !domains.contains_key(&q.domain));
if self.backlog.len() > BACKLOG_MAX {
let mut v: Vec<(String, Queued)> = std::mem::take(&mut self.backlog).into_iter().collect();
v.sort_by_key(|a| std::cmp::Reverse(a.1.hits));
v.truncate(BACKLOG_MAX);
self.backlog = v.into_iter().collect();
}
}
/// The backlog to probe, most dialled first: (domain, host).
pub fn backlog_order(&self, now: u64, ttl: u64) -> Vec<(String, String)> {
let mut v: Vec<(&String, &Queued)> = self
.backlog
.iter()
.filter(|(h, q)| !self.domains.contains_key(&q.domain) && self.hosts.get(*h).is_none_or(|v| v.at + ttl <= now))
.collect();
v.sort_by(|a, b| b.1.hits.cmp(&a.1.hits).then_with(|| a.0.cmp(b.0)));
v.into_iter().map(|(h, q)| (q.domain.clone(), h.clone())).collect()
}
/// Routes to probe again, once per TTL: (domain, host, exit).
pub fn due(&self, now: u64, ttl: u64) -> Vec<(String, String, String)> {
self.domains
.iter()
.filter(|(_, r)| r.verdict == "destination" && now.saturating_sub(r.at) >= ttl)
.map(|(d, r)| (d.clone(), r.host.clone(), r.exit.clone()))
.collect()
}
}
impl State {
/// What the sampler saw, folded in (autoproxy-slow-judge.jq). `hits` crawls on direct
/// within a day make a site owed an exit (`slow_want`); once routed it is judged on that
/// exit alone: a fast transfer keeps it, two slow ones move it to the next. Never moved:
/// censor verdicts (zapret's) and sites skipped for a while.
pub fn judge_slow(&mut self, obs: &[Observation], now: u64, hits: u32) {
self.slow_hits.retain(|_, h| h.first + 86400 > now);
for x in obs {
if let Some(r) = self.domains.get_mut(&x.domain)
&& r.verdict == "slow"
{
if x.exit != r.exit {
} else if x.slow {
r.bad += 1;
} else {
r.bad = 0;
r.at = now;
}
continue;
}
let skip = self.domains.contains_key(&x.domain)
|| x.exit != DIRECT
|| !x.slow
|| self.slow_want.contains_key(&x.domain)
|| self.slow_skip.get(&x.domain).is_some_and(|u| *u > now)
|| self.hosts.get(&x.host).is_some_and(|h| h.verdict == "censor");
if skip {
continue;
}
let h = self.slow_hits.entry(x.host.clone()).or_insert(SlowHits { n: 0, first: now });
h.n += 1;
if h.n >= hits {
self.slow_hits.remove(&x.host);
self.slow_want.insert(x.domain.clone(), SlowWant { host: x.host.clone(), tried: Vec::new() });
}
}
let moved: Vec<(String, Route)> =
self.domains.iter().filter(|(_, r)| r.verdict == "slow" && r.bad >= 2).map(|(d, r)| (d.clone(), r.clone())).collect();
for (d, r) in moved {
self.domains.remove(&d);
let tried = if r.tried.is_empty() { vec![r.exit.clone()] } else { r.tried.clone() };
self.slow_want.insert(d, SlowWant { host: r.host, tried });
}
self.slow_skip.retain(|_, until| *until > now);
if self.slow_hits.len() > 5000 {
let mut v: Vec<(String, SlowHits)> = std::mem::take(&mut self.slow_hits).into_iter().collect();
v.sort_by_key(|(_, h)| std::cmp::Reverse(h.n));
v.truncate(5000);
self.slow_hits = v.into_iter().collect();
}
while self.slow_want.len() > 500 {
let last = self.slow_want.keys().next_back().cloned().unwrap();
self.slow_want.remove(&last);
}
}
/// A crawling site's next exit found: routed through it.
pub fn route_slow(&mut self, domain: &str, host: &str, exit: &str, tried: Vec<String>, now: u64) {
self.domains.insert(
domain.to_owned(),
Route { verdict: "slow".into(), exit: exit.to_owned(), host: host.to_owned(), path: String::new(), at: now, bad: 0, tried },
);
self.slow_want.remove(domain);
}
/// No exit carries a crawling site better: left direct for `ttl`.
pub fn skip_slow(&mut self, domain: &str, now: u64, ttl: u64) {
self.slow_skip.insert(domain.to_owned(), now + ttl);
self.slow_want.remove(domain);
}
}
/// From Clash API `/connections` snapshots a second apart: per host and exit that moved at
/// least `min` bytes, its best connection's fastest second, and whether it never beat `below`
/// in any second (paced streams burst, so they read fast). Probe and test listeners skipped;
/// `chains[0]` is the exit that carried it. (autoproxy-slow-sample.jq)
pub fn sample_transfers(snapshots: &[Value], min: u64, below: u64) -> Vec<(String, String, bool, u64)> {
// id -> (host, exit, [download per snapshot])
let mut seen: BTreeMap<String, (String, String, Vec<Option<u64>>)> = BTreeMap::new();
for (i, snap) in snapshots.iter().enumerate() {
for c in snap["connections"].as_array().into_iter().flatten() {
let kind = c["metadata"]["type"].as_str().unwrap_or("");
if kind.contains("/probe-in-") || kind.ends_with("/proxy-suite-test-in") {
continue;
}
let Some(id) = c["id"].as_str() else { continue };
let host = c["metadata"]["host"].as_str().unwrap_or("").to_owned();
let exit = c["chains"][0].as_str().unwrap_or("").to_owned();
let e = seen.entry(id.to_owned()).or_insert_with(|| (host, exit, vec![None; snapshots.len()]));
e.2[i] = c["download"].as_u64();
}
}
let mut best: BTreeMap<(String, String), (u64, u64)> = BTreeMap::new();
for (host, exit, d) in seen.into_values() {
let deltas: Vec<u64> = d.windows(2).filter_map(|w| Some(w[1]?.saturating_sub(w[0]?))).collect();
let (total, peak) = (deltas.iter().sum::<u64>(), deltas.iter().copied().max().unwrap_or(0));
if host.is_empty() || exit.is_empty() || deltas.is_empty() || total < min {
continue;
}
let b = best.entry((host, exit)).or_insert((0, 0));
if peak >= b.0 {
*b = (peak, total);
}
}
best.into_iter().map(|((host, exit), (peak, _))| (host, exit, peak < below, peak)).collect()
}
fn rebad(e: &mut ExitInfo) {
e.bad = e.strikes.len() >= 2;
let mut s: Vec<(&String, &Strike)> = e.strikes.iter().collect();
s.sort_by_key(|(_, v)| v.at);
e.bad_by = s.into_iter().map(|(d, v)| format!("{d} {}", v.why)).collect();
}
/// The probe order of the exits after direct: round 1, one exit per network (AS); round 2,
/// walked only when round 1 all refused, the rest; bad exits never take a network's round-1
/// place and go last. Also the whole order.
pub fn rounds(exits: &[String], state: &State) -> (Vec<String>, Vec<String>, Vec<String>) {
let info = |t: &str| state.exits.get(t);
let bad = |t: &str| info(t).is_some_and(|e| e.bad);
let mut ordered: Vec<String> = exits.iter().filter(|t| t.as_str() != DIRECT && !bad(t)).cloned().collect();
ordered.extend(exits.iter().filter(|t| t.as_str() != DIRECT && bad(t)).cloned());
let (mut r1, mut r2) = (Vec::new(), Vec::new());
let mut seen = BTreeSet::new();
for t in &ordered {
let asn = info(t).and_then(|e| e.asn.clone()).unwrap_or_default();
if bad(t) {
r2.push(t.clone());
} else if asn.is_empty() || seen.insert(asn) {
r1.push(t.clone());
} else {
r2.push(t.clone());
}
}
(r1, r2, ordered)
}
/// The sing-box rule-set (source format) of the domains routed through `exit`.
pub fn rule_set(state: &State, exit: &str) -> Value {
let domains: Vec<&String> = state.domains.iter().filter(|(_, r)| r.exit == exit).map(|(d, _)| d).collect();
if domains.is_empty() {
json!({ "version": 1, "rules": [] })
} else {
json!({ "version": 1, "rules": [{ "domain_suffix": domains }] })
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ok() -> Fetch {
Fetch { status: Some(200), bytes: 1000, ..Default::default() }
}
fn dead() -> Fetch {
Fetch { status: None, error: "reset".into(), ..Default::default() }
}
fn refused() -> Fetch {
Fetch { status: Some(403), ..Default::default() }
}
fn wall() -> Fetch {
Fetch { status: Some(403), block: "cloudflare".into(), ..Default::default() }
}
/// Runs a future that never waits (the fetches here answer at once).
fn now<F: Future>(f: F) -> F::Output {
let mut f = std::pin::pin!(f);
let mut cx = std::task::Context::from_waker(std::task::Waker::noop());
match f.as_mut().poll(&mut cx) {
std::task::Poll::Ready(v) => v,
std::task::Poll::Pending => panic!("a test fetch waited"),
}
}
fn exits(tags: &[&str]) -> Vec<String> {
tags.iter().map(|s| (*s).to_owned()).collect()
}
#[test]
fn judgements_follow_upstream() {
assert_eq!(judge(&ok()), Judgement::Ok);
assert_eq!(judge(&Fetch { status: Some(404), ..Default::default() }), Judgement::Ok);
assert_eq!(judge(&Fetch { status: Some(302), location: "https://x.example/why-not-available".into(), ..Default::default() }), Judgement::Blocked);
assert_eq!(judge(&Fetch { status: Some(301), location: "https://www.x.example/".into(), ..Default::default() }), Judgement::Ok);
assert_eq!(judge(&dead()), Judgement::Dead);
assert_eq!(judge(&wall()), Judgement::Wall);
assert_eq!(judge(&Fetch { status: Some(403), block: "cloudflare-geo".into(), ..Default::default() }), Judgement::Blocked);
assert_eq!(verdict(&refused(), &ok()), "destination");
assert_eq!(verdict(&dead(), &ok()), "censor");
assert_eq!(verdict(&wall(), &refused()), "destination");
assert_eq!(verdict(&dead(), &dead()), "unreachable");
assert_eq!(verdict(&refused(), &refused()), "both-fail");
}
#[test]
fn block_pages_are_recognised() {
assert_eq!(block_page(403, "HTTP/1.1 403\r\nserver: cloudflare\r\ncf-mitigated: challenge\r\n", b""), "cloudflare");
assert_eq!(block_page(403, "", b"<span class=\"cf-error-code\">1009</span>"), "cloudflare-geo");
assert_eq!(block_page(403, "Server: CloudFront\r\n", b"<h1>Request blocked.</h1>"), "aws-waf");
assert_eq!(block_page(200, "x-datadome: 1\r\n", b""), "");
}
#[test]
fn a_walk_stops_at_the_first_exit_that_reaches() {
let answers = |tag: &str, _path: &str| match tag {
"direct" => refused(),
"a" => refused(),
_ => ok(),
};
let p = now(walk("x.example", &exits(&["direct", "a", "b", "c"]), &PATHS, false, |t: String, p: String| std::future::ready(answers(&t, &p))));
assert_eq!(p.verdict, "destination");
assert_eq!(p.exit.as_deref(), Some("b"));
assert_eq!(p.rows.len(), 3, "c is never asked");
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(ok())));
assert_eq!((p.verdict.as_str(), p.rows.len()), ("ok", 1));
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |_: String, _: String| std::future::ready(dead())));
assert_eq!((p.verdict.as_str(), p.rows.len()), ("unreachable", 4));
}
#[test]
fn robots_txt_can_decide_what_the_page_did_not() {
let p = now(walk("x.example", &exits(&["direct", "a"]), &PATHS, false, |t: String, path: String| std::future::ready(match (t.as_str(), path.as_str()) {
("direct", _) => refused(),
("a", "/") => refused(),
_ => ok(),
})));
assert_eq!((p.verdict.as_str(), p.exit.as_deref(), p.path.as_str()), ("destination", Some("a"), "/robots.txt"));
}
#[test]
fn a_stand_in_must_carry_everything_direct_gets() {
let p = now(stand_in("x.example", "a", &PATHS, |t: String, path: String| std::future::ready(if t == "a" && path == "/robots.txt" { refused() } else { ok() })));
assert_eq!(p.verdict, "blocked");
let p = now(stand_in("x.example", "a", &PATHS, |_: String, _: String| std::future::ready(ok())));
assert_eq!(p.verdict, "ok");
}
#[test]
fn recording_routes_the_domain_and_strikes_who_refused() {
let mut s = State::default();
let p = now(walk("www.x.example", &exits(&["direct", "a", "b"]), &PATHS, false, |t: String, _: String| std::future::ready(match t.as_str() {
"a" => wall(),
"b" => ok(),
_ => refused(),
})));
s.record("x.example", "www.x.example", &p, 100, 1000);
assert_eq!(s.domains["x.example"].exit, "b");
assert_eq!(s.exits["a"].strikes["x.example"].why, "wall:cloudflare");
assert!(!s.exits["a"].bad);
s.strike(&exits(&["a"]), "y.example", "refused", 200, 1000);
assert!(s.exits["a"].bad, "two domains make an exit bad");
assert_eq!(s.exits["a"].bad_by, ["x.example wall:cloudflare", "y.example refused"]);
s.strike(&[], "", "", 1150, 1000);
assert!(!s.exits["a"].bad, "a strike past the TTL stops counting");
s.forget("x.example");
assert!(s.domains.is_empty() && s.hosts.is_empty());
assert_eq!(rule_set(&s, "b"), json!({ "version": 1, "rules": [] }));
}
#[test]
fn rounds_take_one_exit_per_network_first_and_bad_ones_last() {
let mut s = State::default();
for (t, asn) in [("a", "AS1"), ("b", "AS1"), ("c", "AS2")] {
s.exits.insert(t.into(), ExitInfo { asn: Some(asn.into()), ..Default::default() });
}
s.exits.insert("d".into(), ExitInfo { bad: true, ..Default::default() });
let (r1, r2, ordered) = rounds(&exits(&["direct", "d", "a", "b", "c", "e"]), &s);
assert_eq!(r1, ["a", "c", "e"]);
assert_eq!(r2, ["b", "d"]);
assert_eq!(ordered, ["a", "b", "c", "e", "d"]);
}
#[test]
fn the_backlog_skips_what_is_known_and_keeps_counting() {
let mut s = State::default();
s.domains.insert("routed.example".into(), Route { verdict: "destination".into(), exit: "a".into(), host: "routed.example".into(), path: "/".into(), at: 0, bad: 0, tried: Vec::new() });
let counts: BTreeMap<String, (String, u64)> = [
("www.routed.example".to_owned(), ("routed.example".to_owned(), 5)),
("cdn.new.example".to_owned(), ("new.example".to_owned(), 2)),
("api.other.example".to_owned(), ("other.example".to_owned(), 7)),
]
.into();
s.queue(&counts, 10, 1000);
s.queue(&counts, 20, 1000);
assert_eq!(s.backlog.len(), 2);
assert_eq!(s.backlog["cdn.new.example"].hits, 4);
assert_eq!(s.backlog_order(20, 1000)[0], ("other.example".to_owned(), "api.other.example".to_owned()));
s.new_egress("203.0.113.9");
assert!(s.domains.is_empty());
assert_eq!(s.backlog.len(), 2, "the backlog is about the clients, not the address");
}
fn obs(d: &str, exit: &str, slow: bool) -> Observation {
Observation { domain: d.into(), host: format!("www.{d}"), exit: exit.into(), slow, peak: 1 }
}
#[test]
fn crawling_three_times_owes_a_site_an_exit_and_two_more_move_it_on() {
let mut s = State::default();
s.judge_slow(&[obs("slow.example", "direct", true), obs("fast.example", "direct", false)], 10, 3);
s.judge_slow(&[obs("slow.example", "direct", true)], 20, 3);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "direct", true)], 30, 3);
assert_eq!(s.slow_want["slow.example"].host, "www.slow.example");
s.route_slow("slow.example", "www.slow.example", "nl", vec!["nl".into()], 40);
assert!(s.slow_want.is_empty());
s.judge_slow(&[obs("slow.example", "nl", true)], 50, 3);
s.judge_slow(&[obs("slow.example", "nl", false)], 60, 3);
assert_eq!(s.domains["slow.example"].bad, 0, "a fast transfer keeps it");
s.judge_slow(&[obs("slow.example", "nl", true)], 70, 3);
s.judge_slow(&[obs("slow.example", "nl", true)], 80, 3);
assert!(!s.domains.contains_key("slow.example"));
assert_eq!(s.slow_want["slow.example"].tried, ["nl"]);
s.skip_slow("slow.example", 90, 1000);
s.judge_slow(&[obs("slow.example", "direct", true)], 100, 1);
assert!(s.slow_want.is_empty(), "skipped for a while");
}
#[test]
fn transfers_are_judged_by_their_fastest_second() {
let snap = |down: &[(&str, &str, &str, u64)]| {
json!({ "connections": down.iter().map(|(id, host, exit, d)| json!({
"id": id, "download": d, "chains": [exit], "metadata": { "host": host, "type": "mixed/mixed-in" },
})).collect::<Vec<_>>() })
};
let snaps = [
snap(&[("1", "a.example", "direct", 0), ("2", "b.example", "direct", 0)]),
snap(&[("1", "a.example", "direct", 100_000), ("2", "b.example", "direct", 400_000)]),
snap(&[("1", "a.example", "direct", 200_000), ("2", "b.example", "direct", 400_100)]),
snap(&[("1", "a.example", "direct", 300_000), ("2", "b.example", "direct", 400_200)]),
];
let out = sample_transfers(&snaps, 250_000, 150 * 1024);
assert_eq!(out, [("a.example".to_owned(), "direct".to_owned(), true, 100_000), ("b.example".to_owned(), "direct".to_owned(), false, 400_000)]);
}
#[test]
fn sites_and_local_targets() {
assert_eq!(registrable("www.example.co.uk").as_deref(), Some("example.co.uk"));
assert_eq!(registrable("foo.workers.dev").as_deref(), Some("foo.workers.dev"));
assert_eq!(registrable("co.uk"), None);
assert_eq!(site("https://accounts.spotify.com/why"), "spotify.com");
assert!(local_target("http://127.1/"));
assert!(local_target("https://192.168.0.1/admin"));
assert!(local_target("http://localhost:8080/"));
assert!(!local_target("https://example.com/"));
assert!(host_ok("www.example.com") && !host_ok("127.0.0.1") && !host_ok("example") && !host_ok("a b.com"));
}
}
+635
View File
@@ -0,0 +1,635 @@
//! AmneziaWG profiles as upstream's scripts/amneziawg_config.py prepares them: from a `.conf`,
//! a `vpn://` link (AmneziaVPN's export) or declarative settings, to the `.conf` a tunnel runs
//! (`prepare`); and that `.conf` for wireproxy-awg, a SOCKS listener in front of the tunnel
//! (`as_wireproxy`).
use std::collections::BTreeSet;
use std::io::Read;
use base64::Engine;
use serde_json::{Map, Value};
use crate::config::{AwgObfuscation, AwgProfile, AwgSettings};
use crate::wg::conf_sections;
const MAX_INPUT_BYTES: usize = 8 * 1024 * 1024;
const AWG3_SAFE_DEFAULT_MTU: &str = "1280";
const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"];
const AWG_PROTOCOL_KEYS: [&str; 4] = ["awg", "amnezia-awg", "amnezia-awg2", "amnezia-awg3"];
const AWG3_INTERFACE_KEYS: [&str; 9] = [
"headerprotectionkey",
"contentpaddingaddition",
"rekeyaftertime",
"rekeytimeout",
"rejectaftertime",
"keepalivetimeout",
"maxhandshakeattempts",
"randomtrailers",
"disablecookies",
];
/// The obfuscation's keys, normalized (lowercase, letters and digits) and as written.
const VPN_INTERFACE_FIELDS: [(&str, &str); 25] = [
("jc", "Jc"),
("jmin", "Jmin"),
("jmax", "Jmax"),
("s1", "S1"),
("s2", "S2"),
("s3", "S3"),
("s4", "S4"),
("h1", "H1"),
("h2", "H2"),
("h3", "H3"),
("h4", "H4"),
("i1", "I1"),
("i2", "I2"),
("i3", "I3"),
("i4", "I4"),
("i5", "I5"),
("headerprotectionkey", "HeaderProtectionKey"),
("contentpaddingaddition", "ContentPaddingAddition"),
("rekeyaftertime", "RekeyAfterTime"),
("rekeytimeout", "RekeyTimeout"),
("rejectaftertime", "RejectAfterTime"),
("keepalivetimeout", "KeepaliveTimeout"),
("maxhandshakeattempts", "MaxHandshakeAttempts"),
("randomtrailers", "RandomTrailers"),
("disablecookies", "DisableCookies"),
];
type Res<T> = Result<T, String>;
fn normalize(key: &str) -> String {
key.to_lowercase().chars().filter(|c| c.is_ascii_alphanumeric()).collect()
}
/// A `vpn://` link's data: URL-safe base64 of Qt's qCompress (a 4-byte length, then zlib) of
/// JSON, or of the `.conf` itself (AmneziaVPN's compact form, shaped like the JSON here).
pub fn decode_vpn_link(link: &str) -> Res<Value> {
let encoded = link.trim().strip_prefix("vpn://").ok_or("expected a self-contained vpn:// link")?;
let body = encoded.trim_end_matches('=');
if body.is_empty() || !body.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_') || encoded.len() - body.len() > 2 {
return Err("unsupported vpn:// link; API-backed text keys are not supported".into());
}
let raw = base64::engine::general_purpose::URL_SAFE_NO_PAD
.decode(body)
.map_err(|_| "unsupported vpn:// link; expected embedded base64 data, not an API-backed text key")?;
if raw.len() > MAX_INPUT_BYTES {
return Err("vpn:// payload is too large".into());
}
let mut decoded = raw.clone();
if raw.len() >= 5 {
let expected = u32::from_be_bytes([raw[0], raw[1], raw[2], raw[3]]) as usize;
let mut out = Vec::new();
let mut z = flate2::read::ZlibDecoder::new(&raw[4..]).take(MAX_INPUT_BYTES as u64 + 1);
if z.read_to_end(&mut out).is_ok() {
if out.len() > MAX_INPUT_BYTES {
return Err("decompressed vpn:// payload is too large".into());
}
if out.len() != expected {
return Err("vpn:// qCompress length header does not match payload".into());
}
decoded = out;
}
}
let text = String::from_utf8(decoded).map_err(|_| "unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key")?;
if text.trim_start().starts_with("[Interface]") && text.contains("[Peer]") {
return Ok(serde_json::json!({
"defaultContainer": "amnezia-awg",
"containers": [{ "container": "amnezia-awg", "config": text }],
}));
}
match serde_json::from_str::<Value>(&text) {
Ok(v) if v.is_object() => Ok(v),
Ok(_) => Err("invalid vpn:// configuration: expected a JSON object".into()),
Err(_) => Err("unsupported vpn:// link; expected embedded qCompress/base64 JSON, not an API-backed key".into()),
}
}
fn json_object(value: &Value, label: &str) -> Res<Map<String, Value>> {
let v = match value {
Value::String(s) => serde_json::from_str::<Value>(s).map_err(|e| format!("invalid {label} JSON: {e}"))?,
other => other.clone(),
};
match v {
Value::Object(m) => Ok(m),
_ => Err(format!("invalid {label}: expected an object")),
}
}
/// A container's payload: its last configuration and the `.conf` in it.
fn candidate_payload(value: &Value, key: &str) -> Res<(Map<String, Value>, String)> {
let payload = json_object(value, &format!("{key} protocol"))?;
let last = json_object(payload.get("last_config").unwrap_or(&Value::Object(payload.clone())), &format!("{key}.last_config"))?;
match last.get("config").and_then(Value::as_str) {
Some(c) if c.contains("[Interface]") && c.contains("[Peer]") => Ok((last.clone(), c.to_owned())),
_ => Err(format!("{key} candidate does not contain an AmneziaWG config")),
}
}
/// The AmneziaWG `.conf` of a `vpn://` export: its default container's (or `container`'s),
/// DNS placeholders filled, the obfuscation and MTU its last configuration records applied.
pub fn extract_vpn_config(data: &Value, container: Option<&str>) -> Res<String> {
let containers = data["containers"].as_array().ok_or("vpn:// configuration has no containers list")?;
struct Candidate {
id: String,
key: String,
last: Map<String, Value>,
config: String,
}
let mut candidates = Vec::new();
for item in containers {
let Some(obj) = item.as_object() else { continue };
let id = obj.get("container").and_then(Value::as_str).unwrap_or("").to_owned();
let mut protocols: Vec<(String, Value)> = obj.iter().filter(|(k, _)| AWG_PROTOCOL_KEYS.contains(&k.to_lowercase().as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
if AWG_PROTOCOL_KEYS.contains(&id.to_lowercase().as_str()) && protocols.is_empty() && (obj.contains_key("last_config") || obj.contains_key("config")) {
protocols = vec![(id.clone(), item.clone())];
}
for (key, value) in protocols {
if let Ok((last, config)) = candidate_payload(&value, &key) {
candidates.push(Candidate { id: if id.is_empty() { key.clone() } else { id.clone() }, key, last, config });
}
}
}
if candidates.is_empty() {
return Err("vpn:// configuration contains no AmneziaWG client config".into());
}
let named = |c: &Candidate, name: &str| [c.id.to_lowercase(), c.key.to_lowercase()].contains(&name.to_lowercase());
let chosen: Vec<&Candidate> = match container {
Some(want) => {
let found: Vec<&Candidate> = candidates.iter().filter(|c| named(c, want)).collect();
if found.len() != 1 {
return Err(format!("vpnContainer '{want}' matched {} AmneziaWG configs", found.len()));
}
found
}
None => {
let default: Vec<&Candidate> = data["defaultContainer"].as_str().map(|d| candidates.iter().filter(|c| named(c, d)).collect()).unwrap_or_default();
if default.len() == 1 {
default
} else if candidates.len() == 1 {
vec![&candidates[0]]
} else {
let ids: Vec<&str> = candidates.iter().map(|c| c.id.as_str()).collect();
return Err(format!("vpn:// configuration contains multiple AmneziaWG configs ({}); set vpnContainer", ids.join(", ")));
}
}
};
let c = chosen[0];
let mut config = c.config.clone();
if let Some(d) = data["dns1"].as_str().filter(|d| !d.is_empty()) {
config = config.replace("$PRIMARY_DNS", d);
}
if let Some(d) = data["dns2"].as_str().filter(|d| !d.is_empty()) {
config = config.replace("$SECONDARY_DNS", d);
}
if config.contains("$PRIMARY_DNS") || config.contains("$SECONDARY_DNS") {
return Err("vpn:// configuration contains unresolved DNS placeholders".into());
}
let last: Vec<(String, &Value)> = c.last.iter().map(|(k, v)| (normalize(k), v)).collect();
for (norm, key) in VPN_INTERFACE_FIELDS {
let Some((_, value)) = last.iter().find(|(k, _)| k == norm) else { continue };
let text = match value {
Value::Null => continue,
Value::String(s) if s.is_empty() => continue,
Value::Bool(b) if matches!(norm, "randomtrailers" | "disablecookies") => if *b { "on".into() } else { "off".into() },
Value::String(s) => s.clone(),
other => other.to_string(),
};
config = set_interface_value(&config, key, &text)?;
}
for (field, key) in [("mtu", "MTU"), ("port", "ListenPort")] {
let text = match c.last.get(field) {
None | Some(Value::Null) => continue,
Some(Value::String(s)) if s.is_empty() => continue,
Some(Value::String(s)) => s.clone(),
Some(other) => other.to_string(),
};
config = set_interface_value(&config, key, &text)?;
}
apply_awg3_mtu_default(&config)
}
/// Python's `str.splitlines()` and `"\n".join(...) + "\n"`, which upstream's rewrites use.
fn lines(config: &str) -> Vec<String> {
crate::links::py::splitlines(config).into_iter().map(str::to_owned).collect()
}
fn joined(lines: &[String]) -> String {
let mut s = lines.join("\n");
s.push('\n');
s
}
fn key_line(line: &str, key: &str) -> bool {
let t = line.trim_start();
t.len() >= key.len() && t[..key.len()].eq_ignore_ascii_case(key) && t[key.len()..].trim_start().starts_with('=')
}
/// `key = value` in `[Interface]`: the first such line replaced, or one added at its end.
fn set_interface_value(config: &str, key: &str, value: &str) -> Res<String> {
let mut ls = lines(config);
let start = ls.iter().position(|l| l.trim().eq_ignore_ascii_case("[interface]")).ok_or("configuration has no [Interface] section")?;
let end = (start + 1..ls.len()).find(|i| ls[*i].trim().starts_with('[')).unwrap_or(ls.len());
match (start + 1..end).find(|i| key_line(&ls[*i], key)) {
Some(i) => ls[i] = format!("{key} = {value}"),
None => ls.insert(end, format!("{key} = {value}")),
}
Ok(joined(&ls))
}
fn interface_keys(config: &str) -> BTreeSet<String> {
conf_sections(config).into_iter().filter(|(n, _)| n == "interface").flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| normalize(&k))).collect()
}
/// AWG 3's per-packet padding with awg-quick's 1420 black-holes larger packets: without an
/// MTU of its own, such a profile gets the official clients' 1280.
fn apply_awg3_mtu_default(config: &str) -> Res<String> {
let keys = interface_keys(config);
if keys.contains("mtu") || !AWG3_INTERFACE_KEYS.iter().any(|k| keys.contains(*k)) {
return Ok(config.to_owned());
}
set_interface_value(config, "MTU", AWG3_SAFE_DEFAULT_MTU)
}
/// Section headers as awg-quick reads them ("[Peer] # home" opens a Peer section).
fn normalize_headers(config: &str) -> String {
config
.split('\n')
.map(|line| match line.split('#').next().unwrap_or("").trim().to_lowercase().as_str() {
"[interface]" => "[Interface]".to_owned(),
"[peer]" => "[Peer]".to_owned(),
_ => line.to_owned(),
})
.collect::<Vec<_>>()
.join("\n")
}
/// A secret given inline or in a file: exactly one, one line.
fn secret(inline: Option<&str>, file: Option<&str>, label: &str, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
let value = match (inline, file) {
(Some(v), None) => v.to_owned(),
(None, Some(f)) => read(f)?.trim().to_owned(),
_ => return Err(format!("set exactly one of {label} or {label}File")),
};
if value.is_empty() || value.contains(['\n', '\r']) {
return Err(format!("{label} must be one non-empty line"));
}
Ok(value)
}
fn range_text(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
/// The obfuscation given inline, with `obfuscationFile`'s secret fields merged in (a field
/// given both ways is refused, as upstream refuses it).
fn obfuscation_values(o: &AwgObfuscation, file: Option<&str>, read: &dyn Fn(&str) -> Res<String>) -> Res<Vec<(String, String)>> {
let mut values: Vec<(String, String)> = Vec::new();
let mut put = |name: &str, v: Option<String>| {
if let Some(v) = v {
values.push((name.to_owned(), v));
}
};
put("jc", o.jc.map(|v| v.to_string()));
put("jmin", o.jmin.map(|v| v.to_string()));
put("jmax", o.jmax.map(|v| v.to_string()));
put("s1", o.s1.map(|v| v.to_string()));
put("s2", o.s2.map(|v| v.to_string()));
put("s3", o.s3.map(|v| v.to_string()));
put("s4", o.s4.map(|v| v.to_string()));
put("h1", o.h1.as_ref().map(range_text));
put("h2", o.h2.as_ref().map(range_text));
put("h3", o.h3.as_ref().map(range_text));
put("h4", o.h4.as_ref().map(range_text));
put("i1", o.i1.clone());
put("i2", o.i2.clone());
put("i3", o.i3.clone());
put("i4", o.i4.clone());
put("i5", o.i5.clone());
put("contentpaddingaddition", o.content_padding_addition.as_ref().map(range_text));
put("rekeyaftertime", o.rekey_after_time.as_ref().map(range_text));
put("rekeytimeout", o.rekey_timeout.as_ref().map(range_text));
put("rejectaftertime", o.reject_after_time.as_ref().map(range_text));
put("keepalivetimeout", o.keepalive_timeout.as_ref().map(range_text));
put("maxhandshakeattempts", o.max_handshake_attempts.as_ref().map(range_text));
put("randomtrailers", o.random_trailers.map(|b| if b { "on".into() } else { "off".into() }));
put("disablecookies", o.disable_cookies.map(|b| if b { "on".into() } else { "off".into() }));
if let Some(f) = file {
let text = read(f)?;
let secret: Map<String, Value> = match serde_json::from_str::<Value>(&text) {
Ok(Value::Object(m)) => m,
Ok(_) => return Err("obfuscationFile must contain a JSON object".into()),
Err(_) => return Err("cannot read or decode obfuscationFile".into()),
};
for (key, value) in secret {
let norm = normalize(&key);
if !VPN_INTERFACE_FIELDS.iter().any(|(n, _)| *n == norm) {
return Err("obfuscationFile contains an unsupported field".into());
}
if value.is_null() {
continue;
}
if values.iter().any(|(n, _)| *n == norm) || (norm == "headerprotectionkey" && (o.header_protection_key.is_some() || o.header_protection_key_file.is_some())) {
return Err(format!("obfuscationFile field '{key}' has multiple sources"));
}
let unsigned = value.as_u64().is_some();
let text = match norm.as_str() {
"jc" | "jmin" | "jmax" | "s1" | "s2" | "s3" | "s4" if unsigned => value.to_string(),
"randomtrailers" | "disablecookies" => match value.as_bool() {
Some(b) => (if b { "on" } else { "off" }).to_owned(),
None => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
},
"i1" | "i2" | "i3" | "i4" | "i5" | "headerprotectionkey" => match value.as_str() {
Some(s) if !s.trim().is_empty() && !s.contains(['\n', '\r', '\0']) => s.to_owned(),
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
},
"h1" | "h2" | "h3" | "h4" | "contentpaddingaddition" | "rekeyaftertime" | "rekeytimeout" | "rejectaftertime" | "keepalivetimeout" | "maxhandshakeattempts" => {
match &value {
Value::Number(_) if unsigned => value.to_string(),
Value::String(s) if s.split_once('-').map_or(s.chars().all(|c| c.is_ascii_digit()) && !s.is_empty(), |(a, b)| !a.is_empty() && !b.is_empty() && (a.to_owned() + b).chars().all(|c| c.is_ascii_digit())) || s == "(off)" => s.clone(),
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
}
}
_ => return Err(format!("obfuscationFile field '{key}' has an invalid value")),
};
values.push((norm, text));
}
}
Ok(values)
}
/// A `.conf` from declarative settings.
pub fn render_settings(s: &AwgSettings, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
if s.addresses.is_empty() {
return Err("declarative settings require at least one address".into());
}
if s.peers.is_empty() {
return Err("declarative settings require at least one peer".into());
}
let mut out = vec!["[Interface]".to_owned()];
out.push(format!("PrivateKey = {}", secret(s.private_key.as_deref(), s.private_key_file.as_deref(), "privateKey", read)?));
for a in &s.addresses {
out.push(format!("Address = {a}"));
}
if !s.dns.is_empty() {
out.push(format!("DNS = {}", s.dns.join(",")));
}
if let Some(p) = s.listen_port {
out.push(format!("ListenPort = {p}"));
}
if let Some(m) = s.mtu {
out.push(format!("MTU = {m}"));
}
let values = obfuscation_values(&s.obfuscation, s.obfuscation_file.as_deref(), read)?;
for (norm, key) in VPN_INTERFACE_FIELDS {
if norm == "headerprotectionkey" {
continue;
}
if let Some((_, v)) = values.iter().find(|(n, _)| n == norm) {
out.push(format!("{key} = {v}"));
}
}
let from_file = values.iter().find(|(n, _)| n == "headerprotectionkey").map(|(_, v)| v.clone());
let o = &s.obfuscation;
if o.header_protection_key.is_some() || o.header_protection_key_file.is_some() {
out.push(format!("HeaderProtectionKey = {}", secret(o.header_protection_key.as_deref(), o.header_protection_key_file.as_deref(), "headerProtectionKey", read)?));
} else if let Some(v) = from_file {
out.push(format!("HeaderProtectionKey = {v}"));
}
for peer in &s.peers {
if peer.public_key.is_empty() || peer.allowed_ips.is_empty() {
return Err("each peer requires publicKey and allowedIPs".into());
}
out.extend([String::new(), "[Peer]".into(), format!("PublicKey = {}", peer.public_key)]);
if peer.preshared_key.is_some() || peer.preshared_key_file.is_some() {
out.push(format!("PresharedKey = {}", secret(peer.preshared_key.as_deref(), peer.preshared_key_file.as_deref(), "presharedKey", read)?));
}
out.push(format!("AllowedIPs = {}", peer.allowed_ips.join(",")));
if let Some(e) = &peer.endpoint {
out.push(format!("Endpoint = {e}"));
}
if let Some(k) = &peer.persistent_keepalive {
out.push(format!("PersistentKeepalive = {}", range_text(k)));
}
if let Some(a) = peer.advanced_security {
out.push(format!("AdvancedSecurity = {}", if a { "on" } else { "off" }));
}
}
Ok(joined(&out))
}
/// The first peer's `Endpoint` replaced by `endpoint` (host:port, IPv6 in brackets).
pub fn override_endpoint(config: &str, endpoint: &str) -> Res<String> {
let mut done = false;
let out: Vec<String> = config
.split('\n')
.map(|line| {
if !done && key_line(line, "Endpoint") {
let value = line.split_once('=').map(|(_, v)| v.trim()).unwrap_or("");
if value.rsplit_once(':').is_some_and(|(h, p)| !h.is_empty() && !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()) && !value.contains(char::is_whitespace)) {
done = true;
let prefix = &line[..line.find('=').unwrap() + 1];
return format!("{prefix} {endpoint}");
}
}
line.to_owned()
})
.collect();
if !done {
return Err("configuration has no Endpoint to override".into());
}
Ok(out.join("\n"))
}
/// Upstream's checks: no control characters a reader could take for a line end, sections
/// [Interface] (exactly one) and [Peer] only, alone on their lines, and no wg-quick hooks
/// unless allowed.
pub fn validate(config: &str, allow_hooks: bool) -> Res<()> {
let bytes: Vec<char> = config.chars().collect();
for (i, c) in bytes.iter().enumerate() {
let lone_cr = *c == '\r' && bytes.get(i + 1) != Some(&'\n');
let bad = matches!(*c as u32, 0x00..=0x08 | 0x0b | 0x0c | 0x0e..=0x1f | 0x7f | 0x85 | 0x2028 | 0x2029);
if bad || lone_cr {
return Err("configuration contains control characters".into());
}
}
let lowered = config.to_lowercase();
if !lowered.contains("[interface]") || !lowered.contains("[peer]") {
return Err("configuration requires [Interface] and [Peer] sections".into());
}
let mut interfaces = 0;
for line in config.split('\n') {
let stripped = line.trim();
if !stripped.split('#').next().unwrap_or("").trim().starts_with('[') {
continue;
}
let lower = stripped.to_lowercase();
if lower != "[interface]" && lower != "[peer]" {
return Err(format!("unexpected section header {:?}: only [Interface] and [Peer], alone on their line", stripped.chars().take(40).collect::<String>()));
}
interfaces += usize::from(lower == "[interface]");
}
if interfaces != 1 {
return Err("configuration needs exactly one [Interface] section".into());
}
if !allow_hooks {
for line in config.split('\n') {
let key = line.split('#').next().unwrap_or("").split('=').next().unwrap_or("").trim().to_lowercase();
if !key.is_ascii() {
return Err("configuration has a key with non-ASCII characters".into());
}
if FORBIDDEN_WG_QUICK_KEYS.contains(&key.as_str()) {
return Err(format!("configuration contains privileged wg-quick directive '{key}'; set allowConfigHooks = true only for trusted input"));
}
}
}
Ok(())
}
/// A profile's `.conf`, from whichever source it has, as upstream's `prepare` makes it.
pub fn prepare(p: &AwgProfile, read: &dyn Fn(&str) -> Res<String>) -> Res<String> {
let config = match (&p.config, &p.config_file, &p.vpn, &p.vpn_file, &p.settings) {
(Some(text), None, None, None, None) => text.clone(),
(None, Some(f), None, None, None) => read(f)?,
(None, None, Some(link), None, None) => extract_vpn_config(&decode_vpn_link(link)?, p.vpn_container.as_deref())?,
(None, None, None, Some(f), None) => extract_vpn_config(&decode_vpn_link(&read(f)?)?, p.vpn_container.as_deref())?,
(None, None, None, None, Some(s)) => render_settings(s, read)?,
_ => return Err("a profile needs exactly one of config, configFile, vpn, vpnFile and settings".into()),
};
if config.len() > MAX_INPUT_BYTES {
return Err("the configuration is too large".into());
}
let mut config = apply_awg3_mtu_default(&normalize_headers(&config))?;
if let Some(e) = &p.endpoint {
config = override_endpoint(&config, e)?;
}
validate(&config, p.allow_config_hooks)?;
Ok(config)
}
/// A wireproxy-awg configuration: the profile served as a SOCKS5 listener on `socks_address`,
/// with `login`. Only [Interface] and [Peer] are kept, wg-quick's keys dropped.
pub fn as_wireproxy(config: &str, socks_address: &str, login: Option<(&str, &str)>) -> Res<String> {
const LISTS: [&str; 3] = ["address", "dns", "allowedips"];
const DROPPED: [&str; 7] = ["preup", "postup", "predown", "postdown", "saveconfig", "table", "fwmark"];
let mut out: Vec<String> = Vec::new();
for (name, pairs) in conf_sections(config) {
if name != "interface" && name != "peer" {
continue;
}
if !out.is_empty() {
out.push(String::new());
}
out.push(if name == "interface" { "[Interface]".into() } else { "[Peer]".into() });
let mut lists: Vec<(String, Vec<String>)> = Vec::new();
let mut section: Vec<String> = Vec::new();
for (key, value) in pairs {
if DROPPED.contains(&key.as_str()) {
continue;
}
if LISTS.contains(&key.as_str()) {
let items = value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
match lists.iter_mut().find(|(k, _)| *k == key) {
Some((_, l)) => l.extend(items),
None => {
lists.push((key.clone(), items.collect()));
section.push(key);
}
}
} else {
section.push(format!("{key} = {value}"));
}
}
for line in section {
match lists.iter().find(|(k, _)| *k == line) {
Some((k, l)) => out.push(format!("{k} = {}", l.join(","))),
None => out.push(line),
}
}
}
out.extend([String::new(), "[Socks5]".into(), format!("BindAddress = {socks_address}")]);
if let Some((user, password)) = login {
let ok = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'));
if !ok(user) || !ok(password) {
return Err("the SOCKS login must be letters, digits, dot, dash and underscore".into());
}
out.extend([format!("Username = {user}"), format!("Password = {password}")]);
}
Ok(joined(&out))
}
#[cfg(test)]
mod tests {
use super::*;
// Made by upstream's encode_vpn_link (scripts/amneziawg_config.py), and a JSON export with
// DNS placeholders and a last configuration, as AmneziaVPN shares one.
const LINK: &str = "vpn://AAAEX3jalVNdb-IwEPwryM9cwPmQqkh9qNpTA72iSJwQB0HIJOZqNTiRbSgp4r93dxO43sPpVCVKZmbXa3vsPbG80k4oLY1l8fL0h7KYiZ2W70p8E2-_WZ_hNz6xcQ6REPh4pzRAPiQsjoAjxFMOiIDfgQQVjgAVH0EAIEAQdtVKYd0aJt8qmIWdMtbijMUZW460k2YrcrnKMp0adRBOPsmmd9sTjzO7ebxx__s_P9zdwti7ojDSWhjIh96Nxz1_EPigP0ymqHn0AB_nQEMEsEnKJiyOgCPEUw6IgN-BBBUcm6CCRZMAQIAg7KrBu0ylNLSN_aZUebuL3J81xW7W_JhPylwvylzx98V87C_mI_d37BftoiyrN1mMUtzI0KNnMOz34niAK_mui7pS2uEyhgEEOQ-8KI74jY_hFI5aWSe1e5KyFqU6SMyMcH2sn7GXyrqJ2Emy_lBrTx7Fri4lBevKOAhQLaB5qaDOWtWUfPGUMrtQDae1fpUNJXzptLCIleYgzbreb641vuQVLdm-XgeTIFr7YNUWxGXGrhZSmFxkKxx5dQoKyHpNXlEdcAtTxzmxsCVwVTobOi6OxKOWTzmxjvifSNJGeEvaSGtiEhAJWhJeZjtDw-BJYMvhSQB1RmiLGjheuQoi-6IGXdmfL8oUqTCuue_ay5m9PJ9XfVbIrdiX7v6fPV9ImxtVO1Vhqz83vVk6AflyRUD7dEEwX1vq9baR2PkDyhJUgw";
const LINK2: &str = "vpn://AAACXnichVLvb4IwEP1XSLOPDinIpiR-MGoUnY5oYvyBMRXq0gSKgapTwv--O2BZ9mVLafreu-v1Lo-cBIlUTEieZsTRdvkPB0pYLPlDsGd2-yANoHA4Wk4ilqkDJJ4EcpL7pCI-MJ_sXKl4emIB3_u-9FJxZYpP-V3ramy0yo6jtvrvnA16XbjbC8OUZxlcpIbe1qluNi0T9MF8CdqTt3BnvcXmALShPS2H_ff5oOaQNAkgp4UgFrIsUWL2CdhGvKSASmDWYIwKRYAKvjS2AFgIWnU1-HYe52k52-UYiaAaLTBX9zBe3d_W8yiQ2ygQ9LFdT8zt2lW_Y5tytChKbjx0PZzO0MvVNBqa4zSxk6EMz4mQCtswLAhSaum2Y9O2iWEP7BKZ4lJNOT-zSFw5ZtrYHxjlk1hdKjOo9fpSSZOgUmyfFGjmOUkVulfWJEWxBy3kJ3aJVP-PfyCUGUW5o5erlkyUaKsDfZrfmxRfDVi3BA";
const EXTRACTED: &str = "[Interface]\nPrivateKey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\nAddress = 10.8.1.2/32\nDNS = 1.1.1.1\nJc = 4\nJmin = 10\nJmax = 50\nS1 = 0\nS2 = 0\nH1 = 1\nH2 = 2\nH3 = 3\nH4 = 4\n\nListenPort = 51820\n[Peer]\nPublicKey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = 203.0.113.5:51820\nPersistentKeepalive = 25\n";
#[test]
fn vpn_links_extract_as_upstreams_do() {
assert_eq!(extract_vpn_config(&decode_vpn_link(LINK).unwrap(), None).unwrap(), EXTRACTED);
let two = extract_vpn_config(&decode_vpn_link(LINK2).unwrap(), None).unwrap();
assert!(two.contains("DNS = 9.9.9.9, 149.112.112.112\n"), "{two}");
assert!(two.contains("Jc = 5\n") && two.contains("MTU = 1376\n"), "{two}");
assert!(decode_vpn_link("vpn://short.key").is_err());
assert!(decode_vpn_link("https://x").is_err());
}
#[test]
fn wireproxy_as_upstreams() {
let w = as_wireproxy(EXTRACTED, "127.0.0.1:18700", Some(("hop", "pw-123"))).unwrap();
assert_eq!(
w,
"[Interface]\nprivatekey = aGVsbG8taGVsbG8taGVsbG8taGVsbG8taGVsbG8tMDA=\naddress = 10.8.1.2/32\ndns = 1.1.1.1\njc = 4\njmin = 10\njmax = 50\n\
s1 = 0\ns2 = 0\nh1 = 1\nh2 = 2\nh3 = 3\nh4 = 4\nlistenport = 51820\n\n[Peer]\npublickey = c2VydmVyLXNlcnZlci1zZXJ2ZXItc2VydmVyLXNlcnY=\n\
allowedips = 0.0.0.0/0,::/0\nendpoint = 203.0.113.5:51820\npersistentkeepalive = 25\n\n[Socks5]\nBindAddress = 127.0.0.1:18700\nUsername = hop\nPassword = pw-123\n"
);
assert!(as_wireproxy(EXTRACTED, "127.0.0.1:1", Some(("hop", "a b"))).is_err());
}
fn read(_: &str) -> Res<String> {
Err("no files here".into())
}
#[test]
fn prepare_checks_and_overrides() {
let mut p = AwgProfile { config: Some(EXTRACTED.into()), endpoint: Some("198.51.100.9:443".into()), ..Default::default() };
let c = prepare(&p, &read).unwrap();
assert!(c.contains("Endpoint = 198.51.100.9:443"), "{c}");
p.config = Some(format!("{EXTRACTED}PostUp = calc.exe\n"));
p.endpoint = None;
assert!(prepare(&p, &read).unwrap_err().contains("wg-quick directive"));
p.config = Some(EXTRACTED.replace("[Peer]", "[Peer]\r[Interface]"));
assert!(prepare(&p, &read).unwrap_err().contains("control"));
p.config = None;
p.vpn = Some(LINK.into());
assert_eq!(prepare(&p, &read).unwrap(), EXTRACTED);
// AWG 3 keys without an MTU: 1280.
p.vpn = None;
p.config = Some(EXTRACTED.replace("H4 = 4", "H4 = 4\nRandomTrailers = on"));
assert!(prepare(&p, &read).unwrap().contains("MTU = 1280"));
}
#[test]
fn settings_render() {
let s: AwgSettings = serde_json::from_value(serde_json::json!({
"addresses": ["10.9.0.2/32"],
"privateKey": "PRIV",
"obfuscation": { "jc": 3, "h1": "100-200", "randomTrailers": true },
"peers": [{ "publicKey": "PUB", "allowedIPs": ["0.0.0.0/0"], "endpoint": "198.51.100.1:51820", "persistentKeepalive": 25 }],
}))
.unwrap();
let c = render_settings(&s, &read).unwrap();
assert_eq!(
c,
"[Interface]\nPrivateKey = PRIV\nAddress = 10.9.0.2/32\nJc = 3\nH1 = 100-200\nRandomTrailers = on\n\n[Peer]\nPublicKey = PUB\nAllowedIPs = 0.0.0.0/0\nEndpoint = 198.51.100.1:51820\nPersistentKeepalive = 25\n"
);
}
}
+8 -8
View File
@@ -73,15 +73,15 @@ impl Source {
return None;
}
let rel = entry.strip_prefix(self.strip.as_str())?;
if let Some(files) = &self.files {
if !files.contains_key(rel) {
return None;
}
if let Some(files) = &self.files
&& !files.contains_key(rel)
{
return None;
}
if let Some(include) = &self.include {
if !matches(include, rel) {
return None;
}
if let Some(include) = &self.include
&& !matches(include, rel)
{
return None;
}
if matches(&self.exclude, rel) {
return None;
+3 -2
View File
@@ -9,8 +9,9 @@ use serde::{Deserialize, Serialize};
pub struct KillSwitch {
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
/// and after it fails. Windows Filtering Platform filters do it, so it holds even while
/// the service itself is stopped, until `proxy-ctl killswitch off`.
/// and after it fails. Windows Filtering Platform filters in the service's own session do
/// 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 direct_fallbacks: bool,
pub allowed_subnets: Vec<String>,
+1 -1
View File
@@ -21,7 +21,7 @@ pub use misc::*;
pub use privilege::privileged_changes;
pub use proxy::*;
pub use tunnels::*;
pub use validate::{Issue, Severity, validate};
pub use validate::{Issue, Severity, path_name_ok, validate};
pub use zapret::*;
use serde::{Deserialize, Serialize};
+234 -10
View File
@@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::{Backend, Config, GroupStrategy, Selection, ZapretEngine};
use super::{Backend, Config, GroupStrategy, Selection, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -50,11 +50,20 @@ fn tag_pattern_ok(tag: &str) -> bool {
/// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub(crate) fn path_name_ok(name: &str) -> bool {
pub fn path_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
&& !windows_device(name)
}
/// CON, NUL, COM1 and the rest: on Windows a file named so (whatever its extension) is the
/// device.
fn windows_device(name: &str) -> bool {
let stem = name.split('.').next().unwrap_or("").to_ascii_uppercase();
matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.as_bytes()[3].is_ascii_digit())
}
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
@@ -72,6 +81,20 @@ fn profile_name_ok(name: &str) -> bool {
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// A host name, an IPv4 address or a bracketless IPv6 one.
fn ssh_host_ok(host: &str) -> bool {
if host.parse::<std::net::IpAddr>().is_ok() {
return true;
}
!host.is_empty()
&& host.len() <= 253
&& host.split('.').all(|l| !l.is_empty() && l.len() <= 63 && !l.starts_with('-') && l.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_'))
}
fn ssh_user_ok(user: &str) -> bool {
!user.is_empty() && !user.starts_with('-') && user.chars().all(|c| c.is_alphanumeric() || matches!(c, '.' | '_' | '-' | '@' | '$'))
}
fn count_some(values: &[bool]) -> usize {
values.iter().filter(|v| **v).count()
}
@@ -85,14 +108,48 @@ pub fn validate(cfg: &Config) -> Vec<Issue> {
per_app(cfg, &mut v);
inbounds(cfg, &mut v);
ports(cfg, &mut v);
not_ported(cfg, &mut v);
let mut issues = v.0;
issues.sort_by_key(|i| i.severity != Severity::Error);
issues
}
/// What upstream runs and this port does not yet: said, never taken silently. (The kill switch
/// above all: on, it would otherwise look like protection that is not there.)
fn not_ported(cfg: &Config, v: &mut Issues) {
const IGNORED: &str = "is not on Windows yet: this release ignores it";
if cfg.kill_switch.enable {
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 [
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
] {
if on {
v.warn(path, format!("{what} {IGNORED}"));
}
}
let z = &cfg.zapret;
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");
}
}
fn proxy(cfg: &Config, v: &mut Issues) {
let p = &cfg.proxy;
let sing_box = p.backend.runs_sing_box();
// Listen addresses reach other programs' configs and command lines (Tor's torrc, ssh's -D,
// tg-ws-proxy's --host): an IP address, nothing else.
for (path, address) in [
("proxy.listener.address", &p.listener.address),
("sshProxy.listener.address", &cfg.ssh_proxy.listener.address),
("tgWsProxy.listener.address", &cfg.tg_ws_proxy.listener.address),
] {
if address.parse::<std::net::IpAddr>().is_err() {
v.error(path, format!("'{address}' is not an IP address"));
}
}
let mut seen = BTreeSet::new();
for (i, ob) in p.outbounds.iter().enumerate() {
@@ -241,12 +298,14 @@ fn proxy(cfg: &Config, v: &mut Issues) {
if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend");
}
if p.auto_proxy.slow_below_kibps > 0 && p.auto_proxy.enable && p.selection == Selection::First {
v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\"");
}
// Upstream samples transfers through the Clash API, which "first" selection leaves off
// there; here it is always on, so slow sites are routed whatever the selection.
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}
if p.enable && p.backend == Backend::Xray {
xray_backend(cfg, v);
}
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");
}
@@ -274,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) {
let proxy_on = cfg.proxy.enable;
@@ -371,6 +467,23 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
if s.server.user.is_none() {
v.error("sshProxy.server.user", "the SSH tunnel needs a login user");
}
// They reach ssh's command line (as SYSTEM on Windows): a host name or address and a
// login name, nothing that could read as an option or carry another line.
if let Some(host) = &s.server.host
&& !ssh_host_ok(host)
{
v.error("sshProxy.server.host", "a host name or an IP address");
}
if let Some(user) = &s.server.user
&& !ssh_user_ok(user)
{
v.error("sshProxy.server.user", "a login name: letters, digits, '.', '_', '-' and '@', not starting with '-'");
}
for (i, key) in s.host_key.iter().enumerate() {
if key.chars().any(char::is_control) {
v.error(format!("sshProxy.hostKey.{i}"), "a host key is one line");
}
}
v.requires(s.as_outbound, proxy_on, "sshProxy.asOutbound", "sshProxy.asOutbound", "proxy.enable = true");
if s.strict_host_key_checking == crate::config::StrictHostKeyChecking::Yes
&& s.known_hosts_file.is_none()
@@ -396,13 +509,14 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
}
let wl = &cfg.whitelist_bypass;
// Checked on or off: `proxy-ctl wl` names files after them either way.
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
@@ -416,6 +530,26 @@ fn tunnels(cfg: &Config, v: &mut Issues) {
fn zapret(cfg: &Config, v: &mut Issues) {
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 {
return;
}
@@ -428,6 +562,20 @@ fn zapret(cfg: &Config, v: &mut Issues) {
} else if !names.insert(rule.name.as_str()) {
v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name));
}
// Its lists are list-<name>.txt and ipset-<name>.txt beside the release's own.
const RELEASE_LISTS: [&str; 9] = ["general", "general-user", "google", "exclude", "exclude-user", "all", "instagram", "soundcloud", "twitter"];
if RELEASE_LISTS.contains(&rule.name.as_str()) {
v.error(format!("{path}.name"), format!("'{}' is the name of one of zapret's own lists", rule.name));
}
if rule.default_domains.iter().any(|d| matches!(d, ZapretDefaultDomains::Instagram | ZapretDefaultDomains::Soundcloud | ZapretDefaultDomains::Twitter)) {
v.error(format!("{path}.defaultDomains"), "Flowseal's Windows release has no instagram, soundcloud or twitter list");
}
if matches!(rule.preset, Some(ZapretPreset::Instagram | ZapretPreset::Soundcloud | ZapretPreset::Twitter)) {
v.error(format!("{path}.preset"), "Flowseal's Windows release has no instagram, soundcloud or twitter profiles");
}
if !rule.domains.is_empty() && rule.preset.is_none() && rule.default_domains.is_empty() && rule.nfqws_args.is_empty() {
v.error(&path, "a list with domains needs preset, defaultDomains or nfqwsArgs, for its strategy");
}
if rule.config_name.is_some() && !rule.nfqws_args.is_empty() {
v.error(&path, "configName cannot be used with nfqwsArgs");
}
@@ -661,6 +809,33 @@ mod tests {
use super::*;
use crate::config::{Group, Outbound, RoutingRule};
#[test]
fn names_are_plain_file_names_and_never_devices() {
for ok in ["laptop", "wl", "a.b_c-1", "COM", "console", "lpt10", "nul-ish"] {
assert!(path_name_ok(ok), "{ok}");
}
for bad in ["", ".hidden", "a/b", r"a\b", "C:x", "..", "CON", "con.txt", "Nul", "PRN", "aux.json", "COM1", "lpt9.link"] {
assert!(!path_name_ok(bad), "{bad}");
}
}
#[test]
fn zapret2_extra_ports_are_ports() {
let mut cfg = Config::default();
cfg.zapret.zapret2.ports.extra_tcp = vec![serde_json::json!(8443), serde_json::json!("50000-50099"), serde_json::json!("443\n--lua-init=@x.lua")];
cfg.zapret.zapret2.ports.udp = Some("443,590:600".into());
let errs = errors(&cfg);
assert_eq!(errs.iter().filter(|e| e.starts_with("zapret.zapret2.ports")).count(), 1, "{errs:?}");
assert!(crate::zapret2::port_spec_ok("1-65535") && !crate::zapret2::port_spec_ok("0") && !crate::zapret2::port_spec_ok("9-1") && !crate::zapret2::port_spec_ok("443 x"));
}
#[test]
fn whitelist_bypass_names_are_checked_while_it_is_off() {
let mut cfg = Config::default();
cfg.whitelist_bypass.creators.insert(r"C:\Windows\x".into(), serde_json::from_value(serde_json::json!({ "platform": "wbstream" })).unwrap());
assert!(errors(&cfg).iter().any(|e| e.starts_with("whitelistBypass.")), "{:?}", errors(&cfg));
}
fn errors(cfg: &Config) -> Vec<String> {
validate(cfg)
.into_iter()
@@ -678,6 +853,55 @@ mod tests {
assert_eq!(errors(&Config::default()), Vec::<String>::new());
}
#[test]
fn listen_addresses_are_ip_addresses() {
let mut cfg = Config::default();
assert!(!errors(&cfg).iter().any(|e| e.contains("listener.address")));
cfg.proxy.listener.address = "127.0.0.1\nClientTransportPlugin x exec calc.exe".into();
cfg.tg_ws_proxy.listener.address = "::".into();
let errs = errors(&cfg);
assert!(errs.iter().any(|e| e.starts_with("proxy.listener.address:")), "{errs:?}");
assert!(!errs.iter().any(|e| e.starts_with("tgWsProxy.listener.address:")), "{errs:?}");
}
#[test]
fn ssh_host_and_user_cannot_be_options() {
let mut cfg = Config::default();
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.strict_host_key_checking = crate::config::StrictHostKeyChecking::No;
for (host, user, bad) in [
("vps.example", "me", None),
("192.0.2.7", "me.you", None),
("2001:db8::1", "me", None),
("-oProxyCommand=calc.exe", "me", Some("sshProxy.server.host")),
("vps.example", "-oProxyCommand=calc.exe", Some("sshProxy.server.user")),
("vps.example x", "me", Some("sshProxy.server.host")),
("vps.example", "me\nx", Some("sshProxy.server.user")),
] {
cfg.ssh_proxy.server.host = Some(host.into());
cfg.ssh_proxy.server.user = Some(user.into());
let errs = errors(&cfg);
match bad {
None => assert!(!errs.iter().any(|e| e.starts_with("sshProxy.server")), "{host} {user}: {errs:?}"),
Some(p) => assert!(errs.iter().any(|e| e.starts_with(&format!("{p}:"))), "{host} {user}: {errs:?}"),
}
}
}
#[test]
fn what_is_not_ported_is_said() {
let quiet: Vec<String> = validate(&Config::default()).into_iter().filter(|i| i.message.contains("not on Windows yet")).map(|i| i.path).collect();
assert!(quiet.is_empty(), "{quiet:?}");
let mut cfg = Config::default();
cfg.kill_switch.enable = true;
cfg.zapret.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();
// Both are ported: the kill switch says how it differs, the TUN beside zapret nothing.
assert!(paths.is_empty(), "{paths:?}");
assert!(validate(&cfg).iter().any(|i| i.path == "killSwitch.enable" && i.message.contains("not from boot")));
}
#[test]
fn outbound_tags_are_unique_and_not_builtin() {
let mut cfg = Config::default();
+3
View File
@@ -4,12 +4,15 @@
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here
//! touches the network, the file system or processes; the service does that.
pub mod autoproxy;
pub mod awg;
pub mod components;
pub mod config;
pub mod derived;
pub mod duration;
pub mod links;
pub mod render;
pub mod warp;
pub mod wg;
pub mod zapret;
pub mod zapret2;
@@ -0,0 +1,105 @@
//! autoProxy in sing-box's config, as upstream's start script adds it: a loopback listener
//! per exit (direct first) that the prober fetches through, pinned to that exit; and per exit
//! a local rule-set of the domains learned blocked directly, routed through it after every
//! rule of the user's. sing-box reloads a rule-set file when it changes, so what the prober
//! learns takes effect without a restart.
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::outbounds::Inventory;
use super::{Input, RouteMode};
use crate::autoproxy::DIRECT;
/// One exit the prober fetches through.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProbeExit {
pub tag: String,
/// Its loopback listener.
pub port: u16,
/// Its rule-set's tag and file (none for direct: nothing is routed there).
pub rule_set: Option<String>,
pub path: Option<String>,
}
fn inbound(i: usize) -> String {
format!("probe-in-{i}")
}
/// direct, then the exits that are not disabled, `maxExits` in all. The state is kept by tag,
/// so an index that shifts is harmless.
pub fn probe_exits(input: &Input, inv: &Inventory) -> Vec<ProbeExit> {
let a = &input.cfg.proxy.auto_proxy;
let Some(dir) = input.env.autoproxy_rules_dir.as_deref().filter(|_| a.enable) else {
return Vec::new();
};
let dir = dir.trim_end_matches(['/', '\\']);
let sep = if input.env.windows { '\\' } else { '/' };
std::iter::once(DIRECT.to_owned())
.chain(inv.exits.iter().filter(|t| t.as_str() != DIRECT && !inv.disabled.contains(t)).cloned())
.take(a.max_exits.max(1) as usize)
.enumerate()
.map(|(i, tag)| ProbeExit {
port: a.probe_base_port.saturating_add(i as u16),
rule_set: (i > 0).then(|| format!("autoproxy-{i}")),
path: (i > 0).then(|| format!("{dir}{sep}rs-{i}.json")),
tag,
})
.collect()
}
/// Adds the listeners (with the hop login: they reach every exit), their pins at `pin_at`
/// (after the loopback guard, ahead of every rule that picks an outbound), the rule-sets, and
/// the learned rules after the rest, unless the mode sends everything direct. What an exit
/// carries is looked up through the proxy too, as every proxied name is.
#[allow(clippy::too_many_arguments)]
pub(super) fn apply(
input: &Input,
exits: &[ProbeExit],
inbounds: &mut Vec<Value>,
rules: &mut Vec<Value>,
pin_at: usize,
rule_sets: &mut Vec<Value>,
dns_rules: &mut Vec<Value>,
mode: RouteMode,
) {
if exits.is_empty() {
return;
}
for (i, e) in exits.iter().enumerate() {
let mut l = json!({ "type": "mixed", "tag": inbound(i), "listen": "127.0.0.1", "listen_port": e.port });
if let Some((user, password)) = &input.env.hop_login {
l["users"] = json!([{ "username": user, "password": password }]);
}
inbounds.push(l);
}
// The direct probe resolves as a direct dial would, and never reaches this host's LAN: the
// hosts probed are ones apps dialled, or anyone with the autoProxy scope asked for.
let mut pins = vec![
json!({ "inbound": [inbound(0)], "action": "resolve", "server": "local" }),
json!({ "inbound": [inbound(0)], "ip_is_private": true, "action": "reject" }),
];
pins.extend(exits.iter().enumerate().map(|(i, e)| json!({ "inbound": [inbound(i)], "outbound": e.tag })));
let at = pin_at.min(rules.len());
rules.splice(at..at, pins);
// autoProxy.exclude is never routed by it: a site learned whole (example.com) must not take
// an excluded name under it (intranet.example.com) along.
let exclude: Vec<String> = input.cfg.proxy.auto_proxy.exclude.iter().map(|x| x.trim_start_matches('.').to_ascii_lowercase()).filter(|x| !x.is_empty()).collect();
for e in exits {
let (Some(tag), Some(path)) = (&e.rule_set, &e.path) else { continue };
rule_sets.push(json!({ "type": "local", "format": "source", "tag": tag, "path": path }));
if mode != RouteMode::AllBypass {
rules.push(if exclude.is_empty() {
json!({ "rule_set": [tag], "outbound": e.tag })
} else {
json!({
"type": "logical", "mode": "and",
"rules": [{ "rule_set": [tag] }, { "domain_suffix": exclude, "invert": true }],
"outbound": e.tag,
})
});
}
dns_rules.push(json!({ "rule_set": [tag], "server": "remote" }));
}
}
+23 -5
View File
@@ -2,10 +2,14 @@
//! what it has fetched. Upstream builds these in its start scripts (bash and jq over the
//! Nix templates); here it is one pure function the service calls before every (re)start.
mod autoproxy;
pub mod groups;
mod outbounds;
mod routing;
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::fmt;
@@ -15,6 +19,7 @@ use serde_json::Value;
use crate::config::{Config, RouteMatch, RuleSetFormat};
pub use autoproxy::ProbeExit;
pub use outbounds::Inventory;
pub use routing::{WantedRuleSet, wanted_rule_sets};
@@ -101,6 +106,15 @@ pub struct Env {
pub sidecar_secret: String,
/// Running on Windows: the TUN takes Windows' fields only.
pub windows: bool,
/// Where autoProxy's learned rule-sets are (one file per exit), when it runs.
pub autoproxy_rules_dir: Option<String>,
/// zapret2's rule-sets (ps_core::zapret2::routing): what it fixes, sent direct
/// (`zapret.directSync`), and what it cannot, for the proxy (`zapret2.proxyFallback`).
pub zapret2_direct_rule_set: Option<String>,
pub zapret2_proxy_rule_set: Option<String>,
/// 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> {
@@ -123,6 +137,8 @@ pub struct Rendered {
/// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid".
pub xray: Option<Value>,
pub inventory: Inventory,
/// autoProxy's exits and their probe listeners; empty when it is off.
pub probe_exits: Vec<ProbeExit>,
pub warnings: Vec<String>,
}
@@ -143,12 +159,14 @@ pub fn render(input: &Input) -> Result<Rendered, RenderError> {
let assembly = outbounds::assemble(input, &mut warnings)?;
match input.cfg.proxy.backend {
crate::config::Backend::SingBox | crate::config::Backend::Hybrid => {
let (config, sidecar) = sing_box::config(input, &assembly, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, warnings })
let probe_exits = autoproxy::probe_exits(input, &assembly.inventory);
let (config, sidecar) = sing_box::config(input, &assembly, &probe_exits, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, probe_exits, warnings })
}
crate::config::Backend::Xray => {
let config = xray::config(input, &assembly, &mut warnings)?;
Ok(Rendered { sing_box: None, xray: Some(config), inventory: assembly.inventory, probe_exits: Vec::new(), warnings })
}
crate::config::Backend::Xray => Err(RenderError(
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
)),
}
}
+30 -8
View File
@@ -54,6 +54,8 @@ pub(super) struct Assembly {
/// The hybrid sidecar's XRay outbounds.
pub xray: Vec<Value>,
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> {
@@ -136,6 +138,14 @@ impl Builder<'_> {
/// A loopback SOCKS hop to a helper the service runs.
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 });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
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 {
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 {
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
continue;
@@ -296,6 +310,10 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
},
ExtraKind::Awg { profile, kind, port } => match kind {
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 {
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
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
// that contains itself, is left out.
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.retain(|name, _| {
@@ -424,11 +445,12 @@ pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Asse
.cloned()
.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();
every.extend(resolved.groups.keys().cloned());
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::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
"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,
"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.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())))
.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.
@@ -538,7 +560,7 @@ fn chain(b: &mut Builder, warnings: &mut Vec<String>) {
if drop.is_empty() {
for (t, hop) in &hops {
let set = |ob: &mut Value| {
if ob["tag"] == Value::from(t.as_str()) {
if ob["tag"] == t.as_str() {
if xray_tags.contains(t) || b.backend == Backend::Xray {
ob["streamSettings"]["sockopt"]["dialerProxy"] = hop.clone().into();
} else {
@@ -554,7 +576,7 @@ fn chain(b: &mut Builder, warnings: &mut Vec<String>) {
}
for (t, why) in drop {
warnings.push(format!("outbound '{t}': {why}; leaving it out"));
let keep = |o: &Value| o["tag"] != Value::from(t.as_str());
let keep = |o: &Value| o["tag"] != t.as_str();
b.outbounds.retain(keep);
b.endpoints.retain(keep);
b.xray.retain(keep);
+11 -3
View File
@@ -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> {
let cfg = input.cfg;
let mut rules = Vec::new();
if !input.env.direct_processes.is_empty() {
rules.push(json!({ "process_path": input.env.direct_processes, "outbound": "direct" }));
// Only what the TUN takes: sing-box looks a connection's program up on every inbound once a
// 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 {
for prof in &cfg.per_app_routing.profiles {
@@ -177,6 +180,10 @@ pub(super) fn per_app_inbound(name: &str) -> String {
/// Every route and DNS rule, in order, and the final outbound and resolver.
pub(super) struct Route {
pub rules: Vec<Value>,
/// Where rules pinned to an inbound go: after the loopback guard, ahead of every rule that
/// picks an outbound.
pub pin_at: usize,
pub mode: RouteMode,
pub dns_rules: Vec<Value>,
pub final_outbound: &'static str,
pub dns_final: &'static str,
@@ -204,6 +211,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo
let _ = hop_ports;
common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" }));
common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" }));
let pin_at = common.len();
common.extend(always_rules(input, known, warnings));
// The custom rules: each outbound's own routing, then routing.rules, at their priority.
@@ -321,7 +329,7 @@ pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bo
dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" }));
}
Route { rules, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) }
Route { rules, pin_at, mode, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) }
}
fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section {
+31 -4
View File
@@ -3,6 +3,7 @@
use serde_json::{Map, Value, json};
use super::autoproxy::{self, ProbeExit};
use super::outbounds::Assembly;
use super::routing::{self, per_app_inbound};
use super::{Input, RenderError};
@@ -51,7 +52,7 @@ fn hop_ports(input: &Input) -> Vec<u16> {
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 Some(user) = &auth.username else { return Ok(None) };
let password = match (&auth.password, &auth.password_file) {
@@ -64,7 +65,7 @@ fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
Ok(Some(json!([{ "username": user, "password": password }])))
}
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> {
pub(super) fn config(input: &Input, asm: &Assembly, probe_exits: &[ProbeExit], warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> {
let cfg = input.cfg;
let p = &cfg.proxy;
let env = input.env;
@@ -142,6 +143,32 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
test_members.extend(asm.inventory.exits.iter().map(|t| Value::from(t.clone())));
outbounds.push(json!({ "type": "selector", "tag": "proxy-suite-test", "outbounds": test_members, "default": "block" }));
let mut rules = route.rules;
let mut rule_sets = route.rule_set;
let mut dns_rules = route.dns_rules;
autoproxy::apply(input, probe_exits, &mut inbounds, &mut rules, route.pin_at, &mut rule_sets, &mut dns_rules, route.mode);
// zapret2's: what it cannot fix through the proxy, after the explicit rules and autoProxy's,
// ahead of the hosts it does fix, which go direct so it sees them. all-bypass sends
// everything direct, and all-proxy keeps no direct lists.
if let Some(path) = &env.zapret2_proxy_rule_set
&& route.mode != super::RouteMode::AllBypass
{
rule_sets.push(json!({ "type": "local", "format": "source", "tag": "zapret-unfixable", "path": path }));
rules.push(json!({ "rule_set": ["zapret-unfixable"], "outbound": "proxy" }));
}
// 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);
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
if hybrid {
@@ -156,7 +183,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
servers.push(json!({ "type": "fakeip", "tag": "fakeip", "inet4_range": p.dns.fake_ip.inet4_range }));
}
servers.extend(p.dns.sing_box.servers.iter().map(|s| Value::Object(s.clone())));
let mut dns = json!({ "servers": servers, "rules": route.dns_rules, "final": route.dns_final });
let mut dns = json!({ "servers": servers, "rules": dns_rules, "final": route.dns_final });
if let Some(s) = p.dns.strategy {
dns["strategy"] = s.as_str().into();
}
@@ -166,7 +193,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>)
let mut route_obj = json!({
"default_domain_resolver": "local",
"rule_set": route.rule_set,
"rule_set": rule_sets,
"rules": rules,
"final": route.final_outbound,
});
+334
View File
@@ -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))
}
+94
View File
@@ -0,0 +1,94 @@
//! Cloudflare WARP's registration, as wgcf makes it: a device's public key sent to Cloudflare's
//! client API, and the answer turned into the WireGuard profile `wgcf generate` writes.
use serde_json::{Value, json};
/// Cloudflare's client API, the version wgcf speaks.
pub const API: &str = "https://api.cloudflareclient.com/v0a2158/reg";
/// The headers wgcf sends: the API answers the clients it knows.
pub const HEADERS: [(&str, &str); 2] = [("User-Agent", "okhttp/3.12.1"), ("CF-Client-Version", "a-6.30-3596")];
/// The registration's body: the device's public key (base64), the time the terms were
/// accepted (RFC 3339).
pub fn registration(public_key: &str, tos: &str) -> Value {
json!({
"install_id": "",
"fcm_token": "",
"tos": tos,
"key": public_key,
"type": "Android",
"model": "PC",
"locale": "en_US",
})
}
/// The WireGuard profile of a registration's answer, with the device's private key: as
/// `wgcf generate` writes it.
pub fn profile(answer: &Value, private_key: &str) -> Result<String, String> {
let c = &answer["config"];
let v4 = c["interface"]["addresses"]["v4"].as_str().ok_or("the answer has no IPv4 address")?;
let v6 = c["interface"]["addresses"]["v6"].as_str();
let peer = &c["peers"][0];
let public_key = peer["public_key"].as_str().ok_or("the answer has no peer key")?;
let endpoint = peer["endpoint"]["host"].as_str().unwrap_or("engage.cloudflareclient.com:2408");
let mut address = format!("{v4}/32");
if let Some(v6) = v6 {
address.push_str(&format!(", {v6}/128"));
}
Ok(format!(
"[Interface]\nPrivateKey = {private_key}\nAddress = {address}\nDNS = 1.1.1.1, 1.0.0.1, 2606:4700:4700::1111, 2606:4700:4700::1001\nMTU = 1280\n\n\
[Peer]\nPublicKey = {public_key}\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = {endpoint}\n"
))
}
/// What a generator (`warp.generatorUrl`) hands back: the profile, or `{"content": base64}`.
pub fn generated(body: &str) -> Result<String, String> {
let text = if body.trim_start().starts_with("[Interface]") {
body.to_owned()
} else {
let v: Value = serde_json::from_str(body).map_err(|_| "the generator's answer is neither a profile nor JSON")?;
let content = v["content"].as_str().ok_or("the generator's JSON has no content")?;
use base64::Engine;
let bytes = base64::engine::general_purpose::STANDARD.decode(content.trim()).map_err(|_| "the generator's content is not base64")?;
String::from_utf8(bytes).map_err(|_| "the generator's profile is not text")?
};
if !text.lines().any(|l| l.trim_start().starts_with("PrivateKey")) {
return Err("the generator's profile has no private key".into());
}
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_answer_becomes_wgcfs_profile() {
let answer = json!({
"config": {
"interface": { "addresses": { "v4": "172.16.0.2", "v6": "2606:4700:110:8a36::1" } },
"peers": [{ "public_key": "bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=", "endpoint": { "host": "engage.cloudflareclient.com:2408" } }],
}
});
let p = profile(&answer, "PRIV").unwrap();
assert!(p.contains("PrivateKey = PRIV\n"));
assert!(p.contains("Address = 172.16.0.2/32, 2606:4700:110:8a36::1/128\n"));
assert!(p.contains("PublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\n"));
// What sing-box gets of it.
let (ep, _) = crate::wg::sing_box_endpoint(&p, "warp", None).unwrap();
assert_eq!(ep["peers"][0]["address"], "engage.cloudflareclient.com");
assert_eq!(ep["peers"][0]["port"], 2408);
assert!(profile(&json!({}), "PRIV").is_err());
}
#[test]
fn a_generators_answer_either_way() {
let p = "[Interface]\nPrivateKey = K\n";
assert_eq!(generated(p).unwrap(), p);
use base64::Engine;
let b = base64::engine::general_purpose::STANDARD.encode(p);
assert_eq!(generated(&format!(r#"{{"content":"{b}"}}"#)).unwrap(), p);
assert!(generated("<html>").is_err());
}
}
+4 -4
View File
@@ -47,10 +47,10 @@ pub fn conf_sections(config: &str) -> Vec<Section> {
let stripped = line.split('#').next().unwrap_or("").split(';').next().unwrap_or("").trim();
if stripped.starts_with('[') && stripped.ends_with(']') && stripped.len() >= 2 {
sections.push((stripped[1..stripped.len() - 1].trim().to_lowercase(), Vec::new()));
} else if let Some((key, value)) = stripped.split_once('=') {
if let Some(last) = sections.last_mut() {
last.1.push((key.trim().to_lowercase(), value.trim().to_owned()));
}
} else if let Some((key, value)) = stripped.split_once('=')
&& let Some(last) = sections.last_mut()
{
last.1.push((key.trim().to_lowercase(), value.trim().to_owned()));
}
}
sections
+414 -1
View File
@@ -9,7 +9,7 @@
use std::collections::BTreeSet;
use crate::config::{DiscordYoutube, GameFilter, Zapret};
use crate::config::{DiscordYoutube, GameFilter, HostlistRule, Zapret, ZapretDefaultDomains, ZapretDefaultIps, ZapretPreset};
/// What a preset's name is compared by: its letters, digits and brackets, any case.
fn name_key(name: &str) -> String {
@@ -152,6 +152,249 @@ pub fn expand(args: &[String], bin: &str, lists: &str, root: &str, game: GameFil
.collect()
}
/// A list file's entries: trimmed, without comments and blanks, each once.
fn list_entries(text: &str) -> Vec<String> {
let mut seen = BTreeSet::new();
text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#') && seen.insert(*l)).map(str::to_owned).collect()
}
/// The release's lists a rule's `defaultDomains` and `defaultIps` name, as text.
pub struct ReleaseLists<'a> {
pub general: &'a str,
pub google: &'a str,
pub ipset_all: &'a str,
}
/// A hostlist rule, worked out as upstream's zapret-domain-groups.nix does: its sites, and what
/// of which preset its strategy is copied from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rule {
pub name: String,
pub domains: Vec<String>,
pub ips: Vec<String>,
/// The preset profiles copied for its domains: "general", "google".
pub families: Vec<&'static str>,
/// Discord's voice profile copied too (a rule taking another preset, for Discord's sites).
pub discord_voice: bool,
pub config_name: Option<String>,
pub nfqws_args: Vec<String>,
}
/// Instagram's, SoundCloud's and Twitter's lists come with the Linux port upstream uses, not
/// with Flowseal's Windows release.
fn not_in_release(rule: &str, list: &str) -> String {
format!("hostlist rule '{rule}': Flowseal's Windows release has no {list} list")
}
pub fn rule(r: &HostlistRule, lists: &ReleaseLists) -> Result<Rule, String> {
use ZapretDefaultDomains as D;
let mut domains = Vec::new();
let mut families: Vec<&'static str> = Vec::new();
for group in &r.default_domains {
let (list, family) = match group {
D::General | D::Discord => (lists.general, "general"),
D::Google | D::Youtube => (lists.google, "google"),
D::Instagram => return Err(not_in_release(&r.name, "instagram")),
D::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")),
D::Twitter => return Err(not_in_release(&r.name, "twitter")),
};
domains.extend(list_entries(list));
if !families.contains(&family) {
families.push(family);
}
}
domains.extend(r.domains.iter().map(|d| d.trim().to_owned()));
let mut ips = Vec::new();
for group in &r.default_ips {
match group {
ZapretDefaultIps::All => ips.extend(list_entries(lists.ipset_all)),
}
}
ips.extend(r.ips.iter().map(|i| i.trim().to_owned()));
if let Some(preset) = r.preset {
families = vec![match preset {
ZapretPreset::General => "general",
ZapretPreset::Google => "google",
ZapretPreset::Instagram => return Err(not_in_release(&r.name, "instagram")),
ZapretPreset::Soundcloud => return Err(not_in_release(&r.name, "soundcloud")),
ZapretPreset::Twitter => return Err(not_in_release(&r.name, "twitter")),
}];
}
let once = |v: Vec<String>| {
let mut seen = BTreeSet::new();
v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::<Vec<_>>()
};
Ok(Rule {
name: r.name.clone(),
domains: once(domains),
ips: once(ips),
families,
discord_voice: r.config_name.is_some() && r.default_domains.iter().any(|g| matches!(g, D::General | D::Discord)),
config_name: r.config_name.clone(),
nfqws_args: r.nfqws_args.clone(),
})
}
/// A rule's own lists, in the lists directory.
pub fn rule_lists(rule: &Rule) -> (String, String) {
(format!("list-{}.txt", rule.name), format!("ipset-{}.txt", rule.name))
}
/// A preset's arguments cut into the global ones (the WinDivert filter, `--wf-*`, ahead of the
/// first profile) and its profiles (between `--new`).
fn profiles(args: &[String]) -> (Vec<String>, Vec<Vec<String>>) {
let mut global = Vec::new();
let mut out = vec![Vec::new()];
for a in args {
if a == "--new" {
out.push(Vec::new());
} else if out.len() == 1 && out[0].is_empty() && a.starts_with("--wf-") {
global.push(a.clone());
} else {
out.last_mut().unwrap().push(a.clone());
}
}
out.retain(|p| !p.is_empty());
(global, out)
}
/// `--hostlist=…list-general.txt` and the like: `option` naming one of `files`.
fn names_list(arg: &str, option: &str, files: &[&str]) -> bool {
arg.strip_prefix(option).is_some_and(|path| files.contains(&path.rsplit(['\\', '/']).next().unwrap_or(path)))
}
fn family_files(family: &str) -> &'static [&'static str] {
match family {
"general" => &["list-general.txt", "list-general-user.txt"],
_ => &["list-google.txt"],
}
}
/// A profile pointed at one list of the rule's: its own list arguments (those `drop` says)
/// gone, the other kind's gone too, the list put in, and the standard excludes there.
fn retarget(profile: &[String], option: &str, list: &str, drop: impl Fn(&str) -> bool, excludes: &[String]) -> Vec<String> {
let other = if option == "--hostlist=" { "--ipset=" } else { "--hostlist=" };
let mut out: Vec<String> = profile.iter().filter(|a| !drop(a) && !a.starts_with(other)).cloned().collect();
out.push(format!("{option}{list}"));
for e in excludes {
if !out.contains(e) {
out.push(e.clone());
}
}
out
}
/// The ports a profile filters on, by protocol.
fn filter_ports<'a>(profile: &'a [String], proto: &str) -> Vec<&'a str> {
let option = format!("--filter-{proto}=");
profile.iter().filter_map(|a| a.strip_prefix(option.as_str())).collect()
}
/// The preset's arguments (expanded) with the rules' profiles ahead of its own. `source` gives
/// another preset's arguments, expanded, for a rule's `configName`; `expand` fills in a rule's
/// own `nfqwsArgs` as a preset's are. `lists` ends with a separator.
pub fn with_rules(
args: Vec<String>,
rules: &[Rule],
lists: &str,
source: &dyn Fn(&str) -> Result<Vec<String>, String>,
expand: &dyn Fn(&[String]) -> Vec<String>,
) -> Result<Vec<String>, String> {
if rules.is_empty() {
return Ok(args);
}
let (mut global, own) = profiles(&args);
let excludes: Vec<String> = [
("--hostlist-exclude=", "list-exclude.txt"),
("--hostlist-exclude=", "list-exclude-user.txt"),
("--ipset-exclude=", "ipset-exclude.txt"),
("--ipset-exclude=", "ipset-exclude-user.txt"),
]
.iter()
.map(|(o, f)| format!("{o}{lists}{f}"))
.collect();
let mut generated: Vec<Vec<String>> = Vec::new();
// What WinDivert has to let through for them: their filters' ports, another preset's own.
let (mut tcp, mut udp): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
for rule in rules {
let (src_global, src) = match &rule.config_name {
Some(name) => profiles(&source(name).map_err(|e| format!("hostlist rule '{}': {e}", rule.name))?),
None => (Vec::new(), own.clone()),
};
for a in &src_global {
if let Some(p) = a.strip_prefix("--wf-tcp=") {
tcp.push(p.to_owned());
} else if let Some(p) = a.strip_prefix("--wf-udp=") {
udp.push(p.to_owned());
}
}
let (list, ipset) = rule_lists(rule);
let (list, ipset) = (format!("{lists}{list}"), format!("{lists}{ipset}"));
let missing = |what: &str| format!("hostlist rule '{}': the preset has no {what} profile to copy", rule.name);
if !rule.domains.is_empty() {
for family in &rule.families {
let files = family_files(family);
let matching: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--hostlist=", files))).collect();
if matching.is_empty() {
return Err(missing(family));
}
for p in matching {
generated.push(retarget(p, "--hostlist=", &list, |a| names_list(a, "--hostlist=", files), &excludes));
}
}
}
if !rule.ips.is_empty() {
let matching: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| names_list(a, "--ipset=", &["ipset-all.txt"]))).collect();
if matching.is_empty() {
return Err(missing("ipset-all"));
}
for p in matching {
generated.push(retarget(p, "--ipset=", &ipset, |a| names_list(a, "--ipset=", &["ipset-all.txt"]), &excludes));
}
}
if rule.discord_voice {
let voice: Vec<&Vec<String>> = src.iter().filter(|p| p.iter().any(|a| a == "--filter-l7=discord,stun")).collect();
if voice.is_empty() {
return Err(missing("Discord voice"));
}
generated.extend(voice.into_iter().cloned());
}
for fragment in &rule.nfqws_args {
let args = expand(&cmd_tokens(fragment));
tcp.extend(filter_ports(&args, "tcp").into_iter().map(str::to_owned));
udp.extend(filter_ports(&args, "udp").into_iter().map(str::to_owned));
if !rule.domains.is_empty() {
generated.push(retarget(&args, "--hostlist=", &list, |a| a.starts_with("--hostlist="), &excludes));
}
if !rule.ips.is_empty() {
generated.push(retarget(&args, "--ipset=", &ipset, |a| a.starts_with("--ipset="), &excludes));
}
}
}
for (option, extra) in [("--wf-tcp=", &tcp), ("--wf-udp=", &udp)] {
if extra.is_empty() {
continue;
}
let mut all: Vec<&str> = extra.iter().map(String::as_str).collect();
match global.iter_mut().find(|a| a.starts_with(option)) {
Some(a) => {
let have = a[option.len()..].to_owned();
all.push(&have);
*a = format!("{option}{}", crate::zapret2::merge_ports(&all));
}
None => global.push(format!("{option}{}", crate::zapret2::merge_ports(&all))),
}
}
let mut out = global;
for (i, p) in generated.into_iter().chain(own).enumerate() {
if i > 0 {
out.push("--new".into());
}
out.extend(p);
}
Ok(out)
}
/// What the user's lists hold, as files beside the release's: Flowseal's `load_user_lists`
/// placeholders where a list would be empty (winws refuses an empty one).
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -212,6 +455,18 @@ pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclu
domains.extend(parse(list_general));
domains.extend(parse(list_google));
domains.extend(y.domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
// The hostlist rules that ask for it, as upstream's: their sites, their addresses.
let release = ReleaseLists { general: list_general, google: list_google, ipset_all };
for r in y.hostlist_rules.iter().filter(|r| r.enable_direct_sync) {
let Ok(rule) = rule(r, &release) else { continue };
domains.extend(rule.domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
if ds.user_ips {
ips.extend(r.ips.iter().cloned());
}
if ds.upstream_ips && r.default_ips.contains(&ZapretDefaultIps::All) {
ips.extend(parse(ipset_all).into_iter().filter(|i| i != "203.0.113.113/32"));
}
}
let mut excluded: BTreeSet<String> = parse(list_exclude).into_iter().collect();
excluded.extend(y.exclude_domains.iter().map(|d| d.trim_start_matches('^').to_owned()));
domains.retain(|d| !excluded.contains(d));
@@ -242,6 +497,68 @@ pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclu
(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)]
mod tests {
use super::*;
@@ -273,6 +590,95 @@ start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-
assert_eq!(all[0], "--wf-tcp=80,443,1024-65535");
}
const FULL: &str = r#"start "zapret" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,19294-19344,%GameFilterUDP% ^
--filter-udp=443 --hostlist="%LISTS%list-general.txt" --hostlist="%LISTS%list-general-user.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake --new ^
--filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake --new ^
--filter-tcp=443 --hostlist="%LISTS%list-google.txt" --dpi-desync=multisplit --new ^
--filter-tcp=80,443 --ipset="%LISTS%ipset-all.txt" --hostlist-exclude="%LISTS%list-exclude.txt" --dpi-desync=fake
"#;
const OTHER: &str = r#""%BIN%winws.exe" --wf-tcp=443,2053 --wf-udp=443 --filter-tcp=443,2053 --hostlist="%LISTS%list-general.txt" --dpi-desync=hostfakesplit --new --filter-udp=19294-19344 --filter-l7=discord,stun --dpi-desync=fake"#;
fn ex(args: &[String]) -> Vec<String> {
expand(args, "B\\", "L\\", "R\\", GameFilter::Null)
}
fn lists() -> ReleaseLists<'static> {
ReleaseLists { general: "discord.com\n# c\n", google: "youtube.com\ngooglevideo.com\n", ipset_all: "203.0.113.0/24\n" }
}
fn rules(json: serde_json::Value) -> Result<Vec<String>, String> {
let r: HostlistRule = serde_json::from_value(json).unwrap();
let rule = rule(&r, &lists())?;
let source = |name: &str| if name == "other" { Ok(ex(&preset_args(OTHER).unwrap())) } else { Err(format!("no preset {name}")) };
with_rules(ex(&preset_args(FULL).unwrap()), &[rule], "L\\", &source, &ex)
}
fn profile_of(args: &[String], i: usize) -> Vec<String> {
let (_, p) = profiles(args);
p[i].clone()
}
#[test]
fn a_rule_copies_its_family_ahead_of_the_preset() {
let out = rules(serde_json::json!({ "name": "mine", "domains": ["example.com"], "preset": "general" })).unwrap();
let first = profile_of(&out, 0);
assert_eq!(
first,
[
"--filter-udp=443",
"--hostlist-exclude=L\\list-exclude.txt",
"--dpi-desync=fake",
"--hostlist=L\\list-mine.txt",
"--hostlist-exclude=L\\list-exclude-user.txt",
"--ipset-exclude=L\\ipset-exclude.txt",
"--ipset-exclude=L\\ipset-exclude-user.txt",
]
);
// The preset's own follow, untouched; the filter as it was.
let (global, p) = profiles(&out);
assert_eq!(p.len(), 5);
assert_eq!(p[1], profile_of(&ex(&preset_args(FULL).unwrap()), 0));
assert_eq!(global, ["--wf-tcp=80,443,12", "--wf-udp=443,19294-19344,12"]);
}
#[test]
fn default_domains_pick_the_list_and_the_family() {
let r: HostlistRule = serde_json::from_value(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"], "domains": ["extra.example"] })).unwrap();
let rule = rule(&r, &lists()).unwrap();
assert_eq!(rule.domains, ["youtube.com", "googlevideo.com", "extra.example"]);
assert_eq!(rule.families, ["google"]);
let out = rules(serde_json::json!({ "name": "yt", "defaultDomains": ["youtube"] })).unwrap();
assert!(profile_of(&out, 0).contains(&"--dpi-desync=multisplit".to_owned()));
assert!(profile_of(&out, 0).contains(&"--hostlist=L\\list-yt.txt".to_owned()));
}
#[test]
fn another_preset_brings_its_ports_and_discord_voice() {
let out = rules(serde_json::json!({ "name": "d", "defaultDomains": ["discord"], "configName": "other" })).unwrap();
let (global, p) = profiles(&out);
assert_eq!(global, ["--wf-tcp=12,80,443,2053", "--wf-udp=12,443,19294-19344"]);
assert!(p[0].contains(&"--dpi-desync=hostfakesplit".to_owned()));
assert!(p[1].contains(&"--filter-l7=discord,stun".to_owned()));
}
#[test]
fn own_args_and_ips() {
let out = rules(serde_json::json!({ "name": "c", "domains": ["a.example"], "ips": ["198.51.100.0/24"], "nfqwsArgs": ["--filter-tcp=8080 --hostlist=x.txt --dpi-desync=fake"] })).unwrap();
let (global, p) = profiles(&out);
assert_eq!(global[0], "--wf-tcp=12,80,443,8080");
// The ipset-all profile, pointed at the rule's addresses; then its own args, twice.
assert!(p[0].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && p[0].contains(&"--filter-tcp=80,443".to_owned()));
assert_eq!(&p[1][..3], ["--filter-tcp=8080", "--dpi-desync=fake", "--hostlist=L\\list-c.txt"]);
assert!(p[2].contains(&"--ipset=L\\ipset-c.txt".to_owned()) && !p[2].iter().any(|a| a.starts_with("--hostlist=")));
}
#[test]
fn what_the_windows_release_lacks_is_an_error() {
assert!(rules(serde_json::json!({ "name": "i", "defaultDomains": ["instagram"] })).unwrap_err().contains("instagram"));
let err = rules(serde_json::json!({ "name": "g", "domains": ["a.example"], "preset": "google", "configName": "other" })).unwrap_err();
assert!(err.contains("no google profile"), "{err}");
}
#[test]
fn carets_escape_as_cmd_has_them() {
let args = preset_args("\"%BIN%winws.exe\" --dpi-desync-fake-tls=^! --x=\"a^b\" ^\n--y=^^z").unwrap();
@@ -312,6 +718,13 @@ start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-
let (d, i) = direct_sync(&z, "discord.com\n^dns.google\n# c\nyoutube.com\n", "googlevideo.com\n", "", "203.0.113.113/32\n", "");
assert_eq!(d, ["discord.com", "dns.google", "googlevideo.com", "mine.example"]);
assert!(i.is_empty());
z.discord_youtube.hostlist_rules = vec![
serde_json::from_value(serde_json::json!({ "name": "s", "domains": ["synced.example"], "ips": ["198.51.100.1"], "preset": "general", "enableDirectSync": true })).unwrap(),
serde_json::from_value(serde_json::json!({ "name": "n", "domains": ["unsynced.example"], "preset": "general", "enableDirectSync": false })).unwrap(),
];
let (d, i) = direct_sync(&z, "discord.com\n", "", "", "", "");
assert_eq!(d, ["discord.com", "mine.example", "synced.example"]);
assert_eq!(i, ["198.51.100.1"]);
z.direct_sync.enable = false;
assert_eq!(direct_sync(&z, "x.com", "", "", "", "").0, Vec::<String>::new());
}
+505 -28
View File
@@ -1,14 +1,16 @@
//! 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
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`.
//! (NFQUEUE): nfqws2-keenetic's, read and patched as upstream's `zapret2/sources.nix` does, or
//! z2k's, made by its own generator (tools/build-zapret2-extras.sh); the profiles, markers,
//! 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
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's
//! own `--writable` insists on making the directory, which must already hold the list).
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`,
//! `extendedDetection`) and z2k come later.
//! the place of the queue's rules, a filter part hands the detectors the server's TLS
//! records in place of the queue's packet windows, and there are no marks. winws2 drops to
//! Low integrity once it runs, so what it writes lives in a directory the service labels Low
//! for it (winws2's own `--writable` insists on making the directory).
use std::collections::BTreeMap;
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.
#[derive(Debug, Clone, PartialEq)]
/// A strategy source, as upstream's sources.nix takes it: nfqws2-keenetic's or z2k's.
#[derive(Debug, Clone, PartialEq, Default)]
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>,
/// z2k: its profiles with the extended detector learning in its last place.
pub learn_profiles: Option<Vec<String>>,
pub blob_args: Vec<String>,
pub tcp_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
@@ -94,6 +141,7 @@ pub fn keenetic(conf: &str, dir: &str) -> Result<Source, String> {
blob_args,
tcp_ports: bare("TCP_PORTS")?.trim().to_owned(),
udp_ports: bare("UDP_PORTS")?.trim().replace(':', "-"),
..Default::default()
})
}
@@ -108,6 +156,25 @@ pub struct Paths {
pub exclude: String,
/// `zapret-hosts-auto.txt`, in a directory labelled Low integrity.
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
@@ -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))
}
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target).
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) {
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target),
/// 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 base = format!("--hostlist={} --hostlist-exclude={}", p.user, p.exclude);
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() {
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.
@@ -184,19 +302,31 @@ fn circular_fill(z: &Zapret2, token: &str) -> String {
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 {
values
.iter()
.map(|v| match v {
serde_json::Value::String(s) => s.clone(),
serde_json::Value::String(s) => s.trim().to_owned(),
other => other.to_string(),
})
.filter(|s| port_spec_ok(s))
.collect::<Vec<_>>()
.join(",")
}
/// Ports as ranges, merged: upstream's ports.awk.
fn merge_ports(lists: &[&str]) -> String {
pub(crate) fn merge_ports(lists: &[&str]) -> String {
let mut on = vec![false; 65537];
for list in lists {
for p in list.split(',') {
@@ -214,8 +344,9 @@ fn merge_ports(lists: &[&str]) -> String {
}
let mut out = Vec::new();
let mut start = 0;
// One past the last port, so a run that reaches 65535 ends too.
for port in 1..=65536usize {
if port <= 65535 && on[port] {
if on.get(port).copied().unwrap_or(false) {
if start == 0 {
start = port;
}
@@ -229,29 +360,91 @@ fn merge_ports(lists: &[&str]) -> String {
/// winws2's whole command line.
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() {
return Err("only the nfqws2-keenetic strategies are there on Windows yet (zapret.zapret2.strategySource)".into());
if z.strategy_source == StrategySource::Z2k && z.profiles.is_none() && !source.z2k {
return Err("z2k's strategies need the zapret2-extras component (proxy-ctl components)".into());
}
let (with_auto, no_auto) = hostlist_args(z, p);
let render = |profile: &str| {
let (with_auto, no_auto, statics) = hostlist_args(z, p);
// 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
.replace("<HOSTLIST_NOAUTO>", &no_auto)
.replace("<HOSTLIST>", &with_auto)
.replace("<STALLWATCH> ", "")
.replace("<STALLWATCH>", "")
.replace("<HOSTLIST_NOAUTO>", &(no_auto.clone() + &statics))
.replace("<HOSTLIST>", &(with_auto.clone() + &statics))
.replace("<STALLWATCH> ", &if stall_watch.is_empty() { String::new() } else { format!("{stall_watch} ") })
.replace("<STALLWATCH>", &stall_watch)
};
let profiles: Vec<String> = match &z.profiles {
Some(own) => own.iter().map(|x| render(x)).collect(),
None => source.profiles.iter().map(|x| render(x)).collect(),
let mut profiles: Vec<String> = match (&z.profiles, &source.learn_profiles) {
(Some(own), _) => own.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();
if debug_packets {
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"] {
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 {
opt.push(format!("--blob={name}:@{file}"));
}
@@ -312,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));
if !wf_tcp.is_empty() {
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() {
opt.push(format!("--wf-udp-out={wf_udp}"));
@@ -321,10 +517,218 @@ pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Res
if !z.ipv6 {
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);
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)]
mod tests {
use super::*;
@@ -363,9 +767,82 @@ UDP_PORTS=443,590:600
user: r"C:\s\user.txt".into(),
exclude: r"C:\s\exclude.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]
fn keenetic_is_read_and_patched_as_upstream_does() {
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
+395 -4
View File
@@ -2,7 +2,7 @@
//! `xray run -test`, when they are on PATH (the dev shell has both).
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::process::Command;
use ps_core::config::*;
@@ -22,7 +22,7 @@ fn scratch(name: &str) -> PathBuf {
dir
}
fn env(dir: &PathBuf) -> Env {
fn env(dir: &Path) -> Env {
let empty = dir.join("empty.json");
std::fs::write(&empty, r#"{"version":1,"rules":[]}"#).unwrap();
let mut warp = BTreeMap::new();
@@ -45,7 +45,7 @@ fn no_files(path: &str) -> Result<String, String> {
Err(format!("{path}: not found"))
}
fn check_sing_box(config: &Value, dir: &PathBuf) {
fn check_sing_box(config: &Value, dir: &Path) {
if !have("sing-box") {
eprintln!("sing-box not on PATH: skipping the check");
return;
@@ -61,7 +61,7 @@ fn check_sing_box(config: &Value, dir: &PathBuf) {
);
}
fn check_xray(config: &Value, dir: &PathBuf) {
fn check_xray(config: &Value, dir: &Path) {
if !have("xray") {
return;
}
@@ -230,3 +230,394 @@ fn no_outbounds_is_an_error() {
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("no proxy outbounds"));
}
#[test]
fn auto_proxy_adds_probe_listeners_and_learned_rules() {
let dir = scratch("autoproxy");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["blocked.example"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let mut state = State::default();
let render_with = |state: &State| {
render(&Input { cfg: &cfg, state, subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap()
};
let r = render_with(&state);
// direct, then the first exit: maxExits 2.
assert_eq!(r.probe_exits.iter().map(|x| (x.tag.as_str(), x.port)).collect::<Vec<_>>(), [("direct", 18540), ("nl", 18541)]);
let sb = r.sing_box.unwrap();
let probe_in: Vec<&Value> = sb["inbounds"].as_array().unwrap().iter().filter(|i| i["tag"].as_str().unwrap().starts_with("probe-in-")).collect();
assert_eq!(probe_in.len(), 2);
assert_eq!(probe_in[1]["users"], json!([{ "username": "hop", "password": "hop-pass" }]));
let rules = sb["route"]["rules"].as_array().unwrap();
let guard = rules.iter().position(|r| r["domain"] == json!(["localhost"])).unwrap();
let pin = rules.iter().position(|r| r["inbound"] == json!(["probe-in-1"])).unwrap();
assert!(pin > guard, "the probes stay behind the loopback guard");
assert_eq!(rules.last().unwrap(), &json!({ "rule_set": ["autoproxy-1"], "outbound": "nl" }));
assert!(sb["dns"]["rules"].as_array().unwrap().contains(&json!({ "rule_set": ["autoproxy-1"], "server": "remote" })));
check_sing_box(&sb, &dir);
// all-bypass: everything direct, learned routes too.
state.route_mode = Some(RouteMode::AllBypass);
let sb = render_with(&state).sing_box.unwrap();
assert!(!sb["route"]["rules"].as_array().unwrap().iter().any(|r| r["rule_set"] == json!(["autoproxy-1"]) && r.get("outbound").is_some()));
}
#[test]
fn auto_proxy_never_routes_what_it_excludes() {
let dir = scratch("autoproxy-exclude");
let mut cfg = base();
cfg.proxy.auto_proxy.enable = true;
cfg.proxy.auto_proxy.max_exits = 2;
cfg.proxy.auto_proxy.exclude = vec!["intranet.example.com".into()];
let rules_dir = dir.join("rules");
std::fs::create_dir_all(&rules_dir).unwrap();
std::fs::write(rules_dir.join("rs-1.json"), r#"{"version":1,"rules":[{"domain_suffix":["example.com"]}]}"#).unwrap();
let mut e = env(&dir);
e.autoproxy_rules_dir = Some(rules_dir.to_string_lossy().into());
e.windows = false;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &e, read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(
sb["route"]["rules"].as_array().unwrap().last().unwrap(),
&json!({ "type": "logical", "mode": "and", "rules": [{ "rule_set": ["autoproxy-1"] }, { "domain_suffix": ["intranet.example.com"], "invert": true }], "outbound": "nl" })
);
check_sing_box(&sb, &dir);
}
#[test]
fn zapret2s_rule_sets_follow_autoproxy_and_the_mode() {
let dir = scratch("zapret2-sync");
let (direct, proxy, 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"));
}
+2
View File
@@ -12,10 +12,12 @@ path = "src/main.rs"
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
ps-client.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
rpassword.workspace = true
[dev-dependencies]
serde_json.workspace = true
+517 -238
View File
@@ -2,11 +2,13 @@
use std::io::Read;
use anyhow::{Context, Result, anyhow, bail};
use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand};
use ps_ipc::transport::{self, Address};
use ps_ipc::{Request, Response};
use serde_json::{Value, json};
use ps_client::edits::{self, OutboundSource};
use ps_client::{Client, Saved};
use ps_ipc::Request;
use ps_ipc::transport::Address;
use serde_json::Value;
#[derive(Parser)]
#[command(name = "proxy-ctl", version, about = "Control Proxy Suite", disable_help_subcommand = true)]
@@ -47,11 +49,92 @@ enum Cmd {
#[command(subcommand)]
verb: Option<ZapretVerb>,
},
/// Telegram's WebSocket proxy (tg-ws-proxy).
Tg {
#[command(subcommand)]
verb: TgVerb,
},
/// AmneziaWG profiles: the system-wide ones started and stopped.
Awg {
#[command(subcommand)]
verb: Option<AwgVerb>,
},
/// whitelist-bypass creators and joiners.
Wl {
#[command(subcommand)]
verb: Option<WlVerb>,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
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)]
enum TgVerb {
/// Its tg:// links, to open in Telegram.
Link,
}
#[derive(Subcommand)]
enum AwgVerb {
/// Profiles and their state.
List,
/// Start a system-wide profile's tunnel.
On { profile: String },
/// Stop it.
Off { profile: String },
/// Its tunnel's log.
Log {
profile: String,
#[arg(short = 'n', long, default_value_t = 50)]
lines: usize,
},
}
#[derive(Subcommand)]
enum WlVerb {
/// Creators and joiners, and their state.
List,
/// The call a creator made, for its joiner.
Link { creator: String },
/// A creator's login: a cookies export (a file, or - for stdin); DION and Bitrix ask for
/// an email and password without one.
Auth { creator: String, file: Option<String> },
/// The call link a joiner joins (or - for stdin).
Join { joiner: String, link: String },
/// Start a new call, if the platform closed the old one.
New { creator: String },
/// Restart all of them, or the one named.
Restart { name: Option<String> },
}
#[derive(Subcommand)]
@@ -59,10 +142,25 @@ enum ZapretVerb {
Status,
On,
Off,
/// The presets of the installed release; the one in use is marked.
Presets,
/// Use this preset (zapret-discord-youtube), e.g. "general (ALT9)".
Preset { name: String },
/// Which game traffic to handle: all, tcp, udp or null.
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)]
@@ -133,6 +231,39 @@ enum ProxyVerb {
},
/// The config the backend runs.
Config,
/// autoProxy: what it routed and where; probing, learning, forgetting.
Auto {
#[command(subcommand)]
verb: Option<AutoVerb>,
},
}
#[derive(Subcommand)]
enum AutoVerb {
/// The routes learned, the exits, what waits.
List,
/// Probe a site (host, or host/path) through the exits, as autoProxy does.
Probe {
target: String,
/// Only these exits (comma-separated), in this order.
#[arg(long, value_delimiter = ',')]
exits: Option<Vec<String>>,
/// Whether this exit carries what direct reaches.
#[arg(long)]
via: Option<String>,
/// Try every exit, not only up to the first that reaches it.
#[arg(long)]
keep_going: bool,
},
/// Probe these hosts now, and route them if they need it.
Learn {
#[arg(required = true)]
hosts: Vec<String>,
},
/// Forget a domain's route: it is probed again when next dialled.
Forget { domain: String },
/// Forget everything learned.
Clear,
}
#[derive(Subcommand)]
@@ -194,51 +325,29 @@ enum RulesetsVerb {
}
struct Ctl {
addr: Address,
client: Client,
json: bool,
}
impl Ctl {
async fn call(&self, req: Request) -> Result<Value> {
let resp: Response = transport::call(&self.addr, &req).await?;
if !resp.ok {
let mut msg = resp.error.unwrap_or_else(|| "failed".into());
if let Some(issues) = resp.data.get("issues").and_then(Value::as_array) {
for i in issues {
msg.push_str(&format!("\n {} {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or("")));
}
}
bail!(msg);
}
Ok(resp.data)
self.client.call(req).await
}
fn print(&self, v: &Value) {
println!("{}", serde_json::to_string_pretty(v).unwrap());
}
/// Reads the configuration, lets `edit` change it, writes it back against the revision
/// read; a concurrent change is retried.
async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Value> {
for _ in 0..3 {
let got = self.call(Request::ConfigGet).await?;
let mut config = got["config"].clone();
edit(&mut config)?;
match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await {
Err(e) if e.to_string().contains("changed since revision") => continue,
other => {
let r = other?;
for i in r["issues"].as_array().into_iter().flatten() {
eprintln!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or(""));
}
if let Some(e) = r["error"].as_str() {
eprintln!("saved, but not applied: {e}");
}
return Ok(r);
}
}
/// A configuration edit ([`Client::edit`]), and what the validator said of it.
async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result<Saved> {
let saved = self.client.edit(edit).await?;
for i in &saved.issues {
eprintln!("{i}");
}
bail!("the configuration kept changing; try again")
if let Some(e) = &saved.apply_error {
eprintln!("saved, but not applied: {e}");
}
Ok(saved)
}
}
@@ -252,55 +361,13 @@ fn read_arg(value: &str) -> Result<String> {
}
}
/// A file's text, or stdin's for -.
fn read_arg_file(file: &str) -> Result<String> {
if file == "-" { read_arg("-") } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}")) }
}
fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? };
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
}
fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec<Value> {
let mut cur = v;
for p in path {
if cur.get(*p).is_none_or(Value::is_null) {
cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) };
}
cur = cur.get_mut(*p).unwrap();
}
cur.as_array_mut().expect("a list")
}
/// A tag for a link without one: its remark, else its host.
fn tag_for(link: &str) -> String {
if let Some((_, remark)) = link.split_once('#') {
let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark));
if t != "proxy" {
return t;
}
}
let host = link.split("://").nth(1).unwrap_or("").split(['@']).last().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or("");
let t = ps_core::links::subscription::slugify_tag(host);
if t.is_empty() { "outbound".into() } else { t }
}
/// A rule's matches, sorted into their kinds.
fn sort_matches(matches: &[String]) -> Value {
let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] });
for x in matches {
let (key, value) = if let Some(v) = x.strip_prefix("geosite:") {
("geosites", v.to_owned())
} else if let Some(v) = x.strip_prefix("geoip:") {
("geoips", v.to_owned())
} else if let Some(v) = x.strip_prefix("ruleset:") {
("ruleSets", v.to_owned())
} else if let Some(v) = x.strip_prefix("process:") {
("processNames", v.to_owned())
} else if x.parse::<std::net::IpAddr>().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::<std::net::IpAddr>().is_ok()) {
("ips", x.clone())
} else {
("domains", x.trim_start_matches('.').to_lowercase())
};
m[key].as_array_mut().unwrap().push(value.into());
}
m
serde_json::from_str(&read_arg_file(file)?).with_context(|| format!("{file} is not JSON"))
}
async fn status(ctl: &Ctl) -> Result<()> {
@@ -365,64 +432,20 @@ async fn outbounds(ctl: &Ctl, verb: Option<OutboundVerb>) -> Result<()> {
}
}
OutboundVerb::Add { args, detour } => {
let (tag, link) = match args.as_slice() {
let (tag, text) = match args.as_slice() {
[link] => {
let link = read_arg(link)?;
(tag_for(&link), link)
(edits::link_tag(&link), link)
}
[tag, link] => (tag.clone(), read_arg(link)?),
_ => bail!("usage: proxy outbounds add [tag] <link|->"),
};
if link.trim_start().starts_with('{') {
let json: Value = serde_json::from_str(&link).context("not JSON")?;
let key = if json.get("protocol").is_some() { "xrayJson" } else { "singBoxJson" };
let tag2 = tag.clone();
ctl.edit(move |c| {
let list = arr(c, &["proxy", "outbounds"]);
if list.iter().any(|o| o["tag"] == tag2.as_str()) {
bail!("an outbound '{tag2}' exists");
}
let mut ob = json!({ "tag": tag2, key: json });
if let Some(d) = &detour {
ob["detour"] = d.clone().into();
}
list.push(ob);
Ok(())
})
.await?;
} else {
// Checked here first: the service would only say the outbound was left out.
ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::SingBox)
.or_else(|_| ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::Xray))
.map_err(|e| anyhow!("{e}"))?;
let tag2 = tag.clone();
ctl.edit(move |c| {
let list = arr(c, &["proxy", "outbounds"]);
if list.iter().any(|o| o["tag"] == tag2.as_str()) {
bail!("an outbound '{tag2}' exists");
}
let mut ob = json!({ "tag": tag2, "url": link });
if let Some(d) = &detour {
ob["detour"] = d.clone().into();
}
list.push(ob);
Ok(())
})
.await?;
}
let source = OutboundSource::parse(&text)?;
ctl.edit(|c| edits::add_outbound(c, &tag, &source, detour.as_deref())).await?;
println!("added {tag}");
}
OutboundVerb::Rm { tag } => {
ctl.edit(|c| {
let list = arr(c, &["proxy", "outbounds"]);
let before = list.len();
list.retain(|o| o["tag"] != tag.as_str());
if list.len() == before {
bail!("no outbound '{tag}' in the configuration");
}
Ok(())
})
.await?;
ctl.edit(|c| edits::remove_outbound(c, &tag)).await?;
println!("removed {tag}");
}
OutboundVerb::Disable { tag } => {
@@ -476,35 +499,16 @@ async fn subs(ctl: &Ctl, verb: Option<SubsVerb>) -> Result<()> {
let (tag, url) = match args.as_slice() {
[url] => {
let url = read_arg(url)?;
let host = ps_core::links::subscription::url_parts::split(&url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into());
(ps_core::links::subscription::slugify_tag(&host), url)
(edits::subscription_tag(&url), url)
}
[tag, url] => (tag.clone(), read_arg(url)?),
_ => bail!("usage: proxy subs add [tag] <url|->"),
};
let tag2 = tag.clone();
ctl.edit(move |c| {
let list = arr(c, &["proxy", "subscriptions"]);
if list.iter().any(|s| s["tag"] == tag2.as_str()) {
bail!("a subscription '{tag2}' exists");
}
list.push(json!({ "tag": tag2, "url": url }));
Ok(())
})
.await?;
ctl.edit(|c| edits::add_subscription(c, &tag, &url)).await?;
println!("added {tag}; fetching it");
}
SubsVerb::Rm { tag } => {
ctl.edit(|c| {
let list = arr(c, &["proxy", "subscriptions"]);
let before = list.len();
list.retain(|s| s["tag"] != tag.as_str());
if list.len() == before {
bail!("no subscription '{tag}'");
}
Ok(())
})
.await?;
ctl.edit(|c| edits::remove_subscription(c, &tag)).await?;
}
}
Ok(())
@@ -536,73 +540,27 @@ async fn rules(ctl: &Ctl, verb: Option<RulesVerb>) -> Result<()> {
if matches.is_empty() {
bail!("usage: proxy rules add <target> <match...>");
}
let m = sort_matches(&matches);
let name = name.unwrap_or_else(|| target.clone());
ctl.edit(|c| {
let list = arr(c, &["proxy", "routing", "rules"]);
// No --name: the rule named after the target, extended.
if let Some(rule) = list.iter_mut().find(|r| r["name"] == name.as_str()) {
for (k, v) in m.as_object().unwrap() {
let have = rule[k.as_str()].as_array().cloned().unwrap_or_default();
let mut merged = have;
for x in v.as_array().unwrap() {
if !merged.contains(x) {
merged.push(x.clone());
}
}
rule[k.as_str()] = Value::Array(merged);
}
rule["outbound"] = target.clone().into();
if let Some(p) = priority {
rule["priority"] = p.into();
}
} else {
let mut rule = m.clone();
rule["name"] = name.clone().into();
rule["outbound"] = target.clone().into();
rule["priority"] = priority.unwrap_or(50).into();
list.push(rule);
}
Ok(())
})
.await?;
ctl.edit(|c| edits::add_rule(c, &target, &matches, name.as_deref(), priority)).await?;
}
RulesVerb::Rm { name } => {
ctl.edit(|c| {
let list = arr(c, &["proxy", "routing", "rules"]);
let before = list.len();
list.retain(|r| r["name"] != name.as_str());
if list.len() == before {
bail!("no rule named '{name}'");
}
Ok(())
})
.await?;
ctl.edit(|c| edits::remove_rule(c, &name)).await?;
}
RulesVerb::Disable { name } => {
ctl.edit(|c| edits::set_rule_disabled(c, &name, true)).await?;
}
RulesVerb::Enable { name } => {
ctl.edit(|c| edits::set_rule_disabled(c, &name, false)).await?;
}
RulesVerb::Disable { name } | RulesVerb::Enable { name } if name.is_empty() => bail!("a rule name"),
RulesVerb::Disable { name } => set_rule_disabled(ctl, &name, true).await?,
RulesVerb::Enable { name } => set_rule_disabled(ctl, &name, false).await?,
}
Ok(())
}
async fn set_rule_disabled(ctl: &Ctl, name: &str, disabled: bool) -> Result<()> {
ctl.edit(|c| {
let list = arr(c, &["proxy", "routing", "rules"]);
let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?;
rule["disabled"] = disabled.into();
Ok(())
})
.await?;
Ok(())
}
async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
match verb.unwrap_or(ProxyVerb::Status) {
ProxyVerb::Status => status(ctl).await?,
ProxyVerb::On => {
ctl.edit(|c| {
c["proxy"]["enable"] = true.into();
edits::set_proxy_enabled(c, true);
Ok(())
})
.await?;
@@ -648,7 +606,7 @@ async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
}
OnOff::On => {
ctl.edit(|c| {
c["proxy"]["tun"]["enable"] = true.into();
edits::set_tun_enabled(c, true);
Ok(())
})
.await?;
@@ -659,12 +617,137 @@ async fn proxy(ctl: &Ctl, verb: Option<ProxyVerb>) -> Result<()> {
}
},
ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?),
ProxyVerb::Auto { verb } => auto(ctl, verb).await?,
}
Ok(())
}
async fn auto(ctl: &Ctl, verb: Option<AutoVerb>) -> Result<()> {
match verb.unwrap_or(AutoVerb::List) {
AutoVerb::List => {
let r = ctl.call(Request::AutoList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let state = match (r["enabled"] == true, r["running"] == true) {
(false, _) => "off (proxy.autoProxy.enable)",
(true, false) => "on, waiting for the local proxy",
(true, true) => "running",
};
println!("autoProxy: {state}");
if let Some(e) = r["egress"].as_str() {
println!(" egress {e}");
}
let domains = r["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
println!(" nothing routed yet");
} else {
println!(" {:<32} {:<20} PROBED AS", "DOMAIN", "EXIT");
for d in &domains {
println!(" {:<32} {:<20} {}", d["domain"].as_str().unwrap_or(""), d["exit"].as_str().unwrap_or(""), d["host"].as_str().unwrap_or("-"));
}
}
for e in r["exits"].as_array().into_iter().flatten().filter(|e| e["bad"] == true) {
let by: Vec<&str> = e["badBy"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
let why = if by.is_empty() { format!("{} strike(s)", e["strikes"]) } else { by.join(", ") };
println!(" bad exit {} (probed last): {why}", e["tag"].as_str().unwrap_or(""));
}
let censored = r["censored"].as_array().map_or_else(|| r["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
println!(" {} host(s) judged, {censored} left to zapret, {} waiting to be probed", r["hostsJudged"], r["backlog"]);
}
AutoVerb::Probe { target, exits, via, keep_going } => {
let r = ctl.call(Request::AutoProbe { target, exits, via: via.clone(), keep_going }).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
println!(" domain {}", r["domain"].as_str().unwrap_or(""));
let chosen = (r["exit"].as_str().unwrap_or(""), r["path"].as_str().unwrap_or(""));
println!(" exits");
for row in r["rows"].as_array().into_iter().flatten() {
let (tag, path) = (row["tag"].as_str().unwrap_or(""), row["path"].as_str().unwrap_or(""));
let f: ps_core::autoproxy::Fetch = serde_json::from_value(row["fetch"].clone()).unwrap_or_default();
let mark = if (tag, path) == chosen { " <- chosen" } else { "" };
println!(" {tag:<18} {path:<12} {:<44} {}{mark}", ps_core::autoproxy::describe(&f), row["judgement"].as_str().unwrap_or(""));
}
let verdict = r["verdict"].as_str().unwrap_or("");
match via {
Some(v) if verdict == "ok" => println!(" verdict {v} answers it as well as direct does - it can carry it"),
Some(v) => println!(" verdict {v} answers it worse than direct does"),
None => println!(" verdict {}", ps_core::autoproxy::verdict_text(verdict, r["exit"].as_str())),
}
}
AutoVerb::Learn { hosts } => {
let r = ctl.call(Request::AutoLearn { hosts }).await?;
println!("{} host(s) queued; the prober runs now (proxy-ctl logs proxy-suite-autoproxy)", r["queued"]);
}
AutoVerb::Forget { domain } => {
ctl.call(Request::AutoForget { domain: Some(domain.clone()) }).await?;
println!("forgot {domain}");
}
AutoVerb::Clear => {
ctl.call(Request::AutoForget { domain: None }).await?;
println!("forgot everything learned");
}
}
Ok(())
}
/// 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<()> {
match verb.unwrap_or(ZapretVerb::Status) {
ZapretVerb::Cutoff { verb } => return cutoff(ctl, verb).await,
ZapretVerb::Status => {
let s = ctl.call(Request::Status).await?;
let z = &s["zapret"];
@@ -679,27 +762,203 @@ async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
v @ (ZapretVerb::On | ZapretVerb::Off) => {
let on = matches!(v, ZapretVerb::On);
ctl.edit(|c| {
c["zapret"]["enable"] = on.into();
edits::set_zapret_enabled(c, on);
Ok(())
})
.await?;
}
ZapretVerb::Presets => {
let r = ctl.call(Request::ZapretPresets).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let current = r["current"].as_str().unwrap_or("");
for p in r["presets"].as_array().into_iter().flatten().filter_map(Value::as_str) {
println!("{} {p}", if p == current { "*" } else { " " });
}
}
ZapretVerb::Preset { name } => {
ctl.edit(|c| {
c["zapret"]["zapret-discord-youtube"]["configName"] = name.clone().into();
edits::set_zapret_preset(c, &name);
Ok(())
})
.await?;
}
ZapretVerb::GameFilter { filter } => {
if !matches!(filter.as_str(), "all" | "tcp" | "udp" | "null") {
bail!("the game filter is all, tcp, udp or null");
// Checked before asking the service for anything.
edits::set_game_filter(&mut Value::Null, &filter)?;
ctl.edit(|c| edits::set_game_filter(c, &filter)).await?;
}
}
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(());
}
ctl.edit(|c| {
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.clone().into();
Ok(())
})
.await?;
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<()> {
match verb.unwrap_or(AwgVerb::List) {
AwgVerb::List => {
let r = ctl.call(Request::AwgList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let profiles = r["profiles"].as_array().cloned().unwrap_or_default();
if profiles.is_empty() {
println!("No AmneziaWG profiles configured.");
return Ok(());
}
if r["enabled"] != true {
println!("AmneziaWG is off (amneziaWg.enable).");
}
println!(" {:<24} {:<12} {:<12} INTERFACE", "PROFILE", "KIND", "STATUS");
for p in profiles {
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => "system VPN",
"userspace" => "outbound",
"singBox" => "outbound (WG)",
k => k,
};
println!(" {:<24} {:<12} {:<12} {}", p["name"].as_str().unwrap_or(""), kind, p["state"].as_str().unwrap_or(""), p["interface"].as_str().unwrap_or("-"));
}
}
AwgVerb::On { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: true }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Off { profile } => {
let r = ctl.call(Request::AwgSet { name: profile.clone(), on: false }).await?;
println!("{profile}: {}", r["state"].as_str().unwrap_or("?"));
}
AwgVerb::Log { profile, lines } => {
let r = ctl.call(Request::AwgLog { name: profile, lines }).await?;
for l in r["lines"].as_array().into_iter().flatten().filter_map(Value::as_str) {
println!("{l}");
}
}
}
Ok(())
}
/// A login for the DION and Bitrix creators, which log in on their own from it.
fn password_login(platform: &str, name: &str) -> Result<String> {
let fields: &[&str] = match platform {
"dion" => &["email", "password"],
"bitrix" => &["email", "password", "portal"],
_ => bail!("{platform} logs in only in a browser: export its cookies from the desktop Creator, then: proxy-ctl wl auth {name} <file>"),
};
let mut login = serde_json::Map::new();
for field in fields {
let value = if *field == "password" {
rpassword::prompt_password("Password: ")?
} else {
eprint!("{}{}: ", field[..1].to_uppercase(), &field[1..]);
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
line.trim().to_owned()
};
let value = match *field {
"portal" => {
let portal = value.trim_end_matches('/');
if portal.contains("://") { portal.to_owned() } else { format!("https://{portal}") }
}
_ => value,
};
login.insert((*field).to_owned(), Value::String(value));
}
Ok(Value::Object(login).to_string())
}
async fn wl(ctl: &Ctl, verb: Option<WlVerb>) -> Result<()> {
let say = |r: &Value| println!("{}: {}", r["unit"].as_str().unwrap_or("?"), r["state"].as_str().unwrap_or("?"));
match verb.unwrap_or(WlVerb::List) {
WlVerb::List => {
let r = ctl.call(Request::WlList).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let list = r.as_array().cloned().unwrap_or_default();
if list.is_empty() {
println!("No whitelist-bypass creators or joiners configured.");
return Ok(());
}
println!(" {:<16} {:<8} {:<10} STATUS", "NAME", "ROLE", "PLATFORM");
for w in list {
let f = |k: &str| w[k].as_str().unwrap_or("").to_owned();
println!(" {:<16} {:<8} {:<10} {}", f("name"), f("role"), f("platform"), f("state"));
}
}
WlVerb::Link { creator } => {
let r = ctl.call(Request::WlLink { name: creator }).await?;
println!("{}", r["link"].as_str().unwrap_or(""));
}
WlVerb::Auth { creator, file } => {
let login = match file {
Some(f) => {
let text = read_arg_file(&f)?;
serde_json::from_str::<Value>(&text).context("not a cookies export, not valid JSON")?;
text
}
None => {
let list = ctl.call(Request::WlList).await?;
let platform = list
.as_array()
.into_iter()
.flatten()
.find(|w| w["name"] == creator.as_str() && w["role"] == "creator")
.and_then(|w| w["platform"].as_str().map(str::to_owned))
.with_context(|| format!("no whitelist-bypass creator '{creator}'"))?;
password_login(&platform, &creator)?
}
};
say(&ctl.call(Request::WlAuth { name: creator, login }).await?);
}
WlVerb::Join { joiner, link } => {
let link = read_arg(&link)?;
say(&ctl.call(Request::WlJoin { name: joiner, link: link.trim().to_owned() }).await?);
}
WlVerb::New { creator } => {
say(&ctl.call(Request::WlNew { name: creator.clone() }).await?);
println!("Its joiner needs the new call: proxy-ctl wl link {creator}");
}
WlVerb::Restart { name } => {
let list = ctl.call(Request::WlList).await?;
let units: Vec<String> = list
.as_array()
.into_iter()
.flatten()
.filter(|w| name.as_deref().is_none_or(|n| w["name"] == n))
.map(|w| format!("proxy-suite-wb-{}-{}", w["role"].as_str().unwrap_or(""), w["name"].as_str().unwrap_or("")))
.collect();
if units.is_empty() {
bail!("no such whitelist-bypass creator or joiner");
}
ctl.call(Request::Restart { units }).await?;
}
}
Ok(())
@@ -740,33 +999,53 @@ async fn real_main() -> Result<()> {
Some(s) => Address::Unix(s.into()),
None => Address::default_for_platform(),
};
let ctl = Ctl { addr, json: cli.json };
let ctl = Ctl { client: Client::new(addr), json: cli.json };
match cli.command {
Cmd::Status => status(&ctl).await?,
Cmd::Restart { units } => {
ctl.call(Request::Restart { units }).await?;
}
Cmd::Logs { units, lines, follow } => {
let unit = units.first().cloned();
let print = |r: Response| {
if let Some(arr) = r.data.as_array() {
for l in arr {
println!("{}: {}", l["unit"].as_str().unwrap_or(""), l["line"].as_str().unwrap_or(""));
}
} else if r.data.is_object() {
println!("{}: {}", r.data["unit"].as_str().unwrap_or(""), r.data["line"].as_str().unwrap_or(""));
}
true
};
if follow {
transport::stream(&ctl.addr, &Request::Logs { unit, lines, follow: true }, print).await?;
} else {
print(transport::call(&ctl.addr, &Request::Logs { unit, lines, follow: false }).await?);
}
ctl.client
.logs(units.first().cloned(), lines, follow, |unit, line| {
println!("{unit}: {line}");
true
})
.await?;
}
Cmd::Proxy(p) => proxy(&ctl, p.verb).await?,
Cmd::Zapret { verb } => zapret(&ctl, verb).await?,
Cmd::Components { verb } => components(&ctl, verb).await?,
Cmd::Wl { verb } => wl(&ctl, verb).await?,
Cmd::Awg { verb } => awg(&ctl, verb).await?,
Cmd::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 } => {
let r = ctl.call(Request::TgLinks).await?;
for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) {
println!("{l}");
}
}
Cmd::Config { verb } => match verb {
ConfigVerb::Get => {
let c = ctl.call(Request::ConfigGet).await?;
+259
View File
@@ -187,3 +187,262 @@ fn a_page_through_the_whole_stack() {
assert!(ctl(&socket, &["proxy", "rules"]).1.contains("process:Telegram.exe"));
let _ = std::fs::remove_dir_all(&dir);
}
/// A program on PATH, by its full path (sshd will not run by a bare name).
fn on_path(name: &str) -> Option<PathBuf> {
std::env::var_os("PATH").and_then(|p| std::env::split_paths(&p).map(|d| d.join(name)).find(|f| f.is_file()))
}
/// The SSH tunnel, offline: an sshd of the test's own on loopback, the service running
/// OpenSSH's `-D` listener to it and sing-box's SSH outbound, a page fetched through each.
#[test]
fn an_ssh_tunnel() {
let (Some(sshd), Some(keygen), true) = (on_path("sshd"), on_path("ssh-keygen"), Command::new("sing-box").arg("version").output().is_ok()) else {
eprintln!("sshd, ssh-keygen or sing-box is not on PATH: skipping");
return;
};
let dir = std::env::temp_dir().join(format!("ps-e2e-ssh-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (ssh_port, web_port, socks_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port(), free_port());
// On every address: sing-box's outbound is reached by this machine's name (below).
let web = TcpListener::bind(("0.0.0.0", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 15\r\n\r\nhello-over-ssh!");
}
});
for key in ["hostkey", "id"] {
assert!(Command::new(&keygen).args(["-q", "-t", "ed25519", "-N", "", "-f"]).arg(dir.join(key)).status().unwrap().success());
}
std::fs::copy(dir.join("id.pub"), dir.join("authorized_keys")).unwrap();
let host_key = std::fs::read_to_string(dir.join("hostkey.pub")).unwrap().split_whitespace().take(2).collect::<Vec<_>>().join(" ");
std::fs::write(
dir.join("sshd_config"),
format!(
"Port {ssh_port}\nListenAddress 127.0.0.1\nHostKey {d}/hostkey\nPidFile {d}/sshd.pid\nAuthorizedKeysFile {d}/authorized_keys\n\
UsePAM no\nStrictModes no\nPasswordAuthentication no\nKbdInteractiveAuthentication no\nAllowTcpForwarding yes\n",
d = dir.display()
),
)
.unwrap();
let mut sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap());
// One that cannot start says why, here (as root it needs its privilege separation: the
// directory /var/empty and the user sshd).
wait_for("sshd", Duration::from_secs(10), || {
if let Ok(Some(status)) = sshd.0.try_wait() {
panic!("sshd exited ({status}):\n{}", std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default());
}
std::net::TcpStream::connect(("127.0.0.1", ssh_port)).is_ok()
});
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let user = std::env::var("USER").unwrap_or_else(|_| "root".into());
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
"sshProxy": {
"enable": true,
"server": { "host": "127.0.0.1", "port": ssh_port, "user": user },
"identityFile": dir.join("id").to_string_lossy(),
"hostKey": [host_key],
"listener": { "port": socks_port },
"asOutbound": true,
},
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
let diagnose = || {
format!(
"status:\n{}\nlogs:\n{}\nsshd:\n{}\nrendered:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "40"]).1,
std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default(),
ctl(&socket, &["proxy", "config"]).1
)
};
// OpenSSH's listener, as other programs use it.
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(socks_port, "127.0.0.1", web_port).ok()
});
assert!(body.as_deref().is_some_and(|b| b.ends_with("hello-over-ssh!")), "no page through ssh -D\n{}", diagnose());
// sing-box's own SSH outbound. The proxy refuses loopback destinations (a guard), so the
// page is asked for by this machine's name, which the SSH server resolves for itself.
let host = std::fs::read_to_string("/proc/sys/kernel/hostname").unwrap_or_default().trim().to_owned();
assert!(ctl(&socket, &["proxy", "pin", "ssh-proxy"]).0, "{}", diagnose());
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(proxy_port, &host, web_port).ok().filter(|b| b.ends_with("hello-over-ssh!"))
});
assert!(body.is_some(), "no page through sing-box's SSH outbound\n{}", diagnose());
// Two logins with the copied key: OpenSSH's, then sing-box's.
let logins = std::fs::read_to_string(dir.join("sshd.log")).unwrap_or_default().matches("Accepted publickey").count();
assert_eq!(logins, 2, "{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy that wants a login (RFC 1929).
fn socks_get_login(proxy: u16, login: (&str, &str), host: &str, port: u16) -> std::io::Result<String> {
let mut s = TcpStream::connect(("127.0.0.1", proxy))?;
s.set_read_timeout(Some(Duration::from_secs(10)))?;
s.write_all(&[5, 1, 2])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let (u, p) = login;
let mut auth = vec![1, u.len() as u8];
auth.extend_from_slice(u.as_bytes());
auth.push(p.len() as u8);
auth.extend_from_slice(p.as_bytes());
s.write_all(&auth)?;
s.read_exact(&mut buf)?;
if buf[1] != 0 {
return Err(std::io::Error::other("SOCKS login refused"));
}
let ip: std::net::Ipv4Addr = host.parse().map_err(std::io::Error::other)?;
let mut req = vec![5, 1, 0, 1];
req.extend_from_slice(&ip.octets());
req.extend_from_slice(&port.to_be_bytes());
s.write_all(&req)?;
let mut reply = [0u8; 10];
s.read_exact(&mut reply)?;
if reply[1] != 0 {
return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1])));
}
s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?;
let mut body = String::new();
s.read_to_string(&mut body)?;
Ok(body)
}
fn wg_keypair() -> (String, String) {
let out = Command::new("sing-box").args(["generate", "wg-keypair"]).output().unwrap();
let text = String::from_utf8_lossy(&out.stdout).into_owned();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap_or_else(|| panic!("{text}")).trim().to_owned();
(field("PrivateKey:"), field("PublicKey:"))
}
/// AmneziaWG of the "userspace" kind, offline: sing-box as the WireGuard server on loopback
/// (answering for web.test, and taking 10.66.0.1 to this machine), the service running
/// wireproxy-awg as its client, a page through wireproxy's listener and through the proxy.
#[test]
fn an_amneziawg_tunnel() {
if Command::new("sing-box").arg("version").output().is_err() || on_path("wireproxy").is_none() {
eprintln!("sing-box or wireproxy (tools/build-wireproxy-awg.sh OUT linux) is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-awg-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (wg_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap();
std::thread::spawn(move || {
for mut s in web.incoming().flatten() {
let mut buf = [0u8; 1024];
let _ = s.read(&mut buf);
let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 16\r\n\r\nhello-through-wg");
}
});
let (srv_priv, srv_pub) = wg_keypair();
let (cli_priv, cli_pub) = wg_keypair();
let server = serde_json::json!({
"log": { "level": "warn" },
// web.test is the server's own tunnel address, which it takes to this machine's
// loopback (a tunnel's packet to 127.0.0.1 itself would be dropped as martian).
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["10.66.0.1"] } }] },
"endpoints": [{ "type": "wireguard", "tag": "wg-in", "address": ["10.66.0.1/32"], "private_key": srv_priv,
"listen_port": wg_port, "peers": [{ "public_key": cli_pub, "allowed_ips": ["10.66.0.2/32"] }] }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": {
"default_domain_resolver": "hosts",
"rules": [
{ "port": 53, "action": "hijack-dns" },
{ "ip_cidr": ["10.66.0.1/32"], "action": "route", "outbound": "direct", "override_address": "127.0.0.1" },
],
"final": "direct",
},
});
std::fs::write(dir.join("server.json"), server.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(std::fs::File::create(dir.join("server.log")).unwrap()).spawn().unwrap());
let profile = format!(
"[Interface]\nPrivateKey = {cli_priv}\nAddress = 10.66.0.2/32\nDNS = 10.66.0.1\n\n[Peer]\nPublicKey = {srv_pub}\nAllowedIPs = 0.0.0.0/0\nEndpoint = 127.0.0.1:{wg_port}\nPersistentKeepalive = 25\n"
);
let state = dir.join("state");
std::fs::create_dir_all(&state).unwrap();
let config = serde_json::json!({
"proxy": {
"enable": true,
"listener": { "port": proxy_port },
"singBox": { "clashApiPort": clash_port, "testPort": test_port },
"routing": { "directRu": false },
},
"amneziaWg": { "enable": true, "profiles": { "vpn": { "config": profile, "asOutbound": "userspace" } } },
});
std::fs::write(state.join("config.json"), config.to_string()).unwrap();
let socket = dir.join("api.sock");
let _service = Kill(
Command::new(service_binary())
.args(["--console", "--state-dir"])
.arg(&state)
.arg("--socket")
.arg(&socket)
.stderr(std::fs::File::create(dir.join("service.log")).unwrap())
.spawn()
.unwrap(),
);
wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0);
let diagnose = || {
format!(
"status:\n{}\nlogs:\n{}\nserver:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "40"]).1,
std::fs::read_to_string(dir.join("server.log")).unwrap_or_default()
)
};
// wireproxy's own listener, with the login the service gave it.
let conf = state.join("run").join("awg").join("vpn.conf");
wait_for("wireproxy's configuration", Duration::from_secs(10), || conf.is_file());
let text = std::fs::read_to_string(&conf).unwrap();
let field = |name: &str| text.lines().find_map(|l| l.strip_prefix(name)).unwrap().trim().to_owned();
let (user, password) = (field("Username ="), field("Password ="));
let port: u16 = field("BindAddress =").rsplit(':').next().unwrap().parse().unwrap();
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get_login(port, (&user, &password), "10.66.0.1", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through wireproxy\n{}", diagnose());
// The proxy's outbound "vpn", a name resolved inside the tunnel.
assert!(ctl(&socket, &["proxy", "pin", "vpn"]).0, "{}", diagnose());
let body = (0..40).find_map(|_| {
std::thread::sleep(Duration::from_millis(250));
socks_get(proxy_port, "web.test", web_port).ok().filter(|b| b.ends_with("hello-through-wg"))
});
assert!(body.is_some(), "no page through the proxy's AmneziaWG outbound\n{}", diagnose());
let _ = std::fs::remove_dir_all(&dir);
}
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "ps-gui"
description = "Proxy Suite for Windows: the desktop app"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "proxy-suite"
path = "src/main.rs"
[dependencies]
gpui-kit = { version = "0.8.1", features = ["tree-sitter"] }
gpui-tray = { version = "0.3", default-features = false, features = ["gpui-kit", "menu-state"] }
ps-client.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
async-channel = "2"
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_System_Registry",
"Win32_Networking_WinInet",
"Win32_Graphics_Dwm",
"Win32_System_Threading",
"Win32_UI_WindowsAndMessaging",
"Win32_Globalization",
] }
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

+34
View File
@@ -0,0 +1,34 @@
//! The Windows build carries the app's icon as its resource 1, where GPUI loads its windows'
//! icon from (and Explorer, the Start Menu and Settings > Apps show it). The resource compiler
//! is LLVM's (`llvm-rc`, in the dev shell), or `rc.exe` on Windows; `PS_GUI_RC` names another.
//! (Not `RC`: the dev shell sets that to MinGW's windres, which takes other arguments.) Without
//! one the app builds with Windows' default icon, and says so; tools/package.sh refuses that.
use std::path::PathBuf;
use std::process::Command;
fn main() {
let icon = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("assets/proxy-suite.ico");
println!("cargo:rerun-if-changed={}", icon.display());
println!("cargo:rerun-if-env-changed=PS_GUI_RC");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let out = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let rc = out.join("app.rc");
let res = out.join("app.res");
// The resource script's strings are C strings: backslashes doubled.
std::fs::write(&rc, format!("1 ICON \"{}\"\n", icon.display().to_string().replace('\\', "\\\\"))).unwrap();
let compiler = std::env::var("PS_GUI_RC").unwrap_or_else(|_| if cfg!(windows) { "rc.exe".into() } else { "llvm-rc".into() });
let mut command = Command::new(&compiler);
command.arg("/nologo");
if compiler.contains("llvm-rc") {
// Nothing to preprocess, so no C compiler needed for it.
command.arg("/no-preprocess");
}
match command.arg("/fo").arg(&res).arg(&rc).status() {
Ok(s) if s.success() => println!("cargo:rustc-link-arg-bins={}", res.display()),
Ok(s) => println!("cargo:warning=the app's icon: {compiler} failed ({s}); building without it"),
Err(e) => println!("cargo:warning=the app's icon: no {compiler} ({e}); building without it"),
}
}
+27
View File
@@ -0,0 +1,27 @@
//! The icons: the components' own (`Assets`), and the few more the app uses, embedded one by
//! one rather than the whole Lucide catalogue.
use std::borrow::Cow;
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, ExternalLink, Sun, Moon]);
pub struct AppAssets;
impl AssetSource for AppAssets {
fn load(&self, path: &str) -> Result<Option<Cow<'static, [u8]>>> {
match Extra.load(path)? {
Some(bytes) => Ok(Some(bytes)),
None => gpui_kit::assets::Assets.load(path),
}
}
fn list(&self, path: &str) -> Result<Vec<SharedString>> {
let mut paths = gpui_kit::assets::Assets.list(path)?;
paths.extend(Extra.list(path)?);
paths.sort();
paths.dedup();
Ok(paths)
}
}
+76
View File
@@ -0,0 +1,76 @@
//! The service, from the app's side: ps-client on a tokio runtime of its own (the transport is
//! tokio's), its answers awaited from GPUI's executor. A tokio `JoinHandle` is a plain future,
//! so either side can await it.
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Result, anyhow};
use ps_client::{Client, Saved};
use ps_ipc::Request;
use ps_ipc::transport::Address;
use serde_json::Value;
/// A log line, or the follow ending (it starts again by itself).
pub enum LogEvent {
Line { unit: String, line: String },
Lost(String),
}
#[derive(Clone)]
pub struct Bridge {
rt: Arc<tokio::runtime::Runtime>,
client: Client,
}
impl Bridge {
pub fn start(addr: Address) -> Self {
let rt = tokio::runtime::Builder::new_multi_thread()
.worker_threads(2)
.thread_name("proxy-suite-ipc")
.enable_all()
.build()
.expect("a tokio runtime");
Self { rt: Arc::new(rt), client: Client::new(addr) }
}
pub fn call(&self, req: Request) -> impl Future<Output = Result<Value>> + 'static {
let client = self.client.clone();
let task = self.rt.spawn(async move { client.call(req).await });
async move { task.await.map_err(|e| anyhow!("{e}"))? }
}
/// A configuration edit, made again on a newer configuration when another change came
/// first ([`Client::edit`]).
pub fn edit(&self, edit: impl Fn(&mut Value) -> Result<()> + Send + Sync + 'static) -> impl Future<Output = Result<Saved>> + 'static {
let client = self.client.clone();
let task = self.rt.spawn(async move { client.edit(edit).await });
async move { task.await.map_err(|e| anyhow!("{e}"))? }
}
/// Every unit's log, the last `lines` and each new line, until the receiver is dropped.
/// A lost connection is said, then made again.
pub fn follow_logs(&self, lines: usize) -> async_channel::Receiver<LogEvent> {
let (tx, rx) = async_channel::unbounded();
let client = self.client.clone();
self.rt.spawn(async move {
let mut lines = lines;
loop {
let ended = client
.logs(None, lines, true, |unit, line| tx.try_send(LogEvent::Line { unit: unit.into(), line: line.into() }).is_ok())
.await;
if tx.is_closed() {
break;
}
let why = ended.err().map(|e| e.to_string()).unwrap_or_else(|| "the service ended the log".into());
if tx.try_send(LogEvent::Lost(why)).is_err() {
break;
}
// What came before the break was seen; only what comes after is wanted.
lines = 0;
tokio::time::sleep(Duration::from_secs(2)).await;
}
});
rx
}
}
+86
View File
@@ -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)] = &[];
+59
View File
@@ -0,0 +1,59 @@
//! 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
//! 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
//! it; --hidden starts in the tray)
#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]
mod assets;
mod bridge;
mod i18n;
mod model;
mod prefs;
mod shell;
mod sysproxy;
mod ui;
use gpui_kit::*;
use ps_ipc::transport::Address;
struct Args {
address: Address,
/// Start in the tray, without the window (for starting at sign-in).
hidden: bool,
}
fn args() -> Args {
let mut out = Args { address: Address::default_for_platform(), hidden: false };
let mut args = std::env::args().skip(1);
while let Some(arg) = args.next() {
match arg.as_str() {
"--socket" => {
if let Some(s) = args.next() {
out.address = if cfg!(windows) { Address::Pipe(s) } else { Address::Unix(s.into()) };
}
}
"--hidden" => out.hidden = true,
_ => {}
}
}
out
}
fn main() {
let args = args();
let bridge = bridge::Bridge::start(args.address);
// 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::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));
shell::start(model, !args.hidden, cx);
});
}
+370
View File
@@ -0,0 +1,370 @@
//! 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`]).
use std::time::{Duration, Instant};
use anyhow::{Result, bail};
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::bridge::Bridge;
use crate::i18n::{tr, trf};
/// What a change came to.
pub enum Outcome {
Done(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)]
pub enum Connection {
Connecting,
Up,
/// Why the service cannot be reached.
Down(SharedString),
}
pub struct Model {
bridge: Bridge,
connection: Connection,
status: Value,
outbounds: Value,
/// The configuration as the service gives it (secrets hidden without that scope).
config: Value,
presets: Vec<SharedString>,
tg_links: Vec<SharedString>,
/// Changes sent and not yet answered.
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<()>,
}
impl EventEmitter<Outcome> for Model {}
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 {
pub fn new(bridge: Bridge, cx: &mut Context<Self>) -> Self {
let poller = bridge.clone();
let poll = cx.spawn(async move |this, cx| {
let mut round = 0u32;
loop {
let status = poller.call(Request::Status).await;
// Outbounds change less often than states; every fifth round, and on a reconnect.
let reconnect = this.read_with(cx, |m, _| m.connection != Connection::Up).unwrap_or(false);
let outbounds = if round.is_multiple_of(5) || reconnect { Some(poller.call(Request::Outbounds).await) } else { None };
let alive = this.update(cx, |m, cx| {
m.take_status(status, cx);
if let Some(Ok(o)) = outbounds {
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();
});
if alive.is_err() {
break;
}
round += 1;
cx.background_executor().timer(POLL).await;
}
});
Self {
bridge,
connection: Connection::Connecting,
status: Value::Null,
outbounds: Value::Null,
config: Value::Null,
presets: Vec::new(),
tg_links: Vec::new(),
pending: 0,
update: Update::Unknown,
version: env!("CARGO_PKG_VERSION").into(),
update_checked: None,
_poll: poll,
}
}
fn take_status(&mut self, status: Result<Value>, cx: &mut Context<Self>) {
match status {
Ok(s) => {
let was_up = self.connection == Connection::Up;
self.status = s;
self.connection = Connection::Up;
if !was_up {
self.load_config(cx);
self.load_presets(cx);
self.load_tg_links(cx);
}
}
Err(e) => self.connection = Connection::Down(format!("{e:#}").into()),
}
}
pub fn bridge(&self) -> &Bridge {
&self.bridge
}
pub fn connection(&self) -> &Connection {
&self.connection
}
pub fn status(&self) -> &Value {
&self.status
}
pub fn outbounds(&self) -> &Value {
&self.outbounds
}
pub fn config(&self) -> &Value {
&self.config
}
pub fn presets(&self) -> &[SharedString] {
&self.presets
}
pub fn tg_links(&self) -> &[SharedString] {
&self.tg_links
}
pub fn busy(&self) -> bool {
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.
pub fn refresh(&mut self, cx: &mut Context<Self>) {
let status = self.bridge.call(Request::Status);
let outbounds = self.bridge.call(Request::Outbounds);
cx.spawn(async move |this, cx| {
let (status, outbounds) = (status.await, outbounds.await);
this.update(cx, |m, cx| {
m.take_status(status, cx);
if let Ok(o) = outbounds {
m.outbounds = o;
}
cx.notify();
})
.ok();
})
.detach();
}
pub fn load_config(&mut self, cx: &mut Context<Self>) {
let job = self.bridge.call(Request::ConfigGet);
cx.spawn(async move |this, cx| {
if let Ok(r) = job.await {
this.update(cx, |m, cx| {
m.config = r["config"].clone();
cx.notify();
})
.ok();
}
})
.detach();
}
pub fn load_presets(&mut self, cx: &mut Context<Self>) {
let job = self.bridge.call(Request::ZapretPresets);
cx.spawn(async move |this, cx| {
if let Ok(r) = job.await {
let presets = r["presets"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|p| SharedString::from(p.to_owned())).collect();
this.update(cx, |m, cx| {
m.presets = presets;
cx.notify();
})
.ok();
}
})
.detach();
}
/// tg-ws-proxy's links: none without the secrets scope.
pub fn load_tg_links(&mut self, cx: &mut Context<Self>) {
let job = self.bridge.call(Request::TgLinks);
cx.spawn(async move |this, cx| {
let links = job.await.map(|r| r["links"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|l| SharedString::from(l.to_owned())).collect()).unwrap_or_default();
this.update(cx, |m, cx| {
m.tg_links = links;
cx.notify();
})
.ok();
})
.detach();
}
/// Runs `job`, says what came of it, and refreshes.
pub fn track(&mut self, what: impl Into<SharedString>, job: impl Future<Output = Result<()>> + 'static, cx: &mut Context<Self>) {
let what = what.into();
self.pending += 1;
cx.notify();
cx.spawn(async move |this, cx| {
let result = job.await;
this.update(cx, |m, cx| {
m.pending -= 1;
cx.emit(match result {
Ok(()) => Outcome::Done(what),
Err(e) => Outcome::Failed(format!("{what}: {e:#}").into()),
});
m.refresh(cx);
m.load_config(cx);
m.load_tg_links(cx);
})
.ok();
})
.detach();
}
/// A configuration change. Saved but not applied is a failure: the user should hear why.
pub fn edit(&mut self, what: impl Into<SharedString>, edit: impl Fn(&mut Value) -> Result<()> + Send + Sync + 'static, cx: &mut Context<Self>) {
let job = self.bridge.edit(edit);
self.track(
what,
async move {
if let Some(e) = job.await?.apply_error {
bail!(trf("saved, but not applied: {}", &[&e]));
}
Ok(())
},
cx,
);
}
pub fn request(&mut self, what: impl Into<SharedString>, req: Request, cx: &mut Context<Self>) {
let job = self.bridge.call(req);
self.track(what, async move { job.await.map(drop) }, cx);
}
/// The local proxy on (in the configuration too, as proxy-ctl's `proxy on`) or off.
pub fn set_proxy(&mut self, on: bool, cx: &mut Context<Self>) {
let bridge = self.bridge.clone();
let job = async move {
if on {
let saved = bridge
.edit(|c| {
edits::set_proxy_enabled(c, true);
Ok(())
})
.await?;
if let Some(e) = saved.apply_error {
bail!(trf("saved, but not applied: {}", &[&e]));
}
bridge.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
} else {
bridge.call(Request::Stop { unit: "proxy-suite-socks".into() }).await?;
}
Ok(())
};
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", "Локальный прокси выключен"),
];
+153
View File
@@ -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) };
}
+256
View File
@@ -0,0 +1,256 @@
//! The app's life: one window, opened again from the tray; the tray icon, coloured by how things
//! 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.
use crate::i18n::{tr, trf};
use gpui_kit::*;
use gpui_tray::{Icon, Tray};
use ps_client::edits;
use serde_json::Value;
use crate::model::{Connection, Model};
use crate::sysproxy::SystemProxy;
use crate::ui::AppView;
actions!(proxy_suite, [OpenWindow, ToggleProxy, ToggleDpi, ToggleTelegram, Quit]);
struct Shell {
model: Entity<Model>,
/// 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>,
/// The icon's colour and the tooltip now: the tray is only touched when they change (a
/// menu rebuilt while open would close).
colour: &'static str,
tooltip: String,
system_proxy: SystemProxy,
/// The system proxy's last failure, said once.
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 {}
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.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);
if let Some(icon) = icon("#6b7280", cx) {
builder = builder.icon(icon);
}
let tray = builder.build(cx);
match tray {
Ok(tray) => cx.global_mut::<Shell>().tray = Some(tray),
Err(e) => eprintln!("proxy-suite: no tray icon ({e}); closing the window quits"),
}
cx.on_window_closed(|cx, _| {
if cx.global::<Shell>().tray.is_none() && cx.windows().is_empty() && !cx.global::<Shell>().reopening {
cx.quit();
}
})
.detach();
cx.observe(&model, |_, cx| refresh(cx)).detach();
if open || cx.global::<Shell>().tray.is_none() {
open_window(&OpenWindow, cx);
}
}
fn status(cx: &App) -> (Value, bool) {
let m = cx.global::<Shell>().model.read(cx);
(m.status().clone(), *m.connection() == Connection::Up)
}
/// How things are, as a colour: working, something failed, all off, no service.
fn colour(cx: &App) -> &'static str {
let (s, up) = status(cx);
if !up {
return "#dc2626";
}
let parts = [(&s["proxy"]["on"], &s["proxy"]["state"]), (&s["zapret"]["enabled"], &s["zapret"]["state"]), (&s["tgWsProxy"]["enabled"], &s["tgWsProxy"]["state"])];
let wanted: Vec<&Value> = parts.iter().filter(|(on, _)| **on == true).map(|(_, state)| *state).collect();
if wanted.is_empty() {
"#6b7280"
} else if wanted.iter().any(|state| **state == "failed") {
"#d97706"
} else {
"#16a34a"
}
}
/// A filled shield, the app's mark, in `fill`.
fn icon(fill: &str, cx: &App) -> Option<Icon> {
let svg = format!(
r##"<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 24 24"><path d="M12 2.2 4.2 5.1v6.1c0 4.9 3.3 9.1 7.8 10.6 4.5-1.5 7.8-5.7 7.8-10.6V5.1Z" fill="{fill}" stroke="#ffffff" stroke-width="1.4" stroke-linejoin="round"/></svg>"##
);
Icon::from_gpui(&Image::from_bytes(ImageFormat::Svg, svg.into_bytes()), cx).build().inspect_err(|e| eprintln!("proxy-suite: the tray icon: {e}")).ok()
}
/// The system proxy, as the configuration and the local proxy's state say.
fn system_proxy(cx: &mut App) {
let m = cx.global::<Shell>().model.read(cx);
let (s, c) = (m.status(), m.config());
let up = *m.connection() == Connection::Up;
let want = up && c["proxy"]["systemProxy"]["enable"] == true && s["proxy"]["on"] == true && s["proxy"]["state"] == "active";
let listener = s["proxy"]["listener"].as_str().unwrap_or("").replace("0.0.0.0:", "127.0.0.1:");
let bypass: Vec<String> = c["proxy"]["systemProxy"]["bypass"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect();
if listener.is_empty() || c.is_null() {
return;
}
let shell = cx.global_mut::<Shell>();
match shell.system_proxy.update(want, &listener, &bypass) {
Ok(()) => shell.system_proxy_error = None,
Err(e) if shell.system_proxy_error.as_ref() != Some(&e) => {
eprintln!("proxy-suite: the system proxy: {e}");
shell.system_proxy_error = Some(e);
}
Err(_) => {}
}
}
fn refresh(cx: &mut App) {
system_proxy(cx);
let Some(tray) = cx.global::<Shell>().tray.clone() else { return };
let fill = colour(cx);
if fill != cx.global::<Shell>().colour {
cx.global_mut::<Shell>().colour = fill;
if let Some(icon) = icon(fill, cx)
&& let Err(e) = tray.set_icon(icon, cx)
{
eprintln!("proxy-suite: the tray icon: {e}");
}
}
let (s, up) = status(cx);
let tip = if up {
let on = |v: &Value| if *v == true { tr("on") } else { tr("off") };
trf("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", &[&on(&s["proxy"]["on"]), &on(&s["zapret"]["enabled"]), &on(&s["tgWsProxy"]["enabled"])])
} else {
tr("Proxy Suite — the service is not running").into()
};
// The tooltip says what the menu's checks do: the same news.
if tip != cx.global::<Shell>().tooltip {
cx.global_mut::<Shell>().tooltip = tip.clone();
let _ = tray.set_tooltip(Some(tip), cx);
let _ = tray.refresh_menu(cx);
}
}
fn menu(cx: &mut App) -> Vec<MenuItem> {
let (s, up) = status(cx);
vec![
MenuItem::action(tr("Open Proxy Suite"), OpenWindow),
MenuItem::separator(),
MenuItem::action(tr("Local proxy"), ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
MenuItem::action(tr("DPI bypass"), ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
MenuItem::action(tr("Telegram proxy"), ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
MenuItem::separator(),
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) {
if let Some((window, _)) = cx.global::<Shell>().window
&& window.update(cx, |_, window, _| window.activate_window()).is_ok()
{
return;
}
let model = cx.global::<Shell>().model.clone();
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(None, size(px(1080.), px(720.)), cx))),
titlebar: Some(TitlebarOptions { title: Some("Proxy Suite".into()), ..Default::default() }),
window_min_size: Some(size(px(720.), px(480.))),
app_id: Some("proxy-suite".into()),
..Default::default()
};
match gpui_kit::open_window(options, cx, |window, cx| cx.new(|cx| AppView::new(model, window, cx))) {
Ok((window, view)) => cx.global_mut::<Shell>().window = Some((window, view)),
Err(e) => eprintln!("proxy-suite: opening the window: {e}"),
}
}
fn toggle_proxy(_: &ToggleProxy, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["proxy"]["on"] == true;
model.update(cx, |m, cx| m.set_proxy(!on, cx));
}
fn toggle_dpi(_: &ToggleDpi, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["zapret"]["enabled"] != true;
model.update(cx, |m, cx| {
m.edit(
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
},
cx,
)
});
}
fn toggle_telegram(_: &ToggleTelegram, cx: &mut App) {
let model = cx.global::<Shell>().model.clone();
let on = model.read(cx).status()["tgWsProxy"]["enabled"] != true;
model.update(cx, |m, cx| {
m.edit(
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
},
cx,
)
});
}
fn quit(_: &Quit, cx: &mut App) {
cx.global_mut::<Shell>().system_proxy.restore();
if let Some(tray) = cx.global::<Shell>().tray.clone() {
let _ = tray.close(cx);
}
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 выключен"),
];
+278
View File
@@ -0,0 +1,278 @@
//! The system proxy (Windows): the signed-in user's WinINet setting, which browsers and most
//! programs follow, pointed at the local proxy while it runs and `proxy.systemProxy.enable`
//! asks for it; put back as it was when the proxy stops, the service goes, the option is turned
//! off, or the app quits. Elsewhere it does nothing.
/// WinINet's proxy settings: on or off, the server, the hosts that skip it.
#[derive(Clone, Debug, PartialEq, Eq)]
struct Settings {
enable: bool,
server: Option<String>,
bypass: Option<String>,
}
/// Where the settings live: the registry, or a test's stand-in.
trait Store {
fn read(&mut self) -> Result<Settings, String>;
fn write(&mut self, s: &Settings) -> Result<(), String>;
}
struct Registry;
impl Store for Registry {
fn read(&mut self) -> Result<Settings, String> {
platform::read()
}
fn write(&mut self, s: &Settings) -> Result<(), String> {
platform::write(s)
}
}
pub struct SystemProxy {
store: Box<dyn Store>,
/// The user's own settings, from before the app changed them.
saved: Option<Settings>,
/// What the app set, while it is set.
applied: Option<Settings>,
/// Whether a setting left behind by a killed app has been looked for: once, at the start,
/// so a proxy the user sets by hand later is theirs to keep.
looked: bool,
}
impl Default for SystemProxy {
fn default() -> Self {
Self { store: Box::new(Registry), saved: None, applied: None, looked: false }
}
}
impl SystemProxy {
/// Points the system proxy at `listener` (host:port) when `want`, puts the user's own back
/// when not. A setting the app left behind (it was killed) is cleared too.
pub fn update(&mut self, want: bool, listener: &str, bypass: &[String]) -> Result<(), String> {
let ours = Settings { enable: true, server: Some(listener.to_owned()), bypass: Some(bypass_list(bypass)) };
let first = !self.looked;
self.looked = true;
if want {
if self.applied.as_ref() == Some(&ours) {
return Ok(());
}
if self.saved.is_none() {
// At the start, one the app left set (it was killed) is not the user's: theirs
// was off.
let now = self.store.read()?;
let left = first && now.enable && now.server == ours.server;
self.saved = Some(if left { Settings { enable: false, ..now } } else { now });
}
self.store.write(&ours)?;
self.applied = Some(ours);
} else if self.applied.take().is_some() {
if let Some(saved) = self.saved.take() {
self.store.write(&saved)?;
}
} else if first {
let now = self.store.read()?;
if now.enable && now.server.as_deref() == Some(listener) {
self.store.write(&Settings { enable: false, ..now })?;
}
}
Ok(())
}
pub fn restore(&mut self) {
if self.applied.take().is_some()
&& let Some(saved) = self.saved.take()
{
let _ = self.store.write(&saved);
}
}
}
/// WinINet's bypass list: the configured hosts, and names without a dot (`<local>`).
fn bypass_list(bypass: &[String]) -> String {
let mut list: Vec<&str> = bypass.iter().map(String::as_str).filter(|h| !h.is_empty()).collect();
if !list.contains(&"<local>") {
list.push("<local>");
}
list.join(";")
}
#[cfg(windows)]
mod platform {
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::Networking::WinInet::{INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, InternetSetOptionW};
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_DWORD, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
};
use super::Settings;
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
struct Key(HKEY);
impl Drop for Key {
fn drop(&mut self) {
unsafe { RegCloseKey(self.0) };
}
}
fn open() -> Result<Key, String> {
let mut key: HKEY = std::ptr::null_mut();
let rc = unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, wide(KEY).as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) };
if rc != ERROR_SUCCESS {
return Err(format!("opening the Internet settings: error {rc}"));
}
Ok(Key(key))
}
fn query(key: &Key, name: &str) -> Option<Vec<u8>> {
let name = wide(name);
let mut len = 0u32;
let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut(), &mut len) };
if rc != ERROR_SUCCESS {
return None;
}
let mut buf = vec![0u8; len as usize];
let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), buf.as_mut_ptr(), &mut len) };
(rc == ERROR_SUCCESS).then(|| {
buf.truncate(len as usize);
buf
})
}
fn text(bytes: Vec<u8>) -> String {
let units: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0).collect();
String::from_utf16_lossy(&units)
}
pub fn read() -> Result<Settings, String> {
let key = open()?;
let enable = query(&key, "ProxyEnable").and_then(|b| b.get(..4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))).unwrap_or(0) != 0;
Ok(Settings { enable, server: query(&key, "ProxyServer").map(text), bypass: query(&key, "ProxyOverride").map(text) })
}
fn set_text(key: &Key, name: &str, value: Option<&str>) -> Result<(), String> {
let name_w = wide(name);
let rc = match value {
Some(v) => {
let data = wide(v);
unsafe { RegSetValueExW(key.0, name_w.as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) }
}
None => match unsafe { RegDeleteValueW(key.0, name_w.as_ptr()) } {
2 => ERROR_SUCCESS, // was not there
rc => rc,
},
};
if rc != ERROR_SUCCESS { Err(format!("setting {name}: error {rc}")) } else { Ok(()) }
}
pub fn write(s: &Settings) -> Result<(), String> {
let key = open()?;
let enable: u32 = s.enable.into();
let rc = unsafe { RegSetValueExW(key.0, wide("ProxyEnable").as_ptr(), 0, REG_DWORD, (&enable as *const u32).cast(), 4) };
if rc != ERROR_SUCCESS {
return Err(format!("setting ProxyEnable: error {rc}"));
}
set_text(&key, "ProxyServer", s.server.as_deref())?;
set_text(&key, "ProxyOverride", s.bypass.as_deref())?;
// Programs running now are told; others read it when they start.
unsafe {
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_SETTINGS_CHANGED, std::ptr::null(), 0);
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_REFRESH, std::ptr::null(), 0);
}
Ok(())
}
}
#[cfg(not(windows))]
mod platform {
use super::Settings;
pub fn read() -> Result<Settings, String> {
Ok(Settings { enable: false, server: None, bypass: None })
}
pub fn write(_: &Settings) -> Result<(), String> {
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::rc::Rc;
use super::*;
/// The registry, in memory, with a count of reads.
#[derive(Clone)]
struct Fake(Rc<RefCell<(Settings, usize)>>);
impl Store for Fake {
fn read(&mut self) -> Result<Settings, String> {
let mut s = self.0.borrow_mut();
s.1 += 1;
Ok(s.0.clone())
}
fn write(&mut self, s: &Settings) -> Result<(), String> {
self.0.borrow_mut().0 = s.clone();
Ok(())
}
}
fn with(settings: Settings) -> (SystemProxy, Fake) {
let fake = Fake(Rc::new(RefCell::new((settings, 0))));
(SystemProxy { store: Box::new(fake.clone()), saved: None, applied: None, looked: false }, fake)
}
fn set(server: &str, enable: bool) -> Settings {
Settings { enable, server: Some(server.into()), bypass: None }
}
#[test]
fn a_proxy_the_user_sets_by_hand_is_left_alone() {
let (mut sp, fake) = with(set("10.0.0.1:3128", true));
sp.update(false, "127.0.0.1:1080", &[]).unwrap();
// Later the user points it at the local proxy themselves.
fake.0.borrow_mut().0 = set("127.0.0.1:1080", true);
for _ in 0..3 {
sp.update(false, "127.0.0.1:1080", &[]).unwrap();
}
assert_eq!(fake.0.borrow().0, set("127.0.0.1:1080", true));
assert_eq!(fake.0.borrow().1, 1, "looked once, at the start");
}
#[test]
fn one_left_behind_is_cleared_at_the_start() {
let (mut sp, fake) = with(set("127.0.0.1:1080", true));
sp.update(false, "127.0.0.1:1080", &[]).unwrap();
assert!(!fake.0.borrow().0.enable);
}
#[test]
fn the_users_own_comes_back() {
let (mut sp, fake) = with(set("10.0.0.1:3128", true));
sp.update(true, "127.0.0.1:1080", &[]).unwrap();
assert_eq!(fake.0.borrow().0.server.as_deref(), Some("127.0.0.1:1080"));
sp.update(true, "127.0.0.1:1080", &[]).unwrap();
sp.update(false, "127.0.0.1:1080", &[]).unwrap();
assert_eq!(fake.0.borrow().0, set("10.0.0.1:3128", true));
// Left behind at the start (killed while on): the user's was off.
let (mut sp, fake) = with(Settings { bypass: Some("<local>".into()), ..set("127.0.0.1:1080", true) });
sp.update(true, "127.0.0.1:1080", &[]).unwrap();
sp.restore();
assert!(!fake.0.borrow().0.enable);
}
#[test]
fn bypass_always_has_local_names() {
assert_eq!(bypass_list(&[]), "<local>");
assert_eq!(bypass_list(&["*.lan".into(), "<local>".into()]), "*.lan;<local>");
}
}
+237
View File
@@ -0,0 +1,237 @@
//! AmneziaWG: its profiles, system-wide VPNs (started and stopped here, their tunnel's log) or
//! outbounds of the proxy; one added from an AmneziaVPN vpn:// link or a .conf, or removed.
use std::collections::BTreeMap;
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::i18n::{tr, trf};
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const KINDS: [(&str, &str); 3] = [("vpn", "System-wide VPN"), ("userspace", "Outbound (AmneziaWG)"), ("singBox", "Outbound (plain WireGuard)")];
pub struct AmneziaWgPage {
model: Entity<Model>,
name: Entity<InputState>,
text: Entity<TextareaState>,
kind: usize,
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// A profile's tunnel log, while shown.
logs: BTreeMap<String, Result<Vec<String>, String>>,
_subscriptions: Vec<Subscription>,
}
impl AmneziaWgPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("home"));
let text = cx.new(|cx| TextareaState::new(window, cx).rows(5).placeholder(tr("vpn://… from AmneziaVPN, or a .conf: [Interface] …")));
let subscriptions = vec![cx.observe(&model, |this, _, cx| {
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(3)) {
this.load(cx);
}
})];
let mut this = Self { model, name, text, kind: 0, list: Ok(Value::Null), loaded_at: None, logs: BTreeMap::new(), _subscriptions: subscriptions };
this.load(cx);
this
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AwgList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn set(&mut self, name: String, on: bool, cx: &mut Context<Self>) {
let what = if on { trf("{}: tunnel up", &[&name]) } else { trf("{}: tunnel down", &[&name]) };
let job = self.model.read(cx).bridge().call(Request::AwgSet { name, on });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn toggle_log(&mut self, name: String, cx: &mut Context<Self>) {
if self.logs.remove(&name).is_some() {
cx.notify();
return;
}
let job = self.model.read(cx).bridge().call(Request::AwgLog { name: name.clone(), lines: 30 });
cx.spawn(async move |this, cx| {
let r = job.await.map(|v| v["lines"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect()).map_err(|e| format!("{e:#}"));
this.update(cx, |this, cx| {
this.logs.insert(name, r);
cx.notify();
})
.ok();
})
.detach();
}
fn add(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let name = self.name.read(cx).value().trim().to_owned();
let text = self.text.read(cx).value().to_string();
let kind = KINDS[self.kind].0;
// Checked here first, for a message at once.
if let Err(e) = edits::add_awg_profile(&mut serde_json::json!({}), &name, &text, kind) {
window.push_notification(Notification::error(format!("{e:#}")), cx);
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
self.text.update(cx, |s, cx| s.set_value("", window, cx));
let what = 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));
}
fn remove(&mut self, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(trf("AmneziaWG profile '{}' removed", &[&name]), move |c| edits::remove_awg_profile(c, &name), cx));
}
}
impl Render for AmneziaWgPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let body = page("AmneziaWG", cx);
if m.config().is_null() {
return body.child(hint(tr("Waiting for the service…"), cx));
}
let on = m.config()["amneziaWg"]["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("awg-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { tr("AmneziaWG is on") } else { tr("AmneziaWG is off") },
move |c| {
edits::set_path(c, &["amneziaWg", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let about = card("AmneziaWG", Some(enable.into_any_element()), cx).child(hint(
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,
));
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 {
Err(e) => profiles = profiles.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let list = l["profiles"].as_array().cloned().unwrap_or_default();
if list.is_empty() {
profiles = profiles.child(hint(tr("None yet: add one below."), cx));
}
for (i, p) in list.iter().enumerate() {
let name = p["name"].as_str().unwrap_or("").to_owned();
let vpn = p["kind"] == "vpn";
let state = p["state"].as_str().unwrap_or("").to_owned();
let kind = match p["kind"].as_str().unwrap_or("") {
"vpn" => Tag::info().child(tr("system VPN")),
"userspace" => Tag::secondary().child(tr("outbound")),
_ => Tag::secondary().child(tr("outbound (WireGuard)")),
};
let mut line = div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(kind)
// 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());
if vpn {
let (n1, n2) = (name.clone(), name.clone());
let running = matches!(state.as_str(), "active" | "activating");
line = line
.child(Button::new(("awg-log", i)).small().ghost().label(tr("Log")).on_click(cx.listener(move |this, _, _, cx| this.toggle_log(n1.clone(), cx))))
.child(
Switch::new(("awg-on", i))
.checked(running)
.disabled(!on)
.on_change(cx.listener(move |this, v: &bool, _, cx| this.set(n2.clone(), *v, cx))),
);
}
let n3 = name.clone();
line = line.child(Button::new(("awg-remove", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove(n3.clone(), cx))));
let mut row = div().v_flex().gap_2().py_2().border_t_1().border_color(cx.theme().border).child(line);
match self.logs.get(&name) {
Some(Ok(lines)) => {
let text = if lines.is_empty() { 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));
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
None => {}
}
profiles = profiles.child(row);
}
}
}
let kinds = RadioGroup::horizontal("awg-kind").children(KINDS.map(|(_, label)| tr(label))).selected_index(Some(self.kind)).on_change(cx.listener(|this, ix: &usize, _, cx| {
this.kind = *ix;
cx.notify();
}));
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(tr("Name (also the adapter's)"))).child(Input::new(&self.name)))
.child(kinds)
.child(Textarea::new(&self.text))
.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)
}
}
/// 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."),
];
+384
View File
@@ -0,0 +1,384 @@
//! autoProxy: on or off; a site probed through each exit, or learned now; the sites it routed
//! and through what, each forgotten on its own; the exits, bad ones marked; what it never
//! touches, and how slow a site must be to be moved.
use std::time::{Duration, Instant};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::{Value, json};
use super::widgets::{card, hint, page, Inactive as _};
use crate::i18n::{tr, trf};
use crate::model::Model;
pub struct AutoProxyPage {
model: Entity<Model>,
site: Entity<InputState>,
exclude: Entity<TextareaState>,
slow: Entity<InputState>,
/// What the service listed last, or why it could not.
list: Result<Value, String>,
loaded_at: Option<Instant>,
/// The last probe: its answer, or that it runs.
probe: Option<Result<Value, String>>,
probing: bool,
/// The exclusions and threshold the inputs were last filled from (see the DPI page).
shown: (String, String),
_subscriptions: Vec<Subscription>,
}
impl AutoProxyPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let site = cx.new(|cx| InputState::new(window, cx).placeholder("example.com"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(4).placeholder(tr("intranet.example — one per line")));
let slow = cx.new(|cx| InputState::new(window, cx).placeholder("150"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| {
this.sync(window, cx);
// The listing with the service's own refresh, every few seconds at most.
if this.loaded_at.is_none_or(|t| t.elapsed() > Duration::from_secs(5)) {
this.load(cx);
}
})];
let mut this = Self {
model,
site,
exclude,
slow,
list: Ok(Value::Null),
loaded_at: None,
probe: None,
probing: false,
shown: Default::default(),
_subscriptions: subscriptions,
};
this.sync(window, cx);
this.load(cx);
this
}
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let a = self.model.read(cx).config()["proxy"]["autoProxy"].clone();
let exclude = a["exclude"].as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n");
let slow = a["slowBelowKiBps"].as_u64().map(|n| n.to_string()).unwrap_or_default();
let fresh = (exclude, slow);
if fresh != self.shown {
if self.exclude.read(cx).value() == self.shown.0.as_str() {
let v = fresh.0.clone();
self.exclude.update(cx, |s, cx| s.set_value(v, window, cx));
}
if self.slow.read(cx).value() == self.shown.1.as_str() {
let v = fresh.1.clone();
self.slow.update(cx, |s, cx| s.set_value(v, window, cx));
}
self.shown = fresh;
}
}
fn load(&mut self, cx: &mut Context<Self>) {
self.loaded_at = Some(Instant::now());
let job = self.model.read(cx).bridge().call(Request::AutoList);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn site(&self, window: &mut Window, cx: &mut Context<Self>) -> Option<String> {
let site = self.site.read(cx).value().trim().trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_owned();
if site.is_empty() {
window.push_notification(Notification::error(tr("Type a site first: example.com")), cx);
return None;
}
Some(site)
}
fn probe(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(target) = self.site(window, cx) else { return };
self.probing = true;
self.probe = None;
cx.notify();
let job = self.model.read(cx).bridge().call(Request::AutoProbe { target, exits: None, via: None, keep_going: true });
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.probing = false;
this.probe = Some(r.map_err(|e| format!("{e:#}")));
cx.notify();
})
.ok();
})
.detach();
}
fn learn(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(site) = self.site(window, cx) else { return };
let site = site.split('/').next().unwrap_or("").to_owned();
self.model.update(cx, |m, cx| m.request(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>) {
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 model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
model.update(cx, |m, cx| m.track(what, async move { r.map(drop) }, cx));
this.update(cx, |this, cx| this.load(cx)).ok();
})
.detach();
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let exclude: Vec<String> = self.exclude.read(cx).value().lines().map(|l| l.trim().to_owned()).filter(|l| !l.is_empty()).collect();
let slow_text = self.slow.read(cx).value().trim().to_owned();
let Ok(slow) = (if slow_text.is_empty() { Ok(0) } else { slow_text.parse::<u32>() }) else {
window.push_notification(Notification::error(trf("“{}” is not a speed in KiB/s (0 turns it off)", &[&slow_text])), cx);
return;
};
self.shown = (self.exclude.read(cx).value().to_string(), self.slow.read(cx).value().to_string());
self.model.update(cx, |m, cx| {
m.edit(
"autoProxy saved",
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "exclude"], json!(exclude));
edits::set_path(c, &["proxy", "autoProxy", "slowBelowKiBps"], json!(slow));
Ok(())
},
cx,
)
});
}
}
fn row(cx: &App) -> Div {
div().h_flex().gap_3().items_center().py_2().border_t_1().border_color(cx.theme().border)
}
impl Render for AutoProxyPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let a = m.config()["proxy"]["autoProxy"].clone();
let body = page("autoProxy", cx);
if m.config().is_null() {
return body.child(hint(tr("Waiting for the service…"), cx));
}
let list = self.list.clone();
let on = a["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("ap-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { tr("autoProxy is on") } else { tr("autoProxy is off") },
move |c| {
edits::set_path(c, &["proxy", "autoProxy", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let running = list.as_ref().is_ok_and(|l| l["running"] == true);
let state = match (on, running) {
(false, _) => Tag::secondary().child(tr("off")),
(true, false) => Tag::warning().child(tr("waiting for the local proxy")),
(true, true) => Tag::success().child(tr("running")),
};
let about = card("autoProxy", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state))
.child(hint(
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,
));
let probing = self.probing;
let mut try_card = card(tr("Probe or learn a site"), None, 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(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(&self.site)))
.child(
Button::new("ap-probe")
.small()
.icon(IconName::Gauge)
.label(if probing { tr("Probing…") } else { tr("Probe") })
.inactive(probing || !running, cx)
.on_click(cx.listener(|this, _, window, cx| this.probe(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 {
Some(Ok(p)) => {
let verdict = p["verdict"].as_str().unwrap_or("");
let text = match verdict {
"ok" => tr("Reachable directly: nothing to do").to_owned(),
"destination" => trf("Blocked directly: routed through {}", &[&p["exit"].as_str().unwrap_or(tr("an exit"))]),
"censor" => tr("Cut on the way: zapret's to fix, left direct").to_owned(),
"both-fail" => tr("Fails through every exit: not a block").to_owned(),
"unreachable" => tr("No exit reaches it at all").to_owned(),
v => v.to_owned(),
};
try_card = try_card.child(div().font_medium().child(text));
for r in p["rows"].as_array().into_iter().flatten() {
let f = &r["fetch"];
let what = match f["status"].as_u64() {
Some(s) => trf("{}, {} bytes{}", &[&s, &f["bytes"], &f["block"].as_str().filter(|b| !b.is_empty()).map(|b| trf(", {} page", &[&b])).unwrap_or_default()]),
None => trf("no answer ({})", &[&f["error"].as_str().unwrap_or("")]),
};
let judgement = r["judgement"].as_str().unwrap_or("");
let tag = match judgement {
"ok" => Tag::success(),
"dead" => Tag::danger(),
_ => Tag::warning(),
};
try_card = try_card.child(
row(cx)
.text_sm()
.child(div().w(px(150.)).truncate().child(r["tag"].as_str().unwrap_or("").to_owned()))
.child(div().w(px(100.)).text_color(cx.theme().muted_foreground).child(r["path"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().child(what))
.child(tag.child(judgement.to_owned())),
);
}
}
Some(Err(e)) => try_card = try_card.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
None => {}
}
let mut routed = card(
tr("Routed sites"),
Some(
div()
.h_flex()
.gap_2()
.child(Button::new("ap-reload").small().icon(IconName::RefreshCw).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(Button::new("ap-clear").small().ghost().icon(IconName::Trash).label(tr("Forget all")).on_click(cx.listener(|this, _, _, cx| this.forget(None, cx))))
.into_any_element(),
),
cx,
);
match &list {
Err(e) => routed = routed.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(l) => {
let domains = l["domains"].as_array().cloned().unwrap_or_default();
if domains.is_empty() {
routed = routed.child(hint(tr("Nothing routed yet."), cx));
}
for (i, d) in domains.iter().enumerate() {
let domain = d["domain"].as_str().unwrap_or("").to_owned();
let why = if d["verdict"] == "slow" { Tag::warning().child(tr("slow")) } else { Tag::danger().child(tr("blocked")) };
let forget = domain.clone();
routed = routed.child(
row(cx)
.child(div().flex_1().min_w_0().truncate().font_medium().child(domain))
.child(why)
.child(div().w(px(160.)).truncate().text_sm().child(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)))),
);
}
let censored = l["censored"].as_array().map_or_else(|| l["censored"].as_u64().unwrap_or(0) as usize, Vec::len);
routed = routed.child(hint(
trf(
"{} site(s) judged; {} left to zapret; {} waiting to be probed; {} crawling, to be moved.",
&[&l["hostsJudged"].as_u64().unwrap_or(0), &censored, &l["backlog"].as_u64().unwrap_or(0), &l["slowWaiting"].as_u64().unwrap_or(0)],
),
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 {
for e in l["exits"].as_array().into_iter().flatten() {
let bad = e["bad"] == true;
exits = exits.child(
row(cx)
.child(div().w(px(180.)).truncate().font_medium().child(e["tag"].as_str().unwrap_or("").to_owned()))
.child(div().flex_1().min_w_0().truncate().text_sm().text_color(cx.theme().muted_foreground).child(format!(
"{} {}",
e["ip"].as_str().unwrap_or(""),
e["asn"].as_str().unwrap_or("")
)))
.child(if bad { Tag::danger().child(tr("bad")) } else { Tag::success().child(tr("ok")) }),
);
}
}
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(
div()
.h_flex()
.gap_4()
.items_start()
.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(tr("Move sites slower than (KiB/s, 0: never)"))).child(Input::new(&self.slow))),
)
.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)
}
}
/// 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."),
];
+126
View File
@@ -0,0 +1,126 @@
//! 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).
use crate::i18n::{tr, trf};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::Button;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, Inactive as _};
use crate::model::Model;
pub struct ComponentsPage {
model: Entity<Model>,
list: Result<Vec<Value>, String>,
installing: bool,
}
impl ComponentsPage {
pub fn new(model: Entity<Model>, cx: &mut Context<Self>) -> Self {
let mut this = Self { model, list: Ok(Vec::new()), installing: false };
this.load(cx);
this
}
fn load(&mut self, cx: &mut Context<Self>) {
let job = self.model.read(cx).bridge().call(Request::Components);
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.list = r.map(|v| v.as_array().cloned().unwrap_or_default()).map_err(|e| format!("{e:#}"));
cx.notify();
})
.ok();
})
.detach();
}
fn install(&mut self, names: Vec<String>, cx: &mut Context<Self>) {
self.installing = true;
cx.notify();
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 model = self.model.clone();
cx.spawn(async move |this, cx| {
// Each component's own failure comes back in the list, not as an error.
let result = job.await.and_then(|r| {
let failed: Vec<String> = r.as_array().into_iter().flatten().filter_map(|c| Some(format!("{}: {}", c["name"].as_str()?, c["error"].as_str()?))).collect();
if failed.is_empty() { Ok(()) } else { Err(anyhow::anyhow!(failed.join("; "))) }
});
model.update(cx, |m, cx| m.track(what, async move { result }, cx));
this.update(cx, |this, cx| {
this.installing = false;
this.load(cx);
})
.ok();
})
.detach();
}
}
impl Render for ComponentsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let actions = div()
.h_flex()
.gap_2()
.child(Button::new("comp-reload").small().icon(IconName::RefreshCw).label(tr("Reload")).on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(
Button::new("comp-install")
.small()
.icon(IconName::Download)
.label(if self.installing { tr("Installing…") } else { tr("Fetch all again") })
.inactive(self.installing, cx)
.on_click(cx.listener(|this, _, _, cx| this.install(Vec::new(), cx))),
);
let mut list = card(tr("Programs"), Some(actions.into_any_element()), cx).child(hint(
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,
));
match &self.list {
Err(e) => list = list.child(div().text_sm().text_color(cx.theme().danger).child(e.clone())),
Ok(items) => {
for c in items {
let want = c["version"].as_str().unwrap_or("");
let have = c["installed"].as_str();
let state = match have {
Some(v) if v == want => Tag::success().child(tr("installed")),
Some(v) => Tag::warning().child(trf("{} installed", &[&v])),
None => Tag::danger().child(tr("missing")),
};
list = list.child(
div()
.h_flex()
.gap_3()
.items_center()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(div().w(px(130.)).font_medium().child(c["name"].as_str().unwrap_or("").to_owned()))
.child(div().w(px(190.)).text_sm().child(want.to_owned()))
.child(state)
.child(div().flex_1().min_w_0().truncate().text_xs().text_color(cx.theme().muted_foreground).child(format!("{} · {}", c["license"].as_str().unwrap_or(""), c["homepage"].as_str().unwrap_or("")))),
);
}
}
}
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", "Компоненты"),
];
+419
View File
@@ -0,0 +1,419 @@
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies and its 16 KB
//! 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::input::{Textarea, TextareaState};
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::select::{Select, SelectEvent, SelectState};
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{Inactive as _, card, hint, page, state_tag};
use crate::i18n::{tr, trf};
use crate::model::Model;
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")];
/// Preset names as the service matches them: without spaces, any case.
fn same_preset(a: &str, b: &str) -> bool {
let squash = |s: &str| s.chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase();
squash(a) == squash(b)
}
fn lines(v: &Value) -> String {
v.as_array().into_iter().flatten().filter_map(Value::as_str).collect::<Vec<_>>().join("\n")
}
pub struct DpiPage {
model: Entity<Model>,
preset: Entity<SelectState<Vec<SharedString>>>,
presets: Vec<SharedString>,
domains: Entity<TextareaState>,
exclude: Entity<TextareaState>,
/// 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.
shown: (String, String, String),
/// The cutoff probe's findings (`zapret-cutoff`), followed while it probes.
cutoff: Value,
_cutoff_poll: Option<Task<()>>,
_subscriptions: Vec<Subscription>,
}
impl DpiPage {
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 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(tr("bank.example — one per line")));
let subscriptions = vec![
cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx)),
cx.subscribe_in(&preset, window, |this, _, event: &SelectEvent<Vec<SharedString>>, _, cx| {
if let SelectEvent::Confirm(Some(name)) = event {
let name = name.to_string();
this.model.update(cx, |m, cx| {
m.edit(
trf("Preset: {}", &[&name]),
move |c| {
edits::set_zapret_preset(c, &name);
Ok(())
},
cx,
)
});
}
}),
];
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.follow_cutoff(false, cx);
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 {
config["zapret"]["engine"].as_str().unwrap_or("zapret-discord-youtube").to_owned()
}
/// Brings the controls up to what the service says.
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let m = self.model.read(cx);
let config = m.config().clone();
let presets = m.presets().to_vec();
if config.is_null() {
return;
}
if presets != self.presets {
self.presets = presets.clone();
self.preset.update(cx, |s, cx| s.set_items(presets, window, cx));
}
let configured = config["zapret"]["zapret-discord-youtube"]["configName"].as_str().unwrap_or("");
if let Some(name) = self.presets.iter().find(|p| same_preset(p, configured)).cloned()
&& self.preset.read(cx).selected_value() != Some(&name)
{
self.preset.update(cx, |s, cx| s.set_selected_value(&name, window, cx));
}
let engine = Self::engine(&config);
let fresh = (engine.clone(), lines(&config["zapret"][&engine]["domains"]), lines(&config["zapret"][&engine]["excludeDomains"]));
if fresh != self.shown {
let switched = fresh.0 != self.shown.0;
if switched || self.domains.read(cx).value() == self.shown.1.as_str() {
let text = fresh.1.clone();
self.domains.update(cx, |s, cx| s.set_value(text, window, cx));
}
if switched || self.exclude.read(cx).value() == self.shown.2.as_str() {
let text = fresh.2.clone();
self.exclude.update(cx, |s, cx| s.set_value(text, window, cx));
}
self.shown = fresh;
}
}
fn save_sites(&mut self, cx: &mut Context<Self>) {
let split = |t: &str| t.split(['\n', ',', ' ']).map(str::to_owned).filter(|d| !d.trim().is_empty()).collect::<Vec<_>>();
let (domains_text, exclude_text) = (self.domains.read(cx).value().to_string(), self.exclude.read(cx).value().to_string());
let (domains, exclude) = (split(&domains_text), split(&exclude_text));
// Handed over: the lists the service saves (tidied) replace what was typed.
self.shown.1 = domains_text;
self.shown.2 = exclude_text;
let engine = Self::engine(self.model.read(cx).config());
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.
fn option_switch(&self, id: &'static str, label: &'static str, path: &'static [&'static str], config: &Value) -> Switch {
let mut v = config;
for p in path {
v = &v[*p];
}
let model = self.model.clone();
Switch::new(id).label(label).checked(v == true).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
format!("{label}: {}", tr(if on { "on" } else { "off" })),
move |c| {
edits::set_path(c, path, on.into());
Ok(())
},
cx,
)
})
})
}
}
impl Render for DpiPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let status = m.status()["zapret"].clone();
let config = m.config().clone();
let engine = Self::engine(&config);
let body = page(tr("DPI bypass"), cx);
if config.is_null() {
return body.child(hint(tr("Waiting for the service…"), cx));
}
let model = self.model.clone();
let enable = Switch::new("dpi-on").checked(config["zapret"]["enable"] == true).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
tr(if on { "The DPI bypass is on" } else { "The DPI bypass is off" }),
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
},
cx,
)
})
});
let model = self.model.clone();
let engines = RadioGroup::horizontal("engine")
.children(ENGINES.map(|(_, label)| tr(label)))
.selected_index(ENGINES.iter().position(|(e, _)| *e == engine))
.on_change(move |ix, _, cx| {
let (engine, label) = ENGINES[*ix];
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(
card("zapret", Some(enable.into_any_element()), cx)
.child(div().h_flex().child(state_tag(status["state"].as_str().unwrap_or("unknown"))))
.child(engines)
.child(hint(
if engine == "zapret2" {
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 {
tr("Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists.")
},
cx,
)),
);
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(
card("zapret2", None, cx)
.child(div().text_sm().child(tr("Strategies")))
.child(sources)
.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 {
let model = self.model.clone();
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
body = body
.child(
card(tr("Preset"), None, 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(tr("Choose a preset")).menu_max_h(px(320.))),
)
.child(
card(tr("Game traffic"), None, cx).child(hint(tr("Also handle game traffic, on ports above 1023."), cx)).child(
RadioGroup::horizontal("game-filter")
.children(GAME_FILTERS.map(|(_, label)| tr(label)))
.selected_index(GAME_FILTERS.iter().position(|(v, _)| *v == filter))
.on_change(move |ix, _, cx| {
let (value, label) = GAME_FILTERS[*ix];
model.update(cx, |m, cx| m.edit(trf("Game traffic: {}", &[&tr(label)]), move |c| edits::set_game_filter(c, value), cx));
}),
),
);
}
body.child(
card(
tr("Your sites"),
Some(Button::new("save-sites").small().label(tr("Save")).on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
cx,
)
.child(hint(tr("Sites to handle besides the engine's own lists, and sites to leave alone."), cx))
.child(
div()
.h_flex()
.gap_4()
.items_start()
.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(tr("Leave alone"))).child(Textarea::new(&self.exclude))),
),
)
.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 (нужны некоторым стратегиям)"),
];
+162
View File
@@ -0,0 +1,162 @@
//! 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 gpui_kit::component::button::Button;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use super::widgets::{card, hint, page};
use crate::bridge::LogEvent;
use crate::model::Model;
const KEEP: usize = 5000;
/// The line without its terminal colours (sing-box and XRay write them).
fn plain(line: &str) -> String {
let mut out = String::with_capacity(line.len());
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
if c == '\u{1b}' && chars.peek() == Some(&'[') {
chars.next();
for c in chars.by_ref() {
if c.is_ascii_alphabetic() {
break;
}
}
} else {
out.push(c);
}
}
out
}
/// A unit's short name: what follows "proxy-suite-".
fn short(unit: &str) -> &str {
unit.strip_prefix("proxy-suite-").unwrap_or(unit)
}
pub struct LogsPage {
lines: VecDeque<(SharedString, SharedString)>,
units: Vec<SharedString>,
/// Only this unit's lines; all with none.
only: Option<SharedString>,
follow: bool,
lost: Option<SharedString>,
scroll: UniformListScrollHandle,
_drain: Task<()>,
}
impl LogsPage {
pub fn new(model: Entity<Model>, cx: &mut Context<Self>) -> Self {
let events = model.read(cx).bridge().follow_logs(500);
let drain = cx.spawn(async move |this, cx| {
while let Ok(first) = events.recv().await {
// What has piled up comes in one update, not one per line.
let mut batch = vec![first];
while let Ok(more) = events.try_recv() {
batch.push(more);
}
if this.update(cx, |this, cx| this.take(batch, cx)).is_err() {
break;
}
}
});
Self { lines: VecDeque::new(), units: Vec::new(), only: None, follow: true, lost: None, scroll: UniformListScrollHandle::new(), _drain: drain }
}
fn take(&mut self, batch: Vec<LogEvent>, cx: &mut Context<Self>) {
for event in batch {
match event {
LogEvent::Line { unit, line } => {
self.lost = None;
let unit = SharedString::from(unit);
if !self.units.contains(&unit) {
self.units.push(unit.clone());
self.units.sort();
}
self.lines.push_back((unit, plain(&line).into()));
if self.lines.len() > KEEP {
self.lines.pop_front();
}
}
LogEvent::Lost(why) => self.lost = Some(why.into()),
}
}
if self.follow {
let shown = self.shown().len();
if shown > 0 {
self.scroll.scroll_to_item(shown - 1, ScrollStrategy::Bottom);
}
}
cx.notify();
}
fn shown(&self) -> Vec<usize> {
(0..self.lines.len()).filter(|i| self.only.as_ref().is_none_or(|u| &self.lines[*i].0 == u)).collect()
}
}
impl Render for LogsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let shown = self.shown();
let mut choices: Vec<SharedString> = vec![tr("All").into()];
choices.extend(self.units.iter().map(|u| SharedString::from(short(u).to_owned())));
let selected = match &self.only {
None => 0,
Some(u) => self.units.iter().position(|x| x == u).map_or(0, |i| i + 1),
};
let filter = RadioGroup::horizontal("log-unit").children(choices).selected_index(Some(selected)).on_change(cx.listener(|this, ix: &usize, _, cx| {
this.only = if *ix == 0 { None } else { this.units.get(*ix - 1).cloned() };
cx.notify();
}));
let follow = Switch::new("log-follow").label(tr("Follow")).checked(self.follow).on_change(cx.listener(|this, on: &bool, _, cx| {
this.follow = *on;
cx.notify();
}));
let clear = Button::new("log-clear").small().label(tr("Clear")).on_click(cx.listener(|this, _, _, cx| {
this.lines.clear();
cx.notify();
}));
let lines = uniform_list(
"log-lines",
shown.len(),
cx.processor(move |this, range: std::ops::Range<usize>, _, cx| {
range
.map(|i| {
let (unit, line) = &this.lines[shown[i]];
div()
.h_flex()
.gap_2()
.text_xs()
.font_family("monospace")
.child(div().w(px(110.)).flex_none().truncate().text_color(cx.theme().muted_foreground).child(short(unit).to_owned()))
.child(div().flex_1().min_w_0().truncate().child(line.clone()))
})
.collect()
}),
)
.track_scroll(&self.scroll)
.h(px(460.));
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 {
body = body.child(hint(trf("Not receiving logs: {}", &[&why]), cx));
}
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: {}", "Журналы не поступают: {}"),
];
+231
View File
@@ -0,0 +1,231 @@
//! The window: a sidebar of pages, the page shown, and what came of each change as a
//! notification.
pub(crate) mod amneziawg;
pub(crate) mod autoproxy;
pub(crate) mod components;
pub(crate) mod dpi;
pub(crate) mod logs;
pub(crate) mod outbounds;
pub(crate) mod overview;
pub(crate) mod settings;
pub(crate) mod telegram;
pub(crate) mod whitelist;
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::sidebar::{Sidebar, SidebarFooter, SidebarGroup, SidebarHeader, SidebarMenu, SidebarMenuItem};
use gpui_kit::assets::IconName;
use gpui_kit::component::*;
use gpui_kit::*;
use crate::model::{Connection, Model, Outcome};
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Page {
Overview,
Dpi,
Telegram,
Whitelist,
Outbounds,
AutoProxy,
AmneziaWg,
Logs,
Settings,
Components,
}
impl Page {
const ALL: [Page; 10] = [
Page::Overview,
Page::Dpi,
Page::Telegram,
Page::Whitelist,
Page::Outbounds,
Page::AutoProxy,
Page::AmneziaWg,
Page::Logs,
Page::Settings,
Page::Components,
];
fn title(self) -> &'static str {
match self {
Page::Overview => "Overview",
Page::Dpi => "DPI bypass",
Page::Telegram => "Telegram proxy",
Page::Whitelist => "Whitelist bypass",
Page::Outbounds => "Outbounds",
Page::AutoProxy => "autoProxy",
Page::AmneziaWg => "AmneziaWG",
Page::Logs => "Logs",
Page::Settings => "Settings",
Page::Components => "Components",
}
}
fn icon(self) -> IconName {
match self {
Page::Overview => IconName::LayoutDashboard,
Page::Dpi => IconName::Shield,
Page::Telegram => IconName::Send,
Page::Whitelist => IconName::Video,
Page::Outbounds => IconName::Globe,
Page::AutoProxy => IconName::Route,
Page::AmneziaWg => IconName::Lock,
Page::Logs => IconName::SquareTerminal,
Page::Settings => IconName::Settings,
Page::Components => IconName::Package,
}
}
}
pub struct AppView {
model: Entity<Model>,
page: Page,
dpi: Entity<dpi::DpiPage>,
telegram: Entity<telegram::TelegramPage>,
outbounds: Entity<outbounds::OutboundsPage>,
/// Made when first shown.
whitelist: Option<Entity<whitelist::WhitelistPage>>,
autoproxy: Option<Entity<autoproxy::AutoProxyPage>>,
amneziawg: Option<Entity<amneziawg::AmneziaWgPage>>,
/// Made when first shown: following the logs starts then.
logs: Option<Entity<logs::LogsPage>>,
/// Made when first shown, as it loads the configuration into its editor then.
settings: Option<Entity<settings::SettingsPage>>,
components: Option<Entity<components::ComponentsPage>>,
_subscriptions: Vec<Subscription>,
}
impl AppView {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let subscriptions = vec![
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| {
let note = match outcome {
Outcome::Done(m) => Notification::success(m.clone()),
Outcome::Failed(m) => Notification::error(m.clone()).autohide(false),
};
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 telegram = cx.new(|cx| telegram::TelegramPage::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 }
}
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 {
let items = Page::ALL.map(|page| {
SidebarMenuItem::new(tr(page.title())).icon(page.icon()).active(self.page == page).on_click(cx.listener(move |this, _, _, cx| {
this.page = page;
cx.notify();
}))
});
let m = self.model.read(cx);
let (colour, state) = match m.connection() {
Connection::Up if m.busy() => (cx.theme().warning, tr("Applying…")),
Connection::Up => (cx.theme().success, tr("Connected to the service")),
Connection::Connecting => (cx.theme().muted_foreground, tr("Connecting…")),
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));
// 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)
}
}
impl Render for AppView {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let page = match self.page {
Page::Overview => overview::render(&self.model, window, cx).into_any_element(),
Page::Dpi => self.dpi.clone().into_any_element(),
Page::Telegram => self.telegram.clone().into_any_element(),
Page::Whitelist => {
let model = self.model.clone();
self.whitelist.get_or_insert_with(|| cx.new(|cx| whitelist::WhitelistPage::new(model, window, cx))).clone().into_any_element()
}
Page::Outbounds => self.outbounds.clone().into_any_element(),
Page::AmneziaWg => {
let model = self.model.clone();
self.amneziawg.get_or_insert_with(|| cx.new(|cx| amneziawg::AmneziaWgPage::new(model, window, cx))).clone().into_any_element()
}
Page::AutoProxy => {
let model = self.model.clone();
self.autoproxy.get_or_insert_with(|| cx.new(|cx| autoproxy::AutoProxyPage::new(model, window, cx))).clone().into_any_element()
}
Page::Logs => {
let model = self.model.clone();
self.logs.get_or_insert_with(|| cx.new(|cx| logs::LogsPage::new(model, cx))).clone().into_any_element()
}
Page::Settings => {
let model = self.model.clone();
self.settings.get_or_insert_with(|| cx.new(|cx| settings::SettingsPage::new(model, window, cx))).clone().into_any_element()
}
Page::Components => {
let model = self.model.clone();
self.components.get_or_insert_with(|| cx.new(|cx| components::ComponentsPage::new(model, cx))).clone().into_any_element()
}
};
div()
.h_flex()
.size_full()
.bg(cx.theme().background)
.text_color(cx.theme().foreground)
.child(self.sidebar(cx))
.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", "Тёмная тема"),
];
+287
View File
@@ -0,0 +1,287 @@
//! Outbounds: adding one from a link, the list with pins, delays and switches, the routing
//! mode, and subscriptions.
use std::collections::HashMap;
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::tag::Tag;
use gpui_kit::component::*;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use ps_client::edits::{self, OutboundSource};
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, Inactive as _};
use crate::i18n::{tr, trf};
use crate::model::Model;
const MODES: [(&str, &str); 5] = [
("default", "As configured"),
("whitelist", "Proxy only listed sites"),
("blacklist", "Proxy all but listed sites"),
("all-proxy", "Proxy everything"),
("all-bypass", "Proxy nothing"),
];
pub struct OutboundsPage {
model: Entity<Model>,
link: Entity<InputState>,
tag: Entity<InputState>,
sub_url: Entity<InputState>,
/// The last delay test of each outbound: milliseconds, or why it failed.
delays: HashMap<String, Result<u64, String>>,
testing: bool,
_subscriptions: Vec<Subscription>,
}
impl OutboundsPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
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(tr("from the link")));
let sub_url = cx.new(|cx| InputState::new(window, cx).placeholder("https://provider.example/sub/…"));
let subscriptions = vec![cx.observe(&model, |_, _, cx| cx.notify())];
Self { model, link, tag, sub_url, delays: HashMap::new(), testing: false, _subscriptions: subscriptions }
}
fn add(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let text = self.link.read(cx).value().trim().to_owned();
if text.is_empty() {
return;
}
let source = match OutboundSource::parse(&text) {
Ok(s) => s,
Err(e) => {
window.push_notification(Notification::error(trf("Not an outbound: {}", &[&format!("{e:#}")])).autohide(false), cx);
return;
}
};
let typed = self.tag.read(cx).value().trim().to_owned();
let tag = if typed.is_empty() { edits::link_tag(&text) } else { typed };
self.link.update(cx, |s, cx| s.set_value("", window, cx));
self.tag.update(cx, |s, cx| s.set_value("", window, cx));
let what = trf("Added {}", &[&tag]);
self.model.update(cx, |m, cx| m.edit(what, move |c| edits::add_outbound(c, &tag, &source, None), cx));
}
fn add_subscription(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let url = self.sub_url.read(cx).value().trim().to_owned();
if url.is_empty() {
return;
}
let tag = edits::subscription_tag(&url);
self.sub_url.update(cx, |s, cx| s.set_value("", window, 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>) {
self.testing = true;
cx.notify();
let job = self.model.read(cx).bridge().call(Request::Test { tags });
cx.spawn(async move |this, cx| {
let result = job.await;
this.update(cx, |this, cx| {
this.testing = false;
match result {
Ok(list) => {
for t in list.as_array().into_iter().flatten() {
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(tr("no reason given")).to_owned());
this.delays.insert(tag, delay);
}
}
Err(e) => {
this.delays.clear();
this.delays.insert(String::new(), Err(format!("{e:#}")));
}
}
cx.notify();
})
.ok();
})
.detach();
}
fn row(&self, tag: &str, inv: &Value, ix: usize, cx: &mut Context<Self>) -> Div {
let pinned = inv["pinned"] == tag;
let disabled = inv["disabled"].as_array().is_some_and(|d| d.iter().any(|x| x == tag));
let source = inv["sources"][tag].as_str().unwrap_or("").to_owned();
let own = source == "static";
let mut notes = vec![source.clone()];
if let Some(r) = inv["runsOn"][tag].as_str() {
notes.push(r.to_owned());
}
if let Some(h) = inv["detours"][tag].as_str() {
notes.push(trf("through {}", &[&h]));
}
let delay = match self.delays.get(tag) {
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(trf("failed: {}", &[&e])).into_any_element(),
None => div().into_any_element(),
};
let (model_pin, model_dis, model_rm) = (self.model.clone(), self.model.clone(), self.model.clone());
let (t_pin, t_dis, t_rm, t_test) = (tag.to_owned(), tag.to_owned(), tag.to_owned(), tag.to_owned());
div()
.h_flex()
.gap_3()
.items_center()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.v_flex()
.flex_1()
.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(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(delay)
.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 { 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 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));
}))
.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 = if disabled { trf("{} is back", &[&t_dis]) } else { trf("{} is left out", &[&t_dis]) };
let req = Request::Disable { tag: t_dis.clone(), disabled: !disabled };
model_dis.update(cx, |m, cx| m.request(what, req, cx));
}))
.when(own, |d| {
d.child(Button::new(("remove", ix)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| {
let tag = t_rm.clone();
model_rm.update(cx, |m, cx| m.edit(trf("Removed {}", &[&tag]), move |c| edits::remove_outbound(c, &tag), cx));
}))
})
}
}
impl Render for OutboundsPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let inv = m.outbounds()["inventory"].clone();
let mode = m.status()["proxy"]["mode"].as_str().unwrap_or("default").to_owned();
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 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(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))));
let mut list = card(
trf("Outbounds ({})", &[&tags.len()]),
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,
);
if let Some(Err(e)) = self.delays.get("") {
list = list.child(div().text_sm().text_color(cx.theme().danger).child(trf("Testing failed: {}", &[&e])));
}
if tags.is_empty() {
list = list.child(hint(tr("None yet: add a link above, or a subscription below."), cx));
}
for (i, tag) in tags.iter().enumerate() {
list = list.child(self.row(tag, &inv, i, cx));
}
let model = self.model.clone();
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)| tr(label))).selected_index(MODES.iter().position(|(v, _)| *v == mode)).on_change(move |ix, _, cx| {
let (value, label) = MODES[*ix];
let req = Request::Mode { mode: if value == "default" { None } else { Some(value.into()) } };
model.update(cx, |m, cx| m.request(trf("Mode: {}", &[&tr(label)]), req, cx));
}),
);
let model = self.model.clone();
let mut subscriptions = card(
tr("Subscriptions"),
Some(
Button::new("subs-update")
.small()
.icon(IconName::RefreshCw)
.label(tr("Update all"))
.inactive(subs.is_empty(), cx)
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request(tr("Subscriptions updated"), Request::SubsUpdate { tag: None }, cx)))
.into_any_element(),
),
cx,
)
.child(
div()
.h_flex()
.gap_3()
.child(div().flex_1().min_w_0().child(Input::new(&self.sub_url)))
.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() {
let model = self.model.clone();
let t = tag.clone();
subscriptions = subscriptions.child(
div()
.h_flex()
.items_center()
.py_1()
.border_t_1()
.border_color(cx.theme().border)
.child(div().flex_1().child(tag))
.child(Button::new(("sub-rm", i)).small().ghost().icon(IconName::Trash).tooltip(tr("Remove it")).on_click(move |_, _, cx| {
let tag = t.clone();
model.update(cx, |m, cx| m.edit(trf("Removed subscription {}", &[&tag]), move |c| edits::remove_subscription(c, &tag), cx));
})),
);
}
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", "Выходы"),
];
+250
View File
@@ -0,0 +1,250 @@
//! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state
//! 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::button::{Button, ButtonVariants as _};
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use ps_client::edits;
use serde_json::Value;
use super::AppView;
use super::widgets::{card, fact, hint, page, state_tag, Inactive as _};
use crate::model::{Connection, Model, Update};
fn text(v: &Value) -> SharedString {
match v {
Value::String(s) => s.clone().into(),
Value::Null => "—".into(),
other => other.to_string().into(),
}
}
pub fn render(model: &Entity<Model>, _: &mut Window, cx: &mut Context<AppView>) -> Div {
let m = model.read(cx);
let s = m.status().clone();
let connection = m.connection().clone();
let mut body = page(tr("Overview"), cx);
match &connection {
Connection::Down(why) => {
body = body.child(Alert::error("service-down", why.clone()).title(tr("Not connected"))).child(hint(
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,
));
}
Connection::Connecting => body = body.child(Alert::info("connecting", tr("Connecting to the Proxy Suite service…"))),
Connection::Up => {}
}
if connection != Connection::Up {
return body;
}
if let Some(e) = s["error"].as_str() {
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() {
body = body.child(Alert::warning(("warning", i), text(w)));
}
let p = &s["proxy"];
let proxy_on = p["on"] == true;
let model_p = model.clone();
let proxy = card(
tr("Local proxy"),
Some(
Switch::new("proxy-on")
.checked(proxy_on)
.on_change(move |on, _, cx| model_p.update(cx, |m, cx| m.set_proxy(*on, cx)))
.into_any_element(),
),
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(tr("global TUN")))))
.child(fact(tr("Listening on"), text(&p["listener"]), cx))
.child(fact(tr("Backend"), text(&p["backend"]), cx))
.child(fact(tr("Mode"), p["mode"].as_str().unwrap_or("default").to_owned(), 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({
let model = model.clone();
let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
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;
model.update(cx, |m, cx| {
m.edit(
if on { tr("The system proxy follows the local proxy") } else { tr("The system proxy is left alone") },
move |c| {
edits::set_path(c, &["proxy", "systemProxy", "enable"], on.into());
Ok(())
},
cx,
)
})
})
});
let z = &s["zapret"];
let model_z = model.clone();
let dpi = card(
tr("DPI bypass"),
Some(
Switch::new("zapret-on")
.checked(z["enabled"] == true)
.on_change(move |on, _, cx| {
let on = *on;
model_z.update(cx, |m, cx| {
m.edit(
if on { tr("The DPI bypass is on") } else { tr("The DPI bypass is off") },
move |c| {
edits::set_zapret_enabled(c, on);
Ok(())
},
cx,
)
})
})
.into_any_element(),
),
cx,
)
.child(div().h_flex().child(state_tag(z["state"].as_str().unwrap_or("unknown"))))
.child(fact(tr("Engine"), text(&z["engine"]), cx))
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact(tr("Preset"), text(&z["preset"]), cx)));
let t = &s["tgWsProxy"];
let model_t = model.clone();
let telegram = card(
tr("Telegram proxy"),
Some(
Switch::new("tg-on")
.checked(t["enabled"] == true)
.on_change(move |on, _, cx| {
let on = *on;
model_t.update(cx, |m, cx| {
m.edit(
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
},
cx,
)
})
})
.into_any_element(),
),
cx,
)
.child(div().h_flex().child(state_tag(t["state"].as_str().unwrap_or("unknown"))))
.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())).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.", "Установка {}: приложение закроется и через мгновение откроется снова."),
];
+253
View File
@@ -0,0 +1,253 @@
//! Settings: this app's own (its look, updates), and the whole configuration, upstream's option
//! tree as JSON, edited here and checked by the service before it takes it. Every option the
//! other pages show is here too, and the ones they do not.
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
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::prelude::FluentBuilder as _;
use gpui_kit::*;
use ps_client::Issue;
use ps_ipc::Request;
use serde_json::Value;
use super::widgets::{card, hint, page, Inactive as _};
use crate::i18n::{tr, trf};
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,
/// the secret keeps its value.
const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}";
enum Verdict {
None,
Working(&'static str),
Issues(Vec<Issue>),
Failed(String),
Saved { revision: u64, issues: Vec<Issue>, apply_error: Option<String> },
}
pub struct SettingsPage {
model: Entity<Model>,
editor: Entity<EditorState>,
/// The text and revision last loaded: what is saved against, and what "changed" means.
loaded: Option<(String, u64)>,
verdict: Verdict,
_subscriptions: Vec<Subscription>,
}
impl SettingsPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let editor = cx.new(|cx| EditorState::new(window, cx).language("json").line_number(true).folding(true));
// Save is offered once the text differs from what was loaded.
let subscriptions = vec![cx.subscribe(&editor, |_, _, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
cx.notify();
}
})];
let mut this = Self { model, editor, loaded: None, verdict: Verdict::None, _subscriptions: subscriptions };
this.reload(window, cx);
this
}
fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.verdict = Verdict::Working(tr("Loading…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigGet);
cx.spawn_in(window, async move |this, cx| {
let got = job.await;
this.update_in(cx, |this, window, cx| {
match got {
Ok(r) => {
let text = serde_json::to_string_pretty(&r["config"]).unwrap_or_default();
this.loaded = Some((text.clone(), r["revision"].as_u64().unwrap_or(0)));
this.verdict = Verdict::None;
this.editor.update(cx, |s, cx| s.set_value(text, window, cx));
}
Err(e) => this.verdict = Verdict::Failed(format!("{e:#}")),
}
cx.notify();
})
.ok();
})
.detach();
}
/// The editor's text as JSON, or where it is not.
fn parsed(&self, cx: &App) -> Result<Value, String> {
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>) {
let config = match self.parsed(cx) {
Ok(c) => c,
Err(e) => {
self.verdict = Verdict::Failed(e);
return cx.notify();
}
};
self.verdict = Verdict::Working(tr("Checking…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigValidate { config });
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.verdict = match r {
Ok(r) => Verdict::Issues(ps_client::issues(&r)),
Err(e) => Verdict::Failed(format!("{e:#}")),
};
cx.notify();
})
.ok();
})
.detach();
}
fn save(&mut self, cx: &mut Context<Self>) {
let config = match self.parsed(cx) {
Ok(c) => c,
Err(e) => {
self.verdict = Verdict::Failed(e);
return cx.notify();
}
};
let base = self.loaded.as_ref().map(|(_, r)| *r);
self.verdict = Verdict::Working(tr("Saving…"));
cx.notify();
let job = self.model.read(cx).bridge().call(Request::ConfigSet { config, base });
let model = self.model.clone();
cx.spawn(async move |this, cx| {
let r = job.await;
this.update(cx, |this, cx| {
this.verdict = match r {
Ok(r) => {
let revision = r["revision"].as_u64().unwrap_or(0);
let text = this.editor.read(cx).value().to_string();
this.loaded = Some((text, revision));
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") => {
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:#}")),
};
cx.notify();
})
.ok();
model.update(cx, |m, cx| {
m.refresh(cx);
m.load_config(cx);
});
})
.detach();
}
}
fn issue_list(issues: &[Issue], cx: &App) -> Div {
let mut list = div().v_flex().gap_1();
for i in issues {
let colour = if i.severity == "error" { cx.theme().danger } else { cx.theme().warning };
list = list.child(div().text_sm().h_flex().gap_2().child(div().text_color(colour).child(i.severity.clone())).child(div().font_family("monospace").child(i.path.clone())).child(div().flex_1().min_w_0().child(i.message.clone())));
}
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 {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let text = self.editor.read(cx).value();
let changed = self.loaded.as_ref().is_some_and(|(t, _)| t.as_str() != text.as_ref());
let redacted = text.contains(REDACTED);
let actions = div()
.h_flex()
.gap_2()
.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(tr("Check")).on_click(cx.listener(|this, _, _, cx| this.validate(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 {
Verdict::None => div(),
Verdict::Working(what) => hint(*what, cx),
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(tr("It is valid.")),
Verdict::Issues(issues) => issue_list(issues, cx),
Verdict::Saved { revision, issues, apply_error } => div()
.v_flex()
.gap_1()
.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(trf("Saved, but not applied: {}", &[&e]))))
.child(issue_list(issues, cx)),
};
page(tr("Settings"), cx).child(this_app(cx)).child(
card(tr("Configuration"), Some(actions.into_any_element()), 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(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(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••• — секреты, которые вам здесь читать нельзя; если оставить их как есть, они сохранят свои значения."),
];
+186
View File
@@ -0,0 +1,186 @@
//! The Telegram proxy (Flowseal's tg-ws-proxy): on or off, the links to open in Telegram, and
//! where it listens.
use crate::i18n::{tr, trf};
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use serde_json::{Value, json};
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
pub struct TelegramPage {
model: Entity<Model>,
port: Entity<InputState>,
fake_tls: Entity<InputState>,
/// The port and domain the inputs were last filled from (see the DPI page's `shown`).
shown: (String, String),
_subscriptions: Vec<Subscription>,
}
impl TelegramPage {
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 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 mut this = Self { model, port, fake_tls, shown: Default::default(), _subscriptions: subscriptions };
this.sync(window, cx);
this
}
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let t = self.model.read(cx).config()["tgWsProxy"].clone();
if t.is_null() {
return;
}
let fresh = (t["listener"]["port"].to_string(), t["fakeTlsDomain"].as_str().unwrap_or("").to_owned());
if fresh != self.shown {
if self.port.read(cx).value() == self.shown.0.as_str() {
let v = fresh.0.clone();
self.port.update(cx, |s, cx| s.set_value(v, window, cx));
}
if self.fake_tls.read(cx).value() == self.shown.1.as_str() {
let v = fresh.1.clone();
self.fake_tls.update(cx, |s, cx| s.set_value(v, window, cx));
}
self.shown = fresh;
}
}
fn save(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let port_text = self.port.read(cx).value().trim().to_owned();
let Ok(port) = port_text.parse::<u16>() else {
window.push_notification(Notification::error(trf("“{}” is not a port (1–65535)", &[&port_text])), cx);
return;
};
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.model.update(cx, |m, cx| {
m.edit(
tr("Telegram proxy saved"),
move |c| {
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() });
Ok(())
},
cx,
)
});
}
}
impl Render for TelegramPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let status = m.status()["tgWsProxy"].clone();
let t = m.config()["tgWsProxy"].clone();
let links = m.tg_links().to_vec();
let body = page(tr("Telegram proxy"), cx);
if t.is_null() {
return body.child(hint(tr("Waiting for the service…"), cx));
}
let model = self.model.clone();
let enable = Switch::new("tg-enable").checked(t["enable"] == true).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { tr("The Telegram proxy is on") } else { tr("The Telegram proxy is off") },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
},
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() {
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() {
let (copy, open) = (link.clone(), link.clone());
link_card = link_card.child(
div()
.h_flex()
.gap_2()
.items_center()
.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(tr("Copy")).on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.to_string()));
window.push_notification(Notification::success(tr("Copied")), cx);
}))
.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 model = self.model.clone();
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" };
model.update(cx, |m, cx| {
m.edit(
if address == "0.0.0.0" { tr("Other devices may connect") } else { tr("Only this computer may connect") },
move |c| {
edits::set_path(c, &["tgWsProxy", "listener", "address"], json!(address));
Ok(())
},
cx,
)
})
});
body.child(
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(hint(tr("Telegram over WebSocket to its own servers, for networks that block its usual connections."), cx)),
)
.child(link_card)
.child(
card(
tr("Listening"),
Some(Button::new("tg-save").small().label(tr("Save")).on_click(cx.listener(|this, _, window, cx| this.save(window, cx))).into_any_element()),
cx,
)
.child(lan)
.child(
div()
.h_flex()
.gap_4()
.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(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)"),
];
+359
View File
@@ -0,0 +1,359 @@
//! whitelist-bypass: its joiners (outbounds of the proxy, through a video call) and creators
//! (the calls' other ends), their state; a joiner's call link given, a creator's shown, its
//! login given (a cookies export, or DION's and Bitrix's email and password); which there are.
use std::collections::BTreeMap;
use gpui_kit::assets::IconName;
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputState};
use gpui_kit::component::notification::Notification;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::*;
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::i18n::{tr, trf};
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const PLATFORMS: [(&str, &str); 5] = [("wbstream", "WB Stream"), ("telemost", "Telemost"), ("dion", "DION"), ("bitrix", "Bitrix24"), ("vk", "VK (creators only)")];
/// A creator's login by email and password, for the platforms that take one.
struct PasswordLogin {
email: Entity<InputState>,
password: Entity<InputState>,
/// Bitrix only: the portal's address.
portal: Option<Entity<InputState>>,
}
pub struct WhitelistPage {
model: Entity<Model>,
name: Entity<InputState>,
platform: usize,
/// Each joiner's link input, by name.
joins: BTreeMap<String, Entity<InputState>>,
/// DION's and Bitrix's creators' login inputs, by name.
logins: BTreeMap<String, PasswordLogin>,
/// Each creator's call link, or why there is none, once asked for.
links: BTreeMap<String, Result<String, String>>,
_subscriptions: Vec<Subscription>,
}
impl WhitelistPage {
pub fn new(model: Entity<Model>, window: &mut Window, cx: &mut Context<Self>) -> Self {
let name = cx.new(|cx| InputState::new(window, cx).placeholder("laptop"));
let subscriptions = vec![cx.observe_in(&model, window, |this, _, window, cx| this.sync(window, cx))];
let mut this = Self { model, name, platform: 0, joins: BTreeMap::new(), logins: BTreeMap::new(), links: BTreeMap::new(), _subscriptions: subscriptions };
this.sync(window, cx);
this
}
/// Inputs for the creators and joiners there are now.
fn sync(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let w = self.model.read(cx).config()["whitelistBypass"].clone();
let joiners: Vec<String> = w["joiners"].as_object().map(|o| o.keys().cloned().collect()).unwrap_or_default();
self.joins.retain(|n, _| joiners.contains(n));
for n in joiners {
self.joins.entry(n).or_insert_with(|| cx.new(|cx| InputState::new(window, cx).placeholder(tr("the creator's call link"))));
}
let creators: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
self.logins.retain(|n, _| creators.iter().any(|(c, p)| c == n && matches!(p.as_str(), "dion" | "bitrix")));
for (n, platform) in creators {
if matches!(platform.as_str(), "dion" | "bitrix") && !self.logins.contains_key(&n) {
let login = PasswordLogin {
email: cx.new(|cx| InputState::new(window, cx).placeholder(tr("email"))),
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"))),
};
self.logins.insert(n, login);
}
}
}
fn add(&mut self, role: &'static str, window: &mut Window, cx: &mut Context<Self>) {
let name = self.name.read(cx).value().trim().to_owned();
let platform = PLATFORMS[self.platform].0;
// Checked here first, for a message at once.
if let Err(e) = edits::add_wl(&mut Value::Null, role, &name, platform) {
window.push_notification(Notification::error(format!("{e:#}")), cx);
return;
}
self.name.update(cx, |s, cx| s.set_value("", window, cx));
let what = 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));
}
fn join(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(input) = self.joins.get(&name) else { return };
let link = input.read(cx).value().trim().to_owned();
if link.is_empty() {
window.push_notification(Notification::error(tr("Paste the link the creator's side gave (its proxy-ctl wl link)")), cx);
return;
}
input.update(cx, |s, cx| s.set_value("", window, cx));
self.model.update(cx, |m, cx| m.request(trf("'{}' joins the call", &[&name]), Request::WlJoin { name, link }, cx));
}
fn link(&mut self, name: String, cx: &mut Context<Self>) {
let job = self.model.read(cx).bridge().call(Request::WlLink { name: name.clone() });
cx.spawn(async move |this, cx| {
let r = job.await.map(|v| v["link"].as_str().unwrap_or("").to_owned()).map_err(|e| format!("{e:#}"));
this.update(cx, |this, cx| {
this.links.insert(name, r);
cx.notify();
})
.ok();
})
.detach();
}
/// A cookies export, chosen: read here, as the signed-in user, and handed to the service.
fn cookies(&mut self, name: String, cx: &mut Context<Self>) {
let paths = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: Some(tr("Log in").into()) });
let model = self.model.clone();
cx.spawn(async move |_, cx| {
let Ok(Ok(Some(paths))) = paths.await else { return };
let Some(path) = paths.into_iter().next() else { return };
let login = std::fs::read_to_string(&path);
model.update(cx, |m, cx| match login {
Ok(login) => m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx),
Err(e) => m.track(trf("Reading {}", &[&path.display()]), async move { Err(e.into()) }, cx),
});
})
.detach();
}
fn password_login(&mut self, name: String, window: &mut Window, cx: &mut Context<Self>) {
let Some(l) = self.logins.get(&name) else { return };
let mut login = serde_json::Map::new();
login.insert("email".into(), l.email.read(cx).value().trim().into());
login.insert("password".into(), l.password.read(cx).value().to_string().into());
if let Some(p) = &l.portal {
let portal = p.read(cx).value().trim().trim_end_matches('/').to_owned();
login.insert("portal".into(), if portal.contains("://") { portal } else { format!("https://{portal}") }.into());
}
if login.values().any(|v| v.as_str().is_none_or(str::is_empty) || v == "https://") {
window.push_notification(Notification::error(tr("Fill in every field")), cx);
return;
}
l.password.update(cx, |s, cx| s.set_value("", window, cx));
let login = Value::Object(login).to_string();
self.model.update(cx, |m, cx| m.request(trf("'{}' has its login", &[&name]), Request::WlAuth { name, login }, cx));
}
fn remove(&mut self, role: &'static str, name: String, cx: &mut Context<Self>) {
self.model.update(cx, |m, cx| m.edit(trf("'{}' removed", &[&name]), move |c| edits::remove_wl(c, role, &name), cx));
}
}
/// A unit's state from the service's status, "off" when whitelist-bypass is.
fn unit_state(status: &Value, unit: &str, on: bool) -> String {
if !on {
return "off".into();
}
status["units"].as_array().into_iter().flatten().find(|u| u["name"] == unit).and_then(|u| u["state"].as_str()).unwrap_or("waiting").to_owned()
}
fn platform_label(p: &str) -> &str {
PLATFORMS.iter().find(|(id, _)| *id == p).map_or(p, |(_, label)| label.trim_end_matches(" (creators only)"))
}
impl Render for WhitelistPage {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let m = self.model.read(cx);
let w = m.config()["whitelistBypass"].clone();
let status = m.status().clone();
let body = page(tr("Whitelist bypass"), cx);
if m.config().is_null() {
return body.child(hint(tr("Waiting for the service…"), cx));
}
let on = w["enable"] == true;
let model = self.model.clone();
let enable = Switch::new("wl-enable").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { tr("Whitelist bypass is on") } else { tr("Whitelist bypass is off") },
move |c| {
edits::set_path(c, &["whitelistBypass", "enable"], on.into());
Ok(())
},
cx,
)
})
});
let about = card("whitelist-bypass", Some(enable.into_any_element()), cx).child(hint(
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,
));
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)> =
w["joiners"].as_object().map(|o| o.iter().map(|(n, j)| (n.clone(), j["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if joiner_list.is_empty() {
joiners = joiners.child(hint(tr("None yet: add one below."), cx));
}
for (i, (name, platform)) in joiner_list.into_iter().enumerate() {
let Some(input) = self.joins.get(&name) else { continue };
let state = unit_state(&status, &format!("proxy-suite-wb-joiner-{name}"), on);
let (n1, n2) = (name.clone(), name.clone());
joiners = joiners.child(
div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-remove-joiner", i)).small().ghost().icon(IconName::Trash).on_click(cx.listener(move |this, _, _, cx| this.remove("joiners", n1.clone(), cx)))),
)
.child(
div()
.h_flex()
.gap_2()
.child(div().flex_1().min_w_0().child(Input::new(input)))
.child(Button::new(("wl-join", i)).small().primary().label(tr("Join")).on_click(cx.listener(move |this, _, window, cx| this.join(n2.clone(), window, cx)))),
),
);
}
let mut creators = card(tr("Creators"), None, cx).child(hint(
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,
));
let creator_list: Vec<(String, String)> =
w["creators"].as_object().map(|o| o.iter().map(|(n, c)| (n.clone(), c["platform"].as_str().unwrap_or("").to_owned())).collect()).unwrap_or_default();
if creator_list.is_empty() {
creators = creators.child(hint(tr("None here."), cx));
}
for (i, (name, platform)) in creator_list.into_iter().enumerate() {
let state = unit_state(&status, &format!("proxy-suite-wb-creator-{name}"), on);
let (n1, n2, n3, n4, n5) = (name.clone(), name.clone(), name.clone(), name.clone(), name.clone());
let mut row = div()
.v_flex()
.gap_2()
.py_2()
.border_t_1()
.border_color(cx.theme().border)
.child(
div()
.h_flex()
.gap_3()
.items_center()
.child(div().font_medium().child(name.clone()))
.child(div().text_sm().text_color(cx.theme().muted_foreground).child(platform_label(&platform).to_owned()))
.child(state_tag(&state))
.child(div().flex_1())
.child(Button::new(("wl-link", i)).small().icon(IconName::Link).label(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(tr("New call")).on_click(cx.listener(move |this, _, _, cx| {
this.links.remove(&n2);
let name = n2.clone();
this.model.update(cx, |m, cx| m.request(trf("'{}' starts a new call", &[&name]), Request::WlNew { name }, 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)))),
);
match self.links.get(&name) {
Some(Ok(link)) => {
let copy = link.clone();
row = row.child(
div()
.h_flex()
.gap_2()
.items_center()
.child(div().flex_1().min_w_0().truncate().text_sm().font_family("monospace").child(link.clone()))
.child(Button::new(("wl-copy", i)).small().icon(IconName::Copy).label(tr("Copy")).on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.clone()));
window.push_notification(Notification::success(tr("Copied")), cx);
})),
);
}
Some(Err(e)) => row = row.child(hint(e.clone(), cx)),
None => {}
}
if let Some(l) = self.logins.get(&name) {
let mut fields = div().h_flex().gap_2().child(div().flex_1().min_w_0().child(Input::new(&l.email))).child(div().flex_1().min_w_0().child(Input::new(&l.password)));
if let Some(p) = &l.portal {
fields = fields.child(div().flex_1().min_w_0().child(Input::new(p)));
}
row = row.child(fields.child(Button::new(("wl-login", i)).small().primary().label(tr("Log in")).on_click(cx.listener(move |this, _, window, cx| this.password_login(n5.clone(), window, cx)))));
}
creators = creators.child(row);
}
let platforms = RadioGroup::horizontal("wl-platform")
.children(PLATFORMS.map(|(_, label)| tr(label)))
.selected_index(Some(self.platform))
.on_change(cx.listener(|this, ix: &usize, _, cx| {
this.platform = *ix;
cx.notify();
}));
let add = card(tr("Add"), None, cx)
.child(div().v_flex().gap_1().child(div().text_sm().child(tr("Name (letters, digits, '.', '_', '-')"))).child(Input::new(&self.name)))
.child(platforms)
.child(
div()
.h_flex()
.gap_2()
.child(Button::new("wl-add-joiner").small().icon(IconName::Plus).label(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(tr("Add a creator")).on_click(cx.listener(|this, _, window, cx| this.add("creators", window, 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)
}
}
/// 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 (только создатели)"),
];
+92
View File
@@ -0,0 +1,92 @@
//! 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::prelude::FluentBuilder as _;
use crate::i18n::tr;
use gpui_kit::assets::IconName;
use gpui_kit::component::*;
use gpui_kit::*;
pub fn brand(cx: &App) -> impl IntoElement {
div().h_flex().gap_2().items_center().child(Icon::new(IconName::Shield).text_color(cx.theme().primary)).child(div().font_semibold().child("Proxy Suite"))
}
/// A page: its title, then what is under it.
pub fn page(title: &'static str, cx: &App) -> Div {
div().v_flex().gap_4().p_6().w_full().min_w_0().max_w(px(920.)).child(div().text_xl().font_semibold().text_color(cx.theme().foreground).child(title))
}
/// A bordered section of a page, titled, with what it controls on the right of the title.
pub fn card(title: impl Into<SharedString>, action: Option<AnyElement>, cx: &App) -> Div {
div()
.v_flex()
.gap_3()
.p_4()
.min_w_0()
.rounded_lg()
.border_1()
.border_color(cx.theme().border)
.bg(cx.theme().background)
.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, in the user's words.
pub fn state_tag(state: &str) -> Tag {
let tag = match state {
"active" => Tag::success(),
"activating" | "reloading" | "deactivating" => Tag::warning(),
"failed" => Tag::danger(),
_ => Tag::secondary(),
};
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.
pub fn hint(text: impl Into<SharedString>, cx: &App) -> Div {
div().text_sm().text_color(cx.theme().muted_foreground).child(text.into())
}
/// A label and its value, in a row.
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())
}
/// 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", "ожидает"),
];
+58
View File
@@ -59,8 +59,66 @@ pub enum Request {
Test { tags: Vec<String> },
/// Components: what is installed, what the manifest wants.
Components,
/// The presets the installed zapret release has, and the one configured.
ZapretPresets,
/// tg-ws-proxy's tg:// links, which carry its secret. Secrets scope.
TgLinks,
/// Fetch and install components (all wanted, or the named ones).
ComponentsInstall { names: Vec<String> },
/// whitelist-bypass's creators and joiners, and their state.
WlList,
/// The call a creator made and keeps rejoining.
WlLink { name: String },
/// A creator's login: a cookies export, or (DION, Bitrix) the JSON of its email, password
/// and portal.
WlAuth { name: String, login: String },
/// The call link a joiner joins.
WlJoin { name: String, link: String },
/// Drops the call a creator rejoins: it makes a new one.
WlNew { name: String },
/// autoProxy: the routes it learned, its exits, what waits.
AutoList,
/// Probes a destination (a host, or host/path) through the exits as the prober does:
/// through `exits` (all, without), or whether `via` carries what direct reaches.
AutoProbe {
target: String,
#[serde(default)]
exits: Option<Vec<String>>,
#[serde(default)]
via: Option<String>,
#[serde(default)]
keep_going: bool,
},
/// Hosts to probe now.
AutoLearn { hosts: Vec<String> },
/// Forgets a domain's route and verdicts; without one, everything learned.
AutoForget {
#[serde(default)]
domain: Option<String>,
},
/// AmneziaWG's profiles: system-wide ones with their tunnel's state, outbounds by kind.
AwgList,
/// Starts or stops a system-wide profile's tunnel.
AwgSet { name: String, on: bool },
/// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are.
AwgLog { name: String, lines: usize },
/// 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)]
+12
View File
@@ -22,8 +22,12 @@ rustls.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
rand.workspace = true
base64.workspace = true
x25519-dalek = { version = "2", features = ["static_secrets"] }
sha2.workspace = true
zip.workspace = true
flate2 = "1"
tar = { version = "0.4", default-features = false }
[target.'cfg(windows)'.dependencies]
windows-service.workspace = true
@@ -36,4 +40,12 @@ windows-sys = { workspace = true, features = [
"Win32_System_Registry",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Threading",
"Win32_Networking_WinInet",
"Win32_System_RemoteDesktop",
"Win32_System_Environment",
"Win32_NetworkManagement_WindowsFilteringPlatform",
"Win32_System_Rpc",
] }
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
+291 -9
View File
@@ -133,12 +133,35 @@ fn scope_of(req: &Request) -> Option<Scope> {
Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing),
Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds),
// Backend logs name the sites visited (at info), and errors may quote what was dialled.
Request::RenderedConfig | Request::Logs { .. } => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
// 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::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy),
Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg),
Request::AwgLog { .. } => Some(Scope::Secrets),
Request::ZapretCutoff { .. } => Some(Scope::Zapret),
Request::KillSwitch { on: Some(_) } => Some(Scope::Services),
_ => None,
}
}
/// Re-applies whitelist-bypass, so a unit that waited starts, and restarts `unit` on what
/// was just left for it.
async fn wl_restart(s: &mut service::Service, unit: &str) -> Response {
let started = |s: &service::Service| s.sup.status().into_iter().find(|u| u.name == unit).map(|u| u.since);
let before = started(s);
if let Err(e) = s.apply_wl().await {
return Response::err(format!("{e:#}"));
}
// Unless the apply (re)started it on a new spec, or it does not run (off, or its proxy is).
let after = started(s);
if after.is_some() && after == before {
s.sup.restart(unit);
}
Response::ok(json!({ "unit": unit, "state": s.sup.state_of(unit).as_str() }))
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
}
@@ -237,13 +260,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
Request::ConfigSet { mut config, base } => {
let mut s = shared.lock().await;
if let Some(base) = base {
if base != s.store.revision {
return Response::err(format!(
"the configuration changed since revision {base} (now {}): read it again",
s.store.revision
));
}
if let Some(base) = base
&& base != s.store.revision
{
return Response::err(format!("the configuration changed since revision {base} (now {}): read it again", s.store.revision));
}
unredact(&mut config, s.cfg());
let new: Config = match serde_json::from_value(config) {
@@ -284,6 +304,10 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
let shared = shared.clone();
tokio::spawn(async move { service::update_rule_sets(&shared, true).await });
}
{
let shared = shared.clone();
tokio::spawn(async move { service::register_warp(&shared).await });
}
Response::ok(json!({
"revision": revision,
"issues": issues_json(&issues),
@@ -377,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)");
}
s.tun = true;
// A tunnel turned on: the kill switch holds again.
s.killswitch_lifted = false;
}
s.proxy_on = true;
applied(s.apply().await)
@@ -414,6 +440,9 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
}
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 s = shared.lock().await;
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
@@ -454,6 +483,259 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
Response::ok(json!(list))
}
Request::ZapretPresets => {
let s = shared.lock().await;
let bats: Vec<String> = std::fs::read_dir(s.paths().bin().join("zapret"))
.into_iter()
.flatten()
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.collect();
Response::ok(json!({
"presets": ps_core::zapret::presets(&bats),
"current": s.cfg().zapret.discord_youtube.config_name,
}))
}
Request::TgLinks => {
let s = shared.lock().await;
match crate::tg::secret(s.cfg(), s.paths()) {
Ok(secret) => Response::ok(json!({ "links": crate::tg::links(s.cfg(), &secret) })),
Err(e) => Response::err(format!("tg-ws-proxy's secret: {e:#}")),
}
}
Request::WlList => {
let s = shared.lock().await;
let wl = &s.cfg().whitelist_bypass;
let state = |unit: String| if wl.enable { s.sup.state_of(&unit).as_str() } else { "off" };
let mut list: Vec<Value> = wl
.creators
.iter()
.map(|(name, c)| json!({ "name": name, "role": "creator", "platform": c.platform.as_str(), "state": state(format!("{}{name}", crate::wl::CREATOR_PREFIX)) }))
.collect();
list.extend(wl.joiners.iter().map(|(name, j)| {
json!({ "name": name, "role": "joiner", "platform": j.platform.as_str(), "state": state(format!("{}{name}", crate::wl::JOINER_PREFIX)) })
}));
Response::ok(json!(list))
}
Request::WlLink { name } => {
let s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
match crate::wl::last_link(s.paths(), &name) {
Some(link) => Response::ok(json!({ "link": link })),
None => Response::err(format!("{name} has no call yet: see proxy-ctl logs {}{name}", crate::wl::CREATOR_PREFIX)),
}
}
Request::WlAuth { name, login } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.creators.contains_key(&name) {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
}
if login.len() > 1 << 20 || serde_json::from_str::<Value>(&login).is_err() {
return Response::err("not a cookies export (or a login): not valid JSON");
}
let file = match crate::wl::state_file(s.paths(), &name, ".cookies.json") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, login.as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::WlJoin { name, link } => {
let mut s = shared.lock().await;
if !s.cfg().whitelist_bypass.joiners.contains_key(&name) {
return Response::err(format!("no whitelist-bypass joiner '{name}'"));
}
let link = link.trim();
let link = match crate::wl::clean_link(link) {
Ok(l) if l == link => l,
_ => return Response::err("a call link is one word: a room id, a slug or a URL"),
};
let file = match crate::wl::state_file(s.paths(), &name, ".join") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = crate::wl::write_private(&file, format!("{link}\n").as_bytes()) {
return Response::err(format!("{e:#}"));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::JOINER_PREFIX)).await
}
Request::WlNew { name } => {
let mut s = shared.lock().await;
let Some(c) = s.cfg().whitelist_bypass.creators.get(&name) else {
return Response::err(format!("no whitelist-bypass creator '{name}'"));
};
if c.link_file.is_some() {
return Response::err(format!("{name} rejoins the call its linkFile sets: change that instead"));
}
let file = match crate::wl::state_file(s.paths(), &name, ".link") {
Ok(f) => f,
Err(e) => return Response::err(format!("{e:#}")),
};
if let Err(e) = std::fs::remove_file(&file)
&& e.kind() != std::io::ErrorKind::NotFound
{
return Response::err(format!("removing {}: {e}", file.display()));
}
wl_restart(&mut s, &format!("{}{name}", crate::wl::CREATOR_PREFIX)).await
}
Request::AutoList => {
let s = shared.lock().await;
let exits = crate::autoproxy::exits(&s);
Response::ok(crate::autoproxy::listing(s.paths(), exits.as_ref(), &s.cfg().proxy.auto_proxy, has_secrets(s.cfg(), peer)))
}
Request::AutoProbe { target, exits, via, keep_going } => {
let Some(probe_exits) = crate::autoproxy::exits(&*shared.lock().await) else {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
};
// The network, outside the lock.
match probe_exits.probe(&target, exits.as_deref(), via.as_deref(), keep_going).await {
Ok(p) => Response::ok(serde_json::to_value(&p).unwrap()),
Err(e) => Response::err(format!("{e:#}")),
}
}
Request::AutoLearn { hosts } => {
let s = shared.lock().await;
if crate::autoproxy::exits(&s).is_none() {
return Response::err("autoProxy is not running: it needs proxy.autoProxy.enable and the local proxy on");
}
let bad: Vec<&String> = hosts.iter().filter(|h| !ps_core::autoproxy::host_ok(h.trim())).collect();
if !bad.is_empty() {
return Response::err(format!("not host names: {}", bad.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")));
}
let opts = &s.cfg().proxy.auto_proxy;
let skipped: Vec<&String> = hosts.iter().filter(|h| crate::autoproxy::excluded(opts, &h.trim().to_ascii_lowercase())).collect();
if !skipped.is_empty() {
return Response::err(format!(
"in proxy.autoProxy.exclude, never probed: {}",
skipped.iter().map(|h| h.as_str()).collect::<Vec<_>>().join(", ")
));
}
let queued = {
let mut r = s.ap.requests.lock().unwrap();
// Bounded: every request is a probe.
let room = 10_000usize.saturating_sub(r.len());
r.extend(hosts.iter().take(room).map(|h| h.trim().to_owned()));
hosts.len().min(room)
};
s.ap.wake.notify_one();
Response::ok(json!({ "queued": queued }))
}
Request::AutoForget { domain } => match crate::autoproxy::edit(shared, domain.as_deref()).await {
Ok(()) => Response::ok(json!({ "forgot": domain.unwrap_or_else(|| "everything".into()) })),
Err(e) => Response::err(format!("{e:#}")),
},
Request::AwgList => {
let s = shared.lock().await;
let cfg = s.cfg();
let vpns = crate::awgvpn::profiles(cfg);
let list: Vec<Value> = cfg
.amnezia_wg
.profiles
.iter()
.map(|(name, p)| match vpns.iter().find(|v| &v.name == name) {
Some(v) => json!({ "name": name, "kind": "vpn", "interface": v.iface, "autostart": v.autostart, "state": crate::awgvpn::state(&v.iface) }),
None => json!({
"name": name,
"kind": match p.as_outbound { Some(ps_core::config::AwgOutboundKind::SingBox) => "singBox", Some(_) => "userspace", None => "vpn" },
"state": if cfg.amnezia_wg.enable { "outbound" } else { "off" },
}),
})
.collect();
Response::ok(json!({ "enabled": cfg.amnezia_wg.enable, "profiles": list }))
}
Request::AwgSet { name, on } => {
let mut s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}' (is amneziaWg.enable on, and the profile without asOutbound?)"));
};
// The SCM's calls wait for the tunnel: not in the async runtime's threads.
let iface = vpn.iface.clone();
let r = tokio::task::spawn_blocking(move || if on { crate::awgvpn::start(&iface) } else { crate::awgvpn::stop(&iface) }).await;
// 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 {
Ok(Ok(())) => Response::ok(json!({ "name": name, "state": crate::awgvpn::state(&vpn.iface) })),
Ok(Err(e)) => Response::err(format!("{e:#}")),
Err(e) => Response::err(e.to_string()),
}
}
Request::AwgLog { name, lines } => {
let s = shared.lock().await;
let Some(vpn) = crate::awgvpn::profiles(s.cfg()).into_iter().find(|v| v.name == name) else {
return Response::err(format!("no system-wide AmneziaWG profile '{name}'"));
};
Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) }))
}
Request::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 } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
+726
View File
@@ -0,0 +1,726 @@
//! autoProxy's prober, as upstream's autoproxy-run.template.sh runs it: every `interval`, and
//! at once for `proxy-ctl proxy auto learn`, it probes the hosts apps dialled directly (and
//! those asked for) through each exit in turn, remembers the first exit that reaches what
//! direct does not, and publishes it as that exit's rule-set, which sing-box reloads.
//!
//! Upstream learns the hosts from its server inbounds' access log; on a desktop they are the
//! local proxy's own direct connections, which the Clash API lists (`sample`). The judging is
//! ps_core::autoproxy's.
use std::collections::{BTreeMap, BTreeSet, HashSet};
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail};
use ps_core::autoproxy::{self as ap, Fetch, PATHS, Probe, State};
use ps_core::config::AutoProxy as Options;
use ps_core::render::ProbeExit;
use serde_json::{Value, json};
use crate::paths::{Paths, write_atomic};
use crate::service::{SOCKS_UNIT, Shared};
use crate::units::UnitState;
/// Where the prober's lines go: `proxy-ctl logs proxy-suite-autoproxy`.
pub const UNIT: &str = "proxy-suite-autoproxy";
const USER_AGENT: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) proxy-suite-probe";
/// What the service and the prober share.
#[derive(Default)]
pub struct AutoProxy {
/// Runs and edits take turns on the state.
pub lock: tokio::sync::Mutex<()>,
/// Hosts asked for, probed at the next run, which asking wakes.
pub requests: std::sync::Mutex<Vec<String>>,
/// Hosts apps dialled directly since the last run, with how often.
pub dialled: std::sync::Mutex<BTreeMap<String, u64>>,
/// What the transfer sampler saw since the last run: host, exit, crawling, fastest second.
pub samples: std::sync::Mutex<Vec<(String, String, bool, u64)>>,
pub wake: tokio::sync::Notify,
}
pub fn dir(paths: &Paths) -> PathBuf {
paths.root.join("autoproxy")
}
pub fn rules_dir(paths: &Paths) -> PathBuf {
dir(paths).join("rules")
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs())
}
/// The state, or a fresh one; an unreadable one is set aside as state.json.broken.
pub fn load(paths: &Paths) -> State {
let file = dir(paths).join("state.json");
match std::fs::read(&file) {
Ok(bytes) => match serde_json::from_slice(&bytes) {
Ok(s) => s,
Err(e) => {
tracing::warn!("{} is unreadable ({e}); set aside, starting fresh", file.display());
let _ = std::fs::rename(&file, file.with_extension("json.broken"));
State::default()
}
},
Err(_) => State::default(),
}
}
pub fn save(paths: &Paths, state: &State) -> Result<()> {
let d = dir(paths);
std::fs::create_dir_all(&d)?;
write_atomic(&d.join("state.json"), &serde_json::to_vec_pretty(state)?)?;
Ok(())
}
/// Every exit's rule-set file from the state: before sing-box starts (it refuses a missing
/// one), and after each route learned (it reloads a file replaced).
pub fn publish(exits: &[ProbeExit], state: &State) -> Result<()> {
for e in exits {
let Some(path) = &e.path else { continue };
let path = Path::new(path);
if let Some(d) = path.parent() {
std::fs::create_dir_all(d)?;
}
let body = serde_json::to_vec(&ap::rule_set(state, &e.tag))?;
if std::fs::read(path).is_ok_and(|old| old == body) {
continue;
}
write_atomic(path, &body).with_context(|| format!("writing {}", path.display()))?;
}
Ok(())
}
/// The probe listeners and their login, while the proxy and autoProxy run.
#[derive(Clone)]
pub struct Exits {
pub list: Vec<ProbeExit>,
pub login: (String, String),
/// autoProxy.exclude: never probed.
pub opts: Options,
}
impl Exits {
fn port(&self, tag: &str) -> Option<u16> {
self.list.iter().find(|e| e.tag == tag).map(|e| e.port)
}
fn tags(&self) -> Vec<String> {
self.list.iter().map(|e| e.tag.clone()).collect()
}
/// `domain` at `path` through `tag`'s listener.
pub async fn fetch(&self, tag: &str, domain: &str, path: &str) -> Fetch {
match self.port(tag) {
Some(port) => fetch(port, &self.login, domain, path).await,
None => Fetch { error: format!("no exit {tag}"), ..Default::default() },
}
}
/// Whether the direct listener answers at all: a probe through a listener that is not
/// there would judge every site unreachable.
async fn up(&self) -> bool {
let Some(e) = self.list.first() else { return false };
tokio::time::timeout(Duration::from_secs(3), tokio::net::TcpStream::connect(("127.0.0.1", e.port))).await.is_ok_and(|r| r.is_ok())
}
/// A probe of `domain` (a host, or host/path), as `proxy-ctl proxy auto probe` asks it:
/// through `wanted` (all, without), or whether `via` carries what direct reaches.
pub async fn probe(&self, target: &str, wanted: Option<&[String]>, via: Option<&str>, keep_going: bool) -> Result<Probe> {
let target = target.split("://").last().unwrap_or(target);
let (domain, paths): (&str, Vec<String>) = match target.split_once('/') {
Some((d, p)) => (d, vec![format!("/{p}")]),
None => (target, PATHS.iter().map(|p| (*p).to_owned()).collect()),
};
if !ap::host_ok(domain) {
bail!("'{domain}' is not a host name");
}
if excluded(&self.opts, &domain.to_ascii_lowercase()) {
bail!("{domain} is in proxy.autoProxy.exclude: never probed");
}
if !self.up().await {
bail!("the probe listeners are not up: is the local proxy running?");
}
let paths: Vec<&str> = paths.iter().map(String::as_str).collect();
let fetch = |tag: String, path: String| async move { self.fetch(&tag, domain, &path).await };
if let Some(via) = via {
if via == ap::DIRECT || self.port(via).is_none() {
bail!("no exit named {via} other than direct");
}
return Ok(ap::stand_in(domain, via, &paths, fetch).await);
}
let mut exits = vec![ap::DIRECT.to_owned()];
match wanted {
Some(w) => exits.extend(w.iter().filter(|t| t.as_str() != ap::DIRECT && self.port(t).is_some()).cloned()),
None => exits.extend(self.list.iter().skip(1).map(|e| e.tag.clone())),
}
Ok(ap::walk(domain, &exits, &paths, keep_going, fetch).await)
}
}
/// One request through a probe listener: the first hop that is not a same-site redirect
/// (a block can sit at the end of a chain: spotify.com -> www -> open -> why-not-available).
async fn fetch(port: u16, login: &(String, String), domain: &str, path: &str) -> Fetch {
let client = reqwest::Client::builder()
.proxy(match reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)) {
Ok(p) => p,
Err(e) => return Fetch { error: e.to_string(), ..Default::default() },
})
.redirect(reqwest::redirect::Policy::none())
.user_agent(USER_AGENT)
.connect_timeout(Duration::from_secs(8))
.timeout(Duration::from_secs(15))
.build();
let client = match client {
Ok(c) => c,
Err(e) => return Fetch { error: e.to_string(), ..Default::default() },
};
let mut url = format!("https://{domain}{path}");
let site = ap::site(&url);
let mut result = Fetch::default();
for _ in 0..6 {
result = match client.get(&url).send().await {
Err(e) => return Fetch { error: short_error(&e), ..Default::default() },
Ok(mut resp) => {
let status = resp.status().as_u16();
let head: String = resp.headers().iter().map(|(k, v)| format!("{k}: {}\r\n", String::from_utf8_lossy(v.as_bytes()))).collect();
let location = resp
.headers()
.get(reqwest::header::LOCATION)
.and_then(|l| l.to_str().ok())
.and_then(|l| resp.url().join(l).ok())
.map(|u| u.to_string())
.unwrap_or_default();
// Enough to judge a refusal by (its first 8 KiB) and to count what came.
let mut body = Vec::new();
while body.len() < 64 * 1024 {
match resp.chunk().await {
Ok(Some(c)) => body.extend_from_slice(&c),
_ => break,
}
}
Fetch { status: Some(status), block: ap::block_page(status, &head, &body), location, bytes: body.len() as u64, error: String::new() }
}
};
let redirect = result.status.is_some_and(|s| (300..400).contains(&s));
if !redirect || ap::redirect_is_block(&result.location) || result.location.is_empty() {
break;
}
if ap::site(&result.location) != site || ap::local_target(&result.location) || !result.location.starts_with("http") {
break;
}
url = result.location.clone();
}
result
}
fn short_error(e: &reqwest::Error) -> String {
if e.is_timeout() {
"timed out".into()
} else if e.is_connect() {
"could not connect".into()
} else {
let mut s = e.to_string();
let mut src = std::error::Error::source(e);
while let Some(inner) = src {
s = inner.to_string();
src = inner.source();
}
s.chars().take(120).collect()
}
}
/// A plain GET through a probe listener, for the egress address and an exit's network.
async fn get_text(port: u16, login: &(String, String), url: &str) -> Option<String> {
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::all(format!("socks5h://{}:{}@127.0.0.1:{port}", login.0, login.1)).ok()?)
.user_agent(USER_AGENT)
.timeout(Duration::from_secs(10))
.build()
.ok()?;
let resp = client.get(url).send().await.ok()?;
if !resp.status().is_success() {
return None;
}
let text = resp.text().await.ok()?;
(text.len() < 64 * 1024).then_some(text)
}
/// The probe listeners, when autoProxy runs with the local proxy.
pub fn exits(s: &crate::service::Service) -> Option<Exits> {
let cfg = s.cfg();
// 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;
}
let list = s.last.as_ref()?.probe_exits.clone();
(!list.is_empty()).then(|| Exits {
list,
login: (s.store.secrets.hop_user.clone(), s.store.secrets.hop_password.clone()),
opts: cfg.proxy.auto_proxy.clone(),
})
}
pub fn excluded(opts: &Options, host: &str) -> bool {
opts.exclude.iter().any(|x| {
let x = x.trim_start_matches('.').to_ascii_lowercase();
host == x || host.ends_with(&format!(".{x}"))
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum Mode {
/// Everything: rechecks, the backlog, the requests.
Full,
/// `proxy-ctl proxy auto learn`'s hosts only.
Requests,
}
/// One run. Each verdict is saved as it comes: a run cut short keeps what it learned.
pub async fn run(shared: &Shared, mode: Mode) {
let (exits, opts, paths, disabled, auto) = {
let s = shared.lock().await;
let Some(exits) = exits(&s) else { return };
let disabled = s.last.as_ref().map(|r| r.inventory.disabled.clone()).unwrap_or_default();
(exits, s.cfg().proxy.auto_proxy.clone(), s.paths().clone(), disabled, s.ap.clone())
};
let _turn = auto.lock.lock().await;
let note = async |line: String| shared.lock().await.sup.note(UNIT, line);
if !exits.up().await {
note("no probe listeners: is the local proxy running?".into()).await;
return;
}
let ttl = u64::from(opts.ttl_days) * 86400;
let now = now();
let mut state = load(&paths);
let save_and = async |state: &State, publish_too: bool| {
if let Err(e) = save(&paths, state) {
tracing::warn!("autoProxy's state: {e:#}");
}
if publish_too && let Err(e) = publish(&exits.list, state) {
tracing::warn!("autoProxy's rule-sets: {e:#}");
}
};
// Routes through an exit disabled since: probed again without it.
let gone: Vec<(String, String)> = state.domains.iter().filter(|(_, r)| disabled.contains(&r.exit)).map(|(d, r)| (d.clone(), r.exit.clone())).collect();
for (d, exit) in &gone {
state.forget(d);
note(format!("forgot {d}: its exit {exit} is disabled")).await;
}
// Verdicts are about this host's address: a new one discards them. An error page or a
// captive portal must not pass for one.
let direct_port = exits.list[0].port;
if let Some(egress) = get_text(direct_port, &exits.login, "https://api.ipify.org").await.map(|t| t.trim().to_owned())
&& !egress.is_empty()
&& egress.chars().all(|c| c.is_ascii_hexdigit() || c == '.' || c == ':')
&& state.egress.as_deref() != Some(egress.as_str())
{
if state.egress.is_some() {
note(format!("egress is now {egress}; discarding everything learned for the old address")).await;
}
state.new_egress(&egress);
}
// Which network (AS) each exit leaves from, once per TTL.
for e in &exits.list {
if now.saturating_sub(state.exits.get(&e.tag).map_or(0, |x| x.at)) < ttl {
continue;
}
let Some(info) = get_text(e.port, &exits.login, "https://ipinfo.io/json").await.and_then(|t| serde_json::from_str::<Value>(&t).ok()) else {
continue;
};
let Some(ip) = info["ip"].as_str() else { continue };
let x = state.exits.entry(e.tag.clone()).or_default();
x.ip = Some(ip.to_owned());
x.asn = info["org"].as_str().and_then(|o| o.split_whitespace().next()).map(str::to_owned);
x.at = now;
}
state.strike(&[], "", "", now, ttl);
let (r1, r2, _) = ap::rounds(&exits.tags(), &state);
save_and(&state, !gone.is_empty()).await;
// Walks round 1; round 2 only when it all refused, round 1's refusals kept.
let exits = &exits;
let walk = async |host: &str| -> Probe {
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await };
let first: Vec<String> = std::iter::once(ap::DIRECT.to_owned()).chain(r1.iter().cloned()).collect();
let p = ap::walk(host, &first, &PATHS, false, fetch).await;
if matches!(p.verdict.as_str(), "both-fail" | "unreachable") && !r2.is_empty() {
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, host, &path).await };
let second: Vec<String> = std::iter::once(ap::DIRECT.to_owned()).chain(r2.iter().cloned()).collect();
let mut q = ap::walk(host, &second, &PATHS, false, fetch).await;
let mut rows = p.rows;
rows.append(&mut q.rows);
q.rows = rows;
return q;
}
p
};
let mut requeue: Vec<(String, String)> = Vec::new();
if mode == Mode::Full {
// Remembered routes, once per TTL.
for (dom, host, exit) in state.due(now, ttl) {
let h = host.as_str();
let fetch = |tag: String, path: String| async move { exits.fetch(&tag, h, &path).await };
let p = ap::walk(&host, &[ap::DIRECT.to_owned(), exit.clone()], &PATHS, false, fetch).await;
if p.verdict == "destination" && p.exit.as_deref() == Some(exit.as_str()) {
if let Some(r) = state.domains.get_mut(&dom) {
r.at = now;
}
} else if p.verdict == "ok" {
note(format!("recheck {dom}: reachable directly now, dropping {exit}")).await;
state.domains.remove(&dom);
state.record(&dom, &host, &p, now, ttl);
save_and(&state, true).await;
} else {
note(format!("recheck {dom}: {exit} no longer works ({}), walking again", p.verdict)).await;
state.domains.remove(&dom);
save_and(&state, true).await;
requeue.push((dom, host));
}
}
// What apps dialled directly since the last run, per host.
let dialled = std::mem::take(&mut *auto.dialled.lock().unwrap());
let counts: BTreeMap<String, (String, u64)> = dialled
.into_iter()
.filter(|(h, _)| ap::host_ok(h) && !excluded(&opts, h))
.filter_map(|(h, n)| ap::registrable(&h).map(|d| (h, (d, n))))
.collect();
state.queue(&counts, now, ttl);
save_and(&state, false).await;
// What the sampler saw crawl: each such site gets the next exit, in probe order, that
// answers it as well as direct does; none left, it stays direct for a TTL.
let samples = std::mem::take(&mut *auto.samples.lock().unwrap());
if opts.slow_below_kibps > 0 && !samples.is_empty() {
let obs: Vec<ap::Observation> = samples
.into_iter()
.filter(|(h, ..)| ap::host_ok(h) && !excluded(&opts, h))
.filter_map(|(host, exit, slow, peak)| ap::registrable(&host).map(|domain| ap::Observation { domain, host, exit, slow, peak }))
.collect();
let before = state.domains.clone();
state.judge_slow(&obs, now, 3);
let (_, _, ordered) = ap::rounds(&exits.tags(), &state);
let wanted: Vec<(String, ap::SlowWant)> = state.slow_want.iter().take(20).map(|(d, w)| (d.clone(), w.clone())).collect();
for (dom, want) in wanted {
let mut tried = want.tried.clone();
let was = tried.last().cloned();
// It crawled twice on the exit it was routed through.
if let Some(was) = &was {
state.strike(std::slice::from_ref(was), &dom, "slow", now, ttl);
}
let mut via = None;
for tag in &ordered {
if tried.contains(tag) {
continue;
}
tried.push(tag.clone());
let host = want.host.as_str();
let fetch = |t: String, path: String| async move { exits.fetch(&t, host, &path).await };
let p = ap::stand_in(host, tag, &PATHS, fetch).await;
if p.verdict == "ok" {
via = Some(tag.clone());
break;
}
// Refused what direct gets: by a block page, or by the origin.
let rows: Vec<&ap::Row> = p.rows.iter().filter(|r| &r.tag == tag).collect();
let why = rows
.iter()
.find(|r| r.judgement == ap::Judgement::Wall)
.map(|r| format!("wall:{}", r.fetch.block))
.or_else(|| rows.iter().any(|r| r.judgement == ap::Judgement::Blocked).then(|| "refused".to_owned()));
if let Some(why) = why {
state.strike(std::slice::from_ref(tag), &dom, &why, now, ttl);
}
}
let how = was.as_deref().map_or("directly".to_owned(), |w| format!("via {w}"));
match via {
Some(v) => {
note(format!("slow {dom}: crawls {how}, routed via {v}")).await;
state.route_slow(&dom, &want.host, &v, tried, now);
}
None => {
note(format!("slow {dom}: crawls {how}, and no other exit reaches it; left direct")).await;
state.skip_slow(&dom, now, ttl);
}
}
}
save_and(&state, state.domains != before).await;
}
}
// Probe: the requests, then broken routes, then the backlog.
let mut asked: Vec<(String, String)> = Vec::new();
{
let mut requests = auto.requests.lock().unwrap();
let mut seen = BTreeSet::new();
let taken: Vec<String> = std::mem::take(&mut *requests);
for h in taken {
let h = h.trim().to_ascii_lowercase();
if !ap::host_ok(&h) || excluded(&opts, &h) || !seen.insert(h.clone()) {
continue;
}
if let Some(d) = ap::registrable(&h) {
asked.push((d, h));
}
}
let max = opts.probes_per_run as usize;
if asked.len() > max {
requests.extend(asked.split_off(max).into_iter().map(|(_, h)| h));
}
}
let left = auto.requests.lock().unwrap().len();
if left > 0 {
note(format!("{left} requested host(s) past probesPerRun wait for the next run")).await;
}
let backlog = if mode == Mode::Full { state.backlog_order(now, ttl) } else { Vec::new() };
let mut seen: HashSet<String> = HashSet::new();
let mut routed: HashSet<String> = HashSet::new();
let started = Instant::now();
let mut probed = 0usize;
let rows = asked.iter().map(|r| (r, true)).chain(requeue.iter().chain(backlog.iter()).map(|r| (r, false)));
for ((dom, host), was_asked) in rows {
if !was_asked && probed >= opts.probes_per_run as usize {
break;
}
// A run of tarpits must not go on for good: what is left waits for the next.
if started.elapsed() > Duration::from_secs(2 * 3600) {
note("a run ends after two hours; the rest wait for the next".into()).await;
break;
}
if !seen.insert(host.clone()) || routed.contains(dom) {
continue;
}
if !was_asked {
probed += 1;
}
if !exits.up().await {
note("the probe listeners went away; the run ends".into()).await;
break;
}
let p = walk(host).await;
state.record(dom, host, &p, now, ttl);
let destination = p.verdict == "destination";
if destination {
routed.insert(dom.clone());
}
save_and(&state, destination).await;
let how = match (&p.verdict[..], &p.exit) {
("destination", Some(x)) => format!("destination via {x}"),
("censor", Some(x)) => format!("censor ({x} reaches it; left to zapret)"),
(v, _) => v.to_owned(),
};
note(format!("probe {host} -> {how}")).await;
}
if mode == Mode::Full || !asked.is_empty() {
note(format!("probed {} requested and {probed} queued host(s); {} still waiting", asked.len(), state.backlog.len())).await;
}
save_and(&state, true).await;
}
/// The prober's schedule: a first run ten minutes after start (as upstream's timer; sooner with
/// a shorter `interval`), then every `interval`; a learn request wakes it for the requests alone.
pub async fn runner(shared: Shared) {
let (auto, every) = {
let s = shared.lock().await;
(s.ap.clone(), interval(&s.cfg().proxy.auto_proxy))
};
let mut next = Instant::now() + every.min(Duration::from_secs(600));
loop {
tokio::select! {
_ = tokio::time::sleep_until(next.into()) => {
run(&shared, Mode::Full).await;
next = Instant::now() + interval(&shared.lock().await.cfg().proxy.auto_proxy);
}
_ = auto.wake.notified() => run(&shared, Mode::Requests).await,
}
}
}
/// `interval`, a minute at least.
fn interval(opts: &Options) -> Duration {
ps_core::duration::parse(&opts.interval).unwrap_or(Duration::from_secs(600)).max(Duration::from_secs(60))
}
/// The hosts the local proxy's clients dial directly, from the Clash API's connections, every
/// ten seconds while autoProxy runs: what the prober's backlog is made of.
pub async fn sample(shared: Shared) {
let mut seen: HashSet<String> = HashSet::new();
loop {
tokio::time::sleep(Duration::from_secs(10)).await;
let (clash, auto) = {
let s = shared.lock().await;
let cfg = s.cfg();
if exits(&s).is_none() {
continue;
}
(crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone())
};
let Ok(v) = clash.connections().await else { continue };
let mut dialled = auto.dialled.lock().unwrap();
for c in v["connections"].as_array().into_iter().flatten() {
let Some(id) = c["id"].as_str() else { continue };
if !seen.insert(id.to_owned()) {
continue;
}
let m = &c["metadata"];
let inbound = m["type"].as_str().unwrap_or("");
if inbound.contains("probe-in-") || inbound.contains("proxy-suite-test-in") {
continue;
}
// Only what went direct: the rest is routed already.
let chains: Vec<&str> = c["chains"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
if chains != [ap::DIRECT] {
continue;
}
let port = m["destinationPort"].as_str().map(str::to_owned).or_else(|| m["destinationPort"].as_u64().map(|p| p.to_string()));
if !matches!(port.as_deref(), Some("443" | "80")) {
continue;
}
let host = m["host"].as_str().unwrap_or("").to_ascii_lowercase();
if ap::host_ok(&host) {
*dialled.entry(host).or_insert(0) += 1;
}
}
if seen.len() > 50_000 {
seen.clear();
}
// Bounded between runs, as the backlog is.
if dialled.len() > 20_000 {
let mut v: Vec<(String, u64)> = std::mem::take(&mut *dialled).into_iter().collect();
v.sort_by_key(|a| std::cmp::Reverse(a.1));
v.truncate(10_000);
*dialled = v.into_iter().collect();
}
}
}
/// Live transfers every minute while slow sites are routed (`slowBelowKiBps`): eleven Clash
/// API snapshots a second apart, the transfers that moved enough kept for the next run, as
/// upstream's sampler timer does.
pub async fn sample_slow(shared: Shared) {
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
let (clash, auto, below) = {
let s = shared.lock().await;
let cfg = s.cfg();
let below = cfg.proxy.auto_proxy.slow_below_kibps;
if below == 0 || exits(&s).is_none() {
continue;
}
(crate::clash::Clash::new(cfg.proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), s.ap.clone(), below)
};
let mut snapshots = Vec::with_capacity(11);
for i in 0..11 {
if i > 0 {
tokio::time::sleep(Duration::from_secs(1)).await;
}
snapshots.push(clash.connections().await.unwrap_or(Value::Null));
}
let seen = ap::sample_transfers(&snapshots, 300 * 1024, u64::from(below) * 1024);
let mut samples = auto.samples.lock().unwrap();
samples.extend(seen);
let over = samples.len().saturating_sub(10_000);
samples.drain(..over);
}
}
/// What `proxy-ctl proxy auto` lists. Without `detail` (the secrets scope) the sites routed
/// and the counts only: the hosts probed, those left to zapret and the sites behind each
/// strike are browsing history, as the logs are.
pub fn listing(paths: &Paths, exits: Option<&Exits>, opts: &Options, detail: bool) -> Value {
let s = load(paths);
let domains: Vec<Value> = s
.domains
.iter()
.map(|(d, r)| {
let mut v = json!({ "domain": d, "exit": r.exit, "verdict": r.verdict, "at": r.at });
if detail {
v["host"] = r.host.clone().into();
}
v
})
.collect();
let exit_list: Vec<Value> = s
.exits
.iter()
.map(|(t, e)| {
let mut v = json!({ "tag": t, "ip": e.ip, "asn": e.asn, "bad": e.bad, "strikes": e.strikes.len() });
if detail {
v["badBy"] = json!(e.bad_by);
}
v
})
.collect();
let censored: Vec<&String> = s.hosts.iter().filter(|(_, h)| h.verdict == "censor").map(|(h, _)| h).collect();
let censored = if detail { json!(censored) } else { json!(censored.len()) };
json!({
"enabled": opts.enable,
"running": exits.is_some(),
"egress": s.egress,
"lastRun": s.last_run,
"domains": domains,
"exits": exit_list,
"probeExits": exits.map(|e| e.tags()).unwrap_or_default(),
"hostsJudged": s.hosts.len(),
"censored": censored,
"backlog": s.backlog.len(),
"slowWaiting": s.slow_want.len(),
})
}
/// `forget <domain>` or `clear`, under the prober's lock, published at once.
pub async fn edit(shared: &Shared, forget: Option<&str>) -> Result<()> {
let (paths, auto, list) = {
let s = shared.lock().await;
(s.paths().clone(), s.ap.clone(), s.last.as_ref().map(|r| r.probe_exits.clone()).unwrap_or_default())
};
let _turn = auto.lock.lock().await;
let mut state = load(&paths);
match forget {
Some(d) => {
if !ap::host_ok(d) {
bail!("'{d}' is not a domain");
}
state.forget(&d.to_ascii_lowercase());
}
None => state.clear(),
}
save(&paths, &state)?;
publish(&list, &state)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exclusions_take_subdomains() {
let opts = Options { exclude: vec!["internal.example".into()], ..Default::default() };
assert!(excluded(&opts, "internal.example"));
assert!(excluded(&opts, "a.internal.example"));
assert!(!excluded(&opts, "notinternal.example"));
}
#[test]
fn published_rule_sets_follow_the_state() {
let d = std::env::temp_dir().join(format!("ps-ap-{}", std::process::id()));
let path = d.join("rs-1.json");
let exits = [
ProbeExit { tag: "direct".into(), port: 1, rule_set: None, path: None },
ProbeExit { tag: "nl".into(), port: 2, rule_set: Some("autoproxy-1".into()), path: Some(path.to_string_lossy().into()) },
];
let mut s = State::default();
s.domains.insert("x.example".into(), ap::Route { verdict: "destination".into(), exit: "nl".into(), host: "x.example".into(), path: "/".into(), at: 1, bad: 0, tried: Vec::new() });
publish(&exits, &s).unwrap();
let v: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(v, json!({ "version": 1, "rules": [{ "domain_suffix": ["x.example"] }] }));
let _ = std::fs::remove_dir_all(&d);
}
}
+94
View File
@@ -0,0 +1,94 @@
//! AmneziaWG outbounds and WARP devices of the "userspace" kind: wireproxy-awg, a SOCKS
//! listener on loopback in front of each tunnel, with the hop login, as upstream's
//! wg-tunnel.nix runs it. The "singBox" kind needs only the profile's `.conf`, which the
//! renderer makes a WireGuard endpoint of (AmneziaWG's obfuscation dropped, with a warning).
//! AmneziaWG as a system-wide VPN needs its driver, which is not here yet.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::{AwgOutboundKind, Config, WarpOutboundKind};
use ps_core::derived::{self, ExtraKind};
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT_PREFIX: &str = "proxy-suite-awg-";
fn read(f: &str) -> Result<String, String> {
std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"))
}
/// Each "singBox" AmneziaWG outbound's `.conf`, by profile, and why any could not be read.
pub fn sing_box_profiles(cfg: &Config) -> (BTreeMap<String, String>, Vec<String>) {
let mut out = BTreeMap::new();
let mut errors = Vec::new();
for (name, kind, _) in derived::awg_outbounds(cfg) {
if kind != AwgOutboundKind::SingBox {
continue;
}
match ps_core::awg::prepare(&cfg.amnezia_wg.profiles[&name], &read) {
Ok(conf) => {
out.insert(name, conf);
}
Err(e) => errors.push(format!("AmneziaWG profile '{name}': {e}")),
}
}
(out, errors)
}
/// The wireproxy units: one per "userspace" AmneziaWG outbound and WARP device, with what
/// could not be made of the rest. `warp` holds the WARP devices' profiles.
pub fn units(cfg: &Config, paths: &Paths, program: &Path, login: (&str, &str), warp: &BTreeMap<String, String>) -> (Vec<UnitSpec>, Vec<String>) {
let mut tunnels: Vec<(String, Result<String, String>, u16)> = Vec::new();
for extra in derived::extra_outbounds(cfg) {
match extra.kind {
ExtraKind::Awg { profile, kind: AwgOutboundKind::Userspace, port } => {
let conf = ps_core::awg::prepare(&cfg.amnezia_wg.profiles[&profile], &read).map_err(|e| format!("AmneziaWG profile '{profile}': {e}"));
tunnels.push((profile, conf, port));
}
ExtraKind::Warp { device } if device.kind == WarpOutboundKind::Userspace => {
// A device registered (or given) only: until then the outbound waits.
if let Some(profile) = warp.get(&device.tag) {
let conf = ps_core::awg::validate(profile, false).map(|()| profile.clone()).map_err(|e| format!("WARP device '{}': {e}", device.tag));
tunnels.push((device.tag.clone(), conf, device.port));
}
}
_ => {}
}
}
let mut units = Vec::new();
let mut errors = Vec::new();
for (name, conf, port) in tunnels {
let made = conf.and_then(|c| ps_core::awg::as_wireproxy(&c, &format!("127.0.0.1:{port}"), Some(login))).and_then(|text| {
write(paths, &name, &text).map_err(|e| format!("'{name}': {e:#}"))
});
match made {
Ok((file, text)) => units.push(UnitSpec {
name: format!("{UNIT_PREFIX}{name}"),
program: program.to_path_buf(),
args: vec!["-c".into(), file.display().to_string()],
env: Vec::new(),
cwd: None,
generation: text,
}),
Err(e) => errors.push(e),
}
}
(units, errors)
}
/// The configuration, below the protected state root: it holds the tunnel's private key.
fn write(paths: &Paths, name: &str, text: &str) -> Result<(PathBuf, String)> {
let dir = paths.run().join("awg");
std::fs::create_dir_all(&dir)?;
let file = dir.join(format!("{name}.conf"));
write_atomic(&file, text.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok((file, text.to_owned()))
}
+337
View File
@@ -0,0 +1,337 @@
//! AmneziaWG as a system-wide VPN: each profile with no `asOutbound` is a tunnel service of
//! its own, `AmneziaWGTunnel$<interface name>`, as amneziawg-windows's client installs one:
//! amneziawg-go on Wintun, routes and DNS from the configuration, and, for a single peer that
//! takes everything (0.0.0.0/0, ::/0), its firewall blocking what would leave outside the
//! tunnel. It runs `awg-tunnel.exe` (tools/build-amneziawg.sh) with the profile's `.conf`,
//! written below the protected state root, and logs beside it.
//!
//! The service writes the configuration and registers the tunnel; `proxy-ctl awg on|off` and
//! the app start and stop it; `autostart` starts it with the service. Windows only: on Linux
//! (development) the profiles are listed and say so.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::Config;
use crate::paths::{Paths, write_atomic};
/// The tunnel services' names: amneziawg-windows's own.
#[cfg_attr(not(windows), allow(dead_code))]
pub const SERVICE_PREFIX: &str = "AmneziaWGTunnel$";
/// Where the service's notes about the tunnels go: `proxy-ctl logs proxy-suite-awg-vpn`.
pub const UNIT: &str = "proxy-suite-awg-vpn";
/// A system-wide profile.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vpn {
pub name: String,
/// The adapter's and the service's name.
pub iface: String,
pub autostart: bool,
}
/// The profiles that are system-wide VPNs, while AmneziaWG is on.
pub fn profiles(cfg: &Config) -> Vec<Vpn> {
if !cfg.enable || !cfg.amnezia_wg.enable {
return Vec::new();
}
cfg.amnezia_wg
.profiles
.iter()
.filter(|(_, p)| p.as_outbound.is_none())
.map(|(name, p)| Vpn { name: name.clone(), iface: p.interface_name.clone().unwrap_or_else(|| name.clone()), autostart: p.autostart })
.collect()
}
#[cfg_attr(not(windows), allow(dead_code))]
pub fn service_name(iface: &str) -> String {
format!("{SERVICE_PREFIX}{iface}")
}
/// The tunnels' configurations: each `<interface>.conf` there is a tunnel this suite
/// registered, which is how it finds its own to remove.
fn dir(paths: &Paths) -> PathBuf {
paths.root.join("awg-vpn")
}
/// The tunnels registered, by interface name.
fn registered(paths: &Paths) -> Vec<String> {
std::fs::read_dir(dir(paths))
.into_iter()
.flatten()
.flatten()
.filter_map(|e| e.file_name().to_str()?.strip_suffix(".conf").map(str::to_owned))
.collect()
}
/// A tunnel unregistered: its service, configuration and log gone.
fn forget(paths: &Paths, iface: &str) -> Result<()> {
#[cfg(windows)]
scm::remove(iface, &paths.bin())?;
let _ = std::fs::remove_file(conf_path(paths, iface));
let _ = std::fs::remove_file(log_path(paths, iface));
Ok(())
}
pub fn conf_path(paths: &Paths, iface: &str) -> PathBuf {
dir(paths).join(format!("{iface}.conf"))
}
/// The tunnel's log: awg-tunnel.exe writes it anew at each start.
pub fn log_path(paths: &Paths, iface: &str) -> PathBuf {
dir(paths).join(format!("{iface}.conf.log"))
}
/// The profile's `.conf`, as the tunnel reads it: it holds the private key, so only below
/// the protected state root.
pub fn write_conf(cfg: &Config, paths: &Paths, vpn: &Vpn) -> Result<PathBuf> {
let p = &cfg.amnezia_wg.profiles[&vpn.name];
let read = |f: &str| std::fs::read_to_string(f).map_err(|e| format!("{f}: {e}"));
let text = ps_core::awg::prepare(p, &read).map_err(|e| anyhow::anyhow!("AmneziaWG profile '{}': {e}", vpn.name))?;
let file = conf_path(paths, &vpn.iface);
std::fs::create_dir_all(dir(paths))?;
if std::fs::read_to_string(&file).ok().as_deref() != Some(text.as_str()) {
write_atomic(&file, text.as_bytes()).with_context(|| format!("writing {}", file.display()))?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(file)
}
/// The last lines of a tunnel's log.
pub fn log_tail(paths: &Paths, iface: &str, lines: usize) -> Vec<String> {
let text = std::fs::read_to_string(log_path(paths, iface)).unwrap_or_default();
let all: Vec<&str> = text.lines().collect();
all[all.len().saturating_sub(lines)..].iter().map(|l| (*l).to_owned()).collect()
}
#[cfg(windows)]
mod scm {
use std::ffi::OsString;
use std::path::Path;
use std::time::Duration;
use anyhow::{Context, Result};
use windows_service::service::{
ServiceAccess, ServiceDependency, ServiceErrorControl, ServiceInfo, ServiceSidType, ServiceStartType, ServiceState, ServiceType,
};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
fn manager() -> Result<ServiceManager> {
ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE | ServiceManagerAccess::ENUMERATE_SERVICE)
.context("opening the Service Control Manager")
}
const ACCESS: ServiceAccess = ServiceAccess::QUERY_STATUS
.union(ServiceAccess::QUERY_CONFIG)
.union(ServiceAccess::START)
.union(ServiceAccess::STOP)
.union(ServiceAccess::CHANGE_CONFIG)
.union(ServiceAccess::DELETE);
/// The tunnel's service, created or brought in line with `program` and `conf`.
pub fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
let m = manager()?;
let info = ServiceInfo {
name: OsString::from(super::service_name(iface)),
display_name: OsString::from(format!("AmneziaWG tunnel: {iface} (Proxy Suite)")),
service_type: ServiceType::OWN_PROCESS,
start_type: ServiceStartType::OnDemand,
error_control: ServiceErrorControl::Normal,
executable_path: program.to_path_buf(),
launch_arguments: vec![conf.as_os_str().to_owned(), OsString::from(iface)],
// As amneziawg-windows's client: the network stack first.
dependencies: vec![ServiceDependency::Service(OsString::from("Nsi")), ServiceDependency::Service(OsString::from("TcpIp"))],
account_name: None,
account_password: None,
};
let service = match m.open_service(super::service_name(iface), ACCESS) {
Ok(s) => {
let current = s.query_config()?;
let wanted_args = format!("\"{}\" \"{}\" \"{iface}\"", program.display(), conf.display());
if current.executable_path.to_string_lossy() != wanted_args {
s.change_config(&info)?;
}
s
}
Err(_) => m.create_service(&info, ACCESS).context("creating the tunnel service")?,
};
// Its firewall lets the tunnel's own traffic out by the service's SID, which a service
// has in its token only with this.
service.set_config_service_sid_info(ServiceSidType::Unrestricted)?;
Ok(())
}
pub fn start(iface: &str) -> Result<()> {
let s = manager()?.open_service(super::service_name(iface), ACCESS).context("the tunnel is not registered")?;
if s.query_status()?.current_state == ServiceState::Stopped {
s.start::<&str>(&[]).context("starting the tunnel")?;
}
Ok(())
}
pub fn stop(iface: &str) -> Result<()> {
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
if s.query_status()?.current_state != ServiceState::Stopped {
let _ = s.stop();
for _ in 0..40 {
if s.query_status()?.current_state == ServiceState::Stopped {
break;
}
std::thread::sleep(Duration::from_millis(250));
}
}
Ok(())
}
pub fn state(iface: &str) -> String {
let Ok(m) = manager() else { return "unknown".into() };
let Ok(s) = m.open_service(super::service_name(iface), ServiceAccess::QUERY_STATUS) else { return "inactive".into() };
match s.query_status().map(|st| st.current_state) {
Ok(ServiceState::Running) => "active",
Ok(ServiceState::StartPending) => "activating",
Ok(ServiceState::StopPending) => "deactivating",
Ok(_) => "inactive",
Err(_) => "unknown",
}
.into()
}
/// Stopped and deleted, if it runs this suite's program (under `bin`): a tunnel of
/// amneziawg-windows's own client by the same name is left alone.
pub fn remove(iface: &str, bin: &Path) -> Result<()> {
let Ok(s) = manager()?.open_service(super::service_name(iface), ACCESS) else { return Ok(()) };
let bin = bin.to_string_lossy().to_lowercase();
if !s.query_config().is_ok_and(|c| c.executable_path.to_string_lossy().to_lowercase().contains(&bin)) {
return Ok(());
}
stop(iface)?;
s.delete()?;
Ok(())
}
}
/// Registers every system-wide profile's tunnel (its `.conf` written), removes the tunnels
/// of profiles gone, and starts the `autostart` ones when `boot`. Errors per profile are
/// returned as lines, the rest done.
pub fn apply(cfg: &Config, paths: &Paths, program: Option<&Path>, boot: bool) -> Vec<String> {
let wanted = profiles(cfg);
let mut notes = Vec::new();
let keep: Vec<&str> = wanted.iter().map(|v| v.iface.as_str()).collect();
for iface in registered(paths) {
if !keep.contains(&iface.as_str()) {
match forget(paths, &iface) {
Ok(()) => notes.push(format!("AmneziaWG tunnel {iface} removed: its profile is gone, or AmneziaWG is off")),
Err(e) => notes.push(format!("AmneziaWG tunnel {iface}: {e:#}")),
}
}
}
if wanted.is_empty() {
return notes;
}
let Some(program) = program else {
notes.push("AmneziaWG's tunnel (component amneziawg) is not installed: the system-wide profiles cannot start".into());
return notes;
};
for vpn in &wanted {
let r = write_conf(cfg, paths, vpn).and_then(|conf| register(&vpn.iface, program, &conf));
match r {
Ok(()) if boot && vpn.autostart => {
if let Err(e) = start(&vpn.iface) {
notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name));
}
}
Ok(()) => {}
Err(e) => notes.push(format!("AmneziaWG profile '{}': {e:#}", vpn.name)),
}
}
notes
}
#[cfg(windows)]
fn register(iface: &str, program: &Path, conf: &Path) -> Result<()> {
scm::register(iface, program, conf)
}
#[cfg(not(windows))]
fn register(_iface: &str, _program: &Path, _conf: &Path) -> Result<()> {
Ok(())
}
#[cfg(windows)]
pub fn start(iface: &str) -> Result<()> {
scm::start(iface)
}
#[cfg(not(windows))]
pub fn start(_iface: &str) -> Result<()> {
anyhow::bail!("AmneziaWG as a system-wide VPN runs on Windows only")
}
#[cfg(windows)]
pub fn stop(iface: &str) -> Result<()> {
scm::stop(iface)
}
#[cfg(not(windows))]
pub fn stop(_iface: &str) -> Result<()> {
Ok(())
}
#[cfg(windows)]
pub fn state(iface: &str) -> String {
scm::state(iface)
}
#[cfg(not(windows))]
pub fn state(_iface: &str) -> String {
"windows-only".into()
}
/// 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.
#[cfg_attr(not(windows), allow(dead_code))]
pub fn remove_all(paths: &Paths) {
for iface in registered(paths) {
let _ = forget(paths, &iface);
}
}
#[cfg(test)]
mod tests {
use super::*;
use ps_core::config::{AwgOutboundKind, AwgProfile};
#[test]
fn only_profiles_without_an_outbound_are_vpns() {
let mut cfg = Config::default();
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert("home".into(), AwgProfile { autostart: true, ..Default::default() });
cfg.amnezia_wg.profiles.insert("office".into(), AwgProfile { interface_name: Some("awg-office".into()), ..Default::default() });
cfg.amnezia_wg.profiles.insert("exit".into(), AwgProfile { as_outbound: Some(AwgOutboundKind::Userspace), ..Default::default() });
let v = profiles(&cfg);
assert_eq!(v.iter().map(|v| (v.name.as_str(), v.iface.as_str(), v.autostart)).collect::<Vec<_>>(), [("home", "home", true), ("office", "awg-office", false)]);
assert_eq!(service_name("home"), "AmneziaWGTunnel$home");
cfg.amnezia_wg.enable = false;
assert!(profiles(&cfg).is_empty());
}
}
+6
View File
@@ -23,6 +23,7 @@ fn encode(segment: &str) -> String {
out
}
#[allow(dead_code, reason = "for switching the selection live, which is to come")]
impl Clash {
pub fn new(port: u16, secret: &str) -> Self {
let http = reqwest::Client::builder()
@@ -43,6 +44,11 @@ impl Clash {
Ok(body)
}
/// The connections open now, with where each goes and through what.
pub async fn connections(&self) -> Result<Value> {
self.get("/connections").await
}
/// Every proxy (outbound or group) with what a selector holds now.
pub async fn proxies(&self) -> Result<Value> {
self.get("/proxies").await.map(|v| v["proxies"].clone())
+3 -1
View File
@@ -48,8 +48,10 @@ impl Components {
if cfg!(windows) {
return None;
}
// Development: the system's program of that name (a bundle's "tor/tor" is "tor").
let bare = std::path::Path::new(&file).file_name()?.to_owned();
let path = std::env::var_os("PATH")?;
std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file())
std::env::split_paths(&path).map(|dir| dir.join(&bare)).find(|p| p.is_file())
}
pub fn sing_box(&self) -> anyhow::Result<PathBuf> {
+306
View File
@@ -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(())
}
+75 -1
View File
@@ -16,6 +16,12 @@ pub enum Route {
}
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 from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default();
let to = attempt.url().as_str().to_owned();
@@ -34,7 +40,10 @@ fn client(route: &Route) -> Result<reqwest::Client> {
.user_agent(USER_AGENT)
.redirect(policy)
.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 {
Route::Direct => b.no_proxy(),
Route::Proxy { port, login } => {
@@ -69,6 +78,71 @@ pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
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.
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);
for (k, v) in headers {
req = req.header(*k, *v);
}
let resp = req.send().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
if !resp.status().is_success() {
bail!("the server answered {}", resp.status());
}
let bytes = resp.bytes().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
if bytes.len() > 1 << 20 {
bail!("the answer is larger than a MiB");
}
Ok(serde_json::from_slice(&bytes)?)
}
/// A reqwest error without the URL it carries.
fn describe(e: &reqwest::Error) -> String {
let kind = if e.is_timeout() {
+44 -19
View File
@@ -9,7 +9,8 @@ use sha2::{Digest, Sha256};
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();
h.update(data);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
@@ -20,14 +21,14 @@ pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Res
std::fs::create_dir_all(cache)?;
let key = hex(src.url.as_bytes());
let cached = cache.join(&key[..32]);
if let Ok(data) = std::fs::read(&cached) {
if src.sha256.as_ref().is_none_or(|want| hex(&data) == *want) {
return Ok(data);
}
if let Ok(data) = std::fs::read(&cached)
&& src.sha256.as_ref().is_none_or(|want| hex(&data) == *want)
{
return Ok(data);
}
let mut last = None;
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) => {
if let Some(want) = &src.sha256 {
let got = hex(&data);
@@ -44,19 +45,15 @@ pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Res
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")).context(format!("fetching {}", src.url)))
}
/// Extracts what `src` takes from `data` into `dest`, verifying each file it pins.
/// Extracts what `src` takes from `data`, a zip or a gzipped tar, into `dest`, verifying each
/// file it pins. Only plain files are taken from a tar: a link could point anywhere.
pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result<usize> {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?;
let mut seen = std::collections::BTreeSet::new();
let mut n = 0;
for i in 0..zip.len() {
let mut entry = zip.by_index(i)?;
let name = entry.name().to_owned();
let Some(rel) = src.place(&name) else { continue };
let mut body = Vec::with_capacity(entry.size() as usize);
entry.read_to_end(&mut body)?;
let mut take = |name: &str, body: Vec<u8>| -> Result<()> {
let Some(rel) = src.place(name) else { return Ok(()) };
if let Some(files) = &src.files {
let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(&name);
let in_archive = name.strip_prefix(src.strip.as_str()).unwrap_or(name);
let want = &files[in_archive];
let got = hex(&body);
if got != *want {
@@ -70,6 +67,29 @@ pub fn extract(src: &Source, data: &[u8], dest: &Path) -> Result<usize> {
}
std::fs::write(&out, &body).with_context(|| format!("writing {}", out.display()))?;
n += 1;
Ok(())
};
if data.starts_with(&[0x1f, 0x8b]) {
let mut tar = tar::Archive::new(flate2::read::GzDecoder::new(data));
for entry in tar.entries().context("not a gzipped tar archive")? {
let mut entry = entry?;
if !entry.header().entry_type().is_file() {
continue;
}
let name = entry.path()?.to_string_lossy().trim_start_matches("./").to_owned();
let mut body = Vec::with_capacity(entry.size() as usize);
entry.read_to_end(&mut body)?;
take(&name, body)?;
}
} else {
let mut zip = zip::ZipArchive::new(std::io::Cursor::new(data)).context("not a zip archive")?;
for i in 0..zip.len() {
let mut entry = zip.by_index(i)?;
let name = entry.name().to_owned();
let mut body = Vec::with_capacity(entry.size() as usize);
entry.read_to_end(&mut body)?;
take(&name, body)?;
}
}
if let Some(files) = &src.files {
let missing: Vec<&String> = files.keys().filter(|f| !seen.contains(*f)).collect();
@@ -236,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
/// 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> {
let manifest = ps_core::components::manifest();
let mut notes = Vec::new();
for (name, comp) in &manifest.components {
let src = from.join(name);
if installed_version(from, name).as_deref() != Some(comp.version.as_str()) {
continue;
}
if installed_version(bin, name).as_deref() == Some(comp.version.as_str()) {
if !seeds(from, bin, name) {
continue;
}
let staging = bin.join(format!("{name}.staging"));
+432
View File
@@ -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)));
}
}
+30
View File
@@ -4,19 +4,29 @@
//! it); `--console` runs it in the foreground, which is also how it runs off Windows.
mod api;
mod autoproxy;
mod awg;
mod awgvpn;
mod clash;
mod components;
mod cutoff;
mod fetch;
mod install;
#[cfg(windows)]
mod job;
mod killswitch;
mod paths;
mod service;
mod ssh;
mod store;
mod tg;
mod tor;
mod units;
mod update;
mod warp;
#[cfg(windows)]
mod winsvc;
mod wl;
mod zapret;
use std::path::PathBuf;
@@ -81,9 +91,22 @@ pub async fn run(
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.
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()) {
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 interactive = svc.cfg().user_control.enable;
@@ -92,12 +115,18 @@ pub async fn run(
let addr = address(socket);
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
update::report(&paths.updates());
ready();
if let Err(e) = shared.lock().await.apply().await {
tracing::warn!("not starting the proxy yet: {e}");
}
tokio::spawn(api::serve(server, shared.clone()));
tokio::spawn(autoproxy::runner(shared.clone()));
tokio::spawn(autoproxy::sample(shared.clone()));
tokio::spawn(autoproxy::sample_slow(shared.clone()));
tokio::spawn(zapret::sync_loop(shared.clone()));
tokio::spawn(cutoff::runner(shared.clone()));
// First fetches: what the configuration needs and has not got yet.
{
let shared = shared.clone();
@@ -110,6 +139,7 @@ pub async fn run(
service::update_subscriptions(&shared, Some(&tag)).await;
}
service::update_rule_sets(&shared, true).await;
service::register_warp(&shared).await;
service::timers(shared).await;
});
}
+7 -2
View File
@@ -58,6 +58,11 @@ impl Paths {
pub fn run(&self) -> PathBuf {
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 {
self.root.join("logs")
}
@@ -174,14 +179,14 @@ mod secure {
let mut system_owner = true;
for attempt in 0..4 {
let sd = descriptor(system_owner)?;
let mut attrs = SECURITY_ATTRIBUTES {
let attrs = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: sd.0,
bInheritHandle: 0,
};
let path = wide(root.as_os_str());
// SAFETY: NUL-terminated path; attrs outlives the call.
if unsafe { CreateDirectoryW(path.as_ptr(), &mut attrs) } != 0 {
if unsafe { CreateDirectoryW(path.as_ptr(), &attrs) } != 0 {
return Ok(());
}
// SAFETY: plain call.
+346 -22
View File
@@ -1,12 +1,12 @@
//! The service's state and what it does with it: render, write, check, (re)start, fetch.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
use ps_core::config::{Backend, Config, RuleSetFormat};
use ps_core::config::{Backend, Config, RuleSetFormat, Severity, validate};
use ps_core::render::{self, Env, Input, Rendered};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
@@ -37,6 +37,19 @@ pub struct Service {
pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool,
/// What whitelist-bypass's units waited for at the last apply, said when it first did.
wl_waiting: BTreeSet<String>,
/// autoProxy's requests and the hosts its prober learns from (crate::autoproxy).
pub ap: Arc<crate::autoproxy::AutoProxy>,
/// Whether the system-wide AmneziaWG tunnels were registered since the service started:
/// the first time, the `autostart` ones start too.
awg_vpn_started: bool,
/// 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 {
@@ -59,6 +72,11 @@ impl Service {
last_error: None,
last_fetch: BTreeMap::new(),
tcp_timestamps_on: false,
wl_waiting: BTreeSet::new(),
ap: Arc::default(),
awg_vpn_started: false,
killswitch_lifted: false,
awg_wanted: BTreeSet::new(),
store,
})
}
@@ -82,15 +100,52 @@ impl Service {
// The helpers' own connections go out directly under the TUN, as upstream's socket
// marks send them: the sidecar's would loop back into sing-box, the relay's too.
let mut direct = Vec::new();
if cfg.proxy.backend == Backend::Hybrid {
if let Ok(x) = self.comps.xray() {
direct.push(x.to_string_lossy().into_owned());
if cfg.proxy.backend == Backend::Hybrid
&& let Ok(x) = self.comps.xray()
{
direct.push(x.to_string_lossy().into_owned());
}
if cfg.tg_ws_proxy.enable
&& cfg.tg_ws_proxy.bypass_transparent_proxy
&& let Ok(p) = self.comps.program("tg-ws-proxy", "python/python")
{
direct.push(p.to_string_lossy().into_owned());
}
// wireproxy's tunnels, like the sidecar's, would loop back into the TUN.
if derived_userspace(cfg)
&& let Some(p) = self.comps.find("wireproxy-awg", "wireproxy")
{
direct.push(p.to_string_lossy().into_owned());
}
// The joiners' calls, and the creators' unless they go through the proxy.
if cfg.whitelist_bypass.enable {
let wl = &cfg.whitelist_bypass;
let joiners = wl.joiners.values().map(|j| format!("headless-{}-joiner", j.platform.as_str()));
let creators = wl.creators.values().filter(|c| c.upstream == ps_core::config::Upstream::Direct).map(|c| format!("headless-{}-creator", c.platform.as_str()));
for name in joiners.chain(creators).collect::<BTreeSet<_>>() {
if let Some(p) = self.comps.find("whitelist-bypass", &name) {
direct.push(p.to_string_lossy().into_owned());
}
}
}
if cfg.tg_ws_proxy.enable && cfg.tg_ws_proxy.bypass_transparent_proxy {
if let Ok(p) = self.comps.program("tg-ws-proxy", "python/python") {
direct.push(p.to_string_lossy().into_owned());
}
// Tor's own connections, unless it is to go through the proxy (upstream = "proxy").
if cfg.tor.enable
&& cfg.tor.upstream == ps_core::config::Upstream::Direct
&& let Some(p) = self.comps.find("tor", "tor/tor")
{
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());
Env {
@@ -103,8 +158,15 @@ impl Service {
direct_processes: direct,
groups_watched: false,
sidecar_secret: self.sidecar_secret.clone(),
warp_profiles: crate::warp::profiles(cfg, paths),
awg_profiles: crate::awg::sing_box_profiles(cfg).0,
ssh_identity_path: cfg.ssh_proxy.identity_file.as_ref().map(|_| crate::ssh::identity_path(paths).to_string_lossy().into_owned()),
ssh_host_keys: if cfg.ssh_proxy.enable { crate::ssh::host_keys(cfg, |f| std::fs::read_to_string(f).ok()) } else { Vec::new() },
windows: cfg!(windows),
..Default::default()
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),
}
}
@@ -133,8 +195,181 @@ impl Service {
if let Err(e) = &tg {
self.sup.note(crate::tg::UNIT, format!("proxy-suite: tg-ws-proxy: {e:#}"));
}
// Before the proxy: it copies the key sing-box's SSH outbound reads.
let ssh = self.apply_ssh().await;
if let Err(e) = &ssh {
self.sup.note(crate::ssh::UNIT, format!("proxy-suite: the SSH tunnel: {e:#}"));
}
let tor = self.apply_tor().await;
if let Err(e) = &tor {
self.sup.note(crate::tor::UNIT, format!("proxy-suite: Tor: {e:#}"));
}
let awg = self.apply_awg().await;
if let Err(e) = &awg {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: AmneziaWG: {e:#}"));
}
self.apply_awg_vpn();
let wl = self.apply_wl().await;
if let Err(e) = &wl {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: whitelist-bypass: {e:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(proxy)
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)
}
/// 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
/// their profiles, the `autostart` ones started with the service.
fn apply_awg_vpn(&mut self) {
let cfg = self.cfg().clone();
let boot = !self.awg_vpn_started;
self.awg_vpn_started = true;
// 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 !crate::awgvpn::profiles(&cfg).is_empty() {
self.sup.note(crate::awgvpn::UNIT, "proxy-suite: AmneziaWG as a system-wide VPN runs on Windows only; not registered");
}
return;
}
let program = self.comps.program("amneziawg", "awg-tunnel").ok();
for note in crate::awgvpn::apply(&cfg, self.paths(), program.as_deref(), boot) {
self.sup.note(crate::awgvpn::UNIT, format!("proxy-suite: {note}"));
}
}
/// whitelist-bypass: the joiners while the proxy they serve runs, the creators while it
/// is on; the ones no longer wanted stopped, and what the rest wait for said once.
pub async fn apply_wl(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let mut wanted_cfg = cfg.clone();
let on = cfg.enable && cfg.whitelist_bypass.enable;
if !self.proxy_wanted() {
wanted_cfg.whitelist_bypass.joiners.clear();
}
let (units, waiting) = if on {
let auth = &cfg.proxy.listener.auth;
let password = match (&auth.password, &auth.password_file) {
(Some(p), _) => Some(p.clone()),
(None, Some(f)) => Some(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.lines().next().unwrap_or("").to_owned()),
(None, None) => None,
};
let login = auth.username.clone().zip(password);
let hop = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let program = |name: &str| self.comps.program("whitelist-bypass", name);
crate::wl::units(&wanted_cfg, self.paths(), &program, (&hop.0, &hop.1), login)
} else {
(Vec::new(), Vec::new())
};
let waiting: BTreeSet<String> = waiting.into_iter().collect();
for w in waiting.difference(&self.wl_waiting) {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {w}"));
}
self.wl_waiting = waiting;
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if (name.starts_with(crate::wl::JOINER_PREFIX) || name.starts_with(crate::wl::CREATOR_PREFIX)) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
}
/// The wireproxy tunnels behind "userspace" AmneziaWG outbounds and WARP devices, while
/// the proxy they serve runs; the ones no longer wanted stopped.
async fn apply_awg(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
let userspace = derived_userspace(&cfg);
let (units, errors) = if self.proxy_wanted() && userspace {
let program = self.comps.program("wireproxy-awg", "wireproxy")?;
let login = (self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone());
let warp = crate::warp::profiles(&cfg, self.paths());
crate::awg::units(&cfg, self.paths(), &program, (&login.0, &login.1), &warp)
} else {
(Vec::new(), Vec::new())
};
for e in errors {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: {e}; leaving it out"));
}
let wanted: Vec<String> = units.iter().map(|u| u.name.clone()).collect();
for name in self.sup.names() {
if name.starts_with(crate::awg::UNIT_PREFIX) && !wanted.contains(&name) {
self.sup.stop(&name).await;
}
}
for unit in units {
self.sup.ensure(unit);
}
Ok(())
}
async fn apply_tor(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.tor.enable {
self.sup.stop(crate::tor::UNIT).await;
return Ok(());
}
// The Expert Bundle's tor.exe, checked; on Linux (development) the system's tor.
let program = self.comps.program("tor", "tor/tor")?;
let bundle = self.paths().bin().join("tor");
let bundle = program.starts_with(&bundle).then_some(bundle);
let spec = crate::tor::unit(&cfg, self.paths(), program, bundle.as_deref())?;
self.sup.ensure(spec);
Ok(())
}
async fn apply_ssh(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.ssh_proxy.enable {
self.sup.stop(crate::ssh::UNIT).await;
return Ok(());
}
let spec = crate::ssh::unit(&cfg, self.paths(), crate::ssh::program()?)?;
self.sup.ensure(spec);
Ok(())
}
async fn apply_tg(&mut self) -> Result<()> {
@@ -215,6 +450,13 @@ impl Service {
for w in &rendered.warnings {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
}
// sing-box refuses a local rule-set file that is not there: autoProxy's and zapret2's,
// written first.
if !rendered.probe_exits.is_empty() {
crate::autoproxy::publish(&rendered.probe_exits, &crate::autoproxy::load(self.paths()))?;
}
crate::zapret::sync_rule_sets(self.cfg(), self.paths())?;
crate::cutoff::write_rules(self.cfg(), self.paths())?;
let backend = self.cfg().proxy.backend;
let main_program = match backend {
@@ -227,14 +469,26 @@ impl Service {
// last good one running.
let candidate = run.join("candidate.json");
write_atomic(&candidate, &main_json)?;
if backend != Backend::Xray {
let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?;
if !out.status.success() {
let why = String::from_utf8_lossy(&out.stderr).trim().to_owned();
self.last_error = Some(format!("sing-box refused the rendered config: {why}"));
self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}"));
anyhow::bail!("sing-box refused the rendered config: {why}");
// XRay keeps its geodata beside xray.exe (the component's directory).
let asset_dir = main_program.parent().map(|d| d.to_string_lossy().into_owned());
let out = if backend == Backend::Xray {
let mut cmd = tokio::process::Command::new(&main_program);
cmd.args(["run", "-test", "-c"]).arg(&candidate);
if let Some(dir) = &asset_dir {
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) {
std::fs::rename(&candidate, &main_path)?;
@@ -247,7 +501,7 @@ impl Service {
name: SOCKS_UNIT.into(),
program: main_program,
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()),
generation: digest(&main_json),
});
@@ -296,8 +550,23 @@ impl Service {
pub fn status(&self) -> Value {
let cfg = self.cfg();
// The rendering's warnings, and the configuration's own (what is not on Windows yet
// among them): said for as long as they hold, not only when it is saved.
let mut warnings: Vec<String> = self.last.as_ref().map(|r| r.warnings.clone()).unwrap_or_default();
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 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!({
"units": units,
"proxy": {
@@ -311,6 +580,7 @@ impl Service {
"pinned": self.store.state.pin,
"selection": cfg.proxy.selection.as_str(),
},
"killSwitch": kill_switch,
"zapret": {
"enabled": cfg.zapret.enable,
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
@@ -322,7 +592,7 @@ impl Service {
"state": self.sup.state_of(crate::tg::UNIT).as_str(),
"listener": format!("{}:{}", cfg.tg_ws_proxy.listener.address, cfg.tg_ws_proxy.listener.port),
},
"warnings": self.last.as_ref().map(|r| r.warnings.clone()).unwrap_or_default(),
"warnings": warnings,
"error": self.last_error,
"revision": self.store.revision,
})
@@ -456,11 +726,60 @@ async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result<Value> {
Ok(v)
}
/// Whether any outbound runs in wireproxy: a "userspace" AmneziaWG profile or WARP device.
fn derived_userspace(cfg: &Config) -> bool {
ps_core::derived::extra_outbounds(cfg).iter().any(|e| {
matches!(&e.kind, ps_core::derived::ExtraKind::Awg { kind: ps_core::config::AwgOutboundKind::Userspace, .. })
|| matches!(&e.kind, ps_core::derived::ExtraKind::Warp { device } if device.kind == ps_core::config::WarpOutboundKind::Userspace)
})
}
/// WARP devices with no profile, registered (outside the lock: it is the network), and the
/// proxy applied again with them.
pub async fn register_warp(shared: &Shared) {
let (todo, routes, generator) = {
let s = shared.lock().await;
if !s.cfg().enable {
return;
}
(crate::warp::unregistered(s.cfg(), s.paths()), s.fetch_routes(true), s.cfg().warp.generator_url.clone())
};
let mut any = false;
for (tag, file) in todo {
let result = crate::warp::register(&routes, generator.as_deref()).await;
let mut s = shared.lock().await;
s.last_fetch.insert("warp".into(), SystemTime::now());
match result.and_then(|profile| {
std::fs::create_dir_all(file.parent().unwrap())?;
write_atomic(&file, profile.as_bytes())?;
// It holds the device's private key (on Windows the state root's ACL keeps it).
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}) {
Ok(()) => {
s.sup.note(SOCKS_UNIT, format!("proxy-suite: WARP device '{tag}' is registered"));
any = true;
}
Err(e) => s.sup.note(SOCKS_UNIT, format!("proxy-suite: WARP device '{tag}' could not register: {e:#}")),
}
}
if any {
let mut s = shared.lock().await;
if let Err(e) = s.apply().await {
tracing::warn!("after WARP's registration: {e:#}");
}
}
}
/// The timers: subscriptions and rule sets, each on its interval.
pub async fn timers(shared: Shared) {
loop {
tokio::time::sleep(Duration::from_secs(60)).await;
let (sub_due, rules_due) = {
let (sub_due, rules_due, warp_due) = {
let s = shared.lock().await;
let cfg = s.cfg();
let every = |text: &str, default: u64| ps_core::duration::parse(text).unwrap_or(Duration::from_secs(default));
@@ -471,8 +790,13 @@ pub async fn timers(shared: Shared) {
};
let subs: Vec<String> =
cfg.proxy.subscriptions.iter().filter(|x| due(&format!("sub:{}", x.tag), sub_every)).map(|x| x.tag.clone()).collect();
(subs, due("rule-sets", rules_every))
// A registration that failed is tried again every ten minutes.
let warp = !crate::warp::unregistered(cfg, s.paths()).is_empty() && due("warp", Duration::from_secs(600));
(subs, due("rule-sets", rules_every), warp)
};
if warp_due {
register_warp(&shared).await;
}
for tag in sub_due {
update_subscriptions(&shared, Some(&tag)).await;
}
+182
View File
@@ -0,0 +1,182 @@
//! The SSH tunnel: OpenSSH's dynamic SOCKS listener (`ssh -N -D`), run as upstream's
//! ssh-proxy.nix runs it, with Windows' own client (System32\OpenSSH, there since Windows 10
//! 1803). With the sing-box backend the proxy's `ssh-proxy` outbound is sing-box's own SSH
//! client; this listener is for other programs, and the outbound of the other backends.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::Config;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-ssh-proxy";
/// The OpenSSH client.
pub fn program() -> Result<PathBuf> {
#[cfg(windows)]
{
let root = std::env::var_os("SystemRoot").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Windows"));
let ssh = root.join(r"System32\OpenSSH\ssh.exe");
if !ssh.is_file() {
anyhow::bail!("Windows' OpenSSH client is not installed (Settings → System → Optional features → OpenSSH Client)");
}
Ok(ssh)
}
#[cfg(not(windows))]
Ok(PathBuf::from("ssh"))
}
/// Where the key is copied: below the state root, which only SYSTEM and administrators reach.
/// Windows' OpenSSH refuses a key others can read, and to a service running as SYSTEM the
/// user's own copy is someone else's; upstream copies it for its service too (systemd's
/// credentials).
pub fn identity_path(paths: &Paths) -> PathBuf {
paths.root.join("ssh").join("identity")
}
fn copy_identity(cfg: &Config, paths: &Paths) -> Result<Option<PathBuf>> {
let Some(src) = &cfg.ssh_proxy.identity_file else { return Ok(None) };
let data = std::fs::read(src).with_context(|| format!("reading sshProxy.identityFile {src}"))?;
let dst = identity_path(paths);
std::fs::create_dir_all(dst.parent().unwrap())?;
write_atomic(&dst, &data)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&dst, std::fs::Permissions::from_mode(0o600))?;
}
Ok(Some(dst))
}
/// The server's keys as sing-box takes them (`ssh-ed25519 AAAA…`): `hostKey`, else the lines
/// of `hostKeyFile` or `knownHostsFile`, a known-hosts line's host names left off.
pub fn host_keys(cfg: &Config, read: impl Fn(&str) -> Option<String>) -> Vec<String> {
let s = &cfg.ssh_proxy;
if !s.host_key.is_empty() {
return s.host_key.clone();
}
let Some(text) = s.host_key_file.as_deref().or(s.known_hosts_file.as_deref()).and_then(read) else {
return Vec::new();
};
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| {
let fields: Vec<&str> = l.split_whitespace().collect();
// A key type comes first in a key line; in a known-hosts line, the hosts do.
let is_type = |f: &str| f.starts_with("ssh-") || f.starts_with("ecdsa-") || f.starts_with("sk-");
match fields.iter().position(|f| is_type(f)) {
Some(at) => fields[at..].iter().take(2).copied().collect::<Vec<_>>().join(" "),
None => l.to_owned(),
}
})
.collect()
}
/// The known-hosts file ssh is given: `knownHostsFile`, or one written from the server's keys,
/// or one of the service's own, where `accept-new` keeps what it accepts.
fn known_hosts(cfg: &Config, paths: &Paths, keys: &[String]) -> Result<PathBuf> {
let s = &cfg.ssh_proxy;
if let Some(f) = &s.known_hosts_file {
return Ok(PathBuf::from(f));
}
let dir = paths.root.join("ssh");
std::fs::create_dir_all(&dir)?;
if keys.is_empty() {
return Ok(dir.join("known_hosts"));
}
let host = s.server.host.as_deref().unwrap_or("");
let name = if s.server.port == 22 { host.to_owned() } else { format!("[{host}]:{}", s.server.port) };
let text: String = keys.iter().map(|k| format!("{name} {k}\n")).collect();
let file = dir.join("known_hosts.given");
write_atomic(&file, text.as_bytes())?;
Ok(file)
}
pub fn args(cfg: &Config, known_hosts: &Path, identity: Option<&Path>) -> Vec<String> {
let s = &cfg.ssh_proxy;
// ssh reads "::1:1091" as a bad forwarding: an IPv6 address goes in brackets.
let listen = if s.listener.address.contains(':') { format!("[{}]", s.listener.address) } else { s.listener.address.clone() };
let mut a: Vec<String> = [
"-N",
"-o",
"BatchMode=yes",
"-o",
"ExitOnForwardFailure=yes",
"-o",
"ServerAliveInterval=15",
"-o",
"ServerAliveCountMax=3",
"-o",
"ConnectTimeout=10",
]
.map(String::from)
.to_vec();
a.extend(["-o".into(), format!("StrictHostKeyChecking={}", s.strict_host_key_checking.as_str())]);
a.extend(["-o".into(), format!("UserKnownHostsFile={}", known_hosts.display())]);
a.extend(["-D".into(), format!("{listen}:{}", s.listener.port)]);
if s.server.port != 22 {
a.extend(["-p".into(), s.server.port.to_string()]);
}
if let Some(identity) = identity {
// That key alone: not an agent's or ~/.ssh's first, which can use up the server's
// MaxAuthTries before it.
a.extend(["-i".into(), identity.display().to_string(), "-o".into(), "IdentitiesOnly=yes".into()]);
}
a.extend(s.extra_args.iter().cloned());
// The user and the host never read as options (ssh runs as SYSTEM; `-oProxyCommand=…` as
// a host would run a program): the user as -l's value, the host after the options' end.
// The validator also holds them to a login name and a host name or address.
if let Some(u) = &s.server.user {
a.extend(["-l".into(), u.clone()]);
}
a.push("--".into());
a.push(s.server.host.clone().unwrap_or_default());
a
}
pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
let keys = host_keys(cfg, |f| std::fs::read_to_string(f).ok());
let known = known_hosts(cfg, paths, &keys)?;
let identity = copy_identity(cfg, paths)?;
let args = args(cfg, &known, identity.as_deref());
Ok(UnitSpec { name: UNIT.into(), program, generation: args.join("\n"), args, env: Vec::new(), cwd: None })
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg() -> Config {
let mut c = Config::default();
c.ssh_proxy.enable = true;
c.ssh_proxy.server.host = Some("vps.example".into());
c.ssh_proxy.server.user = Some("me".into());
c
}
#[test]
fn upstreams_flags() {
let mut c = cfg();
c.ssh_proxy.server.port = 2222;
let a = args(&c, Path::new("kh"), Some(Path::new(r"C:\keys\id_ed25519")));
assert_eq!(&a[..2], ["-N", "-o"]);
assert!(a.windows(2).any(|w| w == ["-D", "127.0.0.1:1091"]), "{a:?}");
assert!(a.windows(2).any(|w| w == ["-p", "2222"]));
assert!(a.windows(2).any(|w| w == ["-i", r"C:\keys\id_ed25519"]));
assert!(a.contains(&"UserKnownHostsFile=kh".to_owned()));
assert_eq!(&a[a.len() - 4..], ["-l", "me", "--", "vps.example"]);
}
#[test]
fn host_keys_from_lines_of_either_kind() {
let mut c = cfg();
c.ssh_proxy.host_key_file = Some("f".into());
let keys = host_keys(&c, |_| Some("# c\nvps.example ssh-ed25519 AAAA1\nssh-rsa BBBB2 comment\n".into()));
assert_eq!(keys, ["ssh-ed25519 AAAA1", "ssh-rsa BBBB2"]);
c.ssh_proxy.host_key = vec!["ssh-ed25519 CCCC".into()];
assert_eq!(host_keys(&c, |_| None), ["ssh-ed25519 CCCC"]);
}
}
+29
View File
@@ -52,6 +52,26 @@ pub fn args(cfg: &Config, secret: &str) -> Vec<String> {
a
}
/// The links tg-ws-proxy prints for itself: `dd` with the secret, and `ee` with the fake-TLS
/// domain after it when one is set. A wildcard listener is named by this machine's address.
pub fn links(cfg: &Config, secret: &str) -> Vec<String> {
let t = &cfg.tg_ws_proxy;
let host = match t.listener.address.as_str() {
"0.0.0.0" => std::net::UdpSocket::bind("0.0.0.0:0")
.and_then(|s| s.connect("8.8.8.8:80").and_then(|()| s.local_addr()))
.map(|a| a.ip().to_string())
.unwrap_or_else(|_| "127.0.0.1".into()),
h => h.to_owned(),
};
let base = format!("tg://proxy?server={host}&port={}&secret=", t.listener.port);
let mut out = vec![format!("{base}dd{secret}")];
if let Some(domain) = t.fake_tls_domain.as_deref().filter(|d| !d.is_empty()) {
let hex: String = domain.bytes().map(|b| format!("{b:02x}")).collect();
out.push(format!("{base}ee{secret}{hex}"));
}
out
}
/// The secret: given, or read from `secretFile`, or one generated once and kept.
pub fn secret(cfg: &Config, paths: &Paths) -> Result<String> {
let t = &cfg.tg_ws_proxy;
@@ -89,6 +109,15 @@ pub fn unit(cfg: &Config, paths: &Paths, python: PathBuf) -> Result<UnitSpec> {
mod tests {
use super::*;
#[test]
fn links_are_tg_ws_proxys() {
let mut cfg = Config::default();
cfg.tg_ws_proxy.listener.port = 1443;
assert_eq!(links(&cfg, "ab"), ["tg://proxy?server=127.0.0.1&port=1443&secret=ddab"]);
cfg.tg_ws_proxy.fake_tls_domain = Some("x.io".into());
assert_eq!(links(&cfg, "ab")[1], "tg://proxy?server=127.0.0.1&port=1443&secret=eeab782e696f");
}
#[test]
fn upstreams_flags() {
let mut cfg = Config::default();
+192
View File
@@ -0,0 +1,192 @@
//! Tor: the SOCKS listener behind the `tor` outbound, run with the torrc upstream's tor.nix
//! writes, from the Tor Expert Bundle (the Tor Project's, signed; components.json). On Windows
//! the control port is on loopback with cookie authentication, the cookie below the protected
//! state root; upstream uses a Unix socket only Tor's user may open. Onion services serve the
//! inbounds, which are not on Windows yet.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use ps_core::config::{Config, Upstream};
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-tor";
/// A torrc string, which Tor unescapes C's way inside the quotes. Control characters are
/// escaped too: a bare newline would end the line and start a directive of the value's
/// choosing (one that runs a program, as SYSTEM).
fn quote(s: &str) -> String {
let mut out = String::from("\"");
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'"' => out.push_str("\\\""),
c if (c as u32) < 0x20 || c as u32 == 0x7f => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
/// Bridge lines as upstream takes them: trimmed, blanks and comments gone, "Bridge " in front.
/// One with a control character left in it (a lone carriage return) is refused: it could end
/// the line in Tor's reading and start a directive.
fn bridge_lines(text: &str) -> Result<Vec<String>> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| {
if l.chars().any(char::is_control) {
anyhow::bail!("a bridge line has a control character in it");
}
let bare = l.strip_prefix("Bridge").filter(|r| r.starts_with(char::is_whitespace)).map(str::trim_start).unwrap_or(l);
Ok(format!("Bridge {bare}"))
})
.collect()
}
/// The torrc. `bundle` is the Expert Bundle's directory (its GeoIP files and transports), or
/// `None` for a Tor of the system's own (Linux, for development); `data` is Tor's state.
pub fn torrc(cfg: &Config, bundle: Option<&Path>, data: &Path, read: impl Fn(&str) -> Result<String>) -> Result<String> {
let t = &cfg.tor;
let mut c: Vec<String> = Vec::new();
if let Some(b) = bundle {
c.push(format!("GeoIPFile {}", b.join("data").join("geoip").display()));
c.push(format!("GeoIPv6File {}", b.join("data").join("geoip6").display()));
}
c.extend(
["ClientUseIPv6 1", "AvoidDiskWrites 1", "Log notice stdout", "AutomapHostsOnResolve 0", "DNSPort 0", "TransPort 0", "NATDPort 0"]
.map(String::from),
);
if t.client_only {
c.push("ClientOnly 1".into());
}
if t.keep_awake {
c.extend(["DormantTimeoutEnabled 0".into(), "DormantCanceledByStartup 1".into()]);
}
c.push(if t.as_outbound { format!("SocksPort 127.0.0.1:{}", t.socks_port) } else { "SocksPort 0".into() });
let mut bridges: Vec<String> = Vec::new();
for l in &t.bridges.lines {
bridges.extend(bridge_lines(l)?);
}
if let Some(f) = &t.bridges.file {
bridges.extend(bridge_lines(&read(f).with_context(|| format!("reading tor.bridges.file {f}"))?)?);
}
if !bridges.is_empty() {
c.push("UseBridges 1".into());
let pt = |exe: &str| bundle.map(|b| b.join("tor").join("pluggable_transports").join(exe).display().to_string()).unwrap_or_else(|| exe.trim_end_matches(".exe").into());
// The bundle's own pt_config.json: lyrebird carries snowflake too.
c.push(format!("ClientTransportPlugin meek_lite,obfs2,obfs3,obfs4,scramblesuit,webtunnel exec {}", pt("lyrebird.exe")));
c.push(format!("ClientTransportPlugin snowflake exec {}", pt("lyrebird.exe")));
if bundle.is_some() {
c.push(format!("ClientTransportPlugin conjure exec {} -registerURL https://registration.refraction.network/api", pt("conjure-client.exe")));
}
c.extend(bridges);
}
if t.upstream == Upstream::Proxy {
let l = &cfg.proxy.listener;
// Written from the parsed address, never the text: it is not quoted in the torrc.
let ip: std::net::IpAddr = l.address.parse().context("proxy.listener.address is not an IP address")?;
let host = match ip {
ip if ip.is_unspecified() => "127.0.0.1".to_owned(),
std::net::IpAddr::V6(v6) => format!("[{v6}]"),
v4 => v4.to_string(),
};
c.push(format!("Socks5Proxy {host}:{}", l.port));
if let Some(user) = &l.auth.username {
let password = match (&l.auth.password, &l.auth.password_file) {
(Some(p), _) => p.clone(),
(None, Some(f)) => read(f)?.lines().next().unwrap_or("").to_owned(),
(None, None) => String::new(),
};
c.push(format!("Socks5ProxyUsername {}", quote(user)));
c.push(format!("Socks5ProxyPassword {}", quote(&password)));
}
}
c.push(format!("DataDirectory {}", data.display()));
c.push(format!("ControlPort 127.0.0.1:{}", t.control_port));
c.push("CookieAuthentication 1".into());
c.push(format!("CookieAuthFile {}", data.join("control_auth_cookie").display()));
let mut out = c.join("\n");
out.push('\n');
if !t.extra_config.is_empty() {
out.push_str(&t.extra_config);
if !t.extra_config.ends_with('\n') {
out.push('\n');
}
}
Ok(out)
}
/// The program: the bundle's tor.exe (checked against its hashes by the caller), or on Linux
/// the system's `tor`.
pub fn unit(cfg: &Config, paths: &Paths, program: PathBuf, bundle: Option<&Path>) -> Result<UnitSpec> {
let data = paths.root.join("tor");
std::fs::create_dir_all(&data)?;
let text = torrc(cfg, bundle, &data, |f| std::fs::read_to_string(f).with_context(|| format!("reading {f}")))?;
let file = paths.run().join("torrc");
write_atomic(&file, text.as_bytes())?;
Ok(UnitSpec {
name: UNIT.into(),
program,
args: vec!["-f".into(), file.display().to_string()],
env: Vec::new(),
cwd: Some(data),
generation: text,
})
}
#[cfg(test)]
mod tests {
use super::*;
fn cfg() -> Config {
let mut c = Config::default();
c.tor.enable = true;
c.tor.as_outbound = true;
c
}
#[test]
fn upstreams_torrc() {
let t = torrc(&cfg(), Some(Path::new("B")), Path::new("D"), |_| Ok(String::new())).unwrap();
for want in ["GeoIPFile B", "ClientOnly 1", "SocksPort 127.0.0.1:18530", "DNSPort 0", "DataDirectory D", "AutomapHostsOnResolve 0"] {
assert!(t.lines().any(|l| l.starts_with(want)), "{want} in\n{t}");
}
assert!(!t.contains("UseBridges"));
}
#[test]
fn bridges_and_the_proxy_upstream() {
let mut c = cfg();
c.tor.bridges.lines = vec!["obfs4 192.0.2.1:443 FP cert=x iat-mode=0".into(), "Bridge webtunnel 192.0.2.2:443 FP url=https://e.example/x".into()];
c.tor.bridges.file = Some("f".into());
c.tor.upstream = Upstream::Proxy;
c.proxy.listener.auth.username = Some("u".into());
c.proxy.listener.auth.password = Some("p\"#\\".into());
let t = torrc(&c, Some(Path::new("B")), Path::new("D"), |_| Ok("# c\n snowflake 192.0.2.3:80 FP\n".into())).unwrap();
assert!(t.contains("UseBridges 1"));
assert!(t.contains("Bridge obfs4 192.0.2.1:443 FP cert=x iat-mode=0\n"));
assert!(t.contains("Bridge webtunnel 192.0.2.2:443"));
assert!(t.contains("Bridge snowflake 192.0.2.3:80 FP\n"));
assert!(t.contains("lyrebird.exe"));
assert!(t.contains("Socks5Proxy 127.0.0.1:1080\n"));
assert!(t.contains("Socks5ProxyPassword \"p\\\"#\\\\\"\n"), "{t}");
// A newline in a value stays in its line.
c.proxy.listener.auth.username = Some("u\nClientTransportPlugin x exec calc.exe".into());
let t = torrc(&c, None, Path::new("D"), |_| Ok(String::new())).unwrap();
assert!(t.contains("Socks5ProxyUsername \"u\\x0aClientTransportPlugin x exec calc.exe\"\n"), "{t}");
assert!(!t.lines().any(|l| l.starts_with("ClientTransportPlugin x")));
// Nor through the address, which is not quoted, or a bridge line.
c.proxy.listener.auth.username = None;
c.proxy.listener.address = "127.0.0.1\nClientTransportPlugin x exec calc.exe".into();
assert!(torrc(&c, None, Path::new("D"), |_| Ok(String::new())).is_err());
c.proxy.listener.address = "127.0.0.1".into();
c.tor.bridges.lines = vec!["obfs4 192.0.2.1:443 FP\rClientTransportPlugin x exec calc.exe".into()];
assert!(torrc(&c, None, Path::new("D"), |_| Ok(String::new())).is_err());
}
}
+12
View File
@@ -280,6 +280,18 @@ async fn run(ctx: RunCtx, mut stop: watch::Receiver<bool>) {
// No console window for the children.
cmd.creation_flags(0x0800_0000);
}
// On Linux (development, tests) the children end with the service, as the Job Object
// ends them on Windows, even when the service is killed outright. The signal comes when
// the spawning thread ends: a runtime worker, which lives as long as the service.
#[cfg(target_os = "linux")]
unsafe {
cmd.pre_exec(|| {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
return Err(std::io::Error::last_os_error());
}
Ok(())
});
}
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) => {
+386
View File
@@ -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());
}
}
+99
View File
@@ -0,0 +1,99 @@
//! WARP devices: each one's WireGuard profile, given in the configuration or registered with
//! Cloudflare as wgcf registers (ps_core::warp), kept below the protected state root (it holds
//! the device's private key). The renderer makes each a sing-box WireGuard endpoint.
use std::collections::BTreeMap;
use std::path::PathBuf;
use anyhow::{Result, anyhow};
use base64::Engine;
use ps_core::config::Config;
use ps_core::derived::{self, WarpDeviceSpec};
use crate::fetch::{self, Route};
use crate::paths::Paths;
fn profile_file(paths: &Paths, device: &WarpDeviceSpec) -> PathBuf {
paths.root.join(&device.state_subdir).join("wgcf-profile.conf")
}
/// Each device's profile there is without the network: given, or registered before.
pub fn profiles(cfg: &Config, paths: &Paths) -> BTreeMap<String, String> {
derived::warp_devices(cfg)
.into_iter()
.filter_map(|d| {
let text = match (&d.config, &d.config_file) {
(Some(t), _) => Some(t.clone()),
(None, Some(f)) => std::fs::read_to_string(f).ok(),
(None, None) => std::fs::read_to_string(profile_file(paths, &d)).ok(),
};
text.map(|t| (d.tag, t))
})
.collect()
}
/// The devices to register, and where each one's profile goes: none given, none registered.
pub fn unregistered(cfg: &Config, paths: &Paths) -> Vec<(String, PathBuf)> {
derived::warp_devices(cfg)
.into_iter()
.filter(|d| d.auto_register())
.map(|d| {
let file = profile_file(paths, &d);
(d.tag, file)
})
.filter(|(_, file)| !file.is_file())
.collect()
}
/// Now as RFC 3339, the terms' acceptance time the API wants.
fn now() -> String {
let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0);
let (days, rem) = (secs.div_euclid(86400), secs.rem_euclid(86400));
// Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
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}T{:02}:{:02}:{:02}.000Z", rem / 3600, rem % 3600 / 60, rem % 60)
}
/// A new device: a key made here, its public half registered through each route in turn
/// (the local proxy first: the API is blocked in some countries), then `generator` if given.
pub async fn register(routes: &[Route], generator: Option<&str>) -> Result<String> {
let mut seed = [0u8; 32];
rand::fill(&mut seed);
let secret = x25519_dalek::StaticSecret::from(seed);
let public = x25519_dalek::PublicKey::from(&secret);
let b64 = |b: &[u8]| base64::engine::general_purpose::STANDARD.encode(b);
let body = ps_core::warp::registration(&b64(public.as_bytes()), &now());
let mut last = None;
for route in routes {
match fetch::post_json(ps_core::warp::API, &body, &ps_core::warp::HEADERS, route).await {
Ok(answer) => return ps_core::warp::profile(&answer, &b64(&secret.to_bytes())).map_err(anyhow::Error::msg),
Err(e) => last = Some(e),
}
}
if let Some(url) = generator {
for route in routes {
if let Ok(body) = fetch::get(url, route, 64 * 1024).await {
return ps_core::warp::generated(&String::from_utf8_lossy(&body)).map_err(anyhow::Error::msg);
}
}
}
Err(last.unwrap_or_else(|| anyhow!("no way to reach it")).context("registering with Cloudflare"))
}
#[cfg(test)]
mod tests {
#[test]
fn now_is_rfc3339() {
let n = super::now();
assert_eq!(n.len(), 24, "{n}");
assert!(n.starts_with("20") && n.ends_with(".000Z") && &n[10..11] == "T", "{n}");
}
}
+345 -2
View File
@@ -25,7 +25,7 @@ pub fn install_dir() -> PathBuf {
}
/// The files of a release that `install` copies.
const RELEASE_FILES: [&str; 7] = ["proxy-suite-service.exe", "proxy-ctl.exe", "README.md", "THIRD-PARTY.md", "LICENSE", "install.cmd", "uninstall.cmd"];
const RELEASE_FILES: [&str; 8] = ["proxy-suite-service.exe", "proxy-ctl.exe", "proxy-suite.exe", "README.md", "THIRD-PARTY.md", "LICENSE", "install.cmd", "uninstall.cmd"];
fn copy_release(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
@@ -97,13 +97,20 @@ pub fn install() -> Result<()> {
wait_stopped(&existing)?;
}
if from != to {
copy_release(&from, &to)?;
desktop::close();
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
}
Err(_) => {
if from != to {
desktop::close();
copy_release(&from, &to)?;
}
manager.create_service(&info, access).context("creating the service")?
@@ -134,6 +141,17 @@ pub fn install() -> Result<()> {
println!("Start it with: sc start {NAME} (its log: %ProgramData%\\ProxySuite\\logs\\service.log)");
}
}
match desktop::add(&to) {
Ok(true) => {
desktop::start(&to);
println!("The app is in the Start Menu (Proxy Suite) and starts at sign-in, in the tray.");
}
Ok(false) => {}
Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"),
}
if let Err(e) = apps::add(&to) {
println!("warning: the entry in Settings → Apps: {e:#}");
}
println!("Open a new terminal and try: proxy-ctl status");
Ok(())
}
@@ -153,7 +171,11 @@ pub fn uninstall() -> Result<()> {
} else {
println!("{DISPLAY} was not installed.");
}
remove_windivert(&manager);
crate::awgvpn::remove_all(&crate::paths::Paths::platform_default());
let dir = install_dir();
desktop::remove();
apps::remove();
let _ = path::remove(&dir);
if dir.exists() {
// This program may be one of the files: they go a moment after it exits. Raw, as cmd
@@ -174,6 +196,327 @@ pub fn uninstall() -> Result<()> {
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
/// (WinDivert removes its own service as it loads, but one stopped hard can stay): stopped and
/// deleted, as Flowseal's service.bat removes it. One from elsewhere is left alone.
fn remove_windivert(manager: &ServiceManager) {
let ours = crate::paths::Paths::platform_default().root.to_string_lossy().to_lowercase();
for name in ["WinDivert", "WinDivert14"] {
let Ok(service) = manager.open_service(name, ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) else {
continue;
};
let Ok(config) = service.query_config() else { continue };
if config.executable_path.to_string_lossy().to_lowercase().contains(&ours) {
let _ = service.stop();
if service.delete().is_ok() {
println!("WinDivert's driver ({name}) is removed.");
}
}
}
}
/// The entry in Settings → Apps (and Control Panel's Programs and Features): its Uninstall runs
/// uninstall.cmd, which asks for administrator rights; `QuietUninstallString` (winget, scripts
/// that run elevated) the service's own `uninstall`.
mod apps {
use std::path::Path;
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteTreeW,
RegSetValueExW,
};
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn size_kib(dir: &Path) -> u64 {
fn walk(dir: &Path) -> u64 {
std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| match e.file_type() {
Ok(t) if t.is_dir() => walk(&e.path()),
Ok(t) if t.is_file() => e.metadata().map_or(0, |m| m.len()),
_ => 0,
}).sum()
}
walk(dir) / 1024
}
pub fn add(dir: &Path) -> Result<()> {
let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into());
let d = dir.display();
let text = [
("DisplayName", super::DISPLAY.to_owned()),
("DisplayVersion", env!("CARGO_PKG_VERSION").to_owned()),
("Publisher", "Proxy Suite".to_owned()),
("URLInfoAbout", "https://git.faumaray.com/faumaray/proxy-suite-flake".to_owned()),
("InstallLocation", d.to_string()),
("DisplayIcon", format!("{d}\\proxy-suite.exe")),
// cmd's /c takes the whole line in one more pair of quotes.
("UninstallString", format!("\"{system}\\System32\\cmd.exe\" /c \"\"{d}\\uninstall.cmd\"\"")),
("QuietUninstallString", format!("\"{d}\\proxy-suite-service.exe\" uninstall")),
];
let numbers = [("NoModify", 1u32), ("NoRepair", 1), ("EstimatedSize", size_kib(dir).min(u32::MAX as u64) as u32)];
// SAFETY: NUL-terminated names and data, lengths as given; the key is closed below.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegCreateKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, std::ptr::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, std::ptr::null(), &mut key, std::ptr::null_mut()) != ERROR_SUCCESS {
bail!("cannot create the uninstall key");
}
let mut failed = false;
for (name, value) in &text {
let data = wide(value);
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) != ERROR_SUCCESS;
}
for (name, value) in &numbers {
failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_DWORD, (value as *const u32).cast(), 4) != ERROR_SUCCESS;
}
RegCloseKey(key);
if failed {
bail!("cannot write the uninstall key");
}
}
Ok(())
}
pub fn remove() {
// SAFETY: a NUL-terminated name.
unsafe {
RegDeleteTreeW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr());
}
}
}
/// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray;
/// closed before its files are replaced or removed.
mod desktop {
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegSetValueExW};
const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run";
const RUN_VALUE: &str = "Proxy Suite";
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn shortcut() -> PathBuf {
let data = std::env::var_os("ProgramData").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"));
data.join(r"Microsoft\Windows\Start Menu\Programs\Proxy Suite.lnk")
}
/// At sign-in, for every user: `command`, or nothing.
fn set_run(command: Option<&str>) -> Result<()> {
// SAFETY: NUL-terminated names and data; the key is closed below.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegOpenKeyExW(HKEY_LOCAL_MACHINE, wide(RUN_KEY).as_ptr(), 0, KEY_WRITE, &mut key) != ERROR_SUCCESS {
bail!("cannot open the Run key");
}
let name = wide(RUN_VALUE);
let rc = match command {
Some(c) => {
let data = wide(c);
RegSetValueExW(key, name.as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32)
}
None => RegDeleteValueW(key, name.as_ptr()),
};
RegCloseKey(key);
if rc != ERROR_SUCCESS && command.is_some() {
bail!("cannot write the Run key (error {rc})");
}
}
Ok(())
}
fn quiet(cmd: &mut Command) -> &mut Command {
cmd.creation_flags(CREATE_NO_WINDOW).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null())
}
/// Every running copy, every user's: its files are about to change. (It clears a system
/// proxy it left set when it next starts.)
pub fn close() {
let _ = quiet(Command::new("taskkill").args(["/F", "/IM", "proxy-suite.exe"])).status();
}
/// The Start Menu entry and the start at sign-in, when the release has the app.
pub fn add(dir: &Path) -> Result<bool> {
let app = dir.join("proxy-suite.exe");
if !app.is_file() {
return Ok(false);
}
set_run(Some(&format!("\"{}\" --hidden", app.display())))?;
// PowerShell's single-quoted strings: a quote is doubled.
let q = |p: &Path| format!("'{}'", p.display().to_string().replace('\'', "''"));
let script = format!(
"$s = (New-Object -ComObject WScript.Shell).CreateShortcut({}); $s.TargetPath = {}; $s.WorkingDirectory = {}; $s.Description = 'Proxy Suite'; $s.Save()",
q(&shortcut()),
q(&app),
q(dir)
);
let ok = quiet(Command::new("powershell").args(["-NoProfile", "-NonInteractive", "-Command", &script])).status().is_ok_and(|s| s.success());
if !ok {
bail!("PowerShell did not make the Start Menu shortcut");
}
Ok(true)
}
/// 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) {
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() {
close();
clear_system_proxy();
let _ = set_run(None);
let _ = std::fs::remove_file(shortcut());
}
/// The signed-in user's system proxy, when the app (just closed, and going) left it on the
/// local proxy: turned off, or their programs keep using a proxy that is gone. Another
/// proxy of theirs is left alone.
fn clear_system_proxy() {
use windows_sys::Win32::Networking::WinInet::{INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, InternetSetOptionW};
use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, KEY_READ, REG_DWORD, RegQueryValueExW};
let config: serde_json::Value = std::fs::read(crate::paths::Paths::platform_default().root.join("config.json"))
.ok()
.and_then(|b| serde_json::from_slice(&b).ok())
.unwrap_or_default();
let port = config["proxy"]["listener"]["port"].as_u64().unwrap_or(1080);
let ours = [format!("127.0.0.1:{port}"), format!("localhost:{port}")];
// SAFETY: NUL-terminated names; buffers as long as said; the key is closed below.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
let path = wide(r"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
if RegOpenKeyExW(HKEY_CURRENT_USER, path.as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) != ERROR_SUCCESS {
return;
}
let mut server = vec![0u16; 512];
let mut len = (server.len() * 2) as u32;
let read = RegQueryValueExW(key, wide("ProxyServer").as_ptr(), std::ptr::null(), std::ptr::null_mut(), server.as_mut_ptr().cast(), &mut len);
let server = String::from_utf16_lossy(&server[..(len as usize / 2)]).trim_end_matches('\0').to_owned();
if read == ERROR_SUCCESS && ours.contains(&server) {
let off = 0u32;
RegSetValueExW(key, wide("ProxyEnable").as_ptr(), 0, REG_DWORD, (&off as *const u32).cast(), 4);
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_SETTINGS_CHANGED, std::ptr::null(), 0);
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_REFRESH, std::ptr::null(), 0);
}
RegCloseKey(key);
}
}
}
/// The system PATH, in the registry.
mod path {
use std::path::Path;
+221
View File
@@ -0,0 +1,221 @@
//! whitelist-bypass, as upstream's whitelist-bypass.nix runs it: joiners, each a SOCKS listener
//! on loopback (with the hop login) behind its outbound, tunnelled through a video call; and
//! creators, the free ends of those calls. Links, logins and passwords reach them through the
//! environment (the build makes those the flags' defaults), never their command lines.
//!
//! A joiner waits for its call's link (`proxy-ctl wl join`, or `linkFile`); a creator for a login
//! (`proxy-ctl wl auth`, or `cookiesFile`), which it keeps refreshing in its own working copy.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, Upstream, WlCreator, WlResources};
use ps_core::derived::ports;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const JOINER_PREFIX: &str = "proxy-suite-wb-joiner-";
pub const CREATOR_PREFIX: &str = "proxy-suite-wb-creator-";
/// What `proxy-ctl wl` leaves for the units: links (`<name>.join`), logins
/// (`<name>.cookies.json`), and the creators' calls (`<name>.link`, last line the current).
pub fn state_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass")
}
/// The creators' working logins, which they rewrite as they refresh them.
fn sessions_dir(paths: &Paths) -> PathBuf {
paths.root.join("whitelist-bypass-sessions")
}
/// `name`'s file in `dir`: a plain name there, checked here again whatever let it through (on
/// Windows, joining an absolute path replaces the directory).
fn named(dir: &Path, name: &str, suffix: &str) -> Result<PathBuf> {
if !ps_core::config::path_name_ok(name) {
bail!("'{name}' is not a creator or joiner name");
}
Ok(dir.join(format!("{name}{suffix}")))
}
/// `name`'s file in the state directory: `.join`, `.cookies.json` or `.link`.
pub fn state_file(paths: &Paths, name: &str, suffix: &str) -> Result<PathBuf> {
named(&state_dir(paths), name, suffix)
}
fn resources(r: WlResources) -> &'static str {
match r {
WlResources::Moderate => "moderate",
WlResources::Default => "default",
WlResources::Unlimited => "unlimited",
}
}
/// A link as the units take it: whitespace gone, one line.
pub fn clean_link(text: &str) -> Result<String> {
let link: String = text.chars().filter(|c| !c.is_whitespace()).collect();
if link.is_empty() {
bail!("an empty link");
}
if link.len() > 4096 || link.chars().any(char::is_control) {
bail!("that is not a call link");
}
Ok(link)
}
/// The units, and what each that cannot run yet waits for. `program` finds one of the
/// component's programs by name.
pub fn units(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
hop: (&str, &str),
proxy_login: Option<(String, String)>,
) -> (Vec<UnitSpec>, Vec<String>) {
let w = &cfg.whitelist_bypass;
let mut units = Vec::new();
let mut waiting = Vec::new();
for (i, (tag, j)) in w.joiners.iter().enumerate() {
let port = ports::WL_JOINER_BASE + i as u16;
// The link `wl join` gave wins over linkFile.
let link = state_file(paths, tag, ".join")
.and_then(|f| Ok(std::fs::read_to_string(f)?))
.ok()
.or_else(|| j.link_file.as_ref().and_then(|f| std::fs::read_to_string(f).ok()))
.and_then(|t| clean_link(&t).ok());
let Some(link) = link else {
waiting.push(format!("whitelist-bypass joiner '{tag}' waits for its call's link: proxy-ctl wl join {tag} <link>"));
continue;
};
let program = match program(&format!("headless-{}-joiner", j.platform.as_str())) {
Ok(p) => p,
Err(e) => {
waiting.push(format!("whitelist-bypass joiner '{tag}': {e:#}"));
continue;
}
};
let args = vec!["--socks-port".into(), port.to_string(), "--socks-user".into(), hop.0.to_owned()];
units.push(UnitSpec {
name: format!("{JOINER_PREFIX}{tag}"),
program,
generation: format!("{args:?}{link}"),
args,
env: vec![("WB_LINK".into(), link), ("WB_SOCKS_PASS".into(), hop.1.to_owned())],
cwd: None,
});
}
for (name, c) in &w.creators {
match creator(cfg, paths, program, name, c, proxy_login.clone()) {
Ok(Some(unit)) => units.push(unit),
Ok(None) => waiting.push(format!("whitelist-bypass creator '{name}' waits for a login: proxy-ctl wl auth {name} <cookies.json>")),
Err(e) => waiting.push(format!("whitelist-bypass creator '{name}': {e:#}")),
}
}
(units, waiting)
}
/// The call a creator made and keeps rejoining: the last line it wrote.
pub fn last_link(paths: &Paths, name: &str) -> Option<String> {
let text = std::fs::read_to_string(state_file(paths, name, ".link").ok()?).ok()?;
text.lines().map(str::trim).rfind(|l| !l.is_empty()).map(str::to_owned)
}
/// Writes a file only the service reads: a link, a login.
pub fn write_private(file: &Path, data: &[u8]) -> Result<()> {
if let Some(dir) = file.parent() {
std::fs::create_dir_all(dir)?;
}
write_atomic(file, data).with_context(|| format!("writing {}", file.display()))?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(file, std::fs::Permissions::from_mode(0o600))?;
}
Ok(())
}
fn creator(
cfg: &Config,
paths: &Paths,
program: &dyn Fn(&str) -> Result<PathBuf>,
name: &str,
c: &WlCreator,
proxy_login: Option<(String, String)>,
) -> Result<Option<UnitSpec>> {
let program = program(&format!("headless-{}-creator", c.platform.as_str()))?;
let sessions = sessions_dir(paths);
std::fs::create_dir_all(state_dir(paths))?;
std::fs::create_dir_all(&sessions)?;
let given = state_file(paths, name, ".cookies.json")?;
let cookies = named(&sessions, name, ".cookies.json")?;
// A login `wl auth` left replaces the working copy, then goes.
if given.is_file() {
write_private(&cookies, &std::fs::read(&given)?)?;
std::fs::remove_file(&given)?;
} else if !cookies.is_file()
&& let Some(f) = &c.cookies_file
{
write_private(&cookies, &std::fs::read(f).with_context(|| format!("reading {f}"))?)?;
}
if !cookies.is_file() {
return Ok(None);
}
let links = state_file(paths, name, ".link")?;
// linkFile's call, or the last one it made (empty: it makes one).
let link = match &c.link_file {
Some(f) => clean_link(&std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?)?,
None => last_link(paths, name).unwrap_or_default(),
};
let mut args: Vec<String> = vec![
"--cookies".into(),
cookies.display().to_string(),
"--write-file".into(),
links.display().to_string(),
"--resources".into(),
resources(c.resources).into(),
];
let mut env = vec![("WB_LINK".to_owned(), link)];
if c.upstream == Upstream::Proxy {
// From the parsed address, as Tor's: the listener's own, or loopback for a wildcard.
let l = &cfg.proxy.listener;
let host = match l.address.parse::<std::net::IpAddr>().context("proxy.listener.address is not an IP address")? {
ip if ip.is_unspecified() => "127.0.0.1".to_owned(),
std::net::IpAddr::V6(v6) => format!("[{v6}]"),
v4 => v4.to_string(),
};
args.extend(["--upstream-socks".into(), format!("{host}:{}", l.port)]);
if let Some((user, password)) = proxy_login {
args.extend(["--upstream-user".into(), user]);
env.push(("WB_UPSTREAM_PASS".into(), password));
}
}
Ok(Some(UnitSpec {
name: format!("{CREATOR_PREFIX}{name}"),
program,
generation: format!("{args:?}{}", env[0].1),
args,
env,
cwd: None,
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn links_are_one_clean_line() {
assert_eq!(clean_link(" https://stream.wb.ru/room/abc \n").unwrap(), "https://stream.wb.ru/room/abc");
assert!(clean_link(" \n").is_err());
assert!(clean_link("a\u{7}b").is_err());
}
#[test]
fn files_are_only_plain_names_in_the_state_directory() {
let paths = Paths::new("state");
assert_eq!(state_file(&paths, "laptop", ".link").unwrap(), std::path::Path::new("state/whitelist-bypass/laptop.link"));
for bad in [r"C:\Windows\System32\x", "/etc/x", "../x", "..", "a/b", r"a\b", "CON", "nul", "COM1", ""] {
assert!(state_file(&paths, bad, ".link").is_err(), "{bad}");
}
}
}
+235 -13
View File
@@ -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
/// service's run directory (the release's own, the user's entries added) and the game
/// 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> {
let y = &cfg.zapret.discord_youtube;
let component = paths.bin().join("zapret");
@@ -84,15 +90,55 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
all.push_str(&user.ipset_all_extra);
write_atomic(&lists.join("ipset-all.txt"), all.as_bytes())?;
}
if !y.hostlist_rules.is_empty() {
tracing::warn!("zapret.zapret-discord-youtube.hostlistRules are not applied on Windows yet");
// The hostlist rules: their sites in their own lists, their profiles ahead of the preset's.
let read = |f: &str| std::fs::read_to_string(release.join(f)).unwrap_or_default();
let (general, google, ipset_all) = (read("list-general.txt"), read("list-google.txt"), read("ipset-all.txt"));
let release_lists = zapret::ReleaseLists { general: &general, google: &google, ipset_all: &ipset_all };
let rules = y.hostlist_rules.iter().map(|r| zapret::rule(r, &release_lists)).collect::<Result<Vec<_>, _>>().map_err(anyhow::Error::msg)?;
let mut rule_files = Vec::new();
for rule in &rules {
let (list, ipset) = zapret::rule_lists(rule);
for (file, entries) in [(list, &rule.domains), (ipset, &rule.ips)] {
if !entries.is_empty() {
write_atomic(&lists.join(&file), format!("{}\n", entries.join("\n")).as_bytes())?;
rule_files.push(file);
}
}
}
let bin_dir = component.join("bin");
let mut argv = zapret::expand(&args, &with_sep(&bin_dir), &with_sep(&lists), &with_sep(&component), y.game_filter);
let (bin_s, lists_s, root_s) = (with_sep(&bin_dir), with_sep(&lists), with_sep(&component));
let expand = |a: &[String]| zapret::expand(a, &bin_s, &lists_s, &root_s, y.game_filter);
let source = |name: &str| -> Result<Vec<String>, String> {
let file = zapret::find_preset(&bats, name)?;
let bat = std::fs::read(component.join(&file)).map_err(|e| format!("{file}: {e}"))?;
Ok(expand(&zapret::preset_args(&String::from_utf8_lossy(&bat))?))
};
let mut argv = zapret::with_rules(expand(&args), &rules, &lists_s, &source, &expand).map_err(anyhow::Error::msg)?;
if cfg.debug.log_level != ps_core::config::LogLevel::Warn {
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.
let generation = {
use sha2::{Digest, Sha256};
@@ -101,8 +147,9 @@ pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Re
h.update(a.as_bytes());
h.update(b"\n");
}
for f in ["list-general-user.txt", "list-exclude-user.txt", "ipset-exclude-user.txt", "ipset-all.txt"] {
h.update(std::fs::read(lists.join(f)).unwrap_or_default());
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) {
h.update(std::fs::read(lists.join(&f)).unwrap_or_default());
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
};
@@ -126,19 +173,43 @@ pub async fn enable_tcp_timestamps() -> Result<()> {
Ok(())
}
/// The unit for zapret2: winws2 with nfqws2-keenetic's strategies (ps_core::zapret2), its
/// lists in the service's `zapret2\\` directory, the learned one where winws2 can still write
/// once it runs at Low integrity.
/// The unit for zapret2: winws2 with nfqws2-keenetic's or z2k's strategies
/// (ps_core::zapret2), upstream's Lua layers from the zapret2-extras component when it is
/// 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> {
use ps_core::config::StrategySource;
use ps_core::zapret2;
let z = &cfg.zapret.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 source = zapret2::keenetic(&conf, &with_sep(&component.join("keenetic"))).map_err(anyhow::Error::msg)?;
let extras_dir = paths.bin().join("zapret2-extras");
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 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)]
low_integrity(&learned)?;
let user = state.join("zapret-hosts-user.txt");
@@ -150,23 +221,156 @@ pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<Uni
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 {
lua: with_sep(&component.join("lua")),
user: user.to_string_lossy().into_owned(),
exclude: exclude.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)?;
// 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 = {
use sha2::{Digest, Sha256};
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(b"\n");
}
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,
@@ -200,3 +404,21 @@ fn low_integrity(dir: &Path) -> Result<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn options_go_one_a_line_quoted_when_spaced() {
let argv: Vec<String> = ["--filter-tcp=443", "--wf-raw-part=inbound and tcp.Payload[0] == 0x16", r#"--x="a""#].map(String::from).into();
assert_eq!(options_file(&argv).unwrap(), "--filter-tcp=443\n\"--wf-raw-part=inbound and tcp.Payload[0] == 0x16\"\n\"--x=\\\"a\\\"\"\n");
assert!(options_file(&["--filter-tcp=443\n--lua-init=@x.lua".to_owned()]).is_err());
}
#[test]
fn cygwin_names_drives_and_separators() {
assert_eq!(cygwin(r"C:\ProgramData\ProxySuite\zapret2\learned"), "/cygdrive/c/ProgramData/ProxySuite/zapret2/learned");
assert_eq!(cygwin(r"\\?\D:\x"), "/cygdrive/d/x");
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 98 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 130 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 104 KiB

+6
View File
@@ -52,6 +52,12 @@
curl
git
python3Packages.pip
# The SSH tunnel's end-to-end test runs an sshd of its own.
openssh
# wireproxy-awg and whitelist-bypass, built from source (Go cross-compiles).
go
# The setup program (tools/installer.nsi).
nsis
];
buildInputs = guiLibs;
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs;
+57
View File
@@ -0,0 +1,57 @@
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.
### 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
- **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 (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.
- **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.
- **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.
- **Settings:** every option, as JSON, checked by the service before it is saved.
- **Components:** what is installed, at which version.
- **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy.
- **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.
Screenshots are in the README.
### 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`.
- 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.
- 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`.
- 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`).
- Uninstalling removes WinDivert's driver service and the AmneziaWG tunnels too, when they are the suite's.
- Built and published by Gitea Actions.
### Not yet
Tor's onion service, the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe.
### 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`.
+29
View File
@@ -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.
+76
View File
@@ -0,0 +1,76 @@
#!/usr/bin/env bash
# AmneziaWG as a system-wide VPN: amneziawg-windows's tunnel (amneziawg-go on Wintun, its
# firewall that blocks what leaves outside a full tunnel, its DNS and routes), built from its
# pinned commit as awg-tunnel.exe rather than its tunnel.dll: the same Run() a tunnel service
# makes, with a main that takes the config's path and the tunnel's name, and its log in a
# file beside the config (not its ring log). Wintun's signed driver DLL from wintun.net,
# pinned as amneziawg-windows's own build pins it.
#
# tools/build-amneziawg.sh OUT_DIR (needs git, go, curl, unzip)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
COMMIT=e90531d15802cb976773f3b63443bc281f738ca3
VERSION=0-unstable-2026-08-14+e90531d
WINTUN_URL=https://www.wintun.net/builds/wintun-0.14.1.zip
WINTUN_SHA256=07c256185d6ee3652e09fa55c0b673e2624b565e02c4b9091c79ca7d2f24ef51
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_commit https://github.com/amnezia-vpn/amneziawg-windows "$COMMIT" "$WORK/src"
cd "$WORK/src"
# Its exports (tunnel.dll's, through cgo) out; a main of ours in.
rm main.go
grep -q 'err = ringlogger.InitGlobalLogger("TUN")' service.go || { echo "service.go changed: no ring logger to replace"; exit 1; }
sed -i 's|err = ringlogger.InitGlobalLogger("TUN")|err = nil|' service.go
sed -i '/"github.com\/amnezia-vpn\/amneziawg-windows\/v3\/ringlogger"/d' service.go
cat > proxysuite_main.go <<'GO'
/* SPDX-License-Identifier: MIT
*
* Proxy Suite's AmneziaWG tunnel service: run by the Service Control Manager as
* `awg-tunnel <config path> <tunnel name>`, as amneziawg-windows's tunnel.dll is from its
* client's service. Its log goes to <config path>.log, written anew at each start.
*/
package main
import (
"fmt"
"log"
"os"
)
func main() {
if len(os.Args) != 3 {
fmt.Fprintln(os.Stderr, "usage: awg-tunnel <config> <tunnel name> (as a Windows service)")
os.Exit(2)
}
confPath, name := os.Args[1], os.Args[2]
if f, err := os.OpenFile(confPath+".log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o600); err == nil {
log.SetOutput(f)
}
text, err := os.ReadFile(confPath)
if err != nil {
log.Printf("reading %s: %v", confPath, err)
os.Exit(1)
}
if err := Run(string(text), name); err != nil {
log.Printf("the tunnel service: %v", err)
os.Exit(1)
}
}
GO
export GOTOOLCHAIN=local GOFLAGS=-mod=mod CGO_ENABLED=0 GOOS=windows GOARCH=amd64
go build -trimpath -ldflags "-s -w" -o "$WORK/awg-tunnel.exe" .
rm -rf "$OUT" && mkdir -p "$OUT"
cp "$WORK/awg-tunnel.exe" "$OUT/"
# Its license is the MIT text in its README.
sed -n '/^```text/,/^```/p' README.md | sed '1d;$d' >"$OUT/LICENSE"
grep -q 'Permission is hereby granted' "$OUT/LICENSE" || { echo "README.md: no license text"; exit 1; }
fetch_pinned "$WINTUN_URL" "$WINTUN_SHA256" "$WORK/wintun.zip"
unzip -q -o "$WORK/wintun.zip" -d "$WORK/wintun"
cp "$WORK/wintun/wintun/bin/amd64/wintun.dll" "$OUT/"
cp "$WORK/wintun/wintun/LICENSE.txt" "$OUT/wintun-LICENSE.txt"
echo "$VERSION" >"$OUT/.version"
echo "amneziawg $VERSION (windows) in $OUT"
+2 -1
View File
@@ -5,6 +5,7 @@
#
# tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
cd "$(dirname "$0")"
PY_VERSION=3.12.10
@@ -25,7 +26,7 @@ pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_am
mkdir -p "$OUT/python/Lib/site-packages"
for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done
git -c advice.detachedHead=false clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src"
clone_tag https://github.com/Flowseal/tg-ws-proxy "$TG_TAG" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; }
cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/"
+48
View File
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# whitelist-bypass's headless ends for Windows (creators and joiners: a tunnel through the media
# servers of video calls), built from upstream's tag as upstream's pkgs/whitelist-bypass.nix
# builds them: the call link, the local proxy's password and a joiner's SOCKS password read
# from the environment by default, never the command line (any local user reads that).
#
# tools/build-whitelist-bypass.sh OUT_DIR [GOOS] (needs git, go, sed; GOOS: windows)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows}
VERSION=0.4.4
COMMIT=7c19a7ec40900940fe0c43ea1db7768ee632393d
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_tag https://github.com/kulikov0/whitelist-bypass "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src"
# upstream's postPatch: flag.String("NAME", "", …) defaults to os.Getenv("VAR").
env_default() {
local file="headless/$1/main.go"
grep -q "flag.String(\"$2\", \"\"," "$file" || { echo "$file has no flag $2 to patch"; exit 1; }
sed -i "s|flag.String(\"$2\", \"\",|flag.String(\"$2\", os.Getenv(\"$3\"),|" "$file"
}
for p in vk telemost wbstream dion bitrix; do env_default "$p" upstream-pass WB_UPSTREAM_PASS; done
for p in bitrix dion dion-joiner wbstream wbstream-joiner; do env_default "$p" room WB_LINK; done
for p in telemost-joiner wbstream-joiner dion-joiner bitrix-joiner; do env_default "$p" socks-pass WB_SOCKS_PASS; done
env_default bitrix-joiner link WB_LINK
env_default telemost tm-link WB_LINK
env_default telemost-joiner tm-link WB_LINK
env_default vk vk-link WB_LINK
export GOTOOLCHAIN=local CGO_ENABLED=0 GOOS GOARCH=amd64
ext=
[ "$GOOS" = windows ] && ext=.exe
rm -rf "$OUT" && mkdir -p "$OUT"
# Upstream's names (build-headless.sh): headless-<platform>-creator and -joiner.
for p in vk telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-creator$ext" "./headless/$p"
done
for p in telemost wbstream dion bitrix; do
go build -trimpath -ldflags "-s -w" -o "$OUT/headless-$p-joiner$ext" "./headless/$p-joiner"
done
cp LICENSE "$OUT/"
echo "$VERSION" >"$OUT/.version"
echo "whitelist-bypass $VERSION ($GOOS) in $OUT"
+35
View File
@@ -0,0 +1,35 @@
#!/usr/bin/env bash
# wireproxy-awg: the AmneziaWG client as a SOCKS listener, behind AmneziaWG and WARP outbounds
# of the "userspace" kind; no driver, no interface. Built from upstream's tag as upstream's
# pkgs/wireproxy-awg.nix builds it: its patch, and its vendored amneziawg-go with the suite's.
# Modules are checked against the project's go.sum; the source by its commit.
#
# tools/build-wireproxy-awg.sh OUT_DIR [GOOS] (needs git, go, patch; GOOS: windows)
set -euo pipefail
. "$(dirname "$0")/lib.sh"
OUT=$(realpath -m "${1:?output directory}")
GOOS=${2:-windows}
cd "$(dirname "$0")"
VERSION=1.0.18
COMMIT=84f4795ea76f9c3168a61e478d0fe0e5c3238308
PATCHES=$(realpath ../../pkgs/patches)
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
clone_tag https://github.com/artem-russkikh/wireproxy-awg "v$VERSION" "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; }
cd "$WORK/src"
patch -s -p1 <"$PATCHES/wireproxy-awg-fwmark.patch"
# The Go of the shell, never one Go would fetch for itself.
export GOTOOLCHAIN=local GOFLAGS=-mod=mod
go mod vendor
chmod -R u+w vendor/github.com/amnezia-vpn/amneziawg-go/v3
patch -s -p1 -d vendor/github.com/amnezia-vpn/amneziawg-go/v3 <"$PATCHES/amneziawg-go-random-trailers-transport.patch"
rm -rf "$OUT" && mkdir -p "$OUT"
exe=wireproxy
[ "$GOOS" = windows ] && exe=wireproxy.exe
CGO_ENABLED=0 GOOS=$GOOS GOARCH=amd64 GOFLAGS=-mod=vendor go build -trimpath -ldflags "-s -w -X main.version=$VERSION" -o "$OUT/$exe" ./cmd/wireproxy
cp LICENSE "$OUT/"
echo "$VERSION" >"$OUT/.version"
echo "wireproxy-awg $VERSION ($GOOS) in $OUT"
Loaded 100 of 141 files, more files were not shown because too many files have changed in this diff. Show more