
louise
Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.
Dernier runRéussi#1203 · main · 9 min 56 s
1Étoiles
0Forks
0Issues
| 1 | //! The `louise-dist` thread: its poll, the listener, and the connections, |
| 2 | //! each a TLS stream through the handshake (`docs/wire-format.md`, |
| 3 | //! *Handshake*) to `Up`. |
| 4 | //! |
| 5 | //! A connection is driven to `WouldBlock` on every event (the sockets are |
| 6 | //! edge-triggered): read and handle every complete frame, then write what |
| 7 | //! is queued. A connection whose bytes keep coming (or going) yields after |
| 8 | //! [`SLICE`] and is driven again before the next poll waits, so one busy |
| 9 | //! peer cannot hold up the others' heartbeats. Timers (heartbeats, |
| 10 | //! timeouts, reconnections) are checked after each poll, which waits until |
| 11 | //! the next one is due. |
| 12 | //! |
| 13 | //! Writing: a connection's control lane (heartbeats, echoes) goes first at |
| 14 | //! each frame boundary; then the frames it has taken from the peer's queue, |
| 15 | //! in order; then, once those are all handed to TLS, the queue again, |
| 16 | //! whose parked senders are woken then. |
| 17 | //! |
| 18 | //! **Discovery** (`mesh`, `docs/wire-format.md`, *Peers*). A connection |
| 19 | //! whose two hellos set [`frame::FLAG_PEERS`] carries lists of peers (signal |
| 20 | //! op `03`), written after what the peer's queue held when they were made: |
| 21 | //! - A node sends its list to a peer as soon as it is up with it, and to |
| 22 | //! every such peer when a node comes up or goes down, at most once per |
| 23 | //! heartbeat for each [`RETELL_PEERS`] peers up. The list holds this |
| 24 | //! node's advertised address, and each node up whose address it holds |
| 25 | //! from the operator (a seed, `connect`) or from the node itself (its own |
| 26 | //! entry in its list, or a dial that came up). It is encoded once for |
| 27 | //! all peers (each ignores its own entry), and one waits at most per |
| 28 | //! peer: a newer one replaces it ([`Conn::list`]). |
| 29 | //! - A name a list gives that this node does not know becomes *discovered*, |
| 30 | //! and [`Thread::tick`] dials it; simultaneous dials resolve as any |
| 31 | //! others ([`Thread::arbitrate`]). Until the node confirms its address |
| 32 | //! (its own entry, or a dial that came up), each dial tries the next of |
| 33 | //! the addresses its listers give, one each, in the order of their |
| 34 | //! connections: a lister that lies, however often and wherever, holds up |
| 35 | //! the dial at the honest one by one failed dial. A |
| 36 | //! seed's address never changes. |
| 37 | //! - A discovered node is *listed* while it is up or some peer's latest |
| 38 | //! list holds it. A lost one is dialed again with backoff, and forgotten |
| 39 | //! once no peer has listed it for [`FORGET_AFTER`] × `node_down_after_ms`. |
| 40 | //! - At most `max_peers` are discovered, and a peer's list holds at most |
| 41 | //! that many (past it, the rest is not read). A node never seen up and |
| 42 | //! never confirmed is *on probation*, held by the lister whose list |
| 43 | //! brought it ([`Found::lister`]). When none is left, a new name takes |
| 44 | //! the place of one no lister holds, or else of one held by a lister |
| 45 | //! holding more than its share (`max_peers` over the peers that list): |
| 46 | //! one peer's names cannot keep every other node from being discovered |
| 47 | //! ([`Thread::room`]). |
| 48 | |
| 49 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 50 | use std::io::{ErrorKind, IoSlice, Read, Write}; |
| 51 | use std::net::{IpAddr, Shutdown, SocketAddr}; |
| 52 | use std::sync::Arc; |
| 53 | use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; |
| 54 | use std::sync::{Mutex, PoisonError}; |
| 55 | use std::time::{Duration, Instant}; |
| 56 | |
| 57 | use louise_rt_prims::wire::{HEADER_LEN, MessageHeader}; |
| 58 | use mio::net::{TcpListener, TcpStream}; |
| 59 | use mio::{Events, Interest, Poll, Token, Waker}; |
| 60 | use rustls::client::Resumption; |
| 61 | use rustls::pki_types::pem::PemObject; |
| 62 | use rustls::pki_types::{CertificateDer, ServerName}; |
| 63 | use rustls::{ClientConfig, ClientConnection, Connection, ServerConfig, ServerConnection}; |
| 64 | |
| 65 | use super::frame::{self, Entry, Hello}; |
| 66 | use super::relay::Relay; |
| 67 | use super::{ |
| 68 | Command, Config, Inbound, MAX_FRAME, MAX_UNAUTHENTICATED, MAX_UNAUTHENTICATED_PER_SOURCE, |
| 69 | MIN_FRAME, Node, Outbox, PeerStats, Reason, Route, Stats, Throttle, |
| 70 | }; |
| 71 | use crate::sock::NoSigPipe; |
| 72 | use crate::tls::{Authorities, ClientOptions, Identity, ServerOptions, has_name}; |
| 73 | |
| 74 | const WAKER: Token = Token(0); |
| 75 | const LISTENER: Token = Token(1); |
| 76 | /// Plaintext is read in chunks of this size, and framed after each. |
| 77 | const CHUNK: usize = 16 << 10; |
| 78 | /// Frames handed to rustls in one write (two slices each). |
| 79 | const MAX_SLICES: usize = 64; |
| 80 | /// The reconnection delay doubles up to this many times the first. |
| 81 | const MAX_BACKOFF: u32 = 32; |
| 82 | /// How long one connection is read and written before the others, and the |
| 83 | /// timers, have their turn. |
| 84 | const SLICE: Duration = Duration::from_millis(5); |
| 85 | /// Connections accepted in one turn: the listener then waits for the next |
| 86 | /// round, as a connection does when its slice runs out. |
| 87 | const ACCEPTS: usize = 64; |
| 88 | /// A discovered node no peer lists is forgotten after this many times |
| 89 | /// `node_down_after_ms`: meanwhile it is dialed again, with backoff. |
| 90 | pub(super) const FORGET_AFTER: u32 = 10; |
| 91 | /// Lists of peers go to every peer at most once per heartbeat for each |
| 92 | /// this many peers up: a round costs a list of `n` names for each of `n` |
| 93 | /// peers, written to each. |
| 94 | const RETELL_PEERS: usize = 256; |
| 95 | |
| 96 | pub(super) struct Thread { |
| 97 | config: Config, |
| 98 | me: Node, |
| 99 | /// Our hello's body, sent on every connection. |
| 100 | hello: Vec<u8>, |
| 101 | poll: Poll, |
| 102 | listener: TcpListener, |
| 103 | local_addr: SocketAddr, |
| 104 | client: Arc<ClientConfig>, |
| 105 | server: Arc<ServerConfig>, |
| 106 | conns: HashMap<Token, Conn>, |
| 107 | next_token: usize, |
| 108 | /// Connections that used up their [`SLICE`] before `WouldBlock`: no |
| 109 | /// event comes for what they have left, so they are driven again. |
| 110 | again: Vec<Token>, |
| 111 | /// Each node that is up, and its connection. |
| 112 | up: HashMap<String, Token>, |
| 113 | /// Nodes to stay connected to: seeds, `connect`'s, and (`mesh`) the |
| 114 | /// nodes peers list. |
| 115 | known: HashMap<String, Known>, |
| 116 | /// How many of `known` are discovered: at most `max_peers`. |
| 117 | discovered: usize, |
| 118 | /// By connection: how many discovered nodes on probation its lists |
| 119 | /// brought and still hold ([`Found::lister`]). |
| 120 | held: HashMap<Token, usize>, |
| 121 | /// How many discovered nodes no lister holds ([`Found::lister`]): the |
| 122 | /// first a new name may take the place of. |
| 123 | unheld: usize, |
| 124 | /// Per discovered node, how many up peers' latest lists hold it. |
| 125 | listings: HashMap<String, usize>, |
| 126 | /// This node's address in its lists; `None`: it gives none. |
| 127 | advertise: Option<SocketAddr>, |
| 128 | /// Peers up since the last turn, owed this node's list at its end. |
| 129 | welcome: Vec<Token>, |
| 130 | /// A node came up or went down since every peer was last sent the |
| 131 | /// list: sent again at most once per heartbeat ([`Thread::tell`]). |
| 132 | retell: bool, |
| 133 | told: Option<Instant>, |
| 134 | outbox: Arc<Outbox>, |
| 135 | /// What arrives goes to the handler through it. |
| 136 | inbound: Arc<Relay>, |
| 137 | heartbeat: Duration, |
| 138 | down_after: Duration, |
| 139 | /// Accepts that failed (out of descriptors, say): logged sparingly. |
| 140 | accept_errors: Throttle, |
| 141 | } |
| 142 | |
| 143 | struct Known { |
| 144 | addr: SocketAddr, |
| 145 | /// The next delay, in `reconnect_ms`. |
| 146 | backoff: u32, |
| 147 | /// When to dial; `None` while a connection names it. |
| 148 | due: Option<Instant>, |
| 149 | /// Learned from a peer's list; `None`, a seed or `connect`ed node, |
| 150 | /// whose address no list changes and which is never forgotten. |
| 151 | found: Option<Found>, |
| 152 | } |
| 153 | |
| 154 | /// What this node knows of a discovered node. |
| 155 | struct Found { |
| 156 | /// The address is the node's own word (its entry in its own list), or |
| 157 | /// a dial to it there came up: another peer's list does not replace |
| 158 | /// it. |
| 159 | confirmed: bool, |
| 160 | /// It came up, or confirmed its address: not on probation. |
| 161 | proven: bool, |
| 162 | /// The connection whose lists hold it for the discovery budget |
| 163 | /// ([`Thread::room`]): the one whose list brought it, or the next to |
| 164 | /// list it once that one no longer does. `None`: no lister holds it. |
| 165 | lister: Option<Token>, |
| 166 | /// Unconfirmed: how many dials were made, to try its listers' |
| 167 | /// addresses in turn. |
| 168 | dials: usize, |
| 169 | /// Since when it is neither up nor in any up peer's list: it is |
| 170 | /// forgotten [`FORGET_AFTER`] × `node_down_after_ms` later. |
| 171 | unlisted: Option<Instant>, |
| 172 | } |
| 173 | |
| 174 | enum Role { |
| 175 | /// We dialed this node. |
| 176 | Dial(String), |
| 177 | Accept, |
| 178 | } |
| 179 | |
| 180 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| 181 | enum Phase { |
| 182 | /// Waiting for the peer's hello (the dialer's has gone out with the |
| 183 | /// TLS handshake). |
| 184 | Hello, |
| 185 | /// Accepted: our hello went out, waiting for the dialer's ack. |
| 186 | Ack, |
| 187 | Up, |
| 188 | } |
| 189 | |
| 190 | struct Conn { |
| 191 | sock: TcpStream, |
| 192 | tls: Connection, |
| 193 | role: Role, |
| 194 | addr: SocketAddr, |
| 195 | phase: Phase, |
| 196 | /// The peer, once its hello is accepted. |
| 197 | peer: Option<Node>, |
| 198 | /// The name its hello claims, checked or not: for logs. |
| 199 | claimed: Option<String>, |
| 200 | /// The largest frame the peer accepts. |
| 201 | peer_max: u32, |
| 202 | /// The capability flags of the peer's hello. |
| 203 | peer_flags: u64, |
| 204 | /// Plaintext not framed yet: less than a frame and a chunk. |
| 205 | inbuf: Vec<u8>, |
| 206 | /// Frames to write, the first `offset` bytes of the front one given to |
| 207 | /// rustls already. |
| 208 | out: VecDeque<Entry>, |
| 209 | offset: usize, |
| 210 | /// Heartbeats and echoes, put in front of `out` at its next frame |
| 211 | /// boundary. |
| 212 | control: VecDeque<Entry>, |
| 213 | opened: Instant, |
| 214 | last_recv: Instant, |
| 215 | /// When the last heartbeat was queued. |
| 216 | pinged: Instant, |
| 217 | /// The stamp of the latest echo counted: an older one is not. |
| 218 | echoed: Option<u64>, |
| 219 | /// The peer's statistics, once up. |
| 220 | stats: Option<Arc<Stats>>, |
| 221 | /// Not read while the handler has a full backlog of its frames |
| 222 | /// (`relay`): the relay wakes the thread once it is down to half. |
| 223 | paused: bool, |
| 224 | /// Both hellos set [`frame::FLAG_PEERS`]: lists of peers go both ways. |
| 225 | mesh: bool, |
| 226 | /// The discovered nodes its latest list holds, at the address it |
| 227 | /// gives each. |
| 228 | listed: HashMap<String, SocketAddr>, |
| 229 | /// This node's latest list for it, not yet handed to [`Conn::out`]: |
| 230 | /// its frames' bodies, shared by every peer of the same frame limit. A |
| 231 | /// newer list replaces it, so a peer that does not read holds one. |
| 232 | list: Option<Arc<[Vec<u8>]>>, |
| 233 | } |
| 234 | |
| 235 | impl Conn { |
| 236 | fn new(sock: TcpStream, tls: Connection, role: Role, addr: SocketAddr) -> Conn { |
| 237 | let now = Instant::now(); |
| 238 | Conn { |
| 239 | sock, |
| 240 | tls, |
| 241 | role, |
| 242 | addr, |
| 243 | phase: Phase::Hello, |
| 244 | peer: None, |
| 245 | claimed: None, |
| 246 | peer_max: MIN_FRAME, |
| 247 | peer_flags: 0, |
| 248 | inbuf: Vec::new(), |
| 249 | out: VecDeque::new(), |
| 250 | offset: 0, |
| 251 | control: VecDeque::new(), |
| 252 | opened: now, |
| 253 | last_recv: now, |
| 254 | pinged: now, |
| 255 | echoed: None, |
| 256 | stats: None, |
| 257 | paused: false, |
| 258 | mesh: false, |
| 259 | listed: HashMap::new(), |
| 260 | list: None, |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// Microseconds since it opened: a heartbeat's stamp. |
| 265 | fn stamp(&self, now: Instant) -> u64 { |
| 266 | u64::try_from(now.saturating_duration_since(self.opened).as_micros()).unwrap_or(u64::MAX) |
| 267 | } |
| 268 | |
| 269 | /// Queue a heartbeat in the control lane, unless one waits there |
| 270 | /// already (the socket takes nothing). |
| 271 | fn ping(&mut self, now: Instant) { |
| 272 | self.pinged = now; |
| 273 | if !self.control.iter().any(|e| e.kind() == frame::HEARTBEAT) { |
| 274 | let stamp = self.stamp(now).to_le_bytes().to_vec(); |
| 275 | self.control.push_back(Entry::new(frame::HEARTBEAT, stamp)); |
| 276 | } |
| 277 | } |
| 278 | |
| 279 | /// Answer the peer's heartbeat: one echo waits at most, of its latest |
| 280 | /// stamp, so a peer that sends heartbeats and reads nothing does not |
| 281 | /// grow the lane. |
| 282 | fn answer(&mut self, stamp: &[u8]) { |
| 283 | match self.control.iter_mut().find(|e| e.kind() == frame::ECHO) { |
| 284 | Some(echo) => echo.body.copy_from_slice(stamp), |
| 285 | None => self |
| 286 | .control |
| 287 | .push_back(Entry::new(frame::ECHO, stamp.to_vec())), |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | /// The echo of a heartbeat: its round-trip time, unless an echo of a |
| 292 | /// later one was counted already, or it is not a stamp of ours. |
| 293 | fn echo(&mut self, stamp: u64, now: Instant) { |
| 294 | let now = self.stamp(now); |
| 295 | if stamp > now || self.echoed >= Some(stamp) { |
| 296 | return; |
| 297 | } |
| 298 | self.echoed = Some(stamp); |
| 299 | if let Some(stats) = &self.stats { |
| 300 | stats.rtt_us.store(now - stamp, Ordering::Relaxed); |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | /// The node this connection is with, as far as it is known. |
| 305 | fn name(&self) -> Option<&str> { |
| 306 | match (&self.peer, &self.role) { |
| 307 | (Some(peer), _) => Some(&peer.name), |
| 308 | (None, Role::Dial(name)) => Some(name), |
| 309 | (None, Role::Accept) => None, |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | /// For logs: the node, or its address and the name it claims before |
| 314 | /// its hello is accepted. |
| 315 | fn label(&self) -> String { |
| 316 | match (self.name(), &self.claimed) { |
| 317 | (Some(name), _) => name.to_owned(), |
| 318 | (None, Some(claimed)) => format!("{claimed} at {}", self.addr), |
| 319 | (None, None) => self.addr.to_string(), |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | impl Thread { |
| 325 | /// Load the certificates, listen, and set up the poll; the thread runs |
| 326 | /// [`Thread::run`]. |
| 327 | pub(super) fn new(config: Config, me: Node, inbound: Arc<Relay>) -> Result<Thread, String> { |
| 328 | let leaf = CertificateDer::from_pem_file(&config.cert_file) |
| 329 | .map_err(|e| format!("{}: {e}", config.cert_file))?; |
| 330 | if !has_name(&leaf, &config.node) { |
| 331 | return Err(format!( |
| 332 | "the certificate {} is not valid for the node name {}", |
| 333 | config.cert_file, config.node |
| 334 | )); |
| 335 | } |
| 336 | let identity = || Identity { |
| 337 | cert_file: config.cert_file.clone(), |
| 338 | key_file: config.key_file.clone(), |
| 339 | }; |
| 340 | let authorities = || Authorities { |
| 341 | default_roots: false, |
| 342 | pems: Vec::new(), |
| 343 | files: config.ca_files.clone(), |
| 344 | }; |
| 345 | let client = crate::tls::client_config(ClientOptions { |
| 346 | authorities: authorities(), |
| 347 | identity: Some(identity()), |
| 348 | alpn: vec![frame::ALPN.to_vec()], |
| 349 | tls13_only: true, |
| 350 | insecure: false, |
| 351 | })?; |
| 352 | // No resumption: every connection verifies the peer's chain and |
| 353 | // its dates (the acceptor issues no ticket either). |
| 354 | let mut client = Arc::unwrap_or_clone(client); |
| 355 | client.resumption = Resumption::disabled(); |
| 356 | let client = Arc::new(client); |
| 357 | let server = crate::tls::server_config(ServerOptions { |
| 358 | identity: identity(), |
| 359 | client_authorities: Some(authorities()), |
| 360 | alpn: vec![frame::ALPN.to_vec()], |
| 361 | tls13_only: true, |
| 362 | peers: true, |
| 363 | })?; |
| 364 | let poll = Poll::new().map_err(|e| format!("cannot create the transport's poll: {e}"))?; |
| 365 | let waker = Waker::new(poll.registry(), WAKER) |
| 366 | .map_err(|e| format!("cannot create the transport's waker: {e}"))?; |
| 367 | let mut listener = TcpListener::bind(config.listen) |
| 368 | .map_err(|e| format!("cannot listen on {}: {e}", config.listen))?; |
| 369 | let local_addr = listener |
| 370 | .local_addr() |
| 371 | .map_err(|e| format!("cannot listen on {}: {e}", config.listen))?; |
| 372 | poll.registry() |
| 373 | .register(&mut listener, LISTENER, Interest::READABLE) |
| 374 | .map_err(|e| format!("cannot poll the listener: {e}"))?; |
| 375 | let hello = Hello { |
| 376 | version: frame::VERSION, |
| 377 | flags: frame::FLAGS_OPS | if config.mesh { frame::FLAG_PEERS } else { 0 }, |
| 378 | incarnation: me.incarnation, |
| 379 | schema_hash: config.schema_hash, |
| 380 | max_frame: config.max_frame, |
| 381 | cluster: config.cluster.clone(), |
| 382 | node: config.node.clone(), |
| 383 | } |
| 384 | .encode(); |
| 385 | let now = Instant::now(); |
| 386 | let known = config |
| 387 | .seeds |
| 388 | .iter() |
| 389 | .map(|(name, addr)| { |
| 390 | let known = Known { |
| 391 | addr: *addr, |
| 392 | backoff: 1, |
| 393 | due: Some(now), |
| 394 | found: None, |
| 395 | }; |
| 396 | (name.clone(), known) |
| 397 | }) |
| 398 | .collect(); |
| 399 | let outbox = Arc::new(Outbox { |
| 400 | routes: Mutex::default(), |
| 401 | stats: Mutex::new(PeerStats::new(config.max_peers)), |
| 402 | commands: Mutex::default(), |
| 403 | waker, |
| 404 | woken: AtomicBool::new(false), |
| 405 | max_queue: config.max_queue, |
| 406 | open: AtomicUsize::new(0), |
| 407 | dropped: AtomicU64::new(0), |
| 408 | }); |
| 409 | let advertise = config.advertise.or_else(|| { |
| 410 | let listened = (!config.listen.ip().is_unspecified()).then_some(local_addr); |
| 411 | listened.filter(|a| frame::dialable(*a)) |
| 412 | }); |
| 413 | Ok(Thread { |
| 414 | heartbeat: Duration::from_millis(config.heartbeat_ms), |
| 415 | down_after: Duration::from_millis(config.node_down_after_ms), |
| 416 | config, |
| 417 | me, |
| 418 | hello, |
| 419 | poll, |
| 420 | listener, |
| 421 | local_addr, |
| 422 | client, |
| 423 | server, |
| 424 | conns: HashMap::new(), |
| 425 | next_token: LISTENER.0 + 1, |
| 426 | again: Vec::new(), |
| 427 | up: HashMap::new(), |
| 428 | known, |
| 429 | discovered: 0, |
| 430 | held: HashMap::new(), |
| 431 | unheld: 0, |
| 432 | listings: HashMap::new(), |
| 433 | advertise, |
| 434 | welcome: Vec::new(), |
| 435 | retell: false, |
| 436 | told: None, |
| 437 | outbox, |
| 438 | inbound, |
| 439 | accept_errors: Throttle::default(), |
| 440 | }) |
| 441 | } |
| 442 | |
| 443 | pub(super) fn outbox(&self) -> Arc<Outbox> { |
| 444 | self.outbox.clone() |
| 445 | } |
| 446 | |
| 447 | pub(super) fn local_addr(&self) -> SocketAddr { |
| 448 | self.local_addr |
| 449 | } |
| 450 | |
| 451 | /// Until [`Command::Stop`]: then what is queued is written, as far as |
| 452 | /// the sockets take it, and every connection closes. |
| 453 | pub(super) fn run(mut self) { |
| 454 | let mut events = Events::with_capacity(256); |
| 455 | loop { |
| 456 | let timeout = if self.again.is_empty() { |
| 457 | self.next_deadline() |
| 458 | .map(|at| at.saturating_duration_since(Instant::now())) |
| 459 | } else { |
| 460 | Some(Duration::ZERO) |
| 461 | }; |
| 462 | if let Err(e) = self.poll.poll(&mut events, timeout) { |
| 463 | if e.kind() == ErrorKind::Interrupted { |
| 464 | continue; |
| 465 | } |
| 466 | eprintln!("louise: dist: the transport's poll failed: {e}"); |
| 467 | break; |
| 468 | } |
| 469 | // Taken before the events: a connection that an event drives, |
| 470 | // and that runs out of its slice again, waits for the next |
| 471 | // round. |
| 472 | let again = std::mem::take(&mut self.again); |
| 473 | let mut woken = false; |
| 474 | for event in &events { |
| 475 | match event.token() { |
| 476 | WAKER => woken = true, |
| 477 | LISTENER => self.accept(), |
| 478 | token => self.drive(token), |
| 479 | } |
| 480 | } |
| 481 | if woken { |
| 482 | // Before taking anything: a sender that queues after this |
| 483 | // wakes the thread again. |
| 484 | self.outbox.woken.store(false, Ordering::Release); |
| 485 | if self.commands() { |
| 486 | break; |
| 487 | } |
| 488 | let up: Vec<Token> = self.up.values().copied().collect(); |
| 489 | for token in up { |
| 490 | self.drive_write(token); |
| 491 | } |
| 492 | self.resume(); |
| 493 | } |
| 494 | for token in again { |
| 495 | match token { |
| 496 | _ if self.again.contains(&token) => {} |
| 497 | LISTENER => self.accept(), |
| 498 | token => self.drive(token), |
| 499 | } |
| 500 | } |
| 501 | // After reading: a stalled thread finds the bytes that arrived |
| 502 | // meanwhile before it judges a peer silent. |
| 503 | self.tick(Instant::now()); |
| 504 | self.tell(Instant::now()); |
| 505 | } |
| 506 | // What senders queued before the stop is written, as far as each |
| 507 | // socket takes it without waiting: a program's last messages |
| 508 | // before it ends (a reply, say) are not dropped for that alone. |
| 509 | let up: Vec<Token> = self.up.values().copied().collect(); |
| 510 | for token in up { |
| 511 | self.drive_write(token); |
| 512 | } |
| 513 | let mut tokens: Vec<Token> = self.conns.keys().copied().collect(); |
| 514 | tokens.sort_unstable(); |
| 515 | for token in tokens { |
| 516 | if let Some(conn) = self.conns.remove(&token) { |
| 517 | self.close(token, conn, Reason::Stopped); |
| 518 | } |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | /// Carry out the handle's commands; true to stop. |
| 523 | fn commands(&mut self) -> bool { |
| 524 | let commands = std::mem::take( |
| 525 | &mut *self |
| 526 | .outbox |
| 527 | .commands |
| 528 | .lock() |
| 529 | .unwrap_or_else(PoisonError::into_inner), |
| 530 | ); |
| 531 | for command in commands { |
| 532 | match command { |
| 533 | Command::Stop => return true, |
| 534 | Command::Connect(name, addr) => { |
| 535 | if name == self.me.name { |
| 536 | continue; |
| 537 | } |
| 538 | let known = self.known.entry(name).or_insert(Known { |
| 539 | addr, |
| 540 | backoff: 1, |
| 541 | due: None, |
| 542 | found: None, |
| 543 | }); |
| 544 | known.addr = addr; |
| 545 | known.due = Some(Instant::now()); |
| 546 | // Kept from now on, as a seed. |
| 547 | if let Some(found) = known.found.take() { |
| 548 | self.discovered -= 1; |
| 549 | self.release(&found); |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | } |
| 554 | false |
| 555 | } |
| 556 | |
| 557 | // ---- timers ---------------------------------------------------------------------- |
| 558 | |
| 559 | /// Close silent connections and overdue handshakes, send heartbeats, |
| 560 | /// forget the discovered nodes unlisted for long enough, dial the known |
| 561 | /// nodes that are due (a discovered one only below `max_peers`). |
| 562 | fn tick(&mut self, now: Instant) { |
| 563 | let mut expired = Vec::new(); |
| 564 | let mut beats = Vec::new(); |
| 565 | for (&token, c) in &self.conns { |
| 566 | let since = match c.phase { |
| 567 | // Not read by choice (`relay`): not silent. |
| 568 | Phase::Up if c.paused => now, |
| 569 | Phase::Up => c.last_recv, |
| 570 | _ => c.opened, |
| 571 | }; |
| 572 | if now.saturating_duration_since(since) >= self.down_after { |
| 573 | expired.push(token); |
| 574 | } else if c.phase == Phase::Up |
| 575 | && now.saturating_duration_since(c.pinged) >= self.heartbeat |
| 576 | { |
| 577 | beats.push(token); |
| 578 | } |
| 579 | } |
| 580 | expired.sort_unstable(); |
| 581 | for token in expired { |
| 582 | if let Some(conn) = self.conns.remove(&token) { |
| 583 | self.close(token, conn, Reason::Timeout); |
| 584 | } |
| 585 | } |
| 586 | for token in beats { |
| 587 | if let Some(conn) = self.conns.get_mut(&token) { |
| 588 | conn.ping(now); |
| 589 | self.drive_write(token); |
| 590 | } |
| 591 | } |
| 592 | let forget = self.down_after * FORGET_AFTER; |
| 593 | let forgotten: Vec<String> = self |
| 594 | .known |
| 595 | .iter() |
| 596 | .filter(|(_, k)| { |
| 597 | k.found |
| 598 | .as_ref() |
| 599 | .and_then(|f| f.unlisted) |
| 600 | .is_some_and(|at| now.saturating_duration_since(at) >= forget) |
| 601 | }) |
| 602 | .map(|(name, _)| name.clone()) |
| 603 | .collect(); |
| 604 | for name in forgotten { |
| 605 | self.forget(&name); |
| 606 | } |
| 607 | let due: Vec<String> = self |
| 608 | .known |
| 609 | .iter() |
| 610 | .filter(|(_, k)| k.due.is_some_and(|at| at <= now)) |
| 611 | .map(|(name, _)| name.clone()) |
| 612 | .collect(); |
| 613 | for name in due { |
| 614 | let found = self.known.get(&name).is_some_and(|k| k.found.is_some()); |
| 615 | if self.named(&name) { |
| 616 | if let Some(k) = self.known.get_mut(&name) { |
| 617 | k.due = None; |
| 618 | } |
| 619 | } else if found && self.peers() >= self.config.max_peers { |
| 620 | // It would refuse the peer's hello: later, with backoff. |
| 621 | self.lost(&name); |
| 622 | } else { |
| 623 | self.dial(&name); |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | /// When [`Thread::tick`] next has something to do. |
| 629 | fn next_deadline(&self) -> Option<Instant> { |
| 630 | let conns = self.conns.values().flat_map(|c| { |
| 631 | if c.phase == Phase::Up { |
| 632 | [ |
| 633 | (!c.paused).then(|| c.last_recv + self.down_after), |
| 634 | Some(c.pinged + self.heartbeat), |
| 635 | ] |
| 636 | } else { |
| 637 | [Some(c.opened + self.down_after), None] |
| 638 | } |
| 639 | }); |
| 640 | let known = self.known.values().map(|k| k.due); |
| 641 | let forget = self.down_after * FORGET_AFTER; |
| 642 | let unlisted = self.known.values().map(|k| { |
| 643 | let since = k.found.as_ref().and_then(|f| f.unlisted); |
| 644 | since.map(|at| at + forget) |
| 645 | }); |
| 646 | let retell = self |
| 647 | .retell |
| 648 | .then(|| self.told.map_or_else(Instant::now, |t| t + self.heartbeat)); |
| 649 | conns |
| 650 | .chain(known) |
| 651 | .chain(unlisted) |
| 652 | .chain([retell]) |
| 653 | .flatten() |
| 654 | .min() |
| 655 | } |
| 656 | |
| 657 | // ---- connections ------------------------------------------------------------------- |
| 658 | |
| 659 | /// Whether a connection (in the map) is with `name`, up or not. |
| 660 | fn named(&self, name: &str) -> bool { |
| 661 | self.conns.values().any(|c| c.name() == Some(name)) |
| 662 | } |
| 663 | |
| 664 | /// Connections (in the map) past their hello: what `max_peers` caps. |
| 665 | fn peers(&self) -> usize { |
| 666 | self.conns.values().filter(|c| c.peer.is_some()).count() |
| 667 | } |
| 668 | |
| 669 | fn dial(&mut self, name: &str) { |
| 670 | // Unconfirmed: its listers' addresses in turn, one each, in the |
| 671 | // order of their connections. Not in the addresses' order: a liar |
| 672 | // could then list, before each dial, one that sorts just where the |
| 673 | // next turn falls, and hold every turn. |
| 674 | let mut listers: Vec<(Token, SocketAddr)> = self |
| 675 | .conns |
| 676 | .iter() |
| 677 | .filter_map(|(token, c)| Some((*token, *c.listed.get(name)?))) |
| 678 | .collect(); |
| 679 | listers.sort_unstable_by_key(|(token, _)| *token); |
| 680 | let mut given = HashSet::new(); |
| 681 | let addrs: Vec<SocketAddr> = listers |
| 682 | .into_iter() |
| 683 | .map(|(_, addr)| addr) |
| 684 | .filter(|addr| given.insert(*addr)) |
| 685 | .collect(); |
| 686 | let Some(known) = self.known.get_mut(name) else { |
| 687 | return; |
| 688 | }; |
| 689 | known.due = None; |
| 690 | if let Some(found) = known.found.as_mut().filter(|f| !f.confirmed) |
| 691 | && !addrs.is_empty() |
| 692 | { |
| 693 | known.addr = addrs[found.dials % addrs.len()]; |
| 694 | found.dials = found.dials.wrapping_add(1); |
| 695 | } |
| 696 | let addr = known.addr; |
| 697 | let tls = ServerName::try_from(name.to_owned()) |
| 698 | .map_err(|e| e.to_string()) |
| 699 | .and_then(|server| { |
| 700 | ClientConnection::new(self.client.clone(), server).map_err(|e| e.to_string()) |
| 701 | }); |
| 702 | let opened = tls.and_then(|tls| { |
| 703 | TcpStream::connect(addr) |
| 704 | .map(|sock| (sock, tls)) |
| 705 | .map_err(|e| e.to_string()) |
| 706 | }); |
| 707 | let (sock, tls) = match opened { |
| 708 | Ok(opened) => opened, |
| 709 | Err(e) => { |
| 710 | let hearsay = self.hearsay(name); |
| 711 | self.inbound.closed(name, &Reason::Closed(e), hearsay); |
| 712 | self.lost(name); |
| 713 | return; |
| 714 | } |
| 715 | }; |
| 716 | // Small frames go out at once; a failure only delays them. |
| 717 | let _ = sock.set_nodelay(true); |
| 718 | let mut conn = Conn::new(sock, tls.into(), Role::Dial(name.to_owned()), addr); |
| 719 | conn.out |
| 720 | .push_back(Entry::new(frame::HELLO, self.hello.clone())); |
| 721 | self.register(conn); |
| 722 | } |
| 723 | |
| 724 | /// Accept up to [`ACCEPTS`] connections, then let the others have |
| 725 | /// their turn: a flood of connections does not hold up heartbeats. |
| 726 | fn accept(&mut self) { |
| 727 | let mut accepted = 0; |
| 728 | while accepted < ACCEPTS { |
| 729 | let (sock, addr) = match self.listener.accept() { |
| 730 | Ok(accepted) => accepted, |
| 731 | Err(e) if e.kind() == ErrorKind::WouldBlock => return, |
| 732 | Err(e) if e.kind() == ErrorKind::Interrupted => continue, |
| 733 | Err(e) => { |
| 734 | // Out of descriptors, say: the next connection retries. |
| 735 | if let Some(held) = self.accept_errors.admit(Instant::now()) { |
| 736 | eprintln!( |
| 737 | "louise: dist: cannot accept a connection: {e}{}", |
| 738 | Throttle::held_back(held) |
| 739 | ); |
| 740 | } |
| 741 | return; |
| 742 | } |
| 743 | }; |
| 744 | accepted += 1; |
| 745 | let Ok(tls) = ServerConnection::new(self.server.clone()) else { |
| 746 | continue; |
| 747 | }; |
| 748 | self.make_room(source(addr.ip())); |
| 749 | let _ = sock.set_nodelay(true); |
| 750 | self.register(Conn::new(sock, tls.into(), Role::Accept, addr)); |
| 751 | } |
| 752 | if !self.again.contains(&LISTENER) { |
| 753 | self.again.push(LISTENER); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | /// Keep accepted connections whose hello is not in yet under |
| 758 | /// [`MAX_UNAUTHENTICATED_PER_SOURCE`] for `from`, and under |
| 759 | /// [`MAX_UNAUTHENTICATED`] in all, counting the one about to be |
| 760 | /// accepted from `from`: its source's oldest goes, else the oldest of |
| 761 | /// the source that holds the most. Refusing the newest instead would let |
| 762 | /// a host that holds that many idle sockets keep every node from dialing |
| 763 | /// in; closing the oldest of all, a host opening connections faster |
| 764 | /// than a distant node's handshake. |
| 765 | fn make_room(&mut self, from: IpAddr) { |
| 766 | let mut pending: HashMap<IpAddr, (usize, Instant, Token)> = HashMap::new(); |
| 767 | let mut total = 0; |
| 768 | for (&token, c) in &self.conns { |
| 769 | if !matches!(c.role, Role::Accept) || c.peer.is_some() { |
| 770 | continue; |
| 771 | } |
| 772 | total += 1; |
| 773 | let oldest = (c.opened, token); |
| 774 | let entry = pending |
| 775 | .entry(source(c.addr.ip())) |
| 776 | .or_insert((0, oldest.0, oldest.1)); |
| 777 | entry.0 += 1; |
| 778 | if oldest < (entry.1, entry.2) { |
| 779 | (entry.1, entry.2) = oldest; |
| 780 | } |
| 781 | } |
| 782 | let own = pending |
| 783 | .get(&from) |
| 784 | .filter(|p| p.0 >= MAX_UNAUTHENTICATED_PER_SOURCE); |
| 785 | let victim = match own { |
| 786 | Some(&(_, _, token)) => Some(token), |
| 787 | None if total >= MAX_UNAUTHENTICATED => pending |
| 788 | .values() |
| 789 | .max_by_key(|(n, opened, token)| (*n, std::cmp::Reverse((*opened, *token)))) |
| 790 | .map(|&(_, _, token)| token), |
| 791 | None => None, |
| 792 | }; |
| 793 | if let Some(token) = victim |
| 794 | && let Some(conn) = self.conns.remove(&token) |
| 795 | { |
| 796 | self.close(token, conn, Reason::Crowded); |
| 797 | } |
| 798 | } |
| 799 | |
| 800 | fn register(&mut self, mut conn: Conn) { |
| 801 | let token = Token(self.next_token); |
| 802 | self.next_token += 1; |
| 803 | if let Err(e) = self.poll.registry().register( |
| 804 | &mut conn.sock, |
| 805 | token, |
| 806 | Interest::READABLE | Interest::WRITABLE, |
| 807 | ) { |
| 808 | // A local failure, not the peers' doing. |
| 809 | self.inbound |
| 810 | .closed(&conn.label(), &Reason::Closed(e.to_string()), false); |
| 811 | if let Some(name) = conn.name().map(str::to_owned) { |
| 812 | self.lost(&name); |
| 813 | } |
| 814 | return; |
| 815 | } |
| 816 | self.outbox.open.fetch_add(1, Ordering::AcqRel); |
| 817 | self.conns.insert(token, conn); |
| 818 | } |
| 819 | |
| 820 | /// Read, then write, `token`'s connection as far as it goes, for a |
| 821 | /// [`SLICE`] each at most (a peer that floods this node still gets its |
| 822 | /// frames). Out of the map meanwhile: what its frames do may close |
| 823 | /// others. |
| 824 | fn drive(&mut self, token: Token) { |
| 825 | let Some(mut conn) = self.conns.remove(&token) else { |
| 826 | return; |
| 827 | }; |
| 828 | let done = self |
| 829 | .read(token, &mut conn, Instant::now() + SLICE) |
| 830 | .and_then(|more_in| { |
| 831 | let more_out = self.flush(&mut conn, Instant::now() + SLICE)?; |
| 832 | Ok(more_in || more_out) |
| 833 | }); |
| 834 | self.settle(token, conn, done); |
| 835 | } |
| 836 | |
| 837 | /// Read again the paused connections the relay has room for again: |
| 838 | /// no event comes for the bytes their sockets hold already. Silence is |
| 839 | /// timed from now. |
| 840 | fn resume(&mut self) { |
| 841 | let resumed: Vec<Token> = self |
| 842 | .conns |
| 843 | .iter_mut() |
| 844 | .filter(|(_, c)| c.paused) |
| 845 | .filter(|(_, c)| { |
| 846 | c.peer |
| 847 | .as_ref() |
| 848 | .is_some_and(|p| self.inbound.resumed(&p.name)) |
| 849 | }) |
| 850 | .map(|(&token, c)| { |
| 851 | c.paused = false; |
| 852 | c.last_recv = Instant::now(); |
| 853 | token |
| 854 | }) |
| 855 | .collect(); |
| 856 | for token in resumed { |
| 857 | self.drive(token); |
| 858 | } |
| 859 | } |
| 860 | |
| 861 | fn drive_write(&mut self, token: Token) { |
| 862 | let Some(mut conn) = self.conns.remove(&token) else { |
| 863 | return; |
| 864 | }; |
| 865 | let done = self.flush(&mut conn, Instant::now() + SLICE); |
| 866 | self.settle(token, conn, done); |
| 867 | } |
| 868 | |
| 869 | /// Back into the map, and driven again if its slice ran out (`more`), |
| 870 | /// or closed. |
| 871 | fn settle(&mut self, token: Token, conn: Conn, done: Result<bool, Reason>) { |
| 872 | match done { |
| 873 | Ok(more) => { |
| 874 | self.conns.insert(token, conn); |
| 875 | if more && !self.again.contains(&token) { |
| 876 | self.again.push(token); |
| 877 | } |
| 878 | } |
| 879 | Err(reason) => self.close(token, conn, reason), |
| 880 | } |
| 881 | } |
| 882 | |
| 883 | /// Close a connection (out of the map): tell the peer why if it is a |
| 884 | /// refusal and a frame boundary allows, then the node is down if it |
| 885 | /// was up, and a known node is dialed again later. |
| 886 | fn close(&mut self, token: Token, mut conn: Conn, reason: Reason) { |
| 887 | if let Some(code) = reason.code() |
| 888 | && conn.offset == 0 |
| 889 | { |
| 890 | let refusal = Entry::new(frame::REFUSE, frame::refusal(code, &reason.to_string())); |
| 891 | let _ = conn |
| 892 | .tls |
| 893 | .writer() |
| 894 | .write_vectored(&[IoSlice::new(&refusal.head), IoSlice::new(&refusal.body)]); |
| 895 | } |
| 896 | conn.tls.send_close_notify(); |
| 897 | // Best effort, without waiting: a few writes, then the socket goes. |
| 898 | for _ in 0..4 { |
| 899 | if !conn.tls.wants_write() |
| 900 | || conn.tls.write_tls(&mut NoSigPipe::new(&conn.sock)).is_err() |
| 901 | { |
| 902 | break; |
| 903 | } |
| 904 | } |
| 905 | let _ = self.poll.registry().deregister(&mut conn.sock); |
| 906 | let _ = conn.sock.shutdown(Shutdown::Both); |
| 907 | self.outbox.open.fetch_sub(1, Ordering::AcqRel); |
| 908 | // A dial that never got past its hello, to an address only lists |
| 909 | // gave: the peers chose it, so it is logged sparingly. |
| 910 | let hearsay = |
| 911 | matches!(&conn.role, Role::Dial(name) if conn.peer.is_none() && self.hearsay(name)); |
| 912 | self.inbound.closed(&conn.label(), &reason, hearsay); |
| 913 | let now = Instant::now(); |
| 914 | for name in std::mem::take(&mut conn.listed).into_keys() { |
| 915 | self.unlist(token, &name); |
| 916 | self.relist(&name, now); |
| 917 | } |
| 918 | self.held.remove(&token); |
| 919 | if conn.phase == Phase::Up |
| 920 | && let Some(peer) = &conn.peer |
| 921 | { |
| 922 | if self.up.get(&peer.name) == Some(&token) { |
| 923 | self.up.remove(&peer.name); |
| 924 | self.relist(&peer.name, now); |
| 925 | self.retell = true; |
| 926 | let route = self.outbox.routes().remove(&peer.name); |
| 927 | self.outbox.peer_stats().down(&peer.name); |
| 928 | // Lost with the connection; a parked sender's next try is |
| 929 | // refused, and counts its own. |
| 930 | let messages = |q: &VecDeque<Entry>| { |
| 931 | q.iter().filter(|e| e.kind() == frame::MESSAGE).count() as u64 |
| 932 | }; |
| 933 | let lost = messages(&conn.out) + route.as_ref().map_or(0, |r| messages(&r.queue)); |
| 934 | if let Some(stats) = &conn.stats { |
| 935 | Stats::count(&stats.unsent, lost); |
| 936 | } |
| 937 | if let Some(route) = route |
| 938 | && !route.parked.is_empty() |
| 939 | { |
| 940 | self.inbound.drained(peer, &route.parked); |
| 941 | } |
| 942 | } |
| 943 | self.inbound.node_down(peer); |
| 944 | } |
| 945 | if let Some(name) = conn.name() { |
| 946 | self.lost(name); |
| 947 | } |
| 948 | } |
| 949 | |
| 950 | /// A connection with `name` closed: dial it again later if it is known |
| 951 | /// and no other connection is with it. |
| 952 | fn lost(&mut self, name: &str) { |
| 953 | if self.named(name) { |
| 954 | return; |
| 955 | } |
| 956 | let Some(known) = self.known.get_mut(name) else { |
| 957 | return; |
| 958 | }; |
| 959 | let delay = Duration::from_millis(self.config.reconnect_ms) * known.backoff; |
| 960 | known.backoff = (known.backoff * 2).min(MAX_BACKOFF); |
| 961 | known.due = Some(Instant::now() + delay); |
| 962 | } |
| 963 | |
| 964 | // ---- reading ----------------------------------------------------------------------- |
| 965 | |
| 966 | /// Read and handle frames until the socket would block (false) or |
| 967 | /// `until` (true: there may be more). |
| 968 | /// A peer whose frames fill the relay's backlog is not read |
| 969 | /// ([`Conn::paused`]): TCP pushes back on its sender. |
| 970 | fn read(&mut self, token: Token, conn: &mut Conn, until: Instant) -> Result<bool, Reason> { |
| 971 | let mut chunk = [0u8; CHUNK]; |
| 972 | loop { |
| 973 | if let Some(peer) = &conn.peer |
| 974 | && conn.phase == Phase::Up |
| 975 | && self.inbound.full(&peer.name) |
| 976 | { |
| 977 | conn.paused = true; |
| 978 | return Ok(false); |
| 979 | } |
| 980 | if Instant::now() >= until { |
| 981 | return Ok(true); |
| 982 | } |
| 983 | let eof = match conn.tls.read_tls(&mut conn.sock) { |
| 984 | Ok(0) => true, |
| 985 | Ok(_) => { |
| 986 | conn.last_recv = Instant::now(); |
| 987 | false |
| 988 | } |
| 989 | Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(false), |
| 990 | Err(e) if e.kind() == ErrorKind::Interrupted => continue, |
| 991 | Err(e) => return Err(Reason::Closed(e.to_string())), |
| 992 | }; |
| 993 | let state = conn.tls.process_new_packets().map_err(|e| match e { |
| 994 | // In order, but before the handshake completed: a peer that |
| 995 | // dropped a simultaneous dial, say. |
| 996 | rustls::Error::AlertReceived(rustls::AlertDescription::CloseNotify) => { |
| 997 | Reason::PeerClosed |
| 998 | } |
| 999 | e => Reason::Tls(e.to_string()), |
| 1000 | })?; |
| 1001 | let mut left = state.plaintext_bytes_to_read(); |
| 1002 | while left > 0 { |
| 1003 | let n = match conn.tls.reader().read(&mut chunk) { |
| 1004 | Ok(0) => break, |
| 1005 | Ok(n) => n, |
| 1006 | Err(e) if e.kind() == ErrorKind::WouldBlock => break, |
| 1007 | Err(e) => return Err(Reason::Closed(e.to_string())), |
| 1008 | }; |
| 1009 | left = left.saturating_sub(n); |
| 1010 | conn.inbuf.extend_from_slice(&chunk[..n]); |
| 1011 | self.frames(token, conn)?; |
| 1012 | } |
| 1013 | if state.peer_has_closed() { |
| 1014 | return Err(Reason::PeerClosed); |
| 1015 | } |
| 1016 | if eof { |
| 1017 | return Err(Reason::Closed("end of stream".into())); |
| 1018 | } |
| 1019 | } |
| 1020 | } |
| 1021 | |
| 1022 | /// Handle the complete frames of `conn`'s input, keeping the rest. |
| 1023 | fn frames(&mut self, token: Token, conn: &mut Conn) -> Result<(), Reason> { |
| 1024 | let buf = std::mem::take(&mut conn.inbuf); |
| 1025 | let mut at = 0; |
| 1026 | let done = loop { |
| 1027 | // Untrusted peers send handshake frames only. |
| 1028 | let limit = if conn.phase == Phase::Up { |
| 1029 | self.config.max_frame |
| 1030 | } else { |
| 1031 | MIN_FRAME |
| 1032 | }; |
| 1033 | match frame::next(&buf[at..], limit) { |
| 1034 | Ok(Some((kind, body))) => { |
| 1035 | let body = &buf[at + body.start..at + body.end]; |
| 1036 | at += frame::PREFIX + 1 + body.len(); |
| 1037 | if let Err(reason) = self.frame(token, conn, kind, body) { |
| 1038 | break Err(reason); |
| 1039 | } |
| 1040 | } |
| 1041 | Ok(None) => break Ok(()), |
| 1042 | Err(reason) => break Err(reason), |
| 1043 | } |
| 1044 | }; |
| 1045 | conn.inbuf = buf; |
| 1046 | conn.inbuf.drain(..at); |
| 1047 | // A large frame's room is given back once it is handled. |
| 1048 | if conn.inbuf.capacity() > 4 * CHUNK && conn.inbuf.len() < CHUNK { |
| 1049 | conn.inbuf.shrink_to(CHUNK); |
| 1050 | } |
| 1051 | done |
| 1052 | } |
| 1053 | |
| 1054 | fn frame( |
| 1055 | &mut self, |
| 1056 | token: Token, |
| 1057 | conn: &mut Conn, |
| 1058 | kind: u8, |
| 1059 | body: &[u8], |
| 1060 | ) -> Result<(), Reason> { |
| 1061 | match (conn.phase, kind) { |
| 1062 | (_, frame::REFUSE) => Err(frame::refused(body)), |
| 1063 | (Phase::Hello, frame::HELLO) => self.hello(token, conn, body), |
| 1064 | (Phase::Ack, frame::ACK) if body.is_empty() => { |
| 1065 | self.go_up(token, conn); |
| 1066 | Ok(()) |
| 1067 | } |
| 1068 | (Phase::Up, frame::HEARTBEAT) if body.len() == frame::STAMP => { |
| 1069 | conn.answer(body); |
| 1070 | Ok(()) |
| 1071 | } |
| 1072 | (Phase::Up, frame::ECHO) if body.len() == frame::STAMP => { |
| 1073 | let mut stamp = [0; frame::STAMP]; |
| 1074 | stamp.copy_from_slice(body); |
| 1075 | conn.echo(u64::from_le_bytes(stamp), Instant::now()); |
| 1076 | Ok(()) |
| 1077 | } |
| 1078 | (Phase::Up, frame::MESSAGE) => self.message(conn, body), |
| 1079 | (Phase::Up, frame::SIGNAL) if body.first() == Some(&frame::PEERS) => { |
| 1080 | self.listed(token, conn, &body[1..]); |
| 1081 | Ok(()) |
| 1082 | } |
| 1083 | (Phase::Up, frame::SIGNAL) => { |
| 1084 | if let Some(peer) = &conn.peer { |
| 1085 | self.inbound.signal(peer, body); |
| 1086 | } |
| 1087 | Ok(()) |
| 1088 | } |
| 1089 | _ => Err(Reason::Protocol("an unexpected frame")), |
| 1090 | } |
| 1091 | } |
| 1092 | |
| 1093 | /// The peer's hello: check it against its certificate and ours, then |
| 1094 | /// against `max_peers` ([`Thread::full`]). The acceptor answers with |
| 1095 | /// its own hello, the dialer with an ack, and is up. |
| 1096 | /// |
| 1097 | /// The name is checked first: a peer whose certificate is not valid |
| 1098 | /// for the name it claims learns nothing of this node's cluster or |
| 1099 | /// schema from the refusal's code. |
| 1100 | fn hello(&mut self, token: Token, conn: &mut Conn, body: &[u8]) -> Result<(), Reason> { |
| 1101 | let hello = Hello::decode(body)?; |
| 1102 | conn.claimed = Some(hello.node.clone()); |
| 1103 | if conn.tls.alpn_protocol() != Some(frame::ALPN) { |
| 1104 | return Err(Reason::Alpn); |
| 1105 | } |
| 1106 | let dialed = match &conn.role { |
| 1107 | Role::Dial(name) => Some(name.as_str()), |
| 1108 | Role::Accept => None, |
| 1109 | }; |
| 1110 | let certified = conn |
| 1111 | .tls |
| 1112 | .peer_certificates() |
| 1113 | .and_then(|chain| chain.first()) |
| 1114 | .is_some_and(|leaf| has_name(leaf, &hello.node)); |
| 1115 | if !certified || hello.node == self.me.name || dialed.is_some_and(|d| d != hello.node) { |
| 1116 | return Err(Reason::Name(hello.node)); |
| 1117 | } |
| 1118 | if hello.cluster != self.config.cluster { |
| 1119 | return Err(Reason::Cluster(hello.cluster)); |
| 1120 | } |
| 1121 | if hello.schema_hash != self.config.schema_hash { |
| 1122 | return Err(Reason::Schema(hello.schema_hash)); |
| 1123 | } |
| 1124 | if hello.max_frame < MIN_FRAME { |
| 1125 | return Err(Reason::Protocol("a frame limit under 1 KiB")); |
| 1126 | } |
| 1127 | // Before the acceptor's hello or the dialer's ack goes out. |
| 1128 | if self.full(&hello.node) { |
| 1129 | return Err(Reason::Full); |
| 1130 | } |
| 1131 | let peer = Node { |
| 1132 | name: hello.node, |
| 1133 | incarnation: hello.incarnation, |
| 1134 | }; |
| 1135 | conn.peer_max = hello.max_frame.min(MAX_FRAME); |
| 1136 | conn.peer_flags = hello.flags; |
| 1137 | conn.mesh = self.config.mesh && hello.flags & frame::FLAG_PEERS != 0; |
| 1138 | if dialed.is_some() { |
| 1139 | if self.up.contains_key(&peer.name) || self.rivals(token, &peer.name).next().is_some() { |
| 1140 | return Err(Reason::Duplicate); |
| 1141 | } |
| 1142 | conn.peer = Some(peer); |
| 1143 | conn.out.push_back(Entry::new(frame::ACK, Vec::new())); |
| 1144 | self.go_up(token, conn); |
| 1145 | } else { |
| 1146 | self.arbitrate(token, &peer)?; |
| 1147 | conn.peer = Some(peer); |
| 1148 | conn.out |
| 1149 | .push_back(Entry::new(frame::HELLO, self.hello.clone())); |
| 1150 | conn.phase = Phase::Ack; |
| 1151 | } |
| 1152 | Ok(()) |
| 1153 | } |
| 1154 | |
| 1155 | /// Whether a connection with `name` would take this node past |
| 1156 | /// `max_peers` connections past their hello (this one, out of the map |
| 1157 | /// while it is driven, aside). Never for a seed or a `connect`ed node |
| 1158 | /// (the operator named it, and a full node must still reach it), nor |
| 1159 | /// for a node a connection is already past its hello with: this one |
| 1160 | /// replaces it, or is a duplicate. A discovered node may be refused. |
| 1161 | fn full(&self, name: &str) -> bool { |
| 1162 | if self.known.get(name).is_some_and(|k| k.found.is_none()) { |
| 1163 | return false; |
| 1164 | } |
| 1165 | let mut peers = 0; |
| 1166 | for c in self.conns.values() { |
| 1167 | match &c.peer { |
| 1168 | Some(p) if p.name == name => return false, |
| 1169 | Some(_) => peers += 1, |
| 1170 | None => {} |
| 1171 | } |
| 1172 | } |
| 1173 | peers >= self.config.max_peers |
| 1174 | } |
| 1175 | |
| 1176 | /// Other connections with `name` still in their handshake: whether each |
| 1177 | /// is ours (dialed). |
| 1178 | fn rivals<'a>( |
| 1179 | &'a self, |
| 1180 | token: Token, |
| 1181 | name: &'a str, |
| 1182 | ) -> impl Iterator<Item = (Token, bool)> + 'a { |
| 1183 | self.conns |
| 1184 | .iter() |
| 1185 | .filter(move |(t, c)| **t != token && c.phase != Phase::Up && c.name() == Some(name)) |
| 1186 | .map(|(t, c)| (*t, matches!(c.role, Role::Dial(_)))) |
| 1187 | } |
| 1188 | |
| 1189 | /// `peer` dialed us on `token`: keep this connection, or refuse it. |
| 1190 | /// - Up with the same incarnation: refused, the one up is kept (its |
| 1191 | /// own timeout ends it if it is dead). |
| 1192 | /// - Up with another incarnation: that one restarted, the old |
| 1193 | /// connection closes (its node is down). |
| 1194 | /// - Another of its dials further along: refused. |
| 1195 | /// - Our own dial to it in progress: the connection the smaller name |
| 1196 | /// initiated is kept, so both sides keep the same one. |
| 1197 | fn arbitrate(&mut self, token: Token, peer: &Node) -> Result<(), Reason> { |
| 1198 | if let Some(&up) = self.up.get(&peer.name) { |
| 1199 | let same = self |
| 1200 | .conns |
| 1201 | .get(&up) |
| 1202 | .and_then(|c| c.peer.as_ref()) |
| 1203 | .is_some_and(|p| p.incarnation == peer.incarnation); |
| 1204 | if same { |
| 1205 | return Err(Reason::Duplicate); |
| 1206 | } |
| 1207 | if let Some(old) = self.conns.remove(&up) { |
| 1208 | self.close(up, old, Reason::Replaced); |
| 1209 | } |
| 1210 | } |
| 1211 | let rivals: Vec<(Token, bool)> = self.rivals(token, &peer.name).collect(); |
| 1212 | for (rival, ours) in rivals { |
| 1213 | if !ours || keeps_dialer(&self.me.name, &peer.name) { |
| 1214 | return Err(Reason::Duplicate); |
| 1215 | } |
| 1216 | if let Some(conn) = self.conns.remove(&rival) { |
| 1217 | self.close(rival, conn, Reason::Duplicate); |
| 1218 | } |
| 1219 | } |
| 1220 | Ok(()) |
| 1221 | } |
| 1222 | |
| 1223 | fn go_up(&mut self, token: Token, conn: &mut Conn) { |
| 1224 | let Some(peer) = conn.peer.clone() else { |
| 1225 | return; |
| 1226 | }; |
| 1227 | conn.phase = Phase::Up; |
| 1228 | let stats = self.outbox.peer_stats().up(&peer.name); |
| 1229 | stats.incarnation.store(peer.incarnation, Ordering::Relaxed); |
| 1230 | stats.rtt_us.store(u64::MAX, Ordering::Relaxed); |
| 1231 | conn.stats = Some(stats.clone()); |
| 1232 | // A first round-trip time at once. |
| 1233 | conn.ping(Instant::now()); |
| 1234 | self.up.insert(peer.name.clone(), token); |
| 1235 | self.outbox.routes().insert( |
| 1236 | peer.name.clone(), |
| 1237 | Route { |
| 1238 | incarnation: peer.incarnation, |
| 1239 | max_frame: conn.peer_max, |
| 1240 | flags: conn.peer_flags, |
| 1241 | queue: VecDeque::new(), |
| 1242 | queued: 0, |
| 1243 | parked: Vec::new(), |
| 1244 | stats, |
| 1245 | }, |
| 1246 | ); |
| 1247 | if let Some(known) = self.known.get_mut(&peer.name) { |
| 1248 | known.backoff = 1; |
| 1249 | known.due = None; |
| 1250 | // A dial that came up confirms the address it dialed. |
| 1251 | if let (Some(found), Role::Dial(_)) = (&mut known.found, &conn.role) { |
| 1252 | known.addr = conn.addr; |
| 1253 | found.confirmed = true; |
| 1254 | } |
| 1255 | } |
| 1256 | self.prove(&peer.name); |
| 1257 | self.relist(&peer.name, Instant::now()); |
| 1258 | if conn.mesh { |
| 1259 | self.welcome.push(token); |
| 1260 | } |
| 1261 | self.retell = true; |
| 1262 | self.inbound.node_up(&peer); |
| 1263 | } |
| 1264 | |
| 1265 | // ---- discovery --------------------------------------------------------------------- |
| 1266 | |
| 1267 | /// A peer's list of nodes (op `03`; `fields` after the op): what it |
| 1268 | /// names that this node does not know becomes discovered. Dropped and |
| 1269 | /// counted if the connection does not carry lists ([`Conn::mesh`]), or |
| 1270 | /// if it is malformed. Past `max_peers` names (this node's own aside), |
| 1271 | /// the rest of the peer's list is not read. |
| 1272 | fn listed(&mut self, token: Token, conn: &mut Conn, fields: &[u8]) { |
| 1273 | let list = match (&conn.peer, conn.mesh) { |
| 1274 | (Some(peer), true) => frame::Peers::decode(fields) |
| 1275 | .ok() |
| 1276 | .map(|list| (peer.name.clone(), list)), |
| 1277 | _ => None, |
| 1278 | }; |
| 1279 | let Some((lister, list)) = list else { |
| 1280 | if let Some(stats) = &conn.stats { |
| 1281 | Stats::count(&stats.dropped, 1); |
| 1282 | } |
| 1283 | return; |
| 1284 | }; |
| 1285 | let now = Instant::now(); |
| 1286 | let mut changed = Vec::new(); |
| 1287 | if list.first { |
| 1288 | for name in std::mem::take(&mut conn.listed).into_keys() { |
| 1289 | self.unlist(token, &name); |
| 1290 | changed.push(name); |
| 1291 | } |
| 1292 | } |
| 1293 | // Once `room` finds none, it finds none for the rest of this list |
| 1294 | // (it costs a scan of `known`), until the lister's own entry |
| 1295 | // proves a name of its and so changes its share. |
| 1296 | let mut full = false; |
| 1297 | for (name, addr) in list.nodes { |
| 1298 | if name == self.me.name { |
| 1299 | continue; |
| 1300 | } |
| 1301 | let own = name == lister; |
| 1302 | if let Some(given) = conn.listed.get_mut(&name) { |
| 1303 | *given = addr; |
| 1304 | self.learn(token, &lister, &name, addr, now); |
| 1305 | full &= !own; |
| 1306 | continue; |
| 1307 | } |
| 1308 | // Past `max_peers` names, the rest of the list is not taken. |
| 1309 | if conn.listed.len() >= self.config.max_peers { |
| 1310 | continue; |
| 1311 | } |
| 1312 | if !self.known.contains_key(&name) && self.discovered >= self.config.max_peers { |
| 1313 | if full && !own { |
| 1314 | continue; |
| 1315 | } |
| 1316 | if !self.room(token, conn) { |
| 1317 | full = true; |
| 1318 | continue; |
| 1319 | } |
| 1320 | } |
| 1321 | full &= !own; |
| 1322 | if self.learn(token, &lister, &name, addr, now) { |
| 1323 | conn.listed.insert(name.clone(), addr); |
| 1324 | *self.listings.entry(name.clone()).or_default() += 1; |
| 1325 | changed.push(name); |
| 1326 | } |
| 1327 | } |
| 1328 | for name in changed { |
| 1329 | self.relist(&name, now); |
| 1330 | } |
| 1331 | } |
| 1332 | |
| 1333 | /// The list of connection `token`, from `lister`, gives `addr` for |
| 1334 | /// `name`: whether `name` is now a discovered node. A name this node |
| 1335 | /// does not know becomes one (and is dialed) while fewer than |
| 1336 | /// `max_peers` are, held by `token` ([`Found::lister`]); a seed's |
| 1337 | /// address is kept; a discovered node's is replaced by its own word, |
| 1338 | /// or by a third party's while unconfirmed (the address dialed when |
| 1339 | /// none of its listers gives one). |
| 1340 | fn learn( |
| 1341 | &mut self, |
| 1342 | token: Token, |
| 1343 | lister: &str, |
| 1344 | name: &str, |
| 1345 | addr: SocketAddr, |
| 1346 | now: Instant, |
| 1347 | ) -> bool { |
| 1348 | let own = name == lister; |
| 1349 | if let Some(known) = self.known.get_mut(name) { |
| 1350 | let Some(found) = &mut known.found else { |
| 1351 | return false; |
| 1352 | }; |
| 1353 | if own || !found.confirmed { |
| 1354 | known.addr = addr; |
| 1355 | } |
| 1356 | found.confirmed |= own; |
| 1357 | if found.lister.is_none() { |
| 1358 | found.lister = Some(token); |
| 1359 | self.unheld = self.unheld.saturating_sub(1); |
| 1360 | if !found.proven { |
| 1361 | *self.held.entry(token).or_default() += 1; |
| 1362 | } |
| 1363 | } |
| 1364 | if own { |
| 1365 | self.prove(name); |
| 1366 | } |
| 1367 | return true; |
| 1368 | } |
| 1369 | if self.discovered >= self.config.max_peers { |
| 1370 | return false; |
| 1371 | } |
| 1372 | self.discovered += 1; |
| 1373 | let due = (!self.named(name)).then_some(now); |
| 1374 | let proven = own || self.up.contains_key(name); |
| 1375 | let found = Found { |
| 1376 | confirmed: own, |
| 1377 | proven, |
| 1378 | lister: Some(token), |
| 1379 | dials: 0, |
| 1380 | unlisted: None, |
| 1381 | }; |
| 1382 | if !proven { |
| 1383 | *self.held.entry(token).or_default() += 1; |
| 1384 | } |
| 1385 | let known = Known { |
| 1386 | addr, |
| 1387 | backoff: 1, |
| 1388 | due, |
| 1389 | found: Some(found), |
| 1390 | }; |
| 1391 | self.known.insert(name.to_owned(), known); |
| 1392 | true |
| 1393 | } |
| 1394 | |
| 1395 | /// Discovered `name` came up, or confirmed its address: off |
| 1396 | /// probation, its lister holds it no longer against its share. |
| 1397 | fn prove(&mut self, name: &str) { |
| 1398 | let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) else { |
| 1399 | return; |
| 1400 | }; |
| 1401 | if !found.proven { |
| 1402 | found.proven = true; |
| 1403 | if let Some(lister) = found.lister { |
| 1404 | self.unhold(lister); |
| 1405 | } |
| 1406 | } |
| 1407 | } |
| 1408 | |
| 1409 | fn unhold(&mut self, lister: Token) { |
| 1410 | if let Some(n) = self.held.get_mut(&lister) { |
| 1411 | *n = n.saturating_sub(1); |
| 1412 | } |
| 1413 | } |
| 1414 | |
| 1415 | /// Discovered node `found` is forgotten, or no longer discovered: its |
| 1416 | /// lister holds it no longer. |
| 1417 | fn release(&mut self, found: &Found) { |
| 1418 | match found.lister { |
| 1419 | Some(lister) if !found.proven => self.unhold(lister), |
| 1420 | Some(_) => {} |
| 1421 | None => self.unheld = self.unheld.saturating_sub(1), |
| 1422 | } |
| 1423 | } |
| 1424 | |
| 1425 | /// Forget discovered `name`: a dial in progress ends as one to a node |
| 1426 | /// never known. |
| 1427 | fn forget(&mut self, name: &str) { |
| 1428 | if let Some(found) = self.known.remove(name).and_then(|k| k.found) { |
| 1429 | self.discovered -= 1; |
| 1430 | self.release(&found); |
| 1431 | } |
| 1432 | self.listings.remove(name); |
| 1433 | } |
| 1434 | |
| 1435 | /// Room for one more discovered node, which connection `token` (out |
| 1436 | /// of the map, `conn`) lists, all `max_peers` being taken: forget one |
| 1437 | /// that is not up and no lister holds (no up peer's list holds it), on |
| 1438 | /// probation first; else, if `token` holds fewer than its share |
| 1439 | /// (`max_peers` over the connections that carry lists), one on |
| 1440 | /// probation that the lister holding the most holds, if that is more |
| 1441 | /// than its share. Whether there is room now. A lister that holds its |
| 1442 | /// share keeps what it holds, so the slots end up shared, and stay so. |
| 1443 | fn room(&mut self, token: Token, conn: &mut Conn) -> bool { |
| 1444 | let unheld = (self.unheld > 0) |
| 1445 | .then(|| { |
| 1446 | self.known |
| 1447 | .iter() |
| 1448 | .filter_map(|(name, k)| Some((name, k.found.as_ref()?))) |
| 1449 | .filter(|(name, f)| f.lister.is_none() && !self.up.contains_key(*name)) |
| 1450 | .min_by_key(|(_, f)| f.proven) |
| 1451 | .map(|(name, _)| name.clone()) |
| 1452 | }) |
| 1453 | .flatten(); |
| 1454 | let victim = unheld.or_else(|| { |
| 1455 | let listers = 1 + self |
| 1456 | .conns |
| 1457 | .values() |
| 1458 | .filter(|c| c.mesh && c.phase == Phase::Up) |
| 1459 | .count(); |
| 1460 | let share = (self.config.max_peers / listers).max(1); |
| 1461 | if self.held.get(&token).copied().unwrap_or(0) >= share { |
| 1462 | return None; |
| 1463 | } |
| 1464 | let (most, held) = self |
| 1465 | .held |
| 1466 | .iter() |
| 1467 | .filter(|(t, _)| **t != token) |
| 1468 | .max_by_key(|(t, n)| (**n, std::cmp::Reverse(**t)))?; |
| 1469 | if *held <= share { |
| 1470 | return None; |
| 1471 | } |
| 1472 | let most = *most; |
| 1473 | self.known |
| 1474 | .iter() |
| 1475 | .filter_map(|(name, k)| Some((name, k.found.as_ref()?))) |
| 1476 | .find(|(_, f)| f.lister == Some(most) && !f.proven) |
| 1477 | .map(|(name, _)| name.clone()) |
| 1478 | }); |
| 1479 | let Some(victim) = victim else { |
| 1480 | return false; |
| 1481 | }; |
| 1482 | for c in self.conns.values_mut() { |
| 1483 | c.listed.remove(&victim); |
| 1484 | } |
| 1485 | conn.listed.remove(&victim); |
| 1486 | self.forget(&victim); |
| 1487 | true |
| 1488 | } |
| 1489 | |
| 1490 | /// Connection `token`'s list (`token` out of the map) no longer holds |
| 1491 | /// `name`. If `token` held it, another connection whose list holds it |
| 1492 | /// does now, or none: a lister cannot leave its names to the others' |
| 1493 | /// lists for free, nor have a name another peer lists forgotten by |
| 1494 | /// dropping it ([`Thread::room`]). |
| 1495 | fn unlist(&mut self, token: Token, name: &str) { |
| 1496 | if let Some(n) = self.listings.get_mut(name) { |
| 1497 | *n = n.saturating_sub(1); |
| 1498 | if *n == 0 { |
| 1499 | self.listings.remove(name); |
| 1500 | } |
| 1501 | } |
| 1502 | let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) else { |
| 1503 | return; |
| 1504 | }; |
| 1505 | if found.lister != Some(token) { |
| 1506 | return; |
| 1507 | } |
| 1508 | let next = self |
| 1509 | .conns |
| 1510 | .iter() |
| 1511 | .find(|(t, c)| **t != token && c.listed.contains_key(name)) |
| 1512 | .map(|(t, _)| *t); |
| 1513 | found.lister = next; |
| 1514 | let proven = found.proven; |
| 1515 | match next { |
| 1516 | None => self.unheld += 1, |
| 1517 | Some(next) if !proven => *self.held.entry(next).or_default() += 1, |
| 1518 | Some(_) => {} |
| 1519 | } |
| 1520 | if !proven { |
| 1521 | self.unhold(token); |
| 1522 | } |
| 1523 | } |
| 1524 | |
| 1525 | /// Whether discovered `name` is listed (up, or in an up peer's list) |
| 1526 | /// changed: its forgetting starts, or stops. |
| 1527 | fn relist(&mut self, name: &str, now: Instant) { |
| 1528 | let listed = self.up.contains_key(name) || self.listings.contains_key(name); |
| 1529 | if let Some(found) = self.known.get_mut(name).and_then(|k| k.found.as_mut()) { |
| 1530 | if listed { |
| 1531 | found.unlisted = None; |
| 1532 | } else { |
| 1533 | found.unlisted.get_or_insert(now); |
| 1534 | } |
| 1535 | } |
| 1536 | } |
| 1537 | |
| 1538 | /// Whether `name` is a discovered node whose address only peers' |
| 1539 | /// lists gave: a failed dial to it is the listers' doing. |
| 1540 | fn hearsay(&self, name: &str) -> bool { |
| 1541 | self.known |
| 1542 | .get(name) |
| 1543 | .and_then(|k| k.found.as_ref()) |
| 1544 | .is_some_and(|f| !f.confirmed) |
| 1545 | } |
| 1546 | |
| 1547 | /// Send this node's list to the peers that came up this turn, or, after |
| 1548 | /// a node came up or went down, to every peer that takes lists: at most |
| 1549 | /// once per heartbeat for each [`RETELL_PEERS`] peers up. The list is |
| 1550 | /// encoded once for each frame limit, and replaces the one a peer has |
| 1551 | /// not taken yet ([`Conn::list`]); each peer ignores its own entry. |
| 1552 | fn tell(&mut self, now: Instant) { |
| 1553 | if !self.config.mesh { |
| 1554 | self.retell = false; |
| 1555 | return; |
| 1556 | } |
| 1557 | let period = self.heartbeat * self.up.len().div_ceil(RETELL_PEERS).max(1) as u32; |
| 1558 | let every = self.retell && self.told.is_none_or(|t| now >= t + period); |
| 1559 | let welcome = std::mem::take(&mut self.welcome); |
| 1560 | if !every && welcome.is_empty() { |
| 1561 | return; |
| 1562 | } |
| 1563 | let to: Vec<Token> = if every { |
| 1564 | self.retell = false; |
| 1565 | self.told = Some(now); |
| 1566 | let mut all: Vec<Token> = self.up.values().copied().collect(); |
| 1567 | all.sort_unstable(); |
| 1568 | all |
| 1569 | } else { |
| 1570 | welcome |
| 1571 | }; |
| 1572 | let mut up: Vec<&String> = self.up.keys().collect(); |
| 1573 | up.sort_unstable(); |
| 1574 | let me = self.advertise.map(|a| (self.me.name.clone(), a)); |
| 1575 | let list: Vec<(String, SocketAddr)> = me |
| 1576 | .into_iter() |
| 1577 | .chain(up.into_iter().filter_map(|name| { |
| 1578 | let known = self.known.get(name)?; |
| 1579 | let trusted = known.found.as_ref().is_none_or(|f| f.confirmed); |
| 1580 | trusted.then(|| (name.clone(), known.addr)) |
| 1581 | })) |
| 1582 | .collect(); |
| 1583 | let mut encoded: HashMap<u32, Arc<[Vec<u8>]>> = HashMap::new(); |
| 1584 | for token in to { |
| 1585 | let Some(conn) = self |
| 1586 | .conns |
| 1587 | .get_mut(&token) |
| 1588 | .filter(|c| c.mesh && c.phase == Phase::Up) |
| 1589 | else { |
| 1590 | continue; |
| 1591 | }; |
| 1592 | let frames = encoded |
| 1593 | .entry(conn.peer_max) |
| 1594 | .or_insert_with(|| frame::Peers::frames(&list, conn.peer_max).into()); |
| 1595 | conn.list = Some(frames.clone()); |
| 1596 | self.drive_write(token); |
| 1597 | } |
| 1598 | } |
| 1599 | |
| 1600 | fn message(&self, conn: &Conn, body: &[u8]) -> Result<(), Reason> { |
| 1601 | let header = body |
| 1602 | .first_chunk::<HEADER_LEN>() |
| 1603 | .ok_or(Reason::Protocol("a message frame shorter than its header"))?; |
| 1604 | let header = MessageHeader::decode(header) |
| 1605 | .map_err(|_| Reason::Protocol("a malformed message header"))?; |
| 1606 | let payload = &body[HEADER_LEN..]; |
| 1607 | if payload.len() != header.payload_len as usize { |
| 1608 | return Err(Reason::Protocol( |
| 1609 | "a message frame's length is not its header's", |
| 1610 | )); |
| 1611 | } |
| 1612 | if header.incarnation != self.me.incarnation { |
| 1613 | self.outbox.dropped.fetch_add(1, Ordering::Relaxed); |
| 1614 | if let Some(stats) = &conn.stats { |
| 1615 | Stats::count(&stats.dropped, 1); |
| 1616 | } |
| 1617 | return Ok(()); |
| 1618 | } |
| 1619 | if let Some(stats) = &conn.stats { |
| 1620 | Stats::count(&stats.received, 1); |
| 1621 | } |
| 1622 | if let Some(peer) = &conn.peer { |
| 1623 | self.inbound.message(peer, &header, payload); |
| 1624 | } |
| 1625 | Ok(()) |
| 1626 | } |
| 1627 | |
| 1628 | // ---- writing ----------------------------------------------------------------------- |
| 1629 | |
| 1630 | /// Write until the socket would block or nothing is left (false), or |
| 1631 | /// `until` (true: there may be more). |
| 1632 | fn flush(&self, conn: &mut Conn, until: Instant) -> Result<bool, Reason> { |
| 1633 | loop { |
| 1634 | while conn.tls.wants_write() { |
| 1635 | match conn.tls.write_tls(&mut NoSigPipe::new(&conn.sock)) { |
| 1636 | Ok(0) => return Err(Reason::Closed("the socket takes no more".into())), |
| 1637 | Ok(_) => {} |
| 1638 | Err(e) if e.kind() == ErrorKind::WouldBlock => return Ok(false), |
| 1639 | Err(e) if e.kind() == ErrorKind::Interrupted => {} |
| 1640 | Err(e) => return Err(Reason::Closed(e.to_string())), |
| 1641 | } |
| 1642 | } |
| 1643 | if Instant::now() >= until { |
| 1644 | return Ok(true); |
| 1645 | } |
| 1646 | if !self.refill(conn)? { |
| 1647 | return Ok(false); |
| 1648 | } |
| 1649 | } |
| 1650 | } |
| 1651 | |
| 1652 | /// Hand rustls the next frames (its buffer is empty): the control lane |
| 1653 | /// first, at a frame boundary behind the handshake's own frames, then |
| 1654 | /// what was taken from the peer's queue, which is taken again once all |
| 1655 | /// of it is written (its parked senders are woken then). Whether any |
| 1656 | /// byte went. |
| 1657 | fn refill(&self, conn: &mut Conn) -> Result<bool, Reason> { |
| 1658 | if !conn.control.is_empty() { |
| 1659 | let started = usize::from(conn.offset > 0); |
| 1660 | let at = conn |
| 1661 | .out |
| 1662 | .iter() |
| 1663 | .skip(started) |
| 1664 | .position(|e| e.kind() >= frame::MESSAGE) |
| 1665 | .map_or(conn.out.len(), |i| i + started); |
| 1666 | while let Some(entry) = conn.control.pop_back() { |
| 1667 | conn.out.insert(at, entry); |
| 1668 | } |
| 1669 | } |
| 1670 | if conn.out.is_empty() |
| 1671 | && conn.phase == Phase::Up |
| 1672 | && let Some(peer) = &conn.peer |
| 1673 | { |
| 1674 | // Swapped, so each keeps its room; past a burst's, given back. |
| 1675 | if conn.out.capacity() > MAX_SLICES * 4 { |
| 1676 | conn.out = VecDeque::new(); |
| 1677 | } |
| 1678 | let parked = match self.outbox.routes().get_mut(&peer.name) { |
| 1679 | Some(route) => { |
| 1680 | std::mem::swap(&mut conn.out, &mut route.queue); |
| 1681 | route.queued = 0; |
| 1682 | std::mem::take(&mut route.parked) |
| 1683 | } |
| 1684 | None => Vec::new(), |
| 1685 | }; |
| 1686 | // Behind the frames just taken from the queue. |
| 1687 | if let Some(list) = conn.list.take() { |
| 1688 | let frames = list |
| 1689 | .iter() |
| 1690 | .map(|body| Entry::new(frame::SIGNAL, body.clone())); |
| 1691 | conn.out.extend(frames); |
| 1692 | } |
| 1693 | if !parked.is_empty() { |
| 1694 | self.inbound.drained(peer, &parked); |
| 1695 | } |
| 1696 | } |
| 1697 | let mut slices = Vec::with_capacity(MAX_SLICES); |
| 1698 | let mut offset = conn.offset; |
| 1699 | for entry in conn.out.iter().take(MAX_SLICES / 2) { |
| 1700 | if offset < entry.head.len() { |
| 1701 | slices.push(IoSlice::new(&entry.head[offset..])); |
| 1702 | slices.push(IoSlice::new(&entry.body)); |
| 1703 | } else { |
| 1704 | slices.push(IoSlice::new(&entry.body[offset - entry.head.len()..])); |
| 1705 | } |
| 1706 | offset = 0; |
| 1707 | } |
| 1708 | if slices.is_empty() { |
| 1709 | return Ok(false); |
| 1710 | } |
| 1711 | let mut n = conn |
| 1712 | .tls |
| 1713 | .writer() |
| 1714 | .write_vectored(&slices) |
| 1715 | .map_err(|e| Reason::Closed(e.to_string()))?; |
| 1716 | drop(slices); |
| 1717 | let wrote = n > 0; |
| 1718 | while n > 0 |
| 1719 | && let Some(front) = conn.out.front() |
| 1720 | { |
| 1721 | let left = front.total() - conn.offset; |
| 1722 | if n < left { |
| 1723 | conn.offset += n; |
| 1724 | break; |
| 1725 | } |
| 1726 | n -= left; |
| 1727 | conn.offset = 0; |
| 1728 | if conn |
| 1729 | .out |
| 1730 | .pop_front() |
| 1731 | .is_some_and(|e| e.kind() == frame::MESSAGE) |
| 1732 | && let Some(stats) = &conn.stats |
| 1733 | { |
| 1734 | Stats::count(&stats.sent, 1); |
| 1735 | } |
| 1736 | } |
| 1737 | Ok(wrote) |
| 1738 | } |
| 1739 | } |
| 1740 | |
| 1741 | /// A connection's source, for [`MAX_UNAUTHENTICATED_PER_SOURCE`]: an IPv4 |
| 1742 | /// address (mapped into IPv6 or not), or an IPv6 address's /64, which one |
| 1743 | /// host usually holds whole. |
| 1744 | fn source(ip: IpAddr) -> IpAddr { |
| 1745 | match ip { |
| 1746 | IpAddr::V6(v6) => match v6.to_ipv4_mapped() { |
| 1747 | Some(v4) => IpAddr::V4(v4), |
| 1748 | None => IpAddr::V6((u128::from(v6) & !((1 << 64) - 1)).into()), |
| 1749 | }, |
| 1750 | v4 => v4, |
| 1751 | } |
| 1752 | } |
| 1753 | |
| 1754 | /// Simultaneous dials between `me` and `them`: whether the connection |
| 1755 | /// `me` dialed is kept. The smaller name's, on both sides. |
| 1756 | fn keeps_dialer(me: &str, them: &str) -> bool { |
| 1757 | me < them |
| 1758 | } |
| 1759 | |
| 1760 | #[cfg(test)] |
| 1761 | mod tests { |
| 1762 | use super::{keeps_dialer, source}; |
| 1763 | |
| 1764 | #[test] |
| 1765 | fn sources_are_addresses_or_ipv6_64s() { |
| 1766 | let ip = |s: &str| s.parse::<std::net::IpAddr>().expect("an address"); |
| 1767 | assert_eq!(source(ip("10.0.0.5")), ip("10.0.0.5")); |
| 1768 | assert_eq!(source(ip("::ffff:10.0.0.5")), ip("10.0.0.5")); |
| 1769 | assert_eq!(source(ip("2001:db8:1:2:3:4:5:6")), ip("2001:db8:1:2::")); |
| 1770 | assert_ne!(source(ip("2001:db8:1:3::1")), source(ip("2001:db8:1:2::1"))); |
| 1771 | } |
| 1772 | |
| 1773 | #[test] |
| 1774 | fn simultaneous_dials_keep_the_smaller_names() { |
| 1775 | let (a, b) = ("a.example", "b.example"); |
| 1776 | // Each side decides about its own dial: exactly one is kept. |
| 1777 | assert!(keeps_dialer(a, b)); |
| 1778 | assert!(!keeps_dialer(b, a)); |
| 1779 | // Byte order, which node names (lowercase ASCII) make total. |
| 1780 | assert!(keeps_dialer("a-1.example", "a.example")); |
| 1781 | } |
| 1782 | } |