Visual Studio Code, rebuilt in Rust
Rust
//! platform/request (request.ts, requestService.ts): HTTP requests of the workbench, sent by `send` of
//! request/macos.rs (NSURLSession), request/linux.rs (curl) or request/windows.rs (curl with the Windows proxy).
use std::sync::Mutex;
use std::time::Duration;
use anyhow::bail;
#[cfg(any(target_os = "linux", target_os = "windows"))]
mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(any(target_os = "windows", test))]
mod proxy_rules;
#[cfg(target_os = "windows")]
mod windows;
#[cfg(target_os = "linux")]
use linux::{lookup_kerberos_authorization, resolve_proxy_with, send};
#[cfg(target_os = "windows")]
use windows::{lookup_kerberos_authorization, resolve_proxy_with, send};
#[cfg(target_os = "macos")]
use macos::{lookup_kerberos_authorization, resolve_proxy_with, send};
/// Electron's `session.setProxy({ proxyRules, proxyBypassRules })`; never set means the system settings.
static SESSION_PROXY: Mutex<Option<SessionProxy>> = Mutex::new(None);
/// NativeRequestService `http.proxyAuthorization`, sent as the `Proxy-Authorization` header.
static PROXY_AUTHORIZATION: Mutex<Option<String>> = Mutex::new(None);
#[derive(Clone, Debug, PartialEq)]
pub struct SessionProxy {
pub rules: String,
pub bypass_rules: String,
}
/// windowImpl.ts `onConfigurationUpdated`: `http.proxy` of the user settings, else the proxy variables, without
/// user info or a trailing `/`; `http.noProxy`, else `no_proxy`, plus `<local>`. None leaves the session as it is:
/// a proxy still holding `@` or the same rules as `current`.
pub fn session_proxy(user_proxy: &str, no_proxy: &[String], env: &dyn Fn(&str) -> Option<String>, current: Option<&SessionProxy>) -> Option<SessionProxy> {
let from_env = |keys: &[&str]| keys.iter().find_map(|key| env(key).filter(|value| !value.is_empty())).unwrap_or_default().trim().to_owned();
let mut proxy = match user_proxy.trim() {
"" => from_env(&["https_proxy", "HTTPS_PROXY", "http_proxy", "HTTP_PROXY"]),
proxy => proxy.to_owned(),
};
if let Some((scheme, rest)) = proxy.split_once("://") {
let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
if let Some(at) = rest[..authority_end].rfind('@') {
proxy = format!("{scheme}://{}", &rest[at + 1..]);
}
}
if let Some(stripped) = proxy.strip_suffix('/') {
proxy = stripped.to_owned();
}
let no_proxy = match no_proxy.iter().map(|item| item.trim()).collect::<Vec<_>>().join(",") {
joined if joined.is_empty() => from_env(&["no_proxy", "NO_PROXY"]),
joined => joined,
};
let bypass_rules = if no_proxy.is_empty() { "<local>".to_owned() } else { format!("{no_proxy},<local>") };
let unchanged = match current {
Some(current) => current.rules == proxy && current.bypass_rules == bypass_rules,
None => proxy.is_empty() && no_proxy.is_empty(),
};
if proxy.contains('@') || unchanged {
return None;
}
Some(SessionProxy { rules: proxy, bypass_rules })
}
pub fn current_session_proxy() -> Option<SessionProxy> {
SESSION_PROXY.lock().unwrap().clone()
}
pub fn set_session_proxy(proxy: SessionProxy) {
*SESSION_PROXY.lock().unwrap() = Some(proxy);
}
/// Electron's `session.resolveProxy(url)`: the proxies for `url` as a PAC result (`PROXY host:port;DIRECT`).
pub fn resolve_proxy(url: &str) -> Option<String> {
resolve_proxy_with(url, current_session_proxy().as_ref())
}
/// requestService.ts `lookupKerberosAuthorization`: the `Negotiate` header for the proxy at `url`, from the
/// Kerberos ticket the user holds; None when there is none.
pub fn kerberos_authorization(url: &str, spn_config: Option<&str>) -> Option<String> {
let spn = kerberos_spn(url, spn_config)?;
match lookup_kerberos_authorization(&spn) {
Ok(token) => Some(format!("Negotiate {token}")),
Err(error) => {
eprintln!("[request] Kerberos authentication failed for {spn}: {error}");
None
}
}
}
/// `http.proxyKerberosServicePrincipal`, else `HTTP@<hostname>`.
fn kerberos_spn(url: &str, spn_config: Option<&str>) -> Option<String> {
if let Some(spn) = spn_config.filter(|spn| !spn.is_empty()) {
return Some(spn.to_owned());
}
let host = url.split_once("://")?.1.split(['/', '?', '#']).next()?;
let host = host.rsplit_once('@').map_or(host, |(_, host)| host);
// `URL.hostname`: lowercase, an IPv6 address keeps its brackets.
let hostname = match host.find(']') {
Some(end) => &host[..=end],
None => host.split(':').next()?,
};
Some(format!("HTTP@{}", hostname.to_ascii_lowercase()))
}
pub fn set_proxy_authorization(authorization: Option<String>) {
*PROXY_AUTHORIZATION.lock().unwrap() = authorization;
}
pub struct Request<'a> {
pub url: &'a str,
pub method: &'a str,
pub headers: &'a [(&'a str, &'a str)],
pub body: Option<&'a [u8]>,
pub timeout: Duration,
}
impl<'a> Request<'a> {
pub fn get(url: &'a str) -> Self {
Request { url, method: "GET", headers: &[], body: None, timeout: Duration::from_secs(60) }
}
}
#[derive(Debug)]
pub struct Response {
pub status: u16,
pub body: Vec<u8>,
}
impl Response {
/// `isSuccess`: 2xx, or 1223 (IE's 204).
pub fn is_success(&self) -> bool {
(200..300).contains(&self.status) || self.status == 1223
}
/// `hasNoContent`.
pub fn has_no_content(&self) -> bool {
self.status == 204
}
/// `asJson`: null for 204, an error for other statuses than success.
pub fn as_json(&self) -> anyhow::Result<serde_json::Value> {
if !self.is_success() {
bail!("Server returned {}", self.status);
}
if self.has_no_content() {
return Ok(serde_json::Value::Null);
}
serde_json::from_slice(&self.body).map_err(|error| anyhow::anyhow!("{error}:\n{}", String::from_utf8_lossy(&self.body)))
}
/// `asTextOrError`.
pub fn as_text(&self) -> anyhow::Result<Option<String>> {
if !self.is_success() {
bail!("Server returned {}", self.status);
}
if self.has_no_content() {
return Ok(None);
}
Ok(Some(String::from_utf8_lossy(&self.body).into_owned()))
}
}
/// Sends the request and blocks the calling thread until the whole body arrived, gzip decoded.
pub fn request(options: &Request) -> anyhow::Result<Response> {
let proxy = current_session_proxy();
let authorization = PROXY_AUTHORIZATION.lock().unwrap().clone();
send(options, proxy.as_ref(), authorization.as_deref())
}
/// `IDownloadService.download`: the body of a successful GET written to `target`.
pub fn download(url: &str, target: &std::path::Path) -> anyhow::Result<()> {
let response = request(&Request::get(url))?;
if response.status != 200 {
bail!("Expected 200, got back {} instead.\n\n{}", response.status, String::from_utf8_lossy(&response.body));
}
Ok(std::fs::write(target, response.body)?)
}
#[cfg(test)]
mod tests {
use std::io::{Read, Write};
use std::net::TcpListener;
use super::*;
/// One local HTTP exchange: answers `reply` and hands back the raw request.
fn serve_once(reply: &'static str) -> (String, std::thread::JoinHandle<String>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let url = format!("http://{}/path", listener.local_addr().unwrap());
let handle = std::thread::spawn(move || {
let (mut stream, _) = listener.accept().unwrap();
let mut received = Vec::new();
let mut buffer = [0; 4096];
loop {
let read = stream.read(&mut buffer).unwrap();
received.extend_from_slice(&buffer[..read]);
let text = String::from_utf8_lossy(&received);
if let Some(end) = text.find("\r\n\r\n") {
let length = text.lines().find_map(|line| line.to_ascii_lowercase().strip_prefix("content-length: ").map(|value| value.trim().parse::<usize>().unwrap())).unwrap_or(0);
if received.len() >= end + 4 + length {
break;
}
}
}
stream.write_all(reply.as_bytes()).unwrap();
String::from_utf8_lossy(&received).into_owned()
});
(url, handle)
}
#[test]
fn posts_with_headers_and_reads_json() {
let (url, server) = serve_once("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: 11\r\n\r\n{\"a\": true}");
let response = request(&Request { url: &url, method: "POST", headers: &[("X-Market-Client-Id", "VSCode 1.147.0")], body: Some(b"{}"), timeout: Duration::from_secs(10) }).unwrap();
assert_eq!(response.as_json().unwrap(), serde_json::json!({ "a": true }));
let received = server.join().unwrap();
assert!(received.starts_with("POST /path"));
assert!(received.contains("X-Market-Client-Id: VSCode 1.147.0"));
assert!(received.ends_with("{}"));
}
#[test]
fn session_proxy_carries_requests_and_the_proxy_authorization() {
let (url, proxy) = serve_once("HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok");
let rules = url.trim_end_matches("/path").to_owned();
let proxy_settings = SessionProxy { rules, bypass_rules: "<local>".into() };
let response = send(&Request::get("http://example.invalid/path"), Some(&proxy_settings), Some("Basic dTpw")).unwrap();
assert_eq!(response.as_text().unwrap().as_deref(), Some("ok"));
let received = proxy.join().unwrap();
assert!(received.starts_with("GET http://example.invalid/path"), "{received}");
assert!(received.contains("Proxy-Authorization: Basic dTpw"), "{received}");
}
#[test]
fn session_proxy_reads_the_setting_then_the_environment() {
let env = |key: &str| match key {
"HTTPS_PROXY" => Some("http://env:3128".to_owned()),
"no_proxy" => Some("internal.example".to_owned()),
_ => None,
};
let none = |_: &str| None;
let proxy = |rules: &str, bypass: &str| Some(SessionProxy { rules: rules.into(), bypass_rules: bypass.into() });
assert_eq!(session_proxy(" http://user:secret@proxy:8080/ ", &["a.example ".into(), "b".into()], &none, None), proxy("http://proxy:8080", "a.example,b,<local>"));
assert_eq!(session_proxy("", &[], &env, None), proxy("http://env:3128", "internal.example,<local>"));
assert_eq!(session_proxy("", &[], &none, None), None);
assert_eq!(session_proxy("user@proxy:8080", &[], &none, None), None);
let current = SessionProxy { rules: "http://proxy:8080".into(), bypass_rules: "<local>".into() };
assert_eq!(session_proxy("http://proxy:8080", &[], &none, Some(¤t)), None);
assert_eq!(session_proxy("", &[], &none, Some(¤t)), proxy("", "<local>"));
}
/// Electron's `net.request` ignores requestService.ts's `rejectUnauthorized` (`http.proxyStrictSSL`), so a
/// certificate the system does not trust fails the request whatever the setting.
#[test]
fn a_self_signed_server_certificate_fails_the_request() {
let dir = std::env::temp_dir().join(format!("vsrustium-request-tls-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let openssl = |args: &[&str]| {
let mut command = std::process::Command::new(if cfg!(windows) { "openssl" } else { "/usr/bin/openssl" });
command.args(args).current_dir(&dir).stderr(std::process::Stdio::null()).stdout(std::process::Stdio::null());
command
};
assert!(openssl(&["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-subj", "/CN=127.0.0.1", "-keyout", "key.pem", "-out", "cert.pem", "-days", "1"]).status().unwrap().success());
let port = TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();
let mut server = openssl(&["s_server", "-accept", &port.to_string(), "-cert", "cert.pem", "-key", "key.pem", "-www"]).spawn().unwrap();
while std::net::TcpStream::connect(("127.0.0.1", port)).is_err() {
std::thread::sleep(Duration::from_millis(50));
}
let result = request(&Request::get(&format!("https://127.0.0.1:{port}/")));
server.kill().unwrap();
// Windows keeps cert.pem locked until the killed process exits (os error 32).
server.wait().unwrap();
std::fs::remove_dir_all(&dir).unwrap();
assert!(result.is_err(), "{:?}", result.map(|response| response.status));
}
#[test]
fn error_status_is_not_json() {
let (url, server) = serve_once("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
let response = request(&Request::get(&url)).unwrap();
assert_eq!(response.status, 404);
assert_eq!(response.as_json().unwrap_err().to_string(), "Server returned 404");
server.join().unwrap();
}
#[test]
fn kerberos_spn_is_the_setting_else_the_proxy_host() {
assert_eq!(kerberos_spn("http://[email protected]:8080/", None).as_deref(), Some("[email protected]"));
assert_eq!(kerberos_spn("http://[::1]:3128", Some("")).as_deref(), Some("HTTP@[::1]"));
assert_eq!(kerberos_spn("http://proxy:3128", Some("HTTP/proxy.corp")).as_deref(), Some("HTTP/proxy.corp"));
}
#[test]
fn no_content_is_null() {
let (url, server) = serve_once("HTTP/1.1 204 No Content\r\n\r\n");
let response = request(&Request::get(&url)).unwrap();
assert_eq!(response.as_json().unwrap(), serde_json::Value::Null);
assert_eq!(response.as_text().unwrap(), None);
server.join().unwrap();
}
}