Compare commits
41 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 51db5a962b | |||
| a907f705f1 | |||
| 1f95cc8db4 | |||
| 1fca3abd49 | |||
| c2e3c28ed6 | |||
| 110eed8c14 | |||
| a355532881 | |||
| 6207624cb8 | |||
| fd6333620d | |||
| fa08511804 | |||
| 3dd7a8fe94 | |||
| c06fec4be5 | |||
| 10f88e69cd | |||
| a263ef0f9a | |||
| 337f6a72c5 | |||
| 80047c65df | |||
| 509e82d914 | |||
| 989defcc88 | |||
| 3106f2cb46 | |||
| bdd867c521 | |||
| 3aa3775de8 | |||
| 7b9b1f4e9c | |||
| f0aac13f12 | |||
| 95380a3b37 | |||
| db56a5dbb1 | |||
| e082570a3f | |||
| f8bad73121 | |||
| 58910d00fa | |||
| e77c5fcd83 | |||
| eae3b9e754 | |||
| fd4285aff0 | |||
| a86a689b1f | |||
| 27b7f2bf1d | |||
| 54bc9f5faf | |||
| 33b7b90b65 | |||
| 81ddf64bee | |||
| 7a6afed575 | |||
| 0d3a9a7917 | |||
| b62443ef28 | |||
| e1abd7d060 | |||
| 7983833ba6 |
Generated
+1
-1
@@ -241,7 +241,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "domistream"
|
name = "domistream"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
|
|||||||
+1
-1
@@ -5,7 +5,7 @@ exclude = ["fuzz"]
|
|||||||
resolver = "3"
|
resolver = "3"
|
||||||
|
|
||||||
[workspace.package]
|
[workspace.package]
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
rust-version = "1.89"
|
rust-version = "1.89"
|
||||||
license = "CPAL-1.0"
|
license = "CPAL-1.0"
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ bytes, events and deadlines out.
|
|||||||
| Part | What | Day |
|
| Part | What | Day |
|
||||||
| :-- | :-- | :-- |
|
| :-- | :-- | :-- |
|
||||||
| GameStream client | pairing handshake, app list, RTSP, the ENet-compatible control channel, input and gamepad messages, RTP video depacketizer with FEC recovery, Opus audio with FEC, stream encryption | 1 |
|
| GameStream client | pairing handshake, app list, RTSP, the ENet-compatible control channel, input and gamepad messages, RTP video depacketizer with FEC recovery, Opus audio with FEC, stream encryption | 1 |
|
||||||
|
| GameStream host (Lumen) | the host's half of the same protocols: HTTP requests and XML answers, the pairing machine and Tessera-trusted clients, the RTSP session with DESCRIBE and a strict ANNOUNCE parser, the accepting ENet peer, the control host, video packetizer with FEC parity, Opus audio packetizer | Lumen L1 |
|
||||||
| Harness maths | clock sync and the added-latency statistics | 2 |
|
| Harness maths | clock sync and the added-latency statistics | 2 |
|
||||||
| Lumen | the protocol, FEC, pacing and congestion maths of Arena Domi's own engine | 3–7 |
|
| Lumen | the protocol, FEC, pacing and congestion maths of Arena Domi's own engine | 3–7 |
|
||||||
|
|
||||||
@@ -18,13 +19,16 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R
|
|||||||
cargo test --workspace
|
cargo test --workspace
|
||||||
```
|
```
|
||||||
|
|
||||||
## Status: `stream-v0.1.0`
|
## Status: `stream-v0.2.0`
|
||||||
|
|
||||||
Written from the Wolf protocol docs and the approved permissive sources (stock ENet, tokio-enet, fec-rs). **Interop is
|
| Side | State |
|
||||||
unverified**: this release has not yet talked to a real Sunshine host. Ten details that block interop (U1, U2, U4–U10,
|
| :-- | :-- |
|
||||||
U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Arena Domi's Play remotely Day 1, and a
|
| Client (since `stream-v0.1.0`) | complete for Day 1. **Interop with a real Sunshine host is unverified**: ten details that block it (U1, U2, U4–U10, U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Play remotely Day 1 |
|
||||||
`stream-v0.1.x` patch is expected. Evidence for this release: 242 tests, a mutation pass (24 of 24 caught,
|
| Host, for Lumen (new in `stream-v0.2.0`) | complete for Lumen L1 and tested against our own client in one in-memory session. **Interop with real clients (Arena Domi Remote, the Moonlight PC app) is unverified**: it is measured black-box at the end of L1 |
|
||||||
[`docs/MUTATION.md`](docs/MUTATION.md)), and 25 fuzz targets with 0 crashes ([`docs/HANDOVER.md`](docs/HANDOVER.md)).
|
|
||||||
|
Written from the Wolf protocol docs, Moonshine (BSD-2, facts only) and the approved permissive sources (stock ENet,
|
||||||
|
tokio-enet, fec-rs). Evidence for this release is in [`docs/HANDOVER.md`](docs/HANDOVER.md): the test suite, the
|
||||||
|
mutation pass ([`docs/MUTATION.md`](docs/MUTATION.md)) and 32 fuzz targets with 0 crashes.
|
||||||
|
|
||||||
| Path | What |
|
| Path | What |
|
||||||
| :-- | :-- |
|
| :-- | :-- |
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "domistream"
|
name = "domistream"
|
||||||
description = "Sans-I/O GameStream client protocol for Arena Domi Play remotely"
|
description = "Sans-I/O GameStream protocol (client and host) for Arena Domi Play remotely"
|
||||||
version.workspace = true
|
version.workspace = true
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
|
|||||||
@@ -11,15 +11,17 @@ use core::fmt;
|
|||||||
use std::collections::{HashMap, VecDeque};
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
use cbc::cipher::block_padding::Pkcs7;
|
use cbc::cipher::block_padding::Pkcs7;
|
||||||
use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
|
use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
|
||||||
|
|
||||||
use crate::fec::ReedSolomon;
|
use crate::fec::ReedSolomon;
|
||||||
use crate::util::malformed;
|
use crate::util::malformed;
|
||||||
use crate::{Error, Instant, Result, SessionKeys};
|
use crate::{Error, Instant, Result, SessionKeys};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
||||||
|
pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity};
|
||||||
|
|
||||||
/// Data packets per FEC block.
|
/// Data packets per FEC block.
|
||||||
pub const DATA_SHARDS: usize = 4;
|
pub const DATA_SHARDS: usize = 4;
|
||||||
@@ -78,6 +80,30 @@ 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 {
|
impl fmt::Debug for AudioCipher {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("AudioCipher(<redacted>)")
|
f.write_str("AudioCipher(<redacted>)")
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! 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(×tamp.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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
//! 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())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,9 +11,14 @@ use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent};
|
|||||||
use crate::{Instant, RandomSource, Result};
|
use crate::{Instant, RandomSource, Result};
|
||||||
|
|
||||||
pub mod frame;
|
pub mod frame;
|
||||||
|
pub mod host;
|
||||||
pub mod message;
|
pub mod message;
|
||||||
|
|
||||||
pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame};
|
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};
|
pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message};
|
||||||
|
|
||||||
/// Settings of one control stream. `Debug` never prints the key.
|
/// Settings of one control stream. `Debug` never prints the key.
|
||||||
|
|||||||
@@ -0,0 +1,793 @@
|
|||||||
|
//! 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,5 +1,5 @@
|
|||||||
//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1,
|
//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1,
|
||||||
//! `docs/research/open-point-2.md`).
|
//! `docs/research/open-point-2.md`), and its accepting mirror for the Lumen host, [`host::EnetHostPeer`].
|
||||||
//!
|
//!
|
||||||
//! One peer, one connection. The caller owns the UDP socket:
|
//! One peer, one connection. The caller owns the UDP socket:
|
||||||
//!
|
//!
|
||||||
@@ -24,8 +24,11 @@ use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATA
|
|||||||
use crate::util::malformed;
|
use crate::util::malformed;
|
||||||
use crate::{Error, Instant, RandomSource, Result};
|
use crate::{Error, Instant, RandomSource, Result};
|
||||||
|
|
||||||
|
pub mod host;
|
||||||
pub mod protocol;
|
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).
|
/// Maximum size of one reassembled packet, in bytes (control messages are small; this caps fragment memory).
|
||||||
pub const MAX_PACKET_BYTES: usize = 64 * 1024;
|
pub const MAX_PACKET_BYTES: usize = 64 * 1024;
|
||||||
/// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more.
|
/// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more.
|
||||||
@@ -330,8 +333,10 @@ impl EnetClient {
|
|||||||
}
|
}
|
||||||
if self.state == EnetState::Connecting && p.connect_id == self.connect_id {
|
if self.state == EnetState::Connecting && p.connect_id == self.connect_id {
|
||||||
self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID;
|
self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID;
|
||||||
self.out_session = p.incoming_session_id & 0x3;
|
// Both ids are given from the client's point of view (PROTOCOL.md 3.1 [E]): the incoming one is
|
||||||
self.in_session = p.outgoing_session_id & 0x3;
|
// what the host sends with, the outgoing one what we send with.
|
||||||
|
self.in_session = p.incoming_session_id & 0x3;
|
||||||
|
self.out_session = p.outgoing_session_id & 0x3;
|
||||||
let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1);
|
let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1);
|
||||||
self.channel_count = self.channel_count.min(count);
|
self.channel_count = self.channel_count.min(count);
|
||||||
let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES);
|
let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES);
|
||||||
|
|||||||
@@ -0,0 +1,275 @@
|
|||||||
|
//! The host's XML answers (`docs/PROTOCOL.md` 1.1-1.5): every body is `<root status_code="…">` with elements
|
||||||
|
//! inside. Text and attribute values are escaped; a value the client's parser would refuse (too long, empty where
|
||||||
|
//! required, control characters) is refused here first, so the host never sends what its clients cannot read.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::host::pairing::PairAnswer;
|
||||||
|
use crate::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||||
|
use crate::http::launch::MAX_SESSION_URL_BYTES;
|
||||||
|
use crate::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
|
||||||
|
use crate::http::xml::MAX_XML_ELEMENTS;
|
||||||
|
use crate::http::{App, Scheme};
|
||||||
|
use crate::pairing::identity::MAX_CERT_PEM_BYTES;
|
||||||
|
use crate::pairing::{MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, SECRET_LEN};
|
||||||
|
use crate::util::{cap, check_rtsp_url, hex_encode, malformed};
|
||||||
|
|
||||||
|
/// What the host says about itself in `serverinfo` (`docs/PROTOCOL.md` 1.2).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HostInfo {
|
||||||
|
/// `hostname`: the name the client shows. Non-empty.
|
||||||
|
pub hostname: String,
|
||||||
|
/// `appversion`, the protocol version string, e.g. `7.1.431.-1`.
|
||||||
|
pub app_version: String,
|
||||||
|
/// `GfeVersion`, the compatibility version string.
|
||||||
|
pub gfe_version: String,
|
||||||
|
/// `uniqueid`: the host's stable id. Non-empty.
|
||||||
|
pub unique_id: String,
|
||||||
|
/// `HttpsPort`.
|
||||||
|
pub https_port: u16,
|
||||||
|
/// `ExternalPort`: the HTTP port.
|
||||||
|
pub http_port: u16,
|
||||||
|
/// `mac` for Wake-on-LAN, written `aa:bb:cc:dd:ee:ff`; `None` writes an empty element.
|
||||||
|
pub mac: Option<[u8; 6]>,
|
||||||
|
/// `LocalIP`: the host's address as this client reached it; empty is allowed.
|
||||||
|
pub local_ip: String,
|
||||||
|
/// `MaxLumaPixelsHEVC`; 0 = no HEVC.
|
||||||
|
pub max_luma_pixels_hevc: u64,
|
||||||
|
/// `ServerCodecModeSupport` bitmask (bit meanings UNKNOWN U25).
|
||||||
|
pub codec_mode_support: u32,
|
||||||
|
/// `currentgame`: id of the running app, 0 = none.
|
||||||
|
pub current_game: u32,
|
||||||
|
/// Prefix of `state`: written `<prefix>_SERVER_BUSY` when `current_game != 0`, else `<prefix>_SERVER_FREE`.
|
||||||
|
/// Letters, digits and `_` only.
|
||||||
|
pub state_prefix: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Maximum length of an error's `status_message`, in bytes.
|
||||||
|
pub const MAX_STATUS_MESSAGE_BYTES: usize = 256;
|
||||||
|
|
||||||
|
/// Most apps one `applist` answer carries: the client's [`crate::http::applist::MAX_APPS`], which is set so the
|
||||||
|
/// document (the root plus four elements per app) stays within the client's [`crate::http::xml::MAX_XML_ELEMENTS`].
|
||||||
|
pub const MAX_WRITTEN_APPS: usize = MAX_APPS;
|
||||||
|
const _: () =
|
||||||
|
assert!(4 * MAX_WRITTEN_APPS < MAX_XML_ELEMENTS, "an applist at the cap (root + 4 per app) must fit the XML cap");
|
||||||
|
|
||||||
|
/// The declaration every answer starts with.
|
||||||
|
const DECLARATION: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
|
||||||
|
|
||||||
|
/// Checks a value for the client's cap (counted unescaped, as the client counts it) and refuses control
|
||||||
|
/// characters (XML 1.0 cannot carry most of them, and none belongs in these fields).
|
||||||
|
fn check_text(what: &'static str, s: &str, max: usize) -> Result<()> {
|
||||||
|
cap(what, max, s.len())?;
|
||||||
|
if s.chars().any(char::is_control) {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Length of `s` once escaped by [`escape_into`].
|
||||||
|
fn escaped_len(s: &str) -> usize {
|
||||||
|
s.chars()
|
||||||
|
.map(|c| match c {
|
||||||
|
'&' => 5,
|
||||||
|
'<' | '>' => 4,
|
||||||
|
'"' | '\'' => 6,
|
||||||
|
_ => c.len_utf8(),
|
||||||
|
})
|
||||||
|
.sum()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Appends `s` with the five XML special characters escaped (text and attribute values alike).
|
||||||
|
fn escape_into(out: &mut String, s: &str) {
|
||||||
|
for c in s.chars() {
|
||||||
|
match c {
|
||||||
|
'&' => out.push_str("&"),
|
||||||
|
'<' => out.push_str("<"),
|
||||||
|
'>' => out.push_str(">"),
|
||||||
|
'"' => out.push_str("""),
|
||||||
|
'\'' => out.push_str("'"),
|
||||||
|
_ => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<name>escaped text</name>`.
|
||||||
|
fn element(out: &mut String, name: &str, text: &str) {
|
||||||
|
out.push('<');
|
||||||
|
out.push_str(name);
|
||||||
|
out.push('>');
|
||||||
|
escape_into(out, text);
|
||||||
|
out.push_str("</");
|
||||||
|
out.push_str(name);
|
||||||
|
out.push('>');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The whole body: declaration, `<root status_code="200">`, `inner`, `</root>`.
|
||||||
|
fn ok_document(inner: &str) -> Vec<u8> {
|
||||||
|
format!("{DECLARATION}<root status_code=\"200\">{inner}</root>\n").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `serverinfo`. `PairStatus` is 1 only when the request came over HTTPS (`scheme`) with a paired client certificate
|
||||||
|
/// (`client_paired`); over plain HTTP it is always 0 (`docs/PROTOCOL.md` 1.2). `SupportedDisplayMode` is written
|
||||||
|
/// empty (its content is not documented).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::Malformed`] for an empty `hostname` or `unique_id`, a bad `state_prefix`, or control characters;
|
||||||
|
/// [`crate::Error::TooLarge`] for a field over [`MAX_SERVERINFO_FIELD_BYTES`].
|
||||||
|
pub fn server_info_xml(info: &HostInfo, scheme: Scheme, client_paired: bool) -> Result<Vec<u8>> {
|
||||||
|
const BUSY: &str = "_SERVER_BUSY";
|
||||||
|
const FREE: &str = "_SERVER_FREE";
|
||||||
|
for (what, value) in [
|
||||||
|
("serverinfo hostname", &info.hostname),
|
||||||
|
("serverinfo appversion", &info.app_version),
|
||||||
|
("serverinfo GfeVersion", &info.gfe_version),
|
||||||
|
("serverinfo uniqueid", &info.unique_id),
|
||||||
|
("serverinfo LocalIP", &info.local_ip),
|
||||||
|
] {
|
||||||
|
check_text(what, value, MAX_SERVERINFO_FIELD_BYTES)?;
|
||||||
|
}
|
||||||
|
if info.hostname.is_empty() || info.unique_id.is_empty() {
|
||||||
|
return Err(malformed("serverinfo: empty hostname or uniqueid"));
|
||||||
|
}
|
||||||
|
cap("serverinfo state", MAX_SERVERINFO_FIELD_BYTES - BUSY.len(), info.state_prefix.len())?;
|
||||||
|
if info.state_prefix.is_empty() || !info.state_prefix.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'_') {
|
||||||
|
return Err(malformed("serverinfo state prefix"));
|
||||||
|
}
|
||||||
|
let mac = info.mac.map(|m| m.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(":")).unwrap_or_default();
|
||||||
|
let paired = scheme == Scheme::Https && client_paired;
|
||||||
|
let state = format!("{}{}", info.state_prefix, if info.current_game != 0 { BUSY } else { FREE });
|
||||||
|
let mut s = String::new();
|
||||||
|
element(&mut s, "hostname", &info.hostname);
|
||||||
|
element(&mut s, "appversion", &info.app_version);
|
||||||
|
element(&mut s, "GfeVersion", &info.gfe_version);
|
||||||
|
element(&mut s, "uniqueid", &info.unique_id);
|
||||||
|
element(&mut s, "HttpsPort", &info.https_port.to_string());
|
||||||
|
element(&mut s, "ExternalPort", &info.http_port.to_string());
|
||||||
|
element(&mut s, "mac", &mac);
|
||||||
|
element(&mut s, "LocalIP", &info.local_ip);
|
||||||
|
element(&mut s, "MaxLumaPixelsHEVC", &info.max_luma_pixels_hevc.to_string());
|
||||||
|
element(&mut s, "ServerCodecModeSupport", &info.codec_mode_support.to_string());
|
||||||
|
element(&mut s, "SupportedDisplayMode", "");
|
||||||
|
element(&mut s, "PairStatus", if paired { "1" } else { "0" });
|
||||||
|
element(&mut s, "currentgame", &info.current_game.to_string());
|
||||||
|
element(&mut s, "state", &state);
|
||||||
|
let body = ok_document(&s);
|
||||||
|
cap("serverinfo", MAX_SERVERINFO_BYTES, body.len())?;
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `applist`: one `<App>` per app with `AppTitle`, `ID` and `IsHdrSupported`, in the given order.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::TooLarge`] over [`MAX_WRITTEN_APPS`] apps, a title over [`MAX_APP_TITLE_BYTES`] or a body over
|
||||||
|
/// [`MAX_APPLIST_BYTES`]; [`crate::Error::Malformed`] for a duplicate id or control characters.
|
||||||
|
pub fn app_list_xml(apps: &[App]) -> Result<Vec<u8>> {
|
||||||
|
// `<App><AppTitle></AppTitle><ID>4294967295</ID><IsHdrSupported>0</IsHdrSupported></App>` without the title.
|
||||||
|
const PER_APP: usize = 85;
|
||||||
|
cap("applist apps", MAX_WRITTEN_APPS, apps.len())?;
|
||||||
|
let mut ids = std::collections::BTreeSet::new();
|
||||||
|
let mut size = DECLARATION.len() + 64;
|
||||||
|
for app in apps {
|
||||||
|
check_text("applist AppTitle", &app.title, MAX_APP_TITLE_BYTES)?;
|
||||||
|
if !ids.insert(app.id) {
|
||||||
|
return Err(malformed("applist: duplicate ID"));
|
||||||
|
}
|
||||||
|
size = size.saturating_add(PER_APP + escaped_len(&app.title));
|
||||||
|
}
|
||||||
|
cap("applist", MAX_APPLIST_BYTES, size)?;
|
||||||
|
let mut s = String::with_capacity(size);
|
||||||
|
for app in apps {
|
||||||
|
s.push_str("<App>");
|
||||||
|
element(&mut s, "AppTitle", &app.title);
|
||||||
|
element(&mut s, "ID", &app.id.to_string());
|
||||||
|
element(&mut s, "IsHdrSupported", if app.hdr_supported { "1" } else { "0" });
|
||||||
|
s.push_str("</App>");
|
||||||
|
}
|
||||||
|
let body = ok_document(&s);
|
||||||
|
cap("applist", MAX_APPLIST_BYTES, body.len())?;
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `gamesession=1` and `sessionUrl0`.
|
||||||
|
fn session_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
|
||||||
|
const SCHEME: &str = "rtsp://";
|
||||||
|
let port = rtsp_port.to_string();
|
||||||
|
let len = SCHEME.len().saturating_add(rtsp_host.len()).saturating_add(1 + port.len());
|
||||||
|
cap("sessionUrl0", MAX_SESSION_URL_BYTES, len)?;
|
||||||
|
let url = format!("{SCHEME}{rtsp_host}:{port}");
|
||||||
|
check_rtsp_url("sessionUrl0", &url)?;
|
||||||
|
let mut s = String::new();
|
||||||
|
element(&mut s, "gamesession", "1");
|
||||||
|
element(&mut s, "sessionUrl0", &url);
|
||||||
|
Ok(ok_document(&s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `launch`: `gamesession=1` and `sessionUrl0=rtsp://<rtsp_host>:<rtsp_port>` (`docs/PROTOCOL.md` 1.4).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::Malformed`] unless `rtsp_host` is a host name, an IPv4 address or a bracketed IPv6 literal and the
|
||||||
|
/// port is not 0; [`crate::Error::TooLarge`] for a URL over [`MAX_SESSION_URL_BYTES`].
|
||||||
|
pub fn launch_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
|
||||||
|
session_xml(rtsp_host, rtsp_port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `resume`: the same body as [`launch_xml`] (the client reads both with one parser).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// As [`launch_xml`].
|
||||||
|
pub fn resume_xml(rtsp_host: &str, rtsp_port: u16) -> Result<Vec<u8>> {
|
||||||
|
session_xml(rtsp_host, rtsp_port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bare `<root status_code="200"/>`: the answer to `cancel` and `unpair`.
|
||||||
|
#[must_use]
|
||||||
|
pub fn ok_xml() -> Vec<u8> {
|
||||||
|
ok_document("")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pairing answer: `paired` and the phase's element, hex-encoded (`docs/PROTOCOL.md` 1.5).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::TooLarge`] for a certificate over [`MAX_CERT_PEM_BYTES`] or a binary value over
|
||||||
|
/// [`MAX_PAIR_VALUE_BYTES`].
|
||||||
|
pub fn pair_answer_xml(answer: &PairAnswer) -> Result<Vec<u8>> {
|
||||||
|
let mut s = String::new();
|
||||||
|
match answer {
|
||||||
|
PairAnswer::Refused => element(&mut s, "paired", "0"),
|
||||||
|
PairAnswer::Paired => element(&mut s, "paired", "1"),
|
||||||
|
PairAnswer::ServerCert { pem } => {
|
||||||
|
cap("plaincert", MAX_CERT_PEM_BYTES, pem.len())?;
|
||||||
|
element(&mut s, "paired", "1");
|
||||||
|
element(&mut s, "plaincert", &hex_encode(pem.as_bytes()));
|
||||||
|
}
|
||||||
|
PairAnswer::ChallengeResponse(v) => {
|
||||||
|
cap("challengeresponse", MAX_PAIR_VALUE_BYTES, v.len())?;
|
||||||
|
element(&mut s, "paired", "1");
|
||||||
|
element(&mut s, "challengeresponse", &hex_encode(v));
|
||||||
|
}
|
||||||
|
PairAnswer::PairingSecret(v) => {
|
||||||
|
cap("pairingsecret", MAX_PAIR_VALUE_BYTES, v.len())?;
|
||||||
|
element(&mut s, "paired", "1");
|
||||||
|
element(&mut s, "pairingsecret", &hex_encode(v));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let body = ok_document(&s);
|
||||||
|
cap("pairing answer", MAX_PAIR_RESPONSE_BYTES, body.len())?;
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Largest binary value in a pairing answer: a 16-byte secret and an RSA-8192 signature.
|
||||||
|
pub const MAX_PAIR_VALUE_BYTES: usize = SECRET_LEN + MAX_SIGNATURE_BYTES;
|
||||||
|
|
||||||
|
/// The error root: `<root status_code="<code>" status_message="<message>"/>` (`docs/PROTOCOL.md` 1.1).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::Malformed`] for code 200 or a code outside 100..=999, or control characters in `message`;
|
||||||
|
/// [`crate::Error::TooLarge`] for a message over [`MAX_STATUS_MESSAGE_BYTES`].
|
||||||
|
pub fn error_xml(status_code: u32, message: &str) -> Result<Vec<u8>> {
|
||||||
|
if status_code == 200 || !(100..=999).contains(&status_code) {
|
||||||
|
return Err(malformed("error status_code"));
|
||||||
|
}
|
||||||
|
check_text("status_message", message, MAX_STATUS_MESSAGE_BYTES)?;
|
||||||
|
let mut escaped = String::with_capacity(escaped_len(message));
|
||||||
|
escape_into(&mut escaped, message);
|
||||||
|
Ok(format!("{DECLARATION}<root status_code=\"{status_code}\" status_message=\"{escaped}\"/>\n").into_bytes())
|
||||||
|
}
|
||||||
@@ -0,0 +1,486 @@
|
|||||||
|
//! The host's HTTP side (`docs/PROTOCOL.md` section 1): strict parsing of an incoming `GET` request head and its
|
||||||
|
//! query into a typed [`Route`], and the XML answers ([`answer`]).
|
||||||
|
//!
|
||||||
|
//! Every request is hostile input. Caps are checked before anything is allocated: the head
|
||||||
|
//! ([`MAX_HEAD_BYTES`]), the target ([`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`]), the number of parameters
|
||||||
|
//! ([`MAX_PARAMS`]) and each name and value ([`MAX_PARAM_NAME_BYTES`], [`MAX_PARAM_VALUE_BYTES`]), then each typed
|
||||||
|
//! field's own limit. A request never carries a body; a `Content-Length` other than 0 or any `Transfer-Encoding` is
|
||||||
|
//! refused.
|
||||||
|
//!
|
||||||
|
//! Callers whose HTTP server already split the head (TLS front end, an HTTP library) pass the request target to
|
||||||
|
//! [`parse_target`]; callers reading the raw TCP stream cut the head with [`find_head_end`] and pass it to
|
||||||
|
//! [`parse_request_head`].
|
||||||
|
|
||||||
|
use crate::host::pairing::{PairPhase, PairRequest};
|
||||||
|
use crate::http::check_unique_id;
|
||||||
|
use crate::keys::RIKEY_LEN;
|
||||||
|
use crate::pairing::SALT_LEN;
|
||||||
|
use crate::util::{cap, hex_decode, hex_digit, malformed, parse_dec, parse_u32, percent_encode};
|
||||||
|
use crate::{Error, Result, SessionKeys};
|
||||||
|
|
||||||
|
pub mod answer;
|
||||||
|
|
||||||
|
pub use answer::{HostInfo, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, resume_xml, server_info_xml};
|
||||||
|
|
||||||
|
/// Maximum size of a request head (request line, headers and the empty line), in bytes.
|
||||||
|
pub const MAX_HEAD_BYTES: usize = 64 * 1024;
|
||||||
|
/// Maximum number of header lines.
|
||||||
|
pub const MAX_HEADERS: usize = 64;
|
||||||
|
/// Maximum length of the path (before `?`), in bytes.
|
||||||
|
pub const MAX_PATH_BYTES: usize = 256;
|
||||||
|
/// Maximum length of the query (after `?`), in bytes. Room for a phase-1 `clientcert` at its cap.
|
||||||
|
pub const MAX_QUERY_BYTES: usize = 40 * 1024;
|
||||||
|
/// Maximum number of query parameters.
|
||||||
|
pub const MAX_PARAMS: usize = 32;
|
||||||
|
/// Maximum length of a parameter name, in bytes.
|
||||||
|
pub const MAX_PARAM_NAME_BYTES: usize = 64;
|
||||||
|
/// Maximum length of one parameter value as sent (percent-encoded), in bytes: a hex `clientcert` at
|
||||||
|
/// [`crate::pairing::identity::MAX_CERT_PEM_BYTES`].
|
||||||
|
pub const MAX_PARAM_VALUE_BYTES: usize = 2 * crate::pairing::identity::MAX_CERT_PEM_BYTES;
|
||||||
|
/// Maximum length of a hex value other than `clientcert`, in characters (16 bytes of secret plus an RSA-8192
|
||||||
|
/// signature).
|
||||||
|
pub const MAX_HEX_VALUE_CHARS: usize = 2 * (crate::pairing::SECRET_LEN + crate::pairing::MAX_SIGNATURE_BYTES);
|
||||||
|
/// Maximum length of `devicename`, in bytes.
|
||||||
|
pub const MAX_DEVICE_NAME_BYTES: usize = crate::host::pairing::MAX_PAIR_DEVICE_NAME_BYTES;
|
||||||
|
/// Largest width or height accepted in `mode`.
|
||||||
|
pub const MAX_MODE_DIMENSION: u32 = 16_384;
|
||||||
|
/// Largest frame rate accepted in `mode`.
|
||||||
|
pub const MAX_MODE_FPS: u32 = 1000;
|
||||||
|
|
||||||
|
/// A stream mode, `mode=<width>x<height>x<fps>`.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct DisplayMode {
|
||||||
|
/// Width in pixels, 1..=[`MAX_MODE_DIMENSION`].
|
||||||
|
pub width: u32,
|
||||||
|
/// Height in pixels, 1..=[`MAX_MODE_DIMENSION`].
|
||||||
|
pub height: u32,
|
||||||
|
/// Frames per second, 1..=[`MAX_MODE_FPS`].
|
||||||
|
pub fps: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /launch` (`docs/PROTOCOL.md` 1.4).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct LaunchRequest {
|
||||||
|
/// `appid`.
|
||||||
|
pub app_id: u32,
|
||||||
|
/// `mode`.
|
||||||
|
pub mode: DisplayMode,
|
||||||
|
/// `rikey` and `rikeyid`.
|
||||||
|
pub keys: SessionKeys,
|
||||||
|
/// `hdrMode`, if sent.
|
||||||
|
pub hdr: Option<bool>,
|
||||||
|
/// `surroundAudioInfo`, if sent: `(channel_mask << 16) | channel_count`.
|
||||||
|
pub surround_audio_info: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `GET /resume` (`docs/PROTOCOL.md` 1.4): fresh keys; the launch parameters only if the client repeats them.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ResumeRequest {
|
||||||
|
/// `rikey` and `rikeyid`.
|
||||||
|
pub keys: SessionKeys,
|
||||||
|
/// `appid`, if sent.
|
||||||
|
pub app_id: Option<u32>,
|
||||||
|
/// `mode`, if sent.
|
||||||
|
pub mode: Option<DisplayMode>,
|
||||||
|
/// `hdrMode`, if sent.
|
||||||
|
pub hdr: Option<bool>,
|
||||||
|
/// `surroundAudioInfo`, if sent.
|
||||||
|
pub surround_audio_info: Option<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the request asks for.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Route {
|
||||||
|
/// `/serverinfo` (HTTP or HTTPS).
|
||||||
|
ServerInfo,
|
||||||
|
/// `/applist` (HTTPS).
|
||||||
|
AppList,
|
||||||
|
/// `/launch` (HTTPS).
|
||||||
|
Launch(LaunchRequest),
|
||||||
|
/// `/resume` (HTTPS).
|
||||||
|
Resume(ResumeRequest),
|
||||||
|
/// `/cancel` (HTTPS).
|
||||||
|
Cancel,
|
||||||
|
/// `/pair` (phases 1-4 over HTTP, phase 5 over HTTPS); feed it to [`crate::host::pairing::HostPairingSession`].
|
||||||
|
Pair(PairRequest),
|
||||||
|
/// `/unpair` (HTTPS).
|
||||||
|
Unpair,
|
||||||
|
/// `/appasset` (HTTPS): box art of one app.
|
||||||
|
AppAsset {
|
||||||
|
/// `appid`.
|
||||||
|
app_id: u32,
|
||||||
|
},
|
||||||
|
/// Any other path (answer 404). The path as sent, never decoded, never used to open anything.
|
||||||
|
Unknown {
|
||||||
|
/// The path.
|
||||||
|
path: String,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One parsed request.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HostRequest {
|
||||||
|
/// The route and its typed parameters.
|
||||||
|
pub route: Route,
|
||||||
|
/// `uniqueid`, if sent (required for `/pair`).
|
||||||
|
pub unique_id: Option<String>,
|
||||||
|
/// Parameters this parser does not know, decoded, in order: kept for logs so black-box clients can be measured
|
||||||
|
/// (`docs/PROTOCOL.md` UNKNOWN U4). Never used to decide anything.
|
||||||
|
pub other_params: Vec<(String, String)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The empty line that ends a head.
|
||||||
|
const HEAD_END: &[u8] = b"\r\n\r\n";
|
||||||
|
|
||||||
|
/// Finds the end of a request head in the bytes read so far: `Some(len)` (the head is `buf[..len]`, ending in the
|
||||||
|
/// empty line) or `None` (read more).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] when no head end is within the first [`MAX_HEAD_BYTES`] (so a buffer of that size without
|
||||||
|
/// one is refused: the head could only end past the cap).
|
||||||
|
pub fn find_head_end(buf: &[u8]) -> Result<Option<usize>> {
|
||||||
|
let window = buf.get(..MAX_HEAD_BYTES).unwrap_or(buf);
|
||||||
|
if let Some(at) = window.windows(HEAD_END.len()).position(|w| w == HEAD_END) {
|
||||||
|
return Ok(Some(at + HEAD_END.len()));
|
||||||
|
}
|
||||||
|
if buf.len() >= MAX_HEAD_BYTES {
|
||||||
|
return Err(Error::TooLarge { what: "http request head", max: MAX_HEAD_BYTES, actual: buf.len() });
|
||||||
|
}
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RFC 9110 `tchar`.
|
||||||
|
fn is_token(b: u8) -> bool {
|
||||||
|
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses one complete request head (`GET <target> HTTP/1.1`, headers, the empty line, nothing after it).
|
||||||
|
///
|
||||||
|
/// Only visible ASCII, space and tab are accepted inside lines, every line ends in CRLF, header lines are never
|
||||||
|
/// folded, and header names are tokens. Headers are otherwise ignored (the host needs none of them), except that a
|
||||||
|
/// `Content-Length` other than `0` or any `Transfer-Encoding` is refused: a `GET` here never carries a body.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`MAX_HEAD_BYTES`], [`MAX_HEADERS`] or a target cap, [`Error::Unsupported`] for a
|
||||||
|
/// method other than `GET`, [`Error::Malformed`] for anything else that is not a strict HTTP/1.x head or a valid
|
||||||
|
/// target (see [`parse_target`]).
|
||||||
|
pub fn parse_request_head(head: &[u8]) -> Result<HostRequest> {
|
||||||
|
cap("http request head", MAX_HEAD_BYTES, head.len())?;
|
||||||
|
let end = head.windows(HEAD_END.len()).position(|w| w == HEAD_END).ok_or(malformed("http head: no empty line"))?;
|
||||||
|
if end + HEAD_END.len() != head.len() {
|
||||||
|
return Err(malformed("http head: bytes after the empty line"));
|
||||||
|
}
|
||||||
|
if !head.iter().all(|&b| matches!(b, b' '..=b'~' | b'\t' | b'\r' | b'\n')) {
|
||||||
|
return Err(malformed("http head: a byte that is not visible ASCII"));
|
||||||
|
}
|
||||||
|
let text = core::str::from_utf8(head.get(..end).unwrap_or(&[])).map_err(|_| malformed("http head: not ASCII"))?;
|
||||||
|
let mut lines = text.split("\r\n");
|
||||||
|
let request_line = lines.next().unwrap_or("");
|
||||||
|
if request_line.contains(['\r', '\n']) {
|
||||||
|
return Err(malformed("http head: bare CR or LF"));
|
||||||
|
}
|
||||||
|
let mut parts = request_line.split(' ');
|
||||||
|
let (Some(method), Some(target), Some(version), None) = (parts.next(), parts.next(), parts.next(), parts.next())
|
||||||
|
else {
|
||||||
|
return Err(malformed("http request line"));
|
||||||
|
};
|
||||||
|
if method.is_empty() || !method.bytes().all(is_token) || target.is_empty() {
|
||||||
|
return Err(malformed("http request line"));
|
||||||
|
}
|
||||||
|
if version != "HTTP/1.1" && version != "HTTP/1.0" {
|
||||||
|
return Err(malformed("http version"));
|
||||||
|
}
|
||||||
|
if method != "GET" {
|
||||||
|
return Err(Error::Unsupported { what: "http method other than GET" });
|
||||||
|
}
|
||||||
|
let mut count = 0usize;
|
||||||
|
let mut content_length = false;
|
||||||
|
for line in lines {
|
||||||
|
count += 1;
|
||||||
|
cap("http headers", MAX_HEADERS, count)?;
|
||||||
|
if line.contains(['\r', '\n']) {
|
||||||
|
return Err(malformed("http head: bare CR or LF"));
|
||||||
|
}
|
||||||
|
if line.starts_with([' ', '\t']) {
|
||||||
|
return Err(malformed("http head: folded header line"));
|
||||||
|
}
|
||||||
|
let (name, value) = line.split_once(':').ok_or(malformed("http header without :"))?;
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("http header name"));
|
||||||
|
}
|
||||||
|
let value = value.trim_matches([' ', '\t']);
|
||||||
|
if name.eq_ignore_ascii_case("content-length") {
|
||||||
|
if content_length || value != "0" {
|
||||||
|
return Err(malformed("http head: a body on a GET"));
|
||||||
|
}
|
||||||
|
content_length = true;
|
||||||
|
} else if name.eq_ignore_ascii_case("transfer-encoding") {
|
||||||
|
return Err(malformed("http head: a body on a GET"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parse_target(target)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The parsed parameters; typed fields are taken out one by one, the rest stays for [`HostRequest::other_params`].
|
||||||
|
struct Params(Vec<(String, String)>);
|
||||||
|
|
||||||
|
impl Params {
|
||||||
|
fn take(&mut self, name: &str) -> Option<String> {
|
||||||
|
let at = self.0.iter().position(|(n, _)| n == name)?;
|
||||||
|
Some(self.0.remove(at).1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require(&mut self, name: &str, what: &'static str) -> Result<String> {
|
||||||
|
self.take(name).ok_or(malformed(what))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<width>x<height>x<fps>`, each strict decimal and in range.
|
||||||
|
fn parse_mode(s: &str) -> Result<DisplayMode> {
|
||||||
|
let mut parts = s.split('x');
|
||||||
|
let (Some(w), Some(h), Some(f), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else {
|
||||||
|
return Err(malformed("mode"));
|
||||||
|
};
|
||||||
|
let (width, height, fps) = (parse_u32("mode", w)?, parse_u32("mode", h)?, parse_u32("mode", f)?);
|
||||||
|
let dims = 1..=MAX_MODE_DIMENSION;
|
||||||
|
if !dims.contains(&width) || !dims.contains(&height) || !(1..=MAX_MODE_FPS).contains(&fps) {
|
||||||
|
return Err(malformed("mode out of range"));
|
||||||
|
}
|
||||||
|
Ok(DisplayMode { width, height, fps })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `rikeyid`: unsigned decimal, or a negative 32-bit decimal read as its two's complement (tolerated: a client
|
||||||
|
/// may print the id as a signed integer; the bytes on the wire are the same).
|
||||||
|
fn parse_rikeyid(s: &str) -> Result<u32> {
|
||||||
|
match s.strip_prefix('-') {
|
||||||
|
Some(digits) => {
|
||||||
|
let v = parse_dec("rikeyid", digits)?;
|
||||||
|
if v == 0 || v > 1 << 31 {
|
||||||
|
return Err(malformed("rikeyid"));
|
||||||
|
}
|
||||||
|
Ok(0u32.wrapping_sub(u32::try_from(v).map_err(|_| malformed("rikeyid"))?))
|
||||||
|
}
|
||||||
|
None => parse_u32("rikeyid", s),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `rikey` (exactly 32 hex digits) and `rikeyid`, both required.
|
||||||
|
fn parse_keys(p: &mut Params) -> Result<SessionKeys> {
|
||||||
|
let rikey = p.require("rikey", "no rikey")?;
|
||||||
|
if rikey.len() != 2 * RIKEY_LEN {
|
||||||
|
return Err(malformed("rikey"));
|
||||||
|
}
|
||||||
|
let bytes = hex_decode("rikey", &rikey)?;
|
||||||
|
let rikey = crate::util::array::<RIKEY_LEN>("rikey", &bytes, 0)?;
|
||||||
|
let rikeyid = parse_rikeyid(&p.require("rikeyid", "no rikeyid")?)?;
|
||||||
|
Ok(SessionKeys { rikey, rikeyid })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_flag(what: &'static str, s: &str) -> Result<bool> {
|
||||||
|
match s {
|
||||||
|
"0" => Ok(false),
|
||||||
|
"1" => Ok(true),
|
||||||
|
_ => Err(malformed(what)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `hdrMode` and `surroundAudioInfo`, both optional.
|
||||||
|
fn parse_stream_options(p: &mut Params) -> Result<(Option<bool>, Option<u32>)> {
|
||||||
|
let hdr = p.take("hdrMode").map(|v| parse_flag("hdrMode", &v)).transpose()?;
|
||||||
|
let audio = p.take("surroundAudioInfo").map(|v| parse_u32("surroundAudioInfo", &v)).transpose()?;
|
||||||
|
Ok((hdr, audio))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_launch(p: &mut Params) -> Result<LaunchRequest> {
|
||||||
|
let app_id = parse_u32("appid", &p.require("appid", "no appid")?)?;
|
||||||
|
let mode = parse_mode(&p.require("mode", "no mode")?)?;
|
||||||
|
let keys = parse_keys(p)?;
|
||||||
|
let (hdr, surround_audio_info) = parse_stream_options(p)?;
|
||||||
|
Ok(LaunchRequest { app_id, mode, keys, hdr, surround_audio_info })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_resume(p: &mut Params) -> Result<ResumeRequest> {
|
||||||
|
let keys = parse_keys(p)?;
|
||||||
|
let app_id = p.take("appid").map(|v| parse_u32("appid", &v)).transpose()?;
|
||||||
|
let mode = p.take("mode").map(|v| parse_mode(&v)).transpose()?;
|
||||||
|
let (hdr, surround_audio_info) = parse_stream_options(p)?;
|
||||||
|
Ok(ResumeRequest { keys, app_id, mode, hdr, surround_audio_info })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A non-empty hex value of at most `max` characters.
|
||||||
|
fn pair_hex(what: &'static str, s: &str, max: usize) -> Result<Vec<u8>> {
|
||||||
|
cap(what, max, s.len())?;
|
||||||
|
if s.is_empty() {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
hex_decode(what, s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The phase of a `/pair` request (`docs/PROTOCOL.md` 1.5): `phrase=getservercert` (with `salt` and `clientcert`),
|
||||||
|
/// `phrase=pairchallenge`, or exactly one of `clientchallenge`, `serverchallengeresp`, `clientpairingsecret`.
|
||||||
|
fn parse_pair(p: &mut Params, unique_id: Option<&str>) -> Result<PairRequest> {
|
||||||
|
let unique_id = unique_id.ok_or(malformed("pair: no uniqueid"))?.to_owned();
|
||||||
|
let device_name = match p.take("devicename") {
|
||||||
|
Some(d) => {
|
||||||
|
cap("devicename", MAX_DEVICE_NAME_BYTES, d.len())?;
|
||||||
|
Some(d).filter(|d| !d.is_empty())
|
||||||
|
}
|
||||||
|
None => None,
|
||||||
|
};
|
||||||
|
let phrase = p.take("phrase");
|
||||||
|
let salt = p.take("salt");
|
||||||
|
let cert = p.take("clientcert");
|
||||||
|
let challenge = p.take("clientchallenge");
|
||||||
|
let response = p.take("serverchallengeresp");
|
||||||
|
let secret = p.take("clientpairingsecret");
|
||||||
|
let phase = match (phrase.as_deref(), challenge, response, secret) {
|
||||||
|
(Some("getservercert"), None, None, None) => {
|
||||||
|
let salt = salt.ok_or(malformed("pair: no salt"))?;
|
||||||
|
if salt.len() != 2 * SALT_LEN {
|
||||||
|
return Err(malformed("pair: salt"));
|
||||||
|
}
|
||||||
|
let salt = crate::util::array::<SALT_LEN>("pair: salt", &hex_decode("pair: salt", &salt)?, 0)?;
|
||||||
|
let cert = cert.ok_or(malformed("pair: no clientcert"))?;
|
||||||
|
let client_cert_pem = pair_hex("pair: clientcert", &cert, MAX_PARAM_VALUE_BYTES)?;
|
||||||
|
return Ok(PairRequest {
|
||||||
|
unique_id,
|
||||||
|
device_name,
|
||||||
|
phase: PairPhase::GetServerCert { salt, client_cert_pem },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
(Some("pairchallenge"), None, None, None) => PairPhase::PairChallenge,
|
||||||
|
(None, Some(v), None, None) => {
|
||||||
|
PairPhase::ClientChallenge(pair_hex("clientchallenge", &v, MAX_HEX_VALUE_CHARS)?)
|
||||||
|
}
|
||||||
|
(None, None, Some(v), None) => {
|
||||||
|
PairPhase::ServerChallengeResp(pair_hex("serverchallengeresp", &v, MAX_HEX_VALUE_CHARS)?)
|
||||||
|
}
|
||||||
|
(None, None, None, Some(v)) => {
|
||||||
|
PairPhase::ClientPairingSecret(pair_hex("clientpairingsecret", &v, MAX_HEX_VALUE_CHARS)?)
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("pair: not exactly one known phase")),
|
||||||
|
};
|
||||||
|
if salt.is_some() || cert.is_some() {
|
||||||
|
return Err(malformed("pair: salt or clientcert outside getservercert"));
|
||||||
|
}
|
||||||
|
Ok(PairRequest { unique_id, device_name, phase })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a request target (`/path?query`) into a typed request.
|
||||||
|
///
|
||||||
|
/// The path is matched exactly (case-sensitive, never decoded); an unknown path is [`Route::Unknown`]. The target
|
||||||
|
/// must be visible ASCII without a fragment. `uniqueid` is checked wherever it appears (letters, digits, `-`, `_`,
|
||||||
|
/// at most [`crate::http::MAX_UNIQUE_ID_BYTES`]).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`MAX_PATH_BYTES`], [`MAX_QUERY_BYTES`] or a parameter cap, [`Error::Malformed`] for a
|
||||||
|
/// bad character, a bad or repeated parameter, or a missing or bad required parameter of a known route.
|
||||||
|
pub fn parse_target(target: &str) -> Result<HostRequest> {
|
||||||
|
let (path, query) = match target.split_once('?') {
|
||||||
|
Some((path, query)) => (path, query),
|
||||||
|
None => (target, ""),
|
||||||
|
};
|
||||||
|
cap("http path", MAX_PATH_BYTES, path.len())?;
|
||||||
|
cap("http query", MAX_QUERY_BYTES, query.len())?;
|
||||||
|
if !path.starts_with('/') {
|
||||||
|
return Err(malformed("http target: not a path"));
|
||||||
|
}
|
||||||
|
if !target.bytes().all(|b| b.is_ascii_graphic() && b != b'#') {
|
||||||
|
return Err(malformed("http target: a character outside visible ASCII, or a fragment"));
|
||||||
|
}
|
||||||
|
let mut p = Params(parse_query(query)?);
|
||||||
|
let unique_id = p.take("uniqueid");
|
||||||
|
if let Some(u) = &unique_id {
|
||||||
|
check_unique_id(u)?;
|
||||||
|
}
|
||||||
|
let route = match path {
|
||||||
|
"/serverinfo" => Route::ServerInfo,
|
||||||
|
"/applist" => Route::AppList,
|
||||||
|
"/launch" => Route::Launch(parse_launch(&mut p)?),
|
||||||
|
"/resume" => Route::Resume(parse_resume(&mut p)?),
|
||||||
|
"/cancel" => Route::Cancel,
|
||||||
|
"/pair" => Route::Pair(parse_pair(&mut p, unique_id.as_deref())?),
|
||||||
|
"/unpair" => Route::Unpair,
|
||||||
|
"/appasset" => Route::AppAsset { app_id: parse_u32("appid", &p.require("appid", "no appid")?)? },
|
||||||
|
_ => Route::Unknown { path: path.to_owned() },
|
||||||
|
};
|
||||||
|
Ok(HostRequest { route, unique_id, other_params: p.0 })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One percent-decoded value: `%XX` (either case), `+` as a space, other visible ASCII as itself; UTF-8 without
|
||||||
|
/// control characters.
|
||||||
|
fn percent_decode(value: &str) -> Result<String> {
|
||||||
|
let b = value.as_bytes();
|
||||||
|
let mut out = Vec::with_capacity(b.len());
|
||||||
|
let mut i = 0;
|
||||||
|
while let Some(&c) = b.get(i) {
|
||||||
|
match c {
|
||||||
|
b'%' => {
|
||||||
|
let hi = b.get(i + 1).copied().and_then(hex_digit);
|
||||||
|
let lo = b.get(i + 2).copied().and_then(hex_digit);
|
||||||
|
let (Some(hi), Some(lo)) = (hi, lo) else { return Err(malformed("query: bad % escape")) };
|
||||||
|
out.push((hi << 4) | lo);
|
||||||
|
i += 3;
|
||||||
|
}
|
||||||
|
b'+' => {
|
||||||
|
out.push(b' ');
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
b'!'..=b'~' => {
|
||||||
|
out.push(c);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("query: a raw character outside visible ASCII")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let s = String::from_utf8(out).map_err(|_| malformed("query: value is not UTF-8"))?;
|
||||||
|
if s.chars().any(char::is_control) {
|
||||||
|
return Err(malformed("query: control character in a value"));
|
||||||
|
}
|
||||||
|
Ok(s)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses a query string (without `?`) into decoded `(name, value)` pairs, in order. Names are taken as sent
|
||||||
|
/// (letters, digits, `_`, `-`, `.`); values are percent-decoded (`+` is a space) and must be UTF-8 without control
|
||||||
|
/// characters. Empty segments (`a=1&&b=2`) are skipped; a repeated name is refused.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`MAX_QUERY_BYTES`], [`MAX_PARAMS`], [`MAX_PARAM_NAME_BYTES`] or
|
||||||
|
/// [`MAX_PARAM_VALUE_BYTES`]; [`Error::Malformed`] otherwise.
|
||||||
|
pub fn parse_query(query: &str) -> Result<Vec<(String, String)>> {
|
||||||
|
cap("http query", MAX_QUERY_BYTES, query.len())?;
|
||||||
|
let segments = || query.split('&').filter(|s| !s.is_empty());
|
||||||
|
let count = segments().count();
|
||||||
|
cap("http query parameters", MAX_PARAMS, count)?;
|
||||||
|
let mut out: Vec<(String, String)> = Vec::with_capacity(count);
|
||||||
|
for segment in segments() {
|
||||||
|
let (name, value) = segment.split_once('=').unwrap_or((segment, ""));
|
||||||
|
cap("http parameter name", MAX_PARAM_NAME_BYTES, name.len())?;
|
||||||
|
if name.is_empty() || !name.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-' | b'.')) {
|
||||||
|
return Err(malformed("query: parameter name"));
|
||||||
|
}
|
||||||
|
cap("http parameter value", MAX_PARAM_VALUE_BYTES, value.len())?;
|
||||||
|
if out.iter().any(|(n, _)| n == name) {
|
||||||
|
return Err(malformed("query: repeated parameter"));
|
||||||
|
}
|
||||||
|
let value = percent_decode(value)?;
|
||||||
|
out.push((name.to_owned(), value));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes `(name, value)` pairs as a query string (without `?`): values percent-encoded except RFC 3986 unreserved
|
||||||
|
/// characters, names as given. The inverse of [`parse_query`] for valid names and values.
|
||||||
|
#[must_use]
|
||||||
|
pub fn encode_query(params: &[(&str, &str)]) -> String {
|
||||||
|
let mut out = String::new();
|
||||||
|
for (i, (name, value)) in params.iter().enumerate() {
|
||||||
|
if i > 0 {
|
||||||
|
out.push('&');
|
||||||
|
}
|
||||||
|
out.push_str(name);
|
||||||
|
out.push('=');
|
||||||
|
out.push_str(&percent_encode(value));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
//! The host side of GameStream, for Lumen (Arena Domi's own streaming host). Sans-I/O like the rest of the crate:
|
||||||
|
//! lumen-host owns the sockets, TLS, the clock, randomness and storage; this module only turns bytes into typed
|
||||||
|
//! requests, runs the pairing state machine and writes the XML answers.
|
||||||
|
//!
|
||||||
|
//! | Module | What (see `docs/PROTOCOL.md`) |
|
||||||
|
//! | :-- | :-- |
|
||||||
|
//! | [`http`] | strict parsing of an incoming `GET` request head and query into a typed [`http::Route`], and the XML answers (section 1) |
|
||||||
|
//! | [`pairing`] | the host's half of the PIN handshake, with a pending-PIN slot fed by the caller (section 1.5) |
|
||||||
|
//!
|
||||||
|
//! The client half of this crate ([`crate::pairing`], [`crate::http`]) is tested against this half in memory.
|
||||||
|
|
||||||
|
pub mod http;
|
||||||
|
pub mod pairing;
|
||||||
|
|
||||||
|
pub use http::{HostRequest, Route, parse_request_head, parse_target};
|
||||||
|
pub use pairing::{HostIdentity, HostPairingFailure, HostPairingSession, HostPairingState, PairAnswer, PairedClient};
|
||||||
@@ -0,0 +1,585 @@
|
|||||||
|
//! The host's half of the PIN pairing handshake (`docs/PROTOCOL.md` 1.5), as a sans-I/O state machine: the
|
||||||
|
//! mirror of the client's [`crate::pairing::PairingSession`].
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! new ─▶ AwaitGetServerCert ─(getservercert)─▶ AwaitPin ─(supply_pin)─▶ AwaitClientChallenge
|
||||||
|
//! │ (clientchallenge)
|
||||||
|
//! AwaitClientPairingSecret ◀─(serverchallengeresp)─ AwaitServerChallengeResp ◀┘
|
||||||
|
//! │ (clientpairingsecret: signature and proof checked)
|
||||||
|
//! ▼
|
||||||
|
//! AwaitPairChallenge ─(pairchallenge over HTTPS, same client certificate)─▶ Paired
|
||||||
|
//! any step: wrong phase / bad input / bad signature / wrong PIN / deadline passed / cancel ─▶ Failed
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! The PIN is not known when the first phase arrives: the machine answers it with [`HostPairingStep::HoldForPin`]
|
||||||
|
//! and the caller keeps that HTTP request open until the owner types the code from the phone into Arena Domi's
|
||||||
|
//! "Enter the code from your phone" box; [`HostPairingSession::supply_pin`] then returns the held answer.
|
||||||
|
//!
|
||||||
|
//! **Trusted clients (Tessera grants).** The handshake's AES key is `SHA-256(salt ‖ PIN)`, so the wire handshake
|
||||||
|
//! cannot complete unless both sides know the same PIN. A client the owner already trusts (a Tessera grant) does
|
||||||
|
//! not run it at all: [`PairedClient::trusted`] records its certificate directly, with no PIN anywhere
|
||||||
|
//! (`docs/LUMEN-HOST-PLAN.md` 1.9).
|
||||||
|
//!
|
||||||
|
//! When a call fails, the state becomes [`HostPairingState::Failed`] and the caller answers the request (and a
|
||||||
|
//! held phase-1 request, if any) with [`PairAnswer::Refused`]. Failed and Paired are terminal.
|
||||||
|
|
||||||
|
use core::fmt;
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use crate::http::{Scheme, check_unique_id};
|
||||||
|
use crate::pairing::identity::MAX_CERT_DER_BYTES;
|
||||||
|
use crate::pairing::{CHALLENGE_LEN, ClientIdentity, HASH_LEN, Pin, SALT_LEN, SECRET_LEN, ServerCert, crypto};
|
||||||
|
use crate::util::{array, cap, ct_eq, malformed};
|
||||||
|
use crate::{Error, Instant, RandomSource, Result};
|
||||||
|
|
||||||
|
/// A failed step: why, and the error to return.
|
||||||
|
type StepError = (HostPairingFailure, Error);
|
||||||
|
|
||||||
|
/// Default time the owner has to type the PIN after the first phase arrives (the client waits as long, see
|
||||||
|
/// [`crate::pairing::STEP1_TIMEOUT`]).
|
||||||
|
pub const DEFAULT_PIN_TIMEOUT: Duration = Duration::from_secs(120);
|
||||||
|
/// Default time the client has for each later phase after the host's previous answer.
|
||||||
|
pub const DEFAULT_PHASE_TIMEOUT: Duration = Duration::from_secs(30);
|
||||||
|
/// Maximum length of the device name kept from the first phase, in bytes.
|
||||||
|
pub const MAX_PAIR_DEVICE_NAME_BYTES: usize = 256;
|
||||||
|
/// Length of the encrypted client challenge (phase 2), in bytes.
|
||||||
|
pub const CLIENT_CHALLENGE_LEN: usize = CHALLENGE_LEN;
|
||||||
|
/// Length of the encrypted client proof (phase 3), in bytes.
|
||||||
|
pub const SERVER_CHALLENGE_RESP_LEN: usize = HASH_LEN;
|
||||||
|
/// Length of the host secret (phase 3 answer), in bytes.
|
||||||
|
pub const HOST_SECRET_LEN: usize = SECRET_LEN;
|
||||||
|
|
||||||
|
/// The host's long-lived GameStream identity: a self-signed RSA-2048 / SHA-256 certificate and its key. The same
|
||||||
|
/// certificate is sent as `plaincert` while pairing and presented by the HTTPS server. `Debug` never prints the key.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct HostIdentity {
|
||||||
|
inner: ClientIdentity,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostIdentity {
|
||||||
|
/// Generates a new key and self-signed certificate (same rules as
|
||||||
|
/// [`crate::pairing::ClientIdentity::generate`]); `not_before_unix` is passed in, never read from a clock.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a bad `common_name` or time, [`Error::Crypto`] if key generation fails.
|
||||||
|
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
|
||||||
|
ClientIdentity::generate(rng, common_name, not_before_unix).map(|inner| Self { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Loads a stored identity and checks that the key matches the certificate.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// As [`crate::pairing::ClientIdentity::from_der`].
|
||||||
|
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
||||||
|
ClientIdentity::from_der(cert_der, key_pkcs8_der).map(|inner| Self { inner })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The certificate, DER (what the HTTPS server presents).
|
||||||
|
#[must_use]
|
||||||
|
pub fn cert_der(&self) -> &[u8] {
|
||||||
|
self.inner.cert_der()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The private key, PKCS#8 DER, for the secret store and the TLS stack.
|
||||||
|
#[must_use]
|
||||||
|
pub fn key_pkcs8_der(&self) -> &[u8] {
|
||||||
|
self.inner.key_pkcs8_der()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The certificate as PEM text (what `plaincert` carries, hex-encoded).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// None today.
|
||||||
|
pub fn cert_pem(&self) -> Result<String> {
|
||||||
|
self.inner.cert_pem()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for HostIdentity {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("HostIdentity")
|
||||||
|
.field("cert_der_len", &self.inner.cert_der().len())
|
||||||
|
.field("key", &"<redacted>")
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pairing phase as the client sent it (`docs/PROTOCOL.md` 1.5), hex already decoded by
|
||||||
|
/// [`crate::host::http`]. Lengths are checked by the state machine, not here.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum PairPhase {
|
||||||
|
/// Phase 1 (`phrase=getservercert`): the 16-byte salt and the client certificate as PEM text.
|
||||||
|
GetServerCert {
|
||||||
|
/// `salt`.
|
||||||
|
salt: [u8; SALT_LEN],
|
||||||
|
/// `clientcert`, hex-decoded: the client certificate PEM.
|
||||||
|
client_cert_pem: Vec<u8>,
|
||||||
|
},
|
||||||
|
/// Phase 2 (`clientchallenge`): `E_K(C)`.
|
||||||
|
ClientChallenge(Vec<u8>),
|
||||||
|
/// Phase 3 (`serverchallengeresp`): `E_K(H_c)`.
|
||||||
|
ServerChallengeResp(Vec<u8>),
|
||||||
|
/// Phase 4 (`clientpairingsecret`): `secret_c ‖ Sign_client(secret_c)`.
|
||||||
|
ClientPairingSecret(Vec<u8>),
|
||||||
|
/// Phase 5 (`phrase=pairchallenge`), over HTTPS with the client certificate.
|
||||||
|
PairChallenge,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PairPhase {
|
||||||
|
/// The phase number, 1..=5 (for logs).
|
||||||
|
#[must_use]
|
||||||
|
pub const fn number(&self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::GetServerCert { .. } => 1,
|
||||||
|
Self::ClientChallenge(_) => 2,
|
||||||
|
Self::ServerChallengeResp(_) => 3,
|
||||||
|
Self::ClientPairingSecret(_) => 4,
|
||||||
|
Self::PairChallenge => 5,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `/pair` request: who sends it and which phase.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct PairRequest {
|
||||||
|
/// `uniqueid`: the client's id; every phase of one pairing must carry the same one.
|
||||||
|
pub unique_id: String,
|
||||||
|
/// `devicename`, if sent (kept from phase 1, shown to the owner).
|
||||||
|
pub device_name: Option<String>,
|
||||||
|
/// The phase.
|
||||||
|
pub phase: PairPhase,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How a request reached the host.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Transport<'a> {
|
||||||
|
/// Plain HTTP.
|
||||||
|
Http,
|
||||||
|
/// HTTPS; `client_cert_der` is the certificate the client presented in the TLS handshake.
|
||||||
|
Https {
|
||||||
|
/// The client's TLS certificate, DER.
|
||||||
|
client_cert_der: &'a [u8],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Transport<'_> {
|
||||||
|
/// [`Scheme::Http`] or [`Scheme::Https`].
|
||||||
|
#[must_use]
|
||||||
|
pub const fn scheme(&self) -> Scheme {
|
||||||
|
match self {
|
||||||
|
Self::Http => Scheme::Http,
|
||||||
|
Self::Https { .. } => Scheme::Https,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host answers to one phase (`<root status_code="200"><paired>…</paired>…</root>`); serialize it with
|
||||||
|
/// [`crate::host::http::pair_answer_xml`].
|
||||||
|
#[derive(Clone, PartialEq, Eq)]
|
||||||
|
pub enum PairAnswer {
|
||||||
|
/// `paired=0`: pairing refused or failed.
|
||||||
|
Refused,
|
||||||
|
/// Phase 1: `paired=1`, `plaincert` = the host certificate PEM.
|
||||||
|
ServerCert {
|
||||||
|
/// The host certificate PEM text.
|
||||||
|
pem: String,
|
||||||
|
},
|
||||||
|
/// Phase 2: `paired=1`, `challengeresponse` = `E_K(H_s ‖ S_c)`, 48 bytes.
|
||||||
|
ChallengeResponse(Vec<u8>),
|
||||||
|
/// Phase 3: `paired=1`, `pairingsecret` = `secret_s ‖ Sign_host(secret_s)`.
|
||||||
|
PairingSecret(Vec<u8>),
|
||||||
|
/// Phases 4 and 5: `paired=1` alone.
|
||||||
|
Paired,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for PairAnswer {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Refused => f.write_str("Refused"),
|
||||||
|
Self::ServerCert { pem } => f.debug_struct("ServerCert").field("pem_len", &pem.len()).finish(),
|
||||||
|
Self::ChallengeResponse(v) => f.debug_tuple("ChallengeResponse").field(&v.len()).finish(),
|
||||||
|
Self::PairingSecret(v) => f.debug_tuple("PairingSecret").field(&v.len()).finish(),
|
||||||
|
Self::Paired => f.write_str("Paired"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A client whose certificate the host accepts on HTTPS from now on. Store it (signed by the host key, per
|
||||||
|
/// `docs/LUMEN-HOST-PLAN.md` 1.9).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct PairedClient {
|
||||||
|
/// The client certificate, DER: exactly what its TLS handshake must present.
|
||||||
|
pub cert_der: Vec<u8>,
|
||||||
|
/// `uniqueid` from the pairing, `None` for a trusted client recorded without a handshake.
|
||||||
|
pub unique_id: Option<String>,
|
||||||
|
/// `devicename` from the pairing, if sent.
|
||||||
|
pub device_name: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PairedClient {
|
||||||
|
/// The Tessera grant path: records a client certificate the owner already trusts, with no PIN and no wire
|
||||||
|
/// handshake. Checks that it is one well-formed X.509 certificate with an RSA key.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
|
||||||
|
pub fn trusted(cert_der: &[u8]) -> Result<Self> {
|
||||||
|
ServerCert::from_der(cert_der)?;
|
||||||
|
Ok(Self { cert_der: cert_der.to_vec(), unique_id: None, device_name: None })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TLS authorization: whether the certificate a client presents over HTTPS (DER) is exactly this one, compared
|
||||||
|
/// in constant time.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`crate::pairing::identity::MAX_CERT_DER_BYTES`].
|
||||||
|
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
||||||
|
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
|
||||||
|
Ok(ct_eq(&self.cert_der, presented_der))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client that started a pairing, as phase 1 described it: what the owner's prompt shows.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct PendingClient {
|
||||||
|
/// `uniqueid`.
|
||||||
|
pub unique_id: String,
|
||||||
|
/// `devicename`, if sent.
|
||||||
|
pub device_name: Option<String>,
|
||||||
|
/// The client certificate, DER.
|
||||||
|
pub cert_der: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the host's handshake is.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum HostPairingState {
|
||||||
|
/// Nothing received yet; waiting for phase 1 (`getservercert`).
|
||||||
|
AwaitGetServerCert,
|
||||||
|
/// Phase 1 received; its answer is held until [`HostPairingSession::supply_pin`].
|
||||||
|
AwaitPin,
|
||||||
|
/// Phase 1 answered (`plaincert`); waiting for phase 2 (`clientchallenge`).
|
||||||
|
AwaitClientChallenge,
|
||||||
|
/// Phase 2 answered (`challengeresponse`); waiting for phase 3 (`serverchallengeresp`).
|
||||||
|
AwaitServerChallengeResp,
|
||||||
|
/// Phase 3 answered (`pairingsecret`); waiting for phase 4 (`clientpairingsecret`).
|
||||||
|
AwaitClientPairingSecret,
|
||||||
|
/// Phase 4 checked and answered; waiting for phase 5 (`pairchallenge` over HTTPS).
|
||||||
|
AwaitPairChallenge,
|
||||||
|
/// Done; see [`HostPairingSession::paired_client`].
|
||||||
|
Paired,
|
||||||
|
/// Stopped; see [`HostPairingFailure`]. No further calls are accepted.
|
||||||
|
Failed(HostPairingFailure),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why the host stopped a pairing.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum HostPairingFailure {
|
||||||
|
/// The client's proof `H_c` did not match: the PIN typed on the host differs from the client's (or someone is in
|
||||||
|
/// the middle).
|
||||||
|
WrongPin,
|
||||||
|
/// The client's signature over its secret did not verify against the certificate from phase 1.
|
||||||
|
BadSignature,
|
||||||
|
/// A phase arrived that is not the one expected now (replayed, reordered or skipped).
|
||||||
|
WrongOrder,
|
||||||
|
/// A phase came from another client than phase 1 (other `uniqueid`, or phase 5 without the phase-1 certificate
|
||||||
|
/// over HTTPS).
|
||||||
|
WrongClient,
|
||||||
|
/// A phase's value had the wrong length or the client certificate did not parse.
|
||||||
|
Malformed,
|
||||||
|
/// The caller's time passed the deadline (PIN not typed in time, or the client stopped answering).
|
||||||
|
TimedOut,
|
||||||
|
/// The caller cancelled (the owner closed the code box).
|
||||||
|
Cancelled,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Timeouts of one pairing.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HostPairingConfig {
|
||||||
|
/// How long the owner has to type the PIN after phase 1 arrives.
|
||||||
|
pub pin_timeout: Duration,
|
||||||
|
/// How long the client has for each phase after the host's previous answer (and for phase 1 after `new`).
|
||||||
|
pub phase_timeout: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for HostPairingConfig {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { pin_timeout: DEFAULT_PIN_TIMEOUT, phase_timeout: DEFAULT_PHASE_TIMEOUT }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What to do with the request just handled.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum HostPairingStep {
|
||||||
|
/// Answer it now with this.
|
||||||
|
Answer(PairAnswer),
|
||||||
|
/// Hold it open: the answer comes from [`HostPairingSession::supply_pin`] (or is [`PairAnswer::Refused`] when the
|
||||||
|
/// session fails or times out first). Show the owner the code box for [`HostPairingSession::pending_client`].
|
||||||
|
HoldForPin,
|
||||||
|
/// Pairing finished: answer with [`PairAnswer::Paired`] and store the client.
|
||||||
|
Paired(PairedClient),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One pairing attempt by one client.
|
||||||
|
pub struct HostPairingSession {
|
||||||
|
state: HostPairingState,
|
||||||
|
config: HostPairingConfig,
|
||||||
|
deadline: Instant,
|
||||||
|
host_cert_der: Vec<u8>,
|
||||||
|
pending: Option<PendingClient>,
|
||||||
|
client_cert: Option<ServerCert>,
|
||||||
|
salt: [u8; SALT_LEN],
|
||||||
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
|
server_challenge: [u8; CHALLENGE_LEN],
|
||||||
|
host_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
|
||||||
|
client_proof: [u8; HASH_LEN],
|
||||||
|
paired: Option<PairedClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostPairingSession {
|
||||||
|
/// A new pairing, waiting for phase 1 until `now + config.phase_timeout`. `identity` must be passed to every
|
||||||
|
/// later call (it is borrowed per call, so the session never holds a copy of the private key).
|
||||||
|
#[must_use]
|
||||||
|
pub fn new(identity: &HostIdentity, config: HostPairingConfig, now: Instant) -> Self {
|
||||||
|
Self {
|
||||||
|
state: HostPairingState::AwaitGetServerCert,
|
||||||
|
config,
|
||||||
|
deadline: now.saturating_add(config.phase_timeout),
|
||||||
|
host_cert_der: identity.cert_der().to_vec(),
|
||||||
|
pending: None,
|
||||||
|
client_cert: None,
|
||||||
|
salt: [0; SALT_LEN],
|
||||||
|
key: zeroize::Zeroizing::new([0; 16]),
|
||||||
|
server_challenge: [0; CHALLENGE_LEN],
|
||||||
|
host_secret: zeroize::Zeroizing::new([0; SECRET_LEN]),
|
||||||
|
client_proof: [0; HASH_LEN],
|
||||||
|
paired: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn is_over(&self) -> bool {
|
||||||
|
matches!(self.state, HostPairingState::Paired | HostPairingState::Failed(_))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail<T>(&mut self, why: HostPairingFailure, error: Error) -> Result<T> {
|
||||||
|
self.state = HostPairingState::Failed(why);
|
||||||
|
Err(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Handles one `/pair` request. Draws randomness in phase 2 (host challenge and host secret, 16 bytes each).
|
||||||
|
///
|
||||||
|
/// Phases 1-4 are accepted over either transport; phase 5 only over HTTPS with exactly the certificate of
|
||||||
|
/// phase 1. Every phase must carry the `uniqueid` of phase 1.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::PairingRefused`] for a wrong phase, client, signature or PIN; [`Error::Malformed`] /
|
||||||
|
/// [`Error::TooLarge`] for bad values; [`Error::TimedOut`] past the deadline; in each case the state becomes
|
||||||
|
/// [`HostPairingState::Failed`]. [`Error::State`] after `Paired` or `Failed`; [`Error::Malformed`] for a
|
||||||
|
/// different identity than at `new` (state unchanged).
|
||||||
|
pub fn handle(
|
||||||
|
&mut self,
|
||||||
|
identity: &HostIdentity,
|
||||||
|
request: &PairRequest,
|
||||||
|
transport: Transport<'_>,
|
||||||
|
now: Instant,
|
||||||
|
rng: &mut dyn RandomSource,
|
||||||
|
) -> Result<HostPairingStep> {
|
||||||
|
if self.is_over() {
|
||||||
|
return Err(Error::State { expected: "a pairing in progress" });
|
||||||
|
}
|
||||||
|
if identity.cert_der() != self.host_cert_der.as_slice() {
|
||||||
|
return Err(malformed("host pairing: a different identity than at the start"));
|
||||||
|
}
|
||||||
|
if now > self.deadline {
|
||||||
|
return self.fail(HostPairingFailure::TimedOut, Error::TimedOut);
|
||||||
|
}
|
||||||
|
match self.step(identity, request, transport, now, rng) {
|
||||||
|
Ok(step) => Ok(step),
|
||||||
|
Err((why, e)) => self.fail(why, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every phase after the first must come from the client of phase 1.
|
||||||
|
fn same_client(&self, request: &PairRequest) -> core::result::Result<(), StepError> {
|
||||||
|
match &self.pending {
|
||||||
|
Some(p) if p.unique_id == request.unique_id => Ok(()),
|
||||||
|
_ => Err((HostPairingFailure::WrongClient, Error::PairingRefused)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_phase(&mut self, state: HostPairingState, now: Instant, timeout: Duration) {
|
||||||
|
self.state = state;
|
||||||
|
self.deadline = now.saturating_add(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(
|
||||||
|
&mut self,
|
||||||
|
identity: &HostIdentity,
|
||||||
|
request: &PairRequest,
|
||||||
|
transport: Transport<'_>,
|
||||||
|
now: Instant,
|
||||||
|
rng: &mut dyn RandomSource,
|
||||||
|
) -> core::result::Result<HostPairingStep, StepError> {
|
||||||
|
let bad = |e: Error| (HostPairingFailure::Malformed, e);
|
||||||
|
match (self.state, &request.phase) {
|
||||||
|
(HostPairingState::AwaitGetServerCert, PairPhase::GetServerCert { salt, client_cert_pem }) => {
|
||||||
|
check_unique_id(&request.unique_id).map_err(bad)?;
|
||||||
|
if let Some(name) = &request.device_name {
|
||||||
|
cap("devicename", MAX_PAIR_DEVICE_NAME_BYTES, name.len()).map_err(bad)?;
|
||||||
|
if name.chars().any(char::is_control) {
|
||||||
|
return Err(bad(malformed("devicename")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let cert = ServerCert::from_pem(client_cert_pem).map_err(bad)?;
|
||||||
|
self.salt = *salt;
|
||||||
|
self.pending = Some(PendingClient {
|
||||||
|
unique_id: request.unique_id.clone(),
|
||||||
|
device_name: request.device_name.clone(),
|
||||||
|
cert_der: cert.der().to_vec(),
|
||||||
|
});
|
||||||
|
self.client_cert = Some(cert);
|
||||||
|
self.next_phase(HostPairingState::AwaitPin, now, self.config.pin_timeout);
|
||||||
|
Ok(HostPairingStep::HoldForPin)
|
||||||
|
}
|
||||||
|
(HostPairingState::AwaitClientChallenge, PairPhase::ClientChallenge(encrypted)) => {
|
||||||
|
self.same_client(request)?;
|
||||||
|
if encrypted.len() != CLIENT_CHALLENGE_LEN {
|
||||||
|
return Err(bad(malformed("clientchallenge is not 16 bytes")));
|
||||||
|
}
|
||||||
|
let challenge = array::<CHALLENGE_LEN>(
|
||||||
|
"clientchallenge",
|
||||||
|
&crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
.map_err(bad)?;
|
||||||
|
rng.fill(&mut self.server_challenge);
|
||||||
|
rng.fill(&mut *self.host_secret);
|
||||||
|
let host_sig = identity.inner.cert_signature().map_err(bad)?;
|
||||||
|
let host_proof = crypto::proof_hash(&challenge, &host_sig, &self.host_secret).map_err(bad)?;
|
||||||
|
let plain = [&host_proof[..], &self.server_challenge[..]].concat();
|
||||||
|
let answer = crypto::ecb_encrypt(&self.key, &plain).map_err(bad)?;
|
||||||
|
self.next_phase(HostPairingState::AwaitServerChallengeResp, now, self.config.phase_timeout);
|
||||||
|
Ok(HostPairingStep::Answer(PairAnswer::ChallengeResponse(answer)))
|
||||||
|
}
|
||||||
|
(HostPairingState::AwaitServerChallengeResp, PairPhase::ServerChallengeResp(encrypted)) => {
|
||||||
|
self.same_client(request)?;
|
||||||
|
if encrypted.len() != SERVER_CHALLENGE_RESP_LEN {
|
||||||
|
return Err(bad(malformed("serverchallengeresp is not 32 bytes")));
|
||||||
|
}
|
||||||
|
let proof = crypto::ecb_decrypt(&self.key, encrypted).map_err(bad)?;
|
||||||
|
self.client_proof = array::<HASH_LEN>("serverchallengeresp", &proof, 0).map_err(bad)?;
|
||||||
|
let signature = identity.inner.sign(&*self.host_secret).map_err(bad)?;
|
||||||
|
let answer = [&self.host_secret[..], &signature].concat();
|
||||||
|
self.next_phase(HostPairingState::AwaitClientPairingSecret, now, self.config.phase_timeout);
|
||||||
|
Ok(HostPairingStep::Answer(PairAnswer::PairingSecret(answer)))
|
||||||
|
}
|
||||||
|
(HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => {
|
||||||
|
self.same_client(request)?;
|
||||||
|
let (secret, signature) = crypto::split_pairing_secret(value).map_err(bad)?;
|
||||||
|
let cert = self.client_cert.as_ref().ok_or_else(|| bad(malformed("host pairing: no client cert")))?;
|
||||||
|
cert.verify(&secret, signature)
|
||||||
|
.map_err(|_| (HostPairingFailure::BadSignature, Error::PairingRefused))?;
|
||||||
|
let client_sig = cert.signature().map_err(bad)?;
|
||||||
|
let expected = crypto::proof_hash(&self.server_challenge, &client_sig, &secret).map_err(bad)?;
|
||||||
|
if !ct_eq(&expected, &self.client_proof) {
|
||||||
|
return Err((HostPairingFailure::WrongPin, Error::PairingRefused));
|
||||||
|
}
|
||||||
|
self.next_phase(HostPairingState::AwaitPairChallenge, now, self.config.phase_timeout);
|
||||||
|
Ok(HostPairingStep::Answer(PairAnswer::Paired))
|
||||||
|
}
|
||||||
|
(HostPairingState::AwaitPairChallenge, PairPhase::PairChallenge) => {
|
||||||
|
self.same_client(request)?;
|
||||||
|
let pending = self.pending.as_ref().ok_or((HostPairingFailure::WrongClient, Error::PairingRefused))?;
|
||||||
|
let Transport::Https { client_cert_der } = transport else {
|
||||||
|
return Err((HostPairingFailure::WrongClient, Error::PairingRefused));
|
||||||
|
};
|
||||||
|
if !ct_eq(client_cert_der, &pending.cert_der) {
|
||||||
|
return Err((HostPairingFailure::WrongClient, Error::PairingRefused));
|
||||||
|
}
|
||||||
|
let client = PairedClient {
|
||||||
|
cert_der: pending.cert_der.clone(),
|
||||||
|
unique_id: Some(pending.unique_id.clone()),
|
||||||
|
device_name: pending.device_name.clone(),
|
||||||
|
};
|
||||||
|
self.paired = Some(client.clone());
|
||||||
|
self.state = HostPairingState::Paired;
|
||||||
|
Ok(HostPairingStep::Paired(client))
|
||||||
|
}
|
||||||
|
_ => Err((HostPairingFailure::WrongOrder, Error::PairingRefused)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owner typed the PIN: derives the key `SHA-256(salt ‖ PIN)[0..16]` and returns the held answer to phase 1
|
||||||
|
/// (the host certificate). Whether the PIN matches the client's shows only in phase 4.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::State`] unless the state is [`HostPairingState::AwaitPin`] (state unchanged); [`Error::Malformed`]
|
||||||
|
/// for a different identity (state unchanged); [`Error::TimedOut`] past the PIN deadline (state becomes Failed).
|
||||||
|
pub fn supply_pin(&mut self, identity: &HostIdentity, pin: Pin, now: Instant) -> Result<PairAnswer> {
|
||||||
|
if self.state != HostPairingState::AwaitPin {
|
||||||
|
return Err(Error::State { expected: "a phase-1 request held for the PIN" });
|
||||||
|
}
|
||||||
|
if identity.cert_der() != self.host_cert_der.as_slice() {
|
||||||
|
return Err(malformed("host pairing: a different identity than at the start"));
|
||||||
|
}
|
||||||
|
if now > self.deadline {
|
||||||
|
return self.fail(HostPairingFailure::TimedOut, Error::TimedOut);
|
||||||
|
}
|
||||||
|
let pem = match identity.cert_pem() {
|
||||||
|
Ok(pem) => pem,
|
||||||
|
Err(e) => return self.fail(HostPairingFailure::Malformed, e),
|
||||||
|
};
|
||||||
|
*self.key = crypto::derive_key(&self.salt, &pin)?;
|
||||||
|
self.next_phase(HostPairingState::AwaitClientChallenge, now, self.config.phase_timeout);
|
||||||
|
Ok(PairAnswer::ServerCert { pem })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The owner closed the code box (or the caller gives up): the state becomes `Failed(Cancelled)` unless it is
|
||||||
|
/// already terminal. Answer a held request with [`PairAnswer::Refused`].
|
||||||
|
pub fn cancel(&mut self) {
|
||||||
|
if !self.is_over() {
|
||||||
|
self.state = HostPairingState::Failed(HostPairingFailure::Cancelled);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// When the session times out, if it is still in progress. The session is late only after this instant.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn poll_timeout(&self) -> Option<Instant> {
|
||||||
|
if self.is_over() { None } else { Some(self.deadline) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wakes the session at its deadline: returns `true` when this call moved it to `Failed(TimedOut)` (answer a
|
||||||
|
/// held request with [`PairAnswer::Refused`]).
|
||||||
|
pub fn handle_timeout(&mut self, now: Instant) -> bool {
|
||||||
|
if self.is_over() || now <= self.deadline {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
self.state = HostPairingState::Failed(HostPairingFailure::TimedOut);
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the handshake is.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn state(&self) -> HostPairingState {
|
||||||
|
self.state
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client of phase 1 (for the owner's prompt and the grant check), once phase 1 has arrived.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn pending_client(&self) -> Option<&PendingClient> {
|
||||||
|
self.pending.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The paired client, once [`HostPairingState::Paired`].
|
||||||
|
#[must_use]
|
||||||
|
pub const fn paired_client(&self) -> Option<&PairedClient> {
|
||||||
|
self.paired.as_ref()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Debug for HostPairingSession {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
f.debug_struct("HostPairingSession")
|
||||||
|
.field("state", &self.state)
|
||||||
|
.field("deadline", &self.deadline)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,15 @@
|
|||||||
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
||||||
|
|
||||||
|
use super::xml::MAX_XML_ELEMENTS;
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
use crate::util::{cap, malformed, parse_u32};
|
use crate::util::{cap, malformed, parse_u32};
|
||||||
|
|
||||||
/// Maximum size of an applist body, in bytes.
|
/// Maximum size of an applist body, in bytes.
|
||||||
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
||||||
/// Maximum number of apps accepted in one list.
|
/// Maximum number of apps accepted in one list: as many as fit the XML element cap with the four elements a host
|
||||||
pub const MAX_APPS: usize = 4096;
|
/// writes per app (`App`, `AppTitle`, `ID`, `IsHdrSupported`) plus the root, so a full list is refused by this cap and
|
||||||
|
/// never by the XML parser first.
|
||||||
|
pub const MAX_APPS: usize = (MAX_XML_ELEMENTS - 1) / 4;
|
||||||
/// Maximum length of an app title, in bytes.
|
/// Maximum length of an app title, in bytes.
|
||||||
pub const MAX_APP_TITLE_BYTES: usize = 512;
|
pub const MAX_APP_TITLE_BYTES: usize = 512;
|
||||||
|
|
||||||
|
|||||||
@@ -21,13 +21,14 @@
|
|||||||
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
|
//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) |
|
||||||
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
|
//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) |
|
||||||
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
|
//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) |
|
||||||
//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) |
|
//! | [`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 (sections 3.2, 3.3) |
|
//! | [`control`] | AES-GCM framing and control messages, client and host side (sections 3.2, 3.3) |
|
||||||
//! | [`input`] | input and gamepad packets (section 4) |
|
//! | [`input`] | input and gamepad packets (section 4) |
|
||||||
//! | [`rtp`] | the RTP header shared by video and audio |
|
//! | [`rtp`] | the RTP header shared by video and audio |
|
||||||
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
||||||
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
|
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
|
||||||
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
|
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer |
|
||||||
|
//! | [`host`] | the host side, for Lumen: request parsing, XML answers and the host's pairing machine (sections 1, 1.5) |
|
||||||
//!
|
//!
|
||||||
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
||||||
|
|
||||||
@@ -40,6 +41,7 @@ pub mod enet;
|
|||||||
pub mod entropy;
|
pub mod entropy;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod fec;
|
pub mod fec;
|
||||||
|
pub mod host;
|
||||||
pub mod http;
|
pub mod http;
|
||||||
pub mod input;
|
pub mod input;
|
||||||
pub mod keys;
|
pub mod keys;
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
|
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
|
||||||
//! and the client state machine.
|
//! the client state machine and the host's session ([`server`], section 2.5).
|
||||||
|
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod sdp;
|
pub mod sdp;
|
||||||
|
pub mod server;
|
||||||
|
|
||||||
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
||||||
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
||||||
|
pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply};
|
||||||
|
|
||||||
use crate::util::{cap, malformed, parse_dec};
|
use crate::util::{cap, malformed, parse_dec};
|
||||||
use crate::{Error, Result};
|
use crate::{Error, Result};
|
||||||
@@ -132,6 +134,37 @@ impl RtspResponse {
|
|||||||
pub fn header(&self, name: &str) -> Option<&str> {
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
header(&self.headers, name)
|
header(&self.headers, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serializes the response (`RTSP/1.0 <status> <reason>`, CRLF line ends, empty line, payload) with exactly the
|
||||||
|
/// given headers. The host side's mirror of [`RtspRequest::encode`].
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a
|
||||||
|
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
|
||||||
|
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
|
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||||
|
if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) {
|
||||||
|
return Err(malformed("rtsp status line"));
|
||||||
|
}
|
||||||
|
let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason);
|
||||||
|
for (name, value) in &self.headers {
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
|
||||||
|
return Err(malformed("rtsp header value"));
|
||||||
|
}
|
||||||
|
out.push_str(name);
|
||||||
|
out.push_str(": ");
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
out.push_str("\r\n");
|
||||||
|
let mut bytes = out.into_bytes();
|
||||||
|
cap("rtsp response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||||
|
bytes.extend_from_slice(&self.body);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A message split into start line, headers and payload.
|
/// A message split into start line, headers and payload.
|
||||||
@@ -252,21 +285,31 @@ pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
|
|||||||
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuts the TCP byte stream from the host into whole messages.
|
/// Cuts a TCP byte stream into whole messages.
|
||||||
///
|
///
|
||||||
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
|
/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
|
||||||
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
|
/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
|
||||||
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading
|
||||||
|
/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message
|
||||||
|
/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct RtspFramer {
|
pub struct RtspFramer {
|
||||||
buffer: Vec<u8>,
|
buffer: Vec<u8>,
|
||||||
|
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
|
||||||
|
missing_length_is_zero: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RtspFramer {
|
impl RtspFramer {
|
||||||
/// An empty framer.
|
/// An empty framer for the host's answers (client side).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new() -> Self {
|
pub const fn new() -> Self {
|
||||||
Self { buffer: Vec::new() }
|
Self { buffer: Vec::new(), missing_length_is_zero: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn for_requests() -> Self {
|
||||||
|
Self { buffer: Vec::new(), missing_length_is_zero: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends received bytes.
|
/// Appends received bytes.
|
||||||
@@ -293,7 +336,8 @@ impl RtspFramer {
|
|||||||
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(Some((head_len, content_length(&headers, head_len)?)))
|
let length = content_length(&headers, head_len)?;
|
||||||
|
Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes the next complete message, if one is buffered.
|
/// Takes the next complete message, if one is buffered.
|
||||||
|
|||||||
@@ -199,7 +199,7 @@ impl HostCapabilities {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6).
|
/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
||||||
match codec {
|
match codec {
|
||||||
VideoCodec::H264 => 0,
|
VideoCodec::H264 => 0,
|
||||||
|
|||||||
@@ -0,0 +1,338 @@
|
|||||||
|
//! The ANNOUNCE payload on the host side (`docs/PROTOCOL.md` 2.4, 2.5): a strict parser of the client's SDP into a
|
||||||
|
//! typed [`StreamConfig`], and the matching writer.
|
||||||
|
//!
|
||||||
|
//! The payload is hostile input. The parser caps the payload size, the number of lines, the length of each line and
|
||||||
|
//! the number of `a=` attributes before it looks at any of them, allocates nothing while it reads, refuses a known
|
||||||
|
//! attribute that appears twice, range-checks every number, and counts (then ignores) attributes it does not know.
|
||||||
|
|
||||||
|
use crate::rtsp::client::VideoCodec;
|
||||||
|
use crate::rtsp::sdp::{EncryptionFlags, MAX_AUDIO_CHANNELS};
|
||||||
|
use crate::util::{cap, malformed, parse_dec};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// Maximum size of an ANNOUNCE payload, in bytes (the SDP cap of `docs/PROTOCOL.md` 2.3).
|
||||||
|
pub const MAX_ANNOUNCE_BYTES: usize = crate::rtsp::sdp::MAX_SDP_BYTES;
|
||||||
|
/// Maximum number of non-empty lines in an ANNOUNCE payload.
|
||||||
|
pub const MAX_ANNOUNCE_LINES: usize = 1024;
|
||||||
|
/// Maximum length of one line, in bytes, without its line end.
|
||||||
|
pub const MAX_ANNOUNCE_LINE_BYTES: usize = 1024;
|
||||||
|
/// Maximum number of `a=` attributes, known or not.
|
||||||
|
pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512;
|
||||||
|
|
||||||
|
/// Largest width or height accepted, in pixels (our cap, not the protocol's).
|
||||||
|
pub const MAX_DIMENSION: u32 = 16_384;
|
||||||
|
/// Largest frame rate accepted (our cap, not the protocol's).
|
||||||
|
pub const MAX_FPS: u32 = 1000;
|
||||||
|
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MIN_PACKET_SIZE: u16 = 200;
|
||||||
|
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MAX_PACKET_SIZE: u16 = 65_471;
|
||||||
|
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MAX_BITRATE_KBPS: u32 = 4_294_967;
|
||||||
|
/// Longest audio packet in milliseconds: the longest Opus packet (RFC 6716 section 3.2.5).
|
||||||
|
pub const MAX_AUDIO_PACKET_DURATION_MS: u8 = 120;
|
||||||
|
|
||||||
|
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ChromaSampling {
|
||||||
|
/// 4:2:0, value 0 (the default).
|
||||||
|
#[default]
|
||||||
|
Yuv420,
|
||||||
|
/// 4:4:4, value 1.
|
||||||
|
Yuv444,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio layout the client asks for (`x-nv-audio.surround.*`, `docs/PROTOCOL.md` 2.5).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct SurroundSettings {
|
||||||
|
/// `x-nv-audio.surround.enable`: 0 or 1, default 0. When off, a Moonshine-like host takes the layout from the
|
||||||
|
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\].
|
||||||
|
pub enabled: bool,
|
||||||
|
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 \[M\].
|
||||||
|
pub channels: u8,
|
||||||
|
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` \[M\].
|
||||||
|
pub channel_mask: u32,
|
||||||
|
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\].
|
||||||
|
pub high_quality: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SurroundSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, channels: 2, channel_mask: 0x3, high_quality: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a client asked for in ANNOUNCE, typed and range-checked (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||||
|
///
|
||||||
|
/// Values whose meaning is not settled are kept as the raw number the client sent.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct StreamConfig {
|
||||||
|
/// `x-nv-video[0].clientViewportWd`, required, 1..=[`MAX_DIMENSION`].
|
||||||
|
pub width: u32,
|
||||||
|
/// `x-nv-video[0].clientViewportHt`, required, 1..=[`MAX_DIMENSION`].
|
||||||
|
pub height: u32,
|
||||||
|
/// `x-nv-video[0].maxFPS`, required, 1..=[`MAX_FPS`].
|
||||||
|
pub max_fps: u32,
|
||||||
|
/// `x-nv-video[0].packetSize`, required, [`MIN_PACKET_SIZE`]..=[`MAX_PACKET_SIZE`].
|
||||||
|
pub packet_size: u16,
|
||||||
|
/// `x-ml-video.configuredBitrateKbps`, required, 1..=[`MAX_BITRATE_KBPS`].
|
||||||
|
pub bitrate_kbps: u32,
|
||||||
|
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 \[M\]; anything else is refused.
|
||||||
|
pub codec: VideoCodec,
|
||||||
|
/// `x-nv-vqos[0].fec.minRequiredFecPackets`, required, 0..=255.
|
||||||
|
pub min_fec_packets: u8,
|
||||||
|
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 \[M\]).
|
||||||
|
pub video_qos_traffic_type: u32,
|
||||||
|
/// `x-nv-aqos.packetDuration`, required, 1..=[`MAX_AUDIO_PACKET_DURATION_MS`] milliseconds.
|
||||||
|
pub audio_packet_duration_ms: u8,
|
||||||
|
/// `x-nv-aqos.qosTrafficType`, required, kept as sent.
|
||||||
|
pub audio_qos_traffic_type: u32,
|
||||||
|
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 \[M\]. Kept raw: what 0 means has GPL provenance only
|
||||||
|
/// (\[M*\], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
|
||||||
|
pub max_reference_frames: u32,
|
||||||
|
/// `x-nv-video[0].refPicInvalidation`, 0 or 1. Default 0 (the client cannot invalidate, so the host sends an
|
||||||
|
/// IDR frame on loss, which always works): UNKNOWN U6, settled by measurement.
|
||||||
|
pub reference_frame_invalidation: bool,
|
||||||
|
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR \[M\]; no other value has a
|
||||||
|
/// settled meaning: UNKNOWN U6, settled by measurement.
|
||||||
|
pub dynamic_range_mode: u32,
|
||||||
|
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only (\[M*\]):
|
||||||
|
/// UNKNOWN U6, settled by measurement (`docs/LUMEN-HOST-PLAN.md` 1.3).
|
||||||
|
pub encoder_csc_mode: u32,
|
||||||
|
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) \[M\].
|
||||||
|
pub chroma: ChromaSampling,
|
||||||
|
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 \[M\]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
|
||||||
|
/// [`super::RtspServer`] refuses bits the host did not offer.
|
||||||
|
pub encryption: EncryptionFlags,
|
||||||
|
/// `x-nv-audio.surround.*`.
|
||||||
|
pub surround: SurroundSettings,
|
||||||
|
/// `a=` attributes the parser does not know: counted, otherwise ignored (UNKNOWN U6). Not written by
|
||||||
|
/// [`write_announce`].
|
||||||
|
pub unknown_attributes: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses an ANNOUNCE payload (SDP lines, LF or CRLF, empty lines skipped) into a [`StreamConfig`].
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`MAX_ANNOUNCE_BYTES`], [`MAX_ANNOUNCE_LINES`], [`MAX_ANNOUNCE_LINE_BYTES`] or
|
||||||
|
/// [`MAX_ANNOUNCE_ATTRIBUTES`]; [`Error::Malformed`] for a payload that is not UTF-8, a line without `=`, an empty
|
||||||
|
/// line type, a control character, a known attribute given twice, a required attribute missing or a number that is
|
||||||
|
/// not plain decimal; [`Error::UnexpectedValue`] for a number outside its range.
|
||||||
|
pub fn parse_announce(payload: &[u8]) -> Result<StreamConfig> {
|
||||||
|
cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?;
|
||||||
|
let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?;
|
||||||
|
let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()];
|
||||||
|
let mut lines = 0usize;
|
||||||
|
let mut attributes = 0usize;
|
||||||
|
let mut unknown = 0u32;
|
||||||
|
for raw in text.split('\n') {
|
||||||
|
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||||
|
cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?;
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lines += 1;
|
||||||
|
cap("announce lines", MAX_ANNOUNCE_LINES, lines)?;
|
||||||
|
if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
|
||||||
|
return Err(malformed("announce: control character in a line"));
|
||||||
|
}
|
||||||
|
let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?;
|
||||||
|
if kind.is_empty() {
|
||||||
|
return Err(malformed("announce: line with an empty type"));
|
||||||
|
}
|
||||||
|
// Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read.
|
||||||
|
if kind != "a" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
attributes += 1;
|
||||||
|
cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?;
|
||||||
|
let (name, value) = rest.split_once(':').unwrap_or((rest, ""));
|
||||||
|
match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) {
|
||||||
|
Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),
|
||||||
|
Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])),
|
||||||
|
None => unknown = unknown.saturating_add(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let a = Values(&values);
|
||||||
|
let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? {
|
||||||
|
0 => VideoCodec::H264,
|
||||||
|
1 => VideoCodec::Hevc,
|
||||||
|
_ => VideoCodec::Av1,
|
||||||
|
};
|
||||||
|
Ok(StreamConfig {
|
||||||
|
width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?,
|
||||||
|
height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?,
|
||||||
|
max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?,
|
||||||
|
packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?,
|
||||||
|
bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?,
|
||||||
|
codec,
|
||||||
|
min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?,
|
||||||
|
video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||||
|
audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?,
|
||||||
|
audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||||
|
max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?,
|
||||||
|
reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1,
|
||||||
|
dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||||
|
encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||||
|
chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 {
|
||||||
|
ChromaSampling::Yuv444
|
||||||
|
} else {
|
||||||
|
ChromaSampling::Yuv420
|
||||||
|
},
|
||||||
|
encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?),
|
||||||
|
surround: SurroundSettings {
|
||||||
|
enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1,
|
||||||
|
channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?,
|
||||||
|
channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?,
|
||||||
|
high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1,
|
||||||
|
},
|
||||||
|
unknown_attributes: unknown,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that
|
||||||
|
/// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0).
|
||||||
|
#[must_use]
|
||||||
|
pub fn write_announce(config: &StreamConfig) -> Vec<u8> {
|
||||||
|
let codec: u8 = match config.codec {
|
||||||
|
VideoCodec::H264 => 0,
|
||||||
|
VideoCodec::Hevc => 1,
|
||||||
|
VideoCodec::Av1 => 2,
|
||||||
|
};
|
||||||
|
let chroma: u8 = match config.chroma {
|
||||||
|
ChromaSampling::Yuv420 => 0,
|
||||||
|
ChromaSampling::Yuv444 => 1,
|
||||||
|
};
|
||||||
|
let s = &config.surround;
|
||||||
|
let values: [(usize, u64); ATTRIBUTES.len()] = [
|
||||||
|
(VIEWPORT_WD, u64::from(config.width)),
|
||||||
|
(VIEWPORT_HT, u64::from(config.height)),
|
||||||
|
(MAX_FPS_ATTR, u64::from(config.max_fps)),
|
||||||
|
(PACKET_SIZE, u64::from(config.packet_size)),
|
||||||
|
(BITRATE, u64::from(config.bitrate_kbps)),
|
||||||
|
(BIT_STREAM_FORMAT, u64::from(codec)),
|
||||||
|
(MIN_FEC_PACKETS, u64::from(config.min_fec_packets)),
|
||||||
|
(VIDEO_QOS, u64::from(config.video_qos_traffic_type)),
|
||||||
|
(PACKET_DURATION, u64::from(config.audio_packet_duration_ms)),
|
||||||
|
(AUDIO_QOS, u64::from(config.audio_qos_traffic_type)),
|
||||||
|
(MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)),
|
||||||
|
(REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)),
|
||||||
|
(DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)),
|
||||||
|
(ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)),
|
||||||
|
(CHROMA_SAMPLING, u64::from(chroma)),
|
||||||
|
(ENCRYPTION_ENABLED, u64::from(config.encryption.0)),
|
||||||
|
(SURROUND_ENABLE, u64::from(s.enabled)),
|
||||||
|
(SURROUND_CHANNELS, u64::from(s.channels)),
|
||||||
|
(SURROUND_MASK, u64::from(s.channel_mask)),
|
||||||
|
(AUDIO_QUALITY, u64::from(s.high_quality)),
|
||||||
|
];
|
||||||
|
let mut out = String::with_capacity(1024);
|
||||||
|
out.push_str("v=0\r\n");
|
||||||
|
for (index, value) in values {
|
||||||
|
if let Some(attribute) = ATTRIBUTES.get(index) {
|
||||||
|
out.push_str("a=");
|
||||||
|
out.push_str(attribute.name);
|
||||||
|
out.push(':');
|
||||||
|
out.push_str(&value.to_string());
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||||
|
struct Attribute {
|
||||||
|
/// The SDP attribute name.
|
||||||
|
name: &'static str,
|
||||||
|
/// The error text when a required attribute is missing; `None` for attributes with a default.
|
||||||
|
missing: Option<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn required(name: &'static str, missing: &'static str) -> Attribute {
|
||||||
|
Attribute { name, missing: Some(missing) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn defaulted(name: &'static str) -> Attribute {
|
||||||
|
Attribute { name, missing: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
const VIEWPORT_WD: usize = 0;
|
||||||
|
const VIEWPORT_HT: usize = 1;
|
||||||
|
const MAX_FPS_ATTR: usize = 2;
|
||||||
|
const PACKET_SIZE: usize = 3;
|
||||||
|
const BITRATE: usize = 4;
|
||||||
|
const BIT_STREAM_FORMAT: usize = 5;
|
||||||
|
const MIN_FEC_PACKETS: usize = 6;
|
||||||
|
const VIDEO_QOS: usize = 7;
|
||||||
|
const PACKET_DURATION: usize = 8;
|
||||||
|
const AUDIO_QOS: usize = 9;
|
||||||
|
const MAX_REFERENCE_FRAMES: usize = 10;
|
||||||
|
const REF_PIC_INVALIDATION: usize = 11;
|
||||||
|
const DYNAMIC_RANGE_MODE: usize = 12;
|
||||||
|
const ENCODER_CSC_MODE: usize = 13;
|
||||||
|
const CHROMA_SAMPLING: usize = 14;
|
||||||
|
const ENCRYPTION_ENABLED: usize = 15;
|
||||||
|
const SURROUND_ENABLE: usize = 16;
|
||||||
|
const SURROUND_CHANNELS: usize = 17;
|
||||||
|
const SURROUND_MASK: usize = 18;
|
||||||
|
const AUDIO_QUALITY: usize = 19;
|
||||||
|
|
||||||
|
/// Every attribute read, in the order of the index constants above. The required set is the one a known host
|
||||||
|
/// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on
|
||||||
|
/// [`StreamConfig`].
|
||||||
|
const ATTRIBUTES: [Attribute; 20] = [
|
||||||
|
required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"),
|
||||||
|
required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"),
|
||||||
|
required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"),
|
||||||
|
required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"),
|
||||||
|
required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"),
|
||||||
|
required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"),
|
||||||
|
required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"),
|
||||||
|
required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"),
|
||||||
|
required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"),
|
||||||
|
required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"),
|
||||||
|
defaulted("x-nv-video[0].maxNumReferenceFrames"),
|
||||||
|
defaulted("x-nv-video[0].refPicInvalidation"),
|
||||||
|
defaulted("x-nv-video[0].dynamicRangeMode"),
|
||||||
|
defaulted("x-nv-video[0].encoderCscMode"),
|
||||||
|
defaulted("x-ss-video[0].chromaSamplingType"),
|
||||||
|
defaulted("x-ss-general.encryptionEnabled"),
|
||||||
|
defaulted("x-nv-audio.surround.enable"),
|
||||||
|
defaulted("x-nv-audio.surround.numChannels"),
|
||||||
|
defaulted("x-nv-audio.surround.channelMask"),
|
||||||
|
defaulted("x-nv-audio.surround.AudioQuality"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The values found, one slot per entry of [`ATTRIBUTES`].
|
||||||
|
struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]);
|
||||||
|
|
||||||
|
impl Values<'_, '_> {
|
||||||
|
/// The attribute's number in `lo..=hi`, or `default` when it is absent.
|
||||||
|
fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result<u64> {
|
||||||
|
let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name);
|
||||||
|
match self.0.get(index).copied().flatten() {
|
||||||
|
None => Ok(default),
|
||||||
|
Some(text) => {
|
||||||
|
let value = parse_dec(name, text)?;
|
||||||
|
if value < lo || value > hi {
|
||||||
|
return Err(Error::UnexpectedValue { what: name, value });
|
||||||
|
}
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The attribute's number in `lo..=hi`; refused when absent.
|
||||||
|
fn required(&self, index: usize, lo: u64, hi: u64) -> Result<u64> {
|
||||||
|
if self.0.get(index).copied().flatten().is_none() {
|
||||||
|
let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing");
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
self.optional(index, 0, lo, hi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A range-checked number into its field type (cannot fail after the range check; never panics either way).
|
||||||
|
fn narrow<T: TryFrom<u64>>(value: u64) -> Result<T> {
|
||||||
|
T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value })
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
//! The DESCRIBE answer (`docs/PROTOCOL.md` 2.3, 2.5): what the host offers, written as the SDP lines the client
|
||||||
|
//! reads with [`crate::rtsp::HostCapabilities::from_sdp`].
|
||||||
|
|
||||||
|
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, MAX_OPUS_CONFIGS, OpusConfig, parse_surround_params};
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// The `sprop-parameter-sets` line a known host sends; its value is not used by clients (`docs/PROTOCOL.md` 2.3).
|
||||||
|
const SPROP_LINE: &str = "sprop-parameter-sets=AAAAAU";
|
||||||
|
|
||||||
|
/// What the host offers: written into the DESCRIBE answer, and checked against the client's ANNOUNCE.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HostOffer {
|
||||||
|
/// `x-ss-general.featureFlags` (pen/touch, controller touch).
|
||||||
|
pub feature_flags: FeatureFlags,
|
||||||
|
/// `x-ss-general.encryptionSupported`.
|
||||||
|
pub encryption_supported: EncryptionFlags,
|
||||||
|
/// `x-nv-video[0].refPicInvalidation:1`: the host can invalidate reference frames.
|
||||||
|
pub reference_frame_invalidation: bool,
|
||||||
|
/// H.264: `a=fmtp:96 packetization-mode=1`.
|
||||||
|
pub h264: bool,
|
||||||
|
/// HEVC. No DESCRIBE line is known for it (a host advertises it in serverinfo, `docs/PROTOCOL.md` 1.2, U25);
|
||||||
|
/// used only to check ANNOUNCE.
|
||||||
|
pub hevc: bool,
|
||||||
|
/// AV1: `a=rtpmap:98 AV1/90000`.
|
||||||
|
pub av1: bool,
|
||||||
|
/// HDR. No DESCRIBE line is known for it (serverinfo again); used only to check ANNOUNCE: without it, a
|
||||||
|
/// `dynamicRangeMode` other than 0 (SDR \[M\]) is refused.
|
||||||
|
pub hdr: bool,
|
||||||
|
/// 4:4:4 chroma. No DESCRIBE line is known; used only to check ANNOUNCE.
|
||||||
|
pub yuv444: bool,
|
||||||
|
/// One `a=fmtp:97 surround-params=…` line each, in order (at most
|
||||||
|
/// [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]). The mappings are written as given: whether a host must rotate the
|
||||||
|
/// 5.1/7.1 normal-quality mappings is UNKNOWN U26.
|
||||||
|
pub opus_configs: Vec<OpusConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 \[M\]):
|
||||||
|
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
|
||||||
|
/// `surround-params` line per Opus configuration. CRLF line ends.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for an Opus configuration that the client's `surround-params` parser would refuse (more
|
||||||
|
/// than 8 channels, a mapping entry or count above 9, a wrong mapping length, no streams, more coupled streams than
|
||||||
|
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
|
||||||
|
/// is offered.
|
||||||
|
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
|
||||||
|
if !(offer.h264 || offer.hevc || offer.av1) {
|
||||||
|
return Err(Error::Unsupported { what: "a video codec in the host offer" });
|
||||||
|
}
|
||||||
|
cap("describe opus configurations", MAX_OPUS_CONFIGS, offer.opus_configs.len())?;
|
||||||
|
let mut out = String::with_capacity(256 + 48 * offer.opus_configs.len());
|
||||||
|
let mut line = |text: &str| {
|
||||||
|
out.push_str(text);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
};
|
||||||
|
line(&format!("a=x-ss-general.featureFlags:{}", offer.feature_flags.0));
|
||||||
|
line(&format!("a=x-ss-general.encryptionSupported:{}", offer.encryption_supported.0));
|
||||||
|
line(SPROP_LINE);
|
||||||
|
if offer.reference_frame_invalidation {
|
||||||
|
line("a=x-nv-video[0].refPicInvalidation:1");
|
||||||
|
}
|
||||||
|
if offer.av1 {
|
||||||
|
line("a=rtpmap:98 AV1/90000");
|
||||||
|
}
|
||||||
|
if offer.h264 {
|
||||||
|
line("a=fmtp:96 packetization-mode=1");
|
||||||
|
}
|
||||||
|
for config in &offer.opus_configs {
|
||||||
|
line(&format!("a=fmtp:97 surround-params={}", surround_digits(config)?));
|
||||||
|
}
|
||||||
|
Ok(out.into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `surround-params` digits for `config` (`docs/PROTOCOL.md` 2.3): channel count, stream count, coupled count, then
|
||||||
|
/// one mapping digit per channel. The client's own parser checks the result, so nothing it refuses is written.
|
||||||
|
fn surround_digits(config: &OpusConfig) -> Result<String> {
|
||||||
|
let mut digits = String::with_capacity(3 + config.mapping.len());
|
||||||
|
for n in [config.channels, config.streams, config.coupled_streams].iter().chain(&config.mapping) {
|
||||||
|
let d = char::from_digit(u32::from(*n), 10).ok_or(malformed("surround-params: a value above 9"))?;
|
||||||
|
digits.push(d);
|
||||||
|
}
|
||||||
|
parse_surround_params(&digits)?;
|
||||||
|
Ok(digits)
|
||||||
|
}
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5), the mirror of [`super::client`]: OPTIONS → DESCRIBE →
|
||||||
|
//! SETUP audio, video and control (any order, each once) → ANNOUNCE → PLAY.
|
||||||
|
//!
|
||||||
|
//! The caller accepts TCP on the RTSP port, cuts each connection's bytes with [`super::RtspFramer::for_requests`],
|
||||||
|
//! feeds every whole request to [`RtspServer::handle_request`], writes the [`ServerReply`] back, and reads
|
||||||
|
//! [`ServerEvent`]s from [`RtspServer::poll_event`]. One [`RtspServer`] belongs to one launched session, not to one
|
||||||
|
//! TCP connection: a client may open a connection per request (UNKNOWN U5, `docs/PROTOCOL.md` 2.5), so the caller
|
||||||
|
//! routes every connection of that session to the same machine.
|
||||||
|
//!
|
||||||
|
//! Every request gets an answer. A request that is malformed, out of order or for another session gets an RTSP error
|
||||||
|
//! status and leaves the state unchanged; [`ServerReply::error`] says why, and the caller decides whether to close the
|
||||||
|
//! connection. Nothing here panics on any input.
|
||||||
|
|
||||||
|
mod announce;
|
||||||
|
mod describe;
|
||||||
|
|
||||||
|
pub use announce::{
|
||||||
|
ChromaSampling, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES, MAX_ANNOUNCE_LINES,
|
||||||
|
MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE, MIN_PACKET_SIZE,
|
||||||
|
StreamConfig, SurroundSettings, parse_announce, write_announce,
|
||||||
|
};
|
||||||
|
pub use describe::{HostOffer, build_describe};
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
|
use super::client::{StreamPorts, VideoCodec};
|
||||||
|
use super::sdp::EncryptionFlags;
|
||||||
|
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
|
||||||
|
use crate::util::{hex_encode, malformed, parse_u32};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
|
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
|
||||||
|
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
|
||||||
|
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
|
||||||
|
pub const SESSION_ID_BYTES: usize = 8;
|
||||||
|
|
||||||
|
/// How the host answers.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
/// The UDP ports answered to SETUP audio, video and control (`Transport: server_port=<port>`).
|
||||||
|
pub ports: StreamPorts,
|
||||||
|
/// What DESCRIBE offers and ANNOUNCE is checked against.
|
||||||
|
pub offer: HostOffer,
|
||||||
|
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
|
||||||
|
pub required_encryption: EncryptionFlags,
|
||||||
|
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
|
||||||
|
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
|
||||||
|
/// always checked.
|
||||||
|
pub require_session_header: bool,
|
||||||
|
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
|
||||||
|
pub session_timeout_secs: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which request the session expects next.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum RtspServerState {
|
||||||
|
/// OPTIONS.
|
||||||
|
Options,
|
||||||
|
/// DESCRIBE.
|
||||||
|
Describe,
|
||||||
|
/// SETUP of the streams not set up yet.
|
||||||
|
Setup,
|
||||||
|
/// ANNOUNCE.
|
||||||
|
Announce,
|
||||||
|
/// PLAY.
|
||||||
|
Play,
|
||||||
|
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
|
||||||
|
Playing,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the session tells the caller.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum ServerEvent {
|
||||||
|
/// ANNOUNCE accepted: the stream settings the client asked for.
|
||||||
|
Announced(StreamConfig),
|
||||||
|
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
|
||||||
|
PlayRequested,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The answer to one request.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ServerReply {
|
||||||
|
/// The whole RTSP answer to write to the connection.
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
/// Its status code (200, or 400, 451, 454, 455 or 501).
|
||||||
|
pub status: u16,
|
||||||
|
/// Why the request was refused; `None` with status 200.
|
||||||
|
pub error: Option<Error>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host side of one session's RTSP negotiation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RtspServer {
|
||||||
|
config: ServerConfig,
|
||||||
|
session_id: String,
|
||||||
|
/// The DESCRIBE payload, built once from the offer.
|
||||||
|
describe: Vec<u8>,
|
||||||
|
state: RtspServerState,
|
||||||
|
/// SETUP answered for audio, video, control.
|
||||||
|
set_up: [bool; 3],
|
||||||
|
/// A SETUP was answered, so the session id is known to the client.
|
||||||
|
session_issued: bool,
|
||||||
|
announced: Option<StreamConfig>,
|
||||||
|
/// At most two events ever (one ANNOUNCE, one PLAY).
|
||||||
|
events: VecDeque<ServerEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
|
||||||
|
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
|
||||||
|
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
|
||||||
|
const STREAMS: [&str; 3] = ["audio", "video", "control"];
|
||||||
|
|
||||||
|
/// The CSeq, headers and payload of a 200 answer.
|
||||||
|
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
|
||||||
|
|
||||||
|
/// A refused request: the status, the CSeq to echo if one was readable, and why.
|
||||||
|
struct Refusal {
|
||||||
|
status: u16,
|
||||||
|
cseq: Option<u32>,
|
||||||
|
error: Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RtspServer {
|
||||||
|
/// Checks `config` and draws a fresh session id from `rng`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
|
||||||
|
/// of [`build_describe`] for the offer.
|
||||||
|
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
|
let p = config.ports;
|
||||||
|
if p.audio == 0 || p.video == 0 || p.control == 0 {
|
||||||
|
return Err(malformed("rtsp server: stream port 0"));
|
||||||
|
}
|
||||||
|
if config.session_timeout_secs == 0 {
|
||||||
|
return Err(malformed("rtsp server: session timeout 0"));
|
||||||
|
}
|
||||||
|
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
|
||||||
|
return Err(malformed("rtsp server: required encryption is not offered"));
|
||||||
|
}
|
||||||
|
let describe = build_describe(&config.offer)?;
|
||||||
|
let mut id = [0u8; SESSION_ID_BYTES];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
session_id: hex_encode(&id),
|
||||||
|
describe,
|
||||||
|
state: RtspServerState::Options,
|
||||||
|
set_up: [false; 3],
|
||||||
|
session_issued: false,
|
||||||
|
announced: None,
|
||||||
|
events: VecDeque::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
|
||||||
|
/// state as it was.
|
||||||
|
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
|
||||||
|
match self.answer(message) {
|
||||||
|
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
|
||||||
|
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The headers and payload of a 200 answer, or why the request is refused.
|
||||||
|
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
|
||||||
|
let request = parse_request(message).map_err(|error| {
|
||||||
|
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
|
||||||
|
Refusal { status, cseq: salvage_cseq(message), error }
|
||||||
|
})?;
|
||||||
|
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
|
||||||
|
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
|
||||||
|
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
let mut body = Vec::new();
|
||||||
|
match request.method {
|
||||||
|
Method::Options => {
|
||||||
|
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
|
||||||
|
if self.state == RtspServerState::Options {
|
||||||
|
self.state = RtspServerState::Describe;
|
||||||
|
}
|
||||||
|
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
|
||||||
|
}
|
||||||
|
Method::Describe => {
|
||||||
|
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
|
||||||
|
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
|
||||||
|
body.clone_from(&self.describe);
|
||||||
|
self.state = RtspServerState::Setup;
|
||||||
|
}
|
||||||
|
Method::Setup => {
|
||||||
|
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
|
||||||
|
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
|
||||||
|
if request.header("Transport").is_none() {
|
||||||
|
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
|
||||||
|
}
|
||||||
|
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
|
||||||
|
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||||
|
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||||
|
if *slot {
|
||||||
|
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
|
||||||
|
}
|
||||||
|
*slot = true;
|
||||||
|
self.session_issued = true;
|
||||||
|
if self.set_up.iter().all(|done| *done) {
|
||||||
|
self.state = RtspServerState::Announce;
|
||||||
|
}
|
||||||
|
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
|
||||||
|
headers.push(("Session".to_owned(), session));
|
||||||
|
headers.push(("Transport".to_owned(), format!("server_port={port}")));
|
||||||
|
}
|
||||||
|
Method::Announce => {
|
||||||
|
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
|
||||||
|
.map_err(|e| refuse(455, e))?;
|
||||||
|
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
|
||||||
|
self.check_offer(&config).map_err(|e| refuse(451, e))?;
|
||||||
|
self.events.push_back(ServerEvent::Announced(config.clone()));
|
||||||
|
self.announced = Some(config);
|
||||||
|
self.state = RtspServerState::Play;
|
||||||
|
}
|
||||||
|
Method::Play => {
|
||||||
|
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
|
||||||
|
self.events.push_back(ServerEvent::PlayRequested);
|
||||||
|
self.state = RtspServerState::Playing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((cseq, headers, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
|
||||||
|
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The UDP port answered for stream `index` (audio, video, control).
|
||||||
|
fn port(&self, index: usize) -> Option<u16> {
|
||||||
|
let p = self.config.ports;
|
||||||
|
[p.audio, p.video, p.control].get(index).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
|
||||||
|
/// refused only when the config asks for it.
|
||||||
|
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
|
||||||
|
let mut ids = request
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
|
||||||
|
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
|
||||||
|
let first = ids.next();
|
||||||
|
if let Some(id) = first
|
||||||
|
&& ids.any(|other| other != id)
|
||||||
|
{
|
||||||
|
return Err((400, malformed("rtsp: two different Session headers")));
|
||||||
|
}
|
||||||
|
match first {
|
||||||
|
Some(id) if !self.session_issued || id != self.session_id => {
|
||||||
|
Err((454, malformed("rtsp: Session is not this session's id")))
|
||||||
|
}
|
||||||
|
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
|
||||||
|
Err((454, malformed("rtsp: Session missing")))
|
||||||
|
}
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What ANNOUNCE asks for must be in the offer.
|
||||||
|
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
|
||||||
|
let offer = &self.config.offer;
|
||||||
|
let codec_offered = match config.codec {
|
||||||
|
VideoCodec::H264 => offer.h264,
|
||||||
|
VideoCodec::Hevc => offer.hevc,
|
||||||
|
VideoCodec::Av1 => offer.av1,
|
||||||
|
};
|
||||||
|
if !codec_offered {
|
||||||
|
return Err(Error::Unsupported { what: "the requested video codec" });
|
||||||
|
}
|
||||||
|
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
|
||||||
|
return Err(Error::Unsupported { what: "encryption the host did not offer" });
|
||||||
|
}
|
||||||
|
if !config.encryption.contains(self.config.required_encryption.0) {
|
||||||
|
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
|
||||||
|
}
|
||||||
|
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
|
||||||
|
if config.dynamic_range_mode != 0 && !offer.hdr {
|
||||||
|
return Err(Error::Unsupported { what: "HDR" });
|
||||||
|
}
|
||||||
|
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
|
||||||
|
return Err(Error::Unsupported { what: "4:4:4 chroma" });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next event, if any.
|
||||||
|
pub fn poll_event(&mut self) -> Option<ServerEvent> {
|
||||||
|
self.events.pop_front()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which request the session expects next.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn state(&self) -> RtspServerState {
|
||||||
|
self.state
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session id sent in SETUP answers.
|
||||||
|
#[must_use]
|
||||||
|
pub fn session_id(&self) -> &str {
|
||||||
|
&self.session_id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The accepted ANNOUNCE, once there is one.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn announced(&self) -> Option<&StreamConfig> {
|
||||||
|
self.announced.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The configuration the session answers with.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn config(&self) -> &ServerConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
|
||||||
|
const fn reason(status: u16) -> &'static str {
|
||||||
|
match status {
|
||||||
|
200 => "OK",
|
||||||
|
400 => "Bad Request",
|
||||||
|
451 => "Parameter Not Understood",
|
||||||
|
454 => "Session Not Found",
|
||||||
|
455 => "Method Not Valid in This State",
|
||||||
|
501 => "Not Implemented",
|
||||||
|
_ => "Internal Server Error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
|
||||||
|
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
|
||||||
|
fn reply(
|
||||||
|
status: u16,
|
||||||
|
cseq: Option<u32>,
|
||||||
|
extra: Vec<(String, String)>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
error: Option<Error>,
|
||||||
|
) -> ServerReply {
|
||||||
|
let mut headers = Vec::with_capacity(extra.len() + 2);
|
||||||
|
if let Some(c) = cseq {
|
||||||
|
headers.push(("CSeq".to_owned(), c.to_string()));
|
||||||
|
}
|
||||||
|
headers.extend(extra);
|
||||||
|
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||||
|
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
|
||||||
|
Ok(bytes) => ServerReply { bytes, status, error },
|
||||||
|
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
|
||||||
|
Err(e) => ServerReply {
|
||||||
|
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
|
||||||
|
status: 500,
|
||||||
|
error: Some(e),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
|
||||||
|
fn request_cseq(request: &RtspRequest) -> Result<u32> {
|
||||||
|
let mut found = None;
|
||||||
|
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
|
||||||
|
let n = parse_u32("rtsp CSeq", v)?;
|
||||||
|
if found.is_some_and(|f| f != n) {
|
||||||
|
return Err(malformed("rtsp: two different CSeq values"));
|
||||||
|
}
|
||||||
|
found = Some(n);
|
||||||
|
}
|
||||||
|
found.ok_or(malformed("rtsp request without CSeq"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
|
||||||
|
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
|
||||||
|
fn salvage_cseq(message: &[u8]) -> Option<u32> {
|
||||||
|
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
|
||||||
|
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
|
||||||
|
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
|
||||||
|
if line.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Ok(text) = core::str::from_utf8(line) else { continue };
|
||||||
|
if let Some((name, value)) = text.split_once(':')
|
||||||
|
&& name.eq_ignore_ascii_case("cseq")
|
||||||
|
{
|
||||||
|
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
|
||||||
|
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
|
||||||
|
fn setup_stream(target: &str) -> Result<usize> {
|
||||||
|
let mut parts = target.split("streamid=");
|
||||||
|
parts.next();
|
||||||
|
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(malformed("rtsp SETUP target with two streamid"));
|
||||||
|
}
|
||||||
|
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
|
||||||
|
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
|
||||||
|
}
|
||||||
@@ -95,7 +95,7 @@ pub(crate) fn hex_encode(bytes: &[u8]) -> String {
|
|||||||
s
|
s
|
||||||
}
|
}
|
||||||
|
|
||||||
fn hex_digit(c: u8) -> Option<u8> {
|
pub(crate) fn hex_digit(c: u8) -> Option<u8> {
|
||||||
match c {
|
match c {
|
||||||
b'0'..=b'9' => Some(c - b'0'),
|
b'0'..=b'9' => Some(c - b'0'),
|
||||||
b'a'..=b'f' => Some(c - b'a' + 10),
|
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||||
|
|||||||
@@ -20,8 +20,10 @@ use crate::util::{array, cap, malformed, need};
|
|||||||
use crate::{Error, Instant, Result};
|
use crate::{Error, Instant, Result};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
|
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.
|
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
|
||||||
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
||||||
@@ -69,6 +71,38 @@ 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 {
|
impl fmt::Debug for VideoCipher {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("VideoCipher(<redacted>)")
|
f.write_str("VideoCipher(<redacted>)")
|
||||||
|
|||||||
@@ -0,0 +1,391 @@
|
|||||||
|
//! 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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -60,6 +60,15 @@ fn lying_inputs() -> Vec<Case> {
|
|||||||
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||||
|b| common::implemented(&domistream::rtsp::parse_request(b)),
|
|b| common::implemented(&domistream::rtsp::parse_request(b)),
|
||||||
));
|
));
|
||||||
|
v.push((
|
||||||
|
"rtsp server",
|
||||||
|
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||||
|
rtsp_server_answers,
|
||||||
|
));
|
||||||
|
// ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows.
|
||||||
|
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec();
|
||||||
|
announce.extend_from_slice(&b"a=u:1\n".repeat(600));
|
||||||
|
v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b))));
|
||||||
v.push(("rtsp framer", rtsp, |b| {
|
v.push(("rtsp framer", rtsp, |b| {
|
||||||
let mut f = domistream::rtsp::RtspFramer::new();
|
let mut f = domistream::rtsp::RtspFramer::new();
|
||||||
let pushed = f.push(b);
|
let pushed = f.push(b);
|
||||||
@@ -126,9 +135,46 @@ fn lying_inputs() -> Vec<Case> {
|
|||||||
v.push(("pairing secret", vec![0; 17], |b| {
|
v.push(("pairing secret", vec![0; 17], |b| {
|
||||||
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
|
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
|
||||||
}));
|
}));
|
||||||
|
|
||||||
|
// Host HTTP: a request head claiming a 4 GiB body, and a query of empty segments and many short parameters.
|
||||||
|
v.push((
|
||||||
|
"host request head",
|
||||||
|
b"GET /launch?appid=1 HTTP/1.1\r\nContent-Length: 4294967295\r\n\r\n".to_vec(),
|
||||||
|
|b| common::implemented(&domistream::host::http::parse_request_head(b)),
|
||||||
|
));
|
||||||
|
let mut q = b"/serverinfo?".to_vec();
|
||||||
|
q.extend_from_slice(&b"&".repeat(4000));
|
||||||
|
q.extend_from_slice(&b"a=%41&".repeat(32));
|
||||||
|
v.push(("host target", q, |b| {
|
||||||
|
common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))
|
||||||
|
}));
|
||||||
|
v.push(("host head end", vec![b'a'; 70_000], |b| common::implemented(&domistream::host::http::find_head_end(b))));
|
||||||
v
|
v
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer.
|
||||||
|
fn rtsp_server_answers(b: &[u8]) -> bool {
|
||||||
|
let config = domistream::rtsp::ServerConfig {
|
||||||
|
ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||||
|
offer: domistream::rtsp::HostOffer {
|
||||||
|
feature_flags: domistream::rtsp::sdp::FeatureFlags(3),
|
||||||
|
encryption_supported: domistream::rtsp::EncryptionFlags(7),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: true,
|
||||||
|
hdr: false,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![domistream::rtsp::OpusConfig::stereo()],
|
||||||
|
},
|
||||||
|
required_encryption: domistream::rtsp::EncryptionFlags(1),
|
||||||
|
require_session_header: false,
|
||||||
|
session_timeout_secs: 90,
|
||||||
|
};
|
||||||
|
let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false };
|
||||||
|
s.handle_request(b).error != Some(domistream::Error::Unimplemented)
|
||||||
|
}
|
||||||
|
|
||||||
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
|
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
|
||||||
fn depacketizer_checks() {
|
fn depacketizer_checks() {
|
||||||
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
|
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
|
||||||
@@ -225,6 +271,8 @@ fn parsers_never_allocate_past_their_caps() {
|
|||||||
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
|
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
|
||||||
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
|
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
|
||||||
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
|
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
|
||||||
|
("announce", |b| common::implemented(&domistream::rtsp::server::parse_announce(b))),
|
||||||
|
("rtsp server", rtsp_server_answers),
|
||||||
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
|
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
|
||||||
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
|
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
|
||||||
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
|
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
|
||||||
@@ -233,6 +281,10 @@ fn parsers_never_allocate_past_their_caps() {
|
|||||||
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
|
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
|
||||||
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
|
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
|
||||||
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
|
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
|
||||||
|
("host request head", |b| common::implemented(&domistream::host::http::parse_request_head(b))),
|
||||||
|
("host target", |b| common::implemented(&domistream::host::http::parse_target(&String::from_utf8_lossy(b)))),
|
||||||
|
("host query", |b| common::implemented(&domistream::host::http::parse_query(&String::from_utf8_lossy(b)))),
|
||||||
|
("host head end", |b| common::implemented(&domistream::host::http::find_head_end(b))),
|
||||||
("audio decrypt", |b| {
|
("audio decrypt", |b| {
|
||||||
common::implemented(
|
common::implemented(
|
||||||
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
|
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
|
||||||
|
|||||||
@@ -0,0 +1,157 @@
|
|||||||
|
//! "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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
//! 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,6 +7,8 @@ use std::collections::HashMap;
|
|||||||
|
|
||||||
use domistream::RandomSource;
|
use domistream::RandomSource;
|
||||||
|
|
||||||
|
pub mod wire;
|
||||||
|
|
||||||
// ------------------------------------------------------------------------------------------------ assertions
|
// ------------------------------------------------------------------------------------------------ assertions
|
||||||
|
|
||||||
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
||||||
@@ -212,6 +214,7 @@ pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cer
|
|||||||
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||||||
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||||||
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||||||
|
pub const HOST_KEY_PEM: &str = include_str!("../fixtures/test-only-host-key.pem");
|
||||||
|
|
||||||
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||||||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||||
|
|||||||
@@ -0,0 +1,197 @@
|
|||||||
|
//! 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,786 @@
|
|||||||
|
//! 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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -497,6 +497,53 @@ fn verify_with_wrong_connect_id_does_not_connect() {
|
|||||||
assert!(link.events().is_empty());
|
assert!(link.events().is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_session_ids_are_taken_as_stock_enet_takes_them() {
|
||||||
|
// PROTOCOL.md 3.1 [E]: the verify carries both session ids from the client's point of view. Its incoming id is
|
||||||
|
// the host's outgoing one (what the host puts in its headers, so what the client must accept) and its outgoing id
|
||||||
|
// is the host's incoming one (what the client must put in its headers). A fresh host slot answers 0/0, which hides
|
||||||
|
// a swap; after a reconnect stock ENet answers with two different ids, as here.
|
||||||
|
let (mut client, d, params, _, connect_seq) = start();
|
||||||
|
let host = |session_id: u8, sent_time: u16, commands: Vec<Command>| {
|
||||||
|
encode_datagram(&Datagram {
|
||||||
|
peer_id: params.outgoing_peer_id,
|
||||||
|
session_id,
|
||||||
|
sent_time: Some(sent_time),
|
||||||
|
commands,
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
};
|
||||||
|
let verify = ConnectParams { outgoing_peer_id: 7, incoming_session_id: 1, outgoing_session_id: 2, ..params };
|
||||||
|
let ack = CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: connect_seq,
|
||||||
|
received_sent_time: d.sent_time.unwrap_or(0),
|
||||||
|
};
|
||||||
|
client
|
||||||
|
.handle_datagram(
|
||||||
|
at(1),
|
||||||
|
&host(1, 1, vec![cmd(false, 0xFF, 0, ack), cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(client.poll_event(), Some(EnetEvent::Connected));
|
||||||
|
|
||||||
|
// The client's datagrams carry its outgoing session id: the verify's outgoing id, 2.
|
||||||
|
let sent: Vec<Datagram> =
|
||||||
|
core::iter::from_fn(|| client.poll_transmit(at(1))).map(|d| parse_datagram(&d).unwrap()).collect();
|
||||||
|
assert!(!sent.is_empty(), "the verify is acknowledged");
|
||||||
|
for d in &sent {
|
||||||
|
assert_eq!((d.peer_id, d.session_id), (7, 2), "{d:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
// The host's datagrams carry the host's outgoing id (the verify's incoming id, 1): taken. Id 2 is not the
|
||||||
|
// client's incoming id: dropped.
|
||||||
|
let wrong = cmd(true, 0, 1, CommandBody::SendReliable(b"wrong session".to_vec()));
|
||||||
|
assert_eq!(client.handle_datagram(at(2), &host(2, 2, vec![wrong])), Ok(()));
|
||||||
|
assert_eq!(client.poll_event(), None, "a datagram with the client's outgoing id is not for it");
|
||||||
|
let right = cmd(true, 0, 1, CommandBody::SendReliable(b"right session".to_vec()));
|
||||||
|
client.handle_datagram(at(3), &host(1, 3, vec![right])).unwrap();
|
||||||
|
assert_eq!(client.poll_event(), Some(EnetEvent::Received { channel: 0, data: b"right session".to_vec() }));
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn garbage_never_changes_state() {
|
fn garbage_never_changes_state() {
|
||||||
let mut link = connected();
|
let mut link = connected();
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,795 @@
|
|||||||
|
//! The host's HTTP side (`docs/PROTOCOL.md` 1.1-1.5): hostile request heads and queries, the caps, and the XML
|
||||||
|
//! answers read back with this crate's own client parsers. Every case asserts a specific result.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{CLIENT_CERT_PEM, to_hex};
|
||||||
|
use domistream::host::http::answer::{MAX_STATUS_MESSAGE_BYTES, MAX_WRITTEN_APPS};
|
||||||
|
use domistream::host::http::{
|
||||||
|
self as host_http, DisplayMode, HostInfo, HostRequest, LaunchRequest, MAX_DEVICE_NAME_BYTES, MAX_HEAD_BYTES,
|
||||||
|
MAX_HEADERS, MAX_MODE_DIMENSION, MAX_MODE_FPS, MAX_PARAM_NAME_BYTES, MAX_PARAM_VALUE_BYTES, MAX_PARAMS,
|
||||||
|
MAX_PATH_BYTES, MAX_QUERY_BYTES, ResumeRequest, Route, encode_query, find_head_end, parse_query,
|
||||||
|
parse_request_head, parse_target,
|
||||||
|
};
|
||||||
|
use domistream::host::pairing::{PairAnswer, PairPhase};
|
||||||
|
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPS};
|
||||||
|
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES;
|
||||||
|
use domistream::http::xml::MAX_XML_ELEMENTS;
|
||||||
|
use domistream::http::{self, App, Scheme, xml};
|
||||||
|
use domistream::pairing::identity::MAX_CERT_PEM_BYTES;
|
||||||
|
use domistream::{Error, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
|
||||||
|
fn head(target: &str) -> Vec<u8> {
|
||||||
|
format!("GET {target} HTTP/1.1\r\nHost: lumen.test:47989\r\nUser-Agent: test\r\n\r\n").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn route(target: &str) -> Route {
|
||||||
|
parse_request_head(&head(target)).unwrap_or_else(|e| panic!("{target}: {e:?}")).route
|
||||||
|
}
|
||||||
|
|
||||||
|
fn keys() -> SessionKeys {
|
||||||
|
SessionKeys { rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", rikeyid: 1_234_567 }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the client's own requests
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_client_request_parses_on_the_host() {
|
||||||
|
for scheme in [Scheme::Http, Scheme::Https] {
|
||||||
|
let r = http::server_info_request(scheme, UID).unwrap();
|
||||||
|
let req = parse_request_head(&head(&r.path_and_query)).unwrap();
|
||||||
|
assert_eq!(req, HostRequest { route: Route::ServerInfo, unique_id: Some(UID.into()), other_params: vec![] });
|
||||||
|
}
|
||||||
|
for (r, want) in [
|
||||||
|
(http::app_list_request(UID).unwrap(), Route::AppList),
|
||||||
|
(http::cancel_request(UID).unwrap(), Route::Cancel),
|
||||||
|
(http::unpair_request(UID).unwrap(), Route::Unpair),
|
||||||
|
] {
|
||||||
|
let req = parse_request_head(&head(&r.path_and_query)).unwrap();
|
||||||
|
assert_eq!(req.route, want);
|
||||||
|
assert_eq!(req.unique_id.as_deref(), Some(UID));
|
||||||
|
}
|
||||||
|
|
||||||
|
for (hdr, audio) in [(false, http::launch::AudioLayout::Stereo), (true, http::launch::AudioLayout::Surround71)] {
|
||||||
|
let params =
|
||||||
|
http::LaunchParams { app_id: 881_448_767, width: 3840, height: 2160, fps: 120, keys: keys(), hdr, audio };
|
||||||
|
let r = http::launch::launch_request(¶ms, UID).unwrap();
|
||||||
|
let want = LaunchRequest {
|
||||||
|
app_id: 881_448_767,
|
||||||
|
mode: DisplayMode { width: 3840, height: 2160, fps: 120 },
|
||||||
|
keys: keys(),
|
||||||
|
hdr: Some(hdr),
|
||||||
|
surround_audio_info: Some(audio.surround_audio_info()),
|
||||||
|
};
|
||||||
|
assert_eq!(route(&r.path_and_query), Route::Launch(want));
|
||||||
|
}
|
||||||
|
|
||||||
|
let r = http::launch::resume_request(&keys(), UID).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
route(&r.path_and_query),
|
||||||
|
Route::Resume(ResumeRequest { keys: keys(), app_id: None, mode: None, hdr: None, surround_audio_info: None })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_client_pairing_requests_parse_on_the_host() {
|
||||||
|
let v = common::pairing_vectors();
|
||||||
|
let id =
|
||||||
|
domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
|
||||||
|
.unwrap();
|
||||||
|
let mut rng = common::SeqRng::new(3);
|
||||||
|
let pin = domistream::pairing::Pin::from_digits("4071").unwrap();
|
||||||
|
let (_, r) = domistream::pairing::PairingSession::start(&id, UID, "Living Room TV", pin, &mut rng).unwrap();
|
||||||
|
match route(&r.path_and_query) {
|
||||||
|
Route::Pair(p) => {
|
||||||
|
assert_eq!(p.unique_id, UID);
|
||||||
|
assert_eq!(p.device_name.as_deref(), Some("Living Room TV"));
|
||||||
|
match p.phase {
|
||||||
|
PairPhase::GetServerCert { client_cert_pem, .. } => {
|
||||||
|
assert_eq!(client_cert_pem, id.cert_pem().unwrap().into_bytes());
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pair_phases_from_the_query() {
|
||||||
|
let salt = "00112233445566778899aabbccddeeff";
|
||||||
|
let cert = to_hex(CLIENT_CERT_PEM.as_bytes());
|
||||||
|
let pair = |q: &str| match route(&format!("/pair?uniqueid={UID}&devicename=tv&updateState=1&{q}")) {
|
||||||
|
Route::Pair(p) => p.phase,
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
pair(&format!("phrase=getservercert&salt={salt}&clientcert={cert}")),
|
||||||
|
PairPhase::GetServerCert {
|
||||||
|
salt: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
|
||||||
|
client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec()
|
||||||
|
}
|
||||||
|
);
|
||||||
|
assert_eq!(pair("clientchallenge=0A0b"), PairPhase::ClientChallenge(vec![0x0A, 0x0B]));
|
||||||
|
assert_eq!(pair("serverchallengeresp=ff"), PairPhase::ServerChallengeResp(vec![0xFF]));
|
||||||
|
assert_eq!(pair("clientpairingsecret=0001"), PairPhase::ClientPairingSecret(vec![0, 1]));
|
||||||
|
assert_eq!(pair("phrase=pairchallenge"), PairPhase::PairChallenge);
|
||||||
|
// updateState is known to the client side but not used by the host: it is kept as an unknown parameter.
|
||||||
|
let req = parse_target(&format!("/pair?uniqueid={UID}&updateState=1&phrase=pairchallenge")).unwrap();
|
||||||
|
assert_eq!(req.other_params, vec![("updateState".to_string(), "1".to_string())]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pair_requests_refused() {
|
||||||
|
let salt = "00112233445566778899aabbccddeeff";
|
||||||
|
let cert = to_hex(CLIENT_CERT_PEM.as_bytes());
|
||||||
|
for (q, why) in [
|
||||||
|
(format!("phrase=getservercert&salt={salt}&clientcert={cert}"), "no uniqueid"),
|
||||||
|
(format!("uniqueid={UID}"), "no phase"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&clientcert={cert}"), "no salt"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}"), "no clientcert"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&salt=0011&clientcert={cert}"), "short salt"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}00&clientcert={cert}"), "long salt"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=abc"), "odd hex"),
|
||||||
|
(format!("uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert=zz"), "not hex"),
|
||||||
|
(format!("uniqueid={UID}&phrase=other"), "unknown phrase"),
|
||||||
|
(format!("uniqueid={UID}&phrase=pairchallenge&clientchallenge=00"), "two phases"),
|
||||||
|
(format!("uniqueid={UID}&clientchallenge=00&serverchallengeresp=00"), "two phases"),
|
||||||
|
(format!("uniqueid={UID}&clientchallenge="), "empty hex"),
|
||||||
|
(format!("uniqueid={UID}&clientchallenge=0x00"), "0x prefix"),
|
||||||
|
("uniqueid=a%26b&phrase=pairchallenge".to_string(), "bad uniqueid"),
|
||||||
|
(format!("uniqueid={}&phrase=pairchallenge", "a".repeat(65)), "long uniqueid"),
|
||||||
|
(format!("uniqueid={UID}&uniqueid={UID}&phrase=pairchallenge"), "repeated uniqueid"),
|
||||||
|
(format!("uniqueid={UID}&phrase=pairchallenge&phrase=getservercert"), "repeated phrase"),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
matches!(parse_target(&format!("/pair?{q}")), Err(Error::Malformed { .. })),
|
||||||
|
"{why}: {:?}",
|
||||||
|
parse_target(&format!("/pair?{q}"))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let long_name = "d".repeat(MAX_DEVICE_NAME_BYTES);
|
||||||
|
assert!(parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}&phrase=pairchallenge")).is_ok());
|
||||||
|
assert!(matches!(
|
||||||
|
parse_target(&format!("/pair?uniqueid={UID}&devicename={long_name}d&phrase=pairchallenge")),
|
||||||
|
Err(Error::TooLarge { max: MAX_DEVICE_NAME_BYTES, .. })
|
||||||
|
));
|
||||||
|
// Hex values other than the certificate have their own cap.
|
||||||
|
let big = "00".repeat(domistream::host::http::MAX_HEX_VALUE_CHARS / 2);
|
||||||
|
assert!(parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}")).is_ok());
|
||||||
|
assert!(matches!(
|
||||||
|
parse_target(&format!("/pair?uniqueid={UID}&clientpairingsecret={big}00")),
|
||||||
|
Err(Error::TooLarge { .. })
|
||||||
|
));
|
||||||
|
// The certificate's cap is the PEM cap, in hex.
|
||||||
|
let at_cap = "41".repeat(MAX_CERT_PEM_BYTES);
|
||||||
|
assert!(
|
||||||
|
parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}")).is_ok()
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
parse_target(&format!("/pair?uniqueid={UID}&phrase=getservercert&salt={salt}&clientcert={at_cap}41")),
|
||||||
|
Err(Error::TooLarge { .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ routes
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn routes_and_unknown_parameters() {
|
||||||
|
let req = parse_request_head(&head(&format!("/serverinfo?uniqueid={UID}&uuid=5d1a-77"))).unwrap();
|
||||||
|
assert_eq!(req.route, Route::ServerInfo);
|
||||||
|
assert_eq!(req.other_params, vec![("uuid".to_string(), "5d1a-77".to_string())]);
|
||||||
|
assert_eq!(parse_target("/serverinfo").unwrap().unique_id, None, "uniqueid is optional outside /pair");
|
||||||
|
|
||||||
|
let req = parse_target(&format!("/appasset?uniqueid={UID}&appid=5&AssetType=2&AssetIdx=0")).unwrap();
|
||||||
|
assert_eq!(req.route, Route::AppAsset { app_id: 5 });
|
||||||
|
assert_eq!(req.other_params.len(), 2);
|
||||||
|
assert!(matches!(parse_target("/appasset"), Err(Error::Malformed { .. })), "appid is required");
|
||||||
|
|
||||||
|
assert_eq!(route("/foo/../bar?x=1"), Route::Unknown { path: "/foo/../bar".into() });
|
||||||
|
assert_eq!(route("/"), Route::Unknown { path: "/".into() });
|
||||||
|
assert_eq!(route("/ServerInfo"), Route::Unknown { path: "/ServerInfo".into() }, "paths are case-sensitive");
|
||||||
|
assert_eq!(route("/serverinfo/"), Route::Unknown { path: "/serverinfo/".into() });
|
||||||
|
assert_eq!(route("/%73erverinfo"), Route::Unknown { path: "/%73erverinfo".into() }, "paths are never decoded");
|
||||||
|
assert_eq!(route("/applist?"), Route::AppList, "an empty query is no query");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn launch_q(extra: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"/launch?uniqueid={UID}&appid=7&mode=1920x1080x60&rikey=00112233445566778899AABBCCDDEEFF&rikeyid=1234567{extra}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_values() {
|
||||||
|
let Route::Launch(l) = route(&launch_q("")) else { panic!() };
|
||||||
|
assert_eq!(l.app_id, 7);
|
||||||
|
assert_eq!(l.mode, DisplayMode { width: 1920, height: 1080, fps: 60 });
|
||||||
|
assert_eq!(l.keys, keys());
|
||||||
|
assert_eq!((l.hdr, l.surround_audio_info), (None, None));
|
||||||
|
|
||||||
|
let Route::Launch(l) = route(&launch_q("&hdrMode=1&surroundAudioInfo=196610&localAudioPlayMode=0")) else {
|
||||||
|
panic!()
|
||||||
|
};
|
||||||
|
assert_eq!((l.hdr, l.surround_audio_info), (Some(true), Some(196_610)));
|
||||||
|
|
||||||
|
// rikeyid: unsigned decimal; a negative 32-bit value is read as its two's complement (UNKNOWN: some clients
|
||||||
|
// may print the id signed).
|
||||||
|
let id = |v: &str| match parse_target(&launch_q("").replace("rikeyid=1234567", &format!("rikeyid={v}"))) {
|
||||||
|
Ok(HostRequest { route: Route::Launch(l), .. }) => Ok(l.keys.rikeyid),
|
||||||
|
Ok(other) => panic!("{other:?}"),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
};
|
||||||
|
assert_eq!(id("0"), Ok(0));
|
||||||
|
assert_eq!(id("4294967295"), Ok(u32::MAX));
|
||||||
|
assert_eq!(id("-1"), Ok(u32::MAX));
|
||||||
|
assert_eq!(id("-2147483648"), Ok(0x8000_0000));
|
||||||
|
for bad in ["4294967296", "-2147483649", "-0", "-", "+1", "1.0", "0x10", "", " 1"] {
|
||||||
|
assert!(matches!(id(bad), Err(Error::Malformed { .. })), "rikeyid {bad:?}: {:?}", id(bad));
|
||||||
|
}
|
||||||
|
|
||||||
|
let max = format!("{MAX_MODE_DIMENSION}x{MAX_MODE_DIMENSION}x{MAX_MODE_FPS}");
|
||||||
|
let Route::Launch(l) = route(&launch_q("").replace("1920x1080x60", &max)) else { panic!() };
|
||||||
|
assert_eq!(l.mode.fps, MAX_MODE_FPS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_refused() {
|
||||||
|
let base = launch_q("");
|
||||||
|
for (bad, why) in [
|
||||||
|
(base.replace("&appid=7", ""), "no appid"),
|
||||||
|
(base.replace("&mode=1920x1080x60", ""), "no mode"),
|
||||||
|
(base.replace("&rikey=00112233445566778899AABBCCDDEEFF", ""), "no rikey"),
|
||||||
|
(base.replace("&rikeyid=1234567", ""), "no rikeyid"),
|
||||||
|
(base.replace("appid=7", "appid=-7"), "negative appid"),
|
||||||
|
(base.replace("appid=7", "appid=4294967296"), "appid over u32"),
|
||||||
|
(base.replace("1920x1080x60", "1920x1080"), "mode without fps"),
|
||||||
|
(base.replace("1920x1080x60", "1920x1080x60x1"), "mode with four parts"),
|
||||||
|
(base.replace("1920x1080x60", "0x1080x60"), "zero width"),
|
||||||
|
(base.replace("1920x1080x60", "1920x0x60"), "zero height"),
|
||||||
|
(base.replace("1920x1080x60", "1920x1080x0"), "zero fps"),
|
||||||
|
(base.replace("1920x1080x60", &format!("{}x1080x60", MAX_MODE_DIMENSION + 1)), "too wide"),
|
||||||
|
(base.replace("1920x1080x60", &format!("1920x1080x{}", MAX_MODE_FPS + 1)), "too fast"),
|
||||||
|
(base.replace("1920x1080x60", "1920X1080X60"), "upper-case X"),
|
||||||
|
(base.replace("1920x1080x60", "1920x1080x59.94"), "fractional fps"),
|
||||||
|
(base.replace("1920x1080x60", "+1920x1080x60"), "sign"),
|
||||||
|
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEF"), "short rikey"),
|
||||||
|
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFF00"), "long rikey"),
|
||||||
|
(base.replace("00112233445566778899AABBCCDDEEFF", "00112233445566778899AABBCCDDEEFG"), "rikey not hex"),
|
||||||
|
(launch_q("&hdrMode=2"), "hdrMode 2"),
|
||||||
|
(launch_q("&hdrMode=true"), "hdrMode true"),
|
||||||
|
(launch_q("&surroundAudioInfo=x"), "surroundAudioInfo not decimal"),
|
||||||
|
(launch_q("&appid=8"), "repeated appid"),
|
||||||
|
(launch_q("&rikey=00112233445566778899AABBCCDDEEFF"), "repeated rikey"),
|
||||||
|
] {
|
||||||
|
let r = parse_target(&bad);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_values() {
|
||||||
|
let q = format!("/resume?uniqueid={UID}&rikey=00112233445566778899aabbccddeeff&rikeyid=1234567");
|
||||||
|
let Route::Resume(r) = route(&q) else { panic!() };
|
||||||
|
assert_eq!(r.keys, keys());
|
||||||
|
let Route::Resume(r) = route(&format!("{q}&appid=3&mode=1280x720x30&hdrMode=0&surroundAudioInfo=1")) else {
|
||||||
|
panic!()
|
||||||
|
};
|
||||||
|
assert_eq!(r.app_id, Some(3));
|
||||||
|
assert_eq!(r.mode, Some(DisplayMode { width: 1280, height: 720, fps: 30 }));
|
||||||
|
assert_eq!((r.hdr, r.surround_audio_info), (Some(false), Some(1)));
|
||||||
|
assert!(matches!(parse_target(&format!("/resume?uniqueid={UID}&rikeyid=1")), Err(Error::Malformed { .. })));
|
||||||
|
assert!(matches!(parse_target(&format!("{q}&mode=1x1")), Err(Error::Malformed { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the head
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn heads_that_are_fine() {
|
||||||
|
for h in [
|
||||||
|
"GET /serverinfo HTTP/1.1\r\n\r\n".to_string(),
|
||||||
|
"GET /serverinfo HTTP/1.0\r\n\r\n".to_string(),
|
||||||
|
"GET /serverinfo HTTP/1.1\r\nHost: x\r\nContent-Length: 0\r\n\r\n".to_string(),
|
||||||
|
"GET /serverinfo HTTP/1.1\r\nX-Odd:\tvalue with spaces \t\r\n\r\n".to_string(),
|
||||||
|
"GET /serverinfo HTTP/1.1\r\nEmpty:\r\n\r\n".to_string(),
|
||||||
|
"GET /serverinfo HTTP/1.1\r\ncontent-length: 0\r\n\r\n".to_string(),
|
||||||
|
] {
|
||||||
|
assert_eq!(parse_request_head(h.as_bytes()).map(|r| r.route), Ok(Route::ServerInfo), "{h:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn heads_that_are_refused() {
|
||||||
|
for (h, why) in [
|
||||||
|
(&b""[..], "empty"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n", "no empty line"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n", "no empty line after headers"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\n\n", "bare LF"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: x\n\r\n", "bare LF in a header"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n\r\nbody", "bytes after the head"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n\r\n\r\n", "two empty lines"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n\r\n", "two spaces before the version"),
|
||||||
|
(b"GET /serverinfo\r\n\r\n", "no version"),
|
||||||
|
(b"GET /serverinfo HTTP/2\r\n\r\n", "HTTP/2"),
|
||||||
|
(b"GET /serverinfo http/1.1\r\n\r\n", "lower-case version"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1 x\r\n\r\n", "four parts"),
|
||||||
|
(b" GET /serverinfo HTTP/1.1\r\n\r\n", "leading space"),
|
||||||
|
(b"\r\nGET /serverinfo HTTP/1.1\r\n\r\n", "leading empty line"),
|
||||||
|
(b"GET http://x/serverinfo HTTP/1.1\r\n\r\n", "absolute form"),
|
||||||
|
(b"GET * HTTP/1.1\r\n\r\n", "asterisk form"),
|
||||||
|
(b"GET serverinfo HTTP/1.1\r\n\r\n", "no leading slash"),
|
||||||
|
(b"GET /serverinfo#x HTTP/1.1\r\n\r\n", "fragment"),
|
||||||
|
(b"GET /server\x00info HTTP/1.1\r\n\r\n", "NUL"),
|
||||||
|
(b"GET /server\xc3\xa9 HTTP/1.1\r\n\r\n", "non-ASCII target"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: \xff\r\n\r\n", "non-ASCII header"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: a\x01b\r\n\r\n", "control in a header"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: x\r\n folded\r\n\r\n", "folded header"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost x\r\n\r\n", "no colon"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\n: x\r\n\r\n", "empty name"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost : x\r\n\r\n", "space before the colon"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHo(st: x\r\n\r\n", "not a token"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: 5\r\n\r\n", "a body"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: 0\r\nContent-Length: 0\r\n\r\n", "two lengths"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nContent-Length: +0\r\n\r\n", "signed length"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n", "chunked"),
|
||||||
|
(b"GET /serverinfo HTTP/1.1\r\nHost: x\rY: z\r\n\r\n", "bare CR"),
|
||||||
|
] {
|
||||||
|
let r = parse_request_head(h);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. })), "{why}: {r:?}");
|
||||||
|
}
|
||||||
|
for m in ["POST", "HEAD", "PUT", "get", "OPTIONS", "CONNECT"] {
|
||||||
|
let h = format!("{m} /serverinfo HTTP/1.1\r\n\r\n");
|
||||||
|
assert!(matches!(parse_request_head(h.as_bytes()), Err(Error::Unsupported { .. })), "{m}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn head_caps() {
|
||||||
|
// A head of exactly the cap, padded with one long header line.
|
||||||
|
let at = |total: usize| {
|
||||||
|
let start = "GET /serverinfo HTTP/1.1\r\nX: ";
|
||||||
|
let end = "\r\n\r\n";
|
||||||
|
format!("{start}{}{end}", "a".repeat(total - start.len() - end.len())).into_bytes()
|
||||||
|
};
|
||||||
|
assert_eq!(parse_request_head(&at(MAX_HEAD_BYTES)).map(|r| r.route), Ok(Route::ServerInfo));
|
||||||
|
assert_too_large!(parse_request_head(&at(MAX_HEAD_BYTES + 1)), MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1);
|
||||||
|
assert_too_large!(parse_request_head(&vec![b'G'; 1 << 22]), MAX_HEAD_BYTES, 1 << 22);
|
||||||
|
|
||||||
|
let headers = |n: usize| {
|
||||||
|
let mut s = String::from("GET /serverinfo HTTP/1.1\r\n");
|
||||||
|
for i in 0..n {
|
||||||
|
s.push_str(&format!("X-{i}: v\r\n"));
|
||||||
|
}
|
||||||
|
s.push_str("\r\n");
|
||||||
|
s.into_bytes()
|
||||||
|
};
|
||||||
|
assert!(parse_request_head(&headers(MAX_HEADERS)).is_ok());
|
||||||
|
assert!(matches!(parse_request_head(&headers(MAX_HEADERS + 1)), Err(Error::TooLarge { max: MAX_HEADERS, .. })));
|
||||||
|
|
||||||
|
let path = |n: usize| format!("/{}", "p".repeat(n - 1));
|
||||||
|
assert_eq!(route(&path(MAX_PATH_BYTES)), Route::Unknown { path: path(MAX_PATH_BYTES) });
|
||||||
|
assert!(matches!(parse_target(&path(MAX_PATH_BYTES + 1)), Err(Error::TooLarge { max: MAX_PATH_BYTES, .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn find_head_end_cuts_the_stream() {
|
||||||
|
let h = head("/serverinfo");
|
||||||
|
for cut in 0..h.len() {
|
||||||
|
assert_eq!(find_head_end(&h[..cut]), Ok(None), "{cut} bytes");
|
||||||
|
}
|
||||||
|
assert_eq!(find_head_end(&h), Ok(Some(h.len())));
|
||||||
|
let mut two = h.clone();
|
||||||
|
two.extend_from_slice(&h);
|
||||||
|
assert_eq!(find_head_end(&two), Ok(Some(h.len())), "pipelined: the first head");
|
||||||
|
assert_eq!(find_head_end(b"\r\n\r\n"), Ok(Some(4)));
|
||||||
|
|
||||||
|
let mut at_cap = vec![b'a'; MAX_HEAD_BYTES - 4];
|
||||||
|
at_cap.extend_from_slice(b"\r\n\r\n");
|
||||||
|
assert_eq!(find_head_end(&at_cap), Ok(Some(MAX_HEAD_BYTES)));
|
||||||
|
assert_eq!(find_head_end(&vec![b'a'; MAX_HEAD_BYTES - 1]), Ok(None), "could still end within the cap");
|
||||||
|
let mut almost = vec![b'a'; MAX_HEAD_BYTES - 4];
|
||||||
|
almost.extend_from_slice(b"\r\n\r");
|
||||||
|
assert_eq!(find_head_end(&almost), Ok(None), "one more LF ends it exactly at the cap");
|
||||||
|
for len in [MAX_HEAD_BYTES, MAX_HEAD_BYTES + 1, 1 << 22] {
|
||||||
|
assert!(matches!(find_head_end(&vec![b'a'; len]), Err(Error::TooLarge { max: MAX_HEAD_BYTES, .. })), "{len}");
|
||||||
|
}
|
||||||
|
let mut late = vec![b'a'; MAX_HEAD_BYTES - 3];
|
||||||
|
late.extend_from_slice(b"\r\n\r\n");
|
||||||
|
assert!(matches!(find_head_end(&late), Err(Error::TooLarge { .. })), "ends one byte past the cap");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the query
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn query_decoding() {
|
||||||
|
let q = |s: &str| parse_query(s);
|
||||||
|
assert_eq!(q(""), Ok(vec![]));
|
||||||
|
assert_eq!(q("a=1&b=2"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())]));
|
||||||
|
assert_eq!(q("a=%41%62%2b%2B"), Ok(vec![("a".into(), "Ab++".into())]));
|
||||||
|
assert_eq!(q("a=x+y"), Ok(vec![("a".into(), "x y".into())]));
|
||||||
|
assert_eq!(q("a=%C3%A9"), Ok(vec![("a".into(), "é".into())]));
|
||||||
|
assert_eq!(q("a=%26b%3Dc"), Ok(vec![("a".into(), "&b=c".into())]), "encoded & and = stay in the value");
|
||||||
|
assert_eq!(q("a"), Ok(vec![("a".into(), String::new())]));
|
||||||
|
assert_eq!(q("a="), Ok(vec![("a".into(), String::new())]));
|
||||||
|
assert_eq!(q("a=1&&b=2&"), Ok(vec![("a".into(), "1".into()), ("b".into(), "2".into())]));
|
||||||
|
assert_eq!(q("a=b=c"), Ok(vec![("a".into(), "b=c".into())]));
|
||||||
|
assert_eq!(q("x.y-z_1=0"), Ok(vec![("x.y-z_1".into(), "0".into())]));
|
||||||
|
for (bad, why) in [
|
||||||
|
("=1", "empty name"),
|
||||||
|
("a=%", "cut escape"),
|
||||||
|
("a=%4", "cut escape"),
|
||||||
|
("a=%zz", "bad escape"),
|
||||||
|
("a=%00", "NUL"),
|
||||||
|
("a=%0A", "LF"),
|
||||||
|
("a=%7F", "DEL"),
|
||||||
|
("a=%FF", "not UTF-8"),
|
||||||
|
("a=%C3", "cut UTF-8"),
|
||||||
|
("a%41=1", "escape in a name"),
|
||||||
|
("a b=1", "space in a name"),
|
||||||
|
("a=1&a=2", "repeated name"),
|
||||||
|
("a=1&a", "repeated name"),
|
||||||
|
("a=\u{e9}", "raw non-ASCII"),
|
||||||
|
] {
|
||||||
|
assert!(matches!(q(bad), Err(Error::Malformed { .. })), "{why}: {:?}", q(bad));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn query_caps() {
|
||||||
|
let params = |n: usize| (0..n).map(|i| format!("p{i}=1")).collect::<Vec<_>>().join("&");
|
||||||
|
assert_eq!(parse_query(¶ms(MAX_PARAMS)).unwrap().len(), MAX_PARAMS);
|
||||||
|
assert!(matches!(parse_query(¶ms(MAX_PARAMS + 1)), Err(Error::TooLarge { max: MAX_PARAMS, .. })));
|
||||||
|
// Empty segments do not count, but are still bounded by the query cap.
|
||||||
|
assert_eq!(parse_query(&"&".repeat(10_000)), Ok(vec![]));
|
||||||
|
|
||||||
|
let name = |n: usize| "n".repeat(n);
|
||||||
|
assert!(parse_query(&format!("{}=1", name(MAX_PARAM_NAME_BYTES))).is_ok());
|
||||||
|
assert!(matches!(
|
||||||
|
parse_query(&format!("{}=1", name(MAX_PARAM_NAME_BYTES + 1))),
|
||||||
|
Err(Error::TooLarge { max: MAX_PARAM_NAME_BYTES, .. })
|
||||||
|
));
|
||||||
|
let value = |n: usize| format!("v={}", "x".repeat(n));
|
||||||
|
assert!(parse_query(&value(MAX_PARAM_VALUE_BYTES)).is_ok());
|
||||||
|
assert!(matches!(
|
||||||
|
parse_query(&value(MAX_PARAM_VALUE_BYTES + 1)),
|
||||||
|
Err(Error::TooLarge { max: MAX_PARAM_VALUE_BYTES, .. })
|
||||||
|
));
|
||||||
|
// The value cap counts the bytes as sent: three per escape.
|
||||||
|
assert!(matches!(
|
||||||
|
parse_query(&format!("v={}", "%41".repeat(MAX_PARAM_VALUE_BYTES / 3 + 1))),
|
||||||
|
Err(Error::TooLarge { max: MAX_PARAM_VALUE_BYTES, .. })
|
||||||
|
));
|
||||||
|
let filler =
|
||||||
|
|n: usize| format!("a={}&b={}", "x".repeat(MAX_PARAM_VALUE_BYTES), "y".repeat(n - MAX_PARAM_VALUE_BYTES - 5));
|
||||||
|
assert_eq!(filler(MAX_QUERY_BYTES).len(), MAX_QUERY_BYTES);
|
||||||
|
assert!(parse_query(&filler(MAX_QUERY_BYTES)).is_ok());
|
||||||
|
assert_too_large!(parse_query(&filler(MAX_QUERY_BYTES + 1)), MAX_QUERY_BYTES, MAX_QUERY_BYTES + 1);
|
||||||
|
assert!(matches!(
|
||||||
|
parse_target(&format!("/serverinfo?{}", filler(MAX_QUERY_BYTES + 1))),
|
||||||
|
Err(Error::TooLarge { max: MAX_QUERY_BYTES, .. })
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_query_is_strict() {
|
||||||
|
assert_eq!(encode_query(&[]), "");
|
||||||
|
assert_eq!(encode_query(&[("a", "1"), ("b", "x y&z=é~")]), "a=1&b=x%20y%26z%3D%C3%A9~");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ properties
|
||||||
|
|
||||||
|
fn name_strategy() -> impl Strategy<Value = String> {
|
||||||
|
"[a-zA-Z_][a-zA-Z0-9_.-]{0,12}"
|
||||||
|
}
|
||||||
|
|
||||||
|
fn value_strategy() -> impl Strategy<Value = String> {
|
||||||
|
// Any characters but controls (refused on purpose).
|
||||||
|
proptest::collection::vec(any::<char>().prop_filter("no controls", |c| !c.is_control()), 0..40)
|
||||||
|
.prop_map(|v| v.into_iter().collect())
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn query_round_trips(pairs in proptest::collection::btree_map(name_strategy(), value_strategy(), 0..MAX_PARAMS)) {
|
||||||
|
let list: Vec<(&str, &str)> = pairs.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||||
|
let q = encode_query(&list);
|
||||||
|
let parsed = parse_query(&q).unwrap();
|
||||||
|
let want: Vec<(String, String)> = pairs.into_iter().collect();
|
||||||
|
prop_assert_eq!(parsed, want);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_round_trips(app in any::<u32>(), w in 1..=MAX_MODE_DIMENSION, h in 1..=MAX_MODE_DIMENSION,
|
||||||
|
fps in 1..=MAX_MODE_FPS, rikey in any::<[u8; 16]>(), rikeyid in any::<u32>(),
|
||||||
|
hdr in proptest::option::of(any::<bool>()), audio in proptest::option::of(any::<u32>())) {
|
||||||
|
let (app_s, mode_s, key_s, id_s) = (app.to_string(), format!("{w}x{h}x{fps}"), to_hex(&rikey), rikeyid.to_string());
|
||||||
|
let hdr_s = hdr.map(|b| if b { "1" } else { "0" });
|
||||||
|
let audio_s = audio.map(|a| a.to_string());
|
||||||
|
let mut list: Vec<(&str, &str)> = vec![
|
||||||
|
("uniqueid", UID), ("appid", app_s.as_str()), ("mode", mode_s.as_str()), ("rikey", key_s.as_str()),
|
||||||
|
("rikeyid", id_s.as_str()),
|
||||||
|
];
|
||||||
|
if let Some(h) = hdr_s { list.push(("hdrMode", h)); }
|
||||||
|
if let Some(a) = &audio_s { list.push(("surroundAudioInfo", a.as_str())); }
|
||||||
|
let req = parse_target(&format!("/launch?{}", encode_query(&list))).unwrap();
|
||||||
|
let want = LaunchRequest {
|
||||||
|
app_id: app,
|
||||||
|
mode: DisplayMode { width: w, height: h, fps },
|
||||||
|
keys: SessionKeys { rikey, rikeyid },
|
||||||
|
hdr,
|
||||||
|
surround_audio_info: audio,
|
||||||
|
};
|
||||||
|
prop_assert_eq!(req.route, Route::Launch(want));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn heads_never_panic(data in proptest::collection::vec(any::<u8>(), 0..512)) {
|
||||||
|
let r = parse_request_head(&data);
|
||||||
|
prop_assert!(common::implemented(&r));
|
||||||
|
prop_assert!(common::implemented(&find_head_end(&data)));
|
||||||
|
let text = String::from_utf8_lossy(&data);
|
||||||
|
prop_assert!(common::implemented(&parse_target(&text)));
|
||||||
|
prop_assert!(common::implemented(&parse_query(&text)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn targets_never_panic(target in "/[ -~]{0,200}") {
|
||||||
|
let r = parse_target(&target);
|
||||||
|
prop_assert!(common::implemented(&r));
|
||||||
|
let h = parse_request_head(&head(&target));
|
||||||
|
prop_assert!(common::implemented(&h));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A valid head with one byte changed or cut short: never a panic; a cut head is always an error.
|
||||||
|
#[test]
|
||||||
|
fn mutated_heads(at in 0usize..200, byte in any::<u8>(), cut in 0usize..200) {
|
||||||
|
let good = head(&launch_q("&hdrMode=1"));
|
||||||
|
let mut m = good.clone();
|
||||||
|
let at = at % m.len();
|
||||||
|
m[at] = byte;
|
||||||
|
prop_assert!(common::implemented(&parse_request_head(&m)));
|
||||||
|
let cut = cut % good.len();
|
||||||
|
prop_assert!(parse_request_head(&good[..cut]).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ XML answers
|
||||||
|
|
||||||
|
fn host_info() -> HostInfo {
|
||||||
|
HostInfo {
|
||||||
|
hostname: "LAB-PC".into(),
|
||||||
|
app_version: "7.1.431.-1".into(),
|
||||||
|
gfe_version: "3.23.0.74".into(),
|
||||||
|
unique_id: "0123456789ABCDEF0123456789ABCDEF".into(),
|
||||||
|
https_port: 47984,
|
||||||
|
http_port: 47989,
|
||||||
|
mac: Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]),
|
||||||
|
local_ip: "192.0.2.10".into(),
|
||||||
|
max_luma_pixels_hevc: 1_869_449_984,
|
||||||
|
codec_mode_support: 259,
|
||||||
|
current_game: 0,
|
||||||
|
state_prefix: "LUMEN".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_reads_back() {
|
||||||
|
let body = host_http::server_info_xml(&host_info(), Scheme::Https, true).unwrap();
|
||||||
|
let s = http::parse_server_info(&body).unwrap();
|
||||||
|
assert_eq!(s.hostname, "LAB-PC");
|
||||||
|
assert_eq!(s.app_version, "7.1.431.-1");
|
||||||
|
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
|
||||||
|
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
|
||||||
|
assert_eq!(s.https_port, 47984);
|
||||||
|
assert_eq!(s.http_port, Some(47989));
|
||||||
|
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
|
||||||
|
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
|
||||||
|
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
|
||||||
|
assert_eq!(s.codec_mode_support, Some(259));
|
||||||
|
assert!(s.paired);
|
||||||
|
assert_eq!(s.current_game, 0);
|
||||||
|
assert_eq!(s.state, "LUMEN_SERVER_FREE");
|
||||||
|
assert_eq!(s.is_busy(), Ok(false));
|
||||||
|
|
||||||
|
// Every element of PROTOCOL.md 1.2 is there, SupportedDisplayMode included.
|
||||||
|
let doc = xml::parse(&body).unwrap();
|
||||||
|
for name in [
|
||||||
|
"hostname",
|
||||||
|
"appversion",
|
||||||
|
"GfeVersion",
|
||||||
|
"uniqueid",
|
||||||
|
"HttpsPort",
|
||||||
|
"ExternalPort",
|
||||||
|
"mac",
|
||||||
|
"LocalIP",
|
||||||
|
"MaxLumaPixelsHEVC",
|
||||||
|
"ServerCodecModeSupport",
|
||||||
|
"SupportedDisplayMode",
|
||||||
|
"PairStatus",
|
||||||
|
"currentgame",
|
||||||
|
"state",
|
||||||
|
] {
|
||||||
|
assert!(doc.root.child(name).is_some(), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_pair_status_per_scheme() {
|
||||||
|
for (scheme, paired, want) in [
|
||||||
|
(Scheme::Http, false, false),
|
||||||
|
(Scheme::Http, true, false),
|
||||||
|
(Scheme::Https, false, false),
|
||||||
|
(Scheme::Https, true, true),
|
||||||
|
] {
|
||||||
|
let s = http::parse_server_info(&host_http::server_info_xml(&host_info(), scheme, paired).unwrap()).unwrap();
|
||||||
|
assert_eq!(s.paired, want, "{scheme:?} paired={paired}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_busy_and_optional_fields() {
|
||||||
|
let info = HostInfo { current_game: 42, mac: None, local_ip: String::new(), ..host_info() };
|
||||||
|
let s = http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap();
|
||||||
|
assert_eq!(s.current_game, 42);
|
||||||
|
assert_eq!(s.state, "LUMEN_SERVER_BUSY");
|
||||||
|
assert_eq!(s.is_busy(), Ok(true));
|
||||||
|
assert_eq!((s.mac, s.local_ip), (None, None));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_escapes_and_refuses() {
|
||||||
|
let info = HostInfo { hostname: "Mark's <PC> & \"TV\"".into(), ..host_info() };
|
||||||
|
let s = http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap();
|
||||||
|
assert_eq!(s.hostname, "Mark's <PC> & \"TV\"");
|
||||||
|
|
||||||
|
let long = "h".repeat(MAX_SERVERINFO_FIELD_BYTES);
|
||||||
|
let info = HostInfo { hostname: long.clone(), ..host_info() };
|
||||||
|
assert_eq!(
|
||||||
|
http::parse_server_info(&host_http::server_info_xml(&info, Scheme::Http, false).unwrap()).unwrap().hostname,
|
||||||
|
long
|
||||||
|
);
|
||||||
|
for (info, why) in [
|
||||||
|
(HostInfo { hostname: String::new(), ..host_info() }, "empty hostname"),
|
||||||
|
(HostInfo { unique_id: String::new(), ..host_info() }, "empty uniqueid"),
|
||||||
|
(HostInfo { hostname: "a\u{1}b".into(), ..host_info() }, "control character"),
|
||||||
|
(HostInfo { hostname: "a\nb".into(), ..host_info() }, "line feed"),
|
||||||
|
(HostInfo { state_prefix: "LU MEN".into(), ..host_info() }, "state prefix with a space"),
|
||||||
|
(HostInfo { state_prefix: String::new(), ..host_info() }, "empty state prefix"),
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
matches!(host_http::server_info_xml(&info, Scheme::Http, false), Err(Error::Malformed { .. })),
|
||||||
|
"{why}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let info = HostInfo { hostname: "h".repeat(MAX_SERVERINFO_FIELD_BYTES + 1), ..host_info() };
|
||||||
|
assert!(matches!(host_http::server_info_xml(&info, Scheme::Http, false), Err(Error::TooLarge { .. })));
|
||||||
|
// Escaping can push a short name over the client's cap: refused here, not by the client.
|
||||||
|
let info = HostInfo { hostname: "&".repeat(MAX_SERVERINFO_FIELD_BYTES), ..host_info() };
|
||||||
|
let r = host_http::server_info_xml(&info, Scheme::Http, false);
|
||||||
|
match r {
|
||||||
|
Ok(body) => assert_eq!(http::parse_server_info(&body).unwrap().hostname, info.hostname),
|
||||||
|
Err(e) => assert!(matches!(e, Error::TooLarge { .. }), "{e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applist_reads_back() {
|
||||||
|
let apps = vec![
|
||||||
|
App { id: 1, title: "Desktop".into(), hdr_supported: false },
|
||||||
|
App { id: 881_448_767, title: "Tom & Jerry's <Big> \"Day\"".into(), hdr_supported: true },
|
||||||
|
App { id: u32::MAX, title: "Žluťoučký kůň".into(), hdr_supported: false },
|
||||||
|
App { id: 0, title: "t".repeat(MAX_APP_TITLE_BYTES), hdr_supported: true },
|
||||||
|
];
|
||||||
|
let body = host_http::app_list_xml(&apps).unwrap();
|
||||||
|
assert_eq!(http::parse_app_list(&body).unwrap(), apps);
|
||||||
|
assert_eq!(http::parse_app_list(&host_http::app_list_xml(&[]).unwrap()).unwrap(), vec![]);
|
||||||
|
|
||||||
|
let dup = vec![apps[0].clone(), App { title: "Other".into(), ..apps[0].clone() }];
|
||||||
|
assert!(matches!(host_http::app_list_xml(&dup), Err(Error::Malformed { .. })));
|
||||||
|
let long = vec![App { id: 1, title: "t".repeat(MAX_APP_TITLE_BYTES + 1), hdr_supported: false }];
|
||||||
|
assert!(matches!(host_http::app_list_xml(&long), Err(Error::TooLarge { .. })));
|
||||||
|
let ctrl = vec![App { id: 1, title: "a\u{7}".into(), hdr_supported: false }];
|
||||||
|
assert!(matches!(host_http::app_list_xml(&ctrl), Err(Error::Malformed { .. })));
|
||||||
|
// The writer's cap is what the client can read: MAX_APPS, and the XML element cap (root + 4 per app).
|
||||||
|
assert_eq!(MAX_WRITTEN_APPS, MAX_APPS.min((MAX_XML_ELEMENTS - 1) / 4));
|
||||||
|
let many: Vec<App> =
|
||||||
|
(0..=MAX_WRITTEN_APPS as u32).map(|i| App { id: i, title: "a".into(), hdr_supported: false }).collect();
|
||||||
|
assert!(matches!(host_http::app_list_xml(&many), Err(Error::TooLarge { .. })));
|
||||||
|
let body = host_http::app_list_xml(&many[..MAX_WRITTEN_APPS]).unwrap();
|
||||||
|
assert_eq!(http::parse_app_list(&body).unwrap().len(), MAX_WRITTEN_APPS);
|
||||||
|
// Long, heavily escaped titles: refused when the body would pass the client's size cap.
|
||||||
|
let heavy: Vec<App> = (0..MAX_WRITTEN_APPS as u32)
|
||||||
|
.map(|i| App { id: i, title: "&".repeat(MAX_APP_TITLE_BYTES), hdr_supported: false })
|
||||||
|
.collect();
|
||||||
|
assert!(matches!(host_http::app_list_xml(&heavy), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn app_titles_round_trip(titles in proptest::collection::vec(value_strategy(), 0..8)) {
|
||||||
|
let apps: Vec<App> = titles.into_iter().enumerate()
|
||||||
|
.map(|(i, t)| App { id: i as u32, title: t, hdr_supported: i % 2 == 0 })
|
||||||
|
.collect();
|
||||||
|
let body = host_http::app_list_xml(&apps).unwrap();
|
||||||
|
prop_assert_eq!(http::parse_app_list(&body).unwrap(), apps);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_and_resume_read_back() {
|
||||||
|
for (host, port, url) in [
|
||||||
|
("192.0.2.10", 48010, "rtsp://192.0.2.10:48010"),
|
||||||
|
("lumen-host.local", 1, "rtsp://lumen-host.local:1"),
|
||||||
|
("[2001:db8::1]", 65535, "rtsp://[2001:db8::1]:65535"),
|
||||||
|
] {
|
||||||
|
for body in [host_http::launch_xml(host, port).unwrap(), host_http::resume_xml(host, port).unwrap()] {
|
||||||
|
let r = http::parse_launch_response(&body).unwrap();
|
||||||
|
assert!(r.game_session);
|
||||||
|
assert_eq!(r.session_url.as_deref(), Some(url));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (host, port) in [("", 48010), ("a b", 48010), ("a&b", 48010), ("[]", 48010), ("x", 0), ("a/b", 1), ("[::1", 1)]
|
||||||
|
{
|
||||||
|
assert!(matches!(host_http::launch_xml(host, port), Err(Error::Malformed { .. })), "{host:?}:{port}");
|
||||||
|
assert!(matches!(host_http::resume_xml(host, port), Err(Error::Malformed { .. })), "{host:?}:{port}");
|
||||||
|
}
|
||||||
|
let long = "h".repeat(300);
|
||||||
|
assert!(matches!(host_http::launch_xml(&long, 1), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ok_and_error_roots() {
|
||||||
|
assert_eq!(http::parse_status_response(&host_http::ok_xml()), Ok(()));
|
||||||
|
let body = host_http::error_xml(401, "The client is not authorized & <paired>").unwrap();
|
||||||
|
let d = xml::parse(&body).unwrap();
|
||||||
|
assert_eq!(d.status_code, 401);
|
||||||
|
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized & <paired>"));
|
||||||
|
assert_eq!(http::parse_status_response(&body), Err(Error::HostStatus { code: 401 }));
|
||||||
|
assert_eq!(xml::parse(&host_http::error_xml(404, "").unwrap()).unwrap().status_message.as_deref(), Some(""));
|
||||||
|
for (code, msg, why) in [
|
||||||
|
(200, "x", "200 is not an error"),
|
||||||
|
(99, "x", "code below 100"),
|
||||||
|
(1000, "x", "code over 999"),
|
||||||
|
(400, "a\nb", "line feed"),
|
||||||
|
(400, "a\u{0}", "NUL"),
|
||||||
|
] {
|
||||||
|
assert!(matches!(host_http::error_xml(code, msg), Err(Error::Malformed { .. })), "{why}");
|
||||||
|
}
|
||||||
|
let at = "m".repeat(MAX_STATUS_MESSAGE_BYTES);
|
||||||
|
assert!(host_http::error_xml(500, &at).is_ok());
|
||||||
|
assert!(matches!(host_http::error_xml(500, &format!("{at}m")), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pair_answers_read_back() {
|
||||||
|
use domistream::pairing::parse_pair_response;
|
||||||
|
let r = parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::Refused).unwrap()).unwrap();
|
||||||
|
assert!(!r.paired);
|
||||||
|
let r = parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::Paired).unwrap()).unwrap();
|
||||||
|
assert!(r.paired && r.plain_cert.is_none() && r.challenge_response.is_none() && r.pairing_secret.is_none());
|
||||||
|
let r = parse_pair_response(
|
||||||
|
&host_http::pair_answer_xml(&PairAnswer::ServerCert { pem: CLIENT_CERT_PEM.into() }).unwrap(),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(r.paired);
|
||||||
|
assert_eq!(r.plain_cert.as_deref(), Some(CLIENT_CERT_PEM.as_bytes()));
|
||||||
|
let r =
|
||||||
|
parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::ChallengeResponse(vec![7; 48])).unwrap()).unwrap();
|
||||||
|
assert_eq!(r.challenge_response, Some(vec![7; 48]));
|
||||||
|
let r =
|
||||||
|
parse_pair_response(&host_http::pair_answer_xml(&PairAnswer::PairingSecret(vec![9; 272])).unwrap()).unwrap();
|
||||||
|
assert_eq!(r.pairing_secret, Some(vec![9; 272]));
|
||||||
|
|
||||||
|
let big = PairAnswer::ServerCert { pem: "A".repeat(MAX_CERT_PEM_BYTES + 1) };
|
||||||
|
assert!(matches!(host_http::pair_answer_xml(&big), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
@@ -0,0 +1,661 @@
|
|||||||
|
//! The host's pairing machine (`docs/PROTOCOL.md` 1.5) driven by this crate's own client, entirely in memory: every
|
||||||
|
//! client request goes through the host's HTTP parser, every host answer through the host's XML writer and the
|
||||||
|
//! client's parser. The keys are the test-only fixtures (`tests/fixtures`).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::{CLIENT_CERT_PEM, EC_CERT_PEM, HOST_KEY_PEM, SeqRng, Vectors, pem_blocks};
|
||||||
|
use domistream::host::http::{Route, pair_answer_xml, parse_request_head};
|
||||||
|
use domistream::host::pairing::{
|
||||||
|
DEFAULT_PHASE_TIMEOUT, DEFAULT_PIN_TIMEOUT, HostIdentity, HostPairingConfig, HostPairingFailure,
|
||||||
|
HostPairingSession, HostPairingState, HostPairingStep, PairAnswer, PairPhase, PairRequest, PairedClient, Transport,
|
||||||
|
};
|
||||||
|
use domistream::http::{HttpRequest, Scheme};
|
||||||
|
use domistream::pairing::identity::MAX_CERT_DER_BYTES;
|
||||||
|
use domistream::pairing::{
|
||||||
|
ClientIdentity, MAX_SIGNATURE_BYTES, PairedHost, PairingFailure, PairingSession, PairingState, PairingStep, Pin,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant, RandomSource};
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
const DEVICE: &str = "Pixel Test Phone";
|
||||||
|
|
||||||
|
fn v() -> Vectors {
|
||||||
|
common::pairing_vectors()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_id() -> HostIdentity {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
|
||||||
|
HostIdentity::from_der(&v().bytes("host_cert_der"), &key).expect("HostIdentity::from_der(test-only host)")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_id() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der")).expect("client identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rogue_id() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pin(d: &str) -> Pin {
|
||||||
|
Pin::from_digits(d).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn secs(s: u64) -> Instant {
|
||||||
|
Instant::ZERO.saturating_add(Duration::from_secs(s))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client's request as the host's HTTP layer sees it.
|
||||||
|
fn to_host(req: &HttpRequest) -> PairRequest {
|
||||||
|
let head = format!("GET {} HTTP/1.1\r\nHost: lumen.test\r\n\r\n", req.path_and_query);
|
||||||
|
let parsed = parse_request_head(head.as_bytes()).expect("the host parses the client's pair request");
|
||||||
|
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
|
||||||
|
match parsed.route {
|
||||||
|
Route::Pair(p) => p,
|
||||||
|
other => panic!("expected a /pair route, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A random source that counts what it hands out.
|
||||||
|
struct Counting(SeqRng, usize);
|
||||||
|
|
||||||
|
impl RandomSource for Counting {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
self.1 += dest.len();
|
||||||
|
self.0.fill(dest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One client and one host, wired together in memory.
|
||||||
|
struct Duo {
|
||||||
|
cid: ClientIdentity,
|
||||||
|
hid: HostIdentity,
|
||||||
|
client: PairingSession,
|
||||||
|
host: HostPairingSession,
|
||||||
|
next: Option<HttpRequest>,
|
||||||
|
crng: SeqRng,
|
||||||
|
hrng: Counting,
|
||||||
|
host_pin: Pin,
|
||||||
|
now: Instant,
|
||||||
|
paired_client: Option<PairedClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Duo {
|
||||||
|
fn new(client_pin: &str, host_pin: &str, seed: u64) -> Self {
|
||||||
|
let cid = client_id();
|
||||||
|
let hid = host_id();
|
||||||
|
let mut crng = SeqRng::new(seed);
|
||||||
|
let (client, req) = PairingSession::start(&cid, UID, DEVICE, pin(client_pin), &mut crng).unwrap();
|
||||||
|
let host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
Self {
|
||||||
|
cid,
|
||||||
|
hid,
|
||||||
|
client,
|
||||||
|
host,
|
||||||
|
next: Some(req),
|
||||||
|
crng,
|
||||||
|
hrng: Counting(SeqRng::new(seed ^ 0xA5A5), 0),
|
||||||
|
host_pin: pin(host_pin),
|
||||||
|
now: Instant::ZERO,
|
||||||
|
paired_client: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host handles `req` (supplying the PIN when it holds the request); its answer, or `Refused` on failure.
|
||||||
|
fn host_answers(&mut self, req: &PairRequest, scheme: Scheme) -> PairAnswer {
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(250));
|
||||||
|
let transport = match scheme {
|
||||||
|
Scheme::Http => Transport::Http,
|
||||||
|
Scheme::Https => Transport::Https { client_cert_der: self.cid.cert_der() },
|
||||||
|
};
|
||||||
|
match self.host.handle(&self.hid, req, transport, self.now, &mut self.hrng) {
|
||||||
|
Ok(HostPairingStep::Answer(a)) => a,
|
||||||
|
Ok(HostPairingStep::HoldForPin) => {
|
||||||
|
assert_eq!(self.host.state(), HostPairingState::AwaitPin);
|
||||||
|
self.now = self.now.saturating_add(Duration::from_secs(5));
|
||||||
|
self.host.supply_pin(&self.hid, self.host_pin, self.now).unwrap_or(PairAnswer::Refused)
|
||||||
|
}
|
||||||
|
Ok(HostPairingStep::Paired(c)) => {
|
||||||
|
self.paired_client = Some(c);
|
||||||
|
PairAnswer::Paired
|
||||||
|
}
|
||||||
|
Err(_) => PairAnswer::Refused,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One round trip of the client's next request. `Ok(Some)` when the client is paired, `Err` when it failed.
|
||||||
|
fn round(&mut self) -> Result<Option<PairedHost>, Error> {
|
||||||
|
let req = self.next.take().expect("a request to send");
|
||||||
|
let answer = self.host_answers(&to_host(&req), req.scheme);
|
||||||
|
let body = pair_answer_xml(&answer).expect("pair_answer_xml");
|
||||||
|
match self.client.handle_response(&self.cid, 200, &body, &mut self.crng)? {
|
||||||
|
PairingStep::Send(r) => {
|
||||||
|
self.next = Some(r);
|
||||||
|
Ok(None)
|
||||||
|
}
|
||||||
|
PairingStep::Paired(h) => Ok(Some(h)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs until the client is paired or fails.
|
||||||
|
fn run(&mut self) -> Result<PairedHost, Error> {
|
||||||
|
for _ in 0..5 {
|
||||||
|
if let Some(h) = self.round()? {
|
||||||
|
return Ok(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("pairing did not finish in five round trips")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host after `rounds` full round trips (0..=4).
|
||||||
|
fn after(rounds: usize) -> Self {
|
||||||
|
let mut d = Self::new("4071", "4071", 7);
|
||||||
|
for _ in 0..rounds {
|
||||||
|
assert!(d.round().unwrap().is_none());
|
||||||
|
}
|
||||||
|
d
|
||||||
|
}
|
||||||
|
|
||||||
|
fn handle(&mut self, phase: PairPhase, transport_scheme: Scheme) -> Result<HostPairingStep, Error> {
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: None, phase };
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(250));
|
||||||
|
let now = self.now;
|
||||||
|
let cert = self.cid.cert_der().to_vec();
|
||||||
|
let transport = match transport_scheme {
|
||||||
|
Scheme::Http => Transport::Http,
|
||||||
|
Scheme::Https => Transport::Https { client_cert_der: &cert },
|
||||||
|
};
|
||||||
|
self.host.handle(&self.hid, &req, transport, now, &mut self.hrng)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ both sides agree
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_and_host_pair_in_memory() {
|
||||||
|
let mut d = Duo::new("4071", "4071", 1);
|
||||||
|
let paired_host = d.run().expect("the client pairs with the host");
|
||||||
|
assert_eq!(d.client.state(), PairingState::Paired);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired);
|
||||||
|
|
||||||
|
// The client pins exactly the host's certificate; the host authorizes exactly the client's.
|
||||||
|
assert_eq!(paired_host.server_cert.der(), d.hid.cert_der());
|
||||||
|
assert_eq!(paired_host.server_cert.matches(d.hid.cert_der()), Ok(true));
|
||||||
|
let pc = d.paired_client.clone().expect("the host returned the paired client");
|
||||||
|
assert_eq!(d.host.paired_client(), Some(&pc));
|
||||||
|
assert_eq!(pc.cert_der, d.cid.cert_der());
|
||||||
|
assert_eq!(pc.unique_id.as_deref(), Some(UID));
|
||||||
|
assert_eq!(pc.device_name.as_deref(), Some(DEVICE));
|
||||||
|
assert_eq!(pc.matches(d.cid.cert_der()), Ok(true));
|
||||||
|
assert_eq!(pc.matches(rogue_id().cert_der()), Ok(false));
|
||||||
|
|
||||||
|
let pending = d.host.pending_client().expect("phase 1 described the client");
|
||||||
|
assert_eq!(pending.cert_der, d.cid.cert_der());
|
||||||
|
assert_eq!(pending.unique_id, UID);
|
||||||
|
assert_eq!(pending.device_name.as_deref(), Some(DEVICE));
|
||||||
|
|
||||||
|
// The host draws exactly S_c and secret_s (16 bytes each), nothing else.
|
||||||
|
assert_eq!(d.hrng.1, 32);
|
||||||
|
assert_eq!(d.host.poll_timeout(), None, "Paired is terminal");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_pins_and_seeds_pair() {
|
||||||
|
for (p, seed) in [("0000", 2u64), ("9999", 3), ("1234", 4)] {
|
||||||
|
let mut d = Duo::new(p, p, seed);
|
||||||
|
d.run().unwrap_or_else(|e| panic!("PIN {p}: {e:?}"));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired, "PIN {p}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_generated_host_identity_pairs() {
|
||||||
|
let hid = HostIdentity::generate(&mut SeqRng::new(0x1u64), "Lumen Test Host", 1_764_000_000).unwrap();
|
||||||
|
let parsed = domistream::pairing::ServerCert::from_der(hid.cert_der()).expect("an RSA X.509 certificate");
|
||||||
|
assert!(hid.cert_der().windows(15).any(|w| w == b"Lumen Test Host"));
|
||||||
|
assert!(hid.cert_pem().unwrap().starts_with("-----BEGIN CERTIFICATE-----\n"));
|
||||||
|
let again = HostIdentity::from_der(hid.cert_der(), hid.key_pkcs8_der()).unwrap();
|
||||||
|
assert_eq!(again.cert_der(), hid.cert_der());
|
||||||
|
|
||||||
|
let mut d = Duo::new("2468", "2468", 5);
|
||||||
|
d.host = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
d.hid = hid;
|
||||||
|
let paired = d.run().unwrap();
|
||||||
|
assert_eq!(paired.server_cert, parsed);
|
||||||
|
assert_err!(HostIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_answers_are_fresh_per_session() {
|
||||||
|
// Same client randomness, different host randomness: the phase-2 answers differ (fresh S_c and secret_s).
|
||||||
|
let answer2 = |host_seed: u64| {
|
||||||
|
let mut d = Duo::new("4071", "4071", 9);
|
||||||
|
d.hrng = Counting(SeqRng::new(host_seed), 0);
|
||||||
|
d.round().unwrap();
|
||||||
|
let req = d.next.clone().unwrap();
|
||||||
|
d.host_answers(&to_host(&req), req.scheme)
|
||||||
|
};
|
||||||
|
let (a, b, a2) = (answer2(1), answer2(2), answer2(1));
|
||||||
|
assert!(matches!(a, PairAnswer::ChallengeResponse(ref v) if v.len() == 48), "{a:?}");
|
||||||
|
assert_ne!(a, b);
|
||||||
|
assert_eq!(a, a2, "the host's randomness comes only from the caller");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ wrong PIN
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pin_fails_on_both_sides() {
|
||||||
|
let mut d = Duo::new("1234", "4321", 11);
|
||||||
|
let r = d.run();
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::ProofMismatch), "the client sees it first");
|
||||||
|
// The client stops; the host waits for phase 4 until its deadline, then fails.
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let deadline = d.host.poll_timeout().expect("a deadline while in progress");
|
||||||
|
assert!(!d.host.handle_timeout(deadline), "the deadline itself is still in time");
|
||||||
|
assert!(d.host.handle_timeout(deadline.saturating_add(Duration::from_micros(1))));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
assert!(!d.host.handle_timeout(deadline.saturating_add(Duration::from_secs(1))), "only once");
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pin_is_caught_by_the_host_when_the_client_carries_on() {
|
||||||
|
// A client that ignores its own failed check and sends phase 4 anyway (signed correctly): the host's proof
|
||||||
|
// check catches the PIN mismatch.
|
||||||
|
let mut d = Duo::new("1234", "4321", 12);
|
||||||
|
for _ in 0..2 {
|
||||||
|
d.round().unwrap();
|
||||||
|
}
|
||||||
|
assert!(d.round().is_err());
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let secret = [0x5Au8; 16];
|
||||||
|
let sig = d.cid.sign(&secret).unwrap();
|
||||||
|
let r = d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_right_pin_but_a_forged_proof_is_a_wrong_pin() {
|
||||||
|
// Correct PIN on both sides, but the client's secret is not the one behind H_c.
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientPairingSecret);
|
||||||
|
let secret = [0x11u8; 16];
|
||||||
|
let sig = d.cid.sign(&secret).unwrap();
|
||||||
|
assert_err!(
|
||||||
|
d.handle(PairPhase::ClientPairingSecret([&secret[..], &sig].concat()), Scheme::Http),
|
||||||
|
Error::PairingRefused
|
||||||
|
);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongPin));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ signatures
|
||||||
|
|
||||||
|
/// The genuine phase-4 value the client would send now, split into secret and signature.
|
||||||
|
fn genuine_phase4(d: &mut Duo) -> (Vec<u8>, Vec<u8>) {
|
||||||
|
let req = d.next.clone().expect("phase 4 pending");
|
||||||
|
match to_host(&req).phase {
|
||||||
|
PairPhase::ClientPairingSecret(v) => (v[..16].to_vec(), v[16..].to_vec()),
|
||||||
|
other => panic!("expected phase 4, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds a phase-4 value from the genuine secret and signature.
|
||||||
|
type Forge = dyn Fn(&[u8], &[u8]) -> Vec<u8>;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_client_signatures() {
|
||||||
|
let rogue = rogue_id();
|
||||||
|
let cases: Vec<(&str, Box<Forge>)> = vec![
|
||||||
|
("signed by another key", Box::new(move |s, _| [s.to_vec(), rogue.sign(s).unwrap()].concat())),
|
||||||
|
(
|
||||||
|
"one bit flipped",
|
||||||
|
Box::new(|s, sig| {
|
||||||
|
let mut sig = sig.to_vec();
|
||||||
|
sig[100] ^= 0x08;
|
||||||
|
[s.to_vec(), sig].concat()
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
("cut short", Box::new(|s, sig| [s, &sig[..sig.len() - 1]].concat())),
|
||||||
|
("zeroed", Box::new(|s, sig| [s.to_vec(), vec![0; sig.len()]].concat())),
|
||||||
|
("one byte", Box::new(|s, _| [s, &[1u8][..]].concat())),
|
||||||
|
];
|
||||||
|
for (why, make) in cases {
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
let (secret, sig) = genuine_phase4(&mut d);
|
||||||
|
let r = d.handle(PairPhase::ClientPairingSecret(make(&secret, &sig)), Scheme::Http);
|
||||||
|
assert_err!(r, Error::PairingRefused, "{why}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::BadSignature), "{why}");
|
||||||
|
}
|
||||||
|
// The genuine value passes.
|
||||||
|
let mut d = Duo::after(3);
|
||||||
|
let (secret, sig) = genuine_phase4(&mut d);
|
||||||
|
let step = d.handle(PairPhase::ClientPairingSecret([secret, sig].concat()), Scheme::Http).unwrap();
|
||||||
|
assert_eq!(step, HostPairingStep::Answer(PairAnswer::Paired));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ order
|
||||||
|
|
||||||
|
fn phase(n: u8) -> PairPhase {
|
||||||
|
match n {
|
||||||
|
1 => PairPhase::GetServerCert { salt: [7; 16], client_cert_pem: CLIENT_CERT_PEM.as_bytes().to_vec() },
|
||||||
|
2 => PairPhase::ClientChallenge(vec![0; 16]),
|
||||||
|
3 => PairPhase::ServerChallengeResp(vec![0; 32]),
|
||||||
|
4 => PairPhase::ClientPairingSecret(vec![0; 16 + 256]),
|
||||||
|
_ => PairPhase::PairChallenge,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A host in in-progress state `i` (0..6), with the phase it expects (0 = it expects the PIN, no phase).
|
||||||
|
fn host_in_state(i: usize) -> (Duo, u8) {
|
||||||
|
match i {
|
||||||
|
0 => (Duo::after(0), 1),
|
||||||
|
1 => {
|
||||||
|
// AwaitPin: phase 1 delivered, PIN not supplied.
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
let step = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
assert_eq!(step, HostPairingStep::HoldForPin);
|
||||||
|
(d, 0)
|
||||||
|
}
|
||||||
|
_ => (Duo::after(i - 1), i as u8),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_phases_are_refused() {
|
||||||
|
let states = [
|
||||||
|
HostPairingState::AwaitGetServerCert,
|
||||||
|
HostPairingState::AwaitPin,
|
||||||
|
HostPairingState::AwaitClientChallenge,
|
||||||
|
HostPairingState::AwaitServerChallengeResp,
|
||||||
|
HostPairingState::AwaitClientPairingSecret,
|
||||||
|
HostPairingState::AwaitPairChallenge,
|
||||||
|
];
|
||||||
|
for (i, want) in states.iter().enumerate() {
|
||||||
|
for wrong in 1..=5u8 {
|
||||||
|
let (mut d, expected) = host_in_state(i);
|
||||||
|
assert_eq!(d.host.state(), *want);
|
||||||
|
if wrong == expected {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let r = d.handle(phase(wrong), if wrong == 5 { Scheme::Https } else { Scheme::Http });
|
||||||
|
assert_err!(r, Error::PairingRefused, "phase {wrong} in {want:?}");
|
||||||
|
assert_eq!(
|
||||||
|
d.host.state(),
|
||||||
|
HostPairingState::Failed(HostPairingFailure::WrongOrder),
|
||||||
|
"phase {wrong} in {want:?}"
|
||||||
|
);
|
||||||
|
// Failed is terminal, also for the phase that would have been right.
|
||||||
|
let right = if expected == 0 { 2 } else { expected };
|
||||||
|
assert_err!(d.handle(phase(right), Scheme::Http), Error::State { .. });
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
|
||||||
|
assert_eq!(d.host.poll_timeout(), None);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_replayed_phase_is_refused() {
|
||||||
|
// Phase 2 accepted, then the same request again.
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
assert!(matches!(
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap(),
|
||||||
|
HostPairingStep::Answer(PairAnswer::ChallengeResponse(_))
|
||||||
|
));
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongOrder));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paired_is_terminal() {
|
||||||
|
let mut d = Duo::new("4071", "4071", 21);
|
||||||
|
d.run().unwrap();
|
||||||
|
for n in 1..=5 {
|
||||||
|
assert_err!(d.handle(phase(n), Scheme::Https), Error::State { .. }, "phase {n}");
|
||||||
|
}
|
||||||
|
d.host.cancel();
|
||||||
|
assert!(!d.host.handle_timeout(secs(1_000_000)));
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ who is asking
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_phase_must_come_from_the_phase_1_client() {
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let mut req = to_host(d.next.as_ref().unwrap());
|
||||||
|
req.unique_id = "FEDCBA9876543210".into();
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn phase_5_needs_https_with_the_phase_1_certificate() {
|
||||||
|
let rogue = rogue_id();
|
||||||
|
for (why, cert) in
|
||||||
|
[("plain HTTP", None), ("another certificate", Some(rogue.cert_der().to_vec())), ("empty", Some(vec![]))]
|
||||||
|
{
|
||||||
|
let mut d = Duo::after(4);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPairChallenge);
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: None, phase: PairPhase::PairChallenge };
|
||||||
|
let transport = match &cert {
|
||||||
|
None => Transport::Http,
|
||||||
|
Some(c) => Transport::Https { client_cert_der: c },
|
||||||
|
};
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&d.hid, &req, transport, now, &mut d.hrng), Error::PairingRefused, "{why}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::WrongClient), "{why}");
|
||||||
|
assert_eq!(d.host.paired_client(), None);
|
||||||
|
}
|
||||||
|
let mut d = Duo::after(4);
|
||||||
|
match d.handle(PairPhase::PairChallenge, Scheme::Https).unwrap() {
|
||||||
|
HostPairingStep::Paired(c) => assert_eq!(c.cert_der, d.cid.cert_der()),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identity_must_stay_the_same() {
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
let other = HostIdentity::from_der(d.cid.cert_der(), d.cid.key_pkcs8_der()).unwrap();
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
assert_err!(d.host.handle(&other, &req, Transport::Http, now, &mut d.hrng), Error::Malformed { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "misuse does not end the session");
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let hid = host_id();
|
||||||
|
let now = d.now;
|
||||||
|
d.host.handle(&hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
assert_err!(d.host.supply_pin(&other, pin("4071"), now), Error::Malformed { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitPin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ bad values
|
||||||
|
|
||||||
|
fn expect_malformed(mut d: Duo, ph: PairPhase, why: &str) {
|
||||||
|
let r = d.handle(ph, Scheme::Http);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{why}: {r:?}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed), "{why}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_phase_values() {
|
||||||
|
let pem = |s: &str| PairPhase::GetServerCert { salt: [1; 16], client_cert_pem: s.as_bytes().to_vec() };
|
||||||
|
expect_malformed(Duo::after(0), pem(""), "empty certificate");
|
||||||
|
expect_malformed(Duo::after(0), pem("hello"), "not PEM");
|
||||||
|
expect_malformed(Duo::after(0), pem(EC_CERT_PEM), "not an RSA certificate");
|
||||||
|
expect_malformed(Duo::after(0), pem(&format!("{CLIENT_CERT_PEM}{CLIENT_CERT_PEM}")), "two certificates");
|
||||||
|
expect_malformed(Duo::after(0), pem(&"A".repeat(1 << 20)), "huge");
|
||||||
|
for len in [0usize, 15, 17, 32] {
|
||||||
|
expect_malformed(Duo::after(1), PairPhase::ClientChallenge(vec![0; len]), &format!("challenge {len}"));
|
||||||
|
}
|
||||||
|
for len in [0usize, 16, 31, 33, 48] {
|
||||||
|
expect_malformed(Duo::after(2), PairPhase::ServerChallengeResp(vec![0; len]), &format!("resp {len}"));
|
||||||
|
}
|
||||||
|
for len in [0usize, 15, 16, 16 + MAX_SIGNATURE_BYTES + 1] {
|
||||||
|
expect_malformed(Duo::after(3), PairPhase::ClientPairingSecret(vec![0; len]), &format!("secret {len}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_unique_ids_and_device_names_in_phase_1() {
|
||||||
|
for (uid, dev) in [
|
||||||
|
("", None),
|
||||||
|
("a&b", None),
|
||||||
|
("a b", None),
|
||||||
|
(&*"a".repeat(65), None),
|
||||||
|
(UID, Some("x".repeat(257))),
|
||||||
|
(UID, Some("tv\u{1}".to_string())),
|
||||||
|
] {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = PairRequest { unique_id: uid.to_string(), device_name: dev.clone(), phase: phase(1) };
|
||||||
|
let now = d.now;
|
||||||
|
let r = d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng);
|
||||||
|
assert!(matches!(r, Err(Error::Malformed { .. } | Error::TooLarge { .. })), "{uid:?} {dev:?}: {r:?}");
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Malformed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the PIN slot
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn supply_pin_only_while_a_request_is_held() {
|
||||||
|
let hid = host_id();
|
||||||
|
let mut s = HostPairingSession::new(&hid, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
assert_err!(s.supply_pin(&hid, pin("4071"), Instant::ZERO), Error::State { .. });
|
||||||
|
assert_eq!(s.state(), HostPairingState::AwaitGetServerCert, "an early PIN does not end the session");
|
||||||
|
assert_eq!(s.pending_client(), None);
|
||||||
|
|
||||||
|
let mut d = Duo::after(1);
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), d.now), Error::State { .. });
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::AwaitClientChallenge, "a second PIN is refused, nothing else");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn deadlines_follow_the_caller_clock() {
|
||||||
|
let hid = host_id();
|
||||||
|
let cfg = HostPairingConfig { pin_timeout: Duration::from_secs(60), phase_timeout: Duration::from_secs(10) };
|
||||||
|
assert_eq!(HostPairingConfig::default().pin_timeout, DEFAULT_PIN_TIMEOUT);
|
||||||
|
assert_eq!(HostPairingConfig::default().phase_timeout, DEFAULT_PHASE_TIMEOUT);
|
||||||
|
let mut s = HostPairingSession::new(&hid, cfg, secs(100));
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(110)), "phase 1 within the phase timeout");
|
||||||
|
let req = PairRequest { unique_id: UID.into(), device_name: Some(DEVICE.into()), phase: phase(1) };
|
||||||
|
let mut rng = SeqRng::new(1);
|
||||||
|
assert_eq!(s.handle(&hid, &req, Transport::Http, secs(105), &mut rng).unwrap(), HostPairingStep::HoldForPin);
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(165)), "the PIN within the PIN timeout");
|
||||||
|
assert!(!s.handle_timeout(secs(165)));
|
||||||
|
assert!(matches!(s.supply_pin(&hid, pin("4071"), secs(165)).unwrap(), PairAnswer::ServerCert { .. }));
|
||||||
|
assert_eq!(s.poll_timeout(), Some(secs(175)), "each phase within the phase timeout of the last answer");
|
||||||
|
let late = PairRequest { unique_id: UID.into(), device_name: None, phase: phase(2) };
|
||||||
|
assert_err!(s.handle(&hid, &late, Transport::Http, secs(176), &mut rng), Error::TimedOut);
|
||||||
|
assert_eq!(s.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_not_typed_in_time() {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
|
||||||
|
let deadline = d.host.poll_timeout().unwrap();
|
||||||
|
assert_eq!(deadline, secs(1).saturating_add(DEFAULT_PIN_TIMEOUT));
|
||||||
|
// Typed one microsecond late, without a timer wake-up first.
|
||||||
|
let late = deadline.saturating_add(Duration::from_micros(1));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), late), Error::TimedOut);
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::TimedOut));
|
||||||
|
|
||||||
|
// The timer fires first.
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, secs(1), &mut d.hrng).unwrap();
|
||||||
|
assert!(d.host.handle_timeout(secs(1000)));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), secs(1000)), Error::State { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_owner_cancels() {
|
||||||
|
let mut d = Duo::after(0);
|
||||||
|
let req = to_host(d.next.as_ref().unwrap());
|
||||||
|
let now = d.now;
|
||||||
|
d.host.handle(&d.hid, &req, Transport::Http, now, &mut d.hrng).unwrap();
|
||||||
|
d.host.cancel();
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
|
||||||
|
assert_err!(d.host.supply_pin(&d.hid, pin("4071"), now), Error::State { .. });
|
||||||
|
d.host.cancel();
|
||||||
|
assert_eq!(d.host.state(), HostPairingState::Failed(HostPairingFailure::Cancelled));
|
||||||
|
// The client is answered paired=0 and stops.
|
||||||
|
let body = pair_answer_xml(&PairAnswer::Refused).unwrap();
|
||||||
|
assert_err!(d.client.handle_response(&d.cid, 200, &body, &mut d.crng), Error::PairingRefused);
|
||||||
|
assert_eq!(d.client.state(), PairingState::Failed(PairingFailure::HostRefused));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ trusted clients
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn trusted_clients_need_no_pin() {
|
||||||
|
let cid = client_id();
|
||||||
|
let c = PairedClient::trusted(cid.cert_der()).unwrap();
|
||||||
|
assert_eq!(c.cert_der, cid.cert_der());
|
||||||
|
assert_eq!(c.unique_id, None);
|
||||||
|
assert_eq!(c.matches(cid.cert_der()), Ok(true));
|
||||||
|
let mut flipped = cid.cert_der().to_vec();
|
||||||
|
let mid = flipped.len() / 2;
|
||||||
|
flipped[mid] ^= 1;
|
||||||
|
assert_eq!(c.matches(&flipped), Ok(false));
|
||||||
|
assert_eq!(c.matches(&[]), Ok(false));
|
||||||
|
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||||
|
|
||||||
|
let ec = pem_blocks(EC_CERT_PEM, "CERTIFICATE").pop().unwrap();
|
||||||
|
for (bad, why) in [(vec![], "empty"), (vec![0x30], "one byte"), (ec, "EC key"), (flipped[..100].to_vec(), "cut")] {
|
||||||
|
assert_err!(PairedClient::trusted(&bad), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
PairedClient::trusted(&vec![0x30; MAX_CERT_DER_BYTES + 1]),
|
||||||
|
MAX_CERT_DER_BYTES,
|
||||||
|
MAX_CERT_DER_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ hygiene
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn debug_never_prints_host_secrets() {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().unwrap();
|
||||||
|
let hid = host_id();
|
||||||
|
let s = format!("{hid:?}");
|
||||||
|
assert!(s.contains("redacted"), "{s}");
|
||||||
|
assert!(!s.to_lowercase().contains(&common::to_hex(&key[key.len() - 32..])));
|
||||||
|
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])));
|
||||||
|
|
||||||
|
let mut d = Duo::after(2);
|
||||||
|
let s = format!("{:?}", d.host);
|
||||||
|
assert!(s.len() < 200, "session Debug stays short: {s}");
|
||||||
|
let req = d.next.clone().unwrap();
|
||||||
|
let a = d.host_answers(&to_host(&req), req.scheme);
|
||||||
|
let s = format!("{a:?}");
|
||||||
|
assert!(s.starts_with("PairingSecret"), "{s}");
|
||||||
|
assert!(s.len() < 40, "answers print lengths, not bytes: {s}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn transport_scheme() {
|
||||||
|
assert_eq!(Transport::Http.scheme(), Scheme::Http);
|
||||||
|
assert_eq!(Transport::Https { client_cert_der: &[] }.scheme(), Scheme::Https);
|
||||||
|
assert_eq!(phase(1).number(), 1);
|
||||||
|
assert_eq!(phase(5).number(), 5);
|
||||||
|
}
|
||||||
@@ -497,6 +497,24 @@ fn applist_caps() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applist_cap_is_reachable_with_full_apps() {
|
||||||
|
// Hosts write four elements per app (App, AppTitle, ID, IsHdrSupported; the host writer does too): a list of
|
||||||
|
// MAX_APPS such apps plus the root must fit the XML element cap, so a list at the app cap parses (one app more is
|
||||||
|
// refused, by whichever cap comes first; `applist_caps` checks the app cap itself with three-element apps).
|
||||||
|
use domistream::http::applist::MAX_APPS;
|
||||||
|
let full = |n: usize| {
|
||||||
|
(0..n)
|
||||||
|
.map(|i| format!("<App><AppTitle>g</AppTitle><ID>{i}</ID><IsHdrSupported>1</IsHdrSupported></App>"))
|
||||||
|
.collect::<String>()
|
||||||
|
};
|
||||||
|
const { assert!(4 * MAX_APPS < MAX_XML_ELEMENTS, "root + 4 per app must fit the element cap") };
|
||||||
|
let apps = http::parse_app_list(&xml_root(200, &full(MAX_APPS))).expect("a full list at the app cap");
|
||||||
|
assert_eq!(apps.len(), MAX_APPS);
|
||||||
|
assert!(apps.iter().all(|a| a.hdr_supported));
|
||||||
|
assert_err!(http::parse_app_list(&xml_root(200, &full(MAX_APPS + 1))), Error::TooLarge { .. });
|
||||||
|
}
|
||||||
|
|
||||||
// ================================================================================================ launch
|
// ================================================================================================ launch
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,962 @@
|
|||||||
|
//! A whole GameStream session between DomiStream's client and DomiStream's host (Lumen's protocol half), in memory,
|
||||||
|
//! with simulated time and seeded randomness (`docs/LUMEN-HOST-PLAN.md` 3.1, 7.1). Every stage goes through both
|
||||||
|
//! sides' own parsers and writers, so an asymmetric mistake shows here before a real client is involved:
|
||||||
|
//!
|
||||||
|
//! serverinfo (HTTP) → pairing with the owner typing the phone's code → serverinfo (HTTPS, paired) → applist → launch
|
||||||
|
//! (session keys handed over) → RTSP (the host's stream config equals the client's ANNOUNCE) → ENet + START_B →
|
||||||
|
//! video over a lossy link (FEC within the parity budget, then a burst beyond it, the client asks for recovery) →
|
||||||
|
//! audio (losses reported, no parity) → input and gamepad → rumble → termination, ENet disconnect, cancel.
|
||||||
|
//!
|
||||||
|
//! Also: a Tessera-trusted client that never pairs over the wire, and an unpaired client that HTTPS refuses.
|
||||||
|
//!
|
||||||
|
//! What the client cannot do with its shipped API is said where it happens: `ControlStream` refuses START_B,
|
||||||
|
//! PERIODIC_PING and the IDR request (bodies UNKNOWN U10, PROTOCOL.md 3.3), so the client side of control here is the
|
||||||
|
//! probe-style stack (`EnetClient` + `ControlCipher`) that sends those three with empty bodies, as `tools/gs-probe` does.
|
||||||
|
|
||||||
|
#![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 common::{HOST_KEY_PEM, SeqRng, pem_blocks};
|
||||||
|
use domistream::audio::{
|
||||||
|
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacketizer, AudioPacketizerConfig,
|
||||||
|
AudioParity,
|
||||||
|
};
|
||||||
|
use domistream::control::host::{DEFAULT_STOP_TIMEOUT, TERMINATION_GRACEFUL};
|
||||||
|
use domistream::control::message::encode_client_message;
|
||||||
|
use domistream::control::{
|
||||||
|
ClientControlMessage, ClientMessage, ControlCipher, ControlHost, ControlHostConfig, ControlHostEvent, Direction,
|
||||||
|
HostMessage, MessageType, parse_host_message,
|
||||||
|
};
|
||||||
|
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetHostConfig, EnetHostState, EnetState};
|
||||||
|
use domistream::host::http::{
|
||||||
|
HostInfo, LaunchRequest, Route, app_list_xml, error_xml, launch_xml, ok_xml, pair_answer_xml, parse_request_head,
|
||||||
|
server_info_xml,
|
||||||
|
};
|
||||||
|
use domistream::host::pairing::{
|
||||||
|
HostIdentity, HostPairingConfig, HostPairingSession, HostPairingStep, PairAnswer, PairPhase, PairRequest,
|
||||||
|
PairedClient, Transport,
|
||||||
|
};
|
||||||
|
use domistream::http::launch::{AudioLayout, LaunchParams, launch_request};
|
||||||
|
use domistream::http::{
|
||||||
|
App, HttpRequest, Scheme, ServerInfo, app_list_request, cancel_request, parse_app_list, parse_launch_response,
|
||||||
|
parse_server_info, parse_status_response, server_info_request,
|
||||||
|
};
|
||||||
|
use domistream::input::{ButtonFlags, GamepadState, InputEvent, MouseButton};
|
||||||
|
use domistream::pairing::{
|
||||||
|
ClientIdentity, PairedHost, PairingSession, PairingStep, Pin, ServerCert, parse_pair_response,
|
||||||
|
};
|
||||||
|
use domistream::rtsp::client::{PING_PAYLOAD, VideoCodec};
|
||||||
|
use domistream::rtsp::sdp::{FeatureFlags, parse_surround_params};
|
||||||
|
use domistream::rtsp::server::{
|
||||||
|
ChromaSampling, DEFAULT_SESSION_TIMEOUT_SECS, StreamConfig as HostStreamConfig, SurroundSettings,
|
||||||
|
};
|
||||||
|
use domistream::rtsp::{
|
||||||
|
EncryptionFlags, HostOffer, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, RtspServer, ServerConfig,
|
||||||
|
ServerEvent, StreamConfig as ClientStreamConfig, StreamPorts,
|
||||||
|
};
|
||||||
|
use domistream::video::packet::FRAME_HEADER_LEN;
|
||||||
|
use domistream::video::packetizer::{FecBlock, plan_fec_blocks};
|
||||||
|
use domistream::video::{
|
||||||
|
EncodedFrame, FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoPacketizer,
|
||||||
|
VideoPacketizerConfig,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant, SessionKeys};
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
const DEVICE: &str = "Arena Domi TV test";
|
||||||
|
const HOST_ADDR: &str = "192.0.2.10";
|
||||||
|
const RTSP_PORT: u16 = 48010;
|
||||||
|
const PORTS: StreamPorts = StreamPorts { audio: 48000, video: 47998, control: 47999 };
|
||||||
|
const ALL: u8 = EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO;
|
||||||
|
/// The host's video FEC percentage: Moonshine's default (S-31).
|
||||||
|
const FEC_PERCENT: u8 = 20;
|
||||||
|
|
||||||
|
// ================================================================================================ identities
|
||||||
|
|
||||||
|
fn host_identity() -> HostIdentity {
|
||||||
|
let key = pem_blocks(HOST_KEY_PEM, "PRIVATE KEY").pop().expect("host key PEM");
|
||||||
|
HostIdentity::from_der(&common::pairing_vectors().bytes("host_cert_der"), &key).expect("test-only host identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_identity(name: &str) -> ClientIdentity {
|
||||||
|
let v = common::pairing_vectors();
|
||||||
|
ClientIdentity::from_der(&v.bytes(&format!("{name}_cert_der")), &v.bytes(&format!("{name}_key_pkcs8_der")))
|
||||||
|
.expect("test-only client identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the host's HTTP side
|
||||||
|
|
||||||
|
/// Lumen's HTTP and HTTPS listeners as the caller of `host::http` and `host::pairing` builds them.
|
||||||
|
struct LumenHttp {
|
||||||
|
identity: HostIdentity,
|
||||||
|
info: HostInfo,
|
||||||
|
apps: Vec<App>,
|
||||||
|
/// Clients whose certificate HTTPS accepts (paired, or recorded from a Tessera grant).
|
||||||
|
paired: Vec<PairedClient>,
|
||||||
|
pairing: Option<HostPairingSession>,
|
||||||
|
/// The code the owner types into "Enter the code from your phone" when a pairing request is held.
|
||||||
|
owner_code: Option<Pin>,
|
||||||
|
launched: Option<LaunchRequest>,
|
||||||
|
rng: SeqRng,
|
||||||
|
now: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl LumenHttp {
|
||||||
|
fn new(seed: u64) -> Self {
|
||||||
|
Self {
|
||||||
|
identity: host_identity(),
|
||||||
|
info: HostInfo {
|
||||||
|
hostname: "Lumen test host".into(),
|
||||||
|
app_version: "7.1.431.-1".into(),
|
||||||
|
gfe_version: "3.23.0.74".into(),
|
||||||
|
unique_id: "LUMEN-TEST-HOST-1".into(),
|
||||||
|
https_port: 47984,
|
||||||
|
http_port: 47989,
|
||||||
|
mac: Some([0x02, 0, 0x5e, 0x10, 0x20, 0x30]),
|
||||||
|
local_ip: HOST_ADDR.into(),
|
||||||
|
max_luma_pixels_hevc: 1_869_449_984,
|
||||||
|
codec_mode_support: 0x0101,
|
||||||
|
current_game: 0,
|
||||||
|
state_prefix: "LUMEN".into(),
|
||||||
|
},
|
||||||
|
apps: vec![
|
||||||
|
App { id: 1, title: "Desktop".into(), hdr_supported: false },
|
||||||
|
App { id: 881_100, title: "Hollow & <Knight>".into(), hdr_supported: false },
|
||||||
|
App { id: 4_000_000_000, title: "Forza Horizon 5".into(), hdr_supported: true },
|
||||||
|
],
|
||||||
|
paired: Vec::new(),
|
||||||
|
pairing: None,
|
||||||
|
owner_code: None,
|
||||||
|
launched: None,
|
||||||
|
rng: SeqRng::new(seed),
|
||||||
|
now: Instant::ZERO,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_paired(&self, cert_der: &[u8]) -> bool {
|
||||||
|
self.paired.iter().any(|p| p.matches(cert_der).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One GET: the head through the host's strict parser, the answer from the host's XML writers. HTTPS routes other
|
||||||
|
/// than `/pair` and `/serverinfo` need a paired certificate (refused with status 401 otherwise).
|
||||||
|
fn serve(&mut self, request: &HttpRequest, transport: Transport<'_>) -> Vec<u8> {
|
||||||
|
self.now = self.now.saturating_add(Duration::from_millis(40));
|
||||||
|
let head = format!("GET {} HTTP/1.1\r\nHost: {HOST_ADDR}\r\n\r\n", request.path_and_query);
|
||||||
|
let parsed = parse_request_head(head.as_bytes()).expect("the host parses every request our client builds");
|
||||||
|
assert_eq!(parsed.unique_id.as_deref(), Some(UID));
|
||||||
|
// The host reads every parameter our client sends, except `updateState=1` on `/pair` (U1: whether a host
|
||||||
|
// needs it is unknown; Lumen's parser keeps it for the logs and does not need it).
|
||||||
|
let unread: Vec<&str> = parsed.other_params.iter().map(|(name, _)| name.as_str()).collect();
|
||||||
|
let allowed: &[&str] = if matches!(parsed.route, Route::Pair(_)) { &["updateState"] } else { &[] };
|
||||||
|
assert_eq!(unread, allowed, "parameters the host does not read");
|
||||||
|
let paired = match transport {
|
||||||
|
Transport::Https { client_cert_der } => self.is_paired(client_cert_der),
|
||||||
|
Transport::Http => false,
|
||||||
|
};
|
||||||
|
match parsed.route {
|
||||||
|
Route::ServerInfo => server_info_xml(&self.info, transport.scheme(), paired).unwrap(),
|
||||||
|
Route::Pair(p) => self.pair(&p, transport),
|
||||||
|
_ if !paired => error_xml(401, "This device is not paired with Arena Domi").unwrap(),
|
||||||
|
Route::AppList => app_list_xml(&self.apps).unwrap(),
|
||||||
|
Route::Launch(l) => {
|
||||||
|
self.info.current_game = l.app_id;
|
||||||
|
self.launched = Some(l);
|
||||||
|
launch_xml(HOST_ADDR, RTSP_PORT).unwrap()
|
||||||
|
}
|
||||||
|
Route::Cancel => {
|
||||||
|
self.info.current_game = 0;
|
||||||
|
ok_xml()
|
||||||
|
}
|
||||||
|
other => panic!("the session test does not use {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `/pair`: phase 1 opens a new attempt and is held until the owner types the code.
|
||||||
|
fn pair(&mut self, request: &PairRequest, transport: Transport<'_>) -> Vec<u8> {
|
||||||
|
if matches!(request.phase, PairPhase::GetServerCert { .. }) {
|
||||||
|
self.pairing = Some(HostPairingSession::new(&self.identity, HostPairingConfig::default(), self.now));
|
||||||
|
}
|
||||||
|
let Some(session) = self.pairing.as_mut() else { return pair_answer_xml(&PairAnswer::Refused).unwrap() };
|
||||||
|
let answer = match session.handle(&self.identity, request, transport, self.now, &mut self.rng) {
|
||||||
|
Ok(HostPairingStep::Answer(a)) => a,
|
||||||
|
Ok(HostPairingStep::HoldForPin) => {
|
||||||
|
let code = self.owner_code.take().expect("the owner has the phone's code to type");
|
||||||
|
self.now = self.now.saturating_add(Duration::from_secs(4));
|
||||||
|
session.supply_pin(&self.identity, code, self.now).unwrap_or(PairAnswer::Refused)
|
||||||
|
}
|
||||||
|
Ok(HostPairingStep::Paired(client)) => {
|
||||||
|
self.paired.push(client);
|
||||||
|
PairAnswer::Paired
|
||||||
|
}
|
||||||
|
Err(_) => PairAnswer::Refused,
|
||||||
|
};
|
||||||
|
pair_answer_xml(&answer).unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client's HTTP(S) call. Over HTTPS the client presents its certificate and pins the host's: the TLS stack's
|
||||||
|
/// job in the app (PROTOCOL.md 1.1), an explicit check here.
|
||||||
|
fn get(host: &mut LumenHttp, request: &HttpRequest, client: &ClientIdentity, pinned: Option<&ServerCert>) -> Vec<u8> {
|
||||||
|
match request.scheme {
|
||||||
|
Scheme::Http => host.serve(request, Transport::Http),
|
||||||
|
Scheme::Https => {
|
||||||
|
let pin = pinned.expect("HTTPS only with a pinned host certificate");
|
||||||
|
assert_eq!(
|
||||||
|
pin.matches(host.identity.cert_der()),
|
||||||
|
Ok(true),
|
||||||
|
"TLS: the host presents the pinned certificate"
|
||||||
|
);
|
||||||
|
host.serve(request, Transport::Https { client_cert_der: client.cert_der() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pairs `client` with `host`: the phone makes the code, the owner types it on the PC (`docs/LUMEN-HOST-PLAN.md`
|
||||||
|
/// 1.9). The client pins the phase-1 `plaincert` for the HTTPS phase 5.
|
||||||
|
fn pair(host: &mut LumenHttp, client: &ClientIdentity, rng: &mut SeqRng) -> PairedHost {
|
||||||
|
let code = Pin::generate(rng).unwrap();
|
||||||
|
host.owner_code = Some(code);
|
||||||
|
let (mut session, mut request) = PairingSession::start(client, UID, DEVICE, code, rng).unwrap();
|
||||||
|
let mut plaincert: Option<ServerCert> = None;
|
||||||
|
for _ in 0..5 {
|
||||||
|
let body = get(host, &request, client, plaincert.as_ref());
|
||||||
|
if plaincert.is_none() {
|
||||||
|
let pem = parse_pair_response(&body).unwrap().plain_cert.expect("phase 1 carries plaincert");
|
||||||
|
plaincert = Some(ServerCert::from_pem(&pem).unwrap());
|
||||||
|
}
|
||||||
|
match session.handle_response(client, 200, &body, rng).expect("every phase passes") {
|
||||||
|
PairingStep::Send(next) => request = next,
|
||||||
|
PairingStep::Paired(paired) => return paired,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("pairing did not finish in five round trips");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ RTSP
|
||||||
|
|
||||||
|
fn client_stream_config() -> ClientStreamConfig {
|
||||||
|
ClientStreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
packet_size: 1024,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
encryption: EncryptionFlags(ALL),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rtsp_server_config() -> ServerConfig {
|
||||||
|
ServerConfig {
|
||||||
|
ports: PORTS,
|
||||||
|
offer: HostOffer {
|
||||||
|
feature_flags: FeatureFlags(3),
|
||||||
|
encryption_supported: EncryptionFlags(ALL),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: false,
|
||||||
|
hdr: false,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![parse_surround_params("21101").unwrap()],
|
||||||
|
},
|
||||||
|
required_encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2),
|
||||||
|
// Our client echoes the SETUP session id, so the strict setting holds.
|
||||||
|
require_session_header: true,
|
||||||
|
session_timeout_secs: DEFAULT_SESSION_TIMEOUT_SECS,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the host must read from our client's ANNOUNCE for `c` (the attributes `rtsp::sdp::build_announce` writes).
|
||||||
|
fn announced_by(c: &ClientStreamConfig, enabled: EncryptionFlags) -> HostStreamConfig {
|
||||||
|
let channels = c.audio.channels();
|
||||||
|
HostStreamConfig {
|
||||||
|
width: c.width,
|
||||||
|
height: c.height,
|
||||||
|
max_fps: c.fps,
|
||||||
|
packet_size: c.packet_size,
|
||||||
|
bitrate_kbps: c.bitrate_kbps,
|
||||||
|
codec: c.codec,
|
||||||
|
min_fec_packets: c.min_fec_packets,
|
||||||
|
video_qos_traffic_type: 5,
|
||||||
|
audio_packet_duration_ms: c.audio_packet_duration_ms,
|
||||||
|
audio_qos_traffic_type: 4,
|
||||||
|
max_reference_frames: if c.reference_frame_invalidation { 0 } else { 1 },
|
||||||
|
reference_frame_invalidation: c.reference_frame_invalidation,
|
||||||
|
dynamic_range_mode: u32::from(c.hdr),
|
||||||
|
encoder_csc_mode: if c.hdr { 5 } else { 0 },
|
||||||
|
chroma: ChromaSampling::Yuv420,
|
||||||
|
encryption: enabled,
|
||||||
|
surround: SurroundSettings {
|
||||||
|
enabled: channels > 2,
|
||||||
|
channels,
|
||||||
|
channel_mask: c.audio.channel_mask(),
|
||||||
|
high_quality: true,
|
||||||
|
},
|
||||||
|
unknown_attributes: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// OPTIONS … PLAY, one TCP connection per request (PROTOCOL.md 2.5), bytes cut 7 at a time by both framers.
|
||||||
|
fn negotiate(
|
||||||
|
session_url: &str,
|
||||||
|
config: ClientStreamConfig,
|
||||||
|
server: &mut RtspServer,
|
||||||
|
) -> (NegotiatedStream, Vec<ServerEvent>) {
|
||||||
|
let mut client = RtspClient::new(session_url, config).unwrap();
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for _ in 0..7 {
|
||||||
|
let request = client.poll_request().expect("the client has its next request");
|
||||||
|
let mut to_server = RtspFramer::for_requests();
|
||||||
|
let mut replies = Vec::new();
|
||||||
|
for piece in request.chunks(7) {
|
||||||
|
to_server.push(piece).unwrap();
|
||||||
|
while let Some(message) = to_server.next_message().unwrap() {
|
||||||
|
replies.push(server.handle_request(&message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(replies.len(), 1, "one request, one answer");
|
||||||
|
assert_eq!(replies[0].status, 200, "{:?}", replies[0].error);
|
||||||
|
events.extend(core::iter::from_fn(|| server.poll_event()));
|
||||||
|
let mut to_client = RtspFramer::new();
|
||||||
|
let mut answers = Vec::new();
|
||||||
|
for piece in replies[0].bytes.chunks(7) {
|
||||||
|
to_client.push(piece).unwrap();
|
||||||
|
answers.extend(to_client.next_message().unwrap());
|
||||||
|
}
|
||||||
|
assert_eq!(answers.len(), 1, "the answer is framed by Content-Length");
|
||||||
|
if let RtspProgress::Ready(n) = client.handle_response(&answers[0]).unwrap() {
|
||||||
|
return (n, events);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("RTSP never finished");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ control
|
||||||
|
|
||||||
|
/// The client's control stream, probe-style (see the top of this file).
|
||||||
|
struct ClientControl {
|
||||||
|
enet: EnetClient,
|
||||||
|
cipher: ControlCipher,
|
||||||
|
next_sequence: u32,
|
||||||
|
last_host_sequence: Option<u32>,
|
||||||
|
host_messages: Vec<HostMessage>,
|
||||||
|
enet_events: Vec<EnetEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientControl {
|
||||||
|
fn connect(rikey: [u8; 16], rng: &mut SeqRng) -> Self {
|
||||||
|
let config = EnetConfig {
|
||||||
|
channel_count: 1,
|
||||||
|
mtu: 1392,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
Self {
|
||||||
|
enet: EnetClient::connect(config, Instant::ZERO, rng).unwrap(),
|
||||||
|
cipher: ControlCipher::new(rikey),
|
||||||
|
next_sequence: 0,
|
||||||
|
last_host_sequence: None,
|
||||||
|
host_messages: Vec::new(),
|
||||||
|
enet_events: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_plain(&mut self, now: Instant, plain: &[u8]) {
|
||||||
|
let frame = self.cipher.seal(self.next_sequence, Direction::ClientToHost, plain).unwrap();
|
||||||
|
self.enet.send(now, 0, Delivery::Reliable, &frame).unwrap();
|
||||||
|
self.next_sequence += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(&mut self, now: Instant, message: &ClientMessage) {
|
||||||
|
self.send_plain(now, &encode_client_message(message).unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message with an empty body: START_B, PERIODIC_PING, IDR request (PROTOCOL.md 3.3).
|
||||||
|
fn send_empty(&mut self, now: Instant, message_type: MessageType) {
|
||||||
|
let mut plain = (message_type as u16).to_le_bytes().to_vec();
|
||||||
|
plain.extend_from_slice(&0u16.to_le_bytes());
|
||||||
|
self.send_plain(now, &plain);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(&mut self) {
|
||||||
|
while let Some(event) = self.enet.poll_event() {
|
||||||
|
match event {
|
||||||
|
EnetEvent::Received { data, .. } => {
|
||||||
|
let (sequence, plain) = self.cipher.open(Direction::HostToClient, &data).expect("host frames open");
|
||||||
|
assert!(self.last_host_sequence.is_none_or(|last| sequence > last), "host sequence goes up");
|
||||||
|
self.last_host_sequence = Some(sequence);
|
||||||
|
self.host_messages.push(parse_host_message(&plain).expect("the client reads every host message"));
|
||||||
|
}
|
||||||
|
other => self.enet_events.push(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Endpoint for ClientControl {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lumen's control listener for this client's address: the first datagram must be the CONNECT.
|
||||||
|
struct HostControl {
|
||||||
|
config: ControlHostConfig,
|
||||||
|
host: Option<ControlHost>,
|
||||||
|
events: Vec<ControlHostEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HostControl {
|
||||||
|
fn h(&mut self) -> &mut ControlHost {
|
||||||
|
self.host.as_mut().expect("accepted")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn messages(&self) -> Vec<ClientControlMessage> {
|
||||||
|
self.events
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| match e {
|
||||||
|
ControlHostEvent::Message(m) => Some(m.clone()),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(&mut self) {
|
||||||
|
if let Some(h) = self.host.as_mut() {
|
||||||
|
self.events.extend(core::iter::from_fn(|| h.poll_event()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Endpoint for HostControl {
|
||||||
|
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 => self.host = ControlHost::accept(self.config.clone(), now, datagram).ok(),
|
||||||
|
Some(h) => {
|
||||||
|
let _ = h.handle_datagram(now, datagram);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.drain();
|
||||||
|
}
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type Control = Wire<ClientControl, HostControl>;
|
||||||
|
|
||||||
|
/// Runs the control wire until the host has seen `n` messages; returns the new ones.
|
||||||
|
fn host_receives(w: &mut Control, n: usize) -> Vec<ClientControlMessage> {
|
||||||
|
let before = w.host.messages().len();
|
||||||
|
assert!(w.run_until(w.now_ms + 10_000, |w| w.host.messages().len() >= before + n), "the host never got them");
|
||||||
|
w.host.messages()[before..].to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ media
|
||||||
|
|
||||||
|
/// A synthetic HEVC access unit of exactly `len` bytes (at least 6): start code, a NAL header (IDR_W_RADL for a key
|
||||||
|
/// frame, TRAIL_R otherwise), random payload.
|
||||||
|
fn access_unit(rng: &mut SeqRng, len: usize, key: bool) -> Vec<u8> {
|
||||||
|
let mut au = vec![0, 0, 0, 1, if key { 0x26 } else { 0x02 }, 0x01];
|
||||||
|
au.extend(rng.bytes(len - 6));
|
||||||
|
au
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How the lossy link treats one FEC block: the indices (data first, then parity) it drops.
|
||||||
|
type LossPlan<'a> = &'a mut dyn FnMut(&FecBlock, &mut SeqRng) -> Vec<usize>;
|
||||||
|
|
||||||
|
/// The worst loss FEC still repairs: exactly `m` of the block's `k + m` datagrams, at least one of them data.
|
||||||
|
fn within_budget(b: &FecBlock, rng: &mut SeqRng) -> Vec<usize> {
|
||||||
|
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
|
||||||
|
let mut lost = rng.subset(k + m, m);
|
||||||
|
if !lost.is_empty() && lost.iter().all(|&i| i >= k) {
|
||||||
|
lost[0] = rng.below(k);
|
||||||
|
}
|
||||||
|
lost
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sends one frame over the link: drops what `loss` picks per block, duplicates one survivor, shuffles the rest.
|
||||||
|
/// Returns the data shards lost (what FEC must rebuild) and the duplicates sent.
|
||||||
|
fn send_frame(
|
||||||
|
packetizer: &mut VideoPacketizer,
|
||||||
|
receiver: &mut VideoDepacketizer,
|
||||||
|
frame: &EncodedFrame<'_>,
|
||||||
|
min_parity: u8,
|
||||||
|
loss: LossPlan<'_>,
|
||||||
|
rng: &mut SeqRng,
|
||||||
|
now: Instant,
|
||||||
|
) -> (usize, usize) {
|
||||||
|
let packets = packetizer.packetize(frame).unwrap();
|
||||||
|
let payload = usize::from(client_stream_config().packet_size) - 16;
|
||||||
|
let shards = (FRAME_HEADER_LEN + frame.bitstream.len()).div_ceil(payload);
|
||||||
|
let plan = plan_fec_blocks(shards, FEC_PERCENT, min_parity).unwrap();
|
||||||
|
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards + b.parity_shards)).sum::<usize>(), packets.len());
|
||||||
|
let mut survivors = Vec::new();
|
||||||
|
let mut data_lost = 0;
|
||||||
|
let mut start = 0;
|
||||||
|
for block in &plan {
|
||||||
|
let size = usize::from(block.data_shards + block.parity_shards);
|
||||||
|
let lost = loss(block, rng);
|
||||||
|
data_lost += lost.iter().filter(|&&i| i < usize::from(block.data_shards)).count();
|
||||||
|
survivors.extend((0..size).filter(|i| !lost.contains(i)).map(|i| packets[start + i].clone()));
|
||||||
|
start += size;
|
||||||
|
}
|
||||||
|
let duplicate = survivors[rng.below(survivors.len())].clone();
|
||||||
|
survivors.push(duplicate);
|
||||||
|
rng.shuffle(&mut survivors);
|
||||||
|
for datagram in &survivors {
|
||||||
|
receiver.push(now, datagram).unwrap();
|
||||||
|
}
|
||||||
|
(data_lost, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn video_events(receiver: &mut VideoDepacketizer, now: Instant, out: &mut Vec<VideoEvent>) {
|
||||||
|
if receiver.poll_timeout().is_some_and(|t| t <= now) {
|
||||||
|
receiver.handle_timeout(now).unwrap();
|
||||||
|
}
|
||||||
|
out.extend(core::iter::from_fn(|| receiver.poll_event()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the session
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_whole_session_between_our_client_and_our_host() {
|
||||||
|
let mut rng = SeqRng::new(0x5E55_1011);
|
||||||
|
let client = client_identity("client");
|
||||||
|
let mut host = LumenHttp::new(0x1u64 << 40);
|
||||||
|
|
||||||
|
// serverinfo over HTTP: the host is there, this client is not paired.
|
||||||
|
let info: ServerInfo =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Http, UID).unwrap(), &client, None)).unwrap();
|
||||||
|
assert_eq!((info.hostname.as_str(), info.unique_id.as_str()), ("Lumen test host", "LUMEN-TEST-HOST-1"));
|
||||||
|
assert_eq!((info.https_port, info.http_port, info.mac), (47984, Some(47989), host.info.mac));
|
||||||
|
assert_eq!((info.paired, info.current_game, info.state.as_str()), (false, 0, "LUMEN_SERVER_FREE"));
|
||||||
|
|
||||||
|
// Pairing: the owner types the phone's code; the client pins exactly the host's certificate, the host
|
||||||
|
// authorizes exactly the client's.
|
||||||
|
let paired = pair(&mut host, &client, &mut rng);
|
||||||
|
assert_eq!(paired.server_cert.der(), host.identity.cert_der());
|
||||||
|
assert_eq!(host.paired.len(), 1);
|
||||||
|
assert_eq!(host.paired[0].cert_der, client.cert_der());
|
||||||
|
assert_eq!((host.paired[0].unique_id.as_deref(), host.paired[0].device_name.as_deref()), (Some(UID), Some(DEVICE)));
|
||||||
|
let pin = Some(&paired.server_cert);
|
||||||
|
|
||||||
|
// serverinfo over HTTPS: PairStatus 1. Then the app list, byte for byte as the host holds it.
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(info.paired, "PairStatus 1 over HTTPS with the paired certificate");
|
||||||
|
let apps = parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert_eq!(apps, host.apps);
|
||||||
|
|
||||||
|
// launch: the session keys reach the host unchanged.
|
||||||
|
let keys = SessionKeys::generate(&mut rng).unwrap();
|
||||||
|
let params = LaunchParams {
|
||||||
|
app_id: apps[2].id,
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
keys: keys.clone(),
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
};
|
||||||
|
let launch = parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(launch.game_session);
|
||||||
|
let session_url = launch.session_url.expect("sessionUrl0");
|
||||||
|
assert_eq!(session_url, format!("rtsp://{HOST_ADDR}:{RTSP_PORT}"));
|
||||||
|
let launched = host.launched.clone().expect("the host took the launch");
|
||||||
|
assert_eq!(launched.keys, keys);
|
||||||
|
assert_eq!(
|
||||||
|
(launched.app_id, launched.mode.width, launched.mode.height, launched.mode.fps),
|
||||||
|
(4_000_000_000, 1920, 1080, 60)
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
(launched.hdr, launched.surround_audio_info),
|
||||||
|
(Some(false), Some(AudioLayout::Stereo.surround_audio_info()))
|
||||||
|
);
|
||||||
|
assert_eq!(host.info.current_game, 4_000_000_000);
|
||||||
|
|
||||||
|
// RTSP: the host's stream config is exactly what the client announced.
|
||||||
|
let mut rtsp = RtspServer::new(rtsp_server_config(), &mut rng).unwrap();
|
||||||
|
let (negotiated, events) = negotiate(&session_url, client_stream_config(), &mut rtsp);
|
||||||
|
assert_eq!(negotiated.ports, PORTS);
|
||||||
|
assert_eq!(negotiated.encryption, EncryptionFlags(ALL));
|
||||||
|
assert_eq!(negotiated.session_id.as_deref(), Some(rtsp.session_id()));
|
||||||
|
assert_eq!(negotiated.opus, parse_surround_params("21101").unwrap());
|
||||||
|
assert!(negotiated.host.reference_frame_invalidation);
|
||||||
|
assert_eq!(negotiated.ping_payload, PING_PAYLOAD, "the PING the host's media listeners wait for");
|
||||||
|
let announced = announced_by(&client_stream_config(), negotiated.encryption);
|
||||||
|
assert_eq!(events, vec![ServerEvent::Announced(announced.clone()), ServerEvent::PlayRequested]);
|
||||||
|
assert_eq!(rtsp.announced(), Some(&announced));
|
||||||
|
assert_eq!(
|
||||||
|
(announced.width, announced.height, announced.max_fps),
|
||||||
|
(launched.mode.width, launched.mode.height, launched.mode.fps)
|
||||||
|
);
|
||||||
|
|
||||||
|
// ENet connect on the control port, then START_B. ControlStream refuses START_B (body U10), hence the probe path.
|
||||||
|
assert_err!(encode_client_message(&ClientMessage::StartB), Error::Unsupported { .. });
|
||||||
|
let host_control = HostControl {
|
||||||
|
config: ControlHostConfig {
|
||||||
|
enet: EnetHostConfig {
|
||||||
|
peer_id: 0,
|
||||||
|
channel_limit: 0x30,
|
||||||
|
mtu: 1392,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
},
|
||||||
|
rikey: launched.keys.rikey,
|
||||||
|
stop_timeout: Some(DEFAULT_STOP_TIMEOUT),
|
||||||
|
},
|
||||||
|
host: None,
|
||||||
|
events: Vec::new(),
|
||||||
|
};
|
||||||
|
let mut w: Control = Wire::new(
|
||||||
|
ClientControl::connect(keys.rikey, &mut rng),
|
||||||
|
host_control,
|
||||||
|
Impair::lossy(30, 5),
|
||||||
|
Impair::lossy(30, 5),
|
||||||
|
77,
|
||||||
|
);
|
||||||
|
assert!(w.run_until(10_000, |w| w.client.enet.state() == EnetState::Connected
|
||||||
|
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Connected)));
|
||||||
|
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected]);
|
||||||
|
assert_eq!(w.host.events, vec![ControlHostEvent::Connected]);
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send_empty(t, MessageType::StartB);
|
||||||
|
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::StartB]);
|
||||||
|
|
||||||
|
// A PERIODIC_PING moves the host's stop deadline out (a ControlStream client never sends one: U10).
|
||||||
|
let deadline = w.host.h().stop_deadline().expect("the stop clock runs");
|
||||||
|
w.run_for(1_000);
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send_empty(t, MessageType::PeriodicPing);
|
||||||
|
assert_eq!(host_receives(&mut w, 1), vec![ClientControlMessage::PeriodicPing]);
|
||||||
|
assert!(w.host.h().stop_deadline().unwrap() > deadline);
|
||||||
|
|
||||||
|
// Video: the packet size and minimum parity the client announced, sealed with the session key.
|
||||||
|
let mut packetizer = VideoPacketizer::new(VideoPacketizerConfig {
|
||||||
|
packet_size: announced.packet_size,
|
||||||
|
fec_percentage: FEC_PERCENT,
|
||||||
|
min_required_fec_packets: announced.min_fec_packets,
|
||||||
|
cipher: announced.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(launched.keys.rikey)),
|
||||||
|
first_sequence: 0xFFF0, // the RTP sequence wraps inside the first frame
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut receiver = VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size: client_stream_config().packet_size,
|
||||||
|
cipher: negotiated.encryption.contains(EncryptionFlags::VIDEO).then(|| VideoCipher::new(keys.rikey)),
|
||||||
|
frame_timeout: Duration::from_millis(60),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
// A large IDR (two FEC blocks), sizes at and around one shard, then varied P-frames; frame 12 loses a burst.
|
||||||
|
let mut sizes = vec![400_000, 6, 1_000, 1_001, 2_016, 3_000, 25_000, 60_000, 12_345, 1_500, 90_000];
|
||||||
|
sizes.extend((0..14).map(|_| 500 + rng.below(40_000)));
|
||||||
|
const BURST: u32 = 12;
|
||||||
|
let mut sent: Vec<(u32, FrameType, Vec<u8>)> = Vec::new();
|
||||||
|
let mut video = Vec::new();
|
||||||
|
let (mut rebuilt, mut duplicates) = (0, 0);
|
||||||
|
for (i, &len) in sizes.iter().enumerate() {
|
||||||
|
let index = i as u32;
|
||||||
|
let frame_type = if index == 0 { FrameType::Key } else { FrameType::Predicted };
|
||||||
|
let bitstream = access_unit(&mut rng, len, index == 0);
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: index.wrapping_mul(1500),
|
||||||
|
processing_latency: 20,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
let mut burst = |b: &FecBlock, rng: &mut SeqRng| {
|
||||||
|
rng.subset(usize::from(b.data_shards + b.parity_shards), usize::from(b.parity_shards) + 1)
|
||||||
|
};
|
||||||
|
let mut fine = within_budget;
|
||||||
|
let loss: LossPlan<'_> = if index == BURST { &mut burst } else { &mut fine };
|
||||||
|
let (lost, dups) =
|
||||||
|
send_frame(&mut packetizer, &mut receiver, &frame, announced.min_fec_packets, loss, &mut rng, now);
|
||||||
|
if index != BURST {
|
||||||
|
rebuilt += lost;
|
||||||
|
}
|
||||||
|
duplicates += dups;
|
||||||
|
sent.push((index, frame_type, bitstream));
|
||||||
|
w.run_for(16);
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut video);
|
||||||
|
}
|
||||||
|
w.run_for(200);
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut video);
|
||||||
|
|
||||||
|
// Every frame but the burst comes out byte-identical and in order; the burst is reported lost.
|
||||||
|
let lost: Vec<(u32, u32)> = video
|
||||||
|
.iter()
|
||||||
|
.filter_map(|e| if let VideoEvent::FrameLost { first, last } = e { Some((*first, *last)) } else { None })
|
||||||
|
.collect();
|
||||||
|
assert_eq!(lost, vec![(BURST, BURST)]);
|
||||||
|
let frames: Vec<_> =
|
||||||
|
video.iter().filter_map(|e| if let VideoEvent::Frame(f) = e { Some(f) } else { None }).collect();
|
||||||
|
let expected: Vec<_> = sent.iter().filter(|(i, _, _)| *i != BURST).collect();
|
||||||
|
assert_eq!(frames.len(), expected.len());
|
||||||
|
for (got, (index, frame_type, bitstream)) in frames.iter().zip(expected) {
|
||||||
|
assert_eq!(got.frame_index, *index);
|
||||||
|
assert_eq!(got.header.frame_type, *frame_type, "frame {index}");
|
||||||
|
assert_eq!(got.header.processing_latency, 20);
|
||||||
|
assert_eq!(got.rtp_timestamp, index.wrapping_mul(1500));
|
||||||
|
assert!(got.bitstream == *bitstream, "frame {index}: the bitstream differs");
|
||||||
|
}
|
||||||
|
let stats = receiver.stats();
|
||||||
|
assert!(rebuilt > 0);
|
||||||
|
assert_eq!(stats.shards_recovered, rebuilt as u64, "FEC rebuilt every data shard lost within the budget");
|
||||||
|
assert_eq!((stats.frames, stats.frames_lost, stats.packets_dropped), (frames.len() as u64, 1, duplicates as u64));
|
||||||
|
|
||||||
|
// The client asks for recovery over control: reference invalidation (the host offered it), and an IDR request
|
||||||
|
// (empty body, as above). The host sees both, then sends a recovery frame.
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.client.send(t, &ClientMessage::InvalidateRefFrames { first: BURST, last: BURST });
|
||||||
|
w.client.send_empty(t, MessageType::IdrFrame);
|
||||||
|
assert_eq!(
|
||||||
|
host_receives(&mut w, 2),
|
||||||
|
vec![ClientControlMessage::InvalidateRefFrames { first: BURST, last: BURST }, ClientControlMessage::IdrRequest]
|
||||||
|
);
|
||||||
|
let index = sizes.len() as u32;
|
||||||
|
let bitstream = access_unit(&mut rng, 30_000, false);
|
||||||
|
let recovery = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type: FrameType::Recovery,
|
||||||
|
rtp_timestamp: index * 1500,
|
||||||
|
processing_latency: 20,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
send_frame(
|
||||||
|
&mut packetizer,
|
||||||
|
&mut receiver,
|
||||||
|
&recovery,
|
||||||
|
announced.min_fec_packets,
|
||||||
|
&mut within_budget,
|
||||||
|
&mut rng,
|
||||||
|
at(w.now_ms),
|
||||||
|
);
|
||||||
|
let mut after = Vec::new();
|
||||||
|
video_events(&mut receiver, at(w.now_ms), &mut after);
|
||||||
|
match after.as_slice() {
|
||||||
|
[VideoEvent::Frame(f)] => {
|
||||||
|
assert_eq!((f.frame_index, f.header.frame_type), (index, FrameType::Recovery));
|
||||||
|
assert!(f.bitstream == bitstream);
|
||||||
|
}
|
||||||
|
other => panic!("expected the recovery frame, got {other:?}"),
|
||||||
|
}
|
||||||
|
|
||||||
|
// Audio: Opus-sized packets sealed with the session keys; no parity, so lost packets come out as lost.
|
||||||
|
let mut audio_tx = AudioPacketizer::new(AudioPacketizerConfig {
|
||||||
|
cipher: announced.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&launched.keys)),
|
||||||
|
packet_duration_ms: announced.audio_packet_duration_ms,
|
||||||
|
parity: AudioParity::None,
|
||||||
|
first_sequence: 0,
|
||||||
|
first_timestamp_ms: 0,
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let mut audio_rx = AudioDepacketizer::new(AudioConfig {
|
||||||
|
cipher: negotiated.encryption.contains(EncryptionFlags::AUDIO).then(|| AudioCipher::new(&keys)),
|
||||||
|
packet_duration_ms: client_stream_config().audio_packet_duration_ms,
|
||||||
|
fec: AudioFec::Disabled,
|
||||||
|
loss_timeout: Duration::from_millis(20),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
let dropped = [6u16, 17, 18, 31];
|
||||||
|
let mut opus_sent = Vec::new();
|
||||||
|
let mut audio = Vec::new();
|
||||||
|
for sequence in 0..40u16 {
|
||||||
|
let len = 60 + rng.below(140);
|
||||||
|
let opus = rng.bytes(len);
|
||||||
|
let datagrams = audio_tx.packetize(&opus).unwrap();
|
||||||
|
assert_eq!(datagrams.len(), 1, "no parity packets (U16)");
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
if !dropped.contains(&sequence) {
|
||||||
|
audio_rx.push(now, &datagrams[0]).unwrap();
|
||||||
|
}
|
||||||
|
opus_sent.push(opus);
|
||||||
|
w.run_for(5);
|
||||||
|
let now = at(w.now_ms);
|
||||||
|
if audio_rx.poll_timeout().is_some_and(|t| t <= now) {
|
||||||
|
audio_rx.handle_timeout(now).unwrap();
|
||||||
|
}
|
||||||
|
audio.extend(core::iter::from_fn(|| audio_rx.poll_event()));
|
||||||
|
}
|
||||||
|
let expected_audio: Vec<AudioEvent> = (0..40u16)
|
||||||
|
.map(|sequence| {
|
||||||
|
if dropped.contains(&sequence) {
|
||||||
|
AudioEvent::Lost { sequence }
|
||||||
|
} else {
|
||||||
|
AudioEvent::Packet {
|
||||||
|
sequence,
|
||||||
|
timestamp_ms: u32::from(sequence) * 5,
|
||||||
|
opus: opus_sent[usize::from(sequence)].clone(),
|
||||||
|
recovered: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
assert_eq!(audio, expected_audio, "in order, losses reported, nothing rebuilt");
|
||||||
|
assert_eq!((audio_rx.stats().lost, audio_rx.stats().recovered), (dropped.len() as u64, 0));
|
||||||
|
|
||||||
|
// Input: every kind the client sends arrives typed on the host, in order.
|
||||||
|
let inputs = vec![
|
||||||
|
InputEvent::MouseMoveRel { dx: -12, dy: 7 },
|
||||||
|
InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 },
|
||||||
|
InputEvent::MouseButton { pressed: true, button: MouseButton::Left },
|
||||||
|
InputEvent::MouseButton { pressed: false, button: MouseButton::Left },
|
||||||
|
InputEvent::Key { pressed: true, flags: 0, key_code: 0x41, modifiers: 0 },
|
||||||
|
InputEvent::Key { pressed: false, flags: 0, key_code: 0x41, modifiers: 0 },
|
||||||
|
InputEvent::Scroll { amount: -120 },
|
||||||
|
InputEvent::Gamepad(GamepadState {
|
||||||
|
controller: 0,
|
||||||
|
active_mask: 1,
|
||||||
|
buttons: ButtonFlags(ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::PADDLE1),
|
||||||
|
left_trigger: 0x40,
|
||||||
|
right_trigger: 0xFF,
|
||||||
|
left_stick_x: -32768,
|
||||||
|
left_stick_y: 32767,
|
||||||
|
right_stick_x: 1200,
|
||||||
|
right_stick_y: -104,
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
for e in &inputs {
|
||||||
|
w.client.send(t, &ClientMessage::Input(e.clone()));
|
||||||
|
}
|
||||||
|
let typed: Vec<ClientControlMessage> = inputs.iter().cloned().map(ClientControlMessage::Input).collect();
|
||||||
|
assert_eq!(host_receives(&mut w, inputs.len()), typed);
|
||||||
|
|
||||||
|
// Rumble from the host reaches the client.
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.host.h().send_rumble(t, 0, 0x4000, 0xC000).unwrap();
|
||||||
|
w.host.h().send_rumble_triggers(t, 0, 0x1000, 0x2000).unwrap();
|
||||||
|
assert!(w.run_until(w.now_ms + 10_000, |w| w.client.host_messages.len() >= 2));
|
||||||
|
assert_eq!(
|
||||||
|
w.client.host_messages,
|
||||||
|
vec![
|
||||||
|
HostMessage::Rumble { controller: 0, low_frequency: 0x4000, high_frequency: 0xC000 },
|
||||||
|
HostMessage::RumbleTriggers { controller: 0, left: 0x1000, right: 0x2000 },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
|
||||||
|
// Nothing on control was dropped, timed out or stopped for want of pings.
|
||||||
|
assert!(
|
||||||
|
!w.host.events.iter().any(|e| matches!(
|
||||||
|
e,
|
||||||
|
ControlHostEvent::Dropped | ControlHostEvent::TimedOut | ControlHostEvent::PingTimedOut
|
||||||
|
))
|
||||||
|
);
|
||||||
|
|
||||||
|
// Graceful termination, then the ENet disconnect; both ends close. (Should the client's one acknowledgement of
|
||||||
|
// the disconnect be lost, the host gives up after its timeout, as stock ENet does.)
|
||||||
|
let t = at(w.now_ms);
|
||||||
|
w.host.h().send_termination(t, TERMINATION_GRACEFUL).unwrap();
|
||||||
|
w.host.h().close(t).unwrap();
|
||||||
|
assert!(w.run_until(w.now_ms + 30_000, |w| w.client.enet.state() == EnetState::Disconnected
|
||||||
|
&& w.host.host.as_ref().is_some_and(|h| h.enet().state() == EnetHostState::Disconnected)));
|
||||||
|
assert_eq!(w.client.host_messages.last(), Some(&HostMessage::Termination { error_code: Some(0x8003_0023) }));
|
||||||
|
assert_eq!(w.client.enet_events, vec![EnetEvent::Connected, EnetEvent::Disconnected { data: 0 }]);
|
||||||
|
|
||||||
|
// The client quits the game; the host is free again.
|
||||||
|
parse_status_response(&get(&mut host, &cancel_request(UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert_eq!((info.paired, info.current_game, info.state.as_str()), (true, 0, "LUMEN_SERVER_FREE"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_tessera_trusted_client_needs_no_pairing() {
|
||||||
|
let mut rng = SeqRng::new(0x7E55);
|
||||||
|
let client = client_identity("client");
|
||||||
|
let mut host = LumenHttp::new(2);
|
||||||
|
// The grant: the host records the client's certificate, the client gets the host's out of band. No PIN anywhere.
|
||||||
|
host.paired.push(PairedClient::trusted(client.cert_der()).unwrap());
|
||||||
|
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
|
||||||
|
let pin = Some(&host_cert);
|
||||||
|
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &client, pin)).unwrap();
|
||||||
|
assert!(info.paired);
|
||||||
|
assert_eq!(parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &client, pin)).unwrap(), host.apps);
|
||||||
|
let keys = SessionKeys::generate(&mut rng).unwrap();
|
||||||
|
let params = LaunchParams {
|
||||||
|
app_id: 1,
|
||||||
|
width: 1280,
|
||||||
|
height: 720,
|
||||||
|
fps: 30,
|
||||||
|
keys: keys.clone(),
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
};
|
||||||
|
assert!(
|
||||||
|
parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &client, pin))
|
||||||
|
.unwrap()
|
||||||
|
.game_session
|
||||||
|
);
|
||||||
|
assert_eq!(host.launched.map(|l| l.keys), Some(keys));
|
||||||
|
assert!(host.pairing.is_none(), "no /pair call was made");
|
||||||
|
|
||||||
|
// The pin is what makes it safe: a host presenting another certificate is not the paired one.
|
||||||
|
let rogue_host = ServerCert::from_der(client_identity("rogue").cert_der()).unwrap();
|
||||||
|
assert_eq!(rogue_host.matches(host.identity.cert_der()), Ok(false));
|
||||||
|
assert_eq!(host_cert.matches(client_identity("rogue").cert_der()), Ok(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn an_unpaired_client_is_refused_over_https() {
|
||||||
|
let mut host = LumenHttp::new(3);
|
||||||
|
let paired_client = client_identity("client");
|
||||||
|
host.paired.push(PairedClient::trusted(paired_client.cert_der()).unwrap());
|
||||||
|
let stranger = client_identity("rogue");
|
||||||
|
let host_cert = ServerCert::from_der(host.identity.cert_der()).unwrap();
|
||||||
|
let pin = Some(&host_cert);
|
||||||
|
|
||||||
|
// serverinfo answers, but says "not paired"; everything else is refused.
|
||||||
|
let info =
|
||||||
|
parse_server_info(&get(&mut host, &server_info_request(Scheme::Https, UID).unwrap(), &stranger, pin)).unwrap();
|
||||||
|
assert!(!info.paired);
|
||||||
|
assert_err!(
|
||||||
|
parse_app_list(&get(&mut host, &app_list_request(UID).unwrap(), &stranger, pin)),
|
||||||
|
Error::HostStatus { code: 401 }
|
||||||
|
);
|
||||||
|
let keys = SessionKeys::generate(&mut SeqRng::new(4)).unwrap();
|
||||||
|
let params =
|
||||||
|
LaunchParams { app_id: 1, width: 1280, height: 720, fps: 30, keys, hdr: false, audio: AudioLayout::Stereo };
|
||||||
|
assert_err!(
|
||||||
|
parse_launch_response(&get(&mut host, &launch_request(¶ms, UID).unwrap(), &stranger, pin)),
|
||||||
|
Error::HostStatus { code: 401 }
|
||||||
|
);
|
||||||
|
assert!(host.launched.is_none());
|
||||||
|
// Plain HTTP never reaches the HTTPS routes either.
|
||||||
|
let over_http = HttpRequest { scheme: Scheme::Http, ..app_list_request(UID).unwrap() };
|
||||||
|
assert_err!(parse_app_list(&get(&mut host, &over_http, &paired_client, None)), Error::HostStatus { code: 401 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
//! 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));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -51,6 +51,8 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
|
|||||||
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
||||||
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
||||||
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
||||||
|
| `src/rtsp.rs` (read again as S-30) | `encoderCscMode` bit layout (comment cites Sunshine's colour-space function); `maxNumReferenceFrames` 0 = "host's choice" (comment cites moonlight-common-c); the 5.1/7.1 mapping rotation (comment cites GFE and Moonlight) | Not taken: the host parser keeps both numbers raw and writes the mappings as configured (PROTOCOL.md 2.5, U6, U26) |
|
||||||
|
| `src/session/stream/video/mod.rs` (S-31) | how the stored bitrate is reduced for FEC and audio (comment: "as Sunshine computes it") | Not taken; the parser hands over the client's bitrate unchanged |
|
||||||
|
|
||||||
## How code gets written
|
## How code gets written
|
||||||
|
|
||||||
@@ -91,3 +93,7 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
|
|||||||
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
|
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
|
||||||
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
|
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
|
||||||
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
|
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
|
||||||
|
| 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. |
|
||||||
|
|||||||
@@ -1,5 +1,50 @@
|
|||||||
# DomiStream — handover
|
# DomiStream — handover
|
||||||
|
|
||||||
|
## stream-v0.2.0 (2026-12-04)
|
||||||
|
|
||||||
|
The GameStream host side, sans-I/O, for Lumen (milestone L1, `docs/LUMEN-HOST-PLAN.md` 3.1), next to the client of
|
||||||
|
v0.1.0. The host notes per protocol are listed at the top of `docs/PROTOCOL.md` ("Host side (Lumen)").
|
||||||
|
|
||||||
|
| Part | Module |
|
||||||
|
| :-- | :-- |
|
||||||
|
| request head and query parsing into typed routes, XML answers (serverinfo, applist, launch/resume, pair, errors) | `host::http` |
|
||||||
|
| the host's pairing machine (pending-PIN slot, proof and signature checks), Tessera-trusted clients without a PIN | `host::pairing` |
|
||||||
|
| RTSP session (order, `Session`, statuses), DESCRIBE writer, strict ANNOUNCE parser | `rtsp::server` |
|
||||||
|
| accepting ENet peer, as stock ENet 1.3 accepts | `enet::host` |
|
||||||
|
| control host: client frames (replay refusal), rumble, termination, stop deadline | `control::host` |
|
||||||
|
| video packetizer (FEC blocks with Cauchy parity, AES-GCM sealing), Opus audio packetizer (AES-CBC, no parity: U16) | `video::packetizer`, `audio::packetizer` |
|
||||||
|
|
||||||
|
Fixed on the client side (tests first, separate commits):
|
||||||
|
- **ENet session ids.** `EnetClient` took VERIFY_CONNECT's session ids the wrong way round (stock ENet: the client's
|
||||||
|
incoming id is the verify's incoming id). Hidden against a fresh slot (0/0); after a reconnect a stock host answers
|
||||||
|
with two different ids and the client would have dropped every host datagram. Found by the ENet host engineer.
|
||||||
|
- **Applist cap.** `MAX_APPS` was 4096, but 4096 apps of four elements need 16,385 XML elements (cap 16,384), so the
|
||||||
|
app cap could never be reached. Now 4095 = (`MAX_XML_ELEMENTS` − 1) / 4 on both sides.
|
||||||
|
|
||||||
|
Evidence (worktree checks, 2026-12-04, every cargo run gated on CPU and RAM below 90 % and drives below 95 %):
|
||||||
|
- `cargo test --workspace`: **422 passed, 0 failed**, among them `tests/session.rs`: a whole session between our
|
||||||
|
client and our host in memory (pairing with the owner typing the code, HTTPS, launch, RTSP, ENet + START_B, sealed
|
||||||
|
video with FEC repairing exactly the parity budget per block and a burst beyond it reported lost and answered with
|
||||||
|
invalidation and an IDR request, sealed audio, input, gamepad, rumble, termination), plus the Tessera-trusted path
|
||||||
|
and an unpaired client refused over HTTPS.
|
||||||
|
- Mutation pass on the host modules: **26 of 27 caught, 1 equivalent** (M25–M51, `docs/MUTATION.md`; M36 first survived and got a test; M39 is unreachable for a fresh peer slot); the client rows M1–M24 are those
|
||||||
|
of v0.1.0.
|
||||||
|
- Fuzz, host targets (module engineers; Windows MSVC, SanitizerCoverage, libFuzzer), **0 crashes**: host_http_request
|
||||||
|
8,784,228 runs in 75 s; host_pairing 45,096 in 75 s, then 778,128 in 601 s (lead, 2026-12-04); rtsp_server 895,897 in 121 s; announce 11,659,642 in 121 s;
|
||||||
|
enet_host 2,534,001 in 60 s, then 26,839,291 in 600 s; control_host 611,513 in 60 s; video_packetizer_roundtrip
|
||||||
|
113,740 in 76 s. 32 targets in all; the 25 client targets' runs are those of v0.1.0.
|
||||||
|
- clippy `-D warnings`, fmt and rustdoc `-D warnings` are clean.
|
||||||
|
|
||||||
|
Open:
|
||||||
|
- **Interop with real clients: pairing, serverinfo and applist measured.** Arena Domi Remote 0.1.2 in the Android
|
||||||
|
emulator paired with Arena's lumen-host L1 skeleton (this release's host side) over loopback and listed all games
|
||||||
|
(PROTOCOL.md, "Measured" [L1]). Streaming against a real client starts in L2. The Moonlight PC app is not
|
||||||
|
measured yet.
|
||||||
|
- **START_B, PERIODIC_PING, IDR request from our own client.** `ControlStream` refuses them (bodies U10); decided:
|
||||||
|
it sends them with empty bodies, with the first streaming client of L2. The session test sends them over
|
||||||
|
`EnetClient` + `ControlCipher`, as gs-probe does.
|
||||||
|
- Audio parity (U16), `HDR_MODE` and the plain `TERMINATION` are refused on the host until measured.
|
||||||
|
|
||||||
## stream-v0.1.0 (2026-11-26)
|
## stream-v0.1.0 (2026-11-26)
|
||||||
|
|
||||||
The GameStream client, sans-I/O, for Arena Domi TV (Play remotely Day 1).
|
The GameStream client, sans-I/O, for Arena Domi TV (Play remotely Day 1).
|
||||||
|
|||||||
@@ -44,3 +44,50 @@ caught; none failed to compile, so every row is a real behaviour change the test
|
|||||||
- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since
|
- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since
|
||||||
27b26a9 the dependency tree has no getrandom at all.
|
27b26a9 the dependency tree has no getrandom at all.
|
||||||
- **Missing tests.** No mutation got through, so none were added.
|
- **Missing tests.** No mutation got through, so none were added.
|
||||||
|
|
||||||
|
## Host side (stream-v0.2.0)
|
||||||
|
|
||||||
|
27 rows for the host modules: **26 caught, 1 equivalent** (M39). M36 first survived and now has a test.
|
||||||
|
|
||||||
|
- **When:** 2026-12-04, on `feature/host-session` (the session engineer wrote M25-M51; the lead finished the run,
|
||||||
|
added the M36 test and re-ran M36). Rows may name several test binaries; the tool now runs with `--no-fail-fast`.
|
||||||
|
- **Driver:** as above, `python tools/mutation/mutate.py M25 ... M51`, output on E: through the resource gate.
|
||||||
|
|
||||||
|
| # | Area | Mutation | Test binary | Caught by | Result |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| M25 | host pairing phase | phase 4 accepted while phase 3 is expected (a skipped step) | host_pairing, session | `out_of_order_phases_are_refused` | caught |
|
||||||
|
| M26 | host pairing proof | the client's proof H_c is not compared (any PIN pairs) | host_pairing | `the_right_pin_but_a_forged_proof_is_a_wrong_pin`, `wrong_pin_is_caught_by_the_host_when_the_client_carries_on` | caught |
|
||||||
|
| M27 | host pairing phase 5 | phase 5 accepts any HTTPS client certificate | host_pairing | `phase_5_needs_https_with_the_phase_1_certificate` | caught |
|
||||||
|
| M28 | host HTTP cap | query parameter cap off by one (allows 33) | host_http | `query_caps` | caught |
|
||||||
|
| M29 | host HTTP body | a GET with Content-Length other than 0 accepted | host_http | `heads_that_are_refused` | caught |
|
||||||
|
| M30 | host HTTP answer | PairStatus 1 over plain HTTP too | host_http, session | `serverinfo_pair_status_per_scheme` | caught |
|
||||||
|
| M31 | RTSP order | PLAY accepted before ANNOUNCE | rtsp_server | `order_violations_get_455_and_change_nothing`, `server_random_sequences` | caught |
|
||||||
|
| M32 | RTSP order | a second SETUP of the same stream accepted | rtsp_server | `options_at_any_time_and_setup_once_each` | caught |
|
||||||
|
| M33 | RTSP session | a Session header with another id accepted once issued | rtsp_server | `session_id_is_random_hex_and_checked` | caught |
|
||||||
|
| M34 | ANNOUNCE | a known attribute given twice accepted (the first value kept) | rtsp_server | `announce_duplicates_and_unknowns`, `announce_hostile_lines` | caught |
|
||||||
|
| M35 | DESCRIBE | the refPicInvalidation line written exactly when not offered | rtsp_server, session | `client_and_server_negotiate_in_memory`, `describe_follows_the_offer`, `describe_lines_and_order`, `a_whole_session_between_our_client_and_our_host` | caught |
|
||||||
|
| M36 | ENet host ack | pings acknowledged before the verify is acknowledged | enet_host | `ping_before_the_verify_ack_is_not_acknowledged` | caught |
|
||||||
|
| M37 | ENet host ack | a datagram without sent time goes on after an acknowledged command | enet_host | `acknowledged_commands_need_the_sent_time` | caught |
|
||||||
|
| M38 | ENet host session id | host session ids taken from the wrong offered field | enet_host | `session_ids_follow_stock_enet` | caught |
|
||||||
|
| M39 | ENet host session id | the slot's previous session id not skipped | enet_host | none (see notes) | **equivalent** |
|
||||||
|
| M40 | ENet client session id | verify's session ids swapped again (the bug fixed for v0.2.0) | enet | `verify_session_ids_are_taken_as_stock_enet_takes_them` | caught |
|
||||||
|
| M41 | control host replay | a repeated client sequence number accepted (< instead of <=) | control_host | `replays_and_forgeries_are_dropped` | caught |
|
||||||
|
| M42 | control host replay | the client replay check removed | control_host | `client_sequence_at_u32_wrap`, `replays_and_forgeries_are_dropped` | caught |
|
||||||
|
| M43 | control host message | extended termination code written little-endian | control_host, session | `close_from_either_side`, `host_message_layouts`, `host_messages_reach_the_client`, `a_whole_session_between_our_client_and_our_host` | caught |
|
||||||
|
| M44 | control host stop | a PERIODIC_PING does not move the stop deadline | control_host, session | `no_periodic_ping_ends_the_session`, `stop_deadline_rules`, `a_whole_session_between_our_client_and_our_host` | caught |
|
||||||
|
| M45 | video parity order | parity computed after the parity headers are written (headers become parity) | video_packetizer, session | `a_whole_session_between_our_client_and_our_host`, `every_data_shard_lost_is_rebuilt_when_parity_covers_it`, `fixed_vector_cauchy_parity_k3_m1`, `fixed_vector_one_small_frame` and 9 more | caught |
|
||||||
|
| M46 | video parity | the client's minimum parity count ignored | video_packetizer | `fec_plan_properties`, `minimum_parity_raises_the_written_percentage` | caught |
|
||||||
|
| M47 | video parity | parity shard index written one too high | video_packetizer | `every_data_shard_lost_is_rebuilt_when_parity_covers_it`, `fixed_vector_cauchy_parity_k3_m1`, `fixed_vector_one_small_frame`, `encrypted_stream_round_trips_with_loss` and 8 more | caught |
|
||||||
|
| M48 | video nonce | the GCM nonce counter does not advance per datagram (nonce reuse) | video_packetizer | `encrypted_stream_round_trips_with_loss` | caught |
|
||||||
|
| M49 | audio IV | the host encrypts with the IV of the next sequence number | audio_packetizer, session | `audio_cipher_encrypt_matches_openssl_vectors`, `fixed_vector_encrypted`, `lost_packets_are_reported_and_the_rest_arrive`, `round_trip_encrypted_across_sequence_and_timestamp_wrap` and 3 more | caught |
|
||||||
|
| M50 | audio IV | IV counter written little-endian (both sides) | media, audio_packetizer | `audio_cipher_encrypt_matches_openssl_vectors`, `fixed_vector_encrypted`, `audio_iv_and_decrypt_match_openssl_vectors`, `audio_round_trip_through_the_oracle` | caught |
|
||||||
|
| M51 | audio block start | a first sequence number that is not a block start accepted | audio_packetizer | `config_refusals` | caught |
|
||||||
|
|
||||||
|
### Notes on the host rows
|
||||||
|
- **M36.** A ping that the client asks to have acknowledged, sent before it acknowledged the verify, was answered
|
||||||
|
with an ACK in the mutant and no test noticed. `ping_before_the_verify_ack_is_not_acknowledged` (enet_host) now
|
||||||
|
catches it.
|
||||||
|
- **M39, equivalent.** `next_session` skips "the value the slot used last", as stock ENet does when a slot is
|
||||||
|
reused. An `EnetHostPeer` is always a fresh slot, so it is called with `current` = 0xFF while the result is in
|
||||||
|
0..3: the branch can never run and removing it changes nothing. It is kept so the function matches stock ENet if
|
||||||
|
a peer slot is ever reused.
|
||||||
|
|||||||
+175
-1
@@ -1,10 +1,60 @@
|
|||||||
# GameStream protocol, as DomiStream speaks it (client side)
|
# GameStream protocol, as DomiStream speaks it (client and host side)
|
||||||
|
|
||||||
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
||||||
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
||||||
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
|
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
|
||||||
is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
|
is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
|
||||||
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
|
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
|
||||||
|
2026-12-04: the host side for Lumen added as stream-v0.2.0 (below).
|
||||||
|
|
||||||
|
## Host side (Lumen)
|
||||||
|
|
||||||
|
Since stream-v0.2.0 DomiStream also holds the host's half of every protocol, for Lumen, Arena Domi's own streaming
|
||||||
|
host ([LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md) 3.1). The wire is the one this document describes; what is a choice of
|
||||||
|
ours on the host side is marked as such in the host notes:
|
||||||
|
|
||||||
|
| Section | Host module | Host notes |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| 1.1-1.4 HTTP/HTTPS | `host::http` | strict request head and query parsing into typed routes; XML answers that the client's parsers accept; `PairStatus` 1 only over HTTPS with a paired certificate (1.2). Notes in the module docs |
|
||||||
|
| 1.5 Pairing | `host::pairing` | the mirror state machine with a pending-PIN slot; Tessera-trusted clients recorded without a PIN. Notes in the module docs |
|
||||||
|
| 2.2-2.4 RTSP | `rtsp::server` | 2.5: one session per launch, order, statuses, `Session`, DESCRIBE writer, strict ANNOUNCE parser |
|
||||||
|
| 3.1 ENet | `enet::host` | 3.1, "The accepting side, as stock ENet 1.3 does it" |
|
||||||
|
| 3.2-3.3 Control | `control::host` | 3.3, last paragraph: client frames, host messages, stop deadline |
|
||||||
|
| 5.2-5.3 Video | `video::packetizer` | 5.3, "Host side": FEC block split and parity |
|
||||||
|
| 6.2-6.4 Audio | `audio::packetizer` | 6.4, last paragraph: no parity until U16 |
|
||||||
|
|
||||||
|
Both halves are tested against each other in one in-memory session (`crates/domistream/tests/session.rs`). Found
|
||||||
|
there, still open: the client's `ControlStream` refuses to send `START_B`, `PERIODIC_PING` and the IDR request
|
||||||
|
(bodies U10, 3.3). With `ControlStream` alone our client cannot start a stream on our host, and a host with a stop
|
||||||
|
deadline (60 s by default) would end the session; the session test sends the three with empty bodies over
|
||||||
|
`EnetClient` and `ControlCipher`, as `tools/gs-probe` does. The host keeps the client's `updateState` (1.5, U1) for the
|
||||||
|
logs without reading it. **Decided (lead, 2026-12-04):** `ControlStream` will send the three with empty bodies,
|
||||||
|
what Moonshine and Lumen read; it lands with the first streaming client of L2, and U10 stays open for Sunshine.
|
||||||
|
|
||||||
|
### Measured: Arena Domi Remote against lumen-host [L1]
|
||||||
|
|
||||||
|
Our own black-box measurement (decision D2), 2026-12-04: Arena Domi Remote 0.1.2 (a GameStream client; its code is
|
||||||
|
never read) in the Android emulator on the reference PC, against Arena's lumen-host L1 skeleton (DomiStream
|
||||||
|
`337f6a7`) on loopback, HTTP 48989 / HTTPS 48984, reached as `10.0.2.2:48989`. Facts from lumen-host's request log
|
||||||
|
and the operator's notes:
|
||||||
|
- The client accepts a host entered as `address:port` and uses that port for HTTP; it then reached HTTPS on the port
|
||||||
|
serverinfo gave (`HttpsPort`). While unpaired it polls `/serverinfo` over HTTP every 0.5 to 2.5 s.
|
||||||
|
- Every request carries `uniqueid=0123456789ABCDEF` (the same on every request) and a parameter `uuid` with a fresh
|
||||||
|
random UUID per request (not in sections 1.1-1.5; the host ignores it).
|
||||||
|
- **Pairing (U1, for this client):** five requests in the order of 1.5, phase 4 (`clientpairingsecret`) before
|
||||||
|
phase 5; phases 1-4 over HTTP, phase 5 (`phrase=pairchallenge`) over HTTPS with the client certificate. Every
|
||||||
|
phase also carries `devicename` and `updateState=1`. With the code typed on the host the client showed the PC as
|
||||||
|
paired about 12 s after the code was entered. DomiStream's host pairing (1.5) and lumen-host's TLS (TLS 1.3 offered,
|
||||||
|
ALPN `h2` and `http/1.1`, a self-signed client certificate) were accepted without change.
|
||||||
|
- After pairing: `/serverinfo` and `/applist` over HTTPS; the client showed all 11 games of the applist.
|
||||||
|
- **Box art:** `/appasset?appid=<id>&AssetType=2&AssetIdx=0` over HTTPS for each app, retried about every 2 s while
|
||||||
|
it fails (lumen-host L1 answered 404; the client showed no covers).
|
||||||
|
- **Launch (U4, for this client):** `/launch` over HTTPS with `appid`, `mode` (`1280x720x60`), `additionalStates=1`,
|
||||||
|
`sops=1`, `rikey`, `rikeyid`, `localAudioPlayMode=0`, `surroundAudioInfo=196610`, `remoteControllersBitmap=0`,
|
||||||
|
`gcmap=0`, `gcpersist=0`, `corever=1`, plus `uniqueid` and `uuid`. An answer with HTTP status 503 is shown as
|
||||||
|
"Failed to start <game> (error 503)".
|
||||||
|
|
||||||
|
The other clients (the Moonlight PC app, Arena Domi TV) are measured when they connect.
|
||||||
|
|
||||||
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
||||||
|
|
||||||
@@ -13,6 +63,7 @@ approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows
|
|||||||
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
|
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
|
||||||
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
|
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
|
||||||
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
|
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
|
||||||
|
| [L1] | our own black-box measurement of Arena Domi Remote 0.1.2 against lumen-host, 2026-12-04 ("Measured" above) |
|
||||||
| [T] | tokio-enet `364628e` (S-10), approved 2026-11-25 |
|
| [T] | tokio-enet `364628e` (S-10), approved 2026-11-25 |
|
||||||
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 |
|
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 |
|
||||||
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
|
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
|
||||||
@@ -221,6 +272,76 @@ SDP attribute lines `a=<name>:<value>`. Names the host reads [M]; values and the
|
|||||||
|
|
||||||
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
|
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
|
||||||
|
|
||||||
|
### 2.5 Host side (Lumen): `rtsp::server`
|
||||||
|
|
||||||
|
Facts from Moonshine's host code (`src/rtsp.rs`, `src/session/stream/video/mod.rs` at `f184d5e`, S-30, S-31) and
|
||||||
|
RFC 2326 (S-32); our own choices are marked as such.
|
||||||
|
|
||||||
|
**Connections and framing.** Moonshine reads one request per TCP connection and notes that Moonlight opens a
|
||||||
|
connection per request [M]. So the host's state belongs to the launched session, not to a connection: every
|
||||||
|
connection of that session feeds the same `RtspServer` (UNKNOWN U5 for other clients). A request without
|
||||||
|
`Content-Length` has no payload (RFC 2326 4.4); the host's framer (`RtspFramer::for_requests`) ends it at the empty
|
||||||
|
line. Every answer carries `Content-Length` (ours), so the client never waits for a close. Moonshine needs a parseable
|
||||||
|
`CSeq` and closes without an answer when it is missing [M]; we answer 400 and let the caller close.
|
||||||
|
|
||||||
|
**Order and statuses.** Moonshine checks no order and no `Session` [M]. We enforce 2.2: OPTIONS, DESCRIBE, the three
|
||||||
|
SETUPs (any order, each once: ours, U5), ANNOUNCE, PLAY. OPTIONS may come at any time and changes nothing else
|
||||||
|
(RFC 2326 10.1). Moonshine answers only 200, 400 and 500 [M]; we use the RFC 2326 7.1.1 codes: 400 malformed request
|
||||||
|
or ANNOUNCE payload, 451 a request the offer does not cover (codec, encryption bits, HDR, 4:4:4), 454 a `Session`
|
||||||
|
that is not this session's, 455 a method out of order, 501 an unknown method (TEARDOWN, GET_PARAMETER...). A refused
|
||||||
|
request changes no state; the caller decides whether to close.
|
||||||
|
|
||||||
|
**Session.** Moonshine sends the fixed id `MoonshineSession` and never reads it back [M]. We send a random id
|
||||||
|
(8 bytes from the caller's `RandomSource`, hex; RFC 2326 3.4 asks for at least 8 random octets) as
|
||||||
|
`Session: <id>;timeout = 90` [M]. A `Session` header that is present must carry that id (454 otherwise, and before
|
||||||
|
the first SETUP any id is wrong); a missing one is accepted unless the host config requires it (U5).
|
||||||
|
|
||||||
|
**Answers** [M]: OPTIONS `Public` (we list `OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY`; Moonshine leaves ANNOUNCE
|
||||||
|
out); DESCRIBE the SDP below; SETUP needs a `Transport` header (400 without), takes the stream from the first
|
||||||
|
`streamid=<audio|video|control>` of the target (400 otherwise) and answers `Session` and
|
||||||
|
`Transport: server_port=<port>`; ANNOUNCE and PLAY answer with no payload.
|
||||||
|
|
||||||
|
**DESCRIBE lines, in Moonshine's order** [M]: `a=x-ss-general.featureFlags:3`, `a=x-ss-general.encryptionSupported:`
|
||||||
|
5 or 7 (7 when video encryption is on), `sprop-parameter-sets=AAAAAU`, `a=x-nv-video[0].refPicInvalidation:1`,
|
||||||
|
`a=rtpmap:98 AV1/90000`, `a=fmtp:96 packetization-mode=1`, then one `a=fmtp:97 surround-params=` per Opus
|
||||||
|
configuration. Moonshine writes all of them unconditionally; our writer leaves out the invalidation, AV1 and H.264
|
||||||
|
lines when the host does not offer them. HEVC, HDR and 4:4:4 have no DESCRIBE line (serverinfo, 1.2, U25). Moonshine
|
||||||
|
rotates the 5.1/7.1 normal-quality mappings with a comment that cites GFE and Moonlight [M*]: not used, U26.
|
||||||
|
|
||||||
|
**ANNOUNCE as Moonshine reads it.** Missing or unparseable required attributes give 400 [M]; optional ones fall back
|
||||||
|
to their default [M]. Our parser keeps the required set and the defaults, refuses out-of-range values instead of
|
||||||
|
clamping, refuses a known attribute given twice, and counts unknown attributes.
|
||||||
|
|
||||||
|
| Attribute | Required? | Default | Accepted (ours unless tagged) | Meaning |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| `x-nv-video[0].clientViewportWd`, `…Ht` | yes [M] | | 1..=16384 | resolution |
|
||||||
|
| `x-nv-video[0].maxFPS` | yes [M] | | 1..=1000 (0 refused [M]) | frame rate |
|
||||||
|
| `x-nv-video[0].packetSize` | yes [M] | | 200..=65471 [M] (Moonshine clamps above its own cap; we refuse) | video packet size |
|
||||||
|
| `x-ml-video.configuredBitrateKbps` | yes [M] | | 1..=4294967 (×1000 must fit a u32 [M]) | bitrate |
|
||||||
|
| `x-nv-vqos[0].bitStreamFormat` | yes [M] | | 0 H.264, 1 HEVC, 2 AV1 [M]; others refused [M] | codec |
|
||||||
|
| `x-nv-vqos[0].fec.minRequiredFecPackets` | yes [M] | | 0..=255 | minimum parity per block |
|
||||||
|
| `x-nv-vqos[0].qosTrafficType`, `x-nv-aqos.qosTrafficType` | yes [M] | | any u32, kept raw (Moonshine: QoS off for `0` [M]) | DSCP class |
|
||||||
|
| `x-nv-aqos.packetDuration` | yes [M] | | 1..=120 ms (longest Opus packet, RFC 6716) | audio packet duration |
|
||||||
|
| `x-nv-video[0].maxNumReferenceFrames` | no | 1 [M] | any u32, raw (what 0 means is [M*]) | reference frames |
|
||||||
|
| `x-nv-video[0].refPicInvalidation` | no (Moonshine does not read it) | 0: UNKNOWN U6 | 0, 1 | client can invalidate |
|
||||||
|
| `x-nv-video[0].dynamicRangeMode` | no | 0 [M] | any u32, raw; Moonshine: 0 SDR, 1 HDR [M]; a non-zero value needs the host's HDR offer (ours) | U6 |
|
||||||
|
| `x-nv-video[0].encoderCscMode` | no | 0 [M] | any u32, raw; the bit layout is [M*] (Moonshine cites Sunshine) | U6 |
|
||||||
|
| `x-ss-video[0].chromaSamplingType` | no | 0 [M] | 0 4:2:0, 1 4:4:4 [M] | chroma |
|
||||||
|
| `x-ss-general.encryptionEnabled` | no | 0 [M] | 0..=255, only offered bits (ours) | 2.3 bits |
|
||||||
|
| `x-nv-audio.surround.enable` | no | 0 [M] | 0, 1 | when 0, the layout comes from launch's `surroundAudioInfo` [M] |
|
||||||
|
| `x-nv-audio.surround.numChannels` | no | 2 [M] | 1..=8 | channels |
|
||||||
|
| `x-nv-audio.surround.channelMask` | no | 0x3 [M] | any u32, raw | speaker mask |
|
||||||
|
| `x-nv-audio.surround.AudioQuality` | no | 1 [M] | 0, 1 | high quality |
|
||||||
|
|
||||||
|
`bitStreamFormat` 0/1/2 [M] confirms the values our client sends (`rtsp::sdp`, previously a judgment). Payload caps
|
||||||
|
(ours): 32 KiB, 1024 non-empty lines, 1024 bytes per line, 512 `a=` attributes; blanks around values are trimmed.
|
||||||
|
|
||||||
|
UNKNOWNs left for black-box measurement (Arena Domi Remote and the Moonlight PC app as Lumen's clients, decision D2):
|
||||||
|
U5 (connection per request, the SETUP target form, whether clients echo `Session`, whether every client starts with
|
||||||
|
OPTIONS), U6 (whether real clients always send the ten required attributes, `refPicInvalidation`'s default, the
|
||||||
|
meanings of `dynamicRangeMode` and `encoderCscMode` per client setting, whether `qosTrafficType` is always a number,
|
||||||
|
how many attributes a real ANNOUNCE has), U26 (mapping rotation).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Control channel (ENet + AES-GCM)
|
## 3. Control channel (ENet + AES-GCM)
|
||||||
@@ -270,6 +391,38 @@ 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
|
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.
|
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
|
### 3.2 Encrypted frame
|
||||||
|
|
||||||
Every control message is wrapped [W4] (little-endian):
|
Every control message is wrapped [W4] (little-endian):
|
||||||
@@ -322,6 +475,17 @@ 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
|
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).
|
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
|
## 4. Input and gamepad packets
|
||||||
@@ -468,6 +632,12 @@ 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]]`.
|
`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
|
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.
|
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).
|
- The audio code is **not** this matrix (section 6.4).
|
||||||
|
|
||||||
### 5.4 Feedback
|
### 5.4 Feedback
|
||||||
@@ -526,6 +696,10 @@ 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
|
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.
|
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
|
### 6.5 Decoding
|
||||||
|
|
||||||
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
||||||
|
|||||||
Generated
+1
-1
@@ -236,7 +236,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "domistream"
|
name = "domistream"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
|
|||||||
@@ -211,3 +211,52 @@ path = "fuzz_targets/rtsp_client.rs"
|
|||||||
test = false
|
test = false
|
||||||
doc = false
|
doc = false
|
||||||
bench = false
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "video_packetizer_roundtrip"
|
||||||
|
path = "fuzz_targets/video_packetizer_roundtrip.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "host_http_request"
|
||||||
|
path = "fuzz_targets/host_http_request.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"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "announce"
|
||||||
|
path = "fuzz_targets/announce.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "control_host"
|
||||||
|
path = "fuzz_targets/control_host.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "host_pairing"
|
||||||
|
path = "fuzz_targets/host_pairing.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//! Fuzzes the host's ANNOUNCE parser (hostile client SDP).
|
||||||
|
//! Asserts invariants, not only "no panic": an accepted payload is within every range and cap, and writing it back
|
||||||
|
//! gives the same config.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::server::{
|
||||||
|
MAX_ANNOUNCE_ATTRIBUTES, MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE,
|
||||||
|
MIN_PACKET_SIZE, StreamConfig, parse_announce, write_announce,
|
||||||
|
};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Ok(c) = parse_announce(data) else { return };
|
||||||
|
assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height));
|
||||||
|
assert!((1..=MAX_FPS).contains(&c.max_fps));
|
||||||
|
assert!((MIN_PACKET_SIZE..=MAX_PACKET_SIZE).contains(&c.packet_size));
|
||||||
|
assert!((1..=MAX_BITRATE_KBPS).contains(&c.bitrate_kbps));
|
||||||
|
assert!((1..=MAX_AUDIO_PACKET_DURATION_MS).contains(&c.audio_packet_duration_ms));
|
||||||
|
assert!((1..=8).contains(&c.surround.channels));
|
||||||
|
assert!(c.unknown_attributes as usize <= MAX_ANNOUNCE_ATTRIBUTES);
|
||||||
|
let again = parse_announce(&write_announce(&c)).expect("what was accepted writes back");
|
||||||
|
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||||
|
});
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
//! 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");
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,130 @@
|
|||||||
|
//! 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
//! Fuzzes the host's HTTP request parsing: the head cutter, the head parser, the target parser and the query parser.
|
||||||
|
//! Asserts invariants, not only "no panic": a parsed head ends exactly where the cutter says, a parsed query
|
||||||
|
//! re-encodes to the same parameters, and every typed value of a parsed request is within its documented range.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::host::http::{
|
||||||
|
HostRequest, MAX_HEAD_BYTES, MAX_MODE_DIMENSION, MAX_MODE_FPS, MAX_PARAMS, Route, encode_query, find_head_end,
|
||||||
|
parse_query, parse_request_head, parse_target,
|
||||||
|
};
|
||||||
|
use domistream::host::pairing::PairPhase;
|
||||||
|
|
||||||
|
fn check(req: &HostRequest) {
|
||||||
|
assert!(req.other_params.len() <= MAX_PARAMS);
|
||||||
|
if let Some(u) = &req.unique_id {
|
||||||
|
assert!(!u.is_empty() && u.len() <= 64, "uniqueid {u:?}");
|
||||||
|
}
|
||||||
|
let mode_ok = |m: &domistream::host::http::DisplayMode| {
|
||||||
|
(1..=MAX_MODE_DIMENSION).contains(&m.width)
|
||||||
|
&& (1..=MAX_MODE_DIMENSION).contains(&m.height)
|
||||||
|
&& (1..=MAX_MODE_FPS).contains(&m.fps)
|
||||||
|
};
|
||||||
|
match &req.route {
|
||||||
|
Route::Launch(l) => assert!(mode_ok(&l.mode), "{:?}", l.mode),
|
||||||
|
Route::Resume(r) => assert!(r.mode.as_ref().is_none_or(mode_ok)),
|
||||||
|
Route::Pair(p) => {
|
||||||
|
assert_eq!(req.unique_id.as_deref(), Some(p.unique_id.as_str()), "/pair needs uniqueid");
|
||||||
|
match &p.phase {
|
||||||
|
PairPhase::GetServerCert { client_cert_pem, .. } => assert!(!client_cert_pem.is_empty()),
|
||||||
|
PairPhase::ClientChallenge(v)
|
||||||
|
| PairPhase::ServerChallengeResp(v)
|
||||||
|
| PairPhase::ClientPairingSecret(v) => {
|
||||||
|
assert!(!v.is_empty())
|
||||||
|
}
|
||||||
|
PairPhase::PairChallenge => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Route::Unknown { path } => assert!(path.starts_with('/') && path.len() <= 256),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cut = find_head_end(data);
|
||||||
|
if let Ok(Some(n)) = cut {
|
||||||
|
assert!((4..=MAX_HEAD_BYTES).contains(&n) && data[..n].ends_with(b"\r\n\r\n"));
|
||||||
|
}
|
||||||
|
if let Ok(req) = parse_request_head(data) {
|
||||||
|
assert_eq!(cut, Ok(Some(data.len())), "a parsed head ends where the cutter says");
|
||||||
|
check(&req);
|
||||||
|
}
|
||||||
|
let Ok(text) = core::str::from_utf8(data) else { return };
|
||||||
|
if let Ok(req) = parse_target(text) {
|
||||||
|
check(&req);
|
||||||
|
}
|
||||||
|
if let Ok(params) = parse_query(text) {
|
||||||
|
let list: Vec<(&str, &str)> = params.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
|
||||||
|
match parse_query(&encode_query(&list)) {
|
||||||
|
Ok(again) => assert_eq!(again, params, "parse -> encode -> parse"),
|
||||||
|
// Encoding can triple a value (`+` becomes `%20`), so only a cap may refuse it.
|
||||||
|
Err(e) => assert!(matches!(e, domistream::Error::TooLarge { .. }), "{e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
//! Fuzzes the host's pairing state machine: a session fed arbitrary sequences of phases, PINs, timer wake-ups and
|
||||||
|
//! cancels, with arbitrary values, transports and client ids.
|
||||||
|
//! Asserts invariants, not only "no panic": a fuzzer that holds no client key never gets the session to Paired,
|
||||||
|
//! Failed is terminal, and the session has a deadline exactly while it is in progress.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::host::pairing::{
|
||||||
|
HostIdentity, HostPairingConfig, HostPairingSession, HostPairingState, HostPairingStep, PairPhase, PairRequest,
|
||||||
|
Transport,
|
||||||
|
};
|
||||||
|
use domistream::pairing::Pin;
|
||||||
|
use domistream::{Error, Instant, RandomSource};
|
||||||
|
|
||||||
|
const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt");
|
||||||
|
/// The certificate phase 1 presents: a test-only certificate whose key the fuzzer does not have.
|
||||||
|
const CLIENT_CERT_PEM: &str = include_str!("../../crates/domistream/tests/fixtures/test-only-host-cert.pem");
|
||||||
|
|
||||||
|
fn value(name: &str) -> Vec<u8> {
|
||||||
|
let prefix = format!("{name} = ");
|
||||||
|
let line = VECTORS.lines().find(|l| l.starts_with(&prefix)).expect("fixture value");
|
||||||
|
let hex = &line[prefix.len()..];
|
||||||
|
(0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Fixed;
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(0x5A);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the fuzzer's bytes as a script.
|
||||||
|
struct Script<'a>(&'a [u8]);
|
||||||
|
|
||||||
|
impl Script<'_> {
|
||||||
|
fn byte(&mut self) -> Option<u8> {
|
||||||
|
let (&b, rest) = self.0.split_first()?;
|
||||||
|
self.0 = rest;
|
||||||
|
Some(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bytes(&mut self, n: usize) -> Vec<u8> {
|
||||||
|
let n = n.min(self.0.len());
|
||||||
|
let (head, rest) = self.0.split_at(n);
|
||||||
|
self.0 = rest;
|
||||||
|
head.to_vec()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
// Any RSA identity serves as the host's: the client fixture's.
|
||||||
|
let Ok(host) = HostIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return };
|
||||||
|
let host_cert_der = value("host_cert_der");
|
||||||
|
let mut s = HostPairingSession::new(&host, HostPairingConfig::default(), Instant::ZERO);
|
||||||
|
let mut now = Instant::ZERO;
|
||||||
|
let mut script = Script(data);
|
||||||
|
let mut steps = 0;
|
||||||
|
while let Some(op) = script.byte() {
|
||||||
|
steps += 1;
|
||||||
|
if steps > 24 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let before = s.state();
|
||||||
|
let flags = script.byte().unwrap_or(0);
|
||||||
|
now = now.saturating_add(Duration::from_millis(u64::from(flags & 0x0F) * 700));
|
||||||
|
let unique_id = if flags & 0x10 != 0 {
|
||||||
|
String::from_utf8_lossy(&script.bytes(usize::from(flags >> 5) * 3)).into_owned()
|
||||||
|
} else {
|
||||||
|
"0123456789ABCDEF".to_string()
|
||||||
|
};
|
||||||
|
let len = usize::from(script.byte().unwrap_or(0));
|
||||||
|
let phase = match op % 8 {
|
||||||
|
0 => {
|
||||||
|
let mut salt = [0u8; 16];
|
||||||
|
let raw = script.bytes(16);
|
||||||
|
salt[..raw.len()].copy_from_slice(&raw);
|
||||||
|
let client_cert_pem =
|
||||||
|
if len % 4 == 0 { script.bytes(len * 8) } else { CLIENT_CERT_PEM.as_bytes().to_vec() };
|
||||||
|
Some(PairPhase::GetServerCert { salt, client_cert_pem })
|
||||||
|
}
|
||||||
|
1 => Some(PairPhase::ClientChallenge(script.bytes(len % 40))),
|
||||||
|
2 => Some(PairPhase::ServerChallengeResp(script.bytes(len % 72))),
|
||||||
|
3 => Some(PairPhase::ClientPairingSecret(script.bytes(len * 2))),
|
||||||
|
4 => Some(PairPhase::PairChallenge),
|
||||||
|
5 => {
|
||||||
|
let digits = format!("{:04}", u16::from_le_bytes([len as u8, flags]) % 10_000);
|
||||||
|
if let Ok(pin) = Pin::from_digits(&digits) {
|
||||||
|
let r = s.supply_pin(&host, pin, now);
|
||||||
|
if r.is_ok() {
|
||||||
|
assert_eq!(before, HostPairingState::AwaitPin);
|
||||||
|
assert_eq!(s.state(), HostPairingState::AwaitClientChallenge);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
6 => {
|
||||||
|
let late = now.saturating_add(Duration::from_secs(u64::from(flags)));
|
||||||
|
let fired = s.handle_timeout(late);
|
||||||
|
assert_eq!(
|
||||||
|
fired,
|
||||||
|
matches!(s.state(), HostPairingState::Failed(_)) && !matches!(before, HostPairingState::Failed(_))
|
||||||
|
);
|
||||||
|
None
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
s.cancel();
|
||||||
|
None
|
||||||
|
}
|
||||||
|
};
|
||||||
|
if let Some(phase) = phase {
|
||||||
|
let device_name = (flags & 0x80 != 0).then(|| "fuzz".to_string());
|
||||||
|
let request = PairRequest { unique_id, device_name, phase };
|
||||||
|
let other_cert;
|
||||||
|
let transport = match len % 3 {
|
||||||
|
0 => Transport::Http,
|
||||||
|
1 => Transport::Https { client_cert_der: &host_cert_der },
|
||||||
|
_ => {
|
||||||
|
other_cert = script.bytes(len);
|
||||||
|
Transport::Https { client_cert_der: &other_cert }
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let r = s.handle(&host, &request, transport, now, &mut Fixed);
|
||||||
|
assert!(!matches!(r, Ok(HostPairingStep::Paired(_))), "paired without the client's key");
|
||||||
|
if matches!(before, HostPairingState::Failed(_) | HostPairingState::Paired) {
|
||||||
|
assert!(matches!(r, Err(Error::State { .. })));
|
||||||
|
}
|
||||||
|
if r.is_err() {
|
||||||
|
assert!(matches!(s.state(), HostPairingState::Failed(_)), "an error ends the session: {r:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_ne!(s.state(), HostPairingState::Paired, "paired without the client's key");
|
||||||
|
assert!(s.paired_client().is_none());
|
||||||
|
if let HostPairingState::Failed(_) = before {
|
||||||
|
assert_eq!(s.state(), before, "Failed is terminal");
|
||||||
|
}
|
||||||
|
assert_eq!(
|
||||||
|
s.poll_timeout().is_none(),
|
||||||
|
matches!(s.state(), HostPairingState::Failed(_)),
|
||||||
|
"a deadline while in progress"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
//! Fuzzes the host's RTSP session with arbitrary requests, optionally after a valid prefix of the negotiation so the
|
||||||
|
//! later states are reached too.
|
||||||
|
//! Asserts invariants, not only "no panic": every answer parses with a documented status, 200 exactly when nothing
|
||||||
|
//! was refused, the state only moves forward and never on a refusal, and the events come once each, in order.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::RandomSource;
|
||||||
|
use domistream::rtsp::client::VideoCodec;
|
||||||
|
use domistream::rtsp::sdp::FeatureFlags;
|
||||||
|
use domistream::rtsp::server::{ChromaSampling, StreamConfig, SurroundSettings, parse_announce, write_announce};
|
||||||
|
use domistream::rtsp::{
|
||||||
|
EncryptionFlags, HostOffer, OpusConfig, RtspFramer, RtspServer, RtspServerState, ServerConfig, ServerEvent,
|
||||||
|
StreamPorts, parse_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Fixed(u8);
|
||||||
|
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rank(s: RtspServerState) -> u8 {
|
||||||
|
match s {
|
||||||
|
RtspServerState::Options => 0,
|
||||||
|
RtspServerState::Describe => 1,
|
||||||
|
RtspServerState::Setup => 2,
|
||||||
|
RtspServerState::Announce => 3,
|
||||||
|
RtspServerState::Play => 4,
|
||||||
|
RtspServerState::Playing => 5,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn announce() -> StreamConfig {
|
||||||
|
StreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
max_fps: 60,
|
||||||
|
packet_size: 1024,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
video_qos_traffic_type: 5,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
audio_qos_traffic_type: 4,
|
||||||
|
max_reference_frames: 0,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
dynamic_range_mode: 0,
|
||||||
|
encoder_csc_mode: 0,
|
||||||
|
chroma: ChromaSampling::Yuv420,
|
||||||
|
encryption: EncryptionFlags(7),
|
||||||
|
surround: SurroundSettings::default(),
|
||||||
|
unknown_attributes: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The valid negotiation, one request each.
|
||||||
|
fn prelude(session: &str) -> Vec<Vec<u8>> {
|
||||||
|
let body = write_announce(&announce());
|
||||||
|
let mut v = vec![
|
||||||
|
b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec(),
|
||||||
|
b"DESCRIBE rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 2\r\n\r\n".to_vec(),
|
||||||
|
];
|
||||||
|
for (i, s) in ["audio", "video", "control"].iter().enumerate() {
|
||||||
|
v.push(
|
||||||
|
format!("SETUP streamid={s}/0/0 RTSP/1.0\r\nCSeq: {}\r\nSession: {session}\r\nTransport: x\r\n\r\n", i + 3)
|
||||||
|
.into_bytes(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut a = format!("ANNOUNCE streamid=control/13/0 RTSP/1.0\r\nCSeq: 6\r\nContent-Length: {}\r\n\r\n", body.len())
|
||||||
|
.into_bytes();
|
||||||
|
a.extend_from_slice(&body);
|
||||||
|
v.push(a);
|
||||||
|
v.push(b"PLAY rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 7\r\n\r\n".to_vec());
|
||||||
|
// The first SETUP carries no session: none was issued yet.
|
||||||
|
if let Some(first) = v.get_mut(2) {
|
||||||
|
*first = b"SETUP streamid=audio/0/0 RTSP/1.0\r\nCSeq: 3\r\nTransport: x\r\n\r\n".to_vec();
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Checker {
|
||||||
|
announced: u32,
|
||||||
|
played: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Checker {
|
||||||
|
fn feed(&mut self, s: &mut RtspServer, message: &[u8]) {
|
||||||
|
let before = s.state();
|
||||||
|
let reply = s.handle_request(message);
|
||||||
|
let r = parse_response(&reply.bytes).expect("every answer parses");
|
||||||
|
assert_eq!(r.status, reply.status);
|
||||||
|
assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "status {}", reply.status);
|
||||||
|
assert_eq!(reply.status == 200, reply.error.is_none());
|
||||||
|
assert!(rank(s.state()) >= rank(before), "state went back");
|
||||||
|
if reply.status != 200 {
|
||||||
|
assert_eq!(s.state(), before, "a refusal changed the state");
|
||||||
|
}
|
||||||
|
while let Some(e) = s.poll_event() {
|
||||||
|
match e {
|
||||||
|
ServerEvent::Announced(c) => {
|
||||||
|
assert_eq!(self.announced, 0);
|
||||||
|
self.announced += 1;
|
||||||
|
let again = parse_announce(&write_announce(&c)).expect("an accepted ANNOUNCE writes back");
|
||||||
|
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||||
|
}
|
||||||
|
ServerEvent::PlayRequested => {
|
||||||
|
assert_eq!((self.announced, self.played), (1, 0));
|
||||||
|
self.played += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(self.played == 1, s.state() == RtspServerState::Playing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Some((&mode, rest)) = data.split_first() else { return };
|
||||||
|
let config = ServerConfig {
|
||||||
|
ports: StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||||
|
offer: HostOffer {
|
||||||
|
feature_flags: FeatureFlags(3),
|
||||||
|
encryption_supported: EncryptionFlags(7),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: mode & 0x40 != 0,
|
||||||
|
hdr: mode & 0x80 != 0,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![OpusConfig::stereo()],
|
||||||
|
},
|
||||||
|
required_encryption: EncryptionFlags(1),
|
||||||
|
require_session_header: mode & 0x20 != 0,
|
||||||
|
session_timeout_secs: 90,
|
||||||
|
};
|
||||||
|
let mut s = RtspServer::new(config, &mut Fixed(mode)).expect("a valid config");
|
||||||
|
let mut check = Checker { announced: 0, played: 0 };
|
||||||
|
let session = s.session_id().to_string();
|
||||||
|
// Bits 2..=4: how many valid requests come first (0..=7).
|
||||||
|
for m in prelude(&session).iter().take(usize::from((mode >> 2) & 0x07)) {
|
||||||
|
check.feed(&mut s, m);
|
||||||
|
}
|
||||||
|
if mode & 0x01 == 0 {
|
||||||
|
// Messages separated by NUL bytes, each fed whole.
|
||||||
|
for m in rest.split(|b| *b == 0).take(32) {
|
||||||
|
check.feed(&mut s, m);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// A byte stream through the request framer.
|
||||||
|
let mut f = RtspFramer::for_requests();
|
||||||
|
for chunk in rest.chunks(if mode & 0x02 == 0 { 7 } else { 512 }) {
|
||||||
|
if f.push(chunk).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loop {
|
||||||
|
match f.next_message() {
|
||||||
|
Ok(Some(m)) => check.feed(&mut s, &m),
|
||||||
|
Ok(None) => break,
|
||||||
|
Err(_) => return,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(Some(m)) = f.finish() {
|
||||||
|
check.feed(&mut s, &m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
//! 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
Generated
+1
-1
@@ -228,7 +228,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "domistream"
|
name = "domistream"
|
||||||
version = "0.1.0"
|
version = "0.2.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"aes",
|
"aes",
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
|
|||||||
@@ -127,6 +127,91 @@ mut("M23", "OS randomness", "getrandom added as a dependency and used in src/ent
|
|||||||
"\n#[allow(dead_code)]\nfn os_fill(dest: &mut [u8]) {\n let _ = getrandom::fill(dest);\n}\n")])
|
"\n#[allow(dead_code)]\nfn os_fill(dest: &mut [u8]) {\n let _ = getrandom::fill(dest);\n}\n")])
|
||||||
|
|
||||||
|
|
||||||
|
# ---- host side (Lumen, stream-v0.2.0, 2026-12-04). `test` may name several test binaries, space-separated.
|
||||||
|
HP = SRC + "host/pairing.rs"
|
||||||
|
mut("M25", "host pairing phase", "phase 4 accepted while phase 3 is expected (a skipped step)", "host_pairing session",
|
||||||
|
[(HP, "(HostPairingState::AwaitClientPairingSecret, PairPhase::ClientPairingSecret(value)) => {",
|
||||||
|
"(HostPairingState::AwaitClientPairingSecret | HostPairingState::AwaitServerChallengeResp, "
|
||||||
|
"PairPhase::ClientPairingSecret(value)) => {")])
|
||||||
|
mut("M26", "host pairing proof", "the client's proof H_c is not compared (any PIN pairs)", "host_pairing",
|
||||||
|
[(HP, "if !ct_eq(&expected, &self.client_proof) {", "if false && !ct_eq(&expected, &self.client_proof) {")])
|
||||||
|
mut("M27", "host pairing phase 5", "phase 5 accepts any HTTPS client certificate", "host_pairing",
|
||||||
|
[(HP, "if !ct_eq(client_cert_der, &pending.cert_der) {", "if false && !ct_eq(client_cert_der, &pending.cert_der) {")])
|
||||||
|
HH = SRC + "host/http/mod.rs"
|
||||||
|
mut("M28", "host HTTP cap", "query parameter cap off by one (allows 33)", "host_http",
|
||||||
|
[(HH, 'cap("http query parameters", MAX_PARAMS, count)?;', 'cap("http query parameters", MAX_PARAMS + 1, count)?;')])
|
||||||
|
mut("M29", "host HTTP body", "a GET with Content-Length other than 0 accepted", "host_http",
|
||||||
|
[(HH, 'if content_length || value != "0" {', "if content_length {")])
|
||||||
|
mut("M30", "host HTTP answer", "PairStatus 1 over plain HTTP too", "host_http session",
|
||||||
|
[(SRC + "host/http/answer.rs", "let paired = scheme == Scheme::Https && client_paired;",
|
||||||
|
"let paired = client_paired;")])
|
||||||
|
RS = SRC + "rtsp/server/mod.rs"
|
||||||
|
mut("M31", "RTSP order", "PLAY accepted before ANNOUNCE", "rtsp_server",
|
||||||
|
[(RS, 'self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;',
|
||||||
|
'let _ = self.expect(RtspServerState::Play, "PLAY after ANNOUNCE");')])
|
||||||
|
mut("M32", "RTSP order", "a second SETUP of the same stream accepted", "rtsp_server",
|
||||||
|
[(RS, " if *slot {\n", " if *slot && false {\n")])
|
||||||
|
mut("M33", "RTSP session", "a Session header with another id accepted once issued", "rtsp_server",
|
||||||
|
[(RS, "Some(id) if !self.session_issued || id != self.session_id => {", "Some(id) if !self.session_issued => {")])
|
||||||
|
mut("M34", "ANNOUNCE", "a known attribute given twice accepted (the first value kept)", "rtsp_server",
|
||||||
|
[(SRC + "rtsp/server/announce.rs", 'Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),',
|
||||||
|
"Some(Some(_)) => {}")])
|
||||||
|
mut("M35", "DESCRIBE", "the refPicInvalidation line written exactly when not offered", "rtsp_server session",
|
||||||
|
[(SRC + "rtsp/server/describe.rs", "if offer.reference_frame_invalidation {",
|
||||||
|
"if !offer.reference_frame_invalidation {")])
|
||||||
|
EH = SRC + "enet/host.rs"
|
||||||
|
mut("M36", "ENet host ack", "pings acknowledged before the verify is acknowledged", "enet_host",
|
||||||
|
[(EH, " CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
|
||||||
|
" if c.acknowledge && connected {",
|
||||||
|
" CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {\n"
|
||||||
|
" if c.acknowledge {")])
|
||||||
|
mut("M37", "ENet host ack", "a datagram without sent time goes on after an acknowledged command", "enet_host",
|
||||||
|
[(EH, "if wants_ack && sent_time.is_none() {", "if false && wants_ack && sent_time.is_none() {")])
|
||||||
|
mut("M38", "ENet host session id", "host session ids taken from the wrong offered field", "enet_host",
|
||||||
|
[(EH, "let out_session = next_session(p.incoming_session_id, FRESH_SESSION);\n"
|
||||||
|
" let in_session = next_session(p.outgoing_session_id, FRESH_SESSION);",
|
||||||
|
"let out_session = next_session(p.outgoing_session_id, FRESH_SESSION);\n"
|
||||||
|
" let in_session = next_session(p.incoming_session_id, FRESH_SESSION);")])
|
||||||
|
mut("M39", "ENet host session id", "the slot's previous session id not skipped", "enet_host",
|
||||||
|
[(EH, " if s == current {\n", " if false && s == current {\n")])
|
||||||
|
mut("M40", "ENet client session id", "verify's session ids swapped again (the bug fixed for v0.2.0)", "enet",
|
||||||
|
[(SRC + "enet/mod.rs", "self.in_session = p.incoming_session_id & 0x3;\n self.out_session = p.outgoing_session_id & 0x3;",
|
||||||
|
"self.in_session = p.outgoing_session_id & 0x3;\n self.out_session = p.incoming_session_id & 0x3;")])
|
||||||
|
CH = SRC + "control/host.rs"
|
||||||
|
mut("M41", "control host replay", "a repeated client sequence number accepted (< instead of <=)", "control_host",
|
||||||
|
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
|
||||||
|
"if self.last_client_sequence.is_some_and(|last| sequence < last) {")])
|
||||||
|
mut("M42", "control host replay", "the client replay check removed", "control_host",
|
||||||
|
[(CH, "if self.last_client_sequence.is_some_and(|last| sequence <= last) {",
|
||||||
|
"if self.last_client_sequence.is_some_and(|last| sequence <= last && false) {")])
|
||||||
|
mut("M43", "control host message", "extended termination code written little-endian", "control_host session",
|
||||||
|
[(CH, "framed(MessageType::TerminationExtended, &code.to_be_bytes())",
|
||||||
|
"framed(MessageType::TerminationExtended, &code.to_le_bytes())")])
|
||||||
|
mut("M44", "control host stop", "a PERIODIC_PING does not move the stop deadline", "control_host session",
|
||||||
|
[(CH, "self.deadline = self.deadline.max(now.saturating_add(self.timeout));", "self.deadline = self.deadline.max(now);")])
|
||||||
|
VP = SRC + "video/packetizer.rs"
|
||||||
|
mut("M45", "video parity order", "parity computed after the parity headers are written (headers become parity)",
|
||||||
|
"video_packetizer session",
|
||||||
|
[(VP, " ReedSolomon::new(k, m)?.encode(&mut shards)?;\n", ""),
|
||||||
|
(VP, " parity_packets += m as u64;",
|
||||||
|
" ReedSolomon::new(k, m)?.encode(&mut shards)?;\n parity_packets += m as u64;")])
|
||||||
|
mut("M46", "video parity", "the client's minimum parity count ignored", "video_packetizer",
|
||||||
|
[(VP, "if m < usize::from(min) { usize::from(min) } else { m }", "if m < usize::from(min) { m } else { m }")])
|
||||||
|
mut("M47", "video parity", "parity shard index written one too high", "video_packetizer",
|
||||||
|
[(VP, "let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);",
|
||||||
|
"let h = next_header(0, block, u16::try_from(k + j + 1).unwrap_or(u16::MAX), b);")])
|
||||||
|
mut("M48", "video nonce", "the GCM nonce counter does not advance per datagram (nonce reuse)", "video_packetizer",
|
||||||
|
[(VP, " nonce += 1;\n", " nonce += 0;\n")])
|
||||||
|
mut("M49", "audio IV", "the host encrypts with the IV of the next sequence number", "audio_packetizer session",
|
||||||
|
[(SRC + "audio/mod.rs", "plaintext.len())?;\n let iv = self.iv(sequence)?;",
|
||||||
|
"plaintext.len())?;\n let iv = self.iv(sequence.wrapping_add(1))?;")])
|
||||||
|
mut("M50", "audio IV", "IV counter written little-endian (both sides)", "media audio_packetizer",
|
||||||
|
[(SRC + "audio/mod.rs", "self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();",
|
||||||
|
"self.rikeyid.wrapping_add(u32::from(sequence)).to_le_bytes();")])
|
||||||
|
mut("M51", "audio block start", "a first sequence number that is not a block start accepted", "audio_packetizer",
|
||||||
|
[(SRC + "audio/packetizer.rs", "if !config.first_sequence.is_multiple_of(4) {", "if false {")])
|
||||||
|
|
||||||
|
|
||||||
def sh(args, **kw):
|
def sh(args, **kw):
|
||||||
return subprocess.run(args, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw)
|
return subprocess.run(args, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw)
|
||||||
|
|
||||||
@@ -170,7 +255,8 @@ def main():
|
|||||||
continue
|
continue
|
||||||
apply(m["edits"])
|
apply(m["edits"])
|
||||||
try:
|
try:
|
||||||
cmd = f"cargo test -j 2 --offline --test {m['test']} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
|
tests = " ".join(f"--test {t}" for t in m["test"].split())
|
||||||
|
cmd = f"cargo test -j 2 --offline --no-fail-fast {tests} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
|
||||||
gated(cmd)
|
gated(cmd)
|
||||||
log = open(os.path.join(QA, f"mut-{m['id']}.log"), encoding="utf-8-sig", errors="replace").read()
|
log = open(os.path.join(QA, f"mut-{m['id']}.log"), encoding="utf-8-sig", errors="replace").read()
|
||||||
finally:
|
finally:
|
||||||
|
|||||||
Reference in New Issue
Block a user