Visual Studio Code, rebuilt in Rust
Rust
//! request.rs on Windows: `send` is linux.rs's curl (the curl.exe Windows 10 1803 and later ship in System32) with
//! the proxy Chromium's ProxyConfigServiceWin would pick: the session proxy, else the IE settings of WinHTTP.
use std::sync::OnceLock;
use windows_sys::Win32::Foundation::{GetLastError, GlobalFree};
use windows_sys::Win32::Networking::WinHttp::{
ERROR_WINHTTP_LOGIN_FAILURE, WINHTTP_ACCESS_TYPE_NAMED_PROXY, WINHTTP_ACCESS_TYPE_NO_PROXY, WINHTTP_AUTO_DETECT_TYPE_DHCP, WINHTTP_AUTO_DETECT_TYPE_DNS_A, WINHTTP_AUTOPROXY_AUTO_DETECT,
WINHTTP_AUTOPROXY_CONFIG_URL, WINHTTP_AUTOPROXY_OPTIONS, WINHTTP_CURRENT_USER_IE_PROXY_CONFIG, WINHTTP_PROXY_INFO, WinHttpGetIEProxyConfigForCurrentUser,
WinHttpGetProxyForUrl, WinHttpOpen,
};
use windows_sys::core::PWSTR;
use super::proxy_rules::{curl_proxy, pac_for_list, pac_for_rules};
use super::{Request, Response, SessionProxy};
// shortcut: curl takes one proxy, so the first of the list is used without Chromium's fallback to the next on a
// connection failure; send through WinHTTP when a proxy list with fallbacks is needed.
pub(super) fn send(options: &Request, proxy: Option<&SessionProxy>, proxy_authorization: Option<&str>) -> anyhow::Result<Response> {
let resolved = resolve_proxy_with(options.url, proxy).unwrap_or_default();
let rules = curl_proxy(resolved.split(';').next().unwrap_or_default());
super::linux::send(options, Some(&SessionProxy { rules, bypass_rules: String::new() }), proxy_authorization)
}
/// ProxyConfigServiceWin `SetFromIEConfig`: auto-detect and the PAC URL first; when they give nothing, the manual
/// proxy and its bypass list.
pub(super) fn resolve_proxy_with(url: &str, proxy: Option<&SessionProxy>) -> Option<String> {
if let Some(proxy) = proxy {
return Some(pac_for_rules(url, &proxy.rules, &proxy.bypass_rules));
}
let mut config = WINHTTP_CURRENT_USER_IE_PROXY_CONFIG::default();
// SAFETY: WinHTTP fills the struct; each string it allocates is taken and freed once below.
let read = unsafe { WinHttpGetIEProxyConfigForCurrentUser(&mut config) } != 0;
let (auto_detect, pac_url, manual, bypass) = if read {
// SAFETY: as above.
unsafe { (config.fAutoDetect != 0, take_wide(config.lpszAutoConfigUrl), take_wide(config.lpszProxy), take_wide(config.lpszProxyBypass)) }
} else {
(false, None, None, None)
};
if (auto_detect || pac_url.is_some())
&& let Some(list) = automatic_proxy(url, auto_detect, pac_url.as_deref())
{
return Some(list);
}
Some(pac_for_rules(url, manual.as_deref().unwrap_or_default(), bypass.as_deref().unwrap_or_default()))
}
/// WPAD and the PAC script through `WinHttpGetProxyForUrl`, on one session so WinHTTP keeps the script cached.
fn automatic_proxy(url: &str, auto_detect: bool, pac_url: Option<&str>) -> Option<String> {
static SESSION: OnceLock<usize> = OnceLock::new();
let agent = wide("VSRustium");
// SAFETY: a session without a proxy of its own; the handle lives for the process.
let session = *SESSION.get_or_init(|| unsafe { WinHttpOpen(agent.as_ptr(), WINHTTP_ACCESS_TYPE_NO_PROXY, std::ptr::null(), std::ptr::null(), 0) } as usize);
if session == 0 {
return None;
}
let pac_url = pac_url.map(wide);
let mut options = WINHTTP_AUTOPROXY_OPTIONS::default();
if auto_detect {
options.dwFlags |= WINHTTP_AUTOPROXY_AUTO_DETECT;
options.dwAutoDetectFlags = WINHTTP_AUTO_DETECT_TYPE_DHCP | WINHTTP_AUTO_DETECT_TYPE_DNS_A;
}
if let Some(pac_url) = &pac_url {
options.dwFlags |= WINHTTP_AUTOPROXY_CONFIG_URL;
options.lpszAutoConfigUrl = pac_url.as_ptr();
}
let url = wide(url);
let mut info = WINHTTP_PROXY_INFO::default();
// SAFETY: the strings outlive the call; WinHTTP allocates the info strings, freed by take_wide.
let mut found = unsafe { WinHttpGetProxyForUrl(session as *mut _, url.as_ptr(), &mut options, &mut info) } != 0;
// Chromium's proxy_resolver_winhttp.cc: the logon credentials go to the PAC server only after it asked for them.
// SAFETY: as above.
if !found && unsafe { GetLastError() } == ERROR_WINHTTP_LOGIN_FAILURE {
options.fAutoLogonIfChallenged = 1;
// SAFETY: as above.
found = unsafe { WinHttpGetProxyForUrl(session as *mut _, url.as_ptr(), &mut options, &mut info) } != 0;
}
if !found {
return None;
}
// SAFETY: as above.
let (list, _) = unsafe { (take_wide(info.lpszProxy), take_wide(info.lpszProxyBypass)) };
match info.dwAccessType {
WINHTTP_ACCESS_TYPE_NAMED_PROXY => Some(pac_for_list(list.as_deref().unwrap_or_default())),
_ => Some("DIRECT".to_owned()),
}
}
fn wide(text: &str) -> Vec<u16> {
text.encode_utf16().chain([0]).collect()
}
/// A NUL-terminated string WinHTTP allocated with GlobalAlloc, read and freed.
unsafe fn take_wide(text: PWSTR) -> Option<String> {
if text.is_null() {
return None;
}
// SAFETY: WinHTTP's strings end with NUL.
let value = unsafe {
let length = (0..).take_while(|&index| *text.add(index) != 0).count();
String::from_utf16_lossy(std::slice::from_raw_parts(text, length))
};
// SAFETY: allocated by WinHTTP with GlobalAlloc, freed once.
unsafe { GlobalFree(text.cast()) };
Some(value)
}
// shortcut: no SSPI binding, so proxies that need Kerberos fail; call InitializeSecurityContextW as macos.rs calls GSS.
pub(super) fn lookup_kerberos_authorization(_spn: &str) -> anyhow::Result<String> {
anyhow::bail!("Kerberos is not available on Windows")
}