//! 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, } /// Where the settings live: the registry, or a test's stand-in. trait Store { fn read(&mut self) -> Result; fn write(&mut self, s: &Settings) -> Result<(), String>; } struct Registry; impl Store for Registry { fn read(&mut self) -> Result { platform::read() } fn write(&mut self, s: &Settings) -> Result<(), String> { platform::write(s) } } pub struct SystemProxy { store: Box, /// The user's own settings, from before the app changed them. saved: Option, /// What the app set, while it is set. applied: Option, /// Whether a setting left behind by a killed app has been looked for: once, at the start, /// so a proxy the user sets by hand later is theirs to keep. looked: bool, } impl Default for SystemProxy { fn default() -> Self { Self { store: Box::new(Registry), saved: None, applied: None, looked: false } } } 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)) }; let first = !self.looked; self.looked = true; if want { if self.applied.as_ref() == Some(&ours) { return Ok(()); } if self.saved.is_none() { // At the start, one the app left set (it was killed) is not the user's: theirs // was off. let now = self.store.read()?; let left = first && now.enable && now.server == ours.server; self.saved = Some(if left { Settings { enable: false, ..now } } else { now }); } self.store.write(&ours)?; self.applied = Some(ours); } else if self.applied.take().is_some() { if let Some(saved) = self.saved.take() { self.store.write(&saved)?; } } else if first { let now = self.store.read()?; if now.enable && now.server.as_deref() == Some(listener) { self.store.write(&Settings { enable: false, ..now })?; } } Ok(()) } pub fn restore(&mut self) { if self.applied.take().is_some() && let Some(saved) = self.saved.take() { let _ = self.store.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.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).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 std::cell::RefCell; use std::rc::Rc; use super::*; /// The registry, in memory, with a count of reads. #[derive(Clone)] struct Fake(Rc>); impl Store for Fake { fn read(&mut self) -> Result { let mut s = self.0.borrow_mut(); s.1 += 1; Ok(s.0.clone()) } fn write(&mut self, s: &Settings) -> Result<(), String> { self.0.borrow_mut().0 = s.clone(); Ok(()) } } fn with(settings: Settings) -> (SystemProxy, Fake) { let fake = Fake(Rc::new(RefCell::new((settings, 0)))); (SystemProxy { store: Box::new(fake.clone()), saved: None, applied: None, looked: false }, fake) } fn set(server: &str, enable: bool) -> Settings { Settings { enable, server: Some(server.into()), bypass: None } } #[test] fn a_proxy_the_user_sets_by_hand_is_left_alone() { let (mut sp, fake) = with(set("10.0.0.1:3128", true)); sp.update(false, "127.0.0.1:1080", &[]).unwrap(); // Later the user points it at the local proxy themselves. fake.0.borrow_mut().0 = set("127.0.0.1:1080", true); for _ in 0..3 { sp.update(false, "127.0.0.1:1080", &[]).unwrap(); } assert_eq!(fake.0.borrow().0, set("127.0.0.1:1080", true)); assert_eq!(fake.0.borrow().1, 1, "looked once, at the start"); } #[test] fn one_left_behind_is_cleared_at_the_start() { let (mut sp, fake) = with(set("127.0.0.1:1080", true)); sp.update(false, "127.0.0.1:1080", &[]).unwrap(); assert!(!fake.0.borrow().0.enable); } #[test] fn the_users_own_comes_back() { let (mut sp, fake) = with(set("10.0.0.1:3128", true)); sp.update(true, "127.0.0.1:1080", &[]).unwrap(); assert_eq!(fake.0.borrow().0.server.as_deref(), Some("127.0.0.1:1080")); sp.update(true, "127.0.0.1:1080", &[]).unwrap(); sp.update(false, "127.0.0.1:1080", &[]).unwrap(); assert_eq!(fake.0.borrow().0, set("10.0.0.1:3128", true)); // Left behind at the start (killed while on): the user's was off. let (mut sp, fake) = with(Settings { bypass: Some("".into()), ..set("127.0.0.1:1080", true) }); sp.update(true, "127.0.0.1:1080", &[]).unwrap(); sp.restore(); assert!(!fake.0.borrow().0.enable); } #[test] fn bypass_always_has_local_names() { assert_eq!(bypass_list(&[]), ""); assert_eq!(bypass_list(&["*.lan".into(), "".into()]), "*.lan;"); } }