use anyhow::{Context, Result}; use rustls::pki_types::ServerName; use rustls::{ClientConfig, ClientConnection, RootCertStore, StreamOwned}; use std::collections::HashMap; use std::fs::File; use std::io::{BufRead, BufReader, Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; use std::sync::Arc; use std::time::Duration; pub fn post_json(url: &str, body: &serde_json::Value, headers: &[(&str, &str)]) -> Result { let payload = serde_json::to_string(body)?; request( "POST", url, Some((&mut payload.as_bytes(), payload.len() as u64)), Some("application/json"), headers, Duration::from_secs(30), ) } pub fn post_file( url: &str, file: &mut File, len: u64, headers: &[(&str, &str)], timeout: Duration, ) -> Result { request( "POST", url, Some((file, len)), Some("application/octet-stream"), headers, timeout, ) } pub fn get_file( url: &str, file: &mut File, headers: &[(&str, &str)], timeout: Duration, ) -> Result { let (mut response, length) = response("GET", url, None, None, headers, timeout)?; let length = length.context("missing restore payload length")?; anyhow::ensure!( length > 0 && length <= 100 * 1024 * 1024 * 1024, "invalid restore payload length" ); let read = std::io::copy(&mut response.by_ref().take(length), file)?; anyhow::ensure!(read == length, "incomplete restore payload"); Ok(length) } fn request( method: &str, url: &str, body: Option<(&mut dyn Read, u64)>, content_type: Option<&str>, headers: &[(&str, &str)], timeout: Duration, ) -> Result { let (mut response, length) = response(method, url, body, content_type, headers, timeout)?; let length = length.unwrap_or(64 * 1024); anyhow::ensure!(length <= 64 * 1024, "hub JSON response too large"); let mut body = String::new(); let read = response.by_ref().take(length).read_to_string(&mut body)?; if length < 64 * 1024 { anyhow::ensure!(read as u64 == length, "incomplete hub response"); } Ok(body.trim().to_owned()) } fn response( method: &str, url: &str, body: Option<(&mut dyn Read, u64)>, content_type: Option<&str>, headers: &[(&str, &str)], timeout: Duration, ) -> Result<(BufReader, Option)> { let (https, host, port, path) = parse_url(url)?; let mut stream: Socket = if https { Box::new(connect_tls(&host, port, timeout)?) } else { Box::new(connect(&host, port, timeout)?) }; let mut req = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); for (k, v) in headers { anyhow::ensure!( v.bytes().all(|b| b.is_ascii_graphic() || b == b' '), "invalid HTTP header value" ); req.push_str(&format!("{k}: {v}\r\n")); } if let Some((_, len)) = &body { req.push_str(&format!("Content-Length: {len}\r\n")); if let Some(ct) = content_type { req.push_str(&format!("Content-Type: {ct}\r\n")); } } req.push_str("\r\n"); stream.write_all(req.as_bytes())?; if let Some((reader, len)) = body { anyhow::ensure!( std::io::copy(&mut reader.take(len), &mut stream)? == len, "incomplete upload" ); } stream.flush()?; let mut response = BufReader::new(stream); let mut line = String::new(); response.by_ref().take(16 * 1024).read_line(&mut line)?; let status = line .split_whitespace() .nth(1) .context("missing hub response status")? .parse::()?; anyhow::ensure!((200..300).contains(&status), "hub returned HTTP {status}"); let mut length = None; let mut header_bytes = 0; loop { line.clear(); let read = response.by_ref().take(16 * 1024).read_line(&mut line)?; header_bytes += read; anyhow::ensure!( read != 0 && header_bytes < 16 * 1024, "invalid hub response headers" ); if line == "\r\n" { break; } if let Some((name, value)) = line.split_once(':') { if name.eq_ignore_ascii_case("content-length") { length = Some(value.trim().parse()?); } } } Ok((response, if status == 204 { Some(0) } else { length })) } type Socket = Box; trait ReadWrite: Read + Write {} impl ReadWrite for T {} fn parse_url(url: &str) -> Result<(bool, String, u16, String)> { anyhow::ensure!( !url.bytes().any(|b| b.is_ascii_control() || b == b' '), "invalid hub URL" ); let (https, rest) = if let Some(rest) = url.strip_prefix("https://") { (true, rest) } else if let Some(rest) = url.strip_prefix("http://") { (false, rest) } else { anyhow::bail!("hub url must start with http:// or https://"); }; let (host_port, path) = rest.split_once('/').unwrap_or((rest, "")); anyhow::ensure!( !host_port.is_empty() && !host_port.contains(['@', '?', '#']), "invalid hub authority" ); let path = if path.is_empty() { "/".to_string() } else { format!("/{path}") }; let (host, port) = if let Some((host, port)) = host_port.split_once(':') { (host.to_string(), port.parse()?) } else { (host_port.to_string(), if https { 443 } else { 80 }) }; Ok((https, host, port, path)) } fn connect(host: &str, port: u16, timeout: Duration) -> Result { for address in (host, port).to_socket_addrs()? { if let Ok(socket) = TcpStream::connect_timeout(&address, Duration::from_secs(5)) { socket.set_read_timeout(Some(timeout))?; socket.set_write_timeout(Some(Duration::from_secs(30)))?; return Ok(socket); } } anyhow::bail!("could not connect to hub") } fn connect_tls( host: &str, port: u16, timeout: Duration, ) -> Result> { let _ = rustls::crypto::ring::default_provider().install_default(); let mut roots = RootCertStore::empty(); if let Some(ca) = std::env::var_os("TESSERA_WORMHOLE_CA") { for ca_cert in load_certs(std::path::Path::new(&ca))? { roots .add(ca_cert) .map_err(|error| anyhow::anyhow!("hub CA: {error}"))?; } } else { let native = rustls_native_certs::load_native_certs(); roots.add_parsable_certificates(native.certs); } anyhow::ensure!(!roots.is_empty(), "no trusted hub CA certificates"); let builder = ClientConfig::builder().with_root_certificates(roots); let client = match ( std::env::var_os("TESSERA_WORMHOLE_CLIENT_CERT"), std::env::var_os("TESSERA_WORMHOLE_CLIENT_KEY"), ) { (Some(cert), Some(key)) => builder .with_client_auth_cert( load_certs(std::path::Path::new(&cert))?, load_key(std::path::Path::new(&key))?, ) .map_err(|error| anyhow::anyhow!("client certificate: {error}"))?, (None, None) => builder.with_no_client_auth(), _ => anyhow::bail!("configure both Wormhole client certificate and key"), }; let name = ServerName::try_from(host.to_string()).context("hub hostname")?; let connection = ClientConnection::new(Arc::new(client), name)?; let tcp = connect(host, port, timeout)?; Ok(StreamOwned::new(connection, tcp)) } fn load_certs(path: &std::path::Path) -> Result>> { use rustls::pki_types::{pem::PemObject, CertificateDer}; CertificateDer::pem_file_iter(path) .with_context(|| format!("open {}", path.display()))? .collect::, _>>() .context("parse certificate") } fn load_key(path: &std::path::Path) -> Result> { use rustls::pki_types::{pem::PemObject, PrivateKeyDer}; PrivateKeyDer::from_pem_file(path).context("parse private key in client key file") } #[allow(dead_code)] pub type HeaderMap = HashMap;