diff --git a/.gitea/workflows/windows-release.yml b/.gitea/workflows/windows-release.yml index e03e6f4..31185a1 100644 --- a/.gitea/workflows/windows-release.yml +++ b/.gitea/workflows/windows-release.yml @@ -1,8 +1,8 @@ name: Windows release -# The Windows port (windows/). On a tag windows-v it builds the release zip and -# publishes it as a Gitea release, with the notes in windows/release-notes/.md. Run -# by hand, it only builds: the zip is the run's artifact. +# The Windows port (windows/). On a tag windows-v it builds the setup program and the +# release zip and publishes them as a Gitea release, with the notes in +# windows/release-notes/.md. Run by hand, it only builds: they are the run's artifact. # # Two jobs, as upstream's dependency updates: the one that runs fetched code (crates, # components, wheels, the Nix closure) holds no token that can write. Only the publishing job @@ -90,7 +90,9 @@ jobs: set -euo pipefail version=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -1) mkdir -p ../release - cp "dist/ProxySuite-$version-windows-x64.zip" "dist/ProxySuite-$version-windows-x64.zip.sha256" ../release/ + for f in "ProxySuite-$version-windows-x64-setup.exe" "ProxySuite-$version-windows-x64.zip"; do + cp "dist/$f" "dist/$f.sha256" ../release/ + done if [ -f "release-notes/$version.md" ]; then cp "release-notes/$version.md" ../release/notes.md; fi - name: Upload @@ -150,7 +152,7 @@ jobs: *) echo "::error::looking up the release for $TAG: HTTP $code: $(cat found.json)"; exit 1 ;; esac - for f in release/*.zip release/*.sha256; do + for f in release/*.exe release/*.zip release/*.sha256; do name=$(basename "$f") for old in $(api "$API/releases/$id/assets" | jq -r --arg n "$name" '.[] | select(.name == $n) | .id'); do api -X DELETE "$API/releases/$id/assets/$old" >/dev/null diff --git a/windows/.cargo/config.toml b/windows/.cargo/config.toml index 3604303..9ca66d9 100644 --- a/windows/.cargo/config.toml +++ b/windows/.cargo/config.toml @@ -4,3 +4,10 @@ # is about their debug info only.) [target.x86_64-pc-windows-msvc] rustflags = ["-C", "target-feature=+crt-static", "-C", "link-arg=/ignore:4099"] + +# GPUI's build compiles its manifest with embed-resource, which would take the dev shell's RC +# (MinGW's windres, for the C cross-compiler) and make a COFF object of it; with llvm-rc it makes +# a .res, which the linker merges with the app's icon (crates/ps-gui/build.rs). Two resource +# objects it refuses. +[env] +RC_x86_64_pc_windows_msvc = "llvm-rc" diff --git a/windows/README.md b/windows/README.md index aaad27c..fc3b83f 100644 --- a/windows/README.md +++ b/windows/README.md @@ -29,7 +29,7 @@ tray icon) or with `proxy-ctl`, as upstream's is. | whitelist-bypass | `whitelistBypass`: [whitelist-bypass](https://github.com/kulikov0/whitelist-bypass)'s headless creators and joiners (WB Stream, Telemost, DION, Bitrix; VK creators), built from upstream's source: a joiner is an outbound of the proxy tunnelled through a video call, a creator the call's free end. `proxy-ctl wl` gives the links and logins | | SSH tunnel | `sshProxy`: Windows' own OpenSSH as a SOCKS listener (`ssh -D`) for other programs, and, with `asOutbound`, an outbound of the proxy (sing-box's SSH client) | | TUN | sing-box's TUN (wintun), `proxy-ctl proxy tun on` — **see the caveats** | -| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy | +| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); 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, the kill switch, server inbounds, the XRay-only backend, autoProxy, zapret2's extended @@ -56,7 +56,8 @@ Needs 64-bit Windows 10 (1903 or later) or 11. | 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 | +| The setup program | under Wine (`tools/wine-setup-test.sh`): a silent install puts every file of the release into Program Files and the entry into Settings → Apps, the service runs and answers; the same setup again over the running install upgrades it; the entry's uninstall removes the service, the files and the entry. Its pages (and the Russian ones) not looked at | +| The app's Windows build | built by the release workflow; its shaders by Microsoft's own `fxc.exe` (under Wine) with GPUI's own arguments; its icon and manifest in its resources, no C runtime DLL among its imports; under Wine it starts and gets as far as drawing text | **Not verified: anything that needs real Windows.** Traffic through sing-box on Windows (Wine lacks an API it needs), the TUN adapter, WinDivert actually rewriting packets, the Windows @@ -66,16 +67,27 @@ there), its tray icon, the system proxy and the Start Menu entry. ## Install -1. Unzip `ProxySuite--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). +1. Download `ProxySuite--windows-x64-setup.exe` and run it. It asks for + administrator rights; SmartScreen may warn of an unknown publisher (the programs are not + signed yet): **More info** → **Run anyway**. +2. It installs everything into `C:\Program Files\ProxySuite`, registers the **ProxySuite** + service (starts at boot), adds `proxy-ctl` to PATH, starts it, and opens the app; the app + starts at every sign-in, in the tray (its shield is green while things work, amber when one + failed, grey when all is off). One option, unchecked: Windows' **OpenSSH Client**, for the + SSH tunnel only, where it was removed from Windows (Windows 10 1809 and later have it). 3. Open **Proxy Suite** from the Start Menu or the tray, or in a **new** terminal: `proxy-ctl status`. -To upgrade, unzip the new release and run its `install.cmd`. To remove, run `uninstall.cmd`; -the configuration and state stay in `%ProgramData%\ProxySuite` until you delete it. +Nothing has to be installed first: the C runtime is linked into the programs, and WinDivert, +wintun, Python, Tor and the rest come with it, as components. For a silent install: +`ProxySuite--windows-x64-setup.exe /S`. + +To upgrade, run the new setup: the settings stay. To remove: **Settings → Apps → Proxy Suite → +Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in +`%ProgramData%\ProxySuite` until you delete it. + +Without the setup program: unzip `ProxySuite--windows-x64.zip` anywhere and run +`install.cmd` (it asks for administrator rights): the same install, from the same files. Windows Defender and other antivirus software may flag WinDivert (zapret's driver): it is a packet-filtering driver, which is what it is for. Remove other DPI-bypass tools first: @@ -179,8 +191,9 @@ On Linux with Nix: `nix develop` here (this directory has its own `flake.nix`), ```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/ +tools/package.sh # the setup program and the zip, in dist/ nix shell nixpkgs#wineWow64Packages.stable -c tools/winws-dry-run.sh dist/ProxySuite-*/components +nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite-*-setup.exe dist/ProxySuite-*-x64 ``` The app on Linux, against the service on Linux: @@ -195,10 +208,12 @@ Its Windows build compiles GPUI's shaders with Microsoft's `fxc.exe` under Wine (`tools/fxc-wine.sh`, fetched from the Windows SDK and pinned by hash; it stays on the build 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). +The Windows programs are cross-compiled with `cargo xwin` (MSVC target, the C runtime linked +in: `.cargo/config.toml`), with the toolchain in `rust-toolchain.toml`. The setup program is +NSIS's (`tools/installer.nsi`, `makensis` from the shell): it unpacks the release and runs its +`proxy-suite-service.exe install`, as `install.cmd` does. Design notes: [`DESIGN.md`](DESIGN.md). Releases are built by Gitea Actions (`.gitea/workflows/windows-release.yml`): bump `version` in `Cargo.toml`, add `release-notes/.md`, push a tag `windows-v`. The -workflow tests, packages and publishes the zip and its `.sha256` with the `RELEASE_TOKEN` +workflow tests, packages and publishes the setup program and the zip, each with its `.sha256`, with the `RELEASE_TOKEN` secret (a token with `write:repository`). Run by hand, it only builds. diff --git a/windows/crates/ps-gui/build.rs b/windows/crates/ps-gui/build.rs index 73b37d8..0077d0c 100644 --- a/windows/crates/ps-gui/build.rs +++ b/windows/crates/ps-gui/build.rs @@ -1,7 +1,8 @@ //! The Windows build carries the app's icon as its resource 1, where GPUI loads its windows' //! icon from (and Explorer, the Start Menu and Settings > Apps show it). The resource compiler -//! is LLVM's (`llvm-rc`, in the dev shell; `RC` names another); without one the app builds -//! with Windows' default icon, and says so. +//! is LLVM's (`llvm-rc`, in the dev shell), or `rc.exe` on Windows; `PS_GUI_RC` names another. +//! (Not `RC`: the dev shell sets that to MinGW's windres, which takes other arguments.) Without +//! one the app builds with Windows' default icon, and says so; tools/package.sh refuses that. use std::path::PathBuf; use std::process::Command; @@ -9,7 +10,7 @@ use std::process::Command; fn main() { let icon = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("assets/proxy-suite.ico"); println!("cargo:rerun-if-changed={}", icon.display()); - println!("cargo:rerun-if-env-changed=RC"); + println!("cargo:rerun-if-env-changed=PS_GUI_RC"); if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") { return; } @@ -18,7 +19,7 @@ fn main() { let res = out.join("app.res"); // The resource script's strings are C strings: backslashes doubled. std::fs::write(&rc, format!("1 ICON \"{}\"\n", icon.display().to_string().replace('\\', "\\\\"))).unwrap(); - let compiler = std::env::var("RC").unwrap_or_else(|_| if cfg!(windows) { "rc.exe".into() } else { "llvm-rc".into() }); + let compiler = std::env::var("PS_GUI_RC").unwrap_or_else(|_| if cfg!(windows) { "rc.exe".into() } else { "llvm-rc".into() }); let mut command = Command::new(&compiler); command.arg("/nologo"); if compiler.contains("llvm-rc") { diff --git a/windows/crates/ps-service/src/winsvc.rs b/windows/crates/ps-service/src/winsvc.rs index 41c59b4..a7ff971 100644 --- a/windows/crates/ps-service/src/winsvc.rs +++ b/windows/crates/ps-service/src/winsvc.rs @@ -144,6 +144,9 @@ pub fn install() -> Result<()> { Ok(false) => {} Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"), } + if let Err(e) = apps::add(&to) { + println!("warning: the entry in Settings → Apps: {e:#}"); + } println!("Open a new terminal and try: proxy-ctl status"); Ok(()) } @@ -163,8 +166,10 @@ pub fn uninstall() -> Result<()> { } else { println!("{DISPLAY} was not installed."); } + remove_windivert(&manager); let dir = install_dir(); desktop::remove(); + apps::remove(); let _ = path::remove(&dir); if dir.exists() { // This program may be one of the files: they go a moment after it exits. Raw, as cmd @@ -185,6 +190,100 @@ pub fn uninstall() -> Result<()> { Ok(()) } +/// The WinDivert driver zapret loaded from this suite's components, if it is still registered +/// (WinDivert removes its own service as it loads, but one stopped hard can stay): stopped and +/// deleted, as Flowseal's service.bat removes it. One from elsewhere is left alone. +fn remove_windivert(manager: &ServiceManager) { + let ours = crate::paths::Paths::platform_default().root.to_string_lossy().to_lowercase(); + for name in ["WinDivert", "WinDivert14"] { + let Ok(service) = manager.open_service(name, ServiceAccess::QUERY_CONFIG | ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) else { + continue; + }; + let Ok(config) = service.query_config() else { continue }; + if config.executable_path.to_string_lossy().to_lowercase().contains(&ours) { + let _ = service.stop(); + if service.delete().is_ok() { + println!("WinDivert's driver ({name}) is removed."); + } + } + } +} + +/// The entry in Settings → Apps (and Control Panel's Programs and Features): its Uninstall runs +/// uninstall.cmd, which asks for administrator rights; `QuietUninstallString` (winget, scripts +/// that run elevated) the service's own `uninstall`. +mod apps { + use std::path::Path; + + use anyhow::{Result, bail}; + use windows_sys::Win32::Foundation::ERROR_SUCCESS; + use windows_sys::Win32::System::Registry::{ + HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_DWORD, REG_OPTION_NON_VOLATILE, REG_SZ, RegCloseKey, RegCreateKeyExW, RegDeleteTreeW, + RegSetValueExW, + }; + + const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite"; + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + fn size_kib(dir: &Path) -> u64 { + fn walk(dir: &Path) -> u64 { + std::fs::read_dir(dir).into_iter().flatten().flatten().map(|e| match e.file_type() { + Ok(t) if t.is_dir() => walk(&e.path()), + Ok(t) if t.is_file() => e.metadata().map_or(0, |m| m.len()), + _ => 0, + }).sum() + } + walk(dir) / 1024 + } + + pub fn add(dir: &Path) -> Result<()> { + let system = std::env::var("SystemRoot").unwrap_or_else(|_| r"C:\Windows".into()); + let d = dir.display(); + let text = [ + ("DisplayName", super::DISPLAY.to_owned()), + ("DisplayVersion", env!("CARGO_PKG_VERSION").to_owned()), + ("Publisher", "Proxy Suite".to_owned()), + ("URLInfoAbout", "https://git.faumaray.com/faumaray/proxy-suite-flake".to_owned()), + ("InstallLocation", d.to_string()), + ("DisplayIcon", format!("{d}\\proxy-suite.exe")), + // cmd's /c takes the whole line in one more pair of quotes. + ("UninstallString", format!("\"{system}\\System32\\cmd.exe\" /c \"\"{d}\\uninstall.cmd\"\"")), + ("QuietUninstallString", format!("\"{d}\\proxy-suite-service.exe\" uninstall")), + ]; + let numbers = [("NoModify", 1u32), ("NoRepair", 1), ("EstimatedSize", size_kib(dir).min(u32::MAX as u64) as u32)]; + // SAFETY: NUL-terminated names and data, lengths as given; the key is closed below. + unsafe { + let mut key: HKEY = std::ptr::null_mut(); + if RegCreateKeyExW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr(), 0, std::ptr::null(), REG_OPTION_NON_VOLATILE, KEY_WRITE, std::ptr::null(), &mut key, std::ptr::null_mut()) != ERROR_SUCCESS { + bail!("cannot create the uninstall key"); + } + let mut failed = false; + for (name, value) in &text { + let data = wide(value); + failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) != ERROR_SUCCESS; + } + for (name, value) in &numbers { + failed |= RegSetValueExW(key, wide(name).as_ptr(), 0, REG_DWORD, (value as *const u32).cast(), 4) != ERROR_SUCCESS; + } + RegCloseKey(key); + if failed { + bail!("cannot write the uninstall key"); + } + } + Ok(()) + } + + pub fn remove() { + // SAFETY: a NUL-terminated name. + unsafe { + RegDeleteTreeW(HKEY_LOCAL_MACHINE, wide(KEY).as_ptr()); + } + } +} + /// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray; /// closed before its files are replaced or removed. mod desktop { diff --git a/windows/flake.nix b/windows/flake.nix index d974685..3966538 100644 --- a/windows/flake.nix +++ b/windows/flake.nix @@ -56,6 +56,8 @@ openssh # wireproxy-awg and whitelist-bypass, built from source (Go cross-compiles). go + # The setup program (tools/installer.nsi). + nsis ]; buildInputs = guiLibs; LD_LIBRARY_PATH = pkgs.lib.makeLibraryPath guiLibs; diff --git a/windows/release-notes/0.2.0-pre.1.md b/windows/release-notes/0.2.0-pre.1.md index 5ead068..684530b 100644 --- a/windows/release-notes/0.2.0-pre.1.md +++ b/windows/release-notes/0.2.0-pre.1.md @@ -1,4 +1,4 @@ -The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`. +The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ctl`; and a setup program. **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. @@ -6,10 +6,12 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct - **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. +- **Whitelist bypass:** joiners and creators, added or removed; a joiner's call link given, a creator's call link copied, its login given (a cookies file, or DION's and Bitrix's email and password). - **Outbounds:** add one from a link; pin, test delays, leave out, remove; the routing mode; subscriptions. - **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. +- **Icon:** the app has one now (window, taskbar, Start Menu, Settings → Apps). - **Tray:** a shield, green while things work, amber when one failed, grey when all is off; its menu switches the proxy, the DPI bypass and the Telegram proxy. - **System proxy:** the app can point Windows' proxy setting (browsers, most programs) at the local proxy while it runs, and puts yours back after. @@ -24,10 +26,14 @@ The desktop app: Proxy Suite now has a window and a tray icon, besides `proxy-ct - 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`). +- A setup program (`…-setup.exe`, English and Russian), with an uninstaller in Settings → Apps; `install.cmd` from the zip makes that entry too. Uninstalling removes WinDivert's driver service too, when it is the suite's. +- The programs carry their C runtime: no Visual C++ Redistributable needed. - 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. +Download `ProxySuite-0.2.0-pre.1-windows-x64-setup.exe` and run it (its SHA-256 is in the `.sha256` file next to it); SmartScreen may warn of an unknown publisher, the programs are not signed yet (**More info** → **Run anyway**). It installs everything, starts the service and the app, and adds Proxy Suite to **Settings → Apps**, where its **Uninstall** is. Nothing has to be installed first: the programs carry their C runtime now. Needs 64-bit Windows 10 (1903 or later) or 11. + +The zip is still there, the same files with `install.cmd`. ### Not yet AmneziaWG as a system-wide VPN, Tor's onion service, the kill switch, server inbounds, the XRay-only backend, zapret2's extended detection and the z2k strategies. diff --git a/windows/tools/build-tg-ws-proxy.sh b/windows/tools/build-tg-ws-proxy.sh index e93b3e5..02162ff 100755 --- a/windows/tools/build-tg-ws-proxy.sh +++ b/windows/tools/build-tg-ws-proxy.sh @@ -5,6 +5,7 @@ # # tools/build-tg-ws-proxy.sh OUT_DIR (needs curl, git, unzip, pip) set -euo pipefail +. "$(dirname "$0")/lib.sh" OUT=$(realpath -m "${1:?output directory}") cd "$(dirname "$0")" PY_VERSION=3.12.10 @@ -25,7 +26,7 @@ pip download -q --require-hashes --no-deps --only-binary=:all: --platform win_am mkdir -p "$OUT/python/Lib/site-packages" for w in "$WORK"/wheels/*.whl; do unzip -q -o "$w" -d "$OUT/python/Lib/site-packages"; done -git -c advice.detachedHead=false clone -q --depth 1 --branch "$TG_TAG" https://github.com/Flowseal/tg-ws-proxy "$WORK/src" +clone_tag https://github.com/Flowseal/tg-ws-proxy "$TG_TAG" "$WORK/src" [ "$(git -C "$WORK/src" rev-parse HEAD)" = "$TG_COMMIT" ] || { echo "tag $TG_TAG moved off $TG_COMMIT"; exit 1; } cp -r "$WORK/src/proxy" "$WORK/src/utils" "$WORK/src/LICENSE" "$OUT/app/" diff --git a/windows/tools/build-whitelist-bypass.sh b/windows/tools/build-whitelist-bypass.sh index ece3799..e6e93c1 100755 --- a/windows/tools/build-whitelist-bypass.sh +++ b/windows/tools/build-whitelist-bypass.sh @@ -6,6 +6,7 @@ # # tools/build-whitelist-bypass.sh OUT_DIR [GOOS] (needs git, go, sed; GOOS: windows) set -euo pipefail +. "$(dirname "$0")/lib.sh" OUT=$(realpath -m "${1:?output directory}") GOOS=${2:-windows} VERSION=0.4.4 @@ -13,7 +14,7 @@ COMMIT=7c19a7ec40900940fe0c43ea1db7768ee632393d WORK=$(mktemp -d) trap 'rm -rf "$WORK"' EXIT -git -c advice.detachedHead=false clone -q --depth 1 --branch "v$VERSION" https://github.com/kulikov0/whitelist-bypass "$WORK/src" +clone_tag https://github.com/kulikov0/whitelist-bypass "v$VERSION" "$WORK/src" [ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; } cd "$WORK/src" diff --git a/windows/tools/build-wireproxy-awg.sh b/windows/tools/build-wireproxy-awg.sh index 82cc2ee..eb63acb 100755 --- a/windows/tools/build-wireproxy-awg.sh +++ b/windows/tools/build-wireproxy-awg.sh @@ -6,6 +6,7 @@ # # tools/build-wireproxy-awg.sh OUT_DIR [GOOS] (needs git, go, patch; GOOS: windows) set -euo pipefail +. "$(dirname "$0")/lib.sh" OUT=$(realpath -m "${1:?output directory}") GOOS=${2:-windows} cd "$(dirname "$0")" @@ -15,7 +16,7 @@ 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" +clone_tag https://github.com/artem-russkikh/wireproxy-awg "v$VERSION" "$WORK/src" [ "$(git -C "$WORK/src" rev-parse HEAD)" = "$COMMIT" ] || { echo "tag v$VERSION moved off $COMMIT"; exit 1; } cd "$WORK/src" patch -s -p1 <"$PATCHES/wireproxy-awg-fwmark.patch" diff --git a/windows/tools/installer.nsi b/windows/tools/installer.nsi new file mode 100644 index 0000000..087f55f --- /dev/null +++ b/windows/tools/installer.nsi @@ -0,0 +1,126 @@ +; Proxy Suite's setup program. It unpacks the release into its temporary folder and runs the +; release's own `proxy-suite-service.exe install` from there, as install.cmd does from the zip: +; that stops what runs, copies the release into Program Files, registers the service, PATH, the +; Start Menu entry, the app at sign-in and the entry in Settings > Apps, and starts it all. +; Unpacked straight into Program Files instead, an upgrade would find its files in use. +; The uninstaller is that entry's: uninstall.cmd, which the release carries. +; +; makensis -INPUTCHARSET UTF8 -DVERSION=0.2.0-pre.1 -DVERSION4=0.2.0.0 -DRELEASE= +; -DICON=crates/ps-gui/assets/proxy-suite.ico -DOUT= tools/installer.nsi +; +; Everything the programs need is in the release: the C runtime is linked in, WinDivert, wintun, +; Python and the rest are components. Windows' OpenSSH Client (the SSH tunnel) is Windows' own: +; offered, unchecked, for a Windows that had it removed. + +Unicode true +ManifestDPIAware true +RequestExecutionLevel admin +; Solid, with a dictionary that keeps the build's memory modest: the release is ~600 MB of +; programs, many alike (whitelist-bypass's nine). +SetCompressor /SOLID /FINAL lzma +SetCompressorDictSize 32 + +!include MUI2.nsh +!include LogicLib.nsh +!include x64.nsh +!include WinVer.nsh + +Name "Proxy Suite" +OutFile "${OUT}" +InstallDir "$PROGRAMFILES64\ProxySuite" +BrandingText "Proxy Suite ${VERSION}" +ShowInstDetails show + +VIProductVersion "${VERSION4}" +VIAddVersionKey /LANG=0 "ProductName" "Proxy Suite" +VIAddVersionKey /LANG=0 "ProductVersion" "${VERSION}" +VIAddVersionKey /LANG=0 "FileVersion" "${VERSION}" +VIAddVersionKey /LANG=0 "FileDescription" "Proxy Suite setup" +VIAddVersionKey /LANG=0 "LegalCopyright" "MIT License" + +!define MUI_ICON "${ICON}" +!define MUI_ABORTWARNING +!define MUI_FINISHPAGE_TITLE "$(FinishTitle)" +!define MUI_FINISHPAGE_TEXT "$(FinishText)" +!define MUI_FINISHPAGE_NOAUTOCLOSE + +!insertmacro MUI_PAGE_WELCOME +!insertmacro MUI_PAGE_LICENSE "${RELEASE}/LICENSE" +!insertmacro MUI_PAGE_COMPONENTS +!insertmacro MUI_PAGE_INSTFILES +!insertmacro MUI_PAGE_FINISH + +; The first is the default; Windows' own language picks among them. +!insertmacro MUI_LANGUAGE "English" +!insertmacro MUI_LANGUAGE "Russian" + +LangString NeedX64 ${LANG_ENGLISH} "Proxy Suite needs 64-bit Windows." +LangString NeedX64 ${LANG_RUSSIAN} "Для Proxy Suite нужна 64-битная Windows." +LangString NeedBuild ${LANG_ENGLISH} "Proxy Suite needs Windows 10 version 1903 or later, or Windows 11." +LangString NeedBuild ${LANG_RUSSIAN} "Для Proxy Suite нужна Windows 10 версии 1903 или новее либо Windows 11." +LangString Failed ${LANG_ENGLISH} "Setup did not finish: the details are in the list above. Nothing that was installed before is lost." +LangString Failed ${LANG_RUSSIAN} "Установка не завершена: подробности в списке выше. Установленное ранее не потеряно." +LangString MainName ${LANG_ENGLISH} "Proxy Suite" +LangString MainName ${LANG_RUSSIAN} "Proxy Suite" +LangString MainDesc ${LANG_ENGLISH} "The service, the app, proxy-ctl and every component (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass), into Program Files. Settings already made are kept." +LangString MainDesc ${LANG_RUSSIAN} "Служба, приложение, proxy-ctl и все компоненты (sing-box, XRay, zapret, zapret2, Tor, tg-ws-proxy, wireproxy-awg, whitelist-bypass) в Program Files. Сделанные ранее настройки сохраняются." +LangString SshName ${LANG_ENGLISH} "Windows OpenSSH Client" +LangString SshName ${LANG_RUSSIAN} "Клиент OpenSSH Windows" +LangString SshDesc ${LANG_ENGLISH} "For the SSH tunnel only. Windows 10 1809 and later have it already; this adds it from Windows Update where it was removed." +LangString SshDesc ${LANG_RUSSIAN} "Нужен только для SSH-туннеля. В Windows 10 1809 и новее он уже есть; здесь он добавляется из Центра обновления, если его удалили." +LangString SshThere ${LANG_ENGLISH} "The OpenSSH Client is there already." +LangString SshThere ${LANG_RUSSIAN} "Клиент OpenSSH уже установлен." +LangString SshFailed ${LANG_ENGLISH} "The OpenSSH Client could not be added (is Windows Update reachable?). Everything else works without it; add it later in Settings > System > Optional features." +LangString SshFailed ${LANG_RUSSIAN} "Не удалось добавить клиент OpenSSH (доступен ли Центр обновления?). Всё остальное работает без него; его можно добавить позже: Параметры > Система > Дополнительные компоненты." +LangString FinishTitle ${LANG_ENGLISH} "Proxy Suite is installed" +LangString FinishTitle ${LANG_RUSSIAN} "Proxy Suite установлен" +LangString FinishText ${LANG_ENGLISH} "Its service runs, and the app is in the tray (the shield) and the Start Menu; it starts at every sign-in.$\r$\n$\r$\nIn a new terminal: proxy-ctl status.$\r$\n$\r$\nTo remove it: Settings > Apps > Proxy Suite." +LangString FinishText ${LANG_RUSSIAN} "Служба запущена, приложение в трее (щит) и в меню «Пуск»; оно запускается при каждом входе в систему.$\r$\n$\r$\nВ новом терминале: proxy-ctl status.$\r$\n$\r$\nУдаление: Параметры > Приложения > Proxy Suite." + +Function .onInit + ${IfNot} ${RunningX64} + MessageBox MB_ICONSTOP "$(NeedX64)" /SD IDOK + Abort + ${EndIf} + ${IfNot} ${AtLeastBuild} 18362 + MessageBox MB_ICONSTOP "$(NeedBuild)" /SD IDOK + Abort + ${EndIf} + InitPluginsDir +FunctionEnd + +Section "$(MainName)" SecMain + SectionIn RO + SetOutPath "$PLUGINSDIR\release" + File /r "${RELEASE}/*" + DetailPrint "proxy-suite-service install" + nsExec::ExecToLog '"$PLUGINSDIR\release\proxy-suite-service.exe" install' + Pop $0 + ; Out of the folder, so that it goes with $PLUGINSDIR when setup ends. + SetOutPath "$TEMP" + ${If} $0 != 0 + DetailPrint "$(Failed)" + MessageBox MB_ICONSTOP "$(Failed)" /SD IDOK + SetErrorLevel 2 + Abort + ${EndIf} +SectionEnd + +Section /o "$(SshName)" SecSsh + ; This setup runs as a 32-bit program: Sysnative is the real System32. + ${If} ${FileExists} "$WINDIR\Sysnative\OpenSSH\ssh.exe" + DetailPrint "$(SshThere)" + ${Else} + nsExec::ExecToLog '"$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -Command "Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0 | Out-Null; if (-not (Test-Path $$env:SystemRoot\System32\OpenSSH\ssh.exe)) { exit 1 }"' + Pop $0 + ${If} $0 != 0 + DetailPrint "$(SshFailed)" + MessageBox MB_ICONEXCLAMATION "$(SshFailed)" /SD IDOK + ${EndIf} + ${EndIf} +SectionEnd + +!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN + !insertmacro MUI_DESCRIPTION_TEXT ${SecMain} "$(MainDesc)" + !insertmacro MUI_DESCRIPTION_TEXT ${SecSsh} "$(SshDesc)" +!insertmacro MUI_FUNCTION_DESCRIPTION_END diff --git a/windows/tools/lib.sh b/windows/tools/lib.sh new file mode 100644 index 0000000..62fb5ea --- /dev/null +++ b/windows/tools/lib.sh @@ -0,0 +1,30 @@ +# Shared by tools/build-*.sh (sourced). + +# clone_tag URL TAG DIR: a shallow clone of TAG into DIR, tried three times: a transfer that +# stalls (GitHub's sometimes do) is given up after a minute, a connection that hangs by curl's +# own timeout; a slow one is waited for. With SRC_CACHE set, a clone made is kept there and +# the next build copies it rather than fetching it again (the scripts check its commit either +# way). +clone_tag() { + local url=$1 tag=$2 dir=$3 try cached="" + if [ -n "${SRC_CACHE:-}" ]; then + cached="$SRC_CACHE/$(basename "$url")@$tag" + if [ -d "$cached/.git" ]; then + # Its files as its commit has them, whatever happened to the copy since. + rm -rf "$dir" && cp -a "$cached" "$dir" && git -C "$dir" reset -q --hard && git -C "$dir" clean -qfdx && return 0 + fi + fi + for try in 1 2 3; do + rm -rf "$dir" + if git -c advice.detachedHead=false -c http.lowSpeedLimit=1000 -c http.lowSpeedTime=60 \ + clone -q --depth 1 --branch "$tag" "$url" "$dir"; then + if [ -n "$cached" ]; then + mkdir -p "$SRC_CACHE" && rm -rf "$cached.tmp" && cp -a "$dir" "$cached.tmp" && mv "$cached.tmp" "$cached" + fi + return 0 + fi + echo "cloning $url ($tag) failed, try $try of 3" >&2 + sleep 5 + done + return 1 +} diff --git a/windows/tools/package.sh b/windows/tools/package.sh index 7c065b3..3d66661 100755 --- a/windows/tools/package.sh +++ b/windows/tools/package.sh @@ -1,16 +1,19 @@ #!/usr/bin/env bash -# The release: ProxySuite--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. +# The release, in dist/: ProxySuite--windows-x64-setup.exe, the setup program, and +# ProxySuite--windows-x64.zip, the same unpacked with install.cmd. Both hold 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) +# nix develop --command tools/package.sh (needs curl, git, unzip, zip, pip, go, makensis; +# 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} +# The sources tools/build-*.sh clone, kept for the next build. +export SRC_CACHE=$CACHE/src rm -rf "$DIST" "dist/$NAME.zip" mkdir -p "$DIST/components" @@ -30,6 +33,8 @@ GPUI_FXC_PATH="$PWD/tools/fxc-wine.sh" cargo xwin build -q --release -p ps-gui - for exe in proxy-suite-service proxy-ctl proxy-suite; do cp "target/x86_64-pc-windows-msvc/release/$exe.exe" "$DIST/" done +# Its build only warns without its icon (cargo -q shows no warning): the release has it. +llvm-readobj --coff-resources "$DIST/proxy-suite.exe" | grep 'Type: ICON' >/dev/null || { echo "proxy-suite.exe has no icon"; exit 1; } cp ../LICENSE README.md "$DIST/" cp tools/install.cmd tools/uninstall.cmd "$DIST/" @@ -73,4 +78,11 @@ echo "== 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" + +echo "== setup" +# Windows' file version takes four numbers: 0.2.0-pre.1 is 0.2.0.0. +VERSION4=$(sed 's/-.*//' <<<"$VERSION").0 +rm -f "dist/$NAME-setup.exe" +makensis -V2 -INPUTCHARSET UTF8 -DVERSION="$VERSION" -DVERSION4="$VERSION4" -DRELEASE="$PWD/$DIST" -DICON="$PWD/crates/ps-gui/assets/proxy-suite.ico" -DOUT="$PWD/dist/$NAME-setup.exe" tools/installer.nsi +(cd dist && sha256sum "$NAME-setup.exe" | tee "$NAME-setup.exe.sha256") +du -h "dist/$NAME.zip" "dist/$NAME-setup.exe" diff --git a/windows/tools/wine-setup-test.sh b/windows/tools/wine-setup-test.sh new file mode 100755 index 0000000..8e56c85 --- /dev/null +++ b/windows/tools/wine-setup-test.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# The setup program under Wine: a silent install into Program Files (every file, the +# components' manifests among them), the entry in Settings > Apps, the service registered and +# answering over its pipe; the same setup again over the running install (an upgrade); then the +# entry's quiet uninstall, after which the service, the files and the entry are gone. +# +# nix shell nixpkgs#wineWow64Packages.stable -c tools/wine-setup-test.sh dist/ProxySuite--windows-x64-setup.exe [RELEASE_DIR] +# +# RELEASE_DIR (the unpacked release the setup was made of): its files are compared with the +# installed ones. +set -euo pipefail +SETUP=$(realpath "${1:?the setup program}") +REL=${2:+$(realpath "$2")} +WORK=$(mktemp -d) +export WINEPREFIX=${WINEPREFIX:-$WORK/prefix} WINEDEBUG=-all +trap 'wineserver -k 2>/dev/null || true; rm -rf "$WORK"' EXIT +wineboot -i >/dev/null 2>&1 || true +for key in Tcpip Tcpip6; do + wine reg add "HKLM\\SYSTEM\\CurrentControlSet\\Services\\$key\\Parameters\\Interfaces" /f >/dev/null 2>&1 +done +PF="$WINEPREFIX/drive_c/Program Files/ProxySuite" +KEY='HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall\ProxySuite' +fail() { echo "FAIL: $*"; exit 1; } + +state() { local st; st=$(wine sc query ProxySuite 2>/dev/null || true); st=${st//$'\r'/}; grep STATE <<<"$st" | grep -o '[A-Z_]*$' || echo NONE; } +# Wine's manager often fails the first start right after a create (wine-install-test.sh says +# more); a second start works. +running() { + local s last="" + for _ in $(seq 60); do + s=$(state) + [ "$s" = "$last" ] || echo " $s" + last=$s + [ "$s" = RUNNING ] && return 0 + [ "$s" = STOPPED ] && { wine sc start ProxySuite >/dev/null 2>&1 || true; } + sleep 3 + done + return 1 +} + +echo "== setup /S" +wine "$SETUP" /S && rc=0 || rc=$? +echo " exit code $rc" +[ "$rc" = 0 ] || fail "setup exited with $rc" +[ -f "$PF/proxy-suite-service.exe" ] || fail "nothing in Program Files" +ls "$PF" | sed 's/^/ /' +if [ -n "$REL" ]; then + # Every file of the release, dotfiles too (the components' .files.json and .version). + missing=$(cd "$REL" && find . -type f | while read -r f; do [ -f "$PF/$f" ] || echo "$f"; done) + [ -z "$missing" ] || fail "not installed: $missing" + echo " every file of the release is there ($(cd "$REL" && find . -type f | wc -l))" +fi +ls "$PF"/components/*/.files.json >/dev/null || fail "no component manifests" + +echo "== Settings > Apps" +entry=$(wine reg query "$KEY" 2>/dev/null | tr -d '\r') || fail "no uninstall entry" +sed 's/^/ /' <<<"$entry" +for v in DisplayName DisplayVersion UninstallString QuietUninstallString InstallLocation EstimatedSize; do + grep -q "$v" <<<"$entry" || fail "the entry has no $v" +done + +echo "== the service" +running || fail "the service is $(state)" +for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done +wine "$PF/proxy-ctl.exe" components | tr -d '\r' | sed 's/^/ /' || fail "no answer over the pipe" + +echo "== setup /S again, over the running install" +wine "$SETUP" /S && rc=0 || rc=$? +[ "$rc" = 0 ] || fail "the upgrade exited with $rc" +running || fail "after the upgrade the service is $(state)" +for _ in $(seq 30); do wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 && break; sleep 1; done +wine "$PF/proxy-ctl.exe" status >/dev/null 2>&1 || fail "no answer after the upgrade" +echo " upgraded, running, answering" + +echo "== the entry's quiet uninstall" +quiet=$(wine reg query "$KEY" /v QuietUninstallString | tr -d '\r' | sed -n 's/.*REG_SZ *//p') +echo " $quiet" +# Its command line, as Windows would run it: the quoted program, then its argument. +prog=${quiet#\"}; prog=${prog%%\"*} +wine "$prog" uninstall +sleep 6 +[ "$(state)" = NONE ] || fail "the service is still there: $(state)" +wine reg query "$KEY" >/dev/null 2>&1 && fail "the entry is still there" +[ ! -e "$PF" ] || fail "Program Files\\ProxySuite is still there: $(ls "$PF")" +echo "OK: installed, upgraded and removed by the setup program and its entry"