//! 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 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: //! 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::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 { /// Our peer id, which the client puts in the header of every datagram it sends us (0..=0xFFE). pub peer_id: u16, /// Most channels we grant (the client's request is capped to this; at least 1). 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 received for this long. pub ping_interval: Duration, /// Give up when a reliable command stays unacknowledged this long. pub timeout: Duration, } /// State of the host-side peer. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum EnetHostState { /// Verify connect sent, waiting for the client to acknowledge it. AcknowledgingConnect, /// Connected. Connected, /// Our disconnect sent, waiting for its acknowledgement. Disconnecting, /// Closed (by either side or by timeout). Disconnected, } /// What happened. #[derive(Clone, Debug, PartialEq, Eq)] pub enum EnetHostEvent { /// The client acknowledged our verify connect. Connected { /// The connect command's user data word. data: u32, }, /// A packet arrived (reassembled, in order for reliable and unreliable delivery). Received { /// Channel. channel: u8, /// The packet. data: Vec, }, /// The client closed the connection. Disconnected { /// The client's disconnect data word. data: u32, }, /// The client stopped answering. TimedOut, } /// A client's CONNECT, as [`parse_connect_request`] finds it. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct ConnectRequest { /// The connect parameters. 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. As in stock ENet, only a CONNECT at the /// start of such a datagram counts. /// /// # Errors /// 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 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. The datagram is consumed; do not feed it to /// [`Self::handle_datagram`] again. /// /// # Errors /// [`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 { 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) } 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 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<()> { 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(()) } 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::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; 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. 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; 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, 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 != 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 { 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 == 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: 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<()> { 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 { self.state } /// 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 { self.connect_id } /// Channels granted. #[must_use] pub const fn channel_count(&self) -> u8 { self.channel_count } /// The MTU in use. #[must_use] pub const fn mtu(&self) -> usize { self.mtu } /// Smoothed round-trip time, once measured. #[must_use] pub const fn round_trip_time(&self) -> Option { self.srtt } /// The configuration. #[must_use] pub const fn config(&self) -> &EnetHostConfig { &self.config } }