//! 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.pubconst 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)]pubstructOrigin {/// 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,}implOrigin {/// 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.pubfn 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 => returnErr(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.pubfn authority(&self) -> String {let default = ifself.secure { 443 } else { 80 };let bracketed = ifself.host.contains(':') { format!("[{}]", self.host) } else {self.host.clone() };ifself.port == default { bracketed } else { format!("{bracketed}:{}", self.port) } }fn socket_authority(&self) -> String {ifself.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.pubstructTimed { 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::DebugforTimed {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)}implTimed {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: implFn(&TcpStream, Option<Duration>) -> std::io::Result<()>, ) -> std::io::Result<Option<Instant>> {letSome(deadline) = self.deadline() else {returnOk(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, } }}implReadforTimed {fn read(&mutself, 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)) }}implWriteforTimed {fn write(&mutself, 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(&mutself) -> 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.pubenumWire {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::DebugforWire {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {matchself {Wire::Plain(_) => f.write_str("Wire::Plain"),Wire::Tls(_) => f.write_str("Wire::Tls"), } }}implWire {fn timed(&self) -> &Timed {matchself {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.pubfn 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.pubfn extend_deadline(&self, by: Duration) {letmut until = self.timed().until.lock().unwrap_or_else(|e| e.into_inner());ifletSome(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) }pubfn 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.pubfn 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); })) }}implReadforWire {fn read(&mutself, buf: &mut [u8]) -> std::io::Result<usize> {matchself {Wire::Plain(stream) => stream.read(buf),Wire::Tls(stream) => stream.read(buf), } }}implWriteforWire {fn write(&mutself, buf: &[u8]) -> std::io::Result<usize> {matchself {Wire::Plain(stream) => stream.write(buf),Wire::Tls(stream) => stream.write(buf), } }fn flush(&mutself) -> std::io::Result<()> {matchself {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`].pubfn 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.pubstatic CUT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);/// What a dial says while [`CUT`] holds.pubconst 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.pubfn 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.pubfn 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) {returnErr(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)?;letSome(first) = addresses.first() else {returnErr(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.letmut last: Option<std::io::Error> = None;letmut stream: Option<TcpStream> = None;for address in &addresses {letSome(remaining) = left(deadline) else {returnErr(out_of_time()); };matchTcpStream::connect_timeout(address, remaining) {Ok(open) => { stream = Some(open);break; }Err(error) => last = Some(error), } }let stream = match stream {Some(stream) => stream,Noneif left(deadline).is_none() => returnErr(out_of_time()),None => {let error = last .unwrap_or_else(|| std::io::Error::other(format!("{first} could not be reached")));returnErr(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 {returnOk(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.ifletOk(address) = origin.host.parse::<std::net::IpAddr>() {returnOk(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))?;letSome(remaining) = left(deadline) else {returnErr(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 {usesuper::*;usecrate::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");letmut 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 || {letmut 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"); }}