Author SHA1 Message Date
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
94 changed files with 28214 additions and 366 deletions

No files matched your search

+2 -1
View File
@@ -75,9 +75,10 @@ jobs:
working-directory: windows
run: nix develop --command rustup toolchain install
# The default members: everything the zip carries, not the app (GPUI) yet.
- 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
+7061 -39
View File
File diff suppressed because it is too large. Load diff
+10 -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.2.0-pre.1"
edition = "2024"
license = "MIT"
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
@@ -31,8 +33,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" }
+49 -10
View File
@@ -2,7 +2,8 @@
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.**
@@ -19,14 +20,22 @@ 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) |
| 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 |
| zapret | Flowseal's [zapret-discord-youtube](https://github.com/Flowseal/zapret-discord-youtube) release: `winws.exe` with any of its `general*.bat` presets, your lists, the game filter, and `hostlistRules` (a strategy of its own for a group of sites, copied from a preset or given) |
| zapret2 | `winws2.exe` from bol-van's [zapret-win-bundle](https://github.com/bol-van/zapret-win-bundle) with [nfqws2-keenetic](https://github.com/nfqws/nfqws2-keenetic)'s strategies and nfqws2's own learning of blocked sites |
| tg-ws-proxy | Flowseal's [tg-ws-proxy](https://github.com/Flowseal/tg-ws-proxy), the headless proxy, on a bundled Python |
| Tor | `tor`: the Tor Project's own Windows build (the Expert Bundle, signed, pinned), with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy |
| AmneziaWG | `amneziaWg` profiles as outbounds, from a `.conf`, an AmneziaVPN `vpn://` link or settings: `"userspace"` (wireproxy-awg, built from upstream's source, AmneziaWG's obfuscation kept, no driver) or `"singBox"` (plain WireGuard). WARP devices take either kind too |
| 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` |
| SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) |
| TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** |
| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy |
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 in this release, still to come: AmneziaWG as a system-wide VPN (its driver), Tor's onion service, whitelist-bypass,
the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended
detection and z2k strategies. Their options are accepted (they are upstream's), but the
service says, in its status and in the app, that it does not run them yet.
Needs 64-bit Windows 10 (1903 or later) or 11.
## What has been verified
@@ -39,18 +48,29 @@ backend, zapret2's extended detection and z2k strategies.
| 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 |
| 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`) |
| 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 app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; under Wine it starts and gets as far as drawing text |
**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.
service under the Service Control Manager, `install`/`uninstall`, the system PATH change, and
**the app drawing on Windows** (Wine's DirectWrite cannot match fonts, so no text is drawn
there), 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`.
`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).
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.
@@ -62,6 +82,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"
@@ -92,6 +116,7 @@ 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 +124,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`
@@ -126,6 +151,8 @@ and installing components. Secrets (links, passwords) are hidden from callers wi
- zapret2 learns with nfqws2's own detector, not upstream's extended one; z2k's strategies are
not there yet.
- 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,12 +167,24 @@ 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/
nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components
```
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), with the toolchain
in `rust-toolchain.toml`. Design notes: [`DESIGN.md`](DESIGN.md).
+27
View File
@@ -98,6 +98,33 @@
"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": []
}
}
}
+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
+321
View File
@@ -0,0 +1,321 @@
//! 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;
}
/// 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 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" } }));
}
}
+129
View File
@@ -0,0 +1,129 @@
//! 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(())
}
}
+1
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
+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}");
}
}
+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;
+148 -1
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, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -72,6 +72,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 +99,65 @@ 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", "the kill switch is not on Windows yet: nothing blocks traffic that bypasses the tunnel");
}
for (on, path, what) in [
(cfg.amnezia_wg.enable && cfg.amnezia_wg.profiles.values().any(|p| p.as_outbound.is_none()), "amneziaWg.profiles", "AmneziaWG as a system-wide VPN (its driver; as outbounds it is here)"),
(cfg.warp.enable && cfg.warp.as_amnezia_wg, "warp.asAmneziaWg", "WARP as an AmneziaWG profile"),
(cfg.tor.enable && cfg.tor.onion_service.enable, "tor.onionService.enable", "Tor's onion service (it serves the inbounds)"),
(cfg.whitelist_bypass.enable, "whitelistBypass.enable", "whitelist-bypass"),
(cfg.inbounds.enable, "inbounds.enable", "Serving inbounds"),
(cfg.proxy.auto_proxy.enable, "proxy.autoProxy.enable", "autoProxy"),
] {
if on {
v.warn(path, format!("{what} {IGNORED}"));
}
}
if cfg.proxy.enable && cfg.proxy.backend == Backend::Xray {
v.warn("proxy.backend", "the xray backend is not on Windows yet: the proxy does not start with it (sing-box or hybrid do)");
}
let z = &cfg.zapret;
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");
}
if z.enable && z.engine == ZapretEngine::Zapret2 {
if z.zapret2.strategy_source == StrategySource::Z2k && z.zapret2.profiles.is_none() {
v.warn("zapret.zapret2.strategySource", "z2k's strategies are not on Windows yet: zapret2 does not start with them (nfqws2-keenetic's, or your own profiles, do)");
}
if z.zapret2.auto_hostlist.extended_detection {
v.warn("zapret.zapret2.autoHostlist.extendedDetection", "the extended detection is not on Windows yet: nfqws2's own learning is used");
}
}
if z.enable && cfg.proxy.tun.enable {
v.warn("proxy.tun.enable", "TUN and zapret together: zapret's packets are not kept off the TUN on Windows yet; use one or the other");
}
}
fn proxy(cfg: &Config, v: &mut Issues) {
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() {
@@ -371,6 +436,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()
@@ -428,6 +510,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");
}
@@ -678,6 +774,57 @@ 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.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert("vpn".into(), Default::default());
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();
for want in ["killSwitch.enable", "amneziaWg.profiles", "proxy.tun.enable"] {
assert!(paths.iter().any(|p| p == want), "{want} not in {paths:?}");
}
}
#[test]
fn outbound_tags_are_unique_and_not_builtin() {
let mut cfg = Config::default();
+2
View File
@@ -4,12 +4,14 @@
//! 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 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;
@@ -538,7 +538,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 +554,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);
+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
+352 -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));
@@ -273,6 +528,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 +656,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());
}
+3 -2
View File
@@ -196,7 +196,7 @@ fn port_list(values: &[serde_json::Value]) -> String {
}
/// 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 +214,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;
}
+4 -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;
}
+1
View File
@@ -12,6 +12,7 @@ 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
+77 -237
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,6 +49,11 @@ enum Cmd {
#[command(subcommand)]
verb: Option<ZapretVerb>,
},
/// Telegram's WebSocket proxy (tg-ws-proxy).
Tg {
#[command(subcommand)]
verb: TgVerb,
},
/// The backend programs: what is installed, and installing them (administrator).
Components {
#[command(subcommand)]
@@ -54,11 +61,19 @@ enum Cmd {
},
}
#[derive(Subcommand)]
enum TgVerb {
/// Its tg:// links, to open in Telegram.
Link,
}
#[derive(Subcommand)]
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.
@@ -194,51 +209,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)
}
}
@@ -257,52 +250,6 @@ fn read_file_arg(file: &str) -> Result<Value> {
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
}
async fn status(ctl: &Ctl) -> Result<()> {
let s = ctl.call(Request::Status).await?;
if ctl.json {
@@ -365,64 +312,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 +379,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 +420,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 +486,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?;
@@ -679,27 +517,33 @@ 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");
}
ctl.edit(|c| {
c["zapret"]["zapret-discord-youtube"]["gameFilter"] = filter.clone().into();
Ok(())
})
.await?;
// 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(())
@@ -740,33 +584,29 @@ 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::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?;
+251
View File
@@ -187,3 +187,254 @@ 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 _sshd = Kill(Command::new(&sshd).args(["-D", "-e", "-f"]).arg(dir.join("sshd_config")).stderr(std::fs::File::create(dir.join("sshd.log")).unwrap()).spawn().unwrap());
let 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);
}
+23
View File
@@ -0,0 +1,23 @@
[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_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"] }
+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]);
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
}
}
+52
View File
@@ -0,0 +1,52 @@
//! 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
//! nothing of its own.
//!
//! 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 model;
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 model = cx.new(|cx| model::Model::new(bridge, cx));
shell::start(model, !args.hidden, cx);
});
}
+256
View File
@@ -0,0 +1,256 @@
//! 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;
use anyhow::{Result, bail};
use gpui_kit::*;
use ps_client::edits;
use ps_ipc::Request;
use serde_json::Value;
use crate::bridge::Bridge;
/// What a change came to.
pub enum Outcome {
Done(SharedString),
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,
_poll: Task<()>,
}
impl EventEmitter<Outcome> for Model {}
const POLL: Duration = Duration::from_secs(2);
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;
}
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,
_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
}
/// 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!("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!("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(if on { "The proxy is on" } else { "The proxy is off" }, job, cx);
}
}
+211
View File
@@ -0,0 +1,211 @@
//! 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 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>,
window: Option<WindowHandle<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>,
}
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 });
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.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 { "on" } else { "off" };
format!("Proxy Suite — proxy {}, DPI bypass {}, Telegram proxy {}", on(&s["proxy"]["on"]), on(&s["zapret"]["enabled"]), on(&s["tgWsProxy"]["enabled"]))
} else {
"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("Open Proxy Suite", OpenWindow),
MenuItem::separator(),
MenuItem::action("Local proxy", ToggleProxy).checked(s["proxy"]["on"] == true).disabled(!up),
MenuItem::action("DPI bypass", ToggleDpi).checked(s["zapret"]["enabled"] == true).disabled(!up),
MenuItem::action("Telegram proxy", ToggleTelegram).checked(s["tgWsProxy"]["enabled"] == true).disabled(!up),
MenuItem::separator(),
MenuItem::action("Quit", Quit),
]
}
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, _)) => cx.global_mut::<Shell>().window = window.downcast(),
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 { "The DPI bypass is on" } else { "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 { "The Telegram proxy is on" } else { "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();
}
+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>");
}
}
+111
View File
@@ -0,0 +1,111 @@
//! 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 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};
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() { "Components installed".to_owned() } else { format!("{} 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("Reload").on_click(cx.listener(|this, _, _, cx| this.load(cx))))
.child(
Button::new("comp-install")
.small()
.icon(IconName::Download)
.label(if self.installing { "Installing…" } else { "Fetch all again" })
.disabled(self.installing)
.on_click(cx.listener(|this, _, _, cx| this.install(Vec::new(), cx))),
);
let mut list = card("Programs", Some(actions.into_any_element()), cx).child(hint(
"Each is pinned by version and hash, and checked before it runs. Fetching them again needs an administrator: run the app as one, or proxy-ctl components install in an administrator's terminal.",
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("installed"),
Some(v) => Tag::warning().child(format!("{v} installed")),
None => Tag::danger().child("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("Components", cx).child(list)
}
}
+238
View File
@@ -0,0 +1,238 @@
//! The DPI bypass: zapret with Flowseal's presets, or zapret2 with its strategies; and the
//! sites it handles beside the lists it comes with.
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 serde_json::Value;
use super::widgets::{card, hint, page, state_tag};
use crate::model::Model;
const ENGINES: [(&str, &str); 2] = [("zapret-discord-youtube", "Flowseal's presets (zapret)"), ("zapret2", "zapret2")];
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),
_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("example.com — one per line"));
let exclude = cx.new(|cx| TextareaState::new(window, cx).rows(6).placeholder("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(
format!("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(), _subscriptions: subscriptions };
this.sync(window, cx);
this
}
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("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}: {}", 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("DPI bypass", cx);
if config.is_null() {
return body.child(hint("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(
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)| 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(format!("Engine: {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" {
"zapret2 (winws2) with nfqws2-keenetic's strategies; it learns which sites are blocked as it goes."
} else {
"Flowseal's zapret-discord-youtube: winws with one of its presets, for YouTube, Discord and the sites in its lists."
},
cx,
)),
);
if engine == "zapret2" {
body = body.child(
card("zapret2", None, cx)
.child(self.option_switch("autohostlist", "Learn which sites are blocked", &["zapret", "zapret2", "autoHostlist", "enable"], &config))
.child(self.option_switch("ipv6", "IPv6 too", &["zapret", "zapret2", "ipv6"], &config))
.child(self.option_switch("strategy-log", "Log the strategy each site gets", &["zapret", "zapret2", "strategyLog"], &config)),
);
} else {
let model = self.model.clone();
let filter = config["zapret"]["zapret-discord-youtube"]["gameFilter"].as_str().unwrap_or("null");
body = body
.child(
card("Preset", None, cx)
.child(hint("One of the release's strategies. If a site still does not open, try the next one.", cx))
.child(Select::new(&self.preset).placeholder("Choose a preset").menu_max_h(px(320.))),
)
.child(
card("Game traffic", None, cx).child(hint("Also handle game traffic, on ports above 1023.", cx)).child(
RadioGroup::horizontal("game-filter")
.children(GAME_FILTERS.map(|(_, label)| 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(format!("Game traffic: {label}"), move |c| edits::set_game_filter(c, value), cx));
}),
),
);
}
body.child(
card(
"Your sites",
Some(Button::new("save-sites").small().label("Save").on_click(cx.listener(|this, _, _, cx| this.save_sites(cx))).into_any_element()),
cx,
)
.child(hint("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("Also handle")).child(Textarea::new(&self.domains)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Leave alone")).child(Textarea::new(&self.exclude))),
),
)
.child(card("Windows", None, cx).child(self.option_switch("tcp-timestamps", "TCP timestamps (some strategies need them)", &["zapret", "tcpTimestamps"], &config)))
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Logs: every unit's, as they come, the last few thousand lines kept; one unit's on its own.
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!["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("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("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("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(format!("Not receiving logs: {why}"), cx));
}
page("Logs", cx).child(body.child(div().p_2().rounded_md().bg(cx.theme().muted).child(lines)))
}
}
+139
View File
@@ -0,0 +1,139 @@
//! The window: a sidebar of pages, the page shown, and what came of each change as a
//! notification.
mod components;
mod dpi;
mod logs;
mod outbounds;
mod overview;
mod settings;
mod telegram;
mod widgets;
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,
Outbounds,
Logs,
Settings,
Components,
}
impl Page {
const ALL: [Page; 7] = [Page::Overview, Page::Dpi, Page::Telegram, Page::Outbounds, 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::Outbounds => "Outbounds",
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::Outbounds => IconName::Globe,
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: 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()),
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);
}),
];
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, logs: None, settings: None, components: None, _subscriptions: subscriptions }
}
fn sidebar(&self, cx: &mut Context<Self>) -> impl IntoElement {
let items = Page::ALL.map(|page| {
SidebarMenuItem::new(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, "Applying…"),
Connection::Up => (cx.theme().success, "Connected to the service"),
Connection::Connecting => (cx.theme().muted_foreground, "Connecting…"),
Connection::Down(_) => (cx.theme().danger, "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));
Sidebar::new("pages").header(SidebarHeader::new().child(widgets::brand(cx))).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::Outbounds => self.outbounds.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))
}
}
+241
View File
@@ -0,0 +1,241 @@
//! 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};
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("vless://…, ss://…, trojan://…, hysteria2://… or JSON"));
let tag = cx.new(|cx| InputState::new(window, cx).placeholder("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(format!("Not an outbound: {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 = format!("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(format!("Subscription {tag} added; fetching it"), 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("failed").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(format!("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(format!("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("pinned"))).when(disabled, |d| d.child(Tag::secondary().child("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("Test its delay").on_click(cx.listener(move |this, _, _, cx| this.test(vec![t_test.clone()], cx))))
.child(Button::new(("pin", ix)).small().ghost().icon(if pinned { IconName::PinOff } else { IconName::Pin }).tooltip(if pinned { "Back to automatic selection" } else { "Always use this one" }).on_click(move |_, _, cx| {
let req = Request::Pin { tag: if pinned { None } else { Some(t_pin.clone()) }, group: None };
let what = if pinned { "Back to automatic selection".to_owned() } else { format!("Pinned to {t_pin}") };
model_pin.update(cx, |m, cx| m.request(what, req, cx));
}))
.child(Button::new(("disable", ix)).small().ghost().icon(IconName::Power).tooltip(if disabled { "Use it again" } else { "Leave it out" }).on_click(move |_, _, cx| {
let what = format!("{t_dis} {}", if disabled { "is back" } else { "is left out" });
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("Remove it").on_click(move |_, _, cx| {
let tag = t_rm.clone();
model_rm.update(cx, |m, cx| m.edit(format!("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("Add an outbound", Some(Button::new("add").small().primary().icon(IconName::Plus).label("Add").on_click(cx.listener(|this, _, window, cx| this.add(window, cx))).into_any_element()), cx)
.child(hint("A share link from your provider, or a sing-box or XRay outbound as JSON. Links stay on this computer, in the service's configuration.", cx))
.child(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(
format!("Outbounds ({})", tags.len()),
Some(Button::new("test-all").small().icon(IconName::Gauge).label(if self.testing { "Testing…" } else { "Test all" }).disabled(self.testing || tags.is_empty()).on_click(cx.listener(|this, _, _, cx| this.test(Vec::new(), cx))).into_any_element()),
cx,
);
if let Some(Err(e)) = self.delays.get("") {
list = list.child(div().text_sm().text_color(cx.theme().danger).child(format!("Testing failed: {e}")));
}
if tags.is_empty() {
list = list.child(hint("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("Routing mode", None, cx).child(hint("Overrides the routing rules until changed back; “As configured” follows them.", cx)).child(
RadioGroup::vertical("mode").children(MODES.map(|(_, label)| label)).selected_index(MODES.iter().position(|(v, _)| *v == mode)).on_change(move |ix, _, cx| {
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(format!("Mode: {label}"), req, cx));
}),
);
let model = self.model.clone();
let mut subscriptions = card(
"Subscriptions",
Some(
Button::new("subs-update")
.small()
.icon(IconName::RefreshCw)
.label("Update all")
.disabled(subs.is_empty())
.on_click(move |_, _, cx| model.update(cx, |m, cx| m.request("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("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("Remove it").on_click(move |_, _, cx| {
let tag = t.clone();
model.update(cx, |m, cx| m.edit(format!("Removed subscription {tag}"), move |c| edits::remove_subscription(c, &tag), cx));
})),
);
}
page("Outbounds", cx).child(add).child(list).child(modes).child(subscriptions)
}
}
+142
View File
@@ -0,0 +1,142 @@
//! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state
//! and a switch; what the service warns of.
use gpui_kit::component::alert::Alert;
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};
use crate::model::{Connection, Model};
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("Overview", cx);
match &connection {
Connection::Down(why) => {
body = body.child(Alert::error("service-down", why.clone()).title("Not connected")).child(hint(
"The service runs everything; this app only controls it. Install it with install.cmd from the release, or start it as an administrator: sc start ProxySuite.",
cx,
));
}
Connection::Connecting => body = body.child(Alert::info("connecting", "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("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(
"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("global TUN"))))
.child(fact("Listening on", text(&p["listener"]), cx))
.child(fact("Backend", text(&p["backend"]), cx))
.child(fact("Mode", p["mode"].as_str().unwrap_or("default").to_owned(), cx))
.child(fact("Outbound", p["pinned"].as_str().map(|t| format!("{t} (pinned)")).unwrap_or_else(|| format!("{} selection", p["selection"].as_str().unwrap_or("?"))), cx))
.child({
let model = model.clone();
let on = m.config()["proxy"]["systemProxy"]["enable"] == true;
Switch::new("system-proxy").label("Use it as the system proxy (browsers and most programs follow it)").checked(on).on_change(move |on, _, cx| {
let on = *on;
model.update(cx, |m, cx| {
m.edit(
if on { "The system proxy follows the local proxy" } else { "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(
"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 { "The DPI bypass is on" } else { "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("Engine", text(&z["engine"]), cx))
.when(z["engine"] == "zapret-discord-youtube", |d| d.child(fact("Preset", text(&z["preset"]), cx)));
let t = &s["tgWsProxy"];
let model_t = model.clone();
let telegram = card(
"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 { "The Telegram proxy is on" } else { "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("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()))
}
+190
View File
@@ -0,0 +1,190 @@
//! Settings: 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::*;
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};
use crate::model::Model;
/// 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("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| format!("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("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("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("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
}
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("Reload").on_click(cx.listener(|this, _, window, cx| this.reload(window, cx))))
.child(Button::new("cfg-validate").small().label("Check").on_click(cx.listener(|this, _, _, cx| this.validate(cx))))
.child(Button::new("cfg-save").small().primary().icon(IconName::Save).label("Save").disabled(!changed).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("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(format!("Saved as revision {revision}.")))
.when_some(apply_error.clone(), |d, e| d.child(div().text_sm().text_color(cx.theme().danger).child(format!("Saved, but not applied: {e}"))))
.child(issue_list(issues, cx)),
};
page("Settings", cx).child(
card("Configuration", Some(actions.into_any_element()), cx)
.child(hint("Upstream's options (services.proxy-suite…) as JSON, as proxy-ctl config get prints them. The service checks them before taking them; options that run programs or read files need an administrator.", cx))
.when(redacted, |d| d.child(hint("Values shown as •••redacted••• are secrets you may not read here; left as they are, they keep their values.", cx)))
.child(div().h(px(480.)).border_1().border_color(cx.theme().border).rounded_md().child(Editor::new(&self.editor).h_full()))
.child(verdict),
)
}
}
+161
View File
@@ -0,0 +1,161 @@
//! The Telegram proxy (Flowseal's tg-ws-proxy): on or off, the links to open in Telegram, and
//! where it listens.
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("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(format!("“{port_text}” is not a port (1–65535)")), 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(
"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("Telegram proxy", cx);
if t.is_null() {
return body.child(hint("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 { "The Telegram proxy is on" } else { "The Telegram proxy is off" },
move |c| {
edits::set_tg_ws_proxy_enabled(c, on);
Ok(())
},
cx,
)
})
});
let mut link_card = card("Links", None, cx).child(hint("Open one in Telegram, or copy it to a phone: Telegram then connects through this proxy.", cx));
if links.is_empty() {
link_card = link_card.child(hint("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("Copy").on_click(move |_, window, cx| {
cx.write_to_clipboard(ClipboardItem::new_string(copy.to_string()));
window.push_notification(Notification::success("Copied"), cx);
}))
.child(Button::new(("open-link", i)).small().primary().icon(IconName::Send).label("Open in Telegram").on_click(move |_, _, cx| cx.open_url(&open))),
);
}
let shared = t["listener"]["address"] == "0.0.0.0";
let model = self.model.clone();
let lan = Switch::new("tg-lan").label("Let other devices on this network connect (phones, other computers)").checked(shared).on_change(move |on, _, cx| {
let 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" { "Other devices may connect" } else { "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("Telegram over WebSocket to its own servers, for networks that block its usual connections.", cx)),
)
.child(link_card)
.child(
card(
"Listening",
Some(Button::new("tg-save").small().label("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("Port")).child(Input::new(&self.port)))
.child(div().v_flex().gap_1().flex_1().child(div().text_sm().child("Fake-TLS domain (ee links)")).child(Input::new(&self.fake_tls))),
),
)
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Pieces the pages share: the page frame, cards, a unit's state as a tag.
use gpui_kit::component::tag::Tag;
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.
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.to_owned())
}
/// 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())
}
+4
View File
@@ -59,6 +59,10 @@ 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> },
}
+8
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,8 @@ windows-sys = { workspace = true, features = [
"Win32_System_Registry",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Threading",
"Win32_Networking_WinInet",
] }
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
+30 -8
View File
@@ -133,7 +133,7 @@ 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::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
_ => None,
}
@@ -237,13 +237,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 +281,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),
@@ -454,6 +455,27 @@ 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::ComponentsInstall { names } => {
// Programs the service runs as SYSTEM: an administrator's call, whatever the scopes.
if !peer.admin {
+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()))
}
+1
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()
+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> {
+17
View File
@@ -69,6 +69,23 @@ pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
Ok(body)
}
/// `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() {
+32 -13
View File
@@ -20,10 +20,10 @@ 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 {
@@ -44,19 +44,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 +66,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();
+5
View File
@@ -4,6 +4,7 @@
//! it); `--console` runs it in the foreground, which is also how it runs off Windows.
mod api;
mod awg;
mod clash;
mod components;
mod fetch;
@@ -12,9 +13,12 @@ mod install;
mod job;
mod paths;
mod service;
mod ssh;
mod store;
mod tg;
mod tor;
mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod zapret;
@@ -110,6 +114,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;
});
}
+2 -2
View File
@@ -174,14 +174,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.
+156 -14
View File
@@ -6,7 +6,7 @@ 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};
@@ -82,15 +82,29 @@ 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 {
if let Ok(p) = self.comps.program("tg-ws-proxy", "python/python") {
direct.push(p.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());
}
// 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());
}
let (zd, zi) = crate::zapret::direct_sync(cfg, &paths.bin());
Env {
@@ -103,8 +117,11 @@ 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()
}
}
@@ -133,8 +150,75 @@ 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:#}"));
}
let proxy = self.apply_proxy().await;
zapret.and(tg).and(proxy)
zapret.and(tg).and(ssh).and(tor).and(awg).and(proxy)
}
/// 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<()> {
@@ -296,6 +380,10 @@ 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);
json!({
@@ -322,7 +410,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 +544,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 +608,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) => {
+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}");
}
}
+139 -1
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,6 +97,7 @@ pub fn install() -> Result<()> {
wait_stopped(&existing)?;
}
if from != to {
desktop::close();
copy_release(&from, &to)?;
}
existing.change_config(&info)?;
@@ -104,6 +105,7 @@ pub fn install() -> Result<()> {
}
Err(_) => {
if from != to {
desktop::close();
copy_release(&from, &to)?;
}
manager.create_service(&info, access).context("creating the service")?
@@ -134,6 +136,14 @@ 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:#}"),
}
println!("Open a new terminal and try: proxy-ctl status");
Ok(())
}
@@ -154,6 +164,7 @@ pub fn uninstall() -> Result<()> {
println!("{DISPLAY} was not installed.");
}
let dir = install_dir();
desktop::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 +185,133 @@ pub fn uninstall() -> Result<()> {
Ok(())
}
/// 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.
pub fn start(dir: &Path) {
let _ = Command::new("explorer.exe").arg(dir.join("proxy-suite.exe")).spawn();
}
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;
+25 -5
View File
@@ -84,12 +84,32 @@ 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());
}
@@ -101,8 +121,8 @@ 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());
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()
};
+4
View File
@@ -52,6 +52,10 @@
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
];
buildInputs = guiLibs;
LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs;
+35
View File
@@ -0,0 +1,35 @@
The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`.
**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.
### 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 (learning, IPv6); 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.
- **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions.
- **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.
`install.cmd` puts it in the Start Menu and starts it at every sign-in, in the tray.
### 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).
- Tor (`tor`): the Tor Project's own Windows build, with bridges (obfs4, webtunnel, snowflake, meek, conjure) and, with `asOutbound`, an outbound of the proxy.
- AmneziaWG as outbounds (`amneziaWg`): profiles from a `.conf`, an AmneziaVPN `vpn://` link or settings; `"userspace"` runs wireproxy-awg (AmneziaWG's obfuscation kept, no driver), `"singBox"` plain WireGuard. WARP devices can be either.
- WARP (`warp`, as a sing-box outbound): devices registered with Cloudflare as wgcf registers them (through the local proxy first, where its API is blocked), or profiles given; several grouped as `warp`.
- What is not on Windows yet (the kill switch, AmneziaWG, WARP, Tor, the SSH tunnel, …) is no longer accepted silently: the service warns while it is configured, and the app shows it.
- The service names zapret's presets and gives tg-ws-proxy's links (`proxy-ctl zapret presets`, `proxy-ctl tg link`).
- Built and published by Gitea Actions.
### Install
Download `ProxySuite-0.2.0-pre.1-windows-x64.zip`; its SHA-256 is in the `.sha256` file next to it. Unzip, run `install.cmd` as administrator, then open **Proxy Suite** from the Start Menu. Needs 64-bit Windows 10 (1903 or later) or 11.
### Not yet
AmneziaWG as a system-wide VPN, Tor's onion service, whitelist-bypass, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies.
### 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`.
+34
View File
@@ -0,0 +1,34 @@
#!/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
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
git -c advice.detachedHead=false clone -q --depth 1 --branch "v$VERSION" https://github.com/artem-russkikh/wireproxy-awg "$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"
+53
View File
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# The service on Linux, for working on the app: console mode with its own state directory and
# socket, a local sing-box Shadowsocks server as a demo outbound, and the zapret presets of a
# built release (tools/package.sh) when there is one. In the dev shell:
#
# tools/dev-service.sh [STATE_DIR] (Ctrl-C stops it all)
# cargo run -p ps-gui -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock"
#
# The socket is not in STATE_DIR: a Unix socket's path is limited to about 100 bytes.
set -euo pipefail
cd "$(dirname "$0")/.."
STATE=$(realpath -m "${1:-${TMPDIR:-/tmp}/proxy-suite-dev}")
mkdir -p "$STATE"
SOCK=${SOCK:-${XDG_RUNTIME_DIR:-/tmp}/proxy-suite-dev.sock}
free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1])'; }
# Chosen once and kept, as the configuration that names them is.
if [ ! -f "$STATE/ports" ]; then
echo "SS=$(free_port) PROXY=$(free_port) CLASH=$(free_port) TEST=$(free_port)" >"$STATE/ports"
fi
. "$STATE/ports"
KEY=a2tra2tra2tra2tra2traw==
cat >"$STATE/server.json" <<EOF
{ "log": { "level": "warn" },
"inbounds": [{ "type": "shadowsocks", "listen": "127.0.0.1", "listen_port": $SS,
"method": "2022-blake3-aes-128-gcm", "password": "$KEY" }],
"dns": { "servers": [{ "type": "https", "tag": "local", "server": "1.1.1.1" }] },
"outbounds": [{ "type": "direct" }],
"route": { "default_domain_resolver": "local" } }
EOF
sing-box run -c "$STATE/server.json" &
SERVER=$!
trap 'kill $SERVER ${SERVICE:-} 2>/dev/null || true' EXIT
# A configuration on the first run; after that, whatever the app made of it.
if [ ! -f "$STATE/config.json" ]; then
cat >"$STATE/config.json" <<EOF
{ "proxy": { "enable": true, "listener": { "port": $PROXY },
"singBox": { "clashApiPort": $CLASH, "testPort": $TEST },
"routing": { "directRu": false },
"outbounds": [{ "tag": "demo", "url": "ss://2022-blake3-aes-128-gcm:${KEY//=/%3D}@127.0.0.1:$SS#Demo" }] } }
EOF
fi
release=$(ls -d dist/ProxySuite-*-windows-x64/components/zapret 2>/dev/null | tail -1 || true)
if [ -n "$release" ] && [ ! -e "$STATE/bin/zapret" ]; then
mkdir -p "$STATE/bin" && cp -r "$release" "$STATE/bin/zapret"
fi
cargo build -q -p ps-service
target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" &
SERVICE=$!
echo "the service: $SOCK (state in $STATE)"
wait $SERVICE
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# fxc.exe, Microsoft's HLSL compiler, under Wine: GPUI's shaders, when the app is cross-compiled
# for Windows (GPUI_FXC_PATH names this; see tools/vendor-gpui-windows.py). The compiler comes
# from the Windows SDK 10.0.26100 that Visual Studio's installer offers, pinned by hash, and
# stays on this machine: only the shaders it compiles go into the app.
#
# GPUI_FXC_PATH=$PWD/tools/fxc-wine.sh cargo xwin build --release -p ps-gui --target x86_64-pc-windows-msvc
set -euo pipefail
CACHE=${XDG_CACHE_HOME:-$HOME/.cache}/proxy-suite-windows/fxc-10.0.26100
CAB_URL=https://download.visualstudio.microsoft.com/download/pr/6452c1f1-dc1e-413c-8b19-991b61870a8b/944d105a33e16da614cbf2a17da22954/69661e20556b3ca9456b946c2c881ddd.cab
CAB_SHA256=bef5b038fce288fa1db234bd61c3e450abecc02f5a386248625073a83010f61e
FXC_SHA256=31fa10504b1551337de4d06ec2194143885a76a8b5a81177999e2faa34729183
DLL_SHA256=2b23efdc8b45adc4b79c1c0b940a906336628cd35ed80defd489d70d22ff6d74
# Their names in the cab: the File table of "Windows SDK for Windows Store Apps Tools", bin/10.0.26100.0/x64.
FXC_IN_CAB=fil6dfaf6bbf56939fbab75b569ffa0fd41
DLL_IN_CAB=fil0d3f984977487cd87127d614f654195b
here=$(dirname "$(realpath "$0")")
pkg() { nix build --no-link --print-out-paths --inputs-from "$here/.." "nixpkgs#$1" | head -1; }
verified() {
[ -f "$CACHE/fxc.exe" ] && [ -f "$CACHE/d3dcompiler_47.dll" ] &&
echo "$FXC_SHA256 $CACHE/fxc.exe" | sha256sum -c --quiet 2>/dev/null &&
echo "$DLL_SHA256 $CACHE/d3dcompiler_47.dll" | sha256sum -c --quiet 2>/dev/null
}
if ! verified; then
mkdir -p "$CACHE"
tmp=$(mktemp -d)
curl -sSfL -o "$tmp/tools.cab" "$CAB_URL"
echo "$CAB_SHA256 $tmp/tools.cab" | sha256sum -c --quiet
(cd "$tmp" && "$(pkg gcab.bin)/bin/gcab" -x tools.cab "$FXC_IN_CAB" "$DLL_IN_CAB")
mv "$tmp/$FXC_IN_CAB" "$CACHE/fxc.exe"
mv "$tmp/$DLL_IN_CAB" "$CACHE/d3dcompiler_47.dll"
rm -rf "$tmp"
verified || { echo "fxc-wine.sh: the extracted compiler does not match its hashes" >&2; exit 1; }
fi
WINE=$(pkg wineWow64Packages.stable)/bin
export WINEPREFIX=$CACHE/wine WINEDEBUG=-all WINEDLLOVERRIDES="mscoree,mshtml="
[ -d "$WINEPREFIX" ] || "$WINE/wineboot" -i >/dev/null 2>&1 || true
# Unix paths (the shader sources, the headers it writes) as Wine's Z: paths; a lone /X is a switch.
args=()
for a in "$@"; do
if [[ $a == /*/* ]]; then args+=("$("$WINE/winepath" -w "$a")"); else args+=("$a"); fi
done
exec "$WINE/wine" "$CACHE/fxc.exe" "${args[@]}"
+47
View File
@@ -0,0 +1,47 @@
#!/usr/bin/env bash
# The app without a display: run on Xvfb with Mesa's software Vulkan (lavapipe), and a
# screenshot of it once it has drawn. For checking the GUI on Linux, in the dev shell.
#
# tools/gui-shot.sh OUT.png [SECONDS] [-- APP ARGS...] (APP=target/debug/proxy-suite)
#
# Before the shot, SHOT_STEPS does what it lists, in order, each followed by a moment for the
# app to answer: "click:X,Y" (screen points), "type:TEXT" (no spaces), "key:NAME" (xdotool's
# names, e.g. ctrl+a), "wait:SECONDS".
set -euo pipefail
OUT=$(realpath -m "${1:?the screenshot, a .png}"); shift
WAIT=6
if [ $# -gt 0 ] && [ "$1" != "--" ]; then WAIT=$1; shift; fi
[ "${1:-}" = "--" ] && shift
cd "$(dirname "$0")/.."
APP=$(realpath "${APP:-target/debug/proxy-suite}")
GEOMETRY=${GEOMETRY:-1280x820}
path() { nix build --no-link --print-out-paths --inputs-from . "nixpkgs#$1.out" | head -1; }
XVFB=$(path xvfb) MESA=$(path mesa) MAGICK=$(path imagemagick) XDOTOOL=$(path xdotool)
n=90
while [ -e "/tmp/.X11-unix/X$n" ] || [ -e "/tmp/.X$n-lock" ]; do n=$((n + 1)); done
"$XVFB/bin/Xvfb" ":$n" -screen 0 "${GEOMETRY}x24" -nolisten tcp >/dev/null 2>&1 &
XPID=$!
trap 'kill "${APID:-}" "$XPID" 2>/dev/null || true' EXIT
for _ in $(seq 50); do [ -e "/tmp/.X11-unix/X$n" ] && break; sleep 0.1; done
# Not the desktop's session bus: the app's tray icon would appear on the real desktop.
env -u WAYLAND_DISPLAY -u DBUS_SESSION_BUS_ADDRESS DISPLAY=":$n" VK_ICD_FILENAMES="$MESA/share/vulkan/icd.d/lvp_icd.x86_64.json" \
"$APP" "$@" >"${OUT%.png}.log" 2>&1 &
APID=$!
sleep "$WAIT"
kill -0 "$APID" 2>/dev/null || { echo "the app exited:"; tail -20 "${OUT%.png}.log"; exit 1; }
x() { DISPLAY=":$n" "$XDOTOOL/bin/xdotool" "$@"; }
for step in ${SHOT_STEPS:-}; do
case $step in
click:*) p=${step#click:}; x mousemove "${p%,*}" "${p#*,}" click 1 ;;
type:*) x type --delay 40 "${step#type:}" ;;
key:*) x key "${step#key:}" ;;
wait:*) sleep "${step#wait:}" ;;
*) echo "unknown step: $step"; exit 1 ;;
esac
sleep 1.2
done
DISPLAY=":$n" "$MAGICK/bin/magick" import -window root "$OUT"
echo "$OUT"
+20 -4
View File
@@ -1,8 +1,10 @@
#!/usr/bin/env bash
# The release: ProxySuite-<version>-windows-x64.zip in dist/, with the programs, every
# component (fetched and verified), the install scripts, the README and the licenses.
# The release: ProxySuite-<version>-windows-x64.zip in dist/, with the programs (the service,
# proxy-ctl, the app), every component (fetched and verified), the install scripts, the README
# and the licenses.
#
# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip)
# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go; nix
# for the app's shader compiler, tools/fxc-wine.sh)
set -euo pipefail
cd "$(dirname "$0")/.."
VERSION=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
@@ -14,13 +16,19 @@ mkdir -p "$DIST/components"
echo "== components"
tools/build-tg-ws-proxy.sh "$DIST/components/tg-ws-proxy"
tools/build-wireproxy-awg.sh "$DIST/components/wireproxy-awg" windows
cargo build -q --release -p ps-service
target/release/proxy-suite-service stage-components --to "$DIST/components" --cache "$CACHE"
rm -rf "$DIST"/components/*.old "$DIST"/components/*.staging
echo "== programs"
cargo xwin build -q --release -p ps-service -p ps-ctl --target x86_64-pc-windows-msvc
cp target/x86_64-pc-windows-msvc/release/proxy-suite-service.exe target/x86_64-pc-windows-msvc/release/proxy-ctl.exe "$DIST/"
# The app on its own, so its crates' features do not change the service's (Cargo unifies them
# within one build). Its shaders are compiled by Microsoft's fxc.exe under Wine.
GPUI_FXC_PATH="$PWD/tools/fxc-wine.sh" cargo xwin build -q --release -p ps-gui --target x86_64-pc-windows-msvc
for exe in proxy-suite-service proxy-ctl proxy-suite; do
cp "target/x86_64-pc-windows-msvc/release/$exe.exe" "$DIST/"
done
cp ../LICENSE README.md "$DIST/"
cp tools/install.cmd tools/uninstall.cmd "$DIST/"
@@ -43,7 +51,15 @@ echo "== THIRD-PARTY.md"
echo "- **cygwin1.dll** (zapret, zapret2): LGPL-3.0, https://cygwin.com"
echo "- **zapret2** (winws2.exe, its Lua) and **nfqws2-keenetic** (its strategies, lists, blobs): MIT, https://github.com/bol-van/zapret2, https://github.com/nfqws/nfqws2-keenetic"
echo "- **wintun** (inside sing-box): WireGuard's prebuilt-binary license, https://www.wintun.net"
echo "- **amneziawg-go** (inside wireproxy-awg, with the suite's patch): MIT, https://github.com/amnezia-vpn/amneziawg-go"
echo "- **lyrebird** and **conjure** (Tor's pluggable transports, in the Expert Bundle): their licenses are in components/tor/docs"
echo "- **CPython $( sed 's/.*+py//' "$DIST/components/tg-ws-proxy/.version" )** (tg-ws-proxy): PSF License, https://www.python.org"
echo "- **The programs themselves** (proxy-suite-service, proxy-ctl, proxy-suite) are built from"
echo " this repository and the Rust crates in its Cargo.lock, under their licenses (MIT and/or"
echo " Apache-2.0 for nearly all). The app is built on GPUI (Apache-2.0,"
echo " https://github.com/zed-industries/zed; its Windows backend patched as"
echo " vendor/gpui-pre-windows/PATCHED.md says) and GPUI Kit (Apache-2.0,"
echo " https://github.com/longbridge/gpui-kit), with Lucide's icons (ISC, https://lucide.dev)."
echo "- **Python packages** (tg-ws-proxy):"
sed -n 's/^\([A-Za-z0-9_.-]*\)==\([^ ]*\) .*/ - \1 \2, https:\/\/pypi.org\/project\/\1\/\2\//p' tools/tg-ws-proxy-requirements.txt
echo
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env python3
"""GPUI's Windows backend, vendored with its build script patched, into vendor/gpui-pre-windows.
Upstream compiles the HLSL shaders (with fxc.exe) only when the machine building is Windows:
its build script asks `cfg!(target_os = "windows")`, which in a build script is the host.
Cross-compiled from Linux, the release library then fails for want of the compiled shaders.
The patch asks the target instead (CARGO_CFG_TARGET_OS, CARGO_CFG_DEBUG_ASSERTIONS) and lets
GPUI_FXC_PATH name any program that acts as fxc.exe (tools/fxc-wine.sh runs it under Wine).
Nothing else changes.
python3 -I tools/vendor-gpui-windows.py ~/.cargo/registry/src/*/gpui-pre-windows-0.3.10
"""
import shutil
import sys
from pathlib import Path
src = Path(sys.argv[1])
dst = Path(__file__).resolve().parent.parent / "vendor" / "gpui-pre-windows"
shutil.rmtree(dst, ignore_errors=True)
shutil.copytree(src, dst, ignore=shutil.ignore_patterns(".cargo-ok", ".cargo_vcs_info.json", "Cargo.toml.orig", "Cargo.lock"))
build = (dst / "build.rs").read_text()
def replace(old: str, new: str) -> None:
global build
if build.count(old) != 1:
sys.exit(f"build.rs has changed upstream; update the patch: {old[:60]!r}")
build = build.replace(old, new)
main_start = build.index("fn main() {")
main_end = build.index("\n}\n", main_start) + 3
build = (
build[:main_start]
+ '''// Patched for Proxy Suite (tools/vendor-gpui-windows.py): the shaders are compiled when the
// target is Windows in a release build, whatever machine builds it.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GPUI_FXC_PATH");
let windows = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
let release = std::env::var_os("CARGO_CFG_DEBUG_ASSERTIONS").is_none();
if windows && release {
shader_compilation::compile_shaders();
}
}
'''
+ build[main_end:]
)
replace('#[cfg(all(target_os = "windows", not(debug_assertions)))]\nmod shader_compilation {', "mod shader_compilation {")
replace(" pub fn find_latest_windows_sdk_binary(", " #[cfg(windows)]\n pub fn find_latest_windows_sdk_binary(")
replace(
""" // Try to find in PATH
// NOTE: This has to be `where.exe` on Windows, not `where`, it must be ended with `.exe`
if let Ok(output)""",
""" // Try to find in PATH
// NOTE: This has to be `where.exe` on Windows, not `where`, it must be ended with `.exe`
#[cfg(windows)]
if let Ok(output)""",
)
replace(
""" if let Ok(Some(path)) = find_latest_windows_sdk_binary("fxc.exe") {""",
""" #[cfg(windows)]
if let Ok(Some(path)) = find_latest_windows_sdk_binary("fxc.exe") {""",
)
replace(' panic!("Failed to find fxc.exe");', ' panic!("Failed to find fxc.exe (cross-compiling, set GPUI_FXC_PATH: tools/fxc-wine.sh)");')
replace('#[cfg(all(target_os = "windows", not(debug_assertions)))]\nuse shader_compilation::compile_shaders;\n', "")
(dst / "build.rs").write_text(build)
(dst / "PATCHED.md").write_text(
f"""# gpui-pre-windows, patched
`{src.name}` from crates.io (Apache-2.0, LICENSE-APACHE), unchanged except `build.rs`: the HLSL
shaders are compiled when the target (not the building machine) is Windows in a release build,
and GPUI_FXC_PATH may name any program acting as fxc.exe. Made by
`tools/vendor-gpui-windows.py`; the workspace uses it through `[patch.crates-io]`.
"""
)
print(f"vendored {src.name} into {dst}")
+18
View File
@@ -32,6 +32,24 @@ while IFS= read -r preset; do
done < <(ls "$REL"/*.bat | xargs -n1 -d '\n' basename | grep -vi '^service' | sed 's/\.bat$//')
echo "$((n - fail))/$n preset runs verified by winws.exe"
# The same presets with hostlistRules (tools/zapret-rules-sample.json): their profiles ahead.
r=0 na=0
while IFS= read -r preset; do
built=$(target/debug/examples/zapret_args "$REL" "$(win "$REL")" "$(win "$WORK/lists")" "$preset" null tools/zapret-rules-sample.json "$WORK/lists" 2>&1) || {
# A preset without a profile a rule's family needs: refused, as upstream refuses it.
if grep -q "the preset has no .* profile to copy" <<<"$built"; then na=$((na + 1)); echo " $preset: $built"; continue; fi
fail=$((fail + 1)); echo "FAIL: $preset with rules: $built"; continue
}
mapfile -t args <<<"$built"
r=$((r + 1))
if out=$(cd "$REL/bin" && wine ./winws.exe --dry-run "${args[@]}" 2>&1) && grep -q "parameters verified" <<<"$out"; then
:
else
fail=$((fail + 1)); echo "FAIL: $preset with rules"; grep -v Cygwin <<<"$out" | tail -4
fi
done < <(ls "$REL"/*.bat | xargs -n1 -d '\n' basename | grep -vi '^service' | sed 's/\.bat$//')
echo "$r presets with hostlist rules verified by winws.exe; $na refused, lacking a profile a rule copies"
# zapret2: nfqws2-keenetic's strategies as the service renders them, its lists in place.
Z2="$STAGE/zapret2"
mkdir -p "$WORK/z2/learned" && : > "$WORK/z2/zapret-hosts-user.txt" && : > "$WORK/z2/zapret-hosts-user-exclude.txt" && : > "$WORK/z2/learned/zapret-hosts-auto.txt"
+6
View File
@@ -0,0 +1,6 @@
[
{ "name": "mine", "domains": ["example.com"], "preset": "general" },
{ "name": "yt", "defaultDomains": ["youtube"], "domains": ["extra.example"] },
{ "name": "voice", "defaultDomains": ["discord"], "configName": "general (ALT9)" },
{ "name": "own", "domains": ["own.example"], "ips": ["198.51.100.0/24"], "nfqwsArgs": ["--filter-tcp=8443 --dpi-desync=fake --dpi-desync-repeats=6"] }
]
+227
View File
@@ -0,0 +1,227 @@
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
#
# When uploading crates to the registry Cargo will automatically
# "normalize" Cargo.toml files for maximal compatibility
# with all versions of Cargo and also rewrite `path` dependencies
# to registry (e.g., crates.io) dependencies.
#
# If you are reading this file be aware that the original Cargo.toml
# will likely look very different (and much more reasonable).
# See Cargo.toml.orig for the original contents.
[package]
edition = "2024"
name = "gpui-pre-windows"
version = "0.3.10"
build = "build.rs"
publish = true
autolib = false
autobins = false
autoexamples = false
autotests = false
autobenches = false
description = "Zed's `gpui_windows` crate (gpui-pre snapshot of zed@08cbb88)"
readme = false
license = "Apache-2.0"
repository = "https://github.com/zed-industries/zed"
resolver = "2"
[package.metadata.cargo-shear]
ignored = ["scap"]
[package.metadata.gpui-pre]
zed-crate = "gpui_windows"
zed-version = "0.1.0"
zed-rev = "08cbb88a152c3751a43e853425a70e9f631a5918"
[features]
default = ["gpui/default"]
screen-capture = [
"gpui/screen-capture",
"scap",
]
test-support = ["gpui/test-support"]
[lib]
name = "gpui_windows"
path = "src/gpui_windows.rs"
doctest = false
[dependencies.gpui]
version = "=0.3.10"
default-features = false
package = "gpui-pre"
[target.'cfg(target_os = "windows")'.dependencies.accesskit]
version = "0.24.0"
features = ["enumn"]
[target.'cfg(target_os = "windows")'.dependencies.accesskit_windows]
version = "0.34"
[target.'cfg(target_os = "windows")'.dependencies.anyhow]
version = "1.0.86"
[target.'cfg(target_os = "windows")'.dependencies.collections]
version = "=0.3.10"
package = "gpui-pre-collections"
[target.'cfg(target_os = "windows")'.dependencies.dunce]
version = "1.0"
[target.'cfg(target_os = "windows")'.dependencies.etagere]
version = "0.2"
[target.'cfg(target_os = "windows")'.dependencies.futures]
version = "0.3.34"
[target.'cfg(target_os = "windows")'.dependencies.gpui_util]
version = "=0.3.10"
package = "gpui-pre-util"
[target.'cfg(target_os = "windows")'.dependencies.image]
version = "0.25.1"
features = [
"bmp",
"dds",
"exr",
"ff",
"gif",
"hdr",
"ico",
"jpeg",
"png",
"pnm",
"qoi",
"rayon",
"tga",
"tiff",
"webp",
]
default-features = false
[target.'cfg(target_os = "windows")'.dependencies.itertools]
version = "0.14.0"
[target.'cfg(target_os = "windows")'.dependencies.log]
version = "0.4"
features = ["std"]
default-features = false
[target.'cfg(target_os = "windows")'.dependencies.parking_lot]
version = "0.12.1"
[target.'cfg(target_os = "windows")'.dependencies.rand]
version = "0.9"
features = [
"std",
"std_rng",
"os_rng",
]
default-features = false
[target.'cfg(target_os = "windows")'.dependencies.raw-window-handle]
version = "0.6"
[target.'cfg(target_os = "windows")'.dependencies.scap]
version = "0.0.8-zed"
optional = true
default-features = false
package = "zed-scap"
[target.'cfg(target_os = "windows")'.dependencies.scheduler]
version = "=0.3.10"
package = "gpui-pre-scheduler"
[target.'cfg(target_os = "windows")'.dependencies.smallvec]
version = "1.6"
features = [
"union",
"const_new",
]
[target.'cfg(target_os = "windows")'.dependencies.uuid]
version = "1.1"
features = [
"serde",
"v5",
]
[target.'cfg(target_os = "windows")'.dependencies.windows]
version = "0.62"
features = [
"Win32_Foundation",
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_Storage_FileSystem",
"Win32_System_Com",
"Win32_System_Com_StructuredStorage",
"Win32_System_IO",
"Win32_System_LibraryLoader",
"Win32_System_Ole",
"Win32_System_Threading",
"Win32_System_Variant",
"Win32_UI_Shell",
"Win32_UI_Shell_Common",
"Win32_UI_Shell_PropertiesSystem",
"Win32_UI_WindowsAndMessaging",
"Data_Xml_Dom",
"UI_Notifications",
"UI_ViewManagement",
"Wdk_System_SystemServices",
"Win32_Graphics_Direct3D11",
"Win32_Graphics_Direct3D_Fxc",
"Win32_Graphics_DirectComposition",
"Win32_Graphics_DirectManipulation",
"Win32_Graphics_DirectWrite",
"Win32_Graphics_Dwm",
"Win32_Graphics_Dxgi_Common",
"Win32_Graphics_Hlsl",
"Win32_Media",
"Win32_Security_Credentials",
"Win32_Storage_Packaging_Appx",
"Win32_System_DataExchange",
"Win32_System_Diagnostics_Debug",
"Win32_System_Memory",
"Win32_System_Performance",
"Win32_System_StationsAndDesktops",
"Win32_System_SystemInformation",
"Win32_System_SystemServices",
"Win32_UI_Controls",
"Win32_UI_HiDpi",
"Win32_UI_Input_Ime",
"Win32_UI_Input_Pointer",
]
[target.'cfg(target_os = "windows")'.dependencies.windows-core]
version = "0.62"
[target.'cfg(target_os = "windows")'.dependencies.windows-numerics]
version = "0.3"
[target.'cfg(target_os = "windows")'.dependencies.windows-registry]
version = "0.6.0"
[target.'cfg(target_os = "windows")'.build-dependencies.windows-registry]
version = "0.6.0"
[lints.clippy]
dbg_macro = "deny"
declare_interior_mutable_const = "deny"
disallowed_methods = "deny"
large_enum_variant = "allow"
let_underscore_future = "allow"
nonminimal_bool = "allow"
redundant_clone = "deny"
single_range_in_vec_init = "allow"
todo = "deny"
too_many_arguments = "allow"
type_complexity = "allow"
[lints.clippy.style]
level = "allow"
priority = -1
[lints.rust.unexpected_cfgs]
level = "allow"
priority = 0
+222
View File
@@ -0,0 +1,222 @@
Copyright 2022 - 2025 Zed Industries, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+6
View File
@@ -0,0 +1,6 @@
# gpui-pre-windows, patched
`gpui-pre-windows-0.3.10` from crates.io (Apache-2.0, LICENSE-APACHE), unchanged except `build.rs`: the HLSL
shaders are compiled when the target (not the building machine) is Windows in a release build,
and GPUI_FXC_PATH may name any program acting as fxc.exe. Made by
`tools/vendor-gpui-windows.py`; the workspace uses it through `[patch.crates-io]`.
+245
View File
@@ -0,0 +1,245 @@
#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]
// Patched for Proxy Suite (tools/vendor-gpui-windows.py): the shaders are compiled when the
// target is Windows in a release build, whatever machine builds it.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=GPUI_FXC_PATH");
let windows = std::env::var("CARGO_CFG_TARGET_OS").is_ok_and(|os| os == "windows");
let release = std::env::var_os("CARGO_CFG_DEBUG_ASSERTIONS").is_none();
if windows && release {
shader_compilation::compile_shaders();
}
}
mod shader_compilation {
use std::{
fs,
io::Write,
path::{Path, PathBuf},
process::{self, Command},
};
pub fn compile_shaders() {
let shader_path =
PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/shaders.hlsl");
let out_dir = std::env::var("OUT_DIR").unwrap();
println!("cargo:rerun-if-changed={}", shader_path.display());
// Check if fxc.exe is available
let fxc_path = find_fxc_compiler();
// Define all modules
let modules = [
"quad",
"shadow",
"path_rasterization",
"path_sprite",
"underline",
"monochrome_sprite",
"subpixel_sprite",
"polychrome_sprite",
];
let rust_binding_path = format!("{}/shaders_bytes.rs", out_dir);
if Path::new(&rust_binding_path).exists() {
fs::remove_file(&rust_binding_path)
.expect("Failed to remove existing Rust binding file");
}
for module in modules {
compile_shader_for_module(
module,
&out_dir,
&fxc_path,
shader_path.to_str().unwrap(),
&rust_binding_path,
);
}
{
let shader_path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())
.join("src/color_text_raster.hlsl");
compile_shader_for_module(
"emoji_rasterization",
&out_dir,
&fxc_path,
shader_path.to_str().unwrap(),
&rust_binding_path,
);
}
}
/// Locate `binary` in the newest installed Windows SDK.
#[cfg(windows)]
pub fn find_latest_windows_sdk_binary(
binary: &str,
) -> Result<Option<PathBuf>, Box<dyn std::error::Error>> {
let key = windows_registry::LOCAL_MACHINE
.open("SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0")?;
let install_folder: String = key.get_string("InstallationFolder")?; // "C:\Program Files (x86)\Windows Kits\10\"
let install_folder_bin = Path::new(&install_folder).join("bin");
let mut versions: Vec<_> = std::fs::read_dir(&install_folder_bin)?
.flatten()
.filter(|entry| entry.path().is_dir())
.filter_map(|entry| entry.file_name().into_string().ok())
.collect();
versions.sort_by_key(|s| {
s.split('.')
.filter_map(|p| p.parse().ok())
.collect::<Vec<u32>>()
});
let arch = match std::env::consts::ARCH {
"x86_64" => "x64",
"aarch64" => "arm64",
_ => Err(format!(
"Unsupported architecture: {}",
std::env::consts::ARCH
))?,
};
if let Some(highest_version) = versions.last() {
return Ok(Some(
install_folder_bin
.join(highest_version)
.join(arch)
.join(binary),
));
}
Ok(None)
}
/// You can set the `GPUI_FXC_PATH` environment variable to specify the path to the fxc.exe compiler.
fn find_fxc_compiler() -> String {
// Check environment variable
if let Ok(path) = std::env::var("GPUI_FXC_PATH")
&& Path::new(&path).exists()
{
return path;
}
// Try to find in PATH
// NOTE: This has to be `where.exe` on Windows, not `where`, it must be ended with `.exe`
#[cfg(windows)]
if let Ok(output) = std::process::Command::new("where.exe")
.arg("fxc.exe")
.output()
&& output.status.success()
{
let path = String::from_utf8_lossy(&output.stdout);
return path.trim().to_string();
}
#[cfg(windows)]
if let Ok(Some(path)) = find_latest_windows_sdk_binary("fxc.exe") {
return path.to_string_lossy().into_owned();
}
panic!("Failed to find fxc.exe (cross-compiling, set GPUI_FXC_PATH: tools/fxc-wine.sh)");
}
fn compile_shader_for_module(
module: &str,
out_dir: &str,
fxc_path: &str,
shader_path: &str,
rust_binding_path: &str,
) {
// Compile vertex shader
let output_file = format!("{}/{}_vs.h", out_dir, module);
let const_name = format!("{}_VERTEX_BYTES", module.to_uppercase());
compile_shader_impl(
fxc_path,
&format!("{module}_vertex"),
&output_file,
&const_name,
shader_path,
"vs_4_1",
);
generate_rust_binding(&const_name, &output_file, rust_binding_path);
// Compile fragment shader
let output_file = format!("{}/{}_ps.h", out_dir, module);
let const_name = format!("{}_FRAGMENT_BYTES", module.to_uppercase());
compile_shader_impl(
fxc_path,
&format!("{module}_fragment"),
&output_file,
&const_name,
shader_path,
"ps_4_1",
);
generate_rust_binding(&const_name, &output_file, rust_binding_path);
}
fn compile_shader_impl(
fxc_path: &str,
entry_point: &str,
output_path: &str,
var_name: &str,
shader_path: &str,
target: &str,
) {
let output = Command::new(fxc_path)
.args([
"/T",
target,
"/E",
entry_point,
"/Fh",
output_path,
"/Vn",
var_name,
"/O3",
shader_path,
])
.output();
match output {
Ok(result) => {
if result.status.success() {
return;
}
println!(
"cargo::error=Shader compilation failed for {}:\n{}",
entry_point,
String::from_utf8_lossy(&result.stderr)
);
process::exit(1);
}
Err(e) => {
println!("cargo::error=Failed to run fxc for {}: {}", entry_point, e);
process::exit(1);
}
}
}
fn generate_rust_binding(const_name: &str, head_file: &str, output_path: &str) {
let header_content = fs::read_to_string(head_file).expect("Failed to read header file");
let const_definition = {
let global_var_start = header_content.find("const BYTE").unwrap();
let global_var = &header_content[global_var_start..];
let equal = global_var.find('=').unwrap();
global_var[equal + 1..].trim()
};
let rust_binding = format!(
"const {}: &[u8] = &{}\n",
const_name,
const_definition.replace('{', "[").replace('}', "]")
);
let mut options = fs::OpenOptions::new()
.create(true)
.append(true)
.open(output_path)
.expect("Failed to open Rust binding file");
options
.write_all(rust_binding.as_bytes())
.expect("Failed to write Rust binding file");
}
}
@@ -0,0 +1,49 @@
// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
float color_brightness(float3 color) {
// REC. 601 luminance coefficients for perceived brightness
return dot(color, float3(0.30f, 0.59f, 0.11f));
}
float light_on_dark_contrast(float enhancedContrast, float3 color) {
float brightness = color_brightness(color);
float multiplier = saturate(4.0f * (0.75f - brightness));
return enhancedContrast * multiplier;
}
float enhance_contrast(float alpha, float k) {
return alpha * (k + 1.0f) / (alpha * k + 1.0f);
}
float3 enhance_contrast3(float3 alpha, float k) {
return alpha * (k + 1.0f) / (alpha * k + 1.0f);
}
float apply_alpha_correction(float a, float b, float4 g) {
float brightness_adjustment = g.x * b + g.y;
float correction = brightness_adjustment * a + (g.z * b + g.w);
return a + a * (1.0f - a) * correction;
}
float3 apply_alpha_correction3(float3 a, float3 b, float4 g) {
float3 brightness_adjustment = g.x * b + g.y;
float3 correction = brightness_adjustment * a + (g.z * b + g.w);
return a + a * (1.0f - a) * correction;
}
float apply_contrast_and_gamma_correction(float sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {
float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
float brightness = color_brightness(color);
float contrasted = enhance_contrast(sample, enhanced_contrast);
return apply_alpha_correction(contrasted, brightness, gamma_ratios);
}
float3 apply_contrast_and_gamma_correction3(float3 sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {
float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);
float3 contrasted = enhance_contrast3(sample, enhanced_contrast);
return apply_alpha_correction3(contrasted, color, gamma_ratios);
}
+394
View File
@@ -0,0 +1,394 @@
use std::{borrow::Cow, sync::LazyLock};
use anyhow::Result;
use collections::FxHashMap;
use itertools::Itertools;
use windows::Win32::{
Foundation::{HANDLE, HGLOBAL},
System::{
DataExchange::{
CloseClipboard, CountClipboardFormats, EmptyClipboard, EnumClipboardFormats,
GetClipboardData, GetClipboardFormatNameW, OpenClipboard, RegisterClipboardFormatW,
SetClipboardData,
},
Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock},
Ole::{CF_DIB, CF_HDROP, CF_UNICODETEXT},
},
UI::Shell::{DragQueryFileW, HDROP},
};
use windows::core::{Owned, PCWSTR};
use gpui::{
ClipboardEntry, ClipboardItem, ClipboardString, ExternalPaths, Image, ImageFormat, hash,
};
const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;
static CLIPBOARD_HASH_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal text hash")));
static CLIPBOARD_METADATA_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal metadata")));
static CLIPBOARD_SVG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("image/svg+xml")));
static CLIPBOARD_GIF_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("GIF")));
static CLIPBOARD_PNG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("PNG")));
static CLIPBOARD_JPG_FORMAT: LazyLock<u32> =
LazyLock::new(|| register_clipboard_format(windows::core::w!("JFIF")));
static IMAGE_FORMATS_MAP: LazyLock<FxHashMap<u32, ImageFormat>> = LazyLock::new(|| {
let mut map = FxHashMap::default();
map.insert(*CLIPBOARD_PNG_FORMAT, ImageFormat::Png);
map.insert(*CLIPBOARD_GIF_FORMAT, ImageFormat::Gif);
map.insert(*CLIPBOARD_JPG_FORMAT, ImageFormat::Jpeg);
map.insert(*CLIPBOARD_SVG_FORMAT, ImageFormat::Svg);
map
});
fn register_clipboard_format(format: PCWSTR) -> u32 {
let ret = unsafe { RegisterClipboardFormatW(format) };
if ret == 0 {
panic!(
"Error when registering clipboard format: {}",
std::io::Error::last_os_error()
);
}
log::debug!(
"Registered clipboard format {} as {}",
unsafe { format.display() },
ret
);
ret
}
fn get_clipboard_data(format: u32) -> Option<LockedGlobal> {
let global = HGLOBAL(unsafe { GetClipboardData(format).ok() }?.0);
LockedGlobal::lock(global)
}
pub(crate) fn write_to_clipboard(item: ClipboardItem) {
let Some(_clip) = ClipboardGuard::open() else {
return;
};
let result: Result<()> = (|| {
unsafe { EmptyClipboard()? };
for entry in item.entries() {
match entry {
ClipboardEntry::String(string) => write_string(string)?,
ClipboardEntry::Image(image) => write_image(image)?,
ClipboardEntry::ExternalPaths(_) => {}
}
}
Ok(())
})();
if let Err(e) = result {
log::error!("Failed to write to clipboard: {e}");
}
}
pub(crate) fn read_from_clipboard() -> Option<ClipboardItem> {
let _clip = ClipboardGuard::open()?;
let mut entries = Vec::new();
let mut have_text = false;
let mut have_image = false;
let mut have_files = false;
let count = unsafe { CountClipboardFormats() };
let mut format = 0;
for _ in 0..count {
format = unsafe { EnumClipboardFormats(format) };
if !have_text && format == CF_UNICODETEXT.0 as u32 {
if let Some(entry) = read_string() {
entries.push(entry);
have_text = true;
}
} else if !have_image && is_image_format(format) {
if let Some(entry) = read_image(format) {
entries.push(entry);
have_image = true;
}
} else if !have_files && format == CF_HDROP.0 as u32 {
if let Some(entry) = read_files() {
entries.push(entry);
have_files = true;
}
}
}
if entries.is_empty() {
log_unsupported_clipboard_formats();
return None;
}
Some(ClipboardItem { entries })
}
pub(crate) fn with_file_names<F>(hdrop: HDROP, mut f: F)
where
F: FnMut(String),
{
let file_count = unsafe { DragQueryFileW(hdrop, DRAGDROP_GET_FILES_COUNT, None) };
for file_index in 0..file_count {
let filename_length = unsafe { DragQueryFileW(hdrop, file_index, None) } as usize;
let mut buffer = vec![0u16; filename_length + 1];
let ret = unsafe { DragQueryFileW(hdrop, file_index, Some(buffer.as_mut_slice())) };
if ret == 0 {
log::error!("unable to read file name of dragged file");
continue;
}
match String::from_utf16(&buffer[0..filename_length]) {
Ok(file_name) => f(file_name),
Err(e) => log::error!("dragged file name is not UTF-16: {}", e),
}
}
}
fn set_clipboard_bytes<T>(data: &[T], format: u32) -> Result<()> {
unsafe {
let global = Owned::new(GlobalAlloc(GMEM_MOVEABLE, std::mem::size_of_val(data))?);
let ptr = GlobalLock(*global);
anyhow::ensure!(!ptr.is_null(), "GlobalLock returned null");
std::ptr::copy_nonoverlapping(data.as_ptr(), ptr as _, data.len());
GlobalUnlock(*global).ok();
SetClipboardData(format, Some(HANDLE(global.0)))?;
// SetClipboardData succeeded — the system now owns the memory.
std::mem::forget(global);
}
Ok(())
}
fn get_clipboard_string(format: u32) -> Option<String> {
let locked = get_clipboard_data(format)?;
let bytes = locked.as_bytes();
let words_len = bytes.len() / std::mem::size_of::<u16>();
if words_len == 0 {
return Some(String::new());
}
let slice = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, words_len) };
let actual_len = slice.iter().position(|&c| c == 0).unwrap_or(words_len);
Some(String::from_utf16_lossy(&slice[..actual_len]))
}
fn is_image_format(format: u32) -> bool {
IMAGE_FORMATS_MAP.contains_key(&format) || format == CF_DIB.0 as u32
}
fn write_string(item: &ClipboardString) -> Result<()> {
// CF_UNICODETEXT is null-terminated, so replace embedded NUL characters with spaces.
let text = if item.text.contains('\0') {
Cow::Owned(item.text.replace('\0', " "))
} else {
Cow::Borrowed(item.text.as_str())
};
let wide: Vec<u16> = text.encode_utf16().chain(Some(0)).collect_vec();
set_clipboard_bytes(&wide, CF_UNICODETEXT.0 as u32)?;
if let Some(metadata) = item.metadata.as_ref() {
let hash_bytes = ClipboardString::text_hash(&text).to_ne_bytes();
set_clipboard_bytes(&hash_bytes, *CLIPBOARD_HASH_FORMAT)?;
let wide: Vec<u16> = metadata.encode_utf16().chain(Some(0)).collect_vec();
set_clipboard_bytes(&wide, *CLIPBOARD_METADATA_FORMAT)?;
}
Ok(())
}
fn write_image(item: &Image) -> Result<()> {
let native_format = match item.format {
ImageFormat::Svg => Some(*CLIPBOARD_SVG_FORMAT),
ImageFormat::Gif => Some(*CLIPBOARD_GIF_FORMAT),
ImageFormat::Png => Some(*CLIPBOARD_PNG_FORMAT),
ImageFormat::Jpeg => Some(*CLIPBOARD_JPG_FORMAT),
_ => None,
};
if let Some(format) = native_format {
set_clipboard_bytes(item.bytes(), format)?;
}
// Also provide a PNG copy for broad compatibility.
// SVG can't be rasterized by the image crate, so skip it.
if item.format != ImageFormat::Svg && native_format != Some(*CLIPBOARD_PNG_FORMAT) {
if let Some(png_bytes) = convert_to_png(item.bytes(), item.format) {
set_clipboard_bytes(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;
}
}
Ok(())
}
fn convert_to_png(bytes: &[u8], format: ImageFormat) -> Option<Vec<u8>> {
let img_format = gpui_to_image_format(format)?;
let image = image::load_from_memory_with_format(bytes, img_format)
.map_err(|e| log::warn!("Failed to decode image for PNG conversion: {e}"))
.ok()?;
let mut buf = Vec::new();
image
.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
.map_err(|e| log::warn!("Failed to encode PNG: {e}"))
.ok()?;
Some(buf)
}
fn read_string() -> Option<ClipboardEntry> {
let text = get_clipboard_string(CF_UNICODETEXT.0 as u32)?;
let metadata = read_clipboard_metadata(&text);
Some(ClipboardEntry::String(ClipboardString { text, metadata }))
}
fn read_clipboard_metadata(text: &str) -> Option<String> {
let locked = get_clipboard_data(*CLIPBOARD_HASH_FORMAT)?;
let hash_bytes: [u8; 8] = locked.as_bytes().get(..8)?.try_into().ok()?;
let hash = u64::from_ne_bytes(hash_bytes);
if hash != ClipboardString::text_hash(text) {
return None;
}
get_clipboard_string(*CLIPBOARD_METADATA_FORMAT)
}
fn read_image(format: u32) -> Option<ClipboardEntry> {
let locked = get_clipboard_data(format)?;
let (bytes, image_format) = if format == CF_DIB.0 as u32 {
(convert_dib_to_bmp(locked.as_bytes())?, ImageFormat::Bmp)
} else {
let image_format = *IMAGE_FORMATS_MAP.get(&format)?;
(locked.as_bytes().to_vec(), image_format)
};
let id = hash(&bytes);
Some(ClipboardEntry::Image(Image {
format: image_format,
bytes,
id,
}))
}
fn read_files() -> Option<ClipboardEntry> {
let locked = get_clipboard_data(CF_HDROP.0 as u32)?;
let hdrop = HDROP(locked.ptr as *mut _);
let mut filenames = Vec::new();
with_file_names(hdrop, |name| filenames.push(std::path::PathBuf::from(name)));
Some(ClipboardEntry::ExternalPaths(ExternalPaths(
filenames.into(),
)))
}
/// DIB is BMP without the 14-byte BITMAPFILEHEADER. Prepend one.
fn convert_dib_to_bmp(dib: &[u8]) -> Option<Vec<u8>> {
if dib.len() < 40 {
return None;
}
let header_size = u32::from_le_bytes(dib[0..4].try_into().ok()?);
let bit_count = u16::from_le_bytes(dib[14..16].try_into().ok()?);
let compression = u32::from_le_bytes(dib[16..20].try_into().ok()?);
let color_table_size = if bit_count <= 8 {
let colors_used = u32::from_le_bytes(dib[32..36].try_into().ok()?);
(if colors_used == 0 {
1u32 << bit_count
} else {
colors_used
}) * 4
} else if compression == 3 {
12 // BI_BITFIELDS
} else {
0
};
let pixel_offset = 14 + header_size + color_table_size;
let file_size = 14 + dib.len() as u32;
let mut bmp = Vec::with_capacity(file_size as usize);
bmp.extend_from_slice(b"BM");
bmp.extend_from_slice(&file_size.to_le_bytes());
bmp.extend_from_slice(&[0u8; 4]); // reserved
bmp.extend_from_slice(&pixel_offset.to_le_bytes());
bmp.extend_from_slice(dib);
Some(bmp)
}
fn log_unsupported_clipboard_formats() {
let count = unsafe { CountClipboardFormats() };
let mut format = 0;
for _ in 0..count {
format = unsafe { EnumClipboardFormats(format) };
let mut buffer = [0u16; 64];
unsafe { GetClipboardFormatNameW(format, &mut buffer) };
let format_name = String::from_utf16_lossy(&buffer);
log::warn!(
"Try to paste with unsupported clipboard format: {}, {}.",
format,
format_name
);
}
}
fn gpui_to_image_format(value: ImageFormat) -> Option<image::ImageFormat> {
match value {
ImageFormat::Png => Some(image::ImageFormat::Png),
ImageFormat::Jpeg => Some(image::ImageFormat::Jpeg),
ImageFormat::Webp => Some(image::ImageFormat::WebP),
ImageFormat::Gif => Some(image::ImageFormat::Gif),
ImageFormat::Bmp => Some(image::ImageFormat::Bmp),
ImageFormat::Tiff => Some(image::ImageFormat::Tiff),
other => {
log::warn!("No image crate equivalent for format: {other:?}");
None
}
}
}
struct ClipboardGuard;
impl ClipboardGuard {
fn open() -> Option<Self> {
match unsafe { OpenClipboard(None) } {
Ok(()) => Some(Self),
Err(e) => {
log::error!("Failed to open clipboard: {e}");
None
}
}
}
}
impl Drop for ClipboardGuard {
fn drop(&mut self) {
if let Err(e) = unsafe { CloseClipboard() } {
log::error!("Failed to close clipboard: {e}");
}
}
}
struct LockedGlobal {
global: HGLOBAL,
ptr: *const u8,
size: usize,
}
impl LockedGlobal {
fn lock(global: HGLOBAL) -> Option<Self> {
let size = unsafe { GlobalSize(global) };
let ptr = unsafe { GlobalLock(global) };
if ptr.is_null() {
return None;
}
Some(Self {
global,
ptr: ptr as *const u8,
size,
})
}
fn as_bytes(&self) -> &[u8] {
unsafe { std::slice::from_raw_parts(self.ptr, self.size) }
}
}
impl Drop for LockedGlobal {
fn drop(&mut self) {
unsafe { GlobalUnlock(self.global).ok() };
}
}
@@ -0,0 +1,44 @@
#include "alpha_correction.hlsl"
struct RasterVertexOutput {
float4 position : SV_Position;
float2 texcoord : TEXCOORD0;
};
RasterVertexOutput emoji_rasterization_vertex(uint vertexID : SV_VERTEXID)
{
RasterVertexOutput output;
output.texcoord = float2((vertexID << 1) & 2, vertexID & 2);
output.position = float4(output.texcoord * 2.0f - 1.0f, 0.0f, 1.0f);
output.position.y = -output.position.y;
return output;
}
struct PixelInput {
float4 position: SV_Position;
float2 texcoord : TEXCOORD0;
};
struct Bounds {
int2 origin;
int2 size;
};
Texture2D<float> t_layer : register(t0);
SamplerState s_layer : register(s0);
cbuffer GlyphLayerTextureParams : register(b0) {
Bounds bounds;
float4 run_color;
float4 gamma_ratios;
float grayscale_enhanced_contrast;
float3 _pad;
};
float4 emoji_rasterization_fragment(PixelInput input): SV_Target {
float sample = t_layer.Sample(s_layer, input.texcoord.xy).r;
float alpha_corrected = apply_contrast_and_gamma_correction(sample, run_color.rgb, grayscale_enhanced_contrast, gamma_ratios);
float alpha = alpha_corrected * run_color.a;
return float4(run_color.rgb * alpha, alpha);
}
+207
View File
@@ -0,0 +1,207 @@
use std::{path::PathBuf, sync::Arc};
use itertools::Itertools;
use smallvec::SmallVec;
use windows::{
Win32::{
Foundation::PROPERTYKEY,
Globalization::u_strlen,
System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, StructuredStorage::PROPVARIANT},
UI::{
Controls::INFOTIPSIZE,
Shell::{
Common::{IObjectArray, IObjectCollection},
DestinationList, EnumerableObjectCollection, ICustomDestinationList, IShellLinkW,
PropertiesSystem::IPropertyStore,
ShellLink,
},
},
},
core::{GUID, HSTRING, Interface},
};
use gpui::{Action, MenuItem, SharedString};
pub(crate) struct JumpList {
pub(crate) dock_menus: Vec<DockMenuItem>,
pub(crate) recent_workspaces: Arc<[SmallVec<[PathBuf; 2]>]>,
}
impl JumpList {
pub(crate) fn new() -> Self {
Self {
dock_menus: Vec::default(),
recent_workspaces: Arc::default(),
}
}
}
pub(crate) struct DockMenuItem {
pub(crate) name: SharedString,
pub(crate) description: SharedString,
pub(crate) action: Box<dyn Action>,
}
impl DockMenuItem {
pub(crate) fn new(item: MenuItem) -> anyhow::Result<Self> {
match item {
MenuItem::Action { name, action, .. } => Ok(Self {
name: name.clone(),
description: if name == "New Window" {
"Opens a new window".into()
} else {
name
},
action,
}),
_ => anyhow::bail!("Only `MenuItem::Action` is supported for dock menu on Windows."),
}
}
}
// This code is based on the example from Microsoft:
// https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/Win7Samples/winui/shell/appshellintegration/RecipePropertyHandler/RecipePropertyHandler.cpp
pub(crate) fn update_jump_list(
recent_workspaces: &[SmallVec<[PathBuf; 2]>],
dock_menus: &[(SharedString, SharedString)],
) -> anyhow::Result<Vec<SmallVec<[PathBuf; 2]>>> {
let (list, removed) = create_destination_list()?;
add_recent_folders(&list, recent_workspaces, removed.as_ref())?;
add_dock_menu(&list, dock_menus)?;
unsafe { list.CommitList() }?;
Ok(removed)
}
// Copied from:
// https://github.com/microsoft/windows-rs/blob/0fc3c2e5a13d4316d242bdeb0a52af611eba8bd4/crates/libs/windows/src/Windows/Win32/Storage/EnhancedStorage/mod.rs#L1881
const PKEY_TITLE: PROPERTYKEY = PROPERTYKEY {
fmtid: GUID::from_u128(0xf29f85e0_4ff9_1068_ab91_08002b27b3d9),
pid: 2,
};
fn create_destination_list() -> anyhow::Result<(ICustomDestinationList, Vec<SmallVec<[PathBuf; 2]>>)>
{
let list: ICustomDestinationList =
unsafe { CoCreateInstance(&DestinationList, None, CLSCTX_INPROC_SERVER) }?;
let mut slots = 0;
let user_removed: IObjectArray = unsafe { list.BeginList(&mut slots) }?;
let count = unsafe { user_removed.GetCount() }?;
if count == 0 {
return Ok((list, Vec::new()));
}
let mut removed = Vec::with_capacity(count as usize);
for i in 0..count {
let shell_link: IShellLinkW = unsafe { user_removed.GetAt(i)? };
let description = {
// INFOTIPSIZE is the maximum size of the buffer
// see https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription
let mut buffer = [0u16; INFOTIPSIZE as usize];
unsafe { shell_link.GetDescription(&mut buffer)? };
let len = unsafe { u_strlen(buffer.as_ptr()) };
String::from_utf16_lossy(&buffer[..len as usize])
};
let args = description.split('\n').map(PathBuf::from).collect();
removed.push(args);
}
Ok((list, removed))
}
fn add_dock_menu(
list: &ICustomDestinationList,
dock_menus: &[(SharedString, SharedString)],
) -> anyhow::Result<()> {
unsafe {
let tasks: IObjectCollection =
CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;
for (idx, (name, description)) in dock_menus.iter().enumerate() {
let argument = HSTRING::from(format!("--dock-action {}", idx));
let description = HSTRING::from(description.as_str());
let display = name.as_str();
let task = create_shell_link(argument, description, None, display)?;
tasks.AddObject(&task)?;
}
list.AddUserTasks(&tasks)?;
Ok(())
}
}
fn add_recent_folders(
list: &ICustomDestinationList,
entries: &[SmallVec<[PathBuf; 2]>],
removed: &Vec<SmallVec<[PathBuf; 2]>>,
) -> anyhow::Result<()> {
unsafe {
let tasks: IObjectCollection =
CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;
for folder_path in entries.iter().filter(|path| !removed.contains(path)) {
let argument = HSTRING::from(
folder_path
.iter()
.map(|path| format!("\"{}\"", path.display()))
.join(" "),
);
let description = HSTRING::from(
folder_path
.iter()
.map(|path| path.to_string_lossy())
.collect::<Vec<_>>()
.join("\n"),
);
// simulate folder icon
// https://github.com/microsoft/vscode/blob/7a5dc239516a8953105da34f84bae152421a8886/src/vs/platform/workspaces/electron-main/workspacesHistoryMainService.ts#L380
let icon = HSTRING::from("explorer.exe");
let display = folder_path
.iter()
.map(|p| {
p.file_name()
.map(|name| name.to_string_lossy())
.unwrap_or_else(|| p.to_string_lossy())
})
.join(", ");
tasks.AddObject(&create_shell_link(
argument,
description,
Some(icon),
&display,
)?)?;
}
if tasks.GetCount().unwrap_or(0) > 0 {
list.AppendCategory(&HSTRING::from("Recent Folders"), &tasks)?;
}
Ok(())
}
}
fn create_shell_link(
argument: HSTRING,
description: HSTRING,
icon: Option<HSTRING>,
display: &str,
) -> anyhow::Result<IShellLinkW> {
unsafe {
let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;
let exe_path = HSTRING::from(std::env::current_exe()?.as_os_str());
link.SetPath(&exe_path)?;
link.SetArguments(&argument)?;
link.SetDescription(&description)?;
if let Some(icon) = icon {
link.SetIconLocation(&icon, 0)?;
}
let store: IPropertyStore = link.cast()?;
let title = PROPVARIANT::from(display);
store.SetValue(&PKEY_TITLE, &title)?;
store.Commit()?;
Ok(link)
}
}
+340
View File
@@ -0,0 +1,340 @@
use std::{
cell::RefCell,
rc::Rc,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use anyhow::{Context as _, Result, anyhow};
use futures::{
channel::oneshot,
future::{Either, select},
lock::Mutex,
};
use gpui::ForegroundExecutor;
use gpui_util::ResultExt;
use windows::{
Win32::{
Foundation::*,
System::{Com::*, Threading::GetCurrentThreadId},
UI::{
Controls::{TASKDIALOG_NOTIFICATIONS, TDN_BUTTON_CLICKED},
WindowsAndMessaging::*,
},
},
core::{BOOL, HRESULT, w},
};
use crate::SafeHwnd;
pub(crate) struct DialogOwner {
hwnd: HWND,
closed: Arc<AtomicBool>,
serialization: Mutex<()>,
}
impl DialogOwner {
pub(crate) fn new(hwnd: HWND) -> Rc<Self> {
Rc::new(Self {
hwnd,
closed: Arc::new(AtomicBool::new(false)),
serialization: Mutex::new(()),
})
}
pub(crate) fn close(&self) {
self.closed.store(true, Ordering::Release);
}
pub(crate) async fn when_idle(&self) {
// After close(), queued requests cannot start a native dialog. Only the
// active dialog can still use the HWND, and it holds this lock until exit.
let _guard = self.serialization.lock().await;
}
}
#[derive(Clone, Default)]
struct Cancellation {
requested: Arc<AtomicBool>,
owner_closed: Option<Arc<AtomicBool>>,
}
impl Cancellation {
fn new(owner: Option<&DialogOwner>) -> Self {
Self {
owner_closed: owner.map(|owner| owner.closed.clone()),
..Self::default()
}
}
fn is_requested(&self) -> bool {
self.requested.load(Ordering::Acquire)
|| self
.owner_closed
.as_ref()
.is_some_and(|closed| closed.load(Ordering::Acquire))
}
}
/// Native modal loops may synchronously message their owner, so the foreground
/// thread must keep pumping messages rather than waiting for the dialog thread.
/// Holding the owner's lock through native completion also allows window
/// destruction to wait for the dialog without blocking the foreground thread.
pub(crate) fn show_dialog<T: Send + 'static>(
owner: Option<Rc<DialogOwner>>,
executor: &ForegroundExecutor,
dialog: impl FnOnce(HWND) -> Result<T> + Send + 'static,
) -> oneshot::Receiver<Result<T>> {
let (mut sender, receiver) = oneshot::channel();
let cancellation = Cancellation::new(owner.as_deref());
if cancellation.is_requested() {
sender.send(Err(anyhow!("dialog owner has closed"))).ok();
return receiver;
}
let hwnd = owner.as_ref().map(|owner| SafeHwnd::from(owner.hwnd));
executor
.spawn(async move {
// Let Windows manage enabling and activating the owner. Overlapping
// modal loops could otherwise re-enable it while another dialog is open.
let serialization = if let Some(owner) = owner.as_ref() {
match select(owner.serialization.lock(), sender.cancellation()).await {
Either::Left((guard, _)) => Some(guard),
Either::Right(((), _)) => return,
}
} else {
None
};
if sender.is_canceled() || cancellation.is_requested() {
return;
}
let (result_sender, mut result_receiver) = oneshot::channel();
let thread = std::thread::Builder::new()
.name("windows-native-dialog".into())
.spawn({
let cancellation = cancellation.clone();
move || {
let result = (|| {
let _apartment = Apartment::new()?;
let _timer = CancellationTimer::new(cancellation.clone())?;
if cancellation.is_requested() {
return Err(anyhow!("dialog cancelled"));
}
let result = dialog(hwnd.map(|hwnd| hwnd.as_raw()).unwrap_or_default());
if cancellation.is_requested() {
return Err(anyhow!("dialog cancelled"));
}
result
})();
result_sender.send(result).ok();
}
});
if let Err(error) = thread {
drop(serialization);
sender.send(Err(error.into())).ok();
return;
}
let result = match select(&mut result_receiver, sender.cancellation()).await {
Either::Left((result, _)) => result,
Either::Right(((), _)) => {
cancellation.requested.store(true, Ordering::Release);
result_receiver.await
}
};
// Neither launch another dialog nor destroy the owner until the
// native loop exits, even if the caller no longer wants its result.
drop(serialization);
sender
.send(result.unwrap_or_else(|error| Err(error.into())))
.ok();
})
.detach();
receiver
}
struct Apartment;
impl Apartment {
fn new() -> Result<Self> {
unsafe { CoInitializeEx(None, COINIT_APARTMENTTHREADED).ok()? };
Ok(Self)
}
}
impl Drop for Apartment {
fn drop(&mut self) {
unsafe { CoUninitialize() };
}
}
thread_local! {
static CANCELLATION: RefCell<Option<Cancellation>> = const { RefCell::new(None) };
}
struct CancellationTimer(usize);
impl CancellationTimer {
fn new(cancellation: Cancellation) -> Result<Self> {
let timer = unsafe { SetTimer(None, 0, 100, Some(cancel_dialog)) };
if timer == 0 {
return Err(windows::core::Error::from_thread())
.context("starting native dialog cancellation timer");
}
CANCELLATION.with(|slot| slot.replace(Some(cancellation)));
Ok(Self(timer))
}
}
impl Drop for CancellationTimer {
fn drop(&mut self) {
CANCELLATION.with(|slot| slot.take());
unsafe { KillTimer(None, self.0).log_err() };
}
}
unsafe extern "system" fn cancel_dialog(_: HWND, _: u32, _: usize, _: u32) {
if cancellation_requested() {
unsafe {
EnumThreadWindows(GetCurrentThreadId(), Some(close_dialog), LPARAM(0))
.ok()
.log_err();
};
}
}
fn cancellation_requested() -> bool {
CANCELLATION.with(|slot| {
slot.borrow()
.as_ref()
.is_some_and(Cancellation::is_requested)
})
}
pub(crate) unsafe extern "system" fn task_dialog_callback(
_: HWND,
notification: TASKDIALOG_NOTIFICATIONS,
button: WPARAM,
_: LPARAM,
has_cancel_button: isize,
) -> HRESULT {
// WM_CLOSE requires TDF_ALLOW_DIALOG_CANCELLATION, which also enables Esc/X.
// Only allow those user gestures when the prompt offered a Cancel button.
if notification == TDN_BUTTON_CLICKED
&& button.0 == IDCANCEL.0 as usize
&& has_cancel_button == 0
&& !cancellation_requested()
{
S_FALSE
} else {
S_OK
}
}
unsafe extern "system" fn close_dialog(hwnd: HWND, _: LPARAM) -> BOOL {
// Shell dialogs can open further modal dialogs. Close only dialog windows
// on this dedicated thread, not hidden COM infrastructure windows.
let mut class_name = [0u16; 32];
let length = unsafe { GetClassNameW(hwnd, &mut class_name) } as usize;
let dialog_class = w!("#32770");
if class_name.get(..length) == Some(unsafe { dialog_class.as_wide() }) {
unsafe { PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0)).log_err() };
}
TRUE
}
#[cfg(test)]
mod tests {
use super::*;
use futures::FutureExt as _;
#[test]
fn task_dialog_cancellation_requires_cancel_button_or_internal_request() {
let cancellation = Cancellation::default();
CANCELLATION.with(|slot| slot.replace(Some(cancellation.clone())));
for internally_cancelled in [false, true] {
cancellation
.requested
.store(internally_cancelled, Ordering::Release);
for has_cancel_button in [false, true] {
for button in [IDCANCEL.0, IDOK.0, -1] {
let result = unsafe {
task_dialog_callback(
HWND::default(),
TDN_BUTTON_CLICKED,
WPARAM(button as usize),
LPARAM(0),
has_cancel_button as isize,
)
};
let should_veto =
button == IDCANCEL.0 && !has_cancel_button && !internally_cancelled;
assert_eq!(result, if should_veto { S_FALSE } else { S_OK });
}
}
}
CANCELLATION.with(|slot| slot.take());
}
#[test]
fn closing_owner_cancels_every_outstanding_dialog() {
let owner = DialogOwner::new(HWND::default());
let first = Cancellation::new(Some(&owner));
let second = Cancellation::new(Some(&owner));
assert!(!first.is_requested());
assert!(!second.is_requested());
owner.close();
owner.close();
assert!(first.is_requested());
assert!(second.is_requested());
assert!(Cancellation::new(Some(&owner)).is_requested());
}
#[test]
fn closed_owner_waits_for_active_dialog_but_queued_requests_stay_cancelled() {
let owner = DialogOwner::new(HWND::default());
let active = owner.serialization.try_lock().expect("first dialog");
let queued = Cancellation::new(Some(&owner));
owner.close();
assert!(owner.when_idle().now_or_never().is_none());
drop(active);
assert!(owner.when_idle().now_or_never().is_some());
let _guard = owner.serialization.try_lock().expect("queued request");
assert!(queued.is_requested());
}
#[test]
fn cancelling_one_request_does_not_cancel_its_owner_or_other_requests() {
let owner = DialogOwner::new(HWND::default());
let first = Cancellation::new(Some(&owner));
let second = Cancellation::new(Some(&owner));
first.requested.store(true, Ordering::Release);
assert!(first.is_requested());
assert!(!second.is_requested());
assert!(!owner.closed.load(Ordering::Acquire));
}
#[test]
fn dialogs_serialize_per_owner() {
let owner = DialogOwner::new(HWND::default());
let other_owner = DialogOwner::new(HWND::default());
let guard = owner.serialization.try_lock().expect("first dialog");
assert!(owner.serialization.try_lock().is_none());
assert!(other_owner.serialization.try_lock().is_some());
drop(guard);
assert!(owner.serialization.try_lock().is_some());
}
#[test]
fn ownerless_request_can_be_cancelled_without_a_window() {
let cancellation = Cancellation::new(None);
assert!(!cancellation.is_requested());
cancellation.requested.store(true, Ordering::Release);
assert!(cancellation.is_requested());
}
}
@@ -0,0 +1,361 @@
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use anyhow::Result;
use gpui::*;
use gpui_util::ResultExt;
use windows::Win32::{
Foundation::*,
Graphics::{DirectManipulation::*, Gdi::*},
System::Com::*,
UI::{Input::Pointer::*, WindowsAndMessaging::*},
};
use crate::*;
/// Default viewport size in pixels. The actual content size doesn't matter
/// because we're using the viewport only for gesture recognition, not for
/// visual output.
const DEFAULT_VIEWPORT_SIZE: i32 = 1000;
pub(crate) struct DirectManipulationHandler {
manager: IDirectManipulationManager,
update_manager: IDirectManipulationUpdateManager,
viewport: IDirectManipulationViewport,
_handler_cookie: u32,
window: HWND,
scale_factor: Rc<Cell<f32>>,
pending_events: Rc<RefCell<Vec<PlatformInput>>>,
}
impl DirectManipulationHandler {
pub fn new(window: HWND, scale_factor: f32) -> Result<Self> {
unsafe {
let manager: IDirectManipulationManager =
CoCreateInstance(&DirectManipulationManager, None, CLSCTX_INPROC_SERVER)?;
let update_manager: IDirectManipulationUpdateManager = manager.GetUpdateManager()?;
let viewport: IDirectManipulationViewport = manager.CreateViewport(None, window)?;
let configuration = DIRECTMANIPULATION_CONFIGURATION_INTERACTION
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y
| DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA
| DIRECTMANIPULATION_CONFIGURATION_RAILS_X
| DIRECTMANIPULATION_CONFIGURATION_RAILS_Y
| DIRECTMANIPULATION_CONFIGURATION_SCALING;
viewport.ActivateConfiguration(configuration)?;
viewport.SetViewportOptions(
DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE
| DIRECTMANIPULATION_VIEWPORT_OPTIONS_DISABLEPIXELSNAPPING,
)?;
let mut rect = RECT {
left: 0,
top: 0,
right: DEFAULT_VIEWPORT_SIZE,
bottom: DEFAULT_VIEWPORT_SIZE,
};
viewport.SetViewportRect(&mut rect)?;
manager.Activate(window)?;
viewport.Enable()?;
let scale_factor = Rc::new(Cell::new(scale_factor));
let pending_events = Rc::new(RefCell::new(Vec::new()));
let event_handler: IDirectManipulationViewportEventHandler =
DirectManipulationEventHandler::new(
window,
Rc::clone(&scale_factor),
Rc::clone(&pending_events),
)
.into();
let handler_cookie = viewport.AddEventHandler(Some(window), &event_handler)?;
update_manager.Update(None)?;
Ok(Self {
manager,
update_manager,
viewport,
_handler_cookie: handler_cookie,
window,
scale_factor,
pending_events,
})
}
}
pub fn set_scale_factor(&self, scale_factor: f32) {
self.scale_factor.set(scale_factor);
}
pub fn on_pointer_hit_test(&self, wparam: WPARAM) {
unsafe {
let pointer_id = wparam.loword() as u32;
let mut pointer_type = POINTER_INPUT_TYPE::default();
if GetPointerType(pointer_id, &mut pointer_type).is_ok() && pointer_type == PT_TOUCHPAD
{
self.viewport.SetContact(pointer_id).log_err();
}
}
}
pub fn update(&self) {
unsafe {
self.update_manager.Update(None).log_err();
}
}
pub fn drain_events(&self) -> Vec<PlatformInput> {
std::mem::take(&mut *self.pending_events.borrow_mut())
}
}
impl Drop for DirectManipulationHandler {
fn drop(&mut self) {
unsafe {
self.viewport.Stop().log_err();
self.viewport.Abandon().log_err();
self.manager.Deactivate(self.window).log_err();
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum GestureKind {
None,
Scroll,
Pinch,
}
#[windows_core::implement(IDirectManipulationViewportEventHandler)]
struct DirectManipulationEventHandler {
window: HWND,
scale_factor: Rc<Cell<f32>>,
gesture_kind: Cell<GestureKind>,
last_scale: Cell<f32>,
last_x_offset: Cell<f32>,
last_y_offset: Cell<f32>,
scroll_phase: Cell<TouchPhase>,
pending_events: Rc<RefCell<Vec<PlatformInput>>>,
}
impl DirectManipulationEventHandler {
fn new(
window: HWND,
scale_factor: Rc<Cell<f32>>,
pending_events: Rc<RefCell<Vec<PlatformInput>>>,
) -> Self {
Self {
window,
scale_factor,
gesture_kind: Cell::new(GestureKind::None),
last_scale: Cell::new(1.0),
last_x_offset: Cell::new(0.0),
last_y_offset: Cell::new(0.0),
scroll_phase: Cell::new(TouchPhase::Started),
pending_events,
}
}
fn end_gesture(&self) {
let position = self.mouse_position();
let modifiers = current_modifiers();
match self.gesture_kind.get() {
GestureKind::Scroll => {
self.pending_events
.borrow_mut()
.push(PlatformInput::Scroll(ScrollEvent {
position,
delta: ScrollDelta::Pixels(point(px(0.0), px(0.0))),
modifiers,
touch_phase: TouchPhase::Ended,
source: ScrollSource::Pointer,
}));
}
GestureKind::Pinch => {
self.pending_events
.borrow_mut()
.push(PlatformInput::Pinch(PinchEvent {
position,
delta: 0.0,
modifiers,
phase: TouchPhase::Ended,
}));
}
GestureKind::None => {}
}
self.gesture_kind.set(GestureKind::None);
}
fn mouse_position(&self) -> Point<Pixels> {
let scale_factor = self.scale_factor.get();
unsafe {
let mut point: POINT = std::mem::zeroed();
let _ = GetCursorPos(&mut point);
let _ = ScreenToClient(self.window, &mut point);
logical_point(point.x as f32, point.y as f32, scale_factor)
}
}
}
impl IDirectManipulationViewportEventHandler_Impl for DirectManipulationEventHandler_Impl {
fn OnViewportStatusChanged(
&self,
viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
current: DIRECTMANIPULATION_STATUS,
previous: DIRECTMANIPULATION_STATUS,
) -> windows_core::Result<()> {
if current == previous {
return Ok(());
}
// A new gesture interrupted inertia, so end the old sequence.
if current == DIRECTMANIPULATION_RUNNING && previous == DIRECTMANIPULATION_INERTIA {
self.end_gesture();
}
if current == DIRECTMANIPULATION_READY {
self.end_gesture();
// Reset the content transform so the viewport is ready for the next gesture.
// ZoomToRect triggers a second RUNNING -> READY cycle, so prevent an infinite loop here.
if self.last_scale.get() != 1.0
|| self.last_x_offset.get() != 0.0
|| self.last_y_offset.get() != 0.0
{
if let Some(viewport) = viewport.as_ref() {
unsafe {
viewport
.ZoomToRect(
0.0,
0.0,
DEFAULT_VIEWPORT_SIZE as f32,
DEFAULT_VIEWPORT_SIZE as f32,
false,
)
.log_err();
}
}
}
self.last_scale.set(1.0);
self.last_x_offset.set(0.0);
self.last_y_offset.set(0.0);
}
Ok(())
}
fn OnViewportUpdated(
&self,
_viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
) -> windows_core::Result<()> {
Ok(())
}
fn OnContentUpdated(
&self,
_viewport: windows_core::Ref<'_, IDirectManipulationViewport>,
content: windows_core::Ref<'_, IDirectManipulationContent>,
) -> windows_core::Result<()> {
let content = content.as_ref().ok_or(E_POINTER)?;
// Get the 6-element content transform: [scale, 0, 0, scale, tx, ty]
let mut xform = [0.0f32; 6];
unsafe {
content.GetContentTransform(&mut xform)?;
}
let scale = xform[0];
let scale_factor = self.scale_factor.get();
let x_offset = xform[4] / scale_factor;
let y_offset = xform[5] / scale_factor;
if scale == 0.0 {
return Ok(());
}
let last_scale = self.last_scale.get();
let last_x = self.last_x_offset.get();
let last_y = self.last_y_offset.get();
if float_equals(scale, last_scale)
&& float_equals(x_offset, last_x)
&& float_equals(y_offset, last_y)
{
return Ok(());
}
let position = self.mouse_position();
let modifiers = current_modifiers();
// Direct Manipulation reports both translation and scale in every content update.
// Translation values can shift during a pinch due to the zoom center shifting.
// We classify each gesture as either scroll or pinch and only emit one type of event.
// We allow Scroll -> Pinch (a pinch can start with a small pan) but not the reverse.
if !float_equals(scale, 1.0) {
if self.gesture_kind.get() != GestureKind::Pinch {
self.end_gesture();
self.gesture_kind.set(GestureKind::Pinch);
self.pending_events
.borrow_mut()
.push(PlatformInput::Pinch(PinchEvent {
position,
delta: 0.0,
modifiers,
phase: TouchPhase::Started,
}));
}
} else if self.gesture_kind.get() == GestureKind::None {
self.gesture_kind.set(GestureKind::Scroll);
self.scroll_phase.set(TouchPhase::Started);
}
match self.gesture_kind.get() {
GestureKind::Scroll => {
let dx = x_offset - last_x;
let dy = y_offset - last_y;
let touch_phase = self.scroll_phase.get();
self.scroll_phase.set(TouchPhase::Moved);
self.pending_events
.borrow_mut()
.push(PlatformInput::Scroll(ScrollEvent {
position,
delta: ScrollDelta::Pixels(point(px(dx), px(dy))),
modifiers,
touch_phase,
source: ScrollSource::Pointer,
}));
}
GestureKind::Pinch => {
let scale_delta = scale / last_scale;
self.pending_events
.borrow_mut()
.push(PlatformInput::Pinch(PinchEvent {
position,
delta: scale_delta - 1.0,
modifiers,
phase: TouchPhase::Moved,
}));
}
GestureKind::None => {}
}
self.last_scale.set(scale);
self.last_x_offset.set(x_offset);
self.last_y_offset.set(y_offset);
Ok(())
}
}
fn float_equals(f1: f32, f2: f32) -> bool {
const EPSILON_SCALE: f32 = 0.00001;
(f1 - f2).abs() < EPSILON_SCALE * f1.abs().max(f2.abs()).max(EPSILON_SCALE)
}
File diff suppressed because it is too large. Load diff
+420
View File
@@ -0,0 +1,420 @@
use etagere::BucketedAtlasAllocator;
use parking_lot::Mutex;
use windows::Win32::Graphics::{
Direct3D11::{
D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,
ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D,
},
Dxgi::Common::*,
};
use gpui::{
AtlasBackend, AtlasKey, AtlasState, AtlasTextureId, AtlasTextureKind, AtlasTextureList,
AtlasTile, Bounds, DevicePixels, PlatformAtlas, Point, Size,
};
pub(crate) struct DirectXAtlas(Mutex<AtlasState<DirectXAtlasTextures>>);
struct DirectXAtlasTextures {
device: ID3D11Device,
device_context: ID3D11DeviceContext,
monochrome_textures: AtlasTextureList<DirectXAtlasTexture>,
polychrome_textures: AtlasTextureList<DirectXAtlasTexture>,
subpixel_textures: AtlasTextureList<DirectXAtlasTexture>,
}
struct DirectXAtlasTexture {
id: AtlasTextureId,
bytes_per_pixel: u32,
allocator: BucketedAtlasAllocator,
texture: ID3D11Texture2D,
view: [Option<ID3D11ShaderResourceView>; 1],
live_atlas_keys: u32,
}
impl DirectXAtlas {
pub(crate) fn new(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Self {
DirectXAtlas(Mutex::new(AtlasState::new(DirectXAtlasTextures {
device: device.clone(),
device_context: device_context.clone(),
monochrome_textures: Default::default(),
polychrome_textures: Default::default(),
subpixel_textures: Default::default(),
})))
}
/// Returns the view backing `id`, or `None` once every tile in it has been
/// removed. A scene can still reference such a texture when a cached view
/// replays a paint from before the image was dropped, so callers must skip
/// those sprites rather than assume the texture exists.
pub(crate) fn get_texture_view(
&self,
id: AtlasTextureId,
) -> Option<[Option<ID3D11ShaderResourceView>; 1]> {
let lock = self.0.lock();
let texture = lock.backend.texture(id)?;
Some(texture.view.clone())
}
pub(crate) fn handle_device_lost(
&self,
device: &ID3D11Device,
device_context: &ID3D11DeviceContext,
) {
let mut lock = self.0.lock();
lock.clear(|textures| {
textures.device = device.clone();
textures.device_context = device_context.clone();
textures.monochrome_textures = AtlasTextureList::default();
textures.polychrome_textures = AtlasTextureList::default();
textures.subpixel_textures = AtlasTextureList::default();
});
}
}
impl PlatformAtlas for DirectXAtlas {
fn get_or_insert_with<'a>(
&self,
key: AtlasKey,
build: &mut dyn FnMut() -> anyhow::Result<
Option<(Size<DevicePixels>, std::borrow::Cow<'a, [u8]>)>,
>,
) -> anyhow::Result<Option<AtlasTile>> {
self.0.lock().get_or_insert_with(key, build)
}
fn remove(&self, key: &AtlasKey) {
self.0.lock().remove(key);
}
}
impl AtlasBackend for DirectXAtlasTextures {
fn insert(
&mut self,
kind: AtlasTextureKind,
size: Size<DevicePixels>,
bytes: &[u8],
) -> anyhow::Result<AtlasTile> {
let tile = self
.allocate(size, kind)
.ok_or_else(|| anyhow::anyhow!("failed to allocate"))?;
let texture = self
.texture(tile.texture_id)
.ok_or_else(|| anyhow::anyhow!("allocated tile refers to a missing texture"))?;
texture.upload(&self.device_context, tile.bounds, bytes);
Ok(tile)
}
fn remove(&mut self, tile: AtlasTile) {
let id = tile.texture_id;
let textures = match id.kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
};
let Some(texture_slot) = textures.textures.get_mut(id.index as usize) else {
return;
};
if let Some(mut texture) = texture_slot.take() {
texture.allocator.deallocate(tile.tile_id.into());
texture.decrement_ref_count();
if texture.is_unreferenced() {
textures.free_list.push(texture.id.index as usize);
} else {
*texture_slot = Some(texture);
}
}
}
}
impl DirectXAtlasTextures {
fn allocate(
&mut self,
size: Size<DevicePixels>,
texture_kind: AtlasTextureKind,
) -> Option<AtlasTile> {
{
let textures = match texture_kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
};
if let Some(tile) = textures
.iter_mut()
.rev()
.find_map(|texture| texture.allocate(size))
{
return Some(tile);
}
}
let texture = self.push_texture(size, texture_kind)?;
texture.allocate(size)
}
fn push_texture(
&mut self,
min_size: Size<DevicePixels>,
kind: AtlasTextureKind,
) -> Option<&mut DirectXAtlasTexture> {
const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(1024),
height: DevicePixels(1024),
};
// Max texture size for DirectX. See:
// https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits
const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {
width: DevicePixels(16384),
height: DevicePixels(16384),
};
let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);
let pixel_format;
let bind_flag;
let bytes_per_pixel;
match kind {
AtlasTextureKind::Monochrome => {
pixel_format = DXGI_FORMAT_R8_UNORM;
bind_flag = D3D11_BIND_SHADER_RESOURCE;
bytes_per_pixel = 1;
}
AtlasTextureKind::Polychrome => {
pixel_format = DXGI_FORMAT_B8G8R8A8_UNORM;
bind_flag = D3D11_BIND_SHADER_RESOURCE;
bytes_per_pixel = 4;
}
AtlasTextureKind::Subpixel => {
pixel_format = DXGI_FORMAT_R8G8B8A8_UNORM;
bind_flag = D3D11_BIND_SHADER_RESOURCE;
bytes_per_pixel = 4;
}
}
let texture_desc = D3D11_TEXTURE2D_DESC {
Width: size.width.0 as u32,
Height: size.height.0 as u32,
MipLevels: 1,
ArraySize: 1,
Format: pixel_format,
SampleDesc: DXGI_SAMPLE_DESC {
Count: 1,
Quality: 0,
},
Usage: D3D11_USAGE_DEFAULT,
BindFlags: bind_flag.0 as u32,
CPUAccessFlags: 0,
MiscFlags: 0,
};
let mut texture: Option<ID3D11Texture2D> = None;
unsafe {
// This only returns None if the device is lost, which we will recreate later.
// So it's ok to return None here.
self.device
.CreateTexture2D(&texture_desc, None, Some(&mut texture))
.ok()?;
}
let texture = texture.unwrap();
let texture_list = match kind {
AtlasTextureKind::Monochrome => &mut self.monochrome_textures,
AtlasTextureKind::Polychrome => &mut self.polychrome_textures,
AtlasTextureKind::Subpixel => &mut self.subpixel_textures,
};
let index = texture_list.free_list.pop();
let view = unsafe {
let mut view = None;
self.device
.CreateShaderResourceView(&texture, None, Some(&mut view))
.ok()?;
[view]
};
let atlas_texture = DirectXAtlasTexture {
id: AtlasTextureId {
index: index.unwrap_or(texture_list.textures.len()) as u32,
kind,
},
bytes_per_pixel,
allocator: etagere::BucketedAtlasAllocator::new(device_size_to_etagere(size)),
texture,
view,
live_atlas_keys: 0,
};
if let Some(ix) = index {
texture_list.textures[ix] = Some(atlas_texture);
texture_list.textures.get_mut(ix).unwrap().as_mut()
} else {
texture_list.textures.push(Some(atlas_texture));
texture_list.textures.last_mut().unwrap().as_mut()
}
}
fn texture(&self, id: AtlasTextureId) -> Option<&DirectXAtlasTexture> {
let textures = match id.kind {
AtlasTextureKind::Monochrome => &self.monochrome_textures,
AtlasTextureKind::Polychrome => &self.polychrome_textures,
AtlasTextureKind::Subpixel => &self.subpixel_textures,
};
textures.textures.get(id.index as usize)?.as_ref()
}
}
impl DirectXAtlasTexture {
fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {
let allocation = self.allocator.allocate(device_size_to_etagere(size))?;
let tile = AtlasTile {
texture_id: self.id,
tile_id: allocation.id.into(),
bounds: Bounds {
origin: etagere_point_to_device(allocation.rectangle.min),
size,
},
padding: 0,
};
self.live_atlas_keys += 1;
Some(tile)
}
fn upload(
&self,
device_context: &ID3D11DeviceContext,
bounds: Bounds<DevicePixels>,
bytes: &[u8],
) {
// `UpdateSubresource` reads `row_pitch * height` bytes from `bytes` based on the
// `D3D11_BOX` below. If the caller hands us a slice shorter than that, the driver would
// over-read past the end of the source buffer (potentially by multiple megabytes), so bail
// out instead. This is a first-insert path rather than a per-frame one, so the check is
// effectively free.
let row_bytes = bounds.size.width.to_bytes(self.bytes_per_pixel as u8) as usize;
let expected = row_bytes * bounds.size.height.0.max(0) as usize;
if bytes.len() < expected {
log::error!(
"DirectXAtlasTexture::upload: source slice is {} bytes but the {}x{} region \
requires {} bytes; skipping upload to avoid a driver over-read",
bytes.len(),
bounds.size.width.0,
bounds.size.height.0,
expected,
);
return;
}
unsafe {
device_context.UpdateSubresource(
&self.texture,
0,
Some(&D3D11_BOX {
left: bounds.left().0 as u32,
top: bounds.top().0 as u32,
front: 0,
right: bounds.right().0 as u32,
bottom: bounds.bottom().0 as u32,
back: 1,
}),
bytes.as_ptr() as _,
bounds.size.width.to_bytes(self.bytes_per_pixel as u8),
0,
);
}
}
fn decrement_ref_count(&mut self) {
self.live_atlas_keys -= 1;
}
fn is_unreferenced(&mut self) -> bool {
self.live_atlas_keys == 0
}
}
fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {
etagere::Size::new(size.width.into(), size.height.into())
}
fn etagere_point_to_device(value: etagere::Point) -> Point<DevicePixels> {
Point {
x: DevicePixels::from(value.x),
y: DevicePixels::from(value.y),
}
}
#[cfg(test)]
mod tests {
use super::*;
use gpui::{ImageId, RenderImageParams};
use std::borrow::Cow;
use windows::Win32::{
Foundation::HMODULE,
Graphics::{
Direct3D::D3D_DRIVER_TYPE_WARP,
Direct3D11::{D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION, D3D11CreateDevice},
},
};
fn create_atlas() -> Option<DirectXAtlas> {
let mut device: Option<ID3D11Device> = None;
let mut device_context: Option<ID3D11DeviceContext> = None;
unsafe {
D3D11CreateDevice(
None,
D3D_DRIVER_TYPE_WARP,
HMODULE::default(),
D3D11_CREATE_DEVICE_BGRA_SUPPORT,
None,
D3D11_SDK_VERSION,
Some(&mut device),
None,
Some(&mut device_context),
)
}
.ok()?;
Some(DirectXAtlas::new(&device?, &device_context?))
}
fn make_image_key(image_id: usize) -> AtlasKey {
AtlasKey::Image(RenderImageParams {
image_id: ImageId(image_id),
frame_index: 0,
})
}
fn insert_tile(atlas: &DirectXAtlas, key: AtlasKey, size: Size<DevicePixels>) -> AtlasTile {
atlas
.get_or_insert_with(key, &mut || {
let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;
Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))
})
.expect("allocation should succeed")
.expect("callback returns Some")
}
#[test]
fn test_remove_deallocates_tile_space_for_reuse() {
let Some(atlas) = create_atlas() else {
return;
};
let small = Size {
width: DevicePixels(64),
height: DevicePixels(64),
};
let big = Size {
width: DevicePixels(700),
height: DevicePixels(700),
};
let keeper_key = make_image_key(1);
let big_key_a = make_image_key(2);
let big_key_b = make_image_key(3);
let keeper_tile = insert_tile(&atlas, keeper_key, small);
let tile_a = insert_tile(&atlas, big_key_a.clone(), big);
assert_eq!(keeper_tile.texture_id, tile_a.texture_id);
atlas.remove(&big_key_a);
let tile_b = insert_tile(&atlas, big_key_b, big);
assert_eq!(tile_b.texture_id, keeper_tile.texture_id);
}
}
+194
View File
@@ -0,0 +1,194 @@
use anyhow::{Context, Result};
use gpui_util::ResultExt;
use itertools::Itertools;
use windows::Win32::{
Foundation::HMODULE,
Graphics::{
Direct3D::{
D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1,
},
Direct3D11::{
D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_DEBUG,
D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS,
D3D11_SDK_VERSION, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,
},
Dxgi::{
CreateDXGIFactory2, DXGI_CREATE_FACTORY_DEBUG, DXGI_CREATE_FACTORY_FLAGS,
IDXGIAdapter1, IDXGIFactory6,
},
},
};
use windows::core::Interface;
pub(crate) fn try_to_recover_from_device_lost<T>(mut f: impl FnMut() -> Result<T>) -> Result<T> {
(0..5)
.map(|i| {
if i > 0 {
// Add a small delay before retrying
std::thread::sleep(std::time::Duration::from_millis(100 + i * 10));
}
f()
})
.find_or_last(Result::is_ok)
.unwrap()
.context("DirectXRenderer failed to recover from lost device after multiple attempts")
}
#[derive(Clone)]
pub(crate) struct DirectXDevices {
pub(crate) adapter: IDXGIAdapter1,
pub(crate) dxgi_factory: IDXGIFactory6,
pub(crate) device: ID3D11Device,
pub(crate) device_context: ID3D11DeviceContext,
}
impl DirectXDevices {
pub(crate) fn new() -> Result<Self> {
let debug_layer_available = check_debug_layer_available();
let dxgi_factory =
get_dxgi_factory(debug_layer_available).context("Creating DXGI factory")?;
let (adapter, device, device_context, feature_level) =
get_adapter(&dxgi_factory, debug_layer_available).context("Getting DXGI adapter")?;
match feature_level {
D3D_FEATURE_LEVEL_11_1 => {
log::info!("Created device with Direct3D 11.1 feature level.")
}
D3D_FEATURE_LEVEL_11_0 => {
log::info!("Created device with Direct3D 11.0 feature level.")
}
D3D_FEATURE_LEVEL_10_1 => {
log::info!("Created device with Direct3D 10.1 feature level.")
}
_ => unreachable!(),
}
Ok(Self {
adapter,
dxgi_factory,
device,
device_context,
})
}
}
#[inline]
fn check_debug_layer_available() -> bool {
#[cfg(debug_assertions)]
{
use windows::Win32::Graphics::Dxgi::{DXGIGetDebugInterface1, IDXGIInfoQueue};
unsafe { DXGIGetDebugInterface1::<IDXGIInfoQueue>(0) }
.log_err()
.is_some()
}
#[cfg(not(debug_assertions))]
{
false
}
}
#[inline]
fn get_dxgi_factory(debug_layer_available: bool) -> Result<IDXGIFactory6> {
let factory_flag = if debug_layer_available {
DXGI_CREATE_FACTORY_DEBUG
} else {
#[cfg(debug_assertions)]
log::warn!(
"Failed to get DXGI debug interface. DirectX debugging features will be disabled."
);
DXGI_CREATE_FACTORY_FLAGS::default()
};
unsafe { Ok(CreateDXGIFactory2(factory_flag)?) }
}
#[inline]
fn get_adapter(
dxgi_factory: &IDXGIFactory6,
debug_layer_available: bool,
) -> Result<(
IDXGIAdapter1,
ID3D11Device,
ID3D11DeviceContext,
D3D_FEATURE_LEVEL,
)> {
for adapter_index in 0.. {
let adapter: IDXGIAdapter1 = unsafe { dxgi_factory.EnumAdapters(adapter_index)?.cast()? };
if let Ok(desc) = unsafe { adapter.GetDesc1() } {
let gpu_name = String::from_utf16_lossy(&desc.Description)
.trim_matches(char::from(0))
.to_string();
log::info!("Using GPU: {}", gpu_name);
}
// Check to see whether the adapter supports Direct3D 11 and create
// the device if it does.
let mut context: Option<ID3D11DeviceContext> = None;
let mut feature_level = D3D_FEATURE_LEVEL::default();
if let Some(device) = get_device(
&adapter,
Some(&mut context),
Some(&mut feature_level),
debug_layer_available,
)
.log_err()
{
return Ok((adapter, device, context.unwrap(), feature_level));
}
}
unreachable!()
}
#[inline]
fn get_device(
adapter: &IDXGIAdapter1,
context: Option<*mut Option<ID3D11DeviceContext>>,
feature_level: Option<*mut D3D_FEATURE_LEVEL>,
debug_layer_available: bool,
) -> Result<ID3D11Device> {
let mut device: Option<ID3D11Device> = None;
let device_flags = if debug_layer_available {
D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG
} else {
D3D11_CREATE_DEVICE_BGRA_SUPPORT
};
unsafe {
D3D11CreateDevice(
adapter,
D3D_DRIVER_TYPE_UNKNOWN,
HMODULE::default(),
device_flags,
// 4x MSAA is required for Direct3D Feature Level 10.1 or better
Some(&[
D3D_FEATURE_LEVEL_11_1,
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
]),
D3D11_SDK_VERSION,
Some(&mut device),
feature_level,
context,
)?;
}
let device = device.unwrap();
let mut data = D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS::default();
unsafe {
device
.CheckFeatureSupport(
D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS,
&mut data as *mut _ as _,
std::mem::size_of::<D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS>() as u32,
)
.context("Checking GPU device feature support")?;
}
if data
.ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x
.as_bool()
{
Ok(device)
} else {
Err(anyhow::anyhow!(
"Required feature StructuredBuffer is not supported by GPU/driver"
))
}
}
File diff suppressed because it is too large. Load diff
+191
View File
@@ -0,0 +1,191 @@
use std::{
ffi::c_void,
ptr::NonNull,
sync::atomic::{AtomicBool, Ordering},
thread::{ThreadId, current},
time::Duration,
};
use anyhow::Context;
use gpui_util::ResultExt;
use windows::Win32::{
Foundation::{FILETIME, LPARAM, WPARAM},
Media::{timeBeginPeriod, timeEndPeriod},
System::Threading::{
CloseThreadpoolTimer, CreateThreadpoolTimer, GetCurrentThread, PTP_CALLBACK_INSTANCE,
PTP_TIMER, SetThreadPriority, SetThreadpoolTimer, THREAD_PRIORITY_TIME_CRITICAL,
TP_CALLBACK_ENVIRON_V3, TP_CALLBACK_PRIORITY, TP_CALLBACK_PRIORITY_HIGH,
TP_CALLBACK_PRIORITY_LOW, TP_CALLBACK_PRIORITY_NORMAL, TrySubmitThreadpoolCallback,
},
UI::WindowsAndMessaging::PostMessageW,
};
use crate::{HWND, SafeHwnd, WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD};
use gpui::{
PlatformDispatcher, Priority, PriorityQueueSender, RunnableVariant, TimerResolutionGuard,
};
pub(crate) struct WindowsDispatcher {
pub(crate) wake_posted: AtomicBool,
main_sender: PriorityQueueSender<RunnableVariant>,
main_thread_id: ThreadId,
pub(crate) platform_window_handle: SafeHwnd,
validation_number: usize,
}
impl WindowsDispatcher {
pub(crate) fn new(
main_sender: PriorityQueueSender<RunnableVariant>,
platform_window_handle: HWND,
validation_number: usize,
) -> Self {
let main_thread_id = current().id();
let platform_window_handle = platform_window_handle.into();
WindowsDispatcher {
main_sender,
main_thread_id,
platform_window_handle,
validation_number,
wake_posted: AtomicBool::new(false),
}
}
fn dispatch_on_threadpool(&self, priority: TP_CALLBACK_PRIORITY, runnable: RunnableVariant) {
let environ = TP_CALLBACK_ENVIRON_V3 {
Version: 3,
CallbackPriority: priority,
Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,
..Default::default()
};
// If the thread pool never runs our callback, the matching `from_raw` is never called, which leaks the runnable.
// Dropping the scheduled runnable would cancel its task and make the next poll of any awaiter panic. Since we expect
// the scenario to usually happen during shutdown, this leak is acceptable.
let context = runnable.into_raw().as_ptr() as *mut c_void;
unsafe {
TrySubmitThreadpoolCallback(Some(run_work_callback), Some(context), Some(&environ))
.log_err();
}
}
fn dispatch_on_threadpool_after(&self, runnable: RunnableVariant, duration: Duration) {
let context = runnable.into_raw().as_ptr() as *mut c_void;
unsafe {
if let Ok(timer) = CreateThreadpoolTimer(Some(run_timer_callback), Some(context), None)
{
// Negative FILETIME expresses a relative delay in 100ns ticks
let ticks = (duration.as_nanos() / 100).min(i64::MAX as u128) as i64;
let due = (-ticks) as u64;
let due_time = FILETIME {
dwLowDateTime: due as u32,
dwHighDateTime: (due >> 32) as u32,
};
SetThreadpoolTimer(timer, Some(&due_time), 0, None);
}
}
}
#[inline(always)]
pub(crate) fn execute_runnable(runnable: RunnableVariant) {
let location = runnable.metadata().location;
let spawned = runnable.metadata().spawned;
gpui::profiler::update_running_task(spawned, location);
runnable.run();
gpui::profiler::save_task_timing();
}
}
impl PlatformDispatcher for WindowsDispatcher {
fn is_main_thread(&self) -> bool {
current().id() == self.main_thread_id
}
fn dispatch(&self, runnable: RunnableVariant, priority: Priority) {
let priority = match priority {
Priority::RealtimeAudio => {
panic!("RealtimeAudio priority should use spawn_realtime, not dispatch")
}
Priority::High => TP_CALLBACK_PRIORITY_HIGH,
Priority::Medium => TP_CALLBACK_PRIORITY_NORMAL,
Priority::Low => TP_CALLBACK_PRIORITY_LOW,
};
self.dispatch_on_threadpool(priority, runnable);
}
fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority) {
match self.main_sender.send(priority, runnable) {
Ok(_) => {
if !self.wake_posted.swap(true, Ordering::AcqRel) {
unsafe {
PostMessageW(
Some(self.platform_window_handle.as_raw()),
WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,
WPARAM(self.validation_number),
LPARAM(0),
)
.log_err();
}
}
}
Err(runnable) => {
// NOTE: Runnable may wrap a Future that is !Send.
//
// This is usually safe because we only poll it on the main thread.
// However if the send fails, we know that:
// 1. main_receiver has been dropped (which implies the app is shutting down)
// 2. we are on a background thread.
// It is not safe to drop something !Send on the wrong thread, and
// the app will exit soon anyway, so we must forget the runnable.
std::mem::forget(runnable);
}
}
}
fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {
self.dispatch_on_threadpool_after(runnable, duration);
}
fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {
std::thread::spawn(move || {
// SAFETY: always safe to call
let thread_handle = unsafe { GetCurrentThread() };
// SAFETY: thread_handle is a valid handle to the current thread
unsafe { SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL) }
.context("thread priority")
.log_err();
f();
});
}
fn increase_timer_resolution(&self) -> TimerResolutionGuard {
unsafe {
timeBeginPeriod(1);
}
gpui_util::defer(Box::new(|| unsafe {
timeEndPeriod(1);
}))
}
}
unsafe extern "system" fn run_work_callback(
_instance: PTP_CALLBACK_INSTANCE,
context: *mut c_void,
) {
let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };
WindowsDispatcher::execute_runnable(runnable);
}
unsafe extern "system" fn run_timer_callback(
_instance: PTP_CALLBACK_INSTANCE,
context: *mut c_void,
timer: PTP_TIMER,
) {
let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };
WindowsDispatcher::execute_runnable(runnable);
unsafe { CloseThreadpoolTimer(timer) };
}
+244
View File
@@ -0,0 +1,244 @@
use gpui_util::ResultExt;
use itertools::Itertools;
use smallvec::SmallVec;
use std::rc::Rc;
use uuid::Uuid;
use windows::{
Win32::{
Foundation::*,
Graphics::Gdi::*,
UI::{
HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},
WindowsAndMessaging::USER_DEFAULT_SCREEN_DPI,
},
},
core::*,
};
use crate::logical_point;
use gpui::{
Bounds, DevicePixels, DisplayId, Pixels, PlatformDisplay, point, refresh_interval_from_hz, size,
};
#[derive(Debug, Clone, Copy)]
pub(crate) struct WindowsDisplay {
pub handle: HMONITOR,
pub display_id: DisplayId,
scale_factor: f32,
bounds: Bounds<Pixels>,
visible_bounds: Bounds<Pixels>,
physical_bounds: Bounds<DevicePixels>,
uuid: Uuid,
}
// The `HMONITOR` is thread-safe.
unsafe impl Send for WindowsDisplay {}
unsafe impl Sync for WindowsDisplay {}
impl WindowsDisplay {
pub(crate) fn new(display_id: DisplayId) -> Option<Self> {
let handle = HMONITOR(u64::from(display_id) as _);
let info = get_monitor_info(handle).log_err()?;
let monitor_size = info.monitorInfo.rcMonitor;
let work_area = info.monitorInfo.rcWork;
let uuid = generate_uuid(&info.szDevice);
let scale_factor = get_scale_factor_for_monitor(handle).log_err()?;
let physical_size = size(
(monitor_size.right - monitor_size.left).into(),
(monitor_size.bottom - monitor_size.top).into(),
);
Some(WindowsDisplay {
handle,
display_id,
scale_factor,
bounds: Bounds {
origin: logical_point(
monitor_size.left as f32,
monitor_size.top as f32,
scale_factor,
),
size: physical_size.to_pixels(scale_factor),
},
visible_bounds: Bounds {
origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),
size: size(
(work_area.right - work_area.left) as f32 / scale_factor,
(work_area.bottom - work_area.top) as f32 / scale_factor,
)
.map(gpui::px),
},
physical_bounds: Bounds {
origin: point(monitor_size.left.into(), monitor_size.top.into()),
size: physical_size,
},
uuid,
})
}
pub(crate) fn display_id_for_monitor(monitor: HMONITOR) -> DisplayId {
DisplayId::new(monitor.0 as u64)
}
pub fn primary_monitor() -> Option<Self> {
// https://devblogs.microsoft.com/oldnewthing/20070809-00/?p=25643
const POINT_ZERO: POINT = POINT { x: 0, y: 0 };
let monitor = unsafe { MonitorFromPoint(POINT_ZERO, MONITOR_DEFAULTTOPRIMARY) };
if monitor.is_invalid() {
log::error!(
"can not find the primary monitor: {}",
std::io::Error::last_os_error()
);
return None;
}
WindowsDisplay::new(Self::display_id_for_monitor(monitor))
}
/// The DPI scale factor of this monitor, independent of whatever monitor
/// a not-yet-positioned window currently happens to be on.
pub(crate) fn scale_factor(&self) -> f32 {
self.scale_factor
}
/// Check if the center point of given bounds is inside this monitor
pub fn check_given_bounds(&self, bounds: Bounds<Pixels>) -> bool {
let center = bounds.center();
let center = POINT {
x: (center.x.as_f32() * self.scale_factor) as i32,
y: (center.y.as_f32() * self.scale_factor) as i32,
};
let monitor = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) };
if monitor.is_invalid() {
false
} else {
let Some(display) = WindowsDisplay::new(Self::display_id_for_monitor(monitor)) else {
return false;
};
display.uuid == self.uuid
}
}
pub fn displays() -> Vec<Rc<dyn PlatformDisplay>> {
available_monitors()
.into_iter()
.filter_map(|handle| {
Some(
Rc::new(WindowsDisplay::new(Self::display_id_for_monitor(handle))?)
as Rc<dyn PlatformDisplay>,
)
})
.collect()
}
pub fn physical_bounds(&self) -> Bounds<DevicePixels> {
self.physical_bounds
}
}
impl PlatformDisplay for WindowsDisplay {
fn id(&self) -> DisplayId {
self.display_id
}
fn uuid(&self) -> anyhow::Result<Uuid> {
Ok(self.uuid)
}
fn bounds(&self) -> Bounds<Pixels> {
self.bounds
}
fn visible_bounds(&self) -> Bounds<Pixels> {
self.visible_bounds
}
fn refresh_interval(&self) -> Option<std::time::Duration> {
get_monitor_info(self.handle)
.log_err()
.and_then(|info| refresh_interval_for_device(&info.szDevice))
}
}
/// The refresh rate of the monitor's current mode. With variable refresh
/// rate, the mode's rate is the maximum.
fn refresh_interval_for_device(device_name: &[u16; 32]) -> Option<std::time::Duration> {
let mut mode = DEVMODEW {
dmSize: std::mem::size_of::<DEVMODEW>() as u16,
..Default::default()
};
// SAFETY: `device_name` is the null-terminated `szDevice` from
// `GetMonitorInfoW`, and `mode.dmSize` is initialized.
let found = unsafe {
EnumDisplaySettingsW(
PCWSTR(device_name.as_ptr()),
ENUM_CURRENT_SETTINGS,
&mut mode,
)
};
if !found.as_bool() {
return None;
}
// 0 and 1 mean the hardware's default rate, which isn't reported.
if mode.dmDisplayFrequency <= 1 {
return None;
}
refresh_interval_from_hz(f64::from(mode.dmDisplayFrequency))
}
fn available_monitors() -> SmallVec<[HMONITOR; 4]> {
let mut monitors: SmallVec<[HMONITOR; 4]> = SmallVec::new();
unsafe {
EnumDisplayMonitors(
None,
None,
Some(monitor_enum_proc),
LPARAM(&mut monitors as *mut _ as _),
)
.ok()
.log_err();
}
monitors
}
unsafe extern "system" fn monitor_enum_proc(
hmonitor: HMONITOR,
_hdc: HDC,
_place: *mut RECT,
data: LPARAM,
) -> BOOL {
let monitors = data.0 as *mut SmallVec<[HMONITOR; 4]>;
unsafe { (*monitors).push(hmonitor) };
BOOL(1)
}
fn get_monitor_info(hmonitor: HMONITOR) -> anyhow::Result<MONITORINFOEXW> {
let mut monitor_info: MONITORINFOEXW = unsafe { std::mem::zeroed() };
monitor_info.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;
let status = unsafe {
GetMonitorInfoW(
hmonitor,
&mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO,
)
};
if status.as_bool() {
Ok(monitor_info)
} else {
Err(anyhow::anyhow!(std::io::Error::last_os_error()))
}
}
fn generate_uuid(device_name: &[u16]) -> Uuid {
let name = device_name
.iter()
.flat_map(|&a| a.to_be_bytes())
.collect_vec();
Uuid::new_v5(&Uuid::NAMESPACE_DNS, &name)
}
fn get_scale_factor_for_monitor(monitor: HMONITOR) -> Result<f32> {
let mut dpi_x = 0;
let mut dpi_y = 0;
unsafe { GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) }?;
assert_eq!(dpi_x, dpi_y);
Ok(dpi_x as f32 / USER_DEFAULT_SCREEN_DPI as f32)
}
File diff suppressed because it is too large. Load diff
+43
View File
@@ -0,0 +1,43 @@
#![cfg(target_os = "windows")]
mod clipboard;
mod destination_list;
mod dialog;
mod direct_manipulation;
mod direct_write;
mod directx_atlas;
mod directx_devices;
mod directx_renderer;
mod dispatcher;
mod display;
mod events;
mod keyboard;
mod platform;
mod system_notifications;
mod system_settings;
mod util;
mod vsync;
mod window;
mod wrapper;
pub(crate) use clipboard::*;
pub(crate) use destination_list::*;
pub(crate) use direct_write::*;
pub(crate) use directx_atlas::*;
pub(crate) use directx_devices::*;
pub(crate) use directx_renderer::*;
pub(crate) use dispatcher::*;
pub(crate) use display::*;
pub(crate) use events::*;
pub(crate) use keyboard::*;
pub(crate) use platform::*;
pub(crate) use system_notifications::*;
pub(crate) use system_settings::*;
pub(crate) use util::*;
pub(crate) use vsync::*;
pub(crate) use window::*;
pub(crate) use wrapper::*;
pub use platform::WindowsPlatform;
pub(crate) use windows::Win32::Foundation::HWND;
+371
View File
@@ -0,0 +1,371 @@
use anyhow::Result;
use collections::HashMap;
use windows::Win32::UI::{
Input::KeyboardAndMouse::{
GetKeyboardLayoutNameW, MAPVK_VK_TO_CHAR, MAPVK_VK_TO_VSC, MapVirtualKeyW, ToUnicode,
VIRTUAL_KEY, VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_ABNT_C1,
VK_CONTROL, VK_MENU, VK_OEM_1, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7,
VK_OEM_8, VK_OEM_102, VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_SHIFT,
},
WindowsAndMessaging::KL_NAMELENGTH,
};
use gpui::{
KeybindingKeystroke, Keystroke, Modifiers, PlatformKeyboardLayout, PlatformKeyboardMapper,
};
pub(crate) struct WindowsKeyboardLayout {
id: String,
name: String,
}
pub(crate) struct WindowsKeyboardMapper {
key_to_vkey: HashMap<String, (u16, bool)>,
vkey_to_key: HashMap<u16, String>,
vkey_to_shifted: HashMap<u16, String>,
}
impl PlatformKeyboardLayout for WindowsKeyboardLayout {
fn id(&self) -> &str {
&self.id
}
fn name(&self) -> &str {
&self.name
}
}
impl PlatformKeyboardMapper for WindowsKeyboardMapper {
fn map_key_equivalent(
&self,
mut keystroke: Keystroke,
use_key_equivalents: bool,
) -> KeybindingKeystroke {
let Some((vkey, shifted_key)) = self.get_vkey_from_key(&keystroke.key, use_key_equivalents)
else {
return KeybindingKeystroke::from_keystroke(keystroke);
};
if shifted_key && keystroke.modifiers.shift {
log::warn!(
"Keystroke '{}' has both shift and a shifted key, this is likely a bug",
keystroke.key
);
}
let shift = shifted_key || keystroke.modifiers.shift;
keystroke.modifiers.shift = false;
let Some(key) = self.vkey_to_key.get(&vkey).cloned() else {
log::error!(
"Failed to map key equivalent '{:?}' to a valid key",
keystroke
);
return KeybindingKeystroke::from_keystroke(keystroke);
};
keystroke.key = if shift {
let Some(shifted_key) = self.vkey_to_shifted.get(&vkey).cloned() else {
log::error!(
"Failed to map keystroke {:?} with virtual key '{:?}' to a shifted key",
keystroke,
vkey
);
return KeybindingKeystroke::from_keystroke(keystroke);
};
shifted_key
} else {
key.clone()
};
let modifiers = Modifiers {
shift,
..keystroke.modifiers
};
KeybindingKeystroke::new(keystroke, modifiers, key)
}
fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {
None
}
}
impl WindowsKeyboardLayout {
pub(crate) fn new() -> Result<Self> {
let mut buffer = [0u16; KL_NAMELENGTH as usize]; // KL_NAMELENGTH includes the null terminator
unsafe { GetKeyboardLayoutNameW(&mut buffer)? };
let id = String::from_utf16_lossy(&buffer[..buffer.len() - 1]); // Remove the null terminator
let entry = windows_registry::LOCAL_MACHINE.open(format!(
"System\\CurrentControlSet\\Control\\Keyboard Layouts\\{id}"
))?;
let name = entry.get_string("Layout Text")?;
Ok(Self { id, name })
}
pub(crate) fn unknown() -> Self {
Self {
id: "unknown".to_string(),
name: "unknown".to_string(),
}
}
}
impl WindowsKeyboardMapper {
pub(crate) fn new() -> Self {
let mut key_to_vkey = HashMap::default();
let mut vkey_to_key = HashMap::default();
let mut vkey_to_shifted = HashMap::default();
for vkey in CANDIDATE_VKEYS {
if let Some(key) = get_key_from_vkey(*vkey) {
key_to_vkey.insert(key.clone(), (vkey.0, false));
vkey_to_key.insert(vkey.0, key);
}
let scan_code = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_VSC) };
if scan_code == 0 {
continue;
}
if let Some(shifted_key) = get_shifted_key(*vkey, scan_code) {
key_to_vkey.insert(shifted_key.clone(), (vkey.0, true));
vkey_to_shifted.insert(vkey.0, shifted_key);
}
}
Self {
key_to_vkey,
vkey_to_key,
vkey_to_shifted,
}
}
fn get_vkey_from_key(&self, key: &str, use_key_equivalents: bool) -> Option<(u16, bool)> {
if use_key_equivalents {
get_vkey_from_key_with_us_layout(key)
} else {
self.key_to_vkey.get(key).cloned()
}
}
}
pub(crate) fn get_keystroke_key(
vkey: VIRTUAL_KEY,
scan_code: u32,
modifiers: &mut Modifiers,
) -> Option<String> {
if modifiers.shift && need_to_convert_to_shifted_key(vkey) {
get_shifted_key(vkey, scan_code).inspect(|_| {
modifiers.shift = false;
})
} else {
get_key_from_vkey(vkey)
}
}
fn get_key_from_vkey(vkey: VIRTUAL_KEY) -> Option<String> {
let key_data = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_CHAR) };
if key_data == 0 {
return None;
}
// The high word contains dead key flag, the low word contains the character
let key = char::from_u32(key_data & 0xFFFF)?;
Some(key.to_ascii_lowercase().to_string())
}
#[inline]
fn need_to_convert_to_shifted_key(vkey: VIRTUAL_KEY) -> bool {
matches!(
vkey,
VK_OEM_3
| VK_OEM_MINUS
| VK_OEM_PLUS
| VK_OEM_4
| VK_OEM_5
| VK_OEM_6
| VK_OEM_1
| VK_OEM_7
| VK_OEM_COMMA
| VK_OEM_PERIOD
| VK_OEM_2
| VK_OEM_102
| VK_OEM_8
| VK_ABNT_C1
| VK_0
| VK_1
| VK_2
| VK_3
| VK_4
| VK_5
| VK_6
| VK_7
| VK_8
| VK_9
)
}
fn get_shifted_key(vkey: VIRTUAL_KEY, scan_code: u32) -> Option<String> {
generate_key_char(vkey, scan_code, false, true, false)
}
pub(crate) fn generate_key_char(
vkey: VIRTUAL_KEY,
scan_code: u32,
control: bool,
shift: bool,
alt: bool,
) -> Option<String> {
let mut state = [0; 256];
if control {
state[VK_CONTROL.0 as usize] = 0x80;
}
if shift {
state[VK_SHIFT.0 as usize] = 0x80;
}
if alt {
state[VK_MENU.0 as usize] = 0x80;
}
let mut buffer = [0; 8];
let len = unsafe { ToUnicode(vkey.0 as u32, scan_code, Some(&state), &mut buffer, 0x5) };
match len {
len if len > 0 => String::from_utf16(&buffer[..len as usize])
.ok()
.filter(|candidate| {
!candidate.is_empty() && !candidate.chars().next().unwrap().is_control()
}),
len if len < 0 => String::from_utf16(&buffer[..(-len as usize)]).ok(),
_ => None,
}
}
fn get_vkey_from_key_with_us_layout(key: &str) -> Option<(u16, bool)> {
match key {
// ` => VK_OEM_3
"`" => Some((VK_OEM_3.0, false)),
"~" => Some((VK_OEM_3.0, true)),
"1" => Some((VK_1.0, false)),
"!" => Some((VK_1.0, true)),
"2" => Some((VK_2.0, false)),
"@" => Some((VK_2.0, true)),
"3" => Some((VK_3.0, false)),
"#" => Some((VK_3.0, true)),
"4" => Some((VK_4.0, false)),
"$" => Some((VK_4.0, true)),
"5" => Some((VK_5.0, false)),
"%" => Some((VK_5.0, true)),
"6" => Some((VK_6.0, false)),
"^" => Some((VK_6.0, true)),
"7" => Some((VK_7.0, false)),
"&" => Some((VK_7.0, true)),
"8" => Some((VK_8.0, false)),
"*" => Some((VK_8.0, true)),
"9" => Some((VK_9.0, false)),
"(" => Some((VK_9.0, true)),
"0" => Some((VK_0.0, false)),
")" => Some((VK_0.0, true)),
"-" => Some((VK_OEM_MINUS.0, false)),
"_" => Some((VK_OEM_MINUS.0, true)),
"=" => Some((VK_OEM_PLUS.0, false)),
"+" => Some((VK_OEM_PLUS.0, true)),
"[" => Some((VK_OEM_4.0, false)),
"{" => Some((VK_OEM_4.0, true)),
"]" => Some((VK_OEM_6.0, false)),
"}" => Some((VK_OEM_6.0, true)),
"\\" => Some((VK_OEM_5.0, false)),
"|" => Some((VK_OEM_5.0, true)),
";" => Some((VK_OEM_1.0, false)),
":" => Some((VK_OEM_1.0, true)),
"'" => Some((VK_OEM_7.0, false)),
"\"" => Some((VK_OEM_7.0, true)),
"," => Some((VK_OEM_COMMA.0, false)),
"<" => Some((VK_OEM_COMMA.0, true)),
"." => Some((VK_OEM_PERIOD.0, false)),
">" => Some((VK_OEM_PERIOD.0, true)),
"/" => Some((VK_OEM_2.0, false)),
"?" => Some((VK_OEM_2.0, true)),
_ => None,
}
}
const CANDIDATE_VKEYS: &[VIRTUAL_KEY] = &[
VK_OEM_3,
VK_OEM_MINUS,
VK_OEM_PLUS,
VK_OEM_4,
VK_OEM_5,
VK_OEM_6,
VK_OEM_1,
VK_OEM_7,
VK_OEM_COMMA,
VK_OEM_PERIOD,
VK_OEM_2,
VK_OEM_102,
VK_OEM_8,
VK_ABNT_C1,
VK_0,
VK_1,
VK_2,
VK_3,
VK_4,
VK_5,
VK_6,
VK_7,
VK_8,
VK_9,
];
#[cfg(test)]
mod tests {
use crate::WindowsKeyboardMapper;
use gpui::{Keystroke, Modifiers, PlatformKeyboardMapper};
#[test]
fn test_keyboard_mapper() {
let mapper = WindowsKeyboardMapper::new();
// Normal case
let keystroke = Keystroke {
modifiers: Modifiers::control(),
key: "a".to_string(),
key_char: None,
};
let mapped = mapper.map_key_equivalent(keystroke.clone(), true);
assert_eq!(*mapped.inner(), keystroke);
assert_eq!(mapped.key(), "a");
assert_eq!(*mapped.modifiers(), Modifiers::control());
// Shifted case, ctrl-$
let keystroke = Keystroke {
modifiers: Modifiers::control(),
key: "$".to_string(),
key_char: None,
};
let mapped = mapper.map_key_equivalent(keystroke.clone(), true);
assert_eq!(*mapped.inner(), keystroke);
assert_eq!(mapped.key(), "4");
assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
// Shifted case, but shift is true
let keystroke = Keystroke {
modifiers: Modifiers::control_shift(),
key: "$".to_string(),
key_char: None,
};
let mapped = mapper.map_key_equivalent(keystroke, true);
assert_eq!(mapped.inner().modifiers, Modifiers::control());
assert_eq!(mapped.key(), "4");
assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
// Windows style
let keystroke = Keystroke {
modifiers: Modifiers::control_shift(),
key: "4".to_string(),
key_char: None,
};
let mapped = mapper.map_key_equivalent(keystroke, true);
assert_eq!(mapped.inner().modifiers, Modifiers::control());
assert_eq!(mapped.inner().key, "$");
assert_eq!(mapped.key(), "4");
assert_eq!(*mapped.modifiers(), Modifiers::control_shift());
}
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,198 @@
//! System notifications as Windows toast notifications.
use std::cell::RefCell;
use std::collections::{HashMap, hash_map::DefaultHasher};
use std::hash::{Hash as _, Hasher as _};
use std::rc::Rc;
use futures::StreamExt as _;
use futures::channel::mpsc;
use gpui::{
ForegroundExecutor, SharedString, SystemNotification, SystemNotificationResponse, Task,
};
use windows::Data::Xml::Dom::XmlDocument;
use windows::Foundation::TypedEventHandler;
use windows::UI::Notifications::{
ToastActivatedEventArgs, ToastNotification, ToastNotificationManager, ToastNotifier,
};
use windows::core::{IInspectable, Interface as _, h};
type ResponseCallback = Rc<RefCell<Option<Box<dyn FnMut(SystemNotificationResponse)>>>>;
pub(crate) struct SystemNotificationState {
notifier: Option<ToastNotifier>,
active_toasts: HashMap<SharedString, ToastNotification>,
response_sender: mpsc::UnboundedSender<SystemNotificationResponse>,
response_receiver: Option<mpsc::UnboundedReceiver<SystemNotificationResponse>>,
callback: ResponseCallback,
_response_task: Option<Task<()>>,
}
impl SystemNotificationState {
pub(crate) fn new() -> Self {
let (response_sender, response_receiver) = mpsc::unbounded();
Self {
notifier: None,
active_toasts: HashMap::new(),
response_sender,
response_receiver: Some(response_receiver),
callback: Rc::new(RefCell::new(None)),
_response_task: None,
}
}
pub(crate) fn show(
&mut self,
has_package_identity: bool,
app_identity: Option<(&str, &str)>,
notification: SystemNotification,
) -> windows::core::Result<()> {
let Some(notifier) = self.notifier(has_package_identity, app_identity)? else {
return Ok(());
};
let document = toast_document(&notification)?;
let toast = ToastNotification::CreateToastNotification(&document)?;
// Windows caps toast tags at 64 characters (post-Creators Update),
// so hash the arbitrary GPUI tag down to a fixed-width value.
let tag = {
let mut hasher = DefaultHasher::new();
notification.tag.hash(&mut hasher);
format!("{:016x}", hasher.finish())
};
toast.SetTag(&tag.into())?;
let sender = self.response_sender.clone();
let response_tag = notification.tag.clone();
toast.Activated(&TypedEventHandler::<ToastNotification, IInspectable>::new(
move |_sender, arguments| {
let action_id = arguments
.as_ref()
.and_then(|arguments| arguments.cast::<ToastActivatedEventArgs>().ok())
.and_then(|arguments| arguments.Arguments().ok())
.filter(|arguments| !arguments.is_empty())
.map(|arguments| SharedString::from(arguments.to_string()));
sender
.unbounded_send(SystemNotificationResponse {
tag: response_tag.clone(),
action_id,
})
.ok();
Ok(())
},
))?;
if let Some(previous) = self.active_toasts.remove(&notification.tag) {
notifier.Hide(&previous)?;
}
notifier.Show(&toast)?;
self.active_toasts.insert(notification.tag, toast);
Ok(())
}
pub(crate) fn dismiss(&mut self, tag: &str) {
let Some(toast) = self.active_toasts.remove(tag) else {
return;
};
let Some(notifier) = &self.notifier else {
return;
};
if let Err(error) = notifier.Hide(&toast) {
log::warn!("failed to dismiss system notification: {error}");
}
}
pub(crate) fn on_response(
&mut self,
executor: &ForegroundExecutor,
callback: Box<dyn FnMut(SystemNotificationResponse)>,
) {
*self.callback.borrow_mut() = Some(callback);
if let Some(mut receiver) = self.response_receiver.take() {
let callback = self.callback.clone();
self._response_task = Some(executor.spawn(async move {
while let Some(response) = receiver.next().await {
// Take the callback out for the call: it may re-enter the
// platform (e.g. to dismiss the notification it was told
// about) or replace itself.
let taken = callback.borrow_mut().take();
if let Some(mut taken) = taken {
taken(response);
callback.borrow_mut().get_or_insert(taken);
}
}
}));
}
}
fn notifier(
&mut self,
has_package_identity: bool,
app_identity: Option<(&str, &str)>,
) -> windows::core::Result<Option<ToastNotifier>> {
if let Some(notifier) = &self.notifier {
return Ok(Some(notifier.clone()));
}
let notifier = if has_package_identity {
ToastNotificationManager::CreateToastNotifier()?
} else {
let Some((app_identifier, app_name)) = app_identity else {
log::warn!(
"cannot show a system notification without an app identity; \
call `App::set_app_identity` during startup"
);
return Ok(None);
};
register_app_user_model_id(app_identifier, app_name);
ToastNotificationManager::CreateToastNotifierWithId(&app_identifier.into())?
};
self.notifier = Some(notifier.clone());
Ok(Some(notifier))
}
}
fn toast_document(notification: &SystemNotification) -> windows::core::Result<XmlDocument> {
let document = XmlDocument::new()?;
let toast = document.CreateElement(h!("toast"))?;
document.AppendChild(&toast)?;
let visual = document.CreateElement(h!("visual"))?;
toast.AppendChild(&visual)?;
let binding = document.CreateElement(h!("binding"))?;
binding.SetAttribute(h!("template"), h!("ToastGeneric"))?;
visual.AppendChild(&binding)?;
for text in [&notification.title, &notification.body] {
let element = document.CreateElement(h!("text"))?;
element.SetInnerText(&text.as_ref().into())?;
binding.AppendChild(&element)?;
}
if !notification.actions.is_empty() {
let actions = document.CreateElement(h!("actions"))?;
toast.AppendChild(&actions)?;
for action in &notification.actions {
let action_element = document.CreateElement(h!("action"))?;
action_element.SetAttribute(h!("content"), &action.label.as_ref().into())?;
action_element.SetAttribute(h!("arguments"), &action.id.as_ref().into())?;
actions.AppendChild(&action_element)?;
}
}
let audio = document.CreateElement(h!("audio"))?;
audio.SetAttribute(h!("silent"), h!("true"))?;
toast.AppendChild(&audio)?;
Ok(document)
}
/// Registers the app's AUMID so toasts display correctly for an unpackaged app without a Start Menu shortcut.
fn register_app_user_model_id(app_identifier: &str, app_name: &str) {
let result = windows_registry::CURRENT_USER
.create(format!(r"Software\Classes\AppUserModelId\{app_identifier}"))
.and_then(|key| key.set_string("DisplayName", app_name));
if let Err(error) = result {
log::warn!("failed to register AppUserModelID; notifications may not display: {error}");
}
}
+87
View File
@@ -0,0 +1,87 @@
use std::{
cell::Cell,
ffi::{c_uint, c_void},
};
use gpui_util::ResultExt;
use windows::Win32::UI::WindowsAndMessaging::{
SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES, SYSTEM_PARAMETERS_INFO_ACTION,
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,
};
/// Windows settings pulled from SystemParametersInfo
/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow
#[derive(Default, Debug, Clone)]
pub(crate) struct WindowsSystemSettings {
pub(crate) mouse_wheel_settings: MouseWheelSettings,
}
#[derive(Default, Debug, Clone)]
pub(crate) struct MouseWheelSettings {
/// SEE: SPI_GETWHEELSCROLLCHARS
pub(crate) wheel_scroll_chars: Cell<u32>,
/// SEE: SPI_GETWHEELSCROLLLINES
pub(crate) wheel_scroll_lines: Cell<u32>,
}
impl WindowsSystemSettings {
pub(crate) fn new() -> Self {
let mut settings = Self::default();
settings.init();
settings
}
fn init(&mut self) {
self.mouse_wheel_settings.update();
}
pub(crate) fn update(&self, wparam: usize) {
match SYSTEM_PARAMETERS_INFO_ACTION(wparam as u32) {
SPI_GETWHEELSCROLLLINES | SPI_GETWHEELSCROLLCHARS => self.update_mouse_wheel_settings(),
_ => {}
}
}
fn update_mouse_wheel_settings(&self) {
self.mouse_wheel_settings.update();
}
}
impl MouseWheelSettings {
fn update(&self) {
self.update_wheel_scroll_chars();
self.update_wheel_scroll_lines();
}
fn update_wheel_scroll_chars(&self) {
let mut value = c_uint::default();
let result = unsafe {
SystemParametersInfoW(
SPI_GETWHEELSCROLLCHARS,
0,
Some((&mut value) as *mut c_uint as *mut c_void),
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
)
};
if result.log_err() != None && self.wheel_scroll_chars.get() != value {
self.wheel_scroll_chars.set(value);
}
}
fn update_wheel_scroll_lines(&self) {
let mut value = c_uint::default();
let result = unsafe {
SystemParametersInfoW(
SPI_GETWHEELSCROLLLINES,
0,
Some((&mut value) as *mut c_uint as *mut c_void),
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),
)
};
if result.log_err() != None && self.wheel_scroll_lines.get() != value {
self.wheel_scroll_lines.set(value);
}
}
}
+191
View File
@@ -0,0 +1,191 @@
use std::sync::OnceLock;
use anyhow::Context;
use gpui_util::ResultExt;
use windows::{
UI::{
Color,
ViewManagement::{UIColorType, UISettings},
},
Win32::{
Foundation::*, Graphics::Dwm::*, System::LibraryLoader::LoadLibraryA,
UI::WindowsAndMessaging::*,
},
core::{BOOL, PCSTR},
};
use crate::*;
use gpui::*;
pub(crate) trait HiLoWord {
fn hiword(&self) -> u16;
fn loword(&self) -> u16;
fn signed_hiword(&self) -> i16;
fn signed_loword(&self) -> i16;
}
impl HiLoWord for WPARAM {
fn hiword(&self) -> u16 {
((self.0 >> 16) & 0xFFFF) as u16
}
fn loword(&self) -> u16 {
(self.0 & 0xFFFF) as u16
}
fn signed_hiword(&self) -> i16 {
((self.0 >> 16) & 0xFFFF) as i16
}
fn signed_loword(&self) -> i16 {
(self.0 & 0xFFFF) as i16
}
}
impl HiLoWord for LPARAM {
fn hiword(&self) -> u16 {
((self.0 >> 16) & 0xFFFF) as u16
}
fn loword(&self) -> u16 {
(self.0 & 0xFFFF) as u16
}
fn signed_hiword(&self) -> i16 {
((self.0 >> 16) & 0xFFFF) as i16
}
fn signed_loword(&self) -> i16 {
(self.0 & 0xFFFF) as i16
}
}
pub(crate) unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize {
#[cfg(target_pointer_width = "64")]
unsafe {
GetWindowLongPtrW(hwnd, nindex)
}
#[cfg(target_pointer_width = "32")]
unsafe {
GetWindowLongW(hwnd, nindex) as isize
}
}
pub(crate) unsafe fn set_window_long(
hwnd: HWND,
nindex: WINDOW_LONG_PTR_INDEX,
dwnewlong: isize,
) -> isize {
#[cfg(target_pointer_width = "64")]
unsafe {
SetWindowLongPtrW(hwnd, nindex, dwnewlong)
}
#[cfg(target_pointer_width = "32")]
unsafe {
SetWindowLongW(hwnd, nindex, dwnewlong as i32) as isize
}
}
pub(crate) fn windows_credentials_target_name(url: &str) -> String {
format!("zed:url={}", url)
}
pub(crate) fn load_cursor(style: CursorStyle) -> Option<HCURSOR> {
static ARROW: OnceLock<SafeCursor> = OnceLock::new();
static IBEAM: OnceLock<SafeCursor> = OnceLock::new();
static CROSS: OnceLock<SafeCursor> = OnceLock::new();
static HAND: OnceLock<SafeCursor> = OnceLock::new();
static SIZEWE: OnceLock<SafeCursor> = OnceLock::new();
static SIZENS: OnceLock<SafeCursor> = OnceLock::new();
static SIZENWSE: OnceLock<SafeCursor> = OnceLock::new();
static SIZENESW: OnceLock<SafeCursor> = OnceLock::new();
static NO: OnceLock<SafeCursor> = OnceLock::new();
let (lock, name) = match style {
CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => (&IBEAM, IDC_IBEAM),
CursorStyle::Crosshair => (&CROSS, IDC_CROSS),
CursorStyle::PointingHand | CursorStyle::DragLink => (&HAND, IDC_HAND),
CursorStyle::ResizeLeft
| CursorStyle::ResizeRight
| CursorStyle::ResizeLeftRight
| CursorStyle::ResizeColumn => (&SIZEWE, IDC_SIZEWE),
CursorStyle::ResizeUp
| CursorStyle::ResizeDown
| CursorStyle::ResizeUpDown
| CursorStyle::ResizeRow => (&SIZENS, IDC_SIZENS),
CursorStyle::ResizeUpLeftDownRight => (&SIZENWSE, IDC_SIZENWSE),
CursorStyle::ResizeUpRightDownLeft => (&SIZENESW, IDC_SIZENESW),
CursorStyle::OperationNotAllowed => (&NO, IDC_NO),
_ => (&ARROW, IDC_ARROW),
};
Some(
*(*lock.get_or_init(|| {
HCURSOR(
unsafe { LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED) }
.log_err()
.unwrap_or_default()
.0,
)
.into()
})),
)
}
/// This function is used to configure the dark mode for the window built-in title bar.
pub(crate) fn configure_dwm_dark_mode(hwnd: HWND, appearance: WindowAppearance) {
let dark_mode_enabled: BOOL = match appearance {
WindowAppearance::Dark | WindowAppearance::VibrantDark => true.into(),
WindowAppearance::Light | WindowAppearance::VibrantLight => false.into(),
};
unsafe {
DwmSetWindowAttribute(
hwnd,
DWMWA_USE_IMMERSIVE_DARK_MODE,
&dark_mode_enabled as *const _ as _,
std::mem::size_of::<BOOL>() as u32,
)
.log_err();
}
}
#[inline]
pub(crate) fn logical_point(x: f32, y: f32, scale_factor: f32) -> Point<Pixels> {
Point {
x: px(x / scale_factor),
y: px(y / scale_factor),
}
}
// https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/apply-windows-themes
#[inline]
pub(crate) fn system_appearance() -> Result<WindowAppearance> {
let ui_settings = UISettings::new()?;
let foreground_color = ui_settings.GetColorValue(UIColorType::Foreground)?;
// If the foreground is light, then is_color_light will evaluate to true,
// meaning Dark mode is enabled.
if is_color_light(&foreground_color) {
Ok(WindowAppearance::Dark)
} else {
Ok(WindowAppearance::Light)
}
}
#[inline(always)]
fn is_color_light(color: &Color) -> bool {
((5 * color.G as u32) + (2 * color.R as u32) + color.B as u32) > (8 * 128)
}
pub(crate) fn with_dll_library<R, F>(dll_name: PCSTR, f: F) -> Result<R>
where
F: FnOnce(HMODULE) -> Result<R>,
{
let library = unsafe {
LoadLibraryA(dll_name).with_context(|| format!("Loading dll: {}", dll_name.display()))?
};
let result = f(library);
unsafe {
FreeLibrary(library)
.with_context(|| format!("Freeing dll: {}", dll_name.display()))
.log_err();
}
result
}
+119
View File
@@ -0,0 +1,119 @@
use std::{
sync::LazyLock,
time::{Duration, Instant},
};
use anyhow::{Context, Result};
use gpui::FrameRequestSource;
use gpui_util::ResultExt;
use windows::Win32::{
Foundation::HWND,
Graphics::Dwm::{DWM_TIMING_INFO, DwmFlush, DwmGetCompositionTimingInfo},
System::Performance::QueryPerformanceFrequency,
};
static QPC_TICKS_PER_SECOND: LazyLock<u64> = LazyLock::new(|| {
let mut frequency = 0;
// On systems that run Windows XP or later, the function will always succeed and
// will thus never return zero.
unsafe { QueryPerformanceFrequency(&mut frequency).unwrap() };
frequency as u64
});
const VSYNC_INTERVAL_THRESHOLD: Duration = Duration::from_millis(1);
const DEFAULT_VSYNC_INTERVAL: Duration = Duration::from_micros(16_666); // ~60Hz
pub(crate) struct VSyncProvider {
interval: Duration,
f: Box<dyn Fn() -> bool>,
}
impl VSyncProvider {
pub(crate) fn new() -> Self {
let interval = get_dwm_interval()
.context("Failed to get DWM interval")
.log_err()
.unwrap_or(DEFAULT_VSYNC_INTERVAL);
let f = Box::new(|| unsafe { DwmFlush().is_ok() });
Self { interval, f }
}
pub(crate) fn wait_for_vsync(&self) -> FrameRequestSource {
let vsync_start = Instant::now();
let wait_succeeded = (self.f)();
let elapsed = vsync_start.elapsed();
// DwmFlush and DCompositionWaitForCompositorClock returns very early
// instead of waiting until vblank when the monitor goes to sleep or is
// unplugged (nothing to present due to desktop occlusion). We use 1ms as
// a threshold for the duration of the wait functions and fallback to
// Sleep() if it returns before that. This could happen during normal
// operation for the first call after the vsync thread becomes non-idle,
// but it shouldn't happen often.
if !wait_succeeded || elapsed < VSYNC_INTERVAL_THRESHOLD {
log::trace!("VSyncProvider::wait_for_vsync() took less time than expected");
std::thread::sleep(self.interval);
FrameRequestSource::LocalSchedule
} else {
FrameRequestSource::NativeCallback
}
}
}
fn get_dwm_interval() -> Result<Duration> {
let mut timing_info = DWM_TIMING_INFO {
cbSize: std::mem::size_of::<DWM_TIMING_INFO>() as u32,
..Default::default()
};
unsafe { DwmGetCompositionTimingInfo(HWND::default(), &mut timing_info) }?;
let interval = retrieve_duration(timing_info.qpcRefreshPeriod, *QPC_TICKS_PER_SECOND);
// Check for interval values that are impossibly low. A 29 microsecond
// interval was seen (from a qpcRefreshPeriod of 60).
if interval < VSYNC_INTERVAL_THRESHOLD {
Ok(retrieve_duration(
timing_info.rateRefresh.uiDenominator as u64,
timing_info.rateRefresh.uiNumerator as u64,
))
} else {
Ok(interval)
}
}
#[inline]
fn retrieve_duration(counts: u64, ticks_per_second: u64) -> Duration {
let ticks_per_microsecond = ticks_per_second / 1_000_000;
Duration::from_micros(counts / ticks_per_microsecond)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn successful_compositor_wait_reports_native_callback() {
let provider = VSyncProvider {
interval: Duration::ZERO,
f: Box::new(|| {
std::thread::sleep(VSYNC_INTERVAL_THRESHOLD * 2);
true
}),
};
assert_eq!(
provider.wait_for_vsync(),
FrameRequestSource::NativeCallback
);
}
#[test]
fn failed_compositor_wait_reports_local_schedule_even_after_threshold() {
let provider = VSyncProvider {
interval: Duration::ZERO,
f: Box::new(|| {
std::thread::sleep(VSYNC_INTERVAL_THRESHOLD * 2);
false
}),
};
assert_eq!(provider.wait_for_vsync(), FrameRequestSource::LocalSchedule);
}
}
File diff suppressed because it is too large. Load diff
+53
View File
@@ -0,0 +1,53 @@
use std::ops::Deref;
use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::HCURSOR};
#[derive(Debug, Clone, Copy)]
pub(crate) struct SafeCursor {
raw: HCURSOR,
}
unsafe impl Send for SafeCursor {}
unsafe impl Sync for SafeCursor {}
impl From<HCURSOR> for SafeCursor {
fn from(value: HCURSOR) -> Self {
SafeCursor { raw: value }
}
}
impl Deref for SafeCursor {
type Target = HCURSOR;
fn deref(&self) -> &Self::Target {
&self.raw
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct SafeHwnd {
raw: HWND,
}
impl SafeHwnd {
pub(crate) fn as_raw(&self) -> HWND {
self.raw
}
}
unsafe impl Send for SafeHwnd {}
unsafe impl Sync for SafeHwnd {}
impl From<HWND> for SafeHwnd {
fn from(value: HWND) -> Self {
SafeHwnd { raw: value }
}
}
impl Deref for SafeHwnd {
type Target = HWND;
fn deref(&self) -> &Self::Target {
&self.raw
}
}