// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. //! Minimal HTTP/1.1 clients (plain, TLS with SNI, websocket) that send exactly the headers //! they are given, so both engines see byte-identical requests. use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use bytes::Bytes; use futures_util::{SinkExt, StreamExt}; use http_body_util::{BodyExt, Full}; use hyper_util::rt::TokioIo; use rustls::RootCertStore; use rustls_pki_types::ServerName; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::TcpStream; use tokio_rustls::TlsConnector; use tokio_tungstenite::tungstenite; use tokio_tungstenite::tungstenite::client::IntoClientRequest; #[derive(Debug, Clone, Default)] pub struct Req { pub method: String, pub path: String, /// Sent in this order; include `host` yourself. pub headers: Vec<(String, String)>, pub body: Vec, } impl Req { pub fn get(host: &str, path: &str) -> Req { Req::new("GET", host, path) } pub fn new(method: &str, host: &str, path: &str) -> Req { Req { method: method.into(), path: path.into(), headers: vec![("host".into(), host.into())], body: Vec::new(), } } pub fn header(mut self, name: &str, value: &str) -> Req { self.headers.push((name.into(), value.into())); self } pub fn body(mut self, body: &[u8]) -> Req { self.body = body.to_vec(); self } } #[derive(Debug, Clone, PartialEq, Eq)] pub struct Resp { pub status: u16, /// Lowercase names, in received order. pub headers: Vec<(String, String)>, pub body: Vec, } impl Resp { pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|(n, _)| n.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_str()) } pub fn header_all(&self, name: &str) -> Vec<&str> { self.headers .iter() .filter(|(n, _)| n.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_str()) .collect() } pub fn text(&self) -> String { String::from_utf8_lossy(&self.body).into_owned() } } const TIMEOUT: Duration = Duration::from_secs(15); fn other(e: impl std::fmt::Display) -> io::Error { io::Error::other(e.to_string()) } pub fn tls_connector(roots: Arc) -> TlsConnector { crate::tls::install_crypto(); let mut cfg = rustls::ClientConfig::builder() .with_root_certificates(roots) .with_no_client_auth(); cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; TlsConnector::from(Arc::new(cfg)) } async fn tls_stream( addr: SocketAddr, sni: &str, roots: Arc, ) -> io::Result> { let tcp = TcpStream::connect(addr).await?; let name = ServerName::try_from(sni.to_owned()).map_err(other)?; tls_connector(roots).connect(name, tcp).await } async fn send( io: S, req: &Req, ) -> io::Result { let (mut sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(io)) .await .map_err(other)?; tokio::spawn(async move { let _ = conn.await; }); let mut b = hyper::Request::builder() .method(req.method.as_str()) .uri(req.path.as_str()); for (n, v) in &req.headers { b = b.header(n.as_str(), v.as_str()); } let request = b .body(Full::new(Bytes::from(req.body.clone()))) .map_err(other)?; let resp = sender.send_request(request).await.map_err(other)?; let status = resp.status().as_u16(); let headers = resp .headers() .iter() .map(|(n, v)| { ( n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned(), ) }) .collect(); let body = resp .into_body() .collect() .await .map_err(other)? .to_bytes() .to_vec(); Ok(Resp { status, headers, body, }) } /// One request over a fresh TLS connection to `addr` with the given SNI. pub async fn https( addr: SocketAddr, sni: &str, roots: Arc, req: &Req, ) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = tls_stream(addr, sni, roots).await?; send(s, req).await }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } /// One request over a fresh plain TCP connection. pub async fn http(addr: SocketAddr, req: &Req) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = TcpStream::connect(addr).await?; send(s, req).await }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } #[derive(Debug, Clone, PartialEq, Eq)] pub enum WsOutcome { /// 101, the echoed message. Upgraded { status: u16, headers: Vec<(String, String)>, echo: String, }, /// The upgrade was answered with a normal HTTP response. Refused(Resp), } /// Open a websocket over TLS, send `message`, return the echo (or the refusal). pub async fn websocket( addr: SocketAddr, sni: &str, roots: Arc, host: &str, path: &str, extra: &[(&str, &str)], message: &str, ) -> io::Result { tokio::time::timeout(TIMEOUT, async { let s = tls_stream(addr, sni, roots).await?; let mut request = format!("wss://{host}{path}") .into_client_request() .map_err(other)?; for (n, v) in extra { request.headers_mut().insert( http::HeaderName::from_bytes(n.as_bytes()).map_err(other)?, http::HeaderValue::from_str(v).map_err(other)?, ); } match tokio_tungstenite::client_async(request, s).await { Ok((mut ws, resp)) => { let status = resp.status().as_u16(); let headers = resp .headers() .iter() .map(|(n, v)| { ( n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned(), ) }) .collect(); ws.send(tungstenite::Message::text(message)) .await .map_err(other)?; let echo = match ws.next().await { Some(Ok(m)) => m.into_text().map_err(other)?.to_string(), other_msg => return Err(other(format!("no echo: {other_msg:?}"))), }; let _ = ws.close(None).await; Ok(WsOutcome::Upgraded { status, headers, echo, }) } Err(tungstenite::Error::Http(resp)) => { let status = resp.status().as_u16(); let headers = resp .headers() .iter() .map(|(n, v)| { ( n.as_str().to_owned(), String::from_utf8_lossy(v.as_bytes()).into_owned(), ) }) .collect(); let body = resp.body().clone().unwrap_or_default(); Ok(WsOutcome::Refused(Resp { status, headers, body, })) } Err(e) => Err(other(e)), } }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "websocket timed out"))? } /// A client identity for mTLS: a PEM chain (leaf first) and its PEM private key. #[derive(Debug, Clone)] pub struct ClientCert { pub chain_pem: String, pub key_pem: String, /// Offer only TLS 1.2 (client certificates take a different path there). pub tls12_only: bool, } /// One request over a fresh TLS connection that presents `cert` if the server asks for one. pub async fn https_with_cert( addr: SocketAddr, sni: &str, roots: Arc, cert: &ClientCert, req: &Req, ) -> io::Result { use rustls_pki_types::pem::PemObject; use rustls_pki_types::{CertificateDer, PrivateKeyDer}; crate::tls::install_crypto(); let chain: Vec> = CertificateDer::pem_slice_iter(cert.chain_pem.as_bytes()) .collect::>() .map_err(other)?; let key = PrivateKeyDer::from_pem_slice(cert.key_pem.as_bytes()).map_err(other)?; let versions: &[&rustls::SupportedProtocolVersion] = if cert.tls12_only { &[&rustls::version::TLS12] } else { rustls::DEFAULT_VERSIONS }; let mut cfg = rustls::ClientConfig::builder_with_protocol_versions(versions) .with_root_certificates(roots) .with_client_auth_cert(chain, key) .map_err(other)?; cfg.alpn_protocols = vec![b"http/1.1".to_vec()]; let connector = TlsConnector::from(Arc::new(cfg)); tokio::time::timeout(TIMEOUT, async { let tcp = TcpStream::connect(addr).await?; let name = ServerName::try_from(sni.to_owned()).map_err(other)?; let s = connector.connect(name, tcp).await?; send(s, req).await }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? }