From f8bad73121f26223827542a8e10db2e83220e35f Mon Sep 17 00:00:00 2001 From: mnovak Date: Fri, 4 Dec 2026 12:29:28 +0100 Subject: [PATCH] [domistream] ENet host: EnetHostPeer, the accepting side (verify connect, session ids, reliable channels, pings, timeouts, disconnect) One peer per client address. CONNECT answered with a reliable VERIFY CONNECT as stock ENet 1.3 does it (session ids picked from the client's offer, MTU, window and channels clamped, throttle echoed); connected once the client acknowledges the verify; reliable, unreliable and unsequenced delivery with fragment reassembly under the existing caps; duplicate unsequenced groups dropped; pings when the client is quiet; retransmission and timeout as the client; disconnect both ways. Shares the client's channel, fragment and in-flight types. --- crates/domistream/src/enet/host.rs | 681 +++++++++++++++++++++++++-- crates/domistream/src/enet/mod.rs | 2 +- crates/domistream/tests/enet_host.rs | 72 ++- 3 files changed, 694 insertions(+), 61 deletions(-) diff --git a/crates/domistream/src/enet/host.rs b/crates/domistream/src/enet/host.rs index d37f3bf..3c3252e 100644 --- a/crates/domistream/src/enet/host.rs +++ b/crates/domistream/src/enet/host.rs @@ -1,27 +1,57 @@ //! The accepting side of the ENet 1.3 layer (`docs/PROTOCOL.md` 3.1): one host-side peer per client. //! //! The caller owns the UDP socket and **demultiplexes by source address**: a datagram from an address it does not -//! know yet goes to [`EnetHostPeer::accept`] (which takes only a CONNECT); every later datagram from that address -//! goes to [`EnetHostPeer::handle_datagram`] of the peer it created. A CONNECT with a new connect id from a known -//! address is a new connection (the client restarted): [`parse_connect_request`] lets the caller see that and -//! replace the old peer. +//! know yet goes to [`EnetHostPeer::accept`], which takes only a CONNECT and creates the peer; every later datagram +//! from that address goes to [`EnetHostPeer::handle_datagram`] of that peer. A CONNECT with a new connect id from a +//! known address is a new connection (the client restarted): the peer ignores it, and [`parse_connect_request`] +//! lets the caller see it and replace the old peer. Each peer has its own `peer_id` in [`EnetHostConfig`]; it may be +//! the same for every peer, since the caller tells clients apart by address. //! //! ```text //! on datagram d from addr: -//! peer = peers[addr] or EnetHostPeer::accept(config, now, &d)? // refused: drop d -//! peer.handle_datagram(now, &d) // (accept already took d) +//! match peers[addr] { +//! None => peers[addr] = EnetHostPeer::accept(config, now, &d)?, // refused: drop d +//! Some(p) => p.handle_datagram(now, &d)?, +//! } //! loop { //! while let Some(d) = peer.poll_transmit(now) { socket.send_to(&d, addr) } //! while let Some(e) = peer.poll_event() { … } //! wake at peer.poll_timeout() → peer.handle_timeout(now) //! } //! ``` +//! +//! What the host does, as stock ENet 1.3 does it (PROTOCOL.md 3.1): the CONNECT is answered with a reliable VERIFY +//! CONNECT on the connection channel (the CONNECT itself is not acknowledged: the verify retires it on the client); +//! the session ids are picked from the ones the client offers; the connection counts as up when the client +//! acknowledges the verify, and data that arrives earlier is neither taken nor acknowledged (the client sends it +//! again). A command that wants an acknowledgement in a datagram without a sent time is handled but not acknowledged, +//! and the rest of that datagram is skipped. Duplicated unsequenced packets are dropped with a 1024-group window. +//! Not done: the checksum and compression (PROTOCOL.md 3.1: GameStream clients use neither), bandwidth throttling of +//! what the host sends (bandwidth-limit and throttle-configure commands are acknowledged and otherwise ignored), and +//! unreliable fragments (dropped; control messages are small and reliable). use core::time::Duration; +use std::collections::VecDeque; -use super::Delivery; +use super::protocol::{ + self, Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, MAX_PEER_ID, MAX_WINDOW_SIZE, MIN_MTU, + MIN_WINDOW_SIZE, NO_PEER_ID, +}; +use super::{ + CONNECTION_CHANNEL, Channel, Delivery, INITIAL_RTO, InFlight, MAX_IN_FLIGHT, MAX_PACKET_BYTES, MAX_PENDING_ACKS, + MAX_PENDING_PER_CHANNEL, MAX_REASSEMBLIES, MAX_RTO, MAX_SEND_QUEUE, MIN_RTO, Outgoing, Pending, RELIABLE_WINDOW, + Reassembly, check_fragment, ms16, +}; +use crate::util::malformed; use crate::{Error, Instant, Result}; +/// Unsequenced groups tracked per window (stock ENet's window). +const UNSEQUENCED_WINDOW: u32 = 1024; +/// Windows ahead of the current one that are accepted (stock ENet's free windows). +const FREE_UNSEQUENCED_WINDOWS: u32 = 32; +/// The session id of a peer slot that has never been used (stock ENet's reset value). +const FRESH_SESSION: u8 = 0xFF; + /// Settings of the host side. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EnetHostConfig { @@ -31,7 +61,7 @@ pub struct EnetHostConfig { pub channel_limit: u8, /// Our MTU (576..=4096); the connection uses the smaller of this and the client's. pub mtu: u16, - /// Send a ping when nothing was sent for this long. + /// Send a ping when nothing was received for this long. pub ping_interval: Duration, /// Give up when a reliable command stays unacknowledged this long. pub timeout: Duration, @@ -78,118 +108,681 @@ pub enum EnetHostEvent { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ConnectRequest { /// The connect parameters. - pub params: super::protocol::ConnectParams, + pub params: ConnectParams, /// The connect command's user data word. pub data: u32, } -/// The CONNECT in a datagram addressed to "no peer yet", if it holds one. +/// The CONNECT in a datagram addressed to "no peer yet", if it holds one. As in stock ENet, only a CONNECT at the +/// start of such a datagram counts. /// /// # Errors -/// Parser errors as [`super::protocol::parse_datagram`]; [`Error::UnexpectedValue`] when the datagram is addressed -/// to a peer or holds no CONNECT, or the channel count is outside 1..=255. +/// Parser errors as [`protocol::parse_datagram`]; [`Error::UnexpectedValue`] when the datagram is addressed to a +/// peer, does not start with a CONNECT, or asks for a channel count outside 1..=255. pub fn parse_connect_request(datagram: &[u8]) -> Result { - let _ = datagram; - Err(Error::Unimplemented) + let d = protocol::parse_datagram(datagram)?; + if d.peer_id != NO_PEER_ID { + return Err(Error::UnexpectedValue { what: "enet connect peer id", value: d.peer_id.into() }); + } + let Some(first) = d.commands.into_iter().next() else { + return Err(Error::UnexpectedValue { what: "enet connect command", value: 0 }); + }; + let CommandBody::Connect { params, data } = first.body else { + return Err(Error::UnexpectedValue { + what: "enet connect command", + value: (protocol::kind_of(&first.body) as u8).into(), + }); + }; + if params.channel_count == 0 || params.channel_count > u32::from(protocol::MAX_CHANNEL_COUNT) { + return Err(Error::UnexpectedValue { what: "enet channel count", value: params.channel_count.into() }); + } + Ok(ConnectRequest { params, data }) +} + +/// The session id one side ends up with: the offered one (or ours when the client says "pick one", 0xFF) plus +/// one, skipping the value the slot used last (PROTOCOL.md 3.1, stock ENet). +const fn next_session(offered: u8, current: u8) -> u8 { + let base = if offered == FRESH_SESSION { current } else { offered }; + let mut s = base.wrapping_add(1) & 0x3; + if s == current { + s = s.wrapping_add(1) & 0x3; + } + s } /// The host-side ENet peer of one client. #[derive(Debug)] pub struct EnetHostPeer { config: EnetHostConfig, + state: EnetHostState, + connect_id: u32, + connect_data: u32, + /// The client's peer id: the header of every datagram we send. + client_peer_id: u16, + /// Session id in the header of our datagrams. + out_session: u8, + /// Session id the client's datagrams must carry. + in_session: u8, + channel_count: u8, + mtu: usize, + connection_out_reliable: u16, + unsequenced_group: u16, + in_unsequenced_base: u16, + unsequenced_seen: [u32; (UNSEQUENCED_WINDOW / 32) as usize], + channels: Vec, + outgoing: VecDeque, + queued_packets: usize, + resend: VecDeque, + acks: VecDeque, + in_flight: Vec, + reassemblies: Vec, + events: VecDeque, + last_receive: Instant, + srtt: Option, + rttvar: Duration, } impl EnetHostPeer { - /// Accepts a client's CONNECT datagram: queues the verify connect. + /// Accepts a client's CONNECT datagram: queues the verify connect. The datagram is consumed; do not feed it to + /// [`Self::handle_datagram`] again. /// /// # Errors - /// [`Error::Malformed`] for a config outside ENet's limits; anything [`parse_connect_request`] refuses. + /// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel, peer id up to + /// 0xFFE); anything [`parse_connect_request`] refuses. pub fn accept(config: EnetHostConfig, now: Instant, datagram: &[u8]) -> Result { - let _ = (config, now, datagram); - Err(Error::Unimplemented) + if config.mtu < MIN_MTU + || usize::from(config.mtu) > MAX_DATAGRAM_BYTES + || config.channel_limit == 0 + || config.peer_id >= MAX_PEER_ID + { + return Err(malformed("enet host config")); + } + let ConnectRequest { params: p, data } = parse_connect_request(datagram)?; + let out_session = next_session(p.incoming_session_id, FRESH_SESSION); + let in_session = next_session(p.outgoing_session_id, FRESH_SESSION); + let max_mtu = u32::try_from(MAX_DATAGRAM_BYTES).unwrap_or(u32::MAX); + let mtu = p.mtu.clamp(u32::from(MIN_MTU), max_mtu).min(u32::from(config.mtu)); + let window_size = MAX_WINDOW_SIZE.min(p.window_size).clamp(MIN_WINDOW_SIZE, MAX_WINDOW_SIZE); + let channel_count = u8::try_from(p.channel_count.min(u32::from(config.channel_limit))).unwrap_or(1); + let mut peer = Self { + config, + state: EnetHostState::AcknowledgingConnect, + connect_id: p.connect_id, + connect_data: data, + client_peer_id: p.outgoing_peer_id & MAX_PEER_ID, + out_session, + in_session, + channel_count, + mtu: usize::try_from(mtu).unwrap_or(usize::from(MIN_MTU)), + connection_out_reliable: 0, + unsequenced_group: 0, + in_unsequenced_base: 0, + unsequenced_seen: [0; (UNSEQUENCED_WINDOW / 32) as usize], + channels: (0..channel_count).map(|_| Channel::default()).collect(), + outgoing: VecDeque::new(), + queued_packets: 0, + resend: VecDeque::new(), + acks: VecDeque::new(), + in_flight: Vec::new(), + reassemblies: Vec::new(), + events: VecDeque::new(), + last_receive: now, + srtt: None, + rttvar: Duration::ZERO, + }; + let verify = ConnectParams { + outgoing_peer_id: config.peer_id, + incoming_session_id: out_session, + outgoing_session_id: in_session, + mtu, + window_size, + channel_count: u32::from(channel_count), + incoming_bandwidth: 0, + outgoing_bandwidth: 0, + packet_throttle_interval: p.packet_throttle_interval, + packet_throttle_acceleration: p.packet_throttle_acceleration, + packet_throttle_deceleration: p.packet_throttle_deceleration, + connect_id: p.connect_id, + }; + peer.queue_connection_command(CommandBody::VerifyConnect(verify)); + Ok(peer) } - /// Feeds one datagram from the client. + fn queue_connection_command(&mut self, body: CommandBody) { + self.connection_out_reliable = self.connection_out_reliable.wrapping_add(1); + let command = Command { + acknowledge: true, + channel_id: CONNECTION_CHANNEL, + reliable_sequence: self.connection_out_reliable, + body, + }; + self.outgoing.push_back(Outgoing { command, ends_packet: false }); + } + + fn rto(&self) -> Duration { + match self.srtt { + None => INITIAL_RTO, + Some(s) => (s + 4 * self.rttvar).clamp(MIN_RTO, MAX_RTO), + } + } + + /// Closes with `event`. Acknowledgements already queued still go out (the client's disconnect among them). + fn close(&mut self, event: EnetHostEvent) { + self.state = EnetHostState::Disconnected; + self.events.push_back(event); + self.outgoing.clear(); + self.queued_packets = 0; + self.resend.clear(); + self.in_flight.clear(); + self.reassemblies.clear(); + for ch in &mut self.channels { + ch.pending.clear(); + } + } + + /// Feeds one datagram from the client. Datagrams for another peer id or session, and CONNECTs (repeated or + /// new), are dropped without error. /// /// # Errors - /// Parser errors; [`Error::Closed`] once disconnected. + /// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] or [`Error::Malformed`] for a fragment + /// that lies about its lengths; [`Error::Closed`] once disconnected. A malformed datagram never changes the + /// connection state. pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { - let _ = (now, datagram); - Err(Error::Unimplemented) + if self.state == EnetHostState::Disconnected { + return Err(Error::Closed); + } + let d = protocol::parse_datagram(datagram)?; + if d.peer_id != self.config.peer_id || d.session_id != self.in_session { + return Ok(()); + } + self.last_receive = now; + let sent_time = d.sent_time; + for c in d.commands { + if self.state == EnetHostState::Disconnected { + break; + } + let wants_ack = c.acknowledge; + // Stock ENet stops at the first command it cannot handle, and after an acknowledged command in a + // datagram without sent time (PROTOCOL.md 3.1). + self.command(now, sent_time, c)?; + if wants_ack && sent_time.is_none() { + break; + } + } + Ok(()) } - /// Queues a packet. + fn ack(&mut self, channel: u8, seq: u16, sent_time: Option) { + let Some(sent_time) = sent_time else { return }; + if self.acks.len() >= MAX_PENDING_ACKS { + self.acks.pop_front(); + } + self.acks.push_back(Command { + acknowledge: false, + channel_id: channel, + reliable_sequence: seq, + body: CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: sent_time }, + }); + } + + fn command(&mut self, now: Instant, sent_time: Option, c: Command) -> Result<()> { + let (channel, seq) = (c.channel_id, c.reliable_sequence); + let connected = self.state == EnetHostState::Connected; + match c.body { + CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => { + self.acknowledged(now, channel, received_reliable_sequence, received_sent_time); + Ok(()) + } + CommandBody::Disconnect { data } => { + if c.acknowledge && connected { + self.ack(channel, seq, sent_time); + } + self.close(EnetHostEvent::Disconnected { data }); + Ok(()) + } + CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => { + if c.acknowledge && connected { + self.ack(channel, seq, sent_time); + } + Ok(()) + } + CommandBody::Connect { .. } | CommandBody::VerifyConnect(_) | CommandBody::SendUnreliableFragment(_) => { + Ok(()) + } + CommandBody::SendReliable(data) => self.reliable(channel, seq, sent_time, Pending::Data(data)), + CommandBody::SendFragment(f) => { + let check = check_fragment(seq, &f); + let pending = match &check { + Ok(()) => Pending::Fragment(f), + Err(_) => Pending::Skip, + }; + self.reliable(channel, seq, sent_time, pending)?; + check + } + CommandBody::SendUnreliable { unreliable_sequence, data } => { + if connected + && channel < self.channel_count + && let Some(ch) = self.channels.get_mut(usize::from(channel)) + { + let newer = ch + .in_unreliable + .is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last))); + if newer { + ch.in_unreliable = Some(unreliable_sequence); + self.events.push_back(EnetHostEvent::Received { channel, data }); + } + } + Ok(()) + } + CommandBody::SendUnsequenced { unsequenced_group, data } => { + if connected && channel < self.channel_count && self.unsequenced_fresh(unsequenced_group) { + self.events.push_back(EnetHostEvent::Received { channel, data }); + } + Ok(()) + } + } + } + + /// Whether an unsequenced group is new: a window of [`UNSEQUENCED_WINDOW`] groups remembers what was seen; + /// groups up to [`FREE_UNSEQUENCED_WINDOWS`] windows ahead move it, anything else is dropped. + fn unsequenced_fresh(&mut self, group: u16) -> bool { + let index = u32::from(group) % UNSEQUENCED_WINDOW; + let base = u32::from(self.in_unsequenced_base); + let mut g = u32::from(group); + if g < base { + g += 0x1_0000; + } + if g >= base + FREE_UNSEQUENCED_WINDOWS * UNSEQUENCED_WINDOW { + return false; + } + let g = g & 0xFFFF; + let new_base = g - index; + if new_base != base { + self.in_unsequenced_base = u16::try_from(new_base).unwrap_or(0); + self.unsequenced_seen = [0; (UNSEQUENCED_WINDOW / 32) as usize]; + } + let bit = 1u32 << (index % 32); + let Some(word) = self.unsequenced_seen.get_mut(usize::try_from(index / 32).unwrap_or(usize::MAX)) else { + return false; + }; + if *word & bit != 0 { + return false; + } + *word |= bit; + true + } + + /// A reliable command on a data channel: acknowledged, ordered, then processed in sequence. Taken only while + /// connected. + fn reliable(&mut self, channel: u8, seq: u16, sent_time: Option, pending: Pending) -> Result<()> { + if self.state != EnetHostState::Connected || channel >= self.channel_count { + return Ok(()); + } + let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) }; + let next = ch.in_reliable.wrapping_add(1); + let distance = seq.wrapping_sub(next); + if distance >= 0x8000 { + // Already delivered: a retransmission. Acknowledge again, deliver nothing. + self.ack(channel, seq, sent_time); + return Ok(()); + } + if distance >= RELIABLE_WINDOW || ch.pending.len() >= MAX_PENDING_PER_CHANNEL { + return Ok(()); + } + ch.pending.entry(seq).or_insert(pending); + self.ack(channel, seq, sent_time); + self.deliver_in_order(channel); + Ok(()) + } + + fn deliver_in_order(&mut self, channel: u8) { + loop { + let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return }; + let next = ch.in_reliable.wrapping_add(1); + let Some(p) = ch.pending.remove(&next) else { return }; + ch.in_reliable = next; + match p { + Pending::Data(data) => self.events.push_back(EnetHostEvent::Received { channel, data }), + Pending::Fragment(f) => self.fragment(channel, f), + Pending::Skip => {} + } + } + } + + /// One checked fragment ([`check_fragment`] ran before it was queued). + fn fragment(&mut self, channel: u8, f: protocol::Fragment) { + let idx = match self.reassemblies.iter().position(|r| r.channel == channel && r.start == f.start_sequence) { + Some(i) => i, + None => { + if self.reassemblies.len() >= MAX_REASSEMBLIES { + self.reassemblies.remove(0); + } + let (Ok(count), Ok(total)) = (usize::try_from(f.fragment_count), usize::try_from(f.total_length)) + else { + return; + }; + self.reassemblies.push(Reassembly { + channel, + start: f.start_sequence, + count: f.fragment_count, + total: f.total_length, + got: vec![false; count], + received: 0, + data: vec![0; total], + }); + self.reassemblies.len() - 1 + } + }; + let Some(r) = self.reassemblies.get_mut(idx) else { return }; + if r.count != f.fragment_count || r.total != f.total_length { + self.reassemblies.remove(idx); + return; + } + let (Ok(number), Ok(offset)) = (usize::try_from(f.fragment_number), usize::try_from(f.fragment_offset)) else { + return; + }; + let Some(seen) = r.got.get_mut(number) else { return }; + if *seen { + return; + } + let Some(end) = offset.checked_add(f.data.len()) else { return }; + let Some(dest) = r.data.get_mut(offset..end) else { return }; + dest.copy_from_slice(&f.data); + *seen = true; + r.received += 1; + if r.received == r.count { + let done = self.reassemblies.remove(idx); + self.events.push_back(EnetHostEvent::Received { channel, data: done.data }); + } + } + + fn acknowledged(&mut self, now: Instant, channel: u8, seq: u16, sent_time: u16) { + let Some(pos) = + self.in_flight.iter().position(|f| f.command.channel_id == channel && f.command.reliable_sequence == seq) + else { + return; + }; + let done = self.in_flight.remove(pos); + self.resend.retain(|c| !(c.channel_id == channel && c.reliable_sequence == seq)); + let sample = ms16(now).wrapping_sub(sent_time); + if sample < 10_000 { + let sample = Duration::from_millis(u64::from(sample)); + match self.srtt { + None => { + self.srtt = Some(sample); + self.rttvar = sample / 2; + } + Some(s) => { + let diff = s.abs_diff(sample); + self.rttvar = (self.rttvar * 3 + diff) / 4; + self.srtt = Some((s * 7 + sample) / 8); + } + } + } + match (done.command.body, self.state) { + (CommandBody::VerifyConnect(_), EnetHostState::AcknowledgingConnect) => { + self.state = EnetHostState::Connected; + self.events.push_back(EnetHostEvent::Connected { data: self.connect_data }); + } + (CommandBody::Disconnect { .. }, EnetHostState::Disconnecting) => { + self.state = EnetHostState::Disconnected; + self.outgoing.clear(); + self.queued_packets = 0; + self.resend.clear(); + self.in_flight.clear(); + } + _ => {} + } + } + + /// Queues a packet. Packets larger than one command within the MTU are fragmented. /// /// # Errors - /// [`Error::State`] unless connected. + /// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the granted count, + /// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`], an unsequenced packet over one command, or a full queue + /// ([`MAX_SEND_QUEUE`] packets). pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> { - let _ = (now, channel, delivery, data); - Err(Error::Unimplemented) + let _ = now; + if self.state != EnetHostState::Connected { + return Err(Error::State { expected: "enet connected" }); + } + if channel >= self.channel_count { + return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() }); + } + crate::util::cap("enet packet", MAX_PACKET_BYTES, data.len())?; + crate::util::cap("enet send queue", MAX_SEND_QUEUE, self.queued_packets + 1)?; + // Header with sent time (4) plus the command header and its fields. + let single = self.mtu.saturating_sub(4 + 6); + let piece = self.mtu.saturating_sub(4 + 24).max(1); + if delivery == Delivery::Unsequenced && data.len() > single { + return Err(Error::TooLarge { what: "enet unsequenced packet", max: single, actual: data.len() }); + } + let Some(ch) = self.channels.get_mut(usize::from(channel)) else { + return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() }); + }; + let mut commands = Vec::new(); + match delivery { + Delivery::Reliable | Delivery::Unreliable if data.len() > single => { + let count = data.len().div_ceil(piece); + let start = ch.out_reliable.wrapping_add(1); + let total = u32::try_from(data.len()).unwrap_or(u32::MAX); + for (n, chunk) in data.chunks(piece).enumerate() { + ch.out_reliable = ch.out_reliable.wrapping_add(1); + let f = protocol::Fragment { + start_sequence: start, + fragment_count: u32::try_from(count).unwrap_or(u32::MAX), + fragment_number: u32::try_from(n).unwrap_or(u32::MAX), + total_length: total, + fragment_offset: u32::try_from(n * piece).unwrap_or(u32::MAX), + data: chunk.to_vec(), + }; + commands.push(Command { + acknowledge: true, + channel_id: channel, + reliable_sequence: ch.out_reliable, + body: CommandBody::SendFragment(f), + }); + } + } + Delivery::Reliable => { + ch.out_reliable = ch.out_reliable.wrapping_add(1); + commands.push(Command { + acknowledge: true, + channel_id: channel, + reliable_sequence: ch.out_reliable, + body: CommandBody::SendReliable(data.to_vec()), + }); + } + Delivery::Unreliable => { + ch.out_unreliable = ch.out_unreliable.wrapping_add(1); + commands.push(Command { + acknowledge: false, + channel_id: channel, + reliable_sequence: ch.out_reliable, + body: CommandBody::SendUnreliable { unreliable_sequence: ch.out_unreliable, data: data.to_vec() }, + }); + } + Delivery::Unsequenced => { + self.unsequenced_group = self.unsequenced_group.wrapping_add(1); + commands.push(Command { + acknowledge: false, + channel_id: channel, + reliable_sequence: 0, + body: CommandBody::SendUnsequenced { + unsequenced_group: self.unsequenced_group, + data: data.to_vec(), + }, + }); + } + } + let last = commands.len().saturating_sub(1); + for (i, command) in commands.into_iter().enumerate() { + self.outgoing.push_back(Outgoing { command, ends_packet: i == last }); + } + self.queued_packets += 1; + Ok(()) } - /// Starts a graceful disconnect. + /// Starts a graceful disconnect. Packets queued before it still go out first (as stock ENet's + /// `disconnect_later`), so a termination message sent just before arrives. /// /// # Errors /// [`Error::Closed`] when already disconnected or disconnecting. pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> { - let _ = (now, data); - Err(Error::Unimplemented) + let _ = now; + if matches!(self.state, EnetHostState::Disconnected | EnetHostState::Disconnecting) { + return Err(Error::Closed); + } + self.queue_connection_command(CommandBody::Disconnect { data }); + self.state = EnetHostState::Disconnecting; + Ok(()) } - /// The next datagram to send. + /// The next datagram to send, at most the MTU (acknowledgements, retransmissions, queued packets, pings). pub fn poll_transmit(&mut self, now: Instant) -> Option> { - let _ = now; - None + let budget = self.mtu; + let mut size = 4; + let mut commands: Vec = Vec::new(); + let fits = |size: usize, c: &Command, n: usize| { + n < protocol::MAX_COMMANDS_PER_DATAGRAM && size + protocol::command_size(c) <= budget + }; + while let Some(a) = self.acks.front() { + if !fits(size, a, commands.len()) { + break; + } + size += protocol::command_size(a); + if let Some(a) = self.acks.pop_front() { + commands.push(a); + } + } + if self.state != EnetHostState::Disconnected { + let rto = self.rto(); + while let Some(c) = self.resend.front() { + if !fits(size, c, commands.len()) { + break; + } + size += protocol::command_size(c); + if let Some(c) = self.resend.pop_front() { + if let Some(f) = self.in_flight.iter_mut().find(|f| { + f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence + }) { + f.sent_at = now; + } + commands.push(c); + } + } + while let Some(o) = self.outgoing.front() { + if !fits(size, &o.command, commands.len()) || self.in_flight.len() >= MAX_IN_FLIGHT { + break; + } + size += protocol::command_size(&o.command); + let Some(o) = self.outgoing.pop_front() else { break }; + if o.ends_packet { + self.queued_packets = self.queued_packets.saturating_sub(1); + } + if o.command.acknowledge { + self.in_flight.push(InFlight { command: o.command.clone(), first_sent: now, sent_at: now, rto }); + } + commands.push(o.command); + } + } + if commands.is_empty() { + return None; + } + // Stock ENet leaves the session bits out while the remote peer id is unknown (0xFFF). + let session_id = if self.client_peer_id < MAX_PEER_ID { self.out_session } else { 0 }; + let d = Datagram { peer_id: self.client_peer_id, session_id, sent_time: Some(ms16(now)), commands }; + protocol::encode_datagram(&d).ok() } /// The next event. pub fn poll_event(&mut self) -> Option { - None + self.events.pop_front() } - /// When [`Self::handle_timeout`] is due. + /// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever. #[must_use] pub fn poll_timeout(&self) -> Option { - None + if self.state == EnetHostState::Disconnected { + return None; + } + let flight = self + .in_flight + .iter() + .flat_map(|f| [f.sent_at.saturating_add(f.rto), f.first_sent.saturating_add(self.config.timeout)]) + .min(); + let ping = (self.state == EnetHostState::Connected && self.in_flight.is_empty()) + .then(|| self.last_receive.saturating_add(self.config.ping_interval)); + match (flight, ping) { + (Some(a), Some(b)) => Some(a.min(b)), + (a, b) => a.or(b), + } } - /// Advances timers. + /// Advances timers: retransmits, pings a client that has been quiet for the ping interval, or gives up with + /// [`EnetHostEvent::TimedOut`]. /// /// # Errors /// None today. pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { - let _ = now; - Err(Error::Unimplemented) + if self.state == EnetHostState::Disconnected { + return Ok(()); + } + let timeout = self.config.timeout; + if self.in_flight.iter().any(|f| f.first_sent.saturating_add(timeout) <= now) { + self.close(EnetHostEvent::TimedOut); + return Ok(()); + } + for f in &mut self.in_flight { + if f.sent_at.saturating_add(f.rto) <= now + && !self + .resend + .iter() + .any(|c| c.channel_id == f.command.channel_id && c.reliable_sequence == f.command.reliable_sequence) + { + f.rto = (f.rto * 2).min(MAX_RTO); + f.sent_at = now; + self.resend.push_back(f.command.clone()); + } + } + if self.state == EnetHostState::Connected + && self.in_flight.is_empty() + && self.outgoing.is_empty() + && self.last_receive.saturating_add(self.config.ping_interval) <= now + { + self.queue_connection_command(CommandBody::Ping); + } + Ok(()) } /// Connection state. #[must_use] pub const fn state(&self) -> EnetHostState { - EnetHostState::Disconnected + self.state } - /// The connect id of this connection. + /// The connect id of this connection (compare with [`parse_connect_request`] to spot a new connection). #[must_use] pub const fn connect_id(&self) -> u32 { - 0 + self.connect_id } /// Channels granted. #[must_use] pub const fn channel_count(&self) -> u8 { - 0 + self.channel_count } /// The MTU in use. #[must_use] pub const fn mtu(&self) -> usize { - 0 + self.mtu } /// Smoothed round-trip time, once measured. #[must_use] pub const fn round_trip_time(&self) -> Option { - None + self.srtt } /// The configuration. diff --git a/crates/domistream/src/enet/mod.rs b/crates/domistream/src/enet/mod.rs index f7b5f35..76a42e3 100644 --- a/crates/domistream/src/enet/mod.rs +++ b/crates/domistream/src/enet/mod.rs @@ -1,5 +1,5 @@ //! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1, -//! `docs/research/open-point-2.md`). +//! `docs/research/open-point-2.md`), and its accepting mirror for the Lumen host, [`host::EnetHostPeer`]. //! //! One peer, one connection. The caller owns the UDP socket: //! diff --git a/crates/domistream/tests/enet_host.rs b/crates/domistream/tests/enet_host.rs index f7d5b0a..72760f5 100644 --- a/crates/domistream/tests/enet_host.rs +++ b/crates/domistream/tests/enet_host.rs @@ -13,8 +13,8 @@ use domistream::enet::protocol::{ Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, NO_PEER_ID, encode_datagram, parse_datagram, }; use domistream::enet::{ - Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, - EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request, + Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, EnetState, + MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request, }; use domistream::{Error, Instant}; use proptest::prelude::*; @@ -445,7 +445,10 @@ fn data_before_the_verify_ack_is_not_taken() { h.handle_datagram(at(1), &to_host(0, Some(1), vec![data.clone()])).unwrap(); assert!(events(&mut h).is_empty()); assert!( - !transmitted(&mut h, at(1)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. })), + !transmitted(&mut h, at(1)) + .iter() + .flat_map(|d| &d.commands) + .any(|c| matches!(c.body, CommandBody::Acknowledge { .. })), "not acknowledged, so the client sends it again" ); let ack = cmd( @@ -474,6 +477,7 @@ fn lost_verify_is_retransmitted() { #[test] fn verify_never_acknowledged_times_out() { let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap(); + assert_eq!(transmitted(&mut h, at(0)).len(), 1, "the first verify"); let mut verifies = 0; let mut guard = 0; while h.state() != EnetHostState::Disconnected { @@ -506,7 +510,8 @@ fn reliable_both_ways_in_order() { } w.run_for(1_000); for ch in 0..2u8 { - let want: Vec> = (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect(); + let want: Vec> = + (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect(); assert_eq!(w.host.received(ch), want, "host, channel {ch}"); let want: Vec> = (0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| (1000 + i).to_le_bytes().to_vec()).collect(); @@ -525,7 +530,8 @@ fn large_packets_fragment_both_ways() { w.run_for(2_000); assert_eq!(w.host.received(1), vec![up]); assert_eq!(w.client.received(0), vec![down]); - let frags = w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count(); + let frags = + w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count(); assert!(frags > 40, "the host fragmented its 64 KiB packet ({frags})"); } @@ -555,8 +561,12 @@ fn unreliable_from_the_host() { #[test] fn duplicated_and_stale_datagrams_are_delivered_once() { let mut h = scripted_connected(); - let unseq = |group: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() }); - let unrel = |seq: u16, data: &[u8]| cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() }); + let unseq = |group: u16, data: &[u8]| { + cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() }) + }; + let unrel = |seq: u16, data: &[u8]| { + cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() }) + }; let feed = |h: &mut EnetHostPeer, c: Command| h.handle_datagram(at(10), &to_host(0, Some(10), vec![c])).unwrap(); feed(&mut h, unseq(1, b"a")); feed(&mut h, unseq(1, b"a")); @@ -612,7 +622,10 @@ fn reliable_from_the_client_reordered_and_duplicated() { } // Far future and channels outside the grant: never delivered. h.handle_datagram(at(13), &to_host(0, Some(13), vec![rel(40_000, b"evil")])).unwrap(); - let _ = h.handle_datagram(at(13), &to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))])); + let _ = h.handle_datagram( + at(13), + &to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))]), + ); assert!(events(&mut h).is_empty()); assert_eq!(h.state(), EnetHostState::Connected); } @@ -633,7 +646,10 @@ fn acknowledged_commands_need_the_sent_time() { h.handle_datagram(at(10), &d).unwrap(); assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"a".to_vec() }]); assert!( - !transmitted(&mut h, at(10)).iter().flat_map(|d| &d.commands).any(|c| matches!(c.body, CommandBody::Acknowledge { .. })) + !transmitted(&mut h, at(10)) + .iter() + .flat_map(|d| &d.commands) + .any(|c| matches!(c.body, CommandBody::Acknowledge { .. })) ); } @@ -744,15 +760,23 @@ fn the_host_pings_a_quiet_client() { let start = w.host.sent.len(); w.run_for(30_000); assert!(both_connected(&mut w)); - let pings = - w.host.sent[start..].iter().flat_map(|d| &d.commands).filter(|c| c.body == CommandBody::Ping && c.acknowledge).count(); + let pings = w.host.sent[start..] + .iter() + .flat_map(|d| &d.commands) + .filter(|c| c.body == CommandBody::Ping && c.acknowledge) + .count(); assert!(pings >= 30, "the host pings an idle client ({pings})"); // And when nothing comes back at all, its ping times out. let mut h = scripted_connected(); let t = h.poll_timeout().expect("a ping deadline"); assert!(t <= at(2 + host_config().ping_interval.as_millis() as u64)); h.handle_timeout(t).unwrap(); - assert!(transmitted(&mut h, t).iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF)); + assert!( + transmitted(&mut h, t) + .iter() + .flat_map(|d| &d.commands) + .any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF) + ); } #[test] @@ -760,7 +784,8 @@ fn vanished_client_times_out() { let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 10); let cut_at = w.now_ms; w.to_host.cut = true; - let limit = cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000; + let limit = + cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000; assert!(w.run_until(limit, |w| w.host.events.contains(&EnetHostEvent::TimedOut)), "no timeout by {limit} ms"); let earliest = cut_at + host_config().timeout.as_millis() as u64 - host_config().ping_interval.as_millis() as u64; assert!(w.now_ms >= earliest, "not before the timeout"); @@ -817,7 +842,11 @@ fn send_rules() { assert_err!(h.send(at(0), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before the verify is acknowledged"); let mut h = scripted_connected(); assert_err!(h.send(at(3), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2"); - assert_too_large!(h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]), MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1); + assert_too_large!( + h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]), + MAX_PACKET_BYTES, + MAX_PACKET_BYTES + 1 + ); assert!(matches!(h.send(at(3), 0, Delivery::Unsequenced, &[0; 1500]), Err(Error::TooLarge { .. }))); for i in 0..MAX_SEND_QUEUE { h.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}")); @@ -838,7 +867,11 @@ fn garbage_never_changes_state() { assert!(h.handle_datagram(at(5), bad).is_err(), "{bad:?}"); assert_eq!(h.state(), EnetHostState::Connected); } - assert_too_large!(h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1); + assert_too_large!( + h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]), + MAX_DATAGRAM_BYTES, + MAX_DATAGRAM_BYTES + 1 + ); // Another peer id: dropped without error. let other = encode_datagram(&Datagram { peer_id: HOST_PEER_ID + 1, @@ -875,7 +908,14 @@ fn fragments_with_lying_lengths() { MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1 ); - for f in [frag(0, 0, 10, 0, 10), frag(2, 2, 20, 0, 10), frag(2, 0, 20, 15, 10), frag(2, 0, 5, 0, 10), frag(u32::MAX, 0, 100, 0, 10), frag(2, 0, u32::MAX, 0, 10)] { + for f in [ + frag(0, 0, 10, 0, 10), + frag(2, 2, 20, 0, 10), + frag(2, 0, 20, 15, 10), + frag(2, 0, 5, 0, 10), + frag(u32::MAX, 0, 100, 0, 10), + frag(2, 0, u32::MAX, 0, 10), + ] { let mut h = scripted_connected(); let _ = h.handle_datagram(at(5), &to_host(0, Some(5), vec![f.clone()])); assert!(events(&mut h).is_empty(), "{f:?}");