Cotton code
546 lines · 21.4 KB · RustRaw
//! The socket under every request: an origin, a connection, and the two//! timeouts that make a hang impossible.//!//! **Why this crate dials its own socket instead of taking an HTTP client.**//! Two of this lane's rules are about the SOCKET, not about a request://!//! * [`super::REQUEST_CEILING_MS`] — sixty seconds, because on 2026-09-07 one//!   `GET /v1/sync/pull` never settled and a phone stopped syncing for//!   thirty-three minutes with no error anywhere. A ceiling on a future is a//!   ceiling on the WAIT; a ceiling on the socket is a ceiling on the hang.//! * a STALL — sixty seconds WITHOUT A BYTE, restarted on every//!   byte. No HTTP client offers that: what they offer is a whole-body//!   timeout, which is the wrong shape for a four-hundred-megabyte file on a//!   slow train.//!//! A read timeout on the socket is exactly both of those, and it is one line.//!//! **A CEILING IS A DEADLINE FOR THE WHOLE CALL, never a timeout per read.** A//! socket's own timeout restarts on every syscall, so a host that trickles a//! byte a second — through a TLS handshake, a response head or a body — resets//! it for ever and the "sixty-second" ceiling never trips. So a call computes//! ONE deadline when it starts ([`dial_by`]), and every step of it waits only//! for what is LEFT: the name lookup, each connect attempt, every read and//! write of the handshake and the exchange ([`Timed`]). A step that finds//! nothing left fails with [`DEADLINE_PASSED`]. The stall window is the one//! deliberate exception, and a caller asks for it by name//! ([`Wire::set_read_timeout`]).//!//! Apple uses Security.framework through `native-tls`. Other targets use//! rustls with bundled Mozilla roots. Both verify the server's certificate and//! hostname before returning a stream, and neither falls back to plaintext.use std::io::{Read, Write};use std::net::{SocketAddr, TcpStream};use std::sync::Mutex;use std::time::{Duration, Instant};/// What a step that found its call's deadline already passed says.pub const DEADLINE_PASSED: &str = "the time this call waits ran out";#[cfg(not(any(target_os = "ios", target_os = "macos")))]#[path = "wire_tls.rs"]mod tls;/// A server address, split into what a socket needs.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Origin {    /// The origin as it is signed and stored — scheme, host, optional port, no    /// trailing slash.    pub text: String,    pub secure: bool,    /// The host as the `Host` header carries it and TLS verifies it — no    /// brackets around an IPv6 literal.    pub host: String,    pub port: u16,}impl Origin {    /// Split an origin `normalize_server_url` has already accepted.    ///    /// It re-parses rather than trusting a caller: this is the last place    /// before a socket, and a host that reached here unchecked would be a    /// connection to somewhere nobody named.    pub fn parse(origin: &str) -> Result<Origin, String> {        let parsed = url::Url::parse(origin).map_err(|_| format!("{origin} is not an address"))?;        let secure = match parsed.scheme() {            "https" => true,            "http" => false,            other => return Err(format!("{other}:// is not an address this client dials")),        };        // `Url::host_str` keeps the brackets round an IPv6 literal. The BARE        // host is what TLS verifies and what a socket address takes, so they        // come off here and go back on in `authority`.        let host = parsed            .host_str()            .ok_or_else(|| format!("{origin} names no host"))?            .trim_start_matches('[')            .trim_end_matches(']')            .to_string();        let port = parsed.port().unwrap_or(if secure { 443 } else { 80 });        Ok(Origin {            text: super::address::trim_slashes(origin),            secure,            host,            port,        })    }    /// What the `Host` header says: the authority, with a non-default port.    pub fn authority(&self) -> String {        let default = if self.secure { 443 } else { 80 };        let bracketed = if self.host.contains(':') {            format!("[{}]", self.host)        } else {            self.host.clone()        };        if self.port == default {            bracketed        } else {            format!("{bracketed}:{}", self.port)        }    }    fn socket_authority(&self) -> String {        if self.host.contains(':') {            format!("[{}]:{}", self.host, self.port)        } else {            format!("{}:{}", self.host, self.port)        }    }}/// The TCP socket under a [`Wire`], and the deadline its next read or write/// waits under.////// **TLS RUNS OVER THIS, not over the bare socket**, so the deadline reaches/// every syscall of the handshake too: a server that answers a ClientHello one/// byte at a time would otherwise hold a dial for as long as it cared to, each/// byte restarting the socket's own timeout.pub struct Timed {    socket: TcpStream,    /// `Some` while the call has a deadline: every read and write first sets the    /// socket's timeout to the time LEFT. `None` once a caller asked for    /// per-read windows instead, and then the socket's own timeouts stand.    until: Mutex<Option<Instant>>,}impl std::fmt::Debug for Timed {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str("Timed")    }}/// The time left before `deadline`, or `None` when there is none.fn left(deadline: Instant) -> Option<Duration> {    Some(deadline.saturating_duration_since(Instant::now())).filter(|left| !left.is_zero())}fn passed() -> std::io::Error {    std::io::Error::new(std::io::ErrorKind::TimedOut, DEADLINE_PASSED)}impl Timed {    fn new(socket: TcpStream, deadline: Instant) -> Timed {        Timed {            socket,            until: Mutex::new(Some(deadline)),        }    }    fn deadline(&self) -> Option<Instant> {        *self.until.lock().unwrap_or_else(|e| e.into_inner())    }    /// Before one syscall: the time left, on the socket, or the refusal.    fn arm(        &self,        set: impl Fn(&TcpStream, Option<Duration>) -> std::io::Result<()>,    ) -> std::io::Result<Option<Instant>> {        let Some(deadline) = self.deadline() else {            return Ok(None);        };        let remaining = left(deadline).ok_or_else(passed)?;        set(&self.socket, Some(remaining))?;        Ok(Some(deadline))    }    /// After one syscall that failed: a socket timeout AT the deadline is the    /// deadline, and says so rather than "resource temporarily unavailable".    fn named(error: std::io::Error, deadline: Option<Instant>) -> std::io::Error {        let timed_out = matches!(            error.kind(),            std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut        );        match deadline {            Some(deadline) if timed_out && left(deadline).is_none() => passed(),            _ => error,        }    }}impl Read for Timed {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        let deadline = self.arm(TcpStream::set_read_timeout)?;        self.socket            .read(buf)            .map_err(|error| Timed::named(error, deadline))    }}impl Write for Timed {    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {        let deadline = self.arm(TcpStream::set_write_timeout)?;        self.socket            .write(buf)            .map_err(|error| Timed::named(error, deadline))    }    fn flush(&mut self) -> std::io::Result<()> {        self.socket.flush()    }}/// One connection, plaintext or wrapped.////// An enum rather than a `Box<dyn Read + Write>` so the WebSocket can take the/// same value: `tungstenite` handshakes over anything that is `Read + Write`,/// and the socket it gets is the one this module dialled and timed.pub enum Wire {    Plain(Timed),    #[cfg(any(target_os = "ios", target_os = "macos"))]    Tls(Box<native_tls::TlsStream<Timed>>),    #[cfg(not(any(target_os = "ios", target_os = "macos")))]    Tls(Box<rustls::StreamOwned<rustls::ClientConnection, Timed>>),}impl std::fmt::Debug for Wire {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        match self {            Wire::Plain(_) => f.write_str("Wire::Plain"),            Wire::Tls(_) => f.write_str("Wire::Tls"),        }    }}impl Wire {    fn timed(&self) -> &Timed {        match self {            Wire::Plain(stream) => stream,            #[cfg(any(target_os = "ios", target_os = "macos"))]            Wire::Tls(stream) => stream.get_ref(),            #[cfg(not(any(target_os = "ios", target_os = "macos")))]            Wire::Tls(stream) => &stream.sock,        }    }    /// How long ONE read may block before it is a failure — and the end of    /// the call's deadline on this wire.    ///    /// **THE STALL WINDOW, ASKED FOR BY NAME.** A request's deadline covers    /// the whole call; a snapshot's body is a whole database on a slow train,    /// and what bounds it is sixty seconds WITHOUT A BYTE, restarted on every    /// byte. A caller that wants the second shape says so here, and from here    /// on reads wait `timeout` each. Writes keep the timeout they had.    pub fn set_read_timeout(&self, timeout: Duration) -> std::io::Result<()> {        let timed = self.timed();        *timed.until.lock().unwrap_or_else(|e| e.into_inner()) = None;        timed.socket.set_read_timeout(Some(timeout))    }    /// The call's deadline moved `by` later — for a body whose size is known    /// only once its head has arrived (a download's `Content-Length`), which    /// buys the time a body of that size takes ([`super::body_allowance`]). A    /// wire already on per-read windows has no deadline to move.    pub fn extend_deadline(&self, by: Duration) {        let mut until = self.timed().until.lock().unwrap_or_else(|e| e.into_inner());        if let Some(deadline) = *until {            *until = Some(deadline.checked_add(by).unwrap_or(deadline));        }    }    /// Per-syscall windows of `window` for reads AND writes from here on —    /// the shape a long-lived stream (a WebSocket, a streamed upload) wants    /// once its dial is done.    fn windows(self, window: Duration) -> std::io::Result<Wire> {        let timed = self.timed();        *timed.until.lock().unwrap_or_else(|e| e.into_inner()) = None;        timed.socket.set_read_timeout(Some(window))?;        timed.socket.set_write_timeout(Some(window))?;        Ok(self)    }    pub fn shutdown(&self) {        let _ = self.timed().socket.shutdown(std::net::Shutdown::Both);    }    /// What shuts this socket from another thread; `None` when the socket    /// cannot be shared.    pub fn closer(&self) -> Option<super::records_first::Closer> {        let socket = self.timed().socket.try_clone().ok()?;        Some(Box::new(move || {            let _ = socket.shutdown(std::net::Shutdown::Both);        }))    }}impl Read for Wire {    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {        match self {            Wire::Plain(stream) => stream.read(buf),            Wire::Tls(stream) => stream.read(buf),        }    }}impl Write for Wire {    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {        match self {            Wire::Plain(stream) => stream.write(buf),            Wire::Tls(stream) => stream.write(buf),        }    }    fn flush(&mut self) -> std::io::Result<()> {        match self {            Wire::Plain(stream) => stream.flush(),            Wire::Tls(stream) => stream.flush(),        }    }}/// Dial an origin: the lookup, the connection and the handshake under ONE/// deadline of `timeout`, and then per-syscall windows of `timeout` on the/// socket for whatever the caller streams over it.////// The shape a WebSocket and a streamed upload want: the DIAL is bounded as a/// whole, and what follows is theirs to time. A request/answer exchange wants/// its deadline to run on through the answer, and takes [`dial_by`].pub fn dial(origin: &Origin, timeout: Duration) -> Result<Wire, String> {    dial_by(origin, Instant::now() + timeout)?        .windows(timeout)        .map_err(|error| format!("{} could not be timed ({error})", origin.text))}/// A DEVELOPER'S NETWORK CUT (`developer.cutNetwork`, Cotton Dev only): while/// set, every dial fails as a phone with no network does, so a walk on a/// simulator — which has no airplane mode — can watch the app say it cannot/// reach Cotton and keep trying, and come back when it is lifted.pub static CUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// What a dial says while [`CUT`] holds.pub const CUT_SAID: &str = "the network is off on this device";/// `now + within`, or as far as an `Instant` reaches when that is further —/// a deadline sized to a huge body must not panic the caller on overflow.pub fn deadline_in(within: Duration) -> Instant {    let now = Instant::now();    now.checked_add(within)        .unwrap_or_else(|| now + Duration::from_secs(u64::from(u32::MAX)))}/// Dial an origin under a deadline, and leave that deadline ARMED on the wire:/// every read and write the caller makes waits only for what is left of it.pub fn dial_by(origin: &Origin, deadline: Instant) -> Result<Wire, String> {    cotton_store::held::must_not_wait("a dial to another machine");    if CUT.load(std::sync::atomic::Ordering::SeqCst) {        return Err(format!("{} could not be reached ({CUT_SAID})", origin.text));    }    let out_of_time = || format!("{} could not be reached ({DEADLINE_PASSED})", origin.text);    let addresses: Vec<SocketAddr> = resolve(origin, deadline)?;    let Some(first) = addresses.first() else {        return Err(format!("{} resolved to no address", origin.text));    };    // Every candidate, in the order the resolver gave them: a host with an    // AAAA record on a network with no IPv6 route answers the first address    // and nothing else, which reads as "the server is down". Each attempt    // waits for what is LEFT of the deadline, never the whole of it again —    // three dead addresses are one deadline, not three.    let mut last: Option<std::io::Error> = None;    let mut stream: Option<TcpStream> = None;    for address in &addresses {        let Some(remaining) = left(deadline) else {            return Err(out_of_time());        };        match TcpStream::connect_timeout(address, remaining) {            Ok(open) => {                stream = Some(open);                break;            }            Err(error) => last = Some(error),        }    }    let stream = match stream {        Some(stream) => stream,        None if left(deadline).is_none() => return Err(out_of_time()),        None => {            let error = last                .unwrap_or_else(|| std::io::Error::other(format!("{first} could not be reached")));            return Err(format!("{} could not be reached ({error})", origin.text));        }    };    // Nagle off: every request this client sends is one small write followed by    // a read, which is the exact shape Nagle delays by up to 40 ms.    let _ = stream.set_nodelay(true);    let timed = Timed::new(stream, deadline);    if !origin.secure {        return Ok(Wire::Plain(timed));    }    #[cfg(any(target_os = "ios", target_os = "macos"))]    {        let connector = native_tls::TlsConnector::new()            .map_err(|error| format!("this device's TLS could not start ({error})"))?;        let tls = connector.connect(&origin.host, timed).map_err(|error| {            if left(deadline).is_none() {                out_of_time()            } else {                format!("{} could not be trusted ({error})", origin.text)            }        })?;        Ok(Wire::Tls(Box::new(tls)))    }    #[cfg(not(any(target_os = "ios", target_os = "macos")))]    {        tls::connect(origin, timed, tls::config(tls::roots())?).map_err(|error| {            if left(deadline).is_none() {                out_of_time()            } else {                error            }        })    }}/// The name, looked up under the deadline — THE ONE place this crate asks the/// operating system's resolver (`fetch_deadline_lint_tests.rs` in/// `cotton-server` holds that).////// `to_socket_addrs` has no timeout of its own and `getaddrinfo` cannot be/// cancelled, so the lookup runs on its own thread and this waits for its/// answer for what is left of the deadline. A lookup past it is ABANDONED/// rather than stopped: the thread finishes whenever the resolver lets it, and/// the call has already failed.pub(crate) fn resolve(origin: &Origin, deadline: Instant) -> Result<Vec<SocketAddr>, String> {    // An address needs no resolver, and a thread for one would be a thread    // for nothing.    if let Ok(address) = origin.host.parse::<std::net::IpAddr>() {        return Ok(vec![SocketAddr::new(address, origin.port)]);    }    let authority = origin.socket_authority();    let (answer, answered) = std::sync::mpsc::channel();    std::thread::Builder::new()        .name("cotton-resolve".to_string())        .spawn(move || {            use std::net::ToSocketAddrs;            let _ = answer.send(                authority                    .to_socket_addrs()                    .map(|found| found.collect::<Vec<_>>()),            );        })        .map_err(|error| format!("{} could not be looked up ({error})", origin.text))?;    let Some(remaining) = left(deadline) else {        return Err(format!(            "{} could not be resolved ({DEADLINE_PASSED})",            origin.text        ));    };    match answered.recv_timeout(remaining) {        Ok(Ok(addresses)) => Ok(addresses),        Ok(Err(error)) => Err(format!("{} could not be resolved ({error})", origin.text)),        Err(_) => Err(format!(            "{} could not be resolved ({DEADLINE_PASSED})",            origin.text        )),    }}#[cfg(test)]mod tests {    use super::*;    use crate::transport::scripted::{finishes, trickling};    #[test]    fn an_origin_splits_into_what_a_socket_needs() {        let https = Origin::parse("https://studio.relay.cottondb.com").expect("an origin");        assert!(https.secure);        assert_eq!(https.host, "studio.relay.cottondb.com");        assert_eq!(https.port, 443);        assert_eq!(https.authority(), "studio.relay.cottondb.com");        let local = Origin::parse("http://127.0.0.1:8790").expect("an origin");        assert!(!local.secure);        assert_eq!(local.port, 8790);        assert_eq!(local.authority(), "127.0.0.1:8790");    }    #[test]    fn an_ipv6_literal_keeps_its_brackets_in_the_host_header_and_nowhere_else() {        let origin = Origin::parse("http://[::1]:8790").expect("an origin");        assert_eq!(origin.host, "::1", "TLS verifies the bare host");        assert_eq!(origin.authority(), "[::1]:8790");    }    #[test]    fn a_scheme_this_client_does_not_dial_is_refused_by_name() {        let error = Origin::parse("ftp://example.invalid").expect_err("a refusal");        assert!(error.contains("ftp"), "{error}");    }    #[test]    fn a_handshake_that_trickles_is_given_up_on_at_the_dials_deadline() {        // A TLS record header that promises sixteen kilobytes, and then one        // byte of it every 200 ms: every read of the handshake returns        // something, so a per-read timeout never trips and the dial would take        // most of an hour. One second is the whole dial.        let port = trickling(&[0x16, 0x03, 0x03, 0x40, 0x00], b"");        let origin = Origin::parse(&format!("https://127.0.0.1:{port}")).expect("an origin");        let refused = finishes(Duration::from_secs(4), move || {            dial(&origin, Duration::from_secs(1)).map(|_| ())        })        .expect_err("a handshake that never finished was trusted");        assert!(refused.contains(DEADLINE_PASSED), "{refused}");    }    #[test]    fn a_name_is_looked_up_under_the_deadline_and_an_address_needs_no_lookup() {        let named = Origin::parse("http://localhost:9").expect("an origin");        let refused = resolve(&named, Instant::now()).expect_err("no time was left");        assert!(refused.contains(DEADLINE_PASSED), "{refused}");        // An address is its own answer — no thread, no wait, whatever is left.        let literal = Origin::parse("http://127.0.0.1:9").expect("an origin");        let found = resolve(&literal, Instant::now()).expect("an address");        assert_eq!(found, vec![SocketAddr::from(([127, 0, 0, 1], 9))]);    }    #[test]    fn a_wire_past_its_deadline_refuses_the_next_read_by_name() {        let port = trickling(b"", b"");        let origin = Origin::parse(&format!("http://127.0.0.1:{port}")).expect("an origin");        let mut wire = dial_by(&origin, Instant::now() + Duration::from_millis(300))            .expect("a plain dial to loopback");        let _ = wire.write_all(b"GET / HTTP/1.1\r\n\r\n");        let refused = finishes(Duration::from_secs(3), move || {            let mut sink = Vec::new();            wire.read_to_end(&mut sink)        })        .expect_err("a body that never ends was read to its end");        assert_eq!(refused.kind(), std::io::ErrorKind::TimedOut);        assert!(refused.to_string().contains(DEADLINE_PASSED), "{refused}");    }    #[test]    fn the_trailing_slash_never_reaches_the_signed_origin() {        // The origin is a SIGNED field: one trailing slash and every signature        // is over a string the server did not build.        let origin = Origin::parse("https://example.invalid/").expect("an origin");        assert_eq!(origin.text, "https://example.invalid");    }}