Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| da1f3afd52 | |||
| 948f446a13 | |||
| 71e34e8d9d | |||
| 9c59b69bf0 | |||
| 240190041d | |||
| f3ad3afe00 | |||
| ecc9908082 | |||
| fbfcd588a5 | |||
| fea864d16e | |||
| 38a455a717 |
@@ -0,0 +1,297 @@
|
|||||||
|
//! "Caps every length before it allocates": with a counting global allocator (`peak_alloc`, no unsafe code of
|
||||||
|
//! ours), feeds every parser small inputs whose length fields lie (claim gigabytes) and arbitrary inputs, and checks
|
||||||
|
//! the peak heap growth stays within a bound tied to the input and the parser's caps, never to a claimed length.
|
||||||
|
//!
|
||||||
|
//! 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 domistream::{Instant, SessionKeys};
|
||||||
|
use peak_alloc::PeakAlloc;
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use proptest::test_runner::{Config, TestRunner};
|
||||||
|
|
||||||
|
#[global_allocator]
|
||||||
|
static ALLOC: PeakAlloc = PeakAlloc;
|
||||||
|
|
||||||
|
/// Heap bytes `f` needs at its peak, beyond what was in use when it started.
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The budget for a parser given `input` bytes: its output may be a few times the input, plus fixed slack. A parser
|
||||||
|
/// that trusts a lying length field blows far past this.
|
||||||
|
fn budget(input: usize) -> usize {
|
||||||
|
64 * input + 256 * 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(what: &str, input: &[u8], f: impl FnOnce(&[u8])) {
|
||||||
|
let used = peak_of(|| f(input));
|
||||||
|
assert!(
|
||||||
|
used <= budget(input.len()),
|
||||||
|
"{what}: {used} bytes at peak for a {}-byte input (budget {})",
|
||||||
|
input.len(),
|
||||||
|
budget(input.len())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lying_inputs() -> Vec<(&'static str, Vec<u8>, fn(&[u8]))> {
|
||||||
|
let mut v: Vec<(&'static str, Vec<u8>, fn(&[u8]))> = Vec::new();
|
||||||
|
|
||||||
|
// RTSP: Content-Length claims 4 GiB.
|
||||||
|
let rtsp = b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec();
|
||||||
|
v.push(("rtsp response", rtsp.clone(), |b| {
|
||||||
|
let _ = domistream::rtsp::parse_response(b);
|
||||||
|
}));
|
||||||
|
v.push((
|
||||||
|
"rtsp request",
|
||||||
|
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||||
|
|b| {
|
||||||
|
let _ = domistream::rtsp::parse_request(b);
|
||||||
|
},
|
||||||
|
));
|
||||||
|
v.push(("rtsp framer", rtsp, |b| {
|
||||||
|
let mut f = domistream::rtsp::RtspFramer::new();
|
||||||
|
let _ = f.push(b);
|
||||||
|
let _ = f.next_message();
|
||||||
|
let _ = f.finish();
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ENet: data length 65535 with 3 bytes, fragment claiming 4 GiB and 4 billion fragments.
|
||||||
|
v.push(("enet reliable", vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1, 2, 3], |b| {
|
||||||
|
let _ = domistream::enet::protocol::parse_datagram(b);
|
||||||
|
}));
|
||||||
|
let mut frag = vec![0x00, 0x01, 0x88, 0x00, 0x00, 0x01];
|
||||||
|
frag.extend_from_slice(&1u16.to_be_bytes()); // start sequence
|
||||||
|
frag.extend_from_slice(&10u16.to_be_bytes()); // data length
|
||||||
|
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // fragment count
|
||||||
|
frag.extend_from_slice(&0u32.to_be_bytes()); // fragment number
|
||||||
|
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // total length
|
||||||
|
frag.extend_from_slice(&0u32.to_be_bytes()); // offset
|
||||||
|
frag.extend_from_slice(&[0; 10]);
|
||||||
|
v.push(("enet fragment", frag, |b| {
|
||||||
|
let _ = domistream::enet::protocol::parse_datagram(b);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Control: frame and message length fields at 65535.
|
||||||
|
let mut frame = vec![0x01, 0x00, 0xFF, 0xFF, 0, 0, 0, 0];
|
||||||
|
frame.extend_from_slice(&[0; 16 + 8]);
|
||||||
|
v.push(("control frame", frame.clone(), |b| {
|
||||||
|
let _ = domistream::control::parse_encrypted_frame(b);
|
||||||
|
}));
|
||||||
|
v.push(("control open", frame, |b| {
|
||||||
|
let _ = domistream::control::ControlCipher::new([1; 16]).open(domistream::control::Direction::HostToClient, b);
|
||||||
|
}));
|
||||||
|
v.push(("control message", vec![0x0b, 0x01, 0xFF, 0xFF, 1, 2], |b| {
|
||||||
|
let _ = domistream::control::parse_host_message(b);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Input: size field u32::MAX, length 65535.
|
||||||
|
v.push(("input", vec![0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0, 0, 0, 1, 2], |b| {
|
||||||
|
let _ = domistream::input::parse_input(b);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Video: 1023 data shards, frame header claiming a 4 GiB last payload.
|
||||||
|
let p = common::video_packet_bytes(1, 0, 0, 0x05, 0, common::fec_info(200, 0, 1023), &[0xFF; 48]);
|
||||||
|
v.push(("video packet", p.clone(), |b| {
|
||||||
|
let _ = domistream::video::parse_video_packet(b);
|
||||||
|
}));
|
||||||
|
v.push(("frame header", vec![1, 0, 0, 2, 0xFF, 0xFF, 0xFF, 0xFF], |b| {
|
||||||
|
let _ = domistream::video::packet::parse_frame_header(b);
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Audio, XML, PEM, DER with lying lengths.
|
||||||
|
v.push((
|
||||||
|
"audio packet",
|
||||||
|
vec![0x80, 127, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
|
||||||
|
|b| {
|
||||||
|
let _ = domistream::audio::parse_audio_packet(b);
|
||||||
|
},
|
||||||
|
));
|
||||||
|
v.push(("xml", b"<root status_code=\"200\"><a>�</a></root>".to_vec(), |b| {
|
||||||
|
let _ = domistream::http::xml::parse(b);
|
||||||
|
}));
|
||||||
|
let mut der = vec![0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF];
|
||||||
|
der.extend_from_slice(&[0x30; 20]);
|
||||||
|
v.push(("server cert der", der.clone(), |b| {
|
||||||
|
let _ = domistream::pairing::ServerCert::from_der(b);
|
||||||
|
}));
|
||||||
|
v.push(("client identity der", der, |b| {
|
||||||
|
let _ = domistream::pairing::ClientIdentity::from_der(b, b);
|
||||||
|
}));
|
||||||
|
v.push(("pem", b"-----BEGIN CERTIFICATE-----\nMIT/////\n-----END CERTIFICATE-----\n".to_vec(), |b| {
|
||||||
|
let _ = domistream::pairing::ServerCert::from_pem(b);
|
||||||
|
}));
|
||||||
|
v.push(("pairing secret", vec![0; 17], |b| {
|
||||||
|
let _ = domistream::pairing::crypto::split_pairing_secret(b);
|
||||||
|
}));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
|
||||||
|
fn depacketizer_checks() {
|
||||||
|
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
|
||||||
|
let cap = MAX_FRAMES_IN_FLIGHT * MAX_FRAME_BYTES + 1024 * 1024;
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let mut d = VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size: 1024,
|
||||||
|
cipher: None,
|
||||||
|
frame_timeout: core::time::Duration::from_millis(50),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
// One packet each of many frames that each announce 4 blocks of 255 shards.
|
||||||
|
for frame in 0..64u32 {
|
||||||
|
let mut p = common::video_packet_bytes(
|
||||||
|
frame as u16,
|
||||||
|
0,
|
||||||
|
frame,
|
||||||
|
0x05,
|
||||||
|
3 << 6,
|
||||||
|
common::fec_info(0, 0, 255),
|
||||||
|
&[0xAB; 1024 - 16],
|
||||||
|
);
|
||||||
|
p.resize(1024 + 16, 0);
|
||||||
|
let _ = d.push(Instant::ZERO, &p);
|
||||||
|
}
|
||||||
|
d
|
||||||
|
});
|
||||||
|
assert!(used <= cap, "video depacketizer: {used} bytes at peak (cap {cap})");
|
||||||
|
|
||||||
|
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioFec, MAX_BLOCKS_IN_FLIGHT};
|
||||||
|
let cap = MAX_BLOCKS_IN_FLIGHT * 6 * domistream::audio::packet::MAX_AUDIO_PACKET_BYTES + 256 * 1024;
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let mut d = AudioDepacketizer::new(AudioConfig {
|
||||||
|
cipher: Some(domistream::audio::AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 })),
|
||||||
|
packet_duration_ms: 5,
|
||||||
|
fec: AudioFec::ParityMatrix(common::audio_test_matrix()),
|
||||||
|
loss_timeout: core::time::Duration::from_millis(40),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
for seq in (0..2000u16).step_by(13) {
|
||||||
|
let mut p = vec![0x80, 97];
|
||||||
|
p.extend_from_slice(&seq.wrapping_mul(97).to_be_bytes());
|
||||||
|
p.extend_from_slice(&[0; 8]);
|
||||||
|
p.extend_from_slice(&[0x11; 2000]);
|
||||||
|
let _ = d.push(Instant::ZERO, &p);
|
||||||
|
}
|
||||||
|
d
|
||||||
|
});
|
||||||
|
assert!(used <= cap, "audio depacketizer: {used} bytes at peak (cap {cap})");
|
||||||
|
|
||||||
|
use domistream::enet::{EnetClient, EnetConfig, MAX_PACKET_BYTES};
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let cfg = EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: core::time::Duration::from_millis(500),
|
||||||
|
timeout: core::time::Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
let mut c = EnetClient::connect(cfg, Instant::ZERO, &mut common::SeqRng::new(1)).unwrap();
|
||||||
|
// Fragments of 4 billion pieces and gigabyte totals, addressed to every peer id.
|
||||||
|
for peer in 0..64u16 {
|
||||||
|
let mut d = peer.to_be_bytes().to_vec();
|
||||||
|
d.extend_from_slice(&[0x88, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04]);
|
||||||
|
d.extend_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
d.extend_from_slice(&7u32.to_be_bytes());
|
||||||
|
d.extend_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
d.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
d.extend_from_slice(&[1, 2, 3, 4]);
|
||||||
|
let _ = c.handle_datagram(Instant::ZERO, &d);
|
||||||
|
}
|
||||||
|
c
|
||||||
|
});
|
||||||
|
assert!(used <= 4 * MAX_PACKET_BYTES + 256 * 1024, "enet client: {used} bytes at peak");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parsers_never_allocate_past_their_caps() {
|
||||||
|
for (what, input, f) in lying_inputs() {
|
||||||
|
check(what, &input, f);
|
||||||
|
}
|
||||||
|
depacketizer_checks();
|
||||||
|
|
||||||
|
// Arbitrary inputs to every stateless parser.
|
||||||
|
let mut runner = TestRunner::new(Config { cases: 400, ..Config::default() });
|
||||||
|
let parsers: Vec<(&str, fn(&[u8]))> = vec![
|
||||||
|
("xml", |b| {
|
||||||
|
let _ = domistream::http::xml::parse(b);
|
||||||
|
}),
|
||||||
|
("serverinfo", |b| {
|
||||||
|
let _ = domistream::http::parse_server_info(b);
|
||||||
|
}),
|
||||||
|
("applist", |b| {
|
||||||
|
let _ = domistream::http::parse_app_list(b);
|
||||||
|
}),
|
||||||
|
("launch", |b| {
|
||||||
|
let _ = domistream::http::parse_launch_response(b);
|
||||||
|
}),
|
||||||
|
("pair response", |b| {
|
||||||
|
let _ = domistream::pairing::parse_pair_response(b);
|
||||||
|
}),
|
||||||
|
("pem", |b| {
|
||||||
|
let _ = domistream::pairing::ServerCert::from_pem(b);
|
||||||
|
}),
|
||||||
|
("der", |b| {
|
||||||
|
let _ = domistream::pairing::ServerCert::from_der(b);
|
||||||
|
}),
|
||||||
|
("rtsp response", |b| {
|
||||||
|
let _ = domistream::rtsp::parse_response(b);
|
||||||
|
}),
|
||||||
|
("rtsp request", |b| {
|
||||||
|
let _ = domistream::rtsp::parse_request(b);
|
||||||
|
}),
|
||||||
|
("sdp", |b| {
|
||||||
|
let _ = domistream::rtsp::sdp::parse_sdp(b);
|
||||||
|
}),
|
||||||
|
("enet", |b| {
|
||||||
|
let _ = domistream::enet::protocol::parse_datagram(b);
|
||||||
|
}),
|
||||||
|
("control frame", |b| {
|
||||||
|
let _ = domistream::control::parse_encrypted_frame(b);
|
||||||
|
}),
|
||||||
|
("control message", |b| {
|
||||||
|
let _ = domistream::control::parse_host_message(b);
|
||||||
|
}),
|
||||||
|
("input", |b| {
|
||||||
|
let _ = domistream::input::parse_input(b);
|
||||||
|
}),
|
||||||
|
("rtp", |b| {
|
||||||
|
let _ = domistream::rtp::parse_rtp_header(b);
|
||||||
|
}),
|
||||||
|
("video", |b| {
|
||||||
|
let _ = domistream::video::parse_video_packet(b);
|
||||||
|
}),
|
||||||
|
("audio", |b| {
|
||||||
|
let _ = domistream::audio::parse_audio_packet(b);
|
||||||
|
}),
|
||||||
|
("video decrypt", |b| {
|
||||||
|
let _ = domistream::video::VideoCipher::new([2; 16]).decrypt(b);
|
||||||
|
}),
|
||||||
|
("audio decrypt", |b| {
|
||||||
|
let _ = domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b);
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
for (what, f) in parsers {
|
||||||
|
runner
|
||||||
|
.run(&proptest::collection::vec(any::<u8>(), 0..1500), |data| {
|
||||||
|
let used = peak_of(|| f(&data));
|
||||||
|
prop_assert!(
|
||||||
|
used <= budget(data.len()),
|
||||||
|
"{}: {} bytes at peak for {} input bytes",
|
||||||
|
what,
|
||||||
|
used,
|
||||||
|
data.len()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
//! The audio depacketizer (`docs/PROTOCOL.md` 6): blocks of 4 data + 2 parity packets with a parity matrix passed
|
||||||
|
//! through the `AudioFec::ParityMatrix` hook (U16 is unmeasured, so any MDS matrix must work; the tests use a
|
||||||
|
//! Cauchy matrix and a second one), AES-128-CBC payloads, every loss pattern of a block, sequence wrap, duplicates,
|
||||||
|
//! reordering, far-past and far-future packets.
|
||||||
|
//!
|
||||||
|
//! Reading of PROTOCOL.md 6.2: a parity packet's RTP sequence "continues after the 4 data packets" (base + 4 +
|
||||||
|
//! shard), which overlaps the next block's data sequence numbers; the receiver must key parity by the FEC header's
|
||||||
|
//! base sequence and the payload type, never by the parity packet's RTP sequence.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use common::{AExpect, APkt, AudioHost, SeqRng, audio_test_matrix, subsets_of};
|
||||||
|
use domistream::audio::packet::MAX_AUDIO_PACKET_BYTES;
|
||||||
|
use domistream::audio::{AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioStats};
|
||||||
|
use domistream::{Error, Instant, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"audio-test-key!!";
|
||||||
|
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
|
||||||
|
const DURATION: u32 = 5;
|
||||||
|
|
||||||
|
fn host(encrypt: bool, matrix: [u8; 8]) -> AudioHost {
|
||||||
|
AudioHost { key: KEY, rikeyid: RIKEYID, encrypt, matrix, duration_ms: DURATION, opus_len: 37 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(encrypt: bool, fec: AudioFec) -> AudioConfig {
|
||||||
|
AudioConfig {
|
||||||
|
cipher: encrypt.then(|| AudioCipher::new(&SessionKeys { rikey: KEY, rikeyid: RIKEYID })),
|
||||||
|
packet_duration_ms: DURATION as u8,
|
||||||
|
fec,
|
||||||
|
loss_timeout: Duration::from_millis(40),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Run {
|
||||||
|
events: Vec<AudioEvent>,
|
||||||
|
stats: AudioStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(cfg: AudioConfig, datagrams: &[Vec<u8>]) -> Run {
|
||||||
|
let mut d = AudioDepacketizer::new(cfg).expect("AudioDepacketizer::new");
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for g in datagrams {
|
||||||
|
d.push(Instant::from_micros(now), g).expect("push never fails within the size cap");
|
||||||
|
now += 10;
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
d.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
if d.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Run { events, stats: d.stats() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Want {
|
||||||
|
/// Arrived as sent.
|
||||||
|
Packet,
|
||||||
|
/// Lost and rebuilt by FEC.
|
||||||
|
Recovered,
|
||||||
|
/// Gone: reported lost.
|
||||||
|
Lost,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every data sequence number gets exactly one event, in stream order; packets are byte-exact with the right
|
||||||
|
/// timestamp; `recovered` is set exactly for rebuilt ones.
|
||||||
|
fn check(expect: &[AExpect], want: &[Want], r: &Run) {
|
||||||
|
let pos: HashMap<u16, usize> = expect.iter().enumerate().map(|(i, e)| (e.sequence, i)).collect();
|
||||||
|
let mut seen = vec![false; expect.len()];
|
||||||
|
let mut prev: Option<usize> = None;
|
||||||
|
for e in &r.events {
|
||||||
|
let (seq, i) = match e {
|
||||||
|
AudioEvent::Packet { sequence, .. } | AudioEvent::Lost { sequence } => (
|
||||||
|
*sequence,
|
||||||
|
*pos.get(sequence)
|
||||||
|
.unwrap_or_else(|| panic!("event for sequence {sequence} that was never a data packet")),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
assert!(!seen[i], "two events for sequence {seq}");
|
||||||
|
assert!(prev.is_none_or(|p| i > p), "sequence {seq} out of order");
|
||||||
|
prev = Some(i);
|
||||||
|
seen[i] = true;
|
||||||
|
match (e, want[i]) {
|
||||||
|
(AudioEvent::Packet { timestamp_ms, opus, recovered, .. }, Want::Packet | Want::Recovered) => {
|
||||||
|
assert_eq!(opus, &expect[i].opus, "sequence {seq} corrupt");
|
||||||
|
assert_eq!(*timestamp_ms, expect[i].timestamp_ms, "sequence {seq} timestamp");
|
||||||
|
assert_eq!(*recovered, want[i] == Want::Recovered, "sequence {seq} recovered flag");
|
||||||
|
}
|
||||||
|
(AudioEvent::Lost { .. }, Want::Lost) => {}
|
||||||
|
(got, w) => panic!("sequence {seq}: want {w:?}, got {got:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, s) in seen.iter().enumerate() {
|
||||||
|
assert!(s, "no event for sequence {} (want {:?})", expect[i].sequence, want[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What must come out of a block, given which of its 6 packets arrived.
|
||||||
|
fn block_want(arrived: &[bool; 6], fec: bool) -> [Want; 4] {
|
||||||
|
let count = arrived.iter().filter(|a| **a).count();
|
||||||
|
let mut w = [Want::Packet; 4];
|
||||||
|
for (i, slot) in w.iter_mut().enumerate() {
|
||||||
|
if !arrived[i] {
|
||||||
|
*slot = if fec && count >= 4 { Want::Recovered } else { Want::Lost };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blocks `1..blocks-1` lose what `lose(block, index)` says; the first and last blocks arrive whole.
|
||||||
|
fn scenario(
|
||||||
|
h: &AudioHost,
|
||||||
|
seed: u64,
|
||||||
|
first_seq: u16,
|
||||||
|
blocks: usize,
|
||||||
|
fec: bool,
|
||||||
|
lose: impl Fn(usize, usize) -> bool,
|
||||||
|
) -> (Vec<AExpect>, Vec<Want>, Vec<Vec<u8>>) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, first_seq, 0x7000_0000, blocks);
|
||||||
|
let mut want = Vec::new();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for b in 0..blocks {
|
||||||
|
let mut arrived = [true; 6];
|
||||||
|
for p in packets.iter().filter(|p| p.block == b) {
|
||||||
|
if b != 0 && b + 1 != blocks && lose(b, p.index) {
|
||||||
|
arrived[p.index] = false;
|
||||||
|
} else {
|
||||||
|
datagrams.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want.extend(block_want(&arrived, fec));
|
||||||
|
}
|
||||||
|
(expect, want, datagrams)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ every pattern
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_loss_pattern_of_a_block() {
|
||||||
|
// All 64 subsets of the 6 packets lost in the middle block, encrypted, with the Cauchy matrix.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for size in 0..=6 {
|
||||||
|
for lost in subsets_of(6, size) {
|
||||||
|
let (expect, want, dg) = scenario(&h, 1, 0, 3, true, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_loss_pattern_plaintext_and_another_matrix() {
|
||||||
|
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8) and no encryption.
|
||||||
|
let m = [1, 1, 1, 1, 1, 2, 4, 8];
|
||||||
|
let h = host(false, m);
|
||||||
|
for size in 0..=6 {
|
||||||
|
for lost in subsets_of(6, size) {
|
||||||
|
let (expect, want, dg) = scenario(&h, 2, 400, 3, true, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(false, AudioFec::ParityMatrix(m)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fec_disabled_reports_losses() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for lost in [vec![0usize], vec![3], vec![1, 2], vec![0, 4, 5]] {
|
||||||
|
let (expect, want, dg) = scenario(&h, 3, 8, 3, false, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::Disabled), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_losses_over_many_blocks() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for (seed, pct) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50)] {
|
||||||
|
let mut rng = SeqRng::new(seed * 31);
|
||||||
|
let mask: Vec<bool> = (0..60 * 6).map(|_| rng.below(100) < pct).collect();
|
||||||
|
let (expect, want, dg) = scenario(&h, seed, 0, 60, true, |b, i| mask[b * 6 + i]);
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert_eq!(r.stats.recovered, want.iter().filter(|w| **w == Want::Recovered).count() as u64);
|
||||||
|
assert_eq!(r.stats.lost, want.iter().filter(|w| **w == Want::Lost).count() as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ order and strays
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sequence_wraps() {
|
||||||
|
// Blocks from 0xFFF0 through 0x000F: data sequence 0xFFFF -> 0, base sequence wrap, rikeyid + seq wrap.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let (expect, want, dg) = scenario(&h, 20, 0xFFF0, 8, true, |b, i| (b + i) % 5 == 0);
|
||||||
|
assert!(expect.iter().any(|e| e.sequence == 0xFFFF) && expect.iter().any(|e| e.sequence == 0));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicates_are_dropped() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let (expect, want, dg) = scenario(&h, 21, 0, 10, true, |b, i| (b * 7 + i) % 6 == 0);
|
||||||
|
let doubled: Vec<Vec<u8>> = dg.iter().flat_map(|g| [g.clone(), g.clone()]).collect();
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &doubled);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= dg.len() as u64 / 2, "{:?}", r.stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_within_and_across_blocks() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for seed in 30..36u64 {
|
||||||
|
let (expect, want, mut dg) = scenario(&h, seed, 0, 12, true, |b, i| (b + i + seed as usize) % 7 == 0);
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut i = 6; // the first block stays first, so the stream has a known start
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + 9).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_past_and_far_future() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(40);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 1000, 0, 6);
|
||||||
|
let (old, _) = h.blocks(&mut SeqRng::new(41), 1000u16.wrapping_sub(400), 0, 1);
|
||||||
|
let (future, _) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
|
||||||
|
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block < 3).map(|p| p.bytes.clone()).collect();
|
||||||
|
dg.extend(old.iter().map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block < 2).map(|p| p.bytes.clone())); // replays
|
||||||
|
dg.extend(future.iter().take(1).map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block >= 3).map(|p| p.bytes.clone()));
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
assert!(r.stats.packets_dropped >= 6 + 12, "far-past block and replays dropped: {:?}", r.stats);
|
||||||
|
// No event is ever a corrupt packet, the far-past block never comes out, and the first blocks do, in order.
|
||||||
|
// (Whether the lone far-future packet is played or dropped is the receiver's choice.)
|
||||||
|
let (_, future_expect) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
|
||||||
|
let by_seq: HashMap<u16, &AExpect> = expect.iter().chain(&future_expect[..1]).map(|e| (e.sequence, e)).collect();
|
||||||
|
let mut first_blocks = 0;
|
||||||
|
for e in &r.events {
|
||||||
|
if let AudioEvent::Packet { sequence, opus, .. } = e {
|
||||||
|
assert!(!(600..604).contains(sequence), "far-past sequence {sequence} played");
|
||||||
|
let want = by_seq
|
||||||
|
.get(sequence)
|
||||||
|
.unwrap_or_else(|| panic!("a packet for sequence {sequence} that only strays carried"));
|
||||||
|
assert_eq!(opus, &want.opus);
|
||||||
|
if (1000..1012).contains(sequence) {
|
||||||
|
first_blocks += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(first_blocks, 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parity_of(packets: &[APkt], block: usize, index: usize) -> Vec<u8> {
|
||||||
|
packets.iter().find(|p| p.block == block && p.index == index).unwrap().bytes.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_parity_never_corrupts() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(50);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
|
||||||
|
let mut hostile = Vec::new();
|
||||||
|
// Parity for block 1 with a base sequence that is not a multiple of 4.
|
||||||
|
let mut p = parity_of(&packets, 1, 4);
|
||||||
|
p[14..16].copy_from_slice(&5u16.to_be_bytes());
|
||||||
|
hostile.push(p);
|
||||||
|
// Parity shorter than the data shards.
|
||||||
|
let mut p = parity_of(&packets, 1, 5);
|
||||||
|
p.truncate(p.len() - 16);
|
||||||
|
hostile.push(p);
|
||||||
|
// Parity claiming to protect another payload type.
|
||||||
|
let mut p = parity_of(&packets, 1, 4);
|
||||||
|
p[13] = 96;
|
||||||
|
hostile.push(p);
|
||||||
|
// Block 1 loses data 0 and 1; only the hostile parity (and nothing else) is offered for it.
|
||||||
|
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block == 0).map(|p| p.bytes.clone()).collect();
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block == 1 && (2..4).contains(&p.index)).map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(hostile);
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block == 2).map(|p| p.bytes.clone()));
|
||||||
|
let mut want = vec![Want::Packet; 12];
|
||||||
|
want[4] = Want::Lost;
|
||||||
|
want[5] = Want::Lost;
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn undecryptable_data_is_dropped_and_rebuilt() {
|
||||||
|
// Copies of a data packet with a ciphertext of a wrong length or no payload: dropped, never output, and the
|
||||||
|
// packet is rebuilt from the rest of its block.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(60);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
|
||||||
|
let mut dg: Vec<Vec<u8>> = Vec::new();
|
||||||
|
for p in &packets {
|
||||||
|
if p.block == 1 && p.index == 2 {
|
||||||
|
let mut empty = p.bytes.clone();
|
||||||
|
empty.truncate(12);
|
||||||
|
dg.push(empty);
|
||||||
|
let mut odd = p.bytes.clone();
|
||||||
|
odd.pop();
|
||||||
|
dg.push(odd);
|
||||||
|
} else {
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut want = vec![Want::Packet; 12];
|
||||||
|
want[6] = Want::Recovered;
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ API edges
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_refusals() {
|
||||||
|
assert_err!(
|
||||||
|
AudioDepacketizer::new(AudioConfig { packet_duration_ms: 0, ..config(true, AudioFec::Disabled) }),
|
||||||
|
Error::Malformed { .. }
|
||||||
|
);
|
||||||
|
let mut zero = audio_test_matrix();
|
||||||
|
zero[5] = 0;
|
||||||
|
for bad in [zero, [1; 8], [1, 2, 3, 4, 2, 4, 6, 8], [0; 8]] {
|
||||||
|
assert_err!(
|
||||||
|
AudioDepacketizer::new(config(true, AudioFec::ParityMatrix(bad))),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{bad:?} is not MDS"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(AudioDepacketizer::new(config(false, AudioFec::ParityMatrix(audio_test_matrix()))).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_sizes() {
|
||||||
|
let mut d = AudioDepacketizer::new(config(true, AudioFec::Disabled)).unwrap();
|
||||||
|
assert_too_large!(
|
||||||
|
d.push(Instant::ZERO, &vec![0x80; MAX_AUDIO_PACKET_BYTES + 1]),
|
||||||
|
MAX_AUDIO_PACKET_BYTES,
|
||||||
|
MAX_AUDIO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(d.push(Instant::ZERO, &vec![0x80; 1 << 20]), MAX_AUDIO_PACKET_BYTES, 1 << 20);
|
||||||
|
for g in [
|
||||||
|
vec![],
|
||||||
|
vec![0x80],
|
||||||
|
vec![0x80, 97, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
vec![0xFF; 40],
|
||||||
|
vec![0x80; MAX_AUDIO_PACKET_BYTES],
|
||||||
|
] {
|
||||||
|
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
|
||||||
|
}
|
||||||
|
assert_eq!(d.stats().packets_dropped, 5);
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_packet_waits_for_the_loss_timeout() {
|
||||||
|
let h = host(false, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(70);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 2);
|
||||||
|
let mut d = AudioDepacketizer::new(config(false, AudioFec::Disabled)).unwrap();
|
||||||
|
let t = Instant::from_micros(3_000_000);
|
||||||
|
// Data 0 and 2 of block 0: 0 comes out, 1 is missing, 2 waits behind it.
|
||||||
|
d.push(t, &packets[0].bytes).unwrap();
|
||||||
|
d.push(t, &packets[2].bytes).unwrap();
|
||||||
|
assert!(matches!(d.poll_event(), Some(AudioEvent::Packet { sequence: 0, .. })));
|
||||||
|
assert_eq!(d.poll_event(), None, "sequence 2 waits for 1");
|
||||||
|
let deadline = d.poll_timeout().expect("a deadline for sequence 1");
|
||||||
|
assert!(deadline > t && deadline <= t.saturating_add(Duration::from_millis(40)));
|
||||||
|
d.handle_timeout(t.saturating_add(Duration::from_millis(39))).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), None, "not before the loss timeout");
|
||||||
|
d.handle_timeout(t.saturating_add(Duration::from_millis(40))).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), Some(AudioEvent::Lost { sequence: 1 }));
|
||||||
|
match d.poll_event() {
|
||||||
|
Some(AudioEvent::Packet { sequence: 2, opus, recovered: false, .. }) => assert_eq!(opus, expect[2].opus),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Random loss masks and reordering over random lengths: exact, rebuilt or lost, never corrupt.
|
||||||
|
#[test]
|
||||||
|
fn generated_patterns(seed in any::<u64>(), first in 0u16..16_384, loss in 0usize..50, opus_len in 1usize..120) {
|
||||||
|
let mut h = host(true, audio_test_matrix());
|
||||||
|
h.opus_len = opus_len;
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mask: Vec<bool> = (0..20 * 6).map(|_| rng.below(100) < loss).collect();
|
||||||
|
let (expect, want, mut dg) = scenario(&h, seed, first * 4, 20, true, |b, i| mask[b * 6 + i]);
|
||||||
|
let mut i = 6;
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + 1 + rng.below(8)).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..80), 0..60)) {
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(audio_test_matrix())), &datagrams);
|
||||||
|
prop_assert!(r.events.len() <= datagrams.len() * 4 + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -388,11 +388,7 @@ pub mod gf {
|
|||||||
let k = data.len();
|
let k = data.len();
|
||||||
let len = data[0].len();
|
let len = data[0].len();
|
||||||
(0..parity)
|
(0..parity)
|
||||||
.map(|r| {
|
.map(|r| (0..len).map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x]))).collect())
|
||||||
(0..len)
|
|
||||||
.map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x])))
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.collect()
|
.collect()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -559,8 +555,7 @@ impl VideoHost {
|
|||||||
p.push(0);
|
p.push(0);
|
||||||
p.push(0x10);
|
p.push(0x10);
|
||||||
p.push((block << 4) | (last_block << 6));
|
p.push((block << 4) | (last_block << 6));
|
||||||
let fec_info =
|
let fec_info = (u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
|
||||||
(u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
|
|
||||||
p.extend_from_slice(&fec_info.to_le_bytes());
|
p.extend_from_slice(&fec_info.to_le_bytes());
|
||||||
p
|
p
|
||||||
}
|
}
|
||||||
@@ -603,9 +598,7 @@ pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext:
|
|||||||
iv[..8].copy_from_slice(&counter.to_le_bytes());
|
iv[..8].copy_from_slice(&counter.to_le_bytes());
|
||||||
iv[11] = b'V';
|
iv[11] = b'V';
|
||||||
let mut buf = plaintext.to_vec();
|
let mut buf = plaintext.to_vec();
|
||||||
let tag = cipher
|
let tag = cipher.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into()).expect("gcm encrypt");
|
||||||
.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into())
|
|
||||||
.expect("gcm encrypt");
|
|
||||||
let mut out = iv.to_vec();
|
let mut out = iv.to_vec();
|
||||||
out.extend_from_slice(&frame_number.to_le_bytes());
|
out.extend_from_slice(&frame_number.to_le_bytes());
|
||||||
out.extend_from_slice(tag.as_slice());
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
|||||||
@@ -0,0 +1,633 @@
|
|||||||
|
//! Control channel (`docs/PROTOCOL.md` 3.2, 3.3): nonce layout, AES-GCM frames against .NET vectors
|
||||||
|
//! (`tools/vectors/gcm_vectors.cs`), tampering, direction, replay and sequence wrap through [`ControlStream`], and the
|
||||||
|
//! message layouts.
|
||||||
|
|
||||||
|
#![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::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES, nonce};
|
||||||
|
use domistream::control::message::{MAX_MESSAGE_BYTES, MotionKind, encode_client_message};
|
||||||
|
use domistream::control::{
|
||||||
|
ClientMessage, ControlCipher, ControlConfig, ControlEvent, ControlStream, Direction, HostMessage, MessageType,
|
||||||
|
parse_encrypted_frame, parse_host_message, parse_message,
|
||||||
|
};
|
||||||
|
use domistream::enet::EnetConfig;
|
||||||
|
use domistream::enet::protocol::{Command, CommandBody, ConnectParams, Datagram, encode_datagram, parse_datagram};
|
||||||
|
use domistream::input::InputEvent;
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const NAMES: [&str; 10] = [
|
||||||
|
"c_ping_0",
|
||||||
|
"c_input_1",
|
||||||
|
"c_ping_ffff",
|
||||||
|
"c_ping_10000",
|
||||||
|
"c_ping_fffffffe",
|
||||||
|
"c_ping_ffffffff",
|
||||||
|
"h_rumble_0",
|
||||||
|
"h_rumble_7",
|
||||||
|
"h_termination_ffffffff",
|
||||||
|
"h_rgb_2a",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn dir(v: &common::Vectors, name: &str) -> Direction {
|
||||||
|
match v.str(&format!("{name}_direction")) {
|
||||||
|
"C" => Direction::ClientToHost,
|
||||||
|
"H" => Direction::HostToClient,
|
||||||
|
other => panic!("direction {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ nonce
|
||||||
|
|
||||||
|
fn expected_nonce(seq: u32, direction: Direction) -> [u8; 12] {
|
||||||
|
let mut n = [0u8; 12];
|
||||||
|
n[..4].copy_from_slice(&seq.to_le_bytes());
|
||||||
|
n[10] = match direction {
|
||||||
|
Direction::ClientToHost => b'C',
|
||||||
|
Direction::HostToClient => b'H',
|
||||||
|
};
|
||||||
|
n[11] = b'C';
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nonce_layout() {
|
||||||
|
// seq LE, then 6 zero bytes, then the direction byte, then 'C'.
|
||||||
|
assert_eq!(nonce(0, Direction::ClientToHost).unwrap(), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'C', b'C']);
|
||||||
|
assert_eq!(nonce(1, Direction::HostToClient).unwrap(), [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'H', b'C']);
|
||||||
|
assert_eq!(
|
||||||
|
nonce(0x1234_5678, Direction::ClientToHost).unwrap(),
|
||||||
|
[0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, b'C', b'C']
|
||||||
|
);
|
||||||
|
for seq in [0xFFFF, 0x1_0000, 0xFFFF_FFFE, u32::MAX] {
|
||||||
|
for d in [Direction::ClientToHost, Direction::HostToClient] {
|
||||||
|
assert_eq!(nonce(seq, d).unwrap(), expected_nonce(seq, d), "{seq:#x} {d:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_ne!(nonce(5, Direction::ClientToHost).unwrap(), nonce(5, Direction::HostToClient).unwrap());
|
||||||
|
let v = common::control_vectors();
|
||||||
|
for name in NAMES {
|
||||||
|
let seq = v.u32_hex(&format!("{name}_sequence"));
|
||||||
|
assert_eq!(nonce(seq, dir(&v, name)).unwrap().to_vec(), v.bytes(&format!("{name}_nonce")), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn nonce_matches_the_definition(seq in any::<u32>(), host in any::<bool>()) {
|
||||||
|
let d = if host { Direction::HostToClient } else { Direction::ClientToHost };
|
||||||
|
prop_assert_eq!(nonce(seq, d), Ok(expected_nonce(seq, d)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ seal / open
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_matches_dotnet_vectors() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
for name in NAMES {
|
||||||
|
let seq = v.u32_hex(&format!("{name}_sequence"));
|
||||||
|
let d = dir(&v, name);
|
||||||
|
let plain = v.bytes(&format!("{name}_plain"));
|
||||||
|
let frame = v.bytes(&format!("{name}_frame"));
|
||||||
|
assert_eq!(c.seal(seq, d, &plain).unwrap(), frame, "{name}");
|
||||||
|
assert_eq!(c.open(d, &frame).unwrap(), (seq, plain.clone()), "{name}");
|
||||||
|
let f = parse_encrypted_frame(&frame).unwrap();
|
||||||
|
assert_eq!(f.sequence, seq);
|
||||||
|
assert_eq!(f.ciphertext.len(), plain.len());
|
||||||
|
assert_eq!(f.tag.to_vec(), frame[8..24].to_vec());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_open_round_trip() {
|
||||||
|
let c = ControlCipher::new([7; 16]);
|
||||||
|
for len in [4usize, 5, 16, 100, MAX_FRAME_BYTES - FRAME_HEADER_LEN] {
|
||||||
|
let plain: Vec<u8> = (0..len).map(|i| i as u8).collect();
|
||||||
|
for d in [Direction::ClientToHost, Direction::HostToClient] {
|
||||||
|
let f = c.seal(42, d, &plain).unwrap();
|
||||||
|
assert_eq!(f.len(), FRAME_HEADER_LEN + len);
|
||||||
|
assert_eq!(&f[..2], &[0x01, 0x00]);
|
||||||
|
assert_eq!(u16::from_le_bytes([f[2], f[3]]) as usize, f.len() - 4);
|
||||||
|
assert_eq!(c.open(d, &f).unwrap(), (42, plain.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match c.seal(0, Direction::ClientToHost, &vec![0; MAX_FRAME_BYTES - FRAME_HEADER_LEN + 1]) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_FRAME_BYTES),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tampering_is_refused() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
let frame = v.bytes("h_rumble_7_frame");
|
||||||
|
let d = Direction::HostToClient;
|
||||||
|
for i in 4..frame.len() {
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[i] ^= 0x01;
|
||||||
|
// seq (4..8) changes the nonce, tag (8..24) and ciphertext (24..) break the tag.
|
||||||
|
assert_err!(c.open(d, &t), Error::Crypto, "byte {i} flipped");
|
||||||
|
}
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[2] ^= 1;
|
||||||
|
assert_err!(c.open(d, &t), Error::Malformed { .. }, "length field");
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[0] = 0x02;
|
||||||
|
assert_err!(c.open(d, &t), Error::UnexpectedValue { .. }, "type field");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_direction_and_wrong_key_are_refused() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
for name in NAMES {
|
||||||
|
let other = match dir(&v, name) {
|
||||||
|
Direction::ClientToHost => Direction::HostToClient,
|
||||||
|
Direction::HostToClient => Direction::ClientToHost,
|
||||||
|
};
|
||||||
|
assert_err!(c.open(other, &v.bytes(&format!("{name}_frame"))), Error::Crypto, "{name} opened the other way");
|
||||||
|
}
|
||||||
|
let mut key = v.arr16("key");
|
||||||
|
key[0] ^= 1;
|
||||||
|
assert_err!(ControlCipher::new(key).open(Direction::HostToClient, &v.bytes("h_rumble_0_frame")), Error::Crypto);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_parser_hostile_sizes() {
|
||||||
|
let frame_of = |total: usize| {
|
||||||
|
let mut f = vec![0x01, 0x00];
|
||||||
|
f.extend_from_slice(&((total - 4) as u16).to_le_bytes());
|
||||||
|
f.resize(total, 0xAB);
|
||||||
|
f
|
||||||
|
};
|
||||||
|
assert_err!(parse_encrypted_frame(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_encrypted_frame(&[0x01]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)[..MIN_FRAME_BYTES - 1]), Error::Truncated { .. });
|
||||||
|
assert_err!(
|
||||||
|
parse_encrypted_frame(&frame_of(FRAME_HEADER_LEN)),
|
||||||
|
Error::Truncated { .. },
|
||||||
|
"no room for a message header"
|
||||||
|
);
|
||||||
|
assert_eq!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)).unwrap().ciphertext.len(), 4);
|
||||||
|
assert_eq!(
|
||||||
|
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES - 1)).unwrap().ciphertext.len(),
|
||||||
|
MAX_FRAME_BYTES - 1 - FRAME_HEADER_LEN
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES)).unwrap().ciphertext.len(),
|
||||||
|
MAX_FRAME_BYTES - FRAME_HEADER_LEN
|
||||||
|
);
|
||||||
|
let mut over = frame_of(MAX_FRAME_BYTES);
|
||||||
|
over.push(0);
|
||||||
|
assert_too_large!(parse_encrypted_frame(&over), MAX_FRAME_BYTES, MAX_FRAME_BYTES + 1);
|
||||||
|
assert_too_large!(parse_encrypted_frame(&vec![1; 1 << 20]), MAX_FRAME_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_parser_lying_lengths() {
|
||||||
|
let mut f = vec![0x01, 0x00, 0, 0, 1, 0, 0, 0];
|
||||||
|
f.extend_from_slice(&[0; 16]);
|
||||||
|
f.extend_from_slice(&[9; 10]);
|
||||||
|
for (len, why) in [
|
||||||
|
(f.len() - 4 + 1, "over by one"),
|
||||||
|
(f.len() - 4 - 1, "under by one"),
|
||||||
|
(0xFFFF, "max"),
|
||||||
|
(0, "zero"),
|
||||||
|
(20, "header only"),
|
||||||
|
] {
|
||||||
|
let mut t = f.clone();
|
||||||
|
t[2..4].copy_from_slice(&(len as u16).to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
let mut t = f.clone();
|
||||||
|
t[0..2].copy_from_slice(&0x0002u16.to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. });
|
||||||
|
t[0..2].copy_from_slice(&0x0100u16.to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. }, "big-endian 0x0001");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ messages
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_split() {
|
||||||
|
let r = parse_message(&msg(0x010b, &[1, 2, 3])).unwrap();
|
||||||
|
assert_eq!(r.message_type, 0x010b);
|
||||||
|
assert_eq!(r.body, &[1, 2, 3]);
|
||||||
|
assert_eq!(parse_message(&msg(0x7777, &[])).unwrap().body, &[] as &[u8]);
|
||||||
|
assert_err!(parse_message(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_message(&[0x0b, 0x01, 0x00]), Error::Truncated { .. });
|
||||||
|
let mut over = msg(0x010b, &[1, 2, 3]);
|
||||||
|
over[2] = 4;
|
||||||
|
assert_err!(parse_message(&over), Error::Malformed { .. }, "length over");
|
||||||
|
let mut under = msg(0x010b, &[1, 2, 3]);
|
||||||
|
under[2] = 2;
|
||||||
|
assert_err!(parse_message(&under), Error::Malformed { .. }, "length under");
|
||||||
|
let mut lie = msg(0x010b, &[1, 2, 3]);
|
||||||
|
lie[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
|
||||||
|
assert_err!(parse_message(&lie), Error::Malformed { .. }, "length 65535");
|
||||||
|
let max = msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 4]);
|
||||||
|
assert_eq!(parse_message(&max).unwrap().body.len(), MAX_MESSAGE_BYTES - 4);
|
||||||
|
assert_too_large!(
|
||||||
|
parse_message(&msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 3])),
|
||||||
|
MAX_MESSAGE_BYTES,
|
||||||
|
MAX_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_type_codes() {
|
||||||
|
for (code, t) in [
|
||||||
|
(0x0305, MessageType::StartA),
|
||||||
|
(0x0307, MessageType::StartB),
|
||||||
|
(0x0301, MessageType::InvalidateRefFrames),
|
||||||
|
(0x0302, MessageType::IdrFrame),
|
||||||
|
(0x0201, MessageType::LossStats),
|
||||||
|
(0x0204, MessageType::FrameStats),
|
||||||
|
(0x0206, MessageType::InputData),
|
||||||
|
(0x0200, MessageType::PeriodicPing),
|
||||||
|
(0x0100, MessageType::Termination),
|
||||||
|
(0x0109, MessageType::TerminationExtended),
|
||||||
|
(0x010e, MessageType::HdrMode),
|
||||||
|
(0x010b, MessageType::RumbleData),
|
||||||
|
(0x5500, MessageType::RumbleTriggers),
|
||||||
|
(0x5501, MessageType::MotionEvent),
|
||||||
|
(0x5502, MessageType::RgbLed),
|
||||||
|
(0x5503, MessageType::TriggerEffect),
|
||||||
|
] {
|
||||||
|
assert_eq!(MessageType::try_from(code), Ok(t), "{code:#06x}");
|
||||||
|
assert_eq!(t as u16, code);
|
||||||
|
}
|
||||||
|
for code in [0u16, 0x0001, 0x0101, 0x5504, 0xFFFF] {
|
||||||
|
assert_err!(MessageType::try_from(code), Error::UnexpectedValue { .. }, "{code:#06x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_messages_from_the_field_tables() {
|
||||||
|
// Host event bodies are taken as little-endian (UNKNOWN U23), except the extended termination code (BE).
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
msg(0x010b, &[0, 0, 0, 0, 0x01, 0x00, 0xFF, 0x7F, 0x00, 0x80]),
|
||||||
|
HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5500, &[0x02, 0x00, 0x34, 0x12, 0xCD, 0xAB]),
|
||||||
|
HostMessage::RumbleTriggers { controller: 2, left: 0x1234, right: 0xABCD },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5501, &[0x03, 0x00, 0xC8, 0x00, 0x01]),
|
||||||
|
HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Accelerometer },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5501, &[0x03, 0x00, 0x00, 0x00, 0x02]),
|
||||||
|
HostMessage::MotionEvent { controller: 3, rate_hz: 0, kind: MotionKind::Gyroscope },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5502, &[0x03, 0x00, 0x10, 0x20, 0xFF]),
|
||||||
|
HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF },
|
||||||
|
),
|
||||||
|
(msg(0x0109, &[0x80, 0x03, 0x00, 0x23]), HostMessage::Termination { error_code: Some(0x8003_0023) }),
|
||||||
|
(msg(0x0109, &[0x00, 0x00, 0x00, 0x01]), HostMessage::Termination { error_code: Some(1) }),
|
||||||
|
(msg(0x0100, &[]), HostMessage::Termination { error_code: None }),
|
||||||
|
(msg(0x010e, &[0x00]), HostMessage::HdrMode { enabled: false, metadata: None }),
|
||||||
|
(msg(0x7777, &[1, 2, 3]), HostMessage::Other { message_type: 0x7777, body_len: 3 }),
|
||||||
|
(msg(0x5503, &[9; 12]), HostMessage::Other { message_type: 0x5503, body_len: 12 }),
|
||||||
|
];
|
||||||
|
for (bytes, want) in cases {
|
||||||
|
assert_eq!(parse_host_message(&bytes), Ok(want.clone()), "{want:?}");
|
||||||
|
}
|
||||||
|
// HDR on with metadata.
|
||||||
|
let mut body = vec![0x01];
|
||||||
|
body.extend((1..=15u16).flat_map(|i| (i * 1000).to_le_bytes()));
|
||||||
|
match parse_host_message(&msg(0x010e, &body)).unwrap() {
|
||||||
|
HostMessage::HdrMode { enabled, metadata } => {
|
||||||
|
assert!(enabled);
|
||||||
|
let m = metadata.expect("31-byte body carries metadata");
|
||||||
|
assert_eq!(m.display_primaries[0], (1000, 2000), "first two u16 are the red primary");
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
// The plaintexts of the .NET vectors are messages too.
|
||||||
|
let v = common::control_vectors();
|
||||||
|
assert_eq!(
|
||||||
|
parse_host_message(&v.bytes("h_termination_ffffffff_plain")),
|
||||||
|
Ok(HostMessage::Termination { error_code: Some(0x8003_0023) })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_messages_with_wrong_bodies() {
|
||||||
|
for (ty, len) in [
|
||||||
|
(0x010b, 9),
|
||||||
|
(0x010b, 11),
|
||||||
|
(0x5500, 5),
|
||||||
|
(0x5500, 7),
|
||||||
|
(0x5501, 4),
|
||||||
|
(0x5501, 6),
|
||||||
|
(0x5502, 4),
|
||||||
|
(0x5502, 6),
|
||||||
|
(0x0109, 3),
|
||||||
|
(0x0109, 5),
|
||||||
|
(0x010e, 0),
|
||||||
|
(0x010e, 10),
|
||||||
|
(0x010e, 32),
|
||||||
|
] {
|
||||||
|
assert_err!(
|
||||||
|
parse_host_message(&msg(ty, &vec![0x01; len])),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{ty:#06x} with {len} bytes"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for kind in [0u8, 3, 0xFF] {
|
||||||
|
assert_err!(
|
||||||
|
parse_host_message(&msg(0x5501, &[0, 0, 1, 0, kind])),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"motion kind {kind}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_err!(parse_host_message(&[0x0b, 0x01]), Error::Truncated { .. });
|
||||||
|
let mut lie = msg(0x010b, &[0; 10]);
|
||||||
|
lie[2] = 200;
|
||||||
|
assert_err!(parse_host_message(&lie), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_messages() {
|
||||||
|
let m = encode_client_message(&ClientMessage::InvalidateRefFrames { first: 5, last: 9 }).unwrap();
|
||||||
|
let mut want = vec![0x01, 0x03, 0x18, 0x00];
|
||||||
|
want.extend_from_slice(&5u32.to_le_bytes());
|
||||||
|
want.extend_from_slice(&[0; 4]);
|
||||||
|
want.extend_from_slice(&9u32.to_le_bytes());
|
||||||
|
want.extend_from_slice(&[0; 12]);
|
||||||
|
assert_eq!(m, want);
|
||||||
|
let ev = InputEvent::MouseMoveRel { dx: -1, dy: 0 };
|
||||||
|
assert_eq!(
|
||||||
|
encode_client_message(&ClientMessage::Input(ev.clone())).unwrap(),
|
||||||
|
domistream::input::encode_input(&ev).unwrap()
|
||||||
|
);
|
||||||
|
// Bodies still UNKNOWN (U10) are refused rather than guessed.
|
||||||
|
for m in [ClientMessage::StartA, ClientMessage::StartB, ClientMessage::PeriodicPing, ClientMessage::RequestIdrFrame]
|
||||||
|
{
|
||||||
|
assert_err!(encode_client_message(&m), Error::Unsupported { .. }, "{m:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..300)) {
|
||||||
|
if let Ok(raw) = parse_message(&data) {
|
||||||
|
prop_assert_eq!(raw.body.len() + 4, data.len());
|
||||||
|
}
|
||||||
|
if let Ok(HostMessage::Other { body_len, .. }) = parse_host_message(&data) {
|
||||||
|
prop_assert_eq!(body_len + 4, data.len());
|
||||||
|
}
|
||||||
|
let _ = parse_encrypted_frame(&data);
|
||||||
|
let _ = ControlCipher::new([3; 16]).open(Direction::HostToClient, &data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn open_never_accepts_random_frames(seq in any::<u32>(), tag in proptest::array::uniform16(any::<u8>()), ct in proptest::collection::vec(any::<u8>(), 4..64)) {
|
||||||
|
let mut f = vec![0x01, 0x00];
|
||||||
|
f.extend_from_slice(&((4 + 16 + ct.len()) as u16).to_le_bytes());
|
||||||
|
f.extend_from_slice(&seq.to_le_bytes());
|
||||||
|
f.extend_from_slice(&tag);
|
||||||
|
f.extend_from_slice(&ct);
|
||||||
|
prop_assert_eq!(ControlCipher::new([3; 16]).open(Direction::HostToClient, &f), Err(Error::Crypto));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ control stream
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"control-test-key";
|
||||||
|
|
||||||
|
fn stream_config() -> ControlConfig {
|
||||||
|
ControlConfig {
|
||||||
|
enet: EnetConfig {
|
||||||
|
channel_count: 1,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
},
|
||||||
|
rikey: KEY,
|
||||||
|
ping_interval: Duration::from_millis(100),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Host {
|
||||||
|
stream: ControlStream,
|
||||||
|
to_client: u16,
|
||||||
|
reliable: u16,
|
||||||
|
now_ms: u64,
|
||||||
|
host: ControlCipher,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Host {
|
||||||
|
fn deliver(&mut self, frame: Vec<u8>) {
|
||||||
|
self.reliable = self.reliable.wrapping_add(1);
|
||||||
|
let c = Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: 0,
|
||||||
|
reliable_sequence: self.reliable,
|
||||||
|
body: CommandBody::SendReliable(frame),
|
||||||
|
};
|
||||||
|
self.now_ms += 1;
|
||||||
|
let d = encode_datagram(&Datagram {
|
||||||
|
peer_id: self.to_client,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(self.now_ms as u16),
|
||||||
|
commands: vec![c],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
self.stream.handle_datagram(Instant::from_micros(self.now_ms * 1000), &d).expect("a well-formed datagram");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver_sealed(&mut self, seq: u32, plain: &[u8]) {
|
||||||
|
let f = self.host.seal(seq, Direction::HostToClient, plain).unwrap();
|
||||||
|
self.deliver(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events(&mut self) -> Vec<ControlEvent> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(e) = self.stream.poll_event() {
|
||||||
|
out.push(e);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frames the client sent on channel 0, opened.
|
||||||
|
fn sent_frames(&mut self) -> Vec<(u32, Vec<u8>)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(d) = self.stream.poll_transmit(Instant::from_micros(self.now_ms * 1000)) {
|
||||||
|
for c in parse_datagram(&d).unwrap().commands {
|
||||||
|
let data = match c.body {
|
||||||
|
CommandBody::SendReliable(data) if c.channel_id == 0 => data,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
out.push(self.host.open(Direction::ClientToHost, &data).expect("the client seals with 'C'"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connected_stream() -> Host {
|
||||||
|
let mut stream =
|
||||||
|
ControlStream::connect(stream_config(), Instant::ZERO, &mut SeqRng::new(11)).expect("ControlStream::connect");
|
||||||
|
let d = parse_datagram(&stream.poll_transmit(Instant::ZERO).expect("connect datagram")).unwrap();
|
||||||
|
let (params, seq) = d
|
||||||
|
.commands
|
||||||
|
.iter()
|
||||||
|
.find_map(|c| match &c.body {
|
||||||
|
CommandBody::Connect { params, .. } => Some((*params, c.reliable_sequence)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("connect");
|
||||||
|
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
|
||||||
|
let reply = encode_datagram(&Datagram {
|
||||||
|
peer_id: params.outgoing_peer_id,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: vec![
|
||||||
|
Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: 0xFF,
|
||||||
|
reliable_sequence: 0,
|
||||||
|
body: CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: seq,
|
||||||
|
received_sent_time: d.sent_time.unwrap_or(0),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: 0xFF,
|
||||||
|
reliable_sequence: 1,
|
||||||
|
body: CommandBody::VerifyConnect(verify),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
stream.handle_datagram(Instant::from_micros(1000), &reply).unwrap();
|
||||||
|
let mut h =
|
||||||
|
Host { stream, to_client: params.outgoing_peer_id, reliable: 0, now_ms: 1, host: ControlCipher::new(KEY) };
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Connected]);
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rumble(controller: u16) -> (Vec<u8>, HostMessage) {
|
||||||
|
(
|
||||||
|
msg(0x010b, &[0, 0, 0, 0, controller as u8, 0, 1, 0, 2, 0]),
|
||||||
|
HostMessage::Rumble { controller, low_frequency: 1, high_frequency: 2 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_frames_in_order_and_with_gaps() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
for (seq, c) in [(0u32, 1u16), (1, 2), (2, 3), (10, 4), (1000, 5)] {
|
||||||
|
let (m, want) = rumble(c);
|
||||||
|
h.deliver_sealed(seq, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)], "seq {seq}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replayed_and_old_host_frames_are_dropped() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
let f5 = h.host.seal(5, Direction::HostToClient, &m).unwrap();
|
||||||
|
h.deliver(f5.clone());
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone())]);
|
||||||
|
// The very same frame again (new ENet command, so ENet itself delivers it): a replay.
|
||||||
|
h.deliver(f5);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "replayed seq 5");
|
||||||
|
// A valid frame with an older or equal number.
|
||||||
|
h.deliver_sealed(3, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "older seq 3");
|
||||||
|
h.deliver_sealed(5, &rumble(9).0);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "equal seq 5, other content");
|
||||||
|
// The stream continues.
|
||||||
|
h.deliver_sealed(6, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tampered_and_reflected_frames_are_dropped() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
let mut bad = h.host.seal(0, Direction::HostToClient, &m).unwrap();
|
||||||
|
bad[30] ^= 0x10;
|
||||||
|
h.deliver(bad);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "bad tag");
|
||||||
|
// A frame sealed client-to-host (an attacker reflecting the client's own traffic).
|
||||||
|
let reflected = h.host.seal(1, Direction::ClientToHost, &m).unwrap();
|
||||||
|
h.deliver(reflected);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong direction");
|
||||||
|
// A frame under another key.
|
||||||
|
let other = ControlCipher::new([0; 16]).seal(2, Direction::HostToClient, &m).unwrap();
|
||||||
|
h.deliver(other);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong key");
|
||||||
|
// Not a frame at all.
|
||||||
|
h.deliver(vec![0xFF; 40]);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "garbage");
|
||||||
|
// A failed frame does not burn its sequence number: seq 0 is still accepted.
|
||||||
|
h.deliver_sealed(0, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_sequence_at_u32_wrap() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
h.deliver_sealed(0xFFFF_FFFE, &m);
|
||||||
|
h.deliver_sealed(0xFFFF_FFFF, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone()), ControlEvent::Message(want)]);
|
||||||
|
// Nothing is greater than u32::MAX: a wrapped 0 is a replay, never accepted.
|
||||||
|
h.deliver_sealed(0, &m);
|
||||||
|
h.deliver_sealed(1, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped, ControlEvent::Dropped]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_frames_count_up_from_zero() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let msgs = [
|
||||||
|
ClientMessage::InvalidateRefFrames { first: 1, last: 2 },
|
||||||
|
ClientMessage::Input(InputEvent::MouseMoveRel { dx: 3, dy: -4 }),
|
||||||
|
ClientMessage::Input(InputEvent::Scroll { amount: 120 }),
|
||||||
|
];
|
||||||
|
for m in &msgs {
|
||||||
|
h.stream.send(Instant::from_micros(2000), m).unwrap();
|
||||||
|
}
|
||||||
|
let sent = h.sent_frames();
|
||||||
|
assert_eq!(sent.len(), msgs.len());
|
||||||
|
for (i, ((seq, plain), m)) in sent.iter().zip(&msgs).enumerate() {
|
||||||
|
assert_eq!(*seq, i as u32, "sequence numbers start at 0 and never repeat (U11)");
|
||||||
|
assert_eq!(plain, &encode_client_message(m).unwrap());
|
||||||
|
}
|
||||||
|
assert_err!(h.stream.send(Instant::from_micros(2000), &ClientMessage::StartA), Error::Unsupported { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_stream_refuses() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
h.stream.close(Instant::from_micros(3000)).unwrap();
|
||||||
|
assert_err!(h.stream.close(Instant::from_micros(3001)), Error::Closed);
|
||||||
|
}
|
||||||
@@ -0,0 +1,811 @@
|
|||||||
|
//! ENet (`docs/PROTOCOL.md` 3.1): the datagram codec against byte vectors built from the field definitions, hostile
|
||||||
|
//! datagrams, and the client peer driven by a scripted host: handshake, reliable sequence numbers at the 0xFFFF
|
||||||
|
//! wrap, duplicates, far-future and far-past, fragments with lying lengths, retransmission and timeouts.
|
||||||
|
|
||||||
|
#![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::enet::protocol::{
|
||||||
|
Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, NO_PEER_ID,
|
||||||
|
encode_datagram, parse_datagram,
|
||||||
|
};
|
||||||
|
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
// ================================================================================================ codec vectors
|
||||||
|
|
||||||
|
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
|
||||||
|
Command { acknowledge, channel_id, reliable_sequence, body }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ping_vector() {
|
||||||
|
// peer 1, session 0, sent-time flag; ping with acknowledge flag on channel 0xFF, reliable sequence 1.
|
||||||
|
let bytes = [0x80, 0x01, 0x12, 0x34, 0x85, 0xFF, 0x00, 0x01];
|
||||||
|
let want = Datagram {
|
||||||
|
peer_id: 1,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(0x1234),
|
||||||
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), want);
|
||||||
|
assert_eq!(encode_datagram(&want).unwrap(), bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn acknowledge_reliable_disconnect_vectors() {
|
||||||
|
// peer 0xABC, session 2, no sent time: 0x2ABC.
|
||||||
|
let mut bytes = vec![0x2A, 0xBC];
|
||||||
|
bytes.extend_from_slice(&[0x01, 0x00, 0x00, 0x05, 0x00, 0x07, 0x12, 0x34]); // acknowledge (8)
|
||||||
|
bytes.extend_from_slice(&[0x86, 0x00, 0x00, 0x02, 0x00, 0x03, 0xAA, 0xBB, 0xCC]); // send reliable (6 + 3)
|
||||||
|
bytes.extend_from_slice(&[0x84, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2A]); // disconnect (8)
|
||||||
|
let want = Datagram {
|
||||||
|
peer_id: 0x0ABC,
|
||||||
|
session_id: 2,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![
|
||||||
|
cmd(false, 0, 5, CommandBody::Acknowledge { received_reliable_sequence: 7, received_sent_time: 0x1234 }),
|
||||||
|
cmd(true, 0, 2, CommandBody::SendReliable(vec![0xAA, 0xBB, 0xCC])),
|
||||||
|
cmd(true, 0xFF, 3, CommandBody::Disconnect { data: 42 }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), want);
|
||||||
|
assert_eq!(encode_datagram(&want).unwrap(), bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn params(connect_id: u32) -> ConnectParams {
|
||||||
|
ConnectParams {
|
||||||
|
outgoing_peer_id: 3,
|
||||||
|
incoming_session_id: 0xFF,
|
||||||
|
outgoing_session_id: 0xFF,
|
||||||
|
mtu: 1400,
|
||||||
|
window_size: 32768,
|
||||||
|
channel_count: 2,
|
||||||
|
incoming_bandwidth: 0,
|
||||||
|
outgoing_bandwidth: 0,
|
||||||
|
packet_throttle_interval: 5000,
|
||||||
|
packet_throttle_acceleration: 2,
|
||||||
|
packet_throttle_deceleration: 2,
|
||||||
|
connect_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec<u8>) -> Fragment {
|
||||||
|
Fragment {
|
||||||
|
start_sequence: start,
|
||||||
|
fragment_count: count,
|
||||||
|
fragment_number: number,
|
||||||
|
total_length: total,
|
||||||
|
fragment_offset: offset,
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every command kind, with the total size PROTOCOL.md 3.1 gives for it.
|
||||||
|
fn every_command() -> Vec<(Command, usize)> {
|
||||||
|
vec![
|
||||||
|
(cmd(false, 0, 1, CommandBody::Acknowledge { received_reliable_sequence: 9, received_sent_time: 77 }), 8),
|
||||||
|
(cmd(true, 0xFF, 1, CommandBody::Connect { params: params(0xDEAD_BEEF), data: 0x1234_5678 }), 48),
|
||||||
|
(cmd(true, 0xFF, 1, CommandBody::VerifyConnect(params(0xDEAD_BEEF))), 44),
|
||||||
|
(cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 0 }), 8),
|
||||||
|
(cmd(true, 0xFF, 3, CommandBody::Ping), 4),
|
||||||
|
(cmd(true, 0, 4, CommandBody::SendReliable(vec![1, 2, 3, 4, 5])), 6 + 5),
|
||||||
|
(cmd(false, 1, 4, CommandBody::SendUnreliable { unreliable_sequence: 0xFFFF, data: vec![9; 7] }), 8 + 7),
|
||||||
|
(cmd(true, 0, 5, CommandBody::SendFragment(frag(5, 2, 0, 20, 0, vec![1; 10]))), 24 + 10),
|
||||||
|
(cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 513, data: vec![3; 2] }), 8 + 2),
|
||||||
|
(cmd(true, 0xFF, 6, CommandBody::BandwidthLimit { incoming: 1, outgoing: 2 }), 12),
|
||||||
|
(cmd(true, 0xFF, 7, CommandBody::ThrottleConfigure { interval: 5000, acceleration: 2, deceleration: 2 }), 16),
|
||||||
|
(cmd(false, 0, 8, CommandBody::SendUnreliableFragment(frag(8, 3, 2, 30, 20, vec![4; 10]))), 24 + 10),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_command_round_trips_with_its_wire_size() {
|
||||||
|
for (c, size) in every_command() {
|
||||||
|
for sent_time in [None, Some(0xBEEF)] {
|
||||||
|
let d = Datagram { peer_id: 7, session_id: 1, sent_time, commands: vec![c.clone()] };
|
||||||
|
let bytes = encode_datagram(&d).unwrap();
|
||||||
|
let header = if sent_time.is_some() { 4 } else { 2 };
|
||||||
|
assert_eq!(bytes.len(), header + size, "{:?}", c.body);
|
||||||
|
assert_eq!(bytes[header] & 0x0F, kind(&c.body), "command number of {:?}", c.body);
|
||||||
|
assert_eq!(bytes[header] & 0x80 != 0, c.acknowledge);
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let all = Datagram {
|
||||||
|
peer_id: 0x0FFF,
|
||||||
|
session_id: 3,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: every_command().into_iter().map(|(c, _)| c).collect(),
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&encode_datagram(&all).unwrap()).unwrap(), all);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind(b: &CommandBody) -> u8 {
|
||||||
|
match b {
|
||||||
|
CommandBody::Acknowledge { .. } => 1,
|
||||||
|
CommandBody::Connect { .. } => 2,
|
||||||
|
CommandBody::VerifyConnect(_) => 3,
|
||||||
|
CommandBody::Disconnect { .. } => 4,
|
||||||
|
CommandBody::Ping => 5,
|
||||||
|
CommandBody::SendReliable(_) => 6,
|
||||||
|
CommandBody::SendUnreliable { .. } => 7,
|
||||||
|
CommandBody::SendFragment(_) => 8,
|
||||||
|
CommandBody::SendUnsequenced { .. } => 9,
|
||||||
|
CommandBody::BandwidthLimit { .. } => 10,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => 11,
|
||||||
|
CommandBody::SendUnreliableFragment(_) => 12,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsequenced_carries_its_flag() {
|
||||||
|
let d = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })],
|
||||||
|
};
|
||||||
|
let bytes = encode_datagram(&d).unwrap();
|
||||||
|
assert_eq!(bytes[2] & 0x40, 0x40, "unsequenced flag");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ hostile datagrams
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_truncation() {
|
||||||
|
for (bad, why) in [
|
||||||
|
(&[][..], "empty"),
|
||||||
|
(&[0x00][..], "one byte"),
|
||||||
|
(&[0x80, 0x01, 0x12][..], "sent-time flag, cut sent time"),
|
||||||
|
(&[0x00, 0x01, 0x85, 0xFF, 0x00][..], "cut command header"),
|
||||||
|
(&[0x00, 0x01, 0x01, 0x00, 0x00, 0x05, 0x00, 0x07][..], "cut acknowledge"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00][..], "cut data length"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x0A, 1, 2, 3][..], "data length over"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1][..], "data length 65535"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x01, 1, 2, 3][..], "data length under: 2 stray bytes"),
|
||||||
|
] {
|
||||||
|
assert_err!(parse_datagram(bad), Error::Truncated { .. }, "{why}");
|
||||||
|
}
|
||||||
|
// A connect cut at every length.
|
||||||
|
let full = encode_datagram(&Datagram {
|
||||||
|
peer_id: NO_PEER_ID,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(0),
|
||||||
|
commands: vec![every_command()[1].0.clone()],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
for cut in 5..full.len() {
|
||||||
|
assert_err!(parse_datagram(&full[..cut]), Error::Truncated { .. }, "connect cut at {cut}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_values() {
|
||||||
|
assert_err!(parse_datagram(&[0x40, 0x01, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed");
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"compressed + time"
|
||||||
|
);
|
||||||
|
for number in [0u8, 13, 14, 15] {
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"command {number}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A good command followed by an unknown one: the whole datagram is refused.
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]),
|
||||||
|
Error::UnexpectedValue { .. }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_sizes() {
|
||||||
|
let ping = [0x85, 0xFF, 0x00, 0x01];
|
||||||
|
let pings = |n: usize| {
|
||||||
|
let mut b = vec![0x00, 0x01];
|
||||||
|
for _ in 0..n {
|
||||||
|
b.extend_from_slice(&ping);
|
||||||
|
}
|
||||||
|
b
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM)).unwrap().commands.len(), MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
match parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM + 1)) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_COMMANDS_PER_DATAGRAM),
|
||||||
|
other => panic!("33 commands: {other:?}"),
|
||||||
|
}
|
||||||
|
// A reliable packet filling the datagram exactly; one byte more is over.
|
||||||
|
let reliable = |data: usize| {
|
||||||
|
let mut b = vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01];
|
||||||
|
b.extend_from_slice(&(data as u16).to_be_bytes());
|
||||||
|
b.extend(std::iter::repeat_n(0x5A, data));
|
||||||
|
b
|
||||||
|
};
|
||||||
|
let max_data = MAX_DATAGRAM_BYTES - 8;
|
||||||
|
assert_eq!(reliable(max_data).len(), MAX_DATAGRAM_BYTES);
|
||||||
|
assert!(parse_datagram(&reliable(max_data)).is_ok());
|
||||||
|
assert_eq!(parse_datagram(&reliable(max_data - 1)).unwrap().commands.len(), 1);
|
||||||
|
assert_too_large!(parse_datagram(&reliable(max_data + 1)), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1);
|
||||||
|
assert_too_large!(parse_datagram(&vec![0; 1 << 20]), MAX_DATAGRAM_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_refuses_oversized() {
|
||||||
|
let many = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1],
|
||||||
|
};
|
||||||
|
assert!(matches!(encode_datagram(&many), Err(Error::TooLarge { .. })));
|
||||||
|
let big = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))],
|
||||||
|
};
|
||||||
|
assert!(matches!(encode_datagram(&big), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body() -> impl Strategy<Value = CommandBody> {
|
||||||
|
let data = || proptest::collection::vec(any::<u8>(), 0..64);
|
||||||
|
let fragment = || {
|
||||||
|
(any::<u16>(), any::<u32>(), any::<u32>(), any::<u32>(), any::<u32>(), data())
|
||||||
|
.prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f))
|
||||||
|
};
|
||||||
|
let cparams = || {
|
||||||
|
proptest::array::uniform12(any::<u32>()).prop_map(|a| ConnectParams {
|
||||||
|
outgoing_peer_id: (a[0] & 0xFFFF) as u16,
|
||||||
|
incoming_session_id: a[1] as u8,
|
||||||
|
outgoing_session_id: (a[1] >> 8) as u8,
|
||||||
|
mtu: a[2],
|
||||||
|
window_size: a[3],
|
||||||
|
channel_count: a[4],
|
||||||
|
incoming_bandwidth: a[5],
|
||||||
|
outgoing_bandwidth: a[6],
|
||||||
|
packet_throttle_interval: a[7],
|
||||||
|
packet_throttle_acceleration: a[8],
|
||||||
|
packet_throttle_deceleration: a[9],
|
||||||
|
connect_id: a[10],
|
||||||
|
})
|
||||||
|
};
|
||||||
|
prop_oneof![
|
||||||
|
(any::<u16>(), any::<u16>())
|
||||||
|
.prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }),
|
||||||
|
(cparams(), any::<u32>()).prop_map(|(params, data)| CommandBody::Connect { params, data }),
|
||||||
|
cparams().prop_map(CommandBody::VerifyConnect),
|
||||||
|
any::<u32>().prop_map(|data| CommandBody::Disconnect { data }),
|
||||||
|
Just(CommandBody::Ping),
|
||||||
|
data().prop_map(CommandBody::SendReliable),
|
||||||
|
(any::<u16>(), data())
|
||||||
|
.prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }),
|
||||||
|
fragment().prop_map(CommandBody::SendFragment),
|
||||||
|
(any::<u16>(), data())
|
||||||
|
.prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }),
|
||||||
|
(any::<u32>(), any::<u32>())
|
||||||
|
.prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }),
|
||||||
|
(any::<u32>(), any::<u32>(), any::<u32>()).prop_map(|(interval, acceleration, deceleration)| {
|
||||||
|
CommandBody::ThrottleConfigure { interval, acceleration, deceleration }
|
||||||
|
}),
|
||||||
|
fragment().prop_map(CommandBody::SendUnreliableFragment),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datagram_round_trip(
|
||||||
|
peer_id in 0u16..=0x0FFF,
|
||||||
|
session_id in 0u8..4,
|
||||||
|
sent_time in proptest::option::of(any::<u16>()),
|
||||||
|
commands in proptest::collection::vec((any::<bool>(), any::<u8>(), any::<u16>(), body()), 1..8),
|
||||||
|
) {
|
||||||
|
let commands = commands.into_iter().map(|(a, ch, s, b)| cmd(a, ch, s, b)).collect();
|
||||||
|
let d = Datagram { peer_id, session_id, sent_time, commands };
|
||||||
|
let bytes = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
prop_assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
prop_assert_eq!(parse_datagram(&bytes), Ok(d));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes: no panic; a parsed datagram re-encodes to something that parses to the same value.
|
||||||
|
#[test]
|
||||||
|
fn datagram_parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..512)) {
|
||||||
|
if let Ok(d) = parse_datagram(&data) {
|
||||||
|
prop_assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
prop_assert!(d.peer_id <= 0x0FFF && d.session_id < 4);
|
||||||
|
let again = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
prop_assert_eq!(parse_datagram(&again), Ok(d));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ client peer
|
||||||
|
|
||||||
|
fn config() -> EnetConfig {
|
||||||
|
EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0x0000_1234,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(ms: u64) -> Instant {
|
||||||
|
Instant::from_micros(ms * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client and the scripted host's view of it.
|
||||||
|
struct Link {
|
||||||
|
client: EnetClient,
|
||||||
|
/// Peer id the host addresses the client with (from the client's connect).
|
||||||
|
to_client: u16,
|
||||||
|
/// Next reliable sequence the host uses per channel.
|
||||||
|
host_seq: [u16; 256],
|
||||||
|
now_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Link {
|
||||||
|
fn host_datagram(&self, commands: Vec<Command>) -> Vec<u8> {
|
||||||
|
encode_datagram(&Datagram {
|
||||||
|
peer_id: self.to_client,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(self.now_ms as u16),
|
||||||
|
commands,
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn feed(&mut self, commands: Vec<Command>) -> domistream::Result<()> {
|
||||||
|
self.now_ms += 1;
|
||||||
|
let d = self.host_datagram(commands);
|
||||||
|
self.client.handle_datagram(at(self.now_ms), &d)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reliable(&mut self, channel: u8, data: &[u8]) -> Command {
|
||||||
|
let s = &mut self.host_seq[usize::from(channel)];
|
||||||
|
*s = s.wrapping_add(1);
|
||||||
|
cmd(true, channel, *s, CommandBody::SendReliable(data.to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the client wants to send now, parsed.
|
||||||
|
fn transmitted(&mut self) -> Vec<Datagram> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(d) = self.client.poll_transmit(at(self.now_ms)) {
|
||||||
|
assert!(d.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
out.push(parse_datagram(&d).expect("the client's datagrams parse"));
|
||||||
|
assert!(out.len() < 10_000, "poll_transmit never ends");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events(&mut self) -> Vec<EnetEvent> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(e) = self.client.poll_event() {
|
||||||
|
out.push(e);
|
||||||
|
assert!(out.len() < 100_000, "poll_event never ends");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn received(&mut self) -> Vec<Vec<u8>> {
|
||||||
|
self.events()
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| match e {
|
||||||
|
EnetEvent::Received { data, .. } => data,
|
||||||
|
other => panic!("unexpected event {other:?}"),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a client and returns it with its connect command.
|
||||||
|
fn start() -> (EnetClient, Datagram, ConnectParams, u32, u16) {
|
||||||
|
let mut client = EnetClient::connect(config(), at(0), &mut SeqRng::new(5)).expect("EnetClient::connect");
|
||||||
|
assert_eq!(client.state(), EnetState::Connecting);
|
||||||
|
let d = parse_datagram(&client.poll_transmit(at(0)).expect("connect datagram")).unwrap();
|
||||||
|
let c =
|
||||||
|
d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone();
|
||||||
|
let (params, data) = match c.body {
|
||||||
|
CommandBody::Connect { params, data } => (params, data),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
(client, d.clone(), params, data, c.reliable_sequence)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A connected link: connect, then the host's acknowledge + verify connect.
|
||||||
|
fn connected() -> Link {
|
||||||
|
let (client, d, params, _, connect_seq) = start();
|
||||||
|
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
|
||||||
|
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
|
||||||
|
link.feed(vec![
|
||||||
|
cmd(
|
||||||
|
false,
|
||||||
|
0xFF,
|
||||||
|
0,
|
||||||
|
CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: connect_seq,
|
||||||
|
received_sent_time: d.sent_time.unwrap_or(0),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify)),
|
||||||
|
])
|
||||||
|
.expect("verify connect");
|
||||||
|
assert_eq!(link.events(), vec![EnetEvent::Connected]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
link.transmitted();
|
||||||
|
link
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn connect_offers_the_config() {
|
||||||
|
let (_, d, params, data, _) = start();
|
||||||
|
assert_eq!(d.peer_id, NO_PEER_ID, "no peer id yet");
|
||||||
|
assert_eq!(params.mtu, u32::from(config().mtu));
|
||||||
|
assert_eq!(params.channel_count, u32::from(config().channel_count));
|
||||||
|
assert_eq!(data, config().connect_data);
|
||||||
|
let c = &d.commands[0];
|
||||||
|
assert!(c.acknowledge && c.channel_id == 0xFF, "connect is reliable, connection-level");
|
||||||
|
// The connect id comes from the caller's randomness.
|
||||||
|
let (_, _, p2, _, _) = start();
|
||||||
|
assert_eq!(p2.connect_id, params.connect_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn connect_refuses_configs_outside_enet_limits() {
|
||||||
|
for bad in [
|
||||||
|
EnetConfig { mtu: 575, ..config() },
|
||||||
|
EnetConfig { mtu: 4097, ..config() },
|
||||||
|
EnetConfig { mtu: 0, ..config() },
|
||||||
|
EnetConfig { channel_count: 0, ..config() },
|
||||||
|
] {
|
||||||
|
assert_err!(EnetClient::connect(bad, at(0), &mut SeqRng::new(1)), Error::Malformed { .. }, "{bad:?}");
|
||||||
|
}
|
||||||
|
for ok in [
|
||||||
|
EnetConfig { mtu: 576, ..config() },
|
||||||
|
EnetConfig { mtu: 4096, ..config() },
|
||||||
|
EnetConfig { channel_count: 255, ..config() },
|
||||||
|
] {
|
||||||
|
assert!(EnetClient::connect(ok, at(0), &mut SeqRng::new(1)).is_ok(), "{ok:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_with_wrong_connect_id_does_not_connect() {
|
||||||
|
let (client, _, params, _, _) = start();
|
||||||
|
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
|
||||||
|
let verify = ConnectParams {
|
||||||
|
connect_id: params.connect_id ^ 1,
|
||||||
|
outgoing_peer_id: 0,
|
||||||
|
incoming_session_id: 0,
|
||||||
|
outgoing_session_id: 0,
|
||||||
|
..params
|
||||||
|
};
|
||||||
|
let _ = link.feed(vec![cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connecting);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn garbage_never_changes_state() {
|
||||||
|
let mut link = connected();
|
||||||
|
for bad in [&[][..], &[0x00][..], &[0x40, 0x00, 0x85, 0xFF, 0, 1][..], &[0x00, 0x00, 0x8F, 0, 0, 0][..]] {
|
||||||
|
assert!(link.client.handle_datagram(at(5), bad).is_err(), "{bad:?}");
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
|
||||||
|
MAX_DATAGRAM_BYTES,
|
||||||
|
MAX_DATAGRAM_BYTES + 1
|
||||||
|
);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datagrams_for_another_peer_are_dropped() {
|
||||||
|
let mut link = connected();
|
||||||
|
let c = link.reliable(0, b"not for you");
|
||||||
|
let other = encode_datagram(&Datagram {
|
||||||
|
peer_id: link.to_client ^ 0x0001,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: vec![c],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(link.client.handle_datagram(at(9), &other), Ok(()));
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_in_order_reordered_and_duplicated() {
|
||||||
|
let mut link = connected();
|
||||||
|
let a = link.reliable(0, b"one");
|
||||||
|
let b = link.reliable(0, b"two");
|
||||||
|
let c = link.reliable(0, b"three");
|
||||||
|
link.feed(vec![c.clone()]).unwrap();
|
||||||
|
link.feed(vec![b.clone()]).unwrap();
|
||||||
|
assert!(link.received().is_empty(), "nothing before sequence 1");
|
||||||
|
link.feed(vec![a.clone()]).unwrap();
|
||||||
|
assert_eq!(link.received(), vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]);
|
||||||
|
// Duplicates (retransmissions by the host) are acknowledged but never delivered twice.
|
||||||
|
link.feed(vec![a, b.clone(), c]).unwrap();
|
||||||
|
link.feed(vec![b]).unwrap();
|
||||||
|
assert!(link.received().is_empty());
|
||||||
|
let acks: usize = link
|
||||||
|
.transmitted()
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
|
||||||
|
.count();
|
||||||
|
assert!(acks >= 4, "duplicates are still acknowledged ({acks})");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_sequence_wraps_at_0xffff() {
|
||||||
|
// 70 000 reliable packets, one per datagram: the sequence passes 0xFFFF -> 0 and order is kept.
|
||||||
|
let mut link = connected();
|
||||||
|
let total = 70_000u32;
|
||||||
|
let mut got = 0u32;
|
||||||
|
for i in 0..total {
|
||||||
|
let c = link.reliable(0, &i.to_le_bytes());
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
for data in link.received() {
|
||||||
|
assert_eq!(data, got.to_le_bytes(), "packet {got} out of order");
|
||||||
|
got += 1;
|
||||||
|
}
|
||||||
|
link.transmitted();
|
||||||
|
}
|
||||||
|
assert_eq!(got, total);
|
||||||
|
assert_eq!(link.host_seq[0], (total % 65_536) as u16);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_future_and_far_past_are_dropped() {
|
||||||
|
let mut link = connected();
|
||||||
|
for i in 0..10u8 {
|
||||||
|
let c = link.reliable(0, &[i]);
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(link.received().len(), 10);
|
||||||
|
let next = link.host_seq[0];
|
||||||
|
for seq in [next.wrapping_add(40_000), next.wrapping_add(0x8000), next.wrapping_sub(30_000), next.wrapping_sub(5)] {
|
||||||
|
let _ = link.feed(vec![cmd(true, 0, seq, CommandBody::SendReliable(b"evil".to_vec()))]);
|
||||||
|
assert!(link.received().is_empty(), "sequence {seq} (next {next}) must not be delivered");
|
||||||
|
}
|
||||||
|
// The stream continues normally.
|
||||||
|
let c = link.reliable(0, b"ok");
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
assert_eq!(link.received(), vec![b"ok".to_vec()]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn channels_outside_the_negotiated_count_are_not_delivered() {
|
||||||
|
let mut link = connected();
|
||||||
|
let c = link.reliable(200, b"x");
|
||||||
|
let _ = link.feed(vec![c]);
|
||||||
|
assert!(link.received().is_empty());
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec<Command> {
|
||||||
|
let count = data.len().div_ceil(piece) as u32;
|
||||||
|
let start = link.host_seq[0].wrapping_add(1);
|
||||||
|
(0..count)
|
||||||
|
.map(|n| {
|
||||||
|
link.host_seq[0] = link.host_seq[0].wrapping_add(1);
|
||||||
|
let off = n as usize * piece;
|
||||||
|
let chunk = data[off..(off + piece).min(data.len())].to_vec();
|
||||||
|
cmd(
|
||||||
|
true,
|
||||||
|
0,
|
||||||
|
link.host_seq[0],
|
||||||
|
CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fragments_reassemble_in_any_order() {
|
||||||
|
let mut link = connected();
|
||||||
|
let data: Vec<u8> = (0..3000u32).map(|i| (i * 7) as u8).collect();
|
||||||
|
let mut frags = fragments(&mut link, &data, 1000);
|
||||||
|
frags.swap(0, 2);
|
||||||
|
for f in frags {
|
||||||
|
link.feed(vec![f]).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(link.received(), vec![data]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fragments_with_lying_lengths() {
|
||||||
|
// Total length over the reassembly cap.
|
||||||
|
let mut link = connected();
|
||||||
|
link.host_seq[0] += 1;
|
||||||
|
let s = link.host_seq[0];
|
||||||
|
let r = link.feed(vec![cmd(
|
||||||
|
true,
|
||||||
|
0,
|
||||||
|
s,
|
||||||
|
CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])),
|
||||||
|
)]);
|
||||||
|
assert_too_large!(r, MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
|
||||||
|
// Other lies: never delivered, never a panic, the connection survives.
|
||||||
|
for f in [
|
||||||
|
frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments
|
||||||
|
frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count
|
||||||
|
frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total
|
||||||
|
frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total
|
||||||
|
frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total
|
||||||
|
frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total
|
||||||
|
frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow
|
||||||
|
] {
|
||||||
|
let mut link = connected();
|
||||||
|
link.host_seq[0] += 1;
|
||||||
|
let s = link.host_seq[0];
|
||||||
|
let r =
|
||||||
|
link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]);
|
||||||
|
assert!(link.events().is_empty(), "{f:?} -> {r:?}");
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected, "{f:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn send_rules() {
|
||||||
|
let (mut client, ..) = start();
|
||||||
|
assert_err!(client.send(at(1), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before connected");
|
||||||
|
let mut link = connected();
|
||||||
|
assert_err!(link.client.send(at(2), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
|
||||||
|
assert_err!(link.client.send(at(2), 255, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. });
|
||||||
|
match link.client.send(at(2), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_PACKET_BYTES),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn send_queue_is_capped() {
|
||||||
|
let mut link = connected();
|
||||||
|
for i in 0..MAX_SEND_QUEUE {
|
||||||
|
link.client.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
|
||||||
|
}
|
||||||
|
match link.client.send(at(3), 0, Delivery::Reliable, b"one too many") {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_sends_are_fragmented_within_the_mtu() {
|
||||||
|
let mut link = connected();
|
||||||
|
let data: Vec<u8> = (0..5000u32).map(|i| i as u8).collect();
|
||||||
|
link.client.send(at(4), 1, Delivery::Reliable, &data).unwrap();
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
while let Some(d) = link.client.poll_transmit(at(4)) {
|
||||||
|
assert!(d.len() <= usize::from(config().mtu), "datagram of {} over the MTU", d.len());
|
||||||
|
for c in parse_datagram(&d).unwrap().commands {
|
||||||
|
if let CommandBody::SendFragment(f) = c.body {
|
||||||
|
assert_eq!(c.channel_id, 1);
|
||||||
|
assert_eq!(f.total_length, 5000);
|
||||||
|
pieces.push(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pieces.sort_by_key(|f| f.fragment_number);
|
||||||
|
assert_eq!(pieces.len() as u32, pieces[0].fragment_count);
|
||||||
|
let mut whole = vec![0u8; 5000];
|
||||||
|
for f in &pieces {
|
||||||
|
whole[f.fragment_offset as usize..f.fragment_offset as usize + f.data.len()].copy_from_slice(&f.data);
|
||||||
|
}
|
||||||
|
assert_eq!(whole, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_sends_are_retransmitted_until_acknowledged() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.send(at(10), 0, Delivery::Reliable, b"hello").unwrap();
|
||||||
|
let first = link.transmitted();
|
||||||
|
let sent = first
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec()))
|
||||||
|
.expect("sent")
|
||||||
|
.clone();
|
||||||
|
let when = link.client.poll_timeout().expect("a retransmission deadline");
|
||||||
|
link.now_ms = when.as_micros() / 1000 + 1;
|
||||||
|
link.client.handle_timeout(at(link.now_ms)).unwrap();
|
||||||
|
let again = link.transmitted();
|
||||||
|
assert!(
|
||||||
|
again
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body),
|
||||||
|
"retransmitted"
|
||||||
|
);
|
||||||
|
// Acknowledge it: no more retransmissions of that command.
|
||||||
|
link.feed(vec![cmd(
|
||||||
|
false,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 },
|
||||||
|
)])
|
||||||
|
.unwrap();
|
||||||
|
for _ in 0..5 {
|
||||||
|
if let Some(t) = link.client.poll_timeout() {
|
||||||
|
link.now_ms = link.now_ms.max(t.as_micros() / 1000 + 1);
|
||||||
|
link.client.handle_timeout(at(link.now_ms)).unwrap();
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body),
|
||||||
|
"acknowledged command sent again"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn silence_times_out() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.send(at(1), 0, Delivery::Reliable, b"anyone?").unwrap();
|
||||||
|
let end = at(1 + config().timeout.as_millis() as u64 * 4);
|
||||||
|
let mut guard = 0;
|
||||||
|
while link.client.state() != EnetState::Disconnected {
|
||||||
|
let t = link.client.poll_timeout().expect("a deadline while waiting for an acknowledgement");
|
||||||
|
assert!(t <= end, "no timeout by {end:?}");
|
||||||
|
link.client.handle_timeout(t).unwrap();
|
||||||
|
let _ = link.client.poll_transmit(t);
|
||||||
|
guard += 1;
|
||||||
|
assert!(guard < 10_000);
|
||||||
|
}
|
||||||
|
assert!(link.events().contains(&EnetEvent::TimedOut));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_disconnect_closes() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.feed(vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 7 })]).unwrap();
|
||||||
|
assert_eq!(link.events(), vec![EnetEvent::Disconnected { data: 7 }]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Disconnected);
|
||||||
|
let c = link.reliable(0, b"late");
|
||||||
|
assert_err!(link.feed(vec![c]), Error::Closed);
|
||||||
|
assert_err!(link.client.disconnect(at(100), 0), Error::Closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_disconnect() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.disconnect(at(5), 9).unwrap();
|
||||||
|
assert_eq!(link.client.state(), EnetState::Disconnecting);
|
||||||
|
let sent = link.transmitted();
|
||||||
|
assert!(sent.iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Disconnect { data: 9 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// A connected client fed arbitrary datagrams never panics and never leaves Connected without a reason.
|
||||||
|
#[test]
|
||||||
|
fn client_survives_arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..200), 1..20)) {
|
||||||
|
let mut link = connected();
|
||||||
|
for d in datagrams {
|
||||||
|
let _ = link.client.handle_datagram(at(7), &d);
|
||||||
|
while link.client.poll_transmit(at(7)).is_some() {}
|
||||||
|
for e in link.events() {
|
||||||
|
if let EnetEvent::Received { data, .. } = e {
|
||||||
|
prop_assert!(data.len() <= MAX_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
//! Reed-Solomon over GF(2^8) / 0x11D (`docs/PROTOCOL.md` 5.3, 6.4). The video construction is UNKNOWN U14, so the
|
||||||
|
//! tests check what any correct systematic MDS code must do: data passes through, every erasure pattern of at most
|
||||||
|
//! `m` shards is rebuilt byte-exact, more than `m` is refused. With an explicit matrix
|
||||||
|
//! (`with_parity_matrix`, a Cauchy matrix computed by the independent GF(2^8) reference in `common::gf`), the parity
|
||||||
|
//! bytes themselves are checked.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{SeqRng, gf};
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::fec::{MAX_SHARD_BYTES, MAX_SHARDS, ReedSolomon, parity_count};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
fn data_shards(rng: &mut SeqRng, k: usize, len: usize) -> Vec<Vec<u8>> {
|
||||||
|
(0..k).map(|_| rng.bytes(len)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes `data` with `code`: data shards plus zeroed parity buffers, filled in place.
|
||||||
|
fn encoded(code: &ReedSolomon, data: &[Vec<u8>]) -> Vec<Vec<u8>> {
|
||||||
|
let len = data[0].len();
|
||||||
|
let mut shards: Vec<Vec<u8>> = data.to_vec();
|
||||||
|
shards.extend((0..code.parity_shards()).map(|_| vec![0u8; len]));
|
||||||
|
code.encode(&mut shards).expect("encode");
|
||||||
|
assert_eq!(&shards[..data.len()], data, "systematic: data shards pass through unchanged");
|
||||||
|
shards
|
||||||
|
}
|
||||||
|
|
||||||
|
fn erase(shards: &[Vec<u8>], lost: &[usize]) -> Vec<Option<Vec<u8>>> {
|
||||||
|
shards.iter().enumerate().map(|(i, s)| if lost.contains(&i) { None } else { Some(s.clone()) }).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_recovers(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
|
||||||
|
let mut s = erase(full, lost);
|
||||||
|
code.reconstruct(&mut s)
|
||||||
|
.unwrap_or_else(|e| panic!("k={} m={} lost {lost:?}: {e:?}", code.data_shards(), code.parity_shards()));
|
||||||
|
for (i, (got, want)) in s.iter().zip(full).enumerate() {
|
||||||
|
assert_eq!(
|
||||||
|
got.as_deref(),
|
||||||
|
Some(want.as_slice()),
|
||||||
|
"k={} m={} lost {lost:?}: shard {i}",
|
||||||
|
code.data_shards(),
|
||||||
|
code.parity_shards()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_refuses(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
|
||||||
|
let mut s = erase(full, lost);
|
||||||
|
assert_err!(
|
||||||
|
code.reconstruct(&mut s),
|
||||||
|
Error::Truncated { .. },
|
||||||
|
"k={} m={} lost {lost:?}",
|
||||||
|
code.data_shards(),
|
||||||
|
code.parity_shards()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subsets(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||||||
|
common::subsets_of(n, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ parameters
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parity_counts() {
|
||||||
|
for (k, pct, m) in [
|
||||||
|
(4usize, 50u8, 2usize),
|
||||||
|
(1, 1, 1),
|
||||||
|
(1, 100, 1),
|
||||||
|
(10, 0, 0),
|
||||||
|
(100, 100, 100),
|
||||||
|
(3, 33, 1),
|
||||||
|
(3, 34, 2),
|
||||||
|
(7, 20, 2),
|
||||||
|
(127, 100, 127),
|
||||||
|
(255, 0, 0),
|
||||||
|
(2, 255, 6),
|
||||||
|
] {
|
||||||
|
assert_eq!(parity_count(k, pct), Ok(m), "ceil({k} * {pct} / 100)");
|
||||||
|
}
|
||||||
|
assert_err!(parity_count(0, 50), Error::UnexpectedValue { .. });
|
||||||
|
assert_err!(parity_count(255, 200), Error::UnexpectedValue { .. }, "510 parity shards");
|
||||||
|
assert_err!(parity_count(200, 255), Error::UnexpectedValue { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code_parameters() {
|
||||||
|
for (k, m) in [(0usize, 1usize), (1, 0), (0, 0), (255, 1), (1, 255), (200, 100), (usize::MAX, 1)] {
|
||||||
|
assert_err!(ReedSolomon::new(k, m), Error::UnexpectedValue { .. }, "k={k} m={m}");
|
||||||
|
}
|
||||||
|
for (k, m) in [(1usize, 1usize), (254, 1), (1, 254), (128, 127), (4, 2)] {
|
||||||
|
let c = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
|
||||||
|
assert_eq!((c.data_shards(), c.parity_shards(), c.parity_matrix().len()), (k, m, k * m));
|
||||||
|
}
|
||||||
|
assert_eq!(MAX_SHARDS, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_is_used_exactly() {
|
||||||
|
let mut rng = SeqRng::new(1);
|
||||||
|
for (k, m) in [(4usize, 2usize), (1, 1), (10, 4), (2, 6), (200, 55)] {
|
||||||
|
let matrix = gf::cauchy(m, k);
|
||||||
|
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
|
||||||
|
assert_eq!(code.parity_matrix(), matrix.as_slice());
|
||||||
|
let data = data_shards(&mut rng, k, 33);
|
||||||
|
let full = encoded(&code, &data);
|
||||||
|
assert_eq!(
|
||||||
|
&full[k..],
|
||||||
|
gf::encode(&matrix, &data, m).as_slice(),
|
||||||
|
"k={k} m={m}: parity = matrix x data over GF(2^8)/0x11D"
|
||||||
|
);
|
||||||
|
check_recovers(&code, &full, &(0..m.min(k)).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8): every square submatrix is invertible.
|
||||||
|
let v = [1, 1, 1, 1, 1, 2, 4, 8];
|
||||||
|
let code = ReedSolomon::with_parity_matrix(4, 2, &v).unwrap();
|
||||||
|
let data = data_shards(&mut rng, 4, 5);
|
||||||
|
let full = encoded(&code, &data);
|
||||||
|
assert_eq!(&full[4..], gf::encode(&v, &data, 2).as_slice());
|
||||||
|
for size in 0..=2 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_refusals() {
|
||||||
|
let good = gf::cauchy(2, 4);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &good[..7]), Error::Malformed { .. }, "short");
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[good.clone(), vec![1]].concat()),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"long"
|
||||||
|
);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &[]), Error::Malformed { .. }, "empty");
|
||||||
|
let mut zero = good.clone();
|
||||||
|
zero[3] = 0;
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &zero),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"a zero entry: a 1x1 submatrix is singular"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 1, 1, 1, 1, 1, 1, 1]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"equal rows"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 2, 4, 6, 8]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"row 2 = 2 x row 1"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 1, 2, 5, 6]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"a singular 2x2 minor (cols 0,1)"
|
||||||
|
);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(0, 2, &[]), Error::UnexpectedValue { .. });
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(255, 1, &vec![1; 255]), Error::UnexpectedValue { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encode / reconstruct shapes
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_shape_errors() {
|
||||||
|
let code = ReedSolomon::new(4, 2).unwrap();
|
||||||
|
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 5]), Error::Malformed { .. }, "5 shards for 4 + 2");
|
||||||
|
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 7]), Error::Malformed { .. }, "7 shards");
|
||||||
|
let mut uneven = vec![vec![0u8; 8]; 6];
|
||||||
|
uneven[2].push(0);
|
||||||
|
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "unequal lengths");
|
||||||
|
let mut uneven = vec![vec![0u8; 8]; 6];
|
||||||
|
uneven[5].pop();
|
||||||
|
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "parity buffer of another length");
|
||||||
|
assert!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES]; 6]).is_ok());
|
||||||
|
assert_too_large!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES + 1]; 6]), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reconstruct_shape_errors() {
|
||||||
|
let code = ReedSolomon::new(4, 2).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut SeqRng::new(2), 4, 8));
|
||||||
|
let mut s = erase(&full, &[0]);
|
||||||
|
s.pop();
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "5 entries");
|
||||||
|
let mut s = erase(&full, &[0]);
|
||||||
|
s[3].as_mut().unwrap().push(9);
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "unequal lengths");
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> = vec![None; 6];
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Truncated { .. }, "everything lost");
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> = vec![Some(vec![0; MAX_SHARD_BYTES + 1]); 6];
|
||||||
|
s[0] = None;
|
||||||
|
assert_too_large!(code.reconstruct(&mut s), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
|
||||||
|
// Nothing lost: unchanged.
|
||||||
|
let mut s = erase(&full, &[]);
|
||||||
|
code.reconstruct(&mut s).unwrap();
|
||||||
|
assert!(s.iter().zip(&full).all(|(a, b)| a.as_deref() == Some(b.as_slice())));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ erasure patterns
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_pattern_small_codes_exhaustive() {
|
||||||
|
// k = 1..=8, m = 1..=4: every erasure pattern of size <= m recovers; every pattern of size m + 1 is refused.
|
||||||
|
let mut rng = SeqRng::new(3);
|
||||||
|
for k in 1..=8 {
|
||||||
|
for m in 1..=4 {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 7));
|
||||||
|
for size in 0..=m {
|
||||||
|
for lost in subsets(k + m, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for lost in subsets(k + m, m + 1) {
|
||||||
|
check_refuses(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_pattern_wolf_example() {
|
||||||
|
// 4 KB at packetSize 1024 and 50 %: 4 data + 2 parity (PROTOCOL.md 5.3), full-size shards.
|
||||||
|
let mut rng = SeqRng::new(4);
|
||||||
|
let code = ReedSolomon::new(4, parity_count(4, 50).unwrap()).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, 4, 1024 + 16));
|
||||||
|
for size in 0..=2 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for size in 3..=6 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_refuses(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// k = 1..=255 - m for one m: one worst-case pattern of exactly m erasures (data first) and one random pattern
|
||||||
|
/// recover; m + 1 erasures are refused.
|
||||||
|
fn sweep(m: usize, seed: u64) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
for k in 1..=(MAX_SHARDS - m) {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 3));
|
||||||
|
let data_first: Vec<usize> = (0..m).collect();
|
||||||
|
check_recovers(&code, &full, &data_first);
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, m));
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sweep_m1() {
|
||||||
|
sweep(1, 11);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m2() {
|
||||||
|
sweep(2, 12);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m3() {
|
||||||
|
sweep(3, 13);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m4() {
|
||||||
|
sweep(4, 14);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m8() {
|
||||||
|
sweep(8, 18);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m16() {
|
||||||
|
sweep(16, 116);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m64() {
|
||||||
|
sweep(64, 164);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m127() {
|
||||||
|
sweep(127, 1127);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m254() {
|
||||||
|
sweep(254, 1254);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_codes_random_patterns() {
|
||||||
|
// The biggest blocks: many random patterns of every size up to m.
|
||||||
|
let mut rng = SeqRng::new(5);
|
||||||
|
for (k, m) in [(250usize, 5usize), (200, 55), (128, 127), (64, 191)] {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 4));
|
||||||
|
for _ in 0..6 {
|
||||||
|
let size = 1 + rng.below(m);
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, size));
|
||||||
|
}
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
check_refuses(&code, &full, &(0..k + m).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_sweep() {
|
||||||
|
// The independent Cauchy construction through the crate's decoder, every k for a few m.
|
||||||
|
let mut rng = SeqRng::new(6);
|
||||||
|
for m in [1usize, 2, 5] {
|
||||||
|
for k in (1..=(MAX_SHARDS - m)).step_by(7) {
|
||||||
|
let matrix = gf::cauchy(m, k);
|
||||||
|
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
|
||||||
|
let data = data_shards(&mut rng, k, 2);
|
||||||
|
let mut full = data.clone();
|
||||||
|
full.extend(gf::encode(&matrix, &data, m));
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, m));
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_codes_and_patterns(k in 1usize..40, m in 1usize..12, len in 1usize..48, seed in any::<u64>(), lost_count in 0usize..16) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, len));
|
||||||
|
let lost = rng.subset(k + m, lost_count.min(k + m));
|
||||||
|
let mut s = erase(&full, &lost);
|
||||||
|
let r = code.reconstruct(&mut s);
|
||||||
|
if lost.len() <= m {
|
||||||
|
prop_assert!(r.is_ok(), "{:?}", r);
|
||||||
|
for (got, want) in s.iter().zip(&full) {
|
||||||
|
prop_assert_eq!(got.as_deref(), Some(want.as_slice()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
prop_assert!(matches!(r, Err(Error::Truncated { .. })), "{:?}", r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corrupted (not erased) input never panics; reconstruction only fills the gaps.
|
||||||
|
#[test]
|
||||||
|
fn hostile_shards_never_panic(k in 1usize..10, m in 1usize..5, shards in proptest::collection::vec(proptest::option::of(proptest::collection::vec(any::<u8>(), 0..8)), 0..16)) {
|
||||||
|
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
let mut s = shards.clone();
|
||||||
|
if code.reconstruct(&mut s).is_ok() {
|
||||||
|
prop_assert_eq!(s.len(), k + m);
|
||||||
|
for (before, after) in shards.iter().zip(&s) {
|
||||||
|
prop_assert!(after.is_some());
|
||||||
|
if let Some(b) = before {
|
||||||
|
prop_assert_eq!(Some(b), after.as_ref(), "present shards are never changed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut v: Vec<Vec<u8>> = shards.into_iter().flatten().collect();
|
||||||
|
let _ = code.encode(&mut v);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,9 @@ mod common;
|
|||||||
|
|
||||||
use common::{param, parse_query, xml_padded_to, xml_root};
|
use common::{param, parse_query, xml_padded_to, xml_root};
|
||||||
use domistream::Error;
|
use domistream::Error;
|
||||||
use domistream::http::xml::{self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES};
|
use domistream::http::xml::{
|
||||||
|
self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
|
||||||
|
};
|
||||||
use domistream::http::{self, Scheme};
|
use domistream::http::{self, Scheme};
|
||||||
use proptest::prelude::*;
|
use proptest::prelude::*;
|
||||||
|
|
||||||
@@ -92,7 +94,10 @@ fn xml_refuses_non_documents() {
|
|||||||
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
|
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
|
||||||
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
|
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
|
||||||
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
|
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
|
||||||
(br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#, "entity declaration"),
|
(
|
||||||
|
br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#,
|
||||||
|
"entity declaration",
|
||||||
|
),
|
||||||
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
|
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
|
||||||
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
|
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
|
||||||
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
|
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
|
||||||
@@ -249,9 +254,8 @@ fn tree(depth: u32) -> impl Strategy<Value = Tree> {
|
|||||||
children: vec![],
|
children: vec![],
|
||||||
});
|
});
|
||||||
leaf.prop_recursive(depth, 24, 4, move |inner| {
|
leaf.prop_recursive(depth, 24, 4, move |inner| {
|
||||||
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4)).prop_map(
|
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4))
|
||||||
|(name, attrs, text, children)| Tree { name, attrs, text, children },
|
.prop_map(|(name, attrs, text, children)| Tree { name, attrs, text, children })
|
||||||
)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -457,9 +461,15 @@ fn applist_caps() {
|
|||||||
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
|
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
|
||||||
let t = "t".repeat(MAX_APP_TITLE_BYTES);
|
let t = "t".repeat(MAX_APP_TITLE_BYTES);
|
||||||
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
|
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
|
||||||
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))), MAX_APP_TITLE_BYTES);
|
assert_cap!(
|
||||||
|
http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))),
|
||||||
|
MAX_APP_TITLE_BYTES
|
||||||
|
);
|
||||||
// Multi-byte titles: the cap is in bytes.
|
// Multi-byte titles: the cap is in bytes.
|
||||||
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))), MAX_APP_TITLE_BYTES);
|
assert_cap!(
|
||||||
|
http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))),
|
||||||
|
MAX_APP_TITLE_BYTES
|
||||||
|
);
|
||||||
|
|
||||||
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
|
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
|
||||||
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
|
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
|
||||||
@@ -470,8 +480,16 @@ fn applist_caps() {
|
|||||||
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||||
assert_eq!(apps.len(), 1, "unknown elements are ignored");
|
assert_eq!(apps.len(), 1, "unknown elements are ignored");
|
||||||
}
|
}
|
||||||
assert_too_large!(http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)), MAX_APPLIST_BYTES, MAX_APPLIST_BYTES + 1);
|
assert_too_large!(
|
||||||
assert_too_large!(http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]), MAX_APPLIST_BYTES, 3 * MAX_APPLIST_BYTES);
|
http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)),
|
||||||
|
MAX_APPLIST_BYTES,
|
||||||
|
MAX_APPLIST_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(
|
||||||
|
http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]),
|
||||||
|
MAX_APPLIST_BYTES,
|
||||||
|
3 * MAX_APPLIST_BYTES
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ================================================================================================ launch
|
// ================================================================================================ launch
|
||||||
@@ -605,7 +623,10 @@ fn launch_params() -> http::LaunchParams {
|
|||||||
width: 1920,
|
width: 1920,
|
||||||
height: 1080,
|
height: 1080,
|
||||||
fps: 60,
|
fps: 60,
|
||||||
keys: domistream::SessionKeys { rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", rikeyid: 1_234_567 },
|
keys: domistream::SessionKeys {
|
||||||
|
rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
|
||||||
|
rikeyid: 1_234_567,
|
||||||
|
},
|
||||||
hdr: false,
|
hdr: false,
|
||||||
audio: http::launch::AudioLayout::Stereo,
|
audio: http::launch::AudioLayout::Stereo,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -216,11 +216,17 @@ fn debug_never_prints_keys() {
|
|||||||
("VideoCipher", format!("{video:?}")),
|
("VideoCipher", format!("{video:?}")),
|
||||||
("AudioCipher", format!("{audio:?}")),
|
("AudioCipher", format!("{audio:?}")),
|
||||||
("ControlConfig", format!("{config:?}")),
|
("ControlConfig", format!("{config:?}")),
|
||||||
("VideoConfig", format!("{:?}", domistream::video::VideoConfig {
|
(
|
||||||
packet_size: 1024,
|
"VideoConfig",
|
||||||
cipher: Some(video.clone()),
|
format!(
|
||||||
frame_timeout: core::time::Duration::from_millis(100),
|
"{:?}",
|
||||||
})),
|
domistream::video::VideoConfig {
|
||||||
|
packet_size: 1024,
|
||||||
|
cipher: Some(video.clone()),
|
||||||
|
frame_timeout: core::time::Duration::from_millis(100),
|
||||||
|
}
|
||||||
|
),
|
||||||
|
),
|
||||||
] {
|
] {
|
||||||
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
|
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
|
||||||
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
|
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
|
||||||
|
|||||||
@@ -0,0 +1,464 @@
|
|||||||
|
//! INPUT_DATA (`docs/PROTOCOL.md` 4): vectors rebuilt from the field tables with our own builder, cross-checked
|
||||||
|
//! against the example bytes in PROTOCOL.md; encode, parse, equal; refusals of unknown types and wrong lengths.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::hex;
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::input::{
|
||||||
|
ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState, INPUT_HEADER_LEN, InputEvent, InputType,
|
||||||
|
MAX_INPUT_MESSAGE_BYTES, MouseButton, encode_input, parse_input,
|
||||||
|
};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
/// `0x0206 LE ‖ length LE (= 4 + size) ‖ size BE (= 4 + data) ‖ input type LE ‖ data`.
|
||||||
|
fn input_message(input_type: u32, data: &[u8]) -> Vec<u8> {
|
||||||
|
let size = 4 + data.len();
|
||||||
|
let mut m = 0x0206u16.to_le_bytes().to_vec();
|
||||||
|
m.extend_from_slice(&((4 + size) as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(&(size as u32).to_be_bytes());
|
||||||
|
m.extend_from_slice(&input_type.to_le_bytes());
|
||||||
|
m.extend_from_slice(data);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn be16(v: i16) -> [u8; 2] {
|
||||||
|
v.to_be_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rel(dx: i16, dy: i16) -> Vec<u8> {
|
||||||
|
input_message(0x07, &[be16(dx), be16(dy)].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn abs(x: i16, y: i16, w: u16, h: u16) -> Vec<u8> {
|
||||||
|
input_message(0x05, &[&be16(x)[..], &[0, 0], &w.to_be_bytes(), &h.to_be_bytes()].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn button(down: bool, b: u8) -> Vec<u8> {
|
||||||
|
input_message(if down { 0x08 } else { 0x09 }, &[b])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(down: bool, flags: u8, code: u16, modifiers: u8) -> Vec<u8> {
|
||||||
|
input_message(if down { 0x03 } else { 0x04 }, &[&[flags][..], &code.to_le_bytes(), &[modifiers, 0, 0]].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scroll(amount: i16) -> Vec<u8> {
|
||||||
|
// amount1 and amount2 both carry the amount, as in the PROTOCOL.md example; hosts read amount1.
|
||||||
|
input_message(0x0A, &[&be16(amount)[..], &be16(amount), &[0, 0]].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hscroll(amount: i16) -> Vec<u8> {
|
||||||
|
input_message(0x5500_0001, &be16(amount))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gamepad(g: &GamepadState) -> Vec<u8> {
|
||||||
|
let mut d = Vec::new();
|
||||||
|
d.extend_from_slice(&0x001Au16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&u16::from(g.controller).to_le_bytes());
|
||||||
|
d.extend_from_slice(&g.active_mask.to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0014u16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes());
|
||||||
|
d.push(g.left_trigger);
|
||||||
|
d.push(g.right_trigger);
|
||||||
|
for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] {
|
||||||
|
d.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
d.extend_from_slice(&0x009Cu16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0055u16.to_le_bytes());
|
||||||
|
assert_eq!(d.len(), 26);
|
||||||
|
input_message(0x0C, &d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arrival: controller, type, capabilities, supported buttons (u32, taken as LE like the other gamepad fields:
|
||||||
|
/// PROTOCOL.md gives no byte order, UNKNOWN U22).
|
||||||
|
fn arrival(controller: u8, kind: u8, caps: u8, buttons: u32) -> Vec<u8> {
|
||||||
|
input_message(0x5500_0004, &[&[controller, kind, caps][..], &buttons.to_le_bytes()].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pad(controller: u8, mask: u16, ry: i16) -> GamepadState {
|
||||||
|
GamepadState { controller, active_mask: mask, right_stick_y: ry, ..GamepadState::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builder_matches_the_protocol_md_examples() {
|
||||||
|
// Our field-table builder reproduces every example in PROTOCOL.md §4 byte for byte.
|
||||||
|
assert_eq!(rel(-1, 0), hex("06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00"));
|
||||||
|
assert_eq!(abs(1464, 528, 1919, 1079), hex("06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37"));
|
||||||
|
assert_eq!(button(true, 1), hex("06 02 09 00 00 00 00 05 08 00 00 00 01"));
|
||||||
|
assert_eq!(key(true, 0, 0x80A4, 0x04), hex("06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00"));
|
||||||
|
assert_eq!(scroll(-120), hex("06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00"));
|
||||||
|
assert_eq!(hscroll(30), hex("06 02 0A 00 00 00 00 06 01 00 00 55 00 1E"));
|
||||||
|
assert_eq!(
|
||||||
|
gamepad(&pad(0, 1, -104)),
|
||||||
|
hex(
|
||||||
|
"06 02 22 00 00 00 00 1E 0C 00 00 00 1A 00 00 00 01 00 14 00 00 00 00 00 00 00 00 00 00 00 98 FF 9C 00 00 00 55 00"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vectors() -> Vec<(InputEvent, Vec<u8>)> {
|
||||||
|
let full = GamepadState {
|
||||||
|
controller: 15,
|
||||||
|
active_mask: 0x8001,
|
||||||
|
buttons: ButtonFlags(
|
||||||
|
ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::HOME | ButtonFlags::PADDLE1 | ButtonFlags::MISC,
|
||||||
|
),
|
||||||
|
left_trigger: 0x80,
|
||||||
|
right_trigger: 0xFF,
|
||||||
|
left_stick_x: i16::MIN,
|
||||||
|
left_stick_y: i16::MAX,
|
||||||
|
right_stick_x: -1,
|
||||||
|
right_stick_y: 1,
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
(InputEvent::MouseMoveRel { dx: -1, dy: 0 }, rel(-1, 0)),
|
||||||
|
(InputEvent::MouseMoveRel { dx: i16::MIN, dy: i16::MAX }, rel(i16::MIN, i16::MAX)),
|
||||||
|
(InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 }, abs(1464, 528, 1919, 1079)),
|
||||||
|
(InputEvent::MouseMoveAbs { x: -5, y: 0, width: 0xFFFF, height: 1 }, abs(-5, 0, 0xFFFF, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Left }, button(true, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: false, button: MouseButton::Left }, button(false, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Middle }, button(true, 2)),
|
||||||
|
(InputEvent::MouseButton { pressed: false, button: MouseButton::Right }, button(false, 3)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Side }, button(true, 4)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Extra }, button(true, 5)),
|
||||||
|
(InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 }, key(true, 0, 0x80A4, 0x04)),
|
||||||
|
(InputEvent::Key { pressed: false, flags: 0, key_code: 0x0041, modifiers: 0 }, key(false, 0, 0x0041, 0)),
|
||||||
|
(
|
||||||
|
InputEvent::Key { pressed: true, flags: 0xFF, key_code: 0xFFFF, modifiers: 0xFF },
|
||||||
|
key(true, 0xFF, 0xFFFF, 0xFF),
|
||||||
|
),
|
||||||
|
(InputEvent::Scroll { amount: -120 }, scroll(-120)),
|
||||||
|
(InputEvent::Scroll { amount: 120 }, scroll(120)),
|
||||||
|
(InputEvent::HScroll { amount: 30 }, hscroll(30)),
|
||||||
|
(InputEvent::HScroll { amount: -32768 }, hscroll(-32768)),
|
||||||
|
(InputEvent::Gamepad(pad(0, 1, -104)), gamepad(&pad(0, 1, -104))),
|
||||||
|
(InputEvent::Gamepad(pad(1, 0, 0)), gamepad(&pad(1, 0, 0))),
|
||||||
|
(InputEvent::Gamepad(full), gamepad(&full)),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 2,
|
||||||
|
kind: ControllerKind::PlayStation,
|
||||||
|
capabilities: ControllerCapabilities(0xFF),
|
||||||
|
supported_buttons: ButtonFlags(0x003F_FFFF),
|
||||||
|
},
|
||||||
|
arrival(2, 2, 0xFF, 0x003F_FFFF),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 0,
|
||||||
|
kind: ControllerKind::Unknown,
|
||||||
|
capabilities: ControllerCapabilities(ControllerCapabilities::RUMBLE),
|
||||||
|
supported_buttons: ButtonFlags(0),
|
||||||
|
},
|
||||||
|
arrival(0, 0, 0x02, 0),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 15,
|
||||||
|
kind: ControllerKind::Nintendo,
|
||||||
|
capabilities: ControllerCapabilities(0),
|
||||||
|
supported_buttons: ButtonFlags(ButtonFlags::A),
|
||||||
|
},
|
||||||
|
arrival(15, 3, 0, 0x1000),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 3,
|
||||||
|
kind: ControllerKind::Xbox,
|
||||||
|
capabilities: ControllerCapabilities(0x23),
|
||||||
|
supported_buttons: ButtonFlags(0xFFFF),
|
||||||
|
},
|
||||||
|
arrival(3, 1, 0x23, 0xFFFF),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_then_parse_then_equal() {
|
||||||
|
for (event, bytes) in vectors() {
|
||||||
|
assert_eq!(encode_input(&event).unwrap(), bytes, "encode {event:?}");
|
||||||
|
assert_eq!(parse_input(&bytes).unwrap(), event, "parse {event:?}");
|
||||||
|
assert_eq!(parse_input(&encode_input(&event).unwrap()).unwrap(), event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn input_type_codes() {
|
||||||
|
for (code, t) in [
|
||||||
|
(0x03, InputType::KeyDown),
|
||||||
|
(0x04, InputType::KeyUp),
|
||||||
|
(0x05, InputType::MouseMoveAbs),
|
||||||
|
(0x07, InputType::MouseMoveRel),
|
||||||
|
(0x08, InputType::MouseButtonDown),
|
||||||
|
(0x09, InputType::MouseButtonUp),
|
||||||
|
(0x0A, InputType::MouseScroll),
|
||||||
|
(0x0C, InputType::ControllerMulti),
|
||||||
|
(0x0D, InputType::Haptics),
|
||||||
|
(0x17, InputType::Utf8Text),
|
||||||
|
(0x5500_0001, InputType::MouseHScroll),
|
||||||
|
(0x5500_0002, InputType::Touch),
|
||||||
|
(0x5500_0003, InputType::Pen),
|
||||||
|
(0x5500_0004, InputType::ControllerArrival),
|
||||||
|
(0x5500_0005, InputType::ControllerTouch),
|
||||||
|
(0x5500_0006, InputType::ControllerMotion),
|
||||||
|
(0x5500_0007, InputType::ControllerBattery),
|
||||||
|
] {
|
||||||
|
assert_eq!(InputType::try_from(code), Ok(t), "{code:#x}");
|
||||||
|
}
|
||||||
|
for code in [0u32, 1, 2, 6, 0x0B, 0x0E, 0x16, 0x18, 0x5500_0000, 0x5500_0008, 0x0100_0007, u32::MAX] {
|
||||||
|
assert_err!(InputType::try_from(code), Error::UnexpectedValue { .. }, "{code:#x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_and_unsupported_types() {
|
||||||
|
for code in [0u32, 1, 6, 0x5500_0008, 0x0700_0000, u32::MAX] {
|
||||||
|
assert_err!(parse_input(&input_message(code, &[0; 4])), Error::UnexpectedValue { .. }, "type {code:#x}");
|
||||||
|
}
|
||||||
|
// Known types whose layout is UNKNOWN U21.
|
||||||
|
for code in [0x0D, 0x17, 0x5500_0002, 0x5500_0003, 0x5500_0005, 0x5500_0006, 0x5500_0007] {
|
||||||
|
assert_err!(parse_input(&input_message(code, &[0; 8])), Error::Unsupported { .. }, "type {code:#x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_data_lengths() {
|
||||||
|
// (type, correct data length)
|
||||||
|
for (code, len) in [
|
||||||
|
(0x07u32, 4usize),
|
||||||
|
(0x05, 10),
|
||||||
|
(0x08, 1),
|
||||||
|
(0x09, 1),
|
||||||
|
(0x03, 6),
|
||||||
|
(0x04, 6),
|
||||||
|
(0x0A, 6),
|
||||||
|
(0x5500_0001, 2),
|
||||||
|
(0x0C, 26),
|
||||||
|
(0x5500_0004, 7),
|
||||||
|
] {
|
||||||
|
for wrong in [0, len - 1, len + 1, len + 16] {
|
||||||
|
let mut data = vec![0u8; wrong];
|
||||||
|
if code == 0x08 || code == 0x09 {
|
||||||
|
data.fill(1); // a valid button number, so only the length is wrong
|
||||||
|
}
|
||||||
|
assert_err!(
|
||||||
|
parse_input(&input_message(code, &data)),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"type {code:#x} with {wrong} bytes (wants {len})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lying_length_and_size_fields() {
|
||||||
|
let good = rel(5, 5);
|
||||||
|
let cases: Vec<(Vec<u8>, &str)> = vec![
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2] += 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length over",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2] -= 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length under",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length 65535",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[7] += 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size over",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[7] -= 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size under",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[4..8].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size u32::MAX",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size written little-endian",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[0..2].copy_from_slice(&0x0207u16.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"not INPUT_DATA",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[0..2].copy_from_slice(&0x0206u16.to_be_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"message type big-endian",
|
||||||
|
),
|
||||||
|
([good.clone(), vec![0]].concat(), "trailing byte"),
|
||||||
|
];
|
||||||
|
for (m, why) in cases {
|
||||||
|
assert_err!(parse_input(&m), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_sizes() {
|
||||||
|
assert_err!(parse_input(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_input(&[0x06]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_input(&rel(1, 1)[..INPUT_HEADER_LEN - 1]), Error::Truncated { .. });
|
||||||
|
assert_err!(
|
||||||
|
parse_input(&input_message(0x07, &[])[..INPUT_HEADER_LEN]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"header only: no data"
|
||||||
|
);
|
||||||
|
// max - 1, max, max + 1, huge: valid framing, data too long for any known type.
|
||||||
|
for len in [MAX_INPUT_MESSAGE_BYTES - 1, MAX_INPUT_MESSAGE_BYTES] {
|
||||||
|
let m = input_message(0x07, &vec![0; len - INPUT_HEADER_LEN]);
|
||||||
|
assert_eq!(m.len(), len);
|
||||||
|
assert_err!(parse_input(&m), Error::Malformed { .. }, "{len}");
|
||||||
|
}
|
||||||
|
let m = input_message(0x07, &vec![0; MAX_INPUT_MESSAGE_BYTES + 1 - INPUT_HEADER_LEN]);
|
||||||
|
assert_too_large!(parse_input(&m), MAX_INPUT_MESSAGE_BYTES, MAX_INPUT_MESSAGE_BYTES + 1);
|
||||||
|
assert_too_large!(parse_input(&vec![0; 1 << 20]), MAX_INPUT_MESSAGE_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_field_values() {
|
||||||
|
for b in [0u8, 6, 0xFF] {
|
||||||
|
assert_err!(parse_input(&button(true, b)), Error::UnexpectedValue { .. }, "button {b}");
|
||||||
|
}
|
||||||
|
let mut g = gamepad(&pad(16, 1, 0));
|
||||||
|
assert_err!(parse_input(&g), Error::UnexpectedValue { .. }, "controller 16");
|
||||||
|
for (offset, why) in [(12usize, "0x1A"), (18, "0x14"), (32, "0x9C"), (36, "0x55")] {
|
||||||
|
g = gamepad(&pad(0, 1, 0));
|
||||||
|
g[offset] ^= 0x01;
|
||||||
|
assert_err!(parse_input(&g), Error::Malformed { .. }, "constant {why} changed");
|
||||||
|
}
|
||||||
|
assert_err!(parse_input(&arrival(16, 1, 0, 0)), Error::UnexpectedValue { .. }, "arrival controller 16");
|
||||||
|
assert_err!(parse_input(&arrival(0, 4, 0, 0)), Error::UnexpectedValue { .. }, "controller kind 4");
|
||||||
|
|
||||||
|
for e in [
|
||||||
|
InputEvent::Gamepad(pad(16, 1, 0)),
|
||||||
|
InputEvent::Gamepad(pad(255, 1, 0)),
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 16,
|
||||||
|
kind: ControllerKind::Xbox,
|
||||||
|
capabilities: ControllerCapabilities(0),
|
||||||
|
supported_buttons: ButtonFlags(0),
|
||||||
|
},
|
||||||
|
] {
|
||||||
|
assert_err!(encode_input(&e), Error::UnexpectedValue { .. }, "{e:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event() -> impl Strategy<Value = InputEvent> {
|
||||||
|
let button = prop_oneof![
|
||||||
|
Just(MouseButton::Left),
|
||||||
|
Just(MouseButton::Middle),
|
||||||
|
Just(MouseButton::Right),
|
||||||
|
Just(MouseButton::Side),
|
||||||
|
Just(MouseButton::Extra)
|
||||||
|
];
|
||||||
|
let kind = prop_oneof![
|
||||||
|
Just(ControllerKind::Unknown),
|
||||||
|
Just(ControllerKind::Xbox),
|
||||||
|
Just(ControllerKind::PlayStation),
|
||||||
|
Just(ControllerKind::Nintendo)
|
||||||
|
];
|
||||||
|
let gamepad = (0u8..=15, any::<u16>(), any::<u32>(), any::<u8>(), any::<u8>(), any::<[i16; 4]>()).prop_map(
|
||||||
|
|(c, m, b, l, r, s)| GamepadState {
|
||||||
|
controller: c,
|
||||||
|
active_mask: m,
|
||||||
|
buttons: ButtonFlags(b),
|
||||||
|
left_trigger: l,
|
||||||
|
right_trigger: r,
|
||||||
|
left_stick_x: s[0],
|
||||||
|
left_stick_y: s[1],
|
||||||
|
right_stick_x: s[2],
|
||||||
|
right_stick_y: s[3],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
prop_oneof![
|
||||||
|
(any::<i16>(), any::<i16>()).prop_map(|(dx, dy)| InputEvent::MouseMoveRel { dx, dy }),
|
||||||
|
(any::<i16>(), any::<i16>(), any::<u16>(), any::<u16>())
|
||||||
|
.prop_map(|(x, y, width, height)| InputEvent::MouseMoveAbs { x, y, width, height }),
|
||||||
|
(any::<bool>(), button).prop_map(|(pressed, button)| InputEvent::MouseButton { pressed, button }),
|
||||||
|
(any::<bool>(), any::<u8>(), any::<u16>(), any::<u8>())
|
||||||
|
.prop_map(|(pressed, flags, key_code, modifiers)| InputEvent::Key { pressed, flags, key_code, modifiers }),
|
||||||
|
any::<i16>().prop_map(|amount| InputEvent::Scroll { amount }),
|
||||||
|
any::<i16>().prop_map(|amount| InputEvent::HScroll { amount }),
|
||||||
|
gamepad.prop_map(InputEvent::Gamepad),
|
||||||
|
(0u8..=15, kind, any::<u8>(), any::<u32>()).prop_map(|(controller, kind, c, b)| {
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller,
|
||||||
|
kind,
|
||||||
|
capabilities: ControllerCapabilities(c),
|
||||||
|
supported_buttons: ButtonFlags(b),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_event_round_trips(e in event()) {
|
||||||
|
let bytes = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
|
||||||
|
prop_assert!(bytes.len() <= MAX_INPUT_MESSAGE_BYTES);
|
||||||
|
prop_assert_eq!(&bytes[..2], &[0x06, 0x02]);
|
||||||
|
prop_assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]) as usize, bytes.len() - 4);
|
||||||
|
prop_assert_eq!(u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize, bytes.len() - 8);
|
||||||
|
prop_assert_eq!(parse_input(&bytes), Ok(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes never panic; whatever parses re-encodes to an equal event.
|
||||||
|
#[test]
|
||||||
|
fn parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..64)) {
|
||||||
|
if let Ok(e) = parse_input(&data) {
|
||||||
|
let again = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
|
||||||
|
prop_assert_eq!(parse_input(&again), Ok(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Valid framing around random data of every known type never panics.
|
||||||
|
#[test]
|
||||||
|
fn framed_random_data(code in prop_oneof![Just(3u32), Just(4), Just(5), Just(7), Just(8), Just(9), Just(0x0A), Just(0x0C), Just(0x5500_0001), Just(0x5500_0004)], data in proptest::collection::vec(any::<u8>(), 0..40)) {
|
||||||
|
let _ = parse_input(&input_message(code, &data));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,382 @@
|
|||||||
|
//! Packet parsers and ciphers of the media streams (`docs/PROTOCOL.md` 5.2, 6.2, 6.3, 7): RTP header, video packet
|
||||||
|
//! and frame header, audio packet, video AES-GCM (.NET vectors) and audio AES-CBC (openssl vectors). Also checks the
|
||||||
|
//! RustCrypto test oracles in `common` against the same independent vectors.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{fec_info, video_packet_bytes};
|
||||||
|
use domistream::audio::packet::{AUDIO_FEC_HEADER_LEN, MAX_AUDIO_PACKET_BYTES};
|
||||||
|
use domistream::audio::{AudioCipher, AudioPacket, parse_audio_packet};
|
||||||
|
use domistream::rtp::{RTP_HEADER_LEN, parse_rtp_header};
|
||||||
|
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
|
||||||
|
use domistream::video::{ENCRYPTION_PREFIX_LEN, FrameType, VideoCipher, parse_video_packet};
|
||||||
|
use domistream::{Error, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
// ================================================================================================ RTP
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rtp_header() {
|
||||||
|
let h = parse_rtp_header(&[0x80, 0x61, 0x12, 0x34, 0x00, 0x00, 0x03, 0xE8, 0xCA, 0xFE, 0xBA, 0xBE]).unwrap();
|
||||||
|
assert_eq!((h.flags, h.payload_type, h.sequence, h.timestamp, h.ssrc), (0x80, 97, 0x1234, 1000, 0xCAFE_BABE));
|
||||||
|
let h = parse_rtp_header(&[0x90, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 1, 2, 3]).unwrap();
|
||||||
|
assert_eq!((h.flags, h.sequence, h.timestamp), (0x90, 0xFFFF, u32::MAX), "the rest is ignored");
|
||||||
|
for len in [0usize, 1, RTP_HEADER_LEN - 1] {
|
||||||
|
match parse_rtp_header(&vec![0x80; len]) {
|
||||||
|
Err(Error::Truncated { needed, actual, .. }) => assert_eq!((needed, actual), (RTP_HEADER_LEN, len)),
|
||||||
|
other => panic!("{len} bytes: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for first in [0x00u8, 0x40, 0xC0, 0x3F] {
|
||||||
|
let mut p = vec![first, 97];
|
||||||
|
p.resize(12, 0);
|
||||||
|
assert_err!(parse_rtp_header(&p), Error::UnexpectedValue { .. }, "version bits {first:#x}");
|
||||||
|
}
|
||||||
|
assert!(parse_rtp_header(&vec![0x80; 1 << 20]).is_ok(), "only the first 12 bytes matter");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ video packet
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_fields() {
|
||||||
|
let payload: Vec<u8> = (0..48u8).collect();
|
||||||
|
let p = video_packet_bytes(0xABCD, 0x0102_0304, 77, 0x05, (1 << 4) | (2 << 6), fec_info(50, 3, 4), &payload);
|
||||||
|
let v = parse_video_packet(&p).unwrap();
|
||||||
|
assert_eq!(v.rtp.sequence, 0xABCD);
|
||||||
|
assert_eq!(v.rtp.timestamp, 0x0102_0304);
|
||||||
|
assert_eq!(v.rtp.flags, 0x90);
|
||||||
|
assert_eq!(v.nv.stream_packet_index, 0xABCD << 8);
|
||||||
|
assert_eq!(v.nv.frame_index, 77);
|
||||||
|
assert_eq!(v.nv.flags.0, 0x05);
|
||||||
|
assert_eq!(v.nv.multi_fec_flags, 0x10);
|
||||||
|
assert_eq!(v.nv.fec.shard_index, 3);
|
||||||
|
assert_eq!(v.nv.fec.data_shards, 4);
|
||||||
|
assert_eq!(v.nv.fec.fec_percentage, 50);
|
||||||
|
assert_eq!(v.nv.fec.block_index, 1);
|
||||||
|
assert_eq!(v.nv.fec.last_block_index, 2);
|
||||||
|
assert_eq!(v.payload, payload.as_slice());
|
||||||
|
// Parity shard 5 of 4 + 2 is in range.
|
||||||
|
assert!(parse_video_packet(&video_packet_bytes(1, 0, 0, 0, 0, fec_info(50, 5, 4), &payload)).is_ok());
|
||||||
|
// Bits 0-3 of fecInfo are not part of any field.
|
||||||
|
let v = parse_video_packet(&video_packet_bytes(1, 0, 0, 1, 0, fec_info(50, 0, 4) | 0xF, &payload)).unwrap();
|
||||||
|
assert_eq!((v.nv.fec.shard_index, v.nv.fec.data_shards, v.nv.fec.fec_percentage), (0, 4, 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_hostile_sizes() {
|
||||||
|
let at = |len: usize| {
|
||||||
|
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &[]);
|
||||||
|
p.resize(len, 0xEE);
|
||||||
|
p
|
||||||
|
};
|
||||||
|
for len in [0usize, 1, 16, PAYLOAD_OFFSET - 1] {
|
||||||
|
assert_err!(parse_video_packet(&at(len)[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
assert!(parse_video_packet(&at(PAYLOAD_OFFSET)).unwrap().payload.is_empty());
|
||||||
|
for len in [MAX_VIDEO_PACKET_BYTES - 1, MAX_VIDEO_PACKET_BYTES] {
|
||||||
|
assert_eq!(parse_video_packet(&at(len)).unwrap().payload.len(), len - PAYLOAD_OFFSET);
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_video_packet(&at(MAX_VIDEO_PACKET_BYTES + 1)),
|
||||||
|
MAX_VIDEO_PACKET_BYTES,
|
||||||
|
MAX_VIDEO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_video_packet(&at(1 << 20)), MAX_VIDEO_PACKET_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_inconsistent_fec_fields() {
|
||||||
|
let pay = [0u8; 16];
|
||||||
|
for (blocks, info, why) in [
|
||||||
|
(0u8, fec_info(50, 0, 0), "zero data shards"),
|
||||||
|
(0, fec_info(50, 6, 4), "shard index past data + parity (4 + 2)"),
|
||||||
|
(0, fec_info(0, 4, 4), "parity index with 0 % FEC"),
|
||||||
|
(0, fec_info(50, 1023, 4), "shard index 1023"),
|
||||||
|
(0, fec_info(100, 0, 200), "200 + 200 shards > 255"),
|
||||||
|
(0, fec_info(0, 0, 1023), "1023 data shards > 255"),
|
||||||
|
((2 << 4) | (1 << 6), fec_info(50, 0, 4), "block index past last block index"),
|
||||||
|
(3 << 4, fec_info(50, 0, 4), "block 3 of block 0"),
|
||||||
|
] {
|
||||||
|
assert_err!(
|
||||||
|
parse_video_packet(&video_packet_bytes(1, 0, 0, 1, blocks, info, &pay)),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{why}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &pay);
|
||||||
|
p[0] = 0x50;
|
||||||
|
assert_err!(parse_video_packet(&p), Error::UnexpectedValue { .. }, "RTP version 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_header() {
|
||||||
|
// Moonshine-style fields.
|
||||||
|
let h = parse_frame_header(&[0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00, 0xAA]).unwrap();
|
||||||
|
assert_eq!(h.raw, [0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00]);
|
||||||
|
assert_eq!(
|
||||||
|
(h.header_type, h.processing_latency, h.frame_type, h.last_payload_len),
|
||||||
|
(0x01, 0x1234, FrameType::Key, 16)
|
||||||
|
);
|
||||||
|
for (b, t) in [
|
||||||
|
(1u8, FrameType::Predicted),
|
||||||
|
(2, FrameType::Key),
|
||||||
|
(5, FrameType::Recovery),
|
||||||
|
(0, FrameType::Other(0)),
|
||||||
|
(0x68, FrameType::Other(0x68)),
|
||||||
|
] {
|
||||||
|
assert_eq!(parse_frame_header(&[1, 0, 0, b, 0, 0, 0, 0]).unwrap().frame_type, t);
|
||||||
|
}
|
||||||
|
// Wolf's constant (UNKNOWN U13): parsed, raw kept.
|
||||||
|
let wolf = [0x01, 0x37, 0x63, 0x68, 0x61, 0x72, 0x73, 0x73];
|
||||||
|
let h = parse_frame_header(&wolf).unwrap();
|
||||||
|
assert_eq!(h.raw, wolf);
|
||||||
|
assert_eq!(h.last_payload_len, 0x7373_7261);
|
||||||
|
for len in 0..FRAME_HEADER_LEN {
|
||||||
|
assert_err!(parse_frame_header(&wolf[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ audio packet
|
||||||
|
|
||||||
|
fn audio_data(seq: u16, payload: &[u8]) -> Vec<u8> {
|
||||||
|
let mut p = vec![0x80, 97];
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&1000u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(payload);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio_parity(shard: u8, pt: u8, base_seq: u16, base_ts: u32, parity: &[u8]) -> Vec<u8> {
|
||||||
|
let mut p = vec![0x80, 127];
|
||||||
|
p.extend_from_slice(&base_seq.wrapping_add(4).to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&[shard, pt]);
|
||||||
|
p.extend_from_slice(&base_seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0x1122_3344u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(parity);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_packets() {
|
||||||
|
match parse_audio_packet(&audio_data(5, &[1, 2, 3])).unwrap() {
|
||||||
|
AudioPacket::Data { rtp, payload } => {
|
||||||
|
assert_eq!((rtp.payload_type, rtp.sequence, rtp.timestamp), (97, 5, 1000));
|
||||||
|
assert_eq!(payload, &[1, 2, 3]);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
match parse_audio_packet(&audio_parity(1, 97, 0xFFFC, 0xDEAD_BEEF, &[9; 32])).unwrap() {
|
||||||
|
AudioPacket::Parity { rtp, fec, parity } => {
|
||||||
|
assert_eq!(rtp.payload_type, 127);
|
||||||
|
assert_eq!(
|
||||||
|
(fec.shard_index, fec.payload_type, fec.base_sequence, fec.base_timestamp, fec.ssrc),
|
||||||
|
(1, 97, 0xFFFC, 0xDEAD_BEEF, 0x1122_3344)
|
||||||
|
);
|
||||||
|
assert_eq!(parity, &[9; 32]);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_packet_hostile() {
|
||||||
|
for pt in [0u8, 96, 98, 126] {
|
||||||
|
let mut p = audio_data(1, &[1]);
|
||||||
|
p[1] = pt;
|
||||||
|
assert_err!(parse_audio_packet(&p), Error::UnexpectedValue { .. }, "payload type {pt}");
|
||||||
|
}
|
||||||
|
assert_err!(
|
||||||
|
parse_audio_packet(&audio_parity(2, 97, 0, 0, &[1; 16])),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"parity shard 2"
|
||||||
|
);
|
||||||
|
assert_err!(parse_audio_packet(&audio_parity(0xFF, 97, 0, 0, &[1; 16])), Error::UnexpectedValue { .. });
|
||||||
|
for len in [0usize, 1, RTP_HEADER_LEN - 1, RTP_HEADER_LEN] {
|
||||||
|
assert_err!(parse_audio_packet(&audio_data(1, &[])[..len]), Error::Truncated { .. }, "data, {len} bytes");
|
||||||
|
}
|
||||||
|
let par = audio_parity(0, 97, 0, 0, &[]);
|
||||||
|
for len in [
|
||||||
|
RTP_HEADER_LEN,
|
||||||
|
RTP_HEADER_LEN + 1,
|
||||||
|
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN - 1,
|
||||||
|
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN,
|
||||||
|
] {
|
||||||
|
assert_err!(parse_audio_packet(&par[..len]), Error::Truncated { .. }, "parity, {len} bytes");
|
||||||
|
}
|
||||||
|
let at = |len: usize| audio_data(1, &vec![7; len - RTP_HEADER_LEN]);
|
||||||
|
for len in [MAX_AUDIO_PACKET_BYTES - 1, MAX_AUDIO_PACKET_BYTES] {
|
||||||
|
assert!(parse_audio_packet(&at(len)).is_ok(), "{len}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_audio_packet(&at(MAX_AUDIO_PACKET_BYTES + 1)),
|
||||||
|
MAX_AUDIO_PACKET_BYTES,
|
||||||
|
MAX_AUDIO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_audio_packet(&at(1 << 20)), MAX_AUDIO_PACKET_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ video cipher
|
||||||
|
|
||||||
|
const VIDEO: [&str; 4] = ["v_0", "v_1", "v_big_counter", "v_1040"];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_decrypt_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
for name in VIDEO {
|
||||||
|
assert_eq!(
|
||||||
|
c.decrypt(&v.bytes(&format!("{name}_packet"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_plain")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_oracle_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let key = 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!(
|
||||||
|
common::video_encrypt(&key, counter, frame, &v.bytes(&format!("{name}_plain"))),
|
||||||
|
v.bytes(&format!("{name}_packet")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_decrypt_refuses() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
let p = v.bytes("v_1_packet");
|
||||||
|
for i in (0..11).chain(16..p.len()) {
|
||||||
|
let mut t = p.clone();
|
||||||
|
t[i] ^= 0x01;
|
||||||
|
assert_err!(c.decrypt(&t), Error::Crypto, "byte {i} flipped (IV, tag or ciphertext)");
|
||||||
|
}
|
||||||
|
let mut t = p.clone();
|
||||||
|
t[11] = b'v';
|
||||||
|
assert_err!(c.decrypt(&t), Error::Malformed { .. }, "IV byte 11 must be 'V'");
|
||||||
|
for len in [0usize, 1, ENCRYPTION_PREFIX_LEN - 1] {
|
||||||
|
assert_err!(c.decrypt(&p[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
let mut key = v.arr16("key");
|
||||||
|
key[15] ^= 0x80;
|
||||||
|
assert_err!(VideoCipher::new(key).decrypt(&p), Error::Crypto);
|
||||||
|
let mut big = p.clone();
|
||||||
|
big.resize(MAX_VIDEO_PACKET_BYTES + 1, 0);
|
||||||
|
assert_too_large!(c.decrypt(&big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ audio cipher
|
||||||
|
|
||||||
|
const AUDIO: [&str; 6] = ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"];
|
||||||
|
|
||||||
|
fn audio_cipher(v: &common::Vectors, name: &str) -> (AudioCipher, u16) {
|
||||||
|
let keys = SessionKeys { rikey: v.arr16("key"), rikeyid: v.u32_hex(&format!("{name}_rikeyid")) };
|
||||||
|
(AudioCipher::new(&keys), u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_iv_and_decrypt_match_openssl_vectors() {
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
for name in AUDIO {
|
||||||
|
let (c, seq) = audio_cipher(&v, name);
|
||||||
|
assert_eq!(
|
||||||
|
c.iv(seq).unwrap().to_vec(),
|
||||||
|
v.bytes(&format!("{name}_iv")),
|
||||||
|
"{name}: IV = BE(rikeyid + seq) || 12 zero, wrapping"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
c.decrypt(seq, &v.bytes(&format!("{name}_cipher"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_plain")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_oracle_matches_openssl_vectors() {
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
for name in AUDIO {
|
||||||
|
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
|
||||||
|
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
common::audio_encrypt(&v.arr16("key"), rikeyid, seq, &v.bytes(&format!("{name}_plain"))),
|
||||||
|
v.bytes(&format!("{name}_cipher")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_decrypt_refuses() {
|
||||||
|
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::NoPadding};
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
let (c, seq) = audio_cipher(&v, "a_0");
|
||||||
|
for len in [0usize, 1, 15, 17, 31] {
|
||||||
|
assert_err!(c.decrypt(seq, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||||
|
}
|
||||||
|
// Blocks whose decryption ends in bad PKCS#7 padding.
|
||||||
|
let iv = c.iv(seq).unwrap();
|
||||||
|
for last in [&[0u8][..], &[17], &[16, 16, 16, 15], &[2, 3]] {
|
||||||
|
let mut block = [0x41u8; 16];
|
||||||
|
block[16 - last.len()..].copy_from_slice(last);
|
||||||
|
let mut buf = block;
|
||||||
|
cbc::Encryptor::<aes::Aes128>::new((&v.arr16("key")).into(), &iv.into())
|
||||||
|
.encrypt_padded::<NoPadding>(&mut buf, 16)
|
||||||
|
.unwrap();
|
||||||
|
assert_err!(c.decrypt(seq, &buf), Error::Crypto, "padding ending {last:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn media_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..200)) {
|
||||||
|
if let Ok(h) = parse_rtp_header(&data) {
|
||||||
|
prop_assert!(data.len() >= RTP_HEADER_LEN);
|
||||||
|
prop_assert_eq!(h.flags >> 6, 2);
|
||||||
|
}
|
||||||
|
if let Ok(p) = parse_video_packet(&data) {
|
||||||
|
prop_assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
|
||||||
|
prop_assert!(p.nv.fec.data_shards > 0);
|
||||||
|
prop_assert!(p.nv.fec.block_index <= p.nv.fec.last_block_index);
|
||||||
|
}
|
||||||
|
if let Ok(h) = parse_frame_header(&data) {
|
||||||
|
prop_assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
|
||||||
|
}
|
||||||
|
match parse_audio_packet(&data) {
|
||||||
|
Ok(AudioPacket::Data { payload, .. }) => prop_assert!(!payload.is_empty()),
|
||||||
|
Ok(AudioPacket::Parity { fec, parity, .. }) => prop_assert!(!parity.is_empty() && fec.shard_index <= 1),
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
let _ = VideoCipher::new([1; 16]).decrypt(&data);
|
||||||
|
let _ = AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 }).decrypt(0, &data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_round_trip_through_the_oracle(rikeyid in any::<u32>(), seq in any::<u16>(), plain in proptest::collection::vec(any::<u8>(), 0..100)) {
|
||||||
|
let key = [0x5Au8; 16];
|
||||||
|
let c = AudioCipher::new(&SessionKeys { rikey: key, rikeyid });
|
||||||
|
let ct = common::audio_encrypt(&key, rikeyid, seq, &plain);
|
||||||
|
prop_assert_eq!(c.decrypt(seq, &ct), Ok(plain));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_round_trip_through_the_oracle(counter in any::<u64>(), frame in any::<u32>(), plain in proptest::collection::vec(any::<u8>(), 32..300)) {
|
||||||
|
let key = [0xA5u8; 16];
|
||||||
|
let p = common::video_encrypt(&key, counter, frame, &plain);
|
||||||
|
prop_assert_eq!(VideoCipher::new(key).decrypt(&p), Ok(plain));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -115,7 +115,14 @@ fn hex_param(req: &HttpRequest, name: &str) -> Vec<u8> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds `body` and checks the session fails into `Failed(reason)`.
|
/// Feeds `body` and checks the session fails into `Failed(reason)`.
|
||||||
fn expect_failure(s: &mut PairingSession, id: &ClientIdentity, rng: &mut ScriptedRng, status: u16, body: &[u8], reason: PairingFailure) {
|
fn expect_failure(
|
||||||
|
s: &mut PairingSession,
|
||||||
|
id: &ClientIdentity,
|
||||||
|
rng: &mut ScriptedRng,
|
||||||
|
status: u16,
|
||||||
|
body: &[u8],
|
||||||
|
reason: PairingFailure,
|
||||||
|
) {
|
||||||
let r = s.handle_response(id, status, body, rng);
|
let r = s.handle_response(id, status, body, rng);
|
||||||
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
|
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
|
||||||
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
|
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
|
||||||
@@ -136,7 +143,11 @@ fn recorded_transcript_walks_every_state() {
|
|||||||
|
|
||||||
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
|
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
|
||||||
assert_eq!(req1.scheme, Scheme::Http);
|
assert_eq!(req1.scheme, Scheme::Http);
|
||||||
assert!(req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)), "step 1 timeout {:?}", req1.timeout);
|
assert!(
|
||||||
|
req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)),
|
||||||
|
"step 1 timeout {:?}",
|
||||||
|
req1.timeout
|
||||||
|
);
|
||||||
let (path, q) = parse_query(&req1.path_and_query);
|
let (path, q) = parse_query(&req1.path_and_query);
|
||||||
assert_eq!(path, "/pair");
|
assert_eq!(path, "/pair");
|
||||||
assert_eq!(param(&q, "uniqueid"), UID);
|
assert_eq!(param(&q, "uniqueid"), UID);
|
||||||
@@ -247,14 +258,8 @@ fn a_bare_paired_answer_cannot_skip_any_step() {
|
|||||||
#[test]
|
#[test]
|
||||||
fn out_of_order_answers_fail() {
|
fn out_of_order_answers_fail() {
|
||||||
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
|
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
|
||||||
let cases: Vec<(usize, Vec<u8>)> = vec![
|
let cases: Vec<(usize, Vec<u8>)> =
|
||||||
(0, resp2()),
|
vec![(0, resp2()), (0, resp3()), (1, resp1()), (1, resp3()), (2, resp1()), (2, resp2())];
|
||||||
(0, resp3()),
|
|
||||||
(1, resp1()),
|
|
||||||
(1, resp3()),
|
|
||||||
(2, resp1()),
|
|
||||||
(2, resp2()),
|
|
||||||
];
|
|
||||||
for (steps, body) in cases {
|
for (steps, body) in cases {
|
||||||
let (mut s, mut rng, id) = session_after(steps);
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
|
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
|
||||||
@@ -319,8 +324,14 @@ fn malformed_answers_at_every_step() {
|
|||||||
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
|
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
|
||||||
xml_root(200, ""),
|
xml_root(200, ""),
|
||||||
xml_root(200, "<paired>yes</paired>"),
|
xml_root(200, "<paired>yes</paired>"),
|
||||||
xml_root(200, "<paired>1</paired><plaincert>zz</plaincert><challengeresponse>zz</challengeresponse><pairingsecret>zz</pairingsecret>"),
|
xml_root(
|
||||||
xml_root(200, "<paired>1</paired><plaincert>abc</plaincert><challengeresponse>abc</challengeresponse><pairingsecret>abc</pairingsecret>"),
|
200,
|
||||||
|
"<paired>1</paired><plaincert>zz</plaincert><challengeresponse>zz</challengeresponse><pairingsecret>zz</pairingsecret>",
|
||||||
|
),
|
||||||
|
xml_root(
|
||||||
|
200,
|
||||||
|
"<paired>1</paired><plaincert>abc</plaincert><challengeresponse>abc</challengeresponse><pairingsecret>abc</pairingsecret>",
|
||||||
|
),
|
||||||
];
|
];
|
||||||
for steps in 0..3 {
|
for steps in 0..3 {
|
||||||
for body in &bodies {
|
for body in &bodies {
|
||||||
@@ -334,8 +345,13 @@ fn malformed_answers_at_every_step() {
|
|||||||
fn wrong_pin_is_a_proof_mismatch() {
|
fn wrong_pin_is_a_proof_mismatch() {
|
||||||
let v = v();
|
let v = v();
|
||||||
let (mut s, mut rng, id) = session_after(1);
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes("step2_challengeresponse_wrong_pin")))), &mut rng)
|
s.handle_response(
|
||||||
.unwrap();
|
&id,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("challengeresponse", &v.bytes("step2_challengeresponse_wrong_pin")))),
|
||||||
|
&mut rng,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||||
assert_err!(r, Error::PairingRefused);
|
assert_err!(r, Error::PairingRefused);
|
||||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
||||||
@@ -386,7 +402,14 @@ fn wrong_challenge_response_sizes() {
|
|||||||
];
|
];
|
||||||
for cr in cases {
|
for cr in cases {
|
||||||
let (mut s, mut rng, id) = session_after(1);
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("challengeresponse", &cr))), PairingFailure::MalformedAnswer);
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("challengeresponse", &cr))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -395,7 +418,12 @@ fn bad_host_signatures() {
|
|||||||
let v = v();
|
let v = v();
|
||||||
// Signed by another key.
|
// Signed by another key.
|
||||||
let (mut s, mut rng, id) = session_after(2);
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &v.bytes("step3_pairingsecret_rogue_signature")))), &mut rng);
|
let r = s.handle_response(
|
||||||
|
&id,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("pairingsecret", &v.bytes("step3_pairingsecret_rogue_signature")))),
|
||||||
|
&mut rng,
|
||||||
|
);
|
||||||
assert_err!(r, Error::PairingRefused);
|
assert_err!(r, Error::PairingRefused);
|
||||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
||||||
|
|
||||||
@@ -416,7 +444,10 @@ fn bad_host_signatures() {
|
|||||||
let mut secret = good.clone();
|
let mut secret = good.clone();
|
||||||
secret[0] ^= 1;
|
secret[0] ^= 1;
|
||||||
let (mut s, mut rng, id) = session_after(2);
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
assert_err!(s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &secret))), &mut rng), Error::PairingRefused);
|
assert_err!(
|
||||||
|
s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &secret))), &mut rng),
|
||||||
|
Error::PairingRefused
|
||||||
|
);
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
s.state(),
|
s.state(),
|
||||||
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
|
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
|
||||||
@@ -427,9 +458,18 @@ fn bad_host_signatures() {
|
|||||||
fn wrong_pairing_secret_sizes() {
|
fn wrong_pairing_secret_sizes() {
|
||||||
let v = v();
|
let v = v();
|
||||||
let secret = v.bytes("server_secret");
|
let secret = v.bytes("server_secret");
|
||||||
for ps in [secret[..15].to_vec(), secret.clone(), [secret.clone(), vec![0x55; MAX_SIGNATURE_BYTES + 1]].concat(), vec![]] {
|
for ps in
|
||||||
|
[secret[..15].to_vec(), secret.clone(), [secret.clone(), vec![0x55; MAX_SIGNATURE_BYTES + 1]].concat(), vec![]]
|
||||||
|
{
|
||||||
let (mut s, mut rng, id) = session_after(2);
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("pairingsecret", &ps))), PairingFailure::MalformedAnswer);
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("pairingsecret", &ps))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -449,7 +489,14 @@ fn bad_host_certificates() {
|
|||||||
long,
|
long,
|
||||||
] {
|
] {
|
||||||
let (mut s, mut rng, id) = session_after(0);
|
let (mut s, mut rng, id) = session_after(0);
|
||||||
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("plaincert", pem.as_bytes()))), PairingFailure::MalformedAnswer);
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("plaincert", pem.as_bytes()))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -529,9 +576,11 @@ fn proof_hash_vectors() {
|
|||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}");
|
assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}");
|
||||||
}
|
}
|
||||||
let h = crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret"));
|
let h =
|
||||||
|
crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret"));
|
||||||
assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof"));
|
assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof"));
|
||||||
let h = crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret"));
|
let h =
|
||||||
|
crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret"));
|
||||||
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
|
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
|
||||||
assert_too_large!(
|
assert_too_large!(
|
||||||
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
|
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
|
||||||
@@ -646,11 +695,14 @@ fn server_cert_hostile_der() {
|
|||||||
(vec![0x30], "one byte"),
|
(vec![0x30], "one byte"),
|
||||||
(der[..der.len() - 1].to_vec(), "cut"),
|
(der[..der.len() - 1].to_vec(), "cut"),
|
||||||
([der.clone(), vec![0]].concat(), "trailing byte"),
|
([der.clone(), vec![0]].concat(), "trailing byte"),
|
||||||
({
|
(
|
||||||
let mut d = der.clone();
|
{
|
||||||
d[1] = 0x84; // outer length claims 4 length bytes: lies about the size
|
let mut d = der.clone();
|
||||||
d
|
d[1] = 0x84; // outer length claims 4 length bytes: lies about the size
|
||||||
}, "lying length"),
|
d
|
||||||
|
},
|
||||||
|
"lying length",
|
||||||
|
),
|
||||||
] {
|
] {
|
||||||
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
|
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
|
||||||
}
|
}
|
||||||
@@ -666,7 +718,11 @@ fn client_identity_from_recorded_keys() {
|
|||||||
assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice());
|
assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice());
|
||||||
assert_eq!(id.key_pkcs8_der(), v.bytes("client_key_pkcs8_der").as_slice());
|
assert_eq!(id.key_pkcs8_der(), v.bytes("client_key_pkcs8_der").as_slice());
|
||||||
assert_eq!(id.cert_signature().unwrap(), v.bytes("client_cert_signature"));
|
assert_eq!(id.cert_signature().unwrap(), v.bytes("client_cert_signature"));
|
||||||
assert_eq!(id.sign(&v.bytes("sign_data")).unwrap(), v.bytes("sign_data_client_signature"), "PKCS#1 v1.5 is deterministic");
|
assert_eq!(
|
||||||
|
id.sign(&v.bytes("sign_data")).unwrap(),
|
||||||
|
v.bytes("sign_data_client_signature"),
|
||||||
|
"PKCS#1 v1.5 is deterministic"
|
||||||
|
);
|
||||||
assert_eq!(id.sign(&v.bytes("client_secret")).unwrap(), v.bytes("client_secret_signature"));
|
assert_eq!(id.sign(&v.bytes("client_secret")).unwrap(), v.bytes("client_secret_signature"));
|
||||||
let pem = id.cert_pem().unwrap();
|
let pem = id.cert_pem().unwrap();
|
||||||
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
|
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
|
||||||
@@ -679,7 +735,11 @@ fn client_identity_refuses() {
|
|||||||
let v = v();
|
let v = v();
|
||||||
let cert = v.bytes("client_cert_der");
|
let cert = v.bytes("client_cert_der");
|
||||||
let key = v.bytes("client_key_pkcs8_der");
|
let key = v.bytes("client_key_pkcs8_der");
|
||||||
assert_err!(ClientIdentity::from_der(&cert, &v.bytes("rogue_key_pkcs8_der")), Error::Malformed { .. }, "key of another cert");
|
assert_err!(
|
||||||
|
ClientIdentity::from_der(&cert, &v.bytes("rogue_key_pkcs8_der")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"key of another cert"
|
||||||
|
);
|
||||||
assert_err!(ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &key), Error::Malformed { .. });
|
assert_err!(ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &key), Error::Malformed { .. });
|
||||||
assert_err!(ClientIdentity::from_der(&[], &key), Error::Malformed { .. });
|
assert_err!(ClientIdentity::from_der(&[], &key), Error::Malformed { .. });
|
||||||
assert_err!(ClientIdentity::from_der(&cert, &[]), Error::Malformed { .. });
|
assert_err!(ClientIdentity::from_der(&cert, &[]), Error::Malformed { .. });
|
||||||
@@ -715,7 +775,20 @@ fn client_identity_generate() {
|
|||||||
fn pin_from_digits() {
|
fn pin_from_digits() {
|
||||||
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
|
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
|
||||||
assert_eq!(Pin::from_digits("4071").unwrap().as_bytes(), b"4071");
|
assert_eq!(Pin::from_digits("4071").unwrap().as_bytes(), b"4071");
|
||||||
for bad in ["", "1", "123", "12345", "12a4", " 123", "123 ", "-123", "+123", "\u{0661}\u{0662}\u{0663}\u{0664}", "1234", "12\u{0}4"] {
|
for bad in [
|
||||||
|
"",
|
||||||
|
"1",
|
||||||
|
"123",
|
||||||
|
"12345",
|
||||||
|
"12a4",
|
||||||
|
" 123",
|
||||||
|
"123 ",
|
||||||
|
"-123",
|
||||||
|
"+123",
|
||||||
|
"\u{0661}\u{0662}\u{0663}\u{0664}",
|
||||||
|
"1234",
|
||||||
|
"12\u{0}4",
|
||||||
|
] {
|
||||||
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
|
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -751,7 +824,8 @@ fn pair_response_parser() {
|
|||||||
assert!(r.paired);
|
assert!(r.paired);
|
||||||
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
|
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
|
||||||
assert_eq!(r.challenge_response, None);
|
assert_eq!(r.challenge_response, None);
|
||||||
let r = parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
|
let r =
|
||||||
|
parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
|
||||||
assert!(!r.paired);
|
assert!(!r.paired);
|
||||||
assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..]));
|
assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..]));
|
||||||
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><pairingsecret>00ff</pairingsecret>")).unwrap();
|
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><pairingsecret>00ff</pairingsecret>")).unwrap();
|
||||||
|
|||||||
@@ -106,7 +106,11 @@ fn response_lying_content_length() {
|
|||||||
// Under: more bytes than it claims.
|
// Under: more bytes than it claims.
|
||||||
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
|
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
|
||||||
for cl in ["abc", "-1", "+5", "5 5", "0x5", "", "5;"] {
|
for cl in ["abc", "-1", "+5", "5 5", "0x5", "", "5;"] {
|
||||||
assert_err!(parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")), Error::Malformed { .. }, "{cl:?}");
|
assert_err!(
|
||||||
|
parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{cl:?}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
// Two different lengths.
|
// Two different lengths.
|
||||||
assert_err!(
|
assert_err!(
|
||||||
@@ -125,7 +129,10 @@ fn response_lying_content_length() {
|
|||||||
fn response_header_flood() {
|
fn response_header_flood() {
|
||||||
let names: Vec<String> = (0..=MAX_RTSP_HEADERS).map(|i| format!("X-H{i}")).collect();
|
let names: Vec<String> = (0..=MAX_RTSP_HEADERS).map(|i| format!("X-H{i}")).collect();
|
||||||
let headers = |n: usize| names[..n].iter().map(|n| (n.as_str(), "v")).collect::<Vec<_>>();
|
let headers = |n: usize| names[..n].iter().map(|n| (n.as_str(), "v")).collect::<Vec<_>>();
|
||||||
assert_eq!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(), MAX_RTSP_HEADERS);
|
assert_eq!(
|
||||||
|
parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(),
|
||||||
|
MAX_RTSP_HEADERS
|
||||||
|
);
|
||||||
assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS);
|
assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS);
|
||||||
// A flood of empty-valued headers in under 64 KiB.
|
// A flood of empty-valued headers in under 64 KiB.
|
||||||
let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect();
|
let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect();
|
||||||
@@ -139,7 +146,10 @@ fn response_line_cap() {
|
|||||||
let value = |line: usize| "v".repeat(line - 3);
|
let value = |line: usize| "v".repeat(line - 3);
|
||||||
let ok = value(MAX_RTSP_LINE_BYTES);
|
let ok = value(MAX_RTSP_LINE_BYTES);
|
||||||
assert_eq!(parse_response(&response("200 OK", &[("X", &ok)], b"")).unwrap().header("x"), Some(ok.as_str()));
|
assert_eq!(parse_response(&response("200 OK", &[("X", &ok)], b"")).unwrap().header("x"), Some(ok.as_str()));
|
||||||
assert_cap!(parse_response(&response("200 OK", &[("X", &value(MAX_RTSP_LINE_BYTES + 1))], b"")), MAX_RTSP_LINE_BYTES);
|
assert_cap!(
|
||||||
|
parse_response(&response("200 OK", &[("X", &value(MAX_RTSP_LINE_BYTES + 1))], b"")),
|
||||||
|
MAX_RTSP_LINE_BYTES
|
||||||
|
);
|
||||||
let reason = "r".repeat(MAX_RTSP_LINE_BYTES);
|
let reason = "r".repeat(MAX_RTSP_LINE_BYTES);
|
||||||
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
|
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
|
||||||
}
|
}
|
||||||
@@ -150,7 +160,11 @@ fn response_size_boundaries() {
|
|||||||
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||||
assert_eq!(r.status, 200);
|
assert_eq!(r.status, 200);
|
||||||
}
|
}
|
||||||
assert_too_large!(parse_response(&response_of_size(MAX_RTSP_MESSAGE_BYTES + 1)), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
|
assert_too_large!(
|
||||||
|
parse_response(&response_of_size(MAX_RTSP_MESSAGE_BYTES + 1)),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
assert_too_large!(parse_response(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
|
assert_too_large!(parse_response(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,7 +197,8 @@ fn request_parse_and_encode() {
|
|||||||
(Method::Announce, "ANNOUNCE"),
|
(Method::Announce, "ANNOUNCE"),
|
||||||
(Method::Play, "PLAY"),
|
(Method::Play, "PLAY"),
|
||||||
] {
|
] {
|
||||||
let req = RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] };
|
let req =
|
||||||
|
RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] };
|
||||||
assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes()));
|
assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -194,15 +209,26 @@ fn request_refuses_unknown_methods_and_bad_lines() {
|
|||||||
let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n");
|
let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n");
|
||||||
assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}");
|
assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}");
|
||||||
}
|
}
|
||||||
for bad in [&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"] {
|
for bad in
|
||||||
|
[&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"]
|
||||||
|
{
|
||||||
assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||||
}
|
}
|
||||||
assert_too_large!(parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
|
assert_too_large!(
|
||||||
|
parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn encode_refuses_header_injection() {
|
fn encode_refuses_header_injection() {
|
||||||
let base = || RtspRequest { method: Method::Setup, target: "streamid=video/0/0".into(), headers: vec![("CSeq".into(), "4".into())], body: vec![] };
|
let base = || RtspRequest {
|
||||||
|
method: Method::Setup,
|
||||||
|
target: "streamid=video/0/0".into(),
|
||||||
|
headers: vec![("CSeq".into(), "4".into())],
|
||||||
|
body: vec![],
|
||||||
|
};
|
||||||
let mut cases = Vec::new();
|
let mut cases = Vec::new();
|
||||||
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
|
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
|
||||||
cases.push(RtspRequest { target: evil.into(), ..base() });
|
cases.push(RtspRequest { target: evil.into(), ..base() });
|
||||||
@@ -220,7 +246,13 @@ fn encode_refuses_header_injection() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn method() -> impl Strategy<Value = Method> {
|
fn method() -> impl Strategy<Value = Method> {
|
||||||
prop_oneof![Just(Method::Options), Just(Method::Describe), Just(Method::Setup), Just(Method::Announce), Just(Method::Play)]
|
prop_oneof![
|
||||||
|
Just(Method::Options),
|
||||||
|
Just(Method::Describe),
|
||||||
|
Just(Method::Setup),
|
||||||
|
Just(Method::Announce),
|
||||||
|
Just(Method::Play)
|
||||||
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
proptest! {
|
proptest! {
|
||||||
@@ -331,7 +363,11 @@ fn framer_cap_64k_plus_one() {
|
|||||||
|
|
||||||
// One push over the cap.
|
// One push over the cap.
|
||||||
let mut f = RtspFramer::new();
|
let mut f = RtspFramer::new();
|
||||||
assert_too_large!(f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
|
assert_too_large!(
|
||||||
|
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES + 1]),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
|
||||||
// A whole message of exactly the cap is fine.
|
// A whole message of exactly the cap is fine.
|
||||||
let mut f = RtspFramer::new();
|
let mut f = RtspFramer::new();
|
||||||
@@ -355,10 +391,17 @@ fn framer_refuses_lying_content_length_early() {
|
|||||||
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
|
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
|
||||||
}
|
}
|
||||||
let mut f = RtspFramer::new();
|
let mut f = RtspFramer::new();
|
||||||
assert_cap!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
|
assert_cap!(
|
||||||
|
push_then_next(&mut f, &response("200 OK", &[("Content-Length", "65537")], b"")),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES
|
||||||
|
);
|
||||||
for cl in ["abc", "-1", "1 2"] {
|
for cl in ["abc", "-1", "1 2"] {
|
||||||
let mut f = RtspFramer::new();
|
let mut f = RtspFramer::new();
|
||||||
assert_err!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")), Error::Malformed { .. }, "{cl}");
|
assert_err!(
|
||||||
|
push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{cl}"
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -509,7 +552,10 @@ fn host_capabilities() {
|
|||||||
let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1);
|
let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1);
|
||||||
assert_cap!(HostCapabilities::from_sdp(&sdp::parse_sdp(many.as_bytes()).unwrap()), MAX_OPUS_CONFIGS);
|
assert_cap!(HostCapabilities::from_sdp(&sdp::parse_sdp(many.as_bytes()).unwrap()), MAX_OPUS_CONFIGS);
|
||||||
let max = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS);
|
let max = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS);
|
||||||
assert_eq!(HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(), MAX_OPUS_CONFIGS);
|
assert_eq!(
|
||||||
|
HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(),
|
||||||
|
MAX_OPUS_CONFIGS
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn config() -> StreamConfig {
|
fn config() -> StreamConfig {
|
||||||
@@ -557,7 +603,10 @@ fn announce_refuses_what_the_host_lacks() {
|
|||||||
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
|
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
|
||||||
let mut no_av1 = host.clone();
|
let mut no_av1 = host.clone();
|
||||||
no_av1.av1 = false;
|
no_av1.av1 = false;
|
||||||
assert_err!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &no_av1), Error::Unsupported { .. });
|
assert_err!(
|
||||||
|
sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &no_av1),
|
||||||
|
Error::Unsupported { .. }
|
||||||
|
);
|
||||||
assert!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &host).is_ok());
|
assert!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &host).is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -572,7 +621,11 @@ fn describe_answer(cseq: u32, sdp: &str) -> Vec<u8> {
|
|||||||
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
|
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
|
||||||
response(
|
response(
|
||||||
"200 OK",
|
"200 OK",
|
||||||
&[("CSeq", &cseq.to_string()), ("Session", "DEADBEEFCAFE;timeout = 90"), ("Transport", &format!("server_port={port}"))],
|
&[
|
||||||
|
("CSeq", &cseq.to_string()),
|
||||||
|
("Session", "DEADBEEFCAFE;timeout = 90"),
|
||||||
|
("Transport", &format!("server_port={port}")),
|
||||||
|
],
|
||||||
b"",
|
b"",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -676,7 +729,10 @@ fn client_refuses_hostile_answers() {
|
|||||||
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
|
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
|
||||||
assert_eq!(s, RtspClientState::Failed);
|
assert_eq!(s, RtspClientState::Failed);
|
||||||
|
|
||||||
let (e, s) = run_until_error(|i, n| if i == 1 { response("404 Not Found", &[("CSeq", &n.to_string())], b"") } else { good(i, n) });
|
let (e, s) =
|
||||||
|
run_until_error(
|
||||||
|
|i, n| if i == 1 { response("404 Not Found", &[("CSeq", &n.to_string())], b"") } else { good(i, n) },
|
||||||
|
);
|
||||||
assert_eq!(e, Error::HostStatus { code: 404 });
|
assert_eq!(e, Error::HostStatus { code: 404 });
|
||||||
assert_eq!(s, RtspClientState::Failed);
|
assert_eq!(s, RtspClientState::Failed);
|
||||||
|
|
||||||
@@ -712,7 +768,9 @@ fn client_answer_without_request() {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn client_refuses_bad_setup() {
|
fn client_refuses_bad_setup() {
|
||||||
for url in ["http://192.0.2.10:48010", "rtsp://192.0.2.10", "rtsp://:48010", "", "rtsp://h:99999", "rtsp://h:1\r\nX: y"] {
|
for url in
|
||||||
|
["http://192.0.2.10:48010", "rtsp://192.0.2.10", "rtsp://:48010", "", "rtsp://h:99999", "rtsp://h:1\r\nX: y"]
|
||||||
|
{
|
||||||
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
|
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
|
||||||
}
|
}
|
||||||
for broken in [
|
for broken in [
|
||||||
|
|||||||
@@ -0,0 +1,670 @@
|
|||||||
|
//! The video depacketizer (`docs/PROTOCOL.md` 5) driven with generated loss patterns over multi-block frames:
|
||||||
|
//! random, bursty, all parity lost, all data lost but recoverable, last packet lost, reordered, duplicated,
|
||||||
|
//! sequence and frame index wraps, far-past and far-future packets, encryption. Every frame comes out byte-exact or
|
||||||
|
//! is reported in a `FrameLost` range; never a corrupt frame.
|
||||||
|
//!
|
||||||
|
//! The test host (`common::VideoHost`) packetizes as PROTOCOL.md 5.2-5.3 say, computes parity with the crate's own
|
||||||
|
//! `ReedSolomon::new` (U14 is unknown; `fec.rs` tests the code itself) and writes the parity packets' headers after
|
||||||
|
//! the parity, so bytes 0-31 of any recovered data shard are garbage.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||||
|
|
||||||
|
use common::{SeqRng, VExpect, VPkt, VideoHost, fec_info, video_packet_bytes};
|
||||||
|
use domistream::video::packet::MAX_VIDEO_PACKET_BYTES;
|
||||||
|
use domistream::video::{MAX_FRAMES_IN_FLIGHT, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoStats};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const PACKET_SIZE: u16 = 64; // payload 48 bytes, packet 80 bytes
|
||||||
|
const TIMEOUT: Duration = Duration::from_millis(50);
|
||||||
|
const KEY: [u8; 16] = *b"video-test-key!!";
|
||||||
|
|
||||||
|
fn config(cipher: bool) -> VideoConfig {
|
||||||
|
VideoConfig { packet_size: PACKET_SIZE, cipher: cipher.then(|| VideoCipher::new(KEY)), frame_timeout: TIMEOUT }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One frame of a scenario: its packets as sent and what must come out.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Frame {
|
||||||
|
packets: Vec<VPkt>,
|
||||||
|
expect: VExpect,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frames(rng: &mut SeqRng, host: &mut VideoHost, first_index: u32, n: usize, percentages: &[u8]) -> Vec<Frame> {
|
||||||
|
(0..n)
|
||||||
|
.map(|i| {
|
||||||
|
let len = 10 + rng.below(48 * 14);
|
||||||
|
let bitstream = VideoHost::bitstream(rng, len);
|
||||||
|
let pct = percentages[rng.below(percentages.len())];
|
||||||
|
let blocks = 1 + rng.below(4);
|
||||||
|
let (packets, expect) = host.frame(first_index.wrapping_add(i as u32), &bitstream, pct, blocks);
|
||||||
|
Frame { packets, expect }
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Outcome {
|
||||||
|
Deliver,
|
||||||
|
Lose,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a frame can be rebuilt from the packets that arrive (by shard identity, duplicates counted once).
|
||||||
|
fn outcome(frame: &Frame, arrived: &[&VPkt]) -> Outcome {
|
||||||
|
let mut have: BTreeMap<u8, BTreeSet<u16>> = BTreeMap::new();
|
||||||
|
for p in arrived {
|
||||||
|
have.entry(p.block).or_default().insert(p.shard_index);
|
||||||
|
}
|
||||||
|
let blocks: BTreeMap<u8, u16> = frame.packets.iter().map(|p| (p.block, p.data_shards)).collect();
|
||||||
|
if blocks.iter().all(|(b, k)| have.get(b).map_or(0, BTreeSet::len) >= usize::from(*k)) {
|
||||||
|
Outcome::Deliver
|
||||||
|
} else {
|
||||||
|
Outcome::Lose
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data shards a frame lost (what `recovered_shards` must say when it is delivered).
|
||||||
|
fn data_lost(frame: &Frame, arrived: &[&VPkt]) -> u16 {
|
||||||
|
let got: BTreeSet<(u8, u16)> = arrived.iter().map(|p| (p.block, p.shard_index)).collect();
|
||||||
|
frame.packets.iter().filter(|p| !p.is_parity && !got.contains(&(p.block, p.shard_index))).count() as u16
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Run {
|
||||||
|
events: Vec<VideoEvent>,
|
||||||
|
stats: VideoStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_with(cipher: bool, datagrams: &[Vec<u8>]) -> Run {
|
||||||
|
let mut d = VideoDepacketizer::new(config(cipher)).expect("VideoDepacketizer::new");
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for g in datagrams {
|
||||||
|
d.push(Instant::from_micros(now), g).expect("push never fails for packets within the size cap");
|
||||||
|
now += 10;
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Flush: let every incomplete frame time out.
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
d.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
if d.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Run { events, stats: d.stats() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every Frame event is byte-exact, in order, at most once; every frame marked `Deliver` came out; every frame marked
|
||||||
|
/// `Lose` is in a FrameLost range; nothing is both.
|
||||||
|
fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: &Run) {
|
||||||
|
let pos: HashMap<u32, usize> = frames.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
|
||||||
|
let mut delivered = vec![false; frames.len()];
|
||||||
|
let mut lost = vec![false; frames.len()];
|
||||||
|
let mut last_pos: Option<usize> = None;
|
||||||
|
for e in &run.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
|
||||||
|
let want = &frames[i].expect;
|
||||||
|
assert!(
|
||||||
|
f.bitstream == want.bitstream,
|
||||||
|
"frame {} corrupt: {} bytes, want {}",
|
||||||
|
f.frame_index,
|
||||||
|
f.bitstream.len(),
|
||||||
|
want.bitstream.len()
|
||||||
|
);
|
||||||
|
assert_eq!(f.header.raw, want.header, "frame {} header", f.frame_index);
|
||||||
|
assert_eq!(f.rtp_timestamp, want.rtp_timestamp, "frame {} timestamp", f.frame_index);
|
||||||
|
assert!(f.completed_at >= f.first_packet_at);
|
||||||
|
assert!(!delivered[i], "frame {} delivered twice", f.frame_index);
|
||||||
|
assert!(last_pos.is_none_or(|l| i > l), "frame {} out of order", f.frame_index);
|
||||||
|
if let Some(r) = recovered {
|
||||||
|
assert_eq!(f.recovered_shards, r[i], "frame {} recovered shards", f.frame_index);
|
||||||
|
}
|
||||||
|
last_pos = Some(i);
|
||||||
|
delivered[i] = true;
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => {
|
||||||
|
let span = last.wrapping_sub(*first);
|
||||||
|
assert!(span < 1 << 31, "FrameLost {first}..={last} is not a forward range");
|
||||||
|
for (i, f) in frames.iter().enumerate() {
|
||||||
|
if f.expect.frame_index.wrapping_sub(*first) <= span {
|
||||||
|
lost[i] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, f) in frames.iter().enumerate() {
|
||||||
|
let idx = f.expect.frame_index;
|
||||||
|
assert!(!(delivered[i] && lost[i]), "frame {idx} both delivered and reported lost");
|
||||||
|
match outcomes[i] {
|
||||||
|
Outcome::Deliver => {
|
||||||
|
assert!(delivered[i], "frame {idx} was recoverable but not delivered (lost: {})", lost[i])
|
||||||
|
}
|
||||||
|
Outcome::Lose => assert!(lost[i], "frame {idx} was not recoverable but not reported lost"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a scenario where `keep(frame_number, packet_number_in_frame, packet)` decides what arrives (frames 0 and
|
||||||
|
/// last are always kept whole), optionally reordered and duplicated.
|
||||||
|
fn scenario(
|
||||||
|
seed: u64,
|
||||||
|
n: usize,
|
||||||
|
percentages: &[u8],
|
||||||
|
keep: impl Fn(&mut SeqRng, usize, usize, &VPkt) -> bool,
|
||||||
|
) -> (Vec<Frame>, Vec<Outcome>, Vec<u16>, Vec<Vec<u8>>) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, n, percentages);
|
||||||
|
let mut outcomes = Vec::new();
|
||||||
|
let mut recovered = Vec::new();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let arrived: Vec<&VPkt> = f
|
||||||
|
.packets
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(pi, p)| fi == 0 || fi == n - 1 || keep(&mut rng, fi, *pi, p))
|
||||||
|
.map(|(_, p)| p)
|
||||||
|
.collect();
|
||||||
|
outcomes.push(outcome(f, &arrived));
|
||||||
|
recovered.push(data_lost(f, &arrived));
|
||||||
|
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
(fs, outcomes, recovered, datagrams)
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIXED: &[u8] = &[0, 10, 20, 50, 100, 200];
|
||||||
|
|
||||||
|
// ================================================================================================ patterns
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_loss() {
|
||||||
|
let (fs, out, rec, dg) = scenario(1, 30, MIXED, |_, _, _, _| true);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert_eq!(r.stats.frames, 30);
|
||||||
|
assert_eq!(r.stats.frames_lost, 0);
|
||||||
|
assert_eq!(r.stats.shards_recovered, 0);
|
||||||
|
assert_eq!(r.stats.packets_dropped, 0);
|
||||||
|
assert_eq!(r.stats.packets, dg.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_loss() {
|
||||||
|
for (seed, p) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50), (14, 15), (15, 30)] {
|
||||||
|
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= p);
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
let delivered = out.iter().filter(|o| **o == Outcome::Deliver).count() as u64;
|
||||||
|
assert_eq!(r.stats.frames, delivered, "seed {seed}");
|
||||||
|
// At least the shards of delivered frames; blocks rebuilt inside frames that were lost anyway may add more.
|
||||||
|
assert!(
|
||||||
|
r.stats.shards_recovered
|
||||||
|
>= rec
|
||||||
|
.iter()
|
||||||
|
.zip(&out)
|
||||||
|
.filter(|(_, o)| **o == Outcome::Deliver)
|
||||||
|
.map(|(r, _)| u64::from(*r))
|
||||||
|
.sum::<u64>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bursty_loss() {
|
||||||
|
for seed in 20..26u64 {
|
||||||
|
// One burst of 1..=8 consecutive packets per frame, at a random place.
|
||||||
|
let mut rng = SeqRng::new(seed * 7);
|
||||||
|
let bursts: Vec<(usize, usize)> = (0..40).map(|_| (rng.below(30), 1 + rng.below(8))).collect();
|
||||||
|
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |_, fi, pi, _| {
|
||||||
|
let (start, len) = bursts[fi];
|
||||||
|
!(start..start + len).contains(&pi)
|
||||||
|
});
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
// A burst across a frame boundary: the tail of one frame and the head of the next.
|
||||||
|
let (fs, _, _, _) = scenario(27, 3, &[50], |_, _, _, _| true);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut arrived: Vec<Vec<&VPkt>> = vec![Vec::new(); 3];
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
for (pi, p) in f.packets.iter().enumerate() {
|
||||||
|
let tail = fi == 1 && pi + 2 >= f.packets.len();
|
||||||
|
let head = fi == 2 && pi < 2;
|
||||||
|
if !(tail || head) {
|
||||||
|
arrived[fi].push(p);
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out: Vec<Outcome> = fs.iter().zip(&arrived).map(|(f, a)| outcome(f, a)).collect();
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_parity_lost() {
|
||||||
|
let (fs, out, rec, dg) = scenario(30, 30, &[20, 50, 100], |_, _, _, p| !p.is_parity);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
assert!(rec.iter().all(|r| *r == 0));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_data_lost_but_recoverable() {
|
||||||
|
// 100 % and 200 % FEC: every data shard of a frame lost, rebuilt from parity alone.
|
||||||
|
let (fs, out, rec, dg) = scenario(31, 20, &[100, 200], |_, _, _, p| p.is_parity);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert!(r.stats.shards_recovered > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn last_packet_lost() {
|
||||||
|
// The last packet of each frame (its last parity packet, or the end-of-frame data packet without FEC).
|
||||||
|
let (fs, ..) = scenario(32, 30, MIXED, |_, _, _, _| true);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
let mut outcomes = Vec::new();
|
||||||
|
let mut recovered = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let n = f.packets.len();
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
f.packets.iter().take(if fi == 0 || fi + 1 == fs.len() { n } else { n - 1 }).collect();
|
||||||
|
outcomes.push(outcome(f, &arrived));
|
||||||
|
recovered.push(data_lost(f, &arrived));
|
||||||
|
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
check(&fs, &outcomes, Some(&recovered), &run_with(false, &datagrams));
|
||||||
|
|
||||||
|
// The end-of-frame data packet itself (flags 0x02), with FEC to rebuild it.
|
||||||
|
let (fs, out, rec, dg) = scenario(33, 30, &[20, 50], |_, _, _, p| p.is_parity || p.bytes[24] & 0x02 == 0);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
|
||||||
|
// ... and without FEC: lost.
|
||||||
|
let (fs, out, rec, dg) = scenario(34, 10, &[0], |_, _, _, p| p.bytes[24] & 0x02 == 0);
|
||||||
|
assert!(out[1..9].iter().all(|o| *o == Outcome::Lose));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered() {
|
||||||
|
for seed in 40..46u64 {
|
||||||
|
let (fs, out, _, mut dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
|
||||||
|
// Shuffle within windows spanning about two frames.
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let first_len = fs[0].packets.len();
|
||||||
|
let window = 24;
|
||||||
|
let mut i = first_len; // keep frame 0 first so the stream has a known start
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + window).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicated() {
|
||||||
|
for seed in 50..54u64 {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut with_dups = Vec::new();
|
||||||
|
let mut dups = 0u64;
|
||||||
|
for (i, g) in dg.iter().enumerate() {
|
||||||
|
with_dups.push(g.clone());
|
||||||
|
if i > 0 && rng.below(100) < 30 {
|
||||||
|
// Again now, and an earlier packet again later.
|
||||||
|
with_dups.push(g.clone());
|
||||||
|
with_dups.push(dg[rng.below(i)].clone());
|
||||||
|
dups += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let r = run_with(false, &with_dups);
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(
|
||||||
|
r.stats.packets_dropped >= dups / 2,
|
||||||
|
"duplicates are counted as dropped: {} of {dups}",
|
||||||
|
r.stats.packets_dropped
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_and_duplicated_with_loss() {
|
||||||
|
for seed in 60..64u64 {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= 20);
|
||||||
|
let mut rng = SeqRng::new(seed ^ 0xFF);
|
||||||
|
let mut mixed: Vec<Vec<u8>> = dg
|
||||||
|
.iter()
|
||||||
|
.flat_map(|g| if rng.below(5) == 0 { vec![g.clone(), g.clone()] } else { vec![g.clone()] })
|
||||||
|
.collect();
|
||||||
|
let start = fs[0].packets.len();
|
||||||
|
let mut i = start;
|
||||||
|
while i < mixed.len() {
|
||||||
|
let end = (i + 16).min(mixed.len());
|
||||||
|
rng.shuffle(&mut mixed[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &mixed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ untrusted bytes 0-31
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recovered_shard_headers_are_not_trusted() {
|
||||||
|
// Parity computed over data shards whose bytes 0-31 were scrambled: a rebuilt shard's RTP and NV header bytes
|
||||||
|
// are guaranteed garbage (wrong frame index, flags, FEC fields). Only its payload and its place from the shard
|
||||||
|
// index may be used.
|
||||||
|
let mut rng = SeqRng::new(70);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
host.scramble_parity_headers = true;
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rec = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
// Lose the first data shard of every block (often the start-of-frame packet) and, where the budget allows,
|
||||||
|
// the end-of-frame packet.
|
||||||
|
let arrived: Vec<&VPkt> = f
|
||||||
|
.packets
|
||||||
|
.iter()
|
||||||
|
.filter(|p| {
|
||||||
|
fi == 0 || p.is_parity || (p.shard_index != 0 && !(p.bytes[24] & 0x02 != 0 && p.parity_shards >= 2))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
rec.push(data_lost(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert!(r.stats.shards_recovered >= 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ wraps and strays
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rtp_sequence_wraps_inside_frames() {
|
||||||
|
let mut rng = SeqRng::new(80);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
host.next_sequence = 0xFFE0;
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 20, &[20, 50]);
|
||||||
|
assert!(host.next_sequence < 0xFFE0, "the stream passed 0xFFFF -> 0");
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
f.packets.iter().enumerate().filter(|(pi, _)| fi == 0 || pi % 5 != 1).map(|(_, p)| p).collect();
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_index_wraps() {
|
||||||
|
let mut rng = SeqRng::new(81);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, u32::MAX - 5, 12, &[50]);
|
||||||
|
assert_eq!(fs[6].expect.frame_index, 0);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
// Frame 0 (the one after u32::MAX) is entirely lost; the others lose one packet.
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
if f.expect.frame_index == 0 { vec![] } else { f.packets.iter().skip(usize::from(fi != 0)).collect() };
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
assert_eq!(out[6], Outcome::Lose);
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_past_and_far_future_packets() {
|
||||||
|
let mut rng = SeqRng::new(82);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 5000, 10, &[50]);
|
||||||
|
let mut dg: Vec<Vec<u8>> = fs[..5].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
|
||||||
|
// A stray from long ago, a replay of an already delivered frame, and a lone packet from far ahead.
|
||||||
|
let mut stray = fs[0].packets[0].bytes.clone();
|
||||||
|
stray[20..24].copy_from_slice(&(5000u32 - 1000).to_le_bytes());
|
||||||
|
dg.push(stray);
|
||||||
|
dg.push(fs[1].packets[0].bytes.clone());
|
||||||
|
let mut future = fs[5].packets[0].bytes.clone();
|
||||||
|
future[20..24].copy_from_slice(&(5000u32 + 1_000_000).to_le_bytes());
|
||||||
|
dg.push(future);
|
||||||
|
dg.extend(fs[5..].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
assert!(r.stats.packets_dropped >= 2, "the far-past stray and the replay are dropped: {:?}", r.stats);
|
||||||
|
// Whatever the far-future packet does, no frame comes out corrupt, none twice, and none out of order.
|
||||||
|
let pos: HashMap<u32, usize> = fs.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut prev = None;
|
||||||
|
for e in &r.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
|
||||||
|
assert_eq!(f.bitstream, fs[i].expect.bitstream);
|
||||||
|
assert!(seen.insert(i));
|
||||||
|
assert!(prev.is_none_or(|l| i > l));
|
||||||
|
prev = Some(i);
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(*first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!((0..5).all(|i| seen.contains(&i)), "frames before the strays are delivered");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_packets_inside_a_frame_are_dropped_not_used() {
|
||||||
|
let mut rng = SeqRng::new(83);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 6, &[50]);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
for f in &fs {
|
||||||
|
for p in &f.packets {
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
// Junk carrying the frame's own index: short, long, with impossible FEC fields.
|
||||||
|
let mut short = f.packets[0].bytes.clone();
|
||||||
|
short.truncate(50);
|
||||||
|
let mut long = f.packets[0].bytes.clone();
|
||||||
|
long.extend_from_slice(&[0xEE; 7]);
|
||||||
|
let bad_fec = video_packet_bytes(0, 0, f.expect.frame_index, 0x01, 0, fec_info(50, 900, 2), &[0xEE; 48]);
|
||||||
|
dg.extend([short, long, bad_fec, vec![], vec![0x90]]);
|
||||||
|
}
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
let out = vec![Outcome::Deliver; fs.len()];
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= 5 * fs.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encryption
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encrypted_stream_with_loss_and_tampering() {
|
||||||
|
let mut rng = SeqRng::new(90);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
|
||||||
|
let mut counter = 0u64;
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut tampered = 0u64;
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let mut arrived = Vec::new();
|
||||||
|
for (pi, p) in f.packets.iter().enumerate() {
|
||||||
|
let mut e = common::video_encrypt(&KEY, counter, f.expect.frame_index, &p.bytes);
|
||||||
|
counter += 1;
|
||||||
|
if fi != 0 && pi == 1 {
|
||||||
|
// A flipped ciphertext byte: the tag fails, the packet counts as lost.
|
||||||
|
let last = e.len() - 1;
|
||||||
|
e[last] ^= 0x01;
|
||||||
|
tampered += 1;
|
||||||
|
} else if fi != 0 && rng.below(100) < 10 {
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
arrived.push(p);
|
||||||
|
}
|
||||||
|
dg.push(e);
|
||||||
|
}
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
}
|
||||||
|
let r = run_with(true, &dg);
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= tampered);
|
||||||
|
// The same plaintext packets fed to a receiver that expects encryption are refused, not decoded.
|
||||||
|
let plain: Vec<Vec<u8>> = fs.iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
|
||||||
|
let r = run_with(true, &plain);
|
||||||
|
assert!(r.events.iter().all(|e| !matches!(e, VideoEvent::Frame(_))));
|
||||||
|
assert_eq!(r.stats.packets_dropped, plain.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ API edges
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_bounds() {
|
||||||
|
for ps in [0u16, 1, 15] {
|
||||||
|
assert_err!(
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size: ps, ..config(false) }),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"packet_size {ps}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let max = (MAX_VIDEO_PACKET_BYTES - 16) as u16;
|
||||||
|
assert!(VideoDepacketizer::new(VideoConfig { packet_size: max, ..config(false) }).is_ok());
|
||||||
|
assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: max + 1, ..config(false) }), Error::Malformed { .. });
|
||||||
|
assert_err!(
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size: u16::MAX, ..config(false) }),
|
||||||
|
Error::Malformed { .. }
|
||||||
|
);
|
||||||
|
assert!(VideoDepacketizer::new(VideoConfig { packet_size: 1024, ..config(true) }).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_sizes() {
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
assert_too_large!(
|
||||||
|
d.push(Instant::ZERO, &vec![0; MAX_VIDEO_PACKET_BYTES + 1]),
|
||||||
|
MAX_VIDEO_PACKET_BYTES,
|
||||||
|
MAX_VIDEO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(d.push(Instant::ZERO, &vec![0; 1 << 20]), MAX_VIDEO_PACKET_BYTES, 1 << 20);
|
||||||
|
for g in [vec![], vec![0x90], vec![0; 31], vec![0xFF; 80], vec![0; MAX_VIDEO_PACKET_BYTES]] {
|
||||||
|
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
|
||||||
|
}
|
||||||
|
assert_eq!(d.stats().packets_dropped, 5);
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incomplete_frame_times_out() {
|
||||||
|
let mut rng = SeqRng::new(100);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 2, &[0]);
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
let t0 = Instant::from_micros(5_000_000);
|
||||||
|
for p in &fs[0].packets {
|
||||||
|
d.push(t0, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
match d.poll_event() {
|
||||||
|
Some(VideoEvent::Frame(f)) => {
|
||||||
|
assert_eq!(f.first_packet_at, t0);
|
||||||
|
assert_eq!(f.completed_at, t0);
|
||||||
|
assert_eq!(f.frame_index, 0);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert_eq!(d.poll_timeout(), None, "nothing pending");
|
||||||
|
// Frame 1 without its last packet (no FEC): pending until its timeout.
|
||||||
|
let n = fs[1].packets.len();
|
||||||
|
let t1 = Instant::from_micros(6_000_000);
|
||||||
|
for p in &fs[1].packets[..n - 1] {
|
||||||
|
d.push(t1, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
if n == 1 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
let deadline = d.poll_timeout().expect("a deadline for the incomplete frame");
|
||||||
|
assert!(deadline > t1 && deadline <= t1.saturating_add(TIMEOUT), "{deadline:?}");
|
||||||
|
d.handle_timeout(t1.saturating_add(TIMEOUT / 2)).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), None, "not before the timeout");
|
||||||
|
d.handle_timeout(t1.saturating_add(TIMEOUT)).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), Some(VideoEvent::FrameLost { first: 1, last: 1 }));
|
||||||
|
assert_eq!(d.stats().frames_lost, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frames_in_flight_are_capped() {
|
||||||
|
// One packet each of many incomplete frames: the oldest are declared lost before any timeout.
|
||||||
|
let mut rng = SeqRng::new(101);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, MAX_FRAMES_IN_FLIGHT + 5, &[0]);
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
for p in &fs[0].packets {
|
||||||
|
d.push(Instant::ZERO, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
let mut lost = BTreeSet::new();
|
||||||
|
for f in &fs[1..] {
|
||||||
|
if f.packets.len() < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
d.push(Instant::ZERO, &f.packets[0].bytes).unwrap();
|
||||||
|
}
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
if let VideoEvent::FrameLost { first, last } = e {
|
||||||
|
lost.extend(first..=last);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!lost.is_empty(), "more than MAX_FRAMES_IN_FLIGHT incomplete frames: the oldest must be given up");
|
||||||
|
assert!(!lost.contains(&0));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Random frames, random loss, random reordering: exact or reported lost, never corrupt.
|
||||||
|
#[test]
|
||||||
|
fn generated_patterns(seed in any::<u64>(), loss in 0usize..60, window in 1usize..30, dup in 0usize..30) {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 16, MIXED, move |rng, _, _, _| rng.below(100) >= loss);
|
||||||
|
let mut rng = SeqRng::new(seed.rotate_left(17));
|
||||||
|
let mut mixed: Vec<Vec<u8>> = dg.iter().flat_map(|g| if rng.below(100) < dup { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect();
|
||||||
|
let mut i = fs[0].packets.len();
|
||||||
|
while i < mixed.len() {
|
||||||
|
let end = (i + window).min(mixed.len());
|
||||||
|
rng.shuffle(&mut mixed[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &mixed));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary datagrams never panic, and nothing that comes out is larger than the frame cap.
|
||||||
|
#[test]
|
||||||
|
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..60)) {
|
||||||
|
let r = run_with(false, &datagrams);
|
||||||
|
for e in r.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => prop_assert!(f.bitstream.len() <= domistream::video::MAX_FRAME_BYTES),
|
||||||
|
VideoEvent::FrameLost { first, last } => prop_assert!(last.wrapping_sub(first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
-1
@@ -1,4 +1,4 @@
|
|||||||
# Fuzz targets: one per DomiStream parser. Its own workspace, built only for fuzzing, never released.
|
# Fuzz targets: one per DomiStream parser and state machine; each asserts invariants (round trips, caps). Its own workspace, built only for fuzzing, never released.
|
||||||
#
|
#
|
||||||
# Linux, nightly, cargo-fuzz:
|
# Linux, nightly, cargo-fuzz:
|
||||||
# cargo fuzz run <target> -- -max_total_time=600
|
# cargo fuzz run <target> -- -max_total_time=600
|
||||||
@@ -155,3 +155,59 @@ path = "fuzz_targets/audio_packet.rs"
|
|||||||
test = false
|
test = false
|
||||||
doc = false
|
doc = false
|
||||||
bench = false
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "server_cert_der"
|
||||||
|
path = "fuzz_targets/server_cert_der.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "enet_client"
|
||||||
|
path = "fuzz_targets/enet_client.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "media_decrypt"
|
||||||
|
path = "fuzz_targets/media_decrypt.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "video_depacketizer"
|
||||||
|
path = "fuzz_targets/video_depacketizer.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "audio_depacketizer"
|
||||||
|
path = "fuzz_targets/audio_depacketizer.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "fec_reconstruct"
|
||||||
|
path = "fuzz_targets/fec_reconstruct.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "pairing_session"
|
||||||
|
path = "fuzz_targets/pairing_session.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rtsp_client"
|
||||||
|
path = "fuzz_targets/rtsp_client.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes `/applist` answers: never panics, whatever the bytes.
|
//! Fuzzes `/applist` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": at most MAX_APPS apps, titles within the cap, ids unique.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_app_list(data);
|
let r = domistream::http::parse_app_list(data);
|
||||||
|
if data.len() > MAX_APPLIST_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(apps) = r {
|
||||||
|
assert!(apps.len() <= MAX_APPS);
|
||||||
|
let mut ids: Vec<u32> = apps.iter().map(|a| a.id).collect();
|
||||||
|
ids.sort_unstable();
|
||||||
|
ids.dedup();
|
||||||
|
assert_eq!(ids.len(), apps.len(), "duplicate ids accepted");
|
||||||
|
assert!(apps.iter().all(|a| a.title.len() <= MAX_APP_TITLE_BYTES));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
//! Fuzzes the audio depacketizer with a sequence of datagrams (FEC on, a Cauchy test matrix).
|
||||||
|
//! Asserts invariants, not only "no panic": never two events for one sequence number in a short run; output stays bounded by the input.
|
||||||
|
//! 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::HashSet;
|
||||||
|
|
||||||
|
use domistream::Instant;
|
||||||
|
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioEvent, AudioFec};
|
||||||
|
|
||||||
|
// 1 / (x ^ y) over GF(2^8)/0x11D with x in {0, 1} and y in {2, 3, 4, 5}: a 2 x 4 Cauchy matrix, the same one
|
||||||
|
// tests/common builds with gf::cauchy(2, 4).
|
||||||
|
const MATRIX: [u8; 8] = [0x8e, 0xf4, 0x47, 0xa7, 0xf4, 0x8e, 0xa7, 0x47];
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = AudioConfig {
|
||||||
|
cipher: None,
|
||||||
|
packet_duration_ms: 5,
|
||||||
|
fec: AudioFec::ParityMatrix(MATRIX),
|
||||||
|
loss_timeout: Duration::from_millis(20),
|
||||||
|
};
|
||||||
|
let Ok(mut d) = AudioDepacketizer::new(cfg) else { return };
|
||||||
|
let mut rest = data;
|
||||||
|
let mut us = 0u64;
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut out_bytes = 0usize;
|
||||||
|
while let Some((&len, tail)) = rest.split_first() {
|
||||||
|
let len = usize::from(len).min(tail.len());
|
||||||
|
let (g, tail) = tail.split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
us += 1000;
|
||||||
|
let _ = d.push(Instant::from_micros(us), g);
|
||||||
|
let _ = d.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
let seq = match &e {
|
||||||
|
AudioEvent::Packet { sequence, opus, .. } => {
|
||||||
|
out_bytes += opus.len();
|
||||||
|
*sequence
|
||||||
|
}
|
||||||
|
AudioEvent::Lost { sequence } => *sequence,
|
||||||
|
};
|
||||||
|
assert!(seen.insert(seq), "two events for sequence {seq}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(out_bytes <= data.len() * 2, "FEC rebuilds packets, but not out of nothing");
|
||||||
|
});
|
||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes audio packets: never panics, whatever the bytes.
|
//! Fuzzes audio packets.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": payload types and shard indices are the ones PROTOCOL.md allows; payloads are never empty.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::audio::AudioPacket;
|
||||||
|
use domistream::audio::packet::{AUDIO_FEC_PAYLOAD_TYPE, AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::audio::parse_audio_packet(data);
|
match domistream::audio::parse_audio_packet(data) {
|
||||||
|
Ok(AudioPacket::Data { rtp, payload }) => {
|
||||||
|
assert_eq!(rtp.payload_type, AUDIO_PAYLOAD_TYPE);
|
||||||
|
assert!(!payload.is_empty() && data.len() <= MAX_AUDIO_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
Ok(AudioPacket::Parity { rtp, fec, parity }) => {
|
||||||
|
assert_eq!(rtp.payload_type, AUDIO_FEC_PAYLOAD_TYPE);
|
||||||
|
assert!(fec.shard_index <= 1 && !parity.is_empty());
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,27 @@
|
|||||||
//! Fuzzes encrypted control frames (outer fields): never panics, whatever the bytes.
|
//! Fuzzes encrypted control frames (outer fields), their opening, and seal/open round trips.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": the length field matches the bytes, random frames never pass the GCM tag, and seal then open gives the plaintext back.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES};
|
||||||
|
use domistream::control::{ControlCipher, Direction, parse_encrypted_frame};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::control::parse_encrypted_frame(data);
|
if let Ok(f) = parse_encrypted_frame(data) {
|
||||||
|
assert!(data.len() >= MIN_FRAME_BYTES && data.len() <= MAX_FRAME_BYTES);
|
||||||
|
assert_eq!(f.ciphertext.len() + FRAME_HEADER_LEN, data.len());
|
||||||
|
assert_eq!(&f.tag[..], &data[8..24]);
|
||||||
|
// A fuzzer forging a GCM tag would be a finding of its own.
|
||||||
|
assert_eq!(ControlCipher::new([0x42; 16]).open(Direction::HostToClient, data), Err(domistream::Error::Crypto));
|
||||||
|
}
|
||||||
|
if data.len() >= 4 && data.len() + FRAME_HEADER_LEN <= MAX_FRAME_BYTES {
|
||||||
|
let c = ControlCipher::new([0x24; 16]);
|
||||||
|
let seq = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
|
||||||
|
let sealed = c.seal(seq, Direction::ClientToHost, data).expect("seal");
|
||||||
|
assert_eq!(c.open(Direction::ClientToHost, &sealed), Ok((seq, data.to_vec())));
|
||||||
|
assert!(c.open(Direction::HostToClient, &sealed).is_err());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
//! Fuzzes decrypted control messages from the host: never panics, whatever the bytes.
|
//! Fuzzes decrypted control messages from the host.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": the split matches the length field; a host message always splits as a message; Other keeps the body length.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::control::{HostMessage, parse_host_message, parse_message};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::control::parse_host_message(data);
|
let raw = parse_message(data);
|
||||||
|
if let Ok(r) = raw {
|
||||||
|
assert_eq!(r.body.len() + 4, data.len());
|
||||||
|
assert_eq!(r.message_type, u16::from_le_bytes([data[0], data[1]]));
|
||||||
|
}
|
||||||
|
if let Ok(m) = parse_host_message(data) {
|
||||||
|
assert!(raw.is_ok(), "a host message must split as a message first");
|
||||||
|
if let HostMessage::Other { body_len, .. } = m {
|
||||||
|
assert_eq!(body_len + 4, data.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
//! Fuzzes the ENet client peer: a connecting peer fed a sequence of datagrams.
|
||||||
|
//! Asserts invariants, not only "no panic": never panics; delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse and stay within the MTU.
|
||||||
|
//! 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::enet::protocol::parse_datagram;
|
||||||
|
use domistream::enet::{EnetClient, EnetConfig, EnetEvent, MAX_PACKET_BYTES};
|
||||||
|
use domistream::{Instant, RandomSource};
|
||||||
|
|
||||||
|
struct Fixed;
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(0x5A);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
let Ok(mut c) = EnetClient::connect(cfg, Instant::ZERO, &mut Fixed) else { return };
|
||||||
|
// Datagrams separated by a 2-byte big-endian length; time advances 1 ms per datagram.
|
||||||
|
let mut rest = data;
|
||||||
|
let mut ms = 0u64;
|
||||||
|
while rest.len() >= 2 {
|
||||||
|
let len = usize::from(u16::from_be_bytes([rest[0], rest[1]])).min(rest.len() - 2);
|
||||||
|
let (d, tail) = rest[2..].split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
ms += 1;
|
||||||
|
let now = Instant::from_micros(ms * 1000);
|
||||||
|
let _ = c.handle_datagram(now, d);
|
||||||
|
let _ = c.handle_timeout(now);
|
||||||
|
while let Some(out) = c.poll_transmit(now) {
|
||||||
|
assert!(out.len() <= usize::from(cfg.mtu));
|
||||||
|
parse_datagram(&out).expect("the client's own datagrams parse");
|
||||||
|
}
|
||||||
|
while let Some(e) = c.poll_event() {
|
||||||
|
if let EnetEvent::Received { data, .. } = e {
|
||||||
|
assert!(data.len() <= MAX_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
//! Fuzzes ENet datagrams: never panics, whatever the bytes.
|
//! Fuzzes ENet datagrams.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable and within the datagram and command caps.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::enet::protocol::{MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, encode_datagram, parse_datagram};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::enet::protocol::parse_datagram(data);
|
if let Ok(d) = parse_datagram(data) {
|
||||||
|
assert!(data.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
let bytes = encode_datagram(&d).expect("a parsed datagram encodes");
|
||||||
|
assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
assert_eq!(parse_datagram(&bytes), Ok(d));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
//! Fuzzes Reed-Solomon reconstruction with fuzzer-chosen shapes and erasures.
|
||||||
|
//! Asserts invariants, not only "no panic": up to m erasures always rebuild the encoded data byte-exact; more are refused; hostile shard sets never panic.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::fec::ReedSolomon;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if data.len() < 4 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let k = 1 + usize::from(data[0]) % 32;
|
||||||
|
let m = 1 + usize::from(data[1]) % 16;
|
||||||
|
let len = 1 + usize::from(data[2]) % 32;
|
||||||
|
let Ok(code) = ReedSolomon::new(k, m) else { return };
|
||||||
|
let body = &data[3..];
|
||||||
|
let mut shards: Vec<Vec<u8>> =
|
||||||
|
(0..k).map(|i| (0..len).map(|x| body[(i * len + x) % body.len()]).collect()).collect();
|
||||||
|
shards.extend((0..m).map(|_| vec![0; len]));
|
||||||
|
code.encode(&mut shards).expect("encode");
|
||||||
|
let mask = u32::from(body[body.len() - 1]);
|
||||||
|
let lost: Vec<usize> = (0..k + m).filter(|&i| (mask.rotate_left(i as u32) ^ (i as u32 * 7)) % 3 == 0).collect();
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> =
|
||||||
|
shards.iter().enumerate().map(|(i, v)| (!lost.contains(&i)).then(|| v.clone())).collect();
|
||||||
|
let r = code.reconstruct(&mut s);
|
||||||
|
if lost.len() <= m {
|
||||||
|
r.expect("<= m erasures rebuild");
|
||||||
|
for (a, b) in s.iter().zip(&shards) {
|
||||||
|
assert_eq!(a.as_deref(), Some(b.as_slice()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::Truncated { .. })));
|
||||||
|
}
|
||||||
|
// The raw bytes as a hostile shard set.
|
||||||
|
let mut hostile: Vec<Option<Vec<u8>>> = body.chunks(len).map(|c| (c[0] & 1 == 0).then(|| c.to_vec())).collect();
|
||||||
|
let _ = code.reconstruct(&mut hostile);
|
||||||
|
});
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
//! Fuzzes INPUT_DATA messages: never panics, whatever the bytes.
|
//! Fuzzes INPUT_DATA messages.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable; an accepted message's length field matches.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::input::{MAX_INPUT_MESSAGE_BYTES, encode_input, parse_input};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::input::parse_input(data);
|
if let Ok(e) = parse_input(data) {
|
||||||
|
assert!(data.len() <= MAX_INPUT_MESSAGE_BYTES);
|
||||||
|
assert_eq!(usize::from(u16::from_le_bytes([data[2], data[3]])) + 4, data.len());
|
||||||
|
let bytes = encode_input(&e).expect("a parsed event encodes");
|
||||||
|
assert_eq!(parse_input(&bytes), Ok(e));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
//! Fuzzes `/launch` and `/resume` answers: never panics, whatever the bytes.
|
//! Fuzzes `/launch` and `/resume` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": a session URL is within the cap, starts with rtsp:// and has no control characters.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES, MAX_SESSION_URL_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_launch_response(data);
|
let r = domistream::http::parse_launch_response(data);
|
||||||
|
if data.len() > MAX_LAUNCH_RESPONSE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(l) = r {
|
||||||
|
if let Some(url) = l.session_url {
|
||||||
|
assert!(url.len() <= MAX_SESSION_URL_BYTES);
|
||||||
|
assert!(url.starts_with("rtsp://"));
|
||||||
|
assert!(!url.chars().any(char::is_control));
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
//! Fuzzes the video (AES-GCM) and audio (AES-CBC) decryption of hostile packets.
|
||||||
|
//! Asserts invariants, not only "no panic": random video packets never pass the tag; audio output is shorter than its input, which is whole blocks.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::SessionKeys;
|
||||||
|
use domistream::audio::AudioCipher;
|
||||||
|
use domistream::video::VideoCipher;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Ok(p) = VideoCipher::new([0x42; 16]).decrypt(data) {
|
||||||
|
panic!("forged video packet accepted: {} bytes", p.len());
|
||||||
|
}
|
||||||
|
let seq = data.first().map_or(0, |b| u16::from(*b));
|
||||||
|
if let Ok(p) = AudioCipher::new(&SessionKeys { rikey: [0x42; 16], rikeyid: 7 }).decrypt(seq, data) {
|
||||||
|
assert!(p.len() < data.len() && data.len() % 16 == 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,21 @@
|
|||||||
//! Fuzzes pairing answers: never panics, whatever the bytes.
|
//! Fuzzes pairing answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": decoded values are at most half the body (hex), oversize is TooLarge.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::MAX_PAIR_RESPONSE_BYTES;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::pairing::parse_pair_response(data);
|
let r = domistream::pairing::parse_pair_response(data);
|
||||||
|
if data.len() > MAX_PAIR_RESPONSE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(p) = r {
|
||||||
|
for v in [&p.plain_cert, &p.challenge_response, &p.pairing_secret].into_iter().flatten() {
|
||||||
|
assert!(v.len() * 2 <= data.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
//! Fuzzes the pairing state machine: a session with the test-only identity fed fuzzer bodies at each step.
|
||||||
|
//! Asserts invariants, not only "no panic": a host that knows neither the PIN's key nor the host key never gets the session to Paired, and Failed is terminal.
|
||||||
|
//! 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::pairing::{ClientIdentity, PairingSession, PairingState, PairingStep, Pin};
|
||||||
|
|
||||||
|
const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt");
|
||||||
|
|
||||||
|
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(0x33);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Ok(id) = ClientIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return };
|
||||||
|
let Ok(pin) = Pin::from_digits("4071") else { return };
|
||||||
|
let Ok((mut s, _)) = PairingSession::start(&id, "0123456789ABCDEF", "fuzz", pin, &mut Fixed) else { return };
|
||||||
|
// Bodies separated by 0xFF bytes (never valid in the XML); the HTTP status is always 200.
|
||||||
|
for body in data.split(|b| *b == 0xFF).take(6) {
|
||||||
|
let before = s.state();
|
||||||
|
let r = s.handle_response(&id, 200, body, &mut Fixed);
|
||||||
|
assert!(!matches!(r, Ok(PairingStep::Paired(_))), "paired with a host that cannot know the PIN key");
|
||||||
|
if let PairingState::Failed(_) = before {
|
||||||
|
assert!(r.is_err());
|
||||||
|
assert_eq!(s.state(), before, "Failed is terminal");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Fuzzes the RTP header: never panics, whatever the bytes.
|
//! Fuzzes the RTP header.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": success means at least 12 bytes and version 2, with the fields read big-endian from the bytes.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
@@ -7,5 +7,11 @@
|
|||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtp::parse_rtp_header(data);
|
if let Ok(h) = domistream::rtp::parse_rtp_header(data) {
|
||||||
|
assert!(data.len() >= domistream::rtp::RTP_HEADER_LEN);
|
||||||
|
assert_eq!(h.flags >> 6, 2);
|
||||||
|
assert_eq!(h.flags, data[0]);
|
||||||
|
assert_eq!(h.sequence, u16::from_be_bytes([data[2], data[3]]));
|
||||||
|
assert_eq!(h.timestamp, u32::from_be_bytes([data[4], data[5], data[6], data[7]]));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//! Fuzzes the RTSP client state machine with hostile answers.
|
||||||
|
//! Asserts invariants, not only "no panic": the requests it emits always parse, and it never reports Ready before a full exchange.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::launch::AudioLayout;
|
||||||
|
use domistream::rtsp::client::VideoCodec;
|
||||||
|
use domistream::rtsp::{EncryptionFlags, RtspClient, RtspProgress, StreamConfig, parse_request};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let config = StreamConfig {
|
||||||
|
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(7),
|
||||||
|
};
|
||||||
|
let Ok(mut c) = RtspClient::new("rtsp://192.0.2.10:48010", config) else { return };
|
||||||
|
// Answers separated by NUL bytes.
|
||||||
|
for (answers, answer) in data.split(|b| *b == 0).take(8).enumerate() {
|
||||||
|
if let Some(req) = c.poll_request() {
|
||||||
|
parse_request(&req).expect("the client's requests parse");
|
||||||
|
}
|
||||||
|
if let Ok(RtspProgress::Ready(_)) = c.handle_response(answer) {
|
||||||
|
assert!(answers >= 6, "Ready after {} answers", answers + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,23 +1,37 @@
|
|||||||
//! Fuzzes the RTSP framer over a chunked byte stream: never panics, whatever the bytes.
|
//! Fuzzes the RTSP framer over a chunked byte stream.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": never buffers past the cap, and the messages do not depend on how the stream is chunked (chunked vs one push).
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::{MAX_RTSP_MESSAGE_BYTES, RtspFramer};
|
||||||
|
|
||||||
|
fn frame(stream: &[u8], chunk: usize) -> Option<Vec<Vec<u8>>> {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for piece in stream.chunks(chunk) {
|
||||||
|
f.push(piece).ok()?;
|
||||||
|
assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
while let Some(m) = f.next_message().ok()? {
|
||||||
|
let _ = domistream::rtsp::parse_response(&m);
|
||||||
|
out.push(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(last) = f.finish().ok()? {
|
||||||
|
out.push(last);
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
|
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
|
||||||
let Some((&chunk, rest)) = data.split_first() else { return };
|
let Some((&chunk, rest)) = data.split_first() else { return };
|
||||||
let chunk = usize::from(chunk).max(1);
|
let chunked = frame(rest, usize::from(chunk).max(1));
|
||||||
let mut framer = domistream::rtsp::RtspFramer::new();
|
let whole = frame(rest, rest.len().max(1));
|
||||||
for piece in rest.chunks(chunk) {
|
if let (Some(a), Some(b)) = (&chunked, &whole) {
|
||||||
if framer.push(piece).is_err() {
|
assert_eq!(a, b, "framing depends on chunking");
|
||||||
return;
|
assert!(a.iter().map(Vec::len).sum::<usize>() <= rest.len());
|
||||||
}
|
|
||||||
while let Ok(Some(message)) = framer.next_message() {
|
|
||||||
let _ = domistream::rtsp::parse_response(&message);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
let _ = framer.finish();
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Fuzzes RTSP requests: never panics, whatever the bytes.
|
//! Fuzzes RTSP requests.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
@@ -7,5 +7,8 @@
|
|||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtsp::parse_request(data);
|
if let Ok(req) = domistream::rtsp::parse_request(data) {
|
||||||
|
let bytes = req.encode().expect("a parsed request encodes");
|
||||||
|
assert_eq!(domistream::rtsp::parse_request(&bytes), Ok(req));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
//! Fuzzes RTSP responses: never panics, whatever the bytes.
|
//! Fuzzes RTSP responses.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": header count, line length and body within the caps.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::{MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtsp::parse_response(data);
|
let r = domistream::rtsp::parse_response(data);
|
||||||
|
if data.len() > MAX_RTSP_MESSAGE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(m) = r {
|
||||||
|
assert!(m.headers.len() <= MAX_RTSP_HEADERS);
|
||||||
|
assert!(m.reason.len() <= MAX_RTSP_LINE_BYTES);
|
||||||
|
assert!(m.headers.iter().all(|(k, v)| k.len() + v.len() <= MAX_RTSP_LINE_BYTES));
|
||||||
|
assert!(m.body.len() <= data.len());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,13 +1,32 @@
|
|||||||
//! Fuzzes SDP payloads and the host capabilities read from them: never panics, whatever the bytes.
|
//! Fuzzes SDP payloads, the host capabilities read from them, and `surround-params` values.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": line and config caps hold; every Opus config obeys RFC 7845's rules.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::sdp::{self, MAX_AUDIO_CHANNELS, MAX_OPUS_CONFIGS, MAX_SDP_LINES, OpusConfig};
|
||||||
|
|
||||||
|
fn valid(c: &OpusConfig) {
|
||||||
|
assert!(c.channels >= 1 && usize::from(c.channels) <= MAX_AUDIO_CHANNELS);
|
||||||
|
assert!(c.coupled_streams <= c.streams && c.streams >= 1);
|
||||||
|
assert_eq!(c.mapping.len(), usize::from(c.channels));
|
||||||
|
let total = u16::from(c.streams) + u16::from(c.coupled_streams);
|
||||||
|
assert!(c.mapping.iter().all(|&m| u16::from(m) < total));
|
||||||
|
}
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) {
|
if let Ok(s) = sdp::parse_sdp(data) {
|
||||||
let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp);
|
assert!(s.attributes.len() + s.other.len() <= MAX_SDP_LINES);
|
||||||
|
if let Ok(caps) = domistream::rtsp::HostCapabilities::from_sdp(&s) {
|
||||||
|
assert!(caps.opus_configs.len() <= MAX_OPUS_CONFIGS);
|
||||||
|
caps.opus_configs.iter().for_each(valid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(text) = core::str::from_utf8(data) {
|
||||||
|
if let Ok(c) = sdp::parse_surround_params(text) {
|
||||||
|
valid(&c);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//! Fuzzes stored certificates and identities (`ServerCert::from_der`, `ClientIdentity::from_der`).
|
||||||
|
//! Asserts invariants, not only "no panic": accepted DER round-trips; an identity never loads from a cert and key that do not match (first byte splits the input).
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::{ClientIdentity, ServerCert};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Ok(c) = ServerCert::from_der(data) {
|
||||||
|
assert_eq!(c.der(), data);
|
||||||
|
assert_eq!(c.matches(data), Ok(true));
|
||||||
|
}
|
||||||
|
let Some((&split, rest)) = data.split_first() else { return };
|
||||||
|
let at = (usize::from(split) * rest.len()) / 255;
|
||||||
|
let (cert, key) = rest.split_at(at.min(rest.len()));
|
||||||
|
if let Ok(id) = ClientIdentity::from_der(cert, key) {
|
||||||
|
assert_eq!(id.cert_der(), cert);
|
||||||
|
let sig = id.sign(b"fuzz").expect("a loaded identity signs");
|
||||||
|
ServerCert::from_der(cert).expect("its cert loads").verify(b"fuzz", &sig).expect("key matches cert");
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes the host certificate PEM (`plaincert`): never panics, whatever the bytes.
|
//! Fuzzes the host certificate PEM (`plaincert`).
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": an accepted PEM gives a DER that loads again, equals itself, pins itself, and has a signature.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::ServerCert;
|
||||||
|
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::pairing::ServerCert::from_pem(data);
|
let r = ServerCert::from_pem(data);
|
||||||
|
if data.len() > MAX_CERT_PEM_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(c) = r {
|
||||||
|
assert!(c.der().len() <= MAX_CERT_DER_BYTES);
|
||||||
|
let again = ServerCert::from_der(c.der()).expect("the DER of an accepted PEM loads");
|
||||||
|
assert_eq!(again, c);
|
||||||
|
assert_eq!(c.matches(c.der()), Ok(true));
|
||||||
|
assert!(!c.signature().expect("signature").is_empty());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,26 @@
|
|||||||
//! Fuzzes `/serverinfo` answers: never panics, whatever the bytes.
|
//! Fuzzes `/serverinfo` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": string fields within MAX_SERVERINFO_FIELD_BYTES, required fields non-empty, oversize is TooLarge.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_server_info(data);
|
let r = domistream::http::parse_server_info(data);
|
||||||
|
if data.len() > MAX_SERVERINFO_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(s) = r {
|
||||||
|
for f in [&s.hostname, &s.app_version, &s.unique_id, &s.state] {
|
||||||
|
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
|
||||||
|
}
|
||||||
|
for f in [&s.gfe_version, &s.local_ip].into_iter().flatten() {
|
||||||
|
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
|
||||||
|
}
|
||||||
|
assert!(!s.hostname.is_empty() && !s.unique_id.is_empty());
|
||||||
|
let _ = s.is_busy();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
//! Fuzzes the video depacketizer with a sequence of datagrams.
|
||||||
|
//! Asserts invariants, not only "no panic": frames stay within MAX_FRAME_BYTES and come out in increasing frame order; lost ranges are forward ranges.
|
||||||
|
//! 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::video::{MAX_FRAME_BYTES, VideoConfig, VideoDepacketizer, VideoEvent};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = VideoConfig { packet_size: 64, cipher: None, frame_timeout: Duration::from_millis(20) };
|
||||||
|
let Ok(mut d) = VideoDepacketizer::new(cfg) else { return };
|
||||||
|
let mut rest = data;
|
||||||
|
let mut us = 0u64;
|
||||||
|
let mut prev: Option<u32> = None;
|
||||||
|
// Datagrams separated by a 1-byte length; time advances 1 ms per datagram.
|
||||||
|
while let Some((&len, tail)) = rest.split_first() {
|
||||||
|
let len = usize::from(len).min(tail.len());
|
||||||
|
let (g, tail) = tail.split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
us += 1000;
|
||||||
|
let _ = d.push(Instant::from_micros(us), g);
|
||||||
|
let _ = d.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
assert!(f.bitstream.len() <= MAX_FRAME_BYTES);
|
||||||
|
if let Some(p) = prev {
|
||||||
|
assert!(f.frame_index.wrapping_sub(p).wrapping_sub(1) < 1 << 31, "frame order");
|
||||||
|
}
|
||||||
|
prev = Some(f.frame_index);
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,12 +1,25 @@
|
|||||||
//! Fuzzes video packets and the frame header: never panics, whatever the bytes.
|
//! Fuzzes video packets and the frame header.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": FEC fields are consistent on success, the payload is the rest of the packet, the frame header keeps its raw bytes.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::video::parse_video_packet(data);
|
if let Ok(p) = domistream::video::parse_video_packet(data) {
|
||||||
let _ = domistream::video::packet::parse_frame_header(data);
|
assert!(data.len() >= PAYLOAD_OFFSET && data.len() <= MAX_VIDEO_PACKET_BYTES);
|
||||||
|
assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
|
||||||
|
let f = p.nv.fec;
|
||||||
|
assert!(f.data_shards > 0 && f.block_index <= f.last_block_index && f.last_block_index < 4);
|
||||||
|
let m =
|
||||||
|
domistream::fec::parity_count(usize::from(f.data_shards), f.fec_percentage).expect("a consistent block");
|
||||||
|
assert!(usize::from(f.shard_index) < usize::from(f.data_shards) + m);
|
||||||
|
assert!(usize::from(f.data_shards) + m <= domistream::fec::MAX_SHARDS);
|
||||||
|
}
|
||||||
|
if let Ok(h) = parse_frame_header(data) {
|
||||||
|
assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,43 @@
|
|||||||
//! Fuzzes the XML reader behind every HTTP answer: never panics, whatever the bytes.
|
//! Fuzzes the XML reader behind every HTTP answer, and `parse_status_response` on the same bytes.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": every cap holds on success, size over the cap is TooLarge, and the status parser agrees with the XML parser.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::http::xml::{
|
||||||
|
self, Element, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
|
||||||
|
};
|
||||||
|
|
||||||
|
fn walk(e: &Element, depth: usize, count: &mut usize) {
|
||||||
|
*count += 1;
|
||||||
|
assert!(depth <= MAX_XML_DEPTH);
|
||||||
|
assert!(e.attributes.len() <= MAX_XML_ATTRIBUTES);
|
||||||
|
assert!(e.text.len() <= MAX_XML_TEXT_BYTES);
|
||||||
|
for c in &e.children {
|
||||||
|
walk(c, depth + 1, count);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::xml::parse(data);
|
let parsed = xml::parse(data);
|
||||||
|
if data.len() > MAX_XML_BYTES {
|
||||||
|
assert!(matches!(parsed, Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(d) = &parsed {
|
||||||
|
assert_eq!(d.root.name, "root");
|
||||||
|
let mut count = 0;
|
||||||
|
walk(&d.root, 1, &mut count);
|
||||||
|
assert!(count <= MAX_XML_ELEMENTS);
|
||||||
|
}
|
||||||
|
let status = domistream::http::parse_status_response(data);
|
||||||
|
match (&parsed, &status) {
|
||||||
|
(Ok(d), Ok(())) => assert_eq!(d.status_code, 200),
|
||||||
|
(Ok(d), Err(Error::HostStatus { code })) => assert_eq!(d.status_code, *code),
|
||||||
|
(Ok(_), Err(e)) => panic!("xml parsed but status failed with {e:?}"),
|
||||||
|
(Err(_), Ok(())) => panic!("status accepted what xml refused"),
|
||||||
|
(Err(_), Err(_)) => {}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user