diff --git a/windows/Cargo.lock b/windows/Cargo.lock index 03a26f6..9f518fd 100644 --- a/windows/Cargo.lock +++ b/windows/Cargo.lock @@ -4974,7 +4974,7 @@ dependencies = [ [[package]] name = "ps-client" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "anyhow", "ps-core", @@ -4985,7 +4985,7 @@ dependencies = [ [[package]] name = "ps-core" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "base64 0.22.1", "flate2", @@ -5001,7 +5001,7 @@ dependencies = [ [[package]] name = "ps-ctl" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "anyhow", "clap", @@ -5015,7 +5015,7 @@ dependencies = [ [[package]] name = "ps-gui" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "anyhow", "async-channel", @@ -5023,6 +5023,7 @@ dependencies = [ "gpui-tray", "ps-client", "ps-ipc", + "serde", "serde_json", "tokio", "windows-sys 0.61.2", @@ -5030,7 +5031,7 @@ dependencies = [ [[package]] name = "ps-ipc" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "serde", "serde_json", @@ -5041,7 +5042,7 @@ dependencies = [ [[package]] name = "ps-service" -version = "0.2.0-pre.1" +version = "0.3.0-pre.1" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/windows/README.md b/windows/README.md index 0527fd5..c16b7e1 100644 --- a/windows/README.md +++ b/windows/README.md @@ -31,7 +31,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; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy | +| The app | **Proxy Suite** in the Start Menu, and a tray icon from sign-in: the proxy, DPI bypass and Telegram proxy at a glance and a click; outbounds, subscriptions and the routing mode; zapret's presets and sites; tg-ws-proxy's links; whitelist-bypass's joiners and creators (links, logins); autoProxy's routes, probes and exits; the logs; **every option** in its JSON editor, checked by the service before it takes it; the system proxy; a light and a dark theme (or as Windows is set); a newer release installed from its Overview | Not in this release, still to come: Tor's onion service, the kill switch, server inbounds, the XRay-only backend and zapret2's 16 KB cutoff probe. Their options are accepted (they are upstream's), but the @@ -50,6 +50,7 @@ DPI bypass, which runs on Windows only, shows as inactive. | ![Outbounds](docs/screenshots/outbounds.png) | ![autoProxy](docs/screenshots/autoproxy.png) | | ![AmneziaWG](docs/screenshots/amneziawg.png) | ![Whitelist bypass](docs/screenshots/whitelist-bypass.png) | | ![Telegram proxy](docs/screenshots/telegram.png) | ![Settings](docs/screenshots/settings.png) | +| ![Overview, dark](docs/screenshots/overview-dark.png) | ![Components](docs/screenshots/components.png) | ## What has been verified @@ -97,7 +98,13 @@ Nothing has to be installed first: the C runtime is linked into the programs, an 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 → +To upgrade, run the new setup, or install it from the app: its Overview says when a newer +release is out (it looks when it starts, and daily; Settings → This app turns that off), and +**Install** has the service fetch the setup program from this project's releases, check its +SHA-256 against the one published beside it, and run it silently: the service and the app close +for a moment and start again, new. `proxy-ctl update` and `proxy-ctl update install` do the +same. A pre-release is offered newer pre-releases and releases; a release only releases. The +settings stay either way. To remove: **Settings → Apps → Proxy Suite → Uninstall** (it runs `uninstall.cmd` in that folder); the configuration and state stay in `%ProgramData%\ProxySuite` until you delete it. @@ -188,7 +195,8 @@ Whatever the scopes, these always need an administrator: anything that makes the a program, pass arguments to one, or read or write a file of the caller's choosing — every `*File` option, raw `singBoxJson`/`xrayJson`, `sshProxy.extraArgs`, `tor.extraConfig`, `nfqwsArgs`, zapret2's `profiles` and `blobs`, `allowConfigHooks`, and `userControl` itself — -and installing components. Secrets (links, passwords) are hidden from callers without the +and installing components. Installing an update takes the `services` scope only: it runs no +program but this project's own setup, from its own releases, checked, and only a newer one. Secrets (links, passwords) are hidden from callers without the `secrets` scope, and survive a round trip through `config get`/`config set` unchanged. ## Caveats diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index 7fc1a59..db107a1 100644 --- a/windows/crates/ps-ctl/src/main.rs +++ b/windows/crates/ps-ctl/src/main.rs @@ -69,6 +69,20 @@ enum Cmd { #[command(subcommand)] verb: Option, }, + /// Proxy Suite itself: whether a newer release is out, and installing it. + Update { + #[command(subcommand)] + verb: Option, + }, +} + +#[derive(Subcommand)] +enum UpdateVerb { + /// This version, and a newer release if there is one. + Check, + /// Fetch the newest release's setup program, check it and run it: the service and the app + /// stop for a moment and start again, new. + Install, } #[derive(Subcommand)] @@ -702,6 +716,31 @@ async fn zapret(ctl: &Ctl, verb: Option) -> Result<()> { Ok(()) } +async fn update(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(UpdateVerb::Check) { + UpdateVerb::Check => { + let r = ctl.call(Request::UpdateCheck).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let current = r["current"].as_str().unwrap_or("?"); + match r["available"].as_object() { + Some(a) => { + println!("Proxy Suite {current}; {} is out: {}", a["version"].as_str().unwrap_or("?"), a["page"].as_str().unwrap_or("")); + println!("Install it with: proxy-ctl update install"); + } + None => println!("Proxy Suite {current} is the newest release."), + } + } + UpdateVerb::Install => { + let r = ctl.call(Request::UpdateInstall).await?; + println!("Installing Proxy Suite {}: the service stops for a moment and starts again.", r["version"].as_str().unwrap_or("?")); + } + } + Ok(()) +} + async fn awg(ctl: &Ctl, verb: Option) -> Result<()> { match verb.unwrap_or(AwgVerb::List) { AwgVerb::List => { @@ -901,6 +940,7 @@ async fn real_main() -> Result<()> { Cmd::Components { verb } => components(&ctl, verb).await?, Cmd::Wl { verb } => wl(&ctl, verb).await?, Cmd::Awg { verb } => awg(&ctl, verb).await?, + Cmd::Update { verb } => update(&ctl, verb).await?, Cmd::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) { diff --git a/windows/crates/ps-gui/Cargo.toml b/windows/crates/ps-gui/Cargo.toml index 2903396..c6b9f52 100644 --- a/windows/crates/ps-gui/Cargo.toml +++ b/windows/crates/ps-gui/Cargo.toml @@ -15,9 +15,17 @@ gpui-tray = { version = "0.3", default-features = false, features = ["gpui-kit", ps-client.workspace = true ps-ipc.workspace = true anyhow.workspace = true +serde.workspace = true serde_json.workspace = true tokio.workspace = true async-channel = "2" [target.'cfg(windows)'.dependencies] -windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Registry", "Win32_Networking_WinInet"] } +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_System_Registry", + "Win32_Networking_WinInet", + "Win32_Graphics_Dwm", + "Win32_System_Threading", + "Win32_UI_WindowsAndMessaging", +] } diff --git a/windows/crates/ps-gui/src/assets.rs b/windows/crates/ps-gui/src/assets.rs index b5f55ee..8d275a2 100644 --- a/windows/crates/ps-gui/src/assets.rs +++ b/windows/crates/ps-gui/src/assets.rs @@ -5,7 +5,7 @@ use std::borrow::Cow; use gpui_kit::*; -gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock]); +gpui_kit::assets::icon_assets!(Extra, [Shield, Send, Package, Pin, PinOff, RefreshCw, Save, Trash, Plus, Copy, Download, Link, Gauge, Power, Video, FileUp, Route, Lock, ExternalLink, Sun, Moon]); pub struct AppAssets; diff --git a/windows/crates/ps-gui/src/main.rs b/windows/crates/ps-gui/src/main.rs index b6914b0..0d53dc9 100644 --- a/windows/crates/ps-gui/src/main.rs +++ b/windows/crates/ps-gui/src/main.rs @@ -1,6 +1,6 @@ //! 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. +//! only its own look, and whether it looks for updates (prefs.rs). //! //! proxy-suite [--socket ADDRESS] [--hidden] (the service's pipe or socket, as proxy-ctl takes //! it; --hidden starts in the tray) @@ -10,6 +10,7 @@ mod assets; mod bridge; mod model; +mod prefs; mod shell; mod sysproxy; mod ui; @@ -46,6 +47,8 @@ fn main() { // 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); + cx.set_global(prefs::load()); + prefs::apply_theme(None, cx); let model = cx.new(|cx| model::Model::new(bridge, cx)); shell::start(model, !args.hidden, cx); }); diff --git a/windows/crates/ps-gui/src/model.rs b/windows/crates/ps-gui/src/model.rs index 7b6cbe1..4f73e42 100644 --- a/windows/crates/ps-gui/src/model.rs +++ b/windows/crates/ps-gui/src/model.rs @@ -1,7 +1,7 @@ //! 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 std::time::{Duration, Instant}; use anyhow::{Result, bail}; use gpui_kit::*; @@ -17,6 +17,20 @@ pub enum Outcome { Failed(SharedString), } +/// Whether a newer release of Proxy Suite is out, as the service last found. +#[derive(Clone, PartialEq)] +pub enum Update { + /// Not looked for (yet, or the preference says not to). + Unknown, + Checking, + Newest, + Available { version: SharedString, page: SharedString }, + /// Its setup program being fetched and checked (`started`: and then run, which closes + /// this app and opens the new one), since `at`. + Installing { version: SharedString, started: bool, at: Instant }, + Failed(SharedString), +} + #[derive(Clone, PartialEq)] pub enum Connection { Connecting, @@ -36,12 +50,21 @@ pub struct Model { tg_links: Vec, /// Changes sent and not yet answered. pending: usize, + update: Update, + /// The version the service runs, from its last update check. + version: SharedString, + /// When updates were last looked for. + update_checked: Option, _poll: Task<()>, } impl EventEmitter for Model {} const POLL: Duration = Duration::from_secs(2); +/// How often a running app looks for updates again (when the preference has it look). +const UPDATE_CHECK: Duration = Duration::from_secs(24 * 3600); +/// How long the setup has to close this app once it runs. +const SETUP_WAIT: Duration = Duration::from_secs(5 * 60); impl Model { pub fn new(bridge: Bridge, cx: &mut Context) -> Self { @@ -58,6 +81,16 @@ impl Model { if let Some(Ok(o)) = outbounds { m.outbounds = o; } + // A setup that ran and left this app running did not replace it. + if let Update::Installing { version, started: true, at } = &m.update + && at.elapsed() >= SETUP_WAIT + { + m.update = Update::Failed(format!("the setup of {version} did not finish (the service's log, on the Logs page, may say why)").into()); + } + let due = m.update_checked.is_none_or(|t| t.elapsed() >= UPDATE_CHECK); + if m.connection == Connection::Up && due && cx.global::().check_updates { + m.check_update(cx); + } cx.notify(); }); if alive.is_err() { @@ -76,6 +109,9 @@ impl Model { presets: Vec::new(), tg_links: Vec::new(), pending: 0, + update: Update::Unknown, + version: env!("CARGO_PKG_VERSION").into(), + update_checked: None, _poll: poll, } } @@ -128,6 +164,74 @@ impl Model { self.pending > 0 } + pub fn update(&self) -> &Update { + &self.update + } + + pub fn version(&self) -> &SharedString { + &self.version + } + + /// Asks the service whether a newer release is out. + pub fn check_update(&mut self, cx: &mut Context) { + if matches!(self.update, Update::Checking | Update::Installing { .. }) { + return; + } + self.update = Update::Checking; + self.update_checked = Some(Instant::now()); + cx.notify(); + let job = self.bridge.call(Request::UpdateCheck); + cx.spawn(async move |this, cx| { + let r = job.await; + this.update(cx, |m, cx| { + m.update = match r { + Ok(r) => { + if let Some(v) = r["current"].as_str() { + m.version = v.to_owned().into(); + } + match r["available"].as_object() { + Some(a) => Update::Available { + version: a.get("version").and_then(Value::as_str).unwrap_or("?").to_owned().into(), + page: a.get("page").and_then(Value::as_str).unwrap_or_default().to_owned().into(), + }, + None => Update::Newest, + } + } + Err(e) => Update::Failed(format!("{e:#}").into()), + }; + cx.notify(); + }) + .ok(); + }) + .detach(); + } + + /// Has the service fetch the newest release and run its setup, which replaces the service + /// and this app, and opens the new one. + pub fn install_update(&mut self, cx: &mut Context) { + let Update::Available { version, .. } = &self.update else { return }; + let version = version.clone(); + self.update = Update::Installing { version: version.clone(), started: false, at: Instant::now() }; + cx.notify(); + let job = self.bridge.call(Request::UpdateInstall); + cx.spawn(async move |this, cx| { + let r = job.await; + this.update(cx, |m, cx| { + match r { + Ok(_) => m.update = Update::Installing { version, started: true, at: Instant::now() }, + Err(e) => { + let e: SharedString = format!("{e:#}").into(); + cx.emit(Outcome::Failed(format!("Updating to {version}: {e}").into())); + m.update = Update::Failed(e); + } + } + cx.notify(); + }) + .ok(); + }) + .detach(); + } + /// Status and outbounds now, rather than at the next round. pub fn refresh(&mut self, cx: &mut Context) { let status = self.bridge.call(Request::Status); diff --git a/windows/crates/ps-gui/src/prefs.rs b/windows/crates/ps-gui/src/prefs.rs new file mode 100644 index 0000000..b7f2a37 --- /dev/null +++ b/windows/crates/ps-gui/src/prefs.rs @@ -0,0 +1,108 @@ +//! The app's own preferences, each user's: its look, and whether it looks for updates. All +//! else is the service's configuration. +//! +//! In `%APPDATA%\ProxySuite\app.json` (elsewhere `$XDG_CONFIG_HOME/proxy-suite/app.json`). + +use std::path::PathBuf; + +use gpui_kit::component::{Theme, ThemeMode}; +use gpui_kit::*; +use serde::{Deserialize, Serialize}; + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ThemeChoice { + /// Windows' own: light or dark as apps are set to be (Settings → Personalization → Colors). + #[default] + System, + Light, + Dark, +} + +impl ThemeChoice { + pub const ALL: [(ThemeChoice, &'static str); 3] = [(ThemeChoice::System, "As Windows"), (ThemeChoice::Light, "Light"), (ThemeChoice::Dark, "Dark")]; +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct Prefs { + pub theme: ThemeChoice, + /// At start and daily, ask the service whether a newer release is out. + pub check_updates: bool, +} + +impl Default for Prefs { + fn default() -> Self { + Self { theme: ThemeChoice::System, check_updates: true } + } +} + +impl Global for Prefs {} + +fn path() -> Option { + if cfg!(windows) { + std::env::var_os("APPDATA").map(|d| PathBuf::from(d).join("ProxySuite").join("app.json")) + } else { + let base = std::env::var_os("XDG_CONFIG_HOME").map(PathBuf::from).or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?; + Some(base.join("proxy-suite").join("app.json")) + } +} + +/// The saved preferences, or the defaults where there are none (or they do not read). +pub fn load() -> Prefs { + path().and_then(|p| std::fs::read(p).ok()).and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_default() +} + +impl Prefs { + fn save(&self) { + let Some(path) = path() else { return }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + if let Err(e) = std::fs::write(&path, serde_json::to_vec_pretty(self).unwrap_or_default()) { + eprintln!("proxy-suite: saving {}: {e}", path.display()); + } + } +} + +/// Changes the preferences, saves them, and shows what changed. +pub fn change(cx: &mut App, edit: impl FnOnce(&mut Prefs)) { + let before = cx.global::().theme; + edit(cx.global_mut::()); + cx.global::().save(); + if cx.global::().theme != before { + apply_theme(None, cx); + } + cx.refresh_windows(); +} + +/// The theme the preference picks: Windows' appearance (the window's, when there is one), or +/// the one chosen. +pub fn apply_theme(window: Option<&mut Window>, cx: &mut App) { + match cx.global::().theme { + ThemeChoice::System => Theme::sync_system_appearance(window, cx), + ThemeChoice::Light => Theme::change(ThemeMode::Light, window, cx), + ThemeChoice::Dark => Theme::change(ThemeMode::Dark, window, cx), + } + #[cfg(windows)] + title_bars(Theme::global(cx).is_dark()); +} + +/// Windows draws the window's title bar, light or dark as Windows' own appearance is (GPUI sets +/// it so): as the theme chosen instead. The app's windows are its main thread's. +#[cfg(windows)] +fn title_bars(dark: bool) { + use windows_sys::Win32::Foundation::{HWND, LPARAM}; + use windows_sys::Win32::Graphics::Dwm::{DWMWA_USE_IMMERSIVE_DARK_MODE, DwmSetWindowAttribute}; + use windows_sys::Win32::System::Threading::GetCurrentThreadId; + use windows_sys::Win32::UI::WindowsAndMessaging::EnumThreadWindows; + + unsafe extern "system" fn each(hwnd: HWND, dark: LPARAM) -> windows_sys::core::BOOL { + let value: windows_sys::core::BOOL = (dark != 0).into(); + // SAFETY: a window of this thread, and a BOOL as long as said. + unsafe { DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE as u32, (&value as *const windows_sys::core::BOOL).cast(), 4) }; + 1 + } + // SAFETY: the callback only reads its arguments. + unsafe { EnumThreadWindows(GetCurrentThreadId(), Some(each), dark as LPARAM) }; +} diff --git a/windows/crates/ps-gui/src/ui/mod.rs b/windows/crates/ps-gui/src/ui/mod.rs index 5db7882..72b74c5 100644 --- a/windows/crates/ps-gui/src/ui/mod.rs +++ b/windows/crates/ps-gui/src/ui/mod.rs @@ -13,6 +13,7 @@ mod telegram; mod whitelist; mod widgets; +use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::notification::Notification; use gpui_kit::component::sidebar::{Sidebar, SidebarFooter, SidebarGroup, SidebarHeader, SidebarMenu, SidebarMenuItem}; use gpui_kit::assets::IconName; @@ -102,6 +103,12 @@ impl AppView { pub fn new(model: Entity, window: &mut Window, cx: &mut Context) -> Self { let subscriptions = vec![ cx.observe(&model, |_, _, cx| cx.notify()), + // As Windows' appearance changes, when the theme follows it. + cx.observe_window_appearance(window, |_, window, cx| { + if cx.global::().theme == crate::prefs::ThemeChoice::System { + crate::prefs::apply_theme(Some(window), cx); + } + }), cx.subscribe_in(&model, window, |_, _, outcome: &Outcome, window, cx| { let note = match outcome { Outcome::Done(m) => Notification::success(m.clone()), @@ -110,6 +117,8 @@ impl AppView { window.push_notification(note, cx); }), ]; + // The window's appearance is the one to follow (the app's, before a window, may not be). + crate::prefs::apply_theme(Some(window), cx); let dpi = cx.new(|cx| dpi::DpiPage::new(model.clone(), window, cx)); let telegram = cx.new(|cx| telegram::TelegramPage::new(model.clone(), window, cx)); let outbounds = cx.new(|cx| outbounds::OutboundsPage::new(model.clone(), window, cx)); @@ -131,7 +140,19 @@ impl AppView { 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) + // Light or dark at a click; Settings → This app has "as Windows" too. + let dark = cx.theme().is_dark(); + let theme = Button::new("theme-toggle") + .ghost() + .xsmall() + .icon(if dark { IconName::Sun } else { IconName::Moon }) + .tooltip(if dark { "Light theme" } else { "Dark theme" }) + .on_click(move |_, _, cx| { + let choice = if dark { crate::prefs::ThemeChoice::Light } else { crate::prefs::ThemeChoice::Dark }; + crate::prefs::change(cx, |p| p.theme = choice); + }); + let header = SidebarHeader::new().child(div().h_flex().w_full().justify_between().items_center().child(widgets::brand(cx)).child(theme)); + Sidebar::new("pages").header(header).child(SidebarGroup::new("Proxy Suite").child(SidebarMenu::new().children(items))).footer(footer) } } diff --git a/windows/crates/ps-gui/src/ui/overview.rs b/windows/crates/ps-gui/src/ui/overview.rs index 92f0c48..f7dfe05 100644 --- a/windows/crates/ps-gui/src/ui/overview.rs +++ b/windows/crates/ps-gui/src/ui/overview.rs @@ -1,7 +1,9 @@ //! The overview: the local proxy, the DPI bypass and the Telegram proxy, each with its state -//! and a switch; what the service warns of. +//! and a switch; what the service warns of; Proxy Suite's version, and a newer one to install. +use gpui_kit::assets::IconName; use gpui_kit::component::alert::Alert; +use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::switch::Switch; use gpui_kit::component::*; use gpui_kit::prelude::FluentBuilder as _; @@ -11,7 +13,7 @@ use serde_json::Value; use super::AppView; use super::widgets::{card, fact, hint, page, state_tag}; -use crate::model::{Connection, Model}; +use crate::model::{Connection, Model, Update}; fn text(v: &Value) -> SharedString { match v { @@ -138,5 +140,48 @@ pub fn render(model: &Entity, _: &mut Window, cx: &mut Context) .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())) + body.child(proxy).child(div().h_flex().gap_4().items_start().child(dpi.flex_1()).child(telegram.flex_1())).child(updates(model, cx)) +} + +/// The version, and the newest release when it is newer: installed from here by the service. +fn updates(model: &Entity, cx: &mut Context) -> Div { + let m = model.read(cx); + let update = m.update().clone(); + let busy = matches!(update, Update::Checking | Update::Installing { .. }); + let check = { + let model = model.clone(); + Button::new("update-check") + .small() + .ghost() + .icon(IconName::RefreshCw) + .label("Check for updates") + .disabled(busy) + .on_click(move |_, _, cx| model.update(cx, |m, cx| m.check_update(cx))) + }; + let card = card(format!("Proxy Suite {}", m.version()), Some(check.into_any_element()), cx); + let explain = "The service fetches its setup program from the project's releases, checks its SHA-256 and runs it: the service and this app close for a moment and start again, new. Settings stay."; + match update { + Update::Unknown if !cx.global::().check_updates => card.child(hint("Updates are not looked for by themselves (Settings → This app).", cx)), + Update::Unknown => card.child(hint("Updates are looked for when the app starts, and daily.", cx)), + Update::Checking => card.child(hint("Looking for a newer release…", cx)), + Update::Newest => card.child(hint("This is the newest release.", cx)), + Update::Failed(e) => card.child(div().text_sm().text_color(cx.theme().danger).child(format!("Could not look for updates: {e}"))), + Update::Available { version, page } => { + let install = { + let model = model.clone(); + Button::new("update-install") + .small() + .primary() + .icon(IconName::Download) + .label(format!("Install {version}")) + .on_click(move |_, _, cx| model.update(cx, |m, cx| m.install_update(cx))) + }; + let notes = Button::new("update-notes").small().ghost().icon(IconName::ExternalLink).label("What's new").on_click(move |_, _, cx| cx.open_url(&page)); + card.child(div().h_flex().gap_3().items_center().child(div().text_sm().font_semibold().child(format!("{version} is out."))).child(install).child(notes)).child(hint(explain, cx)) + } + Update::Installing { version, started: false, .. } => card.child(Alert::info("update-fetching", format!("Fetching {version} and checking it…"))), + Update::Installing { version, started: true, .. } => { + card.child(Alert::info("update-running", format!("Installing {version}: this app closes, and opens again in a moment."))) + } + } } diff --git a/windows/crates/ps-gui/src/ui/settings.rs b/windows/crates/ps-gui/src/ui/settings.rs index 91ee83e..3493303 100644 --- a/windows/crates/ps-gui/src/ui/settings.rs +++ b/windows/crates/ps-gui/src/ui/settings.rs @@ -1,10 +1,12 @@ -//! 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. +//! Settings: this app's own (its look, updates), and the whole configuration, upstream's option +//! tree as JSON, edited here and checked by the service before it takes it. Every option the +//! other pages show is here too, and the ones they do not. use gpui_kit::assets::IconName; use gpui_kit::component::button::{Button, ButtonVariants as _}; use gpui_kit::component::input::{Editor, EditorState, InputEvent}; +use gpui_kit::component::radio::RadioGroup; +use gpui_kit::component::switch::Switch; use gpui_kit::component::*; use gpui_kit::prelude::FluentBuilder as _; use gpui_kit::*; @@ -14,6 +16,7 @@ use serde_json::Value; use super::widgets::{card, hint, page}; use crate::model::Model; +use crate::prefs::{self, Prefs, ThemeChoice}; /// What the service shows in place of a secret the caller may not read; saved back as it is, /// the secret keeps its value. @@ -152,6 +155,29 @@ fn issue_list(issues: &[Issue], cx: &App) -> Div { list } +/// The app's own preferences, this user's: not the service's configuration. +fn this_app(cx: &App) -> Div { + let p = cx.global::().clone(); + let theme = RadioGroup::horizontal("app-theme") + .children(ThemeChoice::ALL.map(|(_, label)| label)) + .selected_index(ThemeChoice::ALL.iter().position(|(t, _)| *t == p.theme)) + .on_change(|ix, _, cx| { + let choice = ThemeChoice::ALL[*ix].0; + prefs::change(cx, |p| p.theme = choice); + }); + let updates = Switch::new("app-check-updates") + .label("Look for a newer release when the app starts, and daily") + .checked(p.check_updates) + .on_change(|on, _, cx| { + let on = *on; + prefs::change(cx, |p| p.check_updates = on); + }); + card("This app", None, cx) + .child(div().h_flex().gap_4().items_center().child(div().text_sm().w(px(110.)).text_color(cx.theme().muted_foreground).child("Theme")).child(theme)) + .child(updates) + .child(hint("Yours alone, kept with your Windows account; the service's configuration is below.", cx)) +} + impl Render for SettingsPage { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { let text = self.editor.read(cx).value(); @@ -179,7 +205,7 @@ impl Render for SettingsPage { .child(issue_list(issues, cx)), }; - page("Settings", cx).child( + page("Settings", cx).child(this_app(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))) diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs index 4a2d1ed..869cef8 100644 --- a/windows/crates/ps-ipc/src/lib.rs +++ b/windows/crates/ps-ipc/src/lib.rs @@ -102,6 +102,11 @@ pub enum Request { AwgSet { name: String, on: bool }, /// The last lines of a system-wide profile's tunnel log. Secrets scope, as logs are. AwgLog { name: String, lines: usize }, + /// This version, and the newest release if it is newer. + UpdateCheck, + /// Fetches the newest release's setup program, checks it, and runs it: the service stops, + /// is replaced, and starts again, and the app with it. Services scope. + UpdateInstall, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] diff --git a/windows/crates/ps-service/Cargo.toml b/windows/crates/ps-service/Cargo.toml index 251a86d..c061e16 100644 --- a/windows/crates/ps-service/Cargo.toml +++ b/windows/crates/ps-service/Cargo.toml @@ -41,6 +41,8 @@ windows-sys = { workspace = true, features = [ "Win32_UI_WindowsAndMessaging", "Win32_System_Threading", "Win32_Networking_WinInet", + "Win32_System_RemoteDesktop", + "Win32_System_Environment", ] } [target.'cfg(target_os = "linux")'.dependencies] diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index 5102a1f..77cc175 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -134,7 +134,8 @@ fn scope_of(req: &Request) -> Option { 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), + // An update runs only the project's own setup program, checked: no more than a restart. + Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } | Request::UpdateInstall => Some(Scope::Services), Request::WlList | Request::WlLink { .. } | Request::WlAuth { .. } | Request::WlJoin { .. } | Request::WlNew { .. } => Some(Scope::WhitelistBypass), Request::AutoList | Request::AutoProbe { .. } | Request::AutoLearn { .. } | Request::AutoForget { .. } => Some(Scope::AutoProxy), Request::AwgList | Request::AwgSet { .. } => Some(Scope::AmneziaWg), @@ -673,6 +674,25 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { Response::ok(json!({ "lines": crate::awgvpn::log_tail(s.paths(), &vpn.iface, lines.min(2000)) })) } + Request::UpdateCheck => { + let routes = shared.lock().await.fetch_routes(true); + match crate::update::check(&routes).await { + Ok(r) => Response::ok(json!({ "current": env!("CARGO_PKG_VERSION"), "available": r.map(|r| r.to_json()) })), + Err(e) => Response::err(format!("{e:#}")), + } + } + + Request::UpdateInstall => { + let (routes, dir) = { + let s = shared.lock().await; + (s.fetch_routes(true), s.paths().updates()) + }; + match crate::update::install(&routes, &dir).await { + Ok(r) => Response::ok(r.to_json()), + Err(e) => Response::err(format!("{e:#}")), + } + } + Request::ComponentsInstall { names } => { // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. if !peer.admin { diff --git a/windows/crates/ps-service/src/install.rs b/windows/crates/ps-service/src/install.rs index ca6e7fc..edc8f5b 100644 --- a/windows/crates/ps-service/src/install.rs +++ b/windows/crates/ps-service/src/install.rs @@ -9,7 +9,8 @@ use sha2::{Digest, Sha256}; use crate::fetch; -fn hex(data: &[u8]) -> String { +/// A SHA-256, in lower-case hex. +pub(crate) fn hex(data: &[u8]) -> String { let mut h = Sha256::new(); h.update(data); h.finalize().iter().map(|b| format!("{b:02x}")).collect() diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs index 74a1d02..f38396e 100644 --- a/windows/crates/ps-service/src/main.rs +++ b/windows/crates/ps-service/src/main.rs @@ -20,6 +20,7 @@ mod store; mod tg; mod tor; mod units; +mod update; mod warp; #[cfg(windows)] mod winsvc; @@ -99,6 +100,7 @@ pub async fn run( let addr = address(socket); let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?; tracing::info!("listening on {addr:?}, state in {}", paths.root.display()); + update::report(&paths.updates()); ready(); if let Err(e) = shared.lock().await.apply().await { diff --git a/windows/crates/ps-service/src/paths.rs b/windows/crates/ps-service/src/paths.rs index 3d15812..02c1bdf 100644 --- a/windows/crates/ps-service/src/paths.rs +++ b/windows/crates/ps-service/src/paths.rs @@ -58,6 +58,11 @@ impl Paths { pub fn run(&self) -> PathBuf { self.root.join("run") } + /// Setup programs the service fetched to update itself. + pub fn updates(&self) -> PathBuf { + self.root.join("updates") + } + pub fn logs(&self) -> PathBuf { self.root.join("logs") } diff --git a/windows/crates/ps-service/src/update.rs b/windows/crates/ps-service/src/update.rs new file mode 100644 index 0000000..228bb6f --- /dev/null +++ b/windows/crates/ps-service/src/update.rs @@ -0,0 +1,380 @@ +//! Updating Proxy Suite itself: the newest release on the project's Gitea, its setup program +//! fetched, checked against the SHA-256 published beside it and run silently, as SYSTEM. The +//! setup stops this service, puts the new files in place, and starts the service and the app +//! (in the signed-in users' sessions) again. + +use std::cmp::Ordering; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +use anyhow::{Context, Result, anyhow, bail}; +use serde_json::{Value, json}; + +use crate::fetch::{self, Route}; + +/// The project's releases. `PROXY_SUITE_UPDATE_URL` in the service's own environment (which +/// only an administrator sets) points it at another listing, for tests. +const RELEASES: &str = "https://git.faumaray.com/api/v1/repos/faumaray/proxy-suite-flake/releases?limit=30"; +/// The Windows port's tags, apart from upstream's `v0.x.0`. +const TAG_PREFIX: &str = "windows-v"; +/// A setup program is ~80 MB. +const MAX_SETUP: usize = 512 << 20; + +/// One update at a time: when the one under way began. A setup that never stopped this +/// service (it failed early) leaves the way open again after a while. +static BUSY: Mutex> = Mutex::new(None); +const GIVE_UP: Duration = Duration::from_secs(15 * 60); + +fn begin() -> bool { + let mut busy = BUSY.lock().unwrap_or_else(|e| e.into_inner()); + if busy.is_some_and(|t| t.elapsed() < GIVE_UP) { + return false; + } + *busy = Some(Instant::now()); + true +} + +fn end() { + *BUSY.lock().unwrap_or_else(|e| e.into_inner()) = None; +} + +fn releases_url() -> String { + std::env::var("PROXY_SUITE_UPDATE_URL").unwrap_or_else(|_| RELEASES.into()) +} + +/// A release's version: `major.minor.patch`, with `-pre.N` for a pre-release. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Version { + major: u64, + minor: u64, + patch: u64, + pre: Option, +} + +impl Version { + pub fn parse(s: &str) -> Option { + let (core, pre) = match s.split_once('-') { + Some((core, pre)) => (core, Some(pre.strip_prefix("pre.")?.parse().ok()?)), + None => (s, None), + }; + let mut parts = core.split('.').map(|p| p.parse::().ok()); + let v = Version { major: parts.next()??, minor: parts.next()??, patch: parts.next()??, pre }; + parts.next().is_none().then_some(v) + } + + pub fn current() -> Self { + Self::parse(env!("CARGO_PKG_VERSION")).expect("the package's version reads") + } +} + +impl Ord for Version { + fn cmp(&self, other: &Self) -> Ordering { + (self.major, self.minor, self.patch).cmp(&(other.major, other.minor, other.patch)).then(match (self.pre, other.pre) { + (None, None) => Ordering::Equal, + // A release is newer than its pre-releases. + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(a), Some(b)) => a.cmp(&b), + }) + } +} + +impl PartialOrd for Version { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl std::fmt::Display for Version { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}.{}.{}", self.major, self.minor, self.patch)?; + match self.pre { + Some(n) => write!(f, "-pre.{n}"), + None => Ok(()), + } + } +} + +/// A newer release, with its setup program. +#[derive(Debug, Clone, PartialEq)] +pub struct Release { + pub version: Version, + pub page: String, + pub notes: String, + pub published: String, + pub setup: String, + pub size: u64, + pub checksum: String, +} + +impl Release { + pub fn to_json(&self) -> Value { + json!({ + "version": self.version.to_string(), + "page": self.page, + "notes": self.notes, + "published": self.published, + "size": self.size, + }) + } +} + +/// `scheme://host[:port]` of a URL. +fn origin(url: &str) -> Option<&str> { + let start = url.find("://")? + 3; + let end = url[start..].find(['/', '?', '#']).map_or(url.len(), |i| start + i); + (end > start).then(|| &url[..end]) +} + +/// The newest release newer than `current` in a Gitea releases listing. Drafts and other tags +/// are left out, pre-releases unless `current` is one (who runs a release stays on releases), +/// and a release without its setup program and checksum, or with them on another host than +/// the listing's. +pub fn newest(list: &Value, current: Version, listing: &str) -> Option { + let home = origin(listing)?; + list.as_array()? + .iter() + .filter_map(|r| { + if r["draft"] == true { + return None; + } + let version = Version::parse(r["tag_name"].as_str()?.strip_prefix(TAG_PREFIX)?)?; + if version <= current || ((r["prerelease"] == true || version.pre.is_some()) && current.pre.is_none()) { + return None; + } + let name = format!("ProxySuite-{version}-windows-x64-setup.exe"); + let asset = |n: &str| r["assets"].as_array()?.iter().find(|a| a["name"] == n); + let url = |a: &Value| a["browser_download_url"].as_str().filter(|u| origin(u) == Some(home)).map(str::to_owned); + let setup = asset(&name)?; + Some(Release { + version, + page: r["html_url"].as_str().unwrap_or_default().to_owned(), + notes: r["body"].as_str().unwrap_or_default().to_owned(), + published: r["published_at"].as_str().unwrap_or_default().to_owned(), + setup: url(setup)?, + size: setup["size"].as_u64().unwrap_or(0), + checksum: url(asset(&format!("{name}.sha256"))?)?, + }) + }) + .max_by_key(|r| r.version) +} + +/// The first route's answer that comes. +async fn first>>(routes: &[Route], each: impl Fn(Route) -> F) -> Result { + let mut last = None; + for route in routes { + match each(route.clone()).await { + Ok(v) => return Ok(v), + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| anyhow!("no way to reach the network"))) +} + +/// The newest release, if there is one newer than this. +pub async fn check(routes: &[Route]) -> Result> { + let url = releases_url(); + let body = first(routes, |r| { + let url = url.clone(); + async move { fetch::get(&url, &r, 4 << 20).await } + }) + .await + .context("the releases")?; + let list: Value = serde_json::from_slice(&body).context("the releases' listing")?; + Ok(newest(&list, Version::current(), &url)) +} + +/// The SHA-256 a `.sha256` file holds (`sha256sum`'s line). +fn published_sum(text: &[u8]) -> Result { + let text = std::str::from_utf8(text).unwrap_or_default(); + match text.split_whitespace().next() { + Some(h) if h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit()) => Ok(h.to_ascii_lowercase()), + _ => bail!("the published checksum does not read"), + } +} + +/// The release's setup program in `dir` (older ones gone), once its SHA-256 matches. +async fn download(release: &Release, routes: &[Route], dir: &Path) -> Result { + let sum = first(routes, |r| { + let url = release.checksum.clone(); + async move { fetch::get(&url, &r, 4096).await } + }) + .await + .context("the setup program's checksum")?; + let want = published_sum(&sum)?; + let body = first(routes, |r| { + let url = release.setup.clone(); + async move { fetch::get_large(&url, &r, MAX_SETUP).await } + }) + .await + .context("the setup program")?; + if crate::install::hex(&body) != want { + bail!("the setup program's SHA-256 is not the one published beside it"); + } + std::fs::create_dir_all(dir)?; + for e in std::fs::read_dir(dir)?.flatten() { + let _ = std::fs::remove_file(e.path()); + } + let path = dir.join(format!("ProxySuite-{}-windows-x64-setup.exe", release.version)); + crate::paths::write_atomic(&path, &body).with_context(|| format!("writing {}", path.display()))?; + Ok(path) +} + +/// What `install` leaves for the service that the setup starts: the version it went for. +const PENDING: &str = "pending"; + +/// Fetches the newest release's setup program and runs it, a moment after this returns (so +/// the caller hears of it before the setup stops the service). +pub async fn install(routes: &[Route], dir: &Path) -> Result { + if !begin() { + bail!("an update is under way already"); + } + let r = async { + let release = check(routes).await?.ok_or_else(|| anyhow!("this is the newest release ({})", env!("CARGO_PKG_VERSION")))?; + tracing::info!("update: fetching {}", release.version); + let setup = download(&release, routes, dir).await?; + std::fs::write(dir.join(PENDING), release.version.to_string())?; + run_later(setup); + Ok(release) + } + .await; + if r.is_err() { + end(); + } + r +} + +fn run_later(setup: PathBuf) { + tokio::spawn(async move { + tokio::time::sleep(Duration::from_secs(1)).await; + tracing::info!("update: running {}", setup.display()); + if let Err(e) = run(&setup) { + tracing::error!("update: {e:#}"); + let _ = std::fs::remove_file(setup.with_file_name(PENDING)); + end(); + } + }); +} + +/// The setup, silent, on its own: out of any job this process is in, and of its console, as it +/// outlives the service it stops. +#[cfg(windows)] +fn run(setup: &Path) -> Result<()> { + use std::os::windows::process::CommandExt; + const DETACHED_PROCESS: u32 = 0x8; + const CREATE_NEW_PROCESS_GROUP: u32 = 0x200; + const CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000; + let spawn = |flags: u32| { + std::process::Command::new(setup) + .arg("/S") + .current_dir(setup.parent().unwrap_or(Path::new("."))) + .creation_flags(flags) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + }; + // A job that allows no breakaway refuses the flag; none to break away from ignores it. + spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP | CREATE_BREAKAWAY_FROM_JOB) + .or_else(|_| spawn(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)) + .context("starting the setup program")?; + Ok(()) +} + +#[cfg(not(windows))] +fn run(setup: &Path) -> Result<()> { + bail!("{} is a Windows setup program; not run here", setup.display()) +} + +/// Said once in the log at start: whether the update `install` went for is the version now +/// running. +pub fn report(dir: &Path) { + let path = dir.join(PENDING); + let Ok(wanted) = std::fs::read_to_string(&path) else { return }; + let _ = std::fs::remove_file(&path); + if wanted.trim() == env!("CARGO_PKG_VERSION") { + tracing::info!("updated to {}", env!("CARGO_PKG_VERSION")); + } else { + tracing::warn!("the update to {} did not finish; this is still {}", wanted.trim(), env!("CARGO_PKG_VERSION")); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(s: &str) -> Version { + Version::parse(s).unwrap() + } + + #[test] + fn versions_order_as_releases() { + assert!(v("0.3.0-pre.1") > v("0.2.0-pre.1")); + assert!(v("0.3.0-pre.2") > v("0.3.0-pre.1")); + assert!(v("0.3.0") > v("0.3.0-pre.9")); + assert!(v("0.10.0") > v("0.9.1")); + assert_eq!(v("1.2.3-pre.4").to_string(), "1.2.3-pre.4"); + for bad in ["0.3", "0.3.0.1", "0.3.0-rc.1", "x.1.2", "0.3.0-pre."] { + assert_eq!(Version::parse(bad), None, "{bad}"); + } + assert_eq!(Version::current().to_string(), env!("CARGO_PKG_VERSION")); + } + + fn release(tag: &str, pre: bool, host: &str) -> Value { + let v = tag.trim_start_matches(TAG_PREFIX); + let name = format!("ProxySuite-{v}-windows-x64-setup.exe"); + json!({ + "tag_name": tag, "prerelease": pre, "draft": false, "body": "notes", "html_url": format!("{host}/r/{tag}"), + "assets": [ + { "name": name, "size": 5, "browser_download_url": format!("{host}/d/{tag}/{name}") }, + { "name": format!("{name}.sha256"), "size": 1, "browser_download_url": format!("{host}/d/{tag}/{name}.sha256") }, + ], + }) + } + + const HOME: &str = "https://git.example"; + const LIST: &str = "https://git.example/api/v1/repos/o/r/releases?limit=30"; + + #[test] + fn the_newest_release_with_a_setup_program() { + let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.3.0-pre.1", true, HOME), release("v0.9.0", false, HOME)]); + let r = newest(&list, v("0.3.0-pre.1"), LIST).unwrap(); + assert_eq!(r.version, v("0.3.0-pre.2")); + assert_eq!(r.setup, "https://git.example/d/windows-v0.3.0-pre.2/ProxySuite-0.3.0-pre.2-windows-x64-setup.exe"); + assert!(r.checksum.ends_with(".exe.sha256")); + // Nothing newer. + assert_eq!(newest(&list, v("0.3.0-pre.2"), LIST), None); + // Who runs a release is not offered pre-releases, but a newer release. + assert_eq!(newest(&list, v("0.2.0"), LIST), None); + let list = json!([release("windows-v0.3.0-pre.2", true, HOME), release("windows-v0.2.1", false, HOME)]); + assert_eq!(newest(&list, v("0.2.0"), LIST).unwrap().version, v("0.2.1")); + assert_eq!(newest(&list, v("0.2.0-pre.1"), LIST).unwrap().version, v("0.3.0-pre.2")); + } + + #[test] + fn drafts_strangers_and_releases_without_a_setup_are_passed_over() { + let mut draft = release("windows-v0.4.0", false, HOME); + draft["draft"] = true.into(); + let elsewhere = release("windows-v0.5.0", false, "https://evil.example"); + let mut zip_only = release("windows-v0.6.0", false, HOME); + zip_only["assets"].as_array_mut().unwrap().remove(0); + let mut no_sum = release("windows-v0.7.0", false, HOME); + no_sum["assets"].as_array_mut().unwrap().remove(1); + let list = json!([draft, elsewhere, zip_only, no_sum, release("windows-v0.3.1", false, HOME)]); + assert_eq!(newest(&list, v("0.3.0"), LIST).unwrap().version, v("0.3.1")); + // http is another origin than https. + let list = json!([release("windows-v0.3.1", false, "http://git.example")]); + assert_eq!(newest(&list, v("0.3.0"), LIST), None); + } + + #[test] + fn origins_and_checksums_read() { + assert_eq!(origin("https://h.example:3000/a/b?c"), Some("https://h.example:3000")); + assert_eq!(origin("https://h.example?x"), Some("https://h.example")); + assert_eq!(origin("https://"), None); + let h = "3ff31008aa1d9f4e".repeat(4); + assert_eq!(published_sum(format!("{h} ProxySuite-0.2.0-pre.1-windows-x64-setup.exe\n").as_bytes()).unwrap(), h); + assert!(published_sum(b"not a sum").is_err()); + } +} diff --git a/windows/crates/ps-service/src/winsvc.rs b/windows/crates/ps-service/src/winsvc.rs index 86960a9..c9484f7 100644 --- a/windows/crates/ps-service/src/winsvc.rs +++ b/windows/crates/ps-service/src/winsvc.rs @@ -98,7 +98,12 @@ pub fn install() -> Result<()> { } if from != to { desktop::close(); - copy_release(&from, &to)?; + if let Err(e) = copy_release(&from, &to) { + // Unattended (an update), no one would start again what was running. + let _ = existing.start::<&str>(&[]); + desktop::start(&to); + return Err(e); + } } existing.change_config(&info)?; existing @@ -365,9 +370,102 @@ mod desktop { Ok(true) } - /// The app, as the signed-in user rather than as this elevated installer: Explorer starts it. + /// The app, as the signed-in user rather than as this elevated installer: Explorer starts + /// it. Run by the service (an update, as SYSTEM, in session 0, which no one sees), it is + /// started in each signed-in user's session as that user instead, as at their sign-in. pub fn start(dir: &Path) { - let _ = Command::new("explorer.exe").arg(dir.join("proxy-suite.exe")).spawn(); + let app = dir.join("proxy-suite.exe"); + if session::own() == Some(0) { + session::start_for_each_user(&app); + } else { + let _ = Command::new("explorer.exe").arg(&app).spawn(); + } + } + + mod session { + use std::path::Path; + + use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; + use windows_sys::Win32::System::Environment::{CreateEnvironmentBlock, DestroyEnvironmentBlock}; + use windows_sys::Win32::System::RemoteDesktop::{ + ProcessIdToSessionId, WTS_CURRENT_SERVER_HANDLE, WTS_SESSION_INFOW, WTSActive, WTSEnumerateSessionsW, WTSFreeMemory, WTSQueryUserToken, + }; + use windows_sys::Win32::System::Threading::{ + CREATE_UNICODE_ENVIRONMENT, CreateProcessAsUserW, GetCurrentProcessId, PROCESS_INFORMATION, STARTUPINFOW, + }; + + /// This process's session. + pub fn own() -> Option { + let mut id = 0u32; + // SAFETY: an out pointer to a u32. + (unsafe { ProcessIdToSessionId(GetCurrentProcessId(), &mut id) } != 0).then_some(id) + } + + /// `app` in every session a user is signed in to and at (a console's, a remote + /// desktop's), with that user's token and environment. + pub fn start_for_each_user(app: &Path) { + let mut list: *mut WTS_SESSION_INFOW = std::ptr::null_mut(); + let mut count = 0u32; + // SAFETY: out pointers; the list is freed below and read within `count`. + let sessions: Vec = unsafe { + if WTSEnumerateSessionsW(WTS_CURRENT_SERVER_HANDLE, 0, 1, &mut list, &mut count) == 0 { + return; + } + let ids = std::slice::from_raw_parts(list, count as usize).iter().filter(|s| s.State == WTSActive).map(|s| s.SessionId).collect(); + WTSFreeMemory(list.cast()); + ids + }; + for id in sessions { + if let Err(e) = start_in(id, app) { + println!("warning: the app in session {id}: {e}"); + } + } + } + + fn start_in(session: u32, app: &Path) -> std::io::Result<()> { + let wide = |s: &str| s.encode_utf16().chain(Some(0)).collect::>(); + let mut command = wide(&format!("\"{}\"", app.display())); + let dir = wide(&app.parent().unwrap_or(app).display().to_string()); + let mut desktop = wide("winsta0\\default"); + // SAFETY: the token and environment are released below; the strings are + // NUL-terminated and live across the call; the out structs are zeroed. + unsafe { + let mut token: HANDLE = std::ptr::null_mut(); + if WTSQueryUserToken(session, &mut token) == 0 { + return Err(std::io::Error::last_os_error()); + } + let mut env: *mut core::ffi::c_void = std::ptr::null_mut(); + let have_env = CreateEnvironmentBlock(&mut env, token, 0) != 0; + let mut si: STARTUPINFOW = std::mem::zeroed(); + si.cb = std::mem::size_of::() as u32; + si.lpDesktop = desktop.as_mut_ptr(); + let mut pi: PROCESS_INFORMATION = std::mem::zeroed(); + let ok = CreateProcessAsUserW( + token, + std::ptr::null(), + command.as_mut_ptr(), + std::ptr::null(), + std::ptr::null(), + 0, + CREATE_UNICODE_ENVIRONMENT, + if have_env { env } else { std::ptr::null() }, + dir.as_ptr(), + &si, + &mut pi, + ) != 0; + let err = std::io::Error::last_os_error(); + if have_env { + DestroyEnvironmentBlock(env); + } + CloseHandle(token); + if !ok { + return Err(err); + } + CloseHandle(pi.hProcess); + CloseHandle(pi.hThread); + } + Ok(()) + } } pub fn remove() { diff --git a/windows/docs/screenshots/amneziawg.png b/windows/docs/screenshots/amneziawg.png index c915d2e..9539842 100644 Binary files a/windows/docs/screenshots/amneziawg.png and b/windows/docs/screenshots/amneziawg.png differ diff --git a/windows/docs/screenshots/autoproxy.png b/windows/docs/screenshots/autoproxy.png index 1cb18a0..048c2c5 100644 Binary files a/windows/docs/screenshots/autoproxy.png and b/windows/docs/screenshots/autoproxy.png differ diff --git a/windows/docs/screenshots/components.png b/windows/docs/screenshots/components.png index b5e0fc6..ec31019 100644 Binary files a/windows/docs/screenshots/components.png and b/windows/docs/screenshots/components.png differ diff --git a/windows/docs/screenshots/dpi-bypass.png b/windows/docs/screenshots/dpi-bypass.png index f30795c..161c2af 100644 Binary files a/windows/docs/screenshots/dpi-bypass.png and b/windows/docs/screenshots/dpi-bypass.png differ diff --git a/windows/docs/screenshots/logs.png b/windows/docs/screenshots/logs.png index ae8b99f..f0388ce 100644 Binary files a/windows/docs/screenshots/logs.png and b/windows/docs/screenshots/logs.png differ diff --git a/windows/docs/screenshots/outbounds.png b/windows/docs/screenshots/outbounds.png index 08c7302..737da29 100644 Binary files a/windows/docs/screenshots/outbounds.png and b/windows/docs/screenshots/outbounds.png differ diff --git a/windows/docs/screenshots/overview-dark.png b/windows/docs/screenshots/overview-dark.png new file mode 100644 index 0000000..0099f9e Binary files /dev/null and b/windows/docs/screenshots/overview-dark.png differ diff --git a/windows/docs/screenshots/overview.png b/windows/docs/screenshots/overview.png index f88d2aa..6583a7d 100644 Binary files a/windows/docs/screenshots/overview.png and b/windows/docs/screenshots/overview.png differ diff --git a/windows/docs/screenshots/settings.png b/windows/docs/screenshots/settings.png index ef9fee0..2ac248e 100644 Binary files a/windows/docs/screenshots/settings.png and b/windows/docs/screenshots/settings.png differ diff --git a/windows/docs/screenshots/telegram.png b/windows/docs/screenshots/telegram.png index c74bbee..247e379 100644 Binary files a/windows/docs/screenshots/telegram.png and b/windows/docs/screenshots/telegram.png differ diff --git a/windows/docs/screenshots/whitelist-bypass.png b/windows/docs/screenshots/whitelist-bypass.png index 0bf96ad..d9d6945 100644 Binary files a/windows/docs/screenshots/whitelist-bypass.png and b/windows/docs/screenshots/whitelist-bypass.png differ diff --git a/windows/release-notes/0.3.0-pre.1.md b/windows/release-notes/0.3.0-pre.1.md index 9e47cb1..5bc4f36 100644 --- a/windows/release-notes/0.3.0-pre.1.md +++ b/windows/release-notes/0.3.0-pre.1.md @@ -9,3 +9,5 @@ Proxy Suite for Windows 0.3.0-pre.1. Each has its SHA-256 in the `.sha256` file next to it. SmartScreen may warn of an unknown publisher, as the programs are not signed yet (**More info** → **Run anyway**). Needs 64-bit Windows 10 (1903 or later) or 11. ### New +- **Updates from the app**: its Overview says when a newer release is out and installs it. The service fetches the setup program from this project's releases, checks its SHA-256 against the one published beside it and runs it silently; the service and the app close for a moment and start again, new, settings kept. Also `proxy-ctl update` and `proxy-ctl update install`. It looks at start and daily (Settings → This app turns that off). This is the first release that has it: from 0.2.0-pre.1, update by running the new setup. +- **A dark theme**: light, dark, or as Windows is set (the default), in Settings → This app or at the sun/moon in the sidebar; the window's title bar follows it. diff --git a/windows/tools/screenshots.sh b/windows/tools/screenshots.sh index 3d09d10..8eba963 100755 --- a/windows/tools/screenshots.sh +++ b/windows/tools/screenshots.sh @@ -50,6 +50,11 @@ JSON release=$(ls -d dist/ProxySuite-*-windows-x64/components 2>/dev/null | tail -1 || true) [ -n "$release" ] && cp -r "$release/zapret" "$STATE/bin/" 2>/dev/null || true cargo build -q -p ps-service -p ps-gui +# The app's own preferences for the shots: the light theme (one dark shot below). +mkdir -p "$WORK/prefs/light/proxy-suite" "$WORK/prefs/dark/proxy-suite" +echo '{"theme":"light","checkUpdates":false}' >"$WORK/prefs/light/proxy-suite/app.json" +echo '{"theme":"dark","checkUpdates":false}' >"$WORK/prefs/dark/proxy-suite/app.json" +export XDG_CONFIG_HOME="$WORK/prefs/light" target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" >"$WORK/service.log" 2>&1 & SERVICE=$! trap 'kill $SERVICE $SERVER 2>/dev/null || true; rm -rf "$WORK"' EXIT @@ -75,3 +80,4 @@ shot amneziawg 378 shot logs 414 shot settings 450 shot components 486 +XDG_CONFIG_HOME="$WORK/prefs/dark" shot overview-dark 162