//! The `louise-dist` thread: its poll, the listener, and the connections, //! each a TLS stream through the handshake (`docs/wire-format.md`, //! *Handshake*) to `Up`. //! //! A connection is driven to `WouldBlock` on every event (the sockets are //! edge-triggered): read and handle every complete frame, then write what //! is queued. A connection whose bytes keep coming (or going) yields after //! [`SLICE`] and is driven again before the next poll waits, so one busy //! peer cannot hold up the others' heartbeats. Timers (heartbeats, //! timeouts, reconnections) are checked after each poll, which waits until //! the next one is due. //! //! Writing: a connection's control lane (heartbeats, echoes) goes first at //! each frame boundary; then the frames it has taken from the peer's queue, //! in order; then, once those are all handed to TLS, the queue again, //! whose parked senders are woken then. //! //! **Discovery** (`mesh`, `docs/wire-format.md`, *Peers*). A connection //! whose two hellos set [`frame::FLAG_PEERS`] carries lists of peers (signal //! op `03`), written after what the peer's queue held when they were made: //! - A node sends its list to a peer as soon as it is up with it, and to //! every such peer when a node comes up or goes down, at most once per //! heartbeat for each [`RETELL_PEERS`] peers up. The list holds this //! node's advertised address, and each node up whose address it holds //! from the operator (a seed, `connect`) or from the node itself (its own //! entry in its list, or a dial that came up). It is encoded once for //! all peers (each ignores its own entry), and one waits at most per //! peer: a newer one replaces it ([`Conn::list`]). //! - A name a list gives that this node does not know becomes *discovered*, //! and [`Thread::tick`] dials it; simultaneous dials resolve as any //! others ([`Thread::arbitrate`]). Until the node confirms its address //! (its own entry, or a dial that came up), each dial tries the next of //! the addresses its listers give, one each, in the order of their //! connections: a lister that lies, however often and wherever, holds up //! the dial at the honest one by one failed dial. A //! seed's address never changes. //! - A discovered node is *listed* while it is up or some peer's latest //! list holds it. A lost one is dialed again with backoff, and forgotten //! once no peer has listed it for [`FORGET_AFTER`] × `node_down_after_ms`. //! - At most `max_peers` are discovered, and a peer's list holds at most //! that many (past it, the rest is not read). A node never seen up and //! never confirmed is *on probation*, held by the lister whose list //! brought it ([`Found::lister`]). When none is left, a new name takes //! the place of one no lister holds, or else of one held by a lister //! holding more than its share (`max_peers` over the peers that list): //! one peer's names cannot keep every other node from being discovered //! ([`Thread::room`]). use std::collections::{HashMap, HashSet, VecDeque}; use std::io::{ErrorKind, IoSlice, Read, Write}; use std::net::{IpAddr, Shutdown, SocketAddr}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; use std::sync::{Mutex, PoisonError}; use std::time::{Duration, Instant}; use louise_rt_prims::wire::{HEADER_LEN, MessageHeader}; use mio::net::{TcpListener, TcpStream}; use mio::{Events, Interest, Poll, Token, Waker}; use rustls::client::Resumption; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, ServerName}; use rustls::{ClientConfig, ClientConnection, Connection, ServerConfig, ServerConnection}; use super::frame::{self, Entry, Hello}; use super::relay::Relay; use super::{ Command, Config, Inbound, MAX_FRAME, MAX_UNAUTHENTICATED, MAX_UNAUTHENTICATED_PER_SOURCE, MIN_FRAME, Node, Outbox, PeerStats, Reason, Route, Stats, Throttle, }; use crate::sock::NoSigPipe; use crate::tls::{Authorities, ClientOptions, Identity, ServerOptions, has_name}; const WAKER: Token = Token(0); const LISTENER: Token = Token(1); /// Plaintext is read in chunks of this size, and framed after each. const CHUNK: usize = 16 << 10; /// Frames handed to rustls in one write (two slices each). const MAX_SLICES: usize = 64; /// The reconnection delay doubles up to this many times the first. const MAX_BACKOFF: u32 = 32; /// How long one connection is read and written before the others, and the /// timers, have their turn. const SLICE: Duration = Duration::from_millis(5); /// Connections accepted in one turn: the listener then waits for the next /// round, as a connection does when its slice runs out. const ACCEPTS: usize = 64; /// A discovered node no peer lists is forgotten after this many times /// `node_down_after_ms`: meanwhile it is dialed again, with backoff. pub(super) const FORGET_AFTER: u32 = 10; /// Lists of peers go to every peer at most once per heartbeat for each /// this many peers up: a round costs a list of `n` names for each of `n` /// peers, written to each. const RETELL_PEERS: usize = 256; pub(super) struct Thread { config: Config, me: Node, /// Our hello's body, sent on every connection. hello: Vec, poll: Poll, listener: TcpListener, local_addr: SocketAddr, client: Arc, server: Arc, conns: HashMap, next_token: usize, /// Connections that used up their [`SLICE`] before `WouldBlock`: no /// event comes for what they have left, so they are driven again. again: Vec, /// Each node that is up, and its connection. up: HashMap, /// Nodes to stay connected to: seeds, `connect`'s, and (`mesh`) the /// nodes peers list. known: HashMap, /// How many of `known` are discovered: at most `max_peers`. discovered: usize, /// By connection: how many discovered nodes on probation its lists /// brought and still hold ([`Found::lister`]). held: HashMap, /// How many discovered nodes no lister holds ([`Found::lister`]): the /// first a new name may take the place of. unheld: usize, /// Per discovered node, how many up peers' latest lists hold it. listings: HashMap, /// This node's address in its lists; `None`: it gives none. advertise: Option, /// Peers up since the last turn, owed this node's list at its end. welcome: Vec, /// A node came up or went down since every peer was last sent the /// list: sent again at most once per heartbeat ([`Thread::tell`]). retell: bool, told: Option, outbox: Arc, /// What arrives goes to the handler through it. inbound: Arc, heartbeat: Duration, down_after: Duration, /// Accepts that failed (out of descriptors, say): logged sparingly. accept_errors: Throttle, } struct Known { addr: SocketAddr, /// The next delay, in `reconnect_ms`. backoff: u32, /// When to dial; `None` while a connection names it. due: Option, /// Learned from a peer's list; `None`, a seed or `connect`ed node, /// whose address no list changes and which is never forgotten. found: Option, } /// What this node knows of a discovered node. struct Found { /// The address is the node's own word (its entry in its own list), or /// a dial to it there came up: another peer's list does not replace /// it. confirmed: bool, /// It came up, or confirmed its address: not on probation. proven: bool, /// The connection whose lists hold it for the discovery budget /// ([`Thread::room`]): the one whose list brought it, or the next to /// list it once that one no longer does. `None`: no lister holds it. lister: Option, /// Unconfirmed: how many dials were made, to try its listers' /// addresses in turn. dials: usize, /// Since when it is neither up nor in any up peer's list: it is /// forgotten [`FORGET_AFTER`] × `node_down_after_ms` later. unlisted: Option, } enum Role { /// We dialed this node. Dial(String), Accept, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Phase { /// Waiting for the peer's hello (the dialer's has gone out with the /// TLS handshake). Hello, /// Accepted: our hello went out, waiting for the dialer's ack. Ack, Up, } struct Conn { sock: TcpStream, tls: Connection, role: Role, addr: SocketAddr, phase: Phase, /// The peer, once its hello is accepted. peer: Option, /// The name its hello claims, checked or not: for logs. claimed: Option, /// The largest frame the peer accepts. peer_max: u32, /// The capability flags of the peer's hello. peer_flags: u64, /// Plaintext not framed yet: less than a frame and a chunk. inbuf: Vec, /// Frames to write, the first `offset` bytes of the front one given to /// rustls already. out: VecDeque, offset: usize, /// Heartbeats and echoes, put in front of `out` at its next frame /// boundary. control: VecDeque, opened: Instant, last_recv: Instant, /// When the last heartbeat was queued. pinged: Instant, /// The stamp of the latest echo counted: an older one is not. echoed: Option, /// The peer's statistics, once up. stats: Option>, /// Not read while the handler has a full backlog of its frames /// (`relay`): the relay wakes the thread once it is down to half. paused: bool, /// Both hellos set [`frame::FLAG_PEERS`]: lists of peers go both ways. mesh: bool, /// The discovered nodes its latest list holds, at the address it /// gives each. listed: HashMap, /// This node's latest list for it, not yet handed to [`Conn::out`]: /// its frames' bodies, shared by every peer of the same frame limit. A /// newer list replaces it, so a peer that does not read holds one. list: Option]>>, } impl Conn { fn new(sock: TcpStream, tls: Connection, role: Role, addr: SocketAddr) -> Conn { let now = Instant::now(); Conn { sock, tls, role, addr, phase: Phase::Hello, peer: None, claimed: None, peer_max: MIN_FRAME, peer_flags: 0, inbuf: Vec::new(), out: VecDeque::new(), offset: 0, control: VecDeque::new(), opened: now, last_recv: now, pinged: now, echoed: None, stats: None, paused: false, mesh: false, listed: HashMap::new(), list: None, } } /// Microseconds since it opened: a heartbeat's stamp. fn stamp(&self, now: Instant) -> u64 { u64::try_from(now.saturating_duration_since(self.opened).as_micros()).unwrap_or(u64::MAX) } /// Queue a heartbeat in the control lane, unless one waits there /// already (the socket takes nothing). fn ping(&mut self, now: Instant) { self.pinged = now; if !self.control.iter().any(|e| e.kind() == frame::HEARTBEAT) { let stamp = self.stamp(now).to_le_bytes().to_vec(); self.control.push_back(Entry::new(frame::HEARTBEAT, stamp)); } } /// Answer the peer's heartbeat: one echo waits at most, of its latest /// stamp, so a peer that sends heartbeats and reads nothing does not /// grow the lane. fn answer(&mut self, stamp: &[u8]) { match self.control.iter_mut().find(|e| e.kind() == frame::ECHO) { Some(echo) => echo.body.copy_from_slice(stamp), None => self .control .push_back(Entry::new(frame::ECHO, stamp.to_vec())), } } /// The echo of a heartbeat: its round-trip time, unless an echo of a /// later one was counted already, or it is not a stamp of ours. fn echo(&mut self, stamp: u64, now: Instant) { let now = self.stamp(now); if stamp > now || self.echoed >= Some(stamp) { return; } self.echoed = Some(stamp); if let Some(stats) = &self.stats { stats.rtt_us.store(now - stamp, Ordering::Relaxed); } } /// The node this connection is with, as far as it is known. fn name(&self) -> Option<&str> { match (&self.peer, &self.role) { (Some(peer), _) => Some(&peer.name), (None, Role::Dial(name)) => Some(name), (None, Role::Accept) => None, } } /// For logs: the node, or its address and the name it claims before /// its hello is accepted. fn label(&self) -> String { match (self.name(), &self.claimed) { (Some(name), _) => name.to_owned(), (None, Some(claimed)) => format!("{claimed} at {}", self.addr), (None, None) => self.addr.to_string(), } } } impl Thread { /// Load the certificates, listen, and set up the poll; the thread runs /// [`Thread::run`]. pub(super) fn new(config: Config, me: Node, inbound: Arc) -> Result { let leaf = CertificateDer::from_pem_file(&config.cert_file) .map_err(|e| format!("{}: {e}", config.cert_file))?; if !has_name(&leaf, &config.node) { return Err(format!( "the certificate {} is not valid for the node name {}", config.cert_file, config.node )); } let identity = || Identity { cert_file: config.cert_file.clone(), key_file: config.key_file.clone(), }; let authorities = || Authorities { default_roots: false, pems: Vec::new(), files: config.ca_files.clone(), }; let client = crate::tls::client_config(ClientOptions { authorities: authorities(), identity: Some(identity()), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, insecure: false, })?; // No resumption: every connection verifies the peer's chain and // its dates (the acceptor issues no ticket either). let mut client = Arc::unwrap_or_clone(client); client.resumption = Resumption::disabled(); let client = Arc::new(client); let server = crate::tls::server_config(ServerOptions { identity: identity(), client_authorities: Some(authorities()), alpn: vec![frame::ALPN.to_vec()], tls13_only: true, peers: true, })?; let poll = Poll::new().map_err(|e| format!("cannot create the transport's poll: {e}"))?; let waker = Waker::new(poll.registry(), WAKER) .map_err(|e| format!("cannot create the transport's waker: {e}"))?; let mut listener = TcpListener::bind(config.listen) .map_err(|e| format!("cannot listen on {}: {e}", config.listen))?; let local_addr = listener .local_addr() .map_err(|e| format!("cannot listen on {}: {e}", config.listen))?; poll.registry() .register(&mut listener, LISTENER, Interest::READABLE) .map_err(|e| format!("cannot poll the listener: {e}"))?; let hello = Hello { version: frame::VERSION, flags: frame::FLAGS_OPS | if config.mesh { frame::FLAG_PEERS } else { 0 }, incarnation: me.incarnation, schema_hash: config.schema_hash, max_frame: config.max_frame, cluster: config.cluster.clone(), node: config.node.clone(), } .encode(); let now = Instant::now(); let known = config .seeds .iter() .map(|(name, addr)| { let known = Known { addr: *addr, backoff: 1, due: Some(now), found: None, }; (name.clone(), known) }) .collect(); let outbox = Arc::new(Outbox { routes: Mutex::default(), stats: Mutex::new(PeerStats::new(config.max_peers)), commands: Mutex::default(), waker, woken: AtomicBool::new(false), max_queue: config.max_queue, open: AtomicUsize::new(0), dropped: AtomicU64::new(0), }); let advertise = config.advertise.or_else(|| { let listened = (!config.listen.ip().is_unspecified()).then_some(local_addr); listened.filter(|a| frame::dialable(*a)) }); Ok(Thread { heartbeat: Duration::from_millis(config.heartbeat_ms), down_after: Duration::from_millis(config.node_down_after_ms), config, me, hello, poll, listener, local_addr, client, server, conns: HashMap::new(), next_token: LISTENER.0 + 1, again: Vec::new(), up: HashMap::new(), known, discovered: 0, held: HashMap::new(), unheld: 0, listings: HashMap::new(), advertise, welcome: Vec::new(), retell: false, told: None, outbox, inbound, accept_errors: Throttle::default(), }) } pub(super) fn outbox(&self) -> Arc { self.outbox.clone() } pub(super) fn local_addr(&self) -> SocketAddr { self.local_addr } /// Until [`Command::Stop`]: then what is queued is written, as far as /// the sockets take it, and every connection closes. pub(super) fn run(mut self) { let mut events = Events::with_capacity(256); loop { let timeout = if self.again.is_empty() { self.next_deadline() .map(|at| at.saturating_duration_since(Instant::now())) } else { Some(Duration::ZERO) }; if let Err(e) = self.poll.poll(&mut events, timeout) { if e.kind() == ErrorKind::Interrupted { continue; } eprintln!("louise: dist: the transport's poll failed: {e}"); break; } // Taken before the events: a connection that an event drives, // and that runs out of its slice again, waits for the next // round. let again = std::mem::take(&mut self.again); let mut woken = false; for event in &events { match event.token() { WAKER => woken = true, LISTENER => self.accept(), token => self.drive(token), } } if woken { // Before taking anything: a sender that queues after this // wakes the thread again. self.outbox.woken.store(false, Ordering::Release); if self.commands() { break; } let up: Vec = self.up.values().copied().collect(); for token in up { self.drive_write(token); } self.resume(); } for token in again { match token { _ if self.again.contains(&token) => {} LISTENER => self.accept(), token => self.drive(token), } } // After reading: a stalled thread finds the bytes that arrived // meanwhile before it judges a peer silent. self.tick(Instant::now()); self.tell(Instant::now()); } // What senders queued before the stop is written, as far as each // socket takes it without waiting: a program's last messages // before it ends (a reply, say) are not dropped for that alone. let up: Vec = self.up.values().copied().collect(); for token in up { self.drive_write(token); } let mut tokens: Vec = self.conns.keys().copied().collect(); tokens.sort_unstable(); for token in tokens { if let Some(conn) = self.conns.remove(&token) { self.close(token, conn, Reason::Stopped); } } } /// Carry out the handle's commands; true to stop. fn commands(&mut self) -> bool { let commands = std::mem::take( &mut *self .outbox .commands .lock() .unwrap_or_else(PoisonError::into_inner), ); for command in commands { match command { Command::Stop => return true, Command::Connect(name, addr) => { if name == self.me.name { continue; } let known = self.known.entry(name).or_insert(Known { addr, backoff: 1, due: None, found: None, }); known.addr = addr; known.due = Some(Instant::now()); // Kept from now on, as a seed. if let Some(found) = known.found.take() { self.discovered -= 1; self.release(&found); } } } } false } // ---- timers ---------------------------------------------------------------------- /// Close silent connections and overdue handshakes, send heartbeats, /// forget the discovered nodes unlisted for long enough, dial the known /// nodes that are due (a discovered one only below `max_peers`). fn tick(&mut self, now: Instant) { let mut expired = Vec::new(); let mut beats = Vec::new(); for (&token, c) in &self.conns { let since = match c.phase { // Not read by choice (`relay`): not silent. Phase::Up if c.paused => now, Phase::Up => c.last_recv, _ => c.opened, }; if now.saturating_duration_since(since) >= self.down_after { expired.push(token); } else if c.phase == Phase::Up && now.saturating_duration_since(c.pinged) >= self.heartbeat { beats.push(token); } } expired.sort_unstable(); for token in expired { if let Some(conn) = self.conns.remove(&token) { self.close(token, conn, Reason::Timeout); } } for token in beats { if let Some(conn) = self.conns.get_mut(&token) { conn.ping(now); self.drive_write(token); } } let forget = self.down_after * FORGET_AFTER; let forgotten: Vec = self .known .iter() .filter(|(_, k)| { k.found .as_ref() .and_then(|f| f.unlisted) .is_some_and(|at| now.saturating_duration_since(at) >= forget) }) .map(|(name, _)| name.clone()) .collect(); for name in forgotten { self.forget(&name); } let due: Vec = self .known .iter() .filter(|(_, k)| k.due.is_some_and(|at| at <= now)) .map(|(name, _)| name.clone()) .collect(); for name in due { let found = self.known.get(&name).is_some_and(|k| k.found.is_some()); if self.named(&name) { if let Some(k) = self.known.get_mut(&name) { k.due = None; } } else if found && self.peers() >= self.config.max_peers { // It would refuse the peer's hello: later, with backoff. self.lost(&name); } else { self.dial(&name); } } } /// When [`Thread::tick`] next has something to do. fn next_deadline(&self) -> Option { let conns = self.conns.values().flat_map(|c| { if c.phase == Phase::Up { [ (!c.paused).then(|| c.last_recv + self.down_after), Some(c.pinged + self.heartbeat), ] } else { [Some(c.opened + self.down_after), None] } }); let known = self.known.values().map(|k| k.due); let forget = self.down_after * FORGET_AFTER; let unlisted = self.known.values().map(|k| { let since = k.found.as_ref().and_then(|f| f.unlisted); since.map(|at| at + forget) }); let retell = self .retell .then(|| self.told.map_or_else(Instant::now, |t| t + self.heartbeat)); conns .chain(known) .chain(unlisted) .chain([retell]) .flatten() .min() } // ---- connections ------------------------------------------------------------------- /// Whether a connection (in the map) is with `name`, up or not. fn named(&self, name: &str) -> bool { self.conns.values().any(|c| c.name() == Some(name)) } /// Connections (in the map) past their hello: what `max_peers` caps. fn peers(&self) -> usize { self.conns.values().filter(|c| c.peer.is_some()).count() } fn dial(&mut self, name: &str) { // Unconfirmed: its listers' addresses in turn, one each, in the // order of their connections. Not in the addresses' order: a liar // could then list, before each dial, one that sorts just where the // next turn falls, and hold every turn. let mut listers: Vec<(Token, SocketAddr)> = self .conns .iter() .filter_map(|(token, c)| Some((*token, *c.listed.get(name)?))) .collect(); listers.sort_unstable_by_key(|(token, _)| *token); let mut given = HashSet::new(); let addrs: Vec = listers .into_iter() .map(|(_, addr)| addr) .filter(|addr| given.insert(*addr)) .collect(); let Some(known) = self.known.get_mut(name) else { return; }; known.due = None; if let Some(found) = known.found.as_mut().filter(|f| !f.confirmed) && !addrs.is_empty() { known.addr = addrs[found.dials % addrs.len()]; found.dials = found.dials.wrapping_add(1); } let addr = known.addr; let tls = ServerName::try_from(name.to_owned()) .map_err(|e| e.to_string()) .and_then(|server| { ClientConnection::new(self.client.clone(), server).map_err(|e| e.to_string()) }); let opened = tls.and_then(|tls| { TcpStream::connect(addr) .map(|sock| (sock, tls)) .map_err(|e| e.to_string()) }); let (sock, tls) = match opened { Ok(opened) => opened, Err(e) => { let hearsay = self.hearsay(name); self.inbound.closed(name, &Reason::Closed(e), hearsay); self.lost(name); return; } }; // Small frames go out at once; a failure only delays them. let _ = sock.set_nodelay(true); let mut conn = Conn::new(sock, tls.into(), Role::Dial(name.to_owned()), addr); conn.out .push_back(Entry::new(frame::HELLO, self.hello.clone())); self.register(conn); } /// Accept up to [`ACCEPTS`] connections, then let the others have /// their turn: a flood of connections does not hold up heartbeats. fn accept(&mut self) { let mut accepted = 0; while accepted < ACCEPTS { let (sock, addr) = match self.listener.accept() { Ok(accepted) => accepted, Err(e) if e.kind() == ErrorKind::WouldBlock => return, Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => { // Out of descriptors, say: the next connection retries. if let Some(held) = self.accept_errors.admit(Instant::now()) { eprintln!( "louise: dist: cannot accept a connection: {e}{}", Throttle::held_back(held) ); } return; } }; accepted += 1; let Ok(tls) = ServerConnection::new(self.server.clone()) else { continue; }; self.make_room(source(addr.ip())); let _ = sock.set_nodelay(true); self.register(Conn::new(sock, tls.into(), Role::Accept, addr)); } if !self.again.contains(&LISTENER) { self.again.push(LISTENER); } } /// Keep accepted connections whose hello is not in yet under /// [`MAX_UNAUTHENTICATED_PER_SOURCE`] for `from`, and under /// [`MAX_UNAUTHENTICATED`] in all, counting the one about to be /// accepted from `from`: its source's oldest goes, else the oldest of /// the source that holds the most. Refusing the newest instead would let /// a host that holds that many idle sockets keep every node from dialing /// in; closing the oldest of all, a host opening connections faster /// than a distant node's handshake. fn make_room(&mut self, from: IpAddr) { let mut pending: HashMap = HashMap::new(); let mut total = 0; for (&token, c) in &self.conns { if !matches!(c.role, Role::Accept) || c.peer.is_some() { continue; } total += 1; let oldest = (c.opened, token); let entry = pending .entry(source(c.addr.ip())) .or_insert((0, oldest.0, oldest.1)); entry.0 += 1; if oldest < (entry.1, entry.2) { (entry.1, entry.2) = oldest; } } let own = pending .get(&from) .filter(|p| p.0 >= MAX_UNAUTHENTICATED_PER_SOURCE); let victim = match own { Some(&(_, _, token)) => Some(token), None if total >= MAX_UNAUTHENTICATED => pending .values() .max_by_key(|(n, opened, token)| (*n, std::cmp::Reverse((*opened, *token)))) .map(|&(_, _, token)| token), None => None, }; if let Some(token) = victim && let Some(conn) = self.conns.remove(&token) { self.close(token, conn, Reason::Crowded); } } fn register(&mut self, mut conn: Conn) { let token = Token(self.next_token); self.next_token += 1; if let Err(e) = self.poll.registry().register( &mut conn.sock, token, Interest::READABLE | Interest::WRITABLE, ) { // A local failure, not the peers' doing. self.inbound .closed(&conn.label(), &Reason::Closed(e.to_string()), false); if let Some(name) = conn.name().map(str::to_owned) { self.lost(&name); } return; } self.outbox.open.fetch_add(1, Ordering::AcqRel); self.conns.insert(token, conn); } /// Read, then write, `token`'s connection as far as it goes, for a /// [`SLICE`] each at most (a peer that floods this node still gets its /// frames). Out of the map meanwhile: what its frames do may close /// others. fn drive(&mut self, token: Token) { let Some(mut conn) = self.conns.remove(&token) else { return; }; let done = self .read(token, &mut conn, Instant::now() + SLICE) .and_then(|more_in| { let more_out = self.flush(&mut conn, Instant::now() + SLICE)?; Ok(more_in || more_out) }); self.settle(token, conn, done); } /// Read again the paused connections the relay has room for again: /// no event comes for the bytes their sockets hold already. Silence is /// timed from now. fn resume(&mut self) { let resumed: Vec = self .conns .iter_mut() .filter(|(_, c)| c.paused) .filter(|(_, c)| { c.peer .as_ref() .is_some_and(|p| self.inbound.resumed(&p.name)) }) .map(|(&token, c)| { c.paused = false; c.last_recv = Instant::now(); token }) .collect(); for token in resumed { self.drive(token); } } fn drive_write(&mut self, token: Token) { let Some(mut conn) = self.conns.remove(&token) else { return; }; let done = self.flush(&mut conn, Instant::now() + SLICE); self.settle(token, conn, done); } /// Back into the map, and driven again if its slice ran out (`more`), /// or closed. fn settle(&mut self, token: Token, conn: Conn, done: Result) { match done { Ok(more) => { self.conns.insert(token, conn); if more && !self.again.contains(&token) { self.again.push(token); } } Err(reason) => self.close(token, conn, reason), } } /// Close a connection (out of the map): tell the peer why if it is a /// refusal and a frame boundary allows, then the node is down if it /// was up, and a known node is dialed again later. fn close(&mut self, token: Token, mut conn: Conn, reason: Reason) { if let Some(code) = reason.code() && conn.offset == 0 { let refusal = Entry::new(frame::REFUSE, frame::refusal(code, &reason.to_string())); let _ = conn .tls .writer() .write_vectored(&[IoSlice::new(&refusal.head), IoSlice::new(&refusal.body)]); } conn.tls.send_close_notify(); // Best effort, without waiting: a few writes, then the socket goes. for _ in 0..4 { if !conn.tls.wants_write() || conn.tls.write_tls(&mut NoSigPipe::new(&conn.sock)).is_err() { break; } } let _ = self.poll.registry().deregister(&mut conn.sock); let _ = conn.sock.shutdown(Shutdown::Both); self.outbox.open.fetch_sub(1, Ordering::AcqRel); // A dial that never got past its hello, to an address only lists // gave: the peers chose it, so it is logged sparingly. let hearsay = matches!(&conn.role, Role::Dial(name) if conn.peer.is_none() && self.hearsay(name)); self.inbound.closed(&conn.label(), &reason, hearsay); let now = Instant::now(); for name in std::mem::take(&mut conn.listed).into_keys() { self.unlist(token, &name); self.relist(&name, now); } self.held.remove(&token); if conn.phase == Phase::Up && let Some(peer) = &conn.peer { if self.up.get(&peer.name) == Some(&token) { self.up.remove(&peer.name); self.relist(&peer.name, now); self.retell = true; let route = self.outbox.routes().remove(&peer.name); self.outbox.peer_stats().down(&peer.name); // Lost with the connection; a parked sender's next try is // refused, and counts its own. let messages = |q: &VecDeque| { q.iter().filter(|e| e.kind() == frame::MESSAGE).count() as u64 }; let lost = messages(&conn.out) + route.as_ref().map_or(0, |r| messages(&r.queue)); if let Some(stats) = &conn.stats { Stats::count(&stats.unsent, lost); } if let Some(route) = route && !route.parked.is_empty() { self.inbound.drained(peer, &route.parked); } } self.inbound.node_down(peer); } if let Some(name) = conn.name() { self.lost(name); } } /// A connection with `name` closed: dial it again later if it is known /// and no other connection is with it. fn lost(&mut self, name: &str) { if self.named(name) { return; } let Some(known) = self.known.get_mut(name) else { return; }; let delay = Duration::from_millis(self.config.reconnect_ms) * known.backoff; known.backoff = (known.backoff * 2).min(MAX_BACKOFF); known.due = Some(Instant::now() + delay); } // ---- reading ----------------------------------------------------------------------- /// Read and handle frames until the socket would block (false) or /// `until` (true: there may be more). /// A peer whose frames fill the relay's backlog is not read /// ([`Conn::paused`]): TCP pushes back on its sender. fn read(&mut self, token: Token, conn: &mut Conn, until: Instant) -> Result { let mut chunk = [0u8; CHUNK]; loop { if let Some(peer) = &conn.peer && conn.phase == Phase::Up && self.inbound.full(&peer.name) { conn.paused = true; return Ok(false); } if Instant::now() >= until { return Ok(true); } let eof = match conn.tls.read_tls(&mut conn.sock) { Ok(0) => true, Ok(_) => { conn.last_recv = Instant::now(); false } Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(false), Err(e) if e.kind() == ErrorKind::Interrupted => continue, Err(e) => return Err(Reason::Closed(e.to_string())), }; let state = conn.tls.process_new_packets().map_err(|e| match e { // In order, but before the handshake completed: a peer that // dropped a simultaneous dial, say. rustls::Error::AlertReceived(rustls::AlertDescription::CloseNotify) => { Reason::PeerClosed } e => Reason::Tls(e.to_string()), })?; let mut left = state.plaintext_bytes_to_read(); while left > 0 { let n = match conn.tls.reader().read(&mut chunk) { Ok(0) => break, Ok(n) => n, Err(e) if e.kind() == ErrorKind::WouldBlock => break, Err(e) => return Err(Reason::Closed(e.to_string())), }; left = left.saturating_sub(n); conn.inbuf.extend_from_slice(&chunk[..n]); self.frames(token, conn)?; } if state.peer_has_closed() { return Err(Reason::PeerClosed); } if eof { return Err(Reason::Closed("end of stream".into())); } } } /// Handle the complete frames of `conn`'s input, keeping the rest. fn frames(&mut self, token: Token, conn: &mut Conn) -> Result<(), Reason> { let buf = std::mem::take(&mut conn.inbuf); let mut at = 0; let done = loop { // Untrusted peers send handshake frames only. let limit = if conn.phase == Phase::Up { self.config.max_frame } else { MIN_FRAME }; match frame::next(&buf[at..], limit) { Ok(Some((kind, body))) => { let body = &buf[at + body.start..at + body.end]; at += frame::PREFIX + 1 + body.len(); if let Err(reason) = self.frame(token, conn, kind, body) { break Err(reason); } } Ok(None) => break Ok(()), Err(reason) => break Err(reason), } }; conn.inbuf = buf; conn.inbuf.drain(..at); // A large frame's room is given back once it is handled. if conn.inbuf.capacity() > 4 * CHUNK && conn.inbuf.len() < CHUNK { conn.inbuf.shrink_to(CHUNK); } done } fn frame( &mut self, token: Token, conn: &mut Conn, kind: u8, body: &[u8], ) -> Result<(), Reason> { match (conn.phase, kind) { (_, frame::REFUSE) => Err(frame::refused(body)), (Phase::Hello, frame::HELLO) => self.hello(token, conn, body), (Phase::Ack, frame::ACK) if body.is_empty() => { self.go_up(token, conn); Ok(()) } (Phase::Up, frame::HEARTBEAT) if body.len() == frame::STAMP => { conn.answer(body); Ok(()) } (Phase::Up, frame::ECHO) if body.len() == frame::STAMP => { let mut stamp = [0; frame::STAMP]; stamp.copy_from_slice(body); conn.echo(u64::from_le_bytes(stamp), Instant::now()); Ok(()) } (Phase::Up, frame::MESSAGE) => self.message(conn, body), (Phase::Up, frame::SIGNAL) if body.first() == Some(&frame::PEERS) => { self.listed(token, conn, &body[1..]); Ok(()) } (Phase::Up, frame::SIGNAL) => { if let Some(peer) = &conn.peer { self.inbound.signal(peer, body); } Ok(()) } _ => Err(Reason::Protocol("an unexpected frame")), } } /// The peer's hello: check it against its certificate and ours, then /// against `max_peers` ([`Thread::full`]). The acceptor answers with /// its own hello, the dialer with an ack, and is up. /// /// The name is checked first: a peer whose certificate is not valid /// for the name it claims learns nothing of this node's cluster or /// schema from the refusal's code. fn hello(&mut self, token: Token, conn: &mut Conn, body: &[u8]) -> Result<(), Reason> { let hello = Hello::decode(body)?; conn.claimed = Some(hello.node.clone()); if conn.tls.alpn_protocol() != Some(frame::ALPN) { return Err(Reason::Alpn); } let dialed = match &conn.role { Role::Dial(name) => Some(name.as_str()), Role::Accept => None, }; let certified = conn .tls .peer_certificates() .and_then(|chain| chain.first()) .is_some_and(|leaf| has_name(leaf, &hello.node)); if !certified || hello.node == self.me.name || dialed.is_some_and(|d| d != hello.node) { return Err(Reason::Name(hello.node)); } if hello.cluster != self.config.cluster { return Err(Reason::Cluster(hello.cluster)); } if hello.schema_hash != self.config.schema_hash { return Err(Reason::Schema(hello.schema_hash)); } if hello.max_frame < MIN_FRAME { return Err(Reason::Protocol("a frame limit under 1 KiB")); } // Before the acceptor's hello or the dialer's ack goes out. if self.full(&hello.node) { return Err(Reason::Full); } let peer = Node { name: hello.node, incarnation: hello.incarnation, }; conn.peer_max = hello.max_frame.min(MAX_FRAME); conn.peer_flags = hello.flags; conn.mesh = self.config.mesh && hello.flags & frame::FLAG_PEERS != 0; if dialed.is_some() { if self.up.contains_key(&peer.name) || self.rivals(token, &peer.name).next().is_some() { return Err(Reason::Duplicate); } conn.peer = Some(peer); conn.out.push_back(Entry::new(frame::ACK, Vec::new())); self.go_up(token, conn); } else { self.arbitrate(token, &peer)?; conn.peer = Some(peer); conn.out .push_back(Entry::new(frame::HELLO, self.hello.clone())); conn.phase = Phase::Ack; } Ok(()) } /// Whether a connection with `name` would take this node past /// `max_peers` connections past their hello (this one, out of the map /// while it is driven, aside). Never for a seed or a `connect`ed node /// (the operator named it, and a full node must still reach it), nor /// for a node a connection is already past its hello with: this one /// replaces it, or is a duplicate. A discovered node may be refused. fn full(&self, name: &str) -> bool { if self.known.get(name).is_some_and(|k| k.found.is_none()) { return false; } let mut peers = 0; for c in self.conns.values() { match &c.peer { Some(p) if p.name == name => return false, Some(_) => peers += 1, None => {} } } peers >= self.config.max_peers } /// Other connections with `name` still in their handshake: whether each /// is ours (dialed). fn rivals<'a>( &'a self, token: Token, name: &'a str, ) -> impl Iterator + 'a { self.conns .iter() .filter(move |(t, c)| **t != token && c.phase != Phase::Up && c.name() == Some(name)) .map(|(t, c)| (*t, matches!(c.role, Role::Dial(_)))) } /// `peer` dialed us on `token`: keep this connection, or refuse it. /// - Up with the same incarnation: refused, the one up is kept (its /// own timeout ends it if it is dead). /// - Up with another incarnation: that one restarted, the old /// connection closes (its node is down). /// - Another of its dials further along: refused. /// - Our own dial to it in progress: the connection the smaller name /// initiated is kept, so both sides keep the same one. fn arbitrate(&mut self, token: Token, peer: &Node) -> Result<(), Reason> { if let Some(&up) = self.up.get(&peer.name) { let same = self .conns .get(&up) .and_then(|c| c.peer.as_ref()) .is_some_and(|p| p.incarnation == peer.incarnation); if same { return Err(Reason::Duplicate); } if let Some(old) = self.conns.remove(&up) { self.close(up, old, Reason::Replaced); } } let rivals: Vec<(Token, bool)> = self.rivals(token, &peer.name).collect(); for (rival, ours) in rivals { if !ours || keeps_dialer(&self.me.name, &peer.name) { return Err(Reason::Duplicate); } if let Some(conn) = self.conns.remove(&rival) { self.close(rival, conn, Reason::Duplicate); } } Ok(()) } fn go_up(&mut self, token: Token, conn: &mut Conn) { let Some(peer) = conn.peer.clone() else { return; }; conn.phase = Phase::Up; let stats = self.outbox.peer_stats().up(&peer.name); stats.incarnation.store(peer.incarnation, Ordering::Relaxed); stats.rtt_us.store(u64::MAX, Ordering::Relaxed); conn.stats = Some(stats.clone()); // A first round-trip time at once. conn.ping(Instant::now()); self.up.insert(peer.name.clone(), token); self.outbox.routes().insert( peer.name.clone(), Route { incarnation: peer.incarnation, max_frame: conn.peer_max, flags: conn.peer_flags, queue: VecDeque::new(), queued: 0, parked: Vec::new(), stats, }, ); if let Some(known) = self.known.get_mut(&peer.name) { known.backoff = 1; known.due = None; // A dial that came up confirms the address it dialed. if let (Some(found), Role::Dial(_)) = (&mut known.found, &conn.role) { known.addr = conn.addr; found.confirmed = true; } } self.prove(&peer.name); self.relist(&peer.name, Instant::now()); if conn.mesh { self.welcome.push(token); } self.retell = true; self.inbound.node_up(&peer); } // ---- discovery --------------------------------------------------------------------- /// A peer's list of nodes (op `03`; `fields` after the op): what it /// names that this node does not know becomes discovered. Dropped and /// counted if the connection does not carry lists ([`Conn::mesh`]), or /// if it is malformed. Past `max_peers` names (this node's own aside), /// the rest of the peer's list is not read. fn listed(&mut self, token: Token, conn: &mut Conn, fields: &[u8]) { let list = match (&conn.peer, conn.mesh) { (Some(peer), true) => frame::Peers::decode(fields) .ok() .map(|list| (peer.name.clone(), list)), _ => None, }; let Some((lister, list)) = list else { if let Some(stats) = &conn.stats { Stats::count(&stats.dropped, 1); } return; }; let now = Instant::now(); let mut changed = Vec::new(); if list.first { for name in std::mem::take(&mut conn.listed).into_keys() { self.unlist(token, &name); changed.push(name); } } // Once `room` finds none, it finds none for the rest of this list // (it costs a scan of `known`), until the lister's own entry // proves a name of its and so changes its share. let mut full = false; for (name, addr) in list.nodes { if name == self.me.name { continue; } let own = name == lister; if let Some(given) = conn.listed.get_mut(&name) { *given = addr; self.learn(token, &lister, &name, addr, now); full &= !own; continue; } // Past `max_peers` names, the rest of the list is not taken. if conn.listed.len() >= self.config.max_peers { continue; } if !self.known.contains_key(&name) && self.discovered >= self.config.max_peers { if full && !own { continue; } if !self.room(token, conn) { full = true; continue; } } full &= !own; if self.learn(token, &lister, &name, addr, now) { conn.listed.insert(name.clone(), addr); *self.listings.entry(name.clone()).or_default() += 1; changed.push(name); } } for name in changed { self.relist(&name, now); } } /// The list of connection `token`, from `lister`, gives `addr` for /// `name`: whether `name` is now a discovered node. A name this node /// does not know becomes one (and is dialed) while fewer than /// `max_peers` are, held by `token` ([`Found::lister`]); a seed's /// address is kept; a discovered node's is replaced by its own word, /// or by a third party's while unconfirmed (the address dialed when /// none of its listers gives one). fn learn( &mut self, token: Token, lister: &str, name: &str, addr: SocketAddr, now: Instant, ) -> bool { let own = name == lister; if let Some(known) = self.known.get_mut(name) { let Some(found) = &mut known.found else { return false; }; if own || !found.confirmed { known.addr = addr; } found.confirmed |= own; if found.lister.is_none() { found.lister = Some(token); self.unheld = self.unheld.saturating_sub(1); if !found.proven { *self.held.entry(token).or_default() += 1; } } if own { self.prove(name); } return true; } if self.discovered >= self.config.max_peers { return false; } self.discovered += 1; let due = (!self.named(name)).then_some(now); let proven = own || self.up.contains_key(name); let found = Found { confirmed: own, proven, lister: Some(token), dials: 0, unlisted: None, }; if !proven { *self.held.entry(token).or_default() += 1; } let known = Known { addr, backoff: 1, due, found: Some(found), }; self.known.insert(name.to_owned(), known); true } /// Discovered `name` came up, or confirmed its address: off /// probation, its lister holds it no longer against its share. fn prove(&mut self, name: &str) { let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) else { return; }; if !found.proven { found.proven = true; if let Some(lister) = found.lister { self.unhold(lister); } } } fn unhold(&mut self, lister: Token) { if let Some(n) = self.held.get_mut(&lister) { *n = n.saturating_sub(1); } } /// Discovered node `found` is forgotten, or no longer discovered: its /// lister holds it no longer. fn release(&mut self, found: &Found) { match found.lister { Some(lister) if !found.proven => self.unhold(lister), Some(_) => {} None => self.unheld = self.unheld.saturating_sub(1), } } /// Forget discovered `name`: a dial in progress ends as one to a node /// never known. fn forget(&mut self, name: &str) { if let Some(found) = self.known.remove(name).and_then(|k| k.found) { self.discovered -= 1; self.release(&found); } self.listings.remove(name); } /// Room for one more discovered node, which connection `token` (out /// of the map, `conn`) lists, all `max_peers` being taken: forget one /// that is not up and no lister holds (no up peer's list holds it), on /// probation first; else, if `token` holds fewer than its share /// (`max_peers` over the connections that carry lists), one on /// probation that the lister holding the most holds, if that is more /// than its share. Whether there is room now. A lister that holds its /// share keeps what it holds, so the slots end up shared, and stay so. fn room(&mut self, token: Token, conn: &mut Conn) -> bool { let unheld = (self.unheld > 0) .then(|| { self.known .iter() .filter_map(|(name, k)| Some((name, k.found.as_ref()?))) .filter(|(name, f)| f.lister.is_none() && !self.up.contains_key(*name)) .min_by_key(|(_, f)| f.proven) .map(|(name, _)| name.clone()) }) .flatten(); let victim = unheld.or_else(|| { let listers = 1 + self .conns .values() .filter(|c| c.mesh && c.phase == Phase::Up) .count(); let share = (self.config.max_peers / listers).max(1); if self.held.get(&token).copied().unwrap_or(0) >= share { return None; } let (most, held) = self .held .iter() .filter(|(t, _)| **t != token) .max_by_key(|(t, n)| (**n, std::cmp::Reverse(**t)))?; if *held <= share { return None; } let most = *most; self.known .iter() .filter_map(|(name, k)| Some((name, k.found.as_ref()?))) .find(|(_, f)| f.lister == Some(most) && !f.proven) .map(|(name, _)| name.clone()) }); let Some(victim) = victim else { return false; }; for c in self.conns.values_mut() { c.listed.remove(&victim); } conn.listed.remove(&victim); self.forget(&victim); true } /// Connection `token`'s list (`token` out of the map) no longer holds /// `name`. If `token` held it, another connection whose list holds it /// does now, or none: a lister cannot leave its names to the others' /// lists for free, nor have a name another peer lists forgotten by /// dropping it ([`Thread::room`]). fn unlist(&mut self, token: Token, name: &str) { if let Some(n) = self.listings.get_mut(name) { *n = n.saturating_sub(1); if *n == 0 { self.listings.remove(name); } } let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) else { return; }; if found.lister != Some(token) { return; } let next = self .conns .iter() .find(|(t, c)| **t != token && c.listed.contains_key(name)) .map(|(t, _)| *t); found.lister = next; let proven = found.proven; match next { None => self.unheld += 1, Some(next) if !proven => *self.held.entry(next).or_default() += 1, Some(_) => {} } if !proven { self.unhold(token); } } /// Whether discovered `name` is listed (up, or in an up peer's list) /// changed: its forgetting starts, or stops. fn relist(&mut self, name: &str, now: Instant) { let listed = self.up.contains_key(name) || self.listings.contains_key(name); if let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) { if listed { found.unlisted = None; } else { found.unlisted.get_or_insert(now); } } } /// Whether `name` is a discovered node whose address only peers' /// lists gave: a failed dial to it is the listers' doing. fn hearsay(&self, name: &str) -> bool { self.known .get(name) .and_then(|k| k.found.as_ref()) .is_some_and(|f| !f.confirmed) } /// Send this node's list to the peers that came up this turn, or, after /// a node came up or went down, to every peer that takes lists: at most /// once per heartbeat for each [`RETELL_PEERS`] peers up. The list is /// encoded once for each frame limit, and replaces the one a peer has /// not taken yet ([`Conn::list`]); each peer ignores its own entry. fn tell(&mut self, now: Instant) { if !self.config.mesh { self.retell = false; return; } let period = self.heartbeat * self.up.len().div_ceil(RETELL_PEERS).max(1) as u32; let every = self.retell && self.told.is_none_or(|t| now >= t + period); let welcome = std::mem::take(&mut self.welcome); if !every && welcome.is_empty() { return; } let to: Vec = if every { self.retell = false; self.told = Some(now); let mut all: Vec = self.up.values().copied().collect(); all.sort_unstable(); all } else { welcome }; let mut up: Vec<&String> = self.up.keys().collect(); up.sort_unstable(); let me = self.advertise.map(|a| (self.me.name.clone(), a)); let list: Vec<(String, SocketAddr)> = me .into_iter() .chain(up.into_iter().filter_map(|name| { let known = self.known.get(name)?; let trusted = known.found.as_ref().is_none_or(|f| f.confirmed); trusted.then(|| (name.clone(), known.addr)) })) .collect(); let mut encoded: HashMap]>> = HashMap::new(); for token in to { let Some(conn) = self .conns .get_mut(&token) .filter(|c| c.mesh && c.phase == Phase::Up) else { continue; }; let frames = encoded .entry(conn.peer_max) .or_insert_with(|| frame::Peers::frames(&list, conn.peer_max).into()); conn.list = Some(frames.clone()); self.drive_write(token); } } fn message(&self, conn: &Conn, body: &[u8]) -> Result<(), Reason> { let header = body .first_chunk::() .ok_or(Reason::Protocol("a message frame shorter than its header"))?; let header = MessageHeader::decode(header) .map_err(|_| Reason::Protocol("a malformed message header"))?; let payload = &body[HEADER_LEN..]; if payload.len() != header.payload_len as usize { return Err(Reason::Protocol( "a message frame's length is not its header's", )); } if header.incarnation != self.me.incarnation { self.outbox.dropped.fetch_add(1, Ordering::Relaxed); if let Some(stats) = &conn.stats { Stats::count(&stats.dropped, 1); } return Ok(()); } if let Some(stats) = &conn.stats { Stats::count(&stats.received, 1); } if let Some(peer) = &conn.peer { self.inbound.message(peer, &header, payload); } Ok(()) } // ---- writing ----------------------------------------------------------------------- /// Write until the socket would block or nothing is left (false), or /// `until` (true: there may be more). fn flush(&self, conn: &mut Conn, until: Instant) -> Result { loop { while conn.tls.wants_write() { match conn.tls.write_tls(&mut NoSigPipe::new(&conn.sock)) { Ok(0) => return Err(Reason::Closed("the socket takes no more".into())), Ok(_) => {} Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(false), Err(e) if e.kind() == ErrorKind::Interrupted => {} Err(e) => return Err(Reason::Closed(e.to_string())), } } if Instant::now() >= until { return Ok(true); } if !self.refill(conn)? { return Ok(false); } } } /// Hand rustls the next frames (its buffer is empty): the control lane /// first, at a frame boundary behind the handshake's own frames, then /// what was taken from the peer's queue, which is taken again once all /// of it is written (its parked senders are woken then). Whether any /// byte went. fn refill(&self, conn: &mut Conn) -> Result { if !conn.control.is_empty() { let started = usize::from(conn.offset > 0); let at = conn .out .iter() .skip(started) .position(|e| e.kind() >= frame::MESSAGE) .map_or(conn.out.len(), |i| i + started); while let Some(entry) = conn.control.pop_back() { conn.out.insert(at, entry); } } if conn.out.is_empty() && conn.phase == Phase::Up && let Some(peer) = &conn.peer { // Swapped, so each keeps its room; past a burst's, given back. if conn.out.capacity() > MAX_SLICES * 4 { conn.out = VecDeque::new(); } let parked = match self.outbox.routes().get_mut(&peer.name) { Some(route) => { std::mem::swap(&mut conn.out, &mut route.queue); route.queued = 0; std::mem::take(&mut route.parked) } None => Vec::new(), }; // Behind the frames just taken from the queue. if let Some(list) = conn.list.take() { let frames = list .iter() .map(|body| Entry::new(frame::SIGNAL, body.clone())); conn.out.extend(frames); } if !parked.is_empty() { self.inbound.drained(peer, &parked); } } let mut slices = Vec::with_capacity(MAX_SLICES); let mut offset = conn.offset; for entry in conn.out.iter().take(MAX_SLICES / 2) { if offset < entry.head.len() { slices.push(IoSlice::new(&entry.head[offset..])); slices.push(IoSlice::new(&entry.body)); } else { slices.push(IoSlice::new(&entry.body[offset - entry.head.len()..])); } offset = 0; } if slices.is_empty() { return Ok(false); } let mut n = conn .tls .writer() .write_vectored(&slices) .map_err(|e| Reason::Closed(e.to_string()))?; drop(slices); let wrote = n > 0; while n > 0 && let Some(front) = conn.out.front() { let left = front.total() - conn.offset; if n < left { conn.offset += n; break; } n -= left; conn.offset = 0; if conn .out .pop_front() .is_some_and(|e| e.kind() == frame::MESSAGE) && let Some(stats) = &conn.stats { Stats::count(&stats.sent, 1); } } Ok(wrote) } } /// A connection's source, for [`MAX_UNAUTHENTICATED_PER_SOURCE`]: an IPv4 /// address (mapped into IPv6 or not), or an IPv6 address's /64, which one /// host usually holds whole. fn source(ip: IpAddr) -> IpAddr { match ip { IpAddr::V6(v6) => match v6.to_ipv4_mapped() { Some(v4) => IpAddr::V4(v4), None => IpAddr::V6((u128::from(v6) & !((1 << 64) - 1)).into()), }, v4 => v4, } } /// Simultaneous dials between `me` and `them`: whether the connection /// `me` dialed is kept. The smaller name's, on both sides. fn keeps_dialer(me: &str, them: &str) -> bool { me < them } #[cfg(test)] mod tests { use super::{keeps_dialer, source}; #[test] fn sources_are_addresses_or_ipv6_64s() { let ip = |s: &str| s.parse::().expect("an address"); assert_eq!(source(ip("10.0.0.5")), ip("10.0.0.5")); assert_eq!(source(ip("::ffff:10.0.0.5")), ip("10.0.0.5")); assert_eq!(source(ip("2001:db8:1:2:3:4:5:6")), ip("2001:db8:1:2::")); assert_ne!(source(ip("2001:db8:1:3::1")), source(ip("2001:db8:1:2::1"))); } #[test] fn simultaneous_dials_keep_the_smaller_names() { let (a, b) = ("a.example", "b.example"); // Each side decides about its own dial: exactly one is kept. assert!(keeps_dialer(a, b)); assert!(!keeps_dialer(b, a)); // Byte order, which node names (lowercase ASCII) make total. assert!(keeps_dialer("a-1.example", "a.example")); } }