Compare commits

..

4 Commits

22 changed files with 6 additions and 5531 deletions
+1 -27
View File
@@ -11,17 +11,15 @@ use core::fmt;
use std::collections::{HashMap, VecDeque};
use cbc::cipher::block_padding::Pkcs7;
use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
use crate::fec::ReedSolomon;
use crate::util::malformed;
use crate::{Error, Instant, Result, SessionKeys};
pub mod packet;
pub mod packetizer;
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity};
/// Data packets per FEC block.
pub const DATA_SHARDS: usize = 4;
@@ -80,30 +78,6 @@ impl AudioCipher {
}
}
impl AudioCipher {
/// Encrypts one payload (host side), the exact mirror of [`Self::decrypt`]: AES-128-CBC with the IV of
/// [`Self::iv`] and PKCS#7 padding, so the ciphertext is the plaintext length rounded up to the next multiple of
/// 16, always 1 to 16 bytes longer (`docs/PROTOCOL.md` 6.3).
///
/// # Errors
/// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`] (checked before anything is allocated),
/// [`Error::Crypto`] if the cipher refuses (never for a buffer sized as here).
pub fn encrypt(&self, sequence: u16, plaintext: &[u8]) -> Result<Vec<u8>> {
crate::util::cap("audio plaintext", packet::MAX_AUDIO_PACKET_BYTES, plaintext.len())?;
let iv = self.iv(sequence)?;
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
for (dst, src) in buf.iter_mut().zip(plaintext) {
*dst = *src;
}
let len = cbc::Encryptor::<aes::Aes128>::new((&*self.key).into(), &iv.into())
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
.map_err(|_| Error::Crypto)?
.len();
buf.truncate(len);
Ok(buf)
}
}
impl fmt::Debug for AudioCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AudioCipher(<redacted>)")
-124
View File
@@ -1,124 +0,0 @@
//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram, the mirror of
//! [`super::AudioDepacketizer`] and tested against it.
//!
//! Each datagram is the 12-byte RTP header (byte 0 `0x80`, payload type 97, sequence BE, timestamp BE in
//! milliseconds, SSRC 0) followed by the Opus packet, AES-128-CBC encrypted with [`AudioCipher::encrypt`] when a
//! cipher is set (6.3: IV from `rikeyid + sequence`, PKCS#7). Sequence numbers count up by one per packet and the
//! timestamp by the packet duration, both wrapping.
//!
//! **No parity packets** (6.4): the audio parity matrix is UNKNOWN U16, and the only value seen has GPL provenance,
//! so [`AudioParity`] has a single variant, [`AudioParity::None`], and clients conceal lost packets. The enum is
//! `#[non_exhaustive]` and [`AudioPacketizer::packetize`] returns a list of datagrams, so a measured matrix can be
//! added later as a new variant that appends the 2 parity datagrams after every block's 4th data packet without
//! changing callers. Blocks start at sequence numbers that are multiples of 4 (6.4), so `first_sequence` must be one
//! already (the client's receiver also counts from the first packet's block start).
use super::AudioCipher;
use super::packet::{AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES};
use crate::Result;
use crate::rtp::RTP_HEADER_LEN;
use crate::util::{cap, malformed, need};
/// Byte 0 of every audio RTP header: version 2, no padding, extension or CSRC (`docs/PROTOCOL.md` 6.2).
pub const AUDIO_RTP_BYTE0: u8 = 0x80;
/// Largest Opus packet sent in the clear: the receiver's datagram cap minus the RTP header.
pub const MAX_OPUS_PLAIN_BYTES: usize = MAX_AUDIO_PACKET_BYTES - RTP_HEADER_LEN;
/// Largest Opus packet sent encrypted: PKCS#7 always adds 1 to 16 bytes, and the ciphertext must fit the cap.
pub const MAX_OPUS_ENCRYPTED_BYTES: usize = MAX_OPUS_PLAIN_BYTES / 16 * 16 - 1;
/// Which audio parity packets are sent (`docs/PROTOCOL.md` 6.4).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AudioParity {
/// None: the parity matrix is UNKNOWN U16 (GPL-provenance, unsettled), so clients conceal lost packets.
#[default]
None,
}
/// Settings of the audio sender.
#[derive(Clone, Debug)]
pub struct AudioPacketizerConfig {
/// Encrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17).
pub cipher: Option<AudioCipher>,
/// Packet duration in milliseconds (`x-nv-aqos.packetDuration`): the timestamp step.
pub packet_duration_ms: u8,
/// Parity packets.
pub parity: AudioParity,
/// RTP sequence number of the first packet: a multiple of 4, the start of an FEC block (6.4).
pub first_sequence: u16,
/// RTP timestamp (milliseconds) of the first packet.
pub first_timestamp_ms: u32,
}
/// The audio sender of one stream.
#[derive(Debug)]
pub struct AudioPacketizer {
config: AudioPacketizerConfig,
next_sequence: u16,
next_timestamp_ms: u32,
}
impl AudioPacketizer {
/// A sender for one stream.
///
/// # Errors
/// [`crate::Error::Malformed`] for a zero packet duration or a `first_sequence` that is not a multiple of 4: FEC
/// blocks start at multiples of 4 (6.4), and the client's receiver counts from the start of the first packet's
/// block, so a stream starting mid-block would show it 1 to 3 phantom losses.
pub fn new(config: AudioPacketizerConfig) -> Result<Self> {
if config.packet_duration_ms == 0 {
return Err(malformed("audio packet duration"));
}
if !config.first_sequence.is_multiple_of(4) {
return Err(malformed("audio first sequence is not a block start (a multiple of 4)"));
}
Ok(Self { next_sequence: config.first_sequence, next_timestamp_ms: config.first_timestamp_ms, config })
}
/// The largest Opus packet accepted: [`MAX_OPUS_ENCRYPTED_BYTES`] with a cipher, else [`MAX_OPUS_PLAIN_BYTES`].
#[must_use]
pub const fn max_opus_len(&self) -> usize {
if self.config.cipher.is_some() { MAX_OPUS_ENCRYPTED_BYTES } else { MAX_OPUS_PLAIN_BYTES }
}
/// Packetizes one Opus packet into the datagrams to send now, in order: today exactly one (no parity, see
/// [`AudioParity`]). On error nothing changes (sequence number, timestamp).
///
/// # Errors
/// [`crate::Error::Truncated`] for an empty packet (Opus packets carry at least their TOC byte, RFC 6716),
/// [`crate::Error::TooLarge`] over [`Self::max_opus_len`] (checked before anything is allocated),
/// [`crate::Error::Crypto`] if the cipher refuses.
pub fn packetize(&mut self, opus: &[u8]) -> Result<Vec<Vec<u8>>> {
const W: &str = "opus packet";
need(W, 1, opus.len())?;
cap(W, self.max_opus_len(), opus.len())?;
let (sequence, timestamp) = (self.next_sequence, self.next_timestamp_ms);
let mut packet = Vec::with_capacity(RTP_HEADER_LEN + opus.len() + 16);
packet.extend_from_slice(&[AUDIO_RTP_BYTE0, AUDIO_PAYLOAD_TYPE]);
packet.extend_from_slice(&sequence.to_be_bytes());
packet.extend_from_slice(&timestamp.to_be_bytes());
packet.extend_from_slice(&0u32.to_be_bytes()); // SSRC 0
match &self.config.cipher {
Some(c) => packet.extend_from_slice(&c.encrypt(sequence, opus)?),
None => packet.extend_from_slice(opus),
}
let datagrams = match self.config.parity {
AudioParity::None => vec![packet],
};
self.next_sequence = sequence.wrapping_add(1);
self.next_timestamp_ms = timestamp.wrapping_add(u32::from(self.config.packet_duration_ms));
Ok(datagrams)
}
/// The RTP sequence number of the next packet.
#[must_use]
pub const fn next_sequence(&self) -> u16 {
self.next_sequence
}
/// The RTP timestamp (milliseconds) of the next packet.
#[must_use]
pub const fn next_timestamp_ms(&self) -> u32 {
self.next_timestamp_ms
}
}
-433
View File
@@ -1,433 +0,0 @@
//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3), over one [`EnetHostPeer`].
//!
//! [`ControlHost`] mirrors the client's [`super::ControlStream`]: it accepts the client's ENet connection, opens
//! every client frame (nonce direction `'C'`, PROTOCOL.md 3.2), drops frames that fail the tag, replay old sequence
//! numbers or hold a malformed message (PROTOCOL.md 3.3: inside the encrypted frame such a message is skipped, never
//! fatal), and reports [`ClientControlMessage`]s. It seals every host message with `'H'` and an increasing sequence
//! number from 0, reliable on channel 0 (PROTOCOL.md 3.1). It also keeps the stop deadline of PROTOCOL.md 3.3:
//! without a `PERIODIC_PING` for the configured time it reports [`ControlHostEvent::PingTimedOut`], and the caller
//! ends the session (termination, then [`ControlHost::close`]).
//!
//! Only control V2 (every message inside the encrypted frame) is spoken: a bare message outside the frame is
//! dropped like any frame that does not open (UNKNOWN U10 asks whether a client ever sends one).
use core::time::Duration;
use std::collections::VecDeque;
use super::frame::{ControlCipher, Direction};
use super::message::{HdrMetadata, HostMessage, MAX_MESSAGE_BYTES, MESSAGE_HEADER_LEN, MessageType, parse_message};
use crate::enet::{Delivery, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState};
use crate::input::InputEvent;
use crate::{Error, Instant, Result};
/// Stop a session after this long without a `PERIODIC_PING` (PROTOCOL.md 3.3, Moonshine's default).
pub const DEFAULT_STOP_TIMEOUT: Duration = Duration::from_secs(60);
/// The extended termination code for a graceful end (PROTOCOL.md 3.3).
pub const TERMINATION_GRACEFUL: u32 = 0x8003_0023;
/// The channel every host message goes on, reliable (PROTOCOL.md 3.1).
const HOST_CHANNEL: u8 = 0;
/// Settings of the host side of one control stream. `Debug` never prints the key.
#[derive(Clone, PartialEq, Eq)]
pub struct ControlHostConfig {
/// The ENet host-side peer.
pub enet: EnetHostConfig,
/// The session's `rikey`.
pub rikey: [u8; 16],
/// End the session after this long without a `PERIODIC_PING` ([`DEFAULT_STOP_TIMEOUT`] is Moonshine's);
/// `None` never ends it for that.
pub stop_timeout: Option<Duration>,
}
impl core::fmt::Debug for ControlHostConfig {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("ControlHostConfig")
.field("enet", &self.enet)
.field("rikey", &"<redacted>")
.field("stop_timeout", &self.stop_timeout)
.finish()
}
}
/// A message from the client, as the host reads it (PROTOCOL.md 3.3).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ClientControlMessage {
/// `START_B`: start video and audio. Any body is ignored (PROTOCOL.md 3.3: Moonshine reads none).
StartB,
/// `PERIODIC_PING`: the client is still there. Any body is ignored.
PeriodicPing,
/// `INPUT_DATA` with a known layout (PROTOCOL.md 4).
Input(InputEvent),
/// `INPUT_DATA` that [`crate::input::parse_input`] refused (a layout still UNKNOWN U21, an unknown input type,
/// or a bad size field). Not fatal: the stream goes on.
InputRejected {
/// Body length.
body_len: usize,
/// Why.
error: Error,
},
/// `IDR_FRAME`: send a key frame. Any body is ignored.
IdrRequest,
/// `INVALIDATE_REF_FRAMES`: stop referencing frames `first..=last`. A field the body is too short for reads
/// as 0 (PROTOCOL.md 3.3).
InvalidateRefFrames {
/// First lost frame.
first: u32,
/// Last lost frame.
last: u32,
},
/// `LOSS_STATS`, body kept as it came (layout UNKNOWN U10).
LossStats(Vec<u8>),
/// `FRAME_STATS`, body kept as it came (layout UNKNOWN U10).
FrameStats(Vec<u8>),
/// Any other type, `START_A` among them (PROTOCOL.md 3.3: skipped inside the encrypted frame).
Unknown {
/// Type code.
message_type: u16,
/// Body length.
body_len: usize,
},
}
/// Interprets a decrypted message from the client (PROTOCOL.md 3.3). Only the split is strict; bodies of the
/// messages a host reads nothing from are ignored, input goes through [`crate::input::parse_input`].
///
/// # Errors
/// As [`parse_message`]: [`Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`Error::Truncated`] under the 4-byte
/// header, [`Error::Malformed`] when the length field does not match.
pub fn parse_client_message(message: &[u8]) -> Result<ClientControlMessage> {
let raw = parse_message(message)?;
let b = raw.body;
// `first` at body 0..4, `last` at body 8..12, little-endian; missing means 0 (PROTOCOL.md 3.3).
let field = |at: usize| crate::util::u32_le("invalidate ref frames", b, at).unwrap_or(0);
Ok(match raw.message_type {
t if t == MessageType::StartB as u16 => ClientControlMessage::StartB,
t if t == MessageType::PeriodicPing as u16 => ClientControlMessage::PeriodicPing,
t if t == MessageType::IdrFrame as u16 => ClientControlMessage::IdrRequest,
t if t == MessageType::InvalidateRefFrames as u16 => {
ClientControlMessage::InvalidateRefFrames { first: field(0), last: field(8) }
}
t if t == MessageType::LossStats as u16 => ClientControlMessage::LossStats(b.to_vec()),
t if t == MessageType::FrameStats as u16 => ClientControlMessage::FrameStats(b.to_vec()),
t if t == MessageType::InputData as u16 => match crate::input::parse_input(message) {
Ok(e) => ClientControlMessage::Input(e),
Err(error) => ClientControlMessage::InputRejected { body_len: b.len(), error },
},
other => ClientControlMessage::Unknown { message_type: other, body_len: b.len() },
})
}
/// Type, length, body.
fn framed(message_type: MessageType, body: &[u8]) -> Result<Vec<u8>> {
crate::util::cap("host message", MAX_MESSAGE_BYTES, MESSAGE_HEADER_LEN.saturating_add(body.len()))?;
let len = u16::try_from(body.len()).map_err(|_| crate::util::malformed("host message length"))?;
let mut m = Vec::with_capacity(MESSAGE_HEADER_LEN + body.len());
m.extend_from_slice(&(message_type as u16).to_le_bytes());
m.extend_from_slice(&len.to_le_bytes());
m.extend_from_slice(body);
Ok(m)
}
/// Serializes a message to the client (type, length, body), ready for [`ControlCipher::seal`]: the inverse of
/// [`super::parse_host_message`]. Bodies are little-endian (UNKNOWN U23), the extended termination code big-endian
/// (PROTOCOL.md 3.3).
///
/// # Errors
/// [`Error::Unsupported`] for a message whose layout is not known well enough to send: the plain `TERMINATION`
/// (body UNKNOWN U10), `HDR_MODE` (layout of GPL provenance, `[M*]`) and [`HostMessage::Other`].
pub fn encode_host_message(message: &HostMessage) -> Result<Vec<u8>> {
match *message {
HostMessage::Rumble { controller, low_frequency, high_frequency } => {
let mut b = vec![0u8; 4];
for v in [controller, low_frequency, high_frequency] {
b.extend_from_slice(&v.to_le_bytes());
}
framed(MessageType::RumbleData, &b)
}
HostMessage::RumbleTriggers { controller, left, right } => {
let b: Vec<u8> = [controller, left, right].iter().flat_map(|v| v.to_le_bytes()).collect();
framed(MessageType::RumbleTriggers, &b)
}
HostMessage::MotionEvent { controller, rate_hz, kind } => {
let mut b: Vec<u8> = [controller, rate_hz].iter().flat_map(|v| v.to_le_bytes()).collect();
b.push(match kind {
super::message::MotionKind::Accelerometer => 1,
super::message::MotionKind::Gyroscope => 2,
});
framed(MessageType::MotionEvent, &b)
}
HostMessage::RgbLed { controller, r, g, b } => {
let mut body = controller.to_le_bytes().to_vec();
body.extend_from_slice(&[r, g, b]);
framed(MessageType::RgbLed, &body)
}
HostMessage::Termination { error_code: Some(code) } => {
framed(MessageType::TerminationExtended, &code.to_be_bytes())
}
HostMessage::Termination { error_code: None } => {
Err(Error::Unsupported { what: "the plain TERMINATION message (body UNKNOWN U10)" })
}
// HDR_MODE: Moonshine's layout for it cites Sunshine, so it is GPL provenance ([M*], CLEAN_ROOM.md) and
// stays unused until our own measurement settles it. Lumen streams SDR until then.
HostMessage::HdrMode { .. } => {
Err(Error::Unsupported { what: "HDR_MODE (its layout is GPL provenance [M*], not measured yet)" })
}
HostMessage::Other { .. } => Err(Error::Unsupported { what: "a host message without a known layout" }),
}
}
/// The stop deadline of PROTOCOL.md 3.3: each `PERIODIC_PING` pushes it out to `timeout` after the ping.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct StopDeadline {
timeout: Duration,
deadline: Instant,
}
impl StopDeadline {
/// A deadline `timeout` after `now`.
#[must_use]
pub fn new(now: Instant, timeout: Duration) -> Self {
Self { timeout, deadline: now.saturating_add(timeout) }
}
/// A ping arrived at `now`. The deadline never moves back.
pub fn on_ping(&mut self, now: Instant) {
self.deadline = self.deadline.max(now.saturating_add(self.timeout));
}
/// When the session ends without another ping.
#[must_use]
pub const fn deadline(&self) -> Instant {
self.deadline
}
/// Whether the deadline has passed at `now`.
#[must_use]
pub fn expired(&self, now: Instant) -> bool {
now >= self.deadline
}
}
/// What happened on the host side of the control stream.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ControlHostEvent {
/// The client's ENet connection is up.
Connected,
/// A message from the client.
Message(ClientControlMessage),
/// A client frame failed its tag, came out of order or held a malformed message, and was skipped (counted,
/// never fatal).
Dropped,
/// No `PERIODIC_PING` within the stop timeout: the session should end. Reported once; a later ping starts the
/// clock again.
PingTimedOut,
/// The client closed the stream.
Disconnected,
/// The client stopped answering (ENet).
TimedOut,
}
/// The host side of one control stream.
#[derive(Debug)]
pub struct ControlHost {
enet: EnetHostPeer,
cipher: ControlCipher,
/// Next sequence number to seal with; `u32::MAX + 1` once the space is used up.
next_sequence: u64,
/// Highest client sequence number accepted so far.
last_client_sequence: Option<u32>,
stop_timeout: Option<Duration>,
stop: Option<StopDeadline>,
events: VecDeque<ControlHostEvent>,
}
impl ControlHost {
/// Accepts a client's ENet CONNECT datagram (see [`crate::enet::host`] for the caller's demultiplexing).
///
/// # Errors
/// As [`EnetHostPeer::accept`].
pub fn accept(config: ControlHostConfig, now: Instant, datagram: &[u8]) -> Result<Self> {
Ok(Self {
enet: EnetHostPeer::accept(config.enet, now, datagram)?,
cipher: ControlCipher::new(config.rikey),
next_sequence: 0,
last_client_sequence: None,
stop_timeout: config.stop_timeout,
stop: None,
events: VecDeque::new(),
})
}
/// Moves ENet events into control events, opening every client frame.
fn drain(&mut self, now: Instant) {
while let Some(e) = self.enet.poll_event() {
let event = match e {
EnetHostEvent::Connected { .. } => {
self.stop = self.stop_timeout.map(|t| StopDeadline::new(now, t));
ControlHostEvent::Connected
}
EnetHostEvent::Disconnected { .. } => {
self.stop = None;
ControlHostEvent::Disconnected
}
EnetHostEvent::TimedOut => {
self.stop = None;
ControlHostEvent::TimedOut
}
EnetHostEvent::Received { data, .. } => self.open(now, &data),
};
self.events.push_back(event);
}
}
/// Opens one client 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 malformed.
fn open(&mut self, now: Instant, frame: &[u8]) -> ControlHostEvent {
let Ok((sequence, plain)) = self.cipher.open(Direction::ClientToHost, frame) else {
return ControlHostEvent::Dropped;
};
if self.last_client_sequence.is_some_and(|last| sequence <= last) {
return ControlHostEvent::Dropped;
}
self.last_client_sequence = Some(sequence);
match parse_client_message(&plain) {
Ok(m) => {
if m == ClientControlMessage::PeriodicPing
&& let Some(timeout) = self.stop_timeout
&& self.enet.state() == EnetHostState::Connected
{
match self.stop.as_mut() {
Some(s) => s.on_ping(now),
None => self.stop = Some(StopDeadline::new(now, timeout)),
}
}
ControlHostEvent::Message(m)
}
Err(_) => ControlHostEvent::Dropped,
}
}
/// Feeds one datagram from the client.
///
/// # Errors
/// As [`EnetHostPeer::handle_datagram`]. Bad frames inside a good datagram are not errors; they become
/// [`ControlHostEvent::Dropped`].
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let r = self.enet.handle_datagram(now, datagram);
self.drain(now);
r
}
/// Seals and queues a message to the client (reliable, channel 0).
///
/// # Errors
/// As [`encode_host_message`] and [`EnetHostPeer::send`]; [`Error::Closed`] once the sequence space is used up
/// (2^32 messages).
pub fn send(&mut self, now: Instant, message: &HostMessage) -> Result<()> {
let plain = encode_host_message(message)?;
let sequence = u32::try_from(self.next_sequence).map_err(|_| Error::Closed)?;
let frame = self.cipher.seal(sequence, Direction::HostToClient, &plain)?;
self.enet.send(now, HOST_CHANNEL, Delivery::Reliable, &frame)?;
self.next_sequence += 1;
Ok(())
}
/// Rumbles a controller.
///
/// # Errors
/// As [`Self::send`].
pub fn send_rumble(
&mut self,
now: Instant,
controller: u16,
low_frequency: u16,
high_frequency: u16,
) -> Result<()> {
self.send(now, &HostMessage::Rumble { controller, low_frequency, high_frequency })
}
/// Rumbles a controller's triggers.
///
/// # Errors
/// As [`Self::send`].
pub fn send_rumble_triggers(&mut self, now: Instant, controller: u16, left: u16, right: u16) -> Result<()> {
self.send(now, &HostMessage::RumbleTriggers { controller, left, right })
}
/// Ends the session with an extended termination code ([`TERMINATION_GRACEFUL`] for a normal end). Follow it
/// with [`Self::close`]; the message goes out before the disconnect.
///
/// # Errors
/// As [`Self::send`].
pub fn send_termination(&mut self, now: Instant, error_code: u32) -> Result<()> {
self.send(now, &HostMessage::Termination { error_code: Some(error_code) })
}
/// HDR mode: a typed placeholder that is **not implemented**. The only known layout (PROTOCOL.md 3.3) has GPL
/// provenance (`[M*]`), so nothing is sent until our own measurement settles it.
///
/// # Errors
/// Always [`Error::Unsupported`]; nothing is queued.
pub fn send_hdr_mode(&mut self, now: Instant, enabled: bool, metadata: Option<HdrMetadata>) -> Result<()> {
self.send(now, &HostMessage::HdrMode { enabled, metadata })
}
/// The next datagram to send.
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.enet.poll_transmit(now)
}
/// The next event.
pub fn poll_event(&mut self) -> Option<ControlHostEvent> {
self.events.pop_front()
}
/// When [`Self::handle_timeout`] is due (ENet timers or the stop deadline).
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
let stop = self.stop_deadline();
match (self.enet.poll_timeout(), stop) {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
}
}
/// Advances timers: ENet's, then the stop deadline ([`ControlHostEvent::PingTimedOut`]).
///
/// # Errors
/// As [`EnetHostPeer::handle_timeout`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let r = self.enet.handle_timeout(now);
self.drain(now);
if self.stop.is_some_and(|s| s.expired(now)) {
self.stop = None;
self.events.push_back(ControlHostEvent::PingTimedOut);
}
r
}
/// Closes the stream gracefully (ENet disconnect; messages queued before it go out first).
///
/// # Errors
/// [`Error::Closed`] when already closed.
pub fn close(&mut self, now: Instant) -> Result<()> {
self.stop = None;
self.enet.disconnect(now, 0)
}
/// The ENet peer underneath (state, connect id, round-trip time).
#[must_use]
pub const fn enet(&self) -> &EnetHostPeer {
&self.enet
}
/// When the session ends without another `PERIODIC_PING`, while that clock runs (from the connection on, until
/// it is reported or the stream closes).
#[must_use]
pub fn stop_deadline(&self) -> Option<Instant> {
if self.enet.state() == EnetHostState::Disconnected {
return None;
}
self.stop.map(|s| s.deadline())
}
}
-5
View File
@@ -11,14 +11,9 @@ use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent};
use crate::{Instant, RandomSource, Result};
pub mod frame;
pub mod host;
pub mod message;
pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame};
pub use host::{
ClientControlMessage, ControlHost, ControlHostConfig, ControlHostEvent, StopDeadline, encode_host_message,
parse_client_message,
};
pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message};
/// Settings of one control stream. `Debug` never prints the key.
-793
View File
@@ -1,793 +0,0 @@
//! 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<u8>,
},
/// 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<ConnectRequest> {
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<Channel>,
outgoing: VecDeque<Outgoing>,
queued_packets: usize,
resend: VecDeque<Command>,
acks: VecDeque<Command>,
in_flight: Vec<InFlight>,
reassemblies: Vec<Reassembly>,
events: VecDeque<EnetHostEvent>,
last_receive: Instant,
srtt: Option<Duration>,
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<Self> {
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<u16>) {
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<u16>, 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<u16>, 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<Vec<u8>> {
let budget = self.mtu;
let mut size = 4;
let mut commands: Vec<Command> = 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<EnetHostEvent> {
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<Instant> {
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<Duration> {
self.srtt
}
/// The configuration.
#[must_use]
pub const fn config(&self) -> &EnetHostConfig {
&self.config
}
}
+1 -4
View File
@@ -1,5 +1,5 @@
//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1,
//! `docs/research/open-point-2.md`), and its accepting mirror for the Lumen host, [`host::EnetHostPeer`].
//! `docs/research/open-point-2.md`).
//!
//! One peer, one connection. The caller owns the UDP socket:
//!
@@ -24,11 +24,8 @@ use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATA
use crate::util::malformed;
use crate::{Error, Instant, RandomSource, Result};
pub mod host;
pub mod protocol;
pub use host::{ConnectRequest, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, parse_connect_request};
/// 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.
+4 -4
View File
@@ -21,13 +21,13 @@
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream, client and host side (section 3.1) |
//! | [`control`] | AES-GCM framing and control messages, client and host side (sections 3.2, 3.3) |
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) |
//! | [`control`] | AES-GCM framing and control messages (sections 3.2, 3.3) |
//! | [`input`] | input and gamepad packets (section 4) |
//! | [`rtp`] | the RTP header shared by video and audio |
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer |
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
//!
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
-34
View File
@@ -20,10 +20,8 @@ use crate::util::{array, cap, malformed, need};
use crate::{Error, Instant, Result};
pub mod packet;
pub mod packetizer;
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
pub use packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
@@ -71,38 +69,6 @@ impl VideoCipher {
}
}
impl VideoCipher {
/// Seals one plaintext packet (host side), the exact mirror of [`Self::decrypt`]: IV = `counter` as 8 bytes LE,
/// 3 zero bytes, `'V'`; output `IV ‖ frame number u32 LE ‖ tag ‖ ciphertext` (`docs/PROTOCOL.md` 7, UNKNOWN
/// U19 against Sunshine). The caller must never reuse a `counter` under one key: the packetizer counts from 0
/// per session, and the `'V'` byte keeps video nonces apart from control's (`'C'`).
///
/// # Errors
/// [`Error::TooLarge`] when the sealed packet would exceed [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Crypto`]
/// if the cipher refuses (never for packets within the cap).
pub fn encrypt(&self, counter: u64, frame_number: u32, packet: &[u8]) -> Result<Vec<u8>> {
let sealed = packet.len().saturating_add(ENCRYPTION_PREFIX_LEN);
cap("sealed video packet", packet::MAX_VIDEO_PACKET_BYTES, sealed)?;
let mut iv = [0u8; 12];
for (dst, src) in iv.iter_mut().zip(counter.to_le_bytes()) {
*dst = src;
}
if let Some(last) = iv.last_mut() {
*last = b'V';
}
let mut body = packet.to_vec();
let tag = Aes128Gcm::new((&*self.key).into())
.encrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into())
.map_err(|_| Error::Crypto)?;
let mut out = Vec::with_capacity(sealed);
out.extend_from_slice(&iv);
out.extend_from_slice(&frame_number.to_le_bytes());
out.extend_from_slice(tag.as_slice());
out.extend_from_slice(&body);
Ok(out)
}
}
impl fmt::Debug for VideoCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("VideoCipher(<redacted>)")
-391
View File
@@ -1,391 +0,0 @@
//! The video send path, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7): one encoded access unit → the RTP + NV-header
//! datagrams of one frame, in FEC blocks with Reed-Solomon parity, optionally AES-128-GCM sealed.
//!
//! The mirror of [`super::VideoDepacketizer`], and tested against it:
//!
//! 1. Frame data = the 8-byte frame header ([`write_frame_header`], the structured reading of 5.2; UNKNOWN U13 is
//! open, so the writer is one small function) followed by the Annex-B bitstream, cut into `packetSize - 16`-byte
//! data shards, the last one zero-padded (5.2).
//! 2. The data shards are split into at most 4 FEC blocks ([`plan_fec_blocks`]); each block gets
//! `m = ceil(k × percentage / 100)` parity shards, with the percentage raised for the client's minimum parity
//! count and lowered only when a block would exceed 255 shards (5.3).
//! 3. Each data shard becomes a whole packet (RTP header, 4 reserved bytes, NV header, payload). Parity is computed
//! over these whole packets with [`crate::fec::ReedSolomon`] (the Cauchy matrix of 5.3), and only then are the
//! parity packets' RTP and NV header fields written over their first 32 bytes, exactly as 5.3 says.
//! 4. Sequence numbers run on across frames (one per datagram, data and parity alike, wrapping at 16 bits); the
//! stream packet index is the sequence number shifted left by 8 (5.2).
//! 5. With video encryption, every finished packet is sealed with [`VideoCipher::encrypt`] (FEC before
//! encryption, 7), with a per-session nonce counter that starts at 0.
//!
//! The input is trusted (our own encoder), but nothing here panics: sizes are capped with typed errors before
//! anything is allocated, and a refused frame changes no state.
//!
//! Choices of our own, not from a source (to be compared with a real host's capture): the block split (fewest
//! blocks that carry the requested parity; every block but the last has the same `k`), the percentage arithmetic
//! for the minimum parity count, and what happens to a frame too big for its parity (the parity is lowered, counted
//! in [`VideoPacketizerStats::fec_reduced_blocks`]).
use super::VideoCipher;
use super::packet::{
FRAME_HEADER_LEN, FrameType, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, NV_HEADER_LEN, PAYLOAD_OFFSET, VIDEO_RTP_LEN,
VideoFlags,
};
use super::{ENCRYPTION_PREFIX_LEN, MAX_FRAME_BYTES};
use crate::fec::{MAX_SHARDS, ReedSolomon};
use crate::util::{cap, malformed};
use crate::{Error, Result};
/// The NV header's multi-FEC flags byte (`docs/PROTOCOL.md` 5.2, UNKNOWN U15: sent as documented, meaning unknown).
pub const MULTI_FEC_FLAGS: u8 = 0x10;
/// Byte 0 of the structured frame header (`docs/PROTOCOL.md` 5.2).
pub const FRAME_HEADER_TYPE: u8 = 0x01;
/// Byte 0 of every video RTP header: version 2, extension bit set (`docs/PROTOCOL.md` 5.2).
pub const VIDEO_RTP_BYTE0: u8 = 0x90;
/// Most data shards one frame can carry: [`MAX_FEC_BLOCKS`] blocks of at most [`MAX_SHARDS`] shards.
pub const MAX_DATA_SHARDS_PER_FRAME: usize = MAX_FEC_BLOCKS * MAX_SHARDS;
/// Settings of the video sender, from the client's ANNOUNCE (`docs/PROTOCOL.md` 2.4).
#[derive(Clone, Debug)]
pub struct VideoPacketizerConfig {
/// Negotiated `packetSize`: NV header + payload. Each datagram is `packetSize + 16` bytes (+ 32 when sealed).
pub packet_size: u16,
/// Requested FEC percentage.
pub fec_percentage: u8,
/// Minimum parity packets per block (`x-nv-vqos[0].fec.minRequiredFecPackets`).
pub min_required_fec_packets: u8,
/// Seal every datagram with this cipher when video encryption was negotiated.
pub cipher: Option<VideoCipher>,
/// RTP sequence number of the first datagram.
pub first_sequence: u16,
}
/// One encoded access unit from the encoder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct EncodedFrame<'a> {
/// Frame index (NV header bytes 20-23).
pub frame_index: u32,
/// Frame type written into the frame header.
pub frame_type: FrameType,
/// RTP timestamp shared by every datagram of the frame (UNKNOWN U29: clock rate, probably 90 kHz).
pub rtp_timestamp: u32,
/// Host processing latency, frame header bytes 1-2 (unit UNKNOWN, U13).
pub processing_latency: u16,
/// The Annex-B bitstream, start codes included.
pub bitstream: &'a [u8],
}
/// The FEC geometry of one block.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FecBlock {
/// Data shards `k`.
pub data_shards: u16,
/// Parity shards `m = ceil(k × percentage / 100)`.
pub parity_shards: u16,
/// The percentage written into the block's FEC info (the receiver derives `m` from it).
pub fec_percentage: u8,
/// The requested parity (percentage and minimum count) did not fit in 255 shards and was lowered.
pub reduced: bool,
}
/// Counters.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct VideoPacketizerStats {
/// Frames packetized.
pub frames: u64,
/// Datagrams produced (data + parity).
pub packets: u64,
/// Parity datagrams among them.
pub parity_packets: u64,
/// Blocks whose parity was lowered to fit 255 shards.
pub fec_reduced_blocks: u64,
}
/// The frame type byte of the structured frame header (`docs/PROTOCOL.md` 5.2).
const fn frame_type_byte(t: FrameType) -> u8 {
match t {
FrameType::Predicted => 1,
FrameType::Key => 2,
FrameType::Recovery => 5,
FrameType::Other(v) => v,
}
}
/// Writes the 8-byte frame header in its structured form (`docs/PROTOCOL.md` 5.2): type `0x01`, processing latency
/// u16 LE, frame type, payload bytes in the last data shard u32 LE. UNKNOWN U13 (Wolf shows a constant instead) is
/// open; this is the form our client reads, and the only place to change if the capture says otherwise.
#[must_use]
pub fn write_frame_header(
frame_type: FrameType,
processing_latency: u16,
last_payload_len: u32,
) -> [u8; FRAME_HEADER_LEN] {
let [l0, l1] = processing_latency.to_le_bytes();
let [a, b, c, d] = last_payload_len.to_le_bytes();
[FRAME_HEADER_TYPE, l0, l1, frame_type_byte(frame_type), a, b, c, d]
}
/// Parity of a block of `k` at percentage `p`: `ceil(k × p / 100)` (the receiver's formula, 5.3).
const fn parity_at(k: usize, p: usize) -> usize {
(k * p).div_ceil(100)
}
/// The parity the client asks for a block of `k`: the percentage's, but at least the minimum count.
fn target(k: usize, pct: u8, min: u8) -> usize {
let m = parity_at(k, usize::from(pct));
if m < usize::from(min) { usize::from(min) } else { m }
}
/// The least percentage, at or above `pct`, whose parity reaches the target, if it is an 8-bit value and keeps the
/// block within [`MAX_SHARDS`].
fn wished_percentage(k: usize, pct: u8, min: u8) -> Option<usize> {
if k == 0 {
return None;
}
let t = target(k, pct, min);
let p = if parity_at(k, usize::from(pct)) >= t {
usize::from(pct)
} else {
// The least p with k·p > 100·(t − 1), i.e. ceil(k·p / 100) ≥ t.
100 * (t - 1) / k + 1
};
(p <= usize::from(u8::MAX) && k + parity_at(k, p) <= MAX_SHARDS).then_some(p)
}
/// The FEC geometry of one block of `k` data shards.
fn block(k: usize, pct: u8, min: u8) -> Result<FecBlock> {
let (p, reduced) = match wished_percentage(k, pct, min) {
Some(p) => (p, false),
// The most parity that fits: the largest p with k + ceil(k·p / 100) ≤ 255.
None => ((100 * MAX_SHARDS.saturating_sub(k) / k.max(1)).min(usize::from(u8::MAX)), true),
};
let to_u16 = |v: usize| u16::try_from(v).map_err(|_| malformed("video fec block"));
Ok(FecBlock {
data_shards: to_u16(k)?,
parity_shards: to_u16(parity_at(k, p))?,
fec_percentage: u8::try_from(p).map_err(|_| malformed("video fec percentage"))?,
reduced,
})
}
/// Splits a frame's `data_shards` into FEC blocks (`docs/PROTOCOL.md` 5.3): the fewest blocks (at most
/// [`MAX_FEC_BLOCKS`]) whose blocks can each carry the requested parity, where every block but the last carries
/// `ceil(data_shards / blocks)` data shards. Each block's percentage is the least one, at or above `fec_percentage`,
/// that gives `max(ceil(k × fec_percentage / 100), min_parity)` parity shards; when that cannot fit in
/// [`MAX_SHARDS`] shards (or an 8-bit percentage), the block gets the most parity that fits and is marked `reduced`.
///
/// # Errors
/// [`Error::Malformed`] for 0 data shards, [`Error::TooLarge`] over [`MAX_DATA_SHARDS_PER_FRAME`].
pub fn plan_fec_blocks(data_shards: usize, fec_percentage: u8, min_parity: u8) -> Result<Vec<FecBlock>> {
if data_shards == 0 {
return Err(malformed("video frame without data shards"));
}
cap("video frame data shards", MAX_DATA_SHARDS_PER_FRAME, data_shards)?;
let blocks = (1..=MAX_FEC_BLOCKS)
.find(|&b| wished_percentage(data_shards.div_ceil(b), fec_percentage, min_parity).is_some())
.unwrap_or(MAX_FEC_BLOCKS);
let k_full = data_shards.div_ceil(blocks);
let count = data_shards.div_ceil(k_full);
let mut plan = Vec::with_capacity(count);
let mut left = data_shards;
while left > 0 {
let k = left.min(k_full);
plan.push(block(k, fec_percentage, min_parity)?);
left -= k;
}
Ok(plan)
}
/// The 32 header bytes of one packet (`docs/PROTOCOL.md` 5.2).
struct Header {
sequence: u16,
timestamp: u32,
frame_index: u32,
flags: u8,
block: u8,
last_block: u8,
shard_index: u16,
data_shards: u16,
fec_percentage: u8,
}
impl Header {
fn bytes(&self) -> [u8; PAYLOAD_OFFSET] {
let fec_info = (u32::from(self.fec_percentage) << 4)
| ((u32::from(self.shard_index) & 0x3FF) << 12)
| ((u32::from(self.data_shards) & 0x3FF) << 22);
let parts: [&[u8]; 11] = [
&[VIDEO_RTP_BYTE0, 0], // RTP byte 0, payload type 0
&self.sequence.to_be_bytes(), // sequence, BE
&self.timestamp.to_be_bytes(), // timestamp, BE
&[0; 4], // SSRC 0
&[0; 4], // reserved
&(u32::from(self.sequence) << 8).to_le_bytes(), // stream packet index, LE
&self.frame_index.to_le_bytes(), // frame index, LE
&[self.flags, 0], // flags, reserved
&[MULTI_FEC_FLAGS], // multi-FEC flags (U15)
&[((self.block & 3) << 4) | ((self.last_block & 3) << 6)], // multi-FEC blocks
&fec_info.to_le_bytes(), // FEC info, LE
];
let mut out = [0u8; PAYLOAD_OFFSET];
for (dst, src) in out.iter_mut().zip(parts.iter().flat_map(|p| p.iter())) {
*dst = *src;
}
out
}
}
/// The video sender of one stream.
#[derive(Debug)]
pub struct VideoPacketizer {
config: VideoPacketizerConfig,
payload_len: usize,
next_sequence: u16,
/// Next GCM nonce counter (sealed streams only).
next_nonce: u64,
stats: VideoPacketizerStats,
}
impl VideoPacketizer {
/// A sender for one stream.
///
/// # Errors
/// [`Error::Malformed`] for a `packet_size` not above the NV header size, or one whose datagrams (sealed, when a
/// cipher is set) would not fit [`MAX_VIDEO_PACKET_BYTES`], the receiver's cap.
pub fn new(config: VideoPacketizerConfig) -> Result<Self> {
let size = usize::from(config.packet_size);
let sealed = if config.cipher.is_some() { ENCRYPTION_PREFIX_LEN } else { 0 };
if size <= NV_HEADER_LEN || size + VIDEO_RTP_LEN + sealed > MAX_VIDEO_PACKET_BYTES {
return Err(malformed("video packet_size"));
}
Ok(Self {
payload_len: size - NV_HEADER_LEN,
next_sequence: config.first_sequence,
config,
next_nonce: 0,
stats: VideoPacketizerStats::default(),
})
}
/// The largest bitstream one frame can carry: [`MAX_DATA_SHARDS_PER_FRAME`] shards of payload, and the
/// receiver's [`MAX_FRAME_BYTES`], minus the frame header.
#[must_use]
pub const fn max_bitstream_len(&self) -> usize {
let shards = MAX_DATA_SHARDS_PER_FRAME * self.payload_len;
let max = if shards < MAX_FRAME_BYTES { shards } else { MAX_FRAME_BYTES };
max - FRAME_HEADER_LEN
}
/// Packetizes one frame into its datagrams, in send order: block 0's data shards then its parity, block 1, …
/// On error nothing changes (sequence numbers, nonce counter, stats).
///
/// # Errors
/// [`Error::TooLarge`] for a bitstream over [`Self::max_bitstream_len`] (checked before anything is allocated),
/// [`Error::State`] once the nonce counter of a sealed stream is exhausted (a new session key is needed).
pub fn packetize(&mut self, frame: &EncodedFrame<'_>) -> Result<Vec<Vec<u8>>> {
cap("video access unit", self.max_bitstream_len(), frame.bitstream.len())?;
let p = self.payload_len;
let data_len = FRAME_HEADER_LEN + frame.bitstream.len();
let n = data_len.div_ceil(p);
let plan = plan_fec_blocks(n, self.config.fec_percentage, self.config.min_required_fec_packets)?;
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
let sealed = self.config.cipher.is_some();
if sealed && self.next_nonce.checked_add(total as u64).is_none() {
return Err(Error::State { expected: "a fresh session key (video nonce counter exhausted)" });
}
// Frame data: header + bitstream, zero-padded to n whole shards (5.2).
let last_payload = data_len - (n - 1) * p;
let header =
write_frame_header(frame.frame_type, frame.processing_latency, u32::try_from(last_payload).unwrap_or(0));
let mut data = Vec::with_capacity(n * p);
data.extend_from_slice(&header);
data.extend_from_slice(frame.bitstream);
data.resize(n * p, 0);
let last_block = u8::try_from(plan.len() - 1).map_err(|_| malformed("video fec blocks"))?;
let mut sequence = self.next_sequence;
let mut next_header = |flags: u8, block: u8, shard_index: u16, b: &FecBlock| {
let h = Header {
sequence,
timestamp: frame.rtp_timestamp,
frame_index: frame.frame_index,
flags,
block,
last_block,
shard_index,
data_shards: b.data_shards,
fec_percentage: b.fec_percentage,
};
sequence = sequence.wrapping_add(1);
h.bytes()
};
let packet_len = PAYLOAD_OFFSET + p;
let mut out: Vec<Vec<u8>> = Vec::with_capacity(total);
let mut chunks = data.chunks(p);
let mut shard_no = 0usize;
let mut reduced = 0u64;
let mut parity_packets = 0u64;
for (bi, b) in plan.iter().enumerate() {
let block = u8::try_from(bi).map_err(|_| malformed("video fec blocks"))?;
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
reduced += u64::from(b.reduced);
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
for i in 0..k {
let mut flags = VideoFlags::PICTURE_DATA;
if shard_no == 0 {
flags |= VideoFlags::START_OF_FRAME;
}
if shard_no + 1 == n {
flags |= VideoFlags::END_OF_FRAME;
}
shard_no += 1;
let mut packet = Vec::with_capacity(packet_len);
packet.extend_from_slice(&next_header(flags, block, u16::try_from(i).unwrap_or(u16::MAX), b));
packet.extend_from_slice(chunks.next().ok_or(malformed("video frame shards"))?);
shards.push(packet);
}
if m > 0 {
// Parity over the whole data packets, headers included (5.3) ...
shards.resize_with(k + m, || vec![0u8; packet_len]);
ReedSolomon::new(k, m)?.encode(&mut shards)?;
// ... and only then the parity packets' own header fields, over their first 32 bytes.
for (j, parity) in shards.iter_mut().skip(k).enumerate() {
let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);
if let Some(head) = parity.get_mut(..PAYLOAD_OFFSET) {
head.copy_from_slice(&h);
}
}
parity_packets += m as u64;
}
out.append(&mut shards);
}
if let Some(cipher) = &self.config.cipher {
let mut nonce = self.next_nonce;
for packet in &mut out {
*packet = cipher.encrypt(nonce, frame.frame_index, packet)?;
nonce += 1;
}
self.next_nonce = nonce;
}
self.next_sequence = sequence;
self.stats.frames += 1;
self.stats.packets += out.len() as u64;
self.stats.parity_packets += parity_packets;
self.stats.fec_reduced_blocks += reduced;
Ok(out)
}
/// The RTP sequence number of the next datagram.
#[must_use]
pub const fn next_sequence(&self) -> u16 {
self.next_sequence
}
/// Counters.
#[must_use]
pub const fn stats(&self) -> VideoPacketizerStats {
self.stats
}
}
-157
View File
@@ -1,157 +0,0 @@
//! "Caps every length before it allocates", for the host side of ENet and control: a counting global allocator
//! (`peak_alloc`) checks that lying fragment lengths and lying message lengths never reserve what they claim, and
//! that arbitrary input stays within a bound tied to the input and the caps.
//!
//! The counters are process-wide, so this file holds exactly one #[test] that runs everything in sequence.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use domistream::Instant;
use domistream::control::{ControlCipher, ControlHost, ControlHostConfig, Direction, parse_client_message};
use domistream::enet::protocol::{Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram};
use domistream::enet::{EnetHostConfig, EnetHostPeer, MAX_PACKET_BYTES};
use peak_alloc::PeakAlloc;
use proptest::prelude::*;
use proptest::test_runner::{Config, TestRunner};
#[global_allocator]
static ALLOC: PeakAlloc = PeakAlloc;
fn peak_of<R>(f: impl FnOnce() -> R) -> usize {
ALLOC.reset_peak_usage();
let before = ALLOC.current_usage();
let r = f();
let peak = ALLOC.peak_usage();
drop(r);
peak.saturating_sub(before)
}
fn budget(input: usize) -> usize {
64 * input + 256 * 1024
}
fn enet_config() -> EnetHostConfig {
EnetHostConfig {
peer_id: 1,
channel_limit: 4,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn connect() -> Vec<u8> {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 4,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
}],
})
.unwrap()
}
/// A connected host peer (verify acknowledged).
fn connected() -> EnetHostPeer {
let mut h = EnetHostPeer::accept(enet_config(), Instant::ZERO, &connect()).unwrap();
while h.poll_transmit(Instant::ZERO).is_some() {}
let ack = encode_datagram(&Datagram {
peer_id: 1,
session_id: 0,
sent_time: Some(1),
commands: vec![Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
}],
})
.unwrap();
h.handle_datagram(Instant::from_micros(1000), &ack).unwrap();
h
}
#[test]
fn host_parsers_never_allocate_past_their_caps() {
// Fragments of 4 billion pieces and gigabyte totals on every channel and sequence: at most the reassembly cap.
let used = peak_of(|| {
let mut h = connected();
for i in 0..256u16 {
let mut d = vec![0x80, 0x01, 0x00, 0x02];
d.extend_from_slice(&[0x88, (i % 4) as u8]);
d.extend_from_slice(&(i + 1).to_be_bytes());
d.extend_from_slice(&(i + 1).to_be_bytes()); // start sequence
d.extend_from_slice(&4u16.to_be_bytes());
d.extend_from_slice(&u32::MAX.to_be_bytes());
d.extend_from_slice(&0u32.to_be_bytes());
d.extend_from_slice(&(MAX_PACKET_BYTES as u32).to_be_bytes());
d.extend_from_slice(&0u32.to_be_bytes());
d.extend_from_slice(&[1, 2, 3, 4]);
let _ = h.handle_datagram(Instant::from_micros(2000), &d);
let mut lie = d.clone();
lie[20..24].copy_from_slice(&u32::MAX.to_be_bytes()); // total length
let _ = h.handle_datagram(Instant::from_micros(2000), &lie);
}
h
});
assert!(used <= 4 * MAX_PACKET_BYTES + 512 * 1024, "enet host: {used} bytes at peak");
// A control message whose length field claims 64 KiB.
let lie = [0x01, 0x02, 0xFF, 0xFF, 1, 2, 3];
let used = peak_of(|| common::implemented(&parse_client_message(&lie)));
assert!(used <= budget(lie.len()), "client message: {used}");
// The control host fed sealed frames that lie inside.
let used = peak_of(|| {
let config = ControlHostConfig { enet: enet_config(), rikey: [3; 16], stop_timeout: None };
let mut h = ControlHost::accept(config, Instant::ZERO, &connect()).unwrap();
let cipher = ControlCipher::new([3; 16]);
for seq in 0..64u32 {
let frame =
cipher.seal(seq, Direction::ClientToHost, &[0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF]).unwrap();
let mut d = vec![0x80, 0x01, 0x00, 0x02, 0x86, 0x00];
d.extend_from_slice(&((seq + 1) as u16).to_be_bytes());
d.extend_from_slice(&(frame.len() as u16).to_be_bytes());
d.extend_from_slice(&frame);
let _ = h.handle_datagram(Instant::from_micros(2000), &d);
while h.poll_event().is_some() {}
}
h
});
assert!(used <= 1024 * 1024, "control host: {used}");
// Arbitrary inputs.
let mut runner = TestRunner::new(Config { cases: 300, ..Config::default() });
runner
.run(&proptest::collection::vec(any::<u8>(), 0..1500), |data| {
let used = peak_of(|| common::implemented(&parse_client_message(&data)));
prop_assert!(used <= budget(data.len()), "client message: {} for {}", used, data.len());
let used = peak_of(|| common::implemented(&EnetHostPeer::accept(enet_config(), Instant::ZERO, &data)));
prop_assert!(used <= budget(data.len()), "accept: {} for {}", used, data.len());
Ok(())
})
.unwrap();
}
-261
View File
@@ -1,261 +0,0 @@
//! The audio packetizer, host side (`docs/PROTOCOL.md` 6.2, 6.3), checked against the client half: Opus packets
//! go through the crate's own `AudioDepacketizer` with the session keys and must come out identical, in order,
//! with the millisecond timestamps of 6.2, across sequence and timestamp wrap-around. A fixed vector checks one
//! datagram byte by byte; the cipher is checked against the openssl vectors. No parity packets are sent (U16).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::SeqRng;
use domistream::audio::packet::{MAX_AUDIO_PACKET_BYTES, parse_audio_packet};
use domistream::audio::packetizer::{MAX_OPUS_ENCRYPTED_BYTES, MAX_OPUS_PLAIN_BYTES};
use domistream::audio::{
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacket, AudioPacketizer,
AudioPacketizerConfig, AudioParity,
};
use domistream::{Error, Instant, SessionKeys};
use proptest::prelude::*;
const KEY: [u8; 16] = *b"audio-pack-key!!";
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
fn keys() -> SessionKeys {
SessionKeys { rikey: KEY, rikeyid: RIKEYID }
}
fn cfg(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizerConfig {
AudioPacketizerConfig {
cipher: encrypt.then(|| AudioCipher::new(&keys())),
packet_duration_ms: duration,
parity: AudioParity::None,
first_sequence,
first_timestamp_ms,
}
}
fn sender(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizer {
AudioPacketizer::new(cfg(encrypt, first_sequence, first_timestamp_ms, duration)).expect("AudioPacketizer::new")
}
fn receiver(encrypt: bool, duration: u8) -> AudioDepacketizer {
AudioDepacketizer::new(AudioConfig {
cipher: encrypt.then(|| AudioCipher::new(&keys())),
packet_duration_ms: duration,
fec: AudioFec::Disabled,
loss_timeout: Duration::from_millis(40),
})
.expect("AudioDepacketizer::new")
}
fn receive(rx: &mut AudioDepacketizer, datagrams: &[Vec<u8>]) -> Vec<AudioEvent> {
let mut now = 1_000_000u64;
let mut events = Vec::new();
for d in datagrams {
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
now += 5_000;
while let Some(e) = rx.poll_event() {
events.push(e);
}
}
for _ in 0..64 {
now += 1_000_000;
rx.handle_timeout(Instant::from_micros(now)).unwrap();
while let Some(e) = rx.poll_event() {
events.push(e);
}
if rx.poll_timeout().is_none() {
break;
}
}
events
}
/// One Opus-sized payload: 1 to 1275 bytes (one Opus frame's maximum, RFC 6716), occasionally up to `max`.
fn opus(rng: &mut SeqRng, max: usize) -> Vec<u8> {
let len = if rng.below(20) == 0 { 1 + rng.below(max) } else { 1 + rng.below(1275) };
rng.bytes(len)
}
/// Packetizes `payloads` and returns (datagrams, the events a lossless receiver must report).
fn send(tx: &mut AudioPacketizer, payloads: &[Vec<u8>], duration: u8) -> (Vec<Vec<u8>>, Vec<AudioEvent>) {
let mut datagrams = Vec::new();
let mut want = Vec::new();
for o in payloads {
let (seq, ts) = (tx.next_sequence(), tx.next_timestamp_ms());
let out = tx.packetize(o).expect("packetize");
assert_eq!(out.len(), 1, "AudioParity::None: one datagram per Opus packet, no parity");
assert_eq!(tx.next_sequence(), seq.wrapping_add(1));
assert_eq!(tx.next_timestamp_ms(), ts.wrapping_add(u32::from(duration)));
datagrams.extend(out);
want.push(AudioEvent::Packet { sequence: seq, timestamp_ms: ts, opus: o.clone(), recovered: false });
}
(datagrams, want)
}
// ================================================================================================ fixed vectors
#[test]
fn fixed_vector_plaintext() {
let mut tx = sender(false, 0x0104, 0x0A0B_0C0D, 5);
let out = tx.packetize(&[0xFC, 0xFF, 0xFE]).unwrap();
#[rustfmt::skip]
let want = vec![
0x80, // RTP byte 0: version 2, no extension (6.2)
0x61, // payload type 97
0x01, 0x04, // sequence 0x0104, BE
0x0A, 0x0B, 0x0C, 0x0D, // timestamp (milliseconds), BE
0x00, 0x00, 0x00, 0x00, // SSRC 0
0xFC, 0xFF, 0xFE, // the Opus packet
];
assert_eq!(out, vec![want]);
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), (0x0105, 0x0A0B_0C12));
}
#[test]
fn fixed_vector_encrypted() {
// Header as above; the payload is AES-128-CBC + PKCS#7 with IV = BE(rikeyid + sequence) || 12 zero bytes (6.3),
// here computed by the RustCrypto test oracle (itself checked against openssl in media.rs).
let mut tx = sender(true, 0x0020, 7, 10);
let opus = [0x11u8; 20];
let out = tx.packetize(&opus).unwrap();
let mut want = vec![0x80, 0x61, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00];
want.extend(common::audio_encrypt(&KEY, RIKEYID, 0x0020, &opus));
assert_eq!(out, vec![want]);
assert_eq!(out[0].len(), 12 + 32, "20 bytes pad to 32");
}
#[test]
fn audio_cipher_encrypt_matches_openssl_vectors() {
let v = common::audio_vectors();
for name in ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"] {
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
let c = AudioCipher::new(&SessionKeys { rikey: v.arr16("key"), rikeyid });
assert_eq!(
c.encrypt(seq, &v.bytes(&format!("{name}_plain"))).unwrap(),
v.bytes(&format!("{name}_cipher")),
"{name}"
);
}
}
// ================================================================================================ round trips
#[test]
fn round_trip_encrypted_across_sequence_and_timestamp_wrap() {
let mut rng = SeqRng::new(1);
// Sequence 0xFF00 wraps after 256 packets; the timestamp wraps too; rikeyid + sequence wraps in the IV.
let mut tx = sender(true, 0xFF00, u32::MAX - 1000, 20);
let payloads: Vec<Vec<u8>> = (0..600).map(|_| opus(&mut rng, MAX_OPUS_ENCRYPTED_BYTES)).collect();
let (datagrams, want) = send(&mut tx, &payloads, 20);
assert_eq!(receive(&mut receiver(true, 20), &datagrams), want);
}
#[test]
fn round_trip_plaintext() {
let mut rng = SeqRng::new(2);
let mut tx = sender(false, 0, 0, 5);
let payloads: Vec<Vec<u8>> = (0..300).map(|_| opus(&mut rng, MAX_OPUS_PLAIN_BYTES)).collect();
let (datagrams, want) = send(&mut tx, &payloads, 5);
for d in &datagrams {
assert!(matches!(parse_audio_packet(d), Ok(AudioPacket::Data { .. })));
}
assert_eq!(receive(&mut receiver(false, 5), &datagrams), want);
}
#[test]
fn sequence_wraps_from_ffff_to_0() {
let mut tx = sender(true, 0xFFFC, 100, 10);
let mut seen = Vec::new();
for _ in 0..6 {
let d = tx.packetize(&[1, 2, 3]).unwrap().remove(0);
let Ok(AudioPacket::Data { rtp, .. }) = parse_audio_packet(&d) else { panic!("data packet") };
seen.push((rtp.sequence, rtp.timestamp));
}
assert_eq!(seen, vec![(0xFFFC, 100), (0xFFFD, 110), (0xFFFE, 120), (0xFFFF, 130), (0x0000, 140), (0x0001, 150)]);
}
#[test]
fn lost_packets_are_reported_and_the_rest_arrive() {
let mut rng = SeqRng::new(3);
let mut tx = sender(true, 0x1000, 0, 5);
let payloads: Vec<Vec<u8>> = (0..200).map(|_| opus(&mut rng, 400)).collect();
let (datagrams, want) = send(&mut tx, &payloads, 5);
let mut kept = Vec::new();
let mut expect = Vec::new();
for (i, (d, w)) in datagrams.into_iter().zip(want).enumerate() {
if i > 0 && i < 199 && rng.below(10) == 0 {
let AudioEvent::Packet { sequence, .. } = w else { unreachable!() };
expect.push(AudioEvent::Lost { sequence });
} else {
kept.push(d);
expect.push(w);
}
}
assert_eq!(receive(&mut receiver(true, 5), &kept), expect);
}
// ================================================================================================ refusals
#[test]
fn size_caps() {
assert_eq!(MAX_OPUS_PLAIN_BYTES, MAX_AUDIO_PACKET_BYTES - 12);
assert_eq!(MAX_OPUS_ENCRYPTED_BYTES, 2031, "2031 bytes pad to 2032; 12 + 2032 = 2044 <= 2048");
for (encrypt, max) in [(false, MAX_OPUS_PLAIN_BYTES), (true, MAX_OPUS_ENCRYPTED_BYTES)] {
let mut tx = sender(encrypt, 4, 50, 5);
assert_eq!(tx.max_opus_len(), max);
let state = (tx.next_sequence(), tx.next_timestamp_ms());
assert_err!(tx.packetize(&[]), Error::Truncated { .. }, "an Opus packet has at least its TOC byte");
assert_too_large!(tx.packetize(&vec![7; max + 1]), max, max + 1);
assert_too_large!(tx.packetize(&vec![7; 100_000]), max, 100_000);
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), state, "a refused packet changes nothing");
// The largest packet fits the receiver's datagram cap and comes back.
let (datagrams, want) = send(&mut tx, &[vec![9; max], vec![8; 1]], 5);
assert!(datagrams[0].len() <= MAX_AUDIO_PACKET_BYTES);
assert_eq!(receive(&mut receiver(encrypt, 5), &datagrams), want);
}
let c = AudioCipher::new(&keys());
assert_too_large!(
c.encrypt(0, &vec![0; MAX_AUDIO_PACKET_BYTES + 1]),
MAX_AUDIO_PACKET_BYTES,
MAX_AUDIO_PACKET_BYTES + 1
);
}
#[test]
fn config_refusals() {
assert_err!(AudioPacketizer::new(cfg(true, 0, 0, 0)), Error::Malformed { .. }, "zero packet duration");
// Blocks start at multiples of 4 (6.4), and the receiver counts from the first block's start: a stream that
// began at 5 would make it report 4 as lost.
for first in [1u16, 2, 3, 5, 0xFFFF] {
assert_err!(AudioPacketizer::new(cfg(true, first, 0, 5)), Error::Malformed { .. }, "first sequence {first}");
}
assert!(AudioPacketizer::new(cfg(true, 0xFFFC, 0, 5)).is_ok());
assert_eq!(AudioParity::default(), AudioParity::None);
}
// ================================================================================================ generated
proptest! {
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
#[test]
fn generated_round_trips(
seed in any::<u64>(),
first_sequence in any::<u16>(),
first_ts in any::<u32>(),
duration in 1u8..=40,
count in 1usize..80,
encrypt in any::<bool>(),
) {
let mut rng = SeqRng::new(seed);
let mut tx = sender(encrypt, first_sequence & !3, first_ts, duration);
let max = tx.max_opus_len();
let payloads: Vec<Vec<u8>> = (0..count).map(|_| opus(&mut rng, max)).collect();
let (datagrams, want) = send(&mut tx, &payloads, duration);
prop_assert_eq!(receive(&mut receiver(encrypt, duration), &datagrams), want);
}
}
-2
View File
@@ -7,8 +7,6 @@ use std::collections::HashMap;
use domistream::RandomSource;
pub mod wire;
// ------------------------------------------------------------------------------------------------ assertions
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
-197
View File
@@ -1,197 +0,0 @@
//! An in-memory, simulated-time network for client-against-host tests: two one-way links with optional loss,
//! duplication and reordering (all from a seeded [`SeqRng`], so every run is the same), and a driver that shuttles
//! datagrams between two sans-I/O endpoints, advancing the clock to the next delivery or deadline.
use domistream::Instant;
use super::SeqRng;
/// One side of a session, as the wire drives it.
pub trait Endpoint {
/// The next datagram this side wants to send.
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>>;
/// A datagram arrived.
fn receive(&mut self, now: Instant, datagram: &[u8]);
/// When this side wants [`Endpoint::tick`].
fn deadline(&self) -> Option<Instant>;
/// Timers.
fn tick(&mut self, now: Instant);
}
/// What a one-way link does to datagrams. Rates are per mille.
#[derive(Clone, Copy, Debug, Default)]
pub struct Impair {
pub loss: u32,
pub duplicate: u32,
/// Chance that a datagram is held back by up to `reorder_ms` extra.
pub reorder: u32,
pub reorder_ms: u64,
/// Fixed one-way latency, ms.
pub latency_ms: u64,
}
impl Impair {
pub fn clean(latency_ms: u64) -> Self {
Self { latency_ms, ..Self::default() }
}
pub fn lossy(loss: u32, latency_ms: u64) -> Self {
Self { loss, duplicate: 20, reorder: 100, reorder_ms: 30, latency_ms }
}
}
/// A one-way link.
#[derive(Debug)]
pub struct Link {
pub impair: Impair,
rng: SeqRng,
queue: Vec<(u64, u64, Vec<u8>)>,
order: u64,
/// Datagrams handed to the link, and the ones it dropped.
pub sent: usize,
pub lost: usize,
/// When set, every datagram is dropped (a peer that vanished).
pub cut: bool,
}
impl Link {
pub fn new(impair: Impair, seed: u64) -> Self {
Self { impair, rng: SeqRng::new(seed), queue: Vec::new(), order: 0, sent: 0, lost: 0, cut: false }
}
fn chance(&mut self, per_mille: u32) -> bool {
per_mille > 0 && (self.rng.below(1000) as u32) < per_mille
}
pub fn send(&mut self, now_ms: u64, datagram: Vec<u8>) {
self.sent += 1;
if self.cut || self.chance(self.impair.loss) {
self.lost += 1;
return;
}
let copies = if self.chance(self.impair.duplicate) { 2 } else { 1 };
for _ in 0..copies {
let mut due = now_ms + self.impair.latency_ms;
if self.impair.reorder_ms > 0 && self.chance(self.impair.reorder) {
due += 1 + self.rng.below(self.impair.reorder_ms as usize) as u64;
}
self.order += 1;
self.queue.push((due, self.order, datagram.clone()));
}
}
pub fn next_due(&self) -> Option<u64> {
self.queue.iter().map(|(d, _, _)| *d).min()
}
/// Datagrams due by `now_ms`, in delivery order.
pub fn due(&mut self, now_ms: u64) -> Vec<Vec<u8>> {
let mut ready: Vec<(u64, u64, Vec<u8>)> = Vec::new();
let mut rest = Vec::new();
for item in self.queue.drain(..) {
if item.0 <= now_ms { ready.push(item) } else { rest.push(item) }
}
self.queue = rest;
ready.sort_by_key(|(d, o, _)| (*d, *o));
ready.into_iter().map(|(_, _, d)| d).collect()
}
}
pub fn ms(t: Instant) -> u64 {
t.as_micros().div_ceil(1000)
}
pub fn at(ms: u64) -> Instant {
Instant::from_micros(ms * 1000)
}
/// A client, a host and the two links between them.
pub struct Wire<C: Endpoint, H: Endpoint> {
pub client: C,
pub host: H,
pub to_host: Link,
pub to_client: Link,
pub now_ms: u64,
}
impl<C: Endpoint, H: Endpoint> Wire<C, H> {
pub fn new(client: C, host: H, to_host: Impair, to_client: Impair, seed: u64) -> Self {
Self {
client,
host,
to_host: Link::new(to_host, seed ^ 0xC2C2),
to_client: Link::new(to_client, seed ^ 0x4848),
now_ms: 0,
}
}
/// Moves everything that can move at the current time (transmit, deliver, timers), until quiet.
pub fn settle(&mut self) {
for _ in 0..10_000 {
let now = at(self.now_ms);
let mut moved = false;
if self.client.deadline().is_some_and(|t| t <= now) {
self.client.tick(now);
}
if self.host.deadline().is_some_and(|t| t <= now) {
self.host.tick(now);
}
while let Some(d) = self.client.transmit(now) {
self.to_host.send(self.now_ms, d);
moved = true;
}
while let Some(d) = self.host.transmit(now) {
self.to_client.send(self.now_ms, d);
moved = true;
}
for d in self.to_host.due(self.now_ms) {
self.host.receive(now, &d);
moved = true;
}
for d in self.to_client.due(self.now_ms) {
self.client.receive(now, &d);
moved = true;
}
if !moved {
return;
}
}
panic!("the wire never settles at {} ms", self.now_ms);
}
/// The next moment anything happens, if anything ever does.
pub fn next_event(&self) -> Option<u64> {
[
self.to_host.next_due(),
self.to_client.next_due(),
self.client.deadline().map(ms),
self.host.deadline().map(ms),
]
.into_iter()
.flatten()
.min()
}
/// Runs until `done` holds or `limit_ms` passes; returns whether `done` held.
pub fn run_until(&mut self, limit_ms: u64, mut done: impl FnMut(&mut Self) -> bool) -> bool {
loop {
self.settle();
if done(self) {
return true;
}
let next = self.next_event().unwrap_or(u64::MAX).max(self.now_ms + 1);
if next > limit_ms {
self.now_ms = limit_ms.max(self.now_ms);
self.settle();
return done(self);
}
self.now_ms = next;
}
}
/// Runs for `duration_ms` of simulated time.
pub fn run_for(&mut self, duration_ms: u64) {
let end = self.now_ms + duration_ms;
self.run_until(end, |w| w.now_ms >= end);
}
}
-786
View File
@@ -1,786 +0,0 @@
//! The host side of the control stream (`docs/PROTOCOL.md` 3.2, 3.3, `control::host`): our own [`ControlStream`]
//! (and a probe-style client for the messages whose bodies are empty) talks to a [`ControlHost`] over the in-memory
//! wire. Input arrives typed and byte-identical, host messages reach the client, replays and forgeries are dropped,
//! and the stop deadline ends a session without pings.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::wire::{Endpoint, Impair, Wire, at};
use domistream::control::host::{DEFAULT_STOP_TIMEOUT, TERMINATION_GRACEFUL};
use domistream::control::message::{HdrMetadata, MAX_MESSAGE_BYTES, MotionKind, encode_client_message};
use domistream::control::{
ClientControlMessage, ClientMessage, ControlCipher, ControlConfig, ControlEvent, ControlHost, ControlHostConfig,
ControlHostEvent, ControlStream, Direction, HostMessage, StopDeadline, encode_host_message, parse_client_message,
parse_host_message,
};
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostState, EnetState};
use domistream::input::{
ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState, InputEvent, MouseButton, encode_input,
};
use domistream::{Error, Instant};
use proptest::prelude::*;
const KEY: [u8; 16] = *b"lumen-control-k!";
fn enet_client_config() -> EnetConfig {
EnetConfig {
channel_count: 1,
mtu: 1400,
connect_data: 0,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(30),
}
}
fn host_config(stop_timeout: Option<Duration>) -> ControlHostConfig {
ControlHostConfig {
enet: EnetHostConfig {
peer_id: 0,
channel_limit: 0x30,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(30),
},
rikey: KEY,
stop_timeout,
}
}
fn msg(ty: u16, body: &[u8]) -> Vec<u8> {
let mut m = ty.to_le_bytes().to_vec();
m.extend_from_slice(&(body.len() as u16).to_le_bytes());
m.extend_from_slice(body);
m
}
// ================================================================================================ endpoints
/// Our client as it ships: [`ControlStream`].
struct StreamClient {
stream: ControlStream,
events: Vec<ControlEvent>,
}
impl StreamClient {
fn new(seed: u64) -> Self {
let config =
ControlConfig { enet: enet_client_config(), rikey: KEY, ping_interval: Duration::from_millis(100) };
Self {
stream: ControlStream::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(),
events: Vec::new(),
}
}
fn drain(&mut self) {
while let Some(e) = self.stream.poll_event() {
self.events.push(e);
}
}
fn messages(&self) -> Vec<HostMessage> {
self.events
.iter()
.filter_map(|e| match e {
ControlEvent::Message(m) => Some(m.clone()),
_ => None,
})
.collect()
}
}
impl Endpoint for StreamClient {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.stream.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.stream.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.stream.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.stream.handle_timeout(now).unwrap();
self.drain();
}
}
/// A probe-style client: ENet plus the cipher, sending any plaintext or any frame (PROTOCOL.md 3.3: Moonshine
/// reads no body from START_B, PERIODIC_PING or the IDR request, so they go with empty bodies).
struct RawClient {
enet: EnetClient,
cipher: ControlCipher,
next_sequence: u32,
/// Host frames opened: (sequence, plaintext).
opened: Vec<(u32, Vec<u8>)>,
events: Vec<EnetEvent>,
}
impl RawClient {
fn new(seed: u64) -> Self {
Self {
enet: EnetClient::connect(enet_client_config(), Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap(),
cipher: ControlCipher::new(KEY),
next_sequence: 0,
opened: Vec::new(),
events: Vec::new(),
}
}
fn send_frame(&mut self, now: Instant, frame: Vec<u8>) {
self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap();
}
fn seal(&mut self, plain: &[u8]) -> Vec<u8> {
let f = self.cipher.seal(self.next_sequence, Direction::ClientToHost, plain).unwrap();
self.next_sequence += 1;
f
}
fn send_plain(&mut self, now: Instant, plain: &[u8]) {
let f = self.seal(plain);
self.send_frame(now, f);
}
fn drain(&mut self) {
while let Some(e) = self.enet.poll_event() {
if let EnetEvent::Received { data, .. } = &e {
self.opened.push(self.cipher.open(Direction::HostToClient, data).expect("host frames open with 'H'"));
}
self.events.push(e);
}
}
}
impl Endpoint for RawClient {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.enet.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.enet.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.enet.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.enet.handle_timeout(now).unwrap();
self.drain();
}
}
/// The caller of the control host (one client address).
struct Host {
config: ControlHostConfig,
host: Option<ControlHost>,
events: Vec<ControlHostEvent>,
/// When each PingTimedOut was reported, ms.
ping_timeouts: Vec<u64>,
}
impl Host {
fn new(config: ControlHostConfig) -> Self {
Self { config, host: None, events: Vec::new(), ping_timeouts: Vec::new() }
}
fn h(&mut self) -> &mut ControlHost {
self.host.as_mut().expect("accepted")
}
fn drain(&mut self, now: Instant) {
if let Some(h) = self.host.as_mut() {
while let Some(e) = h.poll_event() {
if e == ControlHostEvent::PingTimedOut {
self.ping_timeouts.push(now.as_micros() / 1000);
}
self.events.push(e);
}
}
}
fn messages(&self) -> Vec<ClientControlMessage> {
self.events
.iter()
.filter_map(|e| match e {
ControlHostEvent::Message(m) => Some(m.clone()),
_ => None,
})
.collect()
}
/// Events after the first `Connected`, without it.
fn take(&mut self) -> Vec<ControlHostEvent> {
let out: Vec<ControlHostEvent> = self.events.drain(..).filter(|e| *e != ControlHostEvent::Connected).collect();
out
}
fn connected(&self) -> bool {
self.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Connected)
}
}
impl Endpoint for Host {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.host.as_mut()?.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
match self.host.as_mut() {
None => {
if let Ok(h) = ControlHost::accept(self.config.clone(), now, datagram) {
self.host = Some(h);
}
}
Some(h) => {
let _ = h.handle_datagram(now, datagram);
}
}
self.drain(now);
}
fn deadline(&self) -> Option<Instant> {
self.host.as_ref()?.poll_timeout()
}
fn tick(&mut self, now: Instant) {
if let Some(h) = self.host.as_mut() {
h.handle_timeout(now).unwrap();
}
self.drain(now);
}
}
fn stream_session(to_host: Impair, to_client: Impair, stop: Option<Duration>, seed: u64) -> Wire<StreamClient, Host> {
let mut w = Wire::new(StreamClient::new(seed), Host::new(host_config(stop)), to_host, to_client, seed);
assert!(
w.run_until(30_000, |w| w.host.connected() && w.client.events.contains(&ControlEvent::Connected)),
"no connection"
);
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
w.host.events.clear();
w
}
fn raw_session(stop: Option<Duration>, seed: u64) -> Wire<RawClient, Host> {
let mut w = Wire::new(RawClient::new(seed), Host::new(host_config(stop)), Impair::clean(3), Impair::clean(3), seed);
assert!(w.run_until(5_000, |w| w.host.connected() && w.client.enet.state() == EnetState::Connected));
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
w.host.events.clear();
w
}
// ================================================================================================ input
fn every_input() -> Vec<InputEvent> {
vec![
InputEvent::MouseMoveRel { dx: -1, dy: 0 },
InputEvent::MouseMoveRel { dx: i16::MAX, dy: i16::MIN },
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
InputEvent::MouseButton { pressed: false, button: MouseButton::Extra },
InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 },
InputEvent::Key { pressed: false, flags: 0, key_code: 0x41, modifiers: 0 },
InputEvent::Scroll { amount: -120 },
InputEvent::HScroll { amount: 30 },
InputEvent::Gamepad(GamepadState {
controller: 0,
active_mask: 1,
buttons: ButtonFlags(0x0010_1001),
left_trigger: 0x10,
right_trigger: 0xFF,
left_stick_x: -32768,
left_stick_y: 32767,
right_stick_x: 5,
right_stick_y: -104,
}),
InputEvent::ControllerArrival {
controller: 1,
kind: ControllerKind::PlayStation,
capabilities: ControllerCapabilities(0x03),
supported_buttons: ButtonFlags(0x000F_F7FF),
},
]
}
#[test]
fn input_arrives_typed_and_byte_identical() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 1);
let t = at(w.now_ms);
let mut sent = Vec::new();
for e in every_input() {
let m = ClientMessage::Input(e);
w.client.stream.send(t, &m).unwrap();
sent.push(m);
}
let invalidate = ClientMessage::InvalidateRefFrames { first: 17, last: 0xFFFF_FFF0 };
w.client.stream.send(t, &invalidate).unwrap();
w.run_for(500);
let got = w.host.messages();
assert_eq!(got.len(), sent.len() + 1, "{got:?}");
for (m, g) in sent.iter().zip(&got) {
let ClientMessage::Input(want) = m else { unreachable!() };
assert_eq!(g, &ClientControlMessage::Input(want.clone()));
let ClientControlMessage::Input(e) = g else { unreachable!() };
assert_eq!(encode_input(e).unwrap(), encode_client_message(m).unwrap(), "byte-identical: {e:?}");
}
assert_eq!(got[sent.len()], ClientControlMessage::InvalidateRefFrames { first: 17, last: 0xFFFF_FFF0 });
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
}
#[test]
fn input_vectors_from_the_wolf_tables() {
// PROTOCOL.md section 4, "Test vectors".
for (hex, want) in [
("06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00", InputEvent::MouseMoveRel { dx: -1, dy: 0 }),
(
"06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37",
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
),
(
"06 02 09 00 00 00 00 05 08 00 00 00 01",
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
),
(
"06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00",
InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 },
),
("06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00", InputEvent::Scroll { amount: -120 }),
("06 02 0A 00 00 00 00 06 01 00 00 55 00 1E", InputEvent::HScroll { amount: 30 }),
] {
let bytes = common::hex(hex);
assert_eq!(parse_client_message(&bytes), Ok(ClientControlMessage::Input(want.clone())), "{hex}");
}
}
#[test]
fn input_the_host_cannot_read_is_reported_not_fatal() {
// TOUCH (layout UNKNOWN U21), an unknown input type, a wrong size field.
let mut touch = 0x0206u16.to_le_bytes().to_vec();
touch.extend_from_slice(&12u16.to_le_bytes());
touch.extend_from_slice(&8u32.to_be_bytes());
touch.extend_from_slice(&0x5500_0002u32.to_le_bytes());
touch.extend_from_slice(&[1, 2, 3, 4]);
let mut unknown = touch.clone();
unknown[8..12].copy_from_slice(&0x0000_0099u32.to_le_bytes());
let mut bad_size = touch.clone();
bad_size[4..8].copy_from_slice(&999u32.to_be_bytes());
for (m, what) in [(touch, "touch"), (unknown, "unknown type"), (bad_size, "size field")] {
match parse_client_message(&m) {
Ok(ClientControlMessage::InputRejected { body_len, .. }) => assert_eq!(body_len, m.len() - 4, "{what}"),
other => panic!("{what}: {other:?}"),
}
}
}
// ================================================================================================ other messages
#[test]
fn client_messages_from_the_field_tables() {
let invalidate = |first: u32, last: u32| {
let mut b = first.to_le_bytes().to_vec();
b.extend_from_slice(&[0; 4]);
b.extend_from_slice(&last.to_le_bytes());
b.extend_from_slice(&[0; 12]);
b
};
for (m, want) in [
(msg(0x0307, &[]), ClientControlMessage::StartB),
(msg(0x0307, &[1, 2, 3, 4]), ClientControlMessage::StartB),
(msg(0x0200, &[]), ClientControlMessage::PeriodicPing),
(msg(0x0200, &[9; 8]), ClientControlMessage::PeriodicPing),
(msg(0x0302, &[]), ClientControlMessage::IdrRequest),
(msg(0x0301, &invalidate(5, 9)), ClientControlMessage::InvalidateRefFrames { first: 5, last: 9 }),
// Short bodies read as zero from where they end (PROTOCOL.md 3.3).
(msg(0x0301, &[]), ClientControlMessage::InvalidateRefFrames { first: 0, last: 0 }),
(msg(0x0301, &7u32.to_le_bytes()), ClientControlMessage::InvalidateRefFrames { first: 7, last: 0 }),
(msg(0x0301, &invalidate(5, 9)[..12]), ClientControlMessage::InvalidateRefFrames { first: 5, last: 9 }),
(msg(0x0301, &invalidate(5, 9)[..11]), ClientControlMessage::InvalidateRefFrames { first: 5, last: 0 }),
(msg(0x0201, &[1, 2, 3]), ClientControlMessage::LossStats(vec![1, 2, 3])),
(msg(0x0204, &[]), ClientControlMessage::FrameStats(vec![])),
(msg(0x0305, &[]), ClientControlMessage::Unknown { message_type: 0x0305, body_len: 0 }),
(msg(0x7777, &[0; 3]), ClientControlMessage::Unknown { message_type: 0x7777, body_len: 3 }),
(msg(0x010b, &[0; 10]), ClientControlMessage::Unknown { message_type: 0x010b, body_len: 10 }),
] {
assert_eq!(parse_client_message(&m), Ok(want.clone()), "{want:?}");
}
assert_err!(parse_client_message(&[]), Error::Truncated { .. });
assert_err!(parse_client_message(&[0x07, 0x03, 0x00]), Error::Truncated { .. });
let mut lie = msg(0x0307, &[0; 4]);
lie[2] = 5;
assert_err!(parse_client_message(&lie), Error::Malformed { .. });
assert_too_large!(
parse_client_message(&msg(0x0201, &vec![0; MAX_MESSAGE_BYTES - 3])),
MAX_MESSAGE_BYTES,
MAX_MESSAGE_BYTES + 1
);
}
#[test]
fn start_ping_idr_and_stats_over_the_wire() {
let mut w = raw_session(None, 2);
let t = at(w.now_ms);
for m in [
msg(0x0305, &[]),
msg(0x0307, &[]),
msg(0x0200, &[]),
msg(0x0302, &[]),
msg(0x0201, &[0xAA; 32]),
msg(0x0204, &[0xBB; 5]),
msg(0x7777, &[1, 2, 3]),
] {
w.client.send_plain(t, &m);
}
w.run_for(200);
assert_eq!(
w.host.take(),
[
ClientControlMessage::Unknown { message_type: 0x0305, body_len: 0 },
ClientControlMessage::StartB,
ClientControlMessage::PeriodicPing,
ClientControlMessage::IdrRequest,
ClientControlMessage::LossStats(vec![0xAA; 32]),
ClientControlMessage::FrameStats(vec![0xBB; 5]),
ClientControlMessage::Unknown { message_type: 0x7777, body_len: 3 },
]
.into_iter()
.map(ControlHostEvent::Message)
.collect::<Vec<_>>()
);
}
// ================================================================================================ host to client
#[test]
fn host_message_layouts() {
for (m, hex) in [
(
HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 },
"0b010a00 00000000 0100 ff7f 0080",
),
(HostMessage::RumbleTriggers { controller: 2, left: 0x1234, right: 0xABCD }, "00550600 0200 3412 cdab"),
(HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) }, "09010400 80030023"),
(HostMessage::Termination { error_code: Some(1) }, "09010400 00000001"),
(
HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Gyroscope },
"01550500 0300 c800 02",
),
(HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF }, "02550500 0300 1020ff"),
] {
let bytes = encode_host_message(&m).unwrap();
assert_eq!(common::to_hex(&bytes), hex.replace(' ', ""), "{m:?}");
assert_eq!(parse_host_message(&bytes), Ok(m.clone()), "round trip through the client's parser");
}
// Not sent: the plain termination's body is UNKNOWN (U10), HDR mode's layout has GPL provenance ([M*]).
for m in [
HostMessage::Termination { error_code: None },
HostMessage::HdrMode { enabled: true, metadata: None },
HostMessage::HdrMode { enabled: true, metadata: Some(HdrMetadata::default()) },
HostMessage::Other { message_type: 0x5503, body_len: 0 },
] {
assert_err!(encode_host_message(&m), Error::Unsupported { .. }, "{m:?}");
}
}
#[test]
fn host_messages_reach_the_client() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 3);
let t = at(w.now_ms);
let h = w.host.h();
h.send_rumble(t, 0, 0x1000, 0x2000).unwrap();
h.send_rumble_triggers(t, 1, 3, 4).unwrap();
h.send(t, &HostMessage::RgbLed { controller: 2, r: 1, g: 2, b: 3 }).unwrap();
h.send(t, &HostMessage::MotionEvent { controller: 2, rate_hz: 100, kind: MotionKind::Accelerometer }).unwrap();
h.send_termination(t, TERMINATION_GRACEFUL).unwrap();
assert_err!(h.send_hdr_mode(t, true, None), Error::Unsupported { .. });
w.run_for(300);
assert_eq!(
w.client.messages(),
vec![
HostMessage::Rumble { controller: 0, low_frequency: 0x1000, high_frequency: 0x2000 },
HostMessage::RumbleTriggers { controller: 1, left: 3, right: 4 },
HostMessage::RgbLed { controller: 2, r: 1, g: 2, b: 3 },
HostMessage::MotionEvent { controller: 2, rate_hz: 100, kind: MotionKind::Accelerometer },
HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) },
]
);
assert!(!w.client.events.contains(&ControlEvent::Dropped));
}
#[test]
fn host_frames_count_up_from_zero_and_go_reliable_on_channel_0() {
let mut w = raw_session(None, 4);
let t = at(w.now_ms);
for c in 0..3u16 {
w.host.h().send_rumble(t, c, 1, 2).unwrap();
}
w.run_for(200);
let seqs: Vec<u32> = w.client.opened.iter().map(|(s, _)| *s).collect();
assert_eq!(seqs, vec![0, 1, 2], "host sequence numbers start at 0 and never repeat (U11)");
assert!(w.client.events.iter().all(|e| !matches!(e, EnetEvent::Received { channel, .. } if *channel != 0)));
}
// ================================================================================================ replay, forgery
#[test]
fn replays_and_forgeries_are_dropped() {
let mut w = raw_session(None, 5);
let t = at(w.now_ms);
let start_b = msg(0x0307, &[]);
let ping = msg(0x0200, &[]);
let c = &mut w.client;
let f5 = c.cipher.seal(5, Direction::ClientToHost, &start_b).unwrap();
c.send_frame(t, f5.clone());
c.send_frame(t, f5); // the very same frame again (a new ENet command): a replay
c.send_frame(t, c.cipher.seal(3, Direction::ClientToHost, &ping).unwrap()); // older
c.send_frame(t, c.cipher.seal(5, Direction::ClientToHost, &ping).unwrap()); // equal, other content
let mut bad = c.cipher.seal(6, Direction::ClientToHost, &ping).unwrap();
bad[26] ^= 0x10;
c.send_frame(t, bad); // bad tag (ciphertext changed)
c.send_frame(t, c.cipher.seal(6, Direction::HostToClient, &ping).unwrap()); // reflected host frame
c.send_frame(t, ControlCipher::new([0; 16]).seal(6, Direction::ClientToHost, &ping).unwrap()); // wrong key
c.send_frame(t, vec![0xFF; 40]); // not a frame
c.send_frame(t, ping.clone()); // a bare message outside the frame (control V2 only)
c.send_frame(t, c.cipher.seal(6, Direction::ClientToHost, &ping).unwrap()); // seq 6 still free
w.run_for(200);
use ClientControlMessage as M;
use ControlHostEvent as E;
assert_eq!(
w.host.take(),
vec![
E::Message(M::StartB),
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Dropped,
E::Message(M::PeriodicPing),
]
);
}
#[test]
fn malformed_message_inside_a_good_frame_is_skipped() {
let mut w = raw_session(None, 6);
let t = at(w.now_ms);
let mut lie = msg(0x0307, &[0; 4]);
lie[2] = 9;
w.client.send_plain(t, &lie);
w.client.send_plain(t, &[0x07]);
w.client.send_plain(t, &msg(0x0307, &[]));
w.run_for(200);
assert_eq!(
w.host.take(),
vec![
ControlHostEvent::Dropped,
ControlHostEvent::Dropped,
ControlHostEvent::Message(ClientControlMessage::StartB)
]
);
}
#[test]
fn client_sequence_at_u32_wrap() {
let mut w = raw_session(None, 7);
let t = at(w.now_ms);
let ping = msg(0x0200, &[]);
for seq in [0xFFFF_FFFEu32, 0xFFFF_FFFF, 0, 1] {
let f = w.client.cipher.seal(seq, Direction::ClientToHost, &ping).unwrap();
w.client.send_frame(t, f);
}
w.run_for(200);
let p = ControlHostEvent::Message(ClientControlMessage::PeriodicPing);
assert_eq!(w.host.take(), vec![p.clone(), p, ControlHostEvent::Dropped, ControlHostEvent::Dropped]);
}
// ================================================================================================ stop deadline
#[test]
fn stop_deadline_rules() {
let mut d = StopDeadline::new(at(1_000), Duration::from_secs(60));
assert_eq!(d.deadline(), at(61_000));
assert!(!d.expired(at(60_999)));
assert!(d.expired(at(61_000)));
d.on_ping(at(30_000));
assert_eq!(d.deadline(), at(90_000));
assert!(!d.expired(at(61_000)));
// A ping never pulls the deadline back (time does not go backwards, but be strict anyway).
d.on_ping(at(10_000));
assert_eq!(d.deadline(), at(90_000));
assert_eq!(DEFAULT_STOP_TIMEOUT, Duration::from_secs(60));
}
#[test]
fn no_periodic_ping_ends_the_session() {
let stop = Duration::from_secs(2);
let mut w = raw_session(Some(stop), 8);
let connected_ms = w.now_ms;
let dl = w.host.h().stop_deadline().expect("the clock runs once connected");
assert!(dl <= at(connected_ms + 2_000) && dl >= at(connected_ms + 1_900), "{dl:?}");
// Pings every 500 ms for 10 s keep it alive.
for _ in 0..20 {
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0200, &[]));
w.run_for(500);
}
assert!(w.host.ping_timeouts.is_empty(), "pinged: no stop");
let last_ping = w.now_ms - 500;
w.run_for(5_000);
assert_eq!(w.host.ping_timeouts.len(), 1, "reported once");
let at_ms = w.host.ping_timeouts[0];
assert!(at_ms >= last_ping + 2_000 && at_ms <= last_ping + 2_000 + 50, "stopped at {at_ms}, last ping {last_ping}");
// Other messages do not count as pings.
assert_eq!(w.host.h().stop_deadline(), None, "the clock stops once reported");
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0200, &[]));
w.run_for(100);
assert!(w.host.h().stop_deadline().is_some(), "a later ping starts it again");
}
#[test]
fn only_pings_push_the_deadline() {
let mut w = raw_session(Some(Duration::from_secs(1)), 9);
for _ in 0..6 {
let t = at(w.now_ms);
w.client.send_plain(t, &msg(0x0307, &[]));
w.run_for(300);
}
assert_eq!(w.host.ping_timeouts.len(), 1, "START_B and friends are not pings");
}
#[test]
fn without_a_stop_timeout_the_session_never_stops_for_pings() {
let mut w = stream_session(Impair::clean(10), Impair::clean(10), None, 10);
w.run_for(120_000);
assert!(w.host.ping_timeouts.is_empty());
assert_eq!(w.host.h().stop_deadline(), None);
assert!(w.host.connected());
}
// ================================================================================================ loss, close
#[test]
fn lossy_session_delivers_everything_in_order() {
let mut w = stream_session(Impair::lossy(150, 15), Impair::lossy(150, 15), None, 11);
let inputs: Vec<InputEvent> = (0..120).map(|i| InputEvent::MouseMoveRel { dx: i, dy: -i }).collect();
for chunk in inputs.chunks(6) {
let t = at(w.now_ms);
for e in chunk {
w.client.stream.send(t, &ClientMessage::Input(e.clone())).unwrap();
if let InputEvent::MouseMoveRel { dx, .. } = *e {
w.host.h().send_rumble(t, 0, dx as u16, 0).unwrap();
}
}
w.run_for(40);
}
assert!(w.run_until(w.now_ms + 120_000, |w| w.host.messages().len() >= 120 && w.client.messages().len() >= 120));
assert_eq!(w.host.messages(), inputs.iter().cloned().map(ClientControlMessage::Input).collect::<Vec<_>>());
assert_eq!(
w.client.messages(),
(0..120u16)
.map(|i| HostMessage::Rumble { controller: 0, low_frequency: i, high_frequency: 0 })
.collect::<Vec<_>>()
);
assert!(!w.host.events.contains(&ControlHostEvent::Dropped));
}
#[test]
fn close_from_either_side() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 12);
let t = at(w.now_ms);
w.client.stream.close(t).unwrap();
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&ControlHostEvent::Disconnected)));
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 13);
let t = at(w.now_ms);
w.host.h().send_termination(t, TERMINATION_GRACEFUL).unwrap();
w.host.h().close(t).unwrap();
assert_err!(w.host.h().close(t), Error::Closed);
assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&ControlEvent::Disconnected)));
assert_eq!(w.client.messages(), vec![HostMessage::Termination { error_code: Some(TERMINATION_GRACEFUL) }]);
assert_err!(w.host.h().send_rumble(at(w.now_ms), 0, 0, 0), Error::State { .. });
}
#[test]
fn vanished_client_times_out() {
let mut w = stream_session(Impair::clean(4), Impair::clean(4), None, 14);
w.to_host.cut = true;
assert!(w.run_until(w.now_ms + 40_000, |w| w.host.events.contains(&ControlHostEvent::TimedOut)));
}
#[test]
fn accept_refuses_what_enet_refuses() {
assert!(ControlHost::accept(host_config(None), at(0), &[1, 2, 3]).is_err());
assert!(ControlHost::accept(host_config(None), at(0), &[]).is_err());
}
#[test]
fn config_debug_never_prints_the_key() {
let s = format!("{:?}", host_config(Some(DEFAULT_STOP_TIMEOUT)));
assert!(s.contains("redacted"), "{s}");
assert!(!s.contains("lumen") && !s.contains(&format!("{:?}", &KEY[..4])), "{s}");
}
// ================================================================================================ properties
proptest! {
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
#[test]
fn parse_client_message_never_panics(data in proptest::collection::vec(any::<u8>(), 0..300)) {
let r = parse_client_message(&data);
prop_assert!(common::implemented(&r));
match r {
Ok(ClientControlMessage::Unknown { body_len, .. } | ClientControlMessage::InputRejected { body_len, .. }) => {
prop_assert_eq!(body_len + 4, data.len())
}
Ok(ClientControlMessage::LossStats(b) | ClientControlMessage::FrameStats(b)) => prop_assert_eq!(b.len() + 4, data.len()),
_ => {}
}
}
#[test]
fn typed_messages_round_trip(dx in any::<i16>(), dy in any::<i16>(), first in any::<u32>(), last in any::<u32>()) {
for m in [ClientMessage::Input(InputEvent::MouseMoveRel { dx, dy }), ClientMessage::InvalidateRefFrames { first, last }] {
let bytes = encode_client_message(&m).unwrap();
let want = match &m {
ClientMessage::Input(e) => ClientControlMessage::Input(e.clone()),
ClientMessage::InvalidateRefFrames { first, last } => ClientControlMessage::InvalidateRefFrames { first: *first, last: *last },
_ => unreachable!(),
};
prop_assert_eq!(parse_client_message(&bytes), Ok(want));
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
/// A connected control host fed arbitrary sealed plaintexts and arbitrary raw datagrams never panics.
#[test]
fn control_host_survives_arbitrary_input(
plains in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..16),
raws in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..16),
) {
let mut w = raw_session(Some(Duration::from_secs(1)), 15);
let t = at(w.now_ms);
for p in &plains {
w.client.send_plain(t, p);
}
w.run_for(100);
let h = w.host.h();
for (i, r) in raws.iter().enumerate() {
let t = at(w.now_ms + i as u64);
let res = h.handle_datagram(t, r);
prop_assert!(common::implemented(&res));
let _ = h.handle_timeout(t);
while h.poll_transmit(t).is_some() {}
while h.poll_event().is_some() {}
}
let messages = w.host.messages().len();
prop_assert!(messages <= plains.len());
}
}
-990
View File
@@ -1,990 +0,0 @@
//! The host side of ENet (`docs/PROTOCOL.md` 3.1, `enet::host`): our own [`EnetClient`] talks to an
//! [`EnetHostPeer`] over an in-memory wire with simulated time, loss, duplication and reordering; plus a scripted
//! client for the wire facts of stock ENet 1.3 (verify connect fields, session ids, what is acknowledged when).
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use common::wire::{Endpoint, Impair, Wire, at};
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, MAX_DATAGRAM_BYTES, NO_PEER_ID, encode_datagram, parse_datagram,
};
use domistream::enet::{
Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, EnetState,
MAX_PACKET_BYTES, MAX_SEND_QUEUE, parse_connect_request,
};
use domistream::{Error, Instant};
use proptest::prelude::*;
// ================================================================================================ setup
const HOST_PEER_ID: u16 = 7;
fn host_config() -> EnetHostConfig {
EnetHostConfig {
peer_id: HOST_PEER_ID,
channel_limit: 0x30,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn client_config() -> EnetConfig {
EnetConfig {
channel_count: 2,
mtu: 1400,
connect_data: 0x0000_1234,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
struct Client {
peer: EnetClient,
events: Vec<EnetEvent>,
count: usize,
}
impl Client {
fn new(config: EnetConfig, seed: u64) -> Self {
let peer = EnetClient::connect(config, Instant::ZERO, &mut common::SeqRng::new(seed)).unwrap();
Self { peer, events: Vec::new(), count: 0 }
}
fn drain(&mut self) {
while let Some(e) = self.peer.poll_event() {
self.count += usize::from(matches!(e, EnetEvent::Received { .. }));
self.events.push(e);
}
}
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
self.events
.iter()
.filter_map(|e| match e {
EnetEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
_ => None,
})
.collect()
}
}
impl Endpoint for Client {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.peer.poll_transmit(now)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
let _ = self.peer.handle_datagram(now, datagram);
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.peer.poll_timeout()
}
fn tick(&mut self, now: Instant) {
self.peer.handle_timeout(now).unwrap();
self.drain();
}
}
/// The caller of the host: one address, so one slot; the first datagram goes to `accept`.
struct Host {
config: EnetHostConfig,
peer: Option<EnetHostPeer>,
events: Vec<EnetHostEvent>,
refused: usize,
/// Every datagram the host sent, parsed.
sent: Vec<Datagram>,
count: usize,
}
impl Host {
fn new(config: EnetHostConfig) -> Self {
Self { config, peer: None, events: Vec::new(), refused: 0, sent: Vec::new(), count: 0 }
}
fn peer(&mut self) -> &mut EnetHostPeer {
self.peer.as_mut().expect("accepted")
}
fn drain(&mut self) {
if let Some(p) = self.peer.as_mut() {
while let Some(e) = p.poll_event() {
self.count += usize::from(matches!(e, EnetHostEvent::Received { .. }));
self.events.push(e);
}
}
}
fn received(&self, channel: u8) -> Vec<Vec<u8>> {
self.events
.iter()
.filter_map(|e| match e {
EnetHostEvent::Received { channel: c, data } if *c == channel => Some(data.clone()),
_ => None,
})
.collect()
}
fn connected(&self) -> bool {
self.peer.as_ref().is_some_and(|p| p.state() == EnetHostState::Connected)
}
}
impl Endpoint for Host {
fn transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let d = self.peer.as_mut()?.poll_transmit(now)?;
let mtu = self.peer.as_ref().unwrap().mtu();
assert!(d.len() <= mtu, "host datagram of {} over the MTU {mtu}", d.len());
self.sent.push(parse_datagram(&d).expect("the host's datagrams parse"));
Some(d)
}
fn receive(&mut self, now: Instant, datagram: &[u8]) {
match self.peer.as_mut() {
None => match EnetHostPeer::accept(self.config, now, datagram) {
Ok(p) => self.peer = Some(p),
Err(_) => self.refused += 1,
},
Some(p) => {
let _ = p.handle_datagram(now, datagram);
}
}
self.drain();
}
fn deadline(&self) -> Option<Instant> {
self.peer.as_ref()?.poll_timeout()
}
fn tick(&mut self, now: Instant) {
if let Some(p) = self.peer.as_mut() {
p.handle_timeout(now).unwrap();
}
self.drain();
}
}
type W = Wire<Client, Host>;
fn wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
wire_with(client_config(), host_config(), to_host, to_client, seed)
}
fn wire_with(client: EnetConfig, host: EnetHostConfig, to_host: Impair, to_client: Impair, seed: u64) -> W {
Wire::new(Client::new(client, seed), Host::new(host), to_host, to_client, seed)
}
/// Long timeouts for the loss tests: a command lost many times in a row must not end the connection.
fn lossy_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
let client = EnetConfig { timeout: Duration::from_secs(60), ..client_config() };
let host = EnetHostConfig { timeout: Duration::from_secs(60), ..host_config() };
wire_with(client, host, to_host, to_client, seed)
}
fn both_connected(w: &mut W) -> bool {
w.client.peer.state() == EnetState::Connected && w.host.connected()
}
fn connected_wire(to_host: Impair, to_client: Impair, seed: u64) -> W {
let mut w = wire(to_host, to_client, seed);
assert!(w.run_until(30_000, both_connected), "no connection (seed {seed})");
w
}
fn now(w: &W) -> Instant {
at(w.now_ms)
}
// ================================================================================================ scripted client
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
Command { acknowledge, channel_id, reliable_sequence, body }
}
fn connect_params(connect_id: u32) -> ConnectParams {
ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 2,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id,
}
}
fn connect_datagram(params: ConnectParams, data: u32) -> Vec<u8> {
encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(1),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Connect { params, data })],
})
.unwrap()
}
fn to_host(session_id: u8, sent_time: Option<u16>, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram { peer_id: HOST_PEER_ID, session_id, sent_time, commands }).unwrap()
}
fn transmitted(peer: &mut EnetHostPeer, t: Instant) -> Vec<Datagram> {
let mut out = Vec::new();
while let Some(d) = peer.poll_transmit(t) {
assert!(d.len() <= peer.mtu());
out.push(parse_datagram(&d).expect("host datagrams parse"));
assert!(out.len() < 10_000, "poll_transmit never ends");
}
out
}
fn events(peer: &mut EnetHostPeer) -> Vec<EnetHostEvent> {
let mut out = Vec::new();
while let Some(e) = peer.poll_event() {
out.push(e);
assert!(out.len() < 100_000);
}
out
}
fn verify_of(ds: &[Datagram]) -> (Command, ConnectParams) {
ds.iter()
.flat_map(|d| &d.commands)
.find_map(|c| match &c.body {
CommandBody::VerifyConnect(p) => Some((c.clone(), *p)),
_ => None,
})
.expect("a verify connect")
}
/// A host that accepted a hand-built connect and had its verify acknowledged at 2 ms.
fn scripted_connected() -> EnetHostPeer {
let mut h = EnetHostPeer::accept(host_config(), at(1), &connect_datagram(connect_params(0xABCD), 9)).unwrap();
let sent = transmitted(&mut h, at(1));
let (v, _) = verify_of(&sent);
let ack = cmd(
false,
0xFF,
v.reliable_sequence,
CommandBody::Acknowledge {
received_reliable_sequence: v.reliable_sequence,
received_sent_time: sent[0].sent_time.unwrap(),
},
);
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack])).unwrap();
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 9 }]);
assert_eq!(h.state(), EnetHostState::Connected);
h
}
// ================================================================================================ handshake
#[test]
fn handshake_over_a_clean_wire() {
let mut w = wire(Impair::clean(5), Impair::clean(5), 1);
assert!(w.run_until(1_000, both_connected));
assert_eq!(w.host.events, vec![EnetHostEvent::Connected { data: client_config().connect_data }]);
assert_eq!(w.client.events, vec![EnetEvent::Connected]);
let p = w.host.peer();
assert_eq!(p.channel_count(), 2, "min(client 2, limit 0x30)");
assert_eq!(p.mtu(), 1400);
assert_eq!(w.host.refused, 0);
// Every host datagram is addressed to the client's peer id (0) after the handshake.
assert!(w.host.sent.iter().all(|d| d.peer_id == 0));
}
#[test]
fn verify_connect_fields() {
let params = connect_params(0xDEAD_BEEF);
let d = connect_datagram(params, 0x55);
assert_eq!(parse_connect_request(&d).unwrap().params, params);
assert_eq!(parse_connect_request(&d).unwrap().data, 0x55);
let cfg = EnetHostConfig { mtu: 1200, ..host_config() };
let mut h = EnetHostPeer::accept(cfg, at(3), &d).unwrap();
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
assert_eq!(h.connect_id(), 0xDEAD_BEEF);
assert!(events(&mut h).is_empty(), "connected only once the verify is acknowledged");
let sent = transmitted(&mut h, at(3));
assert_eq!(sent.len(), 1);
let dg = &sent[0];
assert_eq!(dg.peer_id, params.outgoing_peer_id, "addressed to the client's peer id");
assert_eq!(dg.session_id, 0);
assert_eq!(dg.sent_time, Some(3));
// Stock ENet answers a connect with the verify only: the verify itself retires the client's connect.
assert_eq!(dg.commands.len(), 1, "{:?}", dg.commands);
let (c, v) = verify_of(&sent);
assert!(c.acknowledge, "verify connect is reliable");
assert_eq!(c.channel_id, 0xFF);
assert_eq!(c.reliable_sequence, 1);
assert_eq!(v.outgoing_peer_id, HOST_PEER_ID);
assert_eq!(v.connect_id, 0xDEAD_BEEF);
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (0, 0));
assert_eq!(v.mtu, 1200, "min(client, host)");
assert_eq!(v.window_size, 65536);
assert_eq!(v.channel_count, 2);
assert_eq!((v.incoming_bandwidth, v.outgoing_bandwidth), (0, 0), "our bandwidth: unlimited");
assert_eq!(
(v.packet_throttle_interval, v.packet_throttle_acceleration, v.packet_throttle_deceleration),
(5000, 2, 2),
"throttle echoed"
);
assert_eq!(h.mtu(), 1200);
}
#[test]
fn verify_clamps_what_the_client_offers() {
for (mtu, window, channels, want_mtu, want_window, want_channels) in [
(100u32, 1000u32, 200u32, 576u32, 4096u32, 0x30u32),
(9000, 1 << 20, 1, 1400, 65536, 1),
(576, 4096, 255, 576, 4096, 0x30),
(u32::MAX, 0, 0x30, 1400, 4096, 0x30),
] {
let p = ConnectParams { mtu, window_size: window, channel_count: channels, ..connect_params(1) };
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
let (_, v) = verify_of(&transmitted(&mut h, at(0)));
assert_eq!((v.mtu, v.window_size, v.channel_count), (want_mtu, want_window, want_channels), "{p:?}");
assert_eq!(u32::from(h.channel_count()), want_channels);
}
}
#[test]
fn session_ids_follow_stock_enet() {
// (client's incoming, outgoing) -> (verify incoming = host's outgoing, verify outgoing = host's incoming).
for (inc, out, want_in, want_out) in [(0xFFu8, 0xFFu8, 0u8, 0u8), (1, 2, 2, 3), (3, 0, 0, 1), (2, 2, 3, 3)] {
let p = ConnectParams { incoming_session_id: inc, outgoing_session_id: out, ..connect_params(5) };
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)).unwrap();
let sent = transmitted(&mut h, at(0));
let (c, v) = verify_of(&sent);
assert_eq!((v.incoming_session_id, v.outgoing_session_id), (want_in, want_out), "connect {inc}/{out}");
assert_eq!(sent[0].session_id, want_in, "the host sends with the session the client takes as incoming");
// The client must send with the host's incoming session id; anything else is ignored.
let ack = cmd(
false,
0xFF,
1,
CommandBody::Acknowledge { received_reliable_sequence: c.reliable_sequence, received_sent_time: 0 },
);
let wrong = (want_out + 1) & 3;
h.handle_datagram(at(1), &to_host(wrong, Some(1), vec![ack.clone()])).unwrap();
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect, "wrong session {wrong} ignored");
h.handle_datagram(at(1), &to_host(want_out, Some(1), vec![ack])).unwrap();
assert_eq!(h.state(), EnetHostState::Connected);
assert_eq!(events(&mut h), vec![EnetHostEvent::Connected { data: 0 }]);
}
}
#[test]
fn accept_refuses_what_is_not_a_connect() {
let good = connect_datagram(connect_params(1), 0);
assert!(EnetHostPeer::accept(host_config(), at(0), &good).is_ok());
assert!(EnetHostPeer::accept(host_config(), at(0), &[]).is_err());
assert!(EnetHostPeer::accept(host_config(), at(0), &[0xFF; 3]).is_err());
let ping = encode_datagram(&Datagram {
peer_id: NO_PEER_ID,
session_id: 0,
sent_time: Some(0),
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
})
.unwrap();
assert_err!(EnetHostPeer::accept(host_config(), at(0), &ping), Error::UnexpectedValue { .. }, "no connect");
let mut addressed = parse_datagram(&good).unwrap();
addressed.peer_id = HOST_PEER_ID;
assert_err!(
EnetHostPeer::accept(host_config(), at(0), &encode_datagram(&addressed).unwrap()),
Error::UnexpectedValue { .. },
"a connect addressed to a peer"
);
for channels in [0u32, 256, u32::MAX] {
let p = ConnectParams { channel_count: channels, ..connect_params(1) };
assert_err!(
EnetHostPeer::accept(host_config(), at(0), &connect_datagram(p, 0)),
Error::UnexpectedValue { .. },
"{channels} channels"
);
assert!(parse_connect_request(&connect_datagram(p, 0)).is_err());
}
for bad in [
EnetHostConfig { mtu: 575, ..host_config() },
EnetHostConfig { mtu: 4097, ..host_config() },
EnetHostConfig { channel_limit: 0, ..host_config() },
EnetHostConfig { peer_id: NO_PEER_ID, ..host_config() },
EnetHostConfig { peer_id: 0xFFFF, ..host_config() },
] {
assert_err!(EnetHostPeer::accept(bad, at(0), &good), Error::Malformed { .. }, "{bad:?}");
}
}
#[test]
fn repeated_connect_is_ignored_and_a_new_connect_id_is_visible() {
let d = connect_datagram(connect_params(77), 0);
let mut h = EnetHostPeer::accept(host_config(), at(0), &d).unwrap();
let first = transmitted(&mut h, at(0));
assert_eq!(first.len(), 1);
// The client's connect retransmitted: no second verify, no new state.
assert_eq!(h.handle_datagram(at(5), &d), Ok(()));
assert!(transmitted(&mut h, at(5)).is_empty());
assert_eq!(h.state(), EnetHostState::AcknowledgingConnect);
// A client that restarted: the caller sees another connect id and replaces the peer.
let again = connect_datagram(connect_params(78), 0);
assert_eq!(h.handle_datagram(at(6), &again), Ok(()));
assert_eq!(h.connect_id(), 77);
assert_ne!(parse_connect_request(&again).unwrap().params.connect_id, h.connect_id());
}
#[test]
fn data_before_the_verify_ack_is_not_taken() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
let sent = transmitted(&mut h, at(0));
let (v, _) = verify_of(&sent);
let data = cmd(true, 0, 1, CommandBody::SendReliable(b"early".to_vec()));
h.handle_datagram(at(1), &to_host(0, Some(1), vec![data.clone()])).unwrap();
assert!(events(&mut h).is_empty());
assert!(
!transmitted(&mut h, at(1))
.iter()
.flat_map(|d| &d.commands)
.any(|c| matches!(c.body, CommandBody::Acknowledge { .. })),
"not acknowledged, so the client sends it again"
);
let ack = cmd(
false,
0xFF,
1,
CommandBody::Acknowledge { received_reliable_sequence: v.reliable_sequence, received_sent_time: 0 },
);
h.handle_datagram(at(2), &to_host(0, Some(2), vec![ack, data])).unwrap();
assert_eq!(
events(&mut h),
vec![EnetHostEvent::Connected { data: 0 }, EnetHostEvent::Received { channel: 0, data: b"early".to_vec() }]
);
}
#[test]
fn lost_verify_is_retransmitted() {
let mut w = wire(Impair::clean(5), Impair::clean(5), 2);
w.to_client.cut = true;
w.run_for(50);
assert!(w.host.peer.is_some() && !both_connected(&mut w));
w.to_client.cut = false;
assert!(w.run_until(5_000, both_connected), "the verify is sent again");
}
#[test]
fn verify_never_acknowledged_times_out() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
assert_eq!(transmitted(&mut h, at(0)).len(), 1, "the first verify");
let mut verifies = 0;
let mut guard = 0;
while h.state() != EnetHostState::Disconnected {
let t = h.poll_timeout().expect("a deadline while waiting");
assert!(t <= at(host_config().timeout.as_millis() as u64 + 1), "no timeout by {t:?}");
h.handle_timeout(t).unwrap();
verifies += transmitted(&mut h, t)
.iter()
.flat_map(|d| &d.commands)
.filter(|c| matches!(c.body, CommandBody::VerifyConnect(_)))
.count();
guard += 1;
assert!(guard < 10_000);
}
assert!(verifies >= 3, "the verify was retransmitted ({verifies})");
assert_eq!(events(&mut h), vec![EnetHostEvent::TimedOut]);
assert_eq!(h.poll_timeout(), None);
assert_err!(h.handle_datagram(at(20_000), &[0x00, 0x07]), Error::Closed);
}
// ================================================================================================ data
#[test]
fn reliable_both_ways_in_order() {
let mut w = connected_wire(Impair::clean(3), Impair::clean(3), 3);
let t = now(&w);
for i in 0..50u32 {
w.client.peer.send(t, (i % 2) as u8, Delivery::Reliable, &i.to_le_bytes()).unwrap();
w.host.peer().send(t, (i % 2) as u8, Delivery::Reliable, &(1000 + i).to_le_bytes()).unwrap();
}
w.run_for(1_000);
for ch in 0..2u8 {
let want: Vec<Vec<u8>> =
(0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| i.to_le_bytes().to_vec()).collect();
assert_eq!(w.host.received(ch), want, "host, channel {ch}");
let want: Vec<Vec<u8>> =
(0..50u32).filter(|i| i % 2 == u32::from(ch)).map(|i| (1000 + i).to_le_bytes().to_vec()).collect();
assert_eq!(w.client.received(ch), want, "client, channel {ch}");
}
}
#[test]
fn large_packets_fragment_both_ways() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 4);
let up: Vec<u8> = (0..5000u32).map(|i| (i * 7) as u8).collect();
let down: Vec<u8> = (0..MAX_PACKET_BYTES as u32).map(|i| (i * 13 + 1) as u8).collect();
let t = now(&w);
w.client.peer.send(t, 1, Delivery::Reliable, &up).unwrap();
w.host.peer().send(t, 0, Delivery::Reliable, &down).unwrap();
w.run_for(2_000);
assert_eq!(w.host.received(1), vec![up]);
assert_eq!(w.client.received(0), vec![down]);
let frags =
w.host.sent.iter().flat_map(|d| &d.commands).filter(|c| matches!(c.body, CommandBody::SendFragment(_))).count();
assert!(frags > 40, "the host fragmented its 64 KiB packet ({frags})");
}
#[test]
fn unreliable_and_unsequenced_from_the_client() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 5);
let t = now(&w);
for i in 0..3u8 {
w.client.peer.send(t, 0, Delivery::Unreliable, &[b'u', i]).unwrap();
w.client.peer.send(t, 1, Delivery::Unsequenced, &[b's', i]).unwrap();
}
w.run_for(200);
assert_eq!(w.host.received(0), vec![vec![b'u', 0], vec![b'u', 1], vec![b'u', 2]]);
assert_eq!(w.host.received(1), vec![vec![b's', 0], vec![b's', 1], vec![b's', 2]]);
}
#[test]
fn unreliable_from_the_host() {
let mut w = connected_wire(Impair::clean(2), Impair::clean(2), 6);
let t = now(&w);
w.host.peer().send(t, 0, Delivery::Unreliable, b"u1").unwrap();
w.host.peer().send(t, 0, Delivery::Unsequenced, b"s1").unwrap();
w.run_for(100);
assert_eq!(w.client.received(0), vec![b"u1".to_vec(), b"s1".to_vec()]);
}
#[test]
fn duplicated_and_stale_datagrams_are_delivered_once() {
let mut h = scripted_connected();
let unseq = |group: u16, data: &[u8]| {
cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: group, data: data.to_vec() })
};
let unrel = |seq: u16, data: &[u8]| {
cmd(false, 0, 0, CommandBody::SendUnreliable { unreliable_sequence: seq, data: data.to_vec() })
};
let feed = |h: &mut EnetHostPeer, c: Command| h.handle_datagram(at(10), &to_host(0, Some(10), vec![c])).unwrap();
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unseq(2, b"b"));
feed(&mut h, unseq(1, b"a"));
feed(&mut h, unrel(5, b"x"));
feed(&mut h, unrel(5, b"x"));
feed(&mut h, unrel(4, b"old"));
feed(&mut h, unrel(6, b"y"));
let got: Vec<Vec<u8>> = events(&mut h)
.into_iter()
.map(|e| match e {
EnetHostEvent::Received { data, .. } => data,
other => panic!("{other:?}"),
})
.collect();
assert_eq!(got, vec![b"a".to_vec(), b"b".to_vec(), b"x".to_vec(), b"y".to_vec()]);
// Far ahead of the unsequenced window: dropped.
feed(&mut h, unseq(40_000, b"far"));
assert!(events(&mut h).is_empty());
// The window moves forward with groups within reach.
feed(&mut h, unseq(3000, b"c"));
feed(&mut h, unseq(3000, b"c"));
feed(&mut h, unseq(2, b"b"));
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"c".to_vec() }]);
}
#[test]
fn reliable_from_the_client_reordered_and_duplicated() {
let mut h = scripted_connected();
let rel = |seq: u16, data: &[u8]| cmd(true, 0, seq, CommandBody::SendReliable(data.to_vec()));
h.handle_datagram(at(10), &to_host(0, Some(10), vec![rel(3, b"3"), rel(2, b"2")])).unwrap();
assert!(events(&mut h).is_empty());
h.handle_datagram(at(11), &to_host(0, Some(11), vec![rel(1, b"1"), rel(2, b"2")])).unwrap();
h.handle_datagram(at(12), &to_host(0, Some(12), vec![rel(1, b"1")])).unwrap();
let got: Vec<EnetHostEvent> = events(&mut h);
assert_eq!(
got,
[b"1", b"2", b"3"].iter().map(|d| EnetHostEvent::Received { channel: 0, data: d.to_vec() }).collect::<Vec<_>>()
);
let acks: Vec<(u16, u16)> = transmitted(&mut h, at(12))
.iter()
.flat_map(|d| d.commands.clone())
.filter_map(|c| match c.body {
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
Some((received_reliable_sequence, received_sent_time))
}
_ => None,
})
.collect();
for want in [(3, 10), (2, 10), (1, 11), (2, 11), (1, 12)] {
assert!(acks.contains(&want), "ack {want:?} (with the datagram's sent time) in {acks:?}");
}
// Far future and channels outside the grant: never delivered.
h.handle_datagram(at(13), &to_host(0, Some(13), vec![rel(40_000, b"evil")])).unwrap();
let _ = h.handle_datagram(
at(13),
&to_host(0, Some(13), vec![cmd(true, 9, 1, CommandBody::SendReliable(b"ch9".to_vec()))]),
);
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn acknowledged_commands_need_the_sent_time() {
// Stock ENet: a command that wants an acknowledgement in a datagram without sent time is handled but not
// acknowledged, and the rest of the datagram is skipped.
let mut h = scripted_connected();
let d = to_host(
0,
None,
vec![
cmd(true, 0, 1, CommandBody::SendReliable(b"a".to_vec())),
cmd(true, 0, 2, CommandBody::SendReliable(b"b".to_vec())),
],
);
h.handle_datagram(at(10), &d).unwrap();
assert_eq!(events(&mut h), vec![EnetHostEvent::Received { channel: 0, data: b"a".to_vec() }]);
assert!(
!transmitted(&mut h, at(10))
.iter()
.flat_map(|d| &d.commands)
.any(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
);
}
#[test]
fn connection_commands_are_acknowledged() {
let mut h = scripted_connected();
let d = to_host(
0,
Some(0x0102),
vec![
cmd(true, 0xFF, 2, CommandBody::Ping),
cmd(true, 0xFF, 3, CommandBody::BandwidthLimit { incoming: 1_000_000, outgoing: 2_000_000 }),
cmd(true, 0xFF, 4, CommandBody::ThrottleConfigure { interval: 1000, acceleration: 3, deceleration: 4 }),
],
);
h.handle_datagram(at(10), &d).unwrap();
let acks: Vec<Command> = transmitted(&mut h, at(10))
.into_iter()
.flat_map(|d| d.commands)
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
.collect();
for seq in [2u16, 3, 4] {
assert!(
acks.iter().any(|c| c.channel_id == 0xFF
&& c.body == CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: 0x0102 }),
"ack of {seq} in {acks:?}"
);
}
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn reliable_sequence_wraps_at_0xffff() {
let mut w = connected_wire(Impair::clean(1), Impair::clean(1), 7);
let total = 66_000u32;
let mut sent = 0u32;
while sent < total {
let t = now(&w);
for _ in 0..200 {
if sent < total {
w.client.peer.send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
w.host.peer().send(t, 0, Delivery::Reliable, &sent.to_le_bytes()).unwrap();
sent += 1;
}
}
let want = sent as usize;
assert!(w.run_until(w.now_ms + 5_000, |w| w.host.count >= want && w.client.count >= want));
}
let got = w.host.received(0);
assert_eq!(got.len(), total as usize);
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "host order");
let got = w.client.received(0);
assert_eq!(got.len(), total as usize);
assert!(got.iter().enumerate().all(|(i, d)| *d == (i as u32).to_le_bytes()), "client order");
}
// ================================================================================================ loss and timers
/// Sends `n` reliable messages each way, a few at a time, over a lossy wire; returns what arrived.
fn exchange(w: &mut W, n: u32) -> (Vec<Vec<u8>>, Vec<Vec<u8>>) {
let mut i = 0;
while i < n {
let t = now(w);
for _ in 0..5 {
if i < n {
let _ = w.client.peer.send(t, 0, Delivery::Reliable, &i.to_le_bytes());
if let Some(p) = w.host.peer.as_mut() {
let _ = p.send(t, 0, Delivery::Reliable, &(i + 10_000).to_le_bytes());
}
i += 1;
}
}
w.run_for(30);
}
let n = n as usize;
w.run_until(w.now_ms + 120_000, |w| w.host.count >= n && w.client.count >= n);
(w.host.received(0), w.client.received(0))
}
#[test]
fn retransmission_under_loss_delivers_everything_in_order() {
let mut w = lossy_wire(Impair::lossy(200, 10), Impair::lossy(200, 10), 8);
assert!(w.run_until(60_000, both_connected));
let (up, down) = exchange(&mut w, 200);
assert_eq!(up, (0..200u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
assert_eq!(down, (0..200u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
assert!(w.to_host.lost > 0 && w.to_client.lost > 0, "the wire did lose datagrams");
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
assert!(w.host.peer().round_trip_time().is_some());
}
#[test]
fn idle_connection_stays_up() {
let mut w = connected_wire(Impair::clean(20), Impair::clean(20), 9);
w.run_for(60_000);
assert!(both_connected(&mut w));
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
}
#[test]
fn the_host_pings_a_quiet_client() {
// A client that never pings by itself (only acknowledges): the host's pings keep the connection checked.
let quiet = EnetConfig { ping_interval: Duration::from_secs(3600), ..client_config() };
let mut w = wire_with(quiet, host_config(), Impair::clean(20), Impair::clean(20), 13);
assert!(w.run_until(1_000, both_connected));
let start = w.host.sent.len();
w.run_for(30_000);
assert!(both_connected(&mut w));
let pings = w.host.sent[start..]
.iter()
.flat_map(|d| &d.commands)
.filter(|c| c.body == CommandBody::Ping && c.acknowledge)
.count();
assert!(pings >= 30, "the host pings an idle client ({pings})");
// And when nothing comes back at all, its ping times out.
let mut h = scripted_connected();
let t = h.poll_timeout().expect("a ping deadline");
assert!(t <= at(2 + host_config().ping_interval.as_millis() as u64));
h.handle_timeout(t).unwrap();
assert!(
transmitted(&mut h, t)
.iter()
.flat_map(|d| &d.commands)
.any(|c| c.body == CommandBody::Ping && c.channel_id == 0xFF)
);
}
#[test]
fn vanished_client_times_out() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 10);
let cut_at = w.now_ms;
w.to_host.cut = true;
let limit =
cut_at + host_config().ping_interval.as_millis() as u64 + host_config().timeout.as_millis() as u64 + 1_000;
assert!(w.run_until(limit, |w| w.host.events.contains(&EnetHostEvent::TimedOut)), "no timeout by {limit} ms");
let earliest = cut_at + host_config().timeout.as_millis() as u64 - host_config().ping_interval.as_millis() as u64;
assert!(w.now_ms >= earliest, "not before the timeout");
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
assert_eq!(w.host.peer().poll_timeout(), None);
let t = now(&w);
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"x"), Error::State { .. });
}
// ================================================================================================ disconnect
#[test]
fn client_disconnect_reaches_the_host() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 11);
let t = now(&w);
w.client.peer.disconnect(t, 77).unwrap();
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.events.contains(&EnetHostEvent::Disconnected { data: 77 })));
assert_eq!(w.host.peer().state(), EnetHostState::Disconnected);
assert!(
w.run_until(w.now_ms + 2_000, |w| w.client.peer.state() == EnetState::Disconnected),
"the host acknowledged the disconnect after closing"
);
assert!(!w.client.events.contains(&EnetEvent::TimedOut));
}
#[test]
fn host_disconnect_reaches_the_client() {
let mut w = connected_wire(Impair::clean(5), Impair::clean(5), 12);
let t = now(&w);
w.host.peer().disconnect(t, 42).unwrap();
assert_eq!(w.host.peer().state(), EnetHostState::Disconnecting);
assert_err!(w.host.peer().disconnect(t, 1), Error::Closed);
assert_err!(w.host.peer().send(t, 0, Delivery::Reliable, b"late"), Error::State { .. });
assert!(w.run_until(w.now_ms + 2_000, |w| w.client.events.contains(&EnetEvent::Disconnected { data: 42 })));
assert!(w.run_until(w.now_ms + 2_000, |w| w.host.peer.as_ref().unwrap().state() == EnetHostState::Disconnected));
assert!(!w.host.events.contains(&EnetHostEvent::TimedOut));
}
#[test]
fn disconnect_during_the_handshake() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
let _ = transmitted(&mut h, at(0));
h.handle_datagram(at(1), &to_host(0, Some(1), vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 5 })]))
.unwrap();
assert_eq!(h.state(), EnetHostState::Disconnected);
assert_eq!(events(&mut h), vec![EnetHostEvent::Disconnected { data: 5 }]);
}
// ================================================================================================ rules
#[test]
fn send_rules() {
let mut h = EnetHostPeer::accept(host_config(), at(0), &connect_datagram(connect_params(3), 0)).unwrap();
assert_err!(h.send(at(0), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before the verify is acknowledged");
let mut h = scripted_connected();
assert_err!(h.send(at(3), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
assert_too_large!(
h.send(at(3), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]),
MAX_PACKET_BYTES,
MAX_PACKET_BYTES + 1
);
assert!(matches!(h.send(at(3), 0, Delivery::Unsequenced, &[0; 1500]), Err(Error::TooLarge { .. })));
for i in 0..MAX_SEND_QUEUE {
h.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
}
match h.send(at(3), 0, Delivery::Reliable, b"one too many") {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
other => panic!("{other:?}"),
}
// The queue drains within the MTU, and each datagram parses.
let sent = transmitted(&mut h, at(4));
assert!(!sent.is_empty());
}
#[test]
fn garbage_never_changes_state() {
let mut h = scripted_connected();
for bad in [&[][..], &[0x00][..], &[0x40, 0x07, 0x85, 0xFF, 0, 1][..], &[0x00, 0x07, 0x8F, 0, 0, 0][..]] {
assert!(h.handle_datagram(at(5), bad).is_err(), "{bad:?}");
assert_eq!(h.state(), EnetHostState::Connected);
}
assert_too_large!(
h.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
MAX_DATAGRAM_BYTES,
MAX_DATAGRAM_BYTES + 1
);
// Another peer id: dropped without error.
let other = encode_datagram(&Datagram {
peer_id: HOST_PEER_ID + 1,
session_id: 0,
sent_time: Some(1),
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(b"not for us".to_vec()))],
})
.unwrap();
assert_eq!(h.handle_datagram(at(5), &other), Ok(()));
assert!(events(&mut h).is_empty());
assert_eq!(h.state(), EnetHostState::Connected);
}
#[test]
fn fragments_with_lying_lengths() {
let frag = |count: u32, number: u32, total: u32, offset: u32, len: usize| {
cmd(
true,
0,
1,
CommandBody::SendFragment(domistream::enet::protocol::Fragment {
start_sequence: 1u16.wrapping_sub(number as u16),
fragment_count: count,
fragment_number: number,
total_length: total,
fragment_offset: offset,
data: vec![0; len],
}),
)
};
let mut h = scripted_connected();
assert_too_large!(
h.handle_datagram(at(5), &to_host(0, Some(5), vec![frag(2, 0, MAX_PACKET_BYTES as u32 + 1, 0, 100)])),
MAX_PACKET_BYTES,
MAX_PACKET_BYTES + 1
);
for f in [
frag(0, 0, 10, 0, 10),
frag(2, 2, 20, 0, 10),
frag(2, 0, 20, 15, 10),
frag(2, 0, 5, 0, 10),
frag(u32::MAX, 0, 100, 0, 10),
frag(2, 0, u32::MAX, 0, 10),
] {
let mut h = scripted_connected();
let _ = h.handle_datagram(at(5), &to_host(0, Some(5), vec![f.clone()]));
assert!(events(&mut h).is_empty(), "{f:?}");
assert_eq!(h.state(), EnetHostState::Connected);
}
}
// ================================================================================================ properties
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
/// Arbitrary bytes never panic `accept`, and what it accepts it answers with datagrams that parse.
#[test]
fn accept_never_panics(data in proptest::collection::vec(any::<u8>(), 0..200)) {
let r = EnetHostPeer::accept(host_config(), at(0), &data);
prop_assert!(common::implemented(&r));
if let Ok(mut h) = r {
prop_assert!(!transmitted(&mut h, at(0)).is_empty());
}
}
/// A connected host fed arbitrary datagrams (raw, or with our header so they reach the command loop) never
/// panics; what it delivers fits the cap; what it sends parses and fits the MTU.
#[test]
fn host_survives_arbitrary_datagrams(
datagrams in proptest::collection::vec((any::<bool>(), proptest::collection::vec(any::<u8>(), 0..200)), 1..20)
) {
let mut h = scripted_connected();
for (i, (headed, d)) in datagrams.into_iter().enumerate() {
let t = at(10 + i as u64 * 50);
let bytes = if headed {
let mut b = vec![0x80, HOST_PEER_ID as u8, 0, 10];
b.extend_from_slice(&d);
b
} else {
d
};
let r = h.handle_datagram(t, &bytes);
prop_assert!(common::implemented(&r));
let _ = h.handle_timeout(t);
let _ = transmitted(&mut h, t);
for e in events(&mut h) {
if let EnetHostEvent::Received { data, .. } = e {
prop_assert!(data.len() <= MAX_PACKET_BYTES);
}
}
}
}
}
proptest! {
#![proptest_config(ProptestConfig { cases: 24, ..ProptestConfig::default() })]
/// Random loss, duplication, reordering and latency: the connection comes up and every reliable message
/// arrives exactly once, in order, both ways.
#[test]
fn random_loss_patterns_deliver_reliable_messages_in_order(
seed in any::<u64>(),
loss in 0u32..300,
duplicate in 0u32..150,
reorder in 0u32..400,
latency in 1u64..60,
) {
let impair = Impair { loss, duplicate, reorder, reorder_ms: 40, latency_ms: latency };
let mut w = lossy_wire(impair, impair, seed);
prop_assert!(w.run_until(60_000, both_connected), "no connection");
let (up, down) = exchange(&mut w, 40);
prop_assert_eq!(up, (0..40u32).map(|i| i.to_le_bytes().to_vec()).collect::<Vec<_>>());
prop_assert_eq!(down, (0..40u32).map(|i| (i + 10_000).to_le_bytes().to_vec()).collect::<Vec<_>>());
}
}
-825
View File
@@ -1,825 +0,0 @@
//! The video packetizer, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7), checked against the client half: every frame
//! goes through the crate's own `VideoDepacketizer` and must come out identical and in order, also with up to `m`
//! packets of every block lost, reordered or duplicated; with more lost, the frame is reported lost, never corrupt.
//! Fixed vectors check one small frame byte by byte against the field table of 5.2, and the parity against an
//! independent GF(2^8) encoder with the Cauchy matrix of 5.3.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use core::time::Duration;
use std::collections::BTreeMap;
use common::{SeqRng, gf};
use domistream::fec::parity_count;
use domistream::video::packet::{
FRAME_HEADER_LEN, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header, parse_video_packet,
};
use domistream::video::packetizer::{
EncodedFrame, MAX_DATA_SHARDS_PER_FRAME, VideoPacketizer, VideoPacketizerConfig, VideoPacketizerStats,
plan_fec_blocks, write_frame_header,
};
use domistream::video::{
ENCRYPTION_PREFIX_LEN, FrameType, MAX_FRAME_BYTES, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent,
VideoFrame,
};
use domistream::{Error, Instant};
use proptest::prelude::*;
const KEY: [u8; 16] = *b"video-pack-key!!";
fn config(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizerConfig {
VideoPacketizerConfig {
packet_size,
fec_percentage: pct,
min_required_fec_packets: min,
cipher: encrypt.then(|| VideoCipher::new(KEY)),
first_sequence,
}
}
fn sender(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizer {
VideoPacketizer::new(config(packet_size, pct, min, encrypt, first_sequence)).expect("VideoPacketizer::new")
}
fn receiver(packet_size: u16, encrypt: bool) -> VideoDepacketizer {
VideoDepacketizer::new(VideoConfig {
packet_size,
cipher: encrypt.then(|| VideoCipher::new(KEY)),
frame_timeout: Duration::from_millis(50),
})
.expect("VideoDepacketizer::new")
}
/// A bitstream of exactly `len` bytes: a start code, then random bytes, every third frame with a zero tail (the
/// frame header's last-payload length, not the content, says where the frame ends).
fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
let mut b = rng.bytes(len);
for (dst, src) in b.iter_mut().zip([0u8, 0, 0, 1, 0x65]) {
*dst = src;
}
if rng.below(3) == 0 {
let tail = rng.below(len / 2 + 1);
for x in &mut b[len - tail..] {
*x = 0;
}
}
b
}
/// One frame as sent.
#[derive(Clone, Debug)]
struct Sent {
index: u32,
frame_type: FrameType,
latency: u16,
timestamp: u32,
bitstream: Vec<u8>,
datagrams: Vec<Vec<u8>>,
}
fn send_bytes(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, bitstream: Vec<u8>) -> Sent {
let frame_type = [FrameType::Predicted, FrameType::Key, FrameType::Recovery][rng.below(3)];
let latency = rng.below(65_536) as u16;
let timestamp = rng.next_u64() as u32;
let frame = EncodedFrame {
frame_index: index,
frame_type,
rtp_timestamp: timestamp,
processing_latency: latency,
bitstream: &bitstream,
};
let datagrams = tx.packetize(&frame).expect("packetize");
Sent { index, frame_type, latency, timestamp, bitstream, datagrams }
}
fn send(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, len: usize) -> Sent {
let b = bitstream(rng, len);
send_bytes(tx, rng, index, b)
}
fn plain(datagram: &[u8], encrypt: bool) -> Vec<u8> {
if encrypt { VideoCipher::new(KEY).decrypt(datagram).expect("decrypt our own datagram") } else { datagram.to_vec() }
}
/// A datagram's place in its frame, read from its plaintext.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Place {
block: u8,
shard: u16,
k: u16,
m: u16,
}
fn place(datagram: &[u8], encrypt: bool) -> Place {
let bytes = plain(datagram, encrypt);
let p = parse_video_packet(&bytes).expect("our own datagram parses");
let k = p.nv.fec.data_shards;
let m = parity_count(usize::from(k), p.nv.fec.fec_percentage).expect("consistent FEC fields") as u16;
Place { block: p.nv.fec.block_index, shard: p.nv.fec.shard_index, k, m }
}
/// Datagram positions of each block, and the block's parity count.
fn blocks_of(sent: &Sent, encrypt: bool) -> BTreeMap<u8, (Vec<usize>, usize)> {
let mut out: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
for (i, d) in sent.datagrams.iter().enumerate() {
let p = place(d, encrypt);
let e = out.entry(p.block).or_insert_with(|| (Vec::new(), usize::from(p.m)));
e.0.push(i);
}
out
}
/// The frame's datagrams with, in every block, a random subset of `extra(m)` lost (`extra = 0` keeps all).
fn with_loss(rng: &mut SeqRng, sent: &Sent, encrypt: bool, lose: impl Fn(&mut SeqRng, usize) -> usize) -> Vec<Vec<u8>> {
let mut keep = vec![true; sent.datagrams.len()];
for (positions, m) in blocks_of(sent, encrypt).values() {
let n = lose(rng, *m).min(positions.len());
for i in rng.subset(positions.len(), n) {
keep[positions[i]] = false;
}
}
sent.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()).collect()
}
#[derive(Debug, Default)]
struct Out {
frames: Vec<VideoFrame>,
lost: Vec<(u32, u32)>,
}
fn drain(rx: &mut VideoDepacketizer, out: &mut Out) {
while let Some(e) = rx.poll_event() {
match e {
VideoEvent::Frame(f) => out.frames.push(f),
VideoEvent::FrameLost { first, last } => out.lost.push((first, last)),
}
}
}
fn receive(rx: &mut VideoDepacketizer, datagrams: &[Vec<u8>]) -> Out {
let mut now = 1_000_000u64;
let mut out = Out::default();
for d in datagrams {
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
now += 10;
drain(rx, &mut out);
}
for _ in 0..64 {
now += 10_000_000;
rx.handle_timeout(Instant::from_micros(now)).unwrap();
drain(rx, &mut out);
if rx.poll_timeout().is_none() {
break;
}
}
out
}
/// Every frame not in `lost` came out identical and in order; every frame in `lost` is in a FrameLost range.
fn check(sent: &[Sent], lost: &[u32], out: &Out) {
let want: Vec<&Sent> = sent.iter().filter(|s| !lost.contains(&s.index)).collect();
assert_eq!(
out.frames.iter().map(|f| f.frame_index).collect::<Vec<_>>(),
want.iter().map(|s| s.index).collect::<Vec<_>>(),
"frames delivered (lost ranges {:?})",
out.lost
);
for (f, s) in out.frames.iter().zip(&want) {
assert!(
f.bitstream == s.bitstream,
"frame {} differs: {} bytes, want {}",
s.index,
f.bitstream.len(),
s.bitstream.len()
);
assert_eq!(f.header.header_type, 0x01, "frame {} header type", s.index);
assert_eq!(f.header.frame_type, s.frame_type, "frame {} type", s.index);
assert_eq!(f.header.processing_latency, s.latency, "frame {} latency", s.index);
assert_eq!(f.rtp_timestamp, s.timestamp, "frame {} timestamp", s.index);
}
for &l in lost {
assert!(
out.lost.iter().any(|&(a, b)| l.wrapping_sub(a) <= b.wrapping_sub(a)),
"frame {l} was not reported lost: {:?}",
out.lost
);
}
}
/// Checks every field of every datagram of a frame against PROTOCOL.md 5.2/5.3 and returns the next sequence.
fn check_layout(s: &Sent, packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> u16 {
let payload = usize::from(packet_size) - 16;
let n = (FRAME_HEADER_LEN + s.bitstream.len()).div_ceil(payload);
let plan = plan_fec_blocks(n, pct, min).expect("plan");
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
assert_eq!(s.datagrams.len(), total, "frame {}: datagram count", s.index);
let last_block = (plan.len() - 1) as u8;
let mut seq = first_sequence;
let mut it = s.datagrams.iter();
let mut data_seen = 0usize;
for (b, blk) in plan.iter().enumerate() {
let (k, m) = (usize::from(blk.data_shards), usize::from(blk.parity_shards));
assert_eq!(m, parity_count(k, blk.fec_percentage).unwrap(), "plan m = ceil(k * pct / 100)");
for shard in 0..k + m {
let d = it.next().expect("datagram");
let extra = if encrypt { ENCRYPTION_PREFIX_LEN } else { 0 };
assert_eq!(d.len(), usize::from(packet_size) + 16 + extra, "datagram length");
let bytes = plain(d, encrypt);
let p = parse_video_packet(&bytes).expect("parses");
assert_eq!(bytes[0], 0x90, "RTP byte 0");
assert_eq!(p.rtp.payload_type, 0);
assert_eq!(p.rtp.sequence, seq, "sequence numbers are consecutive");
assert_eq!(p.rtp.timestamp, s.timestamp);
assert_eq!(p.rtp.ssrc, 0);
assert_eq!(&bytes[12..16], &[0, 0, 0, 0], "reserved");
assert_eq!(p.nv.stream_packet_index, u32::from(seq) << 8, "stream packet index");
assert_eq!(p.nv.frame_index, s.index);
assert_eq!(bytes[25], 0, "reserved byte 25");
assert_eq!(p.nv.multi_fec_flags, 0x10, "multi-FEC flags (U15)");
assert_eq!(bytes[27] & 0x0F, 0, "multi-FEC blocks low bits");
assert_eq!(bytes[28] & 0x0F, 0, "FEC info low bits");
assert_eq!(p.nv.fec.block_index, b as u8);
assert_eq!(p.nv.fec.last_block_index, last_block);
assert_eq!(usize::from(p.nv.fec.shard_index), shard, "data first, then parity");
assert_eq!(usize::from(p.nv.fec.data_shards), k);
assert_eq!(p.nv.fec.fec_percentage, blk.fec_percentage);
let flags = p.nv.flags.0;
if shard < k {
let mut want = 0x01;
if data_seen == 0 {
want |= 0x04;
}
if data_seen == n - 1 {
want |= 0x02;
}
assert_eq!(flags, want, "frame {} data shard {data_seen} flags", s.index);
data_seen += 1;
} else {
assert_eq!(flags, 0, "parity flags");
}
seq = seq.wrapping_add(1);
}
}
assert_eq!(data_seen, n);
seq
}
fn sizes(rng: &mut SeqRng, payload: usize, count: usize) -> Vec<usize> {
let max = MAX_DATA_SHARDS_PER_FRAME * payload - FRAME_HEADER_LEN;
// Around the shard boundaries: frame data (8 + len) of exactly one and two shards, and one byte either side.
let mut out = vec![0, 1];
for edge in [payload, 2 * payload] {
let at = edge.saturating_sub(FRAME_HEADER_LEN);
out.extend([at.saturating_sub(1), at, at + 1]);
}
while out.len() < count {
out.push(match rng.below(4) {
0 => rng.below(payload * 3),
1 => rng.below(payload * 40),
_ => rng.below(payload * 300),
});
}
out.into_iter().map(|s| s.min(max)).collect()
}
const PACKET_SIZES: [u16; 9] = [17, 18, 20, 64, 100, 1024, 1040, 1408, 4080];
const PERCENTAGES: [u8; 8] = [0, 1, 10, 20, 50, 100, 200, 255];
// ================================================================================================ fixed vectors
#[test]
fn fixed_vector_one_small_frame() {
// packetSize 32: 16 bytes of payload per datagram. Frame data = 8-byte header + 7-byte bitstream = 15 bytes,
// so one data shard (zero-padded to 16) and, at 100 %, ceil(1 * 100 / 100) = 1 parity shard.
let mut tx = sender(32, 100, 0, false, 0x1234);
let bitstream = [0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB];
let frame = EncodedFrame {
frame_index: 7,
frame_type: FrameType::Key,
rtp_timestamp: 90_000,
processing_latency: 0x0102,
bitstream: &bitstream,
};
let out = tx.packetize(&frame).unwrap();
#[rustfmt::skip]
let payload: [u8; 16] = [
0x01, // frame header type
0x02, 0x01, // processing latency 0x0102, LE
0x02, // frame type: key
0x0F, 0x00, 0x00, 0x00, // last shard payload length 15, LE
0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB, // the bitstream
0x00, // zero padding to the full shard
];
#[rustfmt::skip]
let mut data = vec![
0x90, // RTP byte 0: version 2, extension bit
0x00, // payload type 0
0x12, 0x34, // sequence 0x1234, BE
0x00, 0x01, 0x5F, 0x90, // timestamp 90000, BE
0x00, 0x00, 0x00, 0x00, // SSRC 0
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x34, 0x12, 0x00, // stream packet index 0x1234 << 8 = 0x00123400, LE
0x07, 0x00, 0x00, 0x00, // frame index 7, LE
0x07, // flags: picture data 0x01 | end of frame 0x02 | start of frame 0x04
0x00, // reserved
0x10, // multi-FEC flags (U15)
0x00, // multi-FEC blocks: this block 0 (bits 4-5), last block 0 (bits 6-7)
0x40, 0x06, 0x40, 0x00, // FEC info 0x00400640, LE: 100 << 4 | shard 0 << 12 | k 1 << 22
];
data.extend_from_slice(&payload);
#[rustfmt::skip]
let mut parity = vec![
0x90, 0x00, // RTP byte 0, payload type 0
0x12, 0x35, // sequence 0x1235: the parity packet takes the next number
0x00, 0x01, 0x5F, 0x90, // the frame's timestamp
0x00, 0x00, 0x00, 0x00, // SSRC 0
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x35, 0x12, 0x00, // stream packet index 0x1235 << 8, LE
0x07, 0x00, 0x00, 0x00, // frame index 7
0x00, // flags 0 on parity packets
0x00, // reserved
0x10, // multi-FEC flags
0x00, // block 0 of 0
0x40, 0x16, 0x40, 0x00, // FEC info 0x00401640: 100 << 4 | shard 1 << 12 | k 1 << 22
];
// k = 1, m = 1: the Cauchy matrix is [[1 / ((1 + 0) XOR 0)]] = [[1]], so the parity is the data packet itself
// and its payload part equals the data payload.
parity.extend_from_slice(&payload);
assert_eq!(out, vec![data, parity]);
assert_eq!(tx.next_sequence(), 0x1236);
assert_eq!(tx.stats(), VideoPacketizerStats { frames: 1, packets: 2, parity_packets: 1, fec_reduced_blocks: 0 });
}
#[test]
fn fixed_vector_cauchy_parity_k3_m1() {
// packetSize 20: 4 bytes of payload. 8 + 4 = 12 bytes of frame data = 3 data shards, last one full (4 bytes).
// At 33 %: m = ceil(3 * 33 / 100) = 1. PROTOCOL.md 5.3 gives P = [01 8e f4] for k = 3, m = 1.
let mut tx = sender(20, 33, 0, false, 0);
let bitstream = [0x00, 0x00, 0x01, 0x09];
let frame = EncodedFrame {
frame_index: 0x0102_0304,
frame_type: FrameType::Predicted,
rtp_timestamp: 1,
processing_latency: 0xBEEF,
bitstream: &bitstream,
};
let out = tx.packetize(&frame).unwrap();
assert_eq!(out.len(), 4);
let shards: [[u8; 4]; 3] = [
[0x01, 0xEF, 0xBE, 0x01], // header type, latency 0xBEEF LE, predicted
[0x04, 0x00, 0x00, 0x00], // last shard payload length 4, LE
[0x00, 0x00, 0x01, 0x09], // bitstream
];
for (i, s) in shards.iter().enumerate() {
assert_eq!(&out[i][PAYLOAD_OFFSET..], s, "data shard {i}");
// FEC info: 33 << 4 | i << 12 | 3 << 22
let info = (33u32 << 4) | ((i as u32) << 12) | (3 << 22);
assert_eq!(&out[i][28..32], &info.to_le_bytes(), "FEC info of shard {i}");
}
let p = [0x01u8, 0x8E, 0xF4];
let want: Vec<u8> = (0..4).map(|x| (0..3).fold(0, |acc, i| acc ^ gf::mul(p[i], shards[i][x]))).collect();
assert_eq!(&out[3][PAYLOAD_OFFSET..], want.as_slice(), "parity = 01*d0 + 8e*d1 + f4*d2");
assert_eq!(&out[3][28..32], &((33u32 << 4) | (3 << 12) | (3 << 22)).to_le_bytes(), "parity FEC info");
assert_eq!(out[3][24], 0, "parity flags");
assert_eq!(&out[3][2..4], &3u16.to_be_bytes(), "parity sequence");
}
#[test]
fn frame_header_writer_round_trips() {
for (t, byte) in
[(FrameType::Predicted, 1u8), (FrameType::Key, 2), (FrameType::Recovery, 5), (FrameType::Other(9), 9)]
{
for (lat, last) in [(0u16, 1u32), (0xFFFF, 4064), (0x1234, 0x0A0B_0C0D)] {
let h = write_frame_header(t, lat, last);
let mut want = vec![0x01];
want.extend_from_slice(&lat.to_le_bytes());
want.push(byte);
want.extend_from_slice(&last.to_le_bytes());
assert_eq!(h.to_vec(), want);
let back = parse_frame_header(&h).unwrap();
assert_eq!(
(back.header_type, back.processing_latency, back.frame_type, back.last_payload_len),
(1, lat, t, last)
);
}
}
}
// ================================================================================================ the FEC plan
/// Parity the client asks for a block of `k`: `max(ceil(k * pct / 100), min)`.
fn target(k: usize, pct: u8, min: u8) -> usize {
(k * usize::from(pct)).div_ceil(100).max(usize::from(min))
}
/// Parity a block of `k` gets at percentage `p` (the receiver's formula).
fn m_at(k: usize, p: usize) -> usize {
(k * p).div_ceil(100)
}
/// Whether the least percentage (at or above the request) that gives a block of `k` its target is an 8-bit value
/// and keeps the block within 255 shards. Parity comes in steps of `ceil(k * p / 100)`, so for `k > 100` the least
/// step can overshoot the target.
fn achievable(k: usize, pct: u8, min: u8) -> bool {
let t = target(k, pct, min);
let p = (usize::from(pct)..=255).find(|&p| m_at(k, p) >= t);
k <= 255 && p.is_some_and(|p| k + m_at(k, p) <= 255)
}
#[test]
fn fec_plan_properties() {
for n in (1..=MAX_DATA_SHARDS_PER_FRAME).filter(|n| *n < 40 || n % 7 == 0 || *n > 1000) {
for pct in PERCENTAGES.into_iter().chain([3, 33, 34, 99]) {
for min in [0u8, 1, 2, 3, 4, 10, 255] {
let ctx = format!("n {n} pct {pct} min {min}");
let plan = plan_fec_blocks(n, pct, min).unwrap();
assert!((1..=MAX_FEC_BLOCKS).contains(&plan.len()), "{ctx}: {} blocks", plan.len());
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards)).sum::<usize>(), n, "{ctx}");
let first_k = plan[0].data_shards;
for (i, b) in plan.iter().enumerate() {
let (k, m, p) =
(usize::from(b.data_shards), usize::from(b.parity_shards), usize::from(b.fec_percentage));
assert!(k >= 1 && k + m <= 255, "{ctx}: k {k} m {m}");
assert_eq!(m, parity_count(k, b.fec_percentage).unwrap(), "{ctx}: m follows from the percentage");
if i + 1 < plan.len() {
assert_eq!(b.data_shards, first_k, "{ctx}: every block but the last carries the same k");
} else {
assert!(b.data_shards <= first_k, "{ctx}");
}
let t = target(k, pct, min);
assert_eq!(
b.reduced,
!achievable(k, pct, min),
"{ctx}: reduced exactly when the target cannot fit"
);
if b.reduced {
// The most parity that fits: one percent more would not.
assert!(m < t, "{ctx}");
assert!(p == 255 || k + m_at(k, p + 1) > 255, "{ctx}: k {k} p {p}: not the most that fits");
} else {
// The least percentage, at or above the request, that gives the target.
assert!(m >= t && p >= usize::from(pct), "{ctx}: k {k} m {m} p {p}");
assert!(p == usize::from(pct) || m_at(k, p - 1) < t, "{ctx}: k {k} p {p}: raised too far");
}
}
// Fewest blocks: one block fewer could not carry the frame with the requested parity.
if plan.len() > 1 && !plan[0].reduced {
let fewer = plan.len() - 1;
assert!(!achievable(n.div_ceil(fewer), pct, min), "{ctx}: {} blocks where {fewer} do", plan.len());
}
}
}
}
assert_err!(plan_fec_blocks(0, 20, 0), Error::Malformed { .. });
assert_too_large!(
plan_fec_blocks(MAX_DATA_SHARDS_PER_FRAME + 1, 0, 0),
MAX_DATA_SHARDS_PER_FRAME,
MAX_DATA_SHARDS_PER_FRAME + 1
);
}
#[test]
fn minimum_parity_raises_the_written_percentage() {
// One data shard at 0 % with at least 2 parity packets: 101 % is the smallest percentage giving
// m = ceil(1 * 101 / 100) = 2.
let plan = plan_fec_blocks(1, 0, 2).unwrap();
assert_eq!((plan[0].data_shards, plan[0].parity_shards, plan[0].fec_percentage), (1, 2, 101));
// 3 shards, at least 2: 34 % (ceil(1.02) = 2), not 67 % (which would give 3).
let plan = plan_fec_blocks(3, 0, 2).unwrap();
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage), (2, 34));
// Already enough: unchanged.
let plan = plan_fec_blocks(10, 50, 2).unwrap();
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage, plan[0].reduced), (5, 50, false));
}
// ================================================================================================ round trips
#[test]
fn round_trip_random_sizes() {
for seed in 0..12u64 {
let mut rng = SeqRng::new(seed);
let packet_size =
if seed < PACKET_SIZES.len() as u64 { PACKET_SIZES[seed as usize] } else { 17 + rng.below(4064) as u16 };
let pct = PERCENTAGES[rng.below(PERCENTAGES.len())];
let min = [0u8, 1, 2, 4][rng.below(4)];
let payload = usize::from(packet_size) - 16;
let first_sequence = rng.next_u64() as u16;
let mut tx = sender(packet_size, pct, min, false, first_sequence);
let mut seq = first_sequence;
let first_index = rng.next_u64() as u32;
let sent: Vec<Sent> = sizes(&mut rng, payload, 16)
.into_iter()
.enumerate()
.map(|(i, len)| send(&mut tx, &mut rng, first_index.wrapping_add(i as u32), len))
.collect();
for s in &sent {
seq = check_layout(s, packet_size, pct, min, false, seq);
}
assert_eq!(tx.next_sequence(), seq);
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
check(&sent, &[], &receive(&mut receiver(packet_size, false), &all));
let stats = tx.stats();
assert_eq!(stats.frames, sent.len() as u64);
assert_eq!(stats.packets, all.len() as u64);
}
}
#[test]
fn round_trip_with_up_to_m_lost_per_block() {
for seed in 100..112u64 {
let mut rng = SeqRng::new(seed);
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
let pct = [10u8, 20, 50, 100, 200, 255][rng.below(6)];
let min = [0u8, 1, 2][rng.below(3)];
let payload = usize::from(packet_size) - 16;
let mut tx = sender(packet_size, pct, min, false, rng.next_u64() as u16);
let sent: Vec<Sent> = sizes(&mut rng, payload, 14)
.into_iter()
.enumerate()
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
.collect();
let mut datagrams = Vec::new();
for s in &sent {
datagrams.extend(with_loss(&mut rng, s, false, |r, m| if r.below(3) == 0 { m } else { r.below(m + 1) }));
}
let out = receive(&mut receiver(packet_size, false), &datagrams);
check(&sent, &[], &out);
}
}
#[test]
fn every_data_shard_lost_is_rebuilt_when_parity_covers_it() {
// 100 %: m = k, so the parity alone carries the frame.
let mut rng = SeqRng::new(7);
let mut tx = sender(64, 100, 0, false, 0);
let sent: Vec<Sent> = (0..6).map(|i| send(&mut tx, &mut rng, i, 48 * (1 + 5 * i as usize))).collect();
let mut datagrams = Vec::new();
for s in &sent {
datagrams.extend(s.datagrams.iter().filter(|d| place(d, false).shard >= place(d, false).k).cloned());
}
let out = receive(&mut receiver(64, false), &datagrams);
check(&sent, &[], &out);
assert!(out.frames.iter().all(|f| f.recovered_shards > 0));
}
#[test]
fn more_than_m_lost_reports_the_frame_lost() {
for seed in 200..216u64 {
let mut rng = SeqRng::new(seed);
let packet_size = PACKET_SIZES[1 + rng.below(PACKET_SIZES.len() - 1)];
let pct = [0u8, 10, 20, 50, 100][rng.below(5)];
let payload = usize::from(packet_size) - 16;
let mut tx = sender(packet_size, pct, 0, false, 0xFFF0);
let sent: Vec<Sent> = (0..7)
.map(|i| {
let len = 1 + rng.below(payload * 30);
send(&mut tx, &mut rng, 1000 + i, len)
})
.collect();
let victim = 1 + rng.below(5);
let mut datagrams = Vec::new();
for (i, s) in sent.iter().enumerate() {
if i == victim {
// One block loses m + 1 packets, the others up to m.
let blocks = blocks_of(s, false);
let hit = *blocks.keys().nth(rng.below(blocks.len())).unwrap();
let mut keep = vec![true; s.datagrams.len()];
for (b, (positions, m)) in &blocks {
let n = if *b == hit { m + 1 } else { rng.below(m + 1) };
for j in rng.subset(positions.len(), n) {
keep[positions[j]] = false;
}
}
datagrams.extend(s.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()));
} else {
datagrams.extend(s.datagrams.iter().cloned());
}
}
let out = receive(&mut receiver(packet_size, false), &datagrams);
check(&sent, &[1000 + victim as u32], &out);
}
}
#[test]
fn reordered_and_duplicated() {
for seed in 300..310u64 {
let mut rng = SeqRng::new(seed);
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
let pct = [0u8, 20, 50][rng.below(3)];
let payload = usize::from(packet_size) - 16;
let mut tx = sender(packet_size, pct, 1, false, rng.next_u64() as u16);
let sent: Vec<Sent> = sizes(&mut rng, payload, 12)
.into_iter()
.enumerate()
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
.collect();
let mut datagrams = Vec::new();
for pair in sent.chunks(2) {
// Two frames' datagrams interleaved in random order, with random duplicates.
let mut window: Vec<Vec<u8>> = pair.iter().flat_map(|s| s.datagrams.clone()).collect();
let dups: Vec<Vec<u8>> =
(0..rng.below(window.len() + 1)).map(|_| window[rng.below(window.len())].clone()).collect();
window.extend(dups);
rng.shuffle(&mut window);
if datagrams.is_empty() {
// The receiver starts at the frame of the first datagram it sees: let that be frame 0's.
let first = window.iter().position(|d| pair[0].datagrams.contains(d));
window.swap(0, first.expect("a datagram of frame 0"));
}
datagrams.extend(window);
}
// And a few stale duplicates of earlier frames at the end.
for _ in 0..5 {
let s = &sent[rng.below(sent.len())];
datagrams.push(s.datagrams[rng.below(s.datagrams.len())].clone());
}
check(&sent, &[], &receive(&mut receiver(packet_size, false), &datagrams));
}
}
#[test]
fn sequence_numbers_continue_across_frames_and_wrap() {
let mut rng = SeqRng::new(9);
let mut tx = sender(64, 50, 0, false, 0xFFF0);
let mut seq = 0xFFF0u16;
let mut sent = Vec::new();
for i in 0..10u32 {
let s = send(&mut tx, &mut rng, (u32::MAX - 4).wrapping_add(i), 48 * 3);
seq = check_layout(&s, 64, 50, 0, false, seq);
sent.push(s);
}
assert!(seq < 0xFFF0, "the sequence wrapped");
assert_eq!(tx.next_sequence(), seq);
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
check(&sent, &[], &receive(&mut receiver(64, false), &all));
}
#[test]
fn parity_matches_an_independent_cauchy_encoder() {
// Parity over whole packets (5.3): bytes 32 on of parity j = sum_i 1 / ((m + i) XOR j) * data_i, with headers
// of the parity packets written afterwards.
let mut rng = SeqRng::new(11);
for (packet_size, pct, len) in [(64u16, 50u8, 48 * 9), (100, 20, 84 * 30), (1024, 100, 1008 * 4 + 3), (17, 255, 40)]
{
let mut tx = sender(packet_size, pct, 0, false, 0);
let s = send(&mut tx, &mut rng, 5, len);
for (positions, m) in blocks_of(&s, false).values() {
let k = positions.len() - m;
let data: Vec<Vec<u8>> = positions[..k].iter().map(|&i| s.datagrams[i].clone()).collect();
let matrix: Vec<u8> = (0..*m).flat_map(|j| (0..k).map(move |i| gf::inv(((m + i) ^ j) as u8))).collect();
let parity = gf::encode(&matrix, &data, *m);
for (j, &pos) in positions[k..].iter().enumerate() {
assert_eq!(&s.datagrams[pos][PAYLOAD_OFFSET..], &parity[j][PAYLOAD_OFFSET..], "parity {j}");
}
}
}
}
#[test]
fn several_megabyte_frames() {
let mut rng = SeqRng::new(13);
let packet_size = 4080; // largest: 4064 bytes of payload, 4096-byte datagrams
let mut tx = sender(packet_size, 20, 2, false, 0);
let max = tx.max_bitstream_len();
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * 4064 - FRAME_HEADER_LEN).min(MAX_FRAME_BYTES - FRAME_HEADER_LEN));
let big = send(&mut tx, &mut rng, 1, 3_000_000);
let lossy = with_loss(&mut rng, &big, false, |_, m| m);
let out = receive(&mut receiver(packet_size, false), &lossy);
check(std::slice::from_ref(&big), &[], &out);
// The largest frame: 4 blocks of 255 data shards, no room for parity, so the FEC is lowered and counted.
let before = tx.stats().fec_reduced_blocks;
let largest = send(&mut tx, &mut rng, 2, max);
assert_eq!(tx.stats().fec_reduced_blocks - before, 4);
assert_eq!(largest.datagrams.len(), MAX_DATA_SHARDS_PER_FRAME);
let out = receive(&mut receiver(packet_size, false), &largest.datagrams);
check(std::slice::from_ref(&largest), &[], &out);
}
// ================================================================================================ encryption
#[test]
fn video_cipher_encrypt_matches_dotnet_vectors() {
let v = common::video_vectors();
let c = VideoCipher::new(v.arr16("key"));
for (name, counter, frame) in
[("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)]
{
assert_eq!(
c.encrypt(counter, frame, &v.bytes(&format!("{name}_plain"))).unwrap(),
v.bytes(&format!("{name}_packet")),
"{name}"
);
}
let too_big = vec![0u8; MAX_VIDEO_PACKET_BYTES - ENCRYPTION_PREFIX_LEN + 1];
assert_too_large!(c.encrypt(0, 0, &too_big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
}
#[test]
fn encrypted_stream_round_trips_with_loss() {
let mut rng = SeqRng::new(17);
let mut tx = sender(1024, 20, 1, true, 100);
let mut clear = sender(1024, 20, 1, false, 100);
let mut counter = 0u64;
let mut sent = Vec::new();
for i in 0..10u32 {
let len = rng.below(1008 * 12);
let b = bitstream(&mut rng, len);
let mut r2 = rng.clone();
let s = send_bytes(&mut tx, &mut rng, i, b.clone());
let c = send_bytes(&mut clear, &mut r2, i, b);
assert_eq!(s.datagrams.len(), c.datagrams.len());
for (d, p) in s.datagrams.iter().zip(&c.datagrams) {
// IV = 8-byte LE counter, 3 zero bytes, 'V'; then the frame number, LE (PROTOCOL.md 7).
assert_eq!(&d[..8], &counter.to_le_bytes(), "nonce counter");
assert_eq!(&d[8..12], &[0, 0, 0, b'V']);
assert_eq!(&d[12..16], &i.to_le_bytes(), "frame number");
assert_eq!(
&VideoCipher::new(KEY).decrypt(d).unwrap(),
p,
"FEC before encryption: the plaintext is the clear packet"
);
counter += 1;
}
sent.push(s);
}
let mut datagrams = Vec::new();
for s in &sent {
datagrams.extend(with_loss(&mut rng, s, true, |r, m| r.below(m + 1)));
}
check(&sent, &[], &receive(&mut receiver(1024, true), &datagrams));
}
// ================================================================================================ refusals
#[test]
fn config_refusals() {
for size in [0u16, 1, 16] {
assert_err!(VideoPacketizer::new(config(size, 20, 0, false, 0)), Error::Malformed { .. }, "{size}");
}
assert!(VideoPacketizer::new(config(17, 20, 0, false, 0)).is_ok());
assert!(VideoPacketizer::new(config(4080, 20, 0, false, 0)).is_ok());
assert_err!(VideoPacketizer::new(config(4081, 20, 0, false, 0)), Error::Malformed { .. });
// Sealed datagrams carry 32 more bytes and must stay within the receiver's cap too.
assert!(VideoPacketizer::new(config(4048, 20, 0, true, 0)).is_ok());
assert_err!(VideoPacketizer::new(config(4049, 20, 0, true, 0)), Error::Malformed { .. });
}
#[test]
fn oversized_frame_is_refused_and_nothing_advances() {
for (packet_size, encrypt) in [(17u16, false), (64, true), (1024, false)] {
let mut rng = SeqRng::new(u64::from(packet_size));
let mut tx = sender(packet_size, 20, 0, encrypt, 77);
let max = tx.max_bitstream_len();
let payload = usize::from(packet_size) - 16;
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * payload).min(MAX_FRAME_BYTES) - FRAME_HEADER_LEN);
let first = send(&mut tx, &mut rng, 0, 10);
let (seq, stats) = (tx.next_sequence(), tx.stats());
let big = vec![1u8; max + 1];
let frame = EncodedFrame {
frame_index: 1,
frame_type: FrameType::Key,
rtp_timestamp: 0,
processing_latency: 0,
bitstream: &big,
};
assert_too_large!(tx.packetize(&frame), max, max + 1);
assert_eq!((tx.next_sequence(), tx.stats()), (seq, stats), "a refused frame changes nothing");
// The next frame follows on directly, and the receiver sees no gap (also no nonce reuse when sealed).
let second = send(&mut tx, &mut rng, 1, max);
let all: Vec<Vec<u8>> = [&first, &second].iter().flat_map(|s| s.datagrams.clone()).collect();
check(&[first, second], &[], &receive(&mut receiver(packet_size, encrypt), &all));
}
}
// ================================================================================================ generated
proptest! {
#![proptest_config(ProptestConfig { cases: 32, ..ProptestConfig::default() })]
/// Any sizes, packet sizes, percentages and minimums; up to m lost per block; identical frames out.
#[test]
fn generated_round_trips(
seed in any::<u64>(),
packet_size in 17u16..1500,
pct in any::<u8>(),
min in 0u8..8,
frames in 1usize..6,
encrypt in any::<bool>(),
) {
let mut rng = SeqRng::new(seed);
let payload = usize::from(packet_size) - 16;
let mut tx = sender(packet_size, pct, min, encrypt, rng.next_u64() as u16);
let max = tx.max_bitstream_len();
let first = rng.next_u64() as u32;
let sent: Vec<Sent> = (0..frames)
.map(|i| { let len = rng.below(payload * 30).min(max); send(&mut tx, &mut rng, first.wrapping_add(i as u32), len) })
.collect();
let mut datagrams = Vec::new();
for s in &sent {
datagrams.extend(with_loss(&mut rng, s, encrypt, |r, m| r.below(m + 1)));
}
check(&sent, &[], &receive(&mut receiver(packet_size, encrypt), &datagrams));
}
}
-1
View File
@@ -96,4 +96,3 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
| S-30 | 2026-12-04 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc` (same pin as S-9): `src/rtsp.rs` again, read for the host side | BSD-2, facts only. One request per TCP connection, the note that Moonlight opens a connection per request; `CSeq` required (connection closed without it); no method order and no `Session` check; statuses 200/400/500 only; OPTIONS `Public`; SETUP needs `Transport` (400 without), stream from the first `streamid=` query segment, answer `Session: MoonshineSession;timeout = 90` and `Transport: server_port=<port>`; DESCRIBE line order and values (`featureFlags:3`, `encryptionSupported` 5 or 7, `sprop-parameter-sets=AAAAAU`, invalidation, AV1, H.264, surround lines); ANNOUNCE: the ten required attributes (400 when missing), the defaults of the optional ones (`maxNumReferenceFrames` 1, `dynamicRangeMode`/`chromaSamplingType`/`encoderCscMode`/`encryptionEnabled`/`surround.enable` 0, `numChannels` 2, `channelMask` 0x3, `AudioQuality` 1), `maxFPS` 0 refused, bitrate ×1000 must fit a u32, QoS off for `0`. The comments citing Sunshine, moonlight-common-c or GFE are logged as second-hand GPL facts above and not used. |
| S-31 | 2026-12-04 | Moonshine at `f184d5e`: `src/session/stream/mod.rs`, `src/session/stream/video/mod.rs`; the repository tree listing (GitHub API) | BSD-2, facts only. `bitStreamFormat` 0 H.264 (default), 1 HEVC, 2 AV1, others invalid; dynamic range 0 SDR (default), 1 HDR; chroma 0 4:2:0 (default), 1 4:4:4; valid video packet size 200..=65471 (one stream packet in an IPv6 UDP datagram), below 200 refused; FEC default 20 %. The bitrate comment citing Sunshine is logged above and not used. |
| S-32 | 2026-12-04 | [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) again (as S-3); [RFC 2326](https://www.rfc-editor.org/rfc/rfc2326.txt) | Wolf: nothing new for the host (no per-method answers, no ANNOUNCE list). RFC 2326: reason phrases of 400, 451, 454, 455, 501 (7.1.1); a missing `Content-Length` means zero (4.4); OPTIONS may be sent at any time (10.1); session ids at least 8 random octets (3.4); `Public` as a comma-separated list (10.1 example). |
| S-34 | 2026-12-04 | [Stock ENet](https://github.com/lsalzman/enet) v1.3.18 (`2662c0d`, same pin as S-17), read again for the host side: `protocol.c` (`enet_protocol_handle_connect`, `_verify_connect`, `_disconnect`, `_ping`, `_bandwidth_limit`, `_throttle_configure`, `_acknowledge`, `_send_unsequenced`, `_send_unreliable_fragment`, `_send_reliable`/`_send_fragment` state checks, the acknowledgement rules of `_handle_incoming_commands`, the ping condition of `_send_outgoing_commands`) and `include/enet/enet.h` (peer window constants) | MIT. Facts for PROTOCOL.md 3.1 "The accepting side" and `enet::host`: a CONNECT is answered by a reliable verify on channel 0xFF and is not itself acknowledged; repeated connects from a live peer are refused; session id derivation (offered id or the slot's, plus one mod 4, skipping the slot's previous id) and which verify field carries which; MTU, window and channel clamping, bandwidths are the host's own, throttle echoed, connect data reported with the connect event; connected on the acknowledgement of the verify; acknowledgements only while connected and only with a sent time, a failing command ends the datagram; ping, bandwidth and throttle need the connected state; unsequenced window 1024 groups, 32 free windows; pings when nothing was received for the ping interval and nothing reliable is in flight. Read through an automated summary of the raw files at the pinned commit; no code copied. |
-53
View File
@@ -340,38 +340,6 @@ UNKNOWN U9 (narrowed): anything Sunshine's ENet sends that stock 1.3 does not; t
data` a client offers; whether the client sets non-default ping or timeout values. Settle: the lab capture's control
port datagrams, decoded with our parser (LAB_CAPTURE.md). Until then our client offers stock defaults.
**The accepting side, as stock ENet 1.3 does it** [E] (S-17, S-34; DomiStream `enet::host`, the Lumen host):
- A datagram addressed to `0xFFF` is looked at only for a CONNECT at its start; anything else in it is ignored. A
CONNECT asking for 0 or more than 255 channels is refused. A CONNECT repeated by a client whose connection already
exists (same address, same connect id) is ignored: no second peer, no acknowledgement.
- The CONNECT is **not acknowledged**; the host answers with a reliable VERIFY CONNECT on channel `0xFF` (the
connection channel's first reliable sequence number, 1), and the verify retires the client's connect.
- Session ids: the host's outgoing id is the client's offered *incoming* id (or, for `0xFF`, the slot's previous
outgoing id) plus one, modulo 4, bumped once more if it equals the slot's previous outgoing id; the host's
incoming id likewise from the client's offered *outgoing* id. A fresh slot has `0xFF` for both, so a client offering
`0xFF`/`0xFF` gets 0/0. The verify carries `incoming session = the host's outgoing` and `outgoing session = the
host's incoming`, i.e. both fields from the client's point of view; a sender puts its outgoing id in the header
(only once the remote peer id is known), a receiver drops datagrams whose id is not its incoming id.
- Verify fields: `outgoing peer id` = the host's own peer id (the client addresses it from then on); MTU = the
client's clamped to 576-4096, then at most the host's; window = the client's, at most 65536 when the host's
bandwidth is unlimited, clamped to 4096-65536; channel count = the client's, at most the host's channel limit;
bandwidths = the host's own (0 = unlimited); throttle interval, acceleration and deceleration echoed; connect id
echoed. The connect's `data` word is what the host's connect event reports.
- The peer is connected when the client **acknowledges the verify**. Before that, data, pings and bandwidth or
throttle commands from the client are not taken and not acknowledged (the client sends them again).
- Acknowledgements: a command with the acknowledge flag is acknowledged only while connected, echoing the datagram's
sent time; in a datagram **without** sent time such a command is handled but not acknowledged and the rest of the
datagram is skipped. A failing command also ends the datagram.
- Disconnect from the client while connected: acknowledged (if flagged), the connection closes with the client's
data word. Ping, bandwidth limit and throttle configure need the connected state.
- Unsequenced duplicates are dropped with a window of 1024 groups; groups up to 32 windows ahead move the window,
older or farther ones are dropped.
- The host pings a connected peer when nothing was **received** from it for the ping interval (500 ms by default)
and no reliable command is in flight.
Not in DomiStream's host: the checksum and compression (see above), throttling what it sends by bandwidth, and
unreliable fragments (dropped: every control message is small and reliable).
### 3.2 Encrypted frame
Every control message is wrapped [W4] (little-endian):
@@ -424,17 +392,6 @@ does not match, **ends the session** when it arrives outside the encrypted frame
message is skipped, and so is a frame that fails decryption. Whether Sunshine reads bodies (and which) is what U10
still settles live: the probe sends empty bodies first ([LIVE-INTEROP.md](LIVE-INTEROP.md), table V).
How DomiStream's host side reads the client (`control::host`, for Lumen; ours, on [M] above): frames open with the
client-to-host nonce; a frame that fails, or whose sequence number is not above the last accepted one, is dropped
without moving the replay state (U11: the first number is not checked); a malformed message inside a good frame is
skipped. Bodies of START_B, PERIODIC_PING and the IDR request are ignored, LOSS_STATS and FRAME_STATS are kept raw,
INVALIDATE_REF_FRAMES reads `first`/`last` with missing bytes as 0, INPUT_DATA goes through section 4 (a layout we
cannot read is reported, not fatal), every other type (START_A among them) is skipped. Only control V2 is spoken: a
bare message outside the frame is dropped. Host messages: rumble, trigger rumble, motion event, RGB LED and the
extended termination are sent, reliable on channel 0, numbered from 0; the plain TERMINATION (body U10) and
HDR_MODE (`[M*]`) are refused until measured. Each PERIODIC_PING moves the stop deadline (default 60 s) out; when it
passes, the host reports it once and the caller ends the session.
---
## 4. Input and gamepad packets
@@ -581,12 +538,6 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
captured parity bytes (offset 32 on) of every block.
- **Host side (Lumen, `video::packetizer`).** Our own choices, not from a source, until a capture compares them
with a real host: the fewest blocks (at most 4) in which every block can carry the requested parity within
`k + m <= 255`, every block but the last carrying `k = ceil(n / blocks)` data shards; per block the least
percentage, at or above the requested one, whose `m` reaches `minRequiredFecPackets`; a frame too big for that
gets the most parity that still fits (counted in the packetizer's stats). Data shards in order, then the block's
parity, block by block; RTP sequence numbers run on across frames, one per packet.
- The audio code is **not** this matrix (section 6.4).
### 5.4 Feedback
@@ -645,10 +596,6 @@ coefficients (each parity byte is a linear combination of the 4 data bytes at th
parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the
platform's packet-loss concealment.
Host side (Lumen, `audio::packetizer`): no parity packets until U16 is settled (`AudioParity::None`; the API leaves
room for a parity variant). The first sequence number is a multiple of 4, a block start, because our receiver counts
from the first packet's block start and would otherwise report the 1 to 3 numbers before it as lost.
### 6.5 Decoding
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
-24
View File
@@ -212,20 +212,6 @@ test = false
doc = false
bench = false
[[bin]]
name = "video_packetizer_roundtrip"
path = "fuzz_targets/video_packetizer_roundtrip.rs"
test = false
doc = false
bench = false
[[bin]]
name = "enet_host"
path = "fuzz_targets/enet_host.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_server"
path = "fuzz_targets/rtsp_server.rs"
@@ -239,13 +225,3 @@ path = "fuzz_targets/announce.rs"
test = false
doc = false
bench = false
test = false
doc = false
bench = false
[[bin]]
name = "control_host"
path = "fuzz_targets/control_host.rs"
test = false
doc = false
bench = false
-165
View File
@@ -1,165 +0,0 @@
//! Fuzzes the control host: a connected ControlHost fed a mix of raw datagrams, arbitrary plaintexts sealed with
//! the session key (so the decrypted-message path is reached), arbitrary frames inside valid ENet commands, and
//! time steps; plus `parse_client_message` on every chunk.
//! Asserts invariants, not only "no panic": a client message always splits as a message first; kept bodies and
//! reported lengths match the input; outgoing datagrams parse; a message event never outnumbers what was sealed.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::Instant;
use domistream::control::{
ClientControlMessage, ControlCipher, ControlHost, ControlHostConfig, ControlHostEvent, Direction,
parse_client_message, parse_message,
};
use domistream::enet::EnetHostConfig;
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram, parse_datagram,
};
const PEER_ID: u16 = 3;
const KEY: [u8; 16] = [7; 16];
fn datagram(peer_id: u16, sent_time: u16, commands: Vec<Command>) -> Option<Vec<u8>> {
encode_datagram(&Datagram { peer_id, session_id: 0, sent_time: Some(sent_time), commands }).ok()
}
fn connected() -> ControlHost {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 1,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
let connect = Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
};
let config = ControlHostConfig {
enet: EnetHostConfig {
peer_id: PEER_ID,
channel_limit: 1,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
},
rikey: KEY,
stop_timeout: Some(Duration::from_secs(2)),
};
let mut h = ControlHost::accept(config, Instant::ZERO, &datagram(NO_PEER_ID, 0, vec![connect]).expect("connect"))
.expect("canned connect");
while h.poll_transmit(Instant::ZERO).is_some() {}
let ack = Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
};
h.handle_datagram(Instant::from_micros(1000), &datagram(PEER_ID, 1, vec![ack]).expect("ack")).expect("canned ack");
assert_eq!(h.poll_event(), Some(ControlHostEvent::Connected));
h
}
fn check_parse(chunk: &[u8]) {
let raw = parse_message(chunk);
match parse_client_message(chunk) {
Ok(m) => {
assert!(raw.is_ok(), "a client message must split as a message first");
match m {
ClientControlMessage::Unknown { body_len, .. }
| ClientControlMessage::InputRejected { body_len, .. } => {
assert_eq!(body_len + 4, chunk.len());
}
ClientControlMessage::LossStats(b) | ClientControlMessage::FrameStats(b) => {
assert_eq!(&b[..], &chunk[4..]);
}
_ => {}
}
}
Err(_) => assert!(raw.is_err(), "only the split can fail"),
}
}
fuzz_target!(|data: &[u8]| {
let mut h = connected();
let cipher = ControlCipher::new(KEY);
let mut reliable = 0u16;
let mut sequence = 0u32;
let mut sealed = 0usize;
let mut messages = 0usize;
let mut ms = 2u64;
let mut rest = data;
while let Some((&op, tail)) = rest.split_first() {
if tail.len() < 2 {
break;
}
let len = usize::from(u16::from_be_bytes([tail[0], tail[1]])).min(tail.len() - 2);
let (chunk, t) = tail[2..].split_at(len);
rest = t;
ms += u64::from(op >> 3) * 13;
let now = Instant::from_micros(ms * 1000);
check_parse(chunk);
let wrap = |frame: Vec<u8>, reliable: &mut u16| {
*reliable = reliable.wrapping_add(1);
let c = Command {
acknowledge: true,
channel_id: 0,
reliable_sequence: *reliable,
body: CommandBody::SendReliable(frame),
};
datagram(PEER_ID, (ms & 0xFFFF) as u16, vec![c])
};
let bytes = match op & 0x07 {
// An arbitrary plaintext, sealed with the next sequence number.
0 | 1 | 2 => cipher.seal(sequence, Direction::ClientToHost, chunk).ok().and_then(|f| {
sequence = sequence.wrapping_add(1);
sealed += 1;
wrap(f, &mut reliable)
}),
// An arbitrary plaintext sealed with a sequence number from the chunk (replays, gaps).
3 => {
let seq = chunk.get(..4).map_or(0, |b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]));
cipher.seal(seq, Direction::ClientToHost, chunk).ok().and_then(|f| {
sealed += 1;
wrap(f, &mut reliable)
})
}
// Arbitrary bytes as the frame inside a valid reliable command.
4 => wrap(chunk.to_vec(), &mut reliable),
// A host message.
5 => {
let _ = h.send_rumble(now, u16::from(op), 1, 2);
None
}
// Raw datagram.
_ => Some(chunk.to_vec()),
};
if let Some(b) = bytes {
let _ = h.handle_datagram(now, &b);
}
let _ = h.handle_timeout(now);
while let Some(out) = h.poll_transmit(now) {
parse_datagram(&out).expect("the host's own datagrams parse");
}
while let Some(e) = h.poll_event() {
if let ControlHostEvent::Message(_) = e {
messages += 1;
}
}
assert!(messages <= sealed, "{messages} messages from {sealed} sealed frames");
}
});
-130
View File
@@ -1,130 +0,0 @@
//! Fuzzes the ENet host-side peer: `accept` on the first datagram (or a canned CONNECT, then the verify
//! acknowledged, so the connected state is reached), then a sequence of datagrams, some given our header so they
//! reach the command loop.
//! Asserts invariants, not only "no panic": delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse
//! and stay within the MTU; a disconnected peer has no deadline.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use domistream::Instant;
use domistream::enet::protocol::{
Command, CommandBody, ConnectParams, Datagram, NO_PEER_ID, encode_datagram, parse_datagram,
};
use domistream::enet::{EnetHostConfig, EnetHostEvent, EnetHostPeer, EnetHostState, MAX_PACKET_BYTES};
const PEER_ID: u16 = 3;
fn config() -> EnetHostConfig {
EnetHostConfig {
peer_id: PEER_ID,
channel_limit: 4,
mtu: 1400,
ping_interval: Duration::from_millis(500),
timeout: Duration::from_secs(10),
}
}
fn datagram(peer_id: u16, commands: Vec<Command>) -> Vec<u8> {
encode_datagram(&Datagram { peer_id, session_id: 0, sent_time: Some(0), commands }).expect("canned datagram")
}
fn canned_connect() -> Vec<u8> {
let params = ConnectParams {
outgoing_peer_id: 0,
incoming_session_id: 0xFF,
outgoing_session_id: 0xFF,
mtu: 1400,
window_size: 65536,
channel_count: 2,
incoming_bandwidth: 0,
outgoing_bandwidth: 0,
packet_throttle_interval: 5000,
packet_throttle_acceleration: 2,
packet_throttle_deceleration: 2,
connect_id: 1,
};
let c = Command {
acknowledge: true,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Connect { params, data: 0 },
};
datagram(NO_PEER_ID, vec![c])
}
fn drive(h: &mut EnetHostPeer, now: Instant) {
let _ = h.handle_timeout(now);
while let Some(out) = h.poll_transmit(now) {
assert!(out.len() <= h.mtu());
parse_datagram(&out).expect("the host's own datagrams parse");
}
while let Some(e) = h.poll_event() {
if let EnetHostEvent::Received { data, .. } = e {
assert!(data.len() <= MAX_PACKET_BYTES);
}
}
if h.state() == EnetHostState::Disconnected {
assert_eq!(h.poll_timeout(), None);
}
}
/// The next datagram: a flag byte, a 2-byte big-endian length, the bytes.
fn next(rest: &mut &[u8]) -> Option<(u8, Vec<u8>)> {
let (&flags, tail) = rest.split_first()?;
if tail.len() < 2 {
return None;
}
let len = usize::from(u16::from_be_bytes([tail[0], tail[1]])).min(tail.len() - 2);
let (d, t) = tail[2..].split_at(len);
*rest = t;
Some((flags, d.to_vec()))
}
fuzz_target!(|data: &[u8]| {
let Some((&mode, mut rest)) = data.split_first() else { return };
let mut h = if mode & 1 == 0 {
let Some((_, first)) = next(&mut rest) else { return };
match EnetHostPeer::accept(config(), Instant::ZERO, &first) {
Ok(h) => h,
Err(_) => return,
}
} else {
let mut h = EnetHostPeer::accept(config(), Instant::ZERO, &canned_connect()).expect("canned connect");
while h.poll_transmit(Instant::ZERO).is_some() {}
if mode & 2 != 0 {
let ack = Command {
acknowledge: false,
channel_id: 0xFF,
reliable_sequence: 1,
body: CommandBody::Acknowledge { received_reliable_sequence: 1, received_sent_time: 0 },
};
h.handle_datagram(Instant::from_micros(1000), &datagram(PEER_ID, vec![ack])).expect("canned ack");
assert_eq!(h.state(), EnetHostState::Connected);
}
h
};
let mut ms = 1u64;
while let Some((flags, d)) = next(&mut rest) {
ms += u64::from(flags >> 2) * 7;
let now = Instant::from_micros(ms * 1000);
let bytes = if flags & 1 != 0 {
let mut b = (0x8000 | PEER_ID).to_be_bytes().to_vec();
b.extend_from_slice(&((ms & 0xFFFF) as u16).to_be_bytes());
b.extend_from_slice(&d);
b
} else {
d
};
let _ = h.handle_datagram(now, &bytes);
if flags & 2 != 0 {
let _ = h.send(now, flags % 3, domistream::enet::Delivery::Reliable, &bytes);
}
drive(&mut h, now);
}
});
@@ -1,125 +0,0 @@
//! Fuzzes the host's video packetizer against the client's depacketizer (`docs/PROTOCOL.md` 5.2, 5.3, 7).
//! Arbitrary frame bytes and parameters (packet size, FEC percentage, minimum parity, encryption, frame type,
//! latency) → packetize two frames → lose up to `m` packets of every block → depacketize: both frames must come back
//! byte-exact, in order, with their headers. Every valid configuration must be accepted and every frame within
//! `max_bitstream_len` packetized.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
use core::time::Duration;
use std::collections::BTreeMap;
use domistream::Instant;
use domistream::fec::parity_count;
use domistream::video::packet::parse_video_packet;
use domistream::video::packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
use domistream::video::{FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent};
const KEY: [u8; 16] = *b"fuzz-video-key!!";
/// xorshift64*, seeded from the input: which packets are lost.
struct Rng(u64);
impl Rng {
fn below(&mut self, n: usize) -> usize {
self.0 ^= self.0 >> 12;
self.0 ^= self.0 << 25;
self.0 ^= self.0 >> 27;
(self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n.max(1)
}
}
fuzz_target!(|data: &[u8]| {
let Some((head, body)) = data.split_first_chunk::<10>() else { return };
let [s0, s1, pct, min, flags, loss, split, l0, l1, first] = *head;
// 17..=4048: every packet size the receiver accepts, sealed or not.
let packet_size = 17 + u16::from_le_bytes([s0, s1]) % 4032;
let encrypt = flags & 1 != 0;
let frame_type = match (flags >> 1) & 3 {
0 => FrameType::Predicted,
1 => FrameType::Key,
2 => FrameType::Recovery,
_ => FrameType::Other((flags >> 3) | 0x08), // 8..=31: never a value with its own name (1, 2, 5)
};
let lossy = flags & 0x80 != 0;
let cipher = || encrypt.then(|| VideoCipher::new(KEY));
let config = VideoPacketizerConfig {
packet_size,
fec_percentage: pct,
min_required_fec_packets: min,
cipher: cipher(),
first_sequence: u16::from_le_bytes([first, s0]),
};
let mut tx = VideoPacketizer::new(config).expect("a valid configuration is accepted");
let mut rx =
VideoDepacketizer::new(VideoConfig { packet_size, cipher: cipher(), frame_timeout: Duration::from_millis(20) })
.expect("the receiver accepts the same packet size");
let cut = body.len() * usize::from(split) / 255;
let (a, b) = body.split_at(cut);
let frames = [a, b];
let mut rng = Rng(u64::from_le_bytes([s0, s1, pct, min, flags, loss, split, l0]) | 1);
let mut datagrams = Vec::new();
for (i, bitstream) in frames.iter().enumerate() {
assert!(bitstream.len() <= tx.max_bitstream_len(), "fuzz inputs stay far below the frame cap");
let frame = EncodedFrame {
frame_index: 0xFFFF_FFFF_u32.wrapping_add(i as u32),
frame_type,
rtp_timestamp: u32::from(l1) << 8,
processing_latency: u16::from_le_bytes([l0, l1]),
bitstream,
};
let out = tx.packetize(&frame).expect("a frame within the cap is packetized");
// Group by block (from the plaintext), then lose up to m of each block.
let mut blocks: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
for (j, d) in out.iter().enumerate() {
let plain = if encrypt { VideoCipher::new(KEY).decrypt(d).expect("our own seal opens") } else { d.clone() };
let p = parse_video_packet(&plain).expect("our own packet parses");
let m = parity_count(usize::from(p.nv.fec.data_shards), p.nv.fec.fec_percentage).expect("consistent FEC");
blocks.entry(p.nv.fec.block_index).or_insert_with(|| (Vec::new(), m)).0.push(j);
}
let mut keep = vec![true; out.len()];
if lossy {
for (positions, m) in blocks.values() {
let mut left = positions.clone();
for _ in 0..rng.below(m + 1).min(left.len()) {
let pick = left.swap_remove(rng.below(left.len()));
if let Some(k) = keep.get_mut(pick) {
*k = false;
}
}
}
}
// Sent in order; every block keeps at least k packets, so frame 0 starts the receiver.
datagrams.extend(out.into_iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d));
}
let mut us = 1_000u64;
let mut got = Vec::new();
for d in &datagrams {
rx.push(Instant::from_micros(us), d).expect("within the receiver's cap");
us += 10;
while let Some(e) = rx.poll_event() {
got.push(e);
}
}
for _ in 0..8 {
us += 1_000_000;
let _ = rx.handle_timeout(Instant::from_micros(us));
while let Some(e) = rx.poll_event() {
got.push(e);
}
}
assert_eq!(got.len(), 2, "two frames out: {got:?}");
for (i, (e, want)) in got.iter().zip(frames).enumerate() {
let VideoEvent::Frame(f) = e else { panic!("frame {i} lost: {e:?}") };
assert_eq!(f.frame_index, 0xFFFF_FFFF_u32.wrapping_add(i as u32));
assert!(f.bitstream == want, "frame {i}: {} bytes out, {} in", f.bitstream.len(), want.len());
assert_eq!(f.header.frame_type, frame_type);
assert_eq!(f.header.processing_latency, u16::from_le_bytes([l0, l1]));
assert_eq!(f.rtp_timestamp, u32::from(l1) << 8);
}
});