|
| 1 | +use crate::SystemProxy; |
| 2 | +use std::{net::SocketAddr, str::FromStr}; |
| 3 | +use winapi::shared::ntdef::NULL; |
| 4 | +use winapi::um::wininet::{ |
| 5 | + InternetSetOptionA, INTERNET_OPTION_REFRESH, INTERNET_OPTION_SETTINGS_CHANGED, |
| 6 | +}; |
| 7 | +use winreg::{enums, RegKey}; |
| 8 | + |
| 9 | +const SUB_KEY: &str = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Internet Settings"; |
| 10 | + |
| 11 | +impl SystemProxy { |
| 12 | + pub fn get() -> SystemProxy { |
| 13 | + let current_user = RegKey::predef(enums::HKEY_CURRENT_USER); |
| 14 | + let key = current_user |
| 15 | + .open_subkey_with_flags(SUB_KEY, enums::KEY_READ) |
| 16 | + .map_err(|e| eprintln!("ERROR: Could not open subkey with flags: {}", e.to_string())) |
| 17 | + .unwrap(); |
| 18 | + let is_enabled = key |
| 19 | + .get_value::<u32, _>("ProxyEnable") |
| 20 | + .expect("ERROR: Could not get key value") |
| 21 | + == 1u32; |
| 22 | + let server = key |
| 23 | + .get_value::<String, _>("ProxyServer") |
| 24 | + .expect("ERROR: Could not get key value"); |
| 25 | + let server = server.as_str(); |
| 26 | + let socket = SocketAddr::from_str(server) |
| 27 | + .map_err(|e| { |
| 28 | + eprintln!("ERROR: Could not parse from str: {}", e.to_string()); |
| 29 | + }) |
| 30 | + .unwrap(); |
| 31 | + let host = socket.ip().to_string(); |
| 32 | + let port = socket.port(); |
| 33 | + let bypass: String = key.get_value("ProxyOverride").unwrap_or("".into()); |
| 34 | + |
| 35 | + SystemProxy { |
| 36 | + is_enabled, |
| 37 | + host: host, |
| 38 | + port: port, |
| 39 | + bypass: bypass, |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + pub fn set(proxy: SystemProxy) { |
| 44 | + let hkcu = RegKey::predef(enums::HKEY_CURRENT_USER); |
| 45 | + let cur_var = hkcu |
| 46 | + .open_subkey_with_flags(SUB_KEY, enums::KEY_SET_VALUE) |
| 47 | + .expect("ERROR: Could not open subkey with flags"); |
| 48 | + |
| 49 | + let enable = if proxy.is_enabled { 1u32 } else { 0u32 }; |
| 50 | + let server = format!("{}:{}", proxy.host, proxy.port); |
| 51 | + let bypass = proxy.bypass.as_str(); |
| 52 | + |
| 53 | + cur_var |
| 54 | + .set_value("ProxyEnable", &enable) |
| 55 | + .expect("ERROR: Could not set value ProxyEnable"); |
| 56 | + cur_var |
| 57 | + .set_value("ProxyServer", &server) |
| 58 | + .expect("ERROR: Could not set value ProxyServer"); |
| 59 | + cur_var |
| 60 | + .set_value("ProxyOverride", &bypass) |
| 61 | + .expect("ERROR: Could not set value ProxyOverride"); |
| 62 | + |
| 63 | + unsafe { |
| 64 | + InternetSetOptionA(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0); |
| 65 | + InternetSetOptionA(NULL, INTERNET_OPTION_REFRESH, NULL, 0); |
| 66 | + } |
| 67 | + } |
| 68 | +} |
0 commit comments