Skip to content

Visual Studio Code, rebuilt in Rust

Rust
4.4 KB
Raw Blame
//! request.rs `send` through curl. Without a session proxy curl takes the proxy variables (`https_proxy`,
//! `no_proxy`), which is where Chromium on Linux reads the system proxy outside GNOME and KDE.

use std::io::Write;
use std::process::{Command, Stdio};

use anyhow::{Context, bail};

use super::{Request, Response, SessionProxy};

/// proxy-agent asks only when neither `http.proxy` nor the proxy variables name a proxy, the sources of the session
/// proxy and of Chromium's Linux system proxy outside GNOME and KDE.
#[cfg(target_os = "linux")]
pub(super) fn resolve_proxy_with(_url: &str, _proxy: Option<&SessionProxy>) -> Option<String> {
    Some("DIRECT".to_owned())
}

// shortcut: no GSS-API binding on Linux, so proxies that need Kerberos fail; link libgssapi_krb5 as macos.rs links GSS.
#[cfg(target_os = "linux")]
pub(super) fn lookup_kerberos_authorization(_spn: &str) -> anyhow::Result<String> {
    bail!("Kerberos is not available on Linux")
}

pub(super) fn send(options: &Request, proxy: Option<&SessionProxy>, proxy_authorization: Option<&str>) -> anyhow::Result<Response> {
    let mut curl = Command::new("curl");
    // NSURLSession's timeout is an idle timeout: give up when no byte arrived for that long.
    let idle = options.timeout.as_secs().max(1).to_string();
    curl.args(["--silent", "--show-error", "--location", "--compressed", "--connect-timeout", &idle, "--speed-limit", "1", "--speed-time", &idle]);
    curl.args(["--request", options.method, "--write-out", "%{http_code}"]);
    for (name, value) in options.headers {
        curl.arg("--header").arg(format!("{name}: {value}"));
    }
    if let Some(proxy) = proxy {
        let (scheme, address) = proxy.rules.split_once("://").unwrap_or(("http", &proxy.rules));
        // Chromium's `socks` is SOCKS4.
        let scheme = if scheme == "socks" { "socks4" } else { scheme };
        curl.arg("--proxy").arg(if address.is_empty() { String::new() } else { format!("{scheme}://{address}") });
        curl.arg("--noproxy").arg(no_proxy(&proxy.bypass_rules, options.url));
    }
    if let Some(authorization) = proxy_authorization {
        curl.arg("--proxy-header").arg(format!("Proxy-Authorization: {authorization}"));
    }
    if options.body.is_some() {
        curl.args(["--data-binary", "@-"]);
    }
    curl.arg("--url").arg(options.url);
    let mut child = curl.stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn().context("curl")?;
    let mut stdin = child.stdin.take().expect("piped stdin");
    if let Some(body) = options.body {
        stdin.write_all(body).context("curl")?;
    }
    drop(stdin);
    let output = child.wait_with_output().context("curl")?;
    if !output.status.success() {
        bail!("{}", String::from_utf8_lossy(&output.stderr).trim());
    }
    let mut body = output.stdout;
    let status = body.split_off(body.len().saturating_sub(3));
    let status = std::str::from_utf8(&status).ok().and_then(|status| status.parse().ok()).context("curl gave no status")?;
    Ok(Response { status, body })
}

/// curl's `--noproxy` for Chromium's bypass rules. curl has no `<local>` (a host name without a dot, not an IP
/// literal), so the request's own host joins the list when it is one.
fn no_proxy(bypass_rules: &str, url: &str) -> String {
    let mut hosts: Vec<&str> = bypass_rules.split(',').map(str::trim).filter(|rule| !rule.is_empty() && *rule != "<local>").collect();
    let host = url_host(url);
    if bypass_rules.split(',').any(|rule| rule.trim() == "<local>") && !host.is_empty() && !host.contains(['.', ':', '[']) {
        hosts.push(host);
    }
    hosts.join(",")
}

/// The host of `scheme://user@host:port/path`; an IPv6 literal gives `[`.
fn url_host(url: &str) -> &str {
    let rest = url.split_once("://").map_or(url, |(_, rest)| rest);
    let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
    let host = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
    host.split(':').next().unwrap_or(host)
}

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

    #[test]
    fn local_bypasses_hosts_without_a_dot() {
        assert_eq!(no_proxy("a.example,<local>", "http://intranet:8080/x"), "a.example,intranet");
        assert_eq!(no_proxy("a.example,<local>", "https://[email protected]/"), "a.example");
        assert_eq!(no_proxy("<local>", "http://[::1]:3000/"), "");
        assert_eq!(no_proxy("a.example", "http://intranet/"), "a.example");
    }
}