proxyparser 0.2.0

A cross-platform system proxy detector with strong support for complex enterprise PAC scripts
Documentation
// src/system_proxy/windows.rs

#[cfg(target_os = "windows")]
use crate::proxy::{normalize_proxy_url, parse_proxy_result, ProxyParseOptions, ProxyScheme};
#[cfg(target_os = "windows")]
use crate::system_proxy::SystemProxyConfig;
#[cfg(target_os = "windows")]
use crate::{log_info, log_warn};
#[cfg(target_os = "windows")]
use std::ffi::{OsStr, OsString};
#[cfg(target_os = "windows")]
use std::os::windows::ffi::{OsStrExt, OsStringExt};
#[cfg(target_os = "windows")]
use std::ptr;
#[cfg(target_os = "windows")]
use url::Url;
#[cfg(target_os = "windows")]
use winapi::um::errhandlingapi::GetLastError;
#[cfg(target_os = "windows")]
use winapi::um::winbase::GlobalFree;
#[cfg(target_os = "windows")]
use winapi::um::winhttp::{
    WinHttpCloseHandle, WinHttpGetIEProxyConfigForCurrentUser, WinHttpGetProxyForUrl, WinHttpOpen,
    WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_AUTOPROXY_AUTO_DETECT, WINHTTP_AUTOPROXY_OPTIONS,
    WINHTTP_AUTO_DETECT_TYPE_DHCP, WINHTTP_AUTO_DETECT_TYPE_DNS_A,
    WINHTTP_CURRENT_USER_IE_PROXY_CONFIG, WINHTTP_PROXY_INFO,
};

#[cfg(target_os = "windows")]
pub fn get_windows_proxy(url: &str) -> Option<String> {
    get_windows_proxy_config(url).map(|config| config.as_string().to_string())
}

#[cfg(target_os = "windows")]
pub fn get_windows_proxy_config(url: &str) -> Option<SystemProxyConfig> {
    let parsed_url = Url::parse(url).ok()?;

    let mut ie_config = WINHTTP_CURRENT_USER_IE_PROXY_CONFIG {
        fAutoDetect: 0,
        lpszAutoConfigUrl: ptr::null_mut(),
        lpszProxy: ptr::null_mut(),
        lpszProxyBypass: ptr::null_mut(),
    };

    let success = unsafe { WinHttpGetIEProxyConfigForCurrentUser(&mut ie_config) };
    if success == 0 {
        log_warn!("WinHttpGetIEProxyConfigForCurrentUser failed: {}", unsafe {
            GetLastError()
        });
        return None;
    }

    let _guard = scopeguard::guard((), |_| unsafe {
        if !ie_config.lpszAutoConfigUrl.is_null() {
            GlobalFree(ie_config.lpszAutoConfigUrl as _);
        }
        if !ie_config.lpszProxy.is_null() {
            GlobalFree(ie_config.lpszProxy as _);
        }
        if !ie_config.lpszProxyBypass.is_null() {
            GlobalFree(ie_config.lpszProxyBypass as _);
        }
    });

    if !ie_config.lpszProxyBypass.is_null() {
        let bypass = wide_ptr_to_string(ie_config.lpszProxyBypass);
        if windows_bypass_matches(&parsed_url, &bypass) {
            log_info!("URL is excluded by Windows proxy bypass list");
            return None;
        }
    }

    if !ie_config.lpszAutoConfigUrl.is_null() {
        let pac_url = wide_ptr_to_string(ie_config.lpszAutoConfigUrl);
        if !pac_url.trim().is_empty() {
            log_info!("Found PAC URL from Windows config: {}", pac_url);
            return Some(SystemProxyConfig::PacUrl(pac_url));
        }
    }

    if !ie_config.lpszProxy.is_null() {
        let proxy = wide_ptr_to_string(ie_config.lpszProxy);
        if let Some(proxy) = select_windows_proxy(&proxy, parsed_url.scheme()) {
            log_info!("Found Windows manual proxy: {}", proxy);
            return Some(SystemProxyConfig::Manual(proxy));
        }
    }

    if ie_config.fAutoDetect != 0 {
        if let Some(proxy) = get_wpad_proxy(url) {
            return Some(SystemProxyConfig::Manual(proxy));
        }
    }

    None
}

#[cfg(target_os = "windows")]
fn get_wpad_proxy(url: &str) -> Option<String> {
    let url_wide: Vec<u16> = OsStr::new(url)
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();

    let session = unsafe {
        WinHttpOpen(
            ptr::null(),
            WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY,
            ptr::null(),
            ptr::null(),
            0,
        )
    };
    if session.is_null() {
        log_warn!("WinHttpOpen failed for WPAD");
        return None;
    }

    let mut auto_options = WINHTTP_AUTOPROXY_OPTIONS {
        dwFlags: WINHTTP_AUTOPROXY_AUTO_DETECT,
        dwAutoDetectFlags: WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A,
        lpszAutoConfigUrl: ptr::null_mut(),
        lpvReserved: ptr::null_mut(),
        dwReserved: 0,
        fAutoLogonIfChallenged: 1,
    };

    let mut proxy_info = WINHTTP_PROXY_INFO {
        dwAccessType: 0,
        lpszProxy: ptr::null_mut(),
        lpszProxyBypass: ptr::null_mut(),
    };

    let result = unsafe {
        WinHttpGetProxyForUrl(
            session,
            url_wide.as_ptr(),
            &mut auto_options,
            &mut proxy_info,
        )
    };

    unsafe { WinHttpCloseHandle(session) };

    if result == 0 {
        log_warn!("WinHttpGetProxyForUrl failed: {}", unsafe {
            GetLastError()
        });
        return None;
    }

    let _proxy_guard = scopeguard::guard((), |_| unsafe {
        if !proxy_info.lpszProxy.is_null() {
            GlobalFree(proxy_info.lpszProxy as _);
        }
        if !proxy_info.lpszProxyBypass.is_null() {
            GlobalFree(proxy_info.lpszProxyBypass as _);
        }
    });

    if proxy_info.lpszProxy.is_null() {
        return None;
    }

    let proxy = wide_ptr_to_string(proxy_info.lpszProxy);
    let parsed = parse_proxy_result(&proxy, &ProxyParseOptions::default());
    if parsed.proxies.is_empty() {
        None
    } else {
        let normalized = parsed.to_proxy_string();
        log_info!("Found proxy via Windows WPAD: {}", normalized);
        Some(normalized)
    }
}

#[cfg(target_os = "windows")]
fn select_windows_proxy(raw: &str, target_scheme: &str) -> Option<String> {
    let keyed = raw.contains('=');
    if keyed {
        let preferred_key = match target_scheme {
            "https" => "https",
            "http" => "http",
            _ => "socks",
        };
        for token in raw.split(';') {
            let Some((key, value)) = token.split_once('=') else {
                continue;
            };
            if key.trim().eq_ignore_ascii_case(preferred_key) {
                let scheme = match preferred_key {
                    "https" => ProxyScheme::Https,
                    "socks" => ProxyScheme::Socks5,
                    _ => ProxyScheme::Http,
                };
                if let Some(proxy) = normalize_proxy_url(value, scheme) {
                    return Some(proxy);
                }
            }
        }
    }

    let parsed = parse_proxy_result(raw, &ProxyParseOptions::default());
    if parsed.proxies.is_empty() {
        None
    } else {
        Some(parsed.to_proxy_string())
    }
}

#[cfg(target_os = "windows")]
fn windows_bypass_matches(url: &Url, bypass: &str) -> bool {
    let Some(host) = url.host_str().map(|value| value.to_ascii_lowercase()) else {
        return false;
    };

    for raw_entry in bypass.split([';', ',', ' ']) {
        let entry = raw_entry.trim().to_ascii_lowercase();
        if entry.is_empty() {
            continue;
        }
        if entry == "<local>" && !host.contains('.') {
            return true;
        }
        if entry == "*" {
            return true;
        }
        if let Some(suffix) = entry.strip_prefix("*.") {
            if host == suffix || host.ends_with(&format!(".{}", suffix)) {
                return true;
            }
        } else if host == entry || host.ends_with(&format!(".{}", entry)) {
            return true;
        }
    }
    false
}

#[cfg(target_os = "windows")]
fn wide_ptr_to_string(ptr: *mut u16) -> String {
    if ptr.is_null() {
        return String::new();
    }
    let len = unsafe { (0..).take_while(|&i| *ptr.offset(i) != 0).count() };
    let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
    OsString::from_wide(slice).to_string_lossy().into_owned()
}