From 6ed7a3b1c69f5c3554e32dcff206b6f608f14f55 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 27 Oct 2026 02:12:02 +0300 Subject: [PATCH] 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 --- windows/crates/ps-core/tests/render.rs | 8 +- windows/crates/ps-gui/src/model.rs | 2 +- windows/crates/ps-gui/src/sysproxy.rs | 7 +- windows/crates/ps-service/Cargo.toml | 1 + windows/crates/ps-service/src/clash.rs | 1 + windows/crates/ps-service/src/paths.rs | 2 +- windows/crates/ps-service/src/winsvc.rs | 140 +++++++++++++++++++++++- 7 files changed, 152 insertions(+), 9 deletions(-) diff --git a/windows/crates/ps-core/tests/render.rs b/windows/crates/ps-core/tests/render.rs index 93a140e..8fc8232 100644 --- a/windows/crates/ps-core/tests/render.rs +++ b/windows/crates/ps-core/tests/render.rs @@ -2,7 +2,7 @@ //! `xray run -test`, when they are on PATH (the dev shell has both). use std::collections::BTreeMap; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::Command; use ps_core::config::*; @@ -22,7 +22,7 @@ fn scratch(name: &str) -> PathBuf { dir } -fn env(dir: &PathBuf) -> Env { +fn env(dir: &Path) -> Env { let empty = dir.join("empty.json"); std::fs::write(&empty, r#"{"version":1,"rules":[]}"#).unwrap(); let mut warp = BTreeMap::new(); @@ -45,7 +45,7 @@ fn no_files(path: &str) -> Result { Err(format!("{path}: not found")) } -fn check_sing_box(config: &Value, dir: &PathBuf) { +fn check_sing_box(config: &Value, dir: &Path) { if !have("sing-box") { eprintln!("sing-box not on PATH: skipping the check"); return; @@ -61,7 +61,7 @@ fn check_sing_box(config: &Value, dir: &PathBuf) { ); } -fn check_xray(config: &Value, dir: &PathBuf) { +fn check_xray(config: &Value, dir: &Path) { if !have("xray") { return; } diff --git a/windows/crates/ps-gui/src/model.rs b/windows/crates/ps-gui/src/model.rs index 4058d10..7b6cbe1 100644 --- a/windows/crates/ps-gui/src/model.rs +++ b/windows/crates/ps-gui/src/model.rs @@ -52,7 +52,7 @@ impl Model { 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 % 5 == 0 || reconnect { Some(poller.call(Request::Outbounds).await) } else { None }; + 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 { diff --git a/windows/crates/ps-gui/src/sysproxy.rs b/windows/crates/ps-gui/src/sysproxy.rs index 810b0ec..2e6ac63 100644 --- a/windows/crates/ps-gui/src/sysproxy.rs +++ b/windows/crates/ps-gui/src/sysproxy.rs @@ -29,7 +29,10 @@ impl SystemProxy { return Ok(()); } if self.saved.is_none() { - self.saved = Some(platform::read()?); + // One the app left set (it was killed) is not the user's: theirs was off. + let now = platform::read()?; + let left = now.enable && now.server == ours.server; + self.saved = Some(if left { Settings { enable: false, ..now } } else { now }); } platform::write(&ours)?; self.applied = Some(ours); @@ -113,7 +116,7 @@ mod platform { } fn text(bytes: Vec) -> String { - let units: Vec = bytes.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|u| *u != 0).collect(); + let units: Vec = bytes.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).take_while(|u| *u != 0).collect(); String::from_utf16_lossy(&units) } diff --git a/windows/crates/ps-service/Cargo.toml b/windows/crates/ps-service/Cargo.toml index 40f0a33..cd80415 100644 --- a/windows/crates/ps-service/Cargo.toml +++ b/windows/crates/ps-service/Cargo.toml @@ -36,6 +36,7 @@ windows-sys = { workspace = true, features = [ "Win32_System_Registry", "Win32_UI_WindowsAndMessaging", "Win32_System_Threading", + "Win32_Networking_WinInet", ] } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/windows/crates/ps-service/src/clash.rs b/windows/crates/ps-service/src/clash.rs index c619855..bc8c959 100644 --- a/windows/crates/ps-service/src/clash.rs +++ b/windows/crates/ps-service/src/clash.rs @@ -23,6 +23,7 @@ fn encode(segment: &str) -> String { out } +#[allow(dead_code, reason = "for switching the selection live, which is to come")] impl Clash { pub fn new(port: u16, secret: &str) -> Self { let http = reqwest::Client::builder() diff --git a/windows/crates/ps-service/src/paths.rs b/windows/crates/ps-service/src/paths.rs index b01e558..3d15812 100644 --- a/windows/crates/ps-service/src/paths.rs +++ b/windows/crates/ps-service/src/paths.rs @@ -174,7 +174,7 @@ mod secure { let mut system_owner = true; for attempt in 0..4 { let sd = descriptor(system_owner)?; - let mut attrs = SECURITY_ATTRIBUTES { + let attrs = SECURITY_ATTRIBUTES { nLength: std::mem::size_of::() as u32, lpSecurityDescriptor: sd.0, bInheritHandle: 0, diff --git a/windows/crates/ps-service/src/winsvc.rs b/windows/crates/ps-service/src/winsvc.rs index 27f7cd8..41c59b4 100644 --- a/windows/crates/ps-service/src/winsvc.rs +++ b/windows/crates/ps-service/src/winsvc.rs @@ -25,7 +25,7 @@ pub fn install_dir() -> PathBuf { } /// The files of a release that `install` copies. -const RELEASE_FILES: [&str; 7] = ["proxy-suite-service.exe", "proxy-ctl.exe", "README.md", "THIRD-PARTY.md", "LICENSE", "install.cmd", "uninstall.cmd"]; +const RELEASE_FILES: [&str; 8] = ["proxy-suite-service.exe", "proxy-ctl.exe", "proxy-suite.exe", "README.md", "THIRD-PARTY.md", "LICENSE", "install.cmd", "uninstall.cmd"]; fn copy_release(from: &Path, to: &Path) -> Result<()> { std::fs::create_dir_all(to)?; @@ -97,6 +97,7 @@ pub fn install() -> Result<()> { wait_stopped(&existing)?; } if from != to { + desktop::close(); copy_release(&from, &to)?; } existing.change_config(&info)?; @@ -104,6 +105,7 @@ pub fn install() -> Result<()> { } Err(_) => { if from != to { + desktop::close(); copy_release(&from, &to)?; } manager.create_service(&info, access).context("creating the service")? @@ -134,6 +136,14 @@ pub fn install() -> Result<()> { println!("Start it with: sc start {NAME} (its log: %ProgramData%\\ProxySuite\\logs\\service.log)"); } } + match desktop::add(&to) { + Ok(true) => { + desktop::start(&to); + println!("The app is in the Start Menu (Proxy Suite) and starts at sign-in, in the tray."); + } + Ok(false) => {} + Err(e) => println!("warning: the app's Start Menu entry and start at sign-in: {e:#}"), + } println!("Open a new terminal and try: proxy-ctl status"); Ok(()) } @@ -154,6 +164,7 @@ pub fn uninstall() -> Result<()> { println!("{DISPLAY} was not installed."); } let dir = install_dir(); + desktop::remove(); let _ = path::remove(&dir); if dir.exists() { // This program may be one of the files: they go a moment after it exits. Raw, as cmd @@ -174,6 +185,133 @@ pub fn uninstall() -> Result<()> { Ok(()) } +/// The desktop app: a Start Menu entry for everyone, and started at each sign-in into the tray; +/// closed before its files are replaced or removed. +mod desktop { + use std::os::windows::process::CommandExt; + use std::path::{Path, PathBuf}; + use std::process::{Command, Stdio}; + + use anyhow::{Result, bail}; + use windows_sys::Win32::Foundation::ERROR_SUCCESS; + use windows_sys::Win32::System::Registry::{HKEY, HKEY_LOCAL_MACHINE, KEY_WRITE, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegSetValueExW}; + + const RUN_KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Run"; + const RUN_VALUE: &str = "Proxy Suite"; + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + + fn wide(s: &str) -> Vec { + 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 { + 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;