From fc5b0b116c381e6999620b56065a778043f206f1 Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 11:46:37 +0100 Subject: [PATCH] [domistream] ENet API: sans-I/O 1.3 datagram codec and client peer --- crates/domistream/src/enet/mod.rs | 175 ++++++++++++++++++++ crates/domistream/src/enet/protocol.rs | 216 +++++++++++++++++++++++++ crates/domistream/src/lib.rs | 1 + 3 files changed, 392 insertions(+) create mode 100644 crates/domistream/src/enet/mod.rs create mode 100644 crates/domistream/src/enet/protocol.rs diff --git a/crates/domistream/src/enet/mod.rs b/crates/domistream/src/enet/mod.rs new file mode 100644 index 0000000..f4a0a2d --- /dev/null +++ b/crates/domistream/src/enet/mod.rs @@ -0,0 +1,175 @@ +//! 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() { … } +//! } +//! ``` + +use core::time::Duration; + +use crate::{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; + +/// 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, +} + +/// The ENet client peer. +#[derive(Debug)] +pub struct EnetClient { + state: EnetState, +} + +impl EnetClient { + /// Starts connecting: queues the connect datagram. The connect id comes from `rng`. + /// + /// # Errors + /// [`crate::Error::Malformed`] for a config outside ENet's limits. Phase A: always + /// [`crate::Error::Unimplemented`]. + pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result { + let _ = (config, now, rng); + Err(crate::Error::Unimplemented) + } + + /// Feeds one received datagram. Datagrams for another peer id or session are dropped without error. + /// + /// # Errors + /// Parser errors as [`protocol::parse_datagram`]; [`crate::Error::TooLarge`] when a reassembly would exceed + /// [`MAX_PACKET_BYTES`]; [`crate::Error::Closed`] after `Disconnected`. A malformed datagram never changes the + /// connection state. Phase A: always [`crate::Error::Unimplemented`]. + pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + let _ = (now, datagram); + Err(crate::Error::Unimplemented) + } + + /// Queues a packet. Packets larger than the MTU are fragmented. + /// + /// # Errors + /// [`crate::Error::State`] unless connected, [`crate::Error::UnexpectedValue`] for a channel outside the + /// negotiated count, [`crate::Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue. Phase A: always + /// [`crate::Error::Unimplemented`]. + pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> { + let _ = (now, channel, delivery, data); + Err(crate::Error::Unimplemented) + } + + /// Starts a graceful disconnect. + /// + /// # Errors + /// [`crate::Error::Closed`] when already disconnected. Phase A: always [`crate::Error::Unimplemented`]. + pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> { + let _ = (now, data); + Err(crate::Error::Unimplemented) + } + + /// The next datagram to send, at most [`protocol::MAX_DATAGRAM_BYTES`] (acknowledgements, retransmissions, + /// queued packets, pings). + pub fn poll_transmit(&mut self, now: Instant) -> Option> { + let _ = now; + None + } + + /// The next event. + pub fn poll_event(&mut self) -> Option { + None + } + + /// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever. + #[must_use] + pub fn poll_timeout(&self) -> Option { + None + } + + /// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`]. + /// + /// # Errors + /// Phase A: always [`crate::Error::Unimplemented`]. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + let _ = now; + Err(crate::Error::Unimplemented) + } + + /// 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 { + None + } +} diff --git a/crates/domistream/src/enet/protocol.rs b/crates/domistream/src/enet/protocol.rs new file mode 100644 index 0000000..3e993d8 --- /dev/null +++ b/crates/domistream/src/enet/protocol.rs @@ -0,0 +1,216 @@ +//! The ENet 1.3 datagram codec (`docs/PROTOCOL.md` 3.1). Multi-byte fields are big-endian. + +/// Maximum datagram size accepted or produced (ENet's maximum MTU). +pub const MAX_DATAGRAM_BYTES: usize = 4096; +/// Minimum MTU ENet allows. +pub const MIN_MTU: u16 = 576; +/// Maximum number of commands in one datagram. +pub const MAX_COMMANDS_PER_DATAGRAM: usize = 32; +/// Maximum channel count ENet allows. +pub const MAX_CHANNEL_COUNT: u8 = 255; +/// Maximum peer id ENet allows. +pub const MAX_PEER_ID: u16 = 0x0FFF; +/// Peer id meaning "no peer yet" (used in the connect datagram). +pub const NO_PEER_ID: u16 = MAX_PEER_ID; +/// Minimum ENet window size. +pub const MIN_WINDOW_SIZE: u32 = 4096; +/// Maximum ENet window size. +pub const MAX_WINDOW_SIZE: u32 = 65536; + +/// Header flag: the datagram carries `sent_time`. +pub const HEADER_FLAG_SENT_TIME: u16 = 1 << 15; +/// Header flag: the datagram is compressed (refused by this client). +pub const HEADER_FLAG_COMPRESSED: u16 = 1 << 14; +/// Command flag: the receiver must acknowledge. +pub const COMMAND_FLAG_ACKNOWLEDGE: u8 = 1 << 7; +/// Command flag: unsequenced delivery. +pub const COMMAND_FLAG_UNSEQUENCED: u8 = 1 << 6; + +/// ENet command numbers (low 4 bits of the command byte). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum CommandKind { + /// Acknowledge a reliable command. + Acknowledge = 1, + /// Open a connection. + Connect = 2, + /// Answer to connect. + VerifyConnect = 3, + /// Close. + Disconnect = 4, + /// Keep-alive. + Ping = 5, + /// Reliable data. + SendReliable = 6, + /// Unreliable sequenced data. + SendUnreliable = 7, + /// Reliable fragment. + SendFragment = 8, + /// Unsequenced data. + SendUnsequenced = 9, + /// Bandwidth limits. + BandwidthLimit = 10, + /// Throttle parameters. + ThrottleConfigure = 11, + /// Unreliable fragment. + SendUnreliableFragment = 12, +} + +/// Parameters of connect and verify connect. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ConnectParams { + /// Sender's peer id for the receiver to use. + pub outgoing_peer_id: u16, + /// Session id for incoming traffic. + pub incoming_session_id: u8, + /// Session id for outgoing traffic. + pub outgoing_session_id: u8, + /// MTU. + pub mtu: u32, + /// Reliable window size. + pub window_size: u32, + /// Channel count. + pub channel_count: u32, + /// Incoming bandwidth, bytes/s, 0 = unlimited. + pub incoming_bandwidth: u32, + /// Outgoing bandwidth, bytes/s, 0 = unlimited. + pub outgoing_bandwidth: u32, + /// Throttle interval, ms. + pub packet_throttle_interval: u32, + /// Throttle acceleration. + pub packet_throttle_acceleration: u32, + /// Throttle deceleration. + pub packet_throttle_deceleration: u32, + /// Random id that ties verify connect to connect. + pub connect_id: u32, +} + +/// Fragment fields shared by reliable and unreliable fragments. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fragment { + /// Sequence number of the first fragment. + pub start_sequence: u16, + /// Number of fragments. + pub fragment_count: u32, + /// This fragment's number. + pub fragment_number: u32, + /// Length of the whole packet. + pub total_length: u32, + /// This fragment's offset in the whole packet. + pub fragment_offset: u32, + /// This fragment's bytes. + pub data: Vec, +} + +/// One command with its 4-byte header fields. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Command { + /// The receiver must acknowledge (flag bit 7). + pub acknowledge: bool, + /// Channel id (0xFF for connection-level commands). + pub channel_id: u8, + /// Reliable sequence number. + pub reliable_sequence: u16, + /// The command body. + pub body: CommandBody, +} + +/// Command bodies. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CommandBody { + /// Acknowledges `received_reliable_sequence` sent at `received_sent_time`. + Acknowledge { + /// Acknowledged sequence number. + received_reliable_sequence: u16, + /// The acknowledged datagram's `sent_time`. + received_sent_time: u16, + }, + /// Connect, with its user data word. + Connect { + /// Connection parameters. + params: ConnectParams, + /// User data (UNKNOWN U9: what a GameStream host expects here). + data: u32, + }, + /// Verify connect. + VerifyConnect(ConnectParams), + /// Disconnect with a user data word. + Disconnect { + /// User data. + data: u32, + }, + /// Ping. + Ping, + /// Reliable data. + SendReliable(Vec), + /// Unreliable sequenced data. + SendUnreliable { + /// Unreliable sequence number. + unreliable_sequence: u16, + /// The data. + data: Vec, + }, + /// Reliable fragment. + SendFragment(Fragment), + /// Unsequenced data. + SendUnsequenced { + /// Unsequenced group. + unsequenced_group: u16, + /// The data. + data: Vec, + }, + /// Bandwidth limits, bytes/s. + BandwidthLimit { + /// Incoming. + incoming: u32, + /// Outgoing. + outgoing: u32, + }, + /// Throttle parameters. + ThrottleConfigure { + /// Interval, ms. + interval: u32, + /// Acceleration. + acceleration: u32, + /// Deceleration. + deceleration: u32, + }, + /// Unreliable fragment. + SendUnreliableFragment(Fragment), +} + +/// One datagram: protocol header plus commands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Datagram { + /// Receiver's peer id (12 bits). + pub peer_id: u16, + /// Session id (2 bits). + pub session_id: u8, + /// `sent_time` (low 16 bits of the sender's ms clock), if present. + pub sent_time: Option, + /// The commands, at most [`MAX_COMMANDS_PER_DATAGRAM`]. + pub commands: Vec, +} + +/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and +/// compressed datagrams refused. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`], +/// [`crate::Error::Truncated`] for a cut command, [`crate::Error::UnexpectedValue`] for an unknown command or the +/// compressed flag, [`crate::Error::Malformed`] for a data length that does not match. Phase A: always +/// [`crate::Error::Unimplemented`]. +pub fn parse_datagram(datagram: &[u8]) -> crate::Result { + let _ = datagram; + Err(crate::Error::Unimplemented) +} + +/// Serializes one datagram. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`]. Phase A: always +/// [`crate::Error::Unimplemented`]. +pub fn encode_datagram(datagram: &Datagram) -> crate::Result> { + let _ = datagram; + Err(crate::Error::Unimplemented) +} diff --git a/crates/domistream/src/lib.rs b/crates/domistream/src/lib.rs index cb77df7..e17e060 100644 --- a/crates/domistream/src/lib.rs +++ b/crates/domistream/src/lib.rs @@ -35,6 +35,7 @@ #![forbid(unsafe_code)] #![deny(missing_docs)] +pub mod enet; pub mod entropy; pub mod error; pub mod http;