//! The control stream (`docs/PROTOCOL.md` section 3): ENet underneath, AES-GCM frames, control messages. //! //! [`ControlStream`] ties them together: it connects the ENet peer, seals every [`ClientMessage`] with an //! increasing sequence number, opens every host frame (dropping replays and frames that fail the tag), and reports //! [`HostMessage`]s. use core::time::Duration; use std::collections::VecDeque; use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent}; use crate::{Instant, RandomSource, Result}; pub mod frame; pub mod message; pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame}; pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message}; /// Settings of one control stream. `Debug` never prints the key. #[derive(Clone, PartialEq, Eq)] pub struct ControlConfig { /// The ENet connection to offer. pub enet: EnetConfig, /// The session's `rikey`. pub rikey: [u8; 16], /// Send `PERIODIC_PING` this often (UNKNOWN U10). pub ping_interval: Duration, } impl core::fmt::Debug for ControlConfig { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("ControlConfig") .field("enet", &self.enet) .field("rikey", &"") .field("ping_interval", &self.ping_interval) .finish() } } /// What happened on the control stream. #[derive(Clone, Debug, PartialEq, Eq)] pub enum ControlEvent { /// ENet connected; the client sends `START_A`/`START_B` next. Connected, /// A message from the host. Message(HostMessage), /// A host frame failed its tag or came out of order and was dropped (counted, never fatal). Dropped, /// The host closed the stream. Disconnected, /// The host stopped answering. TimedOut, } /// One control stream. #[derive(Debug)] pub struct ControlStream { enet: EnetClient, cipher: ControlCipher, /// Next sequence number to seal with; `u32::MAX + 1` once the space is used up. next_sequence: u64, /// Highest host sequence number accepted so far. last_host_sequence: Option, events: VecDeque, } impl ControlStream { /// Starts connecting. /// /// # Errors /// As [`crate::enet::EnetClient::connect`]. pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result { Ok(Self { enet: EnetClient::connect(config.enet, now, rng)?, cipher: ControlCipher::new(config.rikey), next_sequence: 0, last_host_sequence: None, events: VecDeque::new(), }) } /// Moves ENet events into control events, opening every host frame. fn drain(&mut self) { while let Some(e) = self.enet.poll_event() { let event = match e { EnetEvent::Connected => ControlEvent::Connected, EnetEvent::Disconnected { .. } => ControlEvent::Disconnected, EnetEvent::TimedOut => ControlEvent::TimedOut, EnetEvent::Received { data, .. } => self.open(&data), }; self.events.push_back(event); } } /// Opens one host frame. A frame that fails, or whose number is not above the last accepted one, is dropped /// without touching the replay state; a frame that opens moves it forward even if its message is unknown. fn open(&mut self, frame: &[u8]) -> ControlEvent { let Ok((sequence, plain)) = self.cipher.open(Direction::HostToClient, frame) else { return ControlEvent::Dropped; }; if self.last_host_sequence.is_some_and(|last| sequence <= last) { return ControlEvent::Dropped; } self.last_host_sequence = Some(sequence); parse_host_message(&plain).map_or(ControlEvent::Dropped, ControlEvent::Message) } /// Feeds one datagram from the control port. /// /// # Errors /// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they /// become [`ControlEvent::Dropped`]. pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { let r = self.enet.handle_datagram(now, datagram); self.drain(); r } /// Seals and queues a message (reliable, channel 0 unless measurement says otherwise). /// /// # Errors /// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once /// the sequence space is used up (2^32 messages). pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> { let plain = message::encode_client_message(message)?; let sequence = u32::try_from(self.next_sequence).map_err(|_| crate::Error::Closed)?; let frame = self.cipher.seal(sequence, Direction::ClientToHost, &plain)?; self.enet.send(now, 0, Delivery::Reliable, &frame)?; self.next_sequence += 1; Ok(()) } /// The next datagram to send. pub fn poll_transmit(&mut self, now: Instant) -> Option> { self.enet.poll_transmit(now) } /// The next event. pub fn poll_event(&mut self) -> Option { self.events.pop_front() } /// When [`Self::handle_timeout`] is due. #[must_use] pub fn poll_timeout(&self) -> Option { self.enet.poll_timeout() } /// Advances timers (ENet). `PERIODIC_PING` is not sent while its body is UNKNOWN (U10); ENet's own pings keep /// the connection alive. /// /// # Errors /// As [`crate::enet::EnetClient::handle_timeout`]. pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { let r = self.enet.handle_timeout(now); self.drain(); r } /// Closes the stream gracefully. /// /// # Errors /// [`crate::Error::Closed`] when already closed. pub fn close(&mut self, now: Instant) -> Result<()> { self.enet.disconnect(now, 0) } }