Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| da1f3afd52 | |||
| 948f446a13 | |||
| 71e34e8d9d | |||
| 9c59b69bf0 | |||
| 240190041d | |||
| f3ad3afe00 | |||
| ecc9908082 | |||
| fbfcd588a5 | |||
| fea864d16e | |||
| 38a455a717 | |||
| e4ca1509c8 | |||
| d0fe9a906c | |||
| b261d7ddc9 | |||
| 9d94b66975 | |||
| 7326767f37 |
@@ -21,3 +21,9 @@ rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigin
|
||||
x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing
|
||||
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
||||
zeroize = "1.8" # wipe keys on drop
|
||||
|
||||
# Tests only. proptest without fork/timeout (no subprocesses, no threads); peak_alloc (MIT) is a counting global
|
||||
# allocator, so tests can check that parsers never allocate past their caps without any unsafe code of ours.
|
||||
[dev-dependencies]
|
||||
proptest = { version = "1.12", default-features = false, features = ["std"] }
|
||||
peak_alloc = "0.3"
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,710 @@
|
||||
//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8)
|
||||
//! reference, and builders for video and audio streams. Test code: panics are the way a test fails.
|
||||
|
||||
#![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use domistream::RandomSource;
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ assertions
|
||||
|
||||
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
||||
#[macro_export]
|
||||
macro_rules! assert_err {
|
||||
($e:expr, $p:pat) => {
|
||||
match $e {
|
||||
Err($p) => {}
|
||||
other => panic!("expected Err({}), got {:?}", stringify!($p), other),
|
||||
}
|
||||
};
|
||||
($e:expr, $p:pat, $($ctx:tt)+) => {
|
||||
match $e {
|
||||
Err($p) => {}
|
||||
other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers.
|
||||
#[macro_export]
|
||||
macro_rules! assert_too_large {
|
||||
($e:expr, $max:expr, $actual:expr) => {
|
||||
match $e {
|
||||
Err(domistream::Error::TooLarge { max, actual, .. }) => {
|
||||
assert_eq!(max, $max, "TooLarge.max");
|
||||
assert_eq!(actual, $actual, "TooLarge.actual");
|
||||
}
|
||||
other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ randomness
|
||||
|
||||
/// A seeded, deterministic random source (splitmix64). Never for production.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SeqRng(u64);
|
||||
|
||||
impl SeqRng {
|
||||
pub fn new(seed: u64) -> Self {
|
||||
Self(seed)
|
||||
}
|
||||
|
||||
pub fn next_u64(&mut self) -> u64 {
|
||||
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||
let mut z = self.0;
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
|
||||
/// Uniform in `0..n` (n > 0); bias is irrelevant for test data.
|
||||
pub fn below(&mut self, n: usize) -> usize {
|
||||
(self.next_u64() % n as u64) as usize
|
||||
}
|
||||
|
||||
pub fn bytes(&mut self, n: usize) -> Vec<u8> {
|
||||
let mut v = vec![0; n];
|
||||
self.fill(&mut v);
|
||||
v
|
||||
}
|
||||
|
||||
/// `count` distinct indices from `0..n`, sorted.
|
||||
pub fn subset(&mut self, n: usize, count: usize) -> Vec<usize> {
|
||||
let mut all: Vec<usize> = (0..n).collect();
|
||||
for i in 0..count.min(n) {
|
||||
let j = i + self.below(n - i);
|
||||
all.swap(i, j);
|
||||
}
|
||||
let mut chosen = all[..count.min(n)].to_vec();
|
||||
chosen.sort_unstable();
|
||||
chosen
|
||||
}
|
||||
|
||||
pub fn shuffle<T>(&mut self, items: &mut [T]) {
|
||||
for i in (1..items.len()).rev() {
|
||||
let j = self.below(i + 1);
|
||||
items.swap(i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RandomSource for SeqRng {
|
||||
fn fill(&mut self, dest: &mut [u8]) {
|
||||
for chunk in dest.chunks_mut(8) {
|
||||
let word = self.next_u64().to_le_bytes();
|
||||
chunk.copy_from_slice(&word[..chunk.len()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under
|
||||
/// test draws more than was recorded.
|
||||
#[derive(Debug)]
|
||||
pub struct ScriptedRng {
|
||||
bytes: Vec<u8>,
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl ScriptedRng {
|
||||
pub fn new(bytes: Vec<u8>) -> Self {
|
||||
Self { bytes, pos: 0 }
|
||||
}
|
||||
|
||||
pub fn drawn(&self) -> usize {
|
||||
self.pos
|
||||
}
|
||||
}
|
||||
|
||||
impl RandomSource for ScriptedRng {
|
||||
fn fill(&mut self, dest: &mut [u8]) {
|
||||
let end = self.pos + dest.len();
|
||||
assert!(
|
||||
end <= self.bytes.len(),
|
||||
"the code drew {} random bytes but the recorded transcript holds only {} \
|
||||
(fixture assumption: salt, then C, then secret_c, 16 bytes each)",
|
||||
end,
|
||||
self.bytes.len()
|
||||
);
|
||||
dest.copy_from_slice(&self.bytes[self.pos..end]);
|
||||
self.pos = end;
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ fixtures
|
||||
|
||||
pub fn hex(s: &str) -> Vec<u8> {
|
||||
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
if s == "-" {
|
||||
return Vec::new();
|
||||
}
|
||||
assert!(s.len() % 2 == 0, "odd hex length");
|
||||
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect()
|
||||
}
|
||||
|
||||
pub fn to_hex(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||
}
|
||||
|
||||
pub fn to_hex_upper(b: &[u8]) -> String {
|
||||
b.iter().map(|x| format!("{x:02X}")).collect()
|
||||
}
|
||||
|
||||
/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`.
|
||||
pub struct Vectors(HashMap<String, String>);
|
||||
|
||||
impl Vectors {
|
||||
pub fn parse(text: &str) -> Self {
|
||||
let mut map = HashMap::new();
|
||||
for line in text.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() || line.starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let (k, v) = line.split_once(" = ").expect("fixture line `name = value`");
|
||||
map.insert(k.to_string(), v.to_string());
|
||||
}
|
||||
Self(map)
|
||||
}
|
||||
|
||||
pub fn str(&self, name: &str) -> &str {
|
||||
self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing"))
|
||||
}
|
||||
|
||||
pub fn bytes(&self, name: &str) -> Vec<u8> {
|
||||
hex(self.str(name))
|
||||
}
|
||||
|
||||
pub fn arr16(&self, name: &str) -> [u8; 16] {
|
||||
self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes"))
|
||||
}
|
||||
|
||||
pub fn u32_hex(&self, name: &str) -> u32 {
|
||||
u32::from_str_radix(self.str(name), 16).expect("hex u32")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pairing_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/pairing.txt"))
|
||||
}
|
||||
|
||||
pub fn control_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/control_gcm.txt"))
|
||||
}
|
||||
|
||||
pub fn video_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/video_gcm.txt"))
|
||||
}
|
||||
|
||||
pub fn audio_vectors() -> Vectors {
|
||||
Vectors::parse(include_str!("../fixtures/audio_cbc.txt"))
|
||||
}
|
||||
|
||||
pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem");
|
||||
pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem");
|
||||
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||||
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||||
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||||
|
||||
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||||
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
let mut acc = 0u32;
|
||||
let mut bits = 0;
|
||||
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
|
||||
let v = match c {
|
||||
b'A'..=b'Z' => c - b'A',
|
||||
b'a'..=b'z' => c - b'a' + 26,
|
||||
b'0'..=b'9' => c - b'0' + 52,
|
||||
b'+' => 62,
|
||||
b'/' => 63,
|
||||
b'=' => break,
|
||||
_ => panic!("not base64: {c:#x}"),
|
||||
};
|
||||
acc = (acc << 6) | u32::from(v);
|
||||
bits += 6;
|
||||
if bits >= 8 {
|
||||
bits -= 8;
|
||||
out.push((acc >> bits) as u8);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The DER inside every `-----BEGIN <label>-----` block of a PEM text.
|
||||
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
|
||||
let begin = format!("-----BEGIN {label}-----");
|
||||
let end = format!("-----END {label}-----");
|
||||
let mut out = Vec::new();
|
||||
let mut rest = pem;
|
||||
while let Some(start) = rest.find(&begin) {
|
||||
let after = &rest[start + begin.len()..];
|
||||
let stop = after.find(&end).expect("PEM end line");
|
||||
out.push(base64_decode(&after[..stop]));
|
||||
rest = &after[stop + end.len()..];
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ HTTP helpers
|
||||
|
||||
/// Splits a `path?query` into the path and its decoded parameters, in order.
|
||||
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
|
||||
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
|
||||
let params = query
|
||||
.split('&')
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| {
|
||||
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||||
(percent_decode(k), percent_decode(v))
|
||||
})
|
||||
.collect();
|
||||
(path.to_string(), params)
|
||||
}
|
||||
|
||||
pub fn percent_decode(s: &str) -> String {
|
||||
let b = s.as_bytes();
|
||||
let mut out = Vec::new();
|
||||
let mut i = 0;
|
||||
while i < b.len() {
|
||||
if b[i] == b'%' && i + 2 < b.len() {
|
||||
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
|
||||
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
|
||||
i += 3;
|
||||
} else if b[i] == b'+' {
|
||||
out.push(b' ');
|
||||
i += 1;
|
||||
} else {
|
||||
out.push(b[i]);
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
String::from_utf8(out).expect("decoded query is UTF-8")
|
||||
}
|
||||
|
||||
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
|
||||
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
|
||||
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
|
||||
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
|
||||
&found[0].1
|
||||
}
|
||||
|
||||
/// `<root status_code="200">` + elements + `</root>`.
|
||||
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
|
||||
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
|
||||
}
|
||||
|
||||
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
|
||||
/// single text is long and the element count stays small.
|
||||
pub fn xml_filler(len: usize) -> String {
|
||||
assert!(len >= 7, "filler needs at least 7 bytes");
|
||||
let mut out = String::with_capacity(len);
|
||||
let mut remaining = len;
|
||||
while remaining > 0 {
|
||||
let piece = if remaining <= 207 {
|
||||
remaining
|
||||
} else if remaining - 207 >= 7 {
|
||||
207
|
||||
} else {
|
||||
remaining - 7
|
||||
};
|
||||
out.push_str("<x>");
|
||||
out.extend(std::iter::repeat_n('a', piece - 7));
|
||||
out.push_str("</x>");
|
||||
remaining -= piece;
|
||||
}
|
||||
assert_eq!(out.len(), len);
|
||||
out
|
||||
}
|
||||
|
||||
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
|
||||
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
|
||||
let bare = xml_root(200, inner).len();
|
||||
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
|
||||
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
|
||||
assert_eq!(doc.len(), total);
|
||||
doc
|
||||
}
|
||||
|
||||
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
|
||||
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||||
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
|
||||
if cur.len() == size {
|
||||
out.push(cur.clone());
|
||||
return;
|
||||
}
|
||||
for i in start..n {
|
||||
cur.push(i);
|
||||
go(i + 1, n, size, cur, out);
|
||||
cur.pop();
|
||||
}
|
||||
}
|
||||
let mut out = Vec::new();
|
||||
go(0, n, size, &mut Vec::new(), &mut out);
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||||
|
||||
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
|
||||
pub mod gf {
|
||||
pub fn mul(mut a: u8, mut b: u8) -> u8 {
|
||||
let mut p = 0u8;
|
||||
while b != 0 {
|
||||
if b & 1 != 0 {
|
||||
p ^= a;
|
||||
}
|
||||
let carry = a & 0x80 != 0;
|
||||
a <<= 1;
|
||||
if carry {
|
||||
a ^= 0x1D;
|
||||
}
|
||||
b >>= 1;
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
pub fn inv(a: u8) -> u8 {
|
||||
assert!(a != 0, "no inverse of 0");
|
||||
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
|
||||
}
|
||||
|
||||
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
|
||||
/// invertible, so `[I; C]` is MDS.
|
||||
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
|
||||
assert!(rows + cols <= 256);
|
||||
let mut m = Vec::with_capacity(rows * cols);
|
||||
for i in 0..rows {
|
||||
for j in 0..cols {
|
||||
m.push(inv((i as u8) ^ ((rows + j) as u8)));
|
||||
}
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// Parity shards for `data` with a row-major `parity × data` matrix.
|
||||
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
|
||||
let k = data.len();
|
||||
let len = data[0].len();
|
||||
(0..parity)
|
||||
.map(|r| (0..len).map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x]))).collect())
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ video
|
||||
|
||||
/// One video packet as the test host built it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VPkt {
|
||||
pub bytes: Vec<u8>,
|
||||
pub frame_index: u32,
|
||||
pub block: u8,
|
||||
pub shard_index: u16,
|
||||
pub data_shards: u16,
|
||||
pub parity_shards: u16,
|
||||
pub is_parity: bool,
|
||||
}
|
||||
|
||||
/// What a frame should come out as.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VExpect {
|
||||
pub frame_index: u32,
|
||||
pub header: [u8; 8],
|
||||
pub bitstream: Vec<u8>,
|
||||
pub rtp_timestamp: u32,
|
||||
}
|
||||
|
||||
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct VideoHost {
|
||||
pub packet_size: u16,
|
||||
pub next_sequence: u16,
|
||||
pub timestamp: u32,
|
||||
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
|
||||
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
|
||||
pub scramble_parity_headers: bool,
|
||||
}
|
||||
|
||||
impl VideoHost {
|
||||
pub fn new(packet_size: u16) -> Self {
|
||||
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
|
||||
}
|
||||
|
||||
pub fn payload_len(&self) -> usize {
|
||||
usize::from(self.packet_size) - 16
|
||||
}
|
||||
|
||||
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
|
||||
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
|
||||
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||||
let mut b = vec![0, 0, 0, 1, 0x65];
|
||||
b.extend(rng.bytes(len.saturating_sub(6)));
|
||||
b.push(0x80 | rng.bytes(1)[0]);
|
||||
b
|
||||
}
|
||||
|
||||
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
|
||||
pub fn frame(
|
||||
&mut self,
|
||||
frame_index: u32,
|
||||
bitstream: &[u8],
|
||||
fec_percentage: u8,
|
||||
blocks: usize,
|
||||
) -> (Vec<VPkt>, VExpect) {
|
||||
let payload_len = self.payload_len();
|
||||
let total_len = 8 + bitstream.len();
|
||||
let shards_total = total_len.div_ceil(payload_len);
|
||||
let last_payload_len = total_len - (shards_total - 1) * payload_len;
|
||||
let mut header = [0u8; 8];
|
||||
header[0] = 0x01;
|
||||
header[1..3].copy_from_slice(&7u16.to_le_bytes());
|
||||
header[3] = 2; // key frame
|
||||
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
|
||||
let mut data = header.to_vec();
|
||||
data.extend_from_slice(bitstream);
|
||||
data.resize(shards_total * payload_len, 0);
|
||||
|
||||
let blocks = blocks.clamp(1, 4).min(shards_total);
|
||||
let base = shards_total / blocks;
|
||||
let extra = shards_total % blocks;
|
||||
let last_block = (blocks - 1) as u8;
|
||||
let mut packets = Vec::new();
|
||||
let mut shard_offset = 0;
|
||||
for b in 0..blocks {
|
||||
let k = base + usize::from(b < extra);
|
||||
let m = (k * usize::from(fec_percentage)).div_ceil(100);
|
||||
assert!(k + m <= 255, "test frame needs k + m <= 255");
|
||||
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||||
for i in 0..k {
|
||||
let global = shard_offset + i;
|
||||
let mut flags = 0x01;
|
||||
if global == 0 {
|
||||
flags |= 0x04;
|
||||
}
|
||||
if global == shards_total - 1 {
|
||||
flags |= 0x02;
|
||||
}
|
||||
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
|
||||
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
|
||||
shards.push(p);
|
||||
}
|
||||
if m > 0 {
|
||||
let code = domistream::fec::ReedSolomon::new(k, m)
|
||||
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
|
||||
let shard_len = shards[0].len();
|
||||
let mut work: Vec<Vec<u8>> = shards.clone();
|
||||
if self.scramble_parity_headers {
|
||||
for (i, s) in work.iter_mut().enumerate() {
|
||||
for (x, byte) in s[..32].iter_mut().enumerate() {
|
||||
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
work.extend((0..m).map(|_| vec![0u8; shard_len]));
|
||||
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
|
||||
for j in 0..m {
|
||||
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
|
||||
p.extend_from_slice(&work[k + j][32..]);
|
||||
shards.push(p);
|
||||
}
|
||||
}
|
||||
for (i, bytes) in shards.into_iter().enumerate() {
|
||||
packets.push(VPkt {
|
||||
bytes,
|
||||
frame_index,
|
||||
block: b as u8,
|
||||
shard_index: i as u16,
|
||||
data_shards: k as u16,
|
||||
parity_shards: m as u16,
|
||||
is_parity: i >= k,
|
||||
});
|
||||
}
|
||||
shard_offset += k;
|
||||
}
|
||||
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
|
||||
self.timestamp = self.timestamp.wrapping_add(1500);
|
||||
(packets, expect)
|
||||
}
|
||||
|
||||
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
|
||||
/// timestamp).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn header(
|
||||
&mut self,
|
||||
frame_index: u32,
|
||||
flags: u8,
|
||||
block: u8,
|
||||
last_block: u8,
|
||||
shard_index: usize,
|
||||
data_shards: usize,
|
||||
fec_percentage: u8,
|
||||
) -> Vec<u8> {
|
||||
let seq = self.next_sequence;
|
||||
self.next_sequence = self.next_sequence.wrapping_add(1);
|
||||
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
|
||||
p.extend_from_slice(&[0x90, 0x00]);
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(&self.timestamp.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.extend_from_slice(&[0; 4]);
|
||||
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||||
p.extend_from_slice(&frame_index.to_le_bytes());
|
||||
p.push(flags);
|
||||
p.push(0);
|
||||
p.push(0x10);
|
||||
p.push((block << 4) | (last_block << 6));
|
||||
let fec_info = (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
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn video_packet_bytes(
|
||||
seq: u16,
|
||||
timestamp: u32,
|
||||
frame_index: u32,
|
||||
flags: u8,
|
||||
multi_fec_blocks: u8,
|
||||
fec_info: u32,
|
||||
payload: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let mut p = vec![0x90, 0x00];
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(×tamp.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.extend_from_slice(&[0; 4]);
|
||||
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||||
p.extend_from_slice(&frame_index.to_le_bytes());
|
||||
p.extend_from_slice(&[flags, 0, 0x10, multi_fec_blocks]);
|
||||
p.extend_from_slice(&fec_info.to_le_bytes());
|
||||
p.extend_from_slice(payload);
|
||||
p
|
||||
}
|
||||
|
||||
pub fn fec_info(fec_percentage: u8, shard_index: u16, data_shards: u16) -> u32 {
|
||||
(u32::from(fec_percentage) << 4) | (u32::from(shard_index) << 12) | (u32::from(data_shards) << 22)
|
||||
}
|
||||
|
||||
/// AES-128-GCM sealing of a plaintext video packet with the layout of `docs/PROTOCOL.md` 7, using RustCrypto as
|
||||
/// the test oracle (checked against the .NET vectors in `media.rs`).
|
||||
pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: &[u8]) -> Vec<u8> {
|
||||
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||
let cipher = aes_gcm::Aes128Gcm::new_from_slice(key).expect("key");
|
||||
let mut iv = [0u8; 12];
|
||||
iv[..8].copy_from_slice(&counter.to_le_bytes());
|
||||
iv[11] = b'V';
|
||||
let mut buf = plaintext.to_vec();
|
||||
let tag = cipher.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into()).expect("gcm encrypt");
|
||||
let mut out = iv.to_vec();
|
||||
out.extend_from_slice(&frame_number.to_le_bytes());
|
||||
out.extend_from_slice(tag.as_slice());
|
||||
out.extend_from_slice(&buf);
|
||||
out
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ audio
|
||||
|
||||
/// AES-128-CBC + PKCS#7 with the audio IV of `docs/PROTOCOL.md` 6.3 (`rikeyid + seq`, wrapping), RustCrypto as
|
||||
/// the test oracle (checked against the openssl vectors in `media.rs`).
|
||||
pub fn audio_encrypt(key: &[u8; 16], rikeyid: u32, seq: u16, plaintext: &[u8]) -> Vec<u8> {
|
||||
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||||
let mut iv = [0u8; 16];
|
||||
iv[..4].copy_from_slice(&rikeyid.wrapping_add(u32::from(seq)).to_be_bytes());
|
||||
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
|
||||
buf[..plaintext.len()].copy_from_slice(plaintext);
|
||||
let len = cbc::Encryptor::<aes::Aes128>::new(key.into(), &iv.into())
|
||||
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
|
||||
.expect("cbc encrypt")
|
||||
.len();
|
||||
buf.truncate(len);
|
||||
buf
|
||||
}
|
||||
|
||||
/// One audio packet as the test host built it.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct APkt {
|
||||
pub bytes: Vec<u8>,
|
||||
pub sequence: u16,
|
||||
pub block: usize,
|
||||
/// 0..4 data, 4..6 parity.
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
/// What a data packet should come out as.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct AExpect {
|
||||
pub sequence: u16,
|
||||
pub timestamp_ms: u32,
|
||||
pub opus: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Parity packets' RTP sequence number: "continues after the 4 data packets" (PROTOCOL.md 6.2), read as
|
||||
/// base + 4 + shard index. The depacketizer must key parity by the FEC header's base sequence, not by this.
|
||||
pub fn audio_parity_rtp_sequence(base: u16, shard: u8) -> u16 {
|
||||
base.wrapping_add(4).wrapping_add(u16::from(shard))
|
||||
}
|
||||
|
||||
/// A test host for audio: blocks of 4 data + 2 parity packets (`docs/PROTOCOL.md` 6.2-6.4).
|
||||
pub struct AudioHost {
|
||||
pub key: [u8; 16],
|
||||
pub rikeyid: u32,
|
||||
pub encrypt: bool,
|
||||
pub matrix: [u8; 8],
|
||||
pub duration_ms: u32,
|
||||
pub opus_len: usize,
|
||||
}
|
||||
|
||||
impl AudioHost {
|
||||
/// `blocks` consecutive blocks starting at `first_seq` (a multiple of 4) and `first_ts`.
|
||||
pub fn blocks(&self, rng: &mut SeqRng, first_seq: u16, first_ts: u32, blocks: usize) -> (Vec<APkt>, Vec<AExpect>) {
|
||||
assert_eq!(first_seq % 4, 0);
|
||||
let mut packets = Vec::new();
|
||||
let mut expect = Vec::new();
|
||||
for b in 0..blocks {
|
||||
let base_seq = first_seq.wrapping_add((4 * b) as u16);
|
||||
let base_ts = first_ts.wrapping_add(4 * b as u32 * self.duration_ms);
|
||||
let mut shards = Vec::new();
|
||||
for i in 0..4u16 {
|
||||
let seq = base_seq.wrapping_add(i);
|
||||
let ts = base_ts.wrapping_add(u32::from(i) * self.duration_ms);
|
||||
let opus = rng.bytes(self.opus_len);
|
||||
let payload =
|
||||
if self.encrypt { audio_encrypt(&self.key, self.rikeyid, seq, &opus) } else { opus.clone() };
|
||||
let mut p = vec![0x80, 97];
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(&ts.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.extend_from_slice(&payload);
|
||||
packets.push(APkt { bytes: p, sequence: seq, block: b, index: usize::from(i) });
|
||||
expect.push(AExpect { sequence: seq, timestamp_ms: ts, opus });
|
||||
shards.push(payload);
|
||||
}
|
||||
let parity = gf::encode(&self.matrix, &shards, 2);
|
||||
for (j, par) in parity.iter().enumerate() {
|
||||
let seq = audio_parity_rtp_sequence(base_seq, j as u8);
|
||||
let mut p = vec![0x80, 127];
|
||||
p.extend_from_slice(&seq.to_be_bytes());
|
||||
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.push(j as u8);
|
||||
p.push(97);
|
||||
p.extend_from_slice(&base_seq.to_be_bytes());
|
||||
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||
p.extend_from_slice(&0u32.to_be_bytes());
|
||||
p.extend_from_slice(par);
|
||||
packets.push(APkt { bytes: p, sequence: seq, block: b, index: 4 + j });
|
||||
}
|
||||
}
|
||||
(packets, expect)
|
||||
}
|
||||
}
|
||||
|
||||
/// The 2 × 4 Cauchy parity matrix the audio tests pass through `AudioFec::ParityMatrix` (U16 is unmeasured; any
|
||||
/// MDS matrix must work).
|
||||
pub fn audio_test_matrix() -> [u8; 8] {
|
||||
gf::cauchy(2, 4).try_into().expect("2x4")
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,684 @@
|
||||
//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
|
||||
//! status answers, and the request builders. Every case asserts a specific result.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{param, parse_query, xml_padded_to, xml_root};
|
||||
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::{self, Scheme};
|
||||
use proptest::prelude::*;
|
||||
|
||||
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
|
||||
macro_rules! assert_cap {
|
||||
($e:expr, $max:expr) => {
|
||||
match $e {
|
||||
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
||||
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// ================================================================================================ XML
|
||||
|
||||
#[test]
|
||||
fn xml_minimal_documents() {
|
||||
let d = xml::parse(br#"<root status_code="200"/>"#).unwrap();
|
||||
assert_eq!(d.status_code, 200);
|
||||
assert_eq!(d.status_message, None);
|
||||
assert_eq!(d.root.name, "root");
|
||||
assert!(d.root.children.is_empty());
|
||||
|
||||
let d = xml::parse(br#"<?xml version="1.0" encoding="utf-8"?><root status_code="200"></root>"#).unwrap();
|
||||
assert_eq!(d.status_code, 200);
|
||||
|
||||
let d = xml::parse(br#"<root status_code="401" status_message="The client is not authorized"/>"#).unwrap();
|
||||
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
|
||||
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_tree_text_and_attributes() {
|
||||
let d = xml::parse(br#"<root status_code="200" a="1"><x k="v&w">t1<y/>t2</x><z><>&"'AB</z></root>"#)
|
||||
.unwrap();
|
||||
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
|
||||
let x = &d.root.children[0];
|
||||
assert_eq!(x.name, "x");
|
||||
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
|
||||
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
|
||||
assert_eq!(x.children[0].name, "y");
|
||||
assert_eq!(d.root.children[1].text, "<>&\"'AB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_text_is_not_trimmed() {
|
||||
let d = xml::parse(b"<root status_code=\"200\"><a> x \n</a></root>").unwrap();
|
||||
assert_eq!(d.root.children[0].text, " x \n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_empty_and_tiny_inputs() {
|
||||
assert_err!(xml::parse(b""), Error::Malformed { .. });
|
||||
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
|
||||
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
|
||||
assert_err!(xml::parse(b"<root"), Error::Malformed { .. });
|
||||
assert_err!(xml::parse(b"<root status_code=\"200\">"), Error::Malformed { .. }, "unclosed root");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_refuses_non_documents() {
|
||||
for (bad, why) in [
|
||||
(&br#"<other status_code="200"/>"#[..], "root must be `root`"),
|
||||
(br#"<root/>"#, "no status_code"),
|
||||
(br#"<root status_code="abc"/>"#, "status_code not decimal"),
|
||||
(br#"<root status_code=""/>"#, "empty status_code"),
|
||||
(br#"<root status_code="99999999999"/>"#, "status_code over u32"),
|
||||
(br#"<root status_code="-200"/>"#, "negative status_code"),
|
||||
(br#"<root status_code=200/>"#, "unquoted attribute"),
|
||||
(br#"<root status_code="200" status_code="200"/>"#, "duplicate attribute"),
|
||||
(br#"<root status_code="200"><a></b></root>"#, "mismatched end tag"),
|
||||
(br#"<root status_code="200"><a></root>"#, "unclosed child"),
|
||||
(br#"<root status_code="200"/><root status_code="200"/>"#, "two roots"),
|
||||
(br#"<root status_code="200"/>garbage"#, "text after the root"),
|
||||
(br#"<root status_code="200">&unknown;</root>"#, "unknown entity"),
|
||||
(br#"<root status_code="200">&</root>"#, "entity without ;"),
|
||||
(br#"<root status_code="200">a & b</root>"#, "bare &"),
|
||||
(br#"<root status_code="200">�</root>"#, "NUL character reference"),
|
||||
(br#"<root status_code="200">�</root>"#, "surrogate character reference"),
|
||||
(br#"<root status_code="200">�</root>"#, "character reference past Unicode"),
|
||||
(br#"<root status_code="200">�</root>"#, "overflowing character reference"),
|
||||
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
|
||||
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
|
||||
(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#"<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#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
|
||||
(b"<root status_code=\"200\">\xff\xfe</root>", "not UTF-8"),
|
||||
(b"<root status_code=\"200\">\xc3</root>", "truncated UTF-8"),
|
||||
(br#"<1root status_code="200"/>"#, "bad name"),
|
||||
] {
|
||||
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_billion_laughs_is_refused_without_expansion() {
|
||||
let mut doc = String::from("<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\">");
|
||||
for i in 1..10 {
|
||||
doc.push_str(&format!("<!ENTITY lol{i} \"{}\">", format!("&lol{};", i - 1).repeat(10)));
|
||||
}
|
||||
doc.push_str("]><root status_code=\"200\">&lol9;</root>");
|
||||
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_size_boundaries() {
|
||||
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
|
||||
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
|
||||
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
|
||||
assert_eq!(d.status_code, 200);
|
||||
}
|
||||
let over = xml_padded_to("", MAX_XML_BYTES + 1);
|
||||
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
||||
// Huge: refused on size alone, whatever the content.
|
||||
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
|
||||
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
|
||||
}
|
||||
|
||||
fn nested(depth: usize) -> Vec<u8> {
|
||||
// root is depth 1
|
||||
let mut s = String::from("<root status_code=\"200\">");
|
||||
for _ in 1..depth {
|
||||
s.push_str("<a>");
|
||||
}
|
||||
for _ in 1..depth {
|
||||
s.push_str("</a>");
|
||||
}
|
||||
s.push_str("</root>");
|
||||
s.into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_depth_cap() {
|
||||
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
|
||||
let mut e = &d.root;
|
||||
let mut depth = 1;
|
||||
while let Some(c) = e.children.first() {
|
||||
e = c;
|
||||
depth += 1;
|
||||
}
|
||||
assert_eq!(depth, MAX_XML_DEPTH);
|
||||
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_depth_bomb_does_not_recurse() {
|
||||
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
|
||||
let mut s = String::from("<root status_code=\"200\">");
|
||||
s.push_str(&"<a>".repeat(300_000));
|
||||
assert!(s.len() < MAX_XML_BYTES);
|
||||
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
||||
// Same with the closing tags present.
|
||||
s.push_str(&"</a>".repeat(300_000));
|
||||
s.push_str("</root>");
|
||||
assert!(s.len() < MAX_XML_BYTES * 2);
|
||||
if s.len() <= MAX_XML_BYTES {
|
||||
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_element_cap() {
|
||||
let ok = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS - 1));
|
||||
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
|
||||
let over = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS));
|
||||
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_attribute_cap() {
|
||||
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
|
||||
let ok = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES));
|
||||
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
|
||||
let over = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES + 1));
|
||||
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn xml_text_cap_counts_unescaped_bytes() {
|
||||
let ok = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES)));
|
||||
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
||||
let over = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
|
||||
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
||||
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
|
||||
let ok = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES)));
|
||||
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
||||
let over = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES + 1)));
|
||||
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ XML properties
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct Tree {
|
||||
name: String,
|
||||
attrs: Vec<(String, String)>,
|
||||
text: String,
|
||||
children: Vec<Tree>,
|
||||
}
|
||||
|
||||
fn escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
||||
}
|
||||
|
||||
fn serialize(t: &Tree, out: &mut String) {
|
||||
out.push('<');
|
||||
out.push_str(&t.name);
|
||||
for (k, v) in &t.attrs {
|
||||
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
|
||||
}
|
||||
out.push('>');
|
||||
out.push_str(&escape(&t.text));
|
||||
for c in &t.children {
|
||||
serialize(c, out);
|
||||
}
|
||||
out.push_str(&format!("</{}>", t.name));
|
||||
}
|
||||
|
||||
fn same(e: &xml::Element, t: &Tree) -> bool {
|
||||
e.name == t.name
|
||||
&& e.attributes == t.attrs
|
||||
&& e.text == t.text
|
||||
&& e.children.len() == t.children.len()
|
||||
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
|
||||
}
|
||||
|
||||
fn tree(depth: u32) -> impl Strategy<Value = Tree> {
|
||||
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
|
||||
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
|
||||
let text = "[ -~&<>\"'é]{0,12}";
|
||||
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
|
||||
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::<Vec<_>>());
|
||||
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
|
||||
name: name.to_string(),
|
||||
attrs,
|
||||
text,
|
||||
children: vec![],
|
||||
});
|
||||
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(|(name, attrs, text, children)| Tree { name, attrs, text, children })
|
||||
})
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
|
||||
#[test]
|
||||
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
|
||||
let root = Tree {
|
||||
name: "root".into(),
|
||||
attrs: vec![("status_code".into(), code.to_string())],
|
||||
text: String::new(),
|
||||
children,
|
||||
};
|
||||
let mut s = String::new();
|
||||
serialize(&root, &mut s);
|
||||
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
|
||||
prop_assert_eq!(d.status_code, code);
|
||||
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
|
||||
}
|
||||
|
||||
/// Arbitrary bytes: never panics; any success respects every cap.
|
||||
#[test]
|
||||
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
|
||||
if let Ok(d) = xml::parse(&data) {
|
||||
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
|
||||
*count += 1;
|
||||
depth <= MAX_XML_DEPTH
|
||||
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
|
||||
&& e.text.len() <= MAX_XML_TEXT_BYTES
|
||||
&& e.children.iter().all(|c| walk(c, depth + 1, count))
|
||||
}
|
||||
let mut count = 0;
|
||||
prop_assert!(walk(&d.root, 1, &mut count));
|
||||
prop_assert!(count <= MAX_XML_ELEMENTS);
|
||||
prop_assert_eq!(d.root.name.as_str(), "root");
|
||||
}
|
||||
}
|
||||
|
||||
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
|
||||
#[test]
|
||||
fn xml_truncation_is_an_error(cut in 0usize..60) {
|
||||
let doc = br#"<root status_code="200"><a k="v">text&</a><b/></root>"#;
|
||||
let cut = cut.min(doc.len() - 1);
|
||||
prop_assert!(xml::parse(&doc[..cut]).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================ serverinfo
|
||||
|
||||
const SERVERINFO: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n\
|
||||
<hostname>LAB-PC</hostname>\n<appversion>7.1.431.-1</appversion>\n<GfeVersion>3.23.0.74</GfeVersion>\n\
|
||||
<uniqueid>0123456789ABCDEF0123456789ABCDEF</uniqueid>\n<HttpsPort>47984</HttpsPort>\n\
|
||||
<ExternalPort>47989</ExternalPort>\n<mac>00:11:22:aa:BB:ff</mac>\n<LocalIP>192.0.2.10</LocalIP>\n\
|
||||
<MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC>\n<ServerCodecModeSupport>259</ServerCodecModeSupport>\n\
|
||||
<SupportedDisplayMode></SupportedDisplayMode>\n<PairStatus>0</PairStatus>\n<currentgame>0</currentgame>\n\
|
||||
<state>SUNSHINE_SERVER_FREE</state>\n</root>\n";
|
||||
|
||||
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec<u8> {
|
||||
let open = format!("<{field}>");
|
||||
let close = format!("</{field}>");
|
||||
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
|
||||
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
|
||||
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
|
||||
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_sample() {
|
||||
let s = http::parse_server_info(SERVERINFO.as_bytes()).unwrap();
|
||||
assert_eq!(s.hostname, "LAB-PC");
|
||||
assert_eq!(s.app_version, "7.1.431.-1");
|
||||
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
|
||||
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
|
||||
assert_eq!(s.https_port, 47984);
|
||||
assert_eq!(s.http_port, Some(47989));
|
||||
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
|
||||
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
|
||||
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
|
||||
assert_eq!(s.codec_mode_support, Some(259));
|
||||
assert!(!s.paired);
|
||||
assert_eq!(s.current_game, 0);
|
||||
assert_eq!(s.state, "SUNSHINE_SERVER_FREE");
|
||||
assert!(!s.is_busy().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_optional_fields() {
|
||||
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
|
||||
assert_eq!(s.mac, None, "empty mac is None");
|
||||
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
|
||||
assert_eq!(s.gfe_version, None);
|
||||
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
|
||||
assert_eq!(s.http_port, None);
|
||||
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
|
||||
assert!(s.paired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_busy() {
|
||||
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
|
||||
assert!(s.is_busy().unwrap());
|
||||
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
|
||||
assert_eq!(s.current_game, 881_448_767);
|
||||
assert!(s.is_busy().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_refuses_bad_fields() {
|
||||
for field in ["hostname", "uniqueid", "HttpsPort"] {
|
||||
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
|
||||
}
|
||||
for (field, value) in [
|
||||
("HttpsPort", "70000"),
|
||||
("HttpsPort", "-1"),
|
||||
("HttpsPort", ""),
|
||||
("HttpsPort", "0x1F"),
|
||||
("HttpsPort", " 47984"),
|
||||
("ExternalPort", "65536"),
|
||||
("currentgame", "abc"),
|
||||
("currentgame", "4294967296"),
|
||||
("MaxLumaPixelsHEVC", "1e9"),
|
||||
("ServerCodecModeSupport", "-3"),
|
||||
("mac", "00:11:22:33:44"),
|
||||
("mac", "00:11:22:33:44:55:66"),
|
||||
("mac", "zz:11:22:33:44:55"),
|
||||
] {
|
||||
assert_err!(
|
||||
http::parse_server_info(&serverinfo_with(field, Some(value))),
|
||||
Error::Malformed { .. },
|
||||
"{field}={value:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_field_cap() {
|
||||
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
|
||||
let ok = "h".repeat(MAX);
|
||||
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
|
||||
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
|
||||
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serverinfo_status_and_sizes() {
|
||||
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
|
||||
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
||||
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
|
||||
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
|
||||
let inner = SERVERINFO
|
||||
.trim_start_matches("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">")
|
||||
.trim_end_matches("</root>\n");
|
||||
for len in [MAX - 1, MAX] {
|
||||
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||
assert_eq!(s.hostname, "LAB-PC");
|
||||
}
|
||||
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
||||
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
|
||||
}
|
||||
|
||||
// ================================================================================================ applist
|
||||
|
||||
#[test]
|
||||
fn applist_sample() {
|
||||
let body = xml_root(
|
||||
200,
|
||||
"<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>\
|
||||
<App><AppTitle>Steam & Friends</AppTitle><ID>2</ID><IsHdrSupported>0</IsHdrSupported></App>\
|
||||
<App><AppTitle>No HDR field</AppTitle><ID>3</ID></App>",
|
||||
);
|
||||
let apps = http::parse_app_list(&body).unwrap();
|
||||
assert_eq!(
|
||||
apps,
|
||||
vec![
|
||||
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
|
||||
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
|
||||
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
|
||||
]
|
||||
);
|
||||
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applist_refuses_bad_apps() {
|
||||
for (inner, why) in [
|
||||
("<App><AppTitle>A</AppTitle></App>", "no ID"),
|
||||
("<App><ID>1</ID></App>", "no AppTitle"),
|
||||
("<App><AppTitle>A</AppTitle><ID>-1</ID></App>", "negative ID"),
|
||||
("<App><AppTitle>A</AppTitle><ID>abc</ID></App>", "ID not decimal"),
|
||||
("<App><AppTitle>A</AppTitle><ID>4294967296</ID></App>", "ID over u32"),
|
||||
("<App><AppTitle>A</AppTitle><ID>1</ID></App><App><AppTitle>B</AppTitle><ID>1</ID></App>", "duplicate ID"),
|
||||
] {
|
||||
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applist_caps() {
|
||||
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
|
||||
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_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.
|
||||
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>();
|
||||
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
|
||||
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
|
||||
|
||||
let inner = app(1, "Desktop");
|
||||
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
|
||||
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_too_large!(
|
||||
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
|
||||
|
||||
#[test]
|
||||
fn launch_response_sample() {
|
||||
let r = http::parse_launch_response(&xml_root(
|
||||
200,
|
||||
"<sessionUrl0>rtsp://192.0.2.10:48010</sessionUrl0><gamesession>1</gamesession>",
|
||||
))
|
||||
.unwrap();
|
||||
assert!(r.game_session);
|
||||
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
|
||||
|
||||
let r = http::parse_launch_response(&xml_root(200, "<gamesession>1</gamesession>")).unwrap();
|
||||
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
|
||||
let r = http::parse_launch_response(&xml_root(200, "<gamesession>0</gamesession>")).unwrap();
|
||||
assert!(!r.game_session);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_response_refuses_bad_urls() {
|
||||
for url in [
|
||||
"http://192.0.2.10:48010",
|
||||
"rtsp://192.0.2.10",
|
||||
"rtsp://192.0.2.10:",
|
||||
"rtsp://192.0.2.10:99999",
|
||||
"rtsp://192.0.2.10:-1",
|
||||
"rtsp://:48010",
|
||||
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
|
||||
"rtsp://192.0.2.10:48a",
|
||||
"",
|
||||
] {
|
||||
let body = xml_root(200, &format!("<sessionUrl0>{url}</sessionUrl0><gamesession>1</gamesession>"));
|
||||
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_response_caps() {
|
||||
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
|
||||
let prefix = "rtsp://";
|
||||
let suffix = ":48010";
|
||||
// A host name of DNS labels of 9 letters, so only the length is unusual.
|
||||
let host = |n: usize| {
|
||||
let len = n - prefix.len() - suffix.len();
|
||||
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::<String>()
|
||||
};
|
||||
let ok = format!("{prefix}{}{suffix}", host(URL));
|
||||
let r = http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{ok}</sessionUrl0>"))).unwrap();
|
||||
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
|
||||
let over = format!("{prefix}{}{suffix}", host(URL + 1));
|
||||
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{over}</sessionUrl0>"))), URL);
|
||||
|
||||
let inner = "<gamesession>1</gamesession>";
|
||||
for len in [MAX - 1, MAX] {
|
||||
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
|
||||
}
|
||||
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
||||
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
|
||||
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
||||
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn status_response() {
|
||||
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
|
||||
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
|
||||
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
|
||||
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
|
||||
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
||||
}
|
||||
|
||||
// ================================================================================================ requests
|
||||
|
||||
const UID: &str = "0123456789ABCDEF";
|
||||
|
||||
#[test]
|
||||
fn simple_requests() {
|
||||
let r = http::server_info_request(Scheme::Http, UID).unwrap();
|
||||
assert_eq!(r.scheme, Scheme::Http);
|
||||
let (path, q) = parse_query(&r.path_and_query);
|
||||
assert_eq!(path, "/serverinfo");
|
||||
assert_eq!(param(&q, "uniqueid"), UID);
|
||||
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
|
||||
|
||||
for (r, want) in [
|
||||
(http::app_list_request(UID).unwrap(), "/applist"),
|
||||
(http::cancel_request(UID).unwrap(), "/cancel"),
|
||||
(http::unpair_request(UID).unwrap(), "/unpair"),
|
||||
] {
|
||||
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
|
||||
let (path, q) = parse_query(&r.path_and_query);
|
||||
assert_eq!(path, want);
|
||||
assert_eq!(param(&q, "uniqueid"), UID);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_refuse_bad_unique_ids() {
|
||||
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
|
||||
for bad in [String::new(), "a".repeat(MAX + 1)] {
|
||||
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
|
||||
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
|
||||
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
|
||||
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
|
||||
}
|
||||
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_cannot_be_injected() {
|
||||
// A unique id with query syntax is refused or encoded; it never adds a parameter.
|
||||
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
|
||||
match http::server_info_request(Scheme::Http, evil) {
|
||||
Err(Error::Malformed { .. }) => {}
|
||||
Ok(r) => {
|
||||
let (path, q) = parse_query(&r.path_and_query);
|
||||
assert_eq!(path, "/serverinfo");
|
||||
assert_eq!(param(&q, "uniqueid"), evil);
|
||||
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
|
||||
}
|
||||
other => panic!("{evil:?}: {other:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn launch_params() -> http::LaunchParams {
|
||||
http::LaunchParams {
|
||||
app_id: 881_448_767,
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
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,
|
||||
},
|
||||
hdr: false,
|
||||
audio: http::launch::AudioLayout::Stereo,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_request_parameters() {
|
||||
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
|
||||
assert_eq!(r.scheme, Scheme::Https);
|
||||
let (path, q) = parse_query(&r.path_and_query);
|
||||
assert_eq!(path, "/launch");
|
||||
assert_eq!(param(&q, "uniqueid"), UID);
|
||||
assert_eq!(param(&q, "appid"), "881448767");
|
||||
assert_eq!(param(&q, "mode"), "1920x1080x60");
|
||||
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
||||
assert_eq!(param(&q, "rikeyid"), "1234567");
|
||||
assert_eq!(param(&q, "hdrMode"), "0");
|
||||
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
|
||||
|
||||
let mut p = launch_params();
|
||||
p.hdr = true;
|
||||
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
|
||||
assert_eq!(param(&q, "hdrMode"), "1");
|
||||
|
||||
for broken in [
|
||||
http::LaunchParams { width: 0, ..launch_params() },
|
||||
http::LaunchParams { height: 0, ..launch_params() },
|
||||
http::LaunchParams { fps: 0, ..launch_params() },
|
||||
] {
|
||||
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
|
||||
}
|
||||
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resume_request_parameters() {
|
||||
let keys = launch_params().keys;
|
||||
let r = http::launch::resume_request(&keys, UID).unwrap();
|
||||
assert_eq!(r.scheme, Scheme::Https);
|
||||
let (path, q) = parse_query(&r.path_and_query);
|
||||
assert_eq!(path, "/resume");
|
||||
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
||||
assert_eq!(param(&q, "rikeyid"), "1234567");
|
||||
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn session_keys_are_fresh() {
|
||||
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
||||
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
|
||||
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
||||
assert_eq!(a, a2, "keys come only from the caller's randomness");
|
||||
assert_ne!(a.rikey, b.rikey);
|
||||
assert_ne!(a.rikey, [0; 16]);
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
//! Repository rules that are checked by reading the crate itself: the sans-I/O guard (no sockets, clocks,
|
||||
//! threads, files or OS randomness in `src/`), `forbid(unsafe_code)`, and that `Debug` never prints a secret.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||
|
||||
mod common;
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// Things `src/` must never contain outside comments (CLAUDE.md "Sans-I/O"). The left side is matched with all
|
||||
/// whitespace removed, so `std :: net` and `use std::{fs, net}` are caught too.
|
||||
const FORBIDDEN: &[(&str, &str)] = &[
|
||||
("std::net", "sockets"),
|
||||
("Instant::now", "clock reads"),
|
||||
("SystemTime::now", "clock reads"),
|
||||
("std::time::Instant", "the std clock type (use crate::Instant)"),
|
||||
("std::time::SystemTime", "the std clock type"),
|
||||
("UNIX_EPOCH", "clock reads"),
|
||||
("std::thread", "threads"),
|
||||
("thread::spawn", "threads"),
|
||||
("std::fs", "files"),
|
||||
("File::open", "files"),
|
||||
("File::create", "files"),
|
||||
("std::process", "processes"),
|
||||
("std::env::var", "environment reads"),
|
||||
("OsRng", "OS randomness (randomness comes in through RandomSource)"),
|
||||
("thread_rng", "OS randomness"),
|
||||
("getrandom", "OS randomness"),
|
||||
("rand::random", "OS randomness"),
|
||||
("tokio", "async runtimes"),
|
||||
("mio::", "async runtimes"),
|
||||
];
|
||||
|
||||
/// Grouped imports `use std::{…}` naming a forbidden module.
|
||||
const FORBIDDEN_IN_STD_GROUP: &[&str] = &["net", "fs", "thread", "process"];
|
||||
|
||||
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||
for entry in std::fs::read_dir(dir).expect("read src dir") {
|
||||
let path = entry.expect("dir entry").path();
|
||||
if path.is_dir() {
|
||||
rust_files(&path, out);
|
||||
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The code of a file with `//` comments (line and doc comments) and `/* */` comments removed. String literals are
|
||||
/// kept: a forbidden name inside a string still fails, on purpose.
|
||||
fn strip_comments(src: &str) -> String {
|
||||
let mut out = String::with_capacity(src.len());
|
||||
let mut chars = src.chars().peekable();
|
||||
let mut in_str = false;
|
||||
while let Some(c) = chars.next() {
|
||||
if in_str {
|
||||
out.push(c);
|
||||
if c == '\\' {
|
||||
if let Some(n) = chars.next() {
|
||||
out.push(n);
|
||||
}
|
||||
} else if c == '"' {
|
||||
in_str = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match (c, chars.peek()) {
|
||||
('"', _) => {
|
||||
in_str = true;
|
||||
out.push(c);
|
||||
}
|
||||
('/', Some('/')) => {
|
||||
for n in chars.by_ref() {
|
||||
if n == '\n' {
|
||||
out.push('\n');
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
('/', Some('*')) => {
|
||||
chars.next();
|
||||
let mut prev = ' ';
|
||||
for n in chars.by_ref() {
|
||||
if prev == '*' && n == '/' {
|
||||
break;
|
||||
}
|
||||
prev = n;
|
||||
}
|
||||
}
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn violations_in(code: &str) -> Vec<String> {
|
||||
let squashed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
|
||||
let mut found = Vec::new();
|
||||
for (needle, why) in FORBIDDEN {
|
||||
if squashed.contains(needle) {
|
||||
found.push(format!("`{needle}` ({why})"));
|
||||
}
|
||||
}
|
||||
let mut rest = squashed.as_str();
|
||||
while let Some(i) = rest.find("std::{") {
|
||||
let group = &rest[i + 6..];
|
||||
let end = group.find('}').unwrap_or(group.len());
|
||||
for item in group[..end].split(',') {
|
||||
let head = item.split("::").next().unwrap_or("");
|
||||
if FORBIDDEN_IN_STD_GROUP.contains(&head) {
|
||||
found.push(format!("`std::{{{head}}}` (grouped import)"));
|
||||
}
|
||||
}
|
||||
rest = &group[end.min(group.len())..];
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn src_is_sans_io() {
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut files = Vec::new();
|
||||
rust_files(&src, &mut files);
|
||||
assert!(files.len() >= 20, "expected the whole crate under {}", src.display());
|
||||
let mut report = Vec::new();
|
||||
for file in &files {
|
||||
let code = strip_comments(&std::fs::read_to_string(file).expect("read source"));
|
||||
for v in violations_in(&code) {
|
||||
report.push(format!("{}: {v}", file.strip_prefix(&src).unwrap_or(file).display()));
|
||||
}
|
||||
}
|
||||
assert!(report.is_empty(), "sans-I/O rule broken:\n{}", report.join("\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guard_catches_what_it_should() {
|
||||
// The guard itself must work, or `src_is_sans_io` proves nothing.
|
||||
for bad in [
|
||||
"use std::net::UdpSocket;",
|
||||
"let t = std::time::Instant::now();",
|
||||
"let t = Instant :: now();",
|
||||
"let t = SystemTime::now();",
|
||||
"std::thread::spawn(|| {});",
|
||||
"let f = std::fs::read(\"x\");",
|
||||
"use std::{fs, io};",
|
||||
"use std::{io, net::TcpStream};",
|
||||
"let mut r = rand::rngs::OsRng;",
|
||||
"getrandom::fill(&mut b);",
|
||||
] {
|
||||
assert!(!violations_in(&strip_comments(bad)).is_empty(), "guard missed: {bad}");
|
||||
}
|
||||
for fine in [
|
||||
"// no std::net here, only a comment",
|
||||
"/// Docs may say Instant::now is forbidden.",
|
||||
"/* std::fs in a block comment */ let x = 1;",
|
||||
"use crate::Instant; let t = Instant::from_micros(5);",
|
||||
"use std::{fmt, error};",
|
||||
"use core::time::Duration;",
|
||||
] {
|
||||
assert!(violations_in(&strip_comments(fine)).is_empty(), "guard flagged: {fine}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_module_forbids_unsafe() {
|
||||
let lib = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).expect("lib.rs");
|
||||
assert!(lib.contains("#![forbid(unsafe_code)]"), "lib.rs must carry #![forbid(unsafe_code)]");
|
||||
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||
let mut files = Vec::new();
|
||||
rust_files(&src, &mut files);
|
||||
for file in files {
|
||||
let code = strip_comments(&std::fs::read_to_string(&file).expect("read"));
|
||||
assert_eq!(
|
||||
code.matches("unsafe").count(),
|
||||
code.matches("unsafe_code").count(),
|
||||
"{}: `unsafe` in src",
|
||||
file.display()
|
||||
);
|
||||
assert!(!code.contains("allow(unsafe_code)"), "{}: unsafe allowed", file.display());
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ secrets
|
||||
|
||||
const KEY: [u8; 16] = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x10];
|
||||
|
||||
/// Every way the key could show up in a `Debug` string.
|
||||
fn leaks_key(s: &str) -> bool {
|
||||
let lower = s.to_lowercase();
|
||||
lower.contains(&common::to_hex(&KEY))
|
||||
|| lower.contains("161, 178")
|
||||
|| lower.contains("0xa1, 0xb2")
|
||||
|| lower.contains("a1b2c3")
|
||||
|| s.contains("[161")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_keys() {
|
||||
let keys = domistream::SessionKeys { rikey: KEY, rikeyid: 7 };
|
||||
let control = domistream::control::ControlCipher::new(KEY);
|
||||
let video = domistream::video::VideoCipher::new(KEY);
|
||||
let audio = domistream::audio::AudioCipher::new(&keys);
|
||||
let config = domistream::control::ControlConfig {
|
||||
enet: domistream::enet::EnetConfig {
|
||||
channel_count: 1,
|
||||
mtu: 1400,
|
||||
connect_data: 0,
|
||||
ping_interval: core::time::Duration::from_millis(500),
|
||||
timeout: core::time::Duration::from_secs(10),
|
||||
},
|
||||
rikey: KEY,
|
||||
ping_interval: core::time::Duration::from_millis(100),
|
||||
};
|
||||
for (what, s) in [
|
||||
("SessionKeys", format!("{keys:?}")),
|
||||
("ControlCipher", format!("{control:?}")),
|
||||
("VideoCipher", format!("{video:?}")),
|
||||
("AudioCipher", format!("{audio:?}")),
|
||||
("ControlConfig", format!("{config:?}")),
|
||||
(
|
||||
"VideoConfig",
|
||||
format!(
|
||||
"{:?}",
|
||||
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!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
|
||||
}
|
||||
// rikeyid is not secret: it may show.
|
||||
assert!(format!("{keys:?}").contains('7'));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_never_prints_the_pin_or_the_private_key() {
|
||||
// Pin and ClientIdentity can only be made through the API (Phase A: Unimplemented, so these fail now).
|
||||
let pin = domistream::pairing::Pin::from_digits("4071").expect("Pin::from_digits");
|
||||
let s = format!("{pin:?}");
|
||||
assert!(!s.contains("4071") && !s.contains("52, 48, 55, 49"), "Pin Debug leaks the PIN: {s}");
|
||||
|
||||
let v = common::pairing_vectors();
|
||||
let key = v.bytes("client_key_pkcs8_der");
|
||||
let identity = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &key)
|
||||
.expect("ClientIdentity::from_der");
|
||||
let s = format!("{identity:?}");
|
||||
assert!(s.contains("redacted"), "{s}");
|
||||
let key_hex = common::to_hex(&key[key.len() - 32..]);
|
||||
assert!(!s.to_lowercase().contains(&key_hex), "ClientIdentity Debug leaks key bytes");
|
||||
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])), "ClientIdentity Debug leaks key bytes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_display_has_no_secret_material() {
|
||||
// Errors are fixed strings and numbers; make sure the variants that come out of crypto paths say nothing.
|
||||
for e in [domistream::Error::Crypto, domistream::Error::PairingRefused] {
|
||||
let s = format!("{e} {e:?}");
|
||||
assert!(!leaks_key(&s), "{s}");
|
||||
assert!(s.len() < 80, "crypto errors are deliberately short: {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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,865 @@
|
||||
//! Pairing (`docs/PROTOCOL.md` 1.5) against recorded vectors made by independent tools
|
||||
//! (`tools/vectors/gen_vectors.py`: Python hashlib, the OpenSSL CLI). The keys are test-only.
|
||||
//!
|
||||
//! Recorded transcript assumption: the state machine draws its randomness as salt (step 1), then C (step 2), then
|
||||
//! secret_c (step 3), 16 bytes each, and nothing else. [`common::ScriptedRng`] fails loudly if that changes.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||
|
||||
mod common;
|
||||
|
||||
use common::{
|
||||
CLIENT_CERT_PEM, CLIENT_KEY_PEM, EC_CERT_PEM, HOST_CERT_PEM, ROGUE_CERT_PEM, ScriptedRng, SeqRng, Vectors, hex,
|
||||
param, parse_query, pem_blocks, to_hex, to_hex_upper, xml_padded_to, xml_root,
|
||||
};
|
||||
use domistream::Error;
|
||||
use domistream::http::{HttpRequest, Scheme};
|
||||
use domistream::pairing::crypto;
|
||||
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
|
||||
use domistream::pairing::{
|
||||
ClientIdentity, MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, PairingFailure, PairingSession, PairingState,
|
||||
PairingStep, Pin, ServerCert, parse_pair_response,
|
||||
};
|
||||
|
||||
const UID: &str = "0123456789ABCDEF";
|
||||
const DEVICE: &str = "DomiStreamTestTV";
|
||||
|
||||
fn v() -> Vectors {
|
||||
common::pairing_vectors()
|
||||
}
|
||||
|
||||
fn client() -> ClientIdentity {
|
||||
let v = v();
|
||||
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
|
||||
.expect("ClientIdentity::from_der(test-only client)")
|
||||
}
|
||||
|
||||
fn rogue() -> ClientIdentity {
|
||||
let v = v();
|
||||
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
|
||||
}
|
||||
|
||||
fn pin() -> Pin {
|
||||
Pin::from_digits(v().str("pin")).expect("Pin::from_digits")
|
||||
}
|
||||
|
||||
fn rng_a() -> ScriptedRng {
|
||||
let v = v();
|
||||
ScriptedRng::new([v.bytes("salt"), v.bytes("client_challenge"), v.bytes("client_secret")].concat())
|
||||
}
|
||||
|
||||
fn rng_b() -> ScriptedRng {
|
||||
let v = v();
|
||||
ScriptedRng::new([v.bytes("salt_b"), v.bytes("client_challenge_b"), v.bytes("client_secret_b")].concat())
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------------------------------ host answers
|
||||
|
||||
fn answer(paired: bool, element: Option<(&str, &[u8])>) -> Vec<u8> {
|
||||
let mut inner = format!("<paired>{}</paired>", u8::from(paired));
|
||||
if let Some((name, value)) = element {
|
||||
// Upper-case hex: the parser must accept both cases (PROTOCOL.md 1.1).
|
||||
inner.push_str(&format!("<{name}>{}</{name}>", to_hex_upper(value)));
|
||||
}
|
||||
xml_root(200, &inner)
|
||||
}
|
||||
|
||||
fn resp1() -> Vec<u8> {
|
||||
answer(true, Some(("plaincert", HOST_CERT_PEM.as_bytes())))
|
||||
}
|
||||
fn resp2() -> Vec<u8> {
|
||||
answer(true, Some(("challengeresponse", &v().bytes("step2_challengeresponse"))))
|
||||
}
|
||||
fn resp3() -> Vec<u8> {
|
||||
answer(true, Some(("pairingsecret", &v().bytes("step3_pairingsecret"))))
|
||||
}
|
||||
fn resp_ok() -> Vec<u8> {
|
||||
answer(true, None)
|
||||
}
|
||||
|
||||
/// The recorded host answers, in order.
|
||||
fn transcript() -> Vec<Vec<u8>> {
|
||||
vec![resp1(), resp2(), resp3(), resp_ok(), resp_ok()]
|
||||
}
|
||||
|
||||
/// A session that has been fed the first `steps` recorded answers.
|
||||
fn session_after(steps: usize) -> (PairingSession, ScriptedRng, ClientIdentity) {
|
||||
let id = client();
|
||||
let mut rng = rng_a();
|
||||
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).expect("PairingSession::start");
|
||||
for body in transcript().into_iter().take(steps) {
|
||||
s.handle_response(&id, 200, &body, &mut rng).expect("recorded answer");
|
||||
}
|
||||
(s, rng, id)
|
||||
}
|
||||
|
||||
const STATES: [PairingState; 5] = [
|
||||
PairingState::AwaitServerCert,
|
||||
PairingState::AwaitChallengeResponse,
|
||||
PairingState::AwaitPairingSecret,
|
||||
PairingState::AwaitClientSecretAck,
|
||||
PairingState::AwaitPairChallenge,
|
||||
];
|
||||
|
||||
fn sent(step: PairingStep) -> HttpRequest {
|
||||
match step {
|
||||
PairingStep::Send(r) => r,
|
||||
PairingStep::Paired(p) => panic!("expected a request, pairing already finished: {p:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn hex_param(req: &HttpRequest, name: &str) -> Vec<u8> {
|
||||
let (path, q) = parse_query(&req.path_and_query);
|
||||
assert_eq!(path, "/pair");
|
||||
hex(param(&q, name))
|
||||
}
|
||||
|
||||
/// 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,
|
||||
) {
|
||||
let r = s.handle_response(id, status, body, rng);
|
||||
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
|
||||
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
|
||||
// Failed is terminal.
|
||||
assert_err!(s.handle_response(id, 200, &resp_ok(), rng), Error::State { .. });
|
||||
assert_eq!(s.state(), PairingState::Failed(reason));
|
||||
}
|
||||
|
||||
// ================================================================================================ happy path
|
||||
|
||||
#[test]
|
||||
fn recorded_transcript_walks_every_state() {
|
||||
let v = v();
|
||||
let id = client();
|
||||
let mut rng = rng_a();
|
||||
let (mut s, req1) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||
assert_eq!(s.state(), PairingState::AwaitServerCert);
|
||||
|
||||
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
|
||||
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
|
||||
);
|
||||
let (path, q) = parse_query(&req1.path_and_query);
|
||||
assert_eq!(path, "/pair");
|
||||
assert_eq!(param(&q, "uniqueid"), UID);
|
||||
assert_eq!(param(&q, "phrase"), "getservercert");
|
||||
assert_eq!(hex(param(&q, "salt")), v.bytes("salt"));
|
||||
let pem = String::from_utf8(hex(param(&q, "clientcert"))).expect("clientcert is PEM text");
|
||||
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "clientcert is the identity's cert");
|
||||
|
||||
// Step 2: clientchallenge = E_K(C).
|
||||
let req2 = sent(s.handle_response(&id, 200, &resp1(), &mut rng).unwrap());
|
||||
assert_eq!(s.state(), PairingState::AwaitChallengeResponse);
|
||||
assert_eq!(req2.scheme, Scheme::Http);
|
||||
assert_eq!(hex_param(&req2, "clientchallenge"), v.bytes("step2_clientchallenge"));
|
||||
assert_eq!(param(&parse_query(&req2.path_and_query).1, "uniqueid"), UID);
|
||||
|
||||
// Step 3: serverchallengeresp = E_K(H_c).
|
||||
let req3 = sent(s.handle_response(&id, 200, &resp2(), &mut rng).unwrap());
|
||||
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
|
||||
assert_eq!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
|
||||
|
||||
// Step 4: clientpairingsecret = secret_c || Sign_client(secret_c), after checking the host's proof.
|
||||
let req4 = sent(s.handle_response(&id, 200, &resp3(), &mut rng).unwrap());
|
||||
assert_eq!(s.state(), PairingState::AwaitClientSecretAck);
|
||||
assert_eq!(hex_param(&req4, "clientpairingsecret"), v.bytes("step4_clientpairingsecret"));
|
||||
|
||||
// Step 5 (HTTPS): pairchallenge.
|
||||
let req5 = sent(s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap());
|
||||
assert_eq!(s.state(), PairingState::AwaitPairChallenge);
|
||||
assert_eq!(req5.scheme, Scheme::Https, "step 5 runs over HTTPS with the client certificate");
|
||||
assert_eq!(param(&parse_query(&req5.path_and_query).1, "phrase"), "pairchallenge");
|
||||
|
||||
match s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap() {
|
||||
PairingStep::Paired(host) => assert_eq!(host.server_cert.der(), v.bytes("host_cert_der").as_slice()),
|
||||
PairingStep::Send(r) => panic!("expected Paired, got another request {r:?}"),
|
||||
}
|
||||
assert_eq!(s.state(), PairingState::Paired);
|
||||
assert_eq!(rng.drawn(), 48, "salt + C + secret_c");
|
||||
assert_err!(s.handle_response(&id, 200, &resp_ok(), &mut rng), Error::State { .. });
|
||||
assert_eq!(s.state(), PairingState::Paired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lower_case_hex_answers_work_too() {
|
||||
let id = client();
|
||||
let mut rng = rng_a();
|
||||
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||
for body in transcript() {
|
||||
let lower = String::from_utf8(body).unwrap();
|
||||
// Lower-case only the hex payloads (element names keep their case).
|
||||
let mut out = String::new();
|
||||
let mut in_text = false;
|
||||
for c in lower.chars() {
|
||||
match c {
|
||||
'>' => {
|
||||
in_text = true;
|
||||
out.push(c);
|
||||
}
|
||||
'<' => {
|
||||
in_text = false;
|
||||
out.push(c);
|
||||
}
|
||||
_ if in_text => out.push(c.to_ascii_lowercase()),
|
||||
_ => out.push(c),
|
||||
}
|
||||
}
|
||||
s.handle_response(&id, 200, out.as_bytes(), &mut rng).unwrap();
|
||||
}
|
||||
assert_eq!(s.state(), PairingState::Paired);
|
||||
}
|
||||
|
||||
// ================================================================================================ no shortcuts
|
||||
|
||||
#[test]
|
||||
fn paired_needs_exactly_five_answers() {
|
||||
// An answer carrying every element at once still moves one step at a time.
|
||||
let v = v();
|
||||
let all = xml_root(
|
||||
200,
|
||||
&format!(
|
||||
"<paired>1</paired><plaincert>{}</plaincert><challengeresponse>{}</challengeresponse><pairingsecret>{}</pairingsecret>",
|
||||
to_hex(HOST_CERT_PEM.as_bytes()),
|
||||
to_hex(&v.bytes("step2_challengeresponse")),
|
||||
to_hex(&v.bytes("step3_pairingsecret")),
|
||||
),
|
||||
);
|
||||
let id = client();
|
||||
let mut rng = rng_a();
|
||||
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||
for (i, want) in STATES.iter().enumerate().skip(1) {
|
||||
let step = s.handle_response(&id, 200, &all, &mut rng).unwrap();
|
||||
assert!(matches!(step, PairingStep::Send(_)), "answer {} must not finish pairing", i);
|
||||
assert_eq!(s.state(), *want, "after {i} answers");
|
||||
}
|
||||
assert!(matches!(s.handle_response(&id, 200, &all, &mut rng).unwrap(), PairingStep::Paired(_)));
|
||||
assert_eq!(s.state(), PairingState::Paired);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bare_paired_answer_cannot_skip_any_step() {
|
||||
// `<paired>1</paired>` is all steps 4 and 5 need. Fed early, it must fail, never jump ahead.
|
||||
for steps in 0..3 {
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
assert_eq!(s.state(), STATES[steps]);
|
||||
expect_failure(&mut s, &id, &mut rng, 200, &resp_ok(), PairingFailure::MalformedAnswer);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_order_answers_fail() {
|
||||
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
|
||||
let cases: Vec<(usize, Vec<u8>)> =
|
||||
vec![(0, resp2()), (0, resp3()), (1, resp1()), (1, resp3()), (2, resp1()), (2, resp2())];
|
||||
for (steps, body) in cases {
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replayed_answers_from_another_session_fail() {
|
||||
// Session B (fresh randomness) fed session A's recorded answers: the host proof cannot match.
|
||||
let id = client();
|
||||
let mut rng = rng_b();
|
||||
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||
s.handle_response(&id, 200, &resp1(), &mut rng).unwrap();
|
||||
s.handle_response(&id, 200, &resp2(), &mut rng).unwrap();
|
||||
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
|
||||
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||
assert_err!(r, Error::PairingRefused);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaying_the_same_answer_twice_fails() {
|
||||
// Step 2's answer accepted, then replayed in place of step 3's.
|
||||
let (mut s, mut rng, id) = session_after(2);
|
||||
expect_failure(&mut s, &id, &mut rng, 200, &resp2(), PairingFailure::MalformedAnswer);
|
||||
}
|
||||
|
||||
// ================================================================================================ hostile host
|
||||
|
||||
#[test]
|
||||
fn host_refusal_at_every_step() {
|
||||
for steps in 0..5 {
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
let body = answer(false, None);
|
||||
let r = s.handle_response(&id, 200, &body, &mut rng);
|
||||
assert_err!(r, Error::PairingRefused, "step {}", steps + 1);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostRefused), "step {}", steps + 1);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_status_errors_at_every_step() {
|
||||
for steps in 0..5 {
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
let r = s.handle_response(&id, 200, &xml_root(500, "<paired>1</paired>"), &mut rng);
|
||||
assert_err!(r, Error::HostStatus { code: 500 }, "step {}", steps + 1);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
|
||||
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
let good = transcript().swap_remove(steps);
|
||||
let r = s.handle_response(&id, 404, &good, &mut rng);
|
||||
assert_err!(r, Error::HostStatus { code: 404 }, "HTTP 404 at step {}", steps + 1);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_answers_at_every_step() {
|
||||
let bodies: Vec<Vec<u8>> = vec![
|
||||
b"".to_vec(),
|
||||
b"garbage".to_vec(),
|
||||
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
|
||||
xml_root(200, ""),
|
||||
xml_root(200, "<paired>yes</paired>"),
|
||||
xml_root(
|
||||
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 body in &bodies {
|
||||
let (mut s, mut rng, id) = session_after(steps);
|
||||
expect_failure(&mut s, &id, &mut rng, 200, body, PairingFailure::MalformedAnswer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_pin_is_a_proof_mismatch() {
|
||||
let v = v();
|
||||
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,
|
||||
)
|
||||
.unwrap();
|
||||
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||
assert_err!(r, Error::PairingRefused);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_host_hash_is_a_proof_mismatch() {
|
||||
let v = v();
|
||||
for name in ["step2_challengeresponse_wrong_hash", "step2_challengeresponse_wrong_cert"] {
|
||||
let (mut s, mut rng, id) = session_after(1);
|
||||
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes(name)))), &mut rng).unwrap();
|
||||
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||
assert_err!(r, Error::PairingRefused, "{name}");
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tampered_challenge_response() {
|
||||
let v = v();
|
||||
// Block 0 or 1 holds H_s: flipping it must end in ProofMismatch once the secret arrives.
|
||||
for byte in [0usize, 17, 31] {
|
||||
let mut cr = v.bytes("step2_challengeresponse");
|
||||
cr[byte] ^= 0x01;
|
||||
let (mut s, mut rng, id) = session_after(1);
|
||||
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap();
|
||||
assert_err!(s.handle_response(&id, 200, &resp3(), &mut rng), Error::PairingRefused);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "byte {byte}");
|
||||
}
|
||||
// Block 2 holds S_c: the client cannot see it, but it must feed S_c into H_c (so step 3 changes).
|
||||
let mut cr = v.bytes("step2_challengeresponse");
|
||||
cr[40] ^= 0x01;
|
||||
let (mut s, mut rng, id) = session_after(1);
|
||||
let req3 = sent(s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap());
|
||||
assert_ne!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_challenge_response_sizes() {
|
||||
let v = v();
|
||||
let good = v.bytes("step2_challengeresponse");
|
||||
let cases: Vec<Vec<u8>> = vec![
|
||||
good[..32].to_vec(),
|
||||
good[..47].to_vec(),
|
||||
[good.clone(), vec![0; 1]].concat(),
|
||||
[good.clone(), vec![0; 16]].concat(),
|
||||
vec![],
|
||||
];
|
||||
for cr in cases {
|
||||
let (mut s, mut rng, id) = session_after(1);
|
||||
expect_failure(
|
||||
&mut s,
|
||||
&id,
|
||||
&mut rng,
|
||||
200,
|
||||
&answer(true, Some(("challengeresponse", &cr))),
|
||||
PairingFailure::MalformedAnswer,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_host_signatures() {
|
||||
let v = v();
|
||||
// Signed by another key.
|
||||
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,
|
||||
);
|
||||
assert_err!(r, Error::PairingRefused);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
||||
|
||||
// One bit of the signature flipped, the signature cut short, or zeroed.
|
||||
let good = v.bytes("step3_pairingsecret");
|
||||
let mut flipped = good.clone();
|
||||
*flipped.last_mut().unwrap() ^= 0x80;
|
||||
let mut zeroed = good.clone();
|
||||
zeroed[16..].fill(0);
|
||||
for ps in [flipped, good[..good.len() - 1].to_vec(), zeroed, [good[..16].to_vec(), vec![0x01]].concat()] {
|
||||
let (mut s, mut rng, id) = session_after(2);
|
||||
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &ps))), &mut rng);
|
||||
assert_err!(r, Error::PairingRefused);
|
||||
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
||||
}
|
||||
|
||||
// The secret itself changed: both checks fail; either reason is a refusal.
|
||||
let mut secret = good.clone();
|
||||
secret[0] ^= 1;
|
||||
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!(matches!(
|
||||
s.state(),
|
||||
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_pairing_secret_sizes() {
|
||||
let v = v();
|
||||
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![]]
|
||||
{
|
||||
let (mut s, mut rng, id) = session_after(2);
|
||||
expect_failure(
|
||||
&mut s,
|
||||
&id,
|
||||
&mut rng,
|
||||
200,
|
||||
&answer(true, Some(("pairingsecret", &ps))),
|
||||
PairingFailure::MalformedAnswer,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_host_certificates() {
|
||||
let two = format!("{HOST_CERT_PEM}{ROGUE_CERT_PEM}");
|
||||
let mut long = HOST_CERT_PEM.to_string();
|
||||
long.push_str(&"\n".repeat(MAX_CERT_PEM_BYTES));
|
||||
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() / 2];
|
||||
for pem in [
|
||||
"".to_string(),
|
||||
"hello".to_string(),
|
||||
EC_CERT_PEM.to_string(),
|
||||
two,
|
||||
CLIENT_KEY_PEM.to_string(),
|
||||
cut.to_string(),
|
||||
long,
|
||||
] {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identity_must_stay_the_same() {
|
||||
let (mut s, mut rng, _) = session_after(1);
|
||||
assert_err!(s.handle_response(&rogue(), 200, &resp2(), &mut rng), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_refuses_bad_names_and_injection() {
|
||||
use domistream::http::{MAX_DEVICE_NAME_BYTES, MAX_UNIQUE_ID_BYTES};
|
||||
let id = client();
|
||||
for (uid, dev) in [
|
||||
("", DEVICE),
|
||||
(&*"a".repeat(MAX_UNIQUE_ID_BYTES + 1), DEVICE),
|
||||
(UID, ""),
|
||||
(UID, &*"d".repeat(MAX_DEVICE_NAME_BYTES + 1)),
|
||||
] {
|
||||
assert_err!(PairingSession::start(&id, uid, dev, pin(), &mut rng_a()), Error::Malformed { .. });
|
||||
}
|
||||
// A device name with query syntax is refused or encoded: never a second `phrase`.
|
||||
for evil in ["tv&phrase=pairchallenge", "tv\r\nHost: x", "tv#x", "tv salt=00"] {
|
||||
match PairingSession::start(&id, UID, evil, pin(), &mut rng_a()) {
|
||||
Err(Error::Malformed { .. }) => {}
|
||||
Ok((_, req)) => {
|
||||
let (_, q) = parse_query(&req.path_and_query);
|
||||
assert_eq!(param(&q, "phrase"), "getservercert");
|
||||
assert_eq!(param(&q, "devicename"), evil);
|
||||
assert!(!req.path_and_query.contains(['\r', '\n', ' ', '#']));
|
||||
}
|
||||
Err(e) => panic!("{evil:?}: {e:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================ crypto vectors
|
||||
|
||||
#[test]
|
||||
fn derive_key_vectors() {
|
||||
let v = v();
|
||||
for i in 0..4 {
|
||||
let salt: [u8; 16] = v.arr16(&format!("derive_{i}_salt"));
|
||||
let p = Pin::from_digits(v.str(&format!("derive_{i}_pin"))).unwrap();
|
||||
assert_eq!(crypto::derive_key(&salt, &p).unwrap().to_vec(), v.bytes(&format!("derive_{i}_key")), "vector {i}");
|
||||
}
|
||||
assert_eq!(crypto::derive_key(&v.arr16("salt"), &pin()).unwrap().to_vec(), v.bytes("key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ecb_vectors() {
|
||||
let v = v();
|
||||
for blocks in 1..=4 {
|
||||
let key = v.arr16(&format!("ecb_{blocks}_key"));
|
||||
let plain = v.bytes(&format!("ecb_{blocks}_plain"));
|
||||
let cipher = v.bytes(&format!("ecb_{blocks}_cipher"));
|
||||
assert_eq!(crypto::ecb_encrypt(&key, &plain).unwrap(), cipher, "{blocks} blocks");
|
||||
assert_eq!(crypto::ecb_decrypt(&key, &cipher).unwrap(), plain, "{blocks} blocks");
|
||||
}
|
||||
let key = v.arr16("key");
|
||||
assert_eq!(crypto::ecb_encrypt(&key, &v.bytes("client_challenge")).unwrap(), v.bytes("step2_clientchallenge"));
|
||||
for len in [1usize, 15, 17, 47] {
|
||||
assert_err!(crypto::ecb_encrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||
assert_err!(crypto::ecb_decrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proof_hash_vectors() {
|
||||
let v = v();
|
||||
for i in 0..6 {
|
||||
let h = crypto::proof_hash(
|
||||
&v.arr16(&format!("proof_{i}_challenge")),
|
||||
&v.bytes(&format!("proof_{i}_signature")),
|
||||
&v.arr16(&format!("proof_{i}_secret")),
|
||||
)
|
||||
.unwrap();
|
||||
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"));
|
||||
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"));
|
||||
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
|
||||
assert_too_large!(
|
||||
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
|
||||
MAX_SIGNATURE_BYTES,
|
||||
MAX_SIGNATURE_BYTES + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_helpers() {
|
||||
let v = v();
|
||||
let key = v.arr16("key");
|
||||
let decrypted = crypto::ecb_decrypt(&key, &v.bytes("step2_challengeresponse")).unwrap();
|
||||
let (h, sc) = crypto::split_challenge_response(&decrypted).unwrap();
|
||||
assert_eq!(h.to_vec(), v.bytes("host_proof"));
|
||||
assert_eq!(sc.to_vec(), v.bytes("server_challenge"));
|
||||
for len in [0usize, 1, 32, 47, 49, 64] {
|
||||
assert_err!(crypto::split_challenge_response(&vec![0; len]), Error::Malformed { .. }, "{len}");
|
||||
}
|
||||
|
||||
let ps = v.bytes("step3_pairingsecret");
|
||||
let (secret, sig) = crypto::split_pairing_secret(&ps).unwrap();
|
||||
assert_eq!(secret.to_vec(), v.bytes("server_secret"));
|
||||
assert_eq!(sig, v.bytes("server_secret_signature").as_slice());
|
||||
assert_eq!(crypto::split_pairing_secret(&[7; 17]).unwrap().1, &[7]);
|
||||
assert_eq!(crypto::split_pairing_secret(&vec![7; 16 + MAX_SIGNATURE_BYTES]).unwrap().1.len(), MAX_SIGNATURE_BYTES);
|
||||
for len in [0usize, 1, 15, 16] {
|
||||
assert_err!(crypto::split_pairing_secret(&vec![0; len]), Error::Malformed { .. }, "{len}");
|
||||
}
|
||||
assert_too_large!(
|
||||
crypto::split_pairing_secret(&vec![0; 16 + MAX_SIGNATURE_BYTES + 1]),
|
||||
MAX_SIGNATURE_BYTES,
|
||||
MAX_SIGNATURE_BYTES + 1
|
||||
);
|
||||
}
|
||||
|
||||
// ================================================================================================ certificates
|
||||
|
||||
#[test]
|
||||
fn server_cert_from_recorded_pem() {
|
||||
let v = v();
|
||||
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
|
||||
assert_eq!(c.der(), v.bytes("host_cert_der").as_slice());
|
||||
assert_eq!(c.signature().unwrap(), v.bytes("host_cert_signature"));
|
||||
assert_eq!(ServerCert::from_der(&v.bytes("host_cert_der")).unwrap(), c);
|
||||
c.verify(&v.bytes("server_secret"), &v.bytes("server_secret_signature")).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_cert_verify_refuses() {
|
||||
let v = v();
|
||||
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
|
||||
let secret = v.bytes("server_secret");
|
||||
let sig = v.bytes("server_secret_signature");
|
||||
let mut flipped = sig.clone();
|
||||
flipped[100] ^= 0x04;
|
||||
let rogue_sig = &v.bytes("step3_pairingsecret_rogue_signature")[16..];
|
||||
let mut other = secret.clone();
|
||||
other[15] ^= 1;
|
||||
assert_err!(c.verify(&secret, &flipped), Error::Crypto);
|
||||
assert_err!(c.verify(&secret, rogue_sig), Error::Crypto);
|
||||
assert_err!(c.verify(&other, &sig), Error::Crypto);
|
||||
assert_err!(c.verify(&secret, &sig[..255]), Error::Crypto);
|
||||
assert_err!(c.verify(&secret, &[]), Error::Crypto);
|
||||
assert_err!(c.verify(&secret, &[sig.clone(), vec![0]].concat()), Error::Crypto);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_cert_pinning() {
|
||||
let v = v();
|
||||
let der = v.bytes("host_cert_der");
|
||||
let c = ServerCert::from_der(&der).unwrap();
|
||||
assert_eq!(c.matches(&der), Ok(true));
|
||||
let mut flipped = der.clone();
|
||||
flipped[der.len() / 2] ^= 1;
|
||||
assert_eq!(c.matches(&flipped), Ok(false));
|
||||
assert_eq!(c.matches(&der[..der.len() - 1]), Ok(false));
|
||||
assert_eq!(c.matches(&[der.clone(), vec![0]].concat()), Ok(false));
|
||||
assert_eq!(c.matches(&v.bytes("rogue_cert_der")), Ok(false));
|
||||
assert_eq!(c.matches(&[]), Ok(false));
|
||||
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_cert_hostile_pem() {
|
||||
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() - 40];
|
||||
let bad_b64 = HOST_CERT_PEM.replacen('M', "!", 3);
|
||||
let two = format!("{HOST_CERT_PEM}{CLIENT_CERT_PEM}");
|
||||
for (pem, why) in [
|
||||
("", "empty"),
|
||||
("x", "one byte"),
|
||||
("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", "empty block"),
|
||||
(cut, "cut"),
|
||||
(&*bad_b64, "bad base64"),
|
||||
(&*two, "two certificates"),
|
||||
(CLIENT_KEY_PEM, "a private key"),
|
||||
(EC_CERT_PEM, "not an RSA key"),
|
||||
] {
|
||||
assert_err!(ServerCert::from_pem(pem.as_bytes()), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
let mut big = HOST_CERT_PEM.as_bytes().to_vec();
|
||||
big.resize(MAX_CERT_PEM_BYTES + 1, b'\n');
|
||||
assert_too_large!(ServerCert::from_pem(&big), MAX_CERT_PEM_BYTES, MAX_CERT_PEM_BYTES + 1);
|
||||
assert_too_large!(ServerCert::from_pem(&vec![b'A'; 1 << 24]), MAX_CERT_PEM_BYTES, 1 << 24);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_cert_hostile_der() {
|
||||
let der = v().bytes("host_cert_der");
|
||||
for (bad, why) in [
|
||||
(vec![], "empty"),
|
||||
(vec![0x30], "one byte"),
|
||||
(der[..der.len() - 1].to_vec(), "cut"),
|
||||
([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
|
||||
d
|
||||
},
|
||||
"lying length",
|
||||
),
|
||||
] {
|
||||
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
let mut big = der.clone();
|
||||
big.resize(MAX_CERT_DER_BYTES + 1, 0);
|
||||
assert_too_large!(ServerCert::from_der(&big), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_from_recorded_keys() {
|
||||
let v = v();
|
||||
let id = client();
|
||||
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.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("client_secret")).unwrap(), v.bytes("client_secret_signature"));
|
||||
let pem = id.cert_pem().unwrap();
|
||||
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
|
||||
assert_eq!(pem_blocks(CLIENT_CERT_PEM, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "fixture sanity");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_refuses() {
|
||||
use domistream::pairing::identity::MAX_KEY_DER_BYTES;
|
||||
let v = v();
|
||||
let cert = v.bytes("client_cert_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(&v.bytes("rogue_cert_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, &key[..key.len() - 1]), Error::Malformed { .. });
|
||||
assert_err!(ClientIdentity::from_der(&cert, &cert), Error::Malformed { .. });
|
||||
let mut big_cert = cert.clone();
|
||||
big_cert.resize(MAX_CERT_DER_BYTES + 1, 0);
|
||||
assert_too_large!(ClientIdentity::from_der(&big_cert, &key), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||
let mut big_key = key.clone();
|
||||
big_key.resize(MAX_KEY_DER_BYTES + 1, 0);
|
||||
assert_too_large!(ClientIdentity::from_der(&cert, &big_key), MAX_KEY_DER_BYTES, MAX_KEY_DER_BYTES + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_identity_generate() {
|
||||
let id = ClientIdentity::generate(&mut SeqRng::new(0xD0D0), "Living Room TV", 1_764_000_000).unwrap();
|
||||
let cert = ServerCert::from_der(id.cert_der()).expect("a generated cert is a valid RSA X.509 certificate");
|
||||
let sig = id.sign(b"hello").unwrap();
|
||||
assert_eq!(sig.len(), domistream::pairing::identity::CLIENT_KEY_BITS / 8);
|
||||
cert.verify(b"hello", &sig).expect("the cert carries the identity's public key");
|
||||
let again = ClientIdentity::from_der(id.cert_der(), id.key_pkcs8_der()).unwrap();
|
||||
assert_eq!(again.cert_der(), id.cert_der());
|
||||
assert!(id.cert_der().windows(14).any(|w| w == b"Living Room TV"), "CN in the certificate");
|
||||
assert_eq!(id.cert_signature().unwrap(), cert.signature().unwrap());
|
||||
|
||||
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
|
||||
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), &"n".repeat(10_000), 0), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
// ================================================================================================ PIN
|
||||
|
||||
#[test]
|
||||
fn pin_from_digits() {
|
||||
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
|
||||
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",
|
||||
] {
|
||||
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pin_generate_is_uniform_digits() {
|
||||
let mut rng = SeqRng::new(42);
|
||||
let mut counts = [[0u32; 10]; 4];
|
||||
let draws = 4000;
|
||||
for _ in 0..draws {
|
||||
let p = Pin::generate(&mut rng).unwrap();
|
||||
for (pos, d) in p.as_bytes().iter().enumerate() {
|
||||
assert!(d.is_ascii_digit(), "{d:#x}");
|
||||
counts[pos][usize::from(d - b'0')] += 1;
|
||||
}
|
||||
}
|
||||
// 400 expected per digit and position; a 4-sigma band (sd ~ 19) catches modulo bias of a u8 draw (+20 %).
|
||||
for (pos, row) in counts.iter().enumerate() {
|
||||
for (digit, &n) in row.iter().enumerate() {
|
||||
assert!((324..=476).contains(&n), "digit {digit} at position {pos}: {n} of {draws}");
|
||||
}
|
||||
}
|
||||
let a = Pin::generate(&mut SeqRng::new(9)).unwrap();
|
||||
let b = Pin::generate(&mut SeqRng::new(9)).unwrap();
|
||||
assert_eq!(a, b, "the PIN comes only from the caller's randomness");
|
||||
}
|
||||
|
||||
// ================================================================================================ answer parser
|
||||
|
||||
#[test]
|
||||
fn pair_response_parser() {
|
||||
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><plaincert>4142</plaincert>")).unwrap();
|
||||
assert!(r.paired);
|
||||
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
|
||||
assert_eq!(r.challenge_response, None);
|
||||
let r =
|
||||
parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
|
||||
assert!(!r.paired);
|
||||
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();
|
||||
assert_eq!(r.pairing_secret.as_deref(), Some(&[0x00, 0xFF][..]));
|
||||
|
||||
for (inner, why) in [
|
||||
("", "no paired"),
|
||||
("<plaincert>4142</plaincert>", "no paired"),
|
||||
("<paired>1</paired><plaincert>414</plaincert>", "odd hex"),
|
||||
("<paired>1</paired><plaincert>41 42</plaincert>", "space in hex"),
|
||||
("<paired>1</paired><plaincert>4G</plaincert>", "not hex"),
|
||||
("<paired>1</paired><challengeresponse>0x41</challengeresponse>", "0x prefix"),
|
||||
] {
|
||||
assert_err!(parse_pair_response(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
assert_err!(parse_pair_response(&xml_root(400, "<paired>0</paired>")), Error::HostStatus { code: 400 });
|
||||
assert_err!(parse_pair_response(b""), Error::Malformed { .. });
|
||||
assert_err!(parse_pair_response(b"<"), Error::Malformed { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pair_response_sizes() {
|
||||
let inner = "<paired>1</paired>";
|
||||
for len in [MAX_PAIR_RESPONSE_BYTES - 1, MAX_PAIR_RESPONSE_BYTES] {
|
||||
assert!(parse_pair_response(&xml_padded_to(inner, len)).unwrap().paired, "{len}");
|
||||
}
|
||||
assert_too_large!(
|
||||
parse_pair_response(&xml_padded_to(inner, MAX_PAIR_RESPONSE_BYTES + 1)),
|
||||
MAX_PAIR_RESPONSE_BYTES,
|
||||
MAX_PAIR_RESPONSE_BYTES + 1
|
||||
);
|
||||
assert_too_large!(parse_pair_response(&vec![b'0'; 1 << 22]), MAX_PAIR_RESPONSE_BYTES, 1 << 22);
|
||||
// A plaincert near the cap: the hex text is within MAX_XML_TEXT_BYTES and decodes to half its size.
|
||||
let cert = vec![0x41u8; 30_000];
|
||||
let r = parse_pair_response(&answer(true, Some(("plaincert", &cert)))).unwrap();
|
||||
assert_eq!(r.plain_cert.unwrap().len(), 30_000);
|
||||
}
|
||||
@@ -0,0 +1,785 @@
|
||||
//! RTSP (`docs/PROTOCOL.md` 2): message parsers, the TCP framer (64 KiB cap), SDP and `surround-params`, the
|
||||
//! ANNOUNCE builder and the client state machine, all with hostile input.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||
|
||||
mod common;
|
||||
|
||||
use domistream::Error;
|
||||
use domistream::http::launch::AudioLayout;
|
||||
use domistream::rtsp::client::VideoCodec;
|
||||
use domistream::rtsp::sdp::{self, MAX_OPUS_CONFIGS, MAX_SDP_BYTES, MAX_SDP_LINES};
|
||||
use domistream::rtsp::{
|
||||
EncryptionFlags, HostCapabilities, MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES, Method,
|
||||
RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, StreamConfig, parse_request, parse_response,
|
||||
};
|
||||
use proptest::prelude::*;
|
||||
|
||||
macro_rules! assert_cap {
|
||||
($e:expr, $max:expr) => {
|
||||
match $e {
|
||||
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
||||
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
fn response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
|
||||
let mut m = format!("RTSP/1.0 {status}\r\n");
|
||||
for (k, v) in headers {
|
||||
m.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
m.push_str("\r\n");
|
||||
let mut m = m.into_bytes();
|
||||
m.extend_from_slice(body);
|
||||
m
|
||||
}
|
||||
|
||||
/// A 200 answer padded with a body to exactly `total` bytes.
|
||||
fn response_of_size(total: usize) -> Vec<u8> {
|
||||
let probe = response("200 OK", &[("CSeq", "1"), ("Content-Length", "00000")], b"");
|
||||
let body_len = total - probe.len();
|
||||
let cl = format!("{body_len:05}");
|
||||
let m = response("200 OK", &[("CSeq", "1"), ("Content-Length", &cl)], &vec![b'b'; body_len]);
|
||||
assert_eq!(m.len(), total);
|
||||
m
|
||||
}
|
||||
|
||||
// ================================================================================================ responses
|
||||
|
||||
#[test]
|
||||
fn response_sample() {
|
||||
let r = parse_response(&response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello")).unwrap();
|
||||
assert_eq!(r.status, 200);
|
||||
assert_eq!(r.reason, "OK");
|
||||
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("Content-Length".into(), "5".into())]);
|
||||
assert_eq!(r.body, b"hello");
|
||||
assert_eq!(r.header("cseq"), Some("1"));
|
||||
assert_eq!(r.header("CONTENT-LENGTH"), Some("5"));
|
||||
|
||||
// Without Content-Length the payload is everything after the headers (UNKNOWN U5).
|
||||
let r = parse_response(&response("404 Not Found", &[("CSeq", "2")], b"rest")).unwrap();
|
||||
assert_eq!(r.status, 404);
|
||||
assert_eq!(r.reason, "Not Found");
|
||||
assert_eq!(r.body, b"rest");
|
||||
|
||||
let r = parse_response(&response("200 OK", &[("content-length", "0")], b"")).unwrap();
|
||||
assert!(r.body.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_bad_start_lines() {
|
||||
for bad in [
|
||||
&b""[..],
|
||||
b"R",
|
||||
b"HTTP/1.1 200 OK\r\n\r\n",
|
||||
b"RTSP/1.0 abc OK\r\n\r\n",
|
||||
b"RTSP/1.0 2000 OK\r\n\r\n",
|
||||
b"RTSP/1.0 -20 OK\r\n\r\n",
|
||||
b"RTSP/1.0\r\n\r\n",
|
||||
b"RTSP/2.0 200 OK\r\n\r\n",
|
||||
b" RTSP/1.0 200 OK\r\n\r\n",
|
||||
b"\r\n\r\n",
|
||||
] {
|
||||
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_bad_headers() {
|
||||
for bad in [
|
||||
&b"RTSP/1.0 200 OK\r\nno colon here\r\n\r\n"[..],
|
||||
b"RTSP/1.0 200 OK\r\n: empty name\r\n\r\n",
|
||||
b"RTSP/1.0 200 OK\r\nCSeq: \xff\xfe\r\n\r\n",
|
||||
b"RTSP/1.0 200 OK\r\nCSeq: 1\rX: y\r\n\r\n",
|
||||
] {
|
||||
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||
}
|
||||
// Headers that never end.
|
||||
assert_err!(parse_response(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n"), Error::Truncated { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_lying_content_length() {
|
||||
// Over: claims more than is there.
|
||||
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "10")], b"12345")), Error::Truncated { .. });
|
||||
// Under: more bytes than it claims.
|
||||
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
|
||||
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:?}"
|
||||
);
|
||||
}
|
||||
// Two different lengths.
|
||||
assert_err!(
|
||||
parse_response(&response("200 OK", &[("Content-Length", "5"), ("Content-Length", "4")], b"12345")),
|
||||
Error::Malformed { .. }
|
||||
);
|
||||
// Past the cap: refused as too large, not waited for.
|
||||
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
|
||||
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "4294967295")], b"")), MAX_RTSP_MESSAGE_BYTES);
|
||||
// Past u64: a number that big is over the cap or not a number; either way refused, never wrapped.
|
||||
let r = parse_response(&response("200 OK", &[("Content-Length", "99999999999999999999999")], b""));
|
||||
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{r:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_header_flood() {
|
||||
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<_>>();
|
||||
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);
|
||||
// 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<(&str, &str)> = flood.iter().map(|(k, v)| (k.as_str(), *v)).collect();
|
||||
assert_cap!(parse_response(&response("200 OK", &flood, b"")), MAX_RTSP_HEADERS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_line_cap() {
|
||||
// "X: " + value, without CRLF.
|
||||
let value = |line: usize| "v".repeat(line - 3);
|
||||
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_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);
|
||||
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn response_size_boundaries() {
|
||||
for len in [MAX_RTSP_MESSAGE_BYTES - 1, MAX_RTSP_MESSAGE_BYTES] {
|
||||
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||
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(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
|
||||
}
|
||||
|
||||
// ================================================================================================ requests
|
||||
|
||||
#[test]
|
||||
fn request_parse_and_encode() {
|
||||
let raw = b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\nX-GS-ClientVersion: 14\r\n\r\n";
|
||||
let r = parse_request(raw).unwrap();
|
||||
assert_eq!(r.method, Method::Options);
|
||||
assert_eq!(r.target, "rtsp://192.0.2.10:48010");
|
||||
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("X-GS-ClientVersion".into(), "14".into())]);
|
||||
assert!(r.body.is_empty());
|
||||
assert_eq!(r.encode().unwrap(), raw.to_vec(), "encode emits exactly the given headers, CRLF, empty line");
|
||||
|
||||
let announce = RtspRequest {
|
||||
method: Method::Announce,
|
||||
target: "streamid=control/13/0".into(),
|
||||
headers: vec![("CSeq".into(), "6".into()), ("Content-Length".into(), "6".into())],
|
||||
body: b"v=0\r\n\r".to_vec(),
|
||||
};
|
||||
let bytes = announce.encode().unwrap();
|
||||
assert!(bytes.starts_with(b"ANNOUNCE streamid=control/13/0 RTSP/1.0\r\n"));
|
||||
assert_eq!(parse_request(&bytes).unwrap(), announce);
|
||||
|
||||
for (m, name) in [
|
||||
(Method::Options, "OPTIONS"),
|
||||
(Method::Describe, "DESCRIBE"),
|
||||
(Method::Setup, "SETUP"),
|
||||
(Method::Announce, "ANNOUNCE"),
|
||||
(Method::Play, "PLAY"),
|
||||
] {
|
||||
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()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_refuses_unknown_methods_and_bad_lines() {
|
||||
for m in ["GET_PARAMETER", "TEARDOWN", "options", "GET", "PAUSE"] {
|
||||
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}");
|
||||
}
|
||||
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_too_large!(
|
||||
parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]),
|
||||
MAX_RTSP_MESSAGE_BYTES,
|
||||
MAX_RTSP_MESSAGE_BYTES + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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 mut cases = Vec::new();
|
||||
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
|
||||
cases.push(RtspRequest { target: evil.into(), ..base() });
|
||||
cases.push(RtspRequest { headers: vec![(evil.into(), "v".into())], ..base() });
|
||||
cases.push(RtspRequest { headers: vec![("Transport".into(), evil.into())], ..base() });
|
||||
}
|
||||
cases.push(RtspRequest { headers: vec![("Bad:Name".into(), "v".into())], ..base() });
|
||||
cases.push(RtspRequest { headers: vec![(String::new(), "v".into())], ..base() });
|
||||
cases.push(RtspRequest { target: String::new(), ..base() });
|
||||
for req in cases {
|
||||
assert_err!(req.encode(), Error::Malformed { .. }, "{req:?}");
|
||||
}
|
||||
let big = RtspRequest { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() };
|
||||
assert_cap!(big.encode(), MAX_RTSP_MESSAGE_BYTES);
|
||||
}
|
||||
|
||||
fn method() -> impl Strategy<Value = Method> {
|
||||
prop_oneof![
|
||||
Just(Method::Options),
|
||||
Just(Method::Describe),
|
||||
Just(Method::Setup),
|
||||
Just(Method::Announce),
|
||||
Just(Method::Play)
|
||||
]
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
/// encode then parse gives the request back.
|
||||
#[test]
|
||||
fn request_round_trip(
|
||||
m in method(),
|
||||
target in "[!-~]{1,40}",
|
||||
headers in proptest::collection::vec(("[A-Za-z][A-Za-z0-9-]{0,15}", "[!-~]([ -~]{0,30}[!-~])?"), 0..10),
|
||||
body in proptest::collection::vec(any::<u8>(), 0..200),
|
||||
) {
|
||||
let mut headers: Vec<(String, String)> =
|
||||
headers.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("content-length")).collect();
|
||||
headers.insert(0, ("CSeq".into(), "1".into()));
|
||||
if !body.is_empty() {
|
||||
headers.push(("Content-Length".into(), body.len().to_string()));
|
||||
}
|
||||
let req = RtspRequest { method: m, target, headers, body };
|
||||
let bytes = req.encode().map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||
prop_assert_eq!(parse_request(&bytes), Ok(req));
|
||||
}
|
||||
|
||||
/// Arbitrary bytes never panic, and a parsed response respects the caps.
|
||||
#[test]
|
||||
fn response_never_panics(data in proptest::collection::vec(any::<u8>(), 0..1024)) {
|
||||
if let Ok(r) = parse_response(&data) {
|
||||
prop_assert!(r.headers.len() <= MAX_RTSP_HEADERS);
|
||||
prop_assert!(r.body.len() <= data.len());
|
||||
prop_assert!(r.reason.len() <= MAX_RTSP_LINE_BYTES);
|
||||
}
|
||||
let _ = parse_request(&data);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================ framer
|
||||
|
||||
fn drain(f: &mut RtspFramer) -> Vec<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(m) = f.next_message().unwrap() {
|
||||
out.push(m);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_cuts_messages() {
|
||||
let a = response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello");
|
||||
let b = response("200 OK", &[("CSeq", "2"), ("Content-Length", "0")], b"");
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(&[a.clone(), b.clone()].concat()).unwrap();
|
||||
assert_eq!(drain(&mut f), vec![a.clone(), b.clone()]);
|
||||
assert_eq!(f.buffered(), 0);
|
||||
assert_eq!(f.finish(), Ok(None));
|
||||
|
||||
// One byte at a time: same messages, nothing early.
|
||||
let mut f = RtspFramer::new();
|
||||
let stream = [a.clone(), b.clone()].concat();
|
||||
let mut got = Vec::new();
|
||||
for (i, byte) in stream.iter().enumerate() {
|
||||
f.push(std::slice::from_ref(byte)).unwrap();
|
||||
got.extend(drain(&mut f));
|
||||
if i + 1 < a.len() {
|
||||
assert!(got.is_empty(), "message returned before its last byte");
|
||||
}
|
||||
}
|
||||
assert_eq!(got, vec![a, b]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_partial_second_message_stays_buffered() {
|
||||
let a = response("200 OK", &[("Content-Length", "2")], b"ok");
|
||||
let partial = b"RTSP/1.0 200 OK\r\nCont";
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(&[a.clone(), partial.to_vec()].concat()).unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), Some(a));
|
||||
assert_eq!(f.next_message().unwrap(), None);
|
||||
assert_eq!(f.buffered(), partial.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_without_content_length_waits_for_close() {
|
||||
let m = response("200 OK", &[("CSeq", "1")], b"payload until close");
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(&m).unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), None, "no Content-Length: the message ends at close (U5)");
|
||||
assert_eq!(f.finish().unwrap(), Some(m));
|
||||
assert_eq!(f.buffered(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_close_mid_body_is_truncated() {
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(&response("200 OK", &[("Content-Length", "10")], b"12345")).unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), None);
|
||||
assert_err!(f.finish(), Error::Truncated { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_cap_64k_plus_one() {
|
||||
// Bytes that never form a complete header section.
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES]).unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), None);
|
||||
assert_eq!(f.buffered(), MAX_RTSP_MESSAGE_BYTES);
|
||||
assert_too_large!(f.push(b"a"), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
|
||||
|
||||
// One push over the cap.
|
||||
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
|
||||
);
|
||||
|
||||
// A whole message of exactly the cap is fine.
|
||||
let mut f = RtspFramer::new();
|
||||
let m = response_of_size(MAX_RTSP_MESSAGE_BYTES);
|
||||
f.push(&m).unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), Some(m));
|
||||
}
|
||||
|
||||
/// Pushes `bytes` and asks for a message; the first error from either call.
|
||||
fn push_then_next(f: &mut RtspFramer, bytes: &[u8]) -> domistream::Result<Option<Vec<u8>>> {
|
||||
f.push(bytes)?;
|
||||
f.next_message()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_refuses_lying_content_length_early() {
|
||||
// The header says the message will be over the cap: refused now, without waiting for (or buffering) it.
|
||||
for cl in ["65537", "4294967295", "18446744073709551615"] {
|
||||
let mut f = RtspFramer::new();
|
||||
let r = push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"x"));
|
||||
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
|
||||
}
|
||||
let mut f = RtspFramer::new();
|
||||
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"] {
|
||||
let mut f = RtspFramer::new();
|
||||
assert_err!(
|
||||
push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")),
|
||||
Error::Malformed { .. },
|
||||
"{cl}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framer_empty_pushes() {
|
||||
let mut f = RtspFramer::new();
|
||||
f.push(b"").unwrap();
|
||||
assert_eq!(f.next_message().unwrap(), None);
|
||||
assert_eq!(f.finish().unwrap(), None);
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
||||
|
||||
/// Any chunking of a stream of messages yields the same messages.
|
||||
#[test]
|
||||
fn framer_is_chunking_invariant(bodies in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..300), 1..6), cuts in proptest::collection::vec(1usize..200, 1..50)) {
|
||||
let msgs: Vec<Vec<u8>> = bodies.iter().enumerate()
|
||||
.map(|(i, b)| response("200 OK", &[("CSeq", &i.to_string()), ("Content-Length", &b.len().to_string())], b))
|
||||
.collect();
|
||||
let stream = msgs.concat();
|
||||
let mut f = RtspFramer::new();
|
||||
let mut got = Vec::new();
|
||||
let mut pos = 0;
|
||||
let mut cut = cuts.iter().cycle();
|
||||
while pos < stream.len() {
|
||||
let end = (pos + cut.next().copied().unwrap_or(1)).min(stream.len());
|
||||
f.push(&stream[pos..end]).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||
while let Some(m) = f.next_message().map_err(|e| TestCaseError::fail(format!("{e:?}")))? {
|
||||
got.push(m);
|
||||
}
|
||||
prop_assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
|
||||
pos = end;
|
||||
}
|
||||
prop_assert_eq!(got, msgs);
|
||||
prop_assert_eq!(f.finish(), Ok(None));
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================ SDP
|
||||
|
||||
const DESCRIBE_SDP: &str = "v=0\r\no=- 0 14 IN IPv4 0.0.0.0\r\ns=Lab host\r\n\
|
||||
a=x-ss-general.featureFlags:3\r\n\
|
||||
a=x-ss-general.encryptionSupported:7\r\n\
|
||||
a=x-nv-video[0].refPicInvalidation:1\r\n\
|
||||
a=rtpmap:98 AV1/90000\r\n\
|
||||
a=fmtp:96 packetization-mode=1\r\n\
|
||||
sprop-parameter-sets=AAAAAU\r\n\
|
||||
a=fmtp:97 surround-params=21101\r\n\
|
||||
a=fmtp:97 surround-params=642012345\r\n\
|
||||
a=fmtp:97 surround-params=85301234567\r\n\
|
||||
a=recvonly\r\n";
|
||||
|
||||
#[test]
|
||||
fn sdp_sample() {
|
||||
let s = sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap();
|
||||
assert_eq!(s.attribute("x-ss-general.featureFlags"), Some("3"));
|
||||
assert_eq!(s.attribute("rtpmap"), Some("98 AV1/90000"));
|
||||
assert_eq!(s.attribute("fmtp"), Some("96 packetization-mode=1"), "first one wins");
|
||||
assert_eq!(s.attribute("recvonly"), Some(""), "flag attribute");
|
||||
assert_eq!(s.attributes.iter().filter(|(n, _)| n == "fmtp").count(), 4);
|
||||
assert_eq!(s.other[0], ('v', "0".to_string()));
|
||||
assert!(s.other.iter().any(|(t, v)| *t == '\0' && v.contains("sprop-parameter-sets")), "{:?}", s.other);
|
||||
// LF-only line ends give the same result.
|
||||
assert_eq!(sdp::parse_sdp(DESCRIBE_SDP.replace("\r\n", "\n").as_bytes()).unwrap(), s);
|
||||
assert_eq!(sdp::parse_sdp(b"").unwrap(), sdp::Sdp::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sdp_hostile() {
|
||||
for (bad, why) in [
|
||||
(&b"v=0\r\nno equals sign\r\n"[..], "line without ="),
|
||||
(b"a=x:\xff\r\n", "not UTF-8"),
|
||||
(b"=x\r\n", "empty type"),
|
||||
] {
|
||||
assert_err!(sdp::parse_sdp(bad), Error::Malformed { .. }, "{why}");
|
||||
}
|
||||
let lines = |n: usize| "a=x:1\n".repeat(n);
|
||||
assert_eq!(sdp::parse_sdp(lines(MAX_SDP_LINES).as_bytes()).unwrap().attributes.len(), MAX_SDP_LINES);
|
||||
assert_cap!(sdp::parse_sdp(lines(MAX_SDP_LINES + 1).as_bytes()), MAX_SDP_LINES);
|
||||
let sized = |n: usize| {
|
||||
let mut s = "a=pad:".to_string();
|
||||
s.push_str(&"p".repeat(n - s.len() - 1));
|
||||
s.push('\n');
|
||||
s
|
||||
};
|
||||
for n in [MAX_SDP_BYTES - 1, MAX_SDP_BYTES] {
|
||||
assert!(sdp::parse_sdp(sized(n).as_bytes()).is_ok(), "{n}");
|
||||
}
|
||||
assert_too_large!(sdp::parse_sdp(sized(MAX_SDP_BYTES + 1).as_bytes()), MAX_SDP_BYTES, MAX_SDP_BYTES + 1);
|
||||
assert_too_large!(sdp::parse_sdp(&vec![b'a'; 1 << 20]), MAX_SDP_BYTES, 1 << 20);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surround_params() {
|
||||
let c = sdp::parse_surround_params("21101").unwrap();
|
||||
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.clone()), (2, 1, 1, vec![0, 1]));
|
||||
let c = sdp::parse_surround_params("642012345").unwrap();
|
||||
assert_eq!((c.channels, c.streams, c.coupled_streams), (6, 4, 2));
|
||||
assert_eq!(c.mapping, vec![0, 1, 2, 3, 4, 5]);
|
||||
let c = sdp::parse_surround_params("85301234567").unwrap();
|
||||
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.len()), (8, 5, 3, 8));
|
||||
let c = sdp::parse_surround_params("11000").unwrap_err();
|
||||
assert!(matches!(c, Error::Malformed { .. }), "one channel needs one mapping digit, not two");
|
||||
assert_eq!(sdp::parse_surround_params("1100").unwrap().mapping, vec![0]);
|
||||
|
||||
for (bad, why) in [
|
||||
("", "empty"),
|
||||
("2", "cut"),
|
||||
("2110", "one mapping digit short"),
|
||||
("211012", "one mapping digit too many"),
|
||||
("21102", "mapping 2 >= streams + coupled"),
|
||||
("21201", "coupled > streams"),
|
||||
("01100", "zero channels"),
|
||||
("20001", "zero streams"),
|
||||
("2a101", "not a digit"),
|
||||
("2 1101", "space"),
|
||||
("9530123456789", "9 channels > MAX_AUDIO_CHANNELS"),
|
||||
("-2110", "sign"),
|
||||
] {
|
||||
assert_err!(sdp::parse_surround_params(bad), Error::Malformed { .. }, "{why}: {bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_capabilities() {
|
||||
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||
assert_eq!(caps.encryption_supported, EncryptionFlags(7));
|
||||
assert_eq!(caps.feature_flags.0, 3);
|
||||
assert!(caps.reference_frame_invalidation);
|
||||
assert!(caps.av1);
|
||||
assert_eq!(caps.opus_configs.len(), 3);
|
||||
assert_eq!(caps.opus_configs[0].mapping, vec![0, 1]);
|
||||
|
||||
let none = HostCapabilities::from_sdp(&sdp::parse_sdp(b"v=0\n").unwrap()).unwrap();
|
||||
assert_eq!(none, HostCapabilities::default());
|
||||
|
||||
for bad in [
|
||||
"a=x-ss-general.encryptionSupported:x\n",
|
||||
"a=x-ss-general.encryptionSupported:256\n",
|
||||
"a=x-ss-general.featureFlags:-1\n",
|
||||
"a=fmtp:97 surround-params=2110\n",
|
||||
"a=fmtp:97 surround-params=\n",
|
||||
] {
|
||||
let s = sdp::parse_sdp(bad.as_bytes()).unwrap();
|
||||
assert_err!(HostCapabilities::from_sdp(&s), Error::Malformed { .. }, "{bad:?}");
|
||||
}
|
||||
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);
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
fn config() -> StreamConfig {
|
||||
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(EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_payload() {
|
||||
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &host).unwrap()).expect("ANNOUNCE is valid SDP");
|
||||
assert_eq!(s.attribute("x-nv-video[0].clientViewportWd"), Some("1920"));
|
||||
assert_eq!(s.attribute("x-nv-video[0].clientViewportHt"), Some("1080"));
|
||||
assert_eq!(s.attribute("x-nv-video[0].maxFPS"), Some("60"));
|
||||
assert_eq!(s.attribute("x-nv-video[0].packetSize"), Some("1024"));
|
||||
assert_eq!(s.attribute("x-ml-video.configuredBitrateKbps"), Some("20000"));
|
||||
assert_eq!(s.attribute("x-nv-aqos.packetDuration"), Some("5"));
|
||||
assert_eq!(s.attribute("x-nv-vqos[0].fec.minRequiredFecPackets"), Some("2"));
|
||||
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
|
||||
|
||||
// Only what both sides support is turned on.
|
||||
let mut partial = host.clone();
|
||||
partial.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO);
|
||||
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &partial).unwrap()).unwrap();
|
||||
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announce_refuses_what_the_host_lacks() {
|
||||
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||
let mut no_v2 = host.clone();
|
||||
no_v2.encryption_supported = EncryptionFlags(EncryptionFlags::VIDEO | EncryptionFlags::AUDIO);
|
||||
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
|
||||
let mut no_av1 = host.clone();
|
||||
no_av1.av1 = false;
|
||||
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());
|
||||
}
|
||||
|
||||
// ================================================================================================ client
|
||||
|
||||
const URL: &str = "rtsp://192.0.2.10:48010";
|
||||
|
||||
fn describe_answer(cseq: u32, sdp: &str) -> Vec<u8> {
|
||||
response("200 OK", &[("CSeq", &cseq.to_string()), ("Content-Length", &sdp.len().to_string())], sdp.as_bytes())
|
||||
}
|
||||
|
||||
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
|
||||
response(
|
||||
"200 OK",
|
||||
&[
|
||||
("CSeq", &cseq.to_string()),
|
||||
("Session", "DEADBEEFCAFE;timeout = 90"),
|
||||
("Transport", &format!("server_port={port}")),
|
||||
],
|
||||
b"",
|
||||
)
|
||||
}
|
||||
|
||||
fn ok_answer(cseq: u32) -> Vec<u8> {
|
||||
response("200 OK", &[("CSeq", &cseq.to_string())], b"")
|
||||
}
|
||||
|
||||
fn next_request(c: &mut RtspClient) -> RtspRequest {
|
||||
let bytes = c.poll_request().expect("a request is due");
|
||||
assert_eq!(c.poll_request(), None, "each request is returned once");
|
||||
parse_request(&bytes).expect("the client's request parses")
|
||||
}
|
||||
|
||||
fn cseq(r: &RtspRequest) -> u32 {
|
||||
r.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("cseq")).expect("CSeq").1.parse().expect("CSeq number")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_full_negotiation() {
|
||||
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||
assert_eq!(c.state(), RtspClientState::Options);
|
||||
let expect = [
|
||||
(Method::Options, RtspClientState::Describe),
|
||||
(Method::Describe, RtspClientState::SetupAudio),
|
||||
(Method::Setup, RtspClientState::SetupVideo),
|
||||
(Method::Setup, RtspClientState::SetupControl),
|
||||
(Method::Setup, RtspClientState::Announce),
|
||||
(Method::Announce, RtspClientState::Play),
|
||||
];
|
||||
let mut last_cseq = 0;
|
||||
let streams = ["streamid=audio", "streamid=video", "streamid=control"];
|
||||
for (i, (method, next_state)) in expect.iter().enumerate() {
|
||||
let req = next_request(&mut c);
|
||||
assert_eq!(req.method, *method, "request {i}");
|
||||
let n = cseq(&req);
|
||||
assert!(n > last_cseq, "CSeq counts up");
|
||||
last_cseq = n;
|
||||
if *method == Method::Setup {
|
||||
assert!(req.target.contains(streams[i - 2]), "SETUP {} target {:?}", i - 2, req.target);
|
||||
assert!(req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("transport")), "SETUP has Transport");
|
||||
}
|
||||
if *method == Method::Announce {
|
||||
let s = sdp::parse_sdp(&req.body).unwrap();
|
||||
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
|
||||
}
|
||||
let answer = match i {
|
||||
1 => describe_answer(n, DESCRIBE_SDP),
|
||||
2 => setup_answer(n, "48000"),
|
||||
3 => setup_answer(n, "47998"),
|
||||
4 => setup_answer(n, "47999"),
|
||||
_ => ok_answer(n),
|
||||
};
|
||||
assert_eq!(c.handle_response(&answer).unwrap(), RtspProgress::Continue);
|
||||
assert_eq!(c.state(), *next_state);
|
||||
}
|
||||
let play = next_request(&mut c);
|
||||
assert_eq!(play.method, Method::Play);
|
||||
match c.handle_response(&ok_answer(cseq(&play))).unwrap() {
|
||||
RtspProgress::Ready(n) => {
|
||||
assert_eq!((n.ports.audio, n.ports.video, n.ports.control), (48000, 47998, 47999));
|
||||
assert_eq!(n.encryption, EncryptionFlags(7));
|
||||
assert_eq!(n.opus.mapping, vec![0, 1]);
|
||||
assert_eq!(n.opus.channels, 2);
|
||||
assert_eq!(n.session_id.as_deref(), Some("DEADBEEFCAFE"));
|
||||
assert!(n.host.av1);
|
||||
assert!(!n.ping_payload.is_empty());
|
||||
}
|
||||
RtspProgress::Continue => panic!("PLAY answered: expected Ready"),
|
||||
}
|
||||
assert_eq!(c.state(), RtspClientState::Ready);
|
||||
assert_eq!(c.poll_request(), None);
|
||||
assert_err!(c.handle_response(&ok_answer(last_cseq + 2)), Error::State { .. });
|
||||
}
|
||||
|
||||
/// Runs the negotiation, answering with `answers(i, cseq)`; returns the first error and the state then.
|
||||
fn run_until_error(answers: impl Fn(usize, u32) -> Vec<u8>) -> (Error, RtspClientState) {
|
||||
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||
for i in 0..7 {
|
||||
let req = next_request(&mut c);
|
||||
if let Err(e) = c.handle_response(&answers(i, cseq(&req))) {
|
||||
return (e, c.state());
|
||||
}
|
||||
}
|
||||
panic!("negotiation finished without an error");
|
||||
}
|
||||
|
||||
fn good(i: usize, n: u32) -> Vec<u8> {
|
||||
match i {
|
||||
1 => describe_answer(n, DESCRIBE_SDP),
|
||||
2 => setup_answer(n, "48000"),
|
||||
3 => setup_answer(n, "47998"),
|
||||
4 => setup_answer(n, "47999"),
|
||||
_ => ok_answer(n),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_refuses_hostile_answers() {
|
||||
let (e, s) = run_until_error(|i, n| if i == 1 { ok_answer(n + 1) } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
|
||||
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) },
|
||||
);
|
||||
assert_eq!(e, Error::HostStatus { code: 404 });
|
||||
assert_eq!(s, RtspClientState::Failed);
|
||||
|
||||
let no_v2 = DESCRIBE_SDP.replace("encryptionSupported:7", "encryptionSupported:6");
|
||||
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, &no_v2) } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Unsupported { .. }), "host without control V2: {e:?}");
|
||||
|
||||
for port in ["0", "70000", "abc", ""] {
|
||||
let (e, s) = run_until_error(|i, n| if i == 3 { setup_answer(n, port) } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Malformed { .. }), "server_port={port:?}: {e:?}");
|
||||
assert_eq!(s, RtspClientState::Failed);
|
||||
}
|
||||
let (e, _) = run_until_error(|i, n| if i == 2 { ok_answer(n) } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Malformed { .. }), "SETUP answer without Transport: {e:?}");
|
||||
|
||||
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, "v=0\nbroken line\n") } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Malformed { .. }), "bad SDP: {e:?}");
|
||||
|
||||
let (e, _) = run_until_error(|i, n| if i == 0 { b"garbage".to_vec() } else { good(i, n) });
|
||||
assert!(matches!(e, Error::Malformed { .. }), "garbage: {e:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn client_answer_without_request() {
|
||||
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||
let req = next_request(&mut c);
|
||||
c.handle_response(&ok_answer(cseq(&req))).unwrap();
|
||||
// DESCRIBE is due but its answer arrives twice.
|
||||
let d = next_request(&mut c);
|
||||
c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)).unwrap();
|
||||
assert_err!(c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)), Error::State { .. });
|
||||
}
|
||||
|
||||
#[test]
|
||||
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"]
|
||||
{
|
||||
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
|
||||
}
|
||||
for broken in [
|
||||
StreamConfig { width: 0, ..config() },
|
||||
StreamConfig { height: 0, ..config() },
|
||||
StreamConfig { fps: 0, ..config() },
|
||||
StreamConfig { bitrate_kbps: 0, ..config() },
|
||||
StreamConfig { packet_size: 0, ..config() },
|
||||
] {
|
||||
assert_err!(RtspClient::new(URL, broken), Error::Malformed { .. });
|
||||
}
|
||||
}
|
||||
@@ -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:
|
||||
# cargo fuzz run <target> -- -max_total_time=600
|
||||
@@ -155,3 +155,59 @@ path = "fuzz_targets/audio_packet.rs"
|
||||
test = false
|
||||
doc = 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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes `/applist` answers.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes audio packets.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes encrypted control frames (outer fields), their opening, and seal/open round trips.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes decrypted control messages from the host.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::control::{HostMessage, parse_host_message, parse_message};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes ENet datagrams.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::enet::protocol::{MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, encode_datagram, parse_datagram};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes INPUT_DATA messages.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::input::{MAX_INPUT_MESSAGE_BYTES, encode_input, parse_input};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes `/launch` and `/resume` answers.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES, MAX_SESSION_URL_BYTES};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes pairing answers.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::pairing::MAX_PAIR_RESPONSE_BYTES;
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes the RTP header.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
@@ -7,5 +7,11 @@
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes the RTSP framer over a chunked byte stream.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
|
||||
let Some((&chunk, rest)) = data.split_first() else { return };
|
||||
let chunk = usize::from(chunk).max(1);
|
||||
let mut framer = domistream::rtsp::RtspFramer::new();
|
||||
for piece in rest.chunks(chunk) {
|
||||
if framer.push(piece).is_err() {
|
||||
return;
|
||||
let chunked = frame(rest, usize::from(chunk).max(1));
|
||||
let whole = frame(rest, rest.len().max(1));
|
||||
if let (Some(a), Some(b)) = (&chunked, &whole) {
|
||||
assert_eq!(a, b, "framing depends on chunking");
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes RTSP requests.
|
||||
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable.
|
||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||
|
||||
#![no_main]
|
||||
@@ -7,5 +7,8 @@
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes RTSP responses.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::rtsp::{MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes SDP payloads, the host capabilities read from them, and `surround-params` values.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) {
|
||||
let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp);
|
||||
if let Ok(s) = sdp::parse_sdp(data) {
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes the host certificate PEM (`plaincert`).
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes `/serverinfo` answers.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
use libfuzzer_sys::fuzz_target;
|
||||
|
||||
use domistream::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
|
||||
|
||||
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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes video packets and the frame header.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
let _ = domistream::video::parse_video_packet(data);
|
||||
let _ = domistream::video::packet::parse_frame_header(data);
|
||||
if let Ok(p) = domistream::video::parse_video_packet(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.
|
||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
||||
//! Fuzzes the XML reader behind every HTTP answer, and `parse_status_response` on the same bytes.
|
||||
//! 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`.
|
||||
|
||||
#![no_main]
|
||||
|
||||
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]| {
|
||||
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(_)) => {}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
// AES-128-GCM test vectors for DomiStream (control frames and video packets), computed with .NET's AesGcm, a
|
||||
// crypto implementation independent of the RustCrypto crates DomiStream uses.
|
||||
//
|
||||
// Run by gen_vectors.py (`dotnet run gcm_vectors.cs -- <input> <output>`), never by hand. Input lines:
|
||||
// <name> <key hex> <nonce hex> <plaintext hex>
|
||||
// Output lines:
|
||||
// <name> <ciphertext hex> <tag hex>
|
||||
// No associated data, 16-byte tags (docs/PROTOCOL.md 3.2 and 7). Keys are fixed test-only values.
|
||||
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
var input = File.ReadAllLines(args[0]);
|
||||
var output = new StringBuilder();
|
||||
foreach (var line in input)
|
||||
{
|
||||
if (line.Trim().Length == 0) continue;
|
||||
var parts = line.Split(' ');
|
||||
var key = Convert.FromHexString(parts[1]);
|
||||
var nonce = Convert.FromHexString(parts[2]);
|
||||
var plaintext = parts[3] == "-" ? Array.Empty<byte>() : Convert.FromHexString(parts[3]);
|
||||
var ciphertext = new byte[plaintext.Length];
|
||||
var tag = new byte[16];
|
||||
using var gcm = new AesGcm(key, 16);
|
||||
gcm.Encrypt(nonce, plaintext, ciphertext, tag);
|
||||
output.Append(parts[0]).Append(' ')
|
||||
.Append(ciphertext.Length == 0 ? "-" : Convert.ToHexString(ciphertext)).Append(' ')
|
||||
.Append(Convert.ToHexString(tag)).Append('\n');
|
||||
}
|
||||
File.WriteAllText(args[1], output.ToString());
|
||||
@@ -0,0 +1,437 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generates DomiStream's crypto test vectors with tools that are independent of the RustCrypto crates DomiStream
|
||||
uses: Python's hashlib (SHA-256), the OpenSSL 3.x command line (RSA keys, X.509 certificates, PKCS#1 v1.5 SHA-256
|
||||
signatures, AES-128-ECB without padding, AES-128-CBC with PKCS#7) and .NET's AesGcm (AES-128-GCM, gcm_vectors.cs).
|
||||
|
||||
Everything written here is TEST-ONLY: the keys are made fresh on this machine for the tests, never a real host's
|
||||
or client's, and must never be used for anything else. Values follow docs/PROTOCOL.md (sections in the comments).
|
||||
|
||||
python tools/vectors/gen_vectors.py # recompute vectors, keep the existing test keys
|
||||
python tools/vectors/gen_vectors.py --fresh-keys # also make new test keys and certificates
|
||||
|
||||
Environment: DOMISTREAM_OPENSSL (path to openssl, default: Git for Windows' OpenSSL 3.5, then PATH) and
|
||||
DOMISTREAM_DOTNET (default: dotnet on PATH). Standard library only; nothing is installed or downloaded.
|
||||
|
||||
Output: crates/domistream/tests/fixtures/ (text only: hex and PEM).
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
FIXTURES = os.path.join(ROOT, "crates", "domistream", "tests", "fixtures")
|
||||
|
||||
HEADER = (
|
||||
"# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.\n"
|
||||
"# Never a real host's or client's key. Do not edit by hand: change the script and run it again.\n"
|
||||
)
|
||||
|
||||
|
||||
def find_openssl():
|
||||
env = os.environ.get("DOMISTREAM_OPENSSL")
|
||||
if env:
|
||||
return env
|
||||
git = r"C:\Program Files\Git\mingw64\bin\openssl.exe"
|
||||
if os.path.exists(git):
|
||||
return git
|
||||
found = shutil.which("openssl")
|
||||
if not found:
|
||||
sys.exit("openssl not found; set DOMISTREAM_OPENSSL")
|
||||
return found
|
||||
|
||||
|
||||
OPENSSL = find_openssl()
|
||||
DOTNET = os.environ.get("DOMISTREAM_DOTNET") or shutil.which("dotnet") or "dotnet"
|
||||
WORK = tempfile.mkdtemp(prefix="domistream-vectors-")
|
||||
OPENSSL_CNF = os.path.join(WORK, "openssl.cnf")
|
||||
with open(OPENSSL_CNF, "w", encoding="ascii") as f:
|
||||
f.write("[req]\ndistinguished_name = dn\nprompt = no\n[dn]\n")
|
||||
|
||||
|
||||
def run(args, stdin=None):
|
||||
env = dict(os.environ, OPENSSL_CONF=OPENSSL_CNF)
|
||||
proc = subprocess.run(args, input=stdin, capture_output=True, env=env, check=False)
|
||||
if proc.returncode != 0:
|
||||
sys.exit(f"command failed: {args}\n{proc.stderr.decode(errors='replace')}")
|
||||
return proc.stdout
|
||||
|
||||
|
||||
def openssl(*args, stdin=None):
|
||||
return run([OPENSSL, *args], stdin=stdin)
|
||||
|
||||
|
||||
def fixed(label, n):
|
||||
"""A fixed, reproducible test value: the first n bytes of SHA-256 of a label (chained when n > 32)."""
|
||||
out = b""
|
||||
counter = 0
|
||||
while len(out) < n:
|
||||
out += hashlib.sha256(f"domistream-test:{label}:{counter}".encode()).digest()
|
||||
counter += 1
|
||||
return out[:n]
|
||||
|
||||
|
||||
def sha256(*parts):
|
||||
h = hashlib.sha256()
|
||||
for p in parts:
|
||||
h.update(p)
|
||||
return h.digest()
|
||||
|
||||
|
||||
def tmp(name, data=None):
|
||||
path = os.path.join(WORK, name)
|
||||
if data is not None:
|
||||
with open(path, "wb") as f:
|
||||
f.write(data)
|
||||
return path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- AES via the OpenSSL CLI
|
||||
|
||||
|
||||
def ecb_encrypt(key, data):
|
||||
assert len(data) % 16 == 0
|
||||
return openssl("enc", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
|
||||
|
||||
|
||||
def ecb_decrypt(key, data):
|
||||
return openssl("enc", "-d", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
|
||||
|
||||
|
||||
def cbc_encrypt(key, iv, data):
|
||||
return openssl("enc", "-aes-128-cbc", "-K", key.hex(), "-iv", iv.hex(), stdin=data)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- RSA and X.509 via the OpenSSL CLI
|
||||
|
||||
|
||||
def make_rsa_identity(stem, common_name):
|
||||
key = os.path.join(FIXTURES, f"{stem}-key.pem")
|
||||
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
|
||||
openssl("genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", key)
|
||||
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", f"/CN={common_name}",
|
||||
"-config", OPENSSL_CNF, "-out", cert)
|
||||
|
||||
|
||||
def make_ec_cert(stem):
|
||||
key = tmp(f"{stem}-key.pem")
|
||||
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
|
||||
openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", key)
|
||||
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", "/CN=DomiStream test-only EC",
|
||||
"-config", OPENSSL_CNF, "-out", cert)
|
||||
|
||||
|
||||
def cert_der(stem):
|
||||
return openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-outform", "DER")
|
||||
|
||||
|
||||
def key_pkcs8_der(stem):
|
||||
return openssl("pkcs8", "-topk8", "-nocrypt", "-in", os.path.join(FIXTURES, f"{stem}-key.pem"), "-outform", "DER")
|
||||
|
||||
|
||||
def sign(stem, data):
|
||||
"""RSASSA-PKCS1-v1_5 with SHA-256 (OpenSSL's default padding for RSA keys)."""
|
||||
sig = openssl("dgst", "-sha256", "-sign", os.path.join(FIXTURES, f"{stem}-key.pem"), tmp("data.bin", data))
|
||||
# Check it with the certificate's public key, so a vector never carries a signature OpenSSL itself rejects.
|
||||
pub = tmp("pub.pem", openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-pubkey", "-noout"))
|
||||
openssl("dgst", "-sha256", "-verify", pub, "-signature", tmp("sig.bin", sig), tmp("data.bin", data))
|
||||
return sig
|
||||
|
||||
|
||||
def der_read(buf, pos):
|
||||
"""One DER TLV at pos: (tag, content_start, content_end)."""
|
||||
tag = buf[pos]
|
||||
length = buf[pos + 1]
|
||||
pos += 2
|
||||
if length & 0x80:
|
||||
n = length & 0x7F
|
||||
length = int.from_bytes(buf[pos:pos + n], "big")
|
||||
pos += n
|
||||
return tag, pos, pos + length
|
||||
|
||||
|
||||
def cert_signature_value(der):
|
||||
"""The raw signatureValue bytes of an X.509 certificate (RFC 5280 4.1): the BIT STRING's content after its
|
||||
unused-bits octet."""
|
||||
tag, start, end = der_read(der, 0)
|
||||
assert tag == 0x30 and end == len(der)
|
||||
_, _, tbs_end = der_read(der, start) # tbsCertificate
|
||||
_, _, alg_end = der_read(der, tbs_end) # signatureAlgorithm
|
||||
tag, sig_start, sig_end = der_read(der, alg_end)
|
||||
assert tag == 0x03 and sig_end == end
|
||||
assert der[sig_start] == 0, "unused bits in signatureValue"
|
||||
return der[sig_start + 1:sig_end]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- AES-GCM via .NET
|
||||
|
||||
|
||||
def gcm_batch(rows):
|
||||
"""rows: (name, key, nonce, plaintext) -> {name: (ciphertext, tag)}"""
|
||||
lines = [f"{n} {k.hex()} {iv.hex()} {pt.hex() if pt else '-'}" for n, k, iv, pt in rows]
|
||||
src = tmp("gcm_in.txt", ("\n".join(lines) + "\n").encode())
|
||||
dst = tmp("gcm_out.txt")
|
||||
run([DOTNET, "run", os.path.join(HERE, "gcm_vectors.cs"), "--", src, dst])
|
||||
out = {}
|
||||
with open(dst, encoding="ascii") as f:
|
||||
for line in f:
|
||||
name, ct, tag = line.split()
|
||||
out[name] = (b"" if ct == "-" else bytes.fromhex(ct), bytes.fromhex(tag))
|
||||
return out
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- writers
|
||||
|
||||
|
||||
def write_vectors(filename, title, entries):
|
||||
path = os.path.join(FIXTURES, filename)
|
||||
with open(path, "w", encoding="ascii", newline="\n") as f:
|
||||
f.write(HEADER)
|
||||
f.write(f"# {title}\n")
|
||||
for name, value in entries:
|
||||
if name.startswith("#"):
|
||||
f.write(f"\n{name}\n")
|
||||
continue
|
||||
if isinstance(value, bytes):
|
||||
value = value.hex()
|
||||
f.write(f"{name} = {value}\n")
|
||||
print("wrote", os.path.relpath(path, ROOT))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- pairing (PROTOCOL.md 1.5)
|
||||
|
||||
|
||||
def pairing_vectors():
|
||||
host_der = cert_der("test-only-host")
|
||||
client_der = cert_der("test-only-client")
|
||||
rogue_der = cert_der("test-only-rogue")
|
||||
host_sig = cert_signature_value(host_der)
|
||||
client_sig = cert_signature_value(client_der)
|
||||
|
||||
pin = b"4071"
|
||||
wrong_pin = b"4072"
|
||||
# The client's randomness, in the order the state machine draws it: salt (step 1), C (step 2), secret_c (step 3).
|
||||
salt = fixed("salt-a", 16)
|
||||
c = fixed("client-challenge-a", 16)
|
||||
secret_c = fixed("client-secret-a", 16)
|
||||
# A second session (different randomness) for the replay test.
|
||||
salt_b = fixed("salt-b", 16)
|
||||
c_b = fixed("client-challenge-b", 16)
|
||||
secret_c_b = fixed("client-secret-b", 16)
|
||||
# The host's values.
|
||||
s_c = fixed("server-challenge", 16)
|
||||
secret_s = fixed("server-secret", 16)
|
||||
|
||||
key = sha256(salt, pin)[:16]
|
||||
req2 = ecb_encrypt(key, c)
|
||||
assert ecb_decrypt(key, req2) == c
|
||||
h_s = sha256(c, host_sig, secret_s)
|
||||
resp2 = ecb_encrypt(key, h_s + s_c)
|
||||
h_c = sha256(s_c, client_sig, secret_c)
|
||||
req3 = ecb_encrypt(key, h_c)
|
||||
secret_s_sig = sign("test-only-host", secret_s)
|
||||
resp3 = secret_s + secret_s_sig
|
||||
secret_c_sig = sign("test-only-client", secret_c)
|
||||
req4 = secret_c + secret_c_sig
|
||||
|
||||
# Wrong PIN on the host: the host decrypts the client challenge with its own key and answers with it.
|
||||
key_wrong = sha256(salt, wrong_pin)[:16]
|
||||
c_seen_by_host = ecb_decrypt(key_wrong, req2)
|
||||
resp2_wrong_pin = ecb_encrypt(key_wrong, sha256(c_seen_by_host, host_sig, secret_s) + s_c)
|
||||
# Right key, but H_s over a different host secret than the one the host reveals in step 3.
|
||||
resp2_wrong_hash = ecb_encrypt(key, sha256(c, host_sig, fixed("other-server-secret", 16)) + s_c)
|
||||
# Right key, but H_s over the rogue certificate's signature instead of the host's.
|
||||
resp2_wrong_cert = ecb_encrypt(key, sha256(c, cert_signature_value(rogue_der), secret_s) + s_c)
|
||||
# Step 3 signed by a key other than the host certificate's.
|
||||
resp3_rogue = secret_s + sign("test-only-rogue", secret_s)
|
||||
|
||||
sign_data = b"DomiStream test-only signing input"
|
||||
|
||||
entries = [
|
||||
("# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.", None),
|
||||
("host_cert_der", host_der),
|
||||
("host_cert_signature", host_sig),
|
||||
("client_cert_der", client_der),
|
||||
("client_key_pkcs8_der", key_pkcs8_der("test-only-client")),
|
||||
("client_cert_signature", client_sig),
|
||||
("rogue_cert_der", rogue_der),
|
||||
("rogue_key_pkcs8_der", key_pkcs8_der("test-only-rogue")),
|
||||
("# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)", None),
|
||||
("pin", pin.decode()),
|
||||
("wrong_pin", wrong_pin.decode()),
|
||||
("salt", salt),
|
||||
("client_challenge", c),
|
||||
("client_secret", secret_c),
|
||||
("# Host values", None),
|
||||
("server_challenge", s_c),
|
||||
("server_secret", secret_s),
|
||||
("# Derived, step by step", None),
|
||||
("key", key),
|
||||
("step2_clientchallenge", req2),
|
||||
("host_proof", h_s),
|
||||
("step2_challengeresponse", resp2),
|
||||
("client_proof", h_c),
|
||||
("step3_serverchallengeresp", req3),
|
||||
("server_secret_signature", secret_s_sig),
|
||||
("step3_pairingsecret", resp3),
|
||||
("client_secret_signature", secret_c_sig),
|
||||
("step4_clientpairingsecret", req4),
|
||||
("# Hostile host answers", None),
|
||||
("step2_challengeresponse_wrong_pin", resp2_wrong_pin),
|
||||
("step2_challengeresponse_wrong_hash", resp2_wrong_hash),
|
||||
("step2_challengeresponse_wrong_cert", resp2_wrong_cert),
|
||||
("step3_pairingsecret_rogue_signature", resp3_rogue),
|
||||
("# Session B: different randomness, for replaying session A's answers", None),
|
||||
("salt_b", salt_b),
|
||||
("client_challenge_b", c_b),
|
||||
("client_secret_b", secret_c_b),
|
||||
("# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)", None),
|
||||
("sign_data", sign_data),
|
||||
("sign_data_client_signature", sign("test-only-client", sign_data)),
|
||||
]
|
||||
|
||||
# derive_key over several salts and PINs.
|
||||
entries.append(("# derive_key: SHA-256(salt || pin)[0..16]", None))
|
||||
for i, p in enumerate([b"0000", b"9999", b"1234", b"4071"]):
|
||||
s = fixed(f"derive-salt-{i}", 16)
|
||||
entries += [(f"derive_{i}_salt", s), (f"derive_{i}_pin", p.decode()), (f"derive_{i}_key", sha256(s, p)[:16])]
|
||||
|
||||
# AES-128-ECB, no padding, 1 to 4 blocks.
|
||||
entries.append(("# ecb: AES-128-ECB without padding", None))
|
||||
for blocks in [1, 2, 3, 4]:
|
||||
k = fixed(f"ecb-key-{blocks}", 16)
|
||||
pt = fixed(f"ecb-plain-{blocks}", 16 * blocks)
|
||||
entries += [(f"ecb_{blocks}_key", k), (f"ecb_{blocks}_plain", pt), (f"ecb_{blocks}_cipher", ecb_encrypt(k, pt))]
|
||||
|
||||
# proof_hash with signatures of several lengths (RSA-1024 .. RSA-8192, plus 0 and 1 byte).
|
||||
entries.append(("# proof_hash: SHA-256(challenge || signature || secret)", None))
|
||||
for i, n in enumerate([0, 1, 128, 256, 512, 1024]):
|
||||
ch = fixed(f"proof-challenge-{i}", 16)
|
||||
sg = fixed(f"proof-signature-{i}", n)
|
||||
se = fixed(f"proof-secret-{i}", 16)
|
||||
entries += [(f"proof_{i}_challenge", ch), (f"proof_{i}_signature", sg if n else "-"),
|
||||
(f"proof_{i}_secret", se), (f"proof_{i}_hash", sha256(ch, sg, se))]
|
||||
|
||||
write_vectors("pairing.txt", "Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl", entries)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- control frames (PROTOCOL.md 3.2)
|
||||
|
||||
|
||||
def control_nonce(seq, direction):
|
||||
return seq.to_bytes(4, "little") + bytes(6) + direction + b"C"
|
||||
|
||||
|
||||
def control_vectors():
|
||||
key = fixed("control-rikey", 16)
|
||||
cases = [
|
||||
# (name, seq, direction byte, plaintext)
|
||||
("c_ping_0", 0, b"C", bytes.fromhex("00020000")),
|
||||
("c_input_1", 1, b"C", bytes.fromhex("06020c000000000807000000ffff0000")),
|
||||
("c_ping_ffff", 0xFFFF, b"C", bytes.fromhex("00020000")),
|
||||
("c_ping_10000", 0x10000, b"C", bytes.fromhex("00020000")),
|
||||
("c_ping_fffffffe", 0xFFFFFFFE, b"C", bytes.fromhex("00020000")),
|
||||
("c_ping_ffffffff", 0xFFFFFFFF, b"C", bytes.fromhex("00020000")),
|
||||
("h_rumble_0", 0, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
|
||||
("h_rumble_7", 7, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
|
||||
("h_termination_ffffffff", 0xFFFFFFFF, b"H", bytes.fromhex("0901040080030023")),
|
||||
("h_rgb_2a", 0x2A, b"H", bytes.fromhex("0255050003001020ff")),
|
||||
]
|
||||
out = gcm_batch([(n, key, control_nonce(s, d), pt) for n, s, d, pt in cases])
|
||||
entries = [("key", key)]
|
||||
for name, seq, direction, pt in cases:
|
||||
ct, tag = out[name]
|
||||
frame = (1).to_bytes(2, "little") + (4 + 16 + len(ct)).to_bytes(2, "little") + seq.to_bytes(4, "little")
|
||||
frame += tag + ct
|
||||
entries += [
|
||||
(f"# {name}", None),
|
||||
(f"{name}_sequence", f"{seq:08x}"),
|
||||
(f"{name}_direction", direction.decode()),
|
||||
(f"{name}_nonce", control_nonce(seq, direction)),
|
||||
(f"{name}_plain", pt),
|
||||
(f"{name}_frame", frame),
|
||||
]
|
||||
write_vectors("control_gcm.txt", "Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm", entries)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- video encryption (PROTOCOL.md 7)
|
||||
|
||||
|
||||
def video_vectors():
|
||||
key = fixed("video-rikey", 16)
|
||||
cases = []
|
||||
for name, counter, frame_number, n in [
|
||||
("v_0", 0, 0, 48),
|
||||
("v_1", 1, 0, 48),
|
||||
("v_big_counter", 0x0102030405060708, 0x11223344, 64),
|
||||
("v_1040", 7, 3, 1040),
|
||||
]:
|
||||
pt = fixed(f"video-plain-{name}", n)
|
||||
iv = counter.to_bytes(8, "little") + bytes(3) + b"V"
|
||||
cases.append((name, counter, frame_number, iv, pt))
|
||||
out = gcm_batch([(n, key, iv, pt) for n, _, _, iv, pt in cases])
|
||||
entries = [("key", key)]
|
||||
for name, counter, frame_number, iv, pt in cases:
|
||||
ct, tag = out[name]
|
||||
packet = iv + frame_number.to_bytes(4, "little") + tag + ct
|
||||
entries += [(f"# {name}", None), (f"{name}_plain", pt), (f"{name}_packet", packet)]
|
||||
write_vectors("video_gcm.txt", "Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm", entries)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- audio encryption (PROTOCOL.md 6.3)
|
||||
|
||||
|
||||
def audio_vectors():
|
||||
key = fixed("audio-rikey", 16)
|
||||
entries = [("key", key)]
|
||||
for name, rikeyid, seq, n in [
|
||||
("a_0", 0, 0, 20),
|
||||
("a_1", 0x01020304, 1, 20),
|
||||
("a_ffff", 0x00000010, 0xFFFF, 33),
|
||||
("a_wrap", 0xFFFFFFFE, 5, 16),
|
||||
("a_exact_block", 7, 100, 32),
|
||||
("a_one_byte", 7, 101, 1),
|
||||
]:
|
||||
iv = ((rikeyid + seq) & 0xFFFFFFFF).to_bytes(4, "big") + bytes(12)
|
||||
pt = fixed(f"audio-plain-{name}", n)
|
||||
entries += [
|
||||
(f"# {name}", None),
|
||||
(f"{name}_rikeyid", f"{rikeyid:08x}"),
|
||||
(f"{name}_sequence", f"{seq:04x}"),
|
||||
(f"{name}_iv", iv),
|
||||
(f"{name}_plain", pt),
|
||||
(f"{name}_cipher", cbc_encrypt(key, iv, pt)),
|
||||
]
|
||||
write_vectors("audio_cbc.txt", "Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl", entries)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
parser.add_argument("--fresh-keys", action="store_true", help="make new test-only keys and certificates")
|
||||
args = parser.parse_args()
|
||||
|
||||
print("openssl:", openssl("version").decode().strip())
|
||||
os.makedirs(FIXTURES, exist_ok=True)
|
||||
stems = ["test-only-host", "test-only-client", "test-only-rogue"]
|
||||
missing = any(not os.path.exists(os.path.join(FIXTURES, f"{s}-cert.pem")) for s in stems)
|
||||
if args.fresh_keys or missing:
|
||||
make_rsa_identity("test-only-host", "DomiStream test-only host")
|
||||
make_rsa_identity("test-only-client", "DomiStream test-only client")
|
||||
make_rsa_identity("test-only-rogue", "DomiStream test-only rogue")
|
||||
make_ec_cert("test-only-ec")
|
||||
print("made fresh test-only keys")
|
||||
|
||||
pairing_vectors()
|
||||
control_vectors()
|
||||
video_vectors()
|
||||
audio_vectors()
|
||||
shutil.rmtree(WORK, ignore_errors=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user