proxyparser 0.2.0

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

#[cfg(target_os = "macos")]
use crate::proxy::{normalize_proxy_url, ProxyScheme};
#[cfg(target_os = "macos")]
use crate::system_proxy::SystemProxyConfig;
#[cfg(target_os = "macos")]
use crate::{log_info, log_warn};
#[cfg(target_os = "macos")]
use core_foundation::base::{CFRelease, TCFType};
#[cfg(target_os = "macos")]
use core_foundation::dictionary::{CFDictionaryGetValue, CFDictionaryRef};
#[cfg(target_os = "macos")]
use core_foundation::number::{kCFNumberSInt32Type, CFNumberGetValue, CFNumberRef};
#[cfg(target_os = "macos")]
use core_foundation::string::{CFString, CFStringRef};
#[cfg(target_os = "macos")]
use scopeguard::defer;
#[cfg(target_os = "macos")]
use std::ptr;
#[cfg(target_os = "macos")]
use system_configuration_sys::dynamic_store_copy_specific::SCDynamicStoreCopyProxies;
#[cfg(target_os = "macos")]
use url::Url;

#[cfg(target_os = "macos")]
const PROXY_AUTO_CONFIG_ENABLE: &str = "ProxyAutoConfigEnable";
#[cfg(target_os = "macos")]
const PROXY_AUTO_CONFIG_URL: &str = "ProxyAutoConfigURLString";
#[cfg(target_os = "macos")]
const HTTPS_ENABLE: &str = "HTTPSEnable";
#[cfg(target_os = "macos")]
const HTTPS_PROXY: &str = "HTTPSProxy";
#[cfg(target_os = "macos")]
const HTTPS_PORT: &str = "HTTPSPort";
#[cfg(target_os = "macos")]
const HTTP_ENABLE: &str = "HTTPEnable";
#[cfg(target_os = "macos")]
const HTTP_PROXY: &str = "HTTPProxy";
#[cfg(target_os = "macos")]
const HTTP_PORT: &str = "HTTPPort";
#[cfg(target_os = "macos")]
const SOCKS_ENABLE: &str = "SOCKSEnable";
#[cfg(target_os = "macos")]
const SOCKS_PROXY: &str = "SOCKSProxy";
#[cfg(target_os = "macos")]
const SOCKS_PORT: &str = "SOCKSPort";

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

#[cfg(target_os = "macos")]
pub fn get_macos_proxy_config(url: &str) -> Option<SystemProxyConfig> {
    let proxies_dict: CFDictionaryRef = unsafe { SCDynamicStoreCopyProxies(ptr::null()) };
    if proxies_dict.is_null() {
        log_warn!("Failed to retrieve macOS proxy settings");
        return None;
    }

    defer! { unsafe { CFRelease(proxies_dict as *const _) }; }

    if get_bool(proxies_dict, PROXY_AUTO_CONFIG_ENABLE).unwrap_or(false) {
        if let Some(pac_url) = get_string(proxies_dict, PROXY_AUTO_CONFIG_URL) {
            if !pac_url.trim().is_empty() {
                log_info!("Found enabled macOS PAC URL: {}", pac_url);
                return Some(SystemProxyConfig::PacUrl(pac_url));
            }
        }
    }

    let parsed = Url::parse(url).ok();
    let scheme = parsed.as_ref().map(Url::scheme).unwrap_or("http");

    let candidates = match scheme {
        "https" => vec![
            (HTTPS_ENABLE, HTTPS_PROXY, HTTPS_PORT, ProxyScheme::Https),
            (HTTP_ENABLE, HTTP_PROXY, HTTP_PORT, ProxyScheme::Http),
            (SOCKS_ENABLE, SOCKS_PROXY, SOCKS_PORT, ProxyScheme::Socks5),
        ],
        "http" => vec![
            (HTTP_ENABLE, HTTP_PROXY, HTTP_PORT, ProxyScheme::Http),
            (HTTPS_ENABLE, HTTPS_PROXY, HTTPS_PORT, ProxyScheme::Https),
            (SOCKS_ENABLE, SOCKS_PROXY, SOCKS_PORT, ProxyScheme::Socks5),
        ],
        _ => vec![
            (SOCKS_ENABLE, SOCKS_PROXY, SOCKS_PORT, ProxyScheme::Socks5),
            (HTTPS_ENABLE, HTTPS_PROXY, HTTPS_PORT, ProxyScheme::Https),
            (HTTP_ENABLE, HTTP_PROXY, HTTP_PORT, ProxyScheme::Http),
        ],
    };

    for (enable_key, host_key, port_key, proxy_scheme) in candidates {
        if !get_bool(proxies_dict, enable_key).unwrap_or(false) {
            continue;
        }
        let Some(host) = get_string(proxies_dict, host_key) else {
            continue;
        };
        let Some(port) = get_i32(proxies_dict, port_key) else {
            continue;
        };
        if host.trim().is_empty() || port <= 0 {
            continue;
        }
        let raw = format!("{}:{}", host, port);
        if let Some(proxy) = normalize_proxy_url(&raw, proxy_scheme) {
            log_info!("Found enabled macOS proxy: {}", proxy);
            return Some(SystemProxyConfig::Manual(proxy));
        }
    }

    None
}

#[cfg(target_os = "macos")]
fn get_value(dict: CFDictionaryRef, key: &str) -> *const std::os::raw::c_void {
    let cf_key = CFString::new(key);
    unsafe { CFDictionaryGetValue(dict, cf_key.as_concrete_TypeRef() as *const _) }
}

#[cfg(target_os = "macos")]
fn get_string(dict: CFDictionaryRef, key: &str) -> Option<String> {
    let value = get_value(dict, key);
    if value.is_null() {
        return None;
    }
    Some(unsafe { CFString::wrap_under_get_rule(value as CFStringRef) }.to_string())
}

#[cfg(target_os = "macos")]
fn get_i32(dict: CFDictionaryRef, key: &str) -> Option<i32> {
    let value = get_value(dict, key);
    if value.is_null() {
        return None;
    }
    let mut number: i32 = 0;
    let ok = unsafe {
        CFNumberGetValue(
            value as CFNumberRef,
            kCFNumberSInt32Type,
            &mut number as *mut i32 as *mut std::os::raw::c_void,
        )
    };
    ok.then_some(number)
}

#[cfg(target_os = "macos")]
fn get_bool(dict: CFDictionaryRef, key: &str) -> Option<bool> {
    get_i32(dict, key).map(|value| value != 0)
}