From 7565e625719e8a8d2fe0539b9640a431957cebc0 Mon Sep 17 00:00:00 2001 From: faumaray Date: Tue, 27 Oct 2026 02:07:02 +0300 Subject: [PATCH] windows: the app sets the system proxy; ps-core lint fixes - The app points the signed-in user's system proxy (WinINet: browsers and most programs follow it) at the local proxy while it runs and proxy.systemProxy.enable asks; the user's own settings are kept and put back when the proxy stops, the service goes, the option is turned off or the app quits; one left behind by a killed app is cleared. A switch for it on the overview. Elsewhere than Windows it does nothing. - ps-core: clippy's collapsible ifs, comparisons without owned values, a range loop without indexing. Co-Authored-By: Claude Opus 5.5 --- windows/crates/ps-core/src/components.rs | 16 +- .../crates/ps-core/src/render/outbounds.rs | 4 +- windows/crates/ps-core/src/wg.rs | 8 +- windows/crates/ps-core/src/zapret2.rs | 3 +- windows/crates/ps-gui/Cargo.toml | 3 + windows/crates/ps-gui/src/main.rs | 1 + windows/crates/ps-gui/src/shell.rs | 30 ++- windows/crates/ps-gui/src/sysproxy.rs | 181 ++++++++++++++++++ windows/crates/ps-gui/src/ui/overview.rs | 19 +- 9 files changed, 248 insertions(+), 17 deletions(-) create mode 100644 windows/crates/ps-gui/src/sysproxy.rs diff --git a/windows/crates/ps-core/src/components.rs b/windows/crates/ps-core/src/components.rs index ecec089..30bda0a 100644 --- a/windows/crates/ps-core/src/components.rs +++ b/windows/crates/ps-core/src/components.rs @@ -73,15 +73,15 @@ impl Source { return None; } let rel = entry.strip_prefix(self.strip.as_str())?; - if let Some(files) = &self.files { - if !files.contains_key(rel) { - return None; - } + if let Some(files) = &self.files + && !files.contains_key(rel) + { + return None; } - if let Some(include) = &self.include { - if !matches(include, rel) { - return None; - } + if let Some(include) = &self.include + && !matches(include, rel) + { + return None; } if matches(&self.exclude, rel) { return None; diff --git a/windows/crates/ps-core/src/render/outbounds.rs b/windows/crates/ps-core/src/render/outbounds.rs index a48efb8..5834b9e 100644 --- a/windows/crates/ps-core/src/render/outbounds.rs +++ b/windows/crates/ps-core/src/render/outbounds.rs @@ -538,7 +538,7 @@ fn chain(b: &mut Builder, warnings: &mut Vec) { if drop.is_empty() { for (t, hop) in &hops { let set = |ob: &mut Value| { - if ob["tag"] == Value::from(t.as_str()) { + if ob["tag"] == t.as_str() { if xray_tags.contains(t) || b.backend == Backend::Xray { ob["streamSettings"]["sockopt"]["dialerProxy"] = hop.clone().into(); } else { @@ -554,7 +554,7 @@ fn chain(b: &mut Builder, warnings: &mut Vec) { } for (t, why) in drop { warnings.push(format!("outbound '{t}': {why}; leaving it out")); - let keep = |o: &Value| o["tag"] != Value::from(t.as_str()); + let keep = |o: &Value| o["tag"] != t.as_str(); b.outbounds.retain(keep); b.endpoints.retain(keep); b.xray.retain(keep); diff --git a/windows/crates/ps-core/src/wg.rs b/windows/crates/ps-core/src/wg.rs index d890d78..3e465cd 100644 --- a/windows/crates/ps-core/src/wg.rs +++ b/windows/crates/ps-core/src/wg.rs @@ -47,10 +47,10 @@ pub fn conf_sections(config: &str) -> Vec
{ let stripped = line.split('#').next().unwrap_or("").split(';').next().unwrap_or("").trim(); if stripped.starts_with('[') && stripped.ends_with(']') && stripped.len() >= 2 { sections.push((stripped[1..stripped.len() - 1].trim().to_lowercase(), Vec::new())); - } else if let Some((key, value)) = stripped.split_once('=') { - if let Some(last) = sections.last_mut() { - last.1.push((key.trim().to_lowercase(), value.trim().to_owned())); - } + } else if let Some((key, value)) = stripped.split_once('=') + && let Some(last) = sections.last_mut() + { + last.1.push((key.trim().to_lowercase(), value.trim().to_owned())); } } sections diff --git a/windows/crates/ps-core/src/zapret2.rs b/windows/crates/ps-core/src/zapret2.rs index 913e2fa..d79f872 100644 --- a/windows/crates/ps-core/src/zapret2.rs +++ b/windows/crates/ps-core/src/zapret2.rs @@ -214,8 +214,9 @@ fn merge_ports(lists: &[&str]) -> String { } let mut out = Vec::new(); let mut start = 0; + // One past the last port, so a run that reaches 65535 ends too. for port in 1..=65536usize { - if port <= 65535 && on[port] { + if on.get(port).copied().unwrap_or(false) { if start == 0 { start = port; } diff --git a/windows/crates/ps-gui/Cargo.toml b/windows/crates/ps-gui/Cargo.toml index 2be194c..2903396 100644 --- a/windows/crates/ps-gui/Cargo.toml +++ b/windows/crates/ps-gui/Cargo.toml @@ -18,3 +18,6 @@ anyhow.workspace = true serde_json.workspace = true tokio.workspace = true async-channel = "2" + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = ["Win32_Foundation", "Win32_System_Registry", "Win32_Networking_WinInet"] } diff --git a/windows/crates/ps-gui/src/main.rs b/windows/crates/ps-gui/src/main.rs index 90a5810..b6914b0 100644 --- a/windows/crates/ps-gui/src/main.rs +++ b/windows/crates/ps-gui/src/main.rs @@ -11,6 +11,7 @@ mod assets; mod bridge; mod model; mod shell; +mod sysproxy; mod ui; use gpui_kit::*; diff --git a/windows/crates/ps-gui/src/shell.rs b/windows/crates/ps-gui/src/shell.rs index ada487b..db778a3 100644 --- a/windows/crates/ps-gui/src/shell.rs +++ b/windows/crates/ps-gui/src/shell.rs @@ -8,6 +8,7 @@ use ps_client::edits; use serde_json::Value; use crate::model::{Connection, Model}; +use crate::sysproxy::SystemProxy; use crate::ui::AppView; actions!(proxy_suite, [OpenWindow, ToggleProxy, ToggleDpi, ToggleTelegram, Quit]); @@ -18,13 +19,16 @@ struct Shell { tray: Option, /// The icon's colour now, so it is only replaced when that changes. colour: &'static str, + system_proxy: SystemProxy, + /// The system proxy's last failure, said once. + system_proxy_error: Option, } impl Global for Shell {} pub fn start(model: Entity, open: bool, cx: &mut App) { cx.on_action(open_window).on_action(toggle_proxy).on_action(toggle_dpi).on_action(toggle_telegram).on_action(quit); - cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "" }); + cx.set_global(Shell { model: model.clone(), window: None, tray: None, colour: "", system_proxy: SystemProxy::default(), system_proxy_error: None }); let mut builder = Tray::builder().tooltip("Proxy Suite").on_activate(OpenWindow).menu(menu); if let Some(icon) = icon("#6b7280", cx) { @@ -78,7 +82,30 @@ fn icon(fill: &str, cx: &App) -> Option { Icon::from_gpui(&Image::from_bytes(ImageFormat::Svg, svg.into_bytes()), cx).build().inspect_err(|e| eprintln!("proxy-suite: the tray icon: {e}")).ok() } +/// The system proxy, as the configuration and the local proxy's state say. +fn system_proxy(cx: &mut App) { + let m = cx.global::().model.read(cx); + let (s, c) = (m.status(), m.config()); + let up = *m.connection() == Connection::Up; + let want = up && c["proxy"]["systemProxy"]["enable"] == true && s["proxy"]["on"] == true && s["proxy"]["state"] == "active"; + let listener = s["proxy"]["listener"].as_str().unwrap_or("").replace("0.0.0.0:", "127.0.0.1:"); + let bypass: Vec = c["proxy"]["systemProxy"]["bypass"].as_array().into_iter().flatten().filter_map(|v| v.as_str().map(str::to_owned)).collect(); + if listener.is_empty() || c.is_null() { + return; + } + let shell = cx.global_mut::(); + match shell.system_proxy.update(want, &listener, &bypass) { + Ok(()) => shell.system_proxy_error = None, + Err(e) if shell.system_proxy_error.as_ref() != Some(&e) => { + eprintln!("proxy-suite: the system proxy: {e}"); + shell.system_proxy_error = Some(e); + } + Err(_) => {} + } +} + fn refresh(cx: &mut App) { + system_proxy(cx); let Some(tray) = cx.global::().tray.clone() else { return }; let fill = colour(cx); if fill != cx.global::().colour { @@ -170,6 +197,7 @@ fn toggle_telegram(_: &ToggleTelegram, cx: &mut App) { } fn quit(_: &Quit, cx: &mut App) { + cx.global_mut::().system_proxy.restore(); if let Some(tray) = cx.global::().tray.clone() { let _ = tray.close(cx); } diff --git a/windows/crates/ps-gui/src/sysproxy.rs b/windows/crates/ps-gui/src/sysproxy.rs new file mode 100644 index 0000000..810b0ec --- /dev/null +++ b/windows/crates/ps-gui/src/sysproxy.rs @@ -0,0 +1,181 @@ +//! The system proxy (Windows): the signed-in user's WinINet setting, which browsers and most +//! programs follow, pointed at the local proxy while it runs and `proxy.systemProxy.enable` +//! asks for it; put back as it was when the proxy stops, the service goes, the option is turned +//! off, or the app quits. Elsewhere it does nothing. + +/// WinINet's proxy settings: on or off, the server, the hosts that skip it. +#[derive(Clone, Debug, PartialEq, Eq)] +struct Settings { + enable: bool, + server: Option, + bypass: Option, +} + +#[derive(Default)] +pub struct SystemProxy { + /// The user's own settings, from before the app changed them. + saved: Option, + /// What the app set, while it is set. + applied: Option, +} + +impl SystemProxy { + /// Points the system proxy at `listener` (host:port) when `want`, puts the user's own back + /// when not. A setting the app left behind (it was killed) is cleared too. + pub fn update(&mut self, want: bool, listener: &str, bypass: &[String]) -> Result<(), String> { + let ours = Settings { enable: true, server: Some(listener.to_owned()), bypass: Some(bypass_list(bypass)) }; + if want { + if self.applied.as_ref() == Some(&ours) { + return Ok(()); + } + if self.saved.is_none() { + self.saved = Some(platform::read()?); + } + platform::write(&ours)?; + self.applied = Some(ours); + } else if self.applied.take().is_some() { + if let Some(saved) = self.saved.take() { + platform::write(&saved)?; + } + } else if self.saved.is_none() { + let now = platform::read()?; + if now.enable && now.server.as_deref() == Some(listener) { + platform::write(&Settings { enable: false, ..now })?; + } + } + Ok(()) + } + + pub fn restore(&mut self) { + if self.applied.take().is_some() + && let Some(saved) = self.saved.take() + { + let _ = platform::write(&saved); + } + } +} + +/// WinINet's bypass list: the configured hosts, and names without a dot (``). +fn bypass_list(bypass: &[String]) -> String { + let mut list: Vec<&str> = bypass.iter().map(String::as_str).filter(|h| !h.is_empty()).collect(); + if !list.contains(&"") { + list.push(""); + } + list.join(";") +} + +#[cfg(windows)] +mod platform { + use windows_sys::Win32::Foundation::ERROR_SUCCESS; + use windows_sys::Win32::Networking::WinInet::{INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, InternetSetOptionW}; + use windows_sys::Win32::System::Registry::{ + HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_DWORD, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW, + }; + + use super::Settings; + + const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings"; + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(Some(0)).collect() + } + + struct Key(HKEY); + + impl Drop for Key { + fn drop(&mut self) { + unsafe { RegCloseKey(self.0) }; + } + } + + fn open() -> Result { + let mut key: HKEY = std::ptr::null_mut(); + let rc = unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, wide(KEY).as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) }; + if rc != ERROR_SUCCESS { + return Err(format!("opening the Internet settings: error {rc}")); + } + Ok(Key(key)) + } + + fn query(key: &Key, name: &str) -> Option> { + let name = wide(name); + let mut len = 0u32; + let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut(), &mut len) }; + if rc != ERROR_SUCCESS { + return None; + } + let mut buf = vec![0u8; len as usize]; + let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), buf.as_mut_ptr(), &mut len) }; + (rc == ERROR_SUCCESS).then(|| { + buf.truncate(len as usize); + buf + }) + } + + fn text(bytes: Vec) -> String { + let units: Vec = bytes.chunks_exact(2).map(|c| u16::from_le_bytes([c[0], c[1]])).take_while(|u| *u != 0).collect(); + String::from_utf16_lossy(&units) + } + + pub fn read() -> Result { + let key = open()?; + let enable = query(&key, "ProxyEnable").and_then(|b| b.get(..4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))).unwrap_or(0) != 0; + Ok(Settings { enable, server: query(&key, "ProxyServer").map(text), bypass: query(&key, "ProxyOverride").map(text) }) + } + + fn set_text(key: &Key, name: &str, value: Option<&str>) -> Result<(), String> { + let name_w = wide(name); + let rc = match value { + Some(v) => { + let data = wide(v); + unsafe { RegSetValueExW(key.0, name_w.as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) } + } + None => match unsafe { RegDeleteValueW(key.0, name_w.as_ptr()) } { + 2 => ERROR_SUCCESS, // was not there + rc => rc, + }, + }; + if rc != ERROR_SUCCESS { Err(format!("setting {name}: error {rc}")) } else { Ok(()) } + } + + pub fn write(s: &Settings) -> Result<(), String> { + let key = open()?; + let enable: u32 = s.enable.into(); + let rc = unsafe { RegSetValueExW(key.0, wide("ProxyEnable").as_ptr(), 0, REG_DWORD, (&enable as *const u32).cast(), 4) }; + if rc != ERROR_SUCCESS { + return Err(format!("setting ProxyEnable: error {rc}")); + } + set_text(&key, "ProxyServer", s.server.as_deref())?; + set_text(&key, "ProxyOverride", s.bypass.as_deref())?; + // Programs running now are told; others read it when they start. + unsafe { + InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_SETTINGS_CHANGED, std::ptr::null(), 0); + InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_REFRESH, std::ptr::null(), 0); + } + Ok(()) + } +} + +#[cfg(not(windows))] +mod platform { + use super::Settings; + + pub fn read() -> Result { + Ok(Settings { enable: false, server: None, bypass: None }) + } + + pub fn write(_: &Settings) -> Result<(), String> { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bypass_always_has_local_names() { + assert_eq!(bypass_list(&[]), ""); + assert_eq!(bypass_list(&["*.lan".into(), "".into()]), "*.lan;"); + } +} diff --git a/windows/crates/ps-gui/src/ui/overview.rs b/windows/crates/ps-gui/src/ui/overview.rs index e1b811b..92f0c48 100644 --- a/windows/crates/ps-gui/src/ui/overview.rs +++ b/windows/crates/ps-gui/src/ui/overview.rs @@ -64,7 +64,24 @@ pub fn render(model: &Entity, _: &mut Window, cx: &mut Context) .child(fact("Listening on", text(&p["listener"]), cx)) .child(fact("Backend", text(&p["backend"]), cx)) .child(fact("Mode", p["mode"].as_str().unwrap_or("default").to_owned(), cx)) - .child(fact("Outbound", p["pinned"].as_str().map(|t| format!("{t} (pinned)")).unwrap_or_else(|| format!("{} selection", p["selection"].as_str().unwrap_or("?"))), cx)); + .child(fact("Outbound", p["pinned"].as_str().map(|t| format!("{t} (pinned)")).unwrap_or_else(|| format!("{} selection", p["selection"].as_str().unwrap_or("?"))), cx)) + .child({ + let model = model.clone(); + let on = m.config()["proxy"]["systemProxy"]["enable"] == true; + Switch::new("system-proxy").label("Use it as the system proxy (browsers and most programs follow it)").checked(on).on_change(move |on, _, cx| { + let on = *on; + model.update(cx, |m, cx| { + m.edit( + if on { "The system proxy follows the local proxy" } else { "The system proxy is left alone" }, + move |c| { + edits::set_path(c, &["proxy", "systemProxy", "enable"], on.into()); + Ok(()) + }, + cx, + ) + }) + }) + }); let z = &s["zapret"]; let model_z = model.clone();