//! 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. The unsequenced flag and the two unused command bits are not kept. /// /// # Errors /// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`], /// [`crate::Error::Truncated`] for a cut header, command or data, [`crate::Error::UnexpectedValue`] for an unknown /// command or the compressed flag. pub fn parse_datagram(datagram: &[u8]) -> crate::Result { use crate::util::{byte, cap, slice, u16_be, u32_be}; const W: &str = "enet datagram"; cap(W, MAX_DATAGRAM_BYTES, datagram.len())?; let raw = u16_be(W, datagram, 0)?; if raw & HEADER_FLAG_COMPRESSED != 0 { return Err(crate::Error::UnexpectedValue { what: "enet compressed datagram", value: raw.into() }); } let mut pos = 2; let sent_time = if raw & HEADER_FLAG_SENT_TIME != 0 { pos = 4; Some(u16_be(W, datagram, 2)?) } else { None }; let mut commands = Vec::new(); while pos < datagram.len() { cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len() + 1)?; let command = byte(W, datagram, pos)?; let channel_id = byte(W, datagram, pos + 1)?; let reliable_sequence = u16_be(W, datagram, pos + 2)?; let kind = command & 0x0F; let at = pos + 4; let u32_at = |off: usize| u32_be(W, datagram, at + off); let data_of = |len_at: usize, data_at: usize| -> crate::Result<(Vec, usize)> { let len = usize::from(u16_be(W, datagram, at + len_at)?); Ok((slice(W, datagram, at + data_at, len)?.to_vec(), at + data_at + len)) }; let params = || -> crate::Result { Ok(ConnectParams { outgoing_peer_id: u16_be(W, datagram, at)?, incoming_session_id: byte(W, datagram, at + 2)?, outgoing_session_id: byte(W, datagram, at + 3)?, mtu: u32_at(4)?, window_size: u32_at(8)?, channel_count: u32_at(12)?, incoming_bandwidth: u32_at(16)?, outgoing_bandwidth: u32_at(20)?, packet_throttle_interval: u32_at(24)?, packet_throttle_acceleration: u32_at(28)?, packet_throttle_deceleration: u32_at(32)?, connect_id: u32_at(36)?, }) }; let fragment = || -> crate::Result<(Fragment, usize)> { let start_sequence = u16_be(W, datagram, at)?; let fragment_count = u32_at(4)?; let fragment_number = u32_at(8)?; let total_length = u32_at(12)?; let fragment_offset = u32_at(16)?; let (data, end) = data_of(2, 20)?; Ok((Fragment { start_sequence, fragment_count, fragment_number, total_length, fragment_offset, data }, end)) }; let (body, end) = match kind { 1 => ( CommandBody::Acknowledge { received_reliable_sequence: u16_be(W, datagram, at)?, received_sent_time: u16_be(W, datagram, at + 2)?, }, at + 4, ), 2 => { let p = params()?; (CommandBody::Connect { params: p, data: u32_at(40)? }, at + 44) } 3 => (CommandBody::VerifyConnect(params()?), at + 40), 4 => (CommandBody::Disconnect { data: u32_at(0)? }, at + 4), 5 => (CommandBody::Ping, at), 6 => { let (data, end) = data_of(0, 2)?; (CommandBody::SendReliable(data), end) } 7 => { let unreliable_sequence = u16_be(W, datagram, at)?; let (data, end) = data_of(2, 4)?; (CommandBody::SendUnreliable { unreliable_sequence, data }, end) } 8 => { let (f, end) = fragment()?; (CommandBody::SendFragment(f), end) } 9 => { let unsequenced_group = u16_be(W, datagram, at)?; let (data, end) = data_of(2, 4)?; (CommandBody::SendUnsequenced { unsequenced_group, data }, end) } 10 => (CommandBody::BandwidthLimit { incoming: u32_at(0)?, outgoing: u32_at(4)? }, at + 8), 11 => ( CommandBody::ThrottleConfigure { interval: u32_at(0)?, acceleration: u32_at(4)?, deceleration: u32_at(8)?, }, at + 12, ), 12 => { let (f, end) = fragment()?; (CommandBody::SendUnreliableFragment(f), end) } other => return Err(crate::Error::UnexpectedValue { what: "enet command", value: other.into() }), }; commands.push(Command { acknowledge: command & COMMAND_FLAG_ACKNOWLEDGE != 0, channel_id, reliable_sequence, body, }); pos = end; } Ok(Datagram { peer_id: raw & MAX_PEER_ID, session_id: ((raw >> 12) & 0x3) as u8, sent_time, commands }) } /// The command number of a body. #[must_use] pub const fn kind_of(body: &CommandBody) -> CommandKind { match body { CommandBody::Acknowledge { .. } => CommandKind::Acknowledge, CommandBody::Connect { .. } => CommandKind::Connect, CommandBody::VerifyConnect(_) => CommandKind::VerifyConnect, CommandBody::Disconnect { .. } => CommandKind::Disconnect, CommandBody::Ping => CommandKind::Ping, CommandBody::SendReliable(_) => CommandKind::SendReliable, CommandBody::SendUnreliable { .. } => CommandKind::SendUnreliable, CommandBody::SendFragment(_) => CommandKind::SendFragment, CommandBody::SendUnsequenced { .. } => CommandKind::SendUnsequenced, CommandBody::BandwidthLimit { .. } => CommandKind::BandwidthLimit, CommandBody::ThrottleConfigure { .. } => CommandKind::ThrottleConfigure, CommandBody::SendUnreliableFragment(_) => CommandKind::SendUnreliableFragment, } } /// Bytes one command takes on the wire. #[must_use] pub fn command_size(c: &Command) -> usize { 4 + match &c.body { CommandBody::Acknowledge { .. } | CommandBody::Disconnect { .. } => 4, CommandBody::Connect { .. } => 44, CommandBody::VerifyConnect(_) => 40, CommandBody::Ping => 0, CommandBody::SendReliable(d) => 2 + d.len(), CommandBody::SendUnreliable { data, .. } | CommandBody::SendUnsequenced { data, .. } => 4 + data.len(), CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => 20 + f.data.len(), CommandBody::BandwidthLimit { .. } => 8, CommandBody::ThrottleConfigure { .. } => 12, } } fn put_params(out: &mut Vec, p: &ConnectParams) { out.extend_from_slice(&p.outgoing_peer_id.to_be_bytes()); out.push(p.incoming_session_id); out.push(p.outgoing_session_id); for v in [ p.mtu, p.window_size, p.channel_count, p.incoming_bandwidth, p.outgoing_bandwidth, p.packet_throttle_interval, p.packet_throttle_acceleration, p.packet_throttle_deceleration, p.connect_id, ] { out.extend_from_slice(&v.to_be_bytes()); } } fn data_len(data: &[u8]) -> crate::Result { u16::try_from(data.len()).map_err(|_| crate::Error::TooLarge { what: "enet command data", max: usize::from(u16::MAX), actual: data.len(), }) } /// Serializes one datagram. /// /// # Errors /// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`], /// [`crate::Error::Malformed`] for a peer id over [`MAX_PEER_ID`] or a session id over 3. pub fn encode_datagram(datagram: &Datagram) -> crate::Result> { use crate::util::cap; cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, datagram.commands.len())?; if datagram.peer_id > MAX_PEER_ID || datagram.session_id > 3 { return Err(crate::util::malformed("enet peer or session id")); } let header_len = if datagram.sent_time.is_some() { 4 } else { 2 }; let size = datagram.commands.iter().map(command_size).fold(header_len, usize::saturating_add); cap("enet datagram", MAX_DATAGRAM_BYTES, size)?; let mut out = Vec::with_capacity(size); let mut header = datagram.peer_id | (u16::from(datagram.session_id) << 12); if datagram.sent_time.is_some() { header |= HEADER_FLAG_SENT_TIME; } out.extend_from_slice(&header.to_be_bytes()); if let Some(t) = datagram.sent_time { out.extend_from_slice(&t.to_be_bytes()); } for c in &datagram.commands { let mut command = kind_of(&c.body) as u8; if c.acknowledge { command |= COMMAND_FLAG_ACKNOWLEDGE; } if matches!(c.body, CommandBody::SendUnsequenced { .. }) { command |= COMMAND_FLAG_UNSEQUENCED; } out.push(command); out.push(c.channel_id); out.extend_from_slice(&c.reliable_sequence.to_be_bytes()); match &c.body { CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => { out.extend_from_slice(&received_reliable_sequence.to_be_bytes()); out.extend_from_slice(&received_sent_time.to_be_bytes()); } CommandBody::Connect { params, data } => { put_params(&mut out, params); out.extend_from_slice(&data.to_be_bytes()); } CommandBody::VerifyConnect(params) => put_params(&mut out, params), CommandBody::Disconnect { data } => out.extend_from_slice(&data.to_be_bytes()), CommandBody::Ping => {} CommandBody::SendReliable(data) => { out.extend_from_slice(&data_len(data)?.to_be_bytes()); out.extend_from_slice(data); } CommandBody::SendUnreliable { unreliable_sequence: s, data } | CommandBody::SendUnsequenced { unsequenced_group: s, data } => { out.extend_from_slice(&s.to_be_bytes()); out.extend_from_slice(&data_len(data)?.to_be_bytes()); out.extend_from_slice(data); } CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => { out.extend_from_slice(&f.start_sequence.to_be_bytes()); out.extend_from_slice(&data_len(&f.data)?.to_be_bytes()); for v in [f.fragment_count, f.fragment_number, f.total_length, f.fragment_offset] { out.extend_from_slice(&v.to_be_bytes()); } out.extend_from_slice(&f.data); } CommandBody::BandwidthLimit { incoming, outgoing } => { out.extend_from_slice(&incoming.to_be_bytes()); out.extend_from_slice(&outgoing.to_be_bytes()); } CommandBody::ThrottleConfigure { interval, acceleration, deceleration } => { for v in [interval, acceleration, deceleration] { out.extend_from_slice(&v.to_be_bytes()); } } } } Ok(out) }