//! The bytes of a connection, after TLS (`docs/wire-format.md`, //! *Handshake*): frames of a length, a kind and a body; the hello each //! side sends, and the refusal that closes a connection. Also the one //! signal the transport handles itself, a node's list of peers //! (*Peers*). use std::collections::HashSet; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use louise_rt_prims::wire::check_node_name; use super::Reason; /// The protocol version a hello carries. pub(super) const VERSION: u16 = 1; /// Capability flag (bit 0): the sender speaks signal op [`PEERS`], and /// takes the lists of peers that discover a full mesh. Set only by a node /// whose discovery is `mesh`. Later protocol changes add flags, as /// Erlang's `DFLAG`s; a peer's unknown flags are ignored. pub(super) const FLAG_PEERS: u64 = 1; /// Capability flags (bits 1 to 4): the sender takes the signal ops of a /// family added since stage 1 (`docs/wire-format.md`, *Hello*). Every /// node sets those it implements ([`FLAGS_OPS`]); a frame of one of /// those ops goes only to a peer that set its flag ([`needs`]). pub(super) const FLAG_DEMONITOR: u64 = 1 << 1; pub(super) const FLAG_SPAWN_LINKED: u64 = 1 << 2; pub(super) const FLAG_SPAWN_MONITORED: u64 = 1 << 3; pub(super) const FLAG_UNLINK: u64 = 1 << 4; /// The op flags this node sets in its hello: all of them. pub(super) const FLAGS_OPS: u64 = FLAG_DEMONITOR | FLAG_SPAWN_LINKED | FLAG_SPAWN_MONITORED | FLAG_UNLINK; /// The flag a peer's hello must set for a signal frame of `op` to go to /// it; 0 for an op every node takes. The ops are `node.rs`'s: /// `16` demonitor, `17` and `18` unlink and its answer, `22` linked /// spawn, `23` monitored spawn. pub(crate) fn needs(op: u8) -> u64 { match op { 0x16 => FLAG_DEMONITOR, 0x17 | 0x18 => FLAG_UNLINK, 0x22 => FLAG_SPAWN_LINKED, 0x23 => FLAG_SPAWN_MONITORED, _ => 0, } } /// The TLS application protocol (ALPN) both sides must negotiate. pub(super) const ALPN: &[u8] = b"louise-dist"; /// Frame kinds. Below `0x10`, the connection's own frames; from it, the /// ordered stream's. A heartbeat and its echo carry a [`STAMP`]. pub(super) const HELLO: u8 = 0x01; pub(super) const ACK: u8 = 0x02; pub(super) const REFUSE: u8 = 0x03; pub(super) const HEARTBEAT: u8 = 0x04; pub(super) const ECHO: u8 = 0x05; pub(super) const MESSAGE: u8 = 0x10; pub(super) const SIGNAL: u8 = 0x11; /// A frame's length prefix: a `u32`, little-endian, counting the kind and /// the body. pub(super) const PREFIX: usize = 4; /// A heartbeat's body: 8 bytes its sender chose (the time it went out), /// which the echo answering it carries back unchanged. pub(super) const STAMP: usize = 8; /// The longest refusal text, in bytes. const MAX_REFUSAL: usize = 255; /// The signal op of a list of peers, inside a [`SIGNAL`] frame: handled /// by the transport, never handed to the [`super::Inbound`] handler. pub(super) const PEERS: u8 = 0x03; /// A list frame's fixed part: the op, whether it starts a list, the count. const PEERS_HEAD: usize = 1 + 1 + 2; /// A frame waiting to be written: its prefix and kind, and its body. pub(crate) struct Entry { pub(super) head: [u8; PREFIX + 1], pub(super) body: Vec, } impl Entry { /// A frame of `kind`. Its body's length is checked against the peer's /// frame limit (at most [`super::MAX_FRAME`]) before it is queued. pub(super) fn new(kind: u8, body: Vec) -> Entry { let len = u32::try_from(1 + body.len()).unwrap_or(u32::MAX); let mut head = [0; PREFIX + 1]; head[..PREFIX].copy_from_slice(&len.to_le_bytes()); head[PREFIX] = kind; Entry { head, body } } /// Prefix, kind and body. pub(super) fn total(&self) -> usize { self.head.len() + self.body.len() } pub(super) fn kind(&self) -> u8 { self.head[PREFIX] } } /// The next frame of `buf`: its kind and the range of its body, once it /// is all there. A length over `limit` (or 0) refuses it as soon as the /// prefix is read, before any of it is buffered. pub(super) fn next(buf: &[u8], limit: u32) -> Result)>, Reason> { let Some(prefix) = buf.first_chunk::() else { return Ok(None); }; let len = u32::from_le_bytes(*prefix); if len == 0 { return Err(Reason::Protocol("a frame without a kind")); } if len > limit { return Err(Reason::TooLarge(len)); } let end = PREFIX + len as usize; if buf.len() < end { return Ok(None); } Ok(Some((buf[PREFIX], PREFIX + 1..end))) } /// What a node says of itself in the handshake. #[derive(Clone, Debug, PartialEq)] pub(super) struct Hello { pub(super) version: u16, pub(super) flags: u64, pub(super) incarnation: u64, pub(super) schema_hash: u64, /// The largest frame it accepts. pub(super) max_frame: u32, pub(super) cluster: String, pub(super) node: String, } /// A hello's fixed part: version, flags, incarnation, schema hash and frame /// limit. const FIXED: usize = 2 + 8 + 8 + 8 + 4; impl Hello { pub(super) fn encode(&self) -> Vec { let mut out = Vec::with_capacity(FIXED + 2 + self.cluster.len() + self.node.len()); out.extend_from_slice(&self.version.to_le_bytes()); out.extend_from_slice(&self.flags.to_le_bytes()); out.extend_from_slice(&self.incarnation.to_le_bytes()); out.extend_from_slice(&self.schema_hash.to_le_bytes()); out.extend_from_slice(&self.max_frame.to_le_bytes()); for name in [&self.cluster, &self.node] { // Node names are at most 253 bytes (checked at start). out.push(name.len() as u8); out.extend_from_slice(name.as_bytes()); } out } /// A peer's hello. Another version is refused first, whatever follows /// it; then the fields must be well formed, the names node names, and /// nothing may follow them. pub(super) fn decode(body: &[u8]) -> Result { let malformed = Reason::Protocol("a malformed hello"); let version = body .first_chunk::<2>() .map(|v| u16::from_le_bytes(*v)) .ok_or(malformed.clone())?; if version != VERSION { return Err(Reason::Version(version)); } let fixed = body.first_chunk::().ok_or(malformed.clone())?; let word = |at: usize| { let mut b = [0; 8]; b.copy_from_slice(&fixed[at..at + 8]); u64::from_le_bytes(b) }; let mut rest = &body[FIXED..]; let mut name = || -> Result { let (&len, tail) = rest.split_first().ok_or(malformed.clone())?; let bytes = tail.get(..usize::from(len)).ok_or(malformed.clone())?; rest = &tail[usize::from(len)..]; if !check_node_name(bytes) { return Err(Reason::Protocol("a hello's name is not a node name")); } // ASCII: a node name is. Ok(String::from_utf8_lossy(bytes).into_owned()) }; let cluster = name()?; let node = name()?; if !rest.is_empty() { return Err(malformed); } let mut max = [0; 4]; max.copy_from_slice(&fixed[26..30]); Ok(Hello { version, flags: word(2), incarnation: word(10), schema_hash: word(18), max_frame: u32::from_le_bytes(max), cluster, node, }) } } /// A refusal's body: its code, then why, in UTF-8 (cut to 255 bytes). pub(super) fn refusal(code: u8, why: &str) -> Vec { let mut end = why.len().min(MAX_REFUSAL); while !why.is_char_boundary(end) { end -= 1; } let mut out = Vec::with_capacity(1 + end); out.push(code); out.extend_from_slice(&why.as_bytes()[..end]); out } /// A peer's refusal, as [`Reason::Refused`]. pub(super) fn refused(body: &[u8]) -> Reason { match body.split_first() { Some((&code, text)) if text.len() <= MAX_REFUSAL => { Reason::Refused(code, String::from_utf8_lossy(text).into_owned()) } _ => Reason::Protocol("a malformed refusal"), } } /// Whether `addr` can be dialed, as a list's entry or this node's /// advertisement must: a port, an address that is neither unspecified, /// multicast nor broadcast, and an IPv4 address as such (not mapped into /// IPv6), so each address has one encoding. pub(super) fn dialable(addr: SocketAddr) -> bool { let ip_ok = match addr.ip() { IpAddr::V4(v4) => !v4.is_unspecified() && !v4.is_multicast() && !v4.is_broadcast(), IpAddr::V6(v6) => { !v6.is_unspecified() && !v6.is_multicast() && v6.to_ipv4_mapped().is_none() } }; addr.port() != 0 && ip_ok } /// One frame of a node's list of peers (`docs/wire-format.md`, *Peers*): /// node names and the addresses to dial them at. Addresses are hints: /// TLS checks the name a dial expects. #[derive(Clone, Debug, PartialEq)] pub(super) struct Peers { /// This frame starts the sender's list, which replaces its previous /// one; otherwise it adds to it. pub(super) first: bool, pub(super) nodes: Vec<(String, SocketAddr)>, } impl Peers { /// `nodes` as the bodies of signal frames (op, then fields), each /// within `limit`, a frame limit (the kind and the body; at least /// 1024): the first starts the list. No nodes is one frame, which /// empties the receiver's list. An entry is at most 273 bytes, so it /// always fits. pub(super) fn frames(nodes: &[(String, SocketAddr)], limit: u32) -> Vec> { let room = (limit as usize).saturating_sub(1).max(PEERS_HEAD + 273); let head = |first: bool| vec![PEERS, u8::from(first), 0, 0]; let mut frames = Vec::new(); let mut body = head(true); let mut count: u16 = 0; for (name, addr) in nodes { let entry = entry(name, *addr); if count == u16::MAX || body.len() + entry.len() > room { body[2..4].copy_from_slice(&count.to_le_bytes()); frames.push(std::mem::replace(&mut body, head(false))); count = 0; } body.extend_from_slice(&entry); count += 1; } body[2..4].copy_from_slice(&count.to_le_bytes()); frames.push(body); frames } /// A list frame's fields, after its op. Each name a node name, once; /// each address [`dialable`]; nothing after the last. What is wrong, /// otherwise. The receiver reads at most `max_peers` names of a list /// (`Thread::listed`): a longer one, from a node that keeps more peers /// than this one, is cut, not refused. pub(super) fn decode(fields: &[u8]) -> Result { let malformed = "a malformed list of peers"; let (&first, rest) = fields.split_first().ok_or(malformed)?; let first = match first { 0 => false, 1 => true, _ => return Err(malformed), }; let count = rest.first_chunk::<2>().ok_or(malformed)?; let count = usize::from(u16::from_le_bytes(*count)); let mut rest = &rest[2..]; // An entry takes at least 9 bytes: no more room than the bytes // hold. let mut nodes = Vec::with_capacity(count.min(rest.len() / 9)); let mut seen = HashSet::with_capacity(nodes.capacity()); let mut take = |n: usize| -> Result<&[u8], &'static str> { let (taken, tail) = rest.split_at_checked(n).ok_or(malformed)?; rest = tail; Ok(taken) }; for _ in 0..count { let len = take(1)?[0]; let name = take(usize::from(len))?; if !check_node_name(name) { return Err("a listed name is not a node name"); } let ip = match take(1)?[0] { 4 => { let b: [u8; 4] = take(4)?.try_into().map_err(|_| malformed)?; IpAddr::V4(Ipv4Addr::from(b)) } 6 => { let b: [u8; 16] = take(16)?.try_into().map_err(|_| malformed)?; IpAddr::V6(Ipv6Addr::from(b)) } _ => return Err(malformed), }; let port: [u8; 2] = take(2)?.try_into().map_err(|_| malformed)?; let addr = SocketAddr::new(ip, u16::from_le_bytes(port)); if !dialable(addr) { return Err("a listed address cannot be dialed"); } // ASCII: a node name is. let name = String::from_utf8_lossy(name).into_owned(); if !seen.insert(name.clone()) { return Err("a name listed twice"); } nodes.push((name, addr)); } if !rest.is_empty() { return Err(malformed); } Ok(Peers { first, nodes }) } } /// A list's entry: the name's length and bytes, the address family (4 or /// 6), the address, the port. fn entry(name: &str, addr: SocketAddr) -> Vec { let mut out = Vec::with_capacity(1 + name.len() + 1 + 16 + 2); // Node names are at most 253 bytes (checked where they come from). out.push(name.len() as u8); out.extend_from_slice(name.as_bytes()); match addr.ip() { IpAddr::V4(v4) => { out.push(4); out.extend_from_slice(&v4.octets()); } IpAddr::V6(v6) => { out.push(6); out.extend_from_slice(&v6.octets()); } } out.extend_from_slice(&addr.port().to_le_bytes()); out } #[cfg(test)] mod tests { use super::*; fn hello() -> Hello { Hello { version: VERSION, flags: 0x0102_0304_0506_0708, incarnation: 0x0123_4567_89ab_cdef, schema_hash: 0x9949_47b8_73cb_1aa7, max_frame: 1 << 20, cluster: "prod".into(), node: "a.example".into(), } } #[test] fn a_hello_has_the_documented_bytes() { // docs/wire-format.md, *Handshake*: the example. let bytes = hello().encode(); let want: Vec = [ &[0x01, 0x00][..], &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01], &[0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01], &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99], &[0x00, 0x00, 0x10, 0x00], &[0x04], b"prod", &[0x09], b"a.example", ] .concat(); assert_eq!(bytes, want); assert_eq!( Entry::new(HELLO, bytes.clone()).head, [0x2e, 0, 0, 0, HELLO] ); assert_eq!(Hello::decode(&bytes), Ok(hello())); } #[test] fn malformed_hellos_are_refused() { let good = hello().encode(); // Another version, whatever follows. assert_eq!(Hello::decode(&[2, 0]), Err(Reason::Version(2))); assert_eq!(Hello::decode(&[0, 1, 9]), Err(Reason::Version(256))); // Every truncation. for n in 0..good.len() { assert!( matches!(Hello::decode(&good[..n]), Err(Reason::Protocol(_))), "{n} bytes" ); } // A byte after the node name. let mut long = good.clone(); long.push(0); assert!(matches!(Hello::decode(&long), Err(Reason::Protocol(_)))); // A name that is not a node name. let mut upper = good.clone(); let at = upper.len() - 1; upper[at] = b'E'; assert!(matches!(Hello::decode(&upper), Err(Reason::Protocol(_)))); let mut empty = hello(); empty.cluster.clear(); assert!(matches!( Hello::decode(&empty.encode()), Err(Reason::Protocol(_)) )); } /// `docs/wire-format.md`, *Hello*: the flags table. Each op family /// has its bit, every flag a node sets round-trips, and unknown bits /// are kept as sent (and ignored). #[test] fn each_op_family_has_its_flag() { assert_eq!( [ FLAG_PEERS, FLAG_DEMONITOR, FLAG_SPAWN_LINKED, FLAG_SPAWN_MONITORED, FLAG_UNLINK ], [1, 2, 4, 8, 16] ); assert_eq!(FLAGS_OPS, 0b1_1110); let flagged: Vec<(u8, u64)> = (0..=u8::MAX) .map(|op| (op, needs(op))) .filter(|(_, f)| *f != 0) .collect(); assert_eq!( flagged, [ (0x16, FLAG_DEMONITOR), (0x17, FLAG_UNLINK), (0x18, FLAG_UNLINK), (0x22, FLAG_SPAWN_LINKED), (0x23, FLAG_SPAWN_MONITORED), ] ); for flags in [0, FLAGS_OPS, FLAG_PEERS | FLAGS_OPS, u64::MAX, 1 << 63] { let h = Hello { flags, ..hello() }; assert_eq!(Hello::decode(&h.encode()), Ok(h)); } } #[test] fn frames_are_cut_by_their_prefix() { let mut buf = Vec::new(); let e = Entry::new(MESSAGE, vec![7; 3]); buf.extend_from_slice(&e.head); buf.extend_from_slice(&e.body); assert_eq!(e.head, [4, 0, 0, 0, MESSAGE]); assert_eq!(next(&buf, 4), Ok(Some((MESSAGE, 5..8)))); assert_eq!(next(&buf[..7], 4), Ok(None), "incomplete"); assert_eq!(next(&buf[..3], 4), Ok(None), "no prefix yet"); assert_eq!(next(&buf, 3), Err(Reason::TooLarge(4)), "over the limit"); // Refused on the prefix alone, before the body is buffered. assert_eq!( next(&u32::MAX.to_le_bytes(), 1 << 20), Err(Reason::TooLarge(u32::MAX)) ); assert!(matches!(next(&[0, 0, 0, 0], 9), Err(Reason::Protocol(_)))); } #[test] fn refusals_are_bounded() { assert_eq!(refusal(3, "schema"), b"\x03schema"); let long = "é".repeat(200); let body = refusal(4, &long); assert_eq!(body.len(), 1 + 254, "cut at a character boundary"); assert_eq!(refused(&body), Reason::Refused(4, "é".repeat(127))); assert!(matches!(refused(&[]), Reason::Protocol(_))); assert!(matches!(refused(&[1; 257]), Reason::Protocol(_))); assert_eq!(refused(&[5, 0xff]), Reason::Refused(5, "\u{fffd}".into())); } fn addr(s: &str) -> SocketAddr { s.parse().expect("an address") } #[test] fn a_list_of_peers_has_the_documented_bytes() { // docs/wire-format.md, *Peers*: the example. let nodes = vec![ ("b.example".to_string(), addr("10.0.0.2:4370")), ("c.example".to_string(), addr("[2001:db8::3]:4370")), ]; let frames = Peers::frames(&nodes, 1 << 20); let want: Vec = [ &[PEERS, 0x01, 0x02, 0x00][..], &[0x09], b"b.example", &[0x04, 10, 0, 0, 2, 0x12, 0x11], &[0x09], b"c.example", &[ 0x06, 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, ], &[0x12, 0x11], ] .concat(); assert_eq!(frames, std::slice::from_ref(&want)); let decoded = Peers::decode(&want[1..]).expect("a list"); assert_eq!(decoded, Peers { first: true, nodes }); // No nodes: one frame, which empties the receiver's list. assert_eq!(Peers::frames(&[], 1024), [vec![PEERS, 1, 0, 0]]); } #[test] fn a_long_list_is_cut_to_the_peers_frame_limit() { let nodes: Vec<(String, SocketAddr)> = (0..40) .map(|i| { ( format!("node-{i}.{}.example", "x".repeat(60)), addr("[2001:db8::1]:9"), ) }) .collect(); let frames = Peers::frames(&nodes, 1024); assert!(frames.len() > 1, "{} frames", frames.len()); let mut back = Vec::new(); for (i, body) in frames.iter().enumerate() { // Its kind and body within the limit. assert!(body.len() < 1024, "frame {i}: {} bytes", body.len()); let list = Peers::decode(&body[1..]).expect("a list"); assert_eq!(list.first, i == 0); back.extend(list.nodes); } assert_eq!(back, nodes); } #[test] fn malformed_lists_of_peers_are_refused() { let good = Peers::frames(&[("b.example".to_string(), addr("10.0.0.2:4370"))], 1024).remove(0); let fields = &good[1..]; assert!(Peers::decode(fields).is_ok()); // Every truncation, and a byte after the last entry. for n in 0..fields.len() { assert!(Peers::decode(&fields[..n]).is_err(), "{n} bytes"); } assert!(Peers::decode(&[fields, &[0]].concat()).is_err()); let with = |at: usize, byte: u8| { let mut f = fields.to_vec(); f[at] = byte; Peers::decode(&f) }; // Neither a first frame nor a next one. assert!(with(0, 2).is_err()); // A count the bytes do not hold. assert!(with(1, 2).is_err()); assert!(Peers::decode(&[1, 0xff, 0xff]).is_err()); // Not a node name: upper case, empty. assert!(with(4, b'B').is_err()); assert!(with(3, 0).is_err()); // Another address family. assert!(with(13, 5).is_err()); assert!(with(13, 6).is_err(), "a v6 address in a v4 entry's bytes"); let one = |a: &str| Peers::frames(&[("b.example".to_string(), addr(a))], 1024).remove(0); for bad in [ "10.0.0.2:0", "0.0.0.0:4370", "255.255.255.255:4370", "224.0.0.1:4370", "[::]:4370", "[ff02::1]:4370", "[::ffff:10.0.0.2]:4370", ] { assert!(Peers::decode(&one(bad)[1..]).is_err(), "{bad}"); assert!(!dialable(addr(bad)), "{bad}"); } assert!(dialable(addr("127.0.0.1:1")) && dialable(addr("[::1]:1"))); // A name twice. let twice = Peers::frames( &[ ("b.example".to_string(), addr("10.0.0.2:1")), ("b.example".to_string(), addr("10.0.0.3:1")), ], 1024, ) .remove(0); assert_eq!(Peers::decode(&twice[1..]), Err("a name listed twice")); } }