Visual Studio Code, rebuilt in Rust
Rust
//! request.rs `send` over NSURLSession, which takes the system proxy settings as Electron's `net` module does,
//! until `set_session_proxy` replaces them.
use std::ffi::c_void;
use std::ptr::{null, null_mut};
use std::sync::mpsc;
use std::time::{Duration, Instant};
use anyhow::Context;
use block2::RcBlock;
use base64::Engine;
use objc2::rc::Retained;
use objc2_foundation::{
NSArray, NSData, NSDictionary, NSError, NSHTTPURLResponse, NSMutableURLRequest, NSNumber, NSObject, NSString, NSURL, NSURLResponse, NSURLSession, NSURLSessionConfiguration,
};
use super::{Request, Response, SessionProxy};
/// The CFNetwork proxy dictionary of Chromium's `proxyRules` (`[scheme://]host[:port]`, one proxy for every
/// request; empty means direct) and `proxyBypassRules` (hosts, `<local>` for names without a dot).
fn proxy_dictionary(proxy: &SessionProxy) -> Retained<NSDictionary> {
let number = |value: i64| NSNumber::numberWithLongLong(value).into_super().into_super();
let string = |value: &str| NSString::from_str(value).into_super();
let mut keys = Vec::new();
let mut values = Vec::new();
let (scheme, address) = proxy.rules.split_once("://").unwrap_or(("http", &proxy.rules));
let (host, port) = match address.rsplit_once(':') {
Some((host, port)) if port.parse::<u16>().is_ok() => (host, port.parse::<i64>().unwrap()),
_ => (address, match scheme { "https" => 443, "socks" | "socks4" | "socks5" => 1080, _ => 80 }),
};
let enabled = !host.is_empty();
match scheme {
"socks" | "socks4" | "socks5" => {
keys.extend(["SOCKSEnable", "SOCKSProxy", "SOCKSPort"]);
values.extend([number(enabled as i64), string(host), number(port)]);
}
_ => {
keys.extend(["HTTPEnable", "HTTPProxy", "HTTPPort", "HTTPSEnable", "HTTPSProxy", "HTTPSPort"]);
values.extend([number(enabled as i64), string(host), number(port), number(enabled as i64), string(host), number(port)]);
}
}
let bypass: Vec<&str> = proxy.bypass_rules.split(',').map(str::trim).filter(|rule| !rule.is_empty()).collect();
let exceptions: Vec<Retained<NSString>> = bypass.iter().filter(|rule| **rule != "<local>").map(|rule| NSString::from_str(rule)).collect();
keys.extend(["ExceptionsList", "ExcludeSimpleHostnames"]);
values.extend([NSArray::from_retained_slice(&exceptions).into_super(), number(bypass.contains(&"<local>") as i64)]);
let keys: Vec<Retained<NSString>> = keys.into_iter().map(NSString::from_str).collect();
let keys: Vec<&NSString> = keys.iter().map(|key| &**key).collect();
let dictionary = NSDictionary::<NSString, NSObject>::from_retained_objects(&keys, &values);
// SAFETY: only the key and value types are erased, as connectionProxyDictionary takes them.
unsafe { Retained::cast_unchecked(dictionary) }
}
#[link(name = "CFNetwork", kind = "framework")]
unsafe extern "C" {
static kCFProxyTypeKey: &'static NSString;
static kCFProxyHostNameKey: &'static NSString;
static kCFProxyPortNumberKey: &'static NSString;
static kCFProxyAutoConfigurationURLKey: &'static NSString;
static kCFProxyAutoConfigurationJavaScriptKey: &'static NSString;
static kCFProxyTypeNone: &'static NSString;
static kCFProxyTypeHTTP: &'static NSString;
static kCFProxyTypeHTTPS: &'static NSString;
static kCFProxyTypeSOCKS: &'static NSString;
static kCFProxyTypeAutoConfigurationURL: &'static NSString;
static kCFProxyTypeAutoConfigurationJavaScript: &'static NSString;
fn CFNetworkCopySystemProxySettings() -> *mut NSDictionary;
fn CFNetworkCopyProxiesForURL(url: &NSURL, proxy_settings: &NSDictionary) -> *mut NSArray;
fn CFNetworkExecuteProxyAutoConfigurationURL(script_url: &NSURL, target_url: &NSURL, callback: PacCallback, context: *mut StreamClientContext) -> *mut c_void;
fn CFNetworkExecuteProxyAutoConfigurationScript(script: &NSString, target_url: &NSURL, callback: PacCallback, context: *mut StreamClientContext) -> *mut c_void;
}
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
fn CFRunLoopGetCurrent() -> *mut c_void;
fn CFRunLoopAddSource(run_loop: *mut c_void, source: *mut c_void, mode: &NSString);
fn CFRunLoopRunInMode(mode: &NSString, seconds: f64, return_after_source_handled: u8) -> i32;
fn CFRunLoopSourceInvalidate(source: *mut c_void);
fn CFRelease(object: *mut c_void);
}
type PacCallback = extern "C" fn(client: *mut c_void, proxies: *mut NSArray, error: *mut c_void);
#[repr(C)]
struct StreamClientContext {
version: isize,
info: *mut c_void,
retain: *const c_void,
release: *const c_void,
copy_description: *const c_void,
}
/// `session.resolveProxy`: the session proxy, else the system settings, with their PAC script run for `url`.
pub(super) fn resolve_proxy_with(url: &str, proxy: Option<&SessionProxy>) -> Option<String> {
let settings = match proxy {
Some(proxy) => proxy_dictionary(proxy),
// SAFETY: a Copy function hands over its reference.
None => unsafe { Retained::from_raw(CFNetworkCopySystemProxySettings())? },
};
proxies_for_url(url, &settings)
}
/// `ProxyList::ToPacString`: `PROXY host:port`, `SOCKS5 host:port` or `DIRECT`, joined by `;`.
fn proxies_for_url(url: &str, settings: &NSDictionary) -> Option<String> {
let target = NSURL::URLWithString(&NSString::from_str(url))?;
// SAFETY: a Copy function hands over its reference.
let proxies = unsafe { Retained::from_raw(CFNetworkCopyProxiesForURL(&target, settings))? };
let mut elements = Vec::new();
pac_elements(&proxies, &target, &mut elements);
if elements.is_empty() {
elements.push("DIRECT".to_owned());
}
Some(elements.join(";"))
}
/// CFNetwork lists a PAC script with a direct fallback after it; Chromium takes the script's answer alone and goes
/// direct only when the script fails.
fn pac_elements(proxies: &NSArray, target: &NSURL, elements: &mut Vec<String>) {
for index in 0..proxies.count() {
let Ok(entry) = proxies.objectAtIndex(index).downcast::<NSDictionary>() else { continue };
// SAFETY: the CFNetwork key and type constants are immutable CFStrings.
let (kind, host, port) = unsafe { (entry.objectForKey(kCFProxyTypeKey), entry.objectForKey(kCFProxyHostNameKey), entry.objectForKey(kCFProxyPortNumberKey)) };
let Some(kind) = kind.and_then(|kind| kind.downcast::<NSString>().ok()) else { continue };
let address = || Some(format!("{}:{}", host.clone()?.downcast::<NSString>().ok()?, port.clone()?.downcast::<NSNumber>().ok()?.longLongValue()));
// SAFETY: as above.
unsafe {
if kind.isEqualToString(kCFProxyTypeNone) {
elements.push("DIRECT".to_owned());
} else if kind.isEqualToString(kCFProxyTypeHTTP) || kind.isEqualToString(kCFProxyTypeHTTPS) {
elements.extend(address().map(|address| format!("PROXY {address}")));
} else if kind.isEqualToString(kCFProxyTypeSOCKS) {
elements.extend(address().map(|address| format!("SOCKS5 {address}")));
} else if kind.isEqualToString(kCFProxyTypeAutoConfigurationURL) {
let Some(script_url) = entry.objectForKey(kCFProxyAutoConfigurationURLKey).and_then(|url| url.downcast::<NSURL>().ok()) else { continue };
if let Some(results) = run_pac(|callback, context| CFNetworkExecuteProxyAutoConfigurationURL(&script_url, target, callback, context)) {
return pac_elements(&results, target, elements);
}
} else if kind.isEqualToString(kCFProxyTypeAutoConfigurationJavaScript) {
let Some(script) = entry.objectForKey(kCFProxyAutoConfigurationJavaScriptKey).and_then(|script| script.downcast::<NSString>().ok()) else { continue };
if let Some(results) = run_pac(|callback, context| CFNetworkExecuteProxyAutoConfigurationScript(&script, target, callback, context)) {
return pac_elements(&results, target, elements);
}
}
}
}
}
/// Runs a CFNetwork PAC source on this thread's run loop in a private mode until it answers, at most 30 s; a
/// script that fails to load or run answers None.
fn run_pac(execute: impl FnOnce(PacCallback, *mut StreamClientContext) -> *mut c_void) -> Option<Retained<NSArray>> {
extern "C" fn answered(client: *mut c_void, proxies: *mut NSArray, _error: *mut c_void) {
// SAFETY: `client` is run_pac's result slot, alive while run_pac runs its run loop.
unsafe { *(client as *mut Option<Option<Retained<NSArray>>>) = Some(Retained::retain(proxies)) };
}
let mut result: Option<Option<Retained<NSArray>>> = None;
let mut context = StreamClientContext { version: 0, info: (&raw mut result).cast(), retain: null(), release: null(), copy_description: null() };
let source = execute(answered, &mut context);
if source.is_null() {
return None;
}
let mode = NSString::from_str("com.vsrustium.ProxyResolver");
let deadline = Instant::now() + Duration::from_secs(30);
// SAFETY: the source is a retained CFRunLoopSource, released once its run loop no longer runs it.
unsafe {
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, &mode);
while result.is_none() && Instant::now() < deadline {
const FINISHED: i32 = 1;
if CFRunLoopRunInMode(&mode, deadline.saturating_duration_since(Instant::now()).as_secs_f64(), 1) == FINISHED {
break;
}
}
CFRunLoopSourceInvalidate(source);
CFRelease(source);
}
result.flatten()
}
#[repr(C)]
struct GssBuffer {
length: usize,
value: *mut c_void,
}
#[link(name = "GSS", kind = "framework")]
unsafe extern "C" {
/// `GSS_C_NT_HOSTBASED_SERVICE`; only its address is used.
static __gss_c_nt_hostbased_service_oid_desc: u8;
fn gss_import_name(minor: *mut u32, name: *const GssBuffer, name_type: *const u8, output: *mut *mut c_void) -> u32;
fn gss_init_sec_context(
minor: *mut u32,
credential: *const c_void,
context: *mut *mut c_void,
target: *mut c_void,
mech: *const c_void,
flags: u32,
time: u32,
bindings: *const c_void,
input: *const GssBuffer,
actual_mech: *mut c_void,
output: *mut GssBuffer,
returned_flags: *mut u32,
time_received: *mut u32,
) -> u32;
fn gss_release_buffer(minor: *mut u32, buffer: *mut GssBuffer) -> u32;
fn gss_release_name(minor: *mut u32, name: *mut *mut c_void) -> u32;
fn gss_delete_sec_context(minor: *mut u32, context: *mut *mut c_void, output: *mut GssBuffer) -> u32;
}
/// kerberos's `initializeClient(spn)` then `step('')`: the first token of a context for `spn` with the default
/// credential and mechanism and `GSS_C_MUTUAL_FLAG | GSS_C_SEQUENCE_FLAG`, base64 encoded.
pub(super) fn lookup_kerberos_authorization(spn: &str) -> anyhow::Result<String> {
const GSS_S_COMPLETE: u32 = 0;
const GSS_S_CONTINUE_NEEDED: u32 = 1;
const FLAGS: u32 = 2 | 8;
let mut minor = 0;
let spn_buffer = GssBuffer { length: spn.len(), value: spn.as_ptr() as *mut c_void };
let mut name = null_mut();
// SAFETY: GSS copies the name buffer, which outlives the call.
let status = unsafe { gss_import_name(&mut minor, &spn_buffer, &raw const __gss_c_nt_hostbased_service_oid_desc, &mut name) };
if status != GSS_S_COMPLETE {
anyhow::bail!("gss_import_name: major {status:#x}, minor {minor}");
}
let (mut context, input) = (null_mut(), GssBuffer { length: 0, value: null_mut() });
let mut output = GssBuffer { length: 0, value: null_mut() };
// SAFETY: every pointer is valid or null where GSS takes null; the name, context and token are released below.
unsafe {
let status = gss_init_sec_context(&mut minor, null(), &mut context, name, null(), FLAGS, 0, null(), &input, null_mut(), &mut output, null_mut(), null_mut());
let token = match status {
GSS_S_COMPLETE | GSS_S_CONTINUE_NEEDED if output.length > 0 => Ok(base64::engine::general_purpose::STANDARD.encode(std::slice::from_raw_parts(output.value as *const u8, output.length))),
_ => Err(anyhow::anyhow!("gss_init_sec_context: major {status:#x}, minor {minor}")),
};
gss_release_buffer(&mut minor, &mut output);
gss_delete_sec_context(&mut minor, &mut context, null_mut());
gss_release_name(&mut minor, &mut name);
token
}
}
pub(super) fn send(options: &Request, proxy: Option<&SessionProxy>, proxy_authorization: Option<&str>) -> anyhow::Result<Response> {
let url = NSURL::URLWithString(&NSString::from_str(options.url)).with_context(|| format!("invalid URL {}", options.url))?;
let request = NSMutableURLRequest::requestWithURL(&url);
request.setHTTPMethod(&NSString::from_str(options.method));
request.setTimeoutInterval(options.timeout.as_secs_f64());
for (name, value) in options.headers {
request.setValue_forHTTPHeaderField(Some(&NSString::from_str(value)), &NSString::from_str(name));
}
if let Some(authorization) = proxy_authorization {
request.setValue_forHTTPHeaderField(Some(&NSString::from_str(authorization)), &NSString::from_str("Proxy-Authorization"));
}
if let Some(body) = options.body {
request.setHTTPBody(Some(&NSData::with_bytes(body)));
}
let (sender, receiver) = mpsc::sync_channel(1);
let completion = RcBlock::new(move |data: *mut NSData, response: *mut NSURLResponse, error: *mut NSError| {
// SAFETY: NSURLSession passes valid objects or null.
let result = unsafe {
match (response.as_ref(), error.as_ref()) {
(_, Some(error)) => Err(error.localizedDescription().to_string()),
(Some(response), None) => {
let status = response.downcast_ref::<NSHTTPURLResponse>().map_or(200, |response| response.statusCode() as u16);
Ok(Response { status, body: data.as_ref().map(|data| data.to_vec()).unwrap_or_default() })
}
(None, None) => Err("no response".to_owned()),
}
};
let _ = sender.send(result);
});
let session = match proxy {
Some(proxy) => {
let configuration = NSURLSessionConfiguration::defaultSessionConfiguration();
// SAFETY: the dictionary holds the CFNetwork proxy keys with string, number and string array values.
unsafe { configuration.setConnectionProxyDictionary(Some(&proxy_dictionary(proxy))) };
NSURLSession::sessionWithConfiguration(&configuration)
}
None => NSURLSession::sharedSession(),
};
// SAFETY: the completion block only moves owned data into a channel, so it may run on the session's queue.
let task = unsafe { session.dataTaskWithRequest_completionHandler(&request, &completion) };
task.resume();
if proxy.is_some() {
session.finishTasksAndInvalidate();
}
let result = receiver.recv().context("the request was dropped")?;
result.map_err(|error| anyhow::anyhow!(error))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn session_proxies_resolve_as_pac_results() {
let proxy = |rules: &str| SessionProxy { rules: rules.into(), bypass_rules: "*.corp.test,<local>".into() };
let http = proxy("http://proxy.test:3128");
assert_eq!(resolve_proxy_with("https://example.com/", Some(&http)).as_deref(), Some("PROXY proxy.test:3128"));
assert_eq!(resolve_proxy_with("https://example.com/", Some(&proxy("socks5://socks.test"))).as_deref(), Some("SOCKS5 socks.test:1080"));
assert_eq!(resolve_proxy_with("https://intranet/", Some(&http)).as_deref(), Some("DIRECT"));
assert_eq!(resolve_proxy_with("https://build.corp.test/", Some(&http)).as_deref(), Some("DIRECT"));
}
#[test]
fn pac_scripts_run_for_the_url() {
let script = "function FindProxyForURL(url, host) { return host == 'example.com' ? 'PROXY pac.test:8080; DIRECT' : 'DIRECT'; }";
let keys = [NSString::from_str("ProxyAutoConfigEnable"), NSString::from_str("ProxyAutoConfigJavaScript")];
let values = [NSNumber::numberWithLongLong(1).into_super().into_super(), NSString::from_str(script).into_super()];
let settings = NSDictionary::<NSString, NSObject>::from_retained_objects(&[&*keys[0], &*keys[1]], &values);
// SAFETY: only the key and value types are erased.
let settings: Retained<NSDictionary> = unsafe { Retained::cast_unchecked(settings) };
assert_eq!(proxies_for_url("https://example.com/", &settings).as_deref(), Some("PROXY pac.test:8080;DIRECT"));
assert_eq!(proxies_for_url("https://other.test/", &settings).as_deref(), Some("DIRECT"));
}
#[test]
fn kerberos_fails_for_a_service_no_realm_knows() {
let error = lookup_kerberos_authorization("[email protected]").unwrap_err().to_string();
assert!(error.starts_with("gss_init_sec_context: major"), "{error}");
}
}