windows: the app sets the system proxy; ps-core lint fixes
- The app points the signed-in user's system proxy (WinINet: browsers and most programs follow it) at the local proxy while it runs and proxy.systemProxy.enable asks; the user's own settings are kept and put back when the proxy stops, the service goes, the option is turned off or the app quits; one left behind by a killed app is cleared. A switch for it on the overview. Elsewhere than Windows it does nothing. - ps-core: clippy's collapsible ifs, comparisons without owned values, a range loop without indexing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
77becc235c
commit
7565e62571
9 files changed
+248
-17
No files matched your search
@@ -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<String>,
|
||||
bypass: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct SystemProxy {
|
||||
/// The user's own settings, from before the app changed them.
|
||||
saved: Option<Settings>,
|
||||
/// What the app set, while it is set.
|
||||
applied: Option<Settings>,
|
||||
}
|
||||
|
||||
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 (`<local>`).
|
||||
fn bypass_list(bypass: &[String]) -> String {
|
||||
let mut list: Vec<&str> = bypass.iter().map(String::as_str).filter(|h| !h.is_empty()).collect();
|
||||
if !list.contains(&"<local>") {
|
||||
list.push("<local>");
|
||||
}
|
||||
list.join(";")
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
mod platform {
|
||||
use windows_sys::Win32::Foundation::ERROR_SUCCESS;
|
||||
use windows_sys::Win32::Networking::WinInet::{INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, InternetSetOptionW};
|
||||
use windows_sys::Win32::System::Registry::{
|
||||
HKEY, HKEY_CURRENT_USER, KEY_READ, KEY_WRITE, REG_DWORD, REG_SZ, RegCloseKey, RegDeleteValueW, RegOpenKeyExW, RegQueryValueExW, RegSetValueExW,
|
||||
};
|
||||
|
||||
use super::Settings;
|
||||
|
||||
const KEY: &str = r"Software\Microsoft\Windows\CurrentVersion\Internet Settings";
|
||||
|
||||
fn wide(s: &str) -> Vec<u16> {
|
||||
s.encode_utf16().chain(Some(0)).collect()
|
||||
}
|
||||
|
||||
struct Key(HKEY);
|
||||
|
||||
impl Drop for Key {
|
||||
fn drop(&mut self) {
|
||||
unsafe { RegCloseKey(self.0) };
|
||||
}
|
||||
}
|
||||
|
||||
fn open() -> Result<Key, String> {
|
||||
let mut key: HKEY = std::ptr::null_mut();
|
||||
let rc = unsafe { RegOpenKeyExW(HKEY_CURRENT_USER, wide(KEY).as_ptr(), 0, KEY_READ | KEY_WRITE, &mut key) };
|
||||
if rc != ERROR_SUCCESS {
|
||||
return Err(format!("opening the Internet settings: error {rc}"));
|
||||
}
|
||||
Ok(Key(key))
|
||||
}
|
||||
|
||||
fn query(key: &Key, name: &str) -> Option<Vec<u8>> {
|
||||
let name = wide(name);
|
||||
let mut len = 0u32;
|
||||
let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), std::ptr::null_mut(), &mut len) };
|
||||
if rc != ERROR_SUCCESS {
|
||||
return None;
|
||||
}
|
||||
let mut buf = vec![0u8; len as usize];
|
||||
let rc = unsafe { RegQueryValueExW(key.0, name.as_ptr(), std::ptr::null(), std::ptr::null_mut(), buf.as_mut_ptr(), &mut len) };
|
||||
(rc == ERROR_SUCCESS).then(|| {
|
||||
buf.truncate(len as usize);
|
||||
buf
|
||||
})
|
||||
}
|
||||
|
||||
fn text(bytes: Vec<u8>) -> String {
|
||||
let units: Vec<u16> = bytes.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<Settings, String> {
|
||||
let key = open()?;
|
||||
let enable = query(&key, "ProxyEnable").and_then(|b| b.get(..4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))).unwrap_or(0) != 0;
|
||||
Ok(Settings { enable, server: query(&key, "ProxyServer").map(text), bypass: query(&key, "ProxyOverride").map(text) })
|
||||
}
|
||||
|
||||
fn set_text(key: &Key, name: &str, value: Option<&str>) -> Result<(), String> {
|
||||
let name_w = wide(name);
|
||||
let rc = match value {
|
||||
Some(v) => {
|
||||
let data = wide(v);
|
||||
unsafe { RegSetValueExW(key.0, name_w.as_ptr(), 0, REG_SZ, data.as_ptr().cast(), (data.len() * 2) as u32) }
|
||||
}
|
||||
None => match unsafe { RegDeleteValueW(key.0, name_w.as_ptr()) } {
|
||||
2 => ERROR_SUCCESS, // was not there
|
||||
rc => rc,
|
||||
},
|
||||
};
|
||||
if rc != ERROR_SUCCESS { Err(format!("setting {name}: error {rc}")) } else { Ok(()) }
|
||||
}
|
||||
|
||||
pub fn write(s: &Settings) -> Result<(), String> {
|
||||
let key = open()?;
|
||||
let enable: u32 = s.enable.into();
|
||||
let rc = unsafe { RegSetValueExW(key.0, wide("ProxyEnable").as_ptr(), 0, REG_DWORD, (&enable as *const u32).cast(), 4) };
|
||||
if rc != ERROR_SUCCESS {
|
||||
return Err(format!("setting ProxyEnable: error {rc}"));
|
||||
}
|
||||
set_text(&key, "ProxyServer", s.server.as_deref())?;
|
||||
set_text(&key, "ProxyOverride", s.bypass.as_deref())?;
|
||||
// Programs running now are told; others read it when they start.
|
||||
unsafe {
|
||||
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_SETTINGS_CHANGED, std::ptr::null(), 0);
|
||||
InternetSetOptionW(std::ptr::null(), INTERNET_OPTION_REFRESH, std::ptr::null(), 0);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(windows))]
|
||||
mod platform {
|
||||
use super::Settings;
|
||||
|
||||
pub fn read() -> Result<Settings, String> {
|
||||
Ok(Settings { enable: false, server: None, bypass: None })
|
||||
}
|
||||
|
||||
pub fn write(_: &Settings) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bypass_always_has_local_names() {
|
||||
assert_eq!(bypass_list(&[]), "<local>");
|
||||
assert_eq!(bypass_list(&["*.lan".into(), "<local>".into()]), "*.lan;<local>");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user