diff --git a/crates/domistream/tests/enet.rs b/crates/domistream/tests/enet.rs new file mode 100644 index 0000000..7863a08 --- /dev/null +++ b/crates/domistream/tests/enet.rs @@ -0,0 +1,683 @@ +//! ENet (`docs/PROTOCOL.md` 3.1): the datagram codec against byte vectors built from the field definitions, hostile +//! datagrams, and the client peer driven by a scripted host: handshake, reliable sequence numbers at the 0xFFFF +//! wrap, duplicates, far-future and far-past, fragments with lying lengths, retransmission and timeouts. + +#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)] + +mod common; + +use core::time::Duration; + +use common::SeqRng; +use domistream::enet::protocol::{ + Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, NO_PEER_ID, + encode_datagram, parse_datagram, +}; +use domistream::enet::{ + Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE, +}; +use domistream::{Error, Instant}; +use proptest::prelude::*; + +// ================================================================================================ codec vectors + +fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command { + Command { acknowledge, channel_id, reliable_sequence, body } +} + +#[test] +fn ping_vector() { + // peer 1, session 0, sent-time flag; ping with acknowledge flag on channel 0xFF, reliable sequence 1. + let bytes = [0x80, 0x01, 0x12, 0x34, 0x85, 0xFF, 0x00, 0x01]; + let want = Datagram { peer_id: 1, session_id: 0, sent_time: Some(0x1234), commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)] }; + assert_eq!(parse_datagram(&bytes).unwrap(), want); + assert_eq!(encode_datagram(&want).unwrap(), bytes); +} + +#[test] +fn acknowledge_reliable_disconnect_vectors() { + // peer 0xABC, session 2, no sent time: 0x2ABC. + let mut bytes = vec![0x2A, 0xBC]; + bytes.extend_from_slice(&[0x01, 0x00, 0x00, 0x05, 0x00, 0x07, 0x12, 0x34]); // acknowledge (8) + bytes.extend_from_slice(&[0x86, 0x00, 0x00, 0x02, 0x00, 0x03, 0xAA, 0xBB, 0xCC]); // send reliable (6 + 3) + bytes.extend_from_slice(&[0x84, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2A]); // disconnect (8) + let want = Datagram { + peer_id: 0x0ABC, + session_id: 2, + sent_time: None, + commands: vec![ + cmd(false, 0, 5, CommandBody::Acknowledge { received_reliable_sequence: 7, received_sent_time: 0x1234 }), + cmd(true, 0, 2, CommandBody::SendReliable(vec![0xAA, 0xBB, 0xCC])), + cmd(true, 0xFF, 3, CommandBody::Disconnect { data: 42 }), + ], + }; + assert_eq!(parse_datagram(&bytes).unwrap(), want); + assert_eq!(encode_datagram(&want).unwrap(), bytes); +} + +fn params(connect_id: u32) -> ConnectParams { + ConnectParams { + outgoing_peer_id: 3, + incoming_session_id: 0xFF, + outgoing_session_id: 0xFF, + mtu: 1400, + window_size: 32768, + channel_count: 2, + incoming_bandwidth: 0, + outgoing_bandwidth: 0, + packet_throttle_interval: 5000, + packet_throttle_acceleration: 2, + packet_throttle_deceleration: 2, + connect_id, + } +} + +fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec) -> Fragment { + Fragment { start_sequence: start, fragment_count: count, fragment_number: number, total_length: total, fragment_offset: offset, data } +} + +/// Every command kind, with the total size PROTOCOL.md 3.1 gives for it. +fn every_command() -> Vec<(Command, usize)> { + vec![ + (cmd(false, 0, 1, CommandBody::Acknowledge { received_reliable_sequence: 9, received_sent_time: 77 }), 8), + (cmd(true, 0xFF, 1, CommandBody::Connect { params: params(0xDEAD_BEEF), data: 0x1234_5678 }), 48), + (cmd(true, 0xFF, 1, CommandBody::VerifyConnect(params(0xDEAD_BEEF))), 44), + (cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 0 }), 8), + (cmd(true, 0xFF, 3, CommandBody::Ping), 4), + (cmd(true, 0, 4, CommandBody::SendReliable(vec![1, 2, 3, 4, 5])), 6 + 5), + (cmd(false, 1, 4, CommandBody::SendUnreliable { unreliable_sequence: 0xFFFF, data: vec![9; 7] }), 8 + 7), + (cmd(true, 0, 5, CommandBody::SendFragment(frag(5, 2, 0, 20, 0, vec![1; 10]))), 24 + 10), + (cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 513, data: vec![3; 2] }), 8 + 2), + (cmd(true, 0xFF, 6, CommandBody::BandwidthLimit { incoming: 1, outgoing: 2 }), 12), + (cmd(true, 0xFF, 7, CommandBody::ThrottleConfigure { interval: 5000, acceleration: 2, deceleration: 2 }), 16), + (cmd(false, 0, 8, CommandBody::SendUnreliableFragment(frag(8, 3, 2, 30, 20, vec![4; 10]))), 24 + 10), + ] +} + +#[test] +fn every_command_round_trips_with_its_wire_size() { + for (c, size) in every_command() { + for sent_time in [None, Some(0xBEEF)] { + let d = Datagram { peer_id: 7, session_id: 1, sent_time, commands: vec![c.clone()] }; + let bytes = encode_datagram(&d).unwrap(); + let header = if sent_time.is_some() { 4 } else { 2 }; + assert_eq!(bytes.len(), header + size, "{:?}", c.body); + assert_eq!(bytes[header] & 0x0F, kind(&c.body), "command number of {:?}", c.body); + assert_eq!(bytes[header] & 0x80 != 0, c.acknowledge); + assert_eq!(parse_datagram(&bytes).unwrap(), d); + } + } + let all = Datagram { peer_id: 0x0FFF, session_id: 3, sent_time: Some(1), commands: every_command().into_iter().map(|(c, _)| c).collect() }; + assert_eq!(parse_datagram(&encode_datagram(&all).unwrap()).unwrap(), all); +} + +fn kind(b: &CommandBody) -> u8 { + match b { + CommandBody::Acknowledge { .. } => 1, + CommandBody::Connect { .. } => 2, + CommandBody::VerifyConnect(_) => 3, + CommandBody::Disconnect { .. } => 4, + CommandBody::Ping => 5, + CommandBody::SendReliable(_) => 6, + CommandBody::SendUnreliable { .. } => 7, + CommandBody::SendFragment(_) => 8, + CommandBody::SendUnsequenced { .. } => 9, + CommandBody::BandwidthLimit { .. } => 10, + CommandBody::ThrottleConfigure { .. } => 11, + CommandBody::SendUnreliableFragment(_) => 12, + } +} + +#[test] +fn unsequenced_carries_its_flag() { + let d = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })] }; + let bytes = encode_datagram(&d).unwrap(); + assert_eq!(bytes[2] & 0x40, 0x40, "unsequenced flag"); +} + +// ================================================================================================ hostile datagrams + +#[test] +fn hostile_truncation() { + for (bad, why) in [ + (&[][..], "empty"), + (&[0x00][..], "one byte"), + (&[0x80, 0x01, 0x12][..], "sent-time flag, cut sent time"), + (&[0x00, 0x01, 0x85, 0xFF, 0x00][..], "cut command header"), + (&[0x00, 0x01, 0x01, 0x00, 0x00, 0x05, 0x00, 0x07][..], "cut acknowledge"), + (&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00][..], "cut data length"), + (&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x0A, 1, 2, 3][..], "data length over"), + (&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1][..], "data length 65535"), + (&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x01, 1, 2, 3][..], "data length under: 2 stray bytes"), + ] { + assert_err!(parse_datagram(bad), Error::Truncated { .. }, "{why}"); + } + // A connect cut at every length. + let full = encode_datagram(&Datagram { peer_id: NO_PEER_ID, session_id: 0, sent_time: Some(0), commands: vec![every_command()[1].0.clone()] }).unwrap(); + for cut in 5..full.len() { + assert_err!(parse_datagram(&full[..cut]), Error::Truncated { .. }, "connect cut at {cut}"); + } +} + +#[test] +fn hostile_values() { + assert_err!(parse_datagram(&[0x40, 0x01, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed"); + assert_err!(parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed + time"); + for number in [0u8, 13, 14, 15] { + assert_err!(parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]), Error::UnexpectedValue { .. }, "command {number}"); + } + // A good command followed by an unknown one: the whole datagram is refused. + assert_err!(parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]), Error::UnexpectedValue { .. }); +} + +#[test] +fn hostile_sizes() { + let ping = [0x85, 0xFF, 0x00, 0x01]; + let pings = |n: usize| { + let mut b = vec![0x00, 0x01]; + for _ in 0..n { + b.extend_from_slice(&ping); + } + b + }; + assert_eq!(parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM)).unwrap().commands.len(), MAX_COMMANDS_PER_DATAGRAM); + match parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM + 1)) { + Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_COMMANDS_PER_DATAGRAM), + other => panic!("33 commands: {other:?}"), + } + // A reliable packet filling the datagram exactly; one byte more is over. + let reliable = |data: usize| { + let mut b = vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01]; + b.extend_from_slice(&(data as u16).to_be_bytes()); + b.extend(std::iter::repeat_n(0x5A, data)); + b + }; + let max_data = MAX_DATAGRAM_BYTES - 8; + assert_eq!(reliable(max_data).len(), MAX_DATAGRAM_BYTES); + assert!(parse_datagram(&reliable(max_data)).is_ok()); + assert_eq!(parse_datagram(&reliable(max_data - 1)).unwrap().commands.len(), 1); + assert_too_large!(parse_datagram(&reliable(max_data + 1)), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1); + assert_too_large!(parse_datagram(&vec![0; 1 << 20]), MAX_DATAGRAM_BYTES, 1 << 20); +} + +#[test] +fn encode_refuses_oversized() { + let many = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1] }; + assert!(matches!(encode_datagram(&many), Err(Error::TooLarge { .. }))); + let big = Datagram { peer_id: 0, session_id: 0, sent_time: None, commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))] }; + assert!(matches!(encode_datagram(&big), Err(Error::TooLarge { .. }))); +} + +fn body() -> impl Strategy { + let data = || proptest::collection::vec(any::(), 0..64); + let fragment = || (any::(), any::(), any::(), any::(), any::(), data()) + .prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f)); + let cparams = || proptest::array::uniform12(any::()).prop_map(|a| ConnectParams { + outgoing_peer_id: (a[0] & 0xFFFF) as u16, + incoming_session_id: a[1] as u8, + outgoing_session_id: (a[1] >> 8) as u8, + mtu: a[2], + window_size: a[3], + channel_count: a[4], + incoming_bandwidth: a[5], + outgoing_bandwidth: a[6], + packet_throttle_interval: a[7], + packet_throttle_acceleration: a[8], + packet_throttle_deceleration: a[9], + connect_id: a[10], + }); + prop_oneof![ + (any::(), any::()).prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }), + (cparams(), any::()).prop_map(|(params, data)| CommandBody::Connect { params, data }), + cparams().prop_map(CommandBody::VerifyConnect), + any::().prop_map(|data| CommandBody::Disconnect { data }), + Just(CommandBody::Ping), + data().prop_map(CommandBody::SendReliable), + (any::(), data()).prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }), + fragment().prop_map(CommandBody::SendFragment), + (any::(), data()).prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }), + (any::(), any::()).prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }), + (any::(), any::(), any::()).prop_map(|(interval, acceleration, deceleration)| CommandBody::ThrottleConfigure { interval, acceleration, deceleration }), + fragment().prop_map(CommandBody::SendUnreliableFragment), + ] +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })] + + #[test] + fn datagram_round_trip( + peer_id in 0u16..=0x0FFF, + session_id in 0u8..4, + sent_time in proptest::option::of(any::()), + commands in proptest::collection::vec((any::(), any::(), any::(), body()), 1..8), + ) { + let commands = commands.into_iter().map(|(a, ch, s, b)| cmd(a, ch, s, b)).collect(); + let d = Datagram { peer_id, session_id, sent_time, commands }; + let bytes = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?; + prop_assert!(bytes.len() <= MAX_DATAGRAM_BYTES); + prop_assert_eq!(parse_datagram(&bytes), Ok(d)); + } + + /// Arbitrary bytes: no panic; a parsed datagram re-encodes to something that parses to the same value. + #[test] + fn datagram_parse_is_stable(data in proptest::collection::vec(any::(), 0..512)) { + if let Ok(d) = parse_datagram(&data) { + prop_assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM); + prop_assert!(d.peer_id <= 0x0FFF && d.session_id < 4); + let again = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?; + prop_assert_eq!(parse_datagram(&again), Ok(d)); + } + } +} + +// ================================================================================================ client peer + +fn config() -> EnetConfig { + EnetConfig { + channel_count: 2, + mtu: 1400, + connect_data: 0x0000_1234, + ping_interval: Duration::from_millis(500), + timeout: Duration::from_secs(10), + } +} + +fn at(ms: u64) -> Instant { + Instant::from_micros(ms * 1000) +} + +/// The client and the scripted host's view of it. +struct Link { + client: EnetClient, + /// Peer id the host addresses the client with (from the client's connect). + to_client: u16, + /// Next reliable sequence the host uses per channel. + host_seq: [u16; 256], + now_ms: u64, +} + +impl Link { + fn host_datagram(&self, commands: Vec) -> Vec { + encode_datagram(&Datagram { peer_id: self.to_client, session_id: 0, sent_time: Some(self.now_ms as u16), commands }).unwrap() + } + + fn feed(&mut self, commands: Vec) -> domistream::Result<()> { + self.now_ms += 1; + let d = self.host_datagram(commands); + self.client.handle_datagram(at(self.now_ms), &d) + } + + fn reliable(&mut self, channel: u8, data: &[u8]) -> Command { + let s = &mut self.host_seq[usize::from(channel)]; + *s = s.wrapping_add(1); + cmd(true, channel, *s, CommandBody::SendReliable(data.to_vec())) + } + + /// Everything the client wants to send now, parsed. + fn transmitted(&mut self) -> Vec { + let mut out = Vec::new(); + while let Some(d) = self.client.poll_transmit(at(self.now_ms)) { + assert!(d.len() <= MAX_DATAGRAM_BYTES); + out.push(parse_datagram(&d).expect("the client's datagrams parse")); + assert!(out.len() < 10_000, "poll_transmit never ends"); + } + out + } + + fn events(&mut self) -> Vec { + let mut out = Vec::new(); + while let Some(e) = self.client.poll_event() { + out.push(e); + assert!(out.len() < 100_000, "poll_event never ends"); + } + out + } + + fn received(&mut self) -> Vec> { + self.events() + .into_iter() + .map(|e| match e { + EnetEvent::Received { data, .. } => data, + other => panic!("unexpected event {other:?}"), + }) + .collect() + } +} + +/// Starts a client and returns it with its connect command. +fn start() -> (EnetClient, Datagram, ConnectParams, u32, u16) { + let mut client = EnetClient::connect(config(), at(0), &mut SeqRng::new(5)).expect("EnetClient::connect"); + assert_eq!(client.state(), EnetState::Connecting); + let d = parse_datagram(&client.poll_transmit(at(0)).expect("connect datagram")).unwrap(); + let c = d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone(); + let (params, data) = match c.body { + CommandBody::Connect { params, data } => (params, data), + _ => unreachable!(), + }; + (client, d.clone(), params, data, c.reliable_sequence) +} + +/// A connected link: connect, then the host's acknowledge + verify connect. +fn connected() -> Link { + let (client, d, params, _, connect_seq) = start(); + let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 }; + let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params }; + link.feed(vec![ + cmd(false, 0xFF, 0, CommandBody::Acknowledge { received_reliable_sequence: connect_seq, received_sent_time: d.sent_time.unwrap_or(0) }), + cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify)), + ]) + .expect("verify connect"); + assert_eq!(link.events(), vec![EnetEvent::Connected]); + assert_eq!(link.client.state(), EnetState::Connected); + link.transmitted(); + link +} + +#[test] +fn connect_offers_the_config() { + let (_, d, params, data, _) = start(); + assert_eq!(d.peer_id, NO_PEER_ID, "no peer id yet"); + assert_eq!(params.mtu, u32::from(config().mtu)); + assert_eq!(params.channel_count, u32::from(config().channel_count)); + assert_eq!(data, config().connect_data); + let c = &d.commands[0]; + assert!(c.acknowledge && c.channel_id == 0xFF, "connect is reliable, connection-level"); + // The connect id comes from the caller's randomness. + let (_, _, p2, _, _) = start(); + assert_eq!(p2.connect_id, params.connect_id); +} + +#[test] +fn connect_refuses_configs_outside_enet_limits() { + for bad in [ + EnetConfig { mtu: 575, ..config() }, + EnetConfig { mtu: 4097, ..config() }, + EnetConfig { mtu: 0, ..config() }, + EnetConfig { channel_count: 0, ..config() }, + ] { + assert_err!(EnetClient::connect(bad, at(0), &mut SeqRng::new(1)), Error::Malformed { .. }, "{bad:?}"); + } + for ok in [EnetConfig { mtu: 576, ..config() }, EnetConfig { mtu: 4096, ..config() }, EnetConfig { channel_count: 255, ..config() }] { + assert!(EnetClient::connect(ok, at(0), &mut SeqRng::new(1)).is_ok(), "{ok:?}"); + } +} + +#[test] +fn verify_with_wrong_connect_id_does_not_connect() { + let (client, _, params, _, _) = start(); + let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 }; + let verify = ConnectParams { connect_id: params.connect_id ^ 1, outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params }; + let _ = link.feed(vec![cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]); + assert_eq!(link.client.state(), EnetState::Connecting); + assert!(link.events().is_empty()); +} + +#[test] +fn garbage_never_changes_state() { + let mut link = connected(); + for bad in [&[][..], &[0x00][..], &[0x40, 0x00, 0x85, 0xFF, 0, 1][..], &[0x00, 0x00, 0x8F, 0, 0, 0][..]] { + assert!(link.client.handle_datagram(at(5), bad).is_err(), "{bad:?}"); + assert_eq!(link.client.state(), EnetState::Connected); + } + assert_too_large!(link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1); + assert!(link.events().is_empty()); +} + +#[test] +fn datagrams_for_another_peer_are_dropped() { + let mut link = connected(); + let c = link.reliable(0, b"not for you"); + let other = encode_datagram(&Datagram { peer_id: link.to_client ^ 0x0001, session_id: 0, sent_time: Some(1), commands: vec![c] }).unwrap(); + assert_eq!(link.client.handle_datagram(at(9), &other), Ok(())); + assert!(link.events().is_empty()); +} + +#[test] +fn reliable_in_order_reordered_and_duplicated() { + let mut link = connected(); + let a = link.reliable(0, b"one"); + let b = link.reliable(0, b"two"); + let c = link.reliable(0, b"three"); + link.feed(vec![c.clone()]).unwrap(); + link.feed(vec![b.clone()]).unwrap(); + assert!(link.received().is_empty(), "nothing before sequence 1"); + link.feed(vec![a.clone()]).unwrap(); + assert_eq!(link.received(), vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]); + // Duplicates (retransmissions by the host) are acknowledged but never delivered twice. + link.feed(vec![a, b.clone(), c]).unwrap(); + link.feed(vec![b]).unwrap(); + assert!(link.received().is_empty()); + let acks: usize = link.transmitted().iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::Acknowledge { .. })).count(); + assert!(acks >= 4, "duplicates are still acknowledged ({acks})"); +} + +#[test] +fn reliable_sequence_wraps_at_0xffff() { + // 70 000 reliable packets, one per datagram: the sequence passes 0xFFFF -> 0 and order is kept. + let mut link = connected(); + let total = 70_000u32; + let mut got = 0u32; + for i in 0..total { + let c = link.reliable(0, &i.to_le_bytes()); + link.feed(vec![c]).unwrap(); + for data in link.received() { + assert_eq!(data, got.to_le_bytes(), "packet {got} out of order"); + got += 1; + } + link.transmitted(); + } + assert_eq!(got, total); + assert_eq!(link.host_seq[0], (total % 65_536) as u16); +} + +#[test] +fn far_future_and_far_past_are_dropped() { + let mut link = connected(); + for i in 0..10u8 { + let c = link.reliable(0, &[i]); + link.feed(vec![c]).unwrap(); + } + assert_eq!(link.received().len(), 10); + let next = link.host_seq[0]; + for seq in [next.wrapping_add(40_000), next.wrapping_add(0x8000), next.wrapping_sub(30_000), next.wrapping_sub(5)] { + let _ = link.feed(vec![cmd(true, 0, seq, CommandBody::SendReliable(b"evil".to_vec()))]); + assert!(link.received().is_empty(), "sequence {seq} (next {next}) must not be delivered"); + } + // The stream continues normally. + let c = link.reliable(0, b"ok"); + link.feed(vec![c]).unwrap(); + assert_eq!(link.received(), vec![b"ok".to_vec()]); + assert_eq!(link.client.state(), EnetState::Connected); +} + +#[test] +fn channels_outside_the_negotiated_count_are_not_delivered() { + let mut link = connected(); + let c = link.reliable(200, b"x"); + let _ = link.feed(vec![c]); + assert!(link.received().is_empty()); + assert_eq!(link.client.state(), EnetState::Connected); +} + +fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec { + let count = data.len().div_ceil(piece) as u32; + let start = link.host_seq[0].wrapping_add(1); + (0..count) + .map(|n| { + link.host_seq[0] = link.host_seq[0].wrapping_add(1); + let off = n as usize * piece; + let chunk = data[off..(off + piece).min(data.len())].to_vec(); + cmd(true, 0, link.host_seq[0], CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk))) + }) + .collect() +} + +#[test] +fn fragments_reassemble_in_any_order() { + let mut link = connected(); + let data: Vec = (0..3000u32).map(|i| (i * 7) as u8).collect(); + let mut frags = fragments(&mut link, &data, 1000); + frags.swap(0, 2); + for f in frags { + link.feed(vec![f]).unwrap(); + } + assert_eq!(link.received(), vec![data]); +} + +#[test] +fn fragments_with_lying_lengths() { + // Total length over the reassembly cap. + let mut link = connected(); + link.host_seq[0] += 1; + let s = link.host_seq[0]; + let r = link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])))]); + assert_too_large!(r, MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1); + assert!(link.events().is_empty()); + + // Other lies: never delivered, never a panic, the connection survives. + for f in [ + frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments + frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count + frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total + frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total + frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total + frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total + frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow + ] { + let mut link = connected(); + link.host_seq[0] += 1; + let s = link.host_seq[0]; + let r = link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]); + assert!(link.events().is_empty(), "{f:?} -> {r:?}"); + assert_eq!(link.client.state(), EnetState::Connected, "{f:?}"); + } +} + +#[test] +fn send_rules() { + let (mut client, ..) = start(); + assert_err!(client.send(at(1), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before connected"); + let mut link = connected(); + assert_err!(link.client.send(at(2), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2"); + assert_err!(link.client.send(at(2), 255, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }); + match link.client.send(at(2), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]) { + Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_PACKET_BYTES), + other => panic!("{other:?}"), + } +} + +#[test] +fn send_queue_is_capped() { + let mut link = connected(); + for i in 0..MAX_SEND_QUEUE { + link.client.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}")); + } + match link.client.send(at(3), 0, Delivery::Reliable, b"one too many") { + Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE), + other => panic!("{other:?}"), + } +} + +#[test] +fn large_sends_are_fragmented_within_the_mtu() { + let mut link = connected(); + let data: Vec = (0..5000u32).map(|i| i as u8).collect(); + link.client.send(at(4), 1, Delivery::Reliable, &data).unwrap(); + let mut pieces = Vec::new(); + while let Some(d) = link.client.poll_transmit(at(4)) { + assert!(d.len() <= usize::from(config().mtu), "datagram of {} over the MTU", d.len()); + for c in parse_datagram(&d).unwrap().commands { + if let CommandBody::SendFragment(f) = c.body { + assert_eq!(c.channel_id, 1); + assert_eq!(f.total_length, 5000); + pieces.push(f); + } + } + } + pieces.sort_by_key(|f| f.fragment_number); + assert_eq!(pieces.len() as u32, pieces[0].fragment_count); + let mut whole = vec![0u8; 5000]; + for f in &pieces { + whole[f.fragment_offset as usize..f.fragment_offset as usize + f.data.len()].copy_from_slice(&f.data); + } + assert_eq!(whole, data); +} + +#[test] +fn reliable_sends_are_retransmitted_until_acknowledged() { + let mut link = connected(); + link.client.send(at(10), 0, Delivery::Reliable, b"hello").unwrap(); + let first = link.transmitted(); + let sent = first.iter().flat_map(|d| &d.commands).find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec())).expect("sent").clone(); + let when = link.client.poll_timeout().expect("a retransmission deadline"); + link.now_ms = when.as_micros() / 1000 + 1; + link.client.handle_timeout(at(link.now_ms)).unwrap(); + let again = link.transmitted(); + assert!(again.iter().flat_map(|d| &d.commands).any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body), "retransmitted"); + // Acknowledge it: no more retransmissions of that command. + link.feed(vec![cmd(false, 0, 0, CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 })]).unwrap(); + for _ in 0..5 { + if let Some(t) = link.client.poll_timeout() { + link.now_ms = link.now_ms.max(t.as_micros() / 1000 + 1); + link.client.handle_timeout(at(link.now_ms)).unwrap(); + } + assert!(!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body), "acknowledged command sent again"); + } +} + +#[test] +fn silence_times_out() { + let mut link = connected(); + link.client.send(at(1), 0, Delivery::Reliable, b"anyone?").unwrap(); + let end = at(1 + config().timeout.as_millis() as u64 * 4); + let mut guard = 0; + while link.client.state() != EnetState::Disconnected { + let t = link.client.poll_timeout().expect("a deadline while waiting for an acknowledgement"); + assert!(t <= end, "no timeout by {end:?}"); + link.client.handle_timeout(t).unwrap(); + let _ = link.client.poll_transmit(t); + guard += 1; + assert!(guard < 10_000); + } + assert!(link.events().contains(&EnetEvent::TimedOut)); +} + +#[test] +fn host_disconnect_closes() { + let mut link = connected(); + link.feed(vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 7 })]).unwrap(); + assert_eq!(link.events(), vec![EnetEvent::Disconnected { data: 7 }]); + assert_eq!(link.client.state(), EnetState::Disconnected); + let c = link.reliable(0, b"late"); + assert_err!(link.feed(vec![c]), Error::Closed); + assert_err!(link.client.disconnect(at(100), 0), Error::Closed); +} + +#[test] +fn client_disconnect() { + let mut link = connected(); + link.client.disconnect(at(5), 9).unwrap(); + assert_eq!(link.client.state(), EnetState::Disconnecting); + let sent = link.transmitted(); + assert!(sent.iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Disconnect { data: 9 })); +} + +proptest! { + #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })] + + /// A connected client fed arbitrary datagrams never panics and never leaves Connected without a reason. + #[test] + fn client_survives_arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::(), 0..200), 1..20)) { + let mut link = connected(); + for d in datagrams { + let _ = link.client.handle_datagram(at(7), &d); + while link.client.poll_transmit(at(7)).is_some() {} + for e in link.events() { + if let EnetEvent::Received { data, .. } = e { + prop_assert!(data.len() <= MAX_PACKET_BYTES); + } + } + } + } +}