Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

21.9 KB
Raw Blame
//! Proxy resolution like Chromium on macOS: the system settings (System Settings › Network ›
//! Proxies, including PAC files and the bypass list) through CFNetwork, falling back to the
//! `HTTPS_PROXY` / `HTTP_PROXY` / `ALL_PROXY` environment variables when the system has none.
//! Loopback never goes through a proxy (checked by the caller).

use std::collections::HashMap;
use std::sync::Mutex;
use std::time::{Duration, Instant};

use crate::conn::Endpoint;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Proxy {
    Direct,
    Http(String, u16),
    Socks(String, u16),
}

/// Decisions are cached per scheme+host+port (PAC scripts can be slow) until the network changes.
static CACHE: Mutex<Option<HashMap<String, (Instant, Vec<Proxy>)>>> = Mutex::new(None);
const CACHE_TTL: Duration = Duration::from_secs(300);

/// Forget cached decisions (network or proxy settings changed).
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub fn invalidate() {
    *CACHE.lock().unwrap() = None;
}

pub fn for_endpoint(ep: &Endpoint) -> Vec<Proxy> {
    let scheme = if ep.tls { "https" } else { "http" };
    let url = format!("{scheme}://{}/", ep.authority(false));
    if let Some((at, v)) = CACHE.lock().unwrap().as_ref().and_then(|c| c.get(&url)) {
        if at.elapsed() < CACHE_TTL {
            return v.clone();
        }
    }
    // Like Chromium, a direct connection is only tried when the configuration lists it (the system
    // resolver says so explicitly; PAC files say `DIRECT`); an empty answer means direct.
    let mut v = system::proxies_for(&url).unwrap_or_default();
    if v.iter().all(|p| *p == Proxy::Direct) {
        v = from_env(ep).into_iter().collect();
    }
    if v.is_empty() {
        v.push(Proxy::Direct);
    }
    v.dedup();
    CACHE.lock().unwrap().get_or_insert_with(HashMap::new).insert(url, (Instant::now(), v.clone()));
    v
}

fn from_env(ep: &Endpoint) -> Option<Proxy> {
    let get = |names: &[&str]| names.iter().find_map(|n| std::env::var(n).ok().filter(|v| !v.trim().is_empty()));
    let raw = if ep.tls { get(&["HTTPS_PROXY", "https_proxy"]) } else { get(&["HTTP_PROXY", "http_proxy"]) }
        .or_else(|| get(&["ALL_PROXY", "all_proxy"]))?;
    if let Some(no) = get(&["NO_PROXY", "no_proxy"]) {
        let host = ep.host.to_ascii_lowercase();
        for pat in no.split(',').map(|s| s.trim().to_ascii_lowercase()).filter(|s| !s.is_empty()) {
            if pat == "*" {
                return None;
            }
            let pat = pat.split(':').next().unwrap_or("").trim_start_matches("*.").trim_start_matches('.').to_string();
            if host == pat || host.ends_with(&format!(".{pat}")) {
                return None;
            }
        }
    }
    parse_proxy_url(&raw)
}

fn parse_proxy_url(raw: &str) -> Option<Proxy> {
    let raw = raw.trim();
    let (scheme, rest) = raw.split_once("://").unwrap_or(("http", raw));
    let hostport = rest.split('/').next()?.rsplit('@').next()?;
    let (host, port) = if let Some(h) = hostport.strip_prefix('[') {
        let (h, p) = h.split_once(']')?;
        (h.to_string(), p.strip_prefix(':').and_then(|p| p.parse().ok()))
    } else {
        match hostport.rsplit_once(':') {
            Some((h, p)) => (h.to_string(), p.parse().ok()),
            None => (hostport.to_string(), None),
        }
    };
    if host.is_empty() {
        return None;
    }
    match scheme.to_ascii_lowercase().as_str() {
        "socks5" | "socks5h" | "socks" => Some(Proxy::Socks(host, port.unwrap_or(1080))),
        "http" | "https" => Some(Proxy::Http(host, port.unwrap_or(80))),
        _ => None,
    }
}

#[cfg(target_os = "macos")]
mod system {
    use std::ffi::c_void;
    use super::*;

    type CFTypeRef = *const c_void;
    type CFStringRef = *const c_void;
    type CFDictionaryRef = *const c_void;
    type CFArrayRef = *const c_void;
    type CFURLRef = *const c_void;
    type CFNumberRef = *const c_void;
    type CFErrorRef = *const c_void;
    type CFRunLoopRef = *const c_void;
    type CFRunLoopSourceRef = *const c_void;
    const UTF8: u32 = 0x0800_0100;

    #[repr(C)]
    struct CFStreamClientContext {
        version: isize,
        info: *mut c_void,
        retain: *const c_void,
        release: *const c_void,
        copy_description: *const c_void,
    }

    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern "C" {
        static kCFRunLoopDefaultMode: CFStringRef;
        fn CFRelease(cf: CFTypeRef);
        fn CFEqual(a: CFTypeRef, b: CFTypeRef) -> u8;
        fn CFGetTypeID(cf: CFTypeRef) -> usize;
        fn CFStringGetTypeID() -> usize;
        fn CFNumberGetTypeID() -> usize;
        fn CFStringGetCString(s: CFStringRef, buf: *mut u8, size: isize, enc: u32) -> u8;
        fn CFURLCreateWithBytes(alloc: CFTypeRef, bytes: *const u8, len: isize, enc: u32, base: CFURLRef) -> CFURLRef;
        fn CFDictionaryGetValue(d: CFDictionaryRef, key: CFTypeRef) -> CFTypeRef;
        fn CFArrayGetCount(a: CFArrayRef) -> isize;
        fn CFArrayGetValueAtIndex(a: CFArrayRef, i: isize) -> CFTypeRef;
        fn CFNumberGetValue(n: CFNumberRef, ty: isize, out: *mut c_void) -> u8;
        fn CFRunLoopGetCurrent() -> CFRunLoopRef;
        fn CFRunLoopAddSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);
        fn CFRunLoopRemoveSource(rl: CFRunLoopRef, src: CFRunLoopSourceRef, mode: CFStringRef);
        fn CFRunLoopRunInMode(mode: CFStringRef, seconds: f64, return_after_source_handled: u8) -> i32;
        fn CFRunLoopSourceInvalidate(src: CFRunLoopSourceRef);
    }

    #[link(name = "CFNetwork", kind = "framework")]
    unsafe extern "C" {
        static kCFProxyTypeKey: CFStringRef;
        static kCFProxyHostNameKey: CFStringRef;
        static kCFProxyPortNumberKey: CFStringRef;
        static kCFProxyAutoConfigurationURLKey: CFStringRef;
        static kCFProxyTypeNone: CFStringRef;
        static kCFProxyTypeHTTP: CFStringRef;
        static kCFProxyTypeHTTPS: CFStringRef;
        static kCFProxyTypeSOCKS: CFStringRef;
        static kCFProxyTypeAutoConfigurationURL: CFStringRef;
        fn CFNetworkCopySystemProxySettings() -> CFDictionaryRef;
        fn CFNetworkCopyProxiesForURL(url: CFURLRef, settings: CFDictionaryRef) -> CFArrayRef;
        fn CFNetworkExecuteProxyAutoConfigurationURL(
            pac: CFURLRef,
            target: CFURLRef,
            cb: unsafe extern "C" fn(*mut c_void, CFArrayRef, CFErrorRef),
            ctx: *mut CFStreamClientContext,
        ) -> CFRunLoopSourceRef;
    }

    struct Owned(CFTypeRef);
    impl Drop for Owned {
        fn drop(&mut self) {
            if !self.0.is_null() {
                unsafe { CFRelease(self.0) }
            }
        }
    }

    fn cf_url(s: &str) -> Owned {
        Owned(unsafe { CFURLCreateWithBytes(std::ptr::null(), s.as_ptr(), s.len() as isize, UTF8, std::ptr::null()) })
    }

    fn cf_string(v: CFTypeRef) -> Option<String> {
        if v.is_null() || unsafe { CFGetTypeID(v) != CFStringGetTypeID() } {
            return None;
        }
        let mut buf = vec![0u8; 1024];
        if unsafe { CFStringGetCString(v, buf.as_mut_ptr(), buf.len() as isize, UTF8) } == 0 {
            return None;
        }
        let n = buf.iter().position(|&b| b == 0).unwrap_or(0);
        buf.truncate(n);
        String::from_utf8(buf).ok()
    }

    fn cf_i32(v: CFTypeRef) -> Option<i32> {
        if v.is_null() || unsafe { CFGetTypeID(v) != CFNumberGetTypeID() } {
            return None;
        }
        let mut out: i32 = 0;
        // kCFNumberSInt32Type = 3
        (unsafe { CFNumberGetValue(v, 3, (&mut out as *mut i32).cast()) } != 0).then_some(out)
    }

    fn eq(a: CFTypeRef, b: CFTypeRef) -> bool {
        !a.is_null() && !b.is_null() && unsafe { CFEqual(a, b) } != 0
    }

    /// Translate a CFNetwork proxy list; PAC entries are evaluated (`depth` guards recursion).
    unsafe fn parse_list(list: CFArrayRef, target: &str, depth: u32) -> Vec<Proxy> {
        let mut out = Vec::new();
        if list.is_null() {
            return out;
        }
        unsafe {
            for i in 0..CFArrayGetCount(list) {
                let d = CFArrayGetValueAtIndex(list, i);
                let ty = CFDictionaryGetValue(d, kCFProxyTypeKey);
                let host = cf_string(CFDictionaryGetValue(d, kCFProxyHostNameKey));
                let port = cf_i32(CFDictionaryGetValue(d, kCFProxyPortNumberKey)).filter(|p| *p > 0 && *p < 65536);
                if eq(ty, kCFProxyTypeNone) {
                    out.push(Proxy::Direct);
                } else if eq(ty, kCFProxyTypeHTTP) || eq(ty, kCFProxyTypeHTTPS) {
                    if let Some(h) = host {
                        out.push(Proxy::Http(h, port.unwrap_or(80) as u16));
                    }
                } else if eq(ty, kCFProxyTypeSOCKS) {
                    if let Some(h) = host {
                        out.push(Proxy::Socks(h, port.unwrap_or(1080) as u16));
                    }
                } else if eq(ty, kCFProxyTypeAutoConfigurationURL) && depth == 0 {
                    let pac = CFDictionaryGetValue(d, kCFProxyAutoConfigurationURLKey);
                    let answer = run_pac(pac, target);
                    if !answer.is_empty() {
                        // The script decided. CFNetwork lists a direct fallback after the PAC entry for
                        // when the script cannot be loaded; Chromium only goes direct if the script
                        // says DIRECT.
                        return answer;
                    }
                }
            }
        }
        out
    }

    struct PacResult {
        done: bool,
        proxies: Vec<Proxy>,
        target: String,
    }

    unsafe extern "C" fn pac_done(info: *mut c_void, list: CFArrayRef, err: CFErrorRef) {
        let r = unsafe { &mut *(info as *mut PacResult) };
        if err.is_null() {
            r.proxies = unsafe { parse_list(list, &r.target, 1) };
        }
        r.done = true;
    }

    /// Evaluate a PAC file for `target` on this (worker) thread's run loop.
    unsafe fn run_pac(pac_url: CFURLRef, target: &str) -> Vec<Proxy> {
        if pac_url.is_null() {
            return Vec::new();
        }
        let t = cf_url(target);
        let mut result = PacResult { done: false, proxies: Vec::new(), target: target.to_string() };
        let mut ctx = CFStreamClientContext {
            version: 0,
            info: (&mut result as *mut PacResult).cast(),
            retain: std::ptr::null(),
            release: std::ptr::null(),
            copy_description: std::ptr::null(),
        };
        unsafe {
            let src = CFNetworkExecuteProxyAutoConfigurationURL(pac_url, t.0, pac_done, &mut ctx);
            if src.is_null() {
                return Vec::new();
            }
            let src = Owned(src);
            let rl = CFRunLoopGetCurrent();
            CFRunLoopAddSource(rl, src.0, kCFRunLoopDefaultMode);
            let deadline = Instant::now() + Duration::from_secs(10);
            while !result.done && Instant::now() < deadline {
                CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0, 1);
            }
            CFRunLoopRemoveSource(rl, src.0, kCFRunLoopDefaultMode);
            CFRunLoopSourceInvalidate(src.0);
        }
        result.proxies
    }

    pub fn proxies_for(url: &str) -> Option<Vec<Proxy>> {
        let settings = Owned(unsafe { CFNetworkCopySystemProxySettings() });
        if settings.0.is_null() {
            return None;
        }
        unsafe { proxies_with(settings.0, url) }
    }

    /// Proxies for `url` under a proxy-settings dictionary (the system's, or a test's).
    pub unsafe fn proxies_with(settings: CFDictionaryRef, url: &str) -> Option<Vec<Proxy>> {
        let u = cf_url(url);
        if u.0.is_null() {
            return None;
        }
        unsafe {
            let list = Owned(CFNetworkCopyProxiesForURL(u.0, settings));
            Some(parse_list(list.0, url, 0))
        }
    }

    #[cfg(test)]
    pub mod testing {
        use super::*;
        #[link(name = "CoreFoundation", kind = "framework")]
        unsafe extern "C" {
            static kCFTypeDictionaryKeyCallBacks: c_void;
            static kCFTypeDictionaryValueCallBacks: c_void;
            static kCFTypeArrayCallBacks: c_void;
            fn CFDictionaryCreate(a: CFTypeRef, k: *const CFTypeRef, v: *const CFTypeRef, n: isize, kc: *const c_void, vc: *const c_void) -> CFDictionaryRef;
            fn CFArrayCreate(a: CFTypeRef, v: *const CFTypeRef, n: isize, cb: *const c_void) -> CFArrayRef;
            fn CFStringCreateWithBytes(a: CFTypeRef, b: *const u8, n: isize, enc: u32, ext: u8) -> CFStringRef;
            fn CFNumberCreate(a: CFTypeRef, ty: isize, v: *const c_void) -> CFNumberRef;
        }
        pub enum V<'a> {
            S(&'a str),
            N(i32),
            A(&'a [&'a str]),
        }
        fn s(x: &str) -> CFTypeRef {
            unsafe { CFStringCreateWithBytes(std::ptr::null(), x.as_ptr(), x.len() as isize, UTF8, 0) }
        }
        /// Resolve `url` under settings given as SCDynamicStore keys (leaks a little; tests only).
        pub fn resolve(entries: &[(&str, V)], url: &str) -> Vec<Proxy> {
            unsafe {
                let keys: Vec<CFTypeRef> = entries.iter().map(|(k, _)| s(k)).collect();
                let vals: Vec<CFTypeRef> = entries
                    .iter()
                    .map(|(_, v)| match v {
                        V::S(x) => s(x),
                        V::N(n) => CFNumberCreate(std::ptr::null(), 3, (n as *const i32).cast()),
                        V::A(xs) => {
                            let items: Vec<CFTypeRef> = xs.iter().map(|x| s(x)).collect();
                            CFArrayCreate(std::ptr::null(), items.as_ptr(), items.len() as isize, &kCFTypeArrayCallBacks)
                        }
                    })
                    .collect();
                let d = CFDictionaryCreate(std::ptr::null(), keys.as_ptr(), vals.as_ptr(), keys.len() as isize, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);
                proxies_with(d, url).unwrap_or_default()
            }
        }
    }
}

#[cfg(target_os = "linux")]
mod system {
    use std::process::Command;

    use super::*;

    fn gsettings(schema: &str, key: &str) -> Option<String> {
        let out = Command::new("gsettings").args(["get", schema, key]).output().ok()?;
        if !out.status.success() {
            return None;
        }
        String::from_utf8(out.stdout).ok().map(|s| s.trim().to_string())
    }

    pub(super) fn parse_gsettings_str(raw: &str) -> String {
        let s = raw.trim();
        s.strip_prefix('\'')
            .and_then(|s| s.strip_suffix('\''))
            .or_else(|| s.strip_prefix('"').and_then(|s| s.strip_suffix('"')))
            .unwrap_or(s)
            .to_string()
    }

    pub(super) fn parse_gsettings_list(raw: &str) -> Vec<String> {
        let s = raw.trim();
        let inner = s.strip_prefix('[').and_then(|s| s.strip_suffix(']')).unwrap_or(s);
        inner
            .split(',')
            .map(|item| parse_gsettings_str(item).to_ascii_lowercase())
            .filter(|item| !item.is_empty())
            .collect()
    }

    fn url_host_and_tls(url: &str) -> Option<(String, bool)> {
        let (scheme, rest) = url.split_once("://")?;
        let tls = scheme.eq_ignore_ascii_case("https");
        let authority = rest.split('/').next()?;
        let hostport = authority.rsplit('@').next()?;
        let host = if let Some(h) = hostport.strip_prefix('[') {
            h.split_once(']')?.0
        } else {
            hostport.split(':').next().unwrap_or(hostport)
        };
        if host.is_empty() {
            None
        } else {
            Some((host.to_ascii_lowercase(), tls))
        }
    }

    pub(super) fn host_ignored(host: &str, patterns: &[String]) -> bool {
        let host = host.to_ascii_lowercase();
        for pat in patterns {
            if pat == "*" {
                return true;
            }
            if let Some(prefix) = pat.strip_suffix("/8") {
                if let Some((a, _)) = prefix.split_once('.') {
                    if host.starts_with(&format!("{a}.")) {
                        return true;
                    }
                }
            }
            let clean = pat.split(':').next().unwrap_or("").trim_start_matches("*.").trim_start_matches('.');
            if !clean.is_empty() && (host == clean || host.ends_with(&format!(".{clean}"))) {
                return true;
            }
        }
        false
    }

    fn manual_entry(schema: &str) -> Option<(String, u16)> {
        let host = parse_gsettings_str(&gsettings(schema, "host")?);
        let port: u16 = gsettings(schema, "port")?.parse().ok()?;
        if host.is_empty() || port == 0 {
            None
        } else {
            Some((host, port))
        }
    }

    /// Resolve system proxy via GNOME/freedesktop `gsettings` (`org.gnome.system.proxy`),
    /// which Clash Verge, Mihomo Party, FlClash, and GNOME Settings write on Linux desktops.
    pub fn proxies_for(url: &str) -> Option<Vec<Proxy>> {
        let mode = parse_gsettings_str(&gsettings("org.gnome.system.proxy", "mode")?);
        if mode != "manual" {
            return None;
        }
        let (host, tls) = url_host_and_tls(url)?;
        if let Some(raw_ignore) = gsettings("org.gnome.system.proxy", "ignore-hosts") {
            let ignored = parse_gsettings_list(&raw_ignore);
            if host_ignored(&host, &ignored) {
                return Some(vec![Proxy::Direct]);
            }
        }
        let mut out = Vec::new();
        if tls {
            if let Some((h, p)) = manual_entry("org.gnome.system.proxy.https").or_else(|| manual_entry("org.gnome.system.proxy.http")) {
                out.push(Proxy::Http(h, p));
            }
        } else if let Some((h, p)) = manual_entry("org.gnome.system.proxy.http") {
            out.push(Proxy::Http(h, p));
        }
        if let Some((h, p)) = manual_entry("org.gnome.system.proxy.socks") {
            out.push(Proxy::Socks(h, p));
        }
        if out.is_empty() { None } else { Some(out) }
    }
}

#[cfg(not(any(target_os = "macos", target_os = "linux")))]
mod system {
    use super::*;
    pub fn proxies_for(_url: &str) -> Option<Vec<Proxy>> {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn env_urls() {
        assert_eq!(parse_proxy_url("http://proxy.local:3128"), Some(Proxy::Http("proxy.local".into(), 3128)));
        assert_eq!(parse_proxy_url("socks5://127.0.0.1:1080/"), Some(Proxy::Socks("127.0.0.1".into(), 1080)));
        assert_eq!(parse_proxy_url("user:[email protected]:8080"), Some(Proxy::Http("10.0.0.1".into(), 8080)));
        assert_eq!(parse_proxy_url("http://[::1]:8080"), Some(Proxy::Http("::1".into(), 8080)));
    }
    #[test]
    fn system_lookup_does_not_crash() {
        let _ = system::proxies_for("https://example.com/");
    }
    #[cfg(target_os = "linux")]
    #[test]
    fn linux_gsettings_parsing_and_ignore_hosts() {
        assert_eq!(system::parse_gsettings_str("'manual'"), "manual");
        assert_eq!(system::parse_gsettings_str("'127.0.0.1'"), "127.0.0.1");
        let list = system::parse_gsettings_list("['localhost', '127.0.0.0/8', '*.local', '::1']");
        assert!(system::host_ignored("localhost", &list));
        assert!(system::host_ignored("127.0.0.1", &list));
        assert!(system::host_ignored("box.local", &list));
        assert!(!system::host_ignored("pocket-agents-island.doodlewind.workers.dev", &list));
    }
    #[cfg(target_os = "macos")]
    #[test]
    fn manual_and_pac_settings() {
        use system::testing::{V, resolve};
        let manual = [
            ("HTTPSEnable", V::N(1)),
            ("HTTPSProxy", V::S("10.1.2.3")),
            ("HTTPSPort", V::N(3128)),
            ("HTTPEnable", V::N(1)),
            ("HTTPProxy", V::S("10.4.5.6")),
            ("HTTPPort", V::N(8080)),
            ("ExceptionsList", V::A(&["*.internal", "192.168.0.0/16"])),
        ];
        assert_eq!(resolve(&manual, "https://example.com/"), vec![Proxy::Http("10.1.2.3".into(), 3128)]);
        assert_eq!(resolve(&manual, "http://example.com/"), vec![Proxy::Http("10.4.5.6".into(), 8080)]);
        assert_eq!(resolve(&manual, "https://db.internal/"), vec![Proxy::Direct]);
        let socks = [("SOCKSEnable", V::N(1)), ("SOCKSProxy", V::S("10.7.7.7")), ("SOCKSPort", V::N(1080))];
        assert_eq!(resolve(&socks, "https://example.com/"), vec![Proxy::Socks("10.7.7.7".into(), 1080)]);
        // PAC: fetched and evaluated by CFNetwork on this thread's run loop (served over HTTP; CFNetwork
        // ignores file: PAC URLs).
        let script = r#"function FindProxyForURL(url, host) {
                if (host == "example.com") return "PROXY 10.9.8.7:3128; DIRECT";
                if (dnsDomainIs(host, ".socks.test")) return "SOCKS 10.1.1.1:1080";
                return "DIRECT";
            }"#;
        let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
        let port = listener.local_addr().unwrap().port();
        std::thread::spawn(move || {
            use std::io::{Read, Write};
            for mut s in listener.incoming().flatten() {
                let mut buf = [0u8; 4096];
                let _ = s.read(&mut buf);
                let _ = write!(s, "HTTP/1.1 200 OK\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{script}", script.len());
            }
        });
        let url = format!("http://127.0.0.1:{port}/proxy.pac");
        let auto = [("ProxyAutoConfigEnable", V::N(1)), ("ProxyAutoConfigURLString", V::S(&url))];
        assert_eq!(resolve(&auto, "https://example.com/"), vec![Proxy::Http("10.9.8.7".into(), 3128), Proxy::Direct]);
        assert_eq!(resolve(&auto, "https://a.socks.test/"), vec![Proxy::Socks("10.1.1.1".into(), 1080)]);
        // An unreachable PAC file falls back to CFNetwork's direct entry.
        let dead = [("ProxyAutoConfigEnable", V::N(1)), ("ProxyAutoConfigURLString", V::S("http://127.0.0.1:1/none.pac"))];
        assert_eq!(resolve(&dead, "https://example.com/"), vec![Proxy::Direct]);
        assert_eq!(resolve(&auto, "https://other.org/"), vec![Proxy::Direct]);
    }
}