Visual Studio Code, rebuilt in Rust
Rust
//! Chromium's ProxyConfig::ProxyRules (proxy_config.cc `ParseFromString`, `Apply`) and ProxyBypassRules
//! (proxy_bypass_rules.cc, scheme_host_port_matcher_rule.cc) for one URL, as `ProxyList::ToPacString` gives it.
//! request/windows.rs resolves the session proxy and the IE proxy settings through it, as ProxyConfigServiceWin.
use std::net::IpAddr;
/// `ProxyRules::Apply` of `rules` (`host:port`, `scheme://host:port`, or `http=...;https=...;socks=...`) with the
/// bypass list (`,`, `;` or whitespace separated, as ProxyConfigServiceWin tokenizes `lpszProxyBypass`).
pub fn pac_for_rules(url: &str, rules: &str, bypass: &str) -> String {
let target = Target::parse(url);
let proxies = proxies_for_scheme(rules, &target.scheme);
if proxies.is_empty() || bypassed(&target, bypass) {
return "DIRECT".to_owned();
}
proxies.join(";")
}
/// `ProxyList::Set` of a WinHTTP proxy list (`host:port;host:port`), as ProxyResolverWinHttp's `UseNamedProxy`.
pub fn pac_for_list(list: &str) -> String {
let proxies: Vec<String> = list.split([';', ' ', '\t']).filter_map(|uri| pac_element(uri, "http")).collect();
if proxies.is_empty() { "DIRECT".to_owned() } else { proxies.join(";") }
}
/// The curl `--proxy` of a PAC element; `DIRECT` is the empty proxy, which turns the proxy variables off.
/// Chromium's SOCKS5 resolves host names at the proxy, curl's `socks5h`.
pub fn curl_proxy(element: &str) -> String {
let Some((keyword, address)) = element.trim().split_once(' ') else { return String::new() };
let scheme = match keyword {
"PROXY" => "http",
"HTTPS" => "https",
"SOCKS" | "SOCKS4" => "socks4",
"SOCKS5" => "socks5h",
_ => return String::new(),
};
format!("{scheme}://{}", address.trim())
}
struct Target {
scheme: String,
host: String,
port: u16,
}
impl Target {
fn parse(url: &str) -> Target {
let (scheme, rest) = url.split_once("://").unwrap_or(("http", url));
let scheme = scheme.to_ascii_lowercase();
let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
let authority = authority.rsplit_once('@').map_or(authority, |(_, host)| host);
let default_port = match scheme.as_str() {
"https" | "wss" => 443,
"ftp" => 21,
_ => 80,
};
let (host, port) = host_port(authority, default_port).unwrap_or((authority.to_ascii_lowercase(), default_port));
Target { scheme, host, port }
}
fn ip(&self) -> Option<IpAddr> {
unbracket(&self.host).parse().ok()
}
}
/// ParseFromString: an entry without `=` before any `scheme=` entry is the list for every scheme; `socks=` is the
/// fallback of the schemes without their own list, SOCKS4 when its proxies name no scheme.
fn proxies_for_scheme(rules: &str, scheme: &str) -> Vec<String> {
let mut per_scheme = false;
let mut own = Vec::new();
let mut fallback = Vec::new();
for entry in rules.split(';').filter(|entry| !entry.is_empty()) {
let Some((name, list)) = entry.split_once('=') else {
if per_scheme {
continue;
}
return pac_elements(entry, "http");
};
per_scheme = true;
match name.trim() {
"socks" => fallback.extend(pac_elements(list, "socks4")),
name if name == scheme && matches!(name, "http" | "https" | "ftp") => own.extend(pac_elements(list, "http")),
_ => {}
}
}
if own.is_empty() { fallback } else { own }
}
fn pac_elements(list: &str, default_scheme: &str) -> Vec<String> {
list.split(',').filter_map(|uri| pac_element(uri, default_scheme)).collect()
}
/// proxy_string_util.cc `ProxyUriToProxyServer`: `socks://` is SOCKS5 in a URI, `direct://` takes no host.
fn pac_element(uri: &str, default_scheme: &str) -> Option<String> {
let uri = uri.trim();
let (scheme, address) = match uri.split_once("://") {
Some((scheme, address)) => (scheme.to_ascii_lowercase(), address),
None => (default_scheme.to_owned(), uri),
};
let (keyword, default_port) = match scheme.as_str() {
"http" => ("PROXY", 80),
"https" => ("HTTPS", 443),
"socks4" => ("SOCKS", 1080),
"socks" | "socks5" => ("SOCKS5", 1080),
"direct" => return address.is_empty().then(|| "DIRECT".to_owned()),
_ => return None,
};
let (host, port) = host_port(address, default_port)?;
Some(format!("{keyword} {host}:{port}"))
}
/// `host`, `host:port`, `[v6]` or `[v6]:port`, the host lowercased; None for an empty host or a bad port.
fn host_port(address: &str, default_port: u16) -> Option<(String, u16)> {
let (host, port) = match address.rsplit_once(':') {
Some((host, port)) if !host.contains(':') || host.ends_with(']') => (host, port.parse().ok()?),
_ => (address, default_port),
};
if host.is_empty() {
return None;
}
Some((host.to_ascii_lowercase(), port))
}
fn unbracket(host: &str) -> &str {
host.strip_prefix('[').and_then(|host| host.strip_suffix(']')).unwrap_or(host)
}
/// `ProxyBypassRules::Matches`: the rules in order, `<-loopback>` excluding the implicit rules where it stands, then
/// the implicit rules (localhost, loopback and link-local addresses).
fn bypassed(target: &Target, bypass: &str) -> bool {
for rule in bypass.split([',', ';', ' ', '\t', '\n', '\r']).filter(|rule| !rule.is_empty()) {
match rule.to_ascii_lowercase().as_str() {
"<local>" if !target.host.contains('.') && target.ip().is_none() => return true,
"<local>" => {}
"<-loopback>" if implicitly_bypassed(target) => return false,
"<-loopback>" => {}
rule if rule_matches(rule, target) => return true,
_ => {}
}
}
implicitly_bypassed(target)
}
fn implicitly_bypassed(target: &Target) -> bool {
let host = target.host.strip_suffix('.').unwrap_or(&target.host);
match target.ip() {
Some(IpAddr::V4(ip)) => ip.is_loopback() || ip.is_link_local(),
Some(IpAddr::V6(ip)) => ip.is_loopback() || ip.segments()[0] & 0xffc0 == 0xfe80,
None => host == "localhost" || host.ends_with(".localhost"),
}
}
/// SchemeHostPortMatcherRule::FromUntrimmedRawString: an optional `scheme://`, then a CIDR block (`10.0.0.0/8`), an
/// IP literal, or a host pattern with `*` and `?` (a leading `.` is `*.`) and an optional port.
fn rule_matches(rule: &str, target: &Target) -> bool {
let rule = match rule.split_once("://") {
Some((scheme, _)) if scheme != target.scheme => return false,
Some((_, rest)) => rest,
None => rule,
};
if let Some((ip, prefix)) = rule.split_once('/') {
let (Ok(ip), Ok(prefix), Some(host)) = (unbracket(ip).parse::<IpAddr>(), prefix.parse::<u32>(), target.ip()) else { return false };
return in_block(host, ip, prefix);
}
let Some((host, port)) = host_port(rule, 0) else { return false };
if port != 0 && port != target.port {
return false;
}
if let Ok(ip) = unbracket(&host).parse::<IpAddr>() {
return target.ip() == Some(ip);
}
let pattern = if host.starts_with('.') { format!("*{host}") } else { host };
glob(pattern.as_bytes(), target.host.as_bytes())
}
fn in_block(host: IpAddr, block: IpAddr, prefix: u32) -> bool {
match (host, block) {
(IpAddr::V4(host), IpAddr::V4(block)) if prefix <= 32 => u32::from(host).checked_shr(32 - prefix).unwrap_or(0) == u32::from(block).checked_shr(32 - prefix).unwrap_or(0),
(IpAddr::V6(host), IpAddr::V6(block)) if prefix <= 128 => u128::from(host).checked_shr(128 - prefix).unwrap_or(0) == u128::from(block).checked_shr(128 - prefix).unwrap_or(0),
_ => false,
}
}
/// base/strings/pattern.cc `MatchPattern`: `*` any run, `?` one character.
fn glob(pattern: &[u8], text: &[u8]) -> bool {
match pattern.split_first() {
None => text.is_empty(),
Some((b'*', rest)) => (0..=text.len()).any(|skip| glob(rest, &text[skip..])),
Some((b'?', rest)) => !text.is_empty() && glob(rest, &text[1..]),
Some((first, rest)) => text.first() == Some(first) && glob(rest, &text[1..]),
}
}
#[cfg(test)]
mod tests {
use super::{curl_proxy, pac_for_list, pac_for_rules};
/// proxy_config_unittest.cc `ParseProxyRules`.
#[test]
fn rules_pick_the_list_of_the_scheme_or_the_socks_fallback() {
let pac = |url, rules| pac_for_rules(url, rules, "");
assert_eq!(pac("http://a.test/", "myproxy:80"), "PROXY myproxy:80");
assert_eq!(pac("https://a.test/", "myproxy"), "PROXY myproxy:80");
assert_eq!(pac("https://a.test/", "https://Secure.Proxy"), "HTTPS secure.proxy:443");
assert_eq!(pac("http://a.test/", "socks://s:1080"), "SOCKS5 s:1080");
assert_eq!(pac("http://a.test/", "a:1,socks4://b,direct://"), "PROXY a:1;SOCKS b:1080;DIRECT");
let per_scheme = "http=h1:80;https=h2:443;socks=s1";
assert_eq!(pac("http://a.test/", per_scheme), "PROXY h1:80");
assert_eq!(pac("https://a.test/", per_scheme), "PROXY h2:443");
assert_eq!(pac("ftp://a.test/", per_scheme), "SOCKS s1:1080");
assert_eq!(pac("https://a.test/", "http=h1:80"), "DIRECT");
assert_eq!(pac("http://a.test/", "http=h1:80;bare:3"), "PROXY h1:80");
assert_eq!(pac("http://a.test/", ""), "DIRECT");
assert_eq!(pac("http://a.test/", "myproxy:port"), "DIRECT");
}
/// proxy_bypass_rules_unittest.cc: `<local>`, wildcards, ports, schemes, CIDR blocks and the implicit rules.
#[test]
fn bypass_rules_match_as_chromium() {
let direct = |url: &str, bypass: &str| pac_for_rules(url, "p:8080", bypass) == "DIRECT";
assert!(direct("http://intranet/", "<local>"));
assert!(!direct("http://intranet.corp/", "<local>"));
assert!(!direct("http://[::5]/", "<local>"));
assert!(direct("http://www.Example.com/", "*.example.com"));
assert!(direct("http://www.example.com/", ".example.com"));
assert!(!direct("http://example.com/", "*.example.com"));
assert!(direct("http://example.com/", "example.com"));
assert!(direct("http://10.1.2.3/", "10.*"));
assert!(direct("http://a.test:81/", "a.test:81") && !direct("http://a.test/", "a.test:81"));
assert!(direct("https://a.test/", "https://a.test") && !direct("http://a.test/", "https://a.test"));
assert!(direct("http://192.168.4.5/", "192.168.0.0/16") && !direct("http://192.169.0.1/", "192.168.0.0/16"));
assert!(direct("http://[fe80::1]/", "<local>"));
assert!(direct("http://localhost:3000/", "") && direct("http://127.0.0.2/", "") && direct("http://a.localhost/", ""));
assert!(!direct("http://localhost/", "<-loopback>"));
assert!(direct("http://a.test/", "a.test;b.test") && direct("http://b.test/", "a.test b.test"));
}
#[test]
fn winhttp_lists_and_curl_proxies() {
assert_eq!(pac_for_list("p1:8080;p2"), "PROXY p1:8080;PROXY p2:80");
assert_eq!(pac_for_list(""), "DIRECT");
assert_eq!(curl_proxy("PROXY p1:8080"), "http://p1:8080");
assert_eq!(curl_proxy("SOCKS5 s:1080"), "socks5h://s:1080");
assert_eq!(curl_proxy("SOCKS s:1080"), "socks4://s:1080");
assert_eq!(curl_proxy("DIRECT"), "");
}
}