
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 bytes of a connection, after TLS (`docs/wire-format.md`, |
| 2 | //! *Handshake*): frames of a length, a kind and a body; the hello each |
| 3 | //! side sends, and the refusal that closes a connection. Also the one |
| 4 | //! signal the transport handles itself, a node's list of peers |
| 5 | //! (*Peers*). |
| 6 | |
| 7 | use std::collections::HashSet; |
| 8 | use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; |
| 9 | |
| 10 | use louise_rt_prims::wire::check_node_name; |
| 11 | |
| 12 | use super::Reason; |
| 13 | |
| 14 | /// The protocol version a hello carries. |
| 15 | pub(super) const VERSION: u16 = 1; |
| 16 | /// Capability flag (bit 0): the sender speaks signal op [`PEERS`], and |
| 17 | /// takes the lists of peers that discover a full mesh. Set only by a node |
| 18 | /// whose discovery is `mesh`. Later protocol changes add flags, as |
| 19 | /// Erlang's `DFLAG`s; a peer's unknown flags are ignored. |
| 20 | pub(super) const FLAG_PEERS: u64 = 1; |
| 21 | /// Capability flags (bits 1 to 4): the sender takes the signal ops of a |
| 22 | /// family added since stage 1 (`docs/wire-format.md`, *Hello*). Every |
| 23 | /// node sets those it implements ([`FLAGS_OPS`]); a frame of one of |
| 24 | /// those ops goes only to a peer that set its flag ([`needs`]). |
| 25 | pub(super) const FLAG_DEMONITOR: u64 = 1 << 1; |
| 26 | pub(super) const FLAG_SPAWN_LINKED: u64 = 1 << 2; |
| 27 | pub(super) const FLAG_SPAWN_MONITORED: u64 = 1 << 3; |
| 28 | pub(super) const FLAG_UNLINK: u64 = 1 << 4; |
| 29 | /// The op flags this node sets in its hello: all of them. |
| 30 | pub(super) const FLAGS_OPS: u64 = |
| 31 | FLAG_DEMONITOR | FLAG_SPAWN_LINKED | FLAG_SPAWN_MONITORED | FLAG_UNLINK; |
| 32 | |
| 33 | /// The flag a peer's hello must set for a signal frame of `op` to go to |
| 34 | /// it; 0 for an op every node takes. The ops are `node.rs`'s: |
| 35 | /// `16` demonitor, `17` and `18` unlink and its answer, `22` linked |
| 36 | /// spawn, `23` monitored spawn. |
| 37 | pub(crate) fn needs(op: u8) -> u64 { |
| 38 | match op { |
| 39 | 0x16 => FLAG_DEMONITOR, |
| 40 | 0x17 | 0x18 => FLAG_UNLINK, |
| 41 | 0x22 => FLAG_SPAWN_LINKED, |
| 42 | 0x23 => FLAG_SPAWN_MONITORED, |
| 43 | _ => 0, |
| 44 | } |
| 45 | } |
| 46 | /// The TLS application protocol (ALPN) both sides must negotiate. |
| 47 | pub(super) const ALPN: &[u8] = b"louise-dist"; |
| 48 | |
| 49 | /// Frame kinds. Below `0x10`, the connection's own frames; from it, the |
| 50 | /// ordered stream's. A heartbeat and its echo carry a [`STAMP`]. |
| 51 | pub(super) const HELLO: u8 = 0x01; |
| 52 | pub(super) const ACK: u8 = 0x02; |
| 53 | pub(super) const REFUSE: u8 = 0x03; |
| 54 | pub(super) const HEARTBEAT: u8 = 0x04; |
| 55 | pub(super) const ECHO: u8 = 0x05; |
| 56 | pub(super) const MESSAGE: u8 = 0x10; |
| 57 | pub(super) const SIGNAL: u8 = 0x11; |
| 58 | |
| 59 | /// A frame's length prefix: a `u32`, little-endian, counting the kind and |
| 60 | /// the body. |
| 61 | pub(super) const PREFIX: usize = 4; |
| 62 | |
| 63 | /// A heartbeat's body: 8 bytes its sender chose (the time it went out), |
| 64 | /// which the echo answering it carries back unchanged. |
| 65 | pub(super) const STAMP: usize = 8; |
| 66 | |
| 67 | /// The longest refusal text, in bytes. |
| 68 | const MAX_REFUSAL: usize = 255; |
| 69 | |
| 70 | /// The signal op of a list of peers, inside a [`SIGNAL`] frame: handled |
| 71 | /// by the transport, never handed to the [`super::Inbound`] handler. |
| 72 | pub(super) const PEERS: u8 = 0x03; |
| 73 | /// A list frame's fixed part: the op, whether it starts a list, the count. |
| 74 | const PEERS_HEAD: usize = 1 + 1 + 2; |
| 75 | |
| 76 | /// A frame waiting to be written: its prefix and kind, and its body. |
| 77 | pub(crate) struct Entry { |
| 78 | pub(super) head: [u8; PREFIX + 1], |
| 79 | pub(super) body: Vec<u8>, |
| 80 | } |
| 81 | |
| 82 | impl Entry { |
| 83 | /// A frame of `kind`. Its body's length is checked against the peer's |
| 84 | /// frame limit (at most [`super::MAX_FRAME`]) before it is queued. |
| 85 | pub(super) fn new(kind: u8, body: Vec<u8>) -> Entry { |
| 86 | let len = u32::try_from(1 + body.len()).unwrap_or(u32::MAX); |
| 87 | let mut head = [0; PREFIX + 1]; |
| 88 | head[..PREFIX].copy_from_slice(&len.to_le_bytes()); |
| 89 | head[PREFIX] = kind; |
| 90 | Entry { head, body } |
| 91 | } |
| 92 | |
| 93 | /// Prefix, kind and body. |
| 94 | pub(super) fn total(&self) -> usize { |
| 95 | self.head.len() + self.body.len() |
| 96 | } |
| 97 | |
| 98 | pub(super) fn kind(&self) -> u8 { |
| 99 | self.head[PREFIX] |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// The next frame of `buf`: its kind and the range of its body, once it |
| 104 | /// is all there. A length over `limit` (or 0) refuses it as soon as the |
| 105 | /// prefix is read, before any of it is buffered. |
| 106 | pub(super) fn next(buf: &[u8], limit: u32) -> Result<Option<(u8, std::ops::Range<usize>)>, Reason> { |
| 107 | let Some(prefix) = buf.first_chunk::<PREFIX>() else { |
| 108 | return Ok(None); |
| 109 | }; |
| 110 | let len = u32::from_le_bytes(*prefix); |
| 111 | if len == 0 { |
| 112 | return Err(Reason::Protocol("a frame without a kind")); |
| 113 | } |
| 114 | if len > limit { |
| 115 | return Err(Reason::TooLarge(len)); |
| 116 | } |
| 117 | let end = PREFIX + len as usize; |
| 118 | if buf.len() < end { |
| 119 | return Ok(None); |
| 120 | } |
| 121 | Ok(Some((buf[PREFIX], PREFIX + 1..end))) |
| 122 | } |
| 123 | |
| 124 | /// What a node says of itself in the handshake. |
| 125 | #[derive(Clone, Debug, PartialEq)] |
| 126 | pub(super) struct Hello { |
| 127 | pub(super) version: u16, |
| 128 | pub(super) flags: u64, |
| 129 | pub(super) incarnation: u64, |
| 130 | pub(super) schema_hash: u64, |
| 131 | /// The largest frame it accepts. |
| 132 | pub(super) max_frame: u32, |
| 133 | pub(super) cluster: String, |
| 134 | pub(super) node: String, |
| 135 | } |
| 136 | |
| 137 | /// A hello's fixed part: version, flags, incarnation, schema hash and frame |
| 138 | /// limit. |
| 139 | const FIXED: usize = 2 + 8 + 8 + 8 + 4; |
| 140 | |
| 141 | impl Hello { |
| 142 | pub(super) fn encode(&self) -> Vec<u8> { |
| 143 | let mut out = Vec::with_capacity(FIXED + 2 + self.cluster.len() + self.node.len()); |
| 144 | out.extend_from_slice(&self.version.to_le_bytes()); |
| 145 | out.extend_from_slice(&self.flags.to_le_bytes()); |
| 146 | out.extend_from_slice(&self.incarnation.to_le_bytes()); |
| 147 | out.extend_from_slice(&self.schema_hash.to_le_bytes()); |
| 148 | out.extend_from_slice(&self.max_frame.to_le_bytes()); |
| 149 | for name in [&self.cluster, &self.node] { |
| 150 | // Node names are at most 253 bytes (checked at start). |
| 151 | out.push(name.len() as u8); |
| 152 | out.extend_from_slice(name.as_bytes()); |
| 153 | } |
| 154 | out |
| 155 | } |
| 156 | |
| 157 | /// A peer's hello. Another version is refused first, whatever follows |
| 158 | /// it; then the fields must be well formed, the names node names, and |
| 159 | /// nothing may follow them. |
| 160 | pub(super) fn decode(body: &[u8]) -> Result<Hello, Reason> { |
| 161 | let malformed = Reason::Protocol("a malformed hello"); |
| 162 | let version = body |
| 163 | .first_chunk::<2>() |
| 164 | .map(|v| u16::from_le_bytes(*v)) |
| 165 | .ok_or(malformed.clone())?; |
| 166 | if version != VERSION { |
| 167 | return Err(Reason::Version(version)); |
| 168 | } |
| 169 | let fixed = body.first_chunk::<FIXED>().ok_or(malformed.clone())?; |
| 170 | let word = |at: usize| { |
| 171 | let mut b = [0; 8]; |
| 172 | b.copy_from_slice(&fixed[at..at + 8]); |
| 173 | u64::from_le_bytes(b) |
| 174 | }; |
| 175 | let mut rest = &body[FIXED..]; |
| 176 | let mut name = || -> Result<String, Reason> { |
| 177 | let (&len, tail) = rest.split_first().ok_or(malformed.clone())?; |
| 178 | let bytes = tail.get(..usize::from(len)).ok_or(malformed.clone())?; |
| 179 | rest = &tail[usize::from(len)..]; |
| 180 | if !check_node_name(bytes) { |
| 181 | return Err(Reason::Protocol("a hello's name is not a node name")); |
| 182 | } |
| 183 | // ASCII: a node name is. |
| 184 | Ok(String::from_utf8_lossy(bytes).into_owned()) |
| 185 | }; |
| 186 | let cluster = name()?; |
| 187 | let node = name()?; |
| 188 | if !rest.is_empty() { |
| 189 | return Err(malformed); |
| 190 | } |
| 191 | let mut max = [0; 4]; |
| 192 | max.copy_from_slice(&fixed[26..30]); |
| 193 | Ok(Hello { |
| 194 | version, |
| 195 | flags: word(2), |
| 196 | incarnation: word(10), |
| 197 | schema_hash: word(18), |
| 198 | max_frame: u32::from_le_bytes(max), |
| 199 | cluster, |
| 200 | node, |
| 201 | }) |
| 202 | } |
| 203 | } |
| 204 | |
| 205 | /// A refusal's body: its code, then why, in UTF-8 (cut to 255 bytes). |
| 206 | pub(super) fn refusal(code: u8, why: &str) -> Vec<u8> { |
| 207 | let mut end = why.len().min(MAX_REFUSAL); |
| 208 | while !why.is_char_boundary(end) { |
| 209 | end -= 1; |
| 210 | } |
| 211 | let mut out = Vec::with_capacity(1 + end); |
| 212 | out.push(code); |
| 213 | out.extend_from_slice(&why.as_bytes()[..end]); |
| 214 | out |
| 215 | } |
| 216 | |
| 217 | /// A peer's refusal, as [`Reason::Refused`]. |
| 218 | pub(super) fn refused(body: &[u8]) -> Reason { |
| 219 | match body.split_first() { |
| 220 | Some((&code, text)) if text.len() <= MAX_REFUSAL => { |
| 221 | Reason::Refused(code, String::from_utf8_lossy(text).into_owned()) |
| 222 | } |
| 223 | _ => Reason::Protocol("a malformed refusal"), |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | /// Whether `addr` can be dialed, as a list's entry or this node's |
| 228 | /// advertisement must: a port, an address that is neither unspecified, |
| 229 | /// multicast nor broadcast, and an IPv4 address as such (not mapped into |
| 230 | /// IPv6), so each address has one encoding. |
| 231 | pub(super) fn dialable(addr: SocketAddr) -> bool { |
| 232 | let ip_ok = match addr.ip() { |
| 233 | IpAddr::V4(v4) => !v4.is_unspecified() && !v4.is_multicast() && !v4.is_broadcast(), |
| 234 | IpAddr::V6(v6) => { |
| 235 | !v6.is_unspecified() && !v6.is_multicast() && v6.to_ipv4_mapped().is_none() |
| 236 | } |
| 237 | }; |
| 238 | addr.port() != 0 && ip_ok |
| 239 | } |
| 240 | |
| 241 | /// One frame of a node's list of peers (`docs/wire-format.md`, *Peers*): |
| 242 | /// node names and the addresses to dial them at. Addresses are hints: |
| 243 | /// TLS checks the name a dial expects. |
| 244 | #[derive(Clone, Debug, PartialEq)] |
| 245 | pub(super) struct Peers { |
| 246 | /// This frame starts the sender's list, which replaces its previous |
| 247 | /// one; otherwise it adds to it. |
| 248 | pub(super) first: bool, |
| 249 | pub(super) nodes: Vec<(String, SocketAddr)>, |
| 250 | } |
| 251 | |
| 252 | impl Peers { |
| 253 | /// `nodes` as the bodies of signal frames (op, then fields), each |
| 254 | /// within `limit`, a frame limit (the kind and the body; at least |
| 255 | /// 1024): the first starts the list. No nodes is one frame, which |
| 256 | /// empties the receiver's list. An entry is at most 273 bytes, so it |
| 257 | /// always fits. |
| 258 | pub(super) fn frames(nodes: &[(String, SocketAddr)], limit: u32) -> Vec<Vec<u8>> { |
| 259 | let room = (limit as usize).saturating_sub(1).max(PEERS_HEAD + 273); |
| 260 | let head = |first: bool| vec![PEERS, u8::from(first), 0, 0]; |
| 261 | let mut frames = Vec::new(); |
| 262 | let mut body = head(true); |
| 263 | let mut count: u16 = 0; |
| 264 | for (name, addr) in nodes { |
| 265 | let entry = entry(name, *addr); |
| 266 | if count == u16::MAX || body.len() + entry.len() > room { |
| 267 | body[2..4].copy_from_slice(&count.to_le_bytes()); |
| 268 | frames.push(std::mem::replace(&mut body, head(false))); |
| 269 | count = 0; |
| 270 | } |
| 271 | body.extend_from_slice(&entry); |
| 272 | count += 1; |
| 273 | } |
| 274 | body[2..4].copy_from_slice(&count.to_le_bytes()); |
| 275 | frames.push(body); |
| 276 | frames |
| 277 | } |
| 278 | |
| 279 | /// A list frame's fields, after its op. Each name a node name, once; |
| 280 | /// each address [`dialable`]; nothing after the last. What is wrong, |
| 281 | /// otherwise. The receiver reads at most `max_peers` names of a list |
| 282 | /// (`Thread::listed`): a longer one, from a node that keeps more peers |
| 283 | /// than this one, is cut, not refused. |
| 284 | pub(super) fn decode(fields: &[u8]) -> Result<Peers, &'static str> { |
| 285 | let malformed = "a malformed list of peers"; |
| 286 | let (&first, rest) = fields.split_first().ok_or(malformed)?; |
| 287 | let first = match first { |
| 288 | 0 => false, |
| 289 | 1 => true, |
| 290 | _ => return Err(malformed), |
| 291 | }; |
| 292 | let count = rest.first_chunk::<2>().ok_or(malformed)?; |
| 293 | let count = usize::from(u16::from_le_bytes(*count)); |
| 294 | let mut rest = &rest[2..]; |
| 295 | // An entry takes at least 9 bytes: no more room than the bytes |
| 296 | // hold. |
| 297 | let mut nodes = Vec::with_capacity(count.min(rest.len() / 9)); |
| 298 | let mut seen = HashSet::with_capacity(nodes.capacity()); |
| 299 | let mut take = |n: usize| -> Result<&[u8], &'static str> { |
| 300 | let (taken, tail) = rest.split_at_checked(n).ok_or(malformed)?; |
| 301 | rest = tail; |
| 302 | Ok(taken) |
| 303 | }; |
| 304 | for _ in 0..count { |
| 305 | let len = take(1)?[0]; |
| 306 | let name = take(usize::from(len))?; |
| 307 | if !check_node_name(name) { |
| 308 | return Err("a listed name is not a node name"); |
| 309 | } |
| 310 | let ip = match take(1)?[0] { |
| 311 | 4 => { |
| 312 | let b: [u8; 4] = take(4)?.try_into().map_err(|_| malformed)?; |
| 313 | IpAddr::V4(Ipv4Addr::from(b)) |
| 314 | } |
| 315 | 6 => { |
| 316 | let b: [u8; 16] = take(16)?.try_into().map_err(|_| malformed)?; |
| 317 | IpAddr::V6(Ipv6Addr::from(b)) |
| 318 | } |
| 319 | _ => return Err(malformed), |
| 320 | }; |
| 321 | let port: [u8; 2] = take(2)?.try_into().map_err(|_| malformed)?; |
| 322 | let addr = SocketAddr::new(ip, u16::from_le_bytes(port)); |
| 323 | if !dialable(addr) { |
| 324 | return Err("a listed address cannot be dialed"); |
| 325 | } |
| 326 | // ASCII: a node name is. |
| 327 | let name = String::from_utf8_lossy(name).into_owned(); |
| 328 | if !seen.insert(name.clone()) { |
| 329 | return Err("a name listed twice"); |
| 330 | } |
| 331 | nodes.push((name, addr)); |
| 332 | } |
| 333 | if !rest.is_empty() { |
| 334 | return Err(malformed); |
| 335 | } |
| 336 | Ok(Peers { first, nodes }) |
| 337 | } |
| 338 | } |
| 339 | |
| 340 | /// A list's entry: the name's length and bytes, the address family (4 or |
| 341 | /// 6), the address, the port. |
| 342 | fn entry(name: &str, addr: SocketAddr) -> Vec<u8> { |
| 343 | let mut out = Vec::with_capacity(1 + name.len() + 1 + 16 + 2); |
| 344 | // Node names are at most 253 bytes (checked where they come from). |
| 345 | out.push(name.len() as u8); |
| 346 | out.extend_from_slice(name.as_bytes()); |
| 347 | match addr.ip() { |
| 348 | IpAddr::V4(v4) => { |
| 349 | out.push(4); |
| 350 | out.extend_from_slice(&v4.octets()); |
| 351 | } |
| 352 | IpAddr::V6(v6) => { |
| 353 | out.push(6); |
| 354 | out.extend_from_slice(&v6.octets()); |
| 355 | } |
| 356 | } |
| 357 | out.extend_from_slice(&addr.port().to_le_bytes()); |
| 358 | out |
| 359 | } |
| 360 | |
| 361 | #[cfg(test)] |
| 362 | mod tests { |
| 363 | use super::*; |
| 364 | |
| 365 | fn hello() -> Hello { |
| 366 | Hello { |
| 367 | version: VERSION, |
| 368 | flags: 0x0102_0304_0506_0708, |
| 369 | incarnation: 0x0123_4567_89ab_cdef, |
| 370 | schema_hash: 0x9949_47b8_73cb_1aa7, |
| 371 | max_frame: 1 << 20, |
| 372 | cluster: "prod".into(), |
| 373 | node: "a.example".into(), |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | #[test] |
| 378 | fn a_hello_has_the_documented_bytes() { |
| 379 | // docs/wire-format.md, *Handshake*: the example. |
| 380 | let bytes = hello().encode(); |
| 381 | let want: Vec<u8> = [ |
| 382 | &[0x01, 0x00][..], |
| 383 | &[0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01], |
| 384 | &[0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01], |
| 385 | &[0xa7, 0x1a, 0xcb, 0x73, 0xb8, 0x47, 0x49, 0x99], |
| 386 | &[0x00, 0x00, 0x10, 0x00], |
| 387 | &[0x04], |
| 388 | b"prod", |
| 389 | &[0x09], |
| 390 | b"a.example", |
| 391 | ] |
| 392 | .concat(); |
| 393 | assert_eq!(bytes, want); |
| 394 | assert_eq!( |
| 395 | Entry::new(HELLO, bytes.clone()).head, |
| 396 | [0x2e, 0, 0, 0, HELLO] |
| 397 | ); |
| 398 | assert_eq!(Hello::decode(&bytes), Ok(hello())); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn malformed_hellos_are_refused() { |
| 403 | let good = hello().encode(); |
| 404 | // Another version, whatever follows. |
| 405 | assert_eq!(Hello::decode(&[2, 0]), Err(Reason::Version(2))); |
| 406 | assert_eq!(Hello::decode(&[0, 1, 9]), Err(Reason::Version(256))); |
| 407 | // Every truncation. |
| 408 | for n in 0..good.len() { |
| 409 | assert!( |
| 410 | matches!(Hello::decode(&good[..n]), Err(Reason::Protocol(_))), |
| 411 | "{n} bytes" |
| 412 | ); |
| 413 | } |
| 414 | // A byte after the node name. |
| 415 | let mut long = good.clone(); |
| 416 | long.push(0); |
| 417 | assert!(matches!(Hello::decode(&long), Err(Reason::Protocol(_)))); |
| 418 | // A name that is not a node name. |
| 419 | let mut upper = good.clone(); |
| 420 | let at = upper.len() - 1; |
| 421 | upper[at] = b'E'; |
| 422 | assert!(matches!(Hello::decode(&upper), Err(Reason::Protocol(_)))); |
| 423 | let mut empty = hello(); |
| 424 | empty.cluster.clear(); |
| 425 | assert!(matches!( |
| 426 | Hello::decode(&empty.encode()), |
| 427 | Err(Reason::Protocol(_)) |
| 428 | )); |
| 429 | } |
| 430 | |
| 431 | /// `docs/wire-format.md`, *Hello*: the flags table. Each op family |
| 432 | /// has its bit, every flag a node sets round-trips, and unknown bits |
| 433 | /// are kept as sent (and ignored). |
| 434 | #[test] |
| 435 | fn each_op_family_has_its_flag() { |
| 436 | assert_eq!( |
| 437 | [ |
| 438 | FLAG_PEERS, |
| 439 | FLAG_DEMONITOR, |
| 440 | FLAG_SPAWN_LINKED, |
| 441 | FLAG_SPAWN_MONITORED, |
| 442 | FLAG_UNLINK |
| 443 | ], |
| 444 | [1, 2, 4, 8, 16] |
| 445 | ); |
| 446 | assert_eq!(FLAGS_OPS, 0b1_1110); |
| 447 | let flagged: Vec<(u8, u64)> = (0..=u8::MAX) |
| 448 | .map(|op| (op, needs(op))) |
| 449 | .filter(|(_, f)| *f != 0) |
| 450 | .collect(); |
| 451 | assert_eq!( |
| 452 | flagged, |
| 453 | [ |
| 454 | (0x16, FLAG_DEMONITOR), |
| 455 | (0x17, FLAG_UNLINK), |
| 456 | (0x18, FLAG_UNLINK), |
| 457 | (0x22, FLAG_SPAWN_LINKED), |
| 458 | (0x23, FLAG_SPAWN_MONITORED), |
| 459 | ] |
| 460 | ); |
| 461 | for flags in [0, FLAGS_OPS, FLAG_PEERS | FLAGS_OPS, u64::MAX, 1 << 63] { |
| 462 | let h = Hello { flags, ..hello() }; |
| 463 | assert_eq!(Hello::decode(&h.encode()), Ok(h)); |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | #[test] |
| 468 | fn frames_are_cut_by_their_prefix() { |
| 469 | let mut buf = Vec::new(); |
| 470 | let e = Entry::new(MESSAGE, vec![7; 3]); |
| 471 | buf.extend_from_slice(&e.head); |
| 472 | buf.extend_from_slice(&e.body); |
| 473 | assert_eq!(e.head, [4, 0, 0, 0, MESSAGE]); |
| 474 | assert_eq!(next(&buf, 4), Ok(Some((MESSAGE, 5..8)))); |
| 475 | assert_eq!(next(&buf[..7], 4), Ok(None), "incomplete"); |
| 476 | assert_eq!(next(&buf[..3], 4), Ok(None), "no prefix yet"); |
| 477 | assert_eq!(next(&buf, 3), Err(Reason::TooLarge(4)), "over the limit"); |
| 478 | // Refused on the prefix alone, before the body is buffered. |
| 479 | assert_eq!( |
| 480 | next(&u32::MAX.to_le_bytes(), 1 << 20), |
| 481 | Err(Reason::TooLarge(u32::MAX)) |
| 482 | ); |
| 483 | assert!(matches!(next(&[0, 0, 0, 0], 9), Err(Reason::Protocol(_)))); |
| 484 | } |
| 485 | |
| 486 | #[test] |
| 487 | fn refusals_are_bounded() { |
| 488 | assert_eq!(refusal(3, "schema"), b"\x03schema"); |
| 489 | let long = "é".repeat(200); |
| 490 | let body = refusal(4, &long); |
| 491 | assert_eq!(body.len(), 1 + 254, "cut at a character boundary"); |
| 492 | assert_eq!(refused(&body), Reason::Refused(4, "é".repeat(127))); |
| 493 | assert!(matches!(refused(&[]), Reason::Protocol(_))); |
| 494 | assert!(matches!(refused(&[1; 257]), Reason::Protocol(_))); |
| 495 | assert_eq!(refused(&[5, 0xff]), Reason::Refused(5, "\u{fffd}".into())); |
| 496 | } |
| 497 | |
| 498 | fn addr(s: &str) -> SocketAddr { |
| 499 | s.parse().expect("an address") |
| 500 | } |
| 501 | |
| 502 | #[test] |
| 503 | fn a_list_of_peers_has_the_documented_bytes() { |
| 504 | // docs/wire-format.md, *Peers*: the example. |
| 505 | let nodes = vec![ |
| 506 | ("b.example".to_string(), addr("10.0.0.2:4370")), |
| 507 | ("c.example".to_string(), addr("[2001:db8::3]:4370")), |
| 508 | ]; |
| 509 | let frames = Peers::frames(&nodes, 1 << 20); |
| 510 | let want: Vec<u8> = [ |
| 511 | &[PEERS, 0x01, 0x02, 0x00][..], |
| 512 | &[0x09], |
| 513 | b"b.example", |
| 514 | &[0x04, 10, 0, 0, 2, 0x12, 0x11], |
| 515 | &[0x09], |
| 516 | b"c.example", |
| 517 | &[ |
| 518 | 0x06, 0x20, 0x01, 0x0d, 0xb8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, |
| 519 | ], |
| 520 | &[0x12, 0x11], |
| 521 | ] |
| 522 | .concat(); |
| 523 | assert_eq!(frames, std::slice::from_ref(&want)); |
| 524 | let decoded = Peers::decode(&want[1..]).expect("a list"); |
| 525 | assert_eq!(decoded, Peers { first: true, nodes }); |
| 526 | // No nodes: one frame, which empties the receiver's list. |
| 527 | assert_eq!(Peers::frames(&[], 1024), [vec![PEERS, 1, 0, 0]]); |
| 528 | } |
| 529 | |
| 530 | #[test] |
| 531 | fn a_long_list_is_cut_to_the_peers_frame_limit() { |
| 532 | let nodes: Vec<(String, SocketAddr)> = (0..40) |
| 533 | .map(|i| { |
| 534 | ( |
| 535 | format!("node-{i}.{}.example", "x".repeat(60)), |
| 536 | addr("[2001:db8::1]:9"), |
| 537 | ) |
| 538 | }) |
| 539 | .collect(); |
| 540 | let frames = Peers::frames(&nodes, 1024); |
| 541 | assert!(frames.len() > 1, "{} frames", frames.len()); |
| 542 | let mut back = Vec::new(); |
| 543 | for (i, body) in frames.iter().enumerate() { |
| 544 | // Its kind and body within the limit. |
| 545 | assert!(body.len() < 1024, "frame {i}: {} bytes", body.len()); |
| 546 | let list = Peers::decode(&body[1..]).expect("a list"); |
| 547 | assert_eq!(list.first, i == 0); |
| 548 | back.extend(list.nodes); |
| 549 | } |
| 550 | assert_eq!(back, nodes); |
| 551 | } |
| 552 | |
| 553 | #[test] |
| 554 | fn malformed_lists_of_peers_are_refused() { |
| 555 | let good = |
| 556 | Peers::frames(&[("b.example".to_string(), addr("10.0.0.2:4370"))], 1024).remove(0); |
| 557 | let fields = &good[1..]; |
| 558 | assert!(Peers::decode(fields).is_ok()); |
| 559 | // Every truncation, and a byte after the last entry. |
| 560 | for n in 0..fields.len() { |
| 561 | assert!(Peers::decode(&fields[..n]).is_err(), "{n} bytes"); |
| 562 | } |
| 563 | assert!(Peers::decode(&[fields, &[0]].concat()).is_err()); |
| 564 | let with = |at: usize, byte: u8| { |
| 565 | let mut f = fields.to_vec(); |
| 566 | f[at] = byte; |
| 567 | Peers::decode(&f) |
| 568 | }; |
| 569 | // Neither a first frame nor a next one. |
| 570 | assert!(with(0, 2).is_err()); |
| 571 | // A count the bytes do not hold. |
| 572 | assert!(with(1, 2).is_err()); |
| 573 | assert!(Peers::decode(&[1, 0xff, 0xff]).is_err()); |
| 574 | // Not a node name: upper case, empty. |
| 575 | assert!(with(4, b'B').is_err()); |
| 576 | assert!(with(3, 0).is_err()); |
| 577 | // Another address family. |
| 578 | assert!(with(13, 5).is_err()); |
| 579 | assert!(with(13, 6).is_err(), "a v6 address in a v4 entry's bytes"); |
| 580 | let one = |a: &str| Peers::frames(&[("b.example".to_string(), addr(a))], 1024).remove(0); |
| 581 | for bad in [ |
| 582 | "10.0.0.2:0", |
| 583 | "0.0.0.0:4370", |
| 584 | "255.255.255.255:4370", |
| 585 | "224.0.0.1:4370", |
| 586 | "[::]:4370", |
| 587 | "[ff02::1]:4370", |
| 588 | "[::ffff:10.0.0.2]:4370", |
| 589 | ] { |
| 590 | assert!(Peers::decode(&one(bad)[1..]).is_err(), "{bad}"); |
| 591 | assert!(!dialable(addr(bad)), "{bad}"); |
| 592 | } |
| 593 | assert!(dialable(addr("127.0.0.1:1")) && dialable(addr("[::1]:1"))); |
| 594 | // A name twice. |
| 595 | let twice = Peers::frames( |
| 596 | &[ |
| 597 | ("b.example".to_string(), addr("10.0.0.2:1")), |
| 598 | ("b.example".to_string(), addr("10.0.0.3:1")), |
| 599 | ], |
| 600 | 1024, |
| 601 | ) |
| 602 | .remove(0); |
| 603 | assert_eq!(Peers::decode(&twice[1..]), Err("a name listed twice")); |
| 604 | } |
| 605 | } |