// 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/. //! Clients the phase 2 tests need: raw request bytes over TLS (for paths a URI type refuses, //! like backslashes), a keep-alive HTTP/1.1 connection that is reused across requests, and //! JSON over a Unix socket (edge's admin socket) or loopback TCP (the control API). use std::io; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use bytes::Bytes; use http_body_util::{BodyExt, Full}; use hyper_util::rt::TokioIo; use rustls::RootCertStore; use rustls_pki_types::ServerName; use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::net::TcpStream; use crate::client::{Req, Resp, tls_connector}; const TIMEOUT: Duration = Duration::from_secs(15); fn other(e: impl std::fmt::Display) -> io::Error { io::Error::other(e.to_string()) } /// Parse a complete HTTP/1.1 response (Content-Length, chunked or read-to-close). pub fn parse_response(raw: &[u8]) -> io::Result { let end = raw .windows(4) .position(|w| w == b"\r\n\r\n") .ok_or_else(|| other("no complete response head"))?; let head = String::from_utf8_lossy(&raw[..end]).into_owned(); let mut lines = head.split("\r\n"); let status_line = lines.next().unwrap_or_default(); let status: u16 = status_line .split(' ') .nth(1) .and_then(|s| s.parse().ok()) .ok_or_else(|| other(format!("bad status line {status_line:?}")))?; let headers: Vec<(String, String)> = lines .filter_map(|l| l.split_once(':')) .map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned())) .collect(); let mut body = raw[end + 4..].to_vec(); if headers .iter() .any(|(n, v)| n == "transfer-encoding" && v.eq_ignore_ascii_case("chunked")) { let mut out = Vec::new(); let mut rest = &body[..]; while let Some(p) = rest.windows(2).position(|w| w == b"\r\n") { let size = usize::from_str_radix( String::from_utf8_lossy(&rest[..p]) .split(';') .next() .unwrap_or("0") .trim(), 16, ) .map_err(other)?; rest = &rest[p + 2..]; if size == 0 || rest.len() < size { break; } out.extend_from_slice(&rest[..size]); rest = &rest[(size + 2).min(rest.len())..]; } body = out; } else if let Some(len) = headers .iter() .find(|(n, _)| n == "content-length") .and_then(|(_, v)| v.parse::().ok()) { body.truncate(len); } Ok(Resp { status, headers, body, }) } /// Send `request` (complete raw bytes, which should ask for `Connection: close`) over a fresh /// TLS connection and read until the server closes. pub async fn https_raw( addr: SocketAddr, sni: &str, roots: Arc, request: &[u8], ) -> io::Result { tokio::time::timeout(TIMEOUT, async { let tcp = TcpStream::connect(addr).await?; let name = ServerName::try_from(sni.to_owned()).map_err(other)?; let mut s = tls_connector(roots).connect(name, tcp).await?; s.write_all(request).await?; let mut buf = Vec::new(); // A close_notify-less close is fine here. let _ = s.read_to_end(&mut buf).await; parse_response(&buf) }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } /// One HTTP/1.1 connection over TLS, reused for every request until it fails. pub struct KeepAlive { sender: hyper::client::conn::http1::SendRequest>, } impl KeepAlive { pub async fn connect( addr: SocketAddr, sni: &str, roots: Arc, ) -> io::Result { let tcp = TcpStream::connect(addr).await?; tcp.set_nodelay(true)?; let name = ServerName::try_from(sni.to_owned()).map_err(other)?; let s = tls_connector(roots).connect(name, tcp).await?; let (sender, conn) = hyper::client::conn::http1::handshake(TokioIo::new(s)) .await .map_err(other)?; tokio::spawn(async move { let _ = conn.await; }); Ok(KeepAlive { sender }) } /// Send one request on this connection. An `Err` means the connection is gone. pub async fn send(&mut self, req: &Req) -> io::Result { self.sender.ready().await.map_err(other)?; 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 = tokio::time::timeout(TIMEOUT, self.sender.send_request(request)) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? .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, }) } } /// A JSON answer: status and parsed body (`Null` when the body is empty or not JSON). #[derive(Debug, Clone)] pub struct JsonResp { pub status: u16, pub headers: Vec<(String, String)>, pub json: serde_json::Value, pub text: String, /// The raw body (for binary answers). pub body: Vec, } impl JsonResp { pub fn header(&self, name: &str) -> Option<&str> { self.headers .iter() .find(|(n, _)| n.eq_ignore_ascii_case(name)) .map(|(_, v)| v.as_str()) } } fn json_resp(r: Resp) -> JsonResp { let text = String::from_utf8_lossy(&r.body).into_owned(); JsonResp { status: r.status, headers: r.headers, json: serde_json::from_str(&text).unwrap_or(serde_json::Value::Null), text, body: r.body, } } fn raw_request( method: &str, path: &str, host: &str, headers: &[(&str, &str)], body: Option<&serde_json::Value>, ) -> Vec { let body = body.map(|b| b.to_string()).unwrap_or_default(); let mut out = format!("{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n"); for (n, v) in headers { out.push_str(&format!("{n}: {v}\r\n")); } if !body.is_empty() || method != "GET" { out.push_str("Content-Type: application/json\r\n"); out.push_str(&format!("Content-Length: {}\r\n", body.len())); } out.push_str("\r\n"); out.push_str(&body); out.into_bytes() } /// A request over a Unix socket (edge's admin socket). #[cfg(unix)] pub async fn unix_json( socket: &std::path::Path, method: &str, path: &str, body: Option<&serde_json::Value>, ) -> io::Result { tokio::time::timeout(TIMEOUT, async { let mut s = tokio::net::UnixStream::connect(socket).await?; s.write_all(&raw_request(method, path, "localhost", &[], body)) .await?; let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; parse_response(&buf).map(json_resp) }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } /// A request over plain TCP (the control API on loopback), with extra headers. pub async fn tcp_json( addr: SocketAddr, method: &str, path: &str, headers: &[(&str, &str)], body: Option<&serde_json::Value>, ) -> io::Result { tokio::time::timeout(Duration::from_secs(120), async { let mut s = TcpStream::connect(addr).await?; s.write_all(&raw_request(method, path, &addr.to_string(), headers, body)) .await?; let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; parse_response(&buf).map(json_resp) }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? } /// Send raw bytes over plain TCP and parse the answer (for malformed requests). pub async fn tcp_raw(addr: SocketAddr, request: &[u8]) -> io::Result { tokio::time::timeout(TIMEOUT, async { let mut s = TcpStream::connect(addr).await?; s.write_all(request).await?; let mut buf = Vec::new(); s.read_to_end(&mut buf).await?; parse_response(&buf) }) .await .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))? }