44 Commits
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
faumarayandClaude Opus 5.5 da6aafaf1d windows: release through Gitea Actions
Windows release / build (push) Successful in 3m37s
Windows release / publish (push) Successful in 15s
.gitea/workflows/windows-release.yml builds the Windows release in the
repository's own Nix dev shell (pinned Nix installer, checked by hash),
tests, packages, and on a tag windows-v<version> publishes the zip and
its .sha256 to a Gitea release with windows/release-notes/<version>.md.
Run by hand it only builds. As upstream's workflow: the job that runs
fetched code holds no token that can write; only the publishing job sees
RELEASE_TOKEN, and it runs curl and jq on the first job's artifact.

rust-toolchain.toml pins the toolchain the release is built with.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:54:49 +03:00
faumarayandClaude Opus 5.5 363caf912a windows: a failed check of the state root is made again (0.1.0-pre.2)
The once-per-process guard recorded the root before ensure_root ran. A
first check that failed (the service log's create_all ignores its error)
left the root marked as checked, so run()'s create_all skipped the check
and the service went on with a root it could not secure, and runs what
is under its bin\ as SYSTEM. Now only a check that passed is recorded,
under the lock, and a failed one fails again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:51:32 +03:00
faumarayandClaude Opus 5.5 e84d42a10c windows: 0.1.0-pre.1: README, install.cmd, release packaging
- README for the Windows port: what this release does, what has been
  verified and how, install, first run, who may change what, caveats.
- install.cmd / uninstall.cmd ask for administrator rights and run the
  service's own install/uninstall.
- tools/package.sh builds the release zip with every component staged
  and pinned; tools/wine-install-test.sh exercises install, the pipe and
  uninstall under Wine's Service Control Manager.
- Release profile: thin LTO, stripped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:41:53 +03:00
faumarayandClaude Opus 5.5 8af7b2e628 windows: authorize streamed requests, self-removal on uninstall, tun on
- Every request is authorized before it is handled, including `logs -f`,
  which skipped the check.
- The state root is checked once per process: a second check under Wine
  moved the live root (and its log) aside.
- uninstall removes Program Files after it exits: cmd got a garbled
  quoted command line; it now runs raw, outside the folder, windowless.
- install no longer fails when the first start does; it says how to start.
- `proxy-ctl proxy tun on` also turns on proxy.tun.enable.
- build-tg-ws-proxy.sh resolves its output path before changing directory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:41:53 +03:00
faumarayandClaude Opus 5.5 28cc7b2cbe windows: install into Program Files, seed components, log as a service
install copies the release into %ProgramFiles%\ProxySuite (upgrading in
place when the service exists), registers it there, and puts it on the
system PATH: a copy in Downloads could be replaced by any user, and the
service runs it as SYSTEM. uninstall removes the service, the PATH
entry and the program files, and leaves the state.

At every start the service copies the release's components into bin\
when they are newer, staged and verified file by file, and only from a
service running in Program Files. Under the Service Control Manager it
logs to logs\service.log, reports StartPending until the API listens,
and a failed start as a service-specific error.

zapret refuses to start while Flowseal's, the win bundle's or
GoodbyeDPI's service holds WinDivert, and says which to remove.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:10:26 +03:00
faumarayandClaude Opus 5.5 d1bce9db94 windows: zapret site names and addresses are validated
A zapret2 domain is split into winws2's arguments: one carrying
whitespace could add an argument of its own (a --lua-init running as
SYSTEM). Names and addresses are checked in validation and filtered
again where the command line is built.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:07:38 +03:00
faumarayandClaude Opus 5.5 bceb754e65 windows: zapret2 on winws2 with nfqws2-keenetic's strategies
ps-core::zapret2 reads nfqws2-keenetic's nfqws2.conf and patches it as
upstream's sources.nix does, expands the hostlist markers as zapret2's
list.sh does (autohostlist with its detector settings, the configured
domains), fills circular's unset detector settings from autoHostlist,
merges the extra ports into the profiles that tell traffic by protocol,
and gives winws2 WinDivert port filters in place of the queue's rules.
The service runs it with the learned list in a directory labelled Low
integrity, where winws2 can still write once it drops to Low. winws2
verifies the whole command line under Wine.

detect.lua, z2k and the cutoff probe are not there yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 00:04:21 +03:00
faumarayandClaude Opus 5.5 9b0d7021f9 windows: zapret-discord-youtube and tg-ws-proxy
zapret: Flowseal's release run as its service.bat runs it: the preset's
winws.exe line (continuations, cmd's caret escapes, %BIN%, %LISTS%, the
game filter) as winws's arguments, the user's domains and addresses in
the lists upstream's module puts them in (kept in the service's own run
directory, the verified release untouched), TCP timestamps on, and
zapret's sites in the proxy's direct list. tools/winws-dry-run.sh has
the release's own winws.exe verify every preset's arguments under Wine:
all 22, both game filters.

tg-ws-proxy: Flowseal's headless proxy on the embeddable CPython 3.12
with hash-pinned win_amd64 wheels (tools/build-tg-ws-proxy.sh), run with
upstream's flags; its relay goes direct under the TUN. Runs under Wine.

proxy-ctl: zapret status|on|off|preset|game-filter, components
list|install.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:55:45 +03:00
faumarayandClaude Opus 5.5 817de77d28 windows: wine-e2e reads the logs before matching them
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:35:15 +03:00
faumarayandClaude Opus 5.5 68b496cafa windows: the component manager, verified programs, a Wine test
components.json pins sing-box, XRay, Flowseal's zapret, bol-van's
winws2 bundle with nfqws2-keenetic's strategies, and tg-ws-proxy (built
with the release): release assets by archive hash, commit snapshots by
the hash of every file taken. The service installs them (admin only),
staged and swapped in, refusing archive paths that leave the directory,
and checks each program against the hashes recorded at install before
running it. stage-components does the same for building a release.

The state root is created with its protected descriptor in one call,
or, existing, checked through a handle that does not follow links.

tools/wine-e2e.sh runs the Windows build under Wine: the service, the
named pipe, impersonation, the component check, rendering and the
supervisor all work; Wine lacks an iphlpapi call sing-box needs, so
proxying itself needs real Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:33:55 +03:00
faumarayandClaude Opus 5.5 b878dd93db windows: an OWNER RIGHTS entry Windows accepts
An empty access mask is refused as an invalid ACL; read-control alone
still takes the owner's implicit WRITE_DAC away.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:19:50 +03:00
faumarayandClaude Opus 5.5 cd0bcae4c9 windows: never adopt a state directory someone else made
A root not owned by SYSTEM or Administrators is moved aside; the root
gets SYSTEM as owner and an OWNER RIGHTS entry, so owning a file below
it grants nothing. Adds the pinned component manifest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:19:19 +03:00
faumarayandClaude Opus 5.5 d678976c2d windows: protect the state directory, names that become files, logs
The state directory gets a protected DACL (SYSTEM and Administrators)
at every start; on Windows programs run only from its bin\, never from
PATH; rule-set and geodata names are validated before they become file
names, and checked again where they do; logs need the secrets scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:16:40 +03:00
faumarayandClaude Opus 5.5 41c8ed4406 windows: the service, its API and proxy-ctl
ps-ipc: line-delimited JSON over a named pipe whose ACL admits SYSTEM,
Administrators and (with userControl) the interactive user; the caller
is identified by impersonation, never by what it claims. A Unix socket
stands in off Windows.

ps-service (proxy-suite-service.exe): a Windows service, or --console.
Keeps the configuration with revisions, runtime state and generated
secrets; renders, checks with sing-box check before replacing what
runs, and supervises the backends (restart with backoff, start limit,
logs in a ring and a file, a Job Object on Windows). Enforces scopes,
admin-only edits and secret redaction that round-trips. Fetches
subscriptions and rule sets through the proxy or directly with
upstream's redirect rules, on timers.

ps-ctl (proxy-ctl.exe): status, restart, logs [-f], config get/set/
validate, and proxy on/off, outbounds, pin, mode, subs, rules,
rulesets, tun and config.

An end-to-end test runs it all offline: a sing-box Shadowsocks server,
the service, proxy-ctl adding the outbound, a page fetched through the
local proxy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 23:13:19 +03:00
faumarayandClaude Opus 5.5 918cdc9a75 windows: rules and per-app profiles fail closed
A rule, an outbound's own routing or a per-app profile whose outbound is
not running blocks what it matches instead of letting it fall through.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:58:28 +03:00
faumarayandClaude Opus 5.5 130c020151 windows: refuse loopback through the proxy; Clash API always has a secret
Per-app rules naming an outbound that is not running are left out with a
warning instead of failing the start, and failover renders as sing-box's
own urltest until the service drives it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:57:06 +03:00
faumarayandClaude Opus 5.5 3665f7f5a0 windows: render sing-box and hybrid configs
ps-core::render builds what upstream's start scripts assemble with bash
and jq: every outbound (declared, subscriptions, SSH, Tor, WARP and AWG
as WireGuard endpoints, joiners, wireproxy hops), chains, groups, the
pin and the 'proxy' selector per selection mode, routing sections by
priority with route modes and the DNS mirror, rule sets, TUN with fake
IP, the Clash API, per-app rules by program, and the hybrid XRay
sidecar. Integration tests run sing-box check and xray -test on the
results.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:51:30 +03:00
faumarayandClaude Opus 5.5 c01538fec9 windows: raw backend JSON is always admin-only; WireGuard profiles
Telling path-shaped values from addresses on Windows (drive letters,
UNC, device paths, sockets) is too easy to get wrong, so raw sing-box
and XRay JSON now needs an administrator outright. ps-core::wg parses
WireGuard/AmneziaWG profiles into sing-box endpoints, as upstream's
warp_outbound.py does. Routing rules gain name, priority and disabled
for proxy-ctl proxy rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:44:31 +03:00
faumarayandClaude Opus 5.5 96958c4e61 windows: close gaps in the admin-only edit check
Null-to-object changes are looked into, keys named just 'file' count,
raw inbound XRay JSON is admin-only outright, and raw outbound JSON is
admin-only when it runs Tor or holds a path-like value.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:41:57 +03:00
faumarayandClaude Opus 5.5 77d4cefe0e windows: share-link and subscription parsing, admin-only edits
ps-core::links ports upstream's proxy_url_parsers.py and proxy_parsing.py:
every scheme, each backend's refusals, XRay rendering, subscription
decoding, tags and the server checks. Upstream's build-outbound tests
are ported case for case, and tools/parity/links.py runs ~750 links
through both implementations: no differences.

config::privileged_changes names the edits only an administrator may
make: anything that runs a program, passes arguments through, or names
a local file, since the service runs as LocalSystem. Names that become
paths or service names are validated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:38:56 +03:00
faumarayandClaude Opus 5.5 c837db1c18 windows: workspace, dev shell and the config model
Start of the native Windows port. windows/ holds a Rust workspace; this
first piece is ps-core's model of the services.proxy-suite option tree,
with upstream's names and defaults, Windows-only additions documented,
validation ported from the module's assertions, and the derived tags and
loopback ports the tunnels add.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-26 22:28:10 +03:00
131 changed files with 44880 additions and 0 deletions

No files matched your search

+161
View File
@@ -0,0 +1,161 @@
name: Windows release
# The Windows port (windows/). On a tag windows-v<version> it builds the release zip and
# publishes it as a Gitea release, with the notes in windows/release-notes/<version>.md. Run
# by hand, it only builds: the zip is the run's artifact.
#
# Two jobs, as upstream's dependency updates: the one that runs fetched code (crates,
# components, wheels, the Nix closure) holds no token that can write. Only the publishing job
# sees RELEASE_TOKEN (write:repository), and it runs nothing it fetched: curl and jq on the
# first job's artifact. Gitea ignores `permissions:`; they are here to say what each job needs.
on:
push:
tags: ["windows-v*"]
workflow_dispatch:
permissions:
contents: read
jobs:
build:
runs-on: ubuntu-24.04
timeout-minutes: 150
env:
# Single-user Nix without a daemon: the job's container has no init to run one, nor
# the namespaces a build sandbox needs. Set for the job, so the installer has it too.
NIX_CONFIG: |
experimental-features = nix-command flakes
sandbox = false
build-users-group =
defaults:
run:
shell: bash
steps:
# Full history: the flake is windows/ inside this repository, fetched by Nix as git.
- name: Check out
uses: https://github.com/actions/checkout@v4
with:
fetch-depth: 0
persist-credentials: false
- name: Check the version
working-directory: windows
run: |
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
if [[ "$GITHUB_REF" == refs/tags/* ]]; then
[[ "$GITHUB_REF_NAME" == "windows-v$version" ]] ||
{ echo "::error::the tag is $GITHUB_REF_NAME, but windows/Cargo.toml says $version"; exit 1; }
[ -f "release-notes/$version.md" ] ||
{ echo "::error::no windows/release-notes/$version.md"; exit 1; }
fi
echo "Proxy Suite for Windows $version"
# Pinned: this installer checks the hash of the Nix it downloads, and is checked here.
- name: Install Nix
env:
NIX_VERSION: 2.34.9
NIX_INSTALL_SHA256: a03ce2e9eaf4ea1560260b9a93e311dbaf589d28fb5c9318f8d9e768ee6339d8
run: |
set -euo pipefail
# The runner may run as root (no sudo in the image) or as a user with sudo.
as_root() { if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi; }
if ! command -v xz >/dev/null 2>&1; then
as_root apt-get update -qq
as_root apt-get install -y -qq xz-utils
fi
as_root install -d -m 0755 -o "$(id -u)" -g "$(id -g)" /nix
tmp=$(mktemp -d)
curl -sSfL -o "$tmp/install" "https://releases.nixos.org/nix/nix-$NIX_VERSION/install"
echo "$NIX_INSTALL_SHA256 $tmp/install" | sha256sum -c --quiet
USER=${USER:-$(id -un)} sh "$tmp/install" --no-daemon --no-modify-profile --no-channel-add
echo "$HOME/.nix-profile/bin" >> "$GITHUB_PATH"
- name: Dev shell and Rust toolchain
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 --locked
- name: Package
working-directory: windows
run: nix develop --command tools/package.sh
- name: Collect
working-directory: windows
run: |
set -euo pipefail
version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1)
mkdir -p ../release
cp "dist/ProxySuite-$version-windows-x64.zip" "dist/ProxySuite-$version-windows-x64.zip.sha256" ../release/
if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi
- name: Upload
uses: https://github.com/actions/upload-artifact@v4
with:
name: windows-release
path: release/
if-no-files-found: error
publish:
needs: build
if: startsWith(github.ref, 'refs/tags/windows-v')
runs-on: ubuntu-24.04
timeout-minutes: 20
permissions:
contents: write
defaults:
run:
shell: bash
steps:
- name: Download
uses: https://github.com/actions/download-artifact@v4
with:
name: windows-release
path: release
# The release for the tag, made if it is not there yet (a pre-release for a version with
# a "-"), and its assets, replacing any of the same name, so a rerun is harmless.
- name: Publish
env:
TOKEN: ${{ secrets.RELEASE_TOKEN }}
API: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}
TAG: ${{ github.ref_name }}
SHA: ${{ github.sha }}
run: |
set -euo pipefail
as_root() { if [ "$(id -u)" -eq 0 ]; then "$@"; else sudo "$@"; fi; }
if ! command -v jq >/dev/null 2>&1; then
as_root apt-get update -qq
as_root apt-get install -y -qq jq
fi
[ -n "$TOKEN" ] || { echo "::error::the RELEASE_TOKEN secret is not set"; exit 1; }
api() { curl -sS --fail-with-body -H "Authorization: token $TOKEN" "$@"; }
version=${TAG#windows-v}
code=$(curl -sS -o found.json -w '%{http_code}' -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG")
case $code in
200) id=$(jq -r .id found.json) ;;
404)
pre=false
[[ "$version" == *-* ]] && pre=true
id=$(jq -n --arg tag "$TAG" --arg sha "$SHA" --arg name "Proxy Suite for Windows $version" \
--rawfile body release/notes.md --argjson pre "$pre" \
'{tag_name: $tag, target_commitish: $sha, name: $name, body: $body, prerelease: $pre, draft: false}' |
api -H 'Content-Type: application/json' --data-binary @- "$API/releases" | jq -r .id)
echo "made the release for $TAG" ;;
*) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;;
esac
for f in release/*.zip release/*.sha256; do
name=$(basename "$f")
for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do
api -X DELETE "$API/releases/$id/assets/$old" >/dev/null
done
api -F "attachment=@$f" "$API/releases/$id/assets?name=$name" >/dev/null
echo "uploaded $name"
done
echo "$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/releases/tag/$TAG"
+2
View File
@@ -0,0 +1,2 @@
target/
dist/
+9065
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -0,0 +1,46 @@
[workspace]
resolver = "2"
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.2.0-pre.1"
edition = "2024"
license = "MIT"
repository = "https://git.faumaray.com/faumaray/proxy-suite-flake"
[workspace.dependencies]
anyhow = "1"
base64 = "0.22"
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
regex = "1"
thiserror = "2"
percent-encoding = "2"
ipnet = "2"
indexmap = { version = "2", features = ["serde"] }
tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] }
clap = { version = "4.6", features = ["derive"] }
reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] }
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
windows-service = "0.8"
windows-sys = "0.61"
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
rand = "0.9"
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" }
+88
View File
@@ -0,0 +1,88 @@
# Proxy Suite for Windows: design
The Linux tree (`modules/`, `pkgs/`, `scripts/`) stays as upstream has it, so `main` keeps
merging from FUFSoB/proxy-suite-flake. Everything Windows-specific lives under `windows/`.
## Why a rewrite and not a port
Upstream's logic sits in Nix: the module evaluates `services.proxy-suite` into bash + jq start
scripts, systemd units, nftables rules and polkit rules. None of that runs on Windows, and Nix
does not either. What carries over is the *behaviour* (option semantics, link parsing, config
shape, routing order, group/detour resolution, CLI verbs, GUI tabs), not the code. The Python
pieces (`scripts/proxy_url_parsers.py`, `proxy_parsing.py`, …) are the reference
implementation: the Rust port is tested against them differentially.
## Shape
One Rust workspace, four binaries, one library:
| Crate | Binary | Role |
|---|---|---|
| `ps-core` | — | Config model (the `services.proxy-suite` tree as serde types, same names), validation, link and subscription parsing, sing-box / XRay config rendering, zapret strategy rendering, AmneziaWG/WARP config handling, share links. Pure: no I/O beyond what callers hand it. |
| `ps-ipc` | — | The service API: request/response types and the framed-JSON transport (named pipe on Windows, Unix socket elsewhere, so the stack runs on Linux for development). |
| `ps-service` | `proxy-suite-service.exe` | Runs as a Windows service (LocalSystem). Owns the config and state, renders backend configs, supervises the backend processes (a Job Object kills them with it), runs the timers (subscriptions, rule sets, autoProxy), talks to sing-box's Clash API, applies the kill switch, serves the API. `--console` runs it in the foreground. |
| `ps-ctl` | `proxy-ctl.exe` | Upstream's CLI verbs over the API. |
| `ps-gui` | `proxy-suite.exe` | GPUI window and tray icon. Every setting is editable here; it never writes files itself, it sends edits to the service, which validates them. |
### Config and state
- `%ProgramData%\ProxySuite\config.json`: the whole option tree, **with upstream's exact
camelCase names** (`proxy.listener.port`, `zapret.zapret2.autoHostlist.failThreshold` …), so
`docs/options/*.md` stays the reference and differential tests compare like with like. Written only by the service,
after validation, atomically. The GUI and `proxy-ctl config get/set/edit` go through the API.
Upstream's split between *declared* (Nix) and *runtime* additions disappears: everything is
runtime-editable. Secrets (`urlFile`, `passwordFile` …) become plain fields kept in a
separate `secrets.json` readable only by SYSTEM and Administrators (and the API returns them
only to callers with the `secrets` scope).
- `%ProgramData%\ProxySuite\state\`: pins, disabled outbounds, route-mode override, subscription
caches, rule-set downloads, autoProxy results, AWG/WARP registrations, inbound users' traffic.
- `%ProgramData%\ProxySuite\bin\<component>\<version>\`: backend binaries, fetched by the
component manager from pinned release URLs with pinned SHA-256s (see below).
- `%ProgramData%\ProxySuite\logs\`: one rotating log per unit, also tailed over the API.
### Units
The service keeps upstream's unit names so `proxy-ctl status`/`logs` read the same:
| Unit | Windows process | Notes |
|---|---|---|
| `proxy-suite-socks` | `sing-box.exe` (or `xray.exe`) | mixed inbound on `listener`; Clash API on loopback |
| `proxy-suite-tun` | `sing-box.exe` | TUN through wintun, `auto_route`, `strict_route` |
| `proxy-suite-xray-sidecar` | `xray.exe` | hybrid backend's XRay-only outbounds |
| `proxy-suite-zapret` | `winws.exe` / `winws2.exe` | a child with the exact arguments Flowseal's / bol-van's Windows strategies use; never their `service.bat`, which would register a competing `zapret` service. zapret v1 and zapret2 are mutually exclusive, and other WinDivert users (GoodbyeDPI) conflict: validation says so |
| `proxy-suite-awg-<p>` | AmneziaWG tunnel | global VPN profile; amneziawg-windows installs each tunnel as its own Windows service, so this unit kind is a *managed service*, not a child (decided once the AWG research is in) |
| `proxy-suite-awg-ob-<p>` | `wireproxy-awg.exe` | AWG as a SOCKS outbound |
| `proxy-suite-tor` | `tor.exe` (+ lyrebird/snowflake) | outbound tagged `tor` |
| `proxy-suite-ssh-proxy` | `ssh.exe -D` (Windows OpenSSH) | outbound tagged `ssh-proxy` |
| `proxy-suite-tg-ws-proxy` | `tg-ws-proxy.exe` | |
| `proxy-suite-wl-<name>` | whitelist-bypass | creators/joiners |
| `proxy-suite-inbounds` | `xray.exe` | server listeners |
| `proxy-suite-killswitch` | in-service | sing-box `strict_route` first if it holds on Windows; WFP filters as the follow-up |
TProxy, cgroup/netns per-app routing and proxychains have no Windows counterpart. Per-app
routing becomes sing-box `process_name` / `process_path` rules on the TUN, plus a
`proxy-ctl apps run` that sets `HTTP(S)_PROXY`/`ALL_PROXY` for programs that honour them.
The system proxy (WinINet, per user) is set by the GUI for its user, not by the service.
### Who may change things
"Everything editable in the app" means no UAC prompt per edit: the API pipe grants SYSTEM and
Administrators full access and, by default, the interactive user (`S-1-5-4`). `userControl`
maps onto this: `userControl.enable = false` keeps the pipe to Administrators, and
`userControl.scopes` limit what non-admin callers may do, as upstream's do.
### Component manager
Binaries are not vendored into git. `ps-core::components` holds a manifest: name, version,
URL, SHA-256, archive layout, files to keep. The service downloads into `bin\`, verifies, and
switches atomically; the GUI's Components page shows versions and offers updates. Each manifest
entry follows its project's own Windows release (zapret's WinDivert driver and files exactly
as Flowseal / bol-van ship them).
### Testing on the Linux dev box
- `ps-core` unit tests, plus differential tests against upstream's Python parsers.
- Rendered configs are checked with `sing-box check` and `xray run -test` (from nixpkgs).
- `ps-service --console` runs on Linux against Linux sing-box/xray, so the API, supervisor,
timers and CLI are exercised end to end without Windows.
- Windows binaries are cross-compiled (see `README.md` for the toolchain).
+194
View File
@@ -0,0 +1,194 @@
# Proxy Suite for Windows
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 from its desktop app (window and
tray icon) or with `proxy-ctl`, as upstream's is.
> [!WARNING]
> **Pre-release.** Built and tested on Linux and under Wine, **never yet run on real Windows.**
> Read [what has been verified](#what-has-been-verified) before relying on it, and please
> report what happens on yours.
> [!IMPORTANT]
> For study and research only, as upstream: learning how proxies, tunnels and traffic
> routing work. No warranty.
## What it does (this release)
| | |
|---|---|
| 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, 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: 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
| Part | How |
|---|---|
| Share-link and subscription parsing | upstream's tests, ported; ~750 links through upstream's Python and this, identical results |
| sing-box and XRay configs | rendered for many setups and accepted by `sing-box check` and `xray run -test` |
| Service, API, `proxy-ctl` | end to end on Linux: a real sing-box Shadowsocks server, the service, `proxy-ctl` adding the outbound, a page fetched through the local proxy |
| Windows build: service, named pipe, its ACL, caller identification, component hashes, supervisor | under Wine (`tools/wine-e2e.sh`) |
| zapret arguments | **every** preset of the release, both game filters, checked by the release's own `winws.exe --dry-run` under Wine (`tools/winws-dry-run.sh`) |
| zapret2 arguments | checked by `winws2.exe --dry-run` under Wine |
| 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, 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, 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.
Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a
packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first:
Flowseal's own `zapret` service (its `service.bat` → Remove Services) or GoodbyeDPI — the
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"
proxy-ctl proxy on
proxy-ctl status
# Then point apps (or Windows: Settings → Network → Proxy) at 127.0.0.1:1080.
# Or a subscription:
proxy-ctl proxy subs add https://provider.example/sub/token
# zapret, Flowseal's presets:
proxy-ctl zapret on
proxy-ctl zapret preset "general (ALT9)"
proxy-ctl zapret game-filter all
# zapret2 instead:
proxy-ctl config get > config.json # set "zapret": { "enable": true, "engine": "zapret2" }
proxy-ctl config set config.json
# Telegram's WebSocket proxy:
proxy-ctl config get > config.json # set "tgWsProxy": { "enable": true }
proxy-ctl config set config.json
proxy-ctl logs proxy-suite-tg-ws-proxy # its tg:// link and secret
proxy-ctl logs -f # everything, following
proxy-ctl --help
```
## The configuration
The app's **Settings** page edits it whole, and checks it with the service before saving.
`proxy-ctl config get` prints it, `proxy-ctl config set <file>` replaces it (checked first; a
bad one changes nothing), `proxy-ctl config validate <file>` only checks. It is upstream's
option tree as JSON, so [upstream's option reference](../docs/options/index.md) describes it:
`services.proxy-suite.proxy.listener.port` is `{"proxy": {"listener": {"port": …}}}`.
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 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`
- inline `config` text where upstream only takes a file (AmneziaWG, WARP)
## Who may change what
The service runs as LocalSystem. Its settings are meant to be edited by whoever uses the
machine, so — **unlike upstream, where changes need root** — `userControl` defaults to on
for the signed-in user, with every scope. On a shared computer, set
`userControl.scopes` (or turn `userControl.enable` off) as an administrator.
Whatever the scopes, these always need an administrator: anything that makes the service run
a program, pass arguments to one, or read or write a file of the caller's choosing — every
`*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`,
`nfqwsArgs`, zapret2's `profiles` and `blobs`, `allowConfigHooks`, and `userControl` itself —
and installing components. Secrets (links, passwords) are hidden from callers without the
`secrets` scope, and survive a round trip through `config get`/`config set` unchanged.
## Caveats
- **TUN and zapret together**: upstream keeps zapret's packets off the TUN interface, which
this release does not do yet. Use one or the other.
- zapret2 learns with nfqws2's own detector, not upstream's extended one; z2k's strategies are
not there yet.
- 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
The release carries every program it runs, each pinned by version and hash
([`components.json`](components.json)), and the service checks each against the hashes
recorded at install before running it. `proxy-ctl components` lists them;
`proxy-ctl components install [name…]` fetches and verifies them again (administrator).
See [`THIRD-PARTY.md`](THIRD-PARTY.md) for their licenses and sources.
## Building
On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`), then
```sh
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).
Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version`
in `Cargo.toml`, add `release-notes/<version>.md`, push a tag `windows-v<version>`. The
workflow tests, packages and publishes the zip and its `.sha256` with the `RELEASE_TOKEN`
secret (a token with `write:repository`). Run by hand, it only builds.
+130
View File
@@ -0,0 +1,130 @@
{
"components": {
"sing-box": {
"version": "1.14.4",
"license": "GPL-3.0-or-later",
"homepage": "https://github.com/SagerNet/sing-box",
"sources": [
{
"url": "https://github.com/SagerNet/sing-box/releases/download/v1.14.4/sing-box-1.14.4-windows-amd64.zip",
"sha256": "99185d75d314a07dbba4a130c8ad986cbeb629a07927975636b341ca61f991df",
"strip": "sing-box-1.14.4-windows-amd64/"
}
]
},
"xray": {
"version": "26.10.21",
"license": "MPL-2.0",
"homepage": "https://github.com/XTLS/Xray-core",
"sources": [
{
"url": "https://github.com/XTLS/Xray-core/releases/download/v26.10.21/Xray-windows-64.zip",
"sha256": "fc58c39ee2f2717b4c54d28d374362389e5319b20ae44aea76ea45a5243ec827",
"strip": "",
"include": [
"xray.exe",
"geoip.dat",
"geosite.dat",
"LICENSE"
]
}
]
},
"zapret": {
"version": "1.10.4",
"license": "MIT",
"homepage": "https://github.com/Flowseal/zapret-discord-youtube",
"sources": [
{
"url": "https://github.com/Flowseal/zapret-discord-youtube/releases/download/1.10.4/zapret-discord-youtube-1.10.4.zip",
"sha256": "291af673bd0238506f9548e0e94ca0abf244000f4c9a06960544fb01c5f97b34",
"strip": "zapret-discord-youtube-1.10.4/",
"exclude": [
"service.bat",
"utils/"
]
}
]
},
"zapret2": {
"version": "2026.10.21+de9795d",
"license": "MIT",
"homepage": "https://github.com/bol-van/zapret-win-bundle",
"sources": [
{
"url": "https://codeload.github.com/bol-van/zapret-win-bundle/zip/de9795d71287fdb21cf8c20b8af1a09d0eb10ab2",
"strip": "zapret-win-bundle-de9795d71287fdb21cf8c20b8af1a09d0eb10ab2/zapret-winws/",
"files": {
"WinDivert.dll": "16abd6a029e65557c6a309bea7b13bf81fff4e193567582e1cddbf6719f323e0",
"WinDivert64.sys": "8da085332782708d8767bcace5327a6ec7283c17cfb85e40b03cd2323a90ddc2",
"cygwin1.dll": "103104a52e5293ce418944725df19e2bf81ad9269b9a120d71d39028e821499b",
"files/list-youtube.txt": "47ea8a9ca11eb9ad833e5f22d12e8857400880e8f555f45687230ce8ba57d299",
"files/quic_initial_www_google_com.bin": "f4589c57749f956bb30538197a521d7005f8b0a8723b4707e72405e51ddac50a",
"lua/zapret-antidpi.lua": "6d1fa9168e5de1682fef91fd174f68b58c50f6739ef00f42ca7db2b940b6246d",
"lua/zapret-auto.lua": "23a9b99a776d868d92f4cc0ee5110f5c1f12fe746620d9c0337022dbc2f52df0",
"lua/zapret-lib.lua": "6bf528fef1f0fc3c65e189216fc8a06bb873f6e25d1c29d2bfa4695a09b73440",
"lua/zapret-obfs.lua": "e2d75840a9f1e3bfb74fa7463886932e03eb02ab33c6146d6392d6a231d1cfd5",
"lua/zapret-pcap.lua": "6866c37c92fbc62075accf94228da48af618c7f416edc682eba99b2196e05f45",
"lua/zapret-tests.lua": "82664cb50a751a531b63dce094ac03de5045b16b489e726ff32a9a1034811459",
"windivert.filter/README.txt": "be9ad4622296c463f1cf278c4f97be0c7eabaff9e79ad36262a8255fafd2b216",
"windivert.filter/windivert_part.dht.txt": "0e0d071239995332c2e45e60c59c5bb3d70233426e430a7babb24b18b75e90c0",
"windivert.filter/windivert_part.discord_media.txt": "2f2deaf49ed68eb684258497134181753188f2b475161deb244488a53872b7c5",
"windivert.filter/windivert_part.quic_initial_ietf.txt": "f243ddc22758b9e04838211a3815e43fb3abe615e6be29e6a812ae4c72b392e0",
"windivert.filter/windivert_part.stun.txt": "2a14f470b00cd9704003e0cade500086398f9222c858d9ae944bdeb89f520595",
"windivert.filter/windivert_part.wireguard.txt": "da68586267462b29e3e370203ce0369ae2baa25a07aa2deab5fb44d69fef27be",
"winws2.exe": "ba4ceccdea3576da0a0991a50d7893ea911de197281338132dbec02a5b2fcf58"
}
},
{
"url": "https://codeload.github.com/nfqws/nfqws2-keenetic/zip/fa22c177b340e73d8b8a94b295af20e0228c4c22",
"strip": "nfqws2-keenetic-fa22c177b340e73d8b8a94b295af20e0228c4c22/etc/nfqws2/",
"dest": "keenetic/",
"files": {
"blobs/quic_initial.bin": "f4589c57749f956bb30538197a521d7005f8b0a8723b4707e72405e51ddac50a",
"blobs/tls_clienthello.bin": "936c2bee4cfb80aa3c426b2dcbcc834b3fbcd1adb17172959dc569c73a14275c",
"lists/auto.list": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
"lists/exclude.list": "e7f87f890ad7916da8e30ceb101e8340955bdbba1e16cd6e6439469cc847f796",
"lists/ipset.list": "88cfdebe5531fd14d3a1ff16e303ae28307563c2ecd0820090918bf92da90b88",
"lists/ipset_exclude.list": "0a332890f577839bcce0651d3cf287d3d820c1bf4495b3f568276856d6e85073",
"lists/user.list": "974016ffc0b0cef05fbb05718f12b721104a72b3fa7261a814d596974dc339cc",
"nfqws2.conf": "b5c6598d5ba03762393a877514e005d2a241e0eb51c4e03142cade544e1e5b30"
}
}
]
},
"tg-ws-proxy": {
"version": "1.11.2+py3.12.10",
"license": "MIT",
"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(())
}
}
+19
View File
@@ -0,0 +1,19 @@
[package]
name = "ps-core"
description = "Proxy Suite for Windows: config model, link parsing and backend config rendering"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
base64.workspace = true
flate2 = "1"
serde.workspace = true
serde_json.workspace = true
regex.workspace = true
thiserror.workspace = true
percent-encoding.workspace = true
ipnet.workspace = true
indexmap.workspace = true
[dev-dependencies]
@@ -0,0 +1,22 @@
//! For the parity check against upstream (tools/parity/links.py): JSON lines in,
//! `{"url", "tag", "backend"}`, JSON lines out, `{"ok": outbound}` or `{"error": message}`.
use std::io::{BufRead, Write};
use ps_core::links::{LinkBackend, build_outbound};
use serde_json::{Value, json};
fn main() {
let stdout = std::io::stdout();
let mut out = stdout.lock();
for line in std::io::stdin().lock().lines() {
let line = line.expect("stdin");
let req: Value = serde_json::from_str(&line).expect("a JSON request");
let backend = if req["backend"] == "xray" { LinkBackend::Xray } else { LinkBackend::SingBox };
let result = match build_outbound(req["url"].as_str().unwrap(), req["tag"].as_str().unwrap(), backend) {
Ok(ob) => json!({ "ok": ob }),
Err(e) => json!({ "error": e.to_string() }),
};
writeln!(out, "{result}").unwrap();
}
}
@@ -0,0 +1,22 @@
//! For tools/winws-dry-run.sh: winws2's arguments as the service builds them, one per line.
//! `zapret2_args <component dir> <component dir as Windows sees it> <state dir as Windows sees it>`
use ps_core::config::Zapret2;
use ps_core::zapret2::{Paths, args, keenetic};
fn main() {
let a: Vec<String> = std::env::args().collect();
let conf = std::fs::read_to_string(std::path::Path::new(&a[1]).join("keenetic").join("nfqws2.conf")).unwrap();
let (comp, state) = (&a[2], &a[3]);
let source = keenetic(&conf, &format!("{comp}keenetic\\")).unwrap();
let paths = Paths {
lua: format!("{comp}lua\\"),
user: format!("{state}zapret-hosts-user.txt"),
exclude: format!("{state}zapret-hosts-user-exclude.txt"),
auto: format!("{state}learned\\zapret-hosts-auto.txt"),
};
let z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
for arg in args(&z, &source, &paths, false).unwrap() {
println!("{arg}");
}
}
@@ -0,0 +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> <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, 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 game: GameFilter = serde_json::from_value(serde_json::json!(game)).unwrap();
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"
);
}
}
+122
View File
@@ -0,0 +1,122 @@
//! The components: the backend programs the service runs, pinned by version and hash
//! (`windows/components.json`). Each is fetched from its project's own Windows release and
//! verified before anything from it runs.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
pub components: BTreeMap<String, Component>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Component {
pub version: String,
pub license: String,
pub homepage: String,
/// Built with the release, not fetched from a source of its own.
#[serde(default)]
pub bundled: bool,
pub sources: Vec<Source>,
}
/// One archive and what to take from it.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Source {
pub url: String,
/// The archive's SHA-256, where the archive is stable (a release asset).
#[serde(default)]
pub sha256: Option<String>,
/// The leading path every taken entry has, removed.
#[serde(default)]
pub strip: String,
/// Where below the component's directory the entries go.
#[serde(default)]
pub dest: String,
/// Only these entries (exact paths, or directories ending in `/`).
#[serde(default)]
pub include: Option<Vec<String>>,
/// Not these.
#[serde(default)]
pub exclude: Vec<String>,
/// Exactly these entries, each with its SHA-256: for an archive that is not byte-stable
/// (a commit snapshot), what is verified is what is taken.
#[serde(default)]
pub files: Option<BTreeMap<String, String>>,
}
/// The manifest this build pins.
pub fn manifest() -> Manifest {
serde_json::from_str(include_str!("../../../components.json")).expect("components.json is valid")
}
fn matches(list: &[String], rel: &str) -> bool {
list.iter().any(|p| if p.ends_with('/') { rel.starts_with(p.as_str()) } else { rel == p })
}
/// A relative path made of plain names only: no root, no drive, no `..`, no `.`.
pub fn safe_relative(rel: &str) -> bool {
!rel.is_empty()
&& !rel.starts_with(['/', '\\'])
&& !rel.contains(':')
&& rel.split(['/', '\\']).all(|part| !part.is_empty() && part != "." && part != "..")
}
impl Source {
/// Where an archive entry goes below the component's directory, or `None` to leave it.
pub fn place(&self, entry: &str) -> Option<String> {
if entry.ends_with('/') {
return None;
}
let rel = entry.strip_prefix(self.strip.as_str())?;
if let Some(files) = &self.files
&& !files.contains_key(rel)
{
return None;
}
if let Some(include) = &self.include
&& !matches(include, rel)
{
return None;
}
if matches(&self.exclude, rel) {
return None;
}
let out = format!("{}{rel}", self.dest);
safe_relative(&out).then_some(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_manifest_reads_and_places_entries() {
let m = manifest();
let sb = &m.components["sing-box"].sources[0];
assert_eq!(sb.place("sing-box-1.14.4-windows-amd64/sing-box.exe").as_deref(), Some("sing-box.exe"));
assert_eq!(sb.place("other/sing-box.exe"), None);
let z = &m.components["zapret"].sources[0];
assert_eq!(z.place("zapret-discord-youtube-1.10.4/bin/winws.exe").as_deref(), Some("bin/winws.exe"));
assert_eq!(z.place("zapret-discord-youtube-1.10.4/service.bat"), None);
assert_eq!(z.place("zapret-discord-youtube-1.10.4/utils/targets.txt"), None);
let k = &m.components["zapret2"].sources[1];
assert_eq!(k.place(&format!("{}nfqws2.conf", k.strip)).as_deref(), Some("keenetic/nfqws2.conf"));
assert!(m.components["tg-ws-proxy"].bundled);
}
#[test]
fn archive_paths_cannot_leave_the_directory() {
for bad in ["../x", "a/../b", "/etc/x", "C:/x", "a\\..\\b", "", "a//b"] {
assert!(!safe_relative(bad), "{bad}");
}
assert!(safe_relative("bin/winws.exe"));
let s = Source { url: String::new(), sha256: None, strip: "p/".into(), dest: String::new(), include: None, exclude: vec![], files: None };
assert_eq!(s.place("p/../../evil.exe"), None);
}
}
@@ -0,0 +1,479 @@
//! `inbounds`: server listeners for remote clients, their users, share links,
//! subscriptions, and the manager that keeps the users' policies.
//!
//! Left out from upstream: `runtime` (everything here is runtime-editable), `serverSource`
//! (a Linux dummy interface), `manager.speedLimits` (nftables policing) and the web server
//! groups; the service serves subscriptions itself on `subscriptions.listen`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::{AwgObfuscation, RouteMatch};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Inbounds {
pub enable: bool,
pub server_address: Option<String>,
pub server_aliases: Vec<String>,
pub server_ports: Vec<Value>,
pub access_log: bool,
/// Add Windows Firewall rules for every listener not on loopback.
pub open_firewall: bool,
pub share_links: bool,
pub subscriptions: InboundSubscriptions,
pub routing: InboundRouting,
pub users: BTreeMap<String, InboundUser>,
pub listeners: BTreeMap<String, InboundListener>,
pub manager: Manager,
}
impl Default for Inbounds {
fn default() -> Self {
Self {
enable: false,
server_address: None,
server_aliases: Vec::new(),
server_ports: Vec::new(),
access_log: false,
open_firewall: true,
share_links: true,
subscriptions: InboundSubscriptions::default(),
routing: InboundRouting::default(),
users: BTreeMap::new(),
listeners: BTreeMap::new(),
manager: Manager::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundSubscriptions {
pub enable: bool,
pub base_url: Option<String>,
/// `null`: a key generated on first start and kept in the state directory. `false`: no
/// key (tokens are a hash of the user alone). A string: a file with the key.
pub key_file: Option<Value>,
/// Windows only: address and port the service serves the subscription files on
/// (`host:port`), since there is no web server to hand a directory to. `null`: not
/// served; `proxy-ctl inbounds sub` still prints them.
pub listen: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundRouting {
pub via: String,
pub proxy: RouteMatch,
pub block_ru: bool,
pub block_private: bool,
pub block_torrent: bool,
pub block_ports: Vec<Value>,
pub zapret_direct: bool,
}
impl Default for InboundRouting {
fn default() -> Self {
Self {
via: "proxy".into(),
proxy: RouteMatch::default(),
block_ru: true,
block_private: true,
block_torrent: true,
block_ports: vec![Value::from(25)],
zapret_direct: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundUser {
pub order: Option<u32>,
pub uuid: Option<String>,
pub uuid_file: Option<String>,
pub password: Option<String>,
pub password_file: Option<String>,
pub public_key: Option<String>,
pub private_key_file: Option<String>,
pub preshared_key_file: Option<String>,
pub address: Option<String>,
pub policy: UserPolicy,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum TrafficPeriod {
Daily,
Weekly,
Monthly,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserPolicy {
pub enabled: bool,
/// A date, an ISO time, or a Unix time.
pub expires_at: Option<Value>,
/// Seconds, or a number with m, h, d or w.
pub expires_after: Option<Value>,
/// Bytes, or a number with K, M, G, T.
pub traffic_limit: Option<Value>,
pub traffic_period: Option<TrafficPeriod>,
pub ip_limit: Option<u32>,
}
impl Default for UserPolicy {
fn default() -> Self {
Self {
enabled: true,
expires_at: None,
expires_after: None,
traffic_limit: None,
traffic_period: None,
ip_limit: None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum InboundType {
Vless,
Vmess,
Trojan,
Hysteria2,
Shadowsocks,
Socks,
Http,
Amneziawg,
}
impl InboundType {
pub fn as_str(self) -> &'static str {
match self {
Self::Vless => "vless",
Self::Vmess => "vmess",
Self::Trojan => "trojan",
Self::Hysteria2 => "hysteria2",
Self::Shadowsocks => "shadowsocks",
Self::Socks => "socks",
Self::Http => "http",
Self::Amneziawg => "amneziawg",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundListener {
#[serde(rename = "type")]
pub kind: Option<InboundType>,
pub port: u16,
pub share_port: Option<u16>,
pub share_address: Option<String>,
pub address: String,
pub accept_proxy_protocol: bool,
pub share_fingerprint: Option<String>,
pub share_variants: Vec<ShareVariant>,
pub via: Option<String>,
pub order: i64,
pub users: Vec<String>,
pub flow: Option<String>,
pub method: String,
pub server_password: Option<String>,
pub server_password_file: Option<String>,
pub transport: InboundTransport,
pub tls: InboundTls,
pub reality: Reality,
pub fallbacks: Vec<Fallback>,
pub xray_json: Option<Map<String, Value>>,
pub json_file: Option<String>,
pub hysteria: Hysteria,
pub amnezia_wg: AwgServer,
}
impl Default for InboundListener {
fn default() -> Self {
Self {
kind: None,
port: 443,
share_port: None,
share_address: None,
address: "::".into(),
accept_proxy_protocol: false,
share_fingerprint: Some("chrome".into()),
share_variants: Vec::new(),
via: None,
order: 1000,
users: Vec::new(),
flow: None,
method: "2022-blake3-aes-128-gcm".into(),
server_password: None,
server_password_file: None,
transport: InboundTransport::default(),
tls: InboundTls::default(),
reality: Reality::default(),
fallbacks: Vec::new(),
xray_json: None,
json_file: None,
hysteria: Hysteria::default(),
amnezia_wg: AwgServer::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ShareVariant {
pub name: String,
pub fingerprint: Option<String>,
pub alpn: Option<Vec<String>>,
pub mode: Option<String>,
pub address: Option<String>,
pub server_name: Option<String>,
pub port_hopping: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundTransport {
#[serde(rename = "type")]
pub kind: String,
pub path: String,
pub host: Option<String>,
pub mode: Option<String>,
pub service_name: String,
pub trusted_x_forwarded_for: Vec<String>,
}
impl Default for InboundTransport {
fn default() -> Self {
Self {
kind: "raw".into(),
path: "/".into(),
host: None,
mode: None,
service_name: String::new(),
trusted_x_forwarded_for: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct InboundTls {
pub enable: bool,
pub certificate_file: Option<String>,
pub key_file: Option<String>,
pub server_name: Option<String>,
pub alpn: Option<Vec<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Reality {
pub enable: bool,
pub dest: String,
pub server_names: Vec<String>,
pub private_key_file: Option<String>,
pub private_key: Option<String>,
pub public_key: Option<String>,
pub short_ids: Vec<String>,
pub xver: u8,
}
impl Default for Reality {
fn default() -> Self {
Self {
enable: false,
dest: "www.microsoft.com:443".into(),
server_names: Vec::new(),
private_key_file: None,
private_key: None,
public_key: None,
short_ids: vec![String::new()],
xver: 0,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Fallback {
pub name: Option<String>,
pub alpn: Option<String>,
pub path: Option<String>,
pub dest: Option<Value>,
pub listener: Option<String>,
pub xver: u8,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Hysteria {
pub masquerade: Option<String>,
pub rewrite_host: bool,
pub x_forwarded: bool,
pub salamander: Salamander,
/// Upstream redirects the range with nftables; Windows has no such redirect, so here it
/// only goes into share links for a front that does it.
pub port_hopping: Option<String>,
}
impl Default for Hysteria {
fn default() -> Self {
Self {
masquerade: None,
rewrite_host: true,
x_forwarded: false,
salamander: Salamander::default(),
port_hopping: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Salamander {
pub enable: bool,
pub password: Option<String>,
pub password_file: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AwgServerMode {
#[default]
Proxy,
Lan,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgServer {
pub mode: AwgServerMode,
/// `null`: `awgi-<tag>`.
pub interface_name: Option<String>,
pub subnet: String,
pub subnet6: Option<String>,
pub private_key_file: Option<String>,
pub obfuscation: AwgObfuscation,
pub dns: Vec<String>,
pub mtu: Option<u32>,
pub persistent_keepalive: Option<u32>,
#[serde(rename = "clientAllowedIPs")]
pub client_allowed_ips: Vec<String>,
}
impl Default for AwgServer {
fn default() -> Self {
Self {
mode: AwgServerMode::Proxy,
interface_name: None,
subnet: "10.66.0.0/24".into(),
subnet6: None,
private_key_file: None,
obfuscation: AwgObfuscation::default(),
dns: vec!["1.1.1.1".into(), "1.0.0.1".into()],
mtu: None,
persistent_keepalive: Some(25),
client_allowed_ips: vec!["0.0.0.0/0".into(), "::/0".into()],
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Manager {
pub enable: bool,
pub interval: u32,
pub api: ManagerApi,
pub subscriptions: ManagerSubscriptions,
pub delete_expired_after: Option<String>,
pub ip_limit: IpLimit,
pub notify: Notify,
pub webhooks: Vec<Webhook>,
}
impl Default for Manager {
fn default() -> Self {
Self {
enable: false,
interval: 30,
api: ManagerApi::default(),
subscriptions: ManagerSubscriptions::default(),
delete_expired_after: None,
ip_limit: IpLimit::default(),
notify: Notify::default(),
webhooks: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ManagerApi {
pub listen: Option<String>,
pub tokens_file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ManagerSubscriptions {
pub enable: bool,
pub listen: Option<String>,
pub profile_title: String,
pub update_interval: Option<u32>,
pub support_url: Option<String>,
pub web_page_url: Option<String>,
}
impl Default for ManagerSubscriptions {
fn default() -> Self {
Self {
enable: true,
listen: None,
profile_title: "{user}".into(),
update_interval: Some(12),
support_url: None,
web_page_url: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct IpLimit {
pub ban_time: u32,
}
impl Default for IpLimit {
fn default() -> Self {
Self { ban_time: 600 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Notify {
pub traffic_percent: Vec<u32>,
pub expiry_days: Vec<u32>,
}
impl Default for Notify {
fn default() -> Self {
Self { traffic_percent: vec![80, 100], expiry_days: vec![3, 1] }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Webhook {
pub url: String,
pub events: Vec<String>,
pub secret_file: Option<String>,
}
+267
View File
@@ -0,0 +1,267 @@
//! `killSwitch`, `perAppRouting`, `geodata`, `userControl`, `gui` and `debug`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct KillSwitch {
/// Block outgoing traffic that bypasses the active global tunnel (TUN or a global
/// AmneziaWG profile), from the service's start until the tunnel is up, while it restarts
/// and after it fails. Windows Filtering Platform filters do it, so it holds even while
/// the service itself is stopped, until `proxy-ctl killswitch off`.
pub enable: bool,
pub direct_fallbacks: bool,
pub allowed_subnets: Vec<String>,
/// Windows only: let the Windows Time service (NTP, UDP 123) past it. Upstream lists the
/// time daemons' users instead.
pub allow_time_sync: bool,
}
impl Default for KillSwitch {
fn default() -> Self {
Self {
enable: false,
direct_fallbacks: true,
allowed_subnets: vec!["192.168.0.0/16".into()],
allow_time_sync: true,
}
}
}
/// Per-app routing, the Windows way: by program, not by cgroup.
///
/// Upstream wraps apps in proxychains or moves them into a cgroup whose packets nftables
/// marks. Windows has neither, but sing-box knows which program owns a connection, so here a
/// profile names programs, and their connections go to its outbound whatever the routing
/// says. `proxy-ctl apps run <profile> -- <cmd>` also starts a command with `HTTP_PROXY`,
/// `HTTPS_PROXY` and `ALL_PROXY` pointing at the profile's own loopback listener, for
/// programs that honour them when no TUN runs.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct PerAppRouting {
pub enable: bool,
pub profiles: Vec<PerAppProfile>,
/// Windows only: the first loopback port of the profiles' listeners, one per profile in
/// order.
pub listener_base_port: u16,
}
impl Default for PerAppRouting {
fn default() -> Self {
Self { enable: false, profiles: Vec::new(), listener_base_port: 18800 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct PerAppProfile {
pub name: String,
/// An outbound or group tag, or "proxy", "direct" or "block".
pub outbound: String,
/// Program file names, such as `Telegram.exe`; matched without regard to case.
pub process_names: Vec<String>,
/// Full program paths.
pub process_paths: Vec<String>,
}
impl Default for PerAppProfile {
fn default() -> Self {
Self {
name: String::new(),
outbound: "proxy".into(),
process_names: Vec::new(),
process_paths: Vec::new(),
}
}
}
/// Where geodata comes from. Upstream names Nix packages; here they are download locations,
/// fetched into the state directory and refreshed with `updateInterval`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Geodata {
pub sing_box: GeodataSingBox,
pub xray: GeodataXray,
/// Windows only: how often the downloads are refreshed.
pub update_interval: String,
}
impl Default for Geodata {
fn default() -> Self {
Self {
sing_box: GeodataSingBox::default(),
xray: GeodataXray::default(),
update_interval: "7d".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct GeodataSingBox {
/// Base URL of the `geoip-<name>.srs` rule sets.
pub geoip: String,
/// Base URL of the `geosite-<name>.srs` rule sets.
pub geosite: String,
}
impl Default for GeodataSingBox {
fn default() -> Self {
Self {
geoip: "https://raw.githubusercontent.com/SagerNet/sing-geoip/rule-set".into(),
geosite: "https://raw.githubusercontent.com/SagerNet/sing-geosite/rule-set".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct GeodataXray {
/// Base URL holding `geoip.dat` and `geosite.dat`. `null`: XRay's own, which only has
/// countries.
pub assets: Option<String>,
}
impl Default for GeodataXray {
fn default() -> Self {
Self {
assets: Some(
"https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download".into(),
),
}
}
}
/// The scopes `userControl` hands out, as upstream names them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum Scope {
Services,
PerApp,
Routing,
Outbounds,
Secrets,
AutoProxy,
Zapret,
Stats,
Inbounds,
WhitelistBypass,
AmneziaWg,
/// Windows only: edit the configuration itself (`proxy-ctl config set`, the app's
/// settings pages). Upstream changes it with a rebuild, which needs root.
Config,
}
impl Scope {
pub const ALL: [Scope; 12] = [
Scope::Services,
Scope::PerApp,
Scope::Routing,
Scope::Outbounds,
Scope::Secrets,
Scope::AutoProxy,
Scope::Zapret,
Scope::Stats,
Scope::Inbounds,
Scope::WhitelistBypass,
Scope::AmneziaWg,
Scope::Config,
];
}
/// Who may use the service without being an administrator.
///
/// Upstream's default keeps every change to root; a Windows desktop app whose settings are
/// all edited in its window would prompt for elevation at every click, so here it defaults
/// on for the signed-in (interactive) user.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserControl {
pub enable: bool,
/// A local group whose members get `scopes`. `null`: whoever is signed in at the console
/// or over Remote Desktop (the INTERACTIVE identity).
pub group: Option<String>,
/// Empty allows everything.
pub scopes: Vec<Scope>,
pub groups: BTreeMap<String, UserControlGroup>,
}
impl Default for UserControl {
fn default() -> Self {
Self { enable: true, group: None, scopes: Vec::new(), groups: BTreeMap::new() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UserControlGroup {
pub scopes: Vec<Scope>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Gui {
pub autostart: bool,
pub refresh_interval: u32,
}
impl Default for Gui {
fn default() -> Self {
Self { autostart: true, refresh_interval: 3 }
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
#[default]
Warn,
Info,
Debug,
Trace,
}
impl LogLevel {
pub fn as_str(self) -> &'static str {
match self {
Self::Warn => "warn",
Self::Info => "info",
Self::Debug => "debug",
Self::Trace => "trace",
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Debug {
pub log_level: LogLevel,
pub connection_log: ConnectionLog,
pub zapret2: DebugZapret2,
pub tg_ws_proxy: bool,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ConnectionLog {
pub enable: bool,
pub hosts: Vec<String>,
pub inbounds: Vec<String>,
pub stall_after: u32,
pub interval: f64,
}
impl Default for ConnectionLog {
fn default() -> Self {
Self { enable: false, hosts: Vec::new(), inbounds: Vec::new(), stall_after: 10, interval: 0.5 }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DebugZapret2 {
pub packets: bool,
pub auto_hostlist: bool,
}
+161
View File
@@ -0,0 +1,161 @@
//! The `services.proxy-suite` option tree, as the Windows port has it.
//!
//! Names, nesting and defaults follow upstream's Nix options (`docs/options/*.md`), so those
//! docs stay the reference and a value means the same thing on both. Options that only mean
//! something on Linux (TProxy, fwmarks, routing tables, kernel and package choices, service
//! users, proxychains) are left out. The few that exist only here say so in their doc comment.
//!
//! Every struct takes `#[serde(default)]`: a config file names only what differs from the
//! defaults, as a Nix config does.
mod inbounds;
mod misc;
mod privilege;
mod proxy;
mod tunnels;
mod validate;
mod zapret;
pub use inbounds::*;
pub use misc::*;
pub use privilege::privileged_changes;
pub use proxy::*;
pub use tunnels::*;
pub use validate::{Issue, Severity, validate};
pub use zapret::*;
use serde::{Deserialize, Serialize};
/// The whole configuration: `services.proxy-suite`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct Config {
/// The master switch. Upstream defaults it off, since the module is imported everywhere;
/// here the service only runs where it was installed, so it defaults on.
pub enable: bool,
pub proxy: Proxy,
pub kill_switch: KillSwitch,
pub per_app_routing: PerAppRouting,
pub zapret: Zapret,
pub amnezia_wg: AmneziaWg,
pub warp: Warp,
pub tor: Tor,
pub ssh_proxy: SshProxy,
pub tg_ws_proxy: TgWsProxy,
pub whitelist_bypass: WhitelistBypass,
pub inbounds: Inbounds,
pub geodata: Geodata,
pub user_control: UserControl,
pub gui: Gui,
pub debug: Debug,
}
impl Default for Config {
fn default() -> Self {
Self {
enable: true,
proxy: Proxy::default(),
kill_switch: KillSwitch::default(),
per_app_routing: PerAppRouting::default(),
zapret: Zapret::default(),
amnezia_wg: AmneziaWg::default(),
warp: Warp::default(),
tor: Tor::default(),
ssh_proxy: SshProxy::default(),
tg_ws_proxy: TgWsProxy::default(),
whitelist_bypass: WhitelistBypass::default(),
inbounds: Inbounds::default(),
geodata: Geodata::default(),
user_control: UserControl::default(),
gui: Gui::default(),
debug: Debug::default(),
}
}
}
impl Config {
/// Reads a config file's text. Unknown keys are refused, so a typo in a hand-edited file
/// is reported instead of silently meaning the default.
pub fn from_json(text: &str) -> Result<Self, serde_json::Error> {
serde_json::from_str(text)
}
pub fn to_json_pretty(&self) -> String {
serde_json::to_string_pretty(self).expect("the config always serializes")
}
}
/// Which address family a name is dialled over first.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DomainStrategy {
PreferIpv4,
PreferIpv6,
Ipv4Only,
Ipv6Only,
}
impl DomainStrategy {
pub fn as_str(self) -> &'static str {
match self {
Self::PreferIpv4 => "prefer_ipv4",
Self::PreferIpv6 => "prefer_ipv6",
Self::Ipv4Only => "ipv4_only",
Self::Ipv6Only => "ipv6_only",
}
}
}
/// "direct" or "proxy": how a helper (Tor, a rule-set download, a whitelist-bypass creator)
/// reaches the network.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Upstream {
#[default]
Direct,
Proxy,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_defaults_round_trip() {
let cfg = Config::default();
assert_eq!(Config::from_json(&cfg.to_json_pretty()).unwrap(), cfg);
}
#[test]
fn a_config_names_only_what_differs() {
let cfg = Config::from_json(
r#"{
"proxy": {
"enable": true,
"outbounds": [{ "tag": "nl", "url": "hy2://pw@example.com:443?sni=example.com" }],
"routing": { "rules": [{ "outbound": "nl", "geosites": ["netflix"], "processNames": ["Telegram.exe"] }] },
"groups": { "eu": { "match": ["de-*"], "strategy": "urltest" } }
},
"zapret": { "enable": true, "zapret-discord-youtube": { "configName": "general (ALT9)" } }
}"#,
)
.unwrap();
assert!(cfg.proxy.enable);
assert_eq!(cfg.proxy.listener.port, 1080);
assert_eq!(cfg.proxy.routing.rules[0].matches.geosites, ["netflix"]);
assert_eq!(cfg.proxy.routing.rules[0].process_names, ["Telegram.exe"]);
assert_eq!(cfg.proxy.groups["eu"].strategy, GroupStrategy::Urltest);
assert!(cfg.proxy.groups["eu"].failback);
assert_eq!(cfg.zapret.discord_youtube.config_name, "general (ALT9)");
assert_eq!(cfg.proxy.dns.local.transport, DnsTransport::Tcp);
}
#[test]
fn unknown_keys_are_refused() {
let err = Config::from_json(r#"{ "proxy": { "listner": {} } }"#).unwrap_err();
assert!(err.to_string().contains("listner"), "{err}");
let err = Config::from_json(r#"{ "proxy": { "routing": { "rules": [{ "outbound": "x", "domain": [] }] } } }"#)
.unwrap_err();
assert!(err.to_string().contains("domain"), "{err}");
}
}
@@ -0,0 +1,222 @@
//! Which edits only an administrator may make.
//!
//! Upstream changes its configuration with a rebuild, as root; here the signed-in user edits
//! it in the app, and the service that runs it is LocalSystem. So whatever `userControl`
//! grants, a change to an option that makes the service run a program, pass arguments
//! through to one, or read or write a file of the caller's choosing needs an administrator:
//! otherwise it is a way to run code or read files as SYSTEM.
use serde_json::Value;
use super::Config;
/// Keys whose value is passed to a program as it stands, or makes one run something.
const RAW_KEYS: [&str; 4] = ["extraArgs", "extraConfig", "nfqwsArgs", "allowConfigHooks"];
/// Option paths (`.`-separated, `*` for any key or index) privileged as a whole.
const PRIVILEGED_PATHS: [&str; 5] = [
"userControl",
"proxy.dns.singBox",
"zapret.zapret2.profiles",
"zapret.zapret2.blobs",
"inbounds.manager.api",
];
/// Where a value of `new` that differs from `old` needs an administrator, as option paths.
pub fn privileged_changes(old: &Config, new: &Config) -> Vec<String> {
let old = serde_json::to_value(old).expect("the config always serializes");
let new = serde_json::to_value(new).expect("the config always serializes");
let mut found = Vec::new();
walk(&mut Vec::new(), Some(&old), Some(&new), &mut found);
found
}
fn walk(path: &mut Vec<String>, old: Option<&Value>, new: Option<&Value>, found: &mut Vec<String>) {
// An unset option serializes as null, or not at all: either way it is unset.
let old = old.filter(|v| !v.is_null());
let new = new.filter(|v| !v.is_null());
if old == new {
return;
}
match privileged_here(path) {
Some(true) => {
found.push(path.join("."));
return;
}
Some(false) => return,
None => {}
}
match (old, new) {
(Some(Value::Object(a)), Some(Value::Object(b))) => {
let keys: Vec<&String> = a.keys().chain(b.keys().filter(|k| !a.contains_key(*k))).collect();
for key in keys {
path.push(key.clone());
walk(path, a.get(key), b.get(key), found);
path.pop();
}
}
(Some(Value::Array(a)), Some(Value::Array(b))) => {
for i in 0..a.len().max(b.len()) {
path.push(i.to_string());
walk(path, a.get(i), b.get(i), found);
path.pop();
}
}
// An object or list appearing, going, or taking another shape: what each side holds
// decides.
(a, b) => {
for v in [a, b].into_iter().flatten() {
if matches!(v, Value::Object(_) | Value::Array(_)) {
walk_new(path, v, found);
}
}
}
}
}
/// A whole subtree added or removed: every privileged value in it counts.
fn walk_new(path: &mut Vec<String>, value: &Value, found: &mut Vec<String>) {
let empty = match value {
Value::Object(_) => Value::Object(Default::default()),
_ => Value::Array(Vec::new()),
};
walk(path, Some(&empty), Some(value), found);
}
/// `Some(true)`: a change at `path` is privileged. `Some(false)`: it is not, and nothing
/// below it is either. `None`: look deeper.
fn privileged_here(path: &[String]) -> Option<bool> {
if PRIVILEGED_PATHS.iter().any(|p| matches_path(p, path)) {
return Some(true);
}
let key = path.last()?.as_str();
let lower = key.to_ascii_lowercase();
if lower.ends_with("file") || lower.ends_with("directory") {
return Some(true);
}
if RAW_KEYS.contains(&key) {
return Some(true);
}
// Raw backend JSON reaches sing-box or XRay as it stands. Upstream takes it from its
// userControl group after a check for file keys, but on Windows a value can name a file
// in too many ways (drive letters, UNC and device paths, sockets) to sort out safely.
if key.ends_with("Json") {
return Some(true);
}
None
}
fn matches_path(pattern: &str, path: &[String]) -> bool {
let parts: Vec<&str> = pattern.split('.').collect();
path.len() >= parts.len() && parts.iter().zip(path).all(|(p, s)| *p == "*" || *p == s)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{AwgProfile, Outbound};
#[test]
fn plain_edits_need_no_administrator() {
let old = Config::default();
let mut new = old.clone();
new.proxy.enable = true;
new.proxy.listener.port = 2080;
new.proxy.outbounds.push(Outbound {
tag: "nl".into(),
url: Some("hy2://pw@example.com:443".into()),
..Default::default()
});
new.zapret.enable = true;
assert_eq!(privileged_changes(&old, &new), Vec::<String>::new());
}
#[test]
fn files_programs_and_access_need_one() {
let old = Config::default();
let mut new = old.clone();
new.ssh_proxy.extra_args = vec!["-oProxyCommand=calc.exe".into()];
new.tor.extra_config = "ClientTransportPlugin x exec C:\\evil.exe".into();
new.proxy.listener.auth.password_file = Some(r"C:\Windows\System32\config\SAM".into());
new.user_control.scopes = vec![crate::config::Scope::Config];
new.amnezia_wg.profiles.insert(
"home".into(),
AwgProfile { allow_config_hooks: true, config_file: Some("x".into()), ..Default::default() },
);
let found = privileged_changes(&old, &new);
for path in [
"sshProxy.extraArgs",
"tor.extraConfig",
"proxy.listener.auth.passwordFile",
"userControl",
"amneziaWg.profiles.home.allowConfigHooks",
"amneziaWg.profiles.home.configFile",
] {
assert!(found.iter().any(|f| f == path), "{path} not in {found:?}");
}
}
#[test]
fn raw_json_always_needs_one() {
let old = Config::default();
let mut new = old.clone();
let mut json = serde_json::Map::new();
json.insert("type".into(), "vless".into());
new.proxy.outbounds.push(Outbound { tag: "a".into(), sing_box_json: Some(json), ..Default::default() });
assert_eq!(privileged_changes(&old, &new), ["proxy.outbounds.0.singBoxJson"]);
}
#[test]
fn lowercase_file_keys_and_appearing_objects_count() {
let old = Config::default();
let mut new = old.clone();
new.tg_ws_proxy.log.file = Some(r"C:\Windows\System32\drivers\etc\hosts".into());
new.tor.bridges.file = Some("x".into());
new.amnezia_wg.profiles.insert(
"p".into(),
AwgProfile {
settings: Some(crate::config::AwgSettings { private_key_file: Some("k".into()), ..Default::default() }),
..Default::default()
},
);
let found = privileged_changes(&old, &new);
for path in ["tgWsProxy.log.file", "tor.bridges.file", "amneziaWg.profiles.p.settings.privateKeyFile"] {
assert!(found.iter().any(|f| f == path), "{path} not in {found:?}");
}
// settings from unset to set, on a profile that was there before.
let mut old = Config::default();
old.amnezia_wg.profiles.insert("p".into(), AwgProfile::default());
let found = privileged_changes(&old, &new);
assert!(found.iter().any(|f| f == "amneziaWg.profiles.p.settings.privateKeyFile"), "{found:?}");
}
#[test]
fn path_like_raw_json_and_inbound_json_count() {
let old = Config::default();
let mut new = old.clone();
let mut json = serde_json::Map::new();
json.insert("protocol".into(), "freedom".into());
json.insert("settings".into(), serde_json::json!({ "redirect": "@xray.sock" }));
new.proxy.outbounds.push(Outbound { tag: "a".into(), xray_json: Some(json), ..Default::default() });
let mut tor = serde_json::Map::new();
tor.insert("type".into(), "tor".into());
new.proxy.outbounds.push(Outbound { tag: "b".into(), sing_box_json: Some(tor), ..Default::default() });
new.inbounds.listeners.insert(
"raw".into(),
crate::config::InboundListener { xray_json: Some(serde_json::Map::new()), ..Default::default() },
);
new.inbounds.listeners.get_mut("raw").unwrap().xray_json.as_mut().unwrap().insert("port".into(), 1.into());
let found = privileged_changes(&old, &new);
for path in ["proxy.outbounds.0.xrayJson", "proxy.outbounds.1.singBoxJson", "inbounds.listeners.raw.xrayJson"] {
assert!(found.iter().any(|f| f == path), "{path} not in {found:?}");
}
}
#[test]
fn removing_a_privileged_value_counts_too() {
let mut old = Config::default();
old.ssh_proxy.extra_args = vec!["-v".into()];
let new = Config::default();
assert_eq!(privileged_changes(&old, &new), ["sshProxy.extraArgs"]);
}
}
+547
View File
@@ -0,0 +1,547 @@
//! `proxy`: the local proxy, its outbounds, subscriptions, selection, routing, DNS and TUN.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use super::DomainStrategy;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum Backend {
#[default]
#[serde(rename = "sing-box")]
SingBox,
#[serde(rename = "xray")]
Xray,
#[serde(rename = "hybrid")]
Hybrid,
}
impl Backend {
pub fn as_str(self) -> &'static str {
match self {
Self::SingBox => "sing-box",
Self::Xray => "xray",
Self::Hybrid => "hybrid",
}
}
/// Whether sing-box runs (alone or in front of XRay).
pub fn runs_sing_box(self) -> bool {
self != Self::Xray
}
}
/// The transparent mode started with the service. Only "tun" exists on Windows: TProxy is
/// a Linux kernel feature.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Autostart {
Tun,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Proxy {
pub enable: bool,
pub backend: Backend,
pub autostart: Option<Autostart>,
pub ipv6: bool,
pub listener: ProxyListener,
pub auto_proxy: AutoProxy,
pub sing_box: SingBoxOptions,
pub xray: XrayOptions,
pub outbounds: Vec<Outbound>,
pub subscriptions: Vec<Subscription>,
pub runtime_subscriptions: RuntimeSubscriptions,
pub subscription_update_interval: String,
pub selection: Selection,
pub groups: BTreeMap<String, Group>,
pub priority: BTreeMap<String, i64>,
pub selection_exclude: Vec<String>,
pub url_test: UrlTest,
pub dns: Dns,
pub routing: Routing,
pub tun: Tun,
/// Windows only: point the signed-in user's system proxy (WinINet, which browsers and most
/// apps follow) at `listener` while the local proxy runs.
pub system_proxy: SystemProxy,
}
impl Default for Proxy {
fn default() -> Self {
Self {
enable: false,
backend: Backend::SingBox,
autostart: None,
ipv6: true,
listener: ProxyListener::default(),
auto_proxy: AutoProxy::default(),
sing_box: SingBoxOptions::default(),
xray: XrayOptions::default(),
outbounds: Vec::new(),
subscriptions: Vec::new(),
runtime_subscriptions: RuntimeSubscriptions::default(),
subscription_update_interval: "1d".into(),
selection: Selection::First,
groups: BTreeMap::new(),
priority: BTreeMap::new(),
selection_exclude: Vec::new(),
url_test: UrlTest::default(),
dns: Dns::default(),
routing: Routing::default(),
tun: Tun::default(),
system_proxy: SystemProxy::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ProxyListener {
pub address: String,
pub port: u16,
pub auth: ListenerAuth,
}
impl Default for ProxyListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1080, auth: ListenerAuth::default() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct ListenerAuth {
pub username: Option<String>,
pub password: Option<String>,
pub password_file: Option<String>,
}
impl ListenerAuth {
pub fn enabled(&self) -> bool {
self.username.is_some()
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AutoProxy {
pub enable: bool,
pub interval: String,
pub probes_per_run: u32,
pub max_exits: u32,
pub ttl_days: u32,
#[serde(rename = "slowBelowKiBps")]
pub slow_below_kibps: u32,
pub exclude: Vec<String>,
pub probe_base_port: u16,
}
impl Default for AutoProxy {
fn default() -> Self {
Self {
enable: false,
interval: "10m".into(),
probes_per_run: 200,
max_exits: 12,
ttl_days: 30,
slow_below_kibps: 150,
exclude: Vec::new(),
probe_base_port: 18540,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SingBoxOptions {
pub clash_api_port: u16,
/// Windows only: the loopback listener `proxy-ctl proxy outbounds test` reaches each
/// outbound through. Upstream fixes it at 18537.
pub test_port: u16,
}
impl Default for SingBoxOptions {
fn default() -> Self {
Self { clash_api_port: 9090, test_port: 18537 }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct XrayOptions {
/// Values are a number or a "low-high" range XRay picks from.
pub xhttp_xmux: Option<BTreeMap<String, Value>>,
}
/// Which engine runs an outbound on the hybrid backend.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum OutboundBackend {
#[default]
#[serde(rename = "auto")]
Auto,
#[serde(rename = "sing-box")]
SingBox,
#[serde(rename = "xray")]
Xray,
}
/// Domains, addresses, geodata and rule sets: what a rule (or an outbound's own routing)
/// matches.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RouteMatch {
pub domains: Vec<String>,
pub ips: Vec<String>,
pub geosites: Vec<String>,
pub geoips: Vec<String>,
pub rule_sets: Vec<String>,
}
impl RouteMatch {
pub fn is_empty(&self) -> bool {
self.domains.is_empty()
&& self.ips.is_empty()
&& self.geosites.is_empty()
&& self.geoips.is_empty()
&& self.rule_sets.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Outbound {
pub tag: String,
pub url: Option<String>,
pub url_file: Option<String>,
pub detour: Option<String>,
pub sing_box_json: Option<Map<String, Value>>,
pub xray_json: Option<Map<String, Value>>,
pub backend: OutboundBackend,
pub routing: RouteMatch,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Subscription {
pub tag: String,
pub url: Option<String>,
pub url_file: Option<String>,
pub detour: Option<String>,
pub allow_private_servers: bool,
pub allow_insecure: bool,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RuntimeSubscriptions {
pub allow_http: bool,
pub allow_insecure: bool,
pub allow_private_servers: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Selection {
#[default]
First,
Selector,
Urltest,
Failover,
}
impl Selection {
pub fn as_str(self) -> &'static str {
match self {
Self::First => "first",
Self::Selector => "selector",
Self::Urltest => "urltest",
Self::Failover => "failover",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GroupStrategy {
#[default]
Failover,
Urltest,
Selector,
}
impl GroupStrategy {
pub fn as_str(self) -> &'static str {
match self {
Self::Failover => "failover",
Self::Urltest => "urltest",
Self::Selector => "selector",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Group {
pub outbounds: Vec<String>,
pub subscriptions: Vec<String>,
#[serde(rename = "match")]
pub match_: Vec<String>,
pub strategy: GroupStrategy,
pub failback: bool,
pub interval: Option<String>,
}
impl Default for Group {
fn default() -> Self {
Self {
outbounds: Vec::new(),
subscriptions: Vec::new(),
match_: Vec::new(),
strategy: GroupStrategy::Failover,
failback: true,
interval: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct UrlTest {
pub url: String,
pub interval: String,
pub tolerance: i64,
}
impl Default for UrlTest {
fn default() -> Self {
Self {
url: "https://www.gstatic.com/generate_204".into(),
interval: "3m".into(),
tolerance: 50,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DnsTransport {
#[default]
Udp,
Tcp,
Tls,
}
impl DnsTransport {
pub fn as_str(self) -> &'static str {
match self {
Self::Udp => "udp",
Self::Tcp => "tcp",
Self::Tls => "tls",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct DnsUpstream {
#[serde(rename = "type", default)]
pub transport: DnsTransport,
pub address: String,
#[serde(default = "default_dns_port")]
pub port: u16,
}
fn default_dns_port() -> u16 {
53
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Dns {
/// TCP by default: DPI boxes answer plain UDP queries to well-known resolvers themselves.
pub local: DnsUpstream,
pub remote: DnsUpstream,
pub strategy: Option<DomainStrategy>,
pub client_subnet: Option<String>,
pub fake_ip: FakeIp,
pub sing_box: DnsSingBox,
}
impl Default for Dns {
fn default() -> Self {
Self {
local: DnsUpstream { transport: DnsTransport::Tcp, address: "1.1.1.1".into(), port: 53 },
remote: DnsUpstream { transport: DnsTransport::Udp, address: "1.1.1.1".into(), port: 53 },
strategy: None,
client_subnet: None,
fake_ip: FakeIp::default(),
sing_box: DnsSingBox::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct FakeIp {
pub enable: bool,
pub inet4_range: String,
}
impl Default for FakeIp {
fn default() -> Self {
Self { enable: false, inet4_range: "198.18.0.0/15".into() }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DnsSingBox {
pub servers: Vec<Map<String, Value>>,
pub rules: Vec<Map<String, Value>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RouteDefault {
#[default]
Proxy,
Direct,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Routing {
pub default: RouteDefault,
pub direct_ru: bool,
pub proxy: RouteMatch,
pub direct: RouteMatch,
pub block: RouteMatch,
pub rules: Vec<RoutingRule>,
pub rule_sets: BTreeMap<String, RuleSet>,
pub rule_set_update_interval: String,
}
impl Default for Routing {
fn default() -> Self {
Self {
default: RouteDefault::Proxy,
direct_ru: true,
proxy: RouteMatch::default(),
direct: RouteMatch::default(),
block: RouteMatch::default(),
rules: Vec::new(),
rule_sets: BTreeMap::new(),
rule_set_update_interval: "1d".into(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct RoutingRule {
/// Windows only: what `proxy-ctl proxy rules` calls the rule. Upstream's runtime rules
/// have names; its declared ones do not, and neither need one here.
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
/// Windows only: where the rule sorts among the configuration's sections, lower first
/// (`proxy.routing.rules` sit at 100, the proxy, block, direct and geo lists at 200 to
/// 500). `null`: 100, in list order.
#[serde(skip_serializing_if = "Option::is_none")]
pub priority: Option<i64>,
/// Windows only: kept, but not applied.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub disabled: bool,
pub outbound: String,
#[serde(flatten)]
pub matches: RouteMatch,
/// Windows only: program file names (`firefox.exe`) whose connections this rule matches.
/// sing-box looks the owning process up, on the TUN and on the local proxy alike.
pub process_names: Vec<String>,
/// Windows only: full program paths, as `process_names` does.
pub process_paths: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleSetFormat {
Binary,
Source,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum RuleSetDetour {
#[default]
Proxy,
Direct,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct RuleSet {
pub url: String,
#[serde(default)]
pub format: Option<RuleSetFormat>,
#[serde(default)]
pub detour: RuleSetDetour,
}
impl RuleSet {
/// The format, guessed from the URL when unset as upstream does.
pub fn effective_format(&self) -> RuleSetFormat {
self.format.unwrap_or_else(|| {
let path = self.url.split(['?', '#']).next().unwrap_or("");
if path.ends_with(".json") { RuleSetFormat::Source } else { RuleSetFormat::Binary }
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Tun {
pub enable: bool,
/// The adapter's name in Windows' network connections.
pub interface: String,
pub address: String,
pub mtu: u32,
}
impl Default for Tun {
fn default() -> Self {
Self {
enable: false,
interface: "ProxySuite".into(),
address: "172.19.0.1/30".into(),
mtu: 1400,
}
}
}
/// Windows only.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SystemProxy {
pub enable: bool,
/// Hosts that skip the system proxy, in WinINet's syntax. `<local>` covers names without
/// a dot.
pub bypass: Vec<String>,
}
impl Default for SystemProxy {
fn default() -> Self {
Self {
enable: false,
bypass: vec![
"localhost".into(),
"127.*".into(),
"10.*".into(),
"172.16.*".into(),
"192.168.*".into(),
"<local>".into(),
],
}
}
}
@@ -0,0 +1,439 @@
//! The tunnels besides the proxy's own outbounds: `amneziaWg`, `warp`, `tor`, `sshProxy`,
//! `tgWsProxy` and `whitelistBypass`.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{DomainStrategy, GroupStrategy, Upstream};
// --- amneziaWg ------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AmneziaWg {
pub enable: bool,
pub profiles: BTreeMap<String, AwgProfile>,
}
/// How a profile is used, when it is not a global VPN.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum AwgOutboundKind {
/// Plain WireGuard in sing-box: AmneziaWG obfuscation is dropped, with a warning.
SingBox,
/// wireproxy-awg, a userspace AmneziaWG client with a SOCKS listener the outbound dials.
Userspace,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgProfile {
/// The tunnel's name, which its Windows service (`AmneziaWGTunnel$<name>`) and adapter
/// take. `null`: the profile's name.
pub interface_name: Option<String>,
pub autostart: bool,
pub as_outbound: Option<AwgOutboundKind>,
pub endpoint: Option<String>,
pub domain_strategy: Option<DomainStrategy>,
pub allow_config_hooks: bool,
pub vpn_container: Option<String>,
pub config_file: Option<String>,
/// Windows only: the `.conf` text itself, as pasted into the app.
pub config: Option<String>,
pub vpn_file: Option<String>,
pub vpn: Option<String>,
pub settings: Option<AwgSettings>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgSettings {
pub addresses: Vec<String>,
pub dns: Vec<String>,
pub private_key: Option<String>,
pub private_key_file: Option<String>,
pub listen_port: Option<u16>,
pub mtu: Option<u32>,
pub obfuscation: AwgObfuscation,
pub obfuscation_file: Option<String>,
pub peers: Vec<AwgPeer>,
}
/// A number, or (AWG 3) a "low-high" range or "(off)".
pub type AwgRange = Value;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgObfuscation {
pub jc: Option<u32>,
pub jmin: Option<u32>,
pub jmax: Option<u32>,
pub s1: Option<u32>,
pub s2: Option<u32>,
pub s3: Option<u32>,
pub s4: Option<u32>,
pub h1: Option<AwgRange>,
pub h2: Option<AwgRange>,
pub h3: Option<AwgRange>,
pub h4: Option<AwgRange>,
pub content_padding_addition: Option<AwgRange>,
pub rekey_after_time: Option<AwgRange>,
pub rekey_timeout: Option<AwgRange>,
pub reject_after_time: Option<AwgRange>,
pub keepalive_timeout: Option<AwgRange>,
pub max_handshake_attempts: Option<AwgRange>,
pub i1: Option<String>,
pub i2: Option<String>,
pub i3: Option<String>,
pub i4: Option<String>,
pub i5: Option<String>,
pub header_protection_key: Option<String>,
pub header_protection_key_file: Option<String>,
pub random_trailers: Option<bool>,
pub disable_cookies: Option<bool>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AwgPeer {
pub public_key: String,
pub preshared_key: Option<String>,
pub preshared_key_file: Option<String>,
#[serde(rename = "allowedIPs")]
pub allowed_ips: Vec<String>,
pub endpoint: Option<String>,
pub persistent_keepalive: Option<AwgRange>,
pub advanced_security: Option<bool>,
}
// --- warp -----------------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum WarpOutboundKind {
SingBox,
Userspace,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Warp {
pub enable: bool,
pub config_file: Option<String>,
/// Windows only: the WireGuard profile text itself.
pub config: Option<String>,
pub generator_url: Option<String>,
pub endpoint: Option<String>,
pub as_outbound: Option<WarpOutboundKind>,
pub domain_strategy: DomainStrategy,
pub devices: BTreeMap<String, WarpDevice>,
pub instances: Option<u32>,
pub group: WarpGroup,
pub as_amnezia_wg: bool,
pub autostart: bool,
}
impl Default for Warp {
fn default() -> Self {
Self {
enable: false,
config_file: None,
config: None,
generator_url: None,
endpoint: None,
as_outbound: None,
domain_strategy: DomainStrategy::PreferIpv6,
devices: BTreeMap::new(),
instances: None,
group: WarpGroup::default(),
as_amnezia_wg: false,
autostart: false,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WarpDevice {
pub config_file: Option<String>,
pub config: Option<String>,
pub endpoint: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WarpGroup {
pub strategy: GroupStrategy,
pub failback: bool,
}
impl Default for WarpGroup {
fn default() -> Self {
Self { strategy: GroupStrategy::Failover, failback: true }
}
}
// --- tor ------------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Tor {
pub enable: bool,
pub as_outbound: bool,
pub route_onion: bool,
pub client_only: bool,
pub keep_awake: bool,
pub upstream: Upstream,
pub socks_port: u16,
/// Windows only: Tor's loopback control port (cookie authentication), for `tor newnym`.
/// Upstream uses a Unix socket.
pub control_port: u16,
pub bridges: TorBridges,
pub onion_service: OnionService,
pub extra_config: String,
}
impl Default for Tor {
fn default() -> Self {
Self {
enable: false,
as_outbound: false,
route_onion: true,
client_only: true,
keep_awake: false,
upstream: Upstream::Direct,
socks_port: 18530,
control_port: 18531,
bridges: TorBridges::default(),
onion_service: OnionService::default(),
extra_config: String::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TorBridges {
pub lines: Vec<String>,
pub file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct OnionService {
pub enable: bool,
pub listeners: Option<Vec<String>>,
pub secret_key_file: Option<String>,
}
// --- sshProxy -------------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum StrictHostKeyChecking {
#[default]
Yes,
AcceptNew,
No,
}
impl StrictHostKeyChecking {
pub fn as_str(self) -> &'static str {
match self {
Self::Yes => "yes",
Self::AcceptNew => "accept-new",
Self::No => "no",
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshProxy {
pub enable: bool,
pub server: SshServer,
pub as_outbound: bool,
pub identity_file: Option<String>,
pub host_key: Vec<String>,
pub host_key_file: Option<String>,
pub known_hosts_file: Option<String>,
pub strict_host_key_checking: StrictHostKeyChecking,
pub listener: SshListener,
pub extra_args: Vec<String>,
pub domain_strategy: Option<DomainStrategy>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshServer {
pub user: Option<String>,
pub host: Option<String>,
pub port: u16,
}
impl Default for SshServer {
fn default() -> Self {
Self { user: None, host: None, port: 22 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct SshListener {
pub address: String,
pub port: u16,
}
impl Default for SshListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1091 }
}
}
// --- tgWsProxy ------------------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgWsProxy {
pub enable: bool,
pub listener: TgListener,
pub secret: Option<String>,
pub secret_file: Option<String>,
pub dc_ips: BTreeMap<String, String>,
pub fake_tls_domain: Option<String>,
pub cloudflare: TgCloudflare,
pub pool_size: u32,
#[serde(rename = "bufferKiB")]
pub buffer_kib: u32,
pub proxy_protocol: bool,
/// Keep the relay's own connections out of the TUN: on Windows, a rule sending its
/// process direct.
pub bypass_transparent_proxy: bool,
pub log: TgLog,
}
impl Default for TgWsProxy {
fn default() -> Self {
Self {
enable: false,
listener: TgListener::default(),
secret: None,
secret_file: None,
dc_ips: BTreeMap::new(),
fake_tls_domain: None,
cloudflare: TgCloudflare::default(),
pool_size: 4,
buffer_kib: 256,
proxy_protocol: false,
bypass_transparent_proxy: true,
log: TgLog::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgListener {
pub address: String,
pub port: u16,
}
impl Default for TgListener {
fn default() -> Self {
Self { address: "127.0.0.1".into(), port: 1443 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgCloudflare {
pub domains: Vec<String>,
pub worker_domains: Vec<String>,
pub fallback: bool,
}
impl Default for TgCloudflare {
fn default() -> Self {
Self { domains: Vec::new(), worker_domains: Vec::new(), fallback: true }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct TgLog {
pub file: Option<String>,
#[serde(rename = "maxSizeMiB")]
pub max_size_mib: f64,
pub keep: u32,
}
impl Default for TgLog {
fn default() -> Self {
Self { file: None, max_size_mib: 5.0, keep: 1 }
}
}
// --- whitelistBypass ------------------------------------------------------------------------
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WlPlatform {
Wbstream,
Telemost,
Dion,
Bitrix,
Vk,
}
impl WlPlatform {
pub fn as_str(self) -> &'static str {
match self {
Self::Wbstream => "wbstream",
Self::Telemost => "telemost",
Self::Dion => "dion",
Self::Bitrix => "bitrix",
Self::Vk => "vk",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum WlResources {
#[default]
Moderate,
Default,
Unlimited,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct WhitelistBypass {
pub enable: bool,
pub joiners: BTreeMap<String, WlJoiner>,
pub creators: BTreeMap<String, WlCreator>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WlJoiner {
pub platform: WlPlatform,
#[serde(default)]
pub link_file: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct WlCreator {
pub platform: WlPlatform,
#[serde(default)]
pub cookies_file: Option<String>,
#[serde(default)]
pub link_file: Option<String>,
#[serde(default)]
pub upstream: Upstream,
#[serde(default)]
pub resources: WlResources,
}
@@ -0,0 +1,890 @@
//! Checks a configuration before the service takes it, as upstream's assertions do at
//! evaluation. Errors refuse the configuration; warnings go with it.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use super::{Backend, Config, GroupStrategy, Selection, StrategySource, ZapretDefaultDomains, ZapretEngine, ZapretPreset};
use crate::derived::{self, BUILTIN_TAGS};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
Error,
Warning,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Issue {
pub severity: Severity,
/// The option it is about, as `proxy.outbounds.2.tag`.
pub path: String,
pub message: String,
}
struct Issues(Vec<Issue>);
impl Issues {
fn error(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Error, path: path.into(), message: message.into() });
}
fn warn(&mut self, path: impl Into<String>, message: impl Into<String>) {
self.0.push(Issue { severity: Severity::Warning, path: path.into(), message: message.into() });
}
/// `used` needs `dependency`: the shape of most of upstream's assertions.
fn requires(&mut self, used: bool, dependency: bool, path: &str, used_label: &str, dependency_label: &str) {
if used && !dependency {
self.error(path, format!("{used_label} requires {dependency_label}"));
}
}
}
fn tag_pattern_ok(tag: &str) -> bool {
let mut chars = tag.chars();
matches!(chars.next(), Some(c) if c.is_ascii_alphanumeric())
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
/// A name that becomes part of a file path, a Windows service name or an adapter name:
/// letters, digits, `.`, `_` and `-`, not starting with a dot, at most 64 characters.
pub(crate) fn path_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-'))
}
/// A geosite or geoip name: "geolocation-!cn" and "google@cn" among them, never a path
/// (upstream's routing-render.jq `geo`).
pub(crate) fn geo_name_ok(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 64
&& !name.starts_with('.')
&& name.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'))
}
fn profile_name_ok(name: &str) -> bool {
let mut chars = name.chars();
matches!(chars.next(), Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit())
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
}
/// 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()
}
/// Every problem with `cfg`, errors first.
pub fn validate(cfg: &Config) -> Vec<Issue> {
let mut v = Issues(Vec::new());
proxy(cfg, &mut v);
tunnels(cfg, &mut v);
zapret(cfg, &mut v);
per_app(cfg, &mut v);
inbounds(cfg, &mut v);
ports(cfg, &mut v);
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() {
let path = format!("proxy.outbounds.{i}");
if ob.tag.is_empty() {
v.error(format!("{path}.tag"), "an outbound needs a tag");
} else if BUILTIN_TAGS.contains(&ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("'{}' is a builtin target and cannot be an outbound's tag", ob.tag));
} else if !seen.insert(ob.tag.as_str()) {
v.error(format!("{path}.tag"), format!("outbound tag '{}' is used twice", ob.tag));
}
let sources = [ob.url.is_some(), ob.url_file.is_some(), ob.sing_box_json.is_some(), ob.xray_json.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("outbound '{}' sets {} of url, urlFile, singBoxJson and xrayJson; it needs exactly one", ob.tag, count_some(&sources)));
}
if ob.sing_box_json.is_some() && p.backend == Backend::Xray {
v.error(&path, format!("outbound '{}' is sing-box JSON, which the xray backend cannot run", ob.tag));
}
if ob.xray_json.is_some() && p.backend == Backend::SingBox {
v.error(&path, format!("outbound '{}' is XRay JSON, which the sing-box backend cannot run", ob.tag));
}
if !ob.routing.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.routing.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
for name in &ob.routing.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.routing.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
let mut subs = BTreeSet::new();
for (i, sub) in p.subscriptions.iter().enumerate() {
let path = format!("proxy.subscriptions.{i}");
if !tag_pattern_ok(&sub.tag) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' must start with a letter or digit and hold only letters, digits, '.', '_' and '-'", sub.tag));
} else if !subs.insert(sub.tag.as_str()) {
v.error(format!("{path}.tag"), format!("subscription tag '{}' is used twice", sub.tag));
}
if count_some(&[sub.url.is_some(), sub.url_file.is_some()]) != 1 {
v.error(&path, format!("subscription '{}' needs exactly one of url and urlFile", sub.tag));
}
}
let known = |t: &str| derived::is_known_target(cfg, t);
for (i, ob) in p.outbounds.iter().enumerate() {
if let Some(hop) = &ob.detour {
if hop == &ob.tag {
v.error(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' cannot chain through itself", ob.tag));
} else if !known(hop) {
// A subscription entry, perhaps: those only exist once fetched.
v.warn(format!("proxy.outbounds.{i}.detour"), format!("outbound '{}' chains through '{hop}', which names no outbound declared here; it must be a subscription entry", ob.tag));
}
}
}
for (i, rule) in p.routing.rules.iter().enumerate() {
let path = format!("proxy.routing.rules.{i}");
if !known(&rule.outbound) {
v.error(format!("{path}.outbound"), format!("routing rule target '{}' is not an outbound, a group, or proxy, direct or block", rule.outbound));
}
if rule.matches.is_empty() && rule.process_names.is_empty() && rule.process_paths.is_empty() {
v.warn(&path, "this rule matches nothing");
}
if !rule.matches.rule_sets.is_empty() && !sing_box {
v.error(format!("{path}.ruleSets"), "rule sets need the sing-box or hybrid backend");
}
if (!rule.process_names.is_empty() || !rule.process_paths.is_empty()) && !sing_box {
v.error(&path, "matching programs needs the sing-box or hybrid backend");
}
for name in &rule.matches.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("{path}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
for (bucket, m) in [("proxy", &p.routing.proxy), ("direct", &p.routing.direct), ("block", &p.routing.block)] {
for name in &m.rule_sets {
if !p.routing.rule_sets.contains_key(name) {
v.error(format!("proxy.routing.{bucket}.ruleSets"), format!("rule set '{name}' is not in proxy.routing.ruleSets"));
}
}
}
let mut geo_lists: Vec<(String, &crate::config::RouteMatch)> = vec![
("proxy.routing.proxy".into(), &p.routing.proxy),
("proxy.routing.direct".into(), &p.routing.direct),
("proxy.routing.block".into(), &p.routing.block),
];
geo_lists.extend(p.routing.rules.iter().enumerate().map(|(i, r)| (format!("proxy.routing.rules.{i}"), &r.matches)));
geo_lists.extend(p.outbounds.iter().enumerate().map(|(i, o)| (format!("proxy.outbounds.{i}.routing"), &o.routing)));
for (path, m) in geo_lists {
for name in m.geosites.iter().chain(&m.geoips) {
if !geo_name_ok(name) {
v.error(&path, format!("'{name}' is not a geosite or geoip name: letters, digits, '!', '@', '.', '_' and '-'"));
}
}
}
for name in p.routing.rule_sets.keys() {
if !path_name_ok(name) {
v.error(format!("proxy.routing.ruleSets.{name}"), "a rule set name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
if !p.routing.rule_sets.is_empty() && !sing_box {
v.error("proxy.routing.ruleSets", "rule sets need the sing-box or hybrid backend");
}
for (name, rs) in &p.routing.rule_sets {
if !rs.url.starts_with("https://") || rs.url.len() <= "https://".len() {
v.error(format!("proxy.routing.ruleSets.{name}.url"), "a rule set is fetched over https only");
}
}
if !p.groups.is_empty() && !sing_box {
v.error("proxy.groups", "outbound groups need the sing-box or hybrid backend");
}
for (name, group) in &p.groups {
let path = format!("proxy.groups.{name}");
if !path_name_ok(name) {
v.error(&path, format!("group name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if BUILTIN_TAGS.contains(&name.as_str()) || p.outbounds.iter().any(|o| &o.tag == name) {
v.error(&path, format!("group '{name}' takes a tag an outbound or builtin already has"));
}
for member in &group.outbounds {
if member == name {
v.error(format!("{path}.outbounds"), format!("group '{name}' cannot contain itself"));
} else if !known(member) {
v.warn(format!("{path}.outbounds"), format!("member '{member}' names no outbound declared here; it is left out unless a subscription brings it"));
}
}
for sub in &group.subscriptions {
if !p.subscriptions.iter().any(|s| &s.tag == sub) {
v.error(format!("{path}.subscriptions"), format!("subscription '{sub}' does not exist"));
}
}
if group.outbounds.is_empty() && group.subscriptions.is_empty() && group.match_.is_empty() {
v.warn(&path, format!("group '{name}' has no members: it blocks"));
}
if group.strategy != GroupStrategy::Failover && !group.failback {
v.warn(format!("{path}.failback"), "failback only applies to the failover strategy");
}
}
if p.selection == Selection::Failover && !sing_box {
v.error("proxy.selection", "\"failover\" selection needs the sing-box or hybrid backend");
}
if p.auto_proxy.enable && !sing_box {
v.error("proxy.autoProxy.enable", "autoProxy needs the sing-box or hybrid backend");
}
if p.auto_proxy.slow_below_kibps > 0 && p.auto_proxy.enable && p.selection == Selection::First {
v.warn("proxy.autoProxy.slowBelowKiBps", "slow destinations are only routed with a selection other than \"first\"");
}
if p.dns.fake_ip.enable && !sing_box {
v.error("proxy.dns.fakeIp.enable", "fake IP needs the sing-box or hybrid backend");
}
if p.enable && !derived::has_available_outbounds(cfg) {
v.warn("proxy.outbounds", "the proxy has no outbound or subscription yet; it starts once one is added");
}
v.requires(p.autostart.is_some(), p.tun.enable, "proxy.autostart", "proxy.autostart = \"tun\"", "proxy.tun.enable = true");
v.requires(p.tun.enable, p.enable, "proxy.tun.enable", "proxy.tun.enable", "proxy.enable = true");
v.requires(p.system_proxy.enable, p.enable, "proxy.systemProxy.enable", "proxy.systemProxy.enable", "proxy.enable = true");
let auth = &p.listener.auth;
if auth.username.is_some() && auth.password.is_none() && auth.password_file.is_none() {
v.error("proxy.listener.auth", "a username needs password or passwordFile");
}
if auth.password.is_some() && auth.password_file.is_some() {
v.error("proxy.listener.auth", "set password or passwordFile, not both");
}
if auth.username.is_none() && (auth.password.is_some() || auth.password_file.is_some()) {
v.error("proxy.listener.auth", "a password needs a username");
}
for (label, value) in [("username", &auth.username), ("password", &auth.password)] {
if value.as_deref().is_some_and(|s| s.is_empty() || s.chars().any(char::is_whitespace)) {
v.error(format!("proxy.listener.auth.{label}"), "it must be a single word");
}
}
if p.system_proxy.enable && auth.enabled() {
v.warn("proxy.systemProxy.enable", "the system proxy cannot carry a login: apps that follow it will be asked for one");
}
}
fn tunnels(cfg: &Config, v: &mut Issues) {
let proxy_on = cfg.proxy.enable;
let w = &cfg.warp;
if w.enable {
if w.as_outbound.is_none() && !w.as_amnezia_wg {
v.warn("warp.enable", "WARP is on, but neither asOutbound nor asAmneziaWg uses it");
}
if w.as_outbound.is_some() && w.as_amnezia_wg {
v.error("warp.asAmneziaWg", "asAmneziaWg cannot be used with asOutbound");
}
v.requires(w.as_outbound.is_some(), proxy_on, "warp.asOutbound", "warp.asOutbound", "proxy.enable = true");
v.requires(w.as_amnezia_wg, cfg.amnezia_wg.enable, "warp.asAmneziaWg", "warp.asAmneziaWg", "amneziaWg.enable = true");
v.requires(w.autostart, w.as_amnezia_wg, "warp.autostart", "warp.autostart", "warp.asAmneziaWg = true");
if w.instances.is_some() && !w.devices.is_empty() {
v.error("warp.instances", "instances cannot be used with devices");
}
if w.devices.len() > 1 && w.devices.contains_key(derived::WARP_TAG) {
v.error("warp.devices", "with several devices, \"warp\" names their group and cannot be a device");
}
if w.config_file.is_some() && w.config.is_some() {
v.error("warp.config", "set configFile or config, not both");
}
for name in w.devices.keys() {
if !path_name_ok(name) {
v.error(format!("warp.devices.{name}"), "a device name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
}
let a = &cfg.amnezia_wg;
if a.enable {
let mut autostarts = Vec::new();
for (name, p) in &a.profiles {
let path = format!("amneziaWg.profiles.{name}");
let sources = [p.config_file.is_some(), p.config.is_some(), p.vpn_file.is_some(), p.vpn.is_some(), p.settings.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("profile '{name}' needs exactly one of configFile, config, vpnFile, vpn and settings"));
}
if p.autostart {
autostarts.push(name.clone());
}
if p.as_outbound.is_some() && p.autostart {
v.warn(format!("{path}.autostart"), "an outbound always runs: autostart only applies to a global profile");
}
v.requires(p.as_outbound.is_some(), proxy_on, &format!("{path}.asOutbound"), &format!("amneziaWg.profiles.{name}.asOutbound"), "proxy.enable = true");
if !path_name_ok(name) {
v.error(&path, format!("profile name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if let Some(iface) = &p.interface_name
&& (!path_name_ok(iface) || iface.len() > 32)
{
v.error(format!("{path}.interfaceName"), "a tunnel name takes letters, digits, '.', '_' and '-' (at most 32, no leading dot)");
}
if let Some(settings) = &p.settings {
if settings.peers.is_empty() {
v.error(format!("{path}.settings.peers"), "a profile needs a peer");
}
if settings.private_key.is_some() == settings.private_key_file.is_some() {
v.error(format!("{path}.settings"), "set exactly one of privateKey and privateKeyFile");
}
}
if BUILTIN_TAGS.contains(&name.as_str()) {
v.error(&path, format!("'{name}' is a builtin target"));
}
}
if w.autostart {
autostarts.push(derived::WARP_TAG.into());
}
if autostarts.len() > 1 {
v.error("amneziaWg.profiles", format!("only one global profile can autostart, not {}", autostarts.join(", ")));
}
if !autostarts.is_empty() && cfg.proxy.autostart.is_some() {
v.error("proxy.autostart", "only one global mode can autostart: a TUN and an AmneziaWG profile both do");
}
}
let t = &cfg.tor;
if t.enable {
v.requires(t.as_outbound, proxy_on, "tor.asOutbound", "tor.asOutbound", "proxy.enable = true");
v.requires(t.onion_service.enable, cfg.inbounds.enable, "tor.onionService.enable", "tor.onionService.enable", "inbounds.enable = true");
if !t.as_outbound && !t.onion_service.enable {
v.warn("tor.enable", "Tor is on, but neither asOutbound nor onionService uses it");
}
if t.socks_port == t.control_port {
v.error("tor.controlPort", "Tor's SOCKS and control ports must differ");
}
}
let s = &cfg.ssh_proxy;
if s.enable {
if s.server.host.is_none() {
v.error("sshProxy.server.host", "the SSH tunnel needs a server");
}
if s.server.user.is_none() {
v.error("sshProxy.server.user", "the SSH tunnel needs a login user");
}
// 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()
&& s.host_key_file.is_none()
&& s.host_key.is_empty()
{
v.error("sshProxy.strictHostKeyChecking", "\"yes\" needs the server's keys: knownHostsFile, hostKeyFile or hostKey");
}
}
let g = &cfg.tg_ws_proxy;
if g.enable {
if g.secret.is_some() && g.secret_file.is_some() {
v.error("tgWsProxy.secret", "set secret or secretFile, not both");
}
if let Some(secret) = &g.secret
&& (secret.len() != 32 || !secret.chars().all(|c| c.is_ascii_hexdigit())) {
v.error("tgWsProxy.secret", "an MTProto secret is 32 hex digits");
}
if g.buffer_kib < 4 {
v.error("tgWsProxy.bufferKiB", "the buffer is at least 4 KiB");
}
}
let wl = &cfg.whitelist_bypass;
if wl.enable {
v.requires(!wl.joiners.is_empty(), proxy_on, "whitelistBypass.joiners", "whitelistBypass.joiners", "proxy.enable = true");
for name in wl.joiners.keys().chain(wl.creators.keys()) {
if !path_name_ok(name) {
v.error(format!("whitelistBypass.{name}"), "a creator or joiner name takes letters, digits, '.', '_' and '-', and no leading dot");
}
}
for (name, j) in &wl.joiners {
if j.platform == crate::config::WlPlatform::Vk {
v.error(format!("whitelistBypass.joiners.{name}.platform"), "VK has no joiner here");
}
}
if wl.joiners.is_empty() && wl.creators.is_empty() {
v.warn("whitelistBypass.enable", "whitelist-bypass is on without creators or joiners");
}
}
}
fn zapret(cfg: &Config, v: &mut Issues) {
let z = &cfg.zapret;
if !z.enable {
return;
}
if z.engine == ZapretEngine::DiscordYoutube {
let mut names = BTreeSet::new();
for (i, rule) in z.discord_youtube.hostlist_rules.iter().enumerate() {
let path = format!("zapret.zapret-discord-youtube.hostlistRules.{i}");
if !profile_name_ok(&rule.name) {
v.error(format!("{path}.name"), "a list name takes lowercase letters, digits and '-'");
} else if !names.insert(rule.name.as_str()) {
v.error(format!("{path}.name"), format!("list '{}' is defined twice", rule.name));
}
// 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");
}
if rule.preset.is_none() && rule.config_name.is_none() && rule.nfqws_args.is_empty() && rule.default_domains.len() != 1 {
v.error(&path, "without preset, configName or nfqwsArgs, use exactly one of defaultDomains, so its strategy can be inferred");
}
if rule.domains.is_empty() && rule.default_domains.is_empty() && rule.ips.is_empty() && rule.default_ips.is_empty() {
v.warn(&path, format!("list '{}' holds no sites", rule.name));
}
}
}
for (label, list) in [
("zapret.zapret2.domains", &z.zapret2.domains),
("zapret.zapret2.excludeDomains", &z.zapret2.exclude_domains),
("zapret.zapret-discord-youtube.domains", &z.discord_youtube.domains),
("zapret.zapret-discord-youtube.excludeDomains", &z.discord_youtube.exclude_domains),
] {
for d in list.iter().filter(|d| !crate::zapret2::host_entry_ok(d)) {
v.error(label, format!("'{d}' is not a site name: letters, digits, '.', '-', '_', '*', and '^' first for an exact match"));
}
}
for (label, list) in [
("zapret.zapret-discord-youtube.ips", &z.discord_youtube.ips),
("zapret.zapret-discord-youtube.excludeIps", &z.discord_youtube.exclude_ips),
("zapret.cidrExemption.cidrs", &z.cidr_exemption.cidrs),
] {
for ip in list.iter().filter(|ip| ip.parse::<ipnet::IpNet>().is_err() && ip.parse::<std::net::IpAddr>().is_err()) {
v.error(label, format!("'{ip}' is not an address or CIDR"));
}
}
if z.engine == ZapretEngine::Zapret2 {
let ah = &z.zapret2.auto_hostlist;
for (label, value) in [("failThreshold", ah.fail_threshold), ("failTime", ah.fail_time), ("retransThreshold", ah.retrans_threshold), ("udpOut", ah.udp_out)] {
if value == 0 {
v.error(format!("zapret.zapret2.autoHostlist.{label}"), "it must be greater than zero");
}
}
if z.zapret2.proxy_fallback && !derived::has_available_outbounds(cfg) {
v.warn("zapret.zapret2.proxyFallback", "proxyFallback needs an outbound to fall back to");
}
if z.zapret2.cutoff.enable && z.zapret2.cutoff.proxy_fallback && !derived::sing_box_enabled(cfg) {
v.warn("zapret.zapret2.cutoff.proxyFallback", "the cutoff fallback needs the sing-box backend");
}
}
if z.cidr_exemption.enable && z.cidr_exemption.cidrs.is_empty() {
v.warn("zapret.cidrExemption", "the exemption is on but lists no networks");
}
}
fn per_app(cfg: &Config, v: &mut Issues) {
let pa = &cfg.per_app_routing;
if !pa.enable {
return;
}
v.requires(true, cfg.proxy.enable, "perAppRouting.enable", "perAppRouting", "proxy.enable = true");
if !cfg.proxy.backend.runs_sing_box() {
v.error("perAppRouting.enable", "per-app routing needs the sing-box or hybrid backend");
}
let mut names = BTreeSet::new();
for (i, prof) in pa.profiles.iter().enumerate() {
let path = format!("perAppRouting.profiles.{i}");
if !profile_name_ok(&prof.name) {
v.error(format!("{path}.name"), "a profile name takes lowercase letters, digits and '-'");
} else if !names.insert(prof.name.as_str()) {
v.error(format!("{path}.name"), format!("profile '{}' is defined twice", prof.name));
}
if !derived::is_known_target(cfg, &prof.outbound) {
v.error(format!("{path}.outbound"), format!("'{}' is not an outbound, a group, or proxy, direct or block", prof.outbound));
}
}
if pa.profiles.len() > 200 {
v.error("perAppRouting.profiles", "at most 200 profiles");
}
}
fn inbounds(cfg: &Config, v: &mut Issues) {
let ib = &cfg.inbounds;
if !ib.enable {
return;
}
let via_ok = |via: &str| {
matches!(via, "proxy" | "direct" | "block") || cfg.proxy.outbounds.iter().any(|o| o.tag == via)
};
if !via_ok(&ib.routing.via) {
v.error("inbounds.routing.via", format!("'{}' is not proxy, direct, block or a proxy.outbounds tag", ib.routing.via));
}
v.requires(ib.routing.via == "proxy", cfg.proxy.enable, "inbounds.routing.via", "inbounds.routing.via = \"proxy\"", "proxy.enable = true");
v.requires(ib.subscriptions.enable, ib.share_links, "inbounds.subscriptions.enable", "inbounds.subscriptions", "inbounds.shareLinks = true");
let mut ports: BTreeMap<(u16, bool), &str> = BTreeMap::new();
for (tag, l) in &ib.listeners {
let path = format!("inbounds.listeners.{tag}");
if !path_name_ok(tag) {
v.error(&path, format!("listener tag '{tag}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
let sources = [l.kind.is_some(), l.xray_json.is_some(), l.json_file.is_some()];
if count_some(&sources) != 1 {
v.error(&path, format!("listener '{tag}' needs exactly one of type, xrayJson and jsonFile"));
}
for user in &l.users {
if !ib.users.contains_key(user) {
v.error(format!("{path}.users"), format!("listener '{tag}' names user '{user}', which inbounds.users does not define"));
}
}
if let Some(via) = &l.via
&& !via_ok(via) {
v.error(format!("{path}.via"), format!("'{via}' is not proxy, direct, block or a proxy.outbounds tag"));
}
if l.tls.enable && l.reality.enable {
v.error(&path, "tls cannot be used with reality");
}
use crate::config::InboundType as T;
let udp = matches!(l.kind, Some(T::Hysteria2) | Some(T::Amneziawg));
if let Some(other) = ports.insert((l.port, udp), tag) {
v.error(format!("{path}.port"), format!("listeners '{other}' and '{tag}' share port {}", l.port));
}
match l.kind {
Some(T::Hysteria2) if !l.tls.enable => {
v.error(format!("{path}.tls"), "hysteria2 needs tls");
}
Some(T::Trojan) if !l.tls.enable && !l.reality.enable => {
v.error(format!("{path}.tls"), "trojan needs tls or reality");
}
_ => {}
}
if l.reality.enable {
if l.reality.server_names.is_empty() {
v.error(format!("{path}.reality.serverNames"), "REALITY needs at least one server name");
}
if l.reality.private_key.is_some() == l.reality.private_key_file.is_some() {
v.error(format!("{path}.reality"), "set exactly one of privateKey and privateKeyFile");
}
if ib.share_links && l.reality.public_key.is_none() {
v.warn(format!("{path}.reality.publicKey"), "share links need the public key");
}
}
if l.tls.enable && (l.tls.certificate_file.is_none() || l.tls.key_file.is_none()) {
v.error(format!("{path}.tls"), "TLS needs certificateFile and keyFile");
}
if l.flow.is_some() && l.transport.kind != "raw" {
v.error(format!("{path}.flow"), "the vision flow only works on the raw transport");
}
}
let mut orders = BTreeMap::new();
for (name, user) in &ib.users {
if !path_name_ok(name) {
v.error(format!("inbounds.users.{name}"), format!("user name '{name}' takes letters, digits, '.', '_' and '-', and no leading dot"));
}
if let Some(order) = user.order
&& let Some(other) = orders.insert(order, name) {
v.error(format!("inbounds.users.{name}.order"), format!("users '{other}' and '{name}' share order {order}"));
}
if user.uuid.is_some() && user.uuid_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set uuid or uuidFile, not both");
}
if user.password.is_some() && user.password_file.is_some() {
v.error(format!("inbounds.users.{name}"), "set password or passwordFile, not both");
}
}
if ib.manager.enable && (ib.manager.interval < 5 || ib.manager.interval > 3600) {
v.error("inbounds.manager.interval", "between 5 and 3600 seconds");
}
if ib.manager.api.listen.is_some() && ib.manager.api.tokens_file.is_none() {
v.error("inbounds.manager.api.listen", "a TCP API needs tokensFile");
}
}
/// Loopback listeners must not collide: whichever starts second would die.
fn ports(cfg: &Config, v: &mut Issues) {
let mut taken: BTreeMap<u16, String> = BTreeMap::new();
let mut claim = |port: u16, who: String, v: &mut Issues| {
if let Some(other) = taken.get(&port) {
v.error(who.clone(), format!("port {port} is taken by {other} too"));
} else {
taken.insert(port, who);
}
};
let p = &cfg.proxy;
if p.enable {
claim(p.listener.port, "proxy.listener.port".into(), v);
if p.backend.runs_sing_box() {
claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v);
}
if p.backend.runs_sing_box() {
claim(p.sing_box.test_port, "proxy.singBox.testPort".into(), v);
}
}
if cfg.tor.enable {
claim(cfg.tor.socks_port, "tor.socksPort".into(), v);
claim(cfg.tor.control_port, "tor.controlPort".into(), v);
}
if cfg.ssh_proxy.enable {
claim(cfg.ssh_proxy.listener.port, "sshProxy.listener.port".into(), v);
}
if cfg.tg_ws_proxy.enable {
claim(cfg.tg_ws_proxy.listener.port, "tgWsProxy.listener.port".into(), v);
}
if cfg.per_app_routing.enable {
for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() {
claim(
cfg.per_app_routing.listener_base_port.saturating_add(i as u16),
format!("perAppRouting.profiles.{i} ({})", prof.name),
v,
);
}
}
for ob in derived::extra_outbounds(cfg) {
use derived::ExtraKind as K;
match ob.kind {
K::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => {
claim(port, format!("AmneziaWG outbound '{}'", ob.tag), v)
}
K::WlJoiner { port, .. } => claim(port, format!("whitelist-bypass joiner '{}'", ob.tag), v),
K::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => {
claim(device.port, format!("WARP device '{}'", device.tag), v)
}
_ => {}
}
}
if p.enable && p.auto_proxy.enable {
let base = p.auto_proxy.probe_base_port;
for i in 0..p.auto_proxy.max_exits.min(64) as u16 {
claim(base.saturating_add(i), format!("proxy.autoProxy.probeBasePort (+{i})"), v);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::{Group, Outbound, RoutingRule};
fn errors(cfg: &Config) -> Vec<String> {
validate(cfg)
.into_iter()
.filter(|i| i.severity == Severity::Error)
.map(|i| format!("{}: {}", i.path, i.message))
.collect()
}
fn outbound(tag: &str) -> Outbound {
Outbound { tag: tag.into(), url: Some("hy2://pw@example.com:443".into()), ..Default::default() }
}
#[test]
fn the_default_config_is_valid() {
assert_eq!(errors(&Config::default()), Vec::<String>::new());
}
#[test]
fn 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();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de"), outbound("de"), outbound("direct")];
let errs = errors(&cfg);
assert!(errs.iter().any(|e| e.contains("'de' is used twice")), "{errs:?}");
assert!(errs.iter().any(|e| e.contains("'direct' is a builtin")), "{errs:?}");
}
#[test]
fn an_outbound_needs_exactly_one_source() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![Outbound { tag: "x".into(), ..Default::default() }];
assert!(errors(&cfg)[0].contains("needs exactly one"));
}
#[test]
fn rule_targets_must_exist() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![outbound("de")];
cfg.proxy.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], ..Default::default() });
let rule = |target: &str| RoutingRule {
outbound: target.into(),
matches: crate::config::RouteMatch { domains: vec!["example.com".into()], ..Default::default() },
..Default::default()
};
cfg.proxy.routing.rules = vec![rule("de"), rule("eu"), rule("direct"), rule("nowhere")];
let errs = errors(&cfg);
assert_eq!(errs.len(), 1, "{errs:?}");
assert!(errs[0].contains("'nowhere'"));
}
#[test]
fn colliding_ports_are_refused() {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![outbound("de")];
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.tor.socks_port = 1080;
assert!(errors(&cfg).iter().any(|e| e.contains("port 1080")));
}
#[test]
fn names_that_become_paths_are_checked() {
let mut cfg = Config::default();
cfg.amnezia_wg.enable = true;
cfg.amnezia_wg.profiles.insert(
"..\\evil".into(),
crate::config::AwgProfile { config: Some("[Interface]".into()), ..Default::default() },
);
assert!(errors(&cfg).iter().any(|e| e.contains("profile name")), "{:?}", errors(&cfg));
}
#[test]
fn groups_need_sing_box() {
let mut cfg = Config::default();
cfg.proxy.backend = Backend::Xray;
cfg.proxy.groups.insert("g".into(), Group::default());
assert!(errors(&cfg).iter().any(|e| e.contains("groups need")));
}
}
+270
View File
@@ -0,0 +1,270 @@
//! `zapret`: DPI bypass without a proxy, through WinDivert.
//!
//! zapret-discord-youtube runs Flowseal's Windows release (`winws.exe`) with the strategy of
//! one of its `general*.bat` presets; zapret2 runs `winws2.exe` from bol-van's
//! zapret-win-bundle with Lua strategies. Both intercept with WinDivert, so only one can run.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use serde_json::Value;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ZapretEngine {
#[default]
#[serde(rename = "zapret-discord-youtube")]
DiscordYoutube,
#[serde(rename = "zapret2")]
Zapret2,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret {
pub enable: bool,
pub engine: ZapretEngine,
pub direct_sync: DirectSync,
pub cidr_exemption: CidrExemption,
/// Windows only: turn on TCP timestamps (`netsh interface tcp set global
/// timestamps=enabled`), which both Flowseal's and bol-van's installers do: strategies
/// that fool DPI with them need them.
pub tcp_timestamps: bool,
#[serde(rename = "zapret-discord-youtube")]
pub discord_youtube: DiscordYoutube,
pub zapret2: Zapret2,
}
impl Default for Zapret {
fn default() -> Self {
Self {
enable: false,
engine: ZapretEngine::DiscordYoutube,
direct_sync: DirectSync::default(),
cidr_exemption: CidrExemption::default(),
tcp_timestamps: true,
discord_youtube: DiscordYoutube::default(),
zapret2: Zapret2::default(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DirectSync {
pub enable: bool,
pub upstream_ips: bool,
pub user_ips: bool,
}
impl Default for DirectSync {
fn default() -> Self {
Self { enable: true, upstream_ips: false, user_ips: true }
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct CidrExemption {
pub enable: bool,
pub cidrs: Vec<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum GameFilter {
All,
Tcp,
Udp,
#[default]
Null,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct DiscordYoutube {
/// A preset's name as Flowseal's release names its `.bat` (spaces are ignored):
/// "general", "general(ALT)" … "general(ALT13)", "general(FAKE TLS AUTO)" …
pub config_name: String,
pub game_filter: GameFilter,
pub domains: Vec<String>,
pub exclude_domains: Vec<String>,
pub ips: Vec<String>,
pub exclude_ips: Vec<String>,
pub include_extra_upstream_lists: bool,
pub hostlist_rules: Vec<HostlistRule>,
}
impl Default for DiscordYoutube {
fn default() -> Self {
Self {
config_name: "general(ALT)".into(),
game_filter: GameFilter::Null,
domains: Vec::new(),
exclude_domains: Vec::new(),
ips: Vec::new(),
exclude_ips: Vec::new(),
include_extra_upstream_lists: false,
hostlist_rules: Vec::new(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretPreset {
General,
Google,
Instagram,
Soundcloud,
Twitter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretDefaultDomains {
General,
Google,
Discord,
Youtube,
Instagram,
Soundcloud,
Twitter,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ZapretDefaultIps {
All,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct HostlistRule {
pub name: String,
pub domains: Vec<String>,
pub default_domains: Vec<ZapretDefaultDomains>,
pub ips: Vec<String>,
pub default_ips: Vec<ZapretDefaultIps>,
pub preset: Option<ZapretPreset>,
pub config_name: Option<String>,
/// Raw winws arguments (nfqws's syntax, which winws shares); `--hostlist` and `--new`
/// are added.
pub nfqws_args: Vec<String>,
pub enable_direct_sync: bool,
}
impl Default for HostlistRule {
fn default() -> Self {
Self {
name: String::new(),
domains: Vec::new(),
default_domains: Vec::new(),
ips: Vec::new(),
default_ips: Vec::new(),
preset: None,
config_name: None,
nfqws_args: Vec::new(),
enable_direct_sync: true,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum StrategySource {
#[default]
#[serde(rename = "nfqws2-keenetic")]
Nfqws2Keenetic,
#[serde(rename = "z2k")]
Z2k,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret2 {
pub strategy_source: StrategySource,
pub profiles: Option<Vec<String>>,
pub blobs: BTreeMap<String, String>,
pub domains: Vec<String>,
pub exclude_domains: Vec<String>,
pub ports: Zapret2Ports,
pub proxy_fallback: bool,
pub strategy_log: bool,
pub ipv6: bool,
pub auto_hostlist: AutoHostlist,
pub cutoff: Cutoff,
}
impl Default for Zapret2 {
fn default() -> Self {
Self {
strategy_source: StrategySource::Nfqws2Keenetic,
profiles: None,
blobs: BTreeMap::new(),
domains: Vec::new(),
exclude_domains: Vec::new(),
ports: Zapret2Ports::default(),
proxy_fallback: true,
strategy_log: true,
ipv6: false,
auto_hostlist: AutoHostlist::default(),
cutoff: Cutoff::default(),
}
}
}
/// A port, or a "low-high" range.
pub type PortOrRange = Value;
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Zapret2Ports {
pub tcp: Option<String>,
pub udp: Option<String>,
pub extra_tcp: Vec<PortOrRange>,
pub extra_udp: Vec<PortOrRange>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct AutoHostlist {
pub enable: bool,
pub fail_threshold: u32,
pub fail_time: u32,
pub retrans_threshold: u32,
pub retrans_reset: bool,
pub retrans_maxseq: u32,
pub incoming_maxseq: u32,
pub udp_out: u32,
pub udp_in: u32,
pub extended_detection: bool,
}
impl Default for AutoHostlist {
fn default() -> Self {
Self {
enable: true,
fail_threshold: 3,
fail_time: 300,
retrans_threshold: 3,
retrans_reset: true,
retrans_maxseq: 32768,
incoming_maxseq: 4096,
udp_out: 4,
udp_in: 1,
extended_detection: true,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default, deny_unknown_fields)]
pub struct Cutoff {
pub enable: bool,
pub proxy_fallback: bool,
}
impl Default for Cutoff {
fn default() -> Self {
Self { enable: true, proxy_fallback: true }
}
}
+262
View File
@@ -0,0 +1,262 @@
//! What the configuration implies beyond its options: the outbounds that tunnels add, the
//! loopback ports everything listens on, which backends run. Upstream's `derived.nix`.
use crate::config::{
AwgOutboundKind, Backend, Config, WarpOutboundKind, WlPlatform,
};
/// Tags no outbound may take: the routing targets every config has.
pub const BUILTIN_TAGS: [&str; 3] = ["proxy", "direct", "block"];
pub const SSH_OUTBOUND_TAG: &str = "ssh-proxy";
pub const TOR_OUTBOUND_TAG: &str = "tor";
pub const WARP_TAG: &str = "warp";
/// Fixed loopback ports, as upstream numbers them where it has them.
pub mod ports {
/// The listener `proxy-ctl proxy outbounds test` dials each outbound through.
pub const OUTBOUND_TEST: u16 = 18537;
/// The global TUN's own Clash API (it is a separate sing-box instance).
pub const TUN_CLASH_API: u16 = 19181;
/// wireproxy-awg listeners of "userspace" AmneziaWG outbounds, one each.
pub const AWG_TUNNEL_BASE: u16 = 18600;
/// whitelist-bypass joiners' SOCKS listeners, one each.
pub const WL_JOINER_BASE: u16 = 18750;
/// wireproxy-awg listeners of "userspace" WARP devices, one each.
pub const WARP_USERSPACE_BASE: u16 = 18900;
/// The hybrid backend's XRay sidecar, which sing-box hands XRay-only outbounds to.
pub const XRAY_SIDECAR_SOCKS: u16 = 33080;
pub const XRAY_SIDECAR_TUN: u16 = 33180;
}
/// An outbound that a tunnel, not `proxy.outbounds`, adds.
#[derive(Debug, Clone, PartialEq)]
pub struct ExtraOutbound {
pub tag: String,
pub kind: ExtraKind,
}
#[derive(Debug, Clone, PartialEq)]
pub enum ExtraKind {
/// OpenSSH's `-D` listener (or sing-box's own SSH outbound, which needs a host key).
Ssh,
/// Tor's SOCKS port.
Tor { port: u16 },
/// A WARP device: a WireGuard endpoint in sing-box, or wireproxy-awg on `port`.
Warp { device: WarpDeviceSpec },
/// An AmneziaWG profile used as an outbound.
Awg { profile: String, kind: AwgOutboundKind, port: u16 },
/// A whitelist-bypass joiner's SOCKS listener.
WlJoiner { platform: WlPlatform, port: u16 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct WarpDeviceSpec {
pub tag: String,
/// The first device keeps a single device's state directory, so a registration carries
/// over when more are added.
pub first: bool,
pub kind: WarpOutboundKind,
pub config_file: Option<String>,
pub config: Option<String>,
pub endpoint: Option<String>,
/// The wireproxy-awg listener, for the "userspace" kind.
pub port: u16,
/// Below the state directory: `warp` for the first device, `warp/<tag>` for the rest.
pub state_subdir: String,
}
impl WarpDeviceSpec {
/// Registered on first start: no profile was given.
pub fn auto_register(&self) -> bool {
self.config_file.is_none() && self.config.is_none()
}
}
/// The WARP device tags: "warp", or what `devices` or `instances` name.
pub fn warp_device_names(cfg: &Config) -> Vec<String> {
if let Some(n) = cfg.warp.instances {
(1..=n).map(|i| format!("warp-{i}")).collect()
} else if !cfg.warp.devices.is_empty() {
cfg.warp.devices.keys().cloned().collect()
} else {
vec![WARP_TAG.to_owned()]
}
}
pub fn warp_devices(cfg: &Config) -> Vec<WarpDeviceSpec> {
let Some(kind) = cfg.warp.as_outbound.filter(|_| cfg.warp.enable) else {
return Vec::new();
};
warp_device_names(cfg)
.into_iter()
.enumerate()
.map(|(index, tag)| {
let device = cfg.warp.devices.get(&tag).cloned().unwrap_or_default();
let first = index == 0;
let (config_file, config) = if device.config_file.is_some() || device.config.is_some() {
(device.config_file, device.config)
} else if first {
(cfg.warp.config_file.clone(), cfg.warp.config.clone())
} else {
(None, None)
};
WarpDeviceSpec {
state_subdir: if first { "warp".into() } else { format!("warp/{tag}") },
tag,
first,
kind,
config_file,
config,
endpoint: device.endpoint.or_else(|| cfg.warp.endpoint.clone()),
port: ports::WARP_USERSPACE_BASE + index as u16,
}
})
.collect()
}
/// Whether "warp" names a group of devices rather than a device.
pub fn warp_grouped(cfg: &Config) -> bool {
warp_devices(cfg).len() > 1
}
/// The AmneziaWG profiles that are outbounds, in name order.
pub fn awg_outbounds(cfg: &Config) -> Vec<(String, AwgOutboundKind, u16)> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
cfg.amnezia_wg
.profiles
.iter()
.filter_map(|(name, p)| p.as_outbound.map(|kind| (name.clone(), kind)))
.enumerate()
.map(|(i, (name, kind))| (name, kind, ports::AWG_TUNNEL_BASE + i as u16))
.collect()
}
/// The AmneziaWG profiles that are global VPNs (`proxy-ctl awg on`), in name order.
pub fn awg_global_profiles(cfg: &Config) -> Vec<String> {
if !cfg.amnezia_wg.enable {
return Vec::new();
}
let mut names: Vec<String> = cfg
.amnezia_wg
.profiles
.iter()
.filter(|(_, p)| p.as_outbound.is_none())
.map(|(name, _)| name.clone())
.collect();
if cfg.warp.enable && cfg.warp.as_amnezia_wg && !names.iter().any(|n| n == WARP_TAG) {
names.push(WARP_TAG.into());
}
names
}
/// Every outbound the tunnels add, in the order upstream lists them.
pub fn extra_outbounds(cfg: &Config) -> Vec<ExtraOutbound> {
let mut out = Vec::new();
if cfg.ssh_proxy.enable && cfg.ssh_proxy.as_outbound {
out.push(ExtraOutbound { tag: SSH_OUTBOUND_TAG.into(), kind: ExtraKind::Ssh });
}
for device in warp_devices(cfg) {
out.push(ExtraOutbound { tag: device.tag.clone(), kind: ExtraKind::Warp { device } });
}
if cfg.tor.enable && cfg.tor.as_outbound {
out.push(ExtraOutbound {
tag: TOR_OUTBOUND_TAG.into(),
kind: ExtraKind::Tor { port: cfg.tor.socks_port },
});
}
if cfg.whitelist_bypass.enable {
for (i, (tag, joiner)) in cfg.whitelist_bypass.joiners.iter().enumerate() {
out.push(ExtraOutbound {
tag: tag.clone(),
kind: ExtraKind::WlJoiner {
platform: joiner.platform,
port: ports::WL_JOINER_BASE + i as u16,
},
});
}
}
for (profile, kind, port) in awg_outbounds(cfg) {
out.push(ExtraOutbound {
tag: profile.clone(),
kind: ExtraKind::Awg { profile, kind, port },
});
}
out
}
/// The tags known before anything runs: declared outbounds and the tunnels'. Subscription
/// entries only exist once fetched.
pub fn effective_outbound_tags(cfg: &Config) -> Vec<String> {
let mut tags: Vec<String> = cfg.proxy.outbounds.iter().map(|o| o.tag.clone()).collect();
tags.extend(extra_outbounds(cfg).into_iter().map(|o| o.tag));
if warp_grouped(cfg) {
tags.push(WARP_TAG.into());
}
tags
}
pub fn group_tags(cfg: &Config) -> Vec<String> {
cfg.proxy.groups.keys().cloned().collect()
}
/// Whether a routing target names something: a builtin, an outbound or a group.
pub fn is_known_target(cfg: &Config, target: &str) -> bool {
BUILTIN_TAGS.contains(&target)
|| effective_outbound_tags(cfg).iter().any(|t| t == target)
|| cfg.proxy.groups.contains_key(target)
}
/// Whether the proxy has anything to send traffic through, before subscriptions are fetched.
pub fn has_available_outbounds(cfg: &Config) -> bool {
!cfg.proxy.outbounds.is_empty()
|| !cfg.proxy.subscriptions.is_empty()
|| !extra_outbounds(cfg).is_empty()
}
pub fn sing_box_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend.runs_sing_box()
}
pub fn xray_enabled(cfg: &Config) -> bool {
cfg.proxy.enable && cfg.proxy.backend != Backend::SingBox
}
pub fn tor_route_onion(cfg: &Config) -> bool {
cfg.tor.enable && cfg.tor.as_outbound && cfg.tor.route_onion && cfg.proxy.enable
}
#[cfg(test)]
mod tests {
use super::*;
use crate::config::WarpDevice;
#[test]
fn warp_names_follow_instances_then_devices() {
let mut cfg = Config::default();
assert_eq!(warp_device_names(&cfg), ["warp"]);
cfg.warp.devices.insert("warp-b".into(), WarpDevice::default());
cfg.warp.devices.insert("warp-a".into(), WarpDevice::default());
assert_eq!(warp_device_names(&cfg), ["warp-a", "warp-b"]);
cfg.warp.instances = Some(3);
assert_eq!(warp_device_names(&cfg), ["warp-1", "warp-2", "warp-3"]);
}
#[test]
fn first_warp_device_inherits_the_top_level_profile() {
let mut cfg = Config::default();
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
cfg.warp.config_file = Some(r"C:\secrets\wgcf.conf".into());
cfg.warp.instances = Some(2);
let devices = warp_devices(&cfg);
assert_eq!(devices[0].config_file.as_deref(), Some(r"C:\secrets\wgcf.conf"));
assert!(!devices[0].auto_register());
assert!(devices[1].auto_register());
assert_eq!(devices[1].state_subdir, "warp/warp-2");
assert!(warp_grouped(&cfg));
assert!(effective_outbound_tags(&cfg).contains(&"warp".to_owned()));
}
}
+58
View File
@@ -0,0 +1,58 @@
//! Time spans as the options write them: systemd's ("1d", "6h", "1h 30min") and Go's
//! ("3m", "15s", "1m30s", "500ms").
use std::time::Duration;
/// A span such as "1d", "6h 30m", "1m30s" or "500ms". A bare number is seconds.
pub fn parse(text: &str) -> Option<Duration> {
let text = text.trim();
if text.is_empty() {
return None;
}
if let Ok(secs) = text.parse::<f64>() {
return (secs >= 0.0).then(|| Duration::from_secs_f64(secs));
}
let mut total = 0f64;
let mut rest = text;
while !rest.is_empty() {
rest = rest.trim_start();
let num_len = rest.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(rest.len());
if num_len == 0 {
return None;
}
let value: f64 = rest[..num_len].parse().ok()?;
rest = &rest[num_len..];
let unit_len = rest.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(rest.len());
let unit = &rest[..unit_len];
rest = &rest[unit_len..];
let factor = match unit {
"ns" => 1e-9,
"us" | "µs" => 1e-6,
"ms" | "msec" => 1e-3,
"s" | "sec" | "second" | "seconds" | "" => 1.0,
"m" | "min" | "minute" | "minutes" => 60.0,
"h" | "hr" | "hour" | "hours" => 3600.0,
"d" | "day" | "days" => 86400.0,
"w" | "week" | "weeks" => 604800.0,
_ => return None,
};
total += value * factor;
}
Some(Duration::from_secs_f64(total))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn both_spellings_read() {
assert_eq!(parse("1d"), Some(Duration::from_secs(86400)));
assert_eq!(parse("6h 30min"), Some(Duration::from_secs(6 * 3600 + 1800)));
assert_eq!(parse("1m30s"), Some(Duration::from_secs(90)));
assert_eq!(parse("500ms"), Some(Duration::from_millis(500)));
assert_eq!(parse("45"), Some(Duration::from_secs(45)));
assert_eq!(parse("soon"), None);
assert_eq!(parse("3x"), None);
}
}
+17
View File
@@ -0,0 +1,17 @@
//! Proxy Suite for Windows: everything that is pure logic.
//!
//! The configuration model (upstream's `services.proxy-suite` options), share-link and
//! subscription parsing, and the sing-box and XRay configs the service runs. Nothing here
//! touches the network, the file system or processes; the service does that.
pub mod 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;
+175
View File
@@ -0,0 +1,175 @@
//! Share links to backend outbounds: upstream's `scripts/proxy_url_parsers.py` and
//! `proxy_parsing.py`, ported with their checks and messages.
//!
//! A link becomes a sing-box-shaped outbound first; for XRay it is then rendered into XRay's
//! shape. Each parser refuses what the backend would refuse to start on, so one bad
//! subscription entry is skipped instead of taking every other outbound down with it.
//!
//! Upstream's `routing_mark` (Linux SO_MARK) has no Windows counterpart and is left out.
mod parsers;
pub mod py;
pub mod subscription;
mod xray;
use std::fmt;
use serde_json::{Map, Value};
pub use parsers::SCHEMES;
pub use xray::render_xray_outbound;
/// Which backend an outbound is built for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkBackend {
SingBox,
Xray,
}
impl LinkBackend {
pub fn as_str(self) -> &'static str {
match self {
Self::SingBox => "sing-box",
Self::Xray => "xray",
}
}
}
/// Why a link was refused. The message never quotes a credential.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LinkError {
/// The link is malformed, or the backend would refuse it.
Invalid(String),
/// A subscription entry whose server is this host, its link, or (unless allowed) a
/// private network: whichever backend reads it, it is skipped.
RefusedServer(String),
}
impl LinkError {
pub(crate) fn invalid(message: impl Into<String>) -> Self {
Self::Invalid(message.into())
}
pub fn message(&self) -> &str {
match self {
Self::Invalid(m) | Self::RefusedServer(m) => m,
}
}
}
impl fmt::Display for LinkError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.message())
}
}
impl std::error::Error for LinkError {}
pub type Result<T> = std::result::Result<T, LinkError>;
/// The scheme of a link, lowercased: what comes before `://`.
pub fn detect_scheme(url: &str) -> String {
url.split("://").next().unwrap_or("").to_lowercase()
}
/// Parses a link into a sing-box-shaped outbound tagged `tag`, checked against `backend`.
pub fn parse_url(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let scheme = detect_scheme(url);
parsers::parse(&scheme, url, tag, backend)
}
/// A link as the backend's outbound: sing-box's shape, or XRay's.
pub fn build_outbound(url: &str, tag: &str, backend: LinkBackend) -> Result<Value> {
let ob = parse_url(url, tag, backend)?;
finish_outbound(ob, backend)
}
pub(crate) fn finish_outbound(ob: Map<String, Value>, backend: LinkBackend) -> Result<Value> {
match backend {
LinkBackend::Xray => render_xray_outbound(&ob),
LinkBackend::SingBox => Ok(Value::Object(ob)),
}
}
/// Every key anywhere in `value`, lowercased.
fn all_keys(value: &Value) -> Vec<String> {
let mut found = Vec::new();
let mut stack = vec![value];
while let Some(item) = stack.pop() {
match item {
Value::Object(map) => {
for (k, v) in map {
found.push(py_lower(k));
stack.push(v);
}
}
Value::Array(list) => stack.extend(list),
_ => {}
}
}
found
}
/// `str.lower()`, which folds the Kelvin sign to `k` as Go's JSON decoding does.
fn py_lower(s: &str) -> String {
s.to_lowercase()
}
/// The keys anywhere in `value` that point a backend at a local file or program. The
/// backends run as SYSTEM here, and a share link is whatever a subscription serves: an xhttp
/// `extra` carries a whole streamSettings, where `certificateFile` is a file XRay reads and
/// `masterKeyLog` one it writes. Any non-ASCII key counts too: Go's JSON folds case, reading
/// "maſterKeyLog" as masterKeyLog.
pub fn local_file_keys(value: &Value) -> Vec<String> {
let mut keys: Vec<String> = all_keys(value)
.into_iter()
.filter(|k| {
!k.is_ascii()
|| k.ends_with("file")
|| k.ends_with("directory")
|| (k.ends_with("path") && k != "path")
|| matches!(k.as_str(), "masterkeylog" | "torrc" | "extra_args")
})
.collect();
keys.sort();
keys.dedup();
keys
}
/// Socket options a share link must not set: a mark or interface steers around the routing,
/// a dialerProxy chains elsewhere. Other socket options stay.
const SOCKET_KEYS: [&str; 5] = ["customsockopt", "dialerproxy", "interface", "mark", "tproxy"];
fn strip_socket_keys(value: &mut Value) {
match value {
Value::Object(map) => {
map.retain(|k, _| !SOCKET_KEYS.contains(&py_lower(k).as_str()));
for v in map.values_mut() {
strip_socket_keys(v);
}
}
Value::Array(list) => list.iter_mut().for_each(strip_socket_keys),
_ => {}
}
}
/// A JSON object carried in a link parameter (xhttp's `extra`), checked as upstream does.
fn parse_json_param(value: &str, name: &str) -> Result<Value> {
let mut parsed: Value = serde_json::from_str(value)
.map_err(|e| LinkError::invalid(format!("invalid {name} JSON: {e}")))?;
if !parsed.is_object() {
return Err(LinkError::invalid(format!("invalid {name} JSON: expected object")));
}
let unsafe_keys = local_file_keys(&parsed);
if !unsafe_keys.is_empty() {
return Err(LinkError::invalid(format!("{name} JSON names local files: {}", unsafe_keys.join(", "))));
}
strip_socket_keys(&mut parsed);
if all_keys(&parsed).iter().any(|k| k == "allowinsecure") {
return Err(LinkError::invalid(format!("{name} JSON sets allowInsecure, which XRay no longer accepts")));
}
Ok(parsed)
}
#[cfg(test)]
mod tests;
+878
View File
@@ -0,0 +1,878 @@
//! One parser per scheme, as `proxy_url_parsers.py` has them.
use std::collections::HashMap;
use std::sync::LazyLock;
use regex::Regex;
use serde_json::{Map, Value, json};
use super::py::{self, b64decode, b64decode_strict, pad, prefix, repr, unquote, urlsafe_b64decode};
use super::{LinkBackend, LinkError, Result, parse_json_param};
/// Every scheme a link may have.
pub const SCHEMES: [&str; 16] = [
"vless", "vmess", "trojan", "ss", "hysteria2", "hy2", "tuic", "anytls", "naive+https", "naive+quic",
"socks5", "socks5h", "socks4", "socks4a", "http", "https",
];
pub(super) fn parse(scheme: &str, url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
match scheme {
"vless" => parse_vless(url, tag, backend),
"vmess" => parse_vmess(url, tag, backend),
"trojan" => parse_trojan(url, tag, backend),
"ss" => parse_shadowsocks(url, tag, backend),
"hysteria2" | "hy2" => parse_hysteria2(url, tag, backend),
"tuic" => parse_tuic(url, tag),
"anytls" => parse_anytls(url, tag),
"naive+https" | "naive+quic" => parse_naive(url, tag),
"socks5" | "socks5h" | "socks4" | "socks4a" => parse_plain_proxy(url, tag, "socks"),
"http" | "https" => parse_plain_proxy(url, tag, "http"),
_ => Err(LinkError::invalid(format!("unsupported scheme '{scheme}'"))),
}
}
const SUPPORTED_VLESS_TRANSPORTS: [&str; 9] = ["", "tcp", "raw", "ws", "grpc", "h2", "http", "httpupgrade", "quic"];
// XRay 26 removed the HTTP/2 and QUIC transports and refuses to start on them.
const SUPPORTED_XRAY_TRANSPORTS: [&str; 8] = ["", "tcp", "raw", "ws", "grpc", "httpupgrade", "xhttp", "splithttp"];
const SING_BOX_VLESS_FLOWS: [&str; 2] = ["", "xtls-rprx-vision"];
const XRAY_VLESS_FLOWS: [&str; 3] = ["", "xtls-rprx-vision", "xtls-rprx-vision-udp443"];
const SING_BOX_VMESS_SECURITY: [&str; 6] = ["auto", "none", "zero", "aes-128-cfb", "aes-128-gcm", "chacha20-poly1305"];
const TUIC_CONGESTION_CONTROLS: [&str; 3] = ["cubic", "new_reno", "bbr"];
const XHTTP_MODES: [&str; 5] = ["", "auto", "packet-up", "stream-up", "stream-one"];
fn ss2022_key_bytes(method: &str) -> Option<usize> {
match method {
"2022-blake3-aes-128-gcm" => Some(16),
"2022-blake3-aes-256-gcm" | "2022-blake3-chacha20-poly1305" => Some(32),
_ => None,
}
}
const SING_BOX_SS_METHODS: [&str; 18] = [
"2022-blake3-aes-128-gcm",
"2022-blake3-aes-256-gcm",
"2022-blake3-chacha20-poly1305",
"none",
"aes-128-gcm",
"aes-192-gcm",
"aes-256-gcm",
"chacha20-ietf-poly1305",
"xchacha20-ietf-poly1305",
"aes-128-ctr",
"aes-192-ctr",
"aes-256-ctr",
"aes-128-cfb",
"aes-192-cfb",
"aes-256-cfb",
"rc4-md5",
"chacha20-ietf",
"xchacha20",
];
// XRay lowercases these; its 2022 methods are matched as written.
const XRAY_SS_METHODS: [&str; 10] = [
"aes-128-gcm",
"aes-256-gcm",
"chacha20-poly1305",
"chacha20-ietf-poly1305",
"xchacha20-poly1305",
"xchacha20-ietf-poly1305",
"aead_aes_128_gcm",
"aead_aes_256_gcm",
"aead_chacha20_poly1305",
"aead_xchacha20_poly1305",
];
fn re(pattern: &str) -> Regex {
Regex::new(&format!("^(?:{pattern})$")).expect("a valid pattern")
}
pub(super) static UUID_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}|[0-9a-fA-F]{32}"));
// REALITY's x25519 key, unpadded base64url; its short id, whole hex bytes, at most 8.
static REALITY_PUBLIC_KEY_RE: LazyLock<Regex> = LazyLock::new(|| re(r"[A-Za-z0-9_-]{43}"));
static REALITY_SHORT_ID_RE: LazyLock<Regex> = LazyLock::new(|| re(r"(?:[0-9a-fA-F]{2}){0,8}"));
// A path Go's url.Parse takes: no control characters, and % only as an escape. XRay ignores
// the parse error on spiderX and dies on the nil URL, taking every outbound with it.
static REALITY_SPIDER_X_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"/(?:[^\x00-\x1f\x7f%]|%[0-9A-Fa-f]{2})*"));
// hysteria2's pinSHA256: the certificate's SHA-256, hex, colons optional.
static CERT_SHA256_RE: LazyLock<Regex> =
LazyLock::new(|| re(r"[0-9A-Fa-f]{64}|[0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){31}"));
static PORT_RANGE_RE: LazyLock<Regex> = LazyLock::new(|| re(r"([0-9]+)(?:-([0-9]+))?"));
fn one_of<'a>(value: &'a str, allowed: &[&str], what: &str) -> Result<&'a str> {
if allowed.contains(&value) {
Ok(value)
} else {
Err(LinkError::invalid(format!("unsupported {what} {}", repr(prefix(value, 80)))))
}
}
// sing-box takes any string as a VLESS/VMess id; XRay a UUID, or 1-30 characters it hashes
// into one.
fn user_id(value: &str, backend: LinkBackend, protocol: &str) -> Result<String> {
let chars = value.chars().count();
if backend == LinkBackend::Xray && !(UUID_RE.is_match(value) || (1..=30).contains(&chars)) {
// Not quoted: the id is the credential.
return Err(LinkError::invalid(format!(
"invalid {protocol} id ({chars} characters): XRay takes a UUID or 1-30 characters"
)));
}
Ok(value.to_owned())
}
type Params = HashMap<String, String>;
// Panels write the unset half of a share link as "&sni=&host=&path=", so a blank parameter
// is an absent one.
fn param<'a>(params: &'a Params, name: &str, default: &'a str) -> &'a str {
match params.get(name) {
Some(v) if !v.is_empty() => v,
_ => default,
}
}
fn get<'a>(params: &'a Params, name: &str) -> &'a str {
params.get(name).map(String::as_str).unwrap_or("")
}
// sing-box stores a port as uint16 and refuses to start on anything else.
fn port(value: &str) -> Result<u16> {
let trimmed = value.trim();
let parsed: i128 = parse_py_int(trimmed)
.ok_or_else(|| LinkError::invalid(format!("invalid port {}", repr(prefix(value, 20)))))?;
if !(1..=65535).contains(&parsed) {
return Err(LinkError::invalid(format!("port {parsed} is out of range (1-65535)")));
}
Ok(parsed as u16)
}
/// `int(str)`: an optional sign, decimal digits, `_` between them.
fn parse_py_int(s: &str) -> Option<i128> {
let (sign, digits) = match s.strip_prefix('-') {
Some(rest) => (-1, rest),
None => (1, s.strip_prefix('+').unwrap_or(s)),
};
if digits.is_empty() || digits.starts_with('_') || digits.ends_with('_') || digits.contains("__") {
return None;
}
let clean: String = digits.chars().filter(|c| *c != '_').collect();
if !clean.chars().all(|c| c.is_ascii_digit()) {
return None;
}
clean.parse::<i128>().ok().map(|n| sign * n)
}
fn port_value(value: &Value) -> Result<u16> {
match value {
Value::Number(n) => {
if let Some(i) = n.as_i64() {
if !(1..=65535).contains(&i) {
return Err(LinkError::invalid(format!("port {i} is out of range (1-65535)")));
}
Ok(i as u16)
} else if let Some(f) = n.as_f64() {
// int(443.9) is 443.
port(&(f.trunc() as i64).to_string())
} else {
Err(LinkError::invalid("invalid port"))
}
}
Value::String(s) => port(s),
Value::Bool(b) => port(if *b { "1" } else { "0" }),
other => Err(LinkError::invalid(format!("invalid port {}", repr(prefix(&py_str(other), 20))))),
}
}
fn split_host_port(hostpart: &str) -> Result<(String, String)> {
let (host, port) = match hostpart.rfind(':') {
Some(i) => (&hostpart[..i], &hostpart[i + 1..]),
None => ("", ""),
};
if host.is_empty() || port.is_empty() {
return Err(LinkError::invalid("URL must include host and port"));
}
let host = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')).unwrap_or(host);
Ok((host.to_owned(), port.to_owned()))
}
/// userinfo, host, port and the query of `scheme://userinfo@host:port/?query#name`.
fn parse_url_parts(url: &str, scheme: &str) -> Result<(String, String, String, Params)> {
let rest = url.get(scheme.len() + 3..).unwrap_or("");
let rest = rest.split('#').next().unwrap_or("");
// The query goes before the userinfo: links carry '@' in their parameters
// (Telegram=@handle), and an rpartition over the whole string would swallow the host.
let (authority, query) = rest.split_once('?').unwrap_or((rest, ""));
let (userinfo, hostpart) = match authority.rfind('@') {
Some(i) => (&authority[..i], &authority[i + 1..]),
None => ("", authority),
};
// "host:443/?type=tcp": a trailing path is not part of the port.
let hostpart = hostpart.split('/').next().unwrap_or("");
let (host, port) = split_host_port(hostpart)?;
Ok((userinfo.to_owned(), host, port, py::parse_qs(query)))
}
#[allow(clippy::too_many_arguments)]
fn mk_transport(
transport_type: &str,
path: &str,
host_header: &str,
service_name: &str,
mode: &str,
extra: &str,
x_padding_bytes: &str,
) -> Result<Option<Value>> {
let t = transport_type.to_lowercase();
Ok(match t.as_str() {
"" | "tcp" | "raw" => None,
"ws" => Some(json!({ "type": "ws", "path": unquote(path), "headers": { "Host": host_header } })),
"grpc" => Some(json!({ "type": "grpc", "service_name": unquote(service_name) })),
"h2" | "http" => Some(json!({ "type": "http", "host": [host_header], "path": unquote(path) })),
"httpupgrade" => Some(json!({ "type": "httpupgrade", "host": host_header, "path": unquote(path) })),
"quic" => Some(json!({ "type": "quic" })),
"xhttp" | "splithttp" => {
let mut tr = Map::new();
tr.insert("type".into(), "xhttp".into());
tr.insert("path".into(), unquote(path).into());
if !host_header.is_empty() {
tr.insert("host".into(), host_header.into());
}
if !one_of(mode, &XHTTP_MODES, "xhttp mode")?.is_empty() {
tr.insert("mode".into(), mode.into());
}
if !extra.is_empty() {
tr.insert("extra".into(), parse_json_param(extra, "xhttp extra")?);
} else if !x_padding_bytes.is_empty() {
tr.insert("extra".into(), json!({ "xPaddingBytes": x_padding_bytes }));
}
Some(Value::Object(tr))
}
_ => None,
})
}
// sing-box refuses to start on a transport it does not know.
fn check_transport(transport: &str, backend: LinkBackend, protocol: &str) -> Result<String> {
let normalized = transport.to_lowercase();
let supported: &[&str] = match backend {
LinkBackend::Xray => &SUPPORTED_XRAY_TRANSPORTS,
LinkBackend::SingBox => &SUPPORTED_VLESS_TRANSPORTS,
};
if !supported.contains(&normalized.as_str()) {
return Err(LinkError::invalid(format!(
"unsupported {protocol} transport '{transport}': proxy-suite only maps {}-documented \
transports; use raw JSON or another client/core",
backend.as_str()
)));
}
Ok(normalized)
}
fn require<'a>(params: &'a Params, name: &str, security: &str) -> Result<&'a str> {
params
.get(name)
.map(String::as_str)
.ok_or_else(|| LinkError::invalid(format!("{security} link is missing the '{name}' parameter")))
}
const SING_BOX_FINGERPRINTS: [&str; 10] =
["chrome", "firefox", "edge", "safari", "360", "qq", "ios", "android", "random", "randomized"];
// XRay's own names (transport/internet/tls), matched lowercased.
const XRAY_HELLO_FINGERPRINTS: &str = "firefox_120 firefox_148 chrome_120 chrome_131 chrome_133 ios_13 ios_14 \
edge_106 safari_26_3 360_11_0 qq_11_1 golang randomized randomizedalpn randomizednoalpn firefox_auto \
firefox_55 firefox_56 firefox_63 firefox_65 firefox_99 firefox_102 firefox_105 chrome_auto chrome_58 \
chrome_62 chrome_70 chrome_72 chrome_83 chrome_87 chrome_96 chrome_100 chrome_102 chrome_106_shuffle \
ios_auto ios_11_1 ios_12_1 android_11_okhttp edge_85 edge_auto safari_16_0 safari_auto 360_auto 360_7_5 \
qq_auto chrome_100_psk chrome_112_psk_shuf chrome_114_padding_psk_shuf chrome_115_pq chrome_115_pq_psk \
chrome_120_pq";
fn xray_fingerprint_known(fp: &str) -> bool {
SING_BOX_FINGERPRINTS.contains(&fp)
|| matches!(fp, "randomizednoalpn" | "unsafe")
|| fp
.strip_prefix("hello")
.is_some_and(|name| XRAY_HELLO_FINGERPRINTS.split_whitespace().any(|n| n == name))
}
fn check_fingerprint(fp: &str, backend: LinkBackend, reality: bool) -> Result<String> {
match backend {
LinkBackend::SingBox => {
if !SING_BOX_FINGERPRINTS.contains(&fp) {
return Err(LinkError::invalid(format!(
"unsupported uTLS fingerprint '{fp}': sing-box would refuse to start"
)));
}
}
LinkBackend::Xray => {
let lower = fp.to_lowercase();
if !xray_fingerprint_known(&lower) || (reality && matches!(lower.as_str(), "unsafe" | "hellogolang")) {
return Err(LinkError::invalid(format!(
"unsupported uTLS fingerprint '{fp}': XRay would refuse to start"
)));
}
}
}
Ok(fp.to_owned())
}
// Panels write alpn either as "h2,http/1.1" or as a JSON list.
fn alpn_list(value: &Value) -> Vec<Value> {
let items: Vec<String> = match value {
Value::Array(list) => list.iter().map(py_str).collect(),
other => py_str(other).split(',').map(str::to_owned).collect(),
};
items.into_iter().map(|a| a.trim().to_owned()).filter(|a| !a.is_empty()).map(Value::from).collect()
}
/// `str(value)` for the JSON values a VMess link carries.
fn py_str(value: &Value) -> String {
match value {
Value::String(s) => s.clone(),
Value::Null => "None".into(),
Value::Bool(true) => "True".into(),
Value::Bool(false) => "False".into(),
other => other.to_string(),
}
}
/// Python truthiness of a JSON value.
fn truthy(value: Option<&Value>) -> bool {
match value {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
}
}
fn mk_tls(server_name: &str, fp: Option<&str>, alpn: Option<&Value>, backend: LinkBackend) -> Result<Map<String, Value>> {
let mut tls = Map::new();
tls.insert("enabled".into(), true.into());
tls.insert("server_name".into(), server_name.into());
if let Some(fp) = fp.filter(|f| !f.is_empty()) {
tls.insert("utls".into(), json!({ "enabled": true, "fingerprint": check_fingerprint(fp, backend, false)? }));
}
if let Some(alpn) = alpn.filter(|a| truthy(Some(a))) {
tls.insert("alpn".into(), Value::Array(alpn_list(alpn)));
}
Ok(tls)
}
// SOCKS4 authenticates with a bare userid: "socks4://me@host" has a username and no password.
fn mk_auth(userinfo: &str) -> (Option<String>, Option<String>) {
if userinfo.is_empty() {
return (None, None);
}
match userinfo.split_once(':') {
Some((u, p)) => (Some(unquote(u)), Some(unquote(p))),
None => (Some(unquote(userinfo)), None),
}
}
fn set_auth(ob: &mut Map<String, Value>, userinfo: &str) {
let (username, password) = mk_auth(userinfo);
if let Some(username) = username {
ob.insert("username".into(), username.into());
if let Some(password) = password {
ob.insert("password".into(), password.into());
}
}
}
// XRay's GetPrivateIPMatcher and GetPrivateDomainMatcher: the only servers it lets VLESS
// reach in the clear.
const XRAY_PRIVATE_NETWORKS: [&str; 18] = [
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24",
"192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24",
"224.0.0.0/3", "::/127", "fc00::/7", "fe80::/10", "ff00::/8",
];
const XRAY_PRIVATE_SUFFIXES: [&str; 9] =
["lan", "localdomain", "example", "invalid", "localhost", "test", "local", "home.arpa", "internal"];
static SINGLE_LABEL_RE: LazyLock<Regex> = LazyLock::new(|| re(r"[a-z]([a-z0-9-]{0,61}[a-z0-9])?"));
fn xray_wants_transport_security(host: &str) -> bool {
match super::subscription::py_ip_address(host) {
None => {
let domain = host.to_lowercase();
let domain = domain.trim_end_matches('.');
if SINGLE_LABEL_RE.is_match(domain) {
return false;
}
!XRAY_PRIVATE_SUFFIXES.iter().any(|s| domain == *s || domain.ends_with(&format!(".{s}")))
}
Some(address) => {
let address = super::subscription::unmap(address);
!XRAY_PRIVATE_NETWORKS.iter().any(|net| {
let net: ipnet::IpNet = net.parse().expect("a valid network");
net.contains(&address)
})
}
}
}
fn parse_vless(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "vless")?;
let security = param(&params, "security", "none");
if params.contains_key("ech") && backend != LinkBackend::Xray {
return Err(LinkError::invalid(
"unsupported VLESS parameter 'ech': proxy-suite does not translate share-link ECH blobs into sing-box TLS config",
));
}
let transport = check_transport(param(&params, "type", "tcp"), backend, "VLESS")?;
let mut ob = Map::new();
ob.insert("type".into(), "vless".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("uuid".into(), user_id(&userinfo, backend, "VLESS")?.into());
ob.insert("packet_encoding".into(), "xudp".into());
if security == "reality" {
let fp = check_fingerprint(param(&params, "fp", "chrome"), backend, true)?;
let mut tls = mk_tls(param(&params, "sni", &host), Some(&fp), None, backend)?;
let public_key = require(&params, "pbk", "reality")?;
if !REALITY_PUBLIC_KEY_RE.is_match(public_key) {
return Err(LinkError::invalid(format!(
"invalid reality pbk '{public_key}': expected a 43-character base64url key"
)));
}
let short_id = get(&params, "sid");
if !REALITY_SHORT_ID_RE.is_match(short_id) {
return Err(LinkError::invalid(format!(
"invalid reality sid '{short_id}': expected up to 16 hex digits, in pairs"
)));
}
let mut reality = Map::new();
reality.insert("enabled".into(), true.into());
reality.insert("public_key".into(), public_key.into());
reality.insert("short_id".into(), short_id.into());
let spx = get(&params, "spx");
if backend == LinkBackend::Xray && !spx.is_empty() {
if !REALITY_SPIDER_X_RE.is_match(spx) {
return Err(LinkError::invalid(format!("invalid reality spx {}: XRay wants a URL path", repr(spx))));
}
reality.insert("spider_x".into(), spx.into());
}
tls.insert("reality".into(), Value::Object(reality));
ob.insert("tls".into(), Value::Object(tls));
} else if security == "tls" {
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut tls = mk_tls(param(&params, "sni", &host), params.get("fp").map(String::as_str), alpn.as_ref(), backend)?;
if backend == LinkBackend::Xray
&& let Some(ech) = params.get("ech") {
tls.insert("ech_config_list".into(), unquote(ech).into());
}
ob.insert("tls".into(), Value::Object(tls));
}
if backend == LinkBackend::Xray && !ob.contains_key("tls") && xray_wants_transport_security(&host) {
return Err(LinkError::invalid("XRay refuses VLESS without TLS or REALITY to a public server"));
}
if let Some(tr) = mk_transport(
&transport,
param(&params, "path", "/"),
param(&params, "host", &host),
get(&params, "serviceName"),
get(&params, "mode"),
get(&params, "extra"),
get(&params, "x_padding_bytes"),
)? {
ob.insert("transport".into(), tr);
}
let flow = unquote(get(&params, "flow"));
let flows: &[&str] = match backend {
LinkBackend::SingBox => &SING_BOX_VLESS_FLOWS,
LinkBackend::Xray => &XRAY_VLESS_FLOWS,
};
if !one_of(&flow, flows, &format!("{} VLESS flow", backend.as_str()))?.is_empty() {
ob.insert("flow".into(), flow.into());
}
Ok(ob)
}
/// VMess alterId as the backends take it: an int a subscription cannot make so large (or
/// fractional, or negative) that the backend refuses the whole configuration.
fn alter_id(value: Option<&Value>) -> Result<i64> {
let invalid = |v: &Value| LinkError::invalid(format!("invalid VMess aid {}", py_repr_value(v)));
let n: i128 = match value {
None | Some(Value::Null) => 0,
Some(v) if !truthy(Some(v)) => 0,
Some(Value::Number(n)) => {
if let Some(i) = n.as_i64() {
i as i128
} else {
n.as_f64().map(|f| f.trunc() as i128).ok_or_else(|| invalid(value.unwrap()))?
}
}
Some(Value::Bool(true)) => 1,
Some(v @ Value::String(s)) => parse_py_int(s.trim()).ok_or_else(|| invalid(v))?,
Some(v) => return Err(invalid(v)),
};
if !(0..=65535).contains(&n) {
return Err(LinkError::invalid("VMess aid must be in 0-65535"));
}
Ok(n as i64)
}
fn py_repr_value(v: &Value) -> String {
match v {
Value::String(s) => repr(s),
other => py_str(other),
}
}
fn parse_vmess(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let b64 = url.get("vmess://".len()..).unwrap_or("");
let b64 = b64.split('#').next().unwrap_or("");
let b64 = b64.split('?').next().unwrap_or("");
let b64 = unquote(b64);
let padded = format!("{b64}{}", pad(b64.chars().count()));
let decode = |bytes: Option<Vec<u8>>| -> Option<Value> {
let text = String::from_utf8(bytes?).ok()?;
serde_json::from_str(&text).ok()
};
let data = decode(b64decode(padded.as_bytes()))
.or_else(|| decode(urlsafe_b64decode(padded.as_bytes())))
.ok_or_else(|| LinkError::invalid("failed to parse vmess URL: not base64 JSON"))?;
let data = data.as_object().ok_or_else(|| LinkError::invalid("failed to parse vmess URL: not a JSON object"))?;
let missing = |k: &str| LinkError::invalid(format!("failed to parse vmess URL: '{k}'"));
let mut host = py_str(data.get("add").ok_or_else(|| missing("add"))?).trim().to_owned();
// "[::1]", as the URL schemes write it: the backends dial it unbracketed.
if host.starts_with('[') && host.ends_with(']') && host.len() >= 2 {
host = host[1..host.len() - 1].to_owned();
}
let port = port_value(data.get("port").ok_or_else(|| missing("port"))?)?;
let net_raw = data.get("net").map(py_str).unwrap_or_else(|| "tcp".into());
let net = check_transport(&net_raw, backend, "VMess")?;
let tls_field = data.get("tls").map(py_str).unwrap_or_default();
let sni = if truthy(data.get("sni")) {
py_str(&data["sni"])
} else if truthy(data.get("host")) {
py_str(&data["host"])
} else {
host.clone()
};
// Panels write unset fields as "": that is the default, not a value.
let security = if truthy(data.get("scy")) { data["scy"].clone() } else { Value::from("auto") };
match backend {
LinkBackend::SingBox => {
let s = py_str(&security);
if !security.is_string() || !SING_BOX_VMESS_SECURITY.contains(&s.as_str()) {
return Err(LinkError::invalid(format!(
"unsupported sing-box VMess security {}",
repr(prefix(&s, 80))
)));
}
}
LinkBackend::Xray => {
if !security.is_string() {
return Err(LinkError::invalid("VMess scy must be a string"));
}
}
}
let id = match data.get("id") {
Some(Value::String(s)) => user_id(s, backend, "VMess")?,
_ => return Err(LinkError::invalid("VMess id must be a string")),
};
let mut ob = Map::new();
ob.insert("type".into(), "vmess".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port.into());
ob.insert("uuid".into(), id.into());
ob.insert("security".into(), security);
ob.insert("alter_id".into(), alter_id(data.get("aid"))?.into());
if tls_field == "tls" || tls_field == "reality" {
let fp = truthy(data.get("fp")).then(|| py_str(&data["fp"]));
let alpn = data.get("alpn").filter(|a| truthy(Some(a)));
ob.insert("tls".into(), Value::Object(mk_tls(&sni, fp.as_deref(), alpn, backend)?));
}
let path = if truthy(data.get("path")) { py_str(&data["path"]) } else { "/".into() };
let h_host = if truthy(data.get("host")) { py_str(&data["host"]) } else { host.clone() };
let net = if net == "http" { "h2".to_owned() } else { net };
if let Some(tr) = mk_transport(&net, &path, &h_host, path.trim_start_matches('/'), "", "", "")? {
ob.insert("transport".into(), tr);
}
Ok(ob)
}
fn parse_trojan(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "trojan")?;
let transport = check_transport(param(&params, "type", "tcp"), backend, "Trojan")?;
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut ob = Map::new();
ob.insert("type".into(), "trojan".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), nonempty_password(unquote(&userinfo), "Trojan")?.into());
ob.insert(
"tls".into(),
Value::Object(mk_tls(param(&params, "sni", &host), params.get("fp").map(String::as_str), alpn.as_ref(), backend)?),
);
if let Some(tr) = mk_transport(
&transport,
param(&params, "path", "/"),
param(&params, "host", &host),
get(&params, "serviceName"),
"",
"",
"",
)? {
ob.insert("transport".into(), tr);
}
Ok(ob)
}
fn decode_ss_userinfo(userinfo: &str) -> Result<(String, String)> {
let plain = unquote(userinfo);
if let Some((m, p)) = plain.split_once(':') {
return Ok((m.to_owned(), p.to_owned()));
}
let padded = format!("{userinfo}{}", pad(userinfo.chars().count()));
urlsafe_b64decode(padded.as_bytes())
.and_then(|b| String::from_utf8(b).ok())
.and_then(|d| d.split_once(':').map(|(m, p)| (m.to_owned(), p.to_owned())))
.ok_or_else(|| LinkError::invalid("invalid shadowsocks userinfo"))
}
// XRay refuses its whole configuration over one empty password.
fn nonempty_password(password: String, protocol: &str) -> Result<String> {
if password.is_empty() {
return Err(LinkError::invalid(format!("{protocol} password is empty")));
}
Ok(password)
}
fn check_ss(method: &str, password: &str, backend: LinkBackend) -> Result<()> {
match backend {
LinkBackend::Xray => {
if ss2022_key_bytes(method).is_none() && !XRAY_SS_METHODS.contains(&method.to_lowercase().as_str()) {
return Err(LinkError::invalid(format!("unsupported XRay shadowsocks method '{method}'")));
}
}
LinkBackend::SingBox => {
one_of(method, &SING_BOX_SS_METHODS, "sing-box shadowsocks method")?;
}
}
if method.to_lowercase() != "none" {
nonempty_password(password.to_owned(), "Shadowsocks")?;
}
let Some(bytes) = ss2022_key_bytes(method) else { return Ok(()) };
// A 2022 password is the key itself, padded base64 ("iPSK:uPSK" for EIH, AES only).
let keys: Vec<&str> = password.split(':').collect();
if keys.len() > 1 && !method.contains("aes") {
return Err(LinkError::invalid(format!("{method} takes a single key")));
}
for key in keys {
if b64decode_strict(key).map(|d| d.len()) != Some(bytes) {
return Err(LinkError::invalid(format!("{method} needs a base64 key of {bytes} bytes")));
}
}
Ok(())
}
fn parse_shadowsocks(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
// SIP002 (ss://base64(method:password)@host:port#name) and legacy links that encode the
// whole endpoint (ss://base64(method:password@host:port)#name).
let rest = url.get("ss://".len()..).unwrap_or("");
let rest = rest.split('#').next().unwrap_or("");
let endpoint = rest.split('?').next().unwrap_or("");
let (userinfo, host, port_s) = if endpoint.contains('@') {
let (u, h, p, _) = parse_url_parts(url, "ss")?;
(u, h, p)
} else {
let padded = format!("{endpoint}{}", pad(endpoint.chars().count()));
let decoded = urlsafe_b64decode(padded.as_bytes())
.and_then(|b| String::from_utf8(b).ok())
.ok_or_else(|| LinkError::invalid("invalid shadowsocks URL"))?;
let at = decoded.rfind('@').ok_or_else(|| LinkError::invalid("invalid legacy shadowsocks URL"))?;
let (h, p) = split_host_port(&decoded[at + 1..])?;
(decoded[..at].to_owned(), h, p)
};
let (method, password) = decode_ss_userinfo(&userinfo)?;
check_ss(&method, &password, backend)?;
let mut ob = Map::new();
ob.insert("type".into(), "shadowsocks".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("method".into(), method.into());
ob.insert("password".into(), password.into());
Ok(ob)
}
// "20000-30000" or a lone "443" in sing-box's "a:b" form: it refuses a bare port.
fn port_range(part: &str, mport: &str) -> Result<String> {
let (low, high) = PORT_RANGE_RE
.captures(part)
.and_then(|c| {
let low: u64 = c.get(1)?.as_str().parse().ok()?;
let high: u64 = c.get(2).map_or(Some(low), |m| m.as_str().parse().ok())?;
Some((low, high))
})
.unwrap_or((0, 0));
if !(1 <= low && low <= high && high <= 65535) {
return Err(LinkError::invalid(format!("invalid hysteria2 mport {}", repr(prefix(mport, 40)))));
}
Ok(format!("{low}:{high}"))
}
fn parse_hysteria2(url: &str, tag: &str, backend: LinkBackend) -> Result<Map<String, Value>> {
let scheme = if url.to_lowercase().starts_with("hysteria2://") { "hysteria2" } else { "hy2" };
let (userinfo, host, port_s, params) = parse_url_parts(url, scheme)?;
let mut tls = Map::new();
tls.insert("enabled".into(), true.into());
tls.insert("server_name".into(), param(&params, "sni", &host).into());
tls.insert("insecure".into(), (params.get("insecure").map(String::as_str).unwrap_or("0") == "1").into());
// XRay checks the certificate against the pin instead (sing-box pins only a public key).
let pin = get(&params, "pinSHA256");
if backend == LinkBackend::Xray && !pin.is_empty() {
if !CERT_SHA256_RE.is_match(pin) {
return Err(LinkError::invalid(format!("invalid hysteria2 pinSHA256 {}", repr(prefix(pin, 100)))));
}
tls.insert("insecure".into(), false.into());
tls.insert("certificate_sha256".into(), pin.replace(':', "").to_lowercase().into());
}
let mut ob = Map::new();
ob.insert("type".into(), "hysteria2".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), unquote(&userinfo).into());
ob.insert("tls".into(), Value::Object(tls));
if get(&params, "obfs") == "salamander" {
let password = get(&params, "obfs-password");
if password.is_empty() {
return Err(LinkError::invalid("hysteria2 salamander obfs is missing its obfs-password"));
}
ob.insert("obfs".into(), json!({ "type": "salamander", "password": password }));
}
// Port hopping, as v2rayN writes it: "20000-30000", or several joined by commas.
let mport = get(&params, "mport");
if !mport.is_empty() {
let ranges = mport
.split(',')
.map(str::trim)
.filter(|r| !r.is_empty())
.map(|r| port_range(r, mport).map(Value::from))
.collect::<Result<Vec<_>>>()?;
ob.insert("server_ports".into(), Value::Array(ranges));
ob.insert("hop_interval".into(), "30s".into());
}
Ok(ob)
}
fn parse_tuic(url: &str, tag: &str) -> Result<Map<String, Value>> {
let (userinfo, host, port_s, params) = parse_url_parts(url, "tuic")?;
let (uuid, password) = userinfo.split_once(':').unwrap_or((&userinfo, ""));
let alpn = alpn_list(&Value::from(param(&params, "alpn", "h3")));
// Unlike VLESS, sing-box's TUIC takes nothing but a UUID.
if !UUID_RE.is_match(uuid) {
return Err(LinkError::invalid("invalid TUIC uuid: not a UUID"));
}
let mut ob = Map::new();
ob.insert("type".into(), "tuic".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("uuid".into(), uuid.into());
ob.insert("password".into(), unquote(password).into());
ob.insert(
"congestion_control".into(),
one_of(param(&params, "congestion_control", "bbr"), &TUIC_CONGESTION_CONTROLS, "TUIC congestion_control")?.into(),
);
ob.insert("udp_relay_mode".into(), param(&params, "udp_relay_mode", "native").into());
ob.insert(
"tls".into(),
json!({ "enabled": true, "server_name": param(&params, "sni", &host), "alpn": alpn }),
);
Ok(ob)
}
fn parse_anytls(url: &str, tag: &str) -> Result<Map<String, Value>> {
// anytls://password@host:port?sni=example.com&insecure=1&fp=chrome&alpn=h2
let (userinfo, host, port_s, params) = parse_url_parts(url, "anytls")?;
if userinfo.is_empty() {
return Err(LinkError::invalid("anytls link is missing the password"));
}
let sni = [get(&params, "sni"), get(&params, "peer")]
.into_iter()
.find(|s| !s.is_empty())
.unwrap_or(&host)
.to_owned();
let alpn = params.get("alpn").map(|a| Value::String(a.clone()));
let mut tls = mk_tls(&sni, params.get("fp").map(String::as_str), alpn.as_ref(), LinkBackend::SingBox)?;
let insecure = params.get("insecure").or_else(|| params.get("allowInsecure")).map(String::as_str).unwrap_or("0");
if insecure == "1" {
tls.insert("insecure".into(), true.into());
}
let mut ob = Map::new();
ob.insert("type".into(), "anytls".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("password".into(), unquote(&userinfo).into());
ob.insert("tls".into(), Value::Object(tls));
Ok(ob)
}
fn parse_naive(url: &str, tag: &str) -> Result<Map<String, Value>> {
// naive+https://user:pass@host:port, or naive+quic:// for HTTP/3 (NekoBox's form).
let scheme = super::detect_scheme(url);
let (userinfo, host, port_s, params) = parse_url_parts(url, &scheme)?;
let sni = Some(get(&params, "sni")).filter(|s| !s.is_empty()).unwrap_or(&host).to_owned();
let mut ob = Map::new();
ob.insert("type".into(), "naive".into());
ob.insert("tag".into(), tag.into());
ob.insert("server".into(), host.into());
ob.insert("server_port".into(), port(&port_s)?.into());
ob.insert("tls".into(), json!({ "enabled": true, "server_name": sni }));
set_auth(&mut ob, &userinfo);
if scheme == "naive+quic" {
ob.insert("quic".into(), true.into());
}
Ok(ob)
}
/// socks:// and http(s)://: host, port and optional credentials, nothing else.
fn parse_plain_proxy(url: &str, tag: &str, kind: &str) -> Result<Map<String, Value>> {
let scheme = super::detect_scheme(url);
let (userinfo, host, port_s, _) = parse_url_parts(url, &scheme)?;
let mut ob = Map::new();
ob.insert("type".into(), kind.into());
ob.insert("tag".into(), tag.into());
if kind == "socks" {
ob.insert("version".into(), (if scheme.starts_with("socks4") { "4" } else { "5" }).into());
}
set_auth(&mut ob, &userinfo);
ob.insert("server".into(), host.clone().into());
ob.insert("server_port".into(), port(&port_s)?.into());
if kind == "http" && scheme == "https" {
ob.insert("tls".into(), json!({ "enabled": true, "server_name": host }));
}
Ok(ob)
}
+231
View File
@@ -0,0 +1,231 @@
//! The few pieces of Python's standard library upstream's parsers lean on, with Python's
//! edge cases: share links in the wild depend on them (lenient base64, `+` in queries,
//! percent escapes that are not).
use std::collections::HashMap;
/// `urllib.parse.unquote`: `%XX` escapes decoded as UTF-8, invalid sequences replaced,
/// a `%` without two hex digits kept as it is. `+` stays `+`.
pub fn unquote(s: &str) -> String {
if !s.contains('%') {
return s.to_owned();
}
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'%' && i + 2 < bytes.len()
&& let (Some(h), Some(l)) = (hex(bytes[i + 1]), hex(bytes[i + 2])) {
out.push(h << 4 | l);
i += 3;
continue;
}
out.push(bytes[i]);
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
fn hex(b: u8) -> Option<u8> {
match b {
b'0'..=b'9' => Some(b - b'0'),
b'a'..=b'f' => Some(b - b'a' + 10),
b'A'..=b'F' => Some(b - b'A' + 10),
_ => None,
}
}
/// `dict(urllib.parse.parse_qsl(query, keep_blank_values=True))`: pairs split on `&`,
/// `+` read as a space, a name without `=` kept with an empty value, the last of a
/// repeated name winning.
pub fn parse_qs(query: &str) -> HashMap<String, String> {
let mut out = HashMap::new();
for pair in query.split('&') {
if pair.is_empty() {
continue;
}
let (name, value) = pair.split_once('=').unwrap_or((pair, ""));
out.insert(unquote(&name.replace('+', " ")), unquote(&value.replace('+', " ")));
}
out
}
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
fn b64_value(c: u8) -> Option<u8> {
B64.iter().position(|&x| x == c).map(|p| p as u8)
}
/// `base64.b64decode(s)` (not `validate`): characters outside the alphabet are skipped, a
/// complete padding ends the input, and a leftover partial quad is an error, as CPython's
/// `binascii.a2b_base64` does.
pub fn b64decode(s: &[u8]) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(s.len() * 3 / 4);
let mut quad_pos = 0u8;
let mut left = 0u32;
let mut pads = 0u8;
for &c in s {
if c == b'=' {
if quad_pos >= 2 {
pads += 1;
if quad_pos + pads >= 4 {
return Some(out);
}
}
continue;
}
let Some(v) = b64_value(c) else { continue };
pads = 0;
match quad_pos {
0 => {
left = v as u32;
quad_pos = 1;
}
1 => {
left = left << 6 | v as u32;
out.push((left >> 4) as u8);
left &= 0x0f;
quad_pos = 2;
}
2 => {
left = left << 6 | v as u32;
out.push((left >> 2) as u8);
left &= 0x03;
quad_pos = 3;
}
_ => {
out.push((left << 6 | v as u32) as u8);
left = 0;
quad_pos = 0;
}
}
}
if quad_pos == 0 { Some(out) } else { None }
}
/// `base64.urlsafe_b64decode(s)`: `-` and `_` read as `+` and `/` first.
pub fn urlsafe_b64decode(s: &[u8]) -> Option<Vec<u8>> {
let translated: Vec<u8> = s
.iter()
.map(|&c| match c {
b'-' => b'+',
b'_' => b'/',
c => c,
})
.collect();
b64decode(&translated)
}
/// `base64.b64decode(s, validate=True)`: only the alphabet, then at most two `=`.
pub fn b64decode_strict(s: &str) -> Option<Vec<u8>> {
let body = s.trim_end_matches('=');
if s.len() - body.len() > 2 || !body.bytes().all(|c| b64_value(c).is_some()) {
return None;
}
b64decode(s.as_bytes())
}
/// `"=" * (-len(s) % 4)`, the padding upstream appends before decoding.
pub fn pad(len: usize) -> &'static str {
["", "===", "==", "="][len % 4]
}
/// `str.splitlines()`: every line boundary Python knows.
pub fn splitlines(s: &str) -> Vec<&str> {
let mut lines = Vec::new();
let mut start = 0;
let mut chars = s.char_indices().peekable();
while let Some((i, c)) = chars.next() {
let boundary = matches!(
c,
'\n' | '\r' | '\x0b' | '\x0c' | '\x1c' | '\x1d' | '\x1e' | '\u{85}' | '\u{2028}' | '\u{2029}'
);
if boundary {
lines.push(&s[start..i]);
let mut end = i + c.len_utf8();
if c == '\r'
&& let Some(&(j, '\n')) = chars.peek() {
chars.next();
end = j + 1;
}
start = end;
}
}
if start < s.len() {
lines.push(&s[start..]);
}
lines
}
/// `repr()` of a short string, for error messages that quote a link's value: escapes,
/// not raw control characters, reach the terminal.
pub fn repr(s: &str) -> String {
let quote = if s.contains('\'') && !s.contains('"') { '"' } else { '\'' };
let mut out = String::new();
out.push(quote);
for c in s.chars() {
match c {
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if c == quote => {
out.push('\\');
out.push(c);
}
c if (c as u32) < 0x20 || c == '\x7f' => out.push_str(&format!("\\x{:02x}", c as u32)),
c => out.push(c),
}
}
out.push(quote);
out
}
/// The first `n` characters (code points, as Python slices).
pub fn prefix(s: &str, n: usize) -> &str {
match s.char_indices().nth(n) {
Some((i, _)) => &s[..i],
None => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unquote_matches_python() {
assert_eq!(unquote("%2Fa%20b%C3%A9"), "/a b\u{e9}");
assert_eq!(unquote("100%"), "100%");
assert_eq!(unquote("%zz%4"), "%zz%4");
assert_eq!(unquote("a+b"), "a+b");
assert_eq!(unquote("%C3"), "\u{fffd}");
}
#[test]
fn query_reads_plus_as_space_and_keeps_blanks() {
let q = parse_qs("sni=&a=1&a=2&flag&x=a+b%2B&&");
assert_eq!(q["sni"], "");
assert_eq!(q["a"], "2");
assert_eq!(q["flag"], "");
assert_eq!(q["x"], "a b+");
}
#[test]
fn base64_is_lenient_like_cpython() {
assert_eq!(b64decode(b"aGVsbG8=").unwrap(), b"hello");
assert_eq!(b64decode(b"aGVs\nbG8=").unwrap(), b"hello");
assert_eq!(b64decode(b"aGVsbG8=garbage").unwrap(), b"hello");
assert!(b64decode(b"aGVsbG8").is_none());
assert_eq!(b64decode(format!("aGVsbG8{}", pad(7)).as_bytes()).unwrap(), b"hello");
assert_eq!(urlsafe_b64decode(b"-_8=").unwrap(), vec![0xfb, 0xff]);
assert!(b64decode_strict("aGVs bG8=").is_none());
assert_eq!(b64decode_strict("aGVsbG8=").unwrap(), b"hello");
}
#[test]
fn splitlines_knows_every_boundary() {
assert_eq!(splitlines("a\r\nb\rc\nd\u{2028}e\n"), ["a", "b", "c", "d", "e"]);
assert_eq!(splitlines("a\n\nb"), ["a", "", "b"]);
}
}
@@ -0,0 +1,497 @@
//! Subscriptions: a list of share links, plain or base64, each becoming an outbound tagged
//! after the subscription and the link's remark. Upstream's `proxy_parsing.py` half.
use std::collections::HashSet;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::sync::LazyLock;
use regex::Regex;
use serde_json::{Map, Value};
use super::py::{self, b64decode, pad, prefix, unquote};
use super::{LinkBackend, LinkError, Result, SCHEMES, detect_scheme, finish_outbound, parse_url};
/// A subscription is a list of share links; the biggest real ones are tens of KiB.
pub const MAX_SUBSCRIPTION_BYTES: usize = 8 * 1024 * 1024;
/// Real subscriptions hold hundreds; more would be minutes of parsing and gigabytes of config.
pub const MAX_SUBSCRIPTION_ENTRIES: usize = 5000;
/// What upstream presents itself as: providers serve v2rayN's format to it.
pub const USER_AGENT: &str = "v2rayN/6.0";
/// `ipaddress.ip_address(host)`: a literal IPv4 (dotted decimal, no leading zeros) or IPv6
/// address, an IPv6 zone ignored.
pub fn py_ip_address(host: &str) -> Option<IpAddr> {
if let Ok(v4) = host.parse::<Ipv4Addr>() {
return Some(IpAddr::V4(v4));
}
let unscoped = host.split('%').next().unwrap_or(host);
unscoped.parse::<Ipv6Addr>().ok().map(IpAddr::V6)
}
/// An IPv4-mapped IPv6 address as the IPv4 address it maps.
pub fn unmap(address: IpAddr) -> IpAddr {
match address {
IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(address),
v4 => v4,
}
}
/// glibc's `inet_aton`: one to four parts, each decimal, octal (`0` first) or hex (`0x`),
/// the last filling what the others leave.
fn inet_aton(s: &str) -> Option<Ipv4Addr> {
let parts: Vec<&str> = s.split('.').collect();
if parts.is_empty() || parts.len() > 4 {
return None;
}
let mut values = Vec::with_capacity(parts.len());
for part in &parts {
let value = if let Some(hex) = part.strip_prefix("0x").or_else(|| part.strip_prefix("0X")) {
if hex.is_empty() { 0 } else { u64::from_str_radix(hex, 16).ok()? }
} else if part.len() > 1 && part.starts_with('0') {
u64::from_str_radix(&part[1..], 8).ok()?
} else if part.is_empty() {
return None;
} else {
part.parse::<u64>().ok()?
};
values.push(value);
}
let (last, head) = values.split_last()?;
if head.iter().any(|v| *v > 0xff) {
return None;
}
let max_last = [0xffff_ffffu64, 0xff_ffff, 0xffff, 0xff][head.len()];
if *last > max_last {
return None;
}
let mut n: u64 = 0;
for (i, v) in head.iter().enumerate() {
n |= v << (24 - 8 * i);
}
Some(Ipv4Addr::from((n | last) as u32))
}
/// A server name as the backends would dial it: a literal address, or one of `inet_aton`'s
/// forms (2130706433, 0x7f.1, 127.1), which a resolver may still take.
fn server_address(host: &str) -> Option<IpAddr> {
let address = match py_ip_address(host) {
Some(a) => a,
None => {
static ATON_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[0-9A-Fa-fXx.]+$").unwrap());
if !ATON_RE.is_match(host) {
return None;
}
IpAddr::V4(inet_aton(host)?)
}
};
Some(unmap(address))
}
fn in_net(address: IpAddr, net: &str) -> bool {
net.parse::<ipnet::IpNet>().is_ok_and(|n| n.contains(&address))
}
// Opt-in per subscription (allowPrivateServers): a provider's servers are not on the LAN.
const PRIVATE_NETWORKS: [&str; 5] = ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "100.64.0.0/10", "fc00::/7"];
fn is_loopback(a: IpAddr) -> bool {
a.is_loopback()
}
fn is_unspecified(a: IpAddr) -> bool {
a.is_unspecified()
}
fn is_link_local(a: IpAddr) -> bool {
match a {
IpAddr::V4(v4) => v4.is_link_local(),
IpAddr::V6(v6) => (v6.segments()[0] & 0xffc0) == 0xfe80,
}
}
fn is_private(a: IpAddr) -> bool {
PRIVATE_NETWORKS.iter().any(|n| in_net(a, n))
}
fn check_address(host: &str, address: IpAddr, allow_private: bool) -> Result<()> {
if is_loopback(address) || is_unspecified(address) || in_net(address, "0.0.0.0/8") {
return Err(LinkError::RefusedServer(format!("server {host} is this host")));
}
if is_link_local(address) || address.is_multicast() {
return Err(LinkError::RefusedServer(format!("server {host} is a link-local or multicast address")));
}
if !allow_private && is_private(address) {
return Err(LinkError::RefusedServer(format!(
"server {host} is a private address (see allowPrivateServers)"
)));
}
Ok(())
}
/// Refuses a literal address (or localhost) on this host, its link, or, unless
/// `allow_private`, a private network: urltest would pick a loopback entry as the exit.
pub fn check_server(host: &Value, allow_private: bool) -> Result<()> {
let Some(host) = host.as_str() else { return Ok(()) };
let mut name = host.trim().trim_end_matches('.').to_lowercase();
// The backends dial "[127.0.0.1]" as 127.0.0.1.
if name.starts_with('[') && name.ends_with(']') && name.len() >= 2 {
name = name[1..name.len() - 1].trim_end_matches('.').to_owned();
}
if name == "localhost" || name.ends_with(".localhost") {
return Err(LinkError::RefusedServer(format!("server {host} is this host")));
}
if let Some(address) = server_address(&name) {
check_address(host, address, allow_private)?;
}
Ok(())
}
/// How close to this host a URL's host is: 2 for this host or its link, 1 for a private
/// network, 0 for anywhere else or a name other than localhost.
pub fn nearness(host: Option<&str>) -> u8 {
let Some(host) = host else { return 0 };
let name = host.trim().trim_end_matches('.').to_lowercase();
if name == "localhost" || name.ends_with(".localhost") {
return 2;
}
let Some(address) = server_address(&name) else { return 0 };
if is_loopback(address) || is_unspecified(address) || is_link_local(address) || in_net(address, "0.0.0.0/8") {
return 2;
}
u8::from(is_private(address))
}
/// Whether a subscription fetch may follow a redirect: http and https only, never from
/// https down to http, never nearer to this host than where it came from.
pub fn redirect_allowed(from: &url_parts::Url, to: &url_parts::Url) -> std::result::Result<(), &'static str> {
if to.scheme != "http" && to.scheme != "https" {
return Err("subscription redirected off http:// and https://");
}
if to.scheme == "http" && from.scheme == "https" {
return Err("subscription redirected from https:// to http://");
}
if nearness(to.hostname.as_deref()) > nearness(from.hostname.as_deref()) {
return Err("subscription redirected to this host or a private network");
}
Ok(())
}
/// The bits of `urllib.parse.urlsplit` upstream reads.
pub mod url_parts {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Url {
pub scheme: String,
pub hostname: Option<String>,
}
/// Scheme (lowercased) and hostname (lowercased, unbracketed) of a URL.
pub fn split(url: &str) -> Result<Url, &'static str> {
let (scheme, rest) = match url.find(':') {
Some(i)
if i > 0
&& url[..i].chars().next().is_some_and(|c| c.is_ascii_alphabetic())
&& url[..i].chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) =>
{
(url[..i].to_lowercase(), &url[i + 1..])
}
_ => (String::new(), url),
};
let netloc = match rest.strip_prefix("//") {
Some(after) => after.split(['/', '?', '#']).next().unwrap_or(""),
None => "",
};
if netloc.contains('[') != netloc.contains(']') {
return Err("Invalid IPv6 URL");
}
let hostinfo = netloc.rsplit_once('@').map_or(netloc, |(_, h)| h);
let hostname = match hostinfo.split_once('[') {
Some((_, bracketed)) => bracketed.split(']').next().unwrap_or(""),
None => hostinfo.split(':').next().unwrap_or(""),
};
let hostname = (!hostname.is_empty()).then(|| match hostname.split_once('%') {
Some((h, zone)) => format!("{}%{zone}", h.to_lowercase()),
None => hostname.to_lowercase(),
});
Ok(Url { scheme, hostname })
}
}
/// The links of a subscription body: base64 (line-wrapped or URL-safe) or plain text.
pub fn decode_subscription(data: &[u8]) -> Vec<String> {
let stripped: Vec<u8> = data
.iter()
.filter(|b| !matches!(b, b' ' | b'\t' | b'\n' | b'\r' | b'\x0b' | b'\x0c'))
.map(|&b| match b {
b'-' => b'+',
b'_' => b'/',
b => b,
})
.collect();
let mut padded = stripped.clone();
padded.extend_from_slice(pad(stripped.len()).as_bytes());
let decoded = b64decode(&padded)
.and_then(|d| String::from_utf8(d).ok())
.filter(|text| SCHEMES.iter().any(|s| text.contains(&format!("{s}://"))));
let text = decoded.unwrap_or_else(|| String::from_utf8_lossy(data).into_owned());
py::splitlines(&text).into_iter().map(str::trim).filter(|l| !l.is_empty()).map(str::to_owned).collect()
}
/// A remark as a tag: letters (any script), digits, `_` and `-`, at most 60 characters.
pub fn slugify_tag(remark: &str) -> String {
static NON_WORD: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[^\w-]").unwrap());
static DASHES: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"-{2,}").unwrap());
let slug = NON_WORD.replace_all(remark, "-");
let slug = DASHES.replace_all(&slug, "-");
let slug = prefix(slug.trim_matches('-'), 60);
if slug.is_empty() { "proxy".into() } else { slug.to_owned() }
}
pub fn make_tag(prefix: &str, remark: &str, index: usize) -> String {
if remark.is_empty() {
format!("{prefix}-{index}")
} else {
format!("{prefix}-{}", slugify_tag(&unquote(remark)))
}
}
fn remark_from_line(line: &str) -> &str {
line.split_once('#').map_or("", |(_, r)| r)
}
fn unique_tag(base: String, seen: &HashSet<String>) -> String {
if !seen.contains(&base) {
return base;
}
(2..).map(|n| format!("{base}-{n}")).find(|t| !seen.contains(t)).expect("an unused suffix")
}
/// The resolver XRay asks for the ECH config, when echConfigList names one instead of
/// holding the config: "[name+]udp://1.1.1.1:53", "https://dns.example/dns-query".
fn ech_dns_server(value: &Value) -> Option<String> {
let value = value.as_str()?;
if !value.contains("://") {
return None;
}
let scheme_part = value.split("://").next().unwrap_or("");
let url = if scheme_part.contains('+') { value.split_once('+').map_or(value, |(_, r)| r) } else { value };
let host = url_parts::split(url).ok().and_then(|u| u.hostname);
Some(host.unwrap_or_else(|| value.to_owned()))
}
/// Every address the outbound dials: its server, any "address" in an xhttp extra's
/// downloadSettings, and the resolver an ECH config is fetched from.
fn dialed_servers(ob: &Map<String, Value>) -> Vec<Value> {
let mut servers = vec![ob.get("server").cloned().unwrap_or(Value::Null)];
if let Some(ech) = ob.get("tls").and_then(Value::as_object).and_then(|t| t.get("ech_config_list")).and_then(ech_dns_server) {
servers.push(ech.into());
}
let mut stack: Vec<&Value> =
ob.get("transport").and_then(Value::as_object).and_then(|t| t.get("extra")).into_iter().collect();
while let Some(item) = stack.pop() {
match item {
Value::Object(map) => {
for (key, value) in map {
let lower = key.to_lowercase();
if lower == "address" {
servers.push(match value {
Value::String(_) => value.clone(),
other => Value::String(other.to_string()),
});
} else if lower == "echconfiglist"
&& let Some(ech) = ech_dns_server(value) {
servers.push(ech.into());
}
stack.push(value);
}
}
Value::Array(list) => stack.extend(list),
_ => {}
}
}
servers
}
/// What reading a subscription gave.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Parsed {
/// Each entry with the backend that took it, in the subscription's order.
pub outbounds: Vec<(LinkBackend, Value)>,
/// tag -> the line it came from, to share it back.
pub links: Vec<(String, String)>,
/// One line per entry left out.
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct Options {
pub allow_private: bool,
pub allow_insecure: bool,
}
/// Parses every supported line, trying each backend in turn. A line no backend accepts is
/// reported with every backend's complaint and skipped, as is one whose server is refused.
pub fn walk(lines: &[String], tag_prefix: &str, backends: &[LinkBackend], opts: Options) -> Parsed {
let mut parsed = Parsed::default();
let mut seen: HashSet<String> = HashSet::new();
for (index, line) in lines.iter().enumerate() {
let scheme = detect_scheme(line);
if !SCHEMES.contains(&scheme.as_str()) {
continue;
}
if seen.len() >= MAX_SUBSCRIPTION_ENTRIES {
parsed.warnings.push(format!(
"subscription has more than {MAX_SUBSCRIPTION_ENTRIES} entries: the rest are left out"
));
break;
}
let tag = unique_tag(make_tag(tag_prefix, remark_from_line(line), index), &seen);
let mut errors = Vec::new();
let mut taken = false;
for &backend in backends {
let attempt = (|| -> Result<Value> {
let ob = parse_url(line, &tag, backend)?;
for server in dialed_servers(&ob) {
check_server(&server, opts.allow_private)?;
}
// Whoever serves the list could otherwise have the tunnel trust any certificate.
let insecure = ob.get("tls").and_then(Value::as_object).and_then(|t| t.get("insecure"));
if !opts.allow_insecure && insecure.is_some_and(|v| v.as_bool().unwrap_or(!v.is_null())) {
return Err(LinkError::invalid("it turns certificate checks off (insecure=1; see allowInsecure)"));
}
finish_outbound(ob, backend)
})();
match attempt {
Ok(ob) => {
seen.insert(tag.clone());
parsed.outbounds.push((backend, ob));
parsed.links.push((tag.clone(), line.clone()));
taken = true;
break;
}
Err(LinkError::RefusedServer(message)) => {
// The same server whichever backend reads the line.
parsed.warnings.push(format!("skipping entry {index} ({scheme}): {message}"));
taken = true;
break;
}
Err(LinkError::Invalid(message)) => {
errors.push(if backends.len() > 1 { format!("{}: {message}", backend.as_str()) } else { message });
}
}
}
if !taken {
parsed.warnings.push(format!("skipping entry {index} ({scheme}): {}", errors.join("; ")));
}
}
parsed
}
/// A subscription for one backend.
pub fn parse_subscription(lines: &[String], tag_prefix: &str, backend: LinkBackend, opts: Options) -> Parsed {
walk(lines, tag_prefix, &[backend], opts)
}
/// A subscription for the hybrid backend: each line goes to whichever backend can dial it,
/// sing-box first.
pub fn parse_hybrid_subscription(lines: &[String], tag_prefix: &str, opts: Options) -> Parsed {
walk(lines, tag_prefix, &[LinkBackend::SingBox, LinkBackend::Xray], opts)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn inet_aton_takes_the_short_forms() {
assert_eq!(inet_aton("2130706433"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("0x7f.1"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("127.1"), Some(Ipv4Addr::new(127, 0, 0, 1)));
assert_eq!(inet_aton("010.0.0.1"), Some(Ipv4Addr::new(8, 0, 0, 1)));
assert_eq!(inet_aton("1.2.3.4.5"), None);
assert_eq!(inet_aton("256.1"), None);
}
#[test]
fn servers_on_this_host_or_its_lan_are_refused() {
for host in ["127.0.0.1", "localhost", "a.localhost", "[::1]", "0x7f.1", "::ffff:127.0.0.1", "169.254.1.1", "0.0.0.0"] {
assert!(matches!(check_server(&json!(host), true), Err(LinkError::RefusedServer(_))), "{host}");
}
assert!(check_server(&json!("192.168.1.10"), false).is_err());
assert!(check_server(&json!("192.168.1.10"), true).is_ok());
assert!(check_server(&json!("example.com"), false).is_ok());
assert!(check_server(&json!(null), false).is_ok());
}
#[test]
fn redirects_never_come_nearer() {
let u = |s| url_parts::split(s).unwrap();
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("https://cdn.example.com/y")).is_ok());
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("http://cdn.example.com/y")).is_err());
assert!(redirect_allowed(&u("https://sub.example.com/x"), &u("http://127.0.0.1/y")).is_err());
assert!(redirect_allowed(&u("http://192.168.1.1/x"), &u("ftp://192.168.1.1/y")).is_err());
assert_eq!(u("https://user@[::1]:8443/p").hostname.as_deref(), Some("::1"));
}
#[test]
fn base64_and_plain_bodies_decode() {
let links = "vless://u@a.example:443?security=tls#A\nhy2://p@b.example:443#B\n";
assert_eq!(decode_subscription(links.as_bytes()).len(), 2);
let b64 = base64::Engine::encode(&base64::engine::general_purpose::URL_SAFE, links);
let wrapped: String = b64.as_bytes().chunks(20).map(|c| String::from_utf8_lossy(c) + "\n").collect();
assert_eq!(decode_subscription(wrapped.as_bytes()), ["vless://u@a.example:443?security=tls#A", "hy2://p@b.example:443#B"]);
}
#[test]
fn tags_follow_remarks() {
assert_eq!(slugify_tag("🇩🇪 Germany | Frankfurt"), "Germany-Frankfurt");
assert_eq!(slugify_tag("Нидерланды 1"), "Нидерланды-1");
assert_eq!(slugify_tag("!!!"), "proxy");
assert_eq!(make_tag("sub", "", 3), "sub-3");
assert_eq!(make_tag("sub", "Fast%20One", 3), "sub-Fast-One");
}
#[test]
fn a_walk_skips_bad_entries_and_numbers_duplicates() {
let lines: Vec<String> = [
"hy2://p@a.example.com:443#Same",
"hy2://p@b.example.com:443#Same",
"hy2://p@127.0.0.1:443#Loop",
"vless://u@c.example.com:70000#Bad",
"garbage",
"hy2://p@d.example.com:443?insecure=1#Insecure",
]
.map(String::from)
.to_vec();
let parsed = parse_subscription(&lines, "s", LinkBackend::SingBox, Options::default());
let tags: Vec<&str> = parsed.links.iter().map(|(t, _)| t.as_str()).collect();
assert_eq!(tags, ["s-Same", "s-Same-2"]);
assert_eq!(parsed.warnings.len(), 3, "{:?}", parsed.warnings);
assert!(parsed.warnings[0].contains("is this host"));
assert!(parsed.warnings[1].contains("out of range"));
assert!(parsed.warnings[2].contains("certificate checks off"));
}
#[test]
fn hybrid_hands_xray_only_links_to_xray() {
let lines = vec![
"vless://u@a.example.com:443?security=tls&type=xhttp&path=%2Fx#X".to_owned(),
"hy2://p@b.example.com:443#H".to_owned(),
];
let parsed = parse_hybrid_subscription(&lines, "s", Options::default());
assert_eq!(parsed.outbounds[0].0, LinkBackend::Xray);
assert_eq!(parsed.outbounds[1].0, LinkBackend::SingBox);
}
#[test]
fn xhttp_download_servers_are_checked_too() {
let extra = py::unquote("%7B%22downloadSettings%22%3A%7B%22address%22%3A%22127.0.0.1%22%7D%7D");
let line = format!(
"vless://u@a.example.com:443?security=tls&type=xhttp&extra={}#X",
percent_encoding::utf8_percent_encode(&extra, percent_encoding::NON_ALPHANUMERIC)
);
let parsed = parse_subscription(&[line], "s", LinkBackend::Xray, Options::default());
assert!(parsed.outbounds.is_empty());
assert!(parsed.warnings[0].contains("is this host"));
}
}
+436
View File
@@ -0,0 +1,436 @@
//! Upstream's `scripts/test-build-outbound.py`, case for case.
use base64::Engine;
use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
use serde_json::{Value, json};
use super::*;
fn sing(url: &str) -> Value {
build_outbound(url, "test-outbound", LinkBackend::SingBox).unwrap_or_else(|e| panic!("{url}: {e}"))
}
fn xray(url: &str) -> Value {
build_outbound(url, "test-outbound", LinkBackend::Xray).unwrap_or_else(|e| panic!("{url}: {e}"))
}
fn err(url: &str, backend: LinkBackend) -> String {
match build_outbound(url, "test-outbound", backend) {
Ok(ob) => panic!("{url} ({}) parsed: {ob}", backend.as_str()),
Err(e) => e.to_string(),
}
}
fn vmess_url(extra: Value) -> String {
let mut body = json!({ "add": "example.com", "port": 443, "id": "uuid", "net": "tcp" });
for (k, v) in extra.as_object().unwrap() {
body[k] = v.clone();
}
format!("vmess://{}", STANDARD.encode(body.to_string()))
}
const PBK: &str = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc";
#[test]
fn vless_reality() {
let ob = sing(&format!(
"vless://uuid@example.com:443?security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com&sid=abcd"
));
assert_eq!(ob["type"], "vless");
assert_eq!(ob["server"], "example.com");
assert_eq!(ob["tls"]["reality"]["public_key"], PBK);
}
#[test]
fn vless_reality_germany_main_shape() {
let url = format!(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=qq&sni=last.fm&sid=8a54\
&spx=%2F-%2Fen%2Fgp%2Fbestsellers&flow=xtls-rprx-vision&encryption=none"
);
let ob = sing(&url);
assert_eq!(ob["server_port"], 443);
assert_eq!(ob["flow"], "xtls-rprx-vision");
assert_eq!(ob["tls"]["server_name"], "last.fm");
assert_eq!(ob["tls"]["utls"]["fingerprint"], "qq");
assert_eq!(ob["tls"]["reality"]["short_id"], "8a54");
assert!(ob["tls"]["reality"].get("spider_x").is_none());
assert!(ob.get("transport").is_none());
let ob = xray(&url);
assert_eq!(ob["protocol"], "vless");
assert_eq!(ob["settings"]["address"], "example.com");
assert_eq!(ob["settings"]["flow"], "xtls-rprx-vision");
assert_eq!(ob["streamSettings"]["network"], "raw");
assert_eq!(ob["streamSettings"]["sockopt"]["domainStrategy"], "UseIP");
assert_eq!(ob["streamSettings"]["realitySettings"]["serverName"], "last.fm");
assert_eq!(ob["streamSettings"]["realitySettings"]["fingerprint"], "qq");
assert_eq!(ob["streamSettings"]["realitySettings"]["spiderX"], "/-/en/gp/bestsellers");
}
#[test]
fn vless_raw_transport_is_tcp() {
let ob = sing(&format!("vless://uuid@example.com:443?type=raw&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com"));
assert!(ob.get("transport").is_none());
}
#[test]
fn at_sign_in_query_does_not_eat_the_host() {
let ob = sing(&format!(
"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com&Telegram=@somechannel,@somechannel"
));
assert_eq!(ob["server"], "example.com");
assert_eq!(ob["server_port"], 443);
}
#[test]
fn trailing_path_is_not_part_of_the_port() {
let ob = sing(&format!("vless://uuid@example.com:23576/?type=tcp&security=reality&pbk={PBK}&fp=chrome&sni=cdn.example.com"));
assert_eq!(ob["server_port"], 23576);
}
#[test]
fn port_out_of_range_is_rejected() {
for url in ["vless://uuid@example.com:70000?type=tcp", "trojan://pw@example.com:0", "ss://YWVzLTI1Ni1nY206cHc@example.com:99999"] {
assert!(err(url, LinkBackend::SingBox).contains("out of range"), "{url}");
}
}
#[test]
fn reality_empty_fingerprint_falls_back_to_chrome() {
let ob = sing(&format!("vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=&sni=cdn.example.com"));
assert_eq!(ob["tls"]["utls"]["fingerprint"], "chrome");
}
#[test]
fn xray_only_fingerprint_rejected_for_sing_box() {
let url = format!("vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&fp=hellochrome_120&sni=cdn.example.com");
err(&url, LinkBackend::SingBox);
assert_eq!(xray(&url)["streamSettings"]["realitySettings"]["fingerprint"], "hellochrome_120");
for fp in ["unsafe", "hellogolang", "bogus"] {
assert!(err(&url.replace("hellochrome_120", fp), LinkBackend::Xray).contains("XRay would refuse"), "{fp}");
}
}
#[test]
fn values_a_backend_refuses_to_start_on_are_rejected() {
let reality = format!("vless://uuid@example.com:443?security=reality&sni=a.example.com&pbk={PBK}&sid=ab");
let tuic = "tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443";
let k16 = STANDARD.encode(b"k".repeat(16));
let k32 = STANDARD.encode(b"k".repeat(32));
let cases: Vec<(String, &str, &str)> = vec![
(format!("{reality}&flow=xtls-rprx-direct"), "both", "flow"),
(format!("{reality}&flow=xtls-rprx-vision-udp443"), "sing-box", "flow"),
(reality.replace("pbk=SbVK", "pbk=SbV+"), "both", "pbk"),
(reality.replace(&format!("pbk={PBK}"), "pbk=pubkey"), "both", "pbk"),
(reality.replace("sid=ab", "sid=abc"), "both", "sid"),
(reality.replace("sid=ab", "sid=0123456789abcdef00"), "both", "sid"),
(reality.replace("sid=ab", "sid=zz"), "both", "sid"),
(format!("{reality}&spx=nopath"), "xray", "spx"),
(format!("{reality}&spx=%2F%25zz"), "xray", "spx"),
(format!("{reality}&spx=%2Fa%01b"), "xray", "spx"),
(reality.replace("uuid@", &format!("{}@", "x".repeat(31))), "xray", "VLESS id"),
("vless://uuid@example.com:443?type=xhttp&security=tls&mode=bogus".into(), "xray", "xhttp mode"),
("vless://uuid@example.com:443?type=h2&security=tls".into(), "xray", "transport"),
("vless://uuid@example.com:443?type=quic&security=tls".into(), "xray", "transport"),
("trojan://pw@example.com:443?security=tls&fp=bogus".into(), "both", "fingerprint"),
(vmess_url(json!({ "scy": "aes-128-ctr" })), "sing-box", "VMess security"),
(vmess_url(json!({ "scy": "bogus" })), "sing-box", "VMess security"),
(vmess_url(json!({ "id": 123 })), "both", "VMess id"),
(vmess_url(json!({ "id": null })), "xray", "VMess id"),
(format!("{tuic}?congestion_control=reno"), "sing-box", "congestion_control"),
("tuic://not-a-uuid:pw@example.com:443".into(), "sing-box", "TUIC uuid"),
("hy2://pw@example.com:443?mport=a-b".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=1-70000".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=0-5".into(), "both", "mport"),
("hy2://pw@example.com:443?mport=30000-20000".into(), "both", "mport"),
("hy2://pw@example.com:443?insecure=1&pinSHA256=abcd".into(), "xray", "pinSHA256"),
("trojan://@example.com:443?security=tls".into(), "both", "password is empty"),
("hy2://pw@example.com:443?obfs=salamander".into(), "both", "obfs-password"),
("ss://plain:pw@example.com:8388".into(), "both", "method"),
("ss://aes-128-ctr:pw@example.com:8388".into(), "xray", "method"),
("ss://chacha20-poly1305:pw@example.com:8388".into(), "sing-box", "method"),
("ss://2022-blake3-aes-128-gcm:pw@example.com:8388".into(), "both", "base64 key"),
(format!("ss://2022-blake3-aes-128-gcm:{k32}@example.com:8388"), "both", "base64 key"),
(format!("ss://2022-blake3-chacha20-poly1305:{k16}%3A{k16}@example.com:8388"), "both", "single key"),
];
for (url, backends, message) in cases {
let list: &[LinkBackend] = match backends {
"both" => &[LinkBackend::SingBox, LinkBackend::Xray],
"sing-box" => &[LinkBackend::SingBox],
_ => &[LinkBackend::Xray],
};
for &backend in list {
let e = err(&url, backend);
assert!(e.contains(message), "{url} ({}): {e:?} lacks {message:?}", backend.as_str());
}
}
}
#[test]
fn values_one_backend_takes_still_parse() {
let reality = format!("vless://uuid@example.com:443?security=reality&sni=a.example.com&pbk={PBK}&sid=0123456789ABCDEF");
assert_eq!(xray(&format!("{reality}&flow=xtls-rprx-vision-udp443"))["settings"]["flow"], "xtls-rprx-vision-udp443");
assert_eq!(sing(&reality)["tls"]["reality"]["short_id"], "0123456789ABCDEF");
assert_eq!(xray(&vmess_url(json!({ "scy": "aes-128-ctr" })))["settings"]["security"], "aes-128-ctr");
assert_eq!(sing(&vmess_url(json!({ "scy": "aes-128-cfb" })))["security"], "aes-128-cfb");
// XRay takes a space (and non-ASCII) in spiderX; only control characters and bad escapes kill it.
let spx = xray(&format!("{reality}&spx=%2Fa%20b%C3%A9"));
assert_eq!(spx["streamSettings"]["realitySettings"]["spiderX"], "/a b\u{e9}");
assert_eq!(xray("ss://chacha20-poly1305:pw@example.com:8388")["settings"]["method"], "chacha20-poly1305");
assert_eq!(sing("ss://aes-128-ctr:pw@example.com:8388")["method"], "aes-128-ctr");
let k16 = STANDARD.encode(b"k".repeat(16));
let ss2022 = sing(&format!("ss://2022-blake3-aes-128-gcm:{k16}%3A{k16}@example.com:8388"));
assert_eq!(ss2022["password"], format!("{k16}:{k16}"));
}
#[test]
fn hysteria2_port_hopping_takes_lone_ports() {
let ob = sing("hy2://pw@example.com:443?mport=443, 20000-30000");
assert_eq!(ob["server_ports"], json!(["443:443", "20000:30000"]));
let remote = xray("hy2://pw@example.com:443?mport=443,20000-30000");
assert_eq!(remote["streamSettings"]["finalmask"]["udp"][0]["settings"]["remotePorts"], "443-443,20000-30000");
}
#[test]
fn hysteria2_pin_replaces_insecure_for_xray() {
let pin = vec!["AB"; 32].join(":");
let url = format!("hy2://pw@example.com:443?sni=a.example.com&insecure=1&pinSHA256={pin}");
let ob = xray(&url);
assert_eq!(ob["streamSettings"]["tlsSettings"]["pinnedPeerCertSha256"], "ab".repeat(32));
// sing-box pins only a public key: the link stays insecure there.
assert_eq!(sing(&url)["tls"]["insecure"], true);
}
#[test]
fn reality_without_pbk_is_rejected_clearly() {
assert!(err("vless://uuid@example.com:443?security=reality&type=tcp", LinkBackend::SingBox).contains("pbk"));
}
#[test]
fn vless_httpupgrade_and_quic_transports() {
let ob = sing("vless://uuid@example.com:443?type=httpupgrade&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fupgrade");
assert_eq!(ob["transport"], json!({ "type": "httpupgrade", "host": "cdn.example.com", "path": "/upgrade" }));
let ob = sing("vless://uuid@example.com:443?type=quic&security=tls&sni=cdn.example.com");
assert_eq!(ob["transport"]["type"], "quic");
}
#[test]
fn vless_xhttp_fails_loudly_on_sing_box() {
assert!(
err("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com", LinkBackend::SingBox)
.contains("unsupported VLESS transport 'xhttp'")
);
}
#[test]
fn xray_vless_xhttp() {
let ob = xray("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&host=cdn.example.com&path=%2Fx");
assert_eq!(ob["settings"]["id"], "uuid");
assert_eq!(ob["streamSettings"]["network"], "xhttp");
assert_eq!(ob["streamSettings"]["xhttpSettings"]["path"], "/x");
}
fn quote(s: &str) -> String {
percent_encoding::utf8_percent_encode(s, percent_encoding::NON_ALPHANUMERIC).to_string()
}
#[test]
fn xray_xhttp_extra_keeps_ordinary_settings() {
let extra = json!({ "xPaddingBytes": "100-1000", "downloadSettings": { "address": "dl.example.com" } });
let ob = xray(&format!(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}",
quote(&extra.to_string())
));
assert_eq!(ob["streamSettings"]["xhttpSettings"]["extra"]["xPaddingBytes"], "100-1000");
}
#[test]
fn xray_xhttp_extra_cannot_name_local_files() {
let extra = json!({ "downloadSettings": { "tlsSettings": { "masterKeyLog": "/etc/x", "certificates": [{ "keyFile": "/root/k" }] } } });
let e = err(
&format!("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}", quote(&extra.to_string())),
LinkBackend::Xray,
);
assert!(e.contains("keyfile, masterkeylog"), "{e}");
}
#[test]
fn xray_xhttp_extra_cannot_set_socket_options() {
let cases = [
(
json!({ "downloadSettings": { "address": "dl.example.com", "sockopt": { "mark": 0, "tcpFastOpen": true } } }),
json!({ "downloadSettings": { "address": "dl.example.com", "sockopt": { "tcpFastOpen": true } } }),
),
(json!({ "downloadSettings": { "sockopt": { "customSockopt": [], "TProxy": "redirect" } } }), json!({ "downloadSettings": { "sockopt": {} } })),
(json!({ "downloadSettings": { "sockopt": { "dialerProxy": "direct", "interface": "eth0" } } }), json!({ "downloadSettings": { "sockopt": {} } })),
(json!({ "Mark": 1, "xPaddingBytes": "100-1000" }), json!({ "xPaddingBytes": "100-1000" })),
// The Kelvin sign, which Go folds to k as Python's lower() does.
(json!({ "downloadSettings": { "sockopt": { "mar\u{212a}": 0 } } }), json!({ "downloadSettings": { "sockopt": {} } })),
];
for (extra, left) in cases {
let ob = xray(&format!(
"vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}",
quote(&extra.to_string())
));
assert_eq!(ob["streamSettings"]["xhttpSettings"]["extra"], left, "{extra}");
}
// Go's JSON decoding folds U+017F to s: a non-ASCII key is refused outright.
let extra = json!({ "downloadSettings": { "tlsSettings": { "ma\u{17f}terKeyLog": "/etc/x" } } });
let e = err(
&format!("vless://uuid@example.com:443?type=xhttp&security=tls&sni=cdn.example.com&extra={}", quote(&extra.to_string())),
LinkBackend::Xray,
);
assert!(e.contains("names local files"), "{e}");
}
#[test]
fn xray_vless_ech() {
let ob = xray("vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=udp%3A%2F%2F1.1.1.1");
assert_eq!(ob["streamSettings"]["tlsSettings"]["echConfigList"], "udp://1.1.1.1");
assert!(
err("vless://uuid@example.com:443?type=tcp&security=tls&sni=cdn.example.com&ech=blob", LinkBackend::SingBox)
.contains("unsupported VLESS parameter 'ech'")
);
}
#[test]
fn xray_socks_and_shadowsocks_use_flat_settings() {
let ob = xray("socks5://user:pass@example.com:1080");
assert_eq!(ob["protocol"], "socks");
assert_eq!(ob["settings"]["address"], "example.com");
assert_eq!(ob["settings"]["user"], "user");
assert!(ob["settings"].get("servers").is_none());
let creds = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd");
let ob = xray(&format!("ss://{creds}@ss.example.com:8388"));
assert_eq!(ob["protocol"], "shadowsocks");
assert_eq!(ob["settings"]["method"], "chacha20-ietf-poly1305");
}
#[test]
fn vmess_forms() {
let payload = json!({
"add": "vmess.example.com", "port": "443", "id": "00000000-0000-0000-0000-000000000000", "aid": "0",
"scy": "auto", "net": "ws", "host": "cdn.example.com", "path": "/ws", "tls": "tls", "sni": "cdn.example.com",
});
let ob = sing(&format!("vmess://{}", STANDARD.encode(payload.to_string())));
assert_eq!(ob["transport"]["type"], "ws");
assert_eq!(ob["tls"]["server_name"], "cdn.example.com");
let payload = json!({ "add": "vmess.example.com", "port": "443", "id": "00000000-0000-0000-0000-000000000000", "aid": "0", "scy": "auto" });
let ob = sing(&format!("vmess://{}#Subscription Remark", URL_SAFE_NO_PAD.encode(payload.to_string())));
assert_eq!(ob["server"], "vmess.example.com");
let payload = json!({ "add": "vmess.example.com", "port": 443, "id": "u", "aid": "", "scy": "" });
let ob = sing(&format!("vmess://{}", STANDARD.encode(payload.to_string())));
assert_eq!((ob["alter_id"].clone(), ob["security"].clone()), (json!(0), json!("auto")));
let as_list = sing(&vmess_url(json!({ "tls": "tls", "alpn": ["h2", "http/1.1"] })));
let as_text = sing(&vmess_url(json!({ "tls": "tls", "alpn": "h2, http/1.1" })));
assert_eq!(as_list["tls"]["alpn"], json!(["h2", "http/1.1"]));
assert_eq!(as_text["tls"]["alpn"], json!(["h2", "http/1.1"]));
assert!(err(&vmess_url(json!({ "net": "kcp" })), LinkBackend::SingBox).contains("unsupported VMess transport 'kcp'"));
}
#[test]
fn socks4_keeps_its_bare_userid() {
let ob = sing("socks4://me@10.0.0.1:1080");
assert_eq!((ob["version"].clone(), ob["username"].clone()), (json!("4"), json!("me")));
assert!(ob.get("password").is_none());
}
#[test]
fn blank_parameters_fall_back_to_the_server() {
let ob = sing("vless://uuid@example.com:443?security=tls&sni=&type=ws&host=&path=");
assert_eq!(ob["tls"]["server_name"], "example.com");
assert_eq!(ob["transport"]["headers"]["Host"], "example.com");
assert_eq!(ob["transport"]["path"], "/");
let tuic = sing("tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?alpn=&congestion_control=&udp_relay_mode=");
assert_eq!(tuic["tls"]["alpn"], json!(["h3"]));
assert_eq!((tuic["congestion_control"].clone(), tuic["udp_relay_mode"].clone()), (json!("bbr"), json!("native")));
}
#[test]
fn trojan_shadowsocks_and_friends() {
let ob = sing("trojan://secret@example.com:443?sni=tls.example.com&fp=chrome");
assert_eq!(ob["password"], "secret");
assert_eq!(ob["tls"]["server_name"], "tls.example.com");
let creds = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd");
assert_eq!(sing(&format!("ss://{creds}@ss.example.com:8388"))["method"], "chacha20-ietf-poly1305");
let legacy = URL_SAFE_NO_PAD.encode("chacha20-ietf-poly1305:passw0rd@legacy.example.com:8388");
let ob = sing(&format!("ss://{legacy}#Legacy Server"));
assert_eq!((ob["server"].clone(), ob["server_port"].clone()), (json!("legacy.example.com"), json!(8388)));
assert_eq!(ob["password"], "passw0rd");
let ob = sing("ss://none:plain%20pass@plain.example.com:8388");
assert_eq!((ob["method"].clone(), ob["password"].clone()), (json!("none"), json!("plain pass")));
let legacy = URL_SAFE_NO_PAD.encode("none:pass@[2001:db8::1]:8388");
assert_eq!(sing(&format!("ss://{legacy}#Legacy IPv6"))["server"], "2001:db8::1");
}
#[test]
fn hysteria2_both_backends() {
let ob = sing("hy2://secret@example.com:443?sni=hy.example.com&insecure=1&obfs=salamander&obfs-password=mask");
assert_eq!(ob["tls"]["insecure"], true);
assert_eq!(ob["obfs"]["password"], "mask");
let ob = xray("hy2://secret@example.com:443?sni=hy.example.com&obfs=salamander&obfs-password=mask");
assert_eq!(ob["protocol"], "hysteria");
assert!(ob["settings"].get("password").is_none());
assert_eq!(ob["streamSettings"]["network"], "hysteria");
assert_eq!(ob["streamSettings"]["tlsSettings"]["serverName"], "hy.example.com");
assert_eq!(ob["streamSettings"]["hysteriaSettings"]["auth"], "secret");
assert_eq!(ob["streamSettings"]["finalmask"]["udp"], json!([{ "type": "salamander", "settings": { "password": "mask" } }]));
assert!(err("hy2://secret@example.com:443?sni=hy.example.com&insecure=1", LinkBackend::Xray).contains("allowInsecure"));
}
#[test]
fn tuic_anytls_naive_and_plain_proxies() {
let ob = sing("tuic://00000000-0000-0000-0000-000000000000:secret@example.com:443?sni=tuic.example.com&alpn=h3,hq-29");
assert_eq!(ob["tls"]["alpn"], json!(["h3", "hq-29"]));
let ob = sing("anytls://p%40ss@example.com:443?sni=a.example.com&insecure=1&fp=chrome#name");
assert_eq!(ob["password"], "p@ss");
assert_eq!(
ob["tls"],
json!({ "enabled": true, "server_name": "a.example.com", "insecure": true, "utls": { "enabled": true, "fingerprint": "chrome" } })
);
assert!(err("anytls://pw@example.com:443", LinkBackend::Xray).contains("unsupported XRay outbound type"));
let ob = sing("naive+https://user:pass@example.com:443#name");
assert_eq!((ob["type"].clone(), ob["username"].clone(), ob["password"].clone()), (json!("naive"), json!("user"), json!("pass")));
assert!(ob.get("quic").is_none());
assert_eq!(sing("naive+quic://user:pass@example.com:443")["quic"], true);
let ob = sing("socks5://user:p@ss@example.com:1080");
assert_eq!((ob["username"].clone(), ob["password"].clone(), ob["server"].clone()), (json!("user"), json!("p@ss"), json!("example.com")));
let ob = sing("https://proxy.example.com:8443");
assert_eq!(ob["type"], "http");
assert_eq!(ob["tls"]["server_name"], "proxy.example.com");
}
#[test]
fn invalid_scheme_and_transports_fail_loudly() {
assert!(err("wireguard://example.com", LinkBackend::SingBox).contains("unsupported scheme"));
let url = "trojan://pw@example.com:443?security=tls&type=xhttp&path=/p";
assert!(err(url, LinkBackend::SingBox).contains("unsupported Trojan transport 'xhttp'"));
assert_eq!(xray(url)["streamSettings"]["network"], "xhttp");
}
#[test]
fn xray_only_fingerprint_for_trojan_and_vmess() {
let trojan = "trojan://pw@example.com:443?security=tls&fp=unsafe";
err(trojan, LinkBackend::SingBox);
assert_eq!(xray(trojan)["streamSettings"]["tlsSettings"]["fingerprint"], "unsafe");
let vmess = vmess_url(json!({ "tls": "tls", "fp": "unsafe" }));
err(&vmess, LinkBackend::SingBox);
assert_eq!(xray(&vmess)["streamSettings"]["tlsSettings"]["fingerprint"], "unsafe");
}
#[test]
fn local_file_keys_catch_what_upstream_does() {
let v = json!({ "a": { "certificatePath": 1, "path": "/", "x": [{ "torrc": 1, "logFile": 2 }] }, "ß": 0 });
assert_eq!(local_file_keys(&v), ["certificatepath", "logfile", "torrc", "ß"]);
}
+253
View File
@@ -0,0 +1,253 @@
//! A sing-box-shaped outbound in XRay's shape: upstream's `render_xray_outbound`.
use serde_json::{Map, Value, json};
use super::{LinkError, Result};
fn s<'a>(map: &'a Map<String, Value>, key: &str) -> Option<&'a Value> {
map.get(key)
}
fn str_of<'a>(map: &'a Map<String, Value>, key: &str) -> &'a str {
map.get(key).and_then(Value::as_str).unwrap_or("")
}
fn truthy(v: Option<&Value>) -> bool {
match v {
None | Some(Value::Null) => false,
Some(Value::Bool(b)) => *b,
Some(Value::String(s)) => !s.is_empty(),
Some(Value::Array(a)) => !a.is_empty(),
Some(Value::Object(o)) => !o.is_empty(),
Some(Value::Number(n)) => n.as_f64() != Some(0.0),
}
}
fn utls_fingerprint(tls: &Map<String, Value>) -> Option<Value> {
let utls = tls.get("utls")?.as_object()?;
(truthy(utls.get("enabled")) && truthy(utls.get("fingerprint"))).then(|| utls["fingerprint"].clone())
}
fn xray_tls(tls: Option<&Value>) -> Result<(&'static str, Map<String, Value>)> {
let Some(tls) = tls.and_then(Value::as_object).filter(|t| truthy(t.get("enabled"))) else {
return Ok(("none", Map::new()));
};
let mut out = Map::new();
if let Some(reality) = tls.get("reality").and_then(Value::as_object).filter(|r| truthy(r.get("enabled"))) {
let mut settings = Map::new();
settings.insert("serverName".into(), str_of(tls, "server_name").into());
settings.insert("publicKey".into(), reality.get("public_key").cloned().unwrap_or(Value::Null));
settings.insert("shortId".into(), str_of(reality, "short_id").into());
if truthy(reality.get("spider_x")) {
settings.insert("spiderX".into(), reality["spider_x"].clone());
}
if let Some(fp) = utls_fingerprint(tls) {
settings.insert("fingerprint".into(), fp);
}
out.insert("realitySettings".into(), Value::Object(settings));
return Ok(("reality", out));
}
let mut settings = Map::new();
settings.insert("serverName".into(), str_of(tls, "server_name").into());
if truthy(tls.get("alpn")) {
settings.insert("alpn".into(), tls["alpn"].clone());
}
if truthy(tls.get("insecure")) {
return Err(LinkError::invalid(
"XRay no longer supports tlsSettings.allowInsecure; remove insecure=1 or use a supported certificate verification option",
));
}
if truthy(tls.get("certificate_sha256")) {
settings.insert("pinnedPeerCertSha256".into(), tls["certificate_sha256"].clone());
}
if truthy(tls.get("ech_config_list")) {
settings.insert("echConfigList".into(), tls["ech_config_list"].clone());
}
if let Some(fp) = utls_fingerprint(tls) {
settings.insert("fingerprint".into(), fp);
}
out.insert("tlsSettings".into(), Value::Object(settings));
Ok(("tls", out))
}
fn xray_transport(transport: Option<&Value>) -> (String, Map<String, Value>) {
let Some(t) = transport.and_then(Value::as_object).filter(|t| !t.is_empty()) else {
return ("raw".into(), Map::new());
};
let kind = str_of(t, "type");
let mut out = Map::new();
let path = || t.get("path").cloned().unwrap_or_else(|| "/".into());
match kind {
"ws" => {
out.insert(
"wsSettings".into(),
json!({ "path": path(), "headers": t.get("headers").cloned().unwrap_or_else(|| json!({})) }),
);
}
"grpc" => {
out.insert("grpcSettings".into(), json!({ "serviceName": t.get("service_name").cloned().unwrap_or_else(|| "".into()) }));
}
"http" => {
out.insert(
"httpSettings".into(),
json!({ "host": t.get("host").cloned().unwrap_or_else(|| json!([])), "path": path() }),
);
}
"httpupgrade" => {
out.insert(
"httpupgradeSettings".into(),
json!({ "host": t.get("host").cloned().unwrap_or_else(|| "".into()), "path": path() }),
);
}
"quic" => {}
"xhttp" => {
let mut settings = Map::new();
settings.insert("path".into(), path());
if truthy(t.get("host")) {
settings.insert("host".into(), t["host"].clone());
}
if truthy(t.get("mode")) {
settings.insert("mode".into(), t["mode"].clone());
}
if let Some(extra) = t.get("extra").filter(|e| !e.is_null()) {
settings.insert("extra".into(), extra.clone());
}
out.insert("xhttpSettings".into(), Value::Object(settings));
}
_ => {}
}
(kind.to_owned(), out)
}
/// `{"protocol", "tag", "settings", "streamSettings"}` for XRay, from a sing-box-shaped
/// outbound as the parsers make them.
pub fn render_xray_outbound(ob: &Map<String, Value>) -> Result<Value> {
let typ = str_of(ob, "type");
let tag = s(ob, "tag").cloned().unwrap_or(Value::Null);
let server = || s(ob, "server").cloned().unwrap_or(Value::Null);
let port = || s(ob, "server_port").cloned().unwrap_or(Value::Null);
let stream_settings = || -> Result<Map<String, Value>> {
let (security, sec) = xray_tls(ob.get("tls"))?;
let (network, net) = xray_transport(ob.get("transport"));
let mut stream = Map::new();
stream.insert("network".into(), network.into());
stream.insert("security".into(), security.into());
stream.extend(sec);
stream.extend(net);
stream.insert("sockopt".into(), json!({ "domainStrategy": "UseIP" }));
Ok(stream)
};
let mut out = Map::new();
match typ {
"vless" => {
let mut settings = Map::new();
settings.insert("address".into(), server());
settings.insert("port".into(), port());
settings.insert("id".into(), ob.get("uuid").cloned().unwrap_or(Value::Null));
settings.insert("encryption".into(), "none".into());
if truthy(ob.get("flow")) {
settings.insert("flow".into(), ob["flow"].clone());
}
out.insert("protocol".into(), "vless".into());
out.insert("tag".into(), tag);
out.insert("settings".into(), Value::Object(settings));
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"vmess" => {
out.insert("protocol".into(), "vmess".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({
"address": server(),
"port": port(),
"id": ob.get("uuid").cloned().unwrap_or(Value::Null),
"security": ob.get("security").cloned().unwrap_or_else(|| "auto".into()),
"alterId": ob.get("alter_id").cloned().unwrap_or_else(|| 0.into()),
}),
);
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"trojan" => {
out.insert("protocol".into(), "trojan".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({ "address": server(), "port": port(), "password": ob.get("password").cloned().unwrap_or(Value::Null) }),
);
out.insert("streamSettings".into(), Value::Object(stream_settings()?));
}
"shadowsocks" => {
out.insert("protocol".into(), "shadowsocks".into());
out.insert("tag".into(), tag);
out.insert(
"settings".into(),
json!({
"address": server(),
"port": port(),
"method": ob.get("method").cloned().unwrap_or(Value::Null),
"password": ob.get("password").cloned().unwrap_or(Value::Null),
}),
);
}
"hysteria2" => {
let mut stream = stream_settings()?;
stream.insert("network".into(), "hysteria".into());
stream.insert("security".into(), "tls".into());
let mut hysteria = Map::new();
hysteria.insert("version".into(), 2.into());
if truthy(ob.get("password")) {
hysteria.insert("auth".into(), ob["password"].clone());
}
stream.insert("hysteriaSettings".into(), Value::Object(hysteria));
let mut udp_masks = Vec::new();
// XRay wants udphop outermost, ahead of any other UDP mask.
if let Some(ports) = ob.get("server_ports").and_then(Value::as_array).filter(|p| !p.is_empty()) {
let remote: Vec<String> =
ports.iter().filter_map(Value::as_str).map(|r| r.replace(':', "-")).collect();
udp_masks.push(json!({
"type": "udphop",
"settings": { "mode": "intervalRemote", "interval": "20-40", "remotePorts": remote.join(",") },
}));
}
if let Some(obfs) = ob.get("obfs").and_then(Value::as_object)
&& str_of(obfs, "type") == "salamander" {
udp_masks.push(json!({
"type": "salamander",
"settings": { "password": obfs.get("password").cloned().unwrap_or_else(|| "".into()) },
}));
}
if !udp_masks.is_empty() {
stream.insert("finalmask".into(), json!({ "udp": udp_masks }));
}
out.insert("protocol".into(), "hysteria".into());
out.insert("tag".into(), tag);
out.insert("settings".into(), json!({ "version": 2, "address": server(), "port": port() }));
out.insert("streamSettings".into(), Value::Object(stream));
}
"socks" | "http" => {
let mut settings = Map::new();
settings.insert("address".into(), server());
settings.insert("port".into(), port());
if truthy(ob.get("username")) {
settings.insert("user".into(), ob["username"].clone());
settings.insert("pass".into(), ob.get("password").cloned().unwrap_or_else(|| "".into()));
}
out.insert("protocol".into(), typ.into());
out.insert("tag".into(), tag);
out.insert("settings".into(), Value::Object(settings));
if typ == "http" && truthy(ob.get("tls")) {
let (security, sec) = xray_tls(ob.get("tls"))?;
let mut stream = Map::new();
stream.insert("security".into(), security.into());
stream.extend(sec);
out.insert("streamSettings".into(), Value::Object(stream));
}
}
_ => return Err(LinkError::invalid(format!("unsupported XRay outbound type '{typ}'"))),
}
Ok(Value::Object(out))
}
+303
View File
@@ -0,0 +1,303 @@
//! Outbound groups, resolved against the outbounds a start has: upstream's
//! `outbound-groups.jq`.
use std::collections::{BTreeMap, HashMap, HashSet};
use regex::Regex;
use serde::Serialize;
use serde_json::{Value, json};
use crate::config::{Group, GroupStrategy};
/// What the groups came to.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Resolved {
pub groups: BTreeMap<String, GroupInfo>,
/// The sing-box group outbounds, inner groups first.
pub outbounds: Vec<Value>,
/// What the top level picks among: outbounds in no group, and outermost groups, in
/// priority order.
pub top: Vec<String>,
/// Groups inside themselves.
pub loops: Vec<String>,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct GroupInfo {
pub strategy: GroupStrategy,
pub failback: bool,
pub interval: String,
pub members: Vec<String>,
/// The members the group names itself, which the front ends edit.
pub listed: Vec<String>,
pub pinned: String,
}
/// `*` and `?` over tags.
fn glob_regex(pattern: &str) -> Regex {
let mut out = String::from("^");
for c in pattern.chars() {
match c {
'*' => out.push_str(".*"),
'?' => out.push('.'),
c => out.push_str(&regex::escape(&c.to_string())),
}
}
out.push('$');
Regex::new(&out).expect("an escaped pattern")
}
const LAST: i64 = 1_000_000_000;
pub struct Inputs<'a> {
/// Every outbound tag, in build order.
pub tags: &'a [String],
/// tag -> where it came from ("sub:<tag>" for a subscription entry).
pub sources: &'a HashMap<String, String>,
pub groups: &'a BTreeMap<String, Group>,
pub priority: &'a BTreeMap<String, i64>,
pub disabled: &'a [String],
/// group -> the member pinned in it.
pub pins: &'a BTreeMap<String, String>,
pub url: &'a str,
pub interval: &'a str,
pub tolerance: i64,
/// Whether the service drives failover groups through the Clash API; without it a
/// failover group is sing-box's own urltest.
pub watched: bool,
}
pub fn resolve(inp: &Inputs) -> Resolved {
let names: Vec<&String> = inp.groups.keys().collect();
let is_group = |t: &str| inp.groups.contains_key(t);
let position: HashMap<&str, i64> = inp.tags.iter().enumerate().map(|(i, t)| (t.as_str(), i as i64)).collect();
let prio = |t: &str| inp.priority.get(t).copied().unwrap_or(LAST);
let pos = |t: &str| position.get(t).copied().unwrap_or(LAST);
let mut warnings = Vec::new();
// Members as configured: the explicit list in its order, then the rest by priority,
// then build order. A member that names nothing is dropped with a warning.
let mut members: BTreeMap<String, Vec<String>> = BTreeMap::new();
for g in &names {
let cfg = &inp.groups[*g];
let explicit: Vec<&String> = cfg.outbounds.iter().filter(|t| *t != *g).collect();
let missing: Vec<&String> =
explicit.iter().copied().filter(|t| !inp.tags.contains(t) && !is_group(t)).collect();
let patterns: Vec<Regex> = cfg.match_.iter().map(|p| glob_regex(p)).collect();
let mut pulled: Vec<String> = inp
.tags
.iter()
.filter(|t| {
cfg.subscriptions.iter().any(|s| inp.sources.get(*t).is_some_and(|src| *src == format!("sub:{s}")))
})
.cloned()
.collect();
pulled.extend(
inp.tags
.iter()
.chain(names.iter().copied())
.filter(|t| *t != *g && patterns.iter().any(|p| p.is_match(t)))
.cloned(),
);
pulled.sort();
pulled.dedup();
let mut rest: Vec<String> = pulled.into_iter().filter(|t| !explicit.contains(&t)).collect();
rest.sort_by(|a, b| (prio(a), pos(a), a.as_str()).cmp(&(prio(b), pos(b), b.as_str())));
let mut list: Vec<String> = explicit.iter().filter(|t| !missing.contains(t)).map(|t| (*t).clone()).collect();
list.extend(rest);
members.insert((*g).clone(), list);
for m in missing {
warnings.push(format!("group '{g}': member '{m}' is not available; leaving it out"));
}
}
// A group inside itself, however deep, has no member to end on.
fn reach(g: &str, seen: &mut Vec<String>, members: &BTreeMap<String, Vec<String>>, out: &mut Vec<String>) {
let subs: Vec<&String> = members[g].iter().filter(|m| members.contains_key(*m)).collect();
for m in &subs {
out.push((*m).clone());
}
for m in subs {
if !seen.contains(m) {
seen.push(m.clone());
reach(m, seen, members, out);
}
}
}
let reach_of = |g: &str| {
let mut out = Vec::new();
reach(g, &mut vec![g.to_owned()], &members, &mut out);
out
};
let loops: Vec<String> = names.iter().filter(|g| reach_of(g).contains(g)).map(|g| (*g).clone()).collect();
// Where a group sits when nothing sets its priority: where its first member would have.
fn spot(g: &str, seen: &mut Vec<String>, members: &BTreeMap<String, Vec<String>>, position: &HashMap<&str, i64>) -> Option<i64> {
members[g]
.iter()
.filter_map(|m| {
if members.contains_key(m) && !seen.contains(m) {
seen.push(m.clone());
spot(m, seen, members, position)
} else {
position.get(m.as_str()).copied()
}
})
.min()
}
let spots: HashMap<&str, i64> = names
.iter()
.map(|g| (g.as_str(), spot(g, &mut vec![(*g).clone()], &members, &position).unwrap_or(LAST)))
.collect();
let grouped: HashSet<&String> = members.values().flatten().collect();
let mut top: Vec<String> =
inp.tags.iter().chain(names.iter().copied()).filter(|t| !grouped.contains(t)).cloned().collect();
top.sort_by_key(|t| (prio(t), position.get(t.as_str()).or(spots.get(t.as_str())).copied().unwrap_or(LAST)));
let mut groups = BTreeMap::new();
let mut outbounds = Vec::new();
for g in &names {
let cfg = &inp.groups[*g];
let all = &members[*g];
let usable: Vec<&String> = all.iter().filter(|t| !inp.disabled.contains(t)).collect();
let pin = inp.pins.get(*g).cloned().unwrap_or_default();
let pinned = if pin.is_empty() {
String::new()
} else if !all.contains(&pin) {
warnings.push(format!("group '{g}': pinned member '{pin}' is not in it; picking automatically"));
String::new()
} else if inp.disabled.contains(&pin) {
warnings.push(format!("group '{g}': pinned member '{pin}' is disabled; picking automatically"));
String::new()
} else {
pin
};
if usable.is_empty() {
// With nothing to pick, the group blocks rather than disappear: rules naming it
// must not fall through to direct.
warnings.push(format!("group '{g}' has no available member; it blocks until one is"));
}
let all_or_block: Vec<String> = if all.is_empty() { vec!["block".into()] } else { all.clone() };
let usable_or_block: Vec<String> =
if usable.is_empty() { vec!["block".into()] } else { usable.iter().map(|t| (*t).clone()).collect() };
let interval = cfg.interval.clone().unwrap_or_else(|| {
if cfg.strategy == GroupStrategy::Urltest { inp.interval.to_owned() } else { "30s".into() }
});
groups.insert(
(*g).clone(),
GroupInfo {
strategy: cfg.strategy,
failback: cfg.failback,
interval: interval.clone(),
members: all_or_block.clone(),
listed: cfg.outbounds.iter().filter(|t| *t != *g).cloned().collect(),
pinned: pinned.clone(),
},
);
let as_urltest = (cfg.strategy == GroupStrategy::Urltest
|| (cfg.strategy == GroupStrategy::Failover && !inp.watched))
&& pinned.is_empty();
outbounds.push(if as_urltest {
json!({
"type": "urltest", "tag": g, "outbounds": usable_or_block, "url": inp.url,
"interval": cfg.interval.clone().unwrap_or_else(|| inp.interval.to_owned()), "tolerance": inp.tolerance,
})
} else {
// A pin holds any strategy: a selector the Clash API switches.
let mut sel = json!({
"type": "selector", "tag": g, "outbounds": all_or_block,
"default": if pinned.is_empty() { usable_or_block[0].clone() } else { pinned.clone() },
});
if cfg.strategy == GroupStrategy::Failover {
sel["interrupt_exist_connections"] = true.into();
}
sel
});
}
// Inner groups first: sing-box wants an outbound defined before a group names it.
let depth = |t: &str| names.iter().filter(|g| reach_of(g).iter().any(|r| r == t)).count();
outbounds.sort_by_key(|o| std::cmp::Reverse(depth(o["tag"].as_str().unwrap_or(""))));
Resolved { groups, outbounds, top, loops, warnings }
}
#[cfg(test)]
mod tests {
use super::*;
fn group(outbounds: &[&str], strategy: GroupStrategy) -> Group {
Group { outbounds: outbounds.iter().map(|s| s.to_string()).collect(), strategy, ..Default::default() }
}
fn run(tags: &[&str], groups: BTreeMap<String, Group>, sources: &[(&str, &str)]) -> Resolved {
let tags: Vec<String> = tags.iter().map(|s| s.to_string()).collect();
let sources = sources.iter().map(|(a, b)| (a.to_string(), b.to_string())).collect();
resolve(&Inputs {
tags: &tags,
sources: &sources,
groups: &groups,
priority: &BTreeMap::new(),
disabled: &[],
pins: &BTreeMap::new(),
url: "https://www.gstatic.com/generate_204",
interval: "3m",
tolerance: 50,
watched: true,
})
}
#[test]
fn members_leave_the_top_level() {
let mut groups = BTreeMap::new();
groups.insert("eu".into(), group(&["de", "nl"], GroupStrategy::Failover));
let r = run(&["de", "nl", "us"], groups, &[]);
assert_eq!(r.top, ["eu", "us"]);
assert_eq!(r.groups["eu"].members, ["de", "nl"]);
assert_eq!(r.outbounds[0]["type"], "selector");
assert_eq!(r.outbounds[0]["interrupt_exist_connections"], true);
}
#[test]
fn subscriptions_and_patterns_pull_members_in() {
let mut groups = BTreeMap::new();
groups.insert(
"pool".into(),
Group { subscriptions: vec!["s".into()], match_: vec!["de-*".into()], strategy: GroupStrategy::Urltest, ..Default::default() },
);
let r = run(&["de-1", "s-a", "s-b", "us"], groups, &[("s-a", "sub:s"), ("s-b", "sub:s")]);
assert_eq!(r.groups["pool"].members, ["de-1", "s-a", "s-b"]);
assert_eq!(r.outbounds[0]["type"], "urltest");
assert_eq!(r.outbounds[0]["interval"], "3m");
}
#[test]
fn loops_and_missing_members_are_reported() {
let mut groups = BTreeMap::new();
groups.insert("a".into(), group(&["b", "ghost"], GroupStrategy::Failover));
groups.insert("b".into(), group(&["a"], GroupStrategy::Failover));
let r = run(&["x"], groups, &[]);
assert_eq!(r.loops, ["a", "b"]);
assert!(r.warnings.iter().any(|w| w.contains("'ghost'")));
}
#[test]
fn an_empty_group_blocks() {
let mut groups = BTreeMap::new();
groups.insert("g".into(), group(&[], GroupStrategy::Selector));
let r = run(&["x"], groups, &[]);
assert_eq!(r.outbounds[0]["outbounds"], json!(["block"]));
assert_eq!(r.outbounds[0]["default"], "block");
}
#[test]
fn inner_groups_come_first() {
let mut groups = BTreeMap::new();
groups.insert("a-outer".into(), group(&["z-inner"], GroupStrategy::Selector));
groups.insert("z-inner".into(), group(&["x"], GroupStrategy::Selector));
let r = run(&["x"], groups, &[]);
assert_eq!(r.outbounds[0]["tag"], "z-inner");
assert_eq!(r.top, ["a-outer"]);
}
}
+155
View File
@@ -0,0 +1,155 @@
//! The configs the backends run, from the configuration, the service's runtime state and
//! what it has fetched. Upstream builds these in its start scripts (bash and jq over the
//! Nix templates); here it is one pure function the service calls before every (re)start.
pub mod groups;
mod outbounds;
mod routing;
mod sing_box;
use std::collections::{BTreeMap, HashMap};
use std::fmt;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::config::{Config, RouteMatch, RuleSetFormat};
pub use outbounds::Inventory;
pub use routing::{WantedRuleSet, wanted_rule_sets};
/// `proxy-ctl proxy mode`: an override of `proxy.routing.default` and the lists it keeps.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum RouteMode {
/// Everything proxied but the direct lists (`routing.default = "proxy"`).
Blacklist,
/// Everything direct but the proxy lists (`routing.default = "direct"`).
Whitelist,
/// Everything proxied: only the proxy and block lists are kept.
AllProxy,
/// Everything direct: only the block lists and private addresses are kept.
AllBypass,
}
impl RouteMode {
pub fn as_str(self) -> &'static str {
match self {
Self::Blacklist => "blacklist",
Self::Whitelist => "whitelist",
Self::AllProxy => "all-proxy",
Self::AllBypass => "all-bypass",
}
}
}
/// What the service keeps between starts and changes without touching the configuration:
/// upstream's state files.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase", default)]
pub struct State {
/// `proxy-ctl proxy pin`: the outbound or group "proxy" stands for.
pub pin: Option<String>,
/// `proxy-ctl proxy pin <tag> --in <group>`.
pub group_pins: BTreeMap<String, String>,
/// `proxy-ctl proxy outbounds disable`: kept out of selection and autoProxy, still usable
/// by name. Subscription entries too, which the configuration does not list.
pub disabled: Vec<String>,
pub route_mode: Option<RouteMode>,
}
/// A rule set file the service has downloaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RuleSetFile {
pub path: String,
pub format: RuleSetFormat,
}
/// What the service provides beyond the configuration: files it fetched or generated, and
/// where things live on this host.
#[derive(Debug, Clone, Default)]
pub struct Env {
/// Downloaded rule sets by tag (`geosite-google`, `geoip-ru`, `ruleset-<name>`,
/// `ruleset-<name>-dns`).
pub rule_sets: BTreeMap<String, RuleSetFile>,
/// An empty source rule set, for one not downloaded yet: it matches nothing until it is.
pub empty_rule_set: String,
/// Where sing-box keeps its fake IP cache.
pub cache_dir: String,
/// The Clash API's secret: the API is on loopback, where any local program could reach it.
pub clash_secret: Option<String>,
/// The login of the loopback SOCKS hops the service runs (wireproxy, joiners), so other
/// local users cannot use them to get past the routing.
pub hop_login: Option<(String, String)>,
/// WARP profiles by device tag: given in the configuration or registered.
pub warp_profiles: BTreeMap<String, String>,
/// AmneziaWG `.conf` text of the "singBox" outbounds, by profile name.
pub awg_profiles: BTreeMap<String, String>,
/// Full paths of the helper programs whose own connections must go direct under TUN
/// (Tor, the XRay sidecar, wireproxy, …), as Linux upstream does with socket marks.
pub direct_processes: Vec<String>,
/// zapret's domains and addresses for `zapret.directSync`, read from its lists.
pub zapret_direct: RouteMatch,
/// Whether the service drives failover through the Clash API. Without it, failover is
/// sing-box's own urltest.
pub groups_watched: bool,
/// The SSH outbound's key and the server's host keys, read by the service.
pub ssh_identity_path: Option<String>,
pub ssh_host_keys: Vec<String>,
/// A UUID drawn per start: the hybrid sidecar's client ids are made from it, so no other
/// local user can guess one.
pub sidecar_secret: String,
/// Running on Windows: the TUN takes Windows' fields only.
pub windows: bool,
}
pub struct Input<'a> {
pub cfg: &'a Config,
pub state: &'a State,
/// Each subscription's cached links, by tag, as fetched last.
pub subscriptions: &'a BTreeMap<String, Vec<String>>,
pub env: &'a Env,
/// Reads a file an option names (`urlFile`, `passwordFile`, …).
pub read_file: &'a dyn Fn(&str) -> Result<String, String>,
/// Render for the global TUN as well as the local proxy.
pub tun: bool,
}
/// What the backends run, and what proxy-ctl and the app show about it.
#[derive(Debug, Clone, PartialEq)]
pub struct Rendered {
/// sing-box's config (the "sing-box" and "hybrid" backends).
pub sing_box: Option<Value>,
/// XRay's: the whole proxy on the "xray" backend, the sidecar on "hybrid".
pub xray: Option<Value>,
pub inventory: Inventory,
pub warnings: Vec<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderError(pub String);
impl fmt::Display for RenderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for RenderError {}
/// The proxy's backend configs.
pub fn render(input: &Input) -> Result<Rendered, RenderError> {
let mut warnings = Vec::new();
let assembly = outbounds::assemble(input, &mut warnings)?;
match input.cfg.proxy.backend {
crate::config::Backend::SingBox | crate::config::Backend::Hybrid => {
let (config, sidecar) = sing_box::config(input, &assembly, &mut warnings)?;
Ok(Rendered { sing_box: Some(config), xray: sidecar, inventory: assembly.inventory, warnings })
}
crate::config::Backend::Xray => Err(RenderError(
"the \"xray\" backend is not rendered yet on Windows; use \"sing-box\" or \"hybrid\"".into(),
)),
}
}
pub(crate) type Sources = HashMap<String, String>;
@@ -0,0 +1,566 @@
//! Every outbound a start has, chained, grouped, and behind the "proxy" selector: upstream's
//! `service/script-blocks/outbounds.nix`.
//!
//! Upstream fails the start over a declared outbound it cannot build and skips a runtime one
//! with a warning. Here everything is edited at runtime, so an outbound that cannot be built
//! is left out with a warning, and what names it (a chain, a rule) is left out after it. Only
//! having no outbound at all, or nothing selection may pick, stops the start.
use std::collections::{BTreeMap, HashMap, HashSet};
use serde::Serialize;
use serde_json::{Value, json};
use super::groups::{self, GroupInfo};
use super::{Input, RenderError, Sources};
use crate::config::{Backend, OutboundBackend, Selection};
use crate::derived::{self, ExtraKind};
use crate::links::{self, LinkBackend, subscription};
/// What proxy-ctl and the app read about the outbounds: upstream's `outbounds.json`.
#[derive(Debug, Clone, Default, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Inventory {
/// Every outbound tag, in build order.
pub tags: Vec<String>,
/// tag -> where it came from: "static", "sub:<tag>", "ssh", "warp", "tor", "awg",
/// "whitelist-bypass".
pub sources: BTreeMap<String, String>,
pub pinned: String,
pub selection: String,
/// tag -> the outbound it chains through.
pub detours: BTreeMap<String, String>,
/// Top-level tags selection leaves alone (`selectionExclude`, Tor).
pub excluded: Vec<String>,
pub disabled: Vec<String>,
pub groups: BTreeMap<String, GroupInfo>,
pub top: Vec<String>,
pub priority: BTreeMap<String, i64>,
pub url: String,
/// The outbounds that are real exits (no selector or urltest), for autoProxy and tests.
pub exits: Vec<String>,
/// tag -> the link it came from, to share it back.
pub links: BTreeMap<String, String>,
/// tag -> the backend that runs it, on hybrid.
pub runs_on: BTreeMap<String, String>,
}
/// The outbounds, before the backend template takes them.
pub(super) struct Assembly {
/// sing-box outbounds (on hybrid, the sidecar's appear here as hops to it), "proxy" first.
pub outbounds: Vec<Value>,
/// sing-box endpoints (WireGuard).
pub endpoints: Vec<Value>,
/// The hybrid sidecar's XRay outbounds.
pub xray: Vec<Value>,
pub inventory: Inventory,
}
struct Builder<'a> {
input: &'a Input<'a>,
backend: Backend,
outbounds: Vec<Value>,
endpoints: Vec<Value>,
xray: Vec<Value>,
sources: Sources,
order: Vec<String>,
links: BTreeMap<String, String>,
runs_on: BTreeMap<String, String>,
}
impl Builder<'_> {
fn taken(&self, tag: &str) -> bool {
self.sources.contains_key(tag) || derived::BUILTIN_TAGS.contains(&tag) || tag.starts_with("proxy-suite-")
}
fn record(&mut self, tag: &str, source: &str) {
self.sources.insert(tag.to_owned(), source.to_owned());
self.order.push(tag.to_owned());
}
fn push(&mut self, ob: Value, source: &str) {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
self.outbounds.push(ob);
self.record(&tag, source);
}
fn push_endpoint(&mut self, ep: Value, source: &str) {
let tag = ep["tag"].as_str().unwrap_or_default().to_owned();
self.endpoints.push(ep);
self.record(&tag, source);
}
/// An XRay outbound on the hybrid backend's sidecar; sing-box reaches it as a hop.
fn push_sidecar(&mut self, ob: Value, source: &str) {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
self.xray.push(ob);
self.runs_on.insert(tag.clone(), "xray".into());
self.record(&tag, source);
}
/// A link as this backend's outbound. On hybrid, sing-box first unless the outbound
/// asks for XRay, XRay when sing-box cannot take it.
fn add_url(&mut self, tag: &str, url: &str, pref: OutboundBackend, source: &str) -> Result<(), String> {
match self.backend {
Backend::SingBox => {
let ob = links::build_outbound(url, tag, LinkBackend::SingBox).map_err(|e| e.to_string())?;
self.push(ob, source);
}
Backend::Xray => {
let ob = links::build_outbound(url, tag, LinkBackend::Xray).map_err(|e| e.to_string())?;
self.push(ob, source);
}
Backend::Hybrid => {
let sing = || links::build_outbound(url, tag, LinkBackend::SingBox);
let xray = || links::build_outbound(url, tag, LinkBackend::Xray);
match pref {
OutboundBackend::SingBox => self.push(sing().map_err(|e| e.to_string())?, source),
OutboundBackend::Xray => self.push_sidecar(xray().map_err(|e| e.to_string())?, source),
OutboundBackend::Auto => match sing() {
Ok(ob) => self.push(ob, source),
Err(sing_err) => match xray() {
Ok(ob) => self.push_sidecar(ob, source),
Err(xray_err) => {
return Err(format!(
"cannot be parsed by sing-box ({sing_err}) or XRay ({xray_err})"
));
}
},
},
}
}
}
self.links.insert(tag.to_owned(), url.to_owned());
Ok(())
}
/// A loopback SOCKS hop to a helper the service runs.
fn hop(&self, tag: &str, port: u16, login: bool) -> Value {
let mut ob = json!({ "type": "socks", "tag": tag, "server": "127.0.0.1", "server_port": port });
if let (true, Some((user, pass))) = (login, &self.input.env.hop_login) {
ob["username"] = user.clone().into();
ob["password"] = pass.clone().into();
}
ob
}
}
pub(super) fn assemble(input: &Input, warnings: &mut Vec<String>) -> Result<Assembly, RenderError> {
let cfg = input.cfg;
let p = &cfg.proxy;
let mut b = Builder {
input,
backend: p.backend,
outbounds: Vec::new(),
endpoints: Vec::new(),
xray: Vec::new(),
sources: HashMap::new(),
order: Vec::new(),
links: BTreeMap::new(),
runs_on: BTreeMap::new(),
};
// Declared outbounds.
for ob in &p.outbounds {
if b.taken(&ob.tag) {
warnings.push(format!("outbound '{}': the tag is taken; leaving it out", ob.tag));
continue;
}
let result = if let Some(json) = &ob.sing_box_json {
let mut j = json.clone();
j.insert("tag".into(), ob.tag.clone().into());
match p.backend {
Backend::Xray => Err("sing-box JSON cannot run on the xray backend".to_owned()),
_ => {
b.push(Value::Object(j), "static");
Ok(())
}
}
} else if let Some(json) = &ob.xray_json {
let mut j = json.clone();
j.insert("tag".into(), ob.tag.clone().into());
match p.backend {
Backend::SingBox => Err("XRay JSON cannot run on the sing-box backend".to_owned()),
Backend::Xray => {
b.push(Value::Object(j), "static");
Ok(())
}
Backend::Hybrid => {
b.push_sidecar(Value::Object(j), "static");
Ok(())
}
}
} else {
let url = match (&ob.url, &ob.url_file) {
(Some(url), _) => Ok(url.trim().to_owned()),
(None, Some(file)) => (input.read_file)(file).map(|s| s.trim().to_owned()),
(None, None) => Err("it has no url, urlFile, singBoxJson or xrayJson".to_owned()),
};
url.and_then(|url| b.add_url(&ob.tag, &url, ob.backend, "static"))
};
if let Err(e) = result {
warnings.push(format!("outbound '{}': {e}; leaving it out", ob.tag));
}
}
// Subscriptions, as last fetched.
let link_backends: Vec<LinkBackend> = match p.backend {
Backend::SingBox => vec![LinkBackend::SingBox],
Backend::Xray => vec![LinkBackend::Xray],
Backend::Hybrid => vec![LinkBackend::SingBox, LinkBackend::Xray],
};
for sub in &p.subscriptions {
let Some(lines) = input.subscriptions.get(&sub.tag) else {
warnings.push(format!("subscription '{}' has not been fetched yet", sub.tag));
continue;
};
let opts = subscription::Options { allow_private: sub.allow_private_servers, allow_insecure: sub.allow_insecure };
let parsed = subscription::walk(lines, &sub.tag, &link_backends, opts);
warnings.extend(parsed.warnings.into_iter().map(|w| format!("subscription '{}': {w}", sub.tag)));
let source = format!("sub:{}", sub.tag);
let links: HashMap<String, String> = parsed.links.into_iter().collect();
for (backend, ob) in parsed.outbounds {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
if b.taken(&tag) {
warnings.push(format!("subscription '{}': entry '{tag}' takes a tag already in use; leaving it out", sub.tag));
continue;
}
match (p.backend, backend) {
(Backend::Hybrid, LinkBackend::Xray) => b.push_sidecar(ob, &source),
_ => b.push(ob, &source),
}
if let Some(line) = links.get(&tag) {
b.links.insert(tag, line.clone());
}
}
}
// What the tunnels add.
let sing_box = p.backend.runs_sing_box();
for extra in derived::extra_outbounds(cfg) {
if b.taken(&extra.tag) {
warnings.push(format!("'{}': the tag is taken by an outbound; leaving the tunnel's outbound out", extra.tag));
continue;
}
match extra.kind {
ExtraKind::Ssh => {
let s = &cfg.ssh_proxy;
if sing_box {
let mut ob = json!({
"type": "ssh",
"tag": extra.tag,
"server": s.server.host.clone().unwrap_or_default(),
"server_port": s.server.port,
"user": s.server.user.clone().unwrap_or_default(),
});
let keys = if input.env.ssh_host_keys.is_empty() { &s.host_key } else { &input.env.ssh_host_keys };
if !keys.is_empty() {
ob["host_key"] = json!(keys);
}
if let Some(path) = &input.env.ssh_identity_path {
ob["private_key_path"] = path.clone().into();
}
b.push(ob, "ssh");
} else {
let ob = b.hop(&extra.tag, s.listener.port, false);
b.push(ob, "ssh");
}
}
ExtraKind::Tor { port } => {
let ob = b.hop(&extra.tag, port, false);
b.push(ob, "tor");
}
ExtraKind::WlJoiner { port, .. } => {
let ob = b.hop(&extra.tag, port, true);
b.push(ob, "whitelist-bypass");
}
ExtraKind::Warp { device } => match device.kind {
crate::config::WarpOutboundKind::SingBox => {
let Some(profile) = input.env.warp_profiles.get(&device.tag) else {
warnings.push(format!("WARP device '{}' is not registered yet; it joins once it is", device.tag));
continue;
};
match crate::wg::sing_box_endpoint(profile, &device.tag, device.endpoint.as_deref()) {
Ok((mut ep, _)) => {
ep["domain_resolver"] =
json!({ "server": "local", "strategy": cfg.warp.domain_strategy.as_str() });
b.push_endpoint(ep, "warp");
}
Err(e) => warnings.push(format!("WARP device '{}': {e}; leaving it out", device.tag)),
}
}
crate::config::WarpOutboundKind::Userspace => {
let ob = b.hop(&device.tag, device.port, true);
b.push(ob, "warp");
}
},
ExtraKind::Awg { profile, kind, port } => match kind {
crate::config::AwgOutboundKind::SingBox => {
let Some(conf) = input.env.awg_profiles.get(&profile) else {
warnings.push(format!("AmneziaWG outbound '{profile}': its config could not be read; leaving it out"));
continue;
};
let endpoint = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.endpoint.as_deref());
match crate::wg::sing_box_endpoint(conf, &profile, endpoint) {
Ok((mut ep, dropped)) => {
if !dropped.is_empty() {
warnings.push(format!(
"AmneziaWG outbound '{profile}': sing-box speaks plain WireGuard; dropping {}. A server that expects them will not answer",
dropped.join(", ")
));
}
let strategy = cfg.amnezia_wg.profiles.get(&profile).and_then(|p| p.domain_strategy);
ep["domain_resolver"] = match strategy {
Some(s) => json!({ "server": "local", "strategy": s.as_str() }),
None => json!("local"),
};
b.push_endpoint(ep, "awg");
}
Err(e) => warnings.push(format!("AmneziaWG outbound '{profile}': {e}; leaving it out")),
}
}
crate::config::AwgOutboundKind::Userspace => {
let ob = b.hop(&profile, port, true);
b.push(ob, "awg");
}
},
}
}
chain(&mut b, warnings);
if b.order.is_empty() {
return Err(RenderError(
"no proxy outbounds are available; add one, or a subscription that has been fetched".into(),
));
}
let disabled: Vec<String> =
input.state.disabled.iter().filter(|t| b.sources.contains_key(*t)).cloned().collect();
// Groups, against the outbounds this start has. A group whose name an outbound took, or
// that contains itself, is left out.
let mut group_cfg = p.groups.clone();
if let Some(warp) = warp_group(cfg) {
group_cfg.entry(derived::WARP_TAG.into()).or_insert(warp);
}
group_cfg.retain(|name, _| {
let free = !b.sources.contains_key(name);
if !free {
warnings.push(format!("group '{name}': an outbound has that tag; leaving the group out"));
}
free
});
let resolved = loop {
let r = groups::resolve(&groups::Inputs {
tags: &b.order,
sources: &b.sources,
groups: &group_cfg,
priority: &p.priority,
disabled: &disabled,
pins: &input.state.group_pins,
url: &p.url_test.url,
interval: &p.url_test.interval,
tolerance: p.url_test.tolerance,
watched: input.env.groups_watched,
});
if r.loops.is_empty() {
break r;
}
for g in &r.loops {
warnings.push(format!("group '{g}' contains itself; leaving it out"));
group_cfg.remove(g);
}
};
warnings.extend(resolved.warnings.iter().cloned());
// The pin.
let all_tags: Vec<&String> = b.order.iter().chain(resolved.groups.keys()).collect();
let mut pinned = input.state.pin.clone().unwrap_or_default();
if !pinned.is_empty() && !all_tags.contains(&&pinned) {
warnings.push(format!("pinned outbound '{pinned}' is not available; picking automatically"));
pinned.clear();
}
if !pinned.is_empty() && disabled.contains(&pinned) {
warnings.push(format!("pinned outbound '{pinned}' is disabled; picking automatically"));
pinned.clear();
}
// What selection may pick on its own. Tor is only for what is routed to it, unless it is
// the one outbound there is.
let tor_out = derived::extra_outbounds(cfg).iter().any(|o| o.tag == derived::TOR_OUTBOUND_TAG);
let top = &resolved.top;
let selectable: Vec<String> = top
.iter()
.filter(|t| {
!p.selection_exclude.contains(t)
&& !disabled.contains(t)
&& !(tor_out && top.len() > 1 && *t == derived::TOR_OUTBOUND_TAG)
})
.cloned()
.collect();
if pinned.is_empty() && selectable.is_empty() {
return Err(RenderError(
"every outbound is in proxy.selectionExclude or disabled, so there is nothing to select; pin one, enable one, or exclude fewer".into(),
));
}
// The detours as they stand, for the inventory.
let detours: BTreeMap<String, String> = b
.outbounds
.iter()
.chain(&b.endpoints)
.chain(&b.xray)
.filter_map(|o| {
let hop = o.get("detour").or_else(|| o.pointer("/streamSettings/sockopt/dialerProxy"))?;
Some((o["tag"].as_str()?.to_owned(), hop.as_str()?.to_owned()))
})
.collect();
let exits: Vec<String> = b
.order
.iter()
.filter(|t| !(tor_out && *t == derived::TOR_OUTBOUND_TAG))
.cloned()
.collect();
// "proxy", as the selection mode has it, ahead of everything; the groups after the rest.
let mut every: Vec<String> = b.order.clone();
every.extend(resolved.groups.keys().cloned());
let default = if pinned.is_empty() { selectable[0].clone() } else { pinned.clone() };
let wrapper = match p.selection {
Selection::First => json!({ "type": "selector", "tag": "proxy", "outbounds": [default], "default": default }),
Selection::Failover if pinned.is_empty() && !input.env.groups_watched => json!({
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
"interval": "30s", "tolerance": p.url_test.tolerance,
}),
Selection::Failover => json!({
"type": "selector", "tag": "proxy", "outbounds": every, "default": default,
"interrupt_exist_connections": true,
}),
Selection::Selector => json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": default }),
Selection::Urltest if !pinned.is_empty() => {
json!({ "type": "selector", "tag": "proxy", "outbounds": every, "default": pinned })
}
Selection::Urltest => json!({
"type": "urltest", "tag": "proxy", "outbounds": selectable, "url": p.url_test.url,
"interval": p.url_test.interval, "tolerance": p.url_test.tolerance,
}),
};
let mut outbounds = vec![wrapper];
outbounds.append(&mut b.outbounds);
outbounds.extend(resolved.outbounds.iter().cloned());
let excluded: Vec<String> = top.iter().filter(|t| !selectable.contains(t)).cloned().collect();
let inventory = Inventory {
tags: b.order.clone(),
sources: b.sources.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
pinned,
selection: p.selection.as_str().into(),
detours,
excluded,
disabled,
groups: resolved.groups.clone(),
top: top.clone(),
priority: p.priority.clone(),
url: p.url_test.url.clone(),
exits,
links: b.links,
runs_on: b
.order
.iter()
.map(|t| (t.clone(), b.runs_on.get(t).cloned().unwrap_or_else(|| p.backend.as_str().to_owned())))
.collect(),
};
Ok(Assembly { outbounds, endpoints: b.endpoints, xray: b.xray, inventory })
}
/// With two or more WARP devices, "warp" names a group of them.
fn warp_group(cfg: &crate::config::Config) -> Option<crate::config::Group> {
let devices = derived::warp_devices(cfg);
(devices.len() > 1).then(|| crate::config::Group {
outbounds: devices.into_iter().map(|d| d.tag).collect(),
strategy: cfg.warp.group.strategy,
failback: cfg.warp.group.failback,
..Default::default()
})
}
/// Chains outbounds through their detour hop: upstream's `outbound-detours.jq`. An outbound
/// whose chain cannot be built is left out, and what chained through it is checked again.
fn chain(b: &mut Builder, warnings: &mut Vec<String>) {
let p = &b.input.cfg.proxy;
let declared: HashMap<&str, &str> =
p.outbounds.iter().filter_map(|o| Some((o.tag.as_str(), o.detour.as_deref()?))).collect();
let by_sub: HashMap<String, &str> =
p.subscriptions.iter().filter_map(|s| Some((format!("sub:{}", s.tag), s.detour.as_deref()?))).collect();
loop {
let hops: BTreeMap<String, String> = b
.order
.iter()
.filter_map(|t| {
let hop = declared.get(t.as_str()).copied().or_else(|| by_sub.get(&b.sources[t]).copied())?;
Some((t.clone(), hop.to_owned()))
})
.collect();
let tags: HashSet<&String> = b.order.iter().collect();
let xray_tags: HashSet<String> = b.xray.iter().filter_map(|o| o["tag"].as_str().map(str::to_owned)).collect();
let mut drop: BTreeMap<String, String> = BTreeMap::new();
for (t, hop) in &hops {
if !tags.contains(hop) {
drop.insert(t.clone(), format!("it chains through '{hop}', which is not an outbound"));
continue;
}
// Upstream's test: the chain from t, as long as there are hops plus one, meets t again.
let mut cur = hop.clone();
let mut back = false;
for _ in 0..=hops.len() {
if cur == *t {
back = true;
break;
}
match hops.get(&cur) {
Some(next) => cur = next.clone(),
None => break,
}
}
if back {
drop.insert(t.clone(), "it chains back to itself".into());
continue;
}
if b.backend == Backend::Hybrid && xray_tags.contains(t) && !xray_tags.contains(hop) {
drop.insert(
t.clone(),
format!("it runs on XRay and can only chain through another XRay outbound, not '{hop}'"),
);
}
}
if drop.is_empty() {
for (t, hop) in &hops {
let set = |ob: &mut Value| {
if ob["tag"] == t.as_str() {
if xray_tags.contains(t) || b.backend == Backend::Xray {
ob["streamSettings"]["sockopt"]["dialerProxy"] = hop.clone().into();
} else {
ob["detour"] = hop.clone().into();
}
}
};
b.outbounds.iter_mut().for_each(set);
b.endpoints.iter_mut().for_each(set);
b.xray.iter_mut().for_each(set);
}
return;
}
for (t, why) in drop {
warnings.push(format!("outbound '{t}': {why}; leaving it out"));
let keep = |o: &Value| o["tag"] != t.as_str();
b.outbounds.retain(keep);
b.endpoints.retain(keep);
b.xray.retain(keep);
b.order.retain(|x| *x != t);
b.sources.remove(&t);
b.links.remove(&t);
}
}
}
@@ -0,0 +1,417 @@
//! sing-box's route and DNS rules: upstream's `rules/sing-box.nix`, composed by section
//! and priority as `routing-compose.jq` does, with the route mode applied.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use super::{Input, RouteMode};
use crate::config::{Config, RouteDefault, RouteMatch, RuleSetFormat};
use crate::derived;
/// Loopback, as a client of the local proxy could ask for it.
pub(super) const LOOPBACK: [&str; 4] = ["127.0.0.0/8", "::1/128", "0.0.0.0/32", "::/128"];
/// A rule set the service should keep downloaded.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WantedRuleSet {
/// The tag the config names it by.
pub tag: String,
pub url: String,
pub format: RuleSetFormat,
/// For a `ruleset-<name>-dns` copy: the rule set whose domain rules it holds. Its URL
/// is the original's.
pub dns_copy_of: Option<String>,
/// Fetch through the proxy rather than directly.
pub via_proxy: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Category {
Proxy,
Direct,
Block,
/// Private addresses and the Telegram relay's: direct, but kept in every mode.
Safety,
}
fn category(target: &str) -> Category {
match target {
"direct" => Category::Direct,
"block" => Category::Block,
_ => Category::Proxy,
}
}
struct Section {
priority: i64,
category: Category,
rules: Vec<Value>,
dns: Vec<Value>,
}
fn geosite(name: &str) -> String {
format!("geosite-{name}")
}
fn geoip(name: &str) -> String {
format!("geoip-{name}")
}
fn remote(name: &str) -> String {
format!("ruleset-{name}")
}
fn remote_dns(name: &str) -> String {
format!("ruleset-{name}-dns")
}
/// A rule sending what it matches to `outbound` ("block" is the block outbound, which groups
/// with nothing to pick fall back to as well).
fn target(rule: Value, outbound: &str) -> Value {
let mut rule = rule;
rule["outbound"] = outbound.into();
rule
}
/// One rule per kind of match, as upstream's `mkCustomRuleEntries`: a rule matches any of
/// them, not all.
fn match_rules(outbound: &str, m: &RouteMatch) -> Vec<Value> {
let mut rules = Vec::new();
if !m.domains.is_empty() {
rules.push(target(json!({ "domain_suffix": m.domains }), outbound));
}
if !m.ips.is_empty() {
rules.push(target(json!({ "ip_cidr": m.ips }), outbound));
}
if !m.geosites.is_empty() {
rules.push(target(json!({ "rule_set": m.geosites.iter().map(|s| geosite(s)).collect::<Vec<_>>() }), outbound));
}
if !m.geoips.is_empty() {
rules.push(target(json!({ "rule_set": m.geoips.iter().map(|s| geoip(s)).collect::<Vec<_>>() }), outbound));
}
if !m.rule_sets.is_empty() {
rules.push(target(json!({ "rule_set": m.rule_sets.iter().map(|s| remote(s)).collect::<Vec<_>>() }), outbound));
}
rules
}
/// The DNS mirror of a match: a name that goes through the proxy is looked up through it.
fn dns_rules(server: &str, domains: &[String], geosites: &[String], rule_sets: &[String]) -> Vec<Value> {
let mut rules = Vec::new();
if !domains.is_empty() {
rules.push(json!({ "domain_suffix": domains, "server": server }));
}
let tags: Vec<String> = geosites.iter().map(|s| geosite(s)).chain(rule_sets.iter().map(|s| remote_dns(s))).collect();
if !tags.is_empty() {
rules.push(json!({ "rule_set": tags, "server": server }));
}
rules
}
fn dns_server_for(c: Category) -> &'static str {
if c == Category::Direct { "local" } else { "remote" }
}
/// The direct lists: the configuration's, zapret's (`zapret.directSync`) and the Russian
/// ones (`routing.directRu`).
pub(super) fn direct_match(input: &Input) -> RouteMatch {
let r = &input.cfg.proxy.routing;
let z = &input.env.zapret_direct;
let uniq = |a: &[String], b: &[String], extra: Option<&str>| {
let mut out: Vec<String> = Vec::new();
for v in a.iter().chain(b).map(String::as_str).chain(extra) {
if !out.iter().any(|x| x == v) {
out.push(v.to_owned());
}
}
out
};
let ru = r.direct_ru;
RouteMatch {
domains: uniq(&r.direct.domains, &z.domains, None),
ips: uniq(&r.direct.ips, &z.ips, None),
geosites: uniq(&r.direct.geosites, &[], ru.then_some("category-ru")),
geoips: uniq(&r.direct.geoips, &[], ru.then_some("ru")),
rule_sets: r.direct.rule_sets.clone(),
}
}
/// The rules that pick an outbound by program, and the loopback hops' guard: kept in every
/// route mode, ahead of everything that picks by destination, as upstream's pin rules are.
fn always_rules(input: &Input, known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Vec<Value> {
let cfg = input.cfg;
let mut rules = Vec::new();
if !input.env.direct_processes.is_empty() {
rules.push(json!({ "process_path": input.env.direct_processes, "outbound": "direct" }));
}
if cfg.per_app_routing.enable {
for prof in &cfg.per_app_routing.profiles {
// An app held to an outbound that is not running is blocked, not let out another way.
let outbound = if derived::BUILTIN_TAGS.contains(&prof.outbound.as_str()) || known(&prof.outbound) {
prof.outbound.as_str()
} else {
warnings.push(format!(
"per-app profile '{}': no outbound or group named '{}' is running; its programs are blocked until it is",
prof.name, prof.outbound
));
"block"
};
let inbound = per_app_inbound(&prof.name);
rules.push(target(json!({ "inbound": [inbound] }), outbound));
if !prof.process_names.is_empty() {
rules.push(target(json!({ "process_name": prof.process_names }), outbound));
}
if !prof.process_paths.is_empty() {
rules.push(target(json!({ "process_path": prof.process_paths }), outbound));
}
}
}
rules
}
pub(super) fn per_app_inbound(name: &str) -> String {
format!("per-app-{name}")
}
/// Every route and DNS rule, in order, and the final outbound and resolver.
pub(super) struct Route {
pub rules: Vec<Value>,
pub dns_rules: Vec<Value>,
pub final_outbound: &'static str,
pub dns_final: &'static str,
pub rule_set: Vec<Value>,
}
pub(super) fn route(input: &Input, hop_ports: &[u16], known: &dyn Fn(&str) -> bool, warnings: &mut Vec<String>) -> Route {
let cfg = input.cfg;
let r = &cfg.proxy.routing;
let direct = direct_match(input);
let mut common = vec![
json!({ "network": ["tcp", "udp"], "port": 53, "action": "hijack-dns" }),
json!({ "action": "sniff" }),
];
let onion = derived::tor_route_onion(cfg) && known(derived::TOR_OUTBOUND_TAG);
if onion {
common.push(json!({ "domain_suffix": ["onion"], "outbound": derived::TOR_OUTBOUND_TAG }));
}
// Nothing reaches this host's loopback through the proxy: the helpers' listeners, the
// Clash API and whatever else listens there would be a client's for the asking, a LAN
// client's too when the listener is exposed. Upstream guards only the hops (its firewall
// keeps the rest from other users); Windows has no such firewall here, so every port. A
// name that resolves to loopback on its own is not caught: keep the listener on loopback.
let _ = hop_ports;
common.push(json!({ "ip_cidr": LOOPBACK, "action": "reject" }));
common.push(json!({ "domain": ["localhost"], "domain_suffix": [".localhost"], "action": "reject" }));
common.extend(always_rules(input, known, warnings));
// The custom rules: each outbound's own routing, then routing.rules, at their priority.
let mut sections = Vec::new();
for ob in &cfg.proxy.outbounds {
if ob.routing.is_empty() {
continue;
}
let outbound = if known(&ob.tag) {
ob.tag.as_str()
} else {
warnings.push(format!("outbound '{}' is not running: what its routing sends to it is blocked until it is", ob.tag));
"block"
};
sections.push(custom_section(100, outbound, &ob.routing, &[], &[]));
}
for (i, rule) in r.rules.iter().enumerate() {
if rule.disabled {
continue;
}
let name = rule.name.clone().unwrap_or_else(|| format!("#{i}"));
// As a group with nothing to pick does: what the rule matches must not fall through to
// another rule, or to direct.
let outbound = if derived::BUILTIN_TAGS.contains(&rule.outbound.as_str()) || known(&rule.outbound) {
rule.outbound.as_str()
} else {
warnings.push(format!(
"routing rule {name}: no outbound or group named '{}' is running; what it matches is blocked until it is",
rule.outbound
));
"block"
};
sections.push(custom_section(
rule.priority.unwrap_or(100),
outbound,
&rule.matches,
&rule.process_names,
&rule.process_paths,
));
}
let proxy_primary = RouteMatch { domains: r.proxy.domains.clone(), ips: r.proxy.ips.clone(), ..Default::default() };
let proxy_geo = RouteMatch {
geosites: r.proxy.geosites.clone(),
geoips: r.proxy.geoips.clone(),
rule_sets: r.proxy.rule_sets.clone(),
..Default::default()
};
sections.push(Section {
priority: 200,
category: Category::Proxy,
rules: match_rules("proxy", &proxy_primary),
dns: dns_rules("remote", &r.proxy.domains, &[], &[]),
});
// Block ahead of the direct lists (category-ru's ad domains are in category-ads-all too).
sections.push(Section { priority: 300, category: Category::Block, rules: match_rules("block", &r.block), dns: Vec::new() });
sections.push(Section {
priority: 400,
category: Category::Direct,
rules: match_rules("direct", &direct),
dns: dns_rules("local", &direct.domains, &direct.geosites, &r.direct.rule_sets),
});
let mut safety = vec![json!({ "ip_is_private": true, "outbound": "direct" })];
let tg = &cfg.tg_ws_proxy;
if tg.enable && tg.bypass_transparent_proxy && !tg.dc_ips.is_empty() {
let ips: BTreeSet<&String> = tg.dc_ips.values().collect();
safety.push(json!({ "ip_cidr": ips, "outbound": "direct" }));
}
sections.push(Section { priority: 400, category: Category::Safety, rules: safety, dns: Vec::new() });
sections.push(Section {
priority: 500,
category: Category::Proxy,
rules: match_rules("proxy", &proxy_geo),
dns: dns_rules("remote", &[], &r.proxy.geosites, &r.proxy.rule_sets),
});
// The mode: the configured default, or proxy-ctl's override.
let mode = input.state.route_mode.unwrap_or(match r.default {
RouteDefault::Proxy => RouteMode::Blacklist,
RouteDefault::Direct => RouteMode::Whitelist,
});
let (final_outbound, dns_final, clear_dns) = match mode {
RouteMode::Blacklist => ("proxy", "remote", false),
RouteMode::Whitelist => ("direct", "local", false),
RouteMode::AllProxy => ("proxy", "remote", true),
RouteMode::AllBypass => ("direct", "local", true),
};
let keep = |c: Category| match mode {
RouteMode::AllProxy => c != Category::Direct,
RouteMode::AllBypass => matches!(c, Category::Block | Category::Safety),
_ => true,
};
// A stable sort: among equals, the list's own order.
sections.sort_by_key(|s| s.priority);
let sections: Vec<Section> = sections.into_iter().filter(|s| keep(s.category)).collect();
let mut rules = common;
rules.extend(sections.iter().flat_map(|s| s.rules.iter().cloned()));
// DNS: the user's rules first (they stay in every mode), then .onion, which no resolver
// may see, then the mirror of the routing.
let mut dns_rules_out: Vec<Value> = cfg.proxy.dns.sing_box.rules.iter().map(|r| Value::Object(r.clone())).collect();
if derived::tor_route_onion(cfg) {
if input.tun && onion {
dns_rules_out.push(json!({
"inbound": ["tun-in"], "domain_suffix": ["onion"], "query_type": ["A", "AAAA"], "server": "fakeip",
}));
}
dns_rules_out.push(json!({ "domain_suffix": ["onion"], "action": "predefined", "rcode": "NXDOMAIN" }));
}
if !clear_dns {
dns_rules_out.extend(sections.iter().flat_map(|s| s.dns.iter().cloned()));
}
if input.tun && cfg.proxy.dns.fake_ip.enable {
dns_rules_out.push(json!({ "inbound": ["tun-in"], "query_type": ["A", "AAAA"], "server": "fakeip" }));
}
Route { rules, dns_rules: dns_rules_out, final_outbound, dns_final, rule_set: rule_set_defs(input, warnings) }
}
fn custom_section(priority: i64, outbound: &str, m: &RouteMatch, names: &[String], paths: &[String]) -> Section {
let c = category(outbound);
let mut rules = match_rules(outbound, m);
if !names.is_empty() {
rules.push(target(json!({ "process_name": names }), outbound));
}
if !paths.is_empty() {
rules.push(target(json!({ "process_path": paths }), outbound));
}
let dns = if c == Category::Block { Vec::new() } else { dns_rules(dns_server_for(c), &m.domains, &m.geosites, &m.rule_sets) };
Section { priority, category: c, rules, dns }
}
/// Every geosite, geoip and declared rule set the routing names.
fn referenced(cfg: &Config) -> (BTreeSet<String>, BTreeSet<String>) {
let r = &cfg.proxy.routing;
let mut sites = BTreeSet::new();
let mut ips = BTreeSet::new();
let mut add = |m: &RouteMatch| {
sites.extend(m.geosites.iter().cloned());
ips.extend(m.geoips.iter().cloned());
};
add(&r.proxy);
add(&r.direct);
add(&r.block);
r.rules.iter().filter(|x| !x.disabled).for_each(|x| add(&x.matches));
cfg.proxy.outbounds.iter().for_each(|o| add(&o.routing));
if r.direct_ru {
sites.insert("category-ru".into());
ips.insert("ru".into());
}
(sites, ips)
}
/// What the service should keep downloaded for this configuration.
pub fn wanted_rule_sets(cfg: &Config) -> Vec<WantedRuleSet> {
if !cfg.proxy.enable || !cfg.proxy.backend.runs_sing_box() {
return Vec::new();
}
let (sites, ips) = referenced(cfg);
let g = &cfg.geodata.sing_box;
let mut out: Vec<WantedRuleSet> = sites
.iter()
.map(|s| WantedRuleSet {
tag: geosite(s),
url: format!("{}/{}.srs", g.geosite.trim_end_matches('/'), geosite(s)),
format: RuleSetFormat::Binary,
dns_copy_of: None,
via_proxy: false,
})
.chain(ips.iter().map(|s| WantedRuleSet {
tag: geoip(s),
url: format!("{}/{}.srs", g.geoip.trim_end_matches('/'), geoip(s)),
format: RuleSetFormat::Binary,
dns_copy_of: None,
via_proxy: false,
}))
.collect();
for (name, rs) in &cfg.proxy.routing.rule_sets {
let via_proxy = rs.detour == crate::config::RuleSetDetour::Proxy;
out.push(WantedRuleSet { tag: remote(name), url: rs.url.clone(), format: rs.effective_format(), dns_copy_of: None, via_proxy });
out.push(WantedRuleSet {
tag: remote_dns(name),
url: rs.url.clone(),
format: RuleSetFormat::Source,
dns_copy_of: Some(remote(name)),
via_proxy,
});
}
out
}
fn rule_set_defs(input: &Input, warnings: &mut Vec<String>) -> Vec<Value> {
wanted_rule_sets(input.cfg)
.into_iter()
.map(|w| match input.env.rule_sets.get(&w.tag) {
Some(file) => json!({
"tag": w.tag,
"type": "local",
"format": if file.format == RuleSetFormat::Binary { "binary" } else { "source" },
"path": file.path,
}),
None => {
if w.dns_copy_of.is_none() {
warnings.push(format!("rule set '{}' is not downloaded yet; it matches nothing until it is", w.tag));
}
json!({ "tag": w.tag, "type": "local", "format": "source", "path": input.env.empty_rule_set })
}
})
.collect()
}
@@ -0,0 +1,266 @@
//! sing-box's whole config, and the hybrid backend's XRay sidecar: upstream's
//! `config-templates/sing-box.nix` with what its start script fills in.
use serde_json::{Map, Value, json};
use super::outbounds::Assembly;
use super::routing::{self, per_app_inbound};
use super::{Input, RenderError};
use crate::config::{Backend, DnsUpstream};
use crate::derived::{self, ExtraKind, ports};
/// The global TUN's IPv6 address, as upstream numbers it.
pub const TUN_IPV6_ADDRESS: &str = "fd66:19::1/64";
/// Where the hybrid sidecar asks sing-box for names.
pub const XRAY_DNS_BRIDGE_PORT: u16 = 18533;
fn dns_server(tag: &str, upstream: &DnsUpstream, detour: Option<&str>) -> Value {
let mut s = json!({
"type": upstream.transport.as_str(),
"tag": tag,
"server": upstream.address,
"server_port": upstream.port,
});
if let Some(d) = detour {
s["detour"] = d.into();
}
s
}
/// The loopback listeners of the helpers sing-box dials: no client of the local proxy may
/// ask sing-box to dial them for it.
fn hop_ports(input: &Input) -> Vec<u16> {
let cfg = input.cfg;
let mut out = Vec::new();
for extra in derived::extra_outbounds(cfg) {
match extra.kind {
ExtraKind::Tor { port } | ExtraKind::WlJoiner { port, .. } => out.push(port),
ExtraKind::Awg { port, kind: crate::config::AwgOutboundKind::Userspace, .. } => out.push(port),
ExtraKind::Warp { device } if device.kind == crate::config::WarpOutboundKind::Userspace => {
out.push(device.port)
}
ExtraKind::Ssh if !cfg.proxy.backend.runs_sing_box() => out.push(cfg.ssh_proxy.listener.port),
_ => {}
}
}
if cfg.proxy.backend == Backend::Hybrid {
out.push(ports::XRAY_SIDECAR_SOCKS);
}
out.sort_unstable();
out.dedup();
out
}
fn listener_users(input: &Input) -> Result<Option<Value>, RenderError> {
let auth = &input.cfg.proxy.listener.auth;
let Some(user) = &auth.username else { return Ok(None) };
let password = match (&auth.password, &auth.password_file) {
(Some(p), _) => p.clone(),
(None, Some(file)) => (input.read_file)(file)
.map(|p| p.trim().to_owned())
.map_err(|e| RenderError(format!("proxy.listener.auth.passwordFile: {e}")))?,
(None, None) => return Err(RenderError("proxy.listener.auth has a username without a password".into())),
};
Ok(Some(json!([{ "username": user, "password": password }])))
}
pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec<String>) -> Result<(Value, Option<Value>), RenderError> {
let cfg = input.cfg;
let p = &cfg.proxy;
let env = input.env;
let hybrid = p.backend == Backend::Hybrid && !asm.xray.is_empty();
// Outbounds: "proxy" and the rest, the sidecar's as hops to it, then direct and block.
let sidecar = hybrid.then(|| sidecar(input, asm));
let mut outbounds = asm.outbounds.clone();
if let Some((_, hops)) = &sidecar {
outbounds.splice(1..1, hops.iter().cloned());
}
outbounds.push(json!({ "type": "direct", "tag": "direct" }));
outbounds.push(json!({ "type": "block", "tag": "block" }));
let known_tags: std::collections::HashSet<String> = asm
.inventory
.tags
.iter()
.chain(asm.inventory.groups.keys())
.cloned()
.collect();
let known = |t: &str| known_tags.contains(t);
let route = routing::route(input, &hop_ports(input), &known, warnings);
// Inbounds.
let mut inbounds = Vec::new();
if hybrid {
inbounds.push(json!({ "type": "direct", "tag": "xray-dns-in", "listen": "127.0.0.1", "listen_port": XRAY_DNS_BRIDGE_PORT }));
}
let mut mixed = json!({
"type": "mixed", "tag": "mixed-in", "listen": p.listener.address, "listen_port": p.listener.port,
});
let users = listener_users(input)?;
if let Some(users) = &users {
mixed["users"] = users.clone();
}
inbounds.push(mixed);
// The test listener `proxy-ctl proxy outbounds test` dials each outbound through, by the
// Clash API's switching of its selector.
let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": p.sing_box.test_port });
if let Some(users) = &users {
test_in["users"] = users.clone();
}
inbounds.push(test_in);
if cfg.per_app_routing.enable {
for (i, prof) in cfg.per_app_routing.profiles.iter().enumerate() {
let mut l = json!({
"type": "mixed", "tag": per_app_inbound(&prof.name), "listen": "127.0.0.1",
"listen_port": cfg.per_app_routing.listener_base_port.saturating_add(i as u16),
});
if let Some(users) = &users {
l["users"] = users.clone();
}
inbounds.push(l);
}
}
if input.tun {
let t = &p.tun;
let mut address = vec![Value::from(t.address.clone())];
if p.ipv6 {
address.push(TUN_IPV6_ADDRESS.into());
}
let mut tun = json!({
"type": "tun", "tag": "tun-in", "interface_name": t.interface, "address": address, "mtu": t.mtu,
"auto_route": true, "strict_route": true, "stack": "mixed",
});
if !env.windows {
tun["auto_redirect"] = true.into();
}
inbounds.push(tun);
}
// The test selector: every exit, block first so an unswitched test reaches nothing.
let mut test_members = vec![Value::from("block")];
test_members.extend(asm.inventory.exits.iter().map(|t| Value::from(t.clone())));
outbounds.push(json!({ "type": "selector", "tag": "proxy-suite-test", "outbounds": test_members, "default": "block" }));
let mut rules = route.rules;
let after_sniff = rules.iter().position(|r| r["action"] == "sniff").map_or(0, |i| i + 1);
rules.insert(after_sniff, json!({ "inbound": ["proxy-suite-test-in"], "outbound": "proxy-suite-test" }));
if hybrid {
rules.insert(0, json!({ "inbound": ["xray-dns-in"], "network": ["tcp", "udp"], "action": "hijack-dns" }));
}
// DNS.
let fake_ip = input.tun && p.dns.fake_ip.enable;
let onion_fake = input.tun && derived::tor_route_onion(cfg);
let mut servers = vec![dns_server("remote", &p.dns.remote, Some("proxy")), dns_server("local", &p.dns.local, None)];
if fake_ip || onion_fake {
servers.push(json!({ "type": "fakeip", "tag": "fakeip", "inet4_range": p.dns.fake_ip.inet4_range }));
}
servers.extend(p.dns.sing_box.servers.iter().map(|s| Value::Object(s.clone())));
let mut dns = json!({ "servers": servers, "rules": route.dns_rules, "final": route.dns_final });
if let Some(s) = p.dns.strategy {
dns["strategy"] = s.as_str().into();
}
if let Some(cs) = &p.dns.client_subnet {
dns["client_subnet"] = cs.clone().into();
}
let mut route_obj = json!({
"default_domain_resolver": "local",
"rule_set": route.rule_set,
"rules": rules,
"final": route.final_outbound,
});
if input.tun {
route_obj["auto_detect_interface"] = true.into();
}
// Any local program could switch selectors or read the connections otherwise.
let Some(secret) = env.clash_secret.as_ref().filter(|s| !s.is_empty()) else {
return Err(RenderError("the Clash API needs a secret".into()));
};
let clash = json!({ "external_controller": format!("127.0.0.1:{}", p.sing_box.clash_api_port), "secret": secret });
let mut experimental = json!({ "clash_api": clash });
if fake_ip || onion_fake {
// Fake addresses handed out survive a restart, so apps still holding one keep working.
experimental["cache_file"] = json!({
"enabled": true,
"path": format!("{}/tun.db", env.cache_dir.trim_end_matches(['/', '\\'])),
"store_fakeip": true,
});
}
let mut config = Map::new();
config.insert("log".into(), json!({ "level": cfg.debug.log_level.as_str() }));
config.insert("dns".into(), dns);
config.insert("inbounds".into(), Value::Array(inbounds));
config.insert("outbounds".into(), Value::Array(outbounds));
if !asm.endpoints.is_empty() {
config.insert("endpoints".into(), Value::Array(asm.endpoints.clone()));
}
config.insert("route".into(), route_obj);
config.insert("experimental".into(), experimental);
Ok((Value::Object(config), sidecar.map(|(c, _)| c)))
}
/// The hybrid backend's XRay sidecar: one loopback VLESS inbound, a client per XRay
/// outbound routed to it by its email, and the sing-box hops that reach each. VLESS rather
/// than SOCKS: UDP rides the stream (XUDP) with the client id, where SOCKS UDP datagrams carry
/// no user to route by.
fn sidecar(input: &Input, asm: &Assembly) -> (Value, Vec<Value>) {
let prefix: String = input.env.sidecar_secret.chars().take(24).collect();
let mut outbounds = Vec::new();
let mut clients = Vec::new();
let mut rules = Vec::new();
let mut hops = Vec::new();
for (i, ob) in asm.xray.iter().enumerate() {
let tag = ob["tag"].as_str().unwrap_or_default().to_owned();
let id = format!("{prefix}{i:012x}");
let mut ob = ob.clone();
apply_xmux(input, &mut ob);
if ob.pointer("/streamSettings/sockopt/domainStrategy").is_none() {
ob["streamSettings"]["sockopt"]["domainStrategy"] = "UseIP".into();
}
outbounds.push(ob);
clients.push(json!({ "id": id, "email": tag }));
rules.push(json!({ "type": "field", "inboundTag": ["sidecar-in"], "user": [tag], "outboundTag": tag }));
hops.push(json!({
"type": "vless", "tag": tag, "server": "127.0.0.1", "server_port": ports::XRAY_SIDECAR_SOCKS,
"uuid": id, "packet_encoding": "xudp",
}));
}
outbounds.push(json!({ "protocol": "freedom", "tag": "direct" }));
rules.push(json!({ "type": "field", "ip": ["127.0.0.1"], "port": XRAY_DNS_BRIDGE_PORT, "outboundTag": "direct" }));
let config = json!({
"log": { "loglevel": xray_log_level(input), "access": "none" },
"dns": { "servers": [{ "address": "127.0.0.1", "port": XRAY_DNS_BRIDGE_PORT, "queryStrategy": "UseIP", "skipFallBack": true }] },
"inbounds": [{
"tag": "sidecar-in", "listen": "127.0.0.1", "port": ports::XRAY_SIDECAR_SOCKS, "protocol": "vless",
"settings": { "clients": clients, "decryption": "none" },
}],
"outbounds": outbounds,
"routing": { "domainStrategy": "AsIs", "rules": rules },
});
(config, hops)
}
/// `debug.logLevel` in XRay's words: it has no "trace".
pub(super) fn xray_log_level(input: &Input) -> &'static str {
use crate::config::LogLevel;
match input.cfg.debug.log_level {
LogLevel::Warn => "warning",
LogLevel::Info => "info",
LogLevel::Debug | LogLevel::Trace => "debug",
}
}
/// `proxy.xray.xhttpXmux` for an XHTTP outbound whose link set no xmux.
pub(super) fn apply_xmux(input: &Input, ob: &mut Value) {
let Some(xmux) = &input.cfg.proxy.xray.xhttp_xmux else { return };
if ob.pointer("/streamSettings/network").and_then(Value::as_str) != Some("xhttp") {
return;
}
let current = ob.pointer("/streamSettings/xhttpSettings/extra/xmux");
if current.is_none_or(|v| v.as_object().is_some_and(|o| o.is_empty())) {
ob["streamSettings"]["xhttpSettings"]["extra"]["xmux"] = json!(xmux);
}
}
+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());
}
}
+175
View File
@@ -0,0 +1,175 @@
//! WireGuard and AmneziaWG `.conf` files: their sections, and a profile as a sing-box
//! WireGuard endpoint (upstream's `warp_outbound.py`).
use serde_json::{Value, json};
/// The AmneziaWG `[Interface]` keys, lowercased, with their spelling. sing-box speaks plain
/// WireGuard and has no use for them.
pub const AWG_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"),
];
/// wg-quick keys that run commands or rewrite the file: refused in imported configs unless
/// `allowConfigHooks`.
pub const FORBIDDEN_WG_QUICK_KEYS: [&str; 5] = ["preup", "postup", "predown", "postdown", "saveconfig"];
pub type Section = (String, Vec<(String, String)>);
/// Each `[Section]`, lowercased, with its `key = value` lines in order; keys lowercased,
/// comments (`#`, `;`) and lines outside a section dropped.
pub fn conf_sections(config: &str) -> Vec<Section> {
let mut sections: Vec<Section> = Vec::new();
for line in crate::links::py::splitlines(config) {
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('=')
&& let Some(last) = sections.last_mut()
{
last.1.push((key.trim().to_lowercase(), value.trim().to_owned()));
}
}
sections
}
fn section<'a>(sections: &'a [Section], name: &str) -> Option<&'a [(String, String)]> {
sections.iter().find(|(n, _)| n == name).map(|(_, pairs)| pairs.as_slice())
}
fn get<'a>(pairs: &'a [(String, String)], key: &str) -> Option<&'a str> {
// dict(pairs): the last value of a repeated key wins.
pairs.iter().rev().find(|(k, _)| k == key).map(|(_, v)| v.as_str()).filter(|v| !v.is_empty())
}
fn split_list(value: &str) -> Vec<String> {
value.split(',').map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).collect()
}
/// `host:port`, IPv6 in brackets.
pub fn split_endpoint(endpoint: &str) -> Result<(String, u16), String> {
let bad = || format!("endpoint '{endpoint}' is not host:port");
let (host, port) = endpoint.rsplit_once(':').ok_or_else(bad)?;
if host.is_empty() || port.is_empty() || !port.chars().all(|c| c.is_ascii_digit()) {
return Err(bad());
}
let port: u16 = port.parse().map_err(|_| bad())?;
Ok((host.trim_matches(|c| c == '[' || c == ']').to_owned(), port))
}
/// A WireGuard profile as a sing-box `wireguard` endpoint tagged `tag`, the profile's
/// endpoint replaced by `endpoint` when given. Also the AmneziaWG keys it had to drop.
pub fn sing_box_endpoint(text: &str, tag: &str, endpoint: Option<&str>) -> Result<(Value, Vec<&'static str>), String> {
let sections = conf_sections(text);
let (Some(interface), Some(peer)) = (section(&sections, "interface"), section(&sections, "peer")) else {
return Err("configuration requires [Interface] and [Peer] sections".into());
};
for (pairs, key) in [(interface, "privatekey"), (interface, "address"), (peer, "publickey"), (peer, "endpoint")] {
if get(pairs, key).is_none() {
return Err(format!("configuration has no {key}"));
}
}
let (host, port) = split_endpoint(endpoint.unwrap_or_else(|| get(peer, "endpoint").unwrap()))?;
let allowed = get(peer, "allowedips").map(split_list).filter(|l| !l.is_empty());
let mut sb_peer = json!({
"address": host,
"port": port,
"public_key": get(peer, "publickey").unwrap(),
"allowed_ips": allowed.unwrap_or_else(|| vec!["0.0.0.0/0".into(), "::/0".into()]),
});
if let Some(ka) = get(peer, "persistentkeepalive") {
// AWG 3 profiles give a range ("25-35"); sing-box takes one value.
let first = ka.split('-').next().unwrap_or("");
let interval: u32 = first.trim().parse().map_err(|_| format!("persistentkeepalive '{ka}' is not a number"))?;
sb_peer["persistent_keepalive_interval"] = interval.into();
}
if let Some(psk) = get(peer, "presharedkey") {
sb_peer["pre_shared_key"] = psk.into();
}
let mtu: u32 = match get(interface, "mtu") {
Some(m) => m.parse().map_err(|_| format!("mtu '{m}' is not a number"))?,
None => 1280,
};
let endpoint = json!({
"type": "wireguard",
"tag": tag,
"address": split_list(get(interface, "address").unwrap()),
"private_key": get(interface, "privatekey").unwrap(),
"mtu": mtu,
"peers": [sb_peer],
});
let mut dropped: Vec<&'static str> = AWG_INTERFACE_FIELDS
.iter()
.filter(|(k, _)| interface.iter().any(|(key, _)| key == k))
.map(|(_, name)| *name)
.collect();
dropped.sort_unstable();
Ok((endpoint, dropped))
}
/// The wg-quick hooks a config would run.
pub fn forbidden_keys(text: &str) -> Vec<String> {
let mut found: Vec<String> = conf_sections(text)
.into_iter()
.flat_map(|(_, pairs)| pairs.into_iter().map(|(k, _)| k))
.filter(|k| FORBIDDEN_WG_QUICK_KEYS.contains(&k.as_str()))
.collect();
found.sort();
found.dedup();
found
}
#[cfg(test)]
mod tests {
use super::*;
const WGCF: &str = "[Interface]\nPrivateKey = cHJpdmF0ZQ==\nAddress = 172.16.0.2/32, 2606:4700:110::2/128\nDNS = 1.1.1.1\nMTU = 1280\nJc = 4\n\n[Peer]\nPublicKey = cHVibGlj\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408 # comment\nPersistentKeepalive = 25-35\n";
#[test]
fn a_wgcf_profile_becomes_an_endpoint() {
let (ep, dropped) = sing_box_endpoint(WGCF, "warp", None).unwrap();
assert_eq!(ep["address"], json!(["172.16.0.2/32", "2606:4700:110::2/128"]));
assert_eq!(ep["peers"][0]["address"], "engage.cloudflareclient.com");
assert_eq!(ep["peers"][0]["port"], 2408);
assert_eq!(ep["peers"][0]["persistent_keepalive_interval"], 25);
assert_eq!(dropped, ["Jc"]);
let (ep, _) = sing_box_endpoint(WGCF, "warp", Some("[2606:4700:d0::a29f:c001]:500")).unwrap();
assert_eq!(ep["peers"][0]["address"], "2606:4700:d0::a29f:c001");
assert_eq!(ep["peers"][0]["port"], 500);
}
#[test]
fn missing_pieces_are_named() {
assert!(sing_box_endpoint("[Interface]\nPrivateKey = x\n", "w", None).unwrap_err().contains("[Peer]"));
let no_ep = WGCF.replace("Endpoint", "#Endpoint");
assert_eq!(sing_box_endpoint(&no_ep, "w", None).unwrap_err(), "configuration has no endpoint");
}
#[test]
fn hooks_are_found() {
assert_eq!(forbidden_keys("[Interface]\nPostUp = calc.exe\nSaveConfig = true\n"), ["postup", "saveconfig"]);
}
}
+695
View File
@@ -0,0 +1,695 @@
//! zapret-discord-youtube on Windows: Flowseal's release, run as its `service.bat` would run
//! it, with the user's lists the way upstream's Linux module fills them.
//!
//! A preset is one of the release's `general*.bat` files. Its `winws.exe` command line
//! (continued over `^` lines) is the strategy; `%BIN%`, `%LISTS%` and the game filter's
//! `%GameFilterTCP%` / `%GameFilterUDP%` are filled in. Unlike `service.bat`, which takes the
//! line apart with cmd's FOR (splitting on commas and `=` too) and glues it back, this splits
//! on whitespace alone and hands winws each argument as it was written.
use std::collections::BTreeSet;
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 {
name.trim_end_matches(".bat").chars().filter(|c| !c.is_whitespace()).collect::<String>().to_lowercase()
}
/// The release's presets: every `.bat` but `service*.bat`, by name without `.bat`.
pub fn presets(bat_files: &[String]) -> Vec<String> {
let mut names: Vec<String> = bat_files
.iter()
.filter(|f| f.to_lowercase().ends_with(".bat") && !f.to_lowercase().starts_with("service"))
.map(|f| f.trim_end_matches(".bat").trim_end_matches(".BAT").to_owned())
.collect();
// As service.bat lists them: numbers padded, so ALT2 comes before ALT10.
names.sort_by_key(|n| {
let mut key = String::new();
let mut digits = String::new();
for c in n.chars() {
if c.is_ascii_digit() {
digits.push(c);
} else {
if !digits.is_empty() {
key.push_str(&format!("{digits:0>8}"));
digits.clear();
}
key.push(c);
}
}
if !digits.is_empty() {
key.push_str(&format!("{digits:0>8}"));
}
key
});
names
}
/// The file of the preset `config_name` ("general(ALT)" finds "general (ALT).bat").
pub fn find_preset(bat_files: &[String], config_name: &str) -> Result<String, String> {
let want = name_key(config_name);
let found: Vec<&String> = bat_files.iter().filter(|f| f.to_lowercase().ends_with(".bat") && name_key(f) == want).collect();
match found.as_slice() {
[one] => Ok((*one).clone()),
[] => Err(format!(
"zapret preset '{config_name}' is not in this release; it has {}",
presets(bat_files).join(", ")
)),
_ => Err(format!("zapret preset '{config_name}' matches several files")),
}
}
/// cmd's splitting of a command line into arguments: whitespace outside double quotes,
/// quotes kept for now. Outside quotes `^` escapes what follows (`^!` is the `!` that tells
/// winws to use its built-in fake); a `^` before whitespace (a continuation) goes.
fn cmd_tokens(line: &str) -> Vec<String> {
let mut out = Vec::new();
let mut cur = String::new();
let mut quoted = false;
let mut chars = line.chars().peekable();
while let Some(c) = chars.next() {
match c {
'"' => {
quoted = !quoted;
cur.push(c);
}
'^' if !quoted => match chars.peek() {
Some(n) if !n.is_whitespace() => cur.push(chars.next().unwrap()),
_ => {}
},
c if c.is_whitespace() && !quoted => {
if !cur.is_empty() {
out.push(std::mem::take(&mut cur));
}
}
c => cur.push(c),
}
}
if !cur.is_empty() {
out.push(cur);
}
out
}
/// The `winws.exe` arguments of a preset's text, unexpanded.
pub fn preset_args(bat: &str) -> Result<Vec<String>, String> {
let lines: Vec<&str> = bat.lines().collect();
let start = lines
.iter()
.position(|l| l.to_lowercase().contains("winws.exe"))
.ok_or("the preset runs no winws.exe")?;
let mut text = String::new();
for line in &lines[start..] {
let t = line.trim_end();
match t.strip_suffix('^') {
Some(rest) => {
text.push_str(rest);
text.push(' ');
}
None => {
text.push_str(t);
break;
}
}
}
// Everything after the program, quoted or not.
let lower = text.to_lowercase();
let at = lower.find("winws.exe").expect("found above") + "winws.exe".len();
let rest = text[at..].strip_prefix('"').unwrap_or(&text[at..]);
let args = cmd_tokens(rest);
if args.is_empty() {
return Err("the preset gives winws.exe no arguments".into());
}
Ok(args)
}
/// `%GameFilterTCP%` and `%GameFilterUDP%`: the range, or Flowseal's dummy port 12 for off.
pub fn game_filter_ports(filter: GameFilter) -> (&'static str, &'static str) {
const RANGE: &str = "1024-65535";
const OFF: &str = "12";
match filter {
GameFilter::All => (RANGE, RANGE),
GameFilter::Tcp => (RANGE, OFF),
GameFilter::Udp => (OFF, RANGE),
GameFilter::Null => (OFF, OFF),
}
}
/// A preset's arguments with its variables filled in and its quotes gone: `bin` and `lists`
/// end with a path separator, as `%BIN%` and `%LISTS%` do.
pub fn expand(args: &[String], bin: &str, lists: &str, root: &str, game: GameFilter) -> Vec<String> {
let (tcp, udp) = game_filter_ports(game);
args.iter()
.map(|a| {
a.replace("%BIN%", bin)
.replace("%LISTS%", lists)
.replace("%~dp0", root)
.replace("%GameFilterTCP%", tcp)
.replace("%GameFilterUDP%", udp)
.replace('"', "")
})
.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)]
pub struct UserLists {
pub general_user: String,
pub exclude_user: String,
pub ipset_exclude_user: String,
/// Lines appended to the release's `ipset-all.txt`.
pub ipset_all_extra: String,
}
fn lines(items: &[String], placeholder: &str) -> String {
let mut seen = BTreeSet::new();
let mut out = String::new();
for i in items.iter().map(|s| s.trim()).filter(|s| !s.is_empty()) {
if seen.insert(i) {
out.push_str(i);
out.push('\n');
}
}
if out.is_empty() {
out.push_str(placeholder);
out.push('\n');
}
out
}
pub fn user_lists(cfg: &DiscordYoutube, cidr_exemption: &[String]) -> UserLists {
let mut exclude_ips = cfg.exclude_ips.clone();
exclude_ips.extend(cidr_exemption.iter().cloned());
UserLists {
general_user: lines(&cfg.domains, "domain.example.abc"),
exclude_user: lines(&cfg.exclude_domains, "domain.example.abc"),
ipset_exclude_user: lines(&exclude_ips, "203.0.113.113/32"),
ipset_all_extra: cfg.ips.iter().map(|s| format!("{}\n", s.trim())).collect(),
}
}
/// zapret's sites for the proxy's direct list (`zapret.directSync`), from the release's
/// lists and the user's: as upstream's rules-zapret-direct.nix has them. "^name" (an exact
/// match in winws) becomes the plain suffix, which is what a proxy rule can say.
pub fn direct_sync(z: &Zapret, list_general: &str, list_google: &str, list_exclude: &str, ipset_all: &str, ipset_exclude: &str) -> (Vec<String>, Vec<String>) {
let ds = &z.direct_sync;
if !z.enable || !ds.enable {
return (Vec::new(), Vec::new());
}
let parse = |text: &str| -> Vec<String> {
text.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|l| l.trim_start_matches('^').to_owned())
.collect()
};
let y = &z.discord_youtube;
let mut domains: Vec<String> = Vec::new();
let mut ips: Vec<String> = Vec::new();
if z.engine == crate::config::ZapretEngine::DiscordYoutube {
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));
if ds.upstream_ips {
// The release's own ipset-all is a placeholder unless loaded; it is what it is.
ips.extend(parse(ipset_all).into_iter().filter(|i| i != "203.0.113.113/32"));
}
if ds.user_ips {
ips.extend(y.ips.iter().cloned());
}
let mut excluded_ips: BTreeSet<String> = BTreeSet::new();
if ds.upstream_ips {
excluded_ips.extend(parse(ipset_exclude));
}
if ds.user_ips {
excluded_ips.extend(y.exclude_ips.iter().cloned());
}
ips.retain(|i| !excluded_ips.contains(i));
} else {
domains.extend(z.zapret2.domains.iter().cloned());
let excluded: BTreeSet<&String> = z.zapret2.exclude_domains.iter().collect();
domains.retain(|d| !excluded.contains(d));
}
let dedup = |v: Vec<String>| {
let mut seen = BTreeSet::new();
v.into_iter().filter(|x| !x.is_empty() && seen.insert(x.clone())).collect::<Vec<_>>()
};
(dedup(domains), dedup(ips))
}
#[cfg(test)]
mod tests {
use super::*;
const ALT: &str = r#"@echo off
chcp 65001 > nul
set "BIN=%~dp0bin\"
set "LISTS=%~dp0lists\"
cd /d %BIN%
start "zapret: %~n0" /min "%BIN%winws.exe" --wf-tcp=80,443,%GameFilterTCP% --wf-udp=443,%GameFilterUDP% ^
--filter-udp=443 --hostlist="%LISTS%list-general.txt" --dpi-desync=fake --dpi-desync-fake-quic="%BIN%quic_initial_www_google_com.bin" --new ^
--filter-tcp=443 --hostlist="%LISTS%list-google.txt" --dpi-desync-fake-tls-mod=rnd,dupsid,sni=www.google.com --dpi-desync-cutoff=n3
"#;
#[test]
fn a_preset_becomes_winws_arguments() {
let args = preset_args(ALT).unwrap();
assert_eq!(args[0], "--wf-tcp=80,443,%GameFilterTCP%");
assert_eq!(args.last().unwrap(), "--dpi-desync-cutoff=n3");
assert!(args.contains(&"--new".to_owned()));
let out = expand(&args, r"C:\z\bin\", r"C:\run\lists\", r"C:\z\", GameFilter::Null);
assert_eq!(out[0], "--wf-tcp=80,443,12");
assert_eq!(out[1], "--wf-udp=443,12");
assert!(out.contains(&r"--hostlist=C:\run\lists\list-general.txt".to_owned()));
assert!(out.contains(&r"--dpi-desync-fake-quic=C:\z\bin\quic_initial_www_google_com.bin".to_owned()));
assert!(out.contains(&"--dpi-desync-fake-tls-mod=rnd,dupsid,sni=www.google.com".to_owned()));
let all = expand(&args, "b\\", "l\\", "r\\", GameFilter::All);
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();
assert_eq!(args, ["--dpi-desync-fake-tls=!", "--x=\"a^b\"", "--y=^z"]);
}
#[test]
fn presets_are_found_by_name_without_spaces() {
let files: Vec<String> = ["general.bat", "general (ALT).bat", "general (ALT10).bat", "general (ALT2).bat", "service.bat"]
.map(String::from)
.to_vec();
assert_eq!(find_preset(&files, "general(ALT)").unwrap(), "general (ALT).bat");
assert_eq!(find_preset(&files, "General (alt2)").unwrap(), "general (ALT2).bat");
assert!(find_preset(&files, "general(ALT99)").unwrap_err().contains("general (ALT2)"));
assert_eq!(presets(&files), ["general", "general (ALT)", "general (ALT2)", "general (ALT10)"]);
}
#[test]
fn user_lists_keep_flowseals_placeholders() {
let mut y = DiscordYoutube::default();
let l = user_lists(&y, &[]);
assert_eq!(l.general_user, "domain.example.abc\n");
assert_eq!(l.ipset_exclude_user, "203.0.113.113/32\n");
y.domains = vec!["a.com".into(), "a.com".into(), "b.com".into()];
y.ips = vec!["198.51.100.0/24".into()];
let l = user_lists(&y, &["192.168.123.0/24".into()]);
assert_eq!(l.general_user, "a.com\nb.com\n");
assert_eq!(l.ipset_all_extra, "198.51.100.0/24\n");
assert_eq!(l.ipset_exclude_user, "192.168.123.0/24\n");
}
#[test]
fn direct_sync_takes_the_lists_minus_the_excludes() {
let mut z = Zapret { enable: true, ..Default::default() };
z.discord_youtube.domains = vec!["mine.example".into()];
z.discord_youtube.exclude_domains = vec!["youtube.com".into()];
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());
}
}
/// Every preset of a real release, when `PS_ZAPRET_RELEASE` names its unpacked directory.
#[cfg(test)]
#[test]
fn every_preset_of_the_release_parses() {
let Ok(dir) = std::env::var("PS_ZAPRET_RELEASE") else { return };
let files: Vec<String> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.filter(|f| f.ends_with(".bat"))
.collect();
let names = presets(&files);
assert!(names.len() > 10, "{names:?}");
for name in names {
let file = find_preset(&files, &name).unwrap();
let text = std::fs::read_to_string(std::path::Path::new(&dir).join(&file)).unwrap();
let args = expand(&preset_args(&text).unwrap(), "B\\", "L\\", "R\\", GameFilter::All);
for a in &args {
assert!(a.starts_with("--"), "{name}: {a:?}");
assert!(!a.contains('%') && !a.contains('"'), "{name}: {a:?}");
}
assert!(args.iter().filter(|a| *a == "--new").count() >= 1, "{name}");
assert!(args[0].starts_with("--wf-"), "{name}: {}", args[0]);
println!("{name}: {} args, {} profiles", args.len(), args.iter().filter(|a| *a == "--new").count() + 1);
}
}
+418
View File
@@ -0,0 +1,418 @@
//! zapret2 on Windows: winws2 (WinDivert) with the strategies upstream's module gives nfqws2
//! (NFQUEUE). The strategy source is nfqws2-keenetic, read and patched as upstream's
//! `zapret2/sources.nix` does; the profiles, markers, circular defaults and ports follow
//! upstream's `zapret2/runtime.nix` and zapret2's own `common/list.sh`.
//!
//! What differs on Windows: WinDivert's port filters (`--wf-tcp-out`, `--wf-udp-out`) take
//! the place of the queue's rules, and there are no marks. winws2 drops to Low integrity once
//! it runs, so the learned list lives in a directory the service labels Low for it (winws2's
//! own `--writable` insists on making the directory, which must already hold the list).
//! Learning is nfqws2's own autohostlist; upstream's detector (`detect.lua`,
//! `extendedDetection`) and z2k come later.
use crate::config::{StrategySource, Zapret2};
fn words(s: &str) -> Vec<&str> {
s.split_whitespace().collect()
}
/// The text between `start` and the next `stop`; exactly one `start`, or the pinned file
/// changed shape.
fn between<'a>(what: &str, start: &str, stop: &str, text: &'a str) -> Result<&'a str, String> {
let mut parts = text.split(start);
let (_, Some(after), None) = (parts.next(), parts.next(), parts.next()) else {
return Err(format!("expected one `{}` in {what}", start.trim()));
};
Ok(after.split(stop).next().unwrap_or(""))
}
fn patch(what: &str, from: &str, to: &str, text: &str) -> Result<String, String> {
if text.contains(from) {
Ok(text.replacen(from, to, 1))
} else {
Err(format!("expected `{from}` in {what}"))
}
}
/// nfqws2-keenetic's strategies, as upstream's sources.nix takes them.
#[derive(Debug, Clone, PartialEq)]
pub struct Source {
/// In nfqws2's order: UDP, QUIC, TCP. Hostlist markers still in.
pub profiles: Vec<String>,
pub blob_args: Vec<String>,
pub tcp_ports: String,
pub udp_ports: String,
}
/// `conf`: its `etc/nfqws2/nfqws2.conf`; `dir`: where its `etc/nfqws2/` is (as winws2 will
/// read it, with a trailing separator).
pub fn keenetic(conf: &str, dir: &str) -> Result<Source, String> {
let quoted = |name: &str| between("nfqws2.conf", &format!("\n{name}=\""), "\"", conf);
let bare = |name: &str| between("nfqws2.conf", &format!("\n{name}="), "\n", conf);
let args = |name: &str| -> Result<String, String> {
let body = quoted(name)?;
let kept: Vec<&str> = body.lines().filter(|l| !l.trim().starts_with('#')).collect();
Ok(words(&kept.join("\n")).join(" "))
};
let sep = if dir.contains('\\') { "\\" } else { "/" };
let lists = format!(
"--hostlist={dir}lists{sep}user.list --hostlist-exclude={dir}lists{sep}exclude.list"
);
let circular = "--lua-desync=circular:fails=2:time=300:retrans=3:nld=2";
let tcp_payload = "--payload=tls_client_hello,mtproto_initial";
let udp_payload = "--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown";
// Its first UDP strategy's fake has no blob, which zapret2 rejects on every packet;
// circular is handed the replies, as in zapret2's manual.
let udp = args("NFQWS_ARGS_UDP")?;
let udp = patch("NFQWS_ARGS_UDP", "--lua-desync=fake:repeats=6:strategy=1", &format!("--lua-desync=fake:blob=0x{}:repeats=6:strategy=1", "0".repeat(128)), &udp)?;
let udp = patch(
"NFQWS_ARGS_UDP",
&format!("--out-range=<n2 {udp_payload} {circular}"),
&format!("--out-range=a --in-range=a {udp_payload} {circular} --out-range=<n2 --in-range=x"),
&udp,
)?;
let quic = format!("{} <HOSTLIST_NOAUTO> {lists}", args("NFQWS_ARGS_QUIC")?);
let tcp = patch(
"NFQWS_ARGS",
&format!("{tcp_payload} {circular}"),
&format!("<STALLWATCH> --in-range=-s5556 {tcp_payload},tls_server_hello,empty,unknown {circular}:key=circular_3_1 --in-range=x {tcp_payload}"),
&args("NFQWS_ARGS")?,
)?;
let tcp = format!("{tcp} <HOSTLIST> {lists}");
let blob_args = words(quoted("NFQWS_BASE_ARGS")?)
.into_iter()
.filter(|w| w.starts_with("--blob="))
.map(|w| {
let w = w.replace("@/opt/etc/nfqws2/", &format!("@{dir}"));
if sep == "\\" { w.replace("blobs/", "blobs\\") } else { w }
})
.collect();
Ok(Source {
profiles: vec![udp, quic, tcp],
blob_args,
tcp_ports: bare("TCP_PORTS")?.trim().to_owned(),
udp_ports: bare("UDP_PORTS")?.trim().replace(':', "-"),
})
}
/// Where winws2's lists are, as it reads them.
#[derive(Debug, Clone)]
pub struct Paths {
/// The component's `lua\`, with a trailing separator.
pub lua: String,
/// `zapret-hosts-user.txt`: `zapret.zapret2.domains` and `proxy-ctl zapret auto add`.
pub user: String,
/// `zapret-hosts-user-exclude.txt`.
pub exclude: String,
/// `zapret-hosts-auto.txt`, in a directory labelled Low integrity.
pub auto: String,
}
/// A hostlist entry as nfqws2 takes one: a name (`^` for an exact match), nothing that could
/// read as another argument or another entry.
pub fn host_entry_ok(entry: &str) -> bool {
!entry.is_empty()
&& entry.len() <= 253
&& !entry.starts_with('-')
&& entry.chars().enumerate().all(|(i, c)| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '*') || (c == '^' && i == 0))
}
/// What `<HOSTLIST>` and `<HOSTLIST_NOAUTO>` expand to (zapret2's filter_apply_hostlist_target).
fn hostlist_args(z: &Zapret2, p: &Paths) -> (String, String) {
let a = &z.auto_hostlist;
let base = format!("--hostlist={} --hostlist-exclude={}", p.user, p.exclude);
let (with_auto, no_auto) = if a.enable {
(
format!(
"{base} --hostlist-auto={} --hostlist-auto-fail-threshold={} --hostlist-auto-fail-time={} \
--hostlist-auto-retrans-threshold={} --hostlist-auto-retrans-reset={} \
--hostlist-auto-retrans-maxseq={} --hostlist-auto-incoming-maxseq={} \
--hostlist-auto-udp-in={} --hostlist-auto-udp-out={}",
p.auto,
a.fail_threshold,
a.fail_time,
a.retrans_threshold,
u8::from(a.retrans_reset),
a.retrans_maxseq,
a.incoming_maxseq,
a.udp_in,
a.udp_out
),
format!("{base} --hostlist={}", p.auto),
)
} else {
(base.clone(), base)
};
// The configuration's domains join every profile that takes a list.
// Validated already; dropped here too, as this text is split into winws2's arguments.
let domains: Vec<&str> = z.domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
let excluded: Vec<&str> = z.exclude_domains.iter().map(String::as_str).filter(|d| host_entry_ok(d)).collect();
let mut statics = String::new();
if !domains.is_empty() {
statics.push_str(&format!(" --hostlist-domains={}", domains.join(",")));
}
if !excluded.is_empty() {
statics.push_str(&format!(" --hostlist-exclude-domains={}", excluded.join(",")));
}
(with_auto + &statics, no_auto + &statics)
}
/// Detector settings a circular instance leaves unset come from autoHostlist.
fn circular_fill(z: &Zapret2, token: &str) -> String {
let a = &z.auto_hostlist;
let mut fill = vec![
format!("retrans={}", a.retrans_threshold),
format!("maxseq={}", a.retrans_maxseq),
format!("inseq={}", a.incoming_maxseq),
format!("udp_out={}", a.udp_out),
format!("udp_in={}", a.udp_in),
];
if a.retrans_reset {
fill.push("reset".into());
}
let mut t = token.to_owned();
for f in fill {
let key = f.split('=').next().unwrap();
let has = t.split(':').skip(1).any(|part| part == key || part.starts_with(&format!("{key}=")));
if !has {
t.push(':');
t.push_str(&f);
}
}
t
}
fn port_list(values: &[serde_json::Value]) -> String {
values
.iter()
.map(|v| match v {
serde_json::Value::String(s) => s.clone(),
other => other.to_string(),
})
.collect::<Vec<_>>()
.join(",")
}
/// Ports as ranges, merged: upstream's ports.awk.
pub(crate) fn merge_ports(lists: &[&str]) -> String {
let mut on = vec![false; 65537];
for list in lists {
for p in list.split(',') {
let p = p.trim();
let Some((lo, hi)) = (match p.split_once('-') {
Some((a, b)) => a.parse::<u32>().ok().zip(b.parse::<u32>().ok()),
None => p.parse::<u32>().ok().map(|n| (n, n)),
}) else {
continue;
};
for port in lo.max(1)..=hi.min(65535) {
on[port as usize] = true;
}
}
}
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 on.get(port).copied().unwrap_or(false) {
if start == 0 {
start = port;
}
} else if start != 0 {
out.push(if start == port - 1 { start.to_string() } else { format!("{start}-{}", port - 1) });
start = 0;
}
}
out.join(",")
}
/// winws2's whole command line.
pub fn args(z: &Zapret2, source: &Source, p: &Paths, debug_packets: bool) -> Result<Vec<String>, String> {
if z.strategy_source != StrategySource::Nfqws2Keenetic && z.profiles.is_none() {
return Err("only the nfqws2-keenetic strategies are there on Windows yet (zapret.zapret2.strategySource)".into());
}
let (with_auto, no_auto) = hostlist_args(z, p);
let render = |profile: &str| {
profile
.replace("<HOSTLIST_NOAUTO>", &no_auto)
.replace("<HOSTLIST>", &with_auto)
.replace("<STALLWATCH> ", "")
.replace("<STALLWATCH>", "")
};
let profiles: Vec<String> = match &z.profiles {
Some(own) => own.iter().map(|x| render(x)).collect(),
None => source.profiles.iter().map(|x| render(x)).collect(),
};
let mut opt: Vec<String> = Vec::new();
if debug_packets {
opt.push("--debug=1".into());
}
for lua in ["zapret-lib.lua", "zapret-antidpi.lua", "zapret-auto.lua"] {
opt.push(format!("--lua-init=@{}{lua}", p.lua));
}
for (name, file) in &z.blobs {
opt.push(format!("--blob={name}:@{file}"));
}
if z.profiles.is_none() {
opt.extend(source.blob_args.iter().cloned());
}
let mut body: Vec<String> = Vec::new();
for (i, profile) in profiles.iter().enumerate() {
if i > 0 {
body.push("--new".into());
}
body.extend(words(profile).into_iter().map(str::to_owned));
}
let body: Vec<String> = body
.into_iter()
.map(|t| if t.starts_with("--lua-desync=circular") { circular_fill(z, &t) } else { t })
.collect();
// Extra ports join every profile that tells its traffic by protocol; the WinDivert
// filter takes the base lists, the extras and every port a profile filters on.
let xtcp = port_list(&z.ports.extra_tcp);
let xudp = port_list(&z.ports.extra_udp);
let mut l7 = std::collections::BTreeSet::new();
let mut prof = 0;
for t in &body {
if t == "--new" {
prof += 1;
} else if t.starts_with("--filter-l7=") {
l7.insert(prof);
}
}
let (mut tcp_ports, mut udp_ports): (Vec<String>, Vec<String>) = (Vec::new(), Vec::new());
let mut prof = 0;
let body: Vec<String> = body
.into_iter()
.map(|t| {
if t == "--new" {
prof += 1;
return t;
}
for (key, extra, list) in [("--filter-tcp=", &xtcp, &mut tcp_ports), ("--filter-udp=", &xudp, &mut udp_ports)] {
if let Some(ports) = t.strip_prefix(key) {
let t = if l7.contains(&prof) && !extra.is_empty() { format!("{t},{extra}") } else { t.clone() };
list.push(t[key.len()..].to_owned());
let _ = ports;
return t;
}
}
t
})
.collect();
let base_tcp = z.ports.tcp.clone().unwrap_or_else(|| source.tcp_ports.clone());
let base_udp = z.ports.udp.clone().unwrap_or_else(|| source.udp_ports.clone());
let mut tcp_all: Vec<&str> = vec![&base_tcp, &xtcp];
tcp_all.extend(tcp_ports.iter().map(String::as_str));
let mut udp_all: Vec<&str> = vec![&base_udp, &xudp];
udp_all.extend(udp_ports.iter().map(String::as_str));
let (wf_tcp, wf_udp) = (merge_ports(&tcp_all), merge_ports(&udp_all));
if !wf_tcp.is_empty() {
opt.push(format!("--wf-tcp-out={wf_tcp}"));
}
if !wf_udp.is_empty() {
opt.push(format!("--wf-udp-out={wf_udp}"));
// UDP has no handshake for the filter to catch: circular judges a flow by its replies.
opt.push(format!("--wf-udp-in={wf_udp}"));
}
if !z.ipv6 {
opt.push("--wf-l3=ipv4".into());
}
opt.extend(body);
Ok(opt)
}
#[cfg(test)]
mod tests {
use super::*;
const CONF: &str = r#"# x
NFQWS_BASE_ARGS="--lua-init=@/opt/etc/nfqws2/lua/zapret-lib.lua
--blob=quic_initial:@/opt/etc/nfqws2/blobs/quic_initial.bin
--blob=tls_clienthello:@/opt/etc/nfqws2/blobs/tls_clienthello.bin"
NFQWS_ARGS="--filter-tcp=443,80 --filter-l7=http,tls
# HTTPS
--payload=tls_client_hello,mtproto_initial
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
# Strategy 1
--lua-desync=fake:blob=tls_clienthello:strategy=1"
NFQWS_ARGS_QUIC="--filter-udp=443 --filter-l7=quic
--payload=quic_initial
--lua-desync=fake:blob=quic_initial:repeats=11"
NFQWS_ARGS_UDP="--filter-udp=590-600,3478-3481
--filter-l7=stun
--out-range=<n2
--payload=wireguard_initiation,wireguard_response,wireguard_cookie,stun,discord_ip_discovery,mtproto_initial,unknown
--lua-desync=circular:fails=2:time=300:retrans=3:nld=2
# Strategy 1
--lua-desync=fake:repeats=6:strategy=1"
TCP_PORTS=80,443,1984
UDP_PORTS=443,590:600
"#;
fn paths() -> Paths {
Paths {
lua: r"C:\z2\lua\".into(),
user: r"C:\s\user.txt".into(),
exclude: r"C:\s\exclude.txt".into(),
auto: r"C:\s\learned\auto.txt".into(),
}
}
#[test]
fn keenetic_is_read_and_patched_as_upstream_does() {
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
assert!(s.profiles[0].contains(&format!("blob=0x{}", "0".repeat(128))));
assert!(s.profiles[0].contains("--out-range=a --in-range=a"));
assert!(s.profiles[1].ends_with(r"<HOSTLIST_NOAUTO> --hostlist=C:\z2\keenetic\lists\user.list --hostlist-exclude=C:\z2\keenetic\lists\exclude.list"));
assert!(s.profiles[2].contains(":key=circular_3_1 --in-range=x"));
assert!(!s.profiles[2].contains("# Strategy"));
assert_eq!(s.blob_args[0], r"--blob=quic_initial:@C:\z2\keenetic\blobs\quic_initial.bin");
assert_eq!((s.tcp_ports.as_str(), s.udp_ports.as_str()), ("80,443,1984", "443,590-600"));
}
#[test]
fn a_whole_command_line() {
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
let mut z = Zapret2 { domains: vec!["rutracker.org".into()], ..Default::default() };
z.ports.extra_tcp = vec![serde_json::json!(8444)];
let a = args(&z, &s, &paths(), false).unwrap();
let line = a.join(" ");
assert!(line.starts_with(r"--lua-init=@C:\z2\lua\zapret-lib.lua"));
assert!(line.contains(r"--hostlist-auto=C:\s\learned\auto.txt --hostlist-auto-fail-threshold=3"));
assert!(line.contains(r"--hostlist=C:\s\learned\auto.txt --hostlist-domains=rutracker.org"));
assert!(line.contains("--filter-tcp=443,80,8444"));
assert!(line.contains("--wf-tcp-out=80,443,1984,8444"));
assert!(line.contains("--wf-udp-out=443,590-600,3478-3481"));
assert!(line.contains("--wf-l3=ipv4"));
// circular got the detector's defaults it left unset.
let circ = a.iter().find(|t| t.starts_with("--lua-desync=circular") && t.contains("key=")).unwrap();
assert!(circ.contains(":maxseq=32768") && circ.contains(":reset") && circ.contains(":retrans=3"));
assert_eq!(circ.matches("retrans=").count(), 1);
assert_eq!(a.iter().filter(|t| *t == "--new").count(), 2);
assert!(!line.contains("<HOSTLIST") && !line.contains("<STALLWATCH"), "{line}");
}
#[test]
fn a_domain_cannot_carry_another_argument() {
let s = keenetic(CONF, r"C:\z2\keenetic\").unwrap();
let z = Zapret2 { domains: vec!["ok.example".into(), "x.com --lua-init=@C:\\evil.lua".into(), "-x".into()], ..Default::default() };
let line = args(&z, &s, &paths(), false).unwrap().join(" ");
assert!(!line.contains("evil") && !line.contains(",-x"), "{line}");
assert!(line.contains("--hostlist-domains=ok.example"));
assert!(host_entry_ok("^dns.google") && !host_entry_ok("a^b") && !host_entry_ok("a,b"));
}
#[test]
fn ports_merge_into_ranges() {
assert_eq!(merge_ports(&["80,443", "443,1000-1002", "1003", "~5", "*"]), "80,443,1000-1003");
}
}
+232
View File
@@ -0,0 +1,232 @@
//! Rendered configs, checked by the backends themselves: `sing-box check` and
//! `xray run -test`, when they are on PATH (the dev shell has both).
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use ps_core::config::*;
use ps_core::render::{Env, Input, RouteMode, State, render};
use serde_json::{Value, json};
const PBK: &str = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc";
const WGCF: &str = "[Interface]\nPrivateKey = yAnz5TF+lXXJte14tji3zlMNq+hd2rYUIgJBgB3fBmk=\nAddress = 172.16.0.2/32, 2606:4700:110:8a36::2/128\nMTU = 1280\n\n[Peer]\nPublicKey = bmXOC+F1FxEMF9dyiK2H5/1SUtzH0JuVo51h2wPfgyo=\nAllowedIPs = 0.0.0.0/0, ::/0\nEndpoint = engage.cloudflareclient.com:2408\n";
fn have(bin: &str) -> bool {
Command::new(bin).arg("version").output().is_ok()
}
fn scratch(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("ps-core-render-{}-{name}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
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();
warp.insert("warp".to_owned(), WGCF.to_owned());
Env {
empty_rule_set: empty.to_string_lossy().into(),
cache_dir: dir.to_string_lossy().into(),
clash_secret: Some("s3cret".into()),
hop_login: Some(("hop".into(), "hop-pass".into())),
warp_profiles: warp,
direct_processes: vec![r"C:\ProgramData\ProxySuite\bin\tor\tor.exe".into()],
groups_watched: false,
sidecar_secret: "0b1c2d3e-4f50-6172-8394-a5b6c7d8e9f0".into(),
windows: true,
..Default::default()
}
}
fn no_files(path: &str) -> Result<String, String> {
Err(format!("{path}: not found"))
}
fn check_sing_box(config: &Value, dir: &Path) {
if !have("sing-box") {
eprintln!("sing-box not on PATH: skipping the check");
return;
}
let path = dir.join("sing-box.json");
std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap();
let out = Command::new("sing-box").args(["check", "-c"]).arg(&path).output().unwrap();
assert!(
out.status.success(),
"sing-box check failed:\n{}\n{}",
String::from_utf8_lossy(&out.stderr),
serde_json::to_string_pretty(config).unwrap()
);
}
fn check_xray(config: &Value, dir: &Path) {
if !have("xray") {
return;
}
let path = dir.join("xray.json");
std::fs::write(&path, serde_json::to_string_pretty(config).unwrap()).unwrap();
let out = Command::new("xray").args(["run", "-test", "-c"]).arg(&path).output().unwrap();
assert!(
out.status.success(),
"xray -test failed:\n{}{}\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
serde_json::to_string_pretty(config).unwrap()
);
}
fn outbound(tag: &str, url: &str) -> Outbound {
Outbound { tag: tag.into(), url: Some(url.into()), ..Default::default() }
}
fn base() -> Config {
let mut cfg = Config::default();
cfg.proxy.enable = true;
cfg.proxy.outbounds = vec![
outbound("nl", "hy2://pw@nl.example.com:443?sni=nl.example.com"),
outbound("de", &format!("vless://00000000-0000-0000-0000-000000000000@de.example.com:443?security=reality&pbk={PBK}&sid=ab&sni=www.microsoft.com&fp=chrome&flow=xtls-rprx-vision")),
];
cfg
}
#[test]
fn a_minimal_proxy_checks() {
let dir = scratch("minimal");
let cfg = base();
let r = render(&Input {
cfg: &cfg,
state: &State::default(),
subscriptions: &BTreeMap::new(),
env: &env(&dir),
read_file: &no_files,
tun: false,
})
.unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(sb["outbounds"][0], json!({ "type": "selector", "tag": "proxy", "outbounds": ["nl"], "default": "nl" }));
assert_eq!(sb["route"]["final"], "proxy");
assert_eq!(r.inventory.top, ["nl", "de"]);
check_sing_box(&sb, &dir);
}
#[test]
fn everything_at_once_checks() {
let dir = scratch("full");
let mut cfg = base();
let p = &mut cfg.proxy;
p.selection = Selection::Urltest;
p.listener.auth = ListenerAuth { username: Some("me".into()), password: Some("pw".into()), password_file: None };
p.outbounds.push(Outbound { detour: Some("nl".into()), ..outbound("chained", "trojan://pw@t.example.com:443?sni=t.example.com") });
p.outbounds.push(outbound("broken", "vless://uuid@x.example.com:70000"));
p.outbounds[1].routing.geosites = vec!["netflix".into()];
p.subscriptions.push(Subscription { tag: "sub".into(), url: Some("https://sub.example.com/x".into()), ..Default::default() });
p.groups.insert("eu".into(), Group { outbounds: vec!["de".into()], subscriptions: vec!["sub".into()], ..Default::default() });
p.groups.insert("fast".into(), Group { match_: vec!["sub-*".into()], strategy: GroupStrategy::Urltest, ..Default::default() });
p.routing.rules.push(RoutingRule {
outbound: "eu".into(),
matches: RouteMatch { domains: vec!["example.org".into()], ips: vec!["203.0.113.0/24".into()], ..Default::default() },
process_names: vec!["Telegram.exe".into()],
..Default::default()
});
p.routing.rules.push(RoutingRule { name: Some("early".into()), priority: Some(10), outbound: "direct".into(), matches: RouteMatch { domains: vec!["bank.example".into()], ..Default::default() }, ..Default::default() });
p.routing.rules.push(RoutingRule { outbound: "gone".into(), matches: RouteMatch { domains: vec!["x.example".into()], ..Default::default() }, ..Default::default() });
p.routing.block.geosites = vec!["category-ads-all".into()];
p.routing.rule_sets.insert("antifilter".into(), RuleSet { url: "https://example.com/antifilter.srs".into(), format: None, detour: RuleSetDetour::Proxy });
p.routing.proxy.rule_sets = vec!["antifilter".into()];
p.tun.enable = true;
p.dns.fake_ip.enable = true;
p.dns.strategy = Some(DomainStrategy::Ipv4Only);
cfg.per_app_routing.enable = true;
cfg.per_app_routing.profiles.push(PerAppProfile { name: "games".into(), outbound: "direct".into(), process_names: vec!["steam.exe".into()], ..Default::default() });
cfg.tor.enable = true;
cfg.tor.as_outbound = true;
cfg.warp.enable = true;
cfg.warp.as_outbound = Some(WarpOutboundKind::SingBox);
cfg.ssh_proxy.enable = true;
cfg.ssh_proxy.as_outbound = true;
cfg.ssh_proxy.server = SshServer { user: Some("root".into()), host: Some("ssh.example.com".into()), port: 22 };
cfg.ssh_proxy.host_key = vec!["ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl".into()];
cfg.whitelist_bypass.enable = true;
cfg.whitelist_bypass.joiners.insert("wl".into(), WlJoiner { platform: WlPlatform::Wbstream, link_file: None });
let mut subs = BTreeMap::new();
subs.insert("sub".to_owned(), vec![
"hy2://pw@a.example.com:443#A".to_owned(),
"hy2://pw@b.example.com:443#B".to_owned(),
"hy2://pw@127.0.0.1:443#Loop".to_owned(),
]);
let mut state = State::default();
state.disabled.push("sub-B".into());
let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &subs, env: &env(&dir), read_file: &no_files, tun: true }).unwrap();
let sb = r.sing_box.unwrap();
let tags: Vec<&str> = sb["outbounds"].as_array().unwrap().iter().map(|o| o["tag"].as_str().unwrap()).collect();
assert!(tags.contains(&"chained") && !tags.contains(&"broken"), "{tags:?}");
assert!(r.warnings.iter().any(|w| w.contains("'broken'")), "{:?}", r.warnings);
assert!(r.warnings.iter().any(|w| w.contains("'gone'")), "{:?}", r.warnings);
let gone = sb["route"]["rules"].as_array().unwrap().iter().find(|r| r["domain_suffix"] == json!(["x.example"])).unwrap();
assert_eq!(gone["outbound"], "block");
assert_eq!(sb["endpoints"][0]["tag"], "warp");
assert_eq!(r.inventory.detours["chained"], "nl");
assert!(r.inventory.excluded.contains(&"tor".to_owned()));
assert!(r.inventory.disabled.contains(&"sub-B".to_owned()));
// The early rule sorts ahead of the configuration's own.
let rules = sb["route"]["rules"].as_array().unwrap();
let early = rules.iter().position(|r| r["domain_suffix"] == json!(["bank.example"])).unwrap();
let eu = rules.iter().position(|r| r["domain_suffix"] == json!(["example.org"])).unwrap();
assert!(early < eu);
assert_eq!(sb["inbounds"].as_array().unwrap().last().unwrap()["type"], "tun");
check_sing_box(&sb, &dir);
}
#[test]
fn hybrid_hands_xhttp_to_the_sidecar() {
let dir = scratch("hybrid");
let mut cfg = base();
cfg.proxy.backend = Backend::Hybrid;
cfg.proxy.outbounds.push(outbound("xh", "vless://00000000-0000-0000-0000-000000000000@x.example.com:443?security=tls&sni=x.example.com&type=xhttp&path=%2Fx&mode=packet-up"));
cfg.proxy.xray.xhttp_xmux = Some(BTreeMap::from([("maxConnections".to_owned(), json!(3))]));
cfg.proxy.selection = Selection::Selector;
let r = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
let hop = sb["outbounds"].as_array().unwrap().iter().find(|o| o["tag"] == "xh").unwrap();
assert_eq!(hop["type"], "vless");
assert_eq!(r.inventory.runs_on["xh"], "xray");
let xray = r.xray.unwrap();
assert_eq!(xray["outbounds"][0]["streamSettings"]["xhttpSettings"]["extra"]["xmux"]["maxConnections"], 3);
check_sing_box(&sb, &dir);
check_xray(&xray, &dir);
}
#[test]
fn route_modes_change_the_final_and_the_lists() {
let dir = scratch("modes");
let mut cfg = base();
cfg.proxy.routing.direct.domains = vec!["direct.example".into()];
cfg.proxy.routing.block.domains = vec!["ads.example".into()];
for (mode, final_ob, has_direct) in [
(None, "proxy", true),
(Some(RouteMode::Whitelist), "direct", true),
(Some(RouteMode::AllProxy), "proxy", false),
(Some(RouteMode::AllBypass), "direct", false),
] {
let state = State { route_mode: mode, ..Default::default() };
let r = render(&Input { cfg: &cfg, state: &state, subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap();
let sb = r.sing_box.unwrap();
assert_eq!(sb["route"]["final"], final_ob, "{mode:?}");
let rules = sb["route"]["rules"].as_array().unwrap();
assert_eq!(rules.iter().any(|r| r["domain_suffix"] == json!(["direct.example"])), has_direct, "{mode:?}");
assert!(rules.iter().any(|r| r["domain_suffix"] == json!(["ads.example"])), "{mode:?}");
check_sing_box(&sb, &dir);
}
}
#[test]
fn no_outbounds_is_an_error() {
let dir = scratch("none");
let mut cfg = Config::default();
cfg.proxy.enable = true;
let err = render(&Input { cfg: &cfg, state: &State::default(), subscriptions: &BTreeMap::new(), env: &env(&dir), read_file: &no_files, tun: false }).unwrap_err();
assert!(err.0.contains("no proxy outbounds"));
}
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "ps-ctl"
description = "Proxy Suite for Windows: proxy-ctl, the command line"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "proxy-ctl"
path = "src/main.rs"
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
ps-client.workspace = true
anyhow.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
[dev-dependencies]
serde_json.workspace = true
+641
View File
@@ -0,0 +1,641 @@
//! proxy-ctl: upstream's command line, over the service's API.
use std::io::Read;
use anyhow::{Context, Result, bail};
use clap::{Args, Parser, Subcommand};
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)]
struct Cli {
/// The service's pipe or socket.
#[arg(long, global = true, value_name = "ADDRESS")]
socket: Option<String>,
/// Print what the service answers, as JSON.
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Cmd,
}
#[derive(Subcommand)]
enum Cmd {
/// Services and routing mode.
Status,
/// Restart running services.
Restart { units: Vec<String> },
/// Show logs (all units, or the ones named); -f follows.
Logs {
units: Vec<String>,
#[arg(short = 'n', long, default_value_t = 100)]
lines: usize,
#[arg(short = 'f', long)]
follow: bool,
},
/// The local proxy.
Proxy(ProxyArgs),
/// The whole configuration.
Config {
#[command(subcommand)]
verb: ConfigVerb,
},
/// DPI bypass: status, on, off, or the presets and the one to use.
Zapret {
#[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)]
verb: Option<ComponentsVerb>,
},
}
#[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.
GameFilter { filter: String },
}
#[derive(Subcommand)]
enum ComponentsVerb {
List,
/// Fetch, verify and install (all, or the named).
Install { names: Vec<String> },
}
#[derive(Subcommand)]
enum ConfigVerb {
/// Print it (secrets hidden without the secrets scope).
Get,
/// Replace it with a file's (or stdin's, with -).
Set { file: String },
/// Check a file without taking it.
Validate { file: String },
}
#[derive(Args)]
struct ProxyArgs {
#[command(subcommand)]
verb: Option<ProxyVerb>,
}
#[derive(Subcommand)]
enum ProxyVerb {
Status,
On,
Off,
/// Outbounds, their source, and the current pick.
Outbounds {
#[command(subcommand)]
verb: Option<OutboundVerb>,
},
/// Always use this outbound.
Pin {
tag: String,
#[arg(long = "in", value_name = "GROUP")]
group: Option<String>,
},
/// Back to automatic selection.
Unpin {
#[arg(long = "in", value_name = "GROUP")]
group: Option<String>,
},
/// Show or override the routing mode: default, whitelist, blacklist, all-proxy, all-bypass.
Mode { mode: Option<String> },
/// Subscriptions.
Subs {
#[command(subcommand)]
verb: Option<SubsVerb>,
},
/// Routing rules.
Rules {
#[command(subcommand)]
verb: Option<RulesVerb>,
},
/// Rule sets: update refetches them.
Rulesets {
#[command(subcommand)]
verb: Option<RulesetsVerb>,
},
/// Global TUN mode.
Tun {
#[command(subcommand)]
verb: Option<OnOff>,
},
/// The config the backend runs.
Config,
}
#[derive(Subcommand)]
enum OnOff {
Status,
On,
Off,
}
#[derive(Subcommand)]
enum OutboundVerb {
List,
/// Add an outbound from a link (- reads it from stdin).
Add {
/// The tag, then the link; or the link alone.
args: Vec<String>,
#[arg(long)]
detour: Option<String>,
},
Rm { tag: String },
Disable { tag: String },
Enable { tag: String },
/// Delay through each (all, or the named).
Test { tags: Vec<String> },
/// Its link.
Link { tag: String },
}
#[derive(Subcommand)]
enum SubsVerb {
List,
Update { tag: Option<String> },
/// Add a subscription (no tag: named after its host; - reads the URL from stdin).
Add { args: Vec<String> },
Rm { tag: String },
}
#[derive(Subcommand)]
enum RulesVerb {
List,
/// Send domains, addresses, geosite:x, geoip:x, ruleset:x or process:x.exe to a target.
Add {
target: String,
matches: Vec<String>,
#[arg(long)]
name: Option<String>,
#[arg(long)]
priority: Option<i64>,
},
Rm { name: String },
Disable { name: String },
Enable { name: String },
}
#[derive(Subcommand)]
enum RulesetsVerb {
List,
Update,
}
struct Ctl {
client: Client,
json: bool,
}
impl Ctl {
async fn call(&self, req: Request) -> Result<Value> {
self.client.call(req).await
}
fn print(&self, v: &Value) {
println!("{}", serde_json::to_string_pretty(v).unwrap());
}
/// 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}");
}
if let Some(e) = &saved.apply_error {
eprintln!("saved, but not applied: {e}");
}
Ok(saved)
}
}
fn read_arg(value: &str) -> Result<String> {
if value == "-" {
let mut s = String::new();
std::io::stdin().read_to_string(&mut s)?;
Ok(s.trim().to_owned())
} else {
Ok(value.to_owned())
}
}
fn read_file_arg(file: &str) -> Result<Value> {
let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? };
serde_json::from_str(&text).with_context(|| format!("{file} is not JSON"))
}
async fn status(ctl: &Ctl) -> Result<()> {
let s = ctl.call(Request::Status).await?;
if ctl.json {
ctl.print(&s);
return Ok(());
}
let p = &s["proxy"];
println!(
"proxy: {} ({}, {}){}",
p["state"].as_str().unwrap_or("?"),
p["backend"].as_str().unwrap_or("?"),
p["listener"].as_str().unwrap_or("?"),
if p["tun"] == true { ", global TUN" } else { "" }
);
println!(
" selection {}, mode {}{}",
p["selection"].as_str().unwrap_or("?"),
p["mode"].as_str().unwrap_or("default"),
p["pinned"].as_str().map(|t| format!(", pinned to {t}")).unwrap_or_default()
);
for u in s["units"].as_array().into_iter().flatten() {
println!("{:32} {}", u["name"].as_str().unwrap_or(""), u["state"].as_str().unwrap_or(""));
}
if let Some(e) = s["error"].as_str() {
println!("error: {e}");
}
for w in s["warnings"].as_array().into_iter().flatten() {
println!("warning: {}", w.as_str().unwrap_or(""));
}
Ok(())
}
async fn outbounds(ctl: &Ctl, verb: Option<OutboundVerb>) -> Result<()> {
match verb.unwrap_or(OutboundVerb::List) {
OutboundVerb::List => {
let r = ctl.call(Request::Outbounds).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
let inv = &r["inventory"];
let pinned = inv["pinned"].as_str().unwrap_or("");
for t in inv["tags"].as_array().into_iter().flatten() {
let t = t.as_str().unwrap_or("");
let mut notes = Vec::new();
if t == pinned {
notes.push("pinned".to_owned());
}
if inv["disabled"].as_array().is_some_and(|d| d.iter().any(|x| x == t)) {
notes.push("disabled".into());
}
if let Some(h) = inv["detours"][t].as_str() {
notes.push(format!("through {h}"));
}
println!("{t:32} {:20} {}", inv["sources"][t].as_str().unwrap_or(""), notes.join(", "));
}
for (g, info) in inv["groups"].as_object().into_iter().flatten() {
let members: Vec<&str> = info["members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect();
println!("{g:32} {:20} {}", format!("group, {}", info["strategy"].as_str().unwrap_or("")), members.join(" "));
}
}
OutboundVerb::Add { args, detour } => {
let (tag, text) = match args.as_slice() {
[link] => {
let link = read_arg(link)?;
(edits::link_tag(&link), link)
}
[tag, link] => (tag.clone(), read_arg(link)?),
_ => bail!("usage: proxy outbounds add [tag] <link|->"),
};
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| edits::remove_outbound(c, &tag)).await?;
println!("removed {tag}");
}
OutboundVerb::Disable { tag } => {
ctl.call(Request::Disable { tag, disabled: true }).await?;
}
OutboundVerb::Enable { tag } => {
ctl.call(Request::Disable { tag, disabled: false }).await?;
}
OutboundVerb::Test { tags } => {
let r = ctl.call(Request::Test { tags }).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
for t in r.as_array().into_iter().flatten() {
match t["delay"].as_u64() {
Some(d) => println!("{:32} {d} ms", t["tag"].as_str().unwrap_or("")),
None => println!("{:32} {}", t["tag"].as_str().unwrap_or(""), t["error"].as_str().unwrap_or("failed")),
}
}
}
OutboundVerb::Link { tag } => {
let r = ctl.call(Request::Outbounds).await?;
match r["inventory"]["links"][&tag].as_str() {
Some(l) => println!("{l}"),
None => bail!("no link for '{tag}' (it has none, or you lack the secrets scope)"),
}
}
}
Ok(())
}
async fn subs(ctl: &Ctl, verb: Option<SubsVerb>) -> Result<()> {
match verb.unwrap_or(SubsVerb::List) {
SubsVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for s in c["config"]["proxy"]["subscriptions"].as_array().into_iter().flatten() {
println!("{}", s["tag"].as_str().unwrap_or(""));
}
}
SubsVerb::Update { tag } => {
let r = ctl.call(Request::SubsUpdate { tag }).await?;
for s in r.as_array().into_iter().flatten() {
match s["links"].as_u64() {
Some(n) => println!("{}: {n} links", s["tag"].as_str().unwrap_or("")),
None => println!("{}: {}", s["tag"].as_str().unwrap_or(""), s["error"].as_str().unwrap_or("failed")),
}
}
}
SubsVerb::Add { args } => {
let (tag, url) = match args.as_slice() {
[url] => {
let url = read_arg(url)?;
(edits::subscription_tag(&url), url)
}
[tag, url] => (tag.clone(), read_arg(url)?),
_ => bail!("usage: proxy subs add [tag] <url|->"),
};
ctl.edit(|c| edits::add_subscription(c, &tag, &url)).await?;
println!("added {tag}; fetching it");
}
SubsVerb::Rm { tag } => {
ctl.edit(|c| edits::remove_subscription(c, &tag)).await?;
}
}
Ok(())
}
async fn rules(ctl: &Ctl, verb: Option<RulesVerb>) -> Result<()> {
match verb.unwrap_or(RulesVerb::List) {
RulesVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for (i, r) in c["config"]["proxy"]["routing"]["rules"].as_array().into_iter().flatten().enumerate() {
let name = r["name"].as_str().map(str::to_owned).unwrap_or_else(|| format!("#{i}"));
let mut matches = Vec::new();
for (k, prefix) in [("domains", ""), ("ips", ""), ("geosites", "geosite:"), ("geoips", "geoip:"), ("ruleSets", "ruleset:"), ("processNames", "process:")] {
for v in r[k].as_array().into_iter().flatten() {
matches.push(format!("{prefix}{}", v.as_str().unwrap_or("")));
}
}
println!(
"{:4} {:20} -> {:16} {}{}",
r["priority"].as_i64().unwrap_or(100),
name,
r["outbound"].as_str().unwrap_or(""),
matches.join(" "),
if r["disabled"] == true { " (disabled)" } else { "" }
);
}
}
RulesVerb::Add { target, matches, name, priority } => {
if matches.is_empty() {
bail!("usage: proxy rules add <target> <match...>");
}
ctl.edit(|c| edits::add_rule(c, &target, &matches, name.as_deref(), priority)).await?;
}
RulesVerb::Rm { name } => {
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?;
}
}
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| {
edits::set_proxy_enabled(c, true);
Ok(())
})
.await?;
ctl.call(Request::Start { unit: "proxy-suite-socks".into() }).await?;
}
ProxyVerb::Off => {
ctl.call(Request::Stop { unit: "proxy-suite-socks".into() }).await?;
}
ProxyVerb::Outbounds { verb } => outbounds(ctl, verb).await?,
ProxyVerb::Pin { tag, group } => {
ctl.call(Request::Pin { tag: Some(tag), group }).await?;
}
ProxyVerb::Unpin { group } => {
ctl.call(Request::Pin { tag: None, group }).await?;
}
ProxyVerb::Mode { mode: None } => {
let s = ctl.call(Request::Status).await?;
println!("{}", s["proxy"]["mode"].as_str().unwrap_or("default"));
}
ProxyVerb::Mode { mode } => {
ctl.call(Request::Mode { mode }).await?;
}
ProxyVerb::Subs { verb } => subs(ctl, verb).await?,
ProxyVerb::Rules { verb } => rules(ctl, verb).await?,
ProxyVerb::Rulesets { verb } => match verb.unwrap_or(RulesetsVerb::List) {
RulesetsVerb::List => {
let c = ctl.call(Request::ConfigGet).await?;
for (name, rs) in c["config"]["proxy"]["routing"]["ruleSets"].as_object().into_iter().flatten() {
println!("{name:24} {}", rs["url"].as_str().unwrap_or(""));
}
}
RulesetsVerb::Update => {
let r = ctl.call(Request::RuleSetsUpdate).await?;
for x in r.as_array().into_iter().flatten() {
println!("{:32} {}", x["tag"].as_str().unwrap_or(""), x["error"].as_str().unwrap_or("ok"));
}
}
},
ProxyVerb::Tun { verb } => match verb.unwrap_or(OnOff::Status) {
OnOff::Status => {
let s = ctl.call(Request::Status).await?;
println!("{}", if s["proxy"]["tun"] == true { "on" } else { "off" });
}
OnOff::On => {
ctl.edit(|c| {
edits::set_tun_enabled(c, true);
Ok(())
})
.await?;
ctl.call(Request::Start { unit: "proxy-suite-tun".into() }).await?;
}
OnOff::Off => {
ctl.call(Request::Stop { unit: "proxy-suite-tun".into() }).await?;
}
},
ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?),
}
Ok(())
}
async fn zapret(ctl: &Ctl, verb: Option<ZapretVerb>) -> Result<()> {
match verb.unwrap_or(ZapretVerb::Status) {
ZapretVerb::Status => {
let s = ctl.call(Request::Status).await?;
let z = &s["zapret"];
if ctl.json {
ctl.print(z);
} else if z["enabled"] == true {
println!("zapret: {} ({}, {})", z["state"].as_str().unwrap_or("?"), z["engine"].as_str().unwrap_or("?"), z["preset"].as_str().unwrap_or("?"));
} else {
println!("zapret: off");
}
}
v @ (ZapretVerb::On | ZapretVerb::Off) => {
let on = matches!(v, ZapretVerb::On);
ctl.edit(|c| {
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| {
edits::set_zapret_preset(c, &name);
Ok(())
})
.await?;
}
ZapretVerb::GameFilter { filter } => {
// Checked before asking the service for anything.
edits::set_game_filter(&mut Value::Null, &filter)?;
ctl.edit(|c| edits::set_game_filter(c, &filter)).await?;
}
}
Ok(())
}
async fn components(ctl: &Ctl, verb: Option<ComponentsVerb>) -> Result<()> {
match verb.unwrap_or(ComponentsVerb::List) {
ComponentsVerb::List => {
let r = ctl.call(Request::Components).await?;
if ctl.json {
ctl.print(&r);
return Ok(());
}
for c in r.as_array().into_iter().flatten() {
let installed = c["installed"].as_str().unwrap_or("not installed");
let want = c["version"].as_str().unwrap_or("");
let note = if installed == want { "" } else { " (update with proxy-ctl components install)" };
println!("{:14} {:22} installed {installed}{note}", c["name"].as_str().unwrap_or(""), want);
}
}
ComponentsVerb::Install { names } => {
let r = ctl.call(Request::ComponentsInstall { names }).await?;
for c in r.as_array().into_iter().flatten() {
match c["error"].as_str() {
Some(e) => println!("{}: {e}", c["name"].as_str().unwrap_or("")),
None => println!("{} {} installed", c["name"].as_str().unwrap_or(""), c["version"].as_str().unwrap_or("")),
}
}
}
}
Ok(())
}
async fn real_main() -> Result<()> {
let cli = Cli::parse();
let addr = match cli.socket {
Some(s) if cfg!(windows) => Address::Pipe(s),
Some(s) => Address::Unix(s.into()),
None => Address::default_for_platform(),
};
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 } => {
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?;
ctl.print(&c["config"]);
}
ConfigVerb::Set { file } => {
let config = read_file_arg(&file)?;
let r = ctl.call(Request::ConfigSet { config, base: None }).await?;
println!("revision {}", r["revision"]);
}
ConfigVerb::Validate { file } => {
let r = ctl.call(Request::ConfigValidate { config: read_file_arg(&file)? }).await?;
let issues = r["issues"].as_array().cloned().unwrap_or_default();
if issues.is_empty() {
println!("valid");
}
for i in issues {
println!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or(""));
}
}
},
}
Ok(())
}
fn main() {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime");
if let Err(e) = rt.block_on(real_main()) {
eprintln!("proxy-ctl: {e}");
std::process::exit(1);
}
}
+440
View File
@@ -0,0 +1,440 @@
//! The whole stack, offline: a sing-box Shadowsocks server and a small web server on
//! loopback, the service in console mode with a fresh state directory, proxy-ctl adding the
//! server as an outbound, and a page fetched through the local proxy.
//!
//! Needs sing-box on PATH (the dev shell has it); skipped otherwise. Unix only: the Windows
//! side of the transport is a named pipe.
#![cfg(unix)]
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};
const KEY: &str = "a2tra2tra2tra2tra2traw=="; // base64 of 16 'k's
fn free_port() -> u16 {
TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port()
}
struct Kill(Child);
impl Drop for Kill {
fn drop(&mut self) {
let _ = self.0.kill();
let _ = self.0.wait();
}
}
fn service_binary() -> PathBuf {
let ctl = PathBuf::from(env!("CARGO_BIN_EXE_proxy-ctl"));
let dir = ctl.parent().unwrap();
let status = Command::new(env!("CARGO"))
.args(["build", "-q", "-p", "ps-service", "--bin", "proxy-suite-service"])
.status()
.unwrap();
assert!(status.success());
dir.join("proxy-suite-service")
}
fn ctl(socket: &Path, args: &[&str]) -> (bool, String) {
let out = Command::new(env!("CARGO_BIN_EXE_proxy-ctl")).arg("--socket").arg(socket).args(args).output().unwrap();
(out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr)))
}
/// GET http://<host>:<port>/ through a SOCKS5 proxy, with the name resolved by the proxy.
fn socks_get(proxy: u16, 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, 0])?;
let mut buf = [0u8; 2];
s.read_exact(&mut buf)?;
let mut req = vec![5, 1, 0, 3, host.len() as u8];
req.extend_from_slice(host.as_bytes());
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 wait_for(what: &str, timeout: Duration, mut check: impl FnMut() -> bool) {
let start = Instant::now();
while start.elapsed() < timeout {
if check() {
return;
}
std::thread::sleep(Duration::from_millis(250));
}
panic!("timed out waiting for {what}");
}
#[test]
fn a_page_through_the_whole_stack() {
if Command::new("sing-box").arg("version").output().is_err() {
eprintln!("sing-box is not on PATH: skipping");
return;
}
let dir = std::env::temp_dir().join(format!("ps-e2e-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let (ss_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port());
// The web server.
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: 19\r\n\r\nhello-through-proxy");
}
});
// The Shadowsocks server, which knows web.test as loopback.
let server_cfg = serde_json::json!({
"log": { "level": "warn" },
"dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["127.0.0.1"] } }] },
"inbounds": [{ "type": "shadowsocks", "tag": "ss-in", "listen": "127.0.0.1", "listen_port": ss_port,
"method": "2022-blake3-aes-128-gcm", "password": KEY }],
"outbounds": [{ "type": "direct", "tag": "direct" }],
"route": { "default_domain_resolver": "hosts", "final": "direct" },
});
std::fs::write(dir.join("server.json"), server_cfg.to_string()).unwrap();
let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(Stdio::null()).spawn().unwrap());
// The service, with no outbound yet and nothing to download.
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 },
},
});
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);
// proxy-ctl adds the server; the service renders, checks and starts sing-box.
let link = format!("ss://2022-blake3-aes-128-gcm:{}@127.0.0.1:{ss_port}#Test%20Server", KEY.replace('=', "%3D"));
let (ok, out) = ctl(&socket, &["proxy", "outbounds", "add", &link]);
assert!(ok, "{out}");
assert!(out.contains("added Test-Server"), "{out}");
let start = Instant::now();
while !ctl(&socket, &["status"]).1.contains("proxy: active") {
if start.elapsed() > Duration::from_secs(15) {
panic!(
"the proxy did not come up\nstatus:\n{}\nlogs:\n{}\nservice:\n{}",
ctl(&socket, &["status"]).1,
ctl(&socket, &["logs", "-n", "60"]).1,
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default()
);
}
std::thread::sleep(Duration::from_millis(250));
}
let body = (0..20)
.find_map(|_| {
std::thread::sleep(Duration::from_millis(300));
socks_get(proxy_port, "web.test", web_port).ok()
})
.unwrap_or_else(|| {
panic!(
"no page through the proxy\nservice log:\n{}\nunit log:\n{}",
std::fs::read_to_string(dir.join("service.log")).unwrap_or_default(),
ctl(&socket, &["logs", "-n", "50"]).1
)
});
assert!(body.ends_with("hello-through-proxy"), "{body}");
// The inventory, a pin, and a route mode that sends everything direct, where web.test
// does not resolve.
let (_, list) = ctl(&socket, &["proxy", "outbounds"]);
assert!(list.contains("Test-Server") && list.contains("static"), "{list}");
assert!(ctl(&socket, &["proxy", "pin", "Test-Server"]).0);
assert!(ctl(&socket, &["status"]).1.contains("pinned to Test-Server"));
assert!(ctl(&socket, &["proxy", "mode", "all-bypass"]).0);
std::thread::sleep(Duration::from_secs(2));
assert!(socks_get(proxy_port, "web.test", web_port).map_or(true, |b| !b.ends_with("hello-through-proxy")));
assert!(ctl(&socket, &["proxy", "mode", "default"]).0);
// A bad edit is refused and changes nothing.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "nowhere-real", "example.com"]);
assert!(!ok && out.contains("is not an outbound"), "{out}");
assert!(!ctl(&socket, &["proxy", "rules"]).1.contains("nowhere-real"));
// A good one goes in.
let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "Test-Server", "example.com", "geoip:us", "process:Telegram.exe"]);
assert!(ok, "{out}");
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())
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "ps-ipc"
description = "Proxy Suite for Windows: the service's API and its transport"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
thiserror.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_System_Pipes",
"Win32_System_Threading",
"Win32_System_SystemServices",
] }
[dev-dependencies]
tokio = { workspace = true }
+119
View File
@@ -0,0 +1,119 @@
//! The service's API: what proxy-ctl and the app ask, what it answers, and how the two
//! reach each other. One JSON request per line, answered by one JSON response per line (a
//! log follow answers with many, up to a final one).
//!
//! On Windows the transport is the named pipe `\\.\pipe\proxy-suite`, whose security
//! descriptor admits SYSTEM, Administrators and (with `userControl`) the interactive user.
//! Elsewhere it is a Unix socket, so the whole stack runs on Linux for development.
pub mod transport;
use serde::{Deserialize, Serialize};
use serde_json::Value;
/// The pipe on Windows.
pub const PIPE_NAME: &str = r"\\.\pipe\proxy-suite";
/// Who is asking, as the transport established it (never as the client claims).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Peer {
/// An administrator (elevated on Windows, root elsewhere): every scope, and the
/// admin-only options.
pub admin: bool,
/// The account, for the log.
pub user: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "kebab-case")]
pub enum Request {
/// Units, their state, the proxy's mode.
Status,
/// The configuration. Secrets (links, passwords) need the `secrets` scope.
ConfigGet,
/// Replaces the whole configuration, if it is valid and `base` (a revision from
/// `config-get`) is still current.
ConfigSet { config: Value, base: Option<u64> },
/// Checks a configuration without taking it.
ConfigValidate { config: Value },
/// Runtime state: pins, disabled outbounds, the route mode.
StateGet,
Pin { tag: Option<String>, group: Option<String> },
Disable { tag: String, disabled: bool },
Mode { mode: Option<String> },
/// What the proxy runs: tags, sources, groups, the pick.
Outbounds,
/// The backend configs as rendered last. Secrets scope.
RenderedConfig,
Restart { units: Vec<String> },
Start { unit: String },
Stop { unit: String },
/// The last `lines` of a unit's log (every unit's, interleaved, without one); `follow`
/// keeps the answer open with each new line.
Logs { unit: Option<String>, lines: usize, follow: bool },
/// Refetch subscriptions (all, or one).
SubsUpdate { tag: Option<String> },
/// Refetch rule sets and geodata.
RuleSetsUpdate,
/// Latency of outbounds through the Clash API.
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> },
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Response {
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
#[serde(default, skip_serializing_if = "Value::is_null")]
pub data: Value,
/// More responses follow (a log follow).
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub more: bool,
}
impl Response {
pub fn ok(data: Value) -> Self {
Self { ok: true, error: None, data, more: false }
}
pub fn err(message: impl Into<String>) -> Self {
Self { ok: false, error: Some(message.into()), data: Value::Null, more: false }
}
pub fn partial(data: Value) -> Self {
Self { ok: true, error: None, data, more: true }
}
}
#[derive(Debug, thiserror::Error)]
pub enum IpcError {
#[error("cannot reach the Proxy Suite service ({0}); is it running?")]
Connect(std::io::Error),
#[error("the service closed the connection")]
Closed,
#[error("{0}")]
Io(#[from] std::io::Error),
#[error("bad message: {0}")]
Json(#[from] serde_json::Error),
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn requests_read_as_upstream_verbs() {
let r: Request = serde_json::from_str(r#"{"op":"pin","tag":"nl","group":null}"#).unwrap();
assert_eq!(r, Request::Pin { tag: Some("nl".into()), group: None });
let s = serde_json::to_string(&Request::Logs { unit: None, lines: 50, follow: true }).unwrap();
assert_eq!(s, r#"{"op":"logs","unit":null,"lines":50,"follow":true}"#);
}
}
+326
View File
@@ -0,0 +1,326 @@
//! Line-delimited JSON over a named pipe (Windows) or a Unix socket (elsewhere).
use std::path::PathBuf;
use serde::Serialize;
use serde::de::DeserializeOwned;
use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf};
use crate::{IpcError, Peer, Request, Response};
/// Where the service listens.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Address {
Pipe(String),
Unix(PathBuf),
}
impl Address {
/// `PROXY_SUITE_SOCKET` if set, else the platform's default.
pub fn default_for_platform() -> Self {
if let Ok(s) = std::env::var("PROXY_SUITE_SOCKET") {
return if cfg!(windows) { Address::Pipe(s) } else { Address::Unix(s.into()) };
}
if cfg!(windows) {
Address::Pipe(crate::PIPE_NAME.into())
} else {
Address::Unix(std::env::temp_dir().join("proxy-suite.sock"))
}
}
}
trait Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static {}
impl<T: AsyncRead + AsyncWrite + Send + Unpin + 'static> Stream for T {}
/// One connection, either end.
pub struct Conn {
reader: BufReader<ReadHalf<Box<dyn Stream>>>,
writer: WriteHalf<Box<dyn Stream>>,
identity: Identity,
}
enum Identity {
Client,
#[cfg(unix)]
Unix(Option<u32>),
#[cfg(windows)]
Pipe(isize),
}
impl Conn {
fn new(stream: Box<dyn Stream>, identity: Identity) -> Self {
let (r, w) = tokio::io::split(stream);
Self { reader: BufReader::new(r), writer: w, identity }
}
/// The next message, or `None` once the other end closed.
pub async fn read_json<T: DeserializeOwned>(&mut self) -> Result<Option<T>, IpcError> {
let mut line = String::new();
// A request is a configuration at most: 16 MiB is far past any.
let n = (&mut self.reader).take(16 * 1024 * 1024).read_line(&mut line).await?;
if n == 0 {
return Ok(None);
}
Ok(Some(serde_json::from_str(line.trim_end())?))
}
pub async fn write_json<T: Serialize>(&mut self, value: &T) -> Result<(), IpcError> {
let mut line = serde_json::to_vec(value)?;
line.push(b'\n');
self.writer.write_all(&line).await?;
self.writer.flush().await?;
Ok(())
}
/// Who the other end is. On Windows the client must have sent its first message: only
/// then can the server impersonate it.
pub fn peer(&self) -> Peer {
match &self.identity {
Identity::Client => Peer { admin: false, user: "client".into() },
#[cfg(unix)]
Identity::Unix(uid) => Peer {
admin: *uid == Some(0),
user: uid.map_or_else(|| "unknown".into(), |u| format!("uid {u}")),
},
#[cfg(windows)]
Identity::Pipe(handle) => windows::peer(*handle),
}
}
}
/// The listening end.
pub struct Server {
#[cfg(unix)]
listener: tokio::net::UnixListener,
#[cfg(windows)]
next: tokio::net::windows::named_pipe::NamedPipeServer,
#[cfg(windows)]
name: String,
#[cfg(windows)]
sddl: String,
}
impl Server {
/// Listens on `address`. `interactive`: whether signed-in users may connect, besides
/// SYSTEM and Administrators (`userControl.enable`); on Unix the socket's mode does it.
pub fn bind(address: &Address, interactive: bool) -> std::io::Result<Self> {
match address {
#[cfg(unix)]
Address::Unix(path) => {
use std::os::unix::fs::PermissionsExt;
let _ = std::fs::remove_file(path);
let listener = tokio::net::UnixListener::bind(path)?;
std::fs::set_permissions(path, std::fs::Permissions::from_mode(if interactive { 0o666 } else { 0o600 }))?;
Ok(Self { listener })
}
#[cfg(windows)]
Address::Pipe(name) => {
let sddl = windows::sddl(interactive);
let next = windows::create(name, &sddl, true)?;
Ok(Self { next, name: name.clone(), sddl })
}
#[allow(unreachable_patterns)]
_ => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "this address does not exist on this platform")),
}
}
pub async fn accept(&mut self) -> std::io::Result<Conn> {
#[cfg(unix)]
{
let (stream, _) = self.listener.accept().await?;
let uid = stream.peer_cred().ok().map(|c| c.uid());
Ok(Conn::new(Box::new(stream), Identity::Unix(uid)))
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
self.next.connect().await?;
let connected = std::mem::replace(&mut self.next, windows::create(&self.name, &self.sddl, false)?);
let handle = connected.as_raw_handle() as isize;
Ok(Conn::new(Box::new(connected), Identity::Pipe(handle)))
}
}
}
pub async fn connect(address: &Address) -> Result<Conn, IpcError> {
match address {
#[cfg(unix)]
Address::Unix(path) => {
let stream = tokio::net::UnixStream::connect(path).await.map_err(IpcError::Connect)?;
Ok(Conn::new(Box::new(stream), Identity::Client))
}
#[cfg(windows)]
Address::Pipe(name) => {
use tokio::net::windows::named_pipe::ClientOptions;
let client = loop {
match ClientOptions::new().open(name) {
Ok(c) => break c,
// Every instance busy: the next is a moment away.
Err(e) if e.raw_os_error() == Some(231) => tokio::time::sleep(std::time::Duration::from_millis(50)).await,
Err(e) => return Err(IpcError::Connect(e)),
}
};
Ok(Conn::new(Box::new(client), Identity::Client))
}
#[allow(unreachable_patterns)]
_ => Err(IpcError::Connect(std::io::Error::new(std::io::ErrorKind::Unsupported, "no such transport here"))),
}
}
/// One request, its one answer.
pub async fn call(address: &Address, request: &Request) -> Result<Response, IpcError> {
let mut conn = connect(address).await?;
conn.write_json(request).await?;
conn.read_json().await?.ok_or(IpcError::Closed)
}
/// One request, every answer until the last (a log follow), each handed to `each`.
pub async fn stream(address: &Address, request: &Request, mut each: impl FnMut(Response) -> bool) -> Result<(), IpcError> {
let mut conn = connect(address).await?;
conn.write_json(request).await?;
while let Some(response) = conn.read_json::<Response>().await? {
let more = response.more;
if !each(response) || !more {
break;
}
}
Ok(())
}
#[cfg(windows)]
mod windows {
use std::ffi::c_void;
use std::ptr::null_mut;
use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions};
use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE, LocalFree, TRUE};
use windows_sys::Win32::Security::Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1,
};
use windows_sys::Win32::Security::{
CheckTokenMembership, CreateWellKnownSid, GetTokenInformation, LookupAccountSidW, RevertToSelf,
SECURITY_ATTRIBUTES, SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid,
};
use windows_sys::Win32::System::Pipes::ImpersonateNamedPipeClient;
use windows_sys::Win32::System::Threading::{GetCurrentThread, OpenThreadToken};
use crate::Peer;
/// SYSTEM and Administrators get everything; the interactive user read and write.
pub fn sddl(interactive: bool) -> String {
let mut s = String::from("D:P(A;;GA;;;SY)(A;;GA;;;BA)");
if interactive {
s.push_str("(A;;GRGW;;;IU)");
}
s
}
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(std::iter::once(0)).collect()
}
pub fn create(name: &str, sddl: &str, first: bool) -> std::io::Result<NamedPipeServer> {
let sddl_w = wide(sddl);
let mut descriptor: *mut c_void = null_mut();
// SAFETY: a NUL-terminated string in, a descriptor LocalFree'd below out.
let ok = unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl_w.as_ptr(), SDDL_REVISION_1, &mut descriptor, null_mut())
};
if ok == 0 {
return Err(std::io::Error::last_os_error());
}
let mut attrs = SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<SECURITY_ATTRIBUTES>() as u32,
lpSecurityDescriptor: descriptor,
bInheritHandle: FALSE,
};
// SAFETY: attrs and the descriptor it points at outlive the call.
let server = unsafe {
ServerOptions::new()
// The first instance: nobody else may have made the pipe first (squatting).
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(name, &mut attrs as *mut _ as *mut c_void)
};
// SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW.
unsafe { LocalFree(descriptor) };
server
}
/// The client of the pipe, impersonated to read its token: an administrator only when
/// its token holds Administrators enabled (elevated), never as it claims.
pub fn peer(pipe: isize) -> Peer {
let unknown = Peer { admin: false, user: "unknown".into() };
// SAFETY: the pipe handle is live for the connection; the impersonation is undone
// before anything else runs on this thread.
unsafe {
if ImpersonateNamedPipeClient(pipe as HANDLE) == 0 {
return unknown;
}
let mut token: HANDLE = null_mut();
let opened = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token);
RevertToSelf();
if opened == 0 {
return unknown;
}
let mut sid = [0u8; 68];
let mut size = sid.len() as u32;
let mut admin = 0;
if CreateWellKnownSid(WinBuiltinAdministratorsSid, null_mut(), sid.as_mut_ptr() as *mut c_void, &mut size) != 0 {
CheckTokenMembership(token, sid.as_mut_ptr() as *mut c_void, &mut admin);
}
let user = token_user(token).unwrap_or_else(|| "unknown".into());
CloseHandle(token);
Peer { admin: admin != 0, user }
}
}
unsafe fn token_user(token: HANDLE) -> Option<String> {
let mut buf = vec![0u8; 256];
let mut len = 0u32;
// SAFETY: buf is as long as said.
if unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) } == 0 {
return None;
}
let user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) };
let mut name = vec![0u16; 256];
let mut domain = vec![0u16; 256];
let (mut nlen, mut dlen) = (name.len() as u32, domain.len() as u32);
let mut kind: SID_NAME_USE = 0;
// SAFETY: the SID points into buf, which is alive; the buffers are as long as said.
let ok = unsafe {
LookupAccountSidW(null_mut(), user.User.Sid, name.as_mut_ptr(), &mut nlen, domain.as_mut_ptr(), &mut dlen, &mut kind)
};
if ok == 0 {
return None;
}
let name = String::from_utf16_lossy(&name[..nlen as usize]);
let domain = String::from_utf16_lossy(&domain[..dlen as usize]);
Some(if domain.is_empty() { name } else { format!("{domain}\\{name}") })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[cfg(unix)]
#[tokio::test]
async fn a_round_trip_over_a_socket() {
let path = std::env::temp_dir().join(format!("ps-ipc-test-{}.sock", std::process::id()));
let address = Address::Unix(path.clone());
let mut server = Server::bind(&address, true).unwrap();
let handle = tokio::spawn(async move {
let mut conn = server.accept().await.unwrap();
let req: Request = conn.read_json().await.unwrap().unwrap();
let peer = conn.peer();
conn.write_json(&Response::ok(serde_json::json!({ "echo": req, "uid": peer.user }))).await.unwrap();
});
let resp = call(&address, &Request::Status).await.unwrap();
assert!(resp.ok);
assert_eq!(resp.data["echo"]["op"], "status");
assert!(resp.data["uid"].as_str().unwrap().starts_with("uid "));
handle.await.unwrap();
let _ = std::fs::remove_file(path);
}
}
+47
View File
@@ -0,0 +1,47 @@
[package]
name = "ps-service"
description = "Proxy Suite for Windows: the service that runs the backends"
version.workspace = true
edition.workspace = true
license.workspace = true
[[bin]]
name = "proxy-suite-service"
path = "src/main.rs"
[dependencies]
ps-core.workspace = true
ps-ipc.workspace = true
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
clap.workspace = true
reqwest.workspace = true
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
windows-sys = { workspace = true, features = [
"Win32_Foundation",
"Win32_Security",
"Win32_System_JobObjects",
"Win32_Security_Authorization",
"Win32_Storage_FileSystem",
"Win32_System_Registry",
"Win32_UI_WindowsAndMessaging",
"Win32_System_Threading",
"Win32_Networking_WinInet",
] }
[target.'cfg(target_os = "linux")'.dependencies]
libc = "0.2"
+574
View File
@@ -0,0 +1,574 @@
//! The API: who may do what, and doing it.
use ps_core::config::{Config, Issue, Scope, Severity, privileged_changes, validate};
use ps_core::render::RouteMode;
use ps_ipc::transport::{Conn, Server};
use ps_ipc::{Peer, Request, Response};
use serde_json::{Value, json};
use crate::service::{self, Shared};
/// What stands in for a secret a caller may not read. Sent back unchanged, it keeps the
/// value it hides.
pub const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}";
/// Option paths holding secrets (`*`: any key or list entry).
const SECRET_PATHS: [&str; 19] = [
"proxy.outbounds.*.url",
"proxy.outbounds.*.singBoxJson",
"proxy.outbounds.*.xrayJson",
"proxy.subscriptions.*.url",
"proxy.listener.auth.password",
"amneziaWg.profiles.*.config",
"amneziaWg.profiles.*.vpn",
"amneziaWg.profiles.*.settings.privateKey",
"amneziaWg.profiles.*.settings.peers.*.presharedKey",
"amneziaWg.profiles.*.settings.obfuscation.headerProtectionKey",
"warp.config",
"warp.devices.*.config",
"tgWsProxy.secret",
"inbounds.users.*.uuid",
"inbounds.users.*.password",
"inbounds.listeners.*.serverPassword",
"inbounds.listeners.*.reality.privateKey",
"inbounds.listeners.*.hysteria.salamander.password",
"inbounds.listeners.*.xrayJson",
];
fn redact_at(value: &mut Value, path: &[&str]) {
let Some((head, rest)) = path.split_first() else {
if !value.is_null() {
*value = REDACTED.into();
}
return;
};
match value {
Value::Object(map) => {
if *head == "*" {
map.values_mut().for_each(|v| redact_at(v, rest));
} else if let Some(v) = map.get_mut(*head) {
redact_at(v, rest);
}
}
Value::Array(list) if *head == "*" => list.iter_mut().for_each(|v| redact_at(v, rest)),
_ => {}
}
}
pub fn redact(config: &Config) -> Value {
let mut v = serde_json::to_value(config).expect("the config serializes");
for p in SECRET_PATHS {
redact_at(&mut v, &p.split('.').collect::<Vec<_>>());
}
v
}
/// The entry of `old` a list entry of `new` stands for: by its tag or name, else its index.
fn counterpart<'a>(old: &'a [Value], new: &Value, index: usize) -> Option<&'a Value> {
for key in ["tag", "name"] {
if let Some(id) = new.get(key).filter(|v| v.is_string()) {
return old.iter().find(|o| o.get(key) == Some(id));
}
}
old.get(index)
}
fn unredact_at(new: &mut Value, old: Option<&Value>, path: &[&str]) {
let Some((head, rest)) = path.split_first() else {
if new.as_str() == Some(REDACTED) {
*new = old.cloned().unwrap_or(Value::Null);
}
return;
};
match new {
Value::Object(map) => {
let old_map = old.and_then(Value::as_object);
if *head == "*" {
for (k, v) in map.iter_mut() {
unredact_at(v, old_map.and_then(|m| m.get(k)), rest);
}
} else if let Some(v) = map.get_mut(*head) {
unredact_at(v, old_map.and_then(|m| m.get(*head)), rest);
}
}
Value::Array(list) if *head == "*" => {
let old_list = old.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
for (i, v) in list.iter_mut().enumerate() {
let o = counterpart(old_list, v, i).cloned();
unredact_at(v, o.as_ref(), rest);
}
}
_ => {}
}
}
/// `new` with every placeholder replaced by the value it hid in `old`.
pub fn unredact(new: &mut Value, old: &Config) {
let old = serde_json::to_value(old).expect("the config serializes");
for p in SECRET_PATHS {
unredact_at(new, Some(&old), &p.split('.').collect::<Vec<_>>());
}
}
/// Whether `peer` may use `scope`, under `cfg.userControl`.
fn allowed(cfg: &Config, peer: &Peer, scope: Option<Scope>) -> Result<(), String> {
if peer.admin {
return Ok(());
}
let Some(scope) = scope else { return Ok(()) };
let uc = &cfg.user_control;
if !uc.enable {
return Err("this needs an administrator (userControl is off)".into());
}
if uc.scopes.is_empty() || uc.scopes.contains(&scope) {
Ok(())
} else {
Err(format!("this needs the {scope:?} scope, which userControl does not give").to_lowercase())
}
}
fn scope_of(req: &Request) -> Option<Scope> {
match req {
Request::ConfigSet { .. } => Some(Scope::Config),
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 { .. } | Request::TgLinks => Some(Scope::Secrets),
Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services),
_ => None,
}
}
fn has_secrets(cfg: &Config, peer: &Peer) -> bool {
allowed(cfg, peer, Some(Scope::Secrets)).is_ok()
}
fn issues_json(issues: &[Issue]) -> Value {
serde_json::to_value(issues).unwrap()
}
/// Serves the API until the process ends.
pub async fn serve(mut server: Server, shared: Shared) {
loop {
match server.accept().await {
Ok(conn) => {
let shared = shared.clone();
tokio::spawn(async move { connection(conn, shared).await });
}
Err(e) => {
tracing::warn!("accepting a client: {e}");
tokio::time::sleep(std::time::Duration::from_millis(200)).await;
}
}
}
}
async fn connection(mut conn: Conn, shared: Shared) {
loop {
let req: Request = match conn.read_json().await {
Ok(Some(r)) => r,
Ok(None) => return,
Err(e) => {
let _ = conn.write_json(&Response::err(format!("bad request: {e}"))).await;
return;
}
};
let peer = conn.peer();
// Every request, streamed or not, is authorized here before anything is done for it.
let denied = {
let s = shared.lock().await;
allowed(s.cfg(), &peer, scope_of(&req)).err()
};
if let Some(e) = denied {
if conn.write_json(&Response::err(e)).await.is_err() {
return;
}
continue;
}
if let Request::Logs { unit, lines, follow: true } = &req {
follow_logs(&mut conn, &shared, unit.clone(), *lines).await;
return;
}
let resp = handle(req, &peer, &shared).await;
if conn.write_json(&resp).await.is_err() {
return;
}
}
}
async fn follow_logs(conn: &mut Conn, shared: &Shared, unit: Option<String>, lines: usize) {
let (backlog, mut feed) = {
let s = shared.lock().await;
(s.sup.tail(unit.as_deref(), lines), s.sup.subscribe())
};
for line in backlog {
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
return;
}
}
loop {
match feed.recv().await {
Ok(line) if unit.as_ref().is_none_or(|u| *u == line.unit) => {
if conn.write_json(&Response::partial(json!(line))).await.is_err() {
return;
}
}
Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
Err(_) => return,
}
}
}
/// Does what `req` asks; the caller has authorized it (`connection`).
pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response {
match req {
Request::Status => Response::ok(shared.lock().await.status()),
Request::ConfigGet => {
let s = shared.lock().await;
let config = if has_secrets(s.cfg(), peer) { serde_json::to_value(s.cfg()).unwrap() } else { redact(s.cfg()) };
Response::ok(json!({ "config": config, "revision": s.store.revision, "redacted": !has_secrets(s.cfg(), peer) }))
}
Request::ConfigValidate { config } => match serde_json::from_value::<Config>(config) {
Ok(cfg) => Response::ok(json!({ "issues": issues_json(&validate(&cfg)) })),
Err(e) => Response::err(format!("not a configuration: {e}")),
},
Request::ConfigSet { mut config, base } => {
let mut s = shared.lock().await;
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) {
Ok(c) => c,
Err(e) => return Response::err(format!("not a configuration: {e}")),
};
let issues = validate(&new);
if issues.iter().any(|i| i.severity == Severity::Error) {
return Response { ok: false, error: Some("the configuration has errors".into()), data: json!({ "issues": issues_json(&issues) }), more: false };
}
if !peer.admin {
let privileged = privileged_changes(s.cfg(), &new);
if !privileged.is_empty() {
return Response {
ok: false,
error: Some(format!("only an administrator may change {}", privileged.join(", "))),
data: json!({ "privileged": privileged }),
more: false,
};
}
}
let subs_before: Vec<String> = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).collect();
if let Err(e) = s.store.save_config(new) {
return Response::err(format!("cannot save the configuration: {e}"));
}
tracing::info!("configuration revision {} set by {}", s.store.revision, peer.user);
let new_subs: Vec<String> =
s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).filter(|t| !subs_before.contains(t)).collect();
let applied = s.apply().await;
let revision = s.store.revision;
drop(s);
// A new subscription is fetched at once, as upstream fetches on first start.
for tag in new_subs {
let shared = shared.clone();
tokio::spawn(async move { service::update_subscriptions(&shared, Some(&tag)).await });
}
{
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),
"applied": applied.as_ref().map(|_| true).unwrap_or(false),
"error": applied.err().map(|e| e.to_string()),
}))
}
Request::StateGet => Response::ok(serde_json::to_value(&shared.lock().await.store.state).unwrap()),
Request::Pin { tag, group } => {
let mut s = shared.lock().await;
match group {
Some(g) => match tag {
Some(t) => {
s.store.state.group_pins.insert(g, t);
}
None => {
s.store.state.group_pins.remove(&g);
}
},
None => s.store.state.pin = tag,
}
finish_state(&mut s).await
}
Request::Disable { tag, disabled } => {
let mut s = shared.lock().await;
s.store.state.disabled.retain(|t| *t != tag);
if disabled {
s.store.state.disabled.push(tag);
}
finish_state(&mut s).await
}
Request::Mode { mode } => {
let mut s = shared.lock().await;
s.store.state.route_mode = match mode.as_deref() {
None | Some("default") => None,
Some(m) => match serde_json::from_value::<RouteMode>(json!(m)) {
Ok(m) => Some(m),
Err(_) => return Response::err(format!("unknown mode '{m}': default, whitelist, blacklist, all-proxy or all-bypass")),
},
};
finish_state(&mut s).await
}
Request::Outbounds => {
let s = shared.lock().await;
let secrets = has_secrets(s.cfg(), peer);
match &s.last {
Some(r) => {
let mut inv = serde_json::to_value(&r.inventory).unwrap();
if !secrets {
inv["links"] = json!({});
}
Response::ok(json!({ "inventory": inv, "warnings": r.warnings }))
}
None => Response::err(s.last_error.clone().unwrap_or_else(|| "the proxy is not running".into())),
}
}
Request::RenderedConfig => {
let s = shared.lock().await;
match &s.last {
Some(r) => Response::ok(json!({ "sing-box": r.sing_box, "xray": r.xray })),
None => Response::err("nothing rendered yet"),
}
}
Request::Restart { units } => {
let mut s = shared.lock().await;
let names = if units.is_empty() { s.sup.names() } else { units };
let mut missing = Vec::new();
for n in &names {
if !s.sup.restart(n) {
missing.push(n.clone());
}
}
if missing.is_empty() { Response::ok(json!({ "restarted": names })) } else { Response::err(format!("no such unit: {}", missing.join(", "))) }
}
Request::Start { unit } | Request::Stop { unit } if unit != service::SOCKS_UNIT && unit != "proxy-suite-tun" => {
Response::err(format!("unit '{unit}' cannot be started or stopped on its own"))
}
Request::Start { unit } => {
let mut s = shared.lock().await;
if unit == "proxy-suite-tun" {
if !s.cfg().proxy.tun.enable {
return Response::err("the global TUN is off in the configuration (proxy.tun.enable)");
}
s.tun = true;
}
s.proxy_on = true;
applied(s.apply().await)
}
Request::Stop { unit } => {
let mut s = shared.lock().await;
if unit == "proxy-suite-tun" {
s.tun = false;
} else {
s.proxy_on = false;
}
applied(s.apply().await)
}
Request::Logs { unit, lines, .. } => {
let s = shared.lock().await;
Response::ok(json!(s.sup.tail(unit.as_deref(), lines)))
}
Request::SubsUpdate { tag } => {
let results = service::update_subscriptions(shared, tag.as_deref()).await;
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
Ok(n) => json!({ "tag": t, "links": n }),
Err(e) => json!({ "tag": t, "error": e }),
}).collect::<Vec<_>>()))
}
Request::RuleSetsUpdate => {
let results = service::update_rule_sets(shared, false).await;
Response::ok(json!(results.into_iter().map(|(t, r)| match r {
Ok(()) => json!({ "tag": t }),
Err(e) => json!({ "tag": t, "error": e }),
}).collect::<Vec<_>>()))
}
Request::Test { tags } => {
let (clash, tags, url) = {
let s = shared.lock().await;
let Some(r) = &s.last else { return Response::err("the proxy is not running") };
let tags = if tags.is_empty() { r.inventory.exits.clone() } else { tags };
(
crate::clash::Clash::new(s.cfg().proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret),
tags,
s.cfg().proxy.url_test.url.clone(),
)
};
let mut out = Vec::new();
for t in tags {
out.push(match clash.delay(&t, &url, 5000).await {
Ok(ms) => json!({ "tag": t, "delay": ms }),
Err(e) => json!({ "tag": t, "error": e.to_string() }),
});
}
Response::ok(json!(out))
}
Request::Components => {
let s = shared.lock().await;
let bin = s.paths().bin();
let list: Vec<Value> = ps_core::components::manifest()
.components
.iter()
.map(|(name, c)| {
json!({
"name": name,
"version": c.version,
"installed": crate::install::installed_version(&bin, name),
"license": c.license,
"homepage": c.homepage,
"bundled": c.bundled,
})
})
.collect();
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 {
return Response::err("installing components needs an administrator");
}
let manifest = ps_core::components::manifest();
let wanted: Vec<String> = if names.is_empty() {
manifest.components.iter().filter(|(_, c)| !c.bundled).map(|(n, _)| n.clone()).collect()
} else {
names
};
let (bin, cache, routes) = {
let s = shared.lock().await;
(s.paths().bin(), s.paths().root.join("downloads"), s.fetch_routes(true))
};
let mut results = Vec::new();
for name in wanted {
let Some(comp) = manifest.components.get(&name) else {
results.push(json!({ "name": name, "error": "no such component" }));
continue;
};
// What runs from it must let go of its files first.
shared.lock().await.sup.stop_all().await;
let r = crate::install::install(&bin, &name, comp, &routes, &cache).await;
results.push(match r {
Ok(()) => json!({ "name": name, "version": comp.version }),
Err(e) => json!({ "name": name, "error": format!("{e:#}") }),
});
}
let _ = shared.lock().await.apply().await;
Response::ok(json!(results))
}
}
}
fn applied(r: anyhow::Result<()>) -> Response {
match r {
Ok(()) => Response::ok(Value::Null),
Err(e) => Response::err(e.to_string()),
}
}
async fn finish_state(s: &mut tokio::sync::MutexGuard<'_, service::Service>) -> Response {
if let Err(e) = s.store.save_state() {
return Response::err(format!("cannot save the state: {e}"));
}
applied(s.apply().await)
}
#[cfg(test)]
mod tests {
use super::*;
use ps_core::config::Outbound;
#[test]
fn redaction_round_trips_by_tag() {
let mut cfg = Config::default();
cfg.proxy.outbounds = vec![
Outbound { tag: "a".into(), url: Some("hy2://secret-a@a:443".into()), ..Default::default() },
Outbound { tag: "b".into(), url: Some("hy2://secret-b@b:443".into()), ..Default::default() },
];
cfg.proxy.listener.auth.password = Some("pw".into());
let mut shown = redact(&cfg);
assert_eq!(shown["proxy"]["outbounds"][0]["url"], REDACTED);
assert_eq!(shown["proxy"]["listener"]["auth"]["password"], REDACTED);
// The client reorders and adds one; the hidden values follow their tags.
let list = shown["proxy"]["outbounds"].as_array_mut().unwrap();
list.swap(0, 1);
list.push(json!({ "tag": "c", "url": "hy2://new@c:443" }));
unredact(&mut shown, &cfg);
let back: Config = serde_json::from_value(shown).unwrap();
assert_eq!(back.proxy.outbounds[0].url.as_deref(), Some("hy2://secret-b@b:443"));
assert_eq!(back.proxy.outbounds[1].url.as_deref(), Some("hy2://secret-a@a:443"));
assert_eq!(back.proxy.outbounds[2].url.as_deref(), Some("hy2://new@c:443"));
assert_eq!(back.proxy.listener.auth.password.as_deref(), Some("pw"));
}
#[test]
fn following_logs_needs_the_secrets_scope_too() {
assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: true }), Some(Scope::Secrets));
assert_eq!(scope_of(&Request::Logs { unit: None, lines: 10, follow: false }), Some(Scope::Secrets));
}
#[test]
fn scopes_follow_user_control() {
let mut cfg = Config::default();
let user = Peer { admin: false, user: "u".into() };
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
cfg.user_control.scopes = vec![Scope::Routing];
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok());
assert!(allowed(&cfg, &user, Some(Scope::Config)).is_err());
cfg.user_control.enable = false;
assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_err());
assert!(allowed(&cfg, &Peer { admin: true, user: "a".into() }, Some(Scope::Config)).is_ok());
}
}
+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()))
}
+91
View File
@@ -0,0 +1,91 @@
//! sing-box's Clash API on loopback: what selectors pick, and outbound latency.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde_json::Value;
pub struct Clash {
base: String,
secret: String,
http: reqwest::Client,
}
fn encode(segment: &str) -> String {
let mut out = String::new();
for b in segment.bytes() {
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') {
out.push(b as char);
} else {
out.push_str(&format!("%{b:02X}"));
}
}
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()
.no_proxy()
.timeout(Duration::from_secs(20))
.build()
.expect("an HTTP client");
Self { base: format!("http://127.0.0.1:{port}"), secret: secret.to_owned(), http }
}
async fn get(&self, path: &str) -> Result<Value> {
let resp = self.http.get(format!("{}{path}", self.base)).bearer_auth(&self.secret).send().await?;
let status = resp.status();
let body: Value = resp.json().await.unwrap_or(Value::Null);
if !status.is_success() {
bail!("{}", body["message"].as_str().unwrap_or(status.as_str()));
}
Ok(body)
}
/// Every proxy (outbound or group) with what a selector holds now.
pub async fn proxies(&self) -> Result<Value> {
self.get("/proxies").await.map(|v| v["proxies"].clone())
}
/// What `group` (a selector or urltest) uses now.
pub async fn current(&self, group: &str) -> Result<Option<String>> {
let v = self.get(&format!("/proxies/{}", encode(group))).await?;
Ok(v["now"].as_str().map(str::to_owned))
}
/// Switches the selector `group` to `tag`, live.
pub async fn select(&self, group: &str, tag: &str) -> Result<()> {
let resp = self
.http
.put(format!("{}/proxies/{}", self.base, encode(group)))
.bearer_auth(&self.secret)
.json(&serde_json::json!({ "name": tag }))
.send()
.await
.context("the Clash API")?;
if !resp.status().is_success() {
let body: Value = resp.json().await.unwrap_or(Value::Null);
bail!("cannot switch {group} to {tag}: {}", body["message"].as_str().unwrap_or("refused"));
}
Ok(())
}
/// The delay to `url` through `tag`, in milliseconds.
pub async fn delay(&self, tag: &str, url: &str, timeout_ms: u32) -> Result<u32> {
let resp = self
.http
.get(format!("{}/proxies/{}/delay", self.base, encode(tag)))
.bearer_auth(&self.secret)
.query(&[("url", url), ("timeout", &timeout_ms.to_string())])
.send()
.await?;
let status = resp.status();
let body: Value = resp.json().await.unwrap_or(Value::Null);
if !status.is_success() {
bail!("{}", body["message"].as_str().unwrap_or("timed out"));
}
body["delay"].as_u64().map(|d| d as u32).context("no delay in the answer")
}
}
@@ -0,0 +1,69 @@
//! Where the backend programs are.
//!
//! The service installs each into `bin\<component>\` (the component manager); a program
//! found there wins. Elsewhere (development on Linux) the one on PATH is taken.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::SystemTime;
pub struct Components {
bin: PathBuf,
/// Programs verified, by path, with the size and time they had then.
verified: Mutex<HashMap<PathBuf, (u64, SystemTime)>>,
}
impl Components {
pub fn new(bin: PathBuf) -> Self {
Self { bin, verified: Mutex::new(HashMap::new()) }
}
/// `find`, and for an installed one, the check that it is what was installed.
pub fn program(&self, component: &str, name: &str) -> anyhow::Result<PathBuf> {
let path = self
.find(component, name)
.ok_or_else(|| anyhow::anyhow!("{component} is not installed (proxy-ctl components install {component})"))?;
let dir = self.bin.join(component);
if path.starts_with(&dir) {
let meta = std::fs::metadata(&path)?;
let stamp = (meta.len(), meta.modified()?);
if self.verified.lock().unwrap().get(&path) != Some(&stamp) {
crate::install::verify(&dir, &path)?;
self.verified.lock().unwrap().insert(path.clone(), stamp);
}
}
Ok(path)
}
/// The program `name` (without `.exe`) of `component`. On Windows only the protected
/// `bin\` counts: what the service runs, it runs as SYSTEM, and PATH may hold a directory
/// any user can write.
pub fn find(&self, component: &str, name: &str) -> Option<PathBuf> {
let file = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() };
let installed = self.bin.join(component).join(&file);
if installed.is_file() {
return Some(installed);
}
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(&bare)).find(|p| p.is_file())
}
pub fn sing_box(&self) -> anyhow::Result<PathBuf> {
self.program("sing-box", "sing-box")
}
pub fn xray(&self) -> anyhow::Result<PathBuf> {
self.program("xray", "xray")
}
#[allow(dead_code)]
pub fn bin_dir(&self) -> &Path {
&self.bin
}
}
+163
View File
@@ -0,0 +1,163 @@
//! Fetching subscriptions and rule sets: through the local proxy when it runs, else (or
//! when that fails, with `killSwitch.directFallbacks`) directly. Redirects follow upstream's
//! rule: http and https only, never down to http, never nearer to this host.
use std::time::Duration;
use anyhow::{Context, Result, bail};
use ps_core::links::subscription::{self, MAX_SUBSCRIPTION_BYTES, USER_AGENT, url_parts};
/// How to reach the network for a fetch.
#[derive(Debug, Clone)]
pub enum Route {
Direct,
/// The local proxy's mixed listener, with its login.
Proxy { port: u16, login: Option<(String, String)> },
}
fn client(route: &Route) -> Result<reqwest::Client> {
let policy = reqwest::redirect::Policy::custom(|attempt| {
let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default();
let to = attempt.url().as_str().to_owned();
if attempt.previous().len() > 10 {
return attempt.error("too many redirects");
}
match (url_parts::split(&from), url_parts::split(&to)) {
(Ok(f), Ok(t)) => match subscription::redirect_allowed(&f, &t) {
Ok(()) => attempt.follow(),
Err(why) => attempt.error(why),
},
_ => attempt.error("a redirect to an unreadable URL"),
}
});
let mut b = reqwest::Client::builder()
.user_agent(USER_AGENT)
.redirect(policy)
.connect_timeout(Duration::from_secs(15))
.timeout(Duration::from_secs(60));
b = match route {
Route::Direct => b.no_proxy(),
Route::Proxy { port, login } => {
// socks5h: the proxy resolves the name, as it would for an app.
let url = match login {
Some((u, p)) => format!("socks5h://{u}:{p}@127.0.0.1:{port}"),
None => format!("socks5h://127.0.0.1:{port}"),
};
b.proxy(reqwest::Proxy::all(url)?)
}
};
Ok(b.build()?)
}
/// The body of `url`, at most `limit` bytes. The error never quotes the URL: it is a secret.
pub async fn get(url: &str, route: &Route, limit: usize) -> Result<Vec<u8>> {
let scheme = url_parts::split(url).map(|u| u.scheme).unwrap_or_default();
if scheme != "http" && scheme != "https" {
bail!("the URL must be http:// or https://");
}
let mut resp = client(route)?.get(url).send().await.map_err(|e| anyhow::anyhow!(describe(&e)))?;
if !resp.status().is_success() {
bail!("the server answered {}", resp.status());
}
let mut body = Vec::new();
while let Some(chunk) = resp.chunk().await.map_err(|e| anyhow::anyhow!(describe(&e)))? {
body.extend_from_slice(&chunk);
if body.len() > limit {
bail!("the answer is larger than {limit} bytes");
}
}
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() {
"timed out"
} else if e.is_connect() {
"cannot connect"
} else if e.is_redirect() {
"a redirect was refused"
} else if e.is_request() {
"the request failed"
} else {
"the transfer failed"
};
let mut source = std::error::Error::source(e);
let mut detail = String::new();
while let Some(s) = source {
detail = s.to_string();
source = s.source();
}
if detail.is_empty() { kind.into() } else { format!("{kind}: {detail}") }
}
/// A subscription's links: fetched by the first route that works.
pub async fn subscription(url: &str, routes: &[Route]) -> Result<Vec<String>> {
let mut last = None;
for route in routes {
match get(url, route, MAX_SUBSCRIPTION_BYTES).await {
Ok(body) => {
let lines = subscription::decode_subscription(&body);
if lines.is_empty() {
bail!("the subscription is empty");
}
return Ok(lines);
}
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")))
}
/// A rule set to `dest`, written atomically.
pub async fn rule_set(url: &str, routes: &[Route], dest: &std::path::Path) -> Result<()> {
let mut last = None;
for route in routes {
match get(url, route, 64 * 1024 * 1024).await {
Ok(body) => {
crate::paths::write_atomic(dest, &body).with_context(|| format!("writing {}", dest.display()))?;
return Ok(());
}
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")))
}
/// The domain-only copy of a source rule set, for DNS rules: sing-box refuses address
/// matches there.
pub fn domain_only(source: &serde_json::Value) -> serde_json::Value {
const DOMAIN_KEYS: [&str; 4] = ["domain", "domain_suffix", "domain_keyword", "domain_regex"];
let rules: Vec<serde_json::Value> = source["rules"]
.as_array()
.map(|rules| {
rules
.iter()
.filter_map(|r| {
let obj = r.as_object()?;
let kept: serde_json::Map<String, serde_json::Value> =
obj.iter().filter(|(k, _)| DOMAIN_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect();
(!kept.is_empty()).then_some(serde_json::Value::Object(kept))
})
.collect()
})
.unwrap_or_default();
serde_json::json!({ "version": source["version"].as_u64().unwrap_or(1), "rules": rules })
}
+281
View File
@@ -0,0 +1,281 @@
//! Installing components: download, verify, extract, swap in.
use std::io::Read;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::components::{Component, Source};
use sha2::{Digest, Sha256};
use crate::fetch;
fn hex(data: &[u8]) -> String {
let mut h = Sha256::new();
h.update(data);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
/// The archive of `src`, from `cache` if it holds a verified copy, else downloaded there.
pub async fn archive(src: &Source, routes: &[fetch::Route], cache: &Path) -> Result<Vec<u8>> {
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)
&& src.sha256.as_ref().is_none_or(|want| hex(&data) == *want)
{
return Ok(data);
}
let mut last = None;
for route in routes {
match fetch::get(&src.url, route, 512 * 1024 * 1024).await {
Ok(data) => {
if let Some(want) = &src.sha256 {
let got = hex(&data);
if got != *want {
bail!("{} has SHA-256 {got}, not the pinned {want}", src.url);
}
}
crate::paths::write_atomic(&cached, &data)?;
return Ok(data);
}
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it")).context(format!("fetching {}", src.url)))
}
/// 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 seen = std::collections::BTreeSet::new();
let mut n = 0;
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 want = &files[in_archive];
let got = hex(&body);
if got != *want {
bail!("{in_archive} has SHA-256 {got}, not the pinned {want}");
}
seen.insert(in_archive.to_owned());
}
let out = dest.join(&rel);
if let Some(parent) = out.parent() {
std::fs::create_dir_all(parent)?;
}
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();
if !missing.is_empty() {
bail!("the archive lacks {}", missing.iter().map(|s| s.as_str()).collect::<Vec<_>>().join(", "));
}
}
Ok(n)
}
/// The version of `name` installed under `bin`.
pub fn installed_version(bin: &Path, name: &str) -> Option<String> {
std::fs::read_to_string(bin.join(name).join(".version")).ok().map(|s| s.trim().to_owned())
}
/// Puts `comp` into `bin\<name>\`: staged next to it, then swapped in whole, so a failure
/// leaves what was there.
pub async fn install(bin: &Path, name: &str, comp: &Component, routes: &[fetch::Route], cache: &Path) -> Result<()> {
if comp.bundled {
bail!("{name} comes with the release and is not fetched on its own");
}
let staging = bin.join(format!("{name}.staging"));
let _ = std::fs::remove_dir_all(&staging);
std::fs::create_dir_all(&staging)?;
for src in &comp.sources {
let data = archive(src, routes, cache).await?;
let n = extract(src, &data, &staging).with_context(|| format!("unpacking {}", src.url))?;
if n == 0 {
bail!("nothing in {} matched", src.url);
}
}
std::fs::write(staging.join(".version"), &comp.version)?;
// What was installed, by hash: checked again before anything from it runs.
let mut files = std::collections::BTreeMap::new();
record(&staging, &staging, &mut files)?;
std::fs::write(staging.join(".files.json"), serde_json::to_vec_pretty(&files)?)?;
swap(bin, name, &staging)
}
fn record(root: &Path, dir: &Path, out: &mut std::collections::BTreeMap<String, String>) -> Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
let ty = entry.file_type()?;
if ty.is_dir() {
record(root, &path, out)?;
} else if ty.is_file() {
let rel = path.strip_prefix(root)?.to_string_lossy().replace('\\', "/");
if !rel.starts_with('.') {
out.insert(rel, hex(&std::fs::read(&path)?));
}
}
}
Ok(())
}
/// Whether `program` (below `bin\<component>\`) still has the hash it was installed with.
pub fn verify(component_dir: &Path, program: &Path) -> Result<()> {
let files: std::collections::BTreeMap<String, String> = serde_json::from_slice(
&std::fs::read(component_dir.join(".files.json")).context("no record of what was installed (reinstall it)")?,
)?;
let rel = program.strip_prefix(component_dir)?.to_string_lossy().replace('\\', "/");
let want = files.get(&rel).with_context(|| format!("{rel} was not installed with the component"))?;
let got = hex(&std::fs::read(program)?);
if got != *want {
bail!("{} has changed since it was installed (SHA-256 {got}); reinstall the component", program.display());
}
Ok(())
}
fn swap(bin: &Path, name: &str, staging: &Path) -> Result<()> {
let target = bin.join(name);
let old: PathBuf = bin.join(format!("{name}.old"));
let _ = std::fs::remove_dir_all(&old);
if target.exists() {
std::fs::rename(&target, &old).with_context(|| format!("moving the old {name} aside (is it running?)"))?;
}
if let Err(e) = std::fs::rename(staging, &target) {
let _ = std::fs::rename(&old, &target);
return Err(e).context(format!("putting {name} in place"));
}
let _ = std::fs::remove_dir_all(&old);
Ok(())
}
/// For the release: every component that has sources, into `to\<name>\`, with a cache.
pub async fn stage(to: &Path, cache: &Path, only: &[String]) -> Result<()> {
let manifest = ps_core::components::manifest();
std::fs::create_dir_all(to)?;
for (name, comp) in &manifest.components {
if !only.is_empty() && !only.contains(name) {
continue;
}
if comp.bundled {
// Built beside this (tools/build-*.sh): recorded as an install records.
let dir = to.join(name);
match installed_version(to, name) {
Some(v) if v == comp.version => {
let mut files = std::collections::BTreeMap::new();
record(&dir, &dir, &mut files)?;
std::fs::write(dir.join(".files.json"), serde_json::to_vec_pretty(&files)?)?;
println!("{name} {} (built)", comp.version);
}
Some(v) => bail!("{name} in {} is {v}, the manifest wants {}", to.display(), comp.version),
None => println!("{name}: not built (tools/build-{name}.sh); left out"),
}
continue;
}
println!("{name} {}", comp.version);
install(to, name, comp, &[fetch::Route::Direct], cache).await.with_context(|| format!("staging {name}"))?;
}
Ok(())
}
/// Where the release's components are, next to the running program, if it runs from a
/// place only administrators can change (on Windows: Program Files, where `install` puts it).
pub fn bundled_components_dir() -> Option<PathBuf> {
let exe = std::env::current_exe().ok()?;
let dir = exe.parent()?.join("components");
if !dir.is_dir() {
return None;
}
#[cfg(windows)]
{
let program_files = std::env::var_os("ProgramFiles").map(PathBuf::from)?;
if !exe.starts_with(&program_files) {
tracing::warn!("not taking components from {}: the service runs outside Program Files", dir.display());
return None;
}
}
Some(dir)
}
fn copy_tree(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let ty = entry.file_type()?;
let dest = to.join(entry.file_name());
if ty.is_dir() {
copy_tree(&entry.path(), &dest)?;
} else if ty.is_file() {
std::fs::copy(entry.path(), &dest)?;
}
}
Ok(())
}
/// Every file `.files.json` names, with its hash.
fn verify_all(dir: &Path) -> Result<()> {
let files: std::collections::BTreeMap<String, String> =
serde_json::from_slice(&std::fs::read(dir.join(".files.json")).context("no .files.json")?)?;
for (rel, want) in files {
if !ps_core::components::safe_relative(&rel) {
bail!("{rel} is not a plain path");
}
let got = hex(&std::fs::read(dir.join(&rel)).with_context(|| format!("{rel} is missing"))?);
if got != want {
bail!("{rel} does not match its recorded hash");
}
}
Ok(())
}
/// Copies each component of `from` (the release's) into `bin` when `bin` lacks it or holds
/// another version: staged, verified file by file, swapped in. What it did, as lines.
pub fn seed(from: &Path, bin: &Path) -> Vec<String> {
let manifest = ps_core::components::manifest();
let mut notes = Vec::new();
for (name, comp) in &manifest.components {
let src = from.join(name);
if installed_version(from, name).as_deref() != Some(comp.version.as_str()) {
continue;
}
if installed_version(bin, name).as_deref() == Some(comp.version.as_str()) {
continue;
}
let staging = bin.join(format!("{name}.staging"));
let _ = std::fs::remove_dir_all(&staging);
let result = copy_tree(&src, &staging).and_then(|()| verify_all(&staging)).and_then(|()| swap(bin, name, &staging));
match result {
Ok(()) => notes.push(format!("installed {name} {} from the release", comp.version)),
Err(e) => {
let _ = std::fs::remove_dir_all(&staging);
notes.push(format!("could not install {name} from the release: {e:#}"));
}
}
}
notes
}
+63
View File
@@ -0,0 +1,63 @@
//! A Windows Job Object that kills every child with the service: a crash of the service
//! must not leave sing-box or winws running, holding the TUN or WinDivert.
use std::ffi::c_void;
use std::ptr::null;
use windows_sys::Win32::Foundation::{CloseHandle, HANDLE};
use windows_sys::Win32::System::JobObjects::{
AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
JobObjectExtendedLimitInformation, SetInformationJobObject,
};
pub struct Job(HANDLE);
// SAFETY: a job handle may be used from any thread.
unsafe impl Send for Job {}
unsafe impl Sync for Job {}
impl Job {
pub fn new() -> std::io::Result<Self> {
// SAFETY: an anonymous job; the handle is closed in Drop.
unsafe {
let job = CreateJobObjectW(null(), null());
if job.is_null() {
return Err(std::io::Error::last_os_error());
}
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
let ok = SetInformationJobObject(
job,
JobObjectExtendedLimitInformation,
&info as *const _ as *const c_void,
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
);
if ok == 0 {
let err = std::io::Error::last_os_error();
CloseHandle(job);
return Err(err);
}
Ok(Self(job))
}
}
pub fn handle(&self) -> isize {
self.0 as isize
}
}
impl Drop for Job {
fn drop(&mut self) {
// SAFETY: ours, closed once.
unsafe { CloseHandle(self.0) };
}
}
/// Puts a process into the job. A failure is logged, not fatal: the process still runs.
pub fn assign(job: isize, process: isize) {
// SAFETY: both handles are live: the job for the service's life, the process until it
// has been waited on.
if unsafe { AssignProcessToJobObject(job as HANDLE, process as HANDLE) } == 0 {
tracing::warn!("cannot add a child to the job: {}", std::io::Error::last_os_error());
}
}
+182
View File
@@ -0,0 +1,182 @@
//! proxy-suite-service: runs the backends, keeps the configuration, serves the API.
//!
//! As a Windows service it is started by the Service Control Manager (`install` registers
//! 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;
mod install;
#[cfg(windows)]
mod job;
mod paths;
mod service;
mod ssh;
mod store;
mod tg;
mod tor;
mod units;
mod warp;
#[cfg(windows)]
mod winsvc;
mod zapret;
use std::path::PathBuf;
use std::sync::Arc;
use anyhow::{Context, Result};
use clap::{Parser, Subcommand};
use ps_ipc::transport::{Address, Server};
use tokio::sync::Mutex;
#[derive(Parser)]
#[command(name = "proxy-suite-service", version, about = "Proxy Suite's service")]
struct Args {
/// Run in the foreground instead of under the Service Control Manager.
#[arg(long)]
console: bool,
/// Where the configuration and state live (default: %ProgramData%\ProxySuite).
#[arg(long, value_name = "DIR")]
state_dir: Option<PathBuf>,
/// The API's pipe or socket (default: \\.\pipe\proxy-suite, or $TMPDIR/proxy-suite.sock).
#[arg(long, value_name = "ADDRESS")]
socket: Option<String>,
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Subcommand)]
enum Command {
/// Register the Windows service (started at boot, as LocalSystem).
Install,
/// Remove the Windows service.
Uninstall,
/// For building a release: fetch and verify every component into DIR.
#[command(hide = true)]
StageComponents {
#[arg(long)]
to: PathBuf,
#[arg(long)]
cache: PathBuf,
only: Vec<String>,
},
}
fn address(arg: Option<String>) -> Address {
match arg {
Some(s) if cfg!(windows) => Address::Pipe(s),
Some(s) => Address::Unix(s.into()),
None => Address::default_for_platform(),
}
}
/// Everything the service does, until `shutdown` resolves. `ready` is called once the API
/// listens.
pub async fn run(
state_dir: Option<PathBuf>,
socket: Option<String>,
ready: impl FnOnce(),
shutdown: impl std::future::Future<Output = ()>,
) -> Result<()> {
let _ = rustls::crypto::ring::default_provider().install_default();
let paths = state_dir.map(paths::Paths::new).unwrap_or_else(paths::Paths::platform_default);
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
// The components the release carries, next to the program, into bin\ when they are newer.
if let Some(dir) = install::bundled_components_dir() {
for note in install::seed(&dir, &paths.bin()) {
tracing::info!("{note}");
}
}
let svc = service::Service::new(paths.clone()).with_context(|| format!("opening {}", paths.root.display()))?;
let interactive = svc.cfg().user_control.enable;
let shared = Arc::new(Mutex::new(svc));
let addr = address(socket);
let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?;
tracing::info!("listening on {addr:?}, state in {}", paths.root.display());
ready();
if let Err(e) = shared.lock().await.apply().await {
tracing::warn!("not starting the proxy yet: {e}");
}
tokio::spawn(api::serve(server, shared.clone()));
// First fetches: what the configuration needs and has not got yet.
{
let shared = shared.clone();
tokio::spawn(async move {
let missing: Vec<String> = {
let s = shared.lock().await;
s.cfg().proxy.subscriptions.iter().filter(|x| !s.store.subscriptions.contains_key(&x.tag)).map(|x| x.tag.clone()).collect()
};
for tag in missing {
service::update_subscriptions(&shared, Some(&tag)).await;
}
service::update_rule_sets(&shared, true).await;
service::register_warp(&shared).await;
service::timers(shared).await;
});
}
shutdown.await;
tracing::info!("stopping");
shared.lock().await.sup.stop_all().await;
if let Address::Unix(path) = addr {
let _ = std::fs::remove_file(path);
}
Ok(())
}
/// `logs\service.log`, started over (one old one kept) past 5 MiB.
fn service_log(dir: &std::path::Path) -> std::io::Result<std::fs::File> {
let path = dir.join("service.log");
if std::fs::metadata(&path).is_ok_and(|m| m.len() > 5 * 1024 * 1024) {
let _ = std::fs::rename(&path, dir.join("service.log.1"));
}
std::fs::OpenOptions::new().create(true).append(true).open(path)
}
fn main() -> Result<()> {
let args = Args::parse();
let filter = || tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into());
let as_service = cfg!(windows) && !args.console && args.command.is_none();
if as_service {
// Under the Service Control Manager nothing reads stderr: the log is a file.
let paths = args.state_dir.clone().map(paths::Paths::new).unwrap_or_else(paths::Paths::platform_default);
let file = paths.create_all().ok().and_then(|()| service_log(&paths.logs()).ok());
match file {
Some(f) => tracing_subscriber::fmt().with_env_filter(filter()).with_ansi(false).with_writer(std::sync::Mutex::new(f)).init(),
None => tracing_subscriber::fmt().with_env_filter(filter()).with_writer(std::io::stderr).init(),
}
} else {
tracing_subscriber::fmt().with_env_filter(filter()).with_writer(std::io::stderr).init();
}
if let Some(Command::StageComponents { to, cache, only }) = &args.command {
let _ = rustls::crypto::ring::default_provider().install_default();
let rt = tokio::runtime::Runtime::new()?;
return rt.block_on(install::stage(to, cache, only));
}
match args.command {
#[cfg(windows)]
Some(Command::Install) => return winsvc::install(),
#[cfg(windows)]
Some(Command::Uninstall) => return winsvc::uninstall(),
#[cfg(not(windows))]
Some(Command::Install | Command::Uninstall) => anyhow::bail!("there are no services to install off Windows; use --console"),
Some(Command::StageComponents { .. }) => unreachable!(),
None => {}
}
if args.console || !cfg!(windows) {
let rt = tokio::runtime::Runtime::new()?;
return rt.block_on(run(args.state_dir, args.socket, || {}, async {
let _ = tokio::signal::ctrl_c().await;
}));
}
#[cfg(windows)]
{
winsvc::dispatch()
}
#[cfg(not(windows))]
unreachable!()
}
+377
View File
@@ -0,0 +1,377 @@
//! Where the service keeps everything.
//!
//! `%ProgramData%\ProxySuite` on Windows, or `--state-dir` (any platform, for development
//! and tests):
//!
//! ```text
//! config.json the configuration, written only by the service
//! state.json pins, disabled outbounds, the route mode
//! secrets.json what the service generated: the Clash API secret, the hop login
//! subscriptions/ each subscription's links as fetched last
//! rule-sets/ downloaded geodata and rule sets
//! cache/ sing-box's fake IP cache
//! run/ the rendered backend configs
//! logs/ one log per unit
//! bin/ the components (sing-box, xray, winws, …)
//! ```
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct Paths {
pub root: PathBuf,
}
impl Paths {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
/// `%ProgramData%\ProxySuite`, or `/var/lib/proxy-suite-windows` elsewhere.
pub fn platform_default() -> Self {
if cfg!(windows) {
let base = std::env::var_os("ProgramData").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"));
Self::new(base.join("ProxySuite"))
} else {
Self::new("/var/lib/proxy-suite-windows")
}
}
pub fn config(&self) -> PathBuf {
self.root.join("config.json")
}
pub fn state(&self) -> PathBuf {
self.root.join("state.json")
}
pub fn secrets(&self) -> PathBuf {
self.root.join("secrets.json")
}
pub fn subscriptions(&self) -> PathBuf {
self.root.join("subscriptions")
}
pub fn rule_sets(&self) -> PathBuf {
self.root.join("rule-sets")
}
pub fn cache(&self) -> PathBuf {
self.root.join("cache")
}
pub fn run(&self) -> PathBuf {
self.root.join("run")
}
pub fn logs(&self) -> PathBuf {
self.root.join("logs")
}
pub fn bin(&self) -> PathBuf {
self.root.join("bin")
}
/// Creates the tree. On Windows its root is SYSTEM's: created with a protected DACL
/// (SYSTEM and Administrators only) in the same call, or, when it exists, checked through a
/// handle that does not follow reparse points. A root that is a link, has another owner, or
/// lets anyone else in is moved aside, never adopted: ProgramData lets any user make
/// folders, and the service runs what is under `bin\` as SYSTEM.
pub fn create_all(&self) -> std::io::Result<()> {
// Once per process: a second check of a root this process made (and may be writing
// its log into) has nothing to learn, and moving it aside then would lose the log.
// Only a check that passed counts: a failed one is made again, and fails again.
static CHECKED: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
{
let mut checked = CHECKED.lock().unwrap_or_else(|e| e.into_inner());
if !checked.contains(&self.root) {
#[cfg(windows)]
secure::ensure_root(&self.root)?;
#[cfg(not(windows))]
std::fs::create_dir_all(&self.root)?;
checked.push(self.root.clone());
}
}
for dir in [self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] {
std::fs::create_dir_all(dir)?;
}
Ok(())
}
}
/// Writes `data` to `path` through a temporary file and a rename, so a reader never sees half
/// of it and a crash leaves the old one.
pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, data)?;
std::fs::rename(&tmp, path)
}
/// Whether `path` holds exactly `data` already.
pub fn same_content(path: &Path, data: &[u8]) -> bool {
std::fs::read(path).is_ok_and(|old| old == data)
}
#[cfg(windows)]
mod secure {
use std::ffi::c_void;
use std::os::windows::ffi::OsStrExt;
use std::path::Path;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{
CloseHandle, ERROR_ALREADY_EXISTS, ERROR_INVALID_OWNER, ERROR_SUCCESS, GetLastError, HANDLE, INVALID_HANDLE_VALUE, LocalFree,
};
use windows_sys::Win32::Security::Authorization::{
ConvertSecurityDescriptorToStringSecurityDescriptorW, ConvertStringSecurityDescriptorToSecurityDescriptorW,
GetSecurityInfo, SDDL_REVISION_1, SE_FILE_OBJECT, SetSecurityInfo,
};
use windows_sys::Win32::Security::{
ACL, DACL_SECURITY_INFORMATION, GetSecurityDescriptorDacl, IsWellKnownSid,
OWNER_SECURITY_INFORMATION, PROTECTED_DACL_SECURITY_INFORMATION, SECURITY_ATTRIBUTES, WinBuiltinAdministratorsSid,
WinLocalSystemSid,
};
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, CreateDirectoryW, CreateFileW, FILE_ATTRIBUTE_DIRECTORY, FILE_ATTRIBUTE_REPARSE_POINT,
FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT, FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
GetFileInformationByHandle, OPEN_EXISTING, READ_CONTROL, WRITE_DAC, WRITE_OWNER,
};
/// SYSTEM and Administrators may do anything; the owner gets nothing implicit (OWNER
/// RIGHTS: read-control only); nothing is inherited from ProgramData.
const DACL: &str = "D:P(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;RC;;;OW)";
fn wide(s: &std::ffi::OsStr) -> Vec<u16> {
s.encode_wide().chain(Some(0)).collect()
}
struct Descriptor(*mut c_void);
impl Drop for Descriptor {
fn drop(&mut self) {
// SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW.
unsafe { LocalFree(self.0) };
}
}
/// The descriptor, with SYSTEM as owner when `system_owner` (only SYSTEM itself, or a
/// process holding SeRestorePrivilege, may name another owner than itself).
fn descriptor(system_owner: bool) -> std::io::Result<Descriptor> {
let text = if system_owner { format!("O:SY{DACL}") } else { DACL.to_owned() };
let sddl = wide(text.as_ref());
let mut sd = null_mut();
// SAFETY: a NUL-terminated string; the descriptor is freed by Descriptor.
if unsafe { ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) } == 0 {
return Err(std::io::Error::last_os_error());
}
Ok(Descriptor(sd))
}
struct Handle(HANDLE);
impl Drop for Handle {
fn drop(&mut self) {
// SAFETY: ours, closed once.
unsafe { CloseHandle(self.0) };
}
}
pub fn ensure_root(root: &Path) -> std::io::Result<()> {
if let Some(parent) = root.parent() {
std::fs::create_dir_all(parent)?;
}
let mut system_owner = true;
for attempt in 0..4 {
let sd = descriptor(system_owner)?;
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(), &attrs) } != 0 {
return Ok(());
}
// SAFETY: plain call.
match unsafe { GetLastError() } {
ERROR_ALREADY_EXISTS => {}
// Not SYSTEM (an administrator's console): the directory is the caller's own.
ERROR_INVALID_OWNER if system_owner => {
system_owner = false;
continue;
}
_ => return Err(std::io::Error::last_os_error()),
}
match check_existing(root, &sd)? {
true => return Ok(()),
false => {
let aside = root.with_extension(format!("untrusted-{}-{attempt}", std::process::id()));
tracing::warn!("{} is not SYSTEM's own; moving it to {}", root.display(), aside.display());
// A rename moves a link itself, never what it points at.
std::fs::rename(root, &aside)?;
}
}
}
Err(std::io::Error::other(format!("{} keeps being taken over", root.display())))
}
/// Whether the existing `root` may be used: a real directory (no link), owned by SYSTEM
/// or Administrators, letting no one else in. It then gets the protected DACL again.
fn check_existing(root: &Path, sd: &Descriptor) -> std::io::Result<bool> {
let path = wide(root.as_os_str());
// SAFETY: NUL-terminated path; the handle is closed by Handle.
let h = unsafe {
CreateFileW(
path.as_ptr(),
READ_CONTROL | WRITE_DAC | WRITE_OWNER,
FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
null_mut(),
OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
null_mut(),
)
};
if h == INVALID_HANDLE_VALUE {
return Err(std::io::Error::last_os_error());
}
let h = Handle(h);
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
// SAFETY: a live handle and a zeroed struct to fill.
if unsafe { GetFileInformationByHandle(h.0, &mut info) } == 0 {
return Err(std::io::Error::last_os_error());
}
if info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT != 0 || info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY == 0 {
return Ok(false);
}
let mut owner = null_mut();
let mut current = null_mut();
// SAFETY: the handle is live; owner points into `current`, freed below.
let rc = unsafe {
GetSecurityInfo(
h.0, SE_FILE_OBJECT, OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION, &mut owner, null_mut(), null_mut(), null_mut(), &mut current,
)
};
if rc != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(rc as i32));
}
// SAFETY: owner is a SID inside `current`. The service's own account counts: whoever
// runs the service could change its files anyway.
let trusted_owner = unsafe {
IsWellKnownSid(owner, WinLocalSystemSid) != 0 || IsWellKnownSid(owner, WinBuiltinAdministratorsSid) != 0 || is_own_user(owner)
};
let closed = only_trusted_aces(current, own_sid_string().as_deref());
// SAFETY: allocated by GetSecurityInfo.
unsafe { LocalFree(current) };
if !trusted_owner || !closed {
tracing::warn!("existing root: trusted owner {trusted_owner}, closed DACL {closed}");
return Ok(false);
}
// Ours: the protected DACL again, on this same handle.
let (mut present, mut defaulted) = (0, 0);
let mut dacl: *mut ACL = null_mut();
// SAFETY: the DACL points into sd, alive for the call.
let rc = unsafe {
GetSecurityDescriptorDacl(sd.0, &mut present, &mut dacl, &mut defaulted);
SetSecurityInfo(h.0, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION, null_mut(), null_mut(), dacl, null_mut())
};
if rc != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(rc as i32));
}
Ok(true)
}
/// Whether `sid` is this process's own account.
#[allow(clippy::not_unsafe_ptr_arg_deref)]
fn is_own_user(sid: *mut c_void) -> bool {
use windows_sys::Win32::Security::{EqualSid, GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
let mut token: HANDLE = null_mut();
// SAFETY: the current process's token, closed below; buf is as long as said.
unsafe {
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
return false;
}
let token = Handle(token);
let mut buf = vec![0u8; 256];
let mut len = 0;
if GetTokenInformation(token.0, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) == 0 {
return false;
}
let user = &*(buf.as_ptr() as *const TOKEN_USER);
EqualSid(user.User.Sid, sid) != 0
}
}
/// This process's account as an SDDL SID string.
fn own_sid_string() -> Option<String> {
use windows_sys::Win32::Security::Authorization::ConvertSidToStringSidW;
use windows_sys::Win32::Security::{GetTokenInformation, TOKEN_QUERY, TOKEN_USER, TokenUser};
use windows_sys::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
let mut token: HANDLE = null_mut();
// SAFETY: the current process's token, closed by Handle; buf as long as said; the
// string LocalFree'd.
unsafe {
if OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token) == 0 {
return None;
}
let token = Handle(token);
let mut buf = vec![0u8; 256];
let mut len = 0;
if GetTokenInformation(token.0, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) == 0 {
return None;
}
let user = &*(buf.as_ptr() as *const TOKEN_USER);
let mut text = null_mut();
if ConvertSidToStringSidW(user.User.Sid, &mut text) == 0 {
return None;
}
let s = wide_to_string(text);
LocalFree(text as *mut c_void);
Some(s)
}
}
/// SAFETY: `p` is a NUL-terminated wide string.
unsafe fn wide_to_string(p: *const u16) -> String {
let mut n = 0;
// SAFETY: as the caller promises.
unsafe {
while *p.add(n) != 0 {
n += 1;
}
String::from_utf16_lossy(std::slice::from_raw_parts(p, n))
}
}
/// Whether a descriptor's DACL allows only SYSTEM, Administrators, OWNER RIGHTS and this
/// process's own account, inherited entries included (any deny entry is fine).
fn only_trusted_aces(sd: *mut c_void, own: Option<&str>) -> bool {
let mut text = null_mut();
// SAFETY: a valid descriptor in; the string out is LocalFree'd.
if unsafe { ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, DACL_SECURITY_INFORMATION, &mut text, null_mut()) } == 0 {
return false;
}
// SAFETY: a NUL-terminated wide string from the call above.
let s = unsafe { wide_to_string(text) };
unsafe { LocalFree(text as *mut c_void) };
tracing::debug!("existing root's DACL: {s}");
let Some(dacl) = s.strip_prefix("D:") else { return false };
dacl.split('(').skip(1).all(|ace| {
let fields: Vec<&str> = ace.trim_end_matches(')').split(';').collect();
fields.len() >= 6 && (fields[0] != "A" || matches!(fields[5], "SY" | "BA" | "OW") || Some(fields[5]) == own)
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_failed_check_is_made_again() {
let dir = std::env::temp_dir().join(format!("ps-paths-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// A root that cannot be made: the first call fails, and so must every later one.
let root = dir.join("root");
std::fs::write(&root, b"").unwrap();
let paths = Paths::new(&root);
assert!(paths.create_all().is_err());
assert!(paths.create_all().is_err());
std::fs::remove_file(&root).unwrap();
paths.create_all().unwrap();
assert!(paths.bin().is_dir());
std::fs::remove_dir_all(&dir).unwrap();
}
}
+626
View File
@@ -0,0 +1,626 @@
//! The service's state and what it does with it: render, write, check, (re)start, fetch.
use std::collections::BTreeMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use anyhow::{Context, Result};
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};
use tokio::sync::Mutex;
use crate::components::Components;
use crate::fetch;
use crate::paths::{Paths, same_content, write_atomic};
use crate::store::{Store, random_uuid};
use crate::units::{Supervisor, UnitSpec, UnitState};
pub const SOCKS_UNIT: &str = "proxy-suite-socks";
pub const SIDECAR_UNIT: &str = "proxy-suite-xray-sidecar";
pub type Shared = Arc<Mutex<Service>>;
pub struct Service {
pub store: Store,
pub sup: Supervisor,
pub comps: Components,
/// `proxy-ctl proxy off` stops the local proxy until `on` or the next start.
pub proxy_on: bool,
/// The global TUN, on with `proxy.autostart = "tun"` or `proxy-ctl proxy tun on`.
pub tun: bool,
sidecar_secret: String,
pub last: Option<Rendered>,
/// Why the last apply did not take.
pub last_error: Option<String>,
pub last_fetch: BTreeMap<String, SystemTime>,
tcp_timestamps_on: bool,
}
fn digest(data: &[u8]) -> String {
let mut h = Sha256::new();
h.update(data);
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
}
impl Service {
pub fn new(paths: Paths) -> Result<Self> {
let store = Store::open(paths.clone())?;
let tun = store.config.proxy.autostart.is_some() && store.config.proxy.tun.enable;
Ok(Self {
sup: Supervisor::new(paths.logs()),
comps: Components::new(paths.bin()),
proxy_on: true,
tun,
sidecar_secret: random_uuid(),
last: None,
last_error: None,
last_fetch: BTreeMap::new(),
tcp_timestamps_on: false,
store,
})
}
pub fn paths(&self) -> &Paths {
&self.store.paths
}
pub fn cfg(&self) -> &Config {
&self.store.config
}
fn proxy_wanted(&self) -> bool {
let cfg = self.cfg();
cfg.enable && cfg.proxy.enable && self.proxy_on
}
fn env(&self) -> Env {
let paths = self.paths();
let cfg = self.cfg();
// 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
&& let Ok(x) = self.comps.xray()
{
direct.push(x.to_string_lossy().into_owned());
}
if cfg.tg_ws_proxy.enable
&& cfg.tg_ws_proxy.bypass_transparent_proxy
&& let Ok(p) = self.comps.program("tg-ws-proxy", "python/python")
{
direct.push(p.to_string_lossy().into_owned());
}
// wireproxy's tunnels, like the sidecar's, would loop back into the TUN.
if derived_userspace(cfg)
&& let Some(p) = self.comps.find("wireproxy-awg", "wireproxy")
{
direct.push(p.to_string_lossy().into_owned());
}
// 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 {
zapret_direct: ps_core::config::RouteMatch { domains: zd, ips: zi, ..Default::default() },
rule_sets: self.store.rule_set_files(),
empty_rule_set: paths.run().join("empty-rule-set.json").to_string_lossy().into_owned(),
cache_dir: paths.cache().to_string_lossy().into_owned(),
clash_secret: Some(self.store.secrets.clash_secret.clone()),
hop_login: Some((self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone())),
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),
}
}
/// Renders and returns the result, without touching anything.
pub fn render(&self) -> Result<Rendered, render::RenderError> {
let env = self.env();
let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}"));
render::render(&Input {
cfg: self.cfg(),
state: &self.store.state,
subscriptions: &self.store.subscriptions,
env: &env,
read_file: &read,
tun: self.tun && self.cfg().proxy.tun.enable,
})
}
/// Brings the units in line with the configuration: render, write, check, start or
/// restart what changed, stop what is no longer wanted.
pub async fn apply(&mut self) -> Result<()> {
let zapret = self.apply_zapret().await;
if let Err(e) = &zapret {
self.sup.note(crate::zapret::UNIT, format!("proxy-suite: zapret: {e:#}"));
}
let tg = self.apply_tg().await;
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(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<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.tg_ws_proxy.enable {
self.sup.stop(crate::tg::UNIT).await;
return Ok(());
}
let python = self.comps.program("tg-ws-proxy", "python/python")?;
let spec = crate::tg::unit(&cfg, self.paths(), python)?;
self.sup.ensure(spec);
Ok(())
}
async fn apply_zapret(&mut self) -> Result<()> {
let cfg = self.cfg().clone();
if !cfg.enable || !cfg.zapret.enable {
self.sup.stop(crate::zapret::UNIT).await;
return Ok(());
}
if !cfg!(windows) {
self.sup.note(crate::zapret::UNIT, "proxy-suite: zapret runs on Windows only (WinDivert); not started");
return Ok(());
}
#[cfg(windows)]
if let Some((name, what)) = crate::winsvc::windivert_conflict() {
self.sup.stop(crate::zapret::UNIT).await;
anyhow::bail!("the Windows service '{name}' runs DPI bypass with WinDivert already: remove {what}, then turn zapret on again");
}
match cfg.zapret.engine {
ps_core::config::ZapretEngine::DiscordYoutube => {
let program = self.comps.program("zapret", "bin/winws")?;
let spec = crate::zapret::discord_youtube_unit(&cfg, self.paths(), program)?;
if cfg.zapret.tcp_timestamps && !self.tcp_timestamps_on {
match crate::zapret::enable_tcp_timestamps().await {
Ok(()) => self.tcp_timestamps_on = true,
Err(e) => self.sup.note(crate::zapret::UNIT, format!("proxy-suite: warning: {e}")),
}
}
self.sup.ensure(spec);
Ok(())
}
ps_core::config::ZapretEngine::Zapret2 => {
let program = self.comps.program("zapret2", "winws2")?;
let spec = crate::zapret::zapret2_unit(&cfg, self.paths(), program)?;
if cfg.zapret.tcp_timestamps && !self.tcp_timestamps_on {
match crate::zapret::enable_tcp_timestamps().await {
Ok(()) => self.tcp_timestamps_on = true,
Err(e) => self.sup.note(crate::zapret::UNIT, format!("proxy-suite: warning: {e}")),
}
}
self.sup.ensure(spec);
Ok(())
}
}
}
async fn apply_proxy(&mut self) -> Result<()> {
if !self.proxy_wanted() {
self.sup.stop(SOCKS_UNIT).await;
self.sup.stop(SIDECAR_UNIT).await;
self.last_error = None;
return Ok(());
}
let run = self.paths().run();
let empty = run.join("empty-rule-set.json");
if !empty.exists() {
write_atomic(&empty, br#"{"version":1,"rules":[]}"#)?;
}
let rendered = match self.render() {
Ok(r) => r,
Err(e) => {
self.last_error = Some(e.0.clone());
self.sup.note(SOCKS_UNIT, format!("proxy-suite: not starting: {e}"));
return Err(anyhow::anyhow!(e.0));
}
};
for w in &rendered.warnings {
self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}"));
}
let backend = self.cfg().proxy.backend;
let main_program = match backend {
Backend::Xray => self.comps.xray()?,
_ => self.comps.sing_box()?,
};
let main_json = serde_json::to_vec_pretty(rendered.sing_box.as_ref().or(rendered.xray.as_ref()).unwrap())?;
let main_path = run.join(if backend == Backend::Xray { "xray.json" } else { "sing-box.json" });
// Checked before it replaces the running one: a config the backend refuses keeps the
// last good one running.
let candidate = run.join("candidate.json");
write_atomic(&candidate, &main_json)?;
if backend != Backend::Xray {
let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?;
if !out.status.success() {
let why = String::from_utf8_lossy(&out.stderr).trim().to_owned();
self.last_error = Some(format!("sing-box refused the rendered config: {why}"));
self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}"));
anyhow::bail!("sing-box refused the rendered config: {why}");
}
}
if !same_content(&main_path, &main_json) {
std::fs::rename(&candidate, &main_path)?;
}
let mut args: Vec<String> = vec!["run".into(), "-c".into(), main_path.to_string_lossy().into_owned()];
if backend != Backend::Xray {
args.extend(["-D".into(), run.to_string_lossy().into_owned(), "--disable-color".into()]);
}
self.sup.ensure(UnitSpec {
name: SOCKS_UNIT.into(),
program: main_program,
args,
env: Vec::new(),
cwd: Some(run.clone()),
generation: digest(&main_json),
});
match (backend, &rendered.xray) {
(Backend::Hybrid, Some(sidecar)) => {
let xray = self.comps.xray().context("the hybrid backend needs xray")?;
let json = serde_json::to_vec_pretty(sidecar)?;
let path = run.join("xray-sidecar.json");
if !same_content(&path, &json) {
write_atomic(&path, &json)?;
}
self.sup.ensure(UnitSpec {
name: SIDECAR_UNIT.into(),
program: xray,
args: vec!["run".into(), "-c".into(), path.to_string_lossy().into_owned()],
env: Vec::new(),
cwd: Some(run.clone()),
generation: digest(&json),
});
}
_ => self.sup.stop(SIDECAR_UNIT).await,
}
self.last = Some(rendered);
self.last_error = None;
Ok(())
}
/// The routes a fetch tries: the local proxy if it runs, and (with directFallbacks or
/// without it) directly.
pub fn fetch_routes(&self, via_proxy: bool) -> Vec<fetch::Route> {
let cfg = self.cfg();
let mut routes = Vec::new();
if via_proxy && self.sup.state_of(SOCKS_UNIT) == UnitState::Active {
let auth = &cfg.proxy.listener.auth;
let login = auth.username.clone().zip(auth.password.clone());
routes.push(fetch::Route::Proxy { port: cfg.proxy.listener.port, login });
if !cfg.kill_switch.enable || cfg.kill_switch.direct_fallbacks {
routes.push(fetch::Route::Direct);
}
} else {
routes.push(fetch::Route::Direct);
}
routes
}
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!({
"units": units,
"proxy": {
"enabled": cfg.proxy.enable,
"on": self.proxy_wanted(),
"state": socks.as_str(),
"backend": cfg.proxy.backend.as_str(),
"listener": format!("{}:{}", cfg.proxy.listener.address, cfg.proxy.listener.port),
"tun": self.tun && cfg.proxy.tun.enable,
"mode": self.store.state.route_mode.map(|m| m.as_str()),
"pinned": self.store.state.pin,
"selection": cfg.proxy.selection.as_str(),
},
"zapret": {
"enabled": cfg.zapret.enable,
"engine": serde_json::to_value(cfg.zapret.engine).unwrap(),
"state": self.sup.state_of(crate::zapret::UNIT).as_str(),
"preset": cfg.zapret.discord_youtube.config_name,
},
"tgWsProxy": {
"enabled": cfg.tg_ws_proxy.enable,
"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": warnings,
"error": self.last_error,
"revision": self.store.revision,
})
}
}
/// Fetches the subscriptions (all, or `only`), saves what came, and applies.
pub async fn update_subscriptions(shared: &Shared, only: Option<&str>) -> Vec<(String, Result<usize, String>)> {
let jobs: Vec<(String, Result<String, String>, Vec<fetch::Route>)> = {
let s = shared.lock().await;
s.cfg()
.proxy
.subscriptions
.iter()
.filter(|sub| only.is_none_or(|t| t == sub.tag))
.map(|sub| {
let url = match (&sub.url, &sub.url_file) {
(Some(u), _) => Ok(u.trim().to_owned()),
(None, Some(f)) => std::fs::read_to_string(f).map(|s| s.trim().to_owned()).map_err(|e| format!("{f}: {e}")),
(None, None) => Err("no url or urlFile".into()),
};
(sub.tag.clone(), url, s.fetch_routes(true))
})
.collect()
};
let mut results = Vec::new();
for (tag, url, routes) in jobs {
let result = match url {
Err(e) => Err(e),
Ok(url) => fetch::subscription(&url, &routes).await.map_err(|e| e.to_string()),
};
let mut s = shared.lock().await;
match result {
Ok(lines) => {
let n = lines.len();
if let Err(e) = s.store.save_subscription(&tag, lines) {
results.push((tag, Err(e.to_string())));
continue;
}
s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now());
s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}': {n} links"));
results.push((tag, Ok(n)));
}
Err(e) => {
s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now());
s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}' could not be fetched: {e}"));
results.push((tag, Err(e)));
}
}
}
let mut s = shared.lock().await;
let _ = s.apply().await;
results
}
/// Fetches the rule sets and geodata the configuration wants (all, or those missing), and
/// applies when something new came.
pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(String, Result<(), String>)> {
let (wanted, have, dir, sing_box, routes_proxy, routes_direct) = {
let s = shared.lock().await;
(
render::wanted_rule_sets(s.cfg()),
s.store.rule_set_files(),
s.paths().rule_sets(),
s.comps.sing_box().ok(),
s.fetch_routes(true),
s.fetch_routes(false),
)
};
let mut results = Vec::new();
let mut changed = false;
// A tag becomes a file name: the configuration is validated, but this writes as SYSTEM.
let safe = |tag: &str| !tag.is_empty() && !tag.starts_with('.') && tag.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '!' | '@' | '.' | '_' | '-'));
for w in wanted.iter().filter(|w| w.dns_copy_of.is_none()) {
if !safe(&w.tag) {
results.push((w.tag.clone(), Err("not a name a file may have".into())));
continue;
}
if missing_only && have.contains_key(&w.tag) {
continue;
}
let ext = if w.format == RuleSetFormat::Binary { "srs" } else { "json" };
let dest = dir.join(format!("{}.{ext}", w.tag));
let routes = if w.via_proxy { &routes_proxy } else { &routes_direct };
let r = fetch::rule_set(&w.url, routes, &dest).await.map_err(|e| e.to_string());
changed |= r.is_ok();
results.push((w.tag.clone(), r));
}
// The DNS copies, from what was fetched.
for w in wanted.iter().filter(|w| w.dns_copy_of.is_some()) {
let of = w.dns_copy_of.as_deref().unwrap();
if !safe(&w.tag) || !safe(of) {
continue;
}
let src_json = dir.join(format!("{of}.json"));
let src_srs = dir.join(format!("{of}.srs"));
let dest = dir.join(format!("{}.json", w.tag));
if missing_only && dest.exists() && !changed {
continue;
}
let source: Result<Value> = if src_json.exists() {
std::fs::read_to_string(&src_json).map_err(Into::into).and_then(|t| serde_json::from_str(&t).map_err(Into::into))
} else if let (true, Some(sb)) = (src_srs.exists(), &sing_box) {
decompile(sb, &src_srs).await
} else {
continue;
};
let r = source
.and_then(|src| Ok(write_atomic(&dest, serde_json::to_string(&fetch::domain_only(&src))?.as_bytes())?))
.map_err(|e| e.to_string());
results.push((w.tag.clone(), r));
}
if changed {
let mut s = shared.lock().await;
let _ = s.apply().await;
}
results
}
async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result<Value> {
let out = srs.with_extension("decompiled.json");
let status = tokio::process::Command::new(sing_box)
.args(["rule-set", "decompile", "--output"])
.arg(&out)
.arg(srs)
.status()
.await?;
anyhow::ensure!(status.success(), "sing-box could not decompile {}", srs.display());
let v = serde_json::from_str(&std::fs::read_to_string(&out)?)?;
let _ = std::fs::remove_file(&out);
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, 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));
let sub_every = every(&cfg.proxy.subscription_update_interval, 86400);
let rules_every = every(&cfg.proxy.routing.rule_set_update_interval, 86400);
let due = |key: &str, every: Duration| {
s.last_fetch.get(key).is_none_or(|t| t.elapsed().unwrap_or_default() >= every)
};
let subs: Vec<String> =
cfg.proxy.subscriptions.iter().filter(|x| due(&format!("sub:{}", x.tag), sub_every)).map(|x| x.tag.clone()).collect();
// 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;
}
if rules_due {
shared.lock().await.last_fetch.insert("rule-sets".into(), SystemTime::now());
update_rule_sets(&shared, false).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"]);
}
}
+125
View File
@@ -0,0 +1,125 @@
//! The configuration, runtime state and generated secrets, as files.
use std::collections::BTreeMap;
use anyhow::{Context, Result};
use ps_core::config::Config;
use ps_core::render::{RuleSetFile, State};
use rand::Rng;
use serde::{Deserialize, Serialize};
use crate::paths::{Paths, write_atomic};
/// What the service generated once and keeps.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Secrets {
pub clash_secret: String,
pub hop_user: String,
pub hop_password: String,
}
pub fn random_token(len: usize) -> String {
const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
let mut rng = rand::rng();
(0..len).map(|_| CHARS[rng.random_range(0..CHARS.len())] as char).collect()
}
pub fn random_uuid() -> String {
let mut rng = rand::rng();
let b: [u8; 16] = rng.random();
format!(
"{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}",
u32::from_be_bytes([b[0], b[1], b[2], b[3]]),
u16::from_be_bytes([b[4], b[5]]),
u16::from_be_bytes([b[6], b[7]]) & 0x0fff,
(u16::from_be_bytes([b[8], b[9]]) & 0x3fff) | 0x8000,
u64::from_be_bytes([0, 0, b[10], b[11], b[12], b[13], b[14], b[15]])
)
}
pub struct Store {
pub paths: Paths,
pub config: Config,
/// Bumped by every change of `config`: a client edits against a revision.
pub revision: u64,
pub state: State,
pub secrets: Secrets,
/// Each subscription's links as fetched last.
pub subscriptions: BTreeMap<String, Vec<String>>,
}
impl Store {
pub fn open(paths: Paths) -> Result<Self> {
paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?;
let config = match std::fs::read_to_string(paths.config()) {
Ok(text) => Config::from_json(&text).with_context(|| format!("reading {}", paths.config().display()))?,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(),
Err(e) => return Err(e).with_context(|| format!("reading {}", paths.config().display())),
};
let state = std::fs::read_to_string(paths.state())
.ok()
.and_then(|t| serde_json::from_str(&t).ok())
.unwrap_or_default();
let secrets = match std::fs::read_to_string(paths.secrets()).ok().and_then(|t| serde_json::from_str(&t).ok()) {
Some(s) => s,
None => {
let s = Secrets { clash_secret: random_token(32), hop_user: "hop".into(), hop_password: random_token(32) };
write_atomic(&paths.secrets(), serde_json::to_string_pretty(&s)?.as_bytes())?;
s
}
};
let mut store = Self { paths, config, revision: 1, state, secrets, subscriptions: BTreeMap::new() };
store.load_subscriptions();
Ok(store)
}
pub fn save_config(&mut self, config: Config) -> Result<()> {
write_atomic(&self.paths.config(), config.to_json_pretty().as_bytes())?;
self.config = config;
self.revision += 1;
Ok(())
}
pub fn save_state(&self) -> Result<()> {
write_atomic(&self.paths.state(), serde_json::to_string_pretty(&self.state)?.as_bytes())?;
Ok(())
}
fn sub_path(&self, tag: &str) -> std::path::PathBuf {
self.paths.subscriptions().join(format!("{tag}.txt"))
}
fn load_subscriptions(&mut self) {
for sub in &self.config.proxy.subscriptions {
if let Ok(text) = std::fs::read_to_string(self.sub_path(&sub.tag)) {
self.subscriptions.insert(sub.tag.clone(), text.lines().map(str::to_owned).collect());
}
}
}
pub fn save_subscription(&mut self, tag: &str, lines: Vec<String>) -> Result<()> {
write_atomic(&self.sub_path(tag), lines.join("\n").as_bytes())?;
self.subscriptions.insert(tag.to_owned(), lines);
Ok(())
}
/// The downloaded rule sets, by tag.
pub fn rule_set_files(&self) -> BTreeMap<String, RuleSetFile> {
let mut out = BTreeMap::new();
let Ok(dir) = std::fs::read_dir(self.paths.rule_sets()) else { return out };
for entry in dir.flatten() {
let path = entry.path();
let (Some(stem), Some(ext)) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) else {
continue;
};
let format = match ext {
"srs" => ps_core::config::RuleSetFormat::Binary,
"json" => ps_core::config::RuleSetFormat::Source,
_ => continue,
};
out.insert(stem.to_owned(), RuleSetFile { path: path.to_string_lossy().into_owned(), format });
}
out
}
}
+133
View File
@@ -0,0 +1,133 @@
//! tg-ws-proxy: Flowseal's Telegram WebSocket bridge, run as upstream's module runs it, on the
//! embedded Python the release carries.
use std::path::PathBuf;
use anyhow::{Context, Result};
use ps_core::config::Config;
use crate::paths::Paths;
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-tg-ws-proxy";
/// The arguments upstream's module gives it (modules/proxy-suite/tg-ws-proxy.nix).
pub fn args(cfg: &Config, secret: &str) -> Vec<String> {
let t = &cfg.tg_ws_proxy;
let mut a = vec![
"-m".into(),
"proxy.tg_ws_proxy".into(),
format!("--port={}", t.listener.port),
format!("--host={}", t.listener.address),
format!("--secret={secret}"),
];
for (dc, ip) in &t.dc_ips {
a.push(format!("--dc-ip={dc}:{ip}"));
}
if cfg.debug.tg_ws_proxy {
a.push("--verbose".into());
}
if let Some(file) = &t.log.file {
a.push(format!("--log-file={file}"));
a.push(format!("--log-max-mb={}", t.log.max_size_mib));
a.push(format!("--log-backups={}", t.log.keep));
}
a.push(format!("--buf-kb={}", t.buffer_kib));
a.push(format!("--pool-size={}", t.pool_size));
for d in &t.cloudflare.domains {
a.push(format!("--cfproxy-domain={d}"));
}
for d in &t.cloudflare.worker_domains {
a.push(format!("--cfproxy-worker-domain={d}"));
}
if !t.cloudflare.fallback {
a.push("--no-cfproxy".into());
}
if let Some(d) = &t.fake_tls_domain {
a.push(format!("--fake-tls-domain={d}"));
}
if t.proxy_protocol {
a.push("--proxy-protocol".into());
}
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;
if let Some(s) = &t.secret {
return Ok(s.clone());
}
if let Some(f) = &t.secret_file {
return Ok(std::fs::read_to_string(f).with_context(|| format!("reading {f}"))?.trim().to_owned());
}
let kept = paths.root.join("tg-ws-proxy.secret");
if let Ok(s) = std::fs::read_to_string(&kept) {
return Ok(s.trim().to_owned());
}
let s: String = (0..32).map(|_| format!("{:x}", rand::random::<u8>() % 16)).collect();
crate::paths::write_atomic(&kept, s.as_bytes())?;
Ok(s)
}
pub fn unit(cfg: &Config, paths: &Paths, python: PathBuf) -> Result<UnitSpec> {
let app = paths.bin().join("tg-ws-proxy").join("app");
let args = args(cfg, &secret(cfg, paths)?);
Ok(UnitSpec {
name: UNIT.into(),
program: python,
generation: args.join("\n"),
args,
// The embedded Python finds its path in its ._pth file; nothing from the
// environment should change it.
env: vec![("PYTHONNOUSERSITE".into(), "1".into()), ("PYTHONDONTWRITEBYTECODE".into(), "1".into())],
cwd: Some(app),
})
}
#[cfg(test)]
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();
cfg.tg_ws_proxy.dc_ips.insert("2".into(), "149.154.167.220".into());
cfg.tg_ws_proxy.cloudflare.fallback = false;
cfg.tg_ws_proxy.fake_tls_domain = Some("www.example.com".into());
let a = args(&cfg, "ab");
assert_eq!(&a[..5], ["-m", "proxy.tg_ws_proxy", "--port=1443", "--host=127.0.0.1", "--secret=ab"]);
for want in ["--dc-ip=2:149.154.167.220", "--buf-kb=256", "--pool-size=4", "--no-cfproxy", "--fake-tls-domain=www.example.com"] {
assert!(a.contains(&want.to_owned()), "{want} in {a:?}");
}
}
}
+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());
}
}
+441
View File
@@ -0,0 +1,441 @@
//! The supervisor: what systemd does for upstream. Each unit is one program, started,
//! watched, restarted with backoff when it dies, its output kept in a ring and a log file.
//! On Windows every child joins a Job Object that kills it with the service.
use std::collections::{BTreeMap, VecDeque};
use std::io::Write;
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::process::Command;
use tokio::sync::{broadcast, watch};
/// How to run a unit. Two specs that compare equal need no restart.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnitSpec {
pub name: String,
pub program: PathBuf,
pub args: Vec<String>,
pub env: Vec<(String, String)>,
pub cwd: Option<PathBuf>,
/// Changes when a file the unit reads changes (its rendered config): a restart.
pub generation: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum UnitState {
Inactive,
Activating,
Active,
Deactivating,
Failed,
}
impl UnitState {
pub fn as_str(self) -> &'static str {
match self {
Self::Inactive => "inactive",
Self::Activating => "activating",
Self::Active => "active",
Self::Deactivating => "deactivating",
Self::Failed => "failed",
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct LogLine {
pub unit: String,
/// Unix time, milliseconds.
pub at: u64,
pub line: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct UnitStatus {
pub name: String,
pub state: UnitState,
pub pid: Option<u32>,
pub restarts: u32,
/// Why it failed last.
pub result: Option<String>,
pub since: Option<u64>,
}
const RING: usize = 2000;
/// A unit that fails this many times within `START_LIMIT_INTERVAL` stays failed.
const START_LIMIT: usize = 5;
const START_LIMIT_INTERVAL: Duration = Duration::from_secs(60);
/// A unit whose log file outgrows this starts a new one, keeping one old.
const LOG_FILE_MAX: u64 = 5 * 1024 * 1024;
struct Shared {
state: UnitState,
pid: Option<u32>,
restarts: u32,
result: Option<String>,
since: Option<u64>,
}
struct Unit {
spec: UnitSpec,
shared: Arc<Mutex<Shared>>,
stop: watch::Sender<bool>,
task: tokio::task::JoinHandle<()>,
}
pub struct Supervisor {
units: BTreeMap<String, Unit>,
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
log_dir: PathBuf,
feed: broadcast::Sender<LogLine>,
#[cfg(windows)]
job: Option<crate::job::Job>,
}
fn now_ms() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64)
}
impl Supervisor {
pub fn new(log_dir: PathBuf) -> Self {
let (feed, _) = broadcast::channel(1024);
Self {
units: BTreeMap::new(),
logs: Arc::new(Mutex::new(BTreeMap::new())),
log_dir,
feed,
#[cfg(windows)]
job: crate::job::Job::new().map_err(|e| tracing::warn!("no job object: {e}")).ok(),
}
}
pub fn subscribe(&self) -> broadcast::Receiver<LogLine> {
self.feed.subscribe()
}
/// The last `n` log lines of `unit`, or of every unit by time.
pub fn tail(&self, unit: Option<&str>, n: usize) -> Vec<LogLine> {
let logs = self.logs.lock().unwrap();
let mut lines: Vec<LogLine> = match unit {
Some(u) => logs.get(u).map(|r| r.iter().cloned().collect()).unwrap_or_default(),
None => logs.values().flatten().cloned().collect(),
};
lines.sort_by_key(|l| l.at);
let skip = lines.len().saturating_sub(n);
lines.split_off(skip)
}
/// A line of the service's own about a unit, in that unit's log.
pub fn note(&self, unit: &str, line: impl Into<String>) {
push_log(&self.logs, &self.feed, &self.log_dir, unit, line.into());
}
pub fn status(&self) -> Vec<UnitStatus> {
self.units
.iter()
.map(|(name, u)| {
let s = u.shared.lock().unwrap();
UnitStatus { name: name.clone(), state: s.state, pid: s.pid, restarts: s.restarts, result: s.result.clone(), since: s.since }
})
.collect()
}
pub fn state_of(&self, name: &str) -> UnitState {
self.units.get(name).map_or(UnitState::Inactive, |u| u.shared.lock().unwrap().state)
}
/// Runs `spec`, restarting the unit if it runs another spec, leaving it be if it runs this one.
pub fn ensure(&mut self, spec: UnitSpec) {
if let Some(u) = self.units.get(&spec.name) {
let alive = !u.task.is_finished();
if alive && u.spec == spec && u.shared.lock().unwrap().state != UnitState::Failed {
return;
}
}
self.start(spec);
}
/// Starts `spec`, stopping what ran under its name first.
pub fn start(&mut self, spec: UnitSpec) {
let name = spec.name.clone();
self.stop_now(&name);
let shared = Arc::new(Mutex::new(Shared { state: UnitState::Activating, pid: None, restarts: 0, result: None, since: Some(now_ms()) }));
let (stop_tx, stop_rx) = watch::channel(false);
let ctx = RunCtx {
spec: spec.clone(),
shared: shared.clone(),
logs: self.logs.clone(),
feed: self.feed.clone(),
log_dir: self.log_dir.clone(),
#[cfg(windows)]
job: self.job.as_ref().map(|j| j.handle()),
};
let task = tokio::spawn(run(ctx, stop_rx));
self.units.insert(name, Unit { spec, shared, stop: stop_tx, task });
}
/// Restarts a unit with the spec it has.
pub fn restart(&mut self, name: &str) -> bool {
match self.units.get(name).map(|u| u.spec.clone()) {
Some(spec) => {
self.start(spec);
true
}
None => false,
}
}
fn stop_now(&mut self, name: &str) {
if let Some(u) = self.units.remove(name) {
let _ = u.stop.send(true);
// The task kills the child as it sees the flag; it is not waited for here, but
// the next start of the unit waits for nothing either: a listener still held for a
// moment shows as one restart.
let shared = u.shared.clone();
tokio::spawn(async move {
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
shared.lock().unwrap().state = UnitState::Inactive;
});
}
}
/// Stops a unit and waits for its process to be gone.
pub async fn stop(&mut self, name: &str) {
if let Some(u) = self.units.remove(name) {
let _ = u.stop.send(true);
let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await;
}
}
pub fn names(&self) -> Vec<String> {
self.units.keys().cloned().collect()
}
pub async fn stop_all(&mut self) {
for name in self.names() {
self.stop(&name).await;
}
}
}
struct RunCtx {
spec: UnitSpec,
shared: Arc<Mutex<Shared>>,
logs: Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
feed: broadcast::Sender<LogLine>,
log_dir: PathBuf,
#[cfg(windows)]
job: Option<isize>,
}
fn push_log(
logs: &Arc<Mutex<BTreeMap<String, VecDeque<LogLine>>>>,
feed: &broadcast::Sender<LogLine>,
log_dir: &std::path::Path,
unit: &str,
line: String,
) {
let entry = LogLine { unit: unit.to_owned(), at: now_ms(), line };
{
let mut logs = logs.lock().unwrap();
let ring = logs.entry(unit.to_owned()).or_default();
if ring.len() >= RING {
ring.pop_front();
}
ring.push_back(entry.clone());
}
let path = log_dir.join(format!("{unit}.log"));
if std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_FILE_MAX) {
let _ = std::fs::rename(&path, log_dir.join(format!("{unit}.log.1")));
}
if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) {
let _ = writeln!(f, "{} {}", entry.at, entry.line);
}
let _ = feed.send(entry);
}
async fn run(ctx: RunCtx, mut stop: watch::Receiver<bool>) {
let mut failures: VecDeque<Instant> = VecDeque::new();
let mut backoff = Duration::from_millis(500);
let log = |line: String| push_log(&ctx.logs, &ctx.feed, &ctx.log_dir, &ctx.spec.name, line);
loop {
let mut cmd = Command::new(&ctx.spec.program);
cmd.args(&ctx.spec.args)
.envs(ctx.spec.env.iter().map(|(k, v)| (k, v)))
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.kill_on_drop(true);
if let Some(cwd) = &ctx.spec.cwd {
cmd.current_dir(cwd);
}
#[cfg(windows)]
{
// 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) => {
let why = format!("cannot start {}: {e}", ctx.spec.program.display());
log(format!("proxy-suite: {why}"));
let mut s = ctx.shared.lock().unwrap();
s.state = UnitState::Failed;
s.result = Some(why);
return;
}
};
#[cfg(windows)]
if let (Some(job), Some(handle)) = (ctx.job, child.raw_handle()) {
crate::job::assign(job, handle as isize);
}
{
let mut s = ctx.shared.lock().unwrap();
s.pid = child.id();
s.state = UnitState::Activating;
s.since = Some(now_ms());
}
log(format!("proxy-suite: started {} (pid {})", ctx.spec.program.display(), child.id().unwrap_or(0)));
for pipe in [child.stdout.take().map(|p| Box::new(p) as Box<dyn tokio::io::AsyncRead + Send + Unpin>), child.stderr.take().map(|p| Box::new(p) as _)].into_iter().flatten() {
let logs = ctx.logs.clone();
let feed = ctx.feed.clone();
let dir = ctx.log_dir.clone();
let unit = ctx.spec.name.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(pipe).lines();
while let Ok(Some(line)) = lines.next_line().await {
push_log(&logs, &feed, &dir, &unit, line);
}
});
}
// Up once it has lived a moment: none of the backends tells when it is ready.
let started = Instant::now();
let status = loop {
tokio::select! {
status = child.wait() => break Some(status),
_ = tokio::time::sleep(Duration::from_millis(700)), if ctx.shared.lock().unwrap().state == UnitState::Activating => {
ctx.shared.lock().unwrap().state = UnitState::Active;
}
_ = stop.changed() => {
if *stop.borrow() {
ctx.shared.lock().unwrap().state = UnitState::Deactivating;
let _ = child.start_kill();
let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await;
let mut s = ctx.shared.lock().unwrap();
s.state = UnitState::Inactive;
s.pid = None;
return;
}
}
}
};
let why = match status {
Some(Ok(s)) => format!("exited ({s})"),
Some(Err(e)) => format!("lost ({e})"),
None => "stopped".into(),
};
log(format!("proxy-suite: {} {why}", ctx.spec.name));
let now = Instant::now();
failures.push_back(now);
while failures.front().is_some_and(|t| now - *t > START_LIMIT_INTERVAL) {
failures.pop_front();
}
{
let mut s = ctx.shared.lock().unwrap();
s.pid = None;
s.result = Some(why.clone());
if failures.len() >= START_LIMIT {
s.state = UnitState::Failed;
drop(s);
log(format!("proxy-suite: {} failed {START_LIMIT} times in a minute; not restarting it", ctx.spec.name));
return;
}
s.state = UnitState::Activating;
s.restarts += 1;
}
// A run that lasted a while starts the backoff over.
if started.elapsed() > Duration::from_secs(30) {
backoff = Duration::from_millis(500);
}
tokio::select! {
_ = tokio::time::sleep(backoff) => {}
_ = stop.changed() => {
if *stop.borrow() {
ctx.shared.lock().unwrap().state = UnitState::Inactive;
return;
}
}
}
backoff = (backoff * 2).min(Duration::from_secs(30));
}
}
#[cfg(test)]
mod tests {
use super::*;
fn spec(name: &str, program: &str, args: &[&str]) -> UnitSpec {
UnitSpec {
name: name.into(),
program: program.into(),
args: args.iter().map(|s| s.to_string()).collect(),
env: Vec::new(),
cwd: None,
generation: "1".into(),
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_unit_runs_logs_and_stops() {
let dir = std::env::temp_dir().join(format!("ps-units-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut sup = Supervisor::new(dir.clone());
sup.start(spec("echo", "sh", &["-c", "echo hello; sleep 30"]));
tokio::time::sleep(Duration::from_millis(1200)).await;
assert_eq!(sup.state_of("echo"), UnitState::Active);
assert!(sup.tail(Some("echo"), 10).iter().any(|l| l.line == "hello"));
sup.stop("echo").await;
assert_eq!(sup.state_of("echo"), UnitState::Inactive);
assert!(std::fs::read_to_string(dir.join("echo.log")).unwrap().contains("hello"));
}
#[cfg(unix)]
#[tokio::test]
async fn a_dying_unit_is_restarted_then_given_up_on() {
let dir = std::env::temp_dir().join(format!("ps-units-die-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let mut sup = Supervisor::new(dir);
sup.start(spec("dies", "sh", &["-c", "exit 3"]));
tokio::time::sleep(Duration::from_secs(10)).await;
let st = sup.status();
assert_eq!(st[0].state, UnitState::Failed);
assert!(st[0].restarts >= 3, "{st:?}");
}
#[tokio::test]
async fn a_missing_program_fails_at_once() {
let mut sup = Supervisor::new(std::env::temp_dir());
sup.start(spec("missing", "/nonexistent/program", &[]));
tokio::time::sleep(Duration::from_millis(200)).await;
assert_eq!(sup.state_of("missing"), UnitState::Failed);
}
}
+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}");
}
}
+458
View File
@@ -0,0 +1,458 @@
//! The Windows service: registration, and the Service Control Manager's entry point.
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result};
use windows_service::service::{
ServiceAccess, ServiceAction, ServiceActionType, ServiceControl, ServiceControlAccept, ServiceErrorControl,
ServiceExitCode, ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType, ServiceState,
ServiceStatus, ServiceType,
};
use windows_service::service_control_handler::{self, ServiceControlHandlerResult};
use windows_service::service_manager::{ServiceManager, ServiceManagerAccess};
use windows_service::{define_windows_service, service_dispatcher};
pub const NAME: &str = "ProxySuite";
const DISPLAY: &str = "Proxy Suite";
const DESCRIPTION: &str = "Runs Proxy Suite's proxy, tunnels and DPI bypass, and serves the app's settings.";
/// Where `install` puts the program: only administrators may change it, so what the service
/// runs as SYSTEM, and the components it takes from beside it, stay theirs.
pub fn install_dir() -> PathBuf {
std::env::var_os("ProgramFiles").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\Program Files")).join("ProxySuite")
}
/// The files of a release that `install` copies.
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)?;
for f in RELEASE_FILES {
let src = from.join(f);
if src.is_file() {
std::fs::copy(&src, to.join(f)).with_context(|| format!("copying {f}"))?;
}
}
let comps = from.join("components");
if comps.is_dir() {
let dest = to.join("components");
let _ = std::fs::remove_dir_all(&dest);
copy_dir(&comps, &dest)?;
}
Ok(())
}
fn copy_dir(from: &Path, to: &Path) -> Result<()> {
std::fs::create_dir_all(to)?;
for entry in std::fs::read_dir(from)? {
let entry = entry?;
let dest = to.join(entry.file_name());
if entry.file_type()?.is_dir() {
copy_dir(&entry.path(), &dest)?;
} else {
std::fs::copy(entry.path(), &dest)?;
}
}
Ok(())
}
fn wait_stopped(service: &windows_service::service::Service) -> Result<()> {
for _ in 0..60 {
if service.query_status()?.current_state == ServiceState::Stopped {
return Ok(());
}
std::thread::sleep(Duration::from_millis(500));
}
anyhow::bail!("the service did not stop")
}
/// Installs (or upgrades) the release this program came with: copied into Program Files,
/// registered there to start at boot as LocalSystem, put on the system PATH, started.
pub fn install() -> Result<()> {
let from = std::env::current_exe()?.parent().context("no program directory")?.to_path_buf();
let to = install_dir();
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE)
.context("opening the Service Control Manager (run this as an administrator)")?;
let info = ServiceInfo {
name: OsString::from(NAME),
display_name: OsString::from(DISPLAY),
service_type: ServiceType::OWN_PROCESS,
start_type: ServiceStartType::AutoStart,
error_control: ServiceErrorControl::Normal,
executable_path: to.join("proxy-suite-service.exe"),
launch_arguments: vec![],
dependencies: vec![],
account_name: None, // LocalSystem
account_password: None,
};
let access = ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::START | ServiceAccess::CHANGE_CONFIG;
let service = match manager.open_service(NAME, access) {
Ok(existing) => {
// An upgrade: what runs lets go of its files first.
if existing.query_status()?.current_state != ServiceState::Stopped {
println!("Stopping {DISPLAY}…");
let _ = existing.stop();
wait_stopped(&existing)?;
}
if from != to {
desktop::close();
copy_release(&from, &to)?;
}
existing.change_config(&info)?;
existing
}
Err(_) => {
if from != to {
desktop::close();
copy_release(&from, &to)?;
}
manager.create_service(&info, access).context("creating the service")?
}
};
service.set_description(DESCRIPTION)?;
// Restarted when it dies, as systemd's Restart=always.
service.update_failure_actions(ServiceFailureActions {
reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400)),
reboot_msg: None,
command: None,
actions: Some(vec![
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(2) },
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(10) },
ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(60) },
]),
})?;
if let Err(e) = path::add(&to) {
println!("warning: could not add {} to PATH: {e:#}", to.display());
}
// A moment for the manager to settle the change just made (Wine's otherwise answers
// ERROR_SERVICE_DATABASE_LOCKED); a start that still fails leaves a working install.
std::thread::sleep(Duration::from_secs(1));
match service.start::<&str>(&[]) {
Ok(()) => println!("{DISPLAY} is installed in {} and started.", to.display()),
Err(e) => {
println!("{DISPLAY} is installed in {}, but did not start: {e}", to.display());
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(())
}
/// Stops and removes the service and takes it off PATH. The configuration and state in
/// ProgramData stay; the program files go once this has exited.
pub fn uninstall() -> Result<()> {
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT)
.context("opening the Service Control Manager (run this as an administrator)")?;
if let Ok(service) = manager.open_service(NAME, ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) {
if service.query_status()?.current_state != ServiceState::Stopped {
let _ = service.stop();
let _ = wait_stopped(&service);
}
service.delete()?;
println!("{DISPLAY} is removed.");
} else {
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
// does its own quote parsing; from outside the folder, which a working directory holds.
use std::os::windows::process::CommandExt;
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
let _ = std::process::Command::new("cmd")
.raw_arg(format!("/c ping -n 3 127.0.0.1 >nul & rmdir /s /q \"{}\"", dir.display()))
.current_dir(std::env::var_os("SystemRoot").unwrap_or_else(|| "C:\\Windows".into()))
.creation_flags(CREATE_NO_WINDOW)
.stdin(std::process::Stdio::null())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn();
println!("Removing {}.", dir.display());
}
println!("The configuration and state stay in %ProgramData%\\ProxySuite; delete that folder to forget them.");
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;
use anyhow::{Result, bail};
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
use windows_sys::Win32::System::Registry::{
HKEY, HKEY_LOCAL_MACHINE, KEY_READ, KEY_WRITE, REG_EXPAND_SZ, RegCloseKey, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
};
use windows_sys::Win32::UI::WindowsAndMessaging::{HWND_BROADCAST, SMTO_ABORTIFHUNG, SendMessageTimeoutW, WM_SETTINGCHANGE};
const KEY: &str = r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
fn wide(s: &str) -> Vec<u16> {
s.encode_utf16().chain(Some(0)).collect()
}
fn with_path(edit: impl FnOnce(&mut Vec<String>)) -> Result<()> {
// SAFETY: NUL-terminated names; the key is closed below; buffers are as long as said.
unsafe {
let mut key: HKEY = std::ptr::null_mut();
if RegOpenKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) != ERROR_SUCCESS {
bail!("cannot open the environment's registry key");
}
let name = wide("Path");
let mut len = 0u32;
let mut kind = 0u32;
RegQueryValueExW(key, name.as_ptr(), std::ptr::null_mut(), &mut kind, std::ptr::null_mut(), &mut len);
let mut buf = vec![0u16; (len as usize / 2) + 1];
let mut len2 = (buf.len() * 2) as u32;
if RegQueryValueExW(key, name.as_ptr(), std::ptr::null_mut(), &mut kind, buf.as_mut_ptr() as *mut u8, &mut len2) != ERROR_SUCCESS {
RegCloseKey(key);
bail!("cannot read the system PATH");
}
let text = String::from_utf16_lossy(&buf[..(len2 as usize / 2)]).trim_end_matches('\0').to_owned();
let mut parts: Vec<String> = text.split(';').filter(|p| !p.is_empty()).map(str::to_owned).collect();
edit(&mut parts);
let new: Vec<u16> = wide(&parts.join(";"));
let rc = RegSetValueExW(key, name.as_ptr(), 0, REG_EXPAND_SZ, new.as_ptr() as *const u8, (new.len() * 2) as u32);
RegCloseKey(key);
if rc != ERROR_SUCCESS {
bail!("cannot write the system PATH");
}
// New terminals see it without a sign-out.
let env = wide("Environment");
SendMessageTimeoutW(HWND_BROADCAST, WM_SETTINGCHANGE, 0, env.as_ptr() as isize, SMTO_ABORTIFHUNG, 2000, std::ptr::null_mut());
}
Ok(())
}
pub fn add(dir: &Path) -> Result<()> {
let d = dir.to_string_lossy().into_owned();
with_path(|parts| {
if !parts.iter().any(|p| p.eq_ignore_ascii_case(&d)) {
parts.push(d);
}
})
}
pub fn remove(dir: &Path) -> Result<()> {
let d = dir.to_string_lossy().into_owned();
with_path(|parts| parts.retain(|p| !p.eq_ignore_ascii_case(&d)))
}
}
/// A running service that holds WinDivert for DPI bypass already: Flowseal's `service.bat`
/// installs "zapret", bol-van's bundle "winws1"/"winws2", and GoodbyeDPI its own. Two such
/// filters fight over the same packets (and winws refuses a duplicate filter).
pub fn windivert_conflict() -> Option<(&'static str, &'static str)> {
const KNOWN: [(&str, &str); 4] = [
("zapret", "Flowseal's zapret-discord-youtube service (service.bat → Remove Services)"),
("winws1", "zapret-win-bundle's winws1 service (service_del.cmd)"),
("winws2", "zapret-win-bundle's winws2 service (service_del.cmd)"),
("GoodbyeDPI", "GoodbyeDPI's service (its service_remove.cmd)"),
];
let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT).ok()?;
KNOWN.into_iter().find(|(name, _)| {
manager
.open_service(name, ServiceAccess::QUERY_STATUS)
.and_then(|s| s.query_status())
.is_ok_and(|st| st.current_state != ServiceState::Stopped)
})
}
define_windows_service!(ffi_service_main, service_main);
pub fn dispatch() -> Result<()> {
service_dispatcher::start(NAME, ffi_service_main).context("not started by the Service Control Manager; use --console to run in a terminal")
}
fn service_main(_args: Vec<OsString>) {
if let Err(e) = run_service() {
tracing::error!("the service failed: {e:#}");
}
}
fn run_service() -> Result<()> {
let result = run_service_inner();
if let Err(e) = &result {
tracing::error!("{e:#}");
}
result
}
fn run_service_inner() -> Result<()> {
let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>();
let mut stop_tx = Some(stop_tx);
let handler = move |control| match control {
ServiceControl::Stop | ServiceControl::Shutdown => {
if let Some(tx) = stop_tx.take() {
let _ = tx.send(());
}
ServiceControlHandlerResult::NoError
}
ServiceControl::Interrogate => ServiceControlHandlerResult::NoError,
_ => ServiceControlHandlerResult::NotImplemented,
};
let status = service_control_handler::register(NAME, handler)?;
let set = move |state: ServiceState, accept: ServiceControlAccept, exit: ServiceExitCode| {
let _ = status.set_service_status(ServiceStatus {
service_type: ServiceType::OWN_PROCESS,
current_state: state,
controls_accepted: accept,
exit_code: exit,
checkpoint: 0,
wait_hint: Duration::from_secs(30),
process_id: None,
});
};
set(ServiceState::StartPending, ServiceControlAccept::empty(), ServiceExitCode::Win32(0));
let rt = tokio::runtime::Runtime::new()?;
let result = rt.block_on(crate::run(
None,
None,
|| set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN, ServiceExitCode::Win32(0)),
async {
let _ = stop_rx.await;
},
));
// A start that failed is one the Service Control Manager reports, not a clean stop.
let exit = if result.is_ok() { ServiceExitCode::Win32(0) } else { ServiceExitCode::ServiceSpecific(1) };
set(ServiceState::Stopped, ServiceControlAccept::empty(), exit);
result
}
+222
View File
@@ -0,0 +1,222 @@
//! zapret on Windows: the unit that runs winws.exe (zapret-discord-youtube) with the
//! configured preset, and the lists it reads.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use ps_core::config::{Config, ZapretEngine};
use ps_core::zapret;
use crate::paths::{Paths, write_atomic};
use crate::units::UnitSpec;
pub const UNIT: &str = "proxy-suite-zapret";
/// The release's list files, as `zapret::direct_sync` reads them.
pub struct ReleaseLists {
pub general: String,
pub google: String,
pub exclude: String,
pub ipset_all: String,
pub ipset_exclude: String,
}
pub fn release_lists(component: &Path) -> ReleaseLists {
let read = |f: &str| std::fs::read_to_string(component.join("lists").join(f)).unwrap_or_default();
ReleaseLists {
general: read("list-general.txt"),
google: read("list-google.txt"),
exclude: read("list-exclude.txt"),
ipset_all: read("ipset-all.txt"),
ipset_exclude: read("ipset-exclude.txt"),
}
}
/// The domains and addresses `zapret.directSync` sends direct.
pub fn direct_sync(cfg: &Config, bin: &Path) -> (Vec<String>, Vec<String>) {
if !cfg.enable || !cfg.zapret.enable || cfg.zapret.engine != ZapretEngine::DiscordYoutube {
return zapret::direct_sync(&cfg.zapret, "", "", "", "", "");
}
let l = release_lists(&bin.join("zapret"));
zapret::direct_sync(&cfg.zapret, &l.general, &l.google, &l.exclude, &l.ipset_all, &l.ipset_exclude)
}
fn with_sep(p: &Path) -> String {
let s = p.to_string_lossy().into_owned();
let sep = if cfg!(windows) { '\\' } else { '/' };
if s.ends_with(sep) { s } else { format!("{s}{sep}") }
}
/// The unit for zapret-discord-youtube: the preset's winws.exe line, with the lists in the
/// service's run directory (the release's own, the user's entries added) and the game
/// filter. `program` is the verified winws.exe.
pub fn discord_youtube_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
let y = &cfg.zapret.discord_youtube;
let component = paths.bin().join("zapret");
let bats: Vec<String> = std::fs::read_dir(&component)
.with_context(|| format!("reading {}", component.display()))?
.filter_map(|e| e.ok()?.file_name().into_string().ok())
.collect();
let file = zapret::find_preset(&bats, &y.config_name).map_err(anyhow::Error::msg)?;
let bat = std::fs::read(component.join(&file))?;
let args = zapret::preset_args(&String::from_utf8_lossy(&bat)).map_err(anyhow::Error::msg)?;
// The lists: the release's, copied, with the user's beside them.
let lists = paths.run().join("zapret").join("lists");
std::fs::create_dir_all(&lists)?;
let release = component.join("lists");
for entry in std::fs::read_dir(&release)?.flatten() {
let name = entry.file_name();
if name.to_string_lossy().ends_with(".txt") {
std::fs::copy(entry.path(), lists.join(&name))?;
}
}
let exempt: &[String] = if cfg.zapret.cidr_exemption.enable { &cfg.zapret.cidr_exemption.cidrs } else { &[] };
let user = zapret::user_lists(y, exempt);
write_atomic(&lists.join("list-general-user.txt"), user.general_user.as_bytes())?;
write_atomic(&lists.join("list-exclude-user.txt"), user.exclude_user.as_bytes())?;
write_atomic(&lists.join("ipset-exclude-user.txt"), user.ipset_exclude_user.as_bytes())?;
if !user.ipset_all_extra.is_empty() {
let mut all = std::fs::read_to_string(lists.join("ipset-all.txt")).unwrap_or_default();
if !all.ends_with('\n') && !all.is_empty() {
all.push('\n');
}
all.push_str(&user.ipset_all_extra);
write_atomic(&lists.join("ipset-all.txt"), all.as_bytes())?;
}
// 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 (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());
}
// A change of the arguments or of a list winws reads is a restart.
let generation = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
for a in &argv {
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"].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()
};
Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(bin_dir), generation })
}
/// TCP timestamps on, as Flowseal's and bol-van's installers turn them on: strategies that
/// fool DPI with them need them.
pub async fn enable_tcp_timestamps() -> Result<()> {
if !cfg!(windows) {
return Ok(());
}
let status = tokio::process::Command::new("netsh")
.args(["interface", "tcp", "set", "global", "timestamps=enabled"])
.status()
.await
.context("running netsh")?;
if !status.success() {
bail!("netsh could not turn TCP timestamps on");
}
Ok(())
}
/// The unit for zapret2: winws2 with nfqws2-keenetic's strategies (ps_core::zapret2), its
/// lists in the service's `zapret2\\` directory, the learned one where winws2 can still write
/// once it runs at Low integrity.
pub fn zapret2_unit(cfg: &Config, paths: &Paths, program: PathBuf) -> Result<UnitSpec> {
use ps_core::zapret2;
let z = &cfg.zapret.zapret2;
let component = paths.bin().join("zapret2");
let conf = std::fs::read_to_string(component.join("keenetic").join("nfqws2.conf")).context("reading nfqws2-keenetic's nfqws2.conf")?;
let source = zapret2::keenetic(&conf, &with_sep(&component.join("keenetic"))).map_err(anyhow::Error::msg)?;
let state = paths.root.join("zapret2");
let learned = state.join("learned");
std::fs::create_dir_all(&learned)?;
#[cfg(windows)]
low_integrity(&learned)?;
let user = state.join("zapret-hosts-user.txt");
let exclude = state.join("zapret-hosts-user-exclude.txt");
let auto = learned.join("zapret-hosts-auto.txt");
// nfqws2 refuses a list it cannot open; an empty one is fine.
for f in [&user, &exclude, &auto] {
if !f.exists() {
std::fs::write(f, b"")?;
}
}
let p = zapret2::Paths {
lua: with_sep(&component.join("lua")),
user: user.to_string_lossy().into_owned(),
exclude: exclude.to_string_lossy().into_owned(),
auto: auto.to_string_lossy().into_owned(),
};
let argv = zapret2::args(z, &source, &p, cfg.debug.zapret2.packets).map_err(anyhow::Error::msg)?;
let generation = {
use sha2::{Digest, Sha256};
let mut h = Sha256::new();
for a in &argv {
h.update(a.as_bytes());
h.update(b"\n");
}
h.finalize().iter().map(|b| format!("{b:02x}")).collect()
};
Ok(UnitSpec { name: UNIT.into(), program, args: argv, env: Vec::new(), cwd: Some(component), generation })
}
/// A Low mandatory label on `dir`, inherited below it: what a Low-integrity process (winws2,
/// once it runs) may still write to. Its DACL stays as it is.
#[cfg(windows)]
fn low_integrity(dir: &Path) -> Result<()> {
use std::ffi::c_void;
use std::os::windows::ffi::OsStrExt;
use std::ptr::null_mut;
use windows_sys::Win32::Foundation::{ERROR_SUCCESS, LocalFree};
use windows_sys::Win32::Security::Authorization::{
ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, SE_FILE_OBJECT, SetNamedSecurityInfoW,
};
use windows_sys::Win32::Security::{ACL, GetSecurityDescriptorSacl, LABEL_SECURITY_INFORMATION};
let sddl: Vec<u16> = "S:(ML;OICI;NW;;;LW)".encode_utf16().chain(Some(0)).collect();
let path: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let mut sd: *mut c_void = null_mut();
// SAFETY: NUL-terminated inputs; the SACL points into sd, freed below.
unsafe {
if ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl.as_ptr(), SDDL_REVISION_1, &mut sd, null_mut()) == 0 {
return Err(std::io::Error::last_os_error().into());
}
let (mut present, mut defaulted) = (0, 0);
let mut sacl: *mut ACL = null_mut();
GetSecurityDescriptorSacl(sd, &mut present, &mut sacl, &mut defaulted);
let rc = SetNamedSecurityInfoW(path.as_ptr() as *mut u16, SE_FILE_OBJECT, LABEL_SECURITY_INFORMATION, null_mut(), null_mut(), null_mut(), sacl);
LocalFree(sd);
if rc != ERROR_SUCCESS {
return Err(std::io::Error::from_raw_os_error(rc as i32).into());
}
}
Ok(())
}
+27
View File
@@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1791594108,
"narHash": "sha256-XK4KceonkwD8LuMAt/vNrz982mXJM5jeHAxMwsUXXAQ=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "6510408d147d8c5e6d76043e899e9251756f6a75",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}
+69
View File
@@ -0,0 +1,69 @@
{
description = "Proxy Suite for Windows: development shell";
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
outputs =
{ nixpkgs, ... }:
let
systems = [
"x86_64-linux"
"aarch64-linux"
];
forAll = nixpkgs.lib.genAttrs systems;
in
{
devShells = forAll (
system:
let
pkgs = import nixpkgs { inherit system; };
# GPUI also runs on Linux, so the GUI can be tried here before a Windows build.
guiLibs = with pkgs; [
libxkbcommon
wayland
vulkan-loader
libx11
libxcb
libxcursor
libxi
libxrandr
fontconfig
freetype
alsa-lib
];
in
{
default = pkgs.mkShell {
packages = with pkgs; [
rustup
pkg-config
cargo-xwin
clang
lld
llvm
pkgsCross.mingwW64.stdenv.cc
# The backends, to check rendered configs and run the service on Linux.
sing-box
xray
python3
jq
zip
unzip
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;
shellHook = ''
export PATH="$HOME/.cargo/bin:$PATH"
'';
};
}
);
};
}
+29
View File
@@ -0,0 +1,29 @@
First pre-release of the native Windows port of proxy-suite-flake: a Windows service with `proxy-ctl`, no GUI yet. It replaces 0.1.0-pre.1, which never had a build, and fixes a local privilege escalation found in it: the service could go on with a state folder it had failed to secure.
**This build has never run on real Windows.** It was built and tested on Linux and under Wine. See "What has been verified" in the README, and please report what happens on yours.
### In this release
- **Local proxy:** SOCKS5/HTTP on `127.0.0.1:1080` through sing-box 1.14.4, or the hybrid sing-box + XRay 26.10.21 backend.
- **Outbounds:**
- Links of every kind upstream parses, plus raw JSON and subscriptions.
- Groups (failover, urltest, selector), chains, pins and route modes.
- Routing rules by site, address, geodata, rule set or **program**.
- **zapret:** Flowseal's zapret-discord-youtube 1.10.4 (`winws.exe` with WinDivert), with any `general*.bat` preset, your lists and the game filter.
- **zapret2:** `winws2.exe` from bol-van's zapret-win-bundle, with nfqws2-keenetic's strategies and nfqws2's own learning of blocked sites.
- **tg-ws-proxy:** Flowseal's tg-ws-proxy 1.11.2 on a bundled Python 3.12.
- **TUN:** sing-box's TUN (wintun). Don't use it together with zapret yet.
Every bundled program is pinned by version and hash, and checked before it runs.
### Install
Download `ProxySuite-0.1.0-pre.2-windows-x64.zip`; its SHA-256 is in the `.sha256` file next to it.
1. Unzip.
2. Run `install.cmd` as administrator. It copies to `C:\Program Files\ProxySuite`, registers the **ProxySuite** service and adds `proxy-ctl` to PATH.
3. In a new terminal, run `proxy-ctl status`.
### Not yet
The desktop app (GPUI, tray), AmneziaWG, WARP, Tor, the SSH tunnel, 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`.
+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`.
+6
View File
@@ -0,0 +1,6 @@
# The toolchain the releases are built with, here and in .gitea/workflows/windows-release.yml.
[toolchain]
channel = "1.99.1"
profile = "minimal"
components = ["clippy", "rustfmt"]
targets = ["x86_64-pc-windows-msvc"]
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
# tg-ws-proxy for Windows: Flowseal's source (the headless proxy, not the tray app) on the
# official embeddable CPython, with its dependencies as pinned win_amd64 wheels. Everything is
# verified: the Python archive and every wheel by hash, the source by its commit.
#
# tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip)
set -euo pipefail
OUT=$(realpath -m "${1:?output directory}")
cd "$(dirname "$0")"
PY_VERSION=3.12.10
PY_URL=https://www.python.org/ftp/python/$PY_VERSION/python-$PY_VERSION-embed-amd64.zip
PY_SHA256=4acbed6dd1c744b0376e3b1cf57ce906f9dc9e95e68824584c8099a63025a3c3
TG_TAG=v1.11.2
TG_COMMIT=307a384ab7f522e34bb1a045884d0bd90f40bee5
WORK=$(mktemp -d)
trap 'rm -rf "$WORK"' EXIT
rm -rf "$OUT" && mkdir -p "$OUT/python" "$OUT/app"
curl -sSfL -o "$WORK/python.zip" "$PY_URL"
echo "$PY_SHA256 $WORK/python.zip" | sha256sum -c --quiet
unzip -q "$WORK/python.zip" -d "$OUT/python"
pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_amd64 \
--python-version 3.12 --implementation cp --dest "$WORK/wheels" -r tg-ws-proxy-requirements.txt
mkdir -p "$OUT/python/Lib/site-packages"
for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done
git -c advice.detachedHead=false clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src"
[ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; }
cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/"
# The embeddable Python reads its path from this file alone: the standard library, the
# wheels, and the source.
printf 'python312.zip\n.\nLib\\site-packages\n..\\app\nimport site\n' > "$OUT/python/python312._pth"
echo "${TG_TAG#v}+py$PY_VERSION" > "$OUT/.version"
echo "tg-ws-proxy ${TG_TAG#v} on Python $PY_VERSION in $OUT"
+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"
+9
View File
@@ -0,0 +1,9 @@
@echo off
:: Proxy Suite: install, or upgrade, as an administrator. Copies the program into
:: %ProgramFiles%\ProxySuite, registers the service there and starts it.
net session >nul 2>&1 || (
powershell -NoProfile -Command "Start-Process -Verb RunAs -FilePath '%~f0'"
exit /b
)
"%~dp0proxy-suite-service.exe" install
pause
+74
View File
@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# 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, 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)
NAME=ProxySuite-$VERSION-windows-x64
DIST=dist/$NAME
CACHE=${CACHE:-${XDG_CACHE_HOME:-$HOME/.cache}/proxy-suite-windows}
rm -rf "$DIST" "dist/$NAME.zip"
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
# 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/"
echo "== THIRD-PARTY.md"
{
echo "# Third-party components"
echo
echo "Proxy Suite for Windows ($VERSION) is MIT-licensed (LICENSE). It carries, unchanged, the"
echo "programs below, each from its project's own release, pinned by version and hash in"
echo "components.json. Their licenses are theirs; where a license asks for its source, it is at"
echo "the address given."
echo
echo "| Component | Version | License | Source |"
echo "|---|---|---|---|"
jq -r '.components | to_entries[] | "| \(.key) | \(.value.version) | \(.value.license) | \(.value.homepage) |"' components.json
echo
echo "Inside them:"
echo
echo "- **WinDivert** (zapret, zapret2): LGPL-3.0 or GPL-2.0, https://github.com/basil00/WinDivert"
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
echo "License files that came with them:"
echo
(cd "$DIST" && find components -iname 'LICENSE*' -o -iname 'COPYING*' | sort | sed 's/^/- /')
} > "$DIST/THIRD-PARTY.md"
echo "== zip"
(cd dist && zip -qr "$NAME.zip" "$NAME")
(cd dist && sha256sum "$NAME.zip" | tee "$NAME.zip.sha256")
du -h "dist/$NAME.zip"
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env python3
"""Parity check: upstream's link parsers (scripts/proxy_parsing.py) against ps-core's.
Feeds the same links to both and reports every link where one accepts and the other
refuses, or both accept with different outbounds. Run from windows/:
python3 -I tools/parity/links.py
"""
import base64
import json
import random
import re
import subprocess
import sys
import urllib.parse
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT / "scripts"))
from proxy_parsing import build_outbound # noqa: E402
PBK = "SbVKOEMjK0sIlbwg4akyBg5mL5KZwwB-ed4eEE7YnRc"
def corpus():
links = set()
# Every link literal in upstream's tests.
for name in ("test-build-outbound.py", "test-fetch-subscription.py"):
text = (ROOT / "scripts" / name).read_text()
links.update(re.findall(r'"((?:vless|vmess|trojan|ss|hy2|hysteria2|tuic|anytls|naive\+https|naive\+quic|socks[45]h?a?|https?)://[^"]*)"', text))
# VMess bodies, which the tests build in code.
for extra in (
{}, {"net": "ws", "path": "/ws", "host": "cdn.example.com", "tls": "tls"}, {"scy": ""}, {"aid": "7"},
{"aid": 70000}, {"net": "grpc", "path": "/svc"}, {"net": "http", "tls": "tls", "alpn": "h2,http/1.1"},
{"port": "0"}, {"port": 443.5}, {"add": "[2001:db8::1]"}, {"fp": "firefox", "tls": "tls"}, {"id": 5},
{"scy": "zero"}, {"net": "kcp"}, {"tls": "reality", "sni": "a.example.com"},
):
body = {"add": "example.com", "port": 443, "id": "00000000-0000-0000-0000-000000000000", "net": "tcp", **extra}
raw = json.dumps(body).encode()
links.add("vmess://" + base64.b64encode(raw).decode())
links.add("vmess://" + base64.urlsafe_b64encode(raw).decode().rstrip("=") + "#Remark")
# Shadowsocks in its three shapes.
for method, pw in (("aes-256-gcm", "pw"), ("chacha20-ietf-poly1305", "p@ss:w"), ("2022-blake3-aes-128-gcm", base64.b64encode(b"k" * 16).decode()), ("none", "")):
cred = f"{method}:{pw}".encode()
links.add(f"ss://{base64.urlsafe_b64encode(cred).decode().rstrip('=')}@ss.example.com:8388#n")
links.add(f"ss://{urllib.parse.quote(method)}:{urllib.parse.quote(pw)}@ss.example.com:8388")
links.add(f"ss://{base64.urlsafe_b64encode(cred + b'@[2001:db8::1]:8388').decode().rstrip('=')}#legacy")
# Mutations of a few rich links: drop, blank or duplicate parameters, change case.
rng = random.Random(1)
seeds = [
f"vless://uuid@example.com:443?type=ws&security=tls&sni=a.example.com&host=h.example.com&path=%2Fp&fp=chrome&alpn=h2,http/1.1&flow=xtls-rprx-vision",
f"vless://uuid@example.com:443?type=tcp&security=reality&pbk={PBK}&sid=ab12&fp=qq&sni=last.fm&spx=%2Fx",
"vless://uuid@example.com:443?type=xhttp&security=tls&mode=packet-up&host=h.example.com&path=%2Fx&x_padding_bytes=100-1000",
"trojan://p%40ss@example.com:443?type=grpc&serviceName=svc&sni=s.example.com&fp=firefox",
"hy2://pw@example.com:443?sni=s.example.com&obfs=salamander&obfs-password=m&mport=20000-30000&insecure=0",
"tuic://00000000-0000-0000-0000-000000000000:pw@example.com:443?sni=s.example.com&alpn=h3&congestion_control=cubic&udp_relay_mode=quic",
"anytls://pw@example.com:443?peer=p.example.com&allowInsecure=1&fp=edge",
"socks5://u%20x:p%3Aw@[2001:db8::2]:1080",
]
for seed in seeds:
links.add(seed)
base, _, query = seed.partition("?")
params = query.split("&") if query else []
for _ in range(60):
p = list(params)
op = rng.randrange(5)
if p and op == 0:
p.pop(rng.randrange(len(p)))
elif p and op == 1:
i = rng.randrange(len(p))
p[i] = p[i].split("=", 1)[0] + "="
elif p and op == 2:
p.append(rng.choice(p))
elif op == 3:
p.append(rng.choice(["type=h2", "type=quic", "type=httpupgrade", "security=none", "fp=random", "fp=unsafe", "ech=udp%3A%2F%2F1.1.1.1", "mode=bogus", "flow=", "sid=zz", "alpn=%5B%22h2%22%5D", "insecure=1", "pinSHA256=" + "ab" * 32]))
else:
base = base.upper() if rng.random() < 0.2 else base
links.add(base + ("?" + "&".join(p) if p else ""))
return sorted(links)
def main():
requests = [
{"url": url, "tag": "t", "backend": backend}
for url in corpus()
for backend in ("sing-box", "xray")
]
rust = subprocess.run(
["cargo", "run", "-q", "-p", "ps-core", "--example", "links_json"],
input="\n".join(json.dumps(r) for r in requests) + "\n",
capture_output=True, text=True, check=True, cwd=ROOT / "windows",
).stdout.splitlines()
mismatches = 0
for req, line in zip(requests, rust):
got = json.loads(line)
try:
want = {"ok": build_outbound(req["url"], req["tag"], backend=req["backend"])}
except Exception as exc: # noqa: BLE001 - every refusal counts
want = {"error": str(exc)}
if ("ok" in got) != ("ok" in want) or ("ok" in got and got["ok"] != want["ok"]):
mismatches += 1
print(f"MISMATCH {req['backend']} {req['url']}\n python: {json.dumps(want)[:300]}\n rust: {json.dumps(got)[:300]}")
accepted = sum("ok" in json.loads(line) for line in rust)
print(f"{len(requests)} cases ({accepted} accepted, {len(requests) - accepted} refused), {mismatches} mismatches")
sys.exit(1 if mismatches else 0)
if __name__ == "__main__":
main()
@@ -0,0 +1,15 @@
# tg-ws-proxy's dependencies for Windows (win_amd64, CPython 3.12), as wheels, by hash.
# Resolved from its pyproject (httpx[http2]==0.28.1, cryptography==46.0.5, certifi): what proxy/ imports.
anyio==4.15.1 --hash=sha256:6152fdbbf9a77fdec97731721bebf7c4c44f7c29b424b0065826173efc7ed101
certifi==2026.10.23 --hash=sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1
cffi==2.1.1 --hash=sha256:f53e442b08449d42821fa4a4fba000095af9f62742a500f978a9f557ec44339a
cryptography==46.0.5 --hash=sha256:38946c54b16c885c72c4f59846be9743d699eee2b69b6988e0a00a01f46a61a4
h11==0.16.0 --hash=sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86
h2==4.4.1 --hash=sha256:0e25f1462b23c9cb82d9eb02e28bc706dac2a68cb457c6a0d74d63c8a2a5d0e6
hpack==4.2.0 --hash=sha256:858ac0b02280fa582b5080d68db0899c62a80375e0e5413a74970c5e518b6986
httpcore==1.0.9 --hash=sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55
httpx==0.28.1 --hash=sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad
hyperframe==6.1.0 --hash=sha256:b03380493a519fce58ea5af42e4a42317bf9bd425596f7a0835ffce80f1a42e5
idna==3.20 --hash=sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c
pycparser==3.12 --hash=sha256:a076f3f489b39b43ed13563a1dafe42447445bec2e294154ec5c57fcdda4c85e
typing-extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8
+9
View File
@@ -0,0 +1,9 @@
@echo off
:: Proxy Suite: remove the service and the program. The configuration and state stay in
:: %ProgramData%\ProxySuite.
net session >nul 2>&1 || (
powershell -NoProfile -Command "Start-Process -Verb RunAs -FilePath '%~f0'"
exit /b
)
:: One line: cmd reads a batch file line by line, and this one is deleted meanwhile.
"%~dp0proxy-suite-service.exe" uninstall & pause & exit /b
+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}")
Loaded 100 of 131 files, more files were not shown because too many files have changed in this diff. Show more