bigtext 0.19.1

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 GB/s search, atomic save
Documentation
//! The proxy for BigText's own web requests: the update check and download, and files opened
//! from `https://` and `s3://` addresses.
//!
//! `ALL_PROXY`, `HTTPS_PROXY` or `HTTP_PROXY` (with `NO_PROXY`) when one is set, as curl reads
//! them; otherwise the system's proxy, which VPN and proxy programs set when they route the
//! computer's web traffic: on Windows Settings → Network & internet → Proxy (the Internet
//! Settings key in the registry), on macOS the network settings (`scutil --proxy`). An
//! automatic configuration script (PAC) is not read; Linux has the environment variables only.

use ureq::{Proxy, ProxyProtocol};

/// The proxy to use, or `None` to connect directly.
pub fn proxy() -> Option<Proxy> {
    Proxy::try_from_env().or_else(system)
}

/// A proxy as the system settings give it.
#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
#[derive(Debug, PartialEq)]
struct Spec {
    socks: bool,
    host: String,
    port: Option<u16>,
    /// Hosts reached directly (`*.example.com`, `10.*`, `localhost`).
    bypass: Vec<String>,
}

#[cfg_attr(not(any(windows, target_os = "macos")), allow(dead_code))]
impl Spec {
    fn build(&self) -> Option<Proxy> {
        let proto = if self.socks {
            ProxyProtocol::Socks5
        } else {
            ProxyProtocol::Http
        };
        let mut b = Proxy::builder(proto).host(&self.host);
        if let Some(p) = self.port {
            b = b.port(p);
        }
        for e in &self.bypass {
            b = b.no_proxy(e);
        }
        b.build().ok()
    }
}

/// `host:port` (or `http://host:port`, or a host alone) as (host, port).
#[cfg_attr(not(windows), allow(dead_code))]
fn host_port(s: &str) -> Option<(String, Option<u16>)> {
    let s = s.trim();
    let s = ["http://", "https://", "socks://", "socks5://"]
        .iter()
        .find_map(|p| s.strip_prefix(p))
        .unwrap_or(s)
        .trim_end_matches('/');
    let (host, port) = match s.rsplit_once(':') {
        // An IPv6 address without a port has colons inside its brackets only.
        Some((h, p)) if !p.contains(']') => (h, Some(p.parse::<u16>().ok()?)),
        _ => (s, None),
    };
    (!host.is_empty() && !host.contains(char::is_whitespace)).then(|| (host.to_string(), port))
}

/// Windows' `ProxyServer` value — `host:port` for every protocol, or per protocol as
/// `http=host:port;https=host:port;socks=host:port` — with its `ProxyOverride` list
/// (`localhost;127.*;*.corp.example;<local>`). The HTTPS proxy is used, then the HTTP one, then
/// SOCKS. `<local>` (names without a dot) has no equivalent and is left out.
#[cfg_attr(not(windows), allow(dead_code))]
fn windows_spec(server: &str, overrides: &str) -> Option<Spec> {
    let mut by_kind: Vec<(String, &str)> = Vec::new();
    for part in server.split(';').map(str::trim).filter(|p| !p.is_empty()) {
        match part.split_once('=') {
            Some((k, v)) => by_kind.push((k.trim().to_ascii_lowercase(), v)),
            None => by_kind.push((String::new(), part)),
        }
    }
    let (kind, value) = ["https", "http", "", "socks"]
        .iter()
        .find_map(|k| by_kind.iter().find(|(kind, _)| kind == k))?;
    let (host, port) = host_port(value)?;
    let bypass = overrides
        .split(';')
        .map(str::trim)
        .filter(|e| !e.is_empty() && !e.eq_ignore_ascii_case("<local>"))
        .map(str::to_string)
        .collect();
    Some(Spec {
        socks: kind == "socks",
        host,
        port,
        bypass,
    })
}

/// What `scutil --proxy` prints on macOS: `HTTPSEnable : 1`, `HTTPSProxy : 127.0.0.1`,
/// `HTTPSPort : 7890` (likewise `HTTP…` and `SOCKS…`) and an `ExceptionsList` array. The HTTPS
/// proxy is used, then the HTTP one, then SOCKS.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
fn scutil_spec(out: &str) -> Option<Spec> {
    let mut keys: Vec<(&str, &str)> = Vec::new();
    let mut bypass = Vec::new();
    let mut in_exceptions = false;
    for line in out.lines().map(str::trim) {
        if line.starts_with('}') {
            in_exceptions = false;
            continue;
        }
        let Some((k, v)) = line.split_once(" : ") else {
            continue;
        };
        let (k, v) = (k.trim(), v.trim());
        if in_exceptions {
            bypass.push(v.to_string());
        } else if k == "ExceptionsList" && v.starts_with("<array>") {
            in_exceptions = true;
        } else {
            keys.push((k, v));
        }
    }
    let get = |k: String| keys.iter().find(|(key, _)| *key == k).map(|(_, v)| *v);
    ["HTTPS", "HTTP", "SOCKS"].iter().find_map(|kind| {
        if get(format!("{kind}Enable")) != Some("1") {
            return None;
        }
        let host = get(format!("{kind}Proxy")).filter(|h| !h.is_empty())?;
        Some(Spec {
            socks: *kind == "SOCKS",
            host: host.to_string(),
            port: get(format!("{kind}Port")).and_then(|p| p.parse().ok()),
            bypass: bypass.clone(),
        })
    })
}

#[cfg(windows)]
fn system() -> Option<Proxy> {
    if win::dword("ProxyEnable") != Some(1) {
        return None;
    }
    let server = win::string("ProxyServer")?;
    let overrides = win::string("ProxyOverride").unwrap_or_default();
    windows_spec(&server, &overrides)?.build()
}

/// Values of the current user's Internet Settings key.
#[cfg(windows)]
mod win {
    use windows_sys::Win32::System::Registry::{
        RegGetValueW, HKEY_CURRENT_USER, REG_ROUTINE_FLAGS, RRF_RT_REG_DWORD, RRF_RT_REG_SZ,
    };

    fn wide(s: &str) -> Vec<u16> {
        s.encode_utf16().chain(Some(0)).collect()
    }

    /// RegGetValueW on the key; `data` null asks for the size in bytes.
    fn get(name: &str, kind: REG_ROUTINE_FLAGS, data: *mut u8, size: &mut u32) -> bool {
        let key = wide(r"Software\Microsoft\Windows\CurrentVersion\Internet Settings");
        let name = wide(name);
        // SAFETY: NUL-terminated key and value names; `data` is null or holds `size` bytes.
        let r = unsafe {
            RegGetValueW(
                HKEY_CURRENT_USER,
                key.as_ptr(),
                name.as_ptr(),
                kind,
                std::ptr::null_mut(),
                data.cast(),
                size,
            )
        };
        r == 0
    }

    pub fn dword(name: &str) -> Option<u32> {
        let mut v = 0u32;
        let mut size = 4;
        get(
            name,
            RRF_RT_REG_DWORD,
            (&mut v as *mut u32).cast(),
            &mut size,
        )
        .then_some(v)
    }

    pub fn string(name: &str) -> Option<String> {
        let mut size = 0;
        if !get(name, RRF_RT_REG_SZ, std::ptr::null_mut(), &mut size) || size == 0 {
            return None;
        }
        let mut buf = vec![0u16; (size as usize).div_ceil(2)];
        size = (buf.len() * 2) as u32;
        if !get(name, RRF_RT_REG_SZ, buf.as_mut_ptr().cast(), &mut size) {
            return None;
        }
        let n = buf.iter().position(|&c| c == 0).unwrap_or(buf.len());
        Some(String::from_utf16_lossy(&buf[..n]))
    }
}

#[cfg(target_os = "macos")]
fn system() -> Option<Proxy> {
    let out = std::process::Command::new("/usr/sbin/scutil")
        .arg("--proxy")
        .stdin(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .output()
        .ok()?;
    scutil_spec(&String::from_utf8_lossy(&out.stdout))?.build()
}

#[cfg(not(any(windows, target_os = "macos")))]
fn system() -> Option<Proxy> {
    None
}

#[cfg(test)]
mod tests {
    use super::*;

    fn spec(socks: bool, host: &str, port: Option<u16>, bypass: &[&str]) -> Option<Spec> {
        Some(Spec {
            socks,
            host: host.into(),
            port,
            bypass: bypass.iter().map(|s| s.to_string()).collect(),
        })
    }

    #[test]
    fn windows_proxy_server_values() {
        // One proxy for everything, as Clash and v2rayN set it.
        assert_eq!(
            windows_spec("127.0.0.1:7890", "localhost;127.*;10.*;<local>"),
            spec(
                false,
                "127.0.0.1",
                Some(7890),
                &["localhost", "127.*", "10.*"]
            )
        );
        // Per protocol: HTTPS first, then HTTP, then SOCKS.
        assert_eq!(
            windows_spec("http=proxy:80;https=secure:8443;socks=s:1080", ""),
            spec(false, "secure", Some(8443), &[])
        );
        assert_eq!(
            windows_spec("ftp=f:21; http=proxy:3128", ""),
            spec(false, "proxy", Some(3128), &[])
        );
        assert_eq!(
            windows_spec("socks=127.0.0.1:10808", ""),
            spec(true, "127.0.0.1", Some(10808), &[])
        );
        // A scheme, no port, an IPv6 address.
        assert_eq!(
            windows_spec("http://proxy.corp:8080/", ""),
            spec(false, "proxy.corp", Some(8080), &[])
        );
        assert_eq!(
            windows_spec("proxy.corp", ""),
            spec(false, "proxy.corp", None, &[])
        );
        assert_eq!(
            windows_spec("[::1]:8080", ""),
            spec(false, "[::1]", Some(8080), &[])
        );
        // Nothing usable.
        for bad in ["", " ; ", "host:port", "ftp=f:21", "a b:1"] {
            assert_eq!(windows_spec(bad, ""), None, "{bad}");
        }
    }

    #[test]
    fn scutil_output() {
        let out = "<dictionary> {
  ExceptionsList : <array> {
    0 : *.local
    1 : 169.254/16
  }
  FTPPassive : 1
  HTTPEnable : 1
  HTTPPort : 7890
  HTTPProxy : 127.0.0.1
  HTTPSEnable : 1
  HTTPSPort : 7891
  HTTPSProxy : 127.0.0.2
  SOCKSEnable : 1
  SOCKSPort : 7892
  SOCKSProxy : 127.0.0.3
}
";
        assert_eq!(
            scutil_spec(out),
            spec(false, "127.0.0.2", Some(7891), &["*.local", "169.254/16"])
        );
        let socks_only = out
            .replace("HTTPEnable : 1", "HTTPEnable : 0")
            .replace("HTTPSEnable : 1", "HTTPSEnable : 0");
        assert_eq!(
            scutil_spec(&socks_only),
            spec(true, "127.0.0.3", Some(7892), &["*.local", "169.254/16"])
        );
        assert_eq!(scutil_spec("<dictionary> {\n  HTTPEnable : 0\n}\n"), None);
    }

    #[test]
    fn specs_build_proxies() {
        let p = spec(false, "127.0.0.1", Some(7890), &["localhost", "*.corp"])
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(
            (p.protocol(), p.host(), p.port()),
            (ProxyProtocol::Http, "127.0.0.1", 7890)
        );
        let p = spec(true, "s", Some(1080), &[]).unwrap().build().unwrap();
        assert_eq!(p.protocol(), ProxyProtocol::Socks5);
    }
}