//! One request, one response, over one socket. HTTP/1.1, `Connection: close`. //! //! Deliberately small: this client speaks to ONE server over routes it wrote //! itself. No redirects (this device knows exactly one server — the one it //! joined — and a server that answers "go elsewhere" is not it); no //! cookies (the credential is a signature in a header); compression ONLY where //! the caller asked for it and only on the way IN //! ([`Inflating`] — a snapshot is a SQLite file, which is mostly text and //! mostly empty pages and goes down about six to one, and four minutes of first //! sync was the price of the sentence that used to stand here); no connection //! reuse //! (`Connection: close` — a pooled socket is a lifetime and a half-closed peer //! to reason about, and the cost is one handshake per cycle, not per row). //! //! The head is parsed by `httparse` rather than by hand: this crate already //! links it under `tungstenite`, and a hand-rolled header split is exactly the //! kind of thing that is nearly right for a year. use std::io::{BufRead, BufReader, Read, Write}; use super::wire::Wire; /// The most a response head may be before the server is not answering this /// client at all. Sixty-four kilobytes is generous by two orders of magnitude /// for the routes here; what it stops is an endless read on a socket that has /// found something else to say. const MAX_HEAD_BYTES: usize = 64 * 1024; /// The most headers one response may carry. const MAX_HEADERS: usize = 64; /// A response's head, with the body still on the socket. pub struct Http1Response { pub status: u16, /// Lower-cased names, in the order they arrived. headers: Vec<(String, String)>, body: Body, } enum Body { /// `Content-Length` said how many. Sized { reader: BufReader, remaining: u64, }, /// `Transfer-Encoding: chunked`. Chunked { reader: BufReader, remaining: u64, done: bool, }, /// Neither, so the body ends when the connection does. ToClose { reader: BufReader }, /// A status that carries no body at all. Empty, } impl std::fmt::Debug for Http1Response { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Http1Response") .field("status", &self.status) .field("headers", &self.headers.len()) .finish_non_exhaustive() } } impl Http1Response { /// One header's value, matched case-insensitively. The first, if a server /// sent two. pub fn header(&self, name: &str) -> Option<&str> { let wanted = name.to_ascii_lowercase(); self.headers .iter() .find(|(key, _)| *key == wanted) .map(|(_, value)| value.as_str()) } /// What `Content-Length` promised, when it said anything. pub fn content_length(&self) -> Option { self.header("content-length") .and_then(|value| value.trim().parse().ok()) } /// Set the read timeout that governs the BODY. /// /// A request's ceiling and a snapshot's stall window are different numbers /// over the same socket: the caller says which one applies from here on. pub fn set_read_timeout(&self, timeout: std::time::Duration) -> std::io::Result<()> { match &self.body { Body::Sized { reader, .. } | Body::Chunked { reader, .. } | Body::ToClose { reader } => reader.get_ref().set_read_timeout(timeout), Body::Empty => Ok(()), } } } impl Http1Response { /// Move the call's deadline `by` later for the BODY still to come — a /// download whose size the head just declared ([`Wire::extend_deadline`]). pub fn extend_deadline(&self, by: std::time::Duration) { match &self.body { Body::Sized { reader, .. } | Body::Chunked { reader, .. } | Body::ToClose { reader } => reader.get_ref().extend_deadline(by), Body::Empty => {} } } } impl super::Answer for Http1Response { fn status(&self) -> u16 { self.status } fn header(&self, name: &str) -> Option { Http1Response::header(self, name).map(str::to_string) } fn content_length(&self) -> Option { Http1Response::content_length(self) } fn set_read_timeout(&mut self, timeout: std::time::Duration) -> std::io::Result<()> { Http1Response::set_read_timeout(self, timeout) } fn closer(&self) -> Option { match &self.body { Body::Sized { reader, .. } | Body::Chunked { reader, .. } | Body::ToClose { reader } => { reader.get_ref().closer() } Body::Empty => None, } } } impl Read for Http1Response { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match &mut self.body { Body::Empty => Ok(0), Body::ToClose { reader } => reader.read(buf), Body::Sized { reader, remaining } => { if *remaining == 0 { return Ok(0); } let want = buf .len() .min(usize::try_from(*remaining).unwrap_or(buf.len())); let read = reader.read(&mut buf[..want])?; if read == 0 { // The promise was not kept: fewer bytes than // `Content-Length` said. Loud, because for a snapshot that // is a truncated database. return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, format!("the connection ended {remaining} bytes before the answer did"), )); } *remaining -= read as u64; Ok(read) } Body::Chunked { reader, remaining, done, } => { if *done { return Ok(0); } if *remaining == 0 { let size = read_chunk_size(reader)?; if size == 0 { *done = true; return Ok(0); } *remaining = size; } let want = buf .len() .min(usize::try_from(*remaining).unwrap_or(buf.len())); let read = reader.read(&mut buf[..want])?; if read == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "the connection ended inside a chunk", )); } *remaining -= read as u64; if *remaining == 0 { // The CRLF that closes a chunk. let mut crlf = [0u8; 2]; reader.read_exact(&mut crlf)?; } Ok(read) } } } } /// A body being INFLATED AS IT IS READ, or passed straight through. /// /// The rule the snapshot download is built on is that a big body is a file and /// never a buffer, and that rule does not stop being true because the bytes /// arrived compressed: `flate2`'s reader decoder pulls from the socket in its /// own small window and hands back plaintext, so the caller's 64 KiB loop is /// unchanged and nothing ever holds a database. /// /// It wraps the WHOLE answer rather than living inside [`Body`] because the /// head has to be read first — `Content-Encoding` says whether to inflate at /// all, `X-Cotton-Snapshot-Bytes` says how big the file will be, and the stall /// window is armed on the socket — and all three of those are questions for /// `Http1Response`, which this then consumes. pub enum Inflating { Plain(R), /// Boxed because `GzDecoder` carries its own window and this enum is /// otherwise the size of a socket. Gzip(Box>), } impl Inflating { /// Wrap `reader`, inflating when `gzipped`. pub fn new(reader: R, gzipped: bool) -> Inflating { if gzipped { Inflating::Gzip(Box::new(flate2::read::GzDecoder::new(reader))) } else { Inflating::Plain(reader) } } /// Does this header value name gzip? /// /// `identity`, an absent header and anything else are all "no": this client /// asks for exactly one coding and a server answering with a second one is /// not something to guess at. pub fn is_gzip(content_encoding: Option<&str>) -> bool { content_encoding.is_some_and(|value| value.trim().eq_ignore_ascii_case("gzip")) } } impl Read for Inflating { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { match self { Inflating::Plain(reader) => reader.read(buf), Inflating::Gzip(decoder) => decoder.read(buf), } } } fn read_chunk_size(reader: &mut BufReader) -> std::io::Result { let mut line = String::new(); reader.read_line(&mut line)?; // A chunk extension (`;name=value`) is legal and nothing here reads one. let head = line.trim().split(';').next().unwrap_or("").trim(); u64::from_str_radix(head, 16) .map_err(|_| std::io::Error::other(format!("{head:?} is not a chunk size"))) } /// What goes out. #[derive(Debug, Clone)] pub struct Http1Request<'a> { pub method: &'a str, /// Path plus query, exactly as it is signed. pub path: &'a str, /// The `Host` header's value. pub authority: &'a str, pub headers: Vec<(String, String)>, pub body: Option<&'a [u8]>, } /// How much of a streamed body is written per turn. /// /// The snapshot download's own number, for the mirror reason: a media upload is /// routinely tens of megabytes and may be a hundred, and the rule that a big /// body is a FILE is the same rule going up as coming down. const UPLOAD_CHUNK_BYTES: usize = 64 * 1024; /// Write the request and read the head. The body stays on the socket. pub fn send(wire: Wire, request: &Http1Request<'_>) -> std::io::Result { send_body(wire, request, None) } /// The same request with its body STREAMED off a reader rather than held. /// /// The way UP for bytes, and it exists for the reason a whole file is streamed /// to disk on the way down: a 100 MB video read into a `Vec` to be written to a /// socket is the jetsam kill build 106 already paid for, spelled backwards. /// `length` is what `Content-Length` promises and what the presigned signature /// may have been minted over, so it is the caller's — read off the file's own /// metadata — and the copy stops there even if the reader has more to give. /// /// `request.body` must be `None`: two bodies is a request nobody can read. pub fn send_stream( wire: Wire, request: &Http1Request<'_>, body: &mut dyn Read, length: u64, ) -> std::io::Result { debug_assert!( request.body.is_none(), "a streamed request carries its body on the reader, not in the request" ); send_body(wire, request, Some((body, length))) } fn send_body( mut wire: Wire, request: &Http1Request<'_>, streamed: Option<(&mut dyn Read, u64)>, ) -> std::io::Result { let mut head = format!( "{} {} HTTP/1.1\r\nHost: {}\r\nConnection: close\r\nAccept: */*\r\n", request.method, request.path, request.authority ); for (name, value) in &request.headers { head.push_str(name); head.push_str(": "); head.push_str(value); head.push_str("\r\n"); } // ALWAYS, including for a bodyless POST: a request with no // `Content-Length` and no `Transfer-Encoding` is one the server may read // as having no body at all, and the signature already committed to the // empty hash. if request.method != "GET" && request.method != "HEAD" { head.push_str(&format!( "Content-Length: {}\r\n", match &streamed { Some((_, length)) => *length, None => request.body.map(<[u8]>::len).unwrap_or(0) as u64, } )); } head.push_str("\r\n"); wire.write_all(head.as_bytes())?; if let Some(body) = request.body { wire.write_all(body)?; } if let Some((reader, length)) = streamed { let mut buffer = vec![0u8; UPLOAD_CHUNK_BYTES]; let mut written = 0u64; while written < length { let want = usize::try_from(length - written) .unwrap_or(UPLOAD_CHUNK_BYTES) .min(UPLOAD_CHUNK_BYTES); let read = reader.read(&mut buffer[..want])?; if read == 0 { // The promise in `Content-Length` cannot be kept. Loud, and // before the server reads a truncated object as a whole one. return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, format!("the file ended {} bytes before its length did", length - written), )); } wire.write_all(&buffer[..read])?; written += read as u64; } } wire.flush()?; let mut reader = BufReader::new(wire); let mut raw: Vec = Vec::with_capacity(1024); let (status, headers) = loop { let read = reader.read_until(b'\n', &mut raw)?; if read == 0 { return Err(std::io::Error::new( std::io::ErrorKind::UnexpectedEof, "the server closed the connection without answering", )); } if raw.len() > MAX_HEAD_BYTES { return Err(std::io::Error::other( "the server's answer head is longer than any answer this client asked for", )); } let mut slots = [httparse::EMPTY_HEADER; MAX_HEADERS]; let mut parsed = httparse::Response::new(&mut slots); match parsed.parse(&raw) { Ok(httparse::Status::Complete(_)) => { let status = parsed.code.ok_or_else(|| { std::io::Error::other("the server's answer carried no status") })?; let headers: Vec<(String, String)> = parsed .headers .iter() .map(|header| { ( header.name.to_ascii_lowercase(), String::from_utf8_lossy(header.value).trim().to_string(), ) }) .collect(); break (status, headers); } Ok(httparse::Status::Partial) => continue, Err(error) => { return Err(std::io::Error::other(format!( "the server's answer is not HTTP ({error})" ))) } } }; let find = |name: &str| -> Option<&str> { headers .iter() .find(|(key, _)| key == name) .map(|(_, value)| value.as_str()) }; // 204 and 304 carry no body whatever their headers say, and a HEAD's // answer describes a body it does not send. let bodyless = status == 204 || status == 304 || request.method == "HEAD"; let chunked = find("transfer-encoding") .is_some_and(|value| value.to_ascii_lowercase().contains("chunked")); let length: Option = find("content-length").and_then(|value| value.trim().parse().ok()); let body = if bodyless { Body::Empty } else if chunked { Body::Chunked { reader, remaining: 0, done: false, } } else if let Some(remaining) = length { Body::Sized { reader, remaining } } else { Body::ToClose { reader } }; Ok(Http1Response { status, headers, body, }) } #[cfg(test)] #[path = "http1_tests.rs"] mod tests;