//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1, //! `docs/research/open-point-2.md`). //! //! One peer, one connection. The caller owns the UDP socket: //! //! ```text //! loop { //! while let Some(d) = peer.poll_transmit(now) { socket.send(&d) } //! wait until a datagram arrives or peer.poll_timeout() //! peer.handle_datagram(now, &d) or peer.handle_timeout(now) //! while let Some(e) = peer.poll_event() { … } //! } //! ``` //! //! Reliable packets are delivered in order per channel; duplicates and stale sequence numbers are acknowledged but //! never delivered twice; sequence numbers too far ahead are dropped. Fragments are reassembled with every length //! checked against [`MAX_PACKET_BYTES`] before memory is reserved. use core::time::Duration; use std::collections::{BTreeMap, VecDeque}; use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATAGRAM_BYTES, MIN_MTU, NO_PEER_ID}; use crate::util::malformed; use crate::{Error, Instant, RandomSource, Result}; pub mod protocol; /// Maximum size of one reassembled packet, in bytes (control messages are small; this caps fragment memory). pub const MAX_PACKET_BYTES: usize = 64 * 1024; /// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more. pub const MAX_SEND_QUEUE: usize = 1024; /// Maximum number of reliable commands waiting for an acknowledgement. pub const MAX_IN_FLIGHT: usize = 256; /// Reliable sequence numbers accepted ahead of the next expected one (7 of ENet's 4096-wide windows). pub const RELIABLE_WINDOW: u16 = 0x7000; /// Out-of-order reliable commands kept per channel while waiting for a gap to fill. pub const MAX_PENDING_PER_CHANNEL: usize = 1024; /// Packets being reassembled at once; the oldest is dropped when another starts. pub const MAX_REASSEMBLIES: usize = 4; /// Acknowledgements kept for sending; beyond this the oldest are dropped (the host retransmits). pub const MAX_PENDING_ACKS: usize = 4096; /// Channel id of connection-level commands. const CONNECTION_CHANNEL: u8 = 0xFF; /// Our peer id towards the host (we are the only peer of this client). const LOCAL_PEER_ID: u16 = 0; /// Window size we offer (ENet's maximum, as for unlimited bandwidth). const WINDOW_SIZE: u32 = 65_536; /// Retransmission timeout before any round trip is measured (stock ENet's initial round-trip time). const INITIAL_RTO: Duration = Duration::from_millis(500); const MIN_RTO: Duration = Duration::from_millis(100); const MAX_RTO: Duration = Duration::from_secs(5); /// How a packet is delivered. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum Delivery { /// Retransmitted until acknowledged, in order. Reliable, /// In order, may be lost, late packets dropped. Unreliable, /// May be lost, any order. Unsequenced, } /// Settings of the connection the client offers. All values are UNKNOWN U9 for Sunshine; tests set them /// explicitly. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct EnetConfig { /// Channels to open. pub channel_count: u8, /// MTU to offer (576..=4096). pub mtu: u16, /// The connect command's user data word. pub connect_data: u32, /// Send a ping when nothing was sent for this long. pub ping_interval: Duration, /// Give up when nothing was acknowledged for this long. pub timeout: Duration, } /// Connection state. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EnetState { /// Connect sent, waiting for verify connect. Connecting, /// Connected. Connected, /// Disconnect sent, waiting for its acknowledgement. Disconnecting, /// Closed (by either side or by timeout). Disconnected, } /// What happened. #[derive(Clone, Debug, PartialEq, Eq)] pub enum EnetEvent { /// The host verified the connection. Connected, /// A packet arrived (reassembled, in order for reliable and unreliable delivery). Received { /// Channel. channel: u8, /// The packet. data: Vec, }, /// The host closed the connection. Disconnected { /// The host's disconnect data word. data: u32, }, /// The host stopped answering. TimedOut, } /// A reliable command in the sequence stream of a channel, as it will be processed in order. #[derive(Debug)] enum Pending { Data(Vec), Fragment(Fragment), /// A command that occupies its sequence number but carries nothing usable (a lying fragment). Skip, } #[derive(Debug, Default)] struct Channel { /// Last reliable sequence number we sent. out_reliable: u16, /// Last unreliable sequence number we sent. out_unreliable: u16, /// Last reliable sequence number delivered from the host. in_reliable: u16, /// Last unreliable sequence number delivered from the host. in_unreliable: Option, pending: BTreeMap, } #[derive(Debug)] struct Reassembly { channel: u8, start: u16, count: u32, total: u32, got: Vec, received: u32, data: Vec, } #[derive(Debug)] struct InFlight { command: Command, first_sent: Instant, sent_at: Instant, rto: Duration, } /// A command waiting to be sent; `ends_packet` marks the last command of a user packet (for the queue cap). #[derive(Debug)] struct Outgoing { command: Command, ends_packet: bool, } /// The ENet client peer. #[derive(Debug)] pub struct EnetClient { config: EnetConfig, state: EnetState, connect_id: u32, host_peer_id: u16, out_session: u8, in_session: u8, channel_count: u8, mtu: usize, connection_out_reliable: u16, unsequenced_group: u16, channels: Vec, outgoing: VecDeque, queued_packets: usize, resend: VecDeque, acks: VecDeque, in_flight: Vec, reassemblies: Vec, events: VecDeque, last_send: Instant, srtt: Option, rttvar: Duration, } fn ms16(t: Instant) -> u16 { ((t.as_micros() / 1000) & 0xFFFF) as u16 } impl EnetClient { /// Starts connecting: queues the connect datagram. The connect id comes from `rng`. /// /// # Errors /// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel). pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result { if config.mtu < MIN_MTU || usize::from(config.mtu) > MAX_DATAGRAM_BYTES || config.channel_count == 0 { return Err(malformed("enet config")); } let mut id = [0u8; 4]; rng.fill(&mut id); let connect_id = u32::from_le_bytes(id); let mut c = Self { config, state: EnetState::Connecting, connect_id, host_peer_id: NO_PEER_ID, out_session: 0, in_session: 0, channel_count: config.channel_count, mtu: usize::from(config.mtu), connection_out_reliable: 0, unsequenced_group: 0, channels: (0..config.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_send: now, srtt: None, rttvar: Duration::ZERO, }; let params = ConnectParams { outgoing_peer_id: LOCAL_PEER_ID, incoming_session_id: 0xFF, outgoing_session_id: 0xFF, mtu: u32::from(config.mtu), window_size: WINDOW_SIZE, channel_count: u32::from(config.channel_count), incoming_bandwidth: 0, outgoing_bandwidth: 0, packet_throttle_interval: 5000, packet_throttle_acceleration: 2, packet_throttle_deceleration: 2, connect_id, }; c.queue_connection_command(CommandBody::Connect { params, data: config.connect_data }); Ok(c) } 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), } } fn close(&mut self, event: EnetEvent) { self.state = EnetState::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 received datagram. Datagrams for another peer id or session are dropped without error. /// /// # Errors /// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] when a fragment announces more than /// [`MAX_PACKET_BYTES`]; [`Error::Closed`] after `Disconnected`. A malformed datagram never changes the /// connection state. pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { if self.state == EnetState::Disconnected { return Err(Error::Closed); } let d = protocol::parse_datagram(datagram)?; if d.peer_id != LOCAL_PEER_ID { return Ok(()); } if self.state != EnetState::Connecting && d.session_id != self.in_session { return Ok(()); } let sent_time = d.sent_time.unwrap_or(0); let mut first_error = None; for c in d.commands { if self.state == EnetState::Disconnected { break; } if let Err(e) = self.command(now, sent_time, c) { first_error.get_or_insert(e); } } first_error.map_or(Ok(()), Err) } fn ack(&mut self, channel: u8, seq: u16, sent_time: u16) { 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: u16, c: Command) -> Result<()> { let (channel, seq) = (c.channel_id, c.reliable_sequence); match c.body { CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => { self.acknowledged(now, channel, received_reliable_sequence, received_sent_time); Ok(()) } CommandBody::VerifyConnect(p) => { if c.acknowledge { self.ack(channel, seq, sent_time); } if self.state == EnetState::Connecting && p.connect_id == self.connect_id { self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID; self.out_session = p.incoming_session_id & 0x3; self.in_session = p.outgoing_session_id & 0x3; let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1); self.channel_count = self.channel_count.min(count); let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES); self.mtu = self.mtu.min(mtu).max(usize::from(MIN_MTU)); self.in_flight.retain(|f| !matches!(f.command.body, CommandBody::Connect { .. })); self.state = EnetState::Connected; self.events.push_back(EnetEvent::Connected); } Ok(()) } CommandBody::Disconnect { data } => { if c.acknowledge { self.ack(channel, seq, sent_time); } self.close(EnetEvent::Disconnected { data }); Ok(()) } CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => { if c.acknowledge { self.ack(channel, seq, sent_time); } Ok(()) } CommandBody::Connect { .. } => 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 self.state == EnetState::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(EnetEvent::Received { channel, data }); } } Ok(()) } CommandBody::SendUnsequenced { data, .. } => { if self.state == EnetState::Connected && channel < self.channel_count { self.events.push_back(EnetEvent::Received { channel, data }); } Ok(()) } CommandBody::SendUnreliableFragment(_) => Ok(()), } } /// A reliable command on a data channel: acknowledged, ordered, then processed in sequence. fn reliable(&mut self, channel: u8, seq: u16, sent_time: u16, pending: Pending) -> Result<()> { if self.state != EnetState::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) } fn deliver_in_order(&mut self, channel: u8) -> Result<()> { loop { let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) }; let next = ch.in_reliable.wrapping_add(1); let Some(p) = ch.pending.remove(&next) else { return Ok(()) }; ch.in_reliable = next; match p { Pending::Data(data) => self.events.push_back(EnetEvent::Received { channel, data }), Pending::Fragment(f) => self.fragment(channel, f), Pending::Skip => {} } } } fn fragment(&mut self, channel: u8, f: 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(dest) = r.data.get_mut(offset..offset + f.data.len()) 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(EnetEvent::Received { channel, data: done.data }); } } fn acknowledged(&mut self, now: Instant, channel: u8, seq: u16, sent_time: u16) { let before = self.in_flight.len(); let mut acked_disconnect = false; self.in_flight.retain(|f| { let hit = f.command.channel_id == channel && f.command.reliable_sequence == seq; if hit && matches!(f.command.body, CommandBody::Disconnect { .. }) { acked_disconnect = true; } !hit }); self.resend.retain(|c| !(c.channel_id == channel && c.reliable_sequence == seq)); if self.in_flight.len() < before { 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); } } } } if acked_disconnect && self.state == EnetState::Disconnecting { self.state = EnetState::Disconnected; } } /// Queues a packet. Packets larger than one command within the MTU are fragmented. /// /// # Errors /// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the negotiated count, /// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue ([`MAX_SEND_QUEUE`] packets). pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> { let _ = now; if self.state != EnetState::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); 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 = 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 => { if data.len() > single { return Err(Error::TooLarge { what: "enet unsequenced packet", max: single, actual: data.len() }); } 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. /// /// # Errors /// [`Error::Closed`] when already disconnected or disconnecting. pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> { let _ = now; if matches!(self.state, EnetState::Disconnected | EnetState::Disconnecting) { return Err(Error::Closed); } self.queue_connection_command(CommandBody::Disconnect { data }); self.state = EnetState::Disconnecting; Ok(()) } /// The next datagram to send, at most the MTU (acknowledgements, retransmissions, queued packets, pings). pub fn poll_transmit(&mut self, now: Instant) -> Option> { 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 != EnetState::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; } self.last_send = now; let peer_id = if self.state == EnetState::Connecting { NO_PEER_ID } else { self.host_peer_id }; let d = Datagram { peer_id, session_id: self.out_session, sent_time: Some(ms16(now)), commands }; protocol::encode_datagram(&d).ok() } /// The next event. pub fn poll_event(&mut self) -> Option { self.events.pop_front() } /// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever. #[must_use] pub fn poll_timeout(&self) -> Option { if self.state == EnetState::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(); // Also while packets are only queued: the caller then still gets a deadline, and the data goes out with the // next poll_transmit at the latest. let ping = (self.state == EnetState::Connected && self.in_flight.is_empty()) .then(|| self.last_send.saturating_add(self.config.ping_interval)); match (flight, ping) { (Some(a), Some(b)) => Some(a.min(b)), (a, b) => a.or(b), } } /// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`]. /// /// # Errors /// None today. pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { if self.state == EnetState::Disconnected { return Ok(()); } let timeout = self.config.timeout; if self.in_flight.iter().any(|f| f.first_sent.saturating_add(timeout) <= now) { self.close(EnetEvent::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 == EnetState::Connected && self.in_flight.is_empty() && self.outgoing.is_empty() && self.last_send.saturating_add(self.config.ping_interval) <= now { self.queue_connection_command(CommandBody::Ping); } Ok(()) } /// Connection state. #[must_use] pub const fn state(&self) -> EnetState { self.state } /// Smoothed round-trip time, once measured. #[must_use] pub fn round_trip_time(&self) -> Option { self.srtt } } /// The checks a fragment must pass before any memory is reserved for it. fn check_fragment(seq: u16, f: &Fragment) -> Result<()> { let total = usize::try_from(f.total_length).unwrap_or(usize::MAX); crate::util::cap("enet fragmented packet", MAX_PACKET_BYTES, total)?; let offset = usize::try_from(f.fragment_offset).unwrap_or(usize::MAX); let sound = f.fragment_count >= 1 && f.fragment_number < f.fragment_count && usize::try_from(f.fragment_count).is_ok_and(|c| c <= total.max(1)) && !f.data.is_empty() && offset.checked_add(f.data.len()).is_some_and(|end| end <= total) && u32::from(seq.wrapping_sub(f.start_sequence)) == f.fragment_number; if sound { Ok(()) } else { Err(malformed("enet fragment")) } }