From da1f3afd525787f9774511a8e2cb8d005651e8fe Mon Sep 17 00:00:00 2001 From: mnovak Date: Wed, 25 Nov 2026 12:52:38 +0100 Subject: [PATCH] [domistream] Tests: rustfmt --- crates/domistream/tests/alloc_caps.rs | 136 +++++++++----- crates/domistream/tests/audio.rs | 46 ++++- crates/domistream/tests/common/mod.rs | 13 +- crates/domistream/tests/control.rs | 151 ++++++++++++--- crates/domistream/tests/enet.rs | 240 ++++++++++++++++++------ crates/domistream/tests/fec.rs | 69 ++++++- crates/domistream/tests/http.rs | 41 +++- crates/domistream/tests/hygiene.rs | 16 +- crates/domistream/tests/input.rs | 197 +++++++++++++++---- crates/domistream/tests/media.rs | 87 +++++++-- crates/domistream/tests/pairing.rs | 136 +++++++++++--- crates/domistream/tests/rtsp.rs | 92 +++++++-- crates/domistream/tests/video.rs | 70 +++++-- fuzz/fuzz_targets/audio_depacketizer.rs | 7 +- fuzz/fuzz_targets/video_packet.rs | 3 +- fuzz/fuzz_targets/xml.rs | 4 +- 16 files changed, 1015 insertions(+), 293 deletions(-) diff --git a/crates/domistream/tests/alloc_caps.rs b/crates/domistream/tests/alloc_caps.rs index 29e5c35..316c592 100644 --- a/crates/domistream/tests/alloc_caps.rs +++ b/crates/domistream/tests/alloc_caps.rs @@ -34,7 +34,12 @@ fn budget(input: usize) -> usize { 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())); + 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, fn(&[u8]))> { @@ -45,9 +50,13 @@ fn lying_inputs() -> Vec<(&'static str, Vec, fn(&[u8]))> { 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 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); @@ -99,9 +108,13 @@ fn lying_inputs() -> Vec<(&'static str, Vec, fn(&[u8]))> { })); // 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(( + "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"�".to_vec(), |b| { let _ = domistream::http::xml::parse(b); })); @@ -127,10 +140,23 @@ 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(); + 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]); + 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); } @@ -161,7 +187,13 @@ fn depacketizer_checks() { 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 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 { @@ -190,68 +222,74 @@ fn parsers_never_allocate_past_their_caps() { 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); - }), + let _ = domistream::http::xml::parse(b); + }), ("serverinfo", |b| { - let _ = domistream::http::parse_server_info(b); - }), + let _ = domistream::http::parse_server_info(b); + }), ("applist", |b| { - let _ = domistream::http::parse_app_list(b); - }), + let _ = domistream::http::parse_app_list(b); + }), ("launch", |b| { - let _ = domistream::http::parse_launch_response(b); - }), + let _ = domistream::http::parse_launch_response(b); + }), ("pair response", |b| { - let _ = domistream::pairing::parse_pair_response(b); - }), + let _ = domistream::pairing::parse_pair_response(b); + }), ("pem", |b| { - let _ = domistream::pairing::ServerCert::from_pem(b); - }), + let _ = domistream::pairing::ServerCert::from_pem(b); + }), ("der", |b| { - let _ = domistream::pairing::ServerCert::from_der(b); - }), + let _ = domistream::pairing::ServerCert::from_der(b); + }), ("rtsp response", |b| { - let _ = domistream::rtsp::parse_response(b); - }), + let _ = domistream::rtsp::parse_response(b); + }), ("rtsp request", |b| { - let _ = domistream::rtsp::parse_request(b); - }), + let _ = domistream::rtsp::parse_request(b); + }), ("sdp", |b| { - let _ = domistream::rtsp::sdp::parse_sdp(b); - }), + let _ = domistream::rtsp::sdp::parse_sdp(b); + }), ("enet", |b| { - let _ = domistream::enet::protocol::parse_datagram(b); - }), + let _ = domistream::enet::protocol::parse_datagram(b); + }), ("control frame", |b| { - let _ = domistream::control::parse_encrypted_frame(b); - }), + let _ = domistream::control::parse_encrypted_frame(b); + }), ("control message", |b| { - let _ = domistream::control::parse_host_message(b); - }), + let _ = domistream::control::parse_host_message(b); + }), ("input", |b| { - let _ = domistream::input::parse_input(b); - }), + let _ = domistream::input::parse_input(b); + }), ("rtp", |b| { - let _ = domistream::rtp::parse_rtp_header(b); - }), + let _ = domistream::rtp::parse_rtp_header(b); + }), ("video", |b| { - let _ = domistream::video::parse_video_packet(b); - }), + let _ = domistream::video::parse_video_packet(b); + }), ("audio", |b| { - let _ = domistream::audio::parse_audio_packet(b); - }), + let _ = domistream::audio::parse_audio_packet(b); + }), ("video decrypt", |b| { - let _ = domistream::video::VideoCipher::new([2; 16]).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); - }), + 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::(), 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()); + prop_assert!( + used <= budget(data.len()), + "{}: {} bytes at peak for {} input bytes", + what, + used, + data.len() + ); Ok(()) }) .unwrap_or_else(|e| panic!("{what}: {e}")); diff --git a/crates/domistream/tests/audio.rs b/crates/domistream/tests/audio.rs index bf54aa1..1547216 100644 --- a/crates/domistream/tests/audio.rs +++ b/crates/domistream/tests/audio.rs @@ -84,9 +84,11 @@ fn check(expect: &[AExpect], want: &[Want], r: &Run) { let mut prev: Option = 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"))) - } + 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"); @@ -120,7 +122,14 @@ fn block_want(arrived: &[bool; 6], fec: bool) -> [Want; 4] { } /// 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, Vec, Vec>) { +fn scenario( + h: &AudioHost, + seed: u64, + first_seq: u16, + blocks: usize, + fec: bool, + lose: impl Fn(usize, usize) -> bool, +) -> (Vec, Vec, Vec>) { let mut rng = SeqRng::new(seed); let (packets, expect) = h.blocks(&mut rng, first_seq, 0x7000_0000, blocks); let mut want = Vec::new(); @@ -248,7 +257,9 @@ fn far_past_and_far_future() { 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")); + 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; @@ -322,11 +333,18 @@ fn undecryptable_data_is_dropped_and_rebuilt() { #[test] fn config_refusals() { - assert_err!(AudioDepacketizer::new(AudioConfig { packet_duration_ms: 0, ..config(true, AudioFec::Disabled) }), Error::Malformed { .. }); + 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_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()); } @@ -334,9 +352,19 @@ fn config_refusals() { #[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; 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]] { + 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); diff --git a/crates/domistream/tests/common/mod.rs b/crates/domistream/tests/common/mod.rs index 8799434..1fc3d07 100644 --- a/crates/domistream/tests/common/mod.rs +++ b/crates/domistream/tests/common/mod.rs @@ -388,11 +388,7 @@ pub mod gf { 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() - }) + .map(|r| (0..len).map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x]))).collect()) .collect() } } @@ -559,8 +555,7 @@ impl VideoHost { 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); + 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 } @@ -603,9 +598,7 @@ pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: iv[..8].copy_from_slice(&counter.to_le_bytes()); iv[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 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()); diff --git a/crates/domistream/tests/control.rs b/crates/domistream/tests/control.rs index 03b3038..775d9fc 100644 --- a/crates/domistream/tests/control.rs +++ b/crates/domistream/tests/control.rs @@ -10,9 +10,7 @@ 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::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, @@ -62,7 +60,10 @@ 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']); + 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:?}"); @@ -170,10 +171,20 @@ fn frame_parser_hostile_sizes() { 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_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); + 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); @@ -185,7 +196,13 @@ 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")] { + 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}"); @@ -225,7 +242,11 @@ fn message_split() { 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); + assert_too_large!( + parse_message(&msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 3])), + MAX_MESSAGE_BYTES, + MAX_MESSAGE_BYTES + 1 + ); } #[test] @@ -260,11 +281,26 @@ fn message_type_codes() { 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(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 }), @@ -296,11 +332,33 @@ fn host_messages_from_the_field_tables() { #[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 (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(&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]); @@ -318,9 +376,13 @@ fn client_messages() { 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()); + 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] { + for m in [ClientMessage::StartA, ClientMessage::StartB, ClientMessage::PeriodicPing, ClientMessage::RequestIdrFrame] + { assert_err!(encode_client_message(&m), Error::Unsupported { .. }, "{m:?}"); } } @@ -357,7 +419,13 @@ 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) }, + 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), } @@ -374,9 +442,20 @@ struct Host { impl Host { fn deliver(&mut self, frame: Vec) { self.reliable = self.reliable.wrapping_add(1); - let c = Command { acknowledge: true, channel_id: 0, reliable_sequence: self.reliable, body: CommandBody::SendReliable(frame) }; + 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(); + 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"); } @@ -410,7 +489,8 @@ impl Host { } fn connected_stream() -> Host { - let mut stream = ControlStream::connect(stream_config(), Instant::ZERO, &mut SeqRng::new(11)).expect("ControlStream::connect"); + 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 @@ -426,19 +506,36 @@ fn connected_stream() -> Host { 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) }, + 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) }; + 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, HostMessage) { - (msg(0x010b, &[0, 0, 0, 0, controller as u8, 0, 1, 0, 2, 0]), HostMessage::Rumble { controller, low_frequency: 1, high_frequency: 2 }) + ( + msg(0x010b, &[0, 0, 0, 0, controller as u8, 0, 1, 0, 2, 0]), + HostMessage::Rumble { controller, low_frequency: 1, high_frequency: 2 }, + ) } #[test] diff --git a/crates/domistream/tests/enet.rs b/crates/domistream/tests/enet.rs index 7863a08..2a9bc8b 100644 --- a/crates/domistream/tests/enet.rs +++ b/crates/domistream/tests/enet.rs @@ -13,9 +13,7 @@ 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::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE}; use domistream::{Error, Instant}; use proptest::prelude::*; @@ -29,7 +27,12 @@ fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandB 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)] }; + 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); } @@ -73,7 +76,14 @@ fn params(connect_id: u32) -> ConnectParams { } fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec) -> Fragment { - Fragment { start_sequence: start, fragment_count: count, fragment_number: number, total_length: total, fragment_offset: offset, data } + 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. @@ -107,7 +117,12 @@ fn every_command_round_trips_with_its_wire_size() { 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() }; + 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); } @@ -130,7 +145,12 @@ fn kind(b: &CommandBody) -> u8 { #[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 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"); } @@ -153,7 +173,13 @@ fn hostile_truncation() { 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(); + 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}"); } @@ -162,12 +188,23 @@ fn hostile_truncation() { #[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"); + 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}"); + 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 { .. }); + assert_err!( + parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]), + Error::UnexpectedValue { .. } + ); } #[test] @@ -202,42 +239,62 @@ fn hostile_sizes() { #[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] }; + 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]))] }; + 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 { let data = || proptest::collection::vec(any::(), 0..64); - let fragment = || (any::(), any::(), any::(), any::(), any::(), data()) - .prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f)); - let cparams = || proptest::array::uniform12(any::()).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], - }); + let fragment = || { + (any::(), any::(), any::(), any::(), any::(), data()) + .prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f)) + }; + let cparams = || { + proptest::array::uniform12(any::()).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::(), any::()).prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }), + (any::(), any::()) + .prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }), (cparams(), any::()).prop_map(|(params, data)| CommandBody::Connect { params, data }), cparams().prop_map(CommandBody::VerifyConnect), any::().prop_map(|data| CommandBody::Disconnect { data }), Just(CommandBody::Ping), data().prop_map(CommandBody::SendReliable), - (any::(), data()).prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }), + (any::(), data()) + .prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }), fragment().prop_map(CommandBody::SendFragment), - (any::(), data()).prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }), - (any::(), any::()).prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }), - (any::(), any::(), any::()).prop_map(|(interval, acceleration, deceleration)| CommandBody::ThrottleConfigure { interval, acceleration, deceleration }), + (any::(), data()) + .prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }), + (any::(), any::()) + .prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }), + (any::(), any::(), any::()).prop_map(|(interval, acceleration, deceleration)| { + CommandBody::ThrottleConfigure { interval, acceleration, deceleration } + }), fragment().prop_map(CommandBody::SendUnreliableFragment), ] } @@ -299,7 +356,13 @@ struct Link { impl Link { fn host_datagram(&self, commands: Vec) -> Vec { - encode_datagram(&Datagram { peer_id: self.to_client, session_id: 0, sent_time: Some(self.now_ms as u16), commands }).unwrap() + 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) -> domistream::Result<()> { @@ -350,7 +413,8 @@ 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 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!(), @@ -364,7 +428,15 @@ fn connected() -> Link { 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( + 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"); @@ -398,7 +470,11 @@ fn connect_refuses_configs_outside_enet_limits() { ] { 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() }] { + 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:?}"); } } @@ -407,7 +483,13 @@ fn connect_refuses_configs_outside_enet_limits() { 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 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()); @@ -420,7 +502,11 @@ fn garbage_never_changes_state() { 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_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()); } @@ -428,7 +514,13 @@ fn garbage_never_changes_state() { 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(); + 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()); } @@ -448,7 +540,12 @@ fn reliable_in_order_reordered_and_duplicated() { 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(); + 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})"); } @@ -508,7 +605,12 @@ fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec { 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))) + cmd( + true, + 0, + link.host_seq[0], + CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)), + ) }) .collect() } @@ -531,24 +633,30 @@ fn fragments_with_lying_lengths() { 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])))]); + 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 + 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() }))]); + 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:?}"); } @@ -609,20 +717,40 @@ 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 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"); + 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(); + 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"); + assert!( + !link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body), + "acknowledged command sent again" + ); } } diff --git a/crates/domistream/tests/fec.rs b/crates/domistream/tests/fec.rs index 39e80ee..4e9e992 100644 --- a/crates/domistream/tests/fec.rs +++ b/crates/domistream/tests/fec.rs @@ -33,15 +33,28 @@ fn erase(shards: &[Vec], lost: &[usize]) -> Vec>> { fn check_recovers(code: &ReedSolomon, full: &[Vec], 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())); + 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()); + 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], 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()); + 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> { @@ -52,7 +65,19 @@ fn subsets(n: usize, size: usize) -> Vec> { #[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)] { + 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 { .. }); @@ -81,7 +106,11 @@ fn explicit_matrix_is_used_exactly() { 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"); + 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::>()); } // A second MDS matrix (rows 1,1,1,1 and 1,2,4,8): every square submatrix is invertible. @@ -101,14 +130,34 @@ fn explicit_matrix_is_used_exactly() { 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, &[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(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 { .. }); } diff --git a/crates/domistream/tests/http.rs b/crates/domistream/tests/http.rs index 490dde0..dacd157 100644 --- a/crates/domistream/tests/http.rs +++ b/crates/domistream/tests/http.rs @@ -7,7 +7,9 @@ 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::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::*; @@ -92,7 +94,10 @@ fn xml_refuses_non_documents() { (br#"&#xZZ;"#, "bad hex reference"), (br#""#, "< in attribute value"), (br#""#, "DTD"), - (br#"]>&a;"#, "entity declaration"), + ( + br#"]>&a;"#, + "entity declaration", + ), (br#""#, "processing instruction in the body"), (br#" "#, "XML declaration not at the start"), (br#""#, "namespaces"), @@ -249,9 +254,8 @@ fn tree(depth: u32) -> impl Strategy { 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 }, - ) + ("[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 }) }) } @@ -457,9 +461,15 @@ fn applist_caps() { let app = |i: usize, title: &str| format!("{title}{i}"); 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); + 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); + 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::(); assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS); @@ -470,8 +480,16 @@ fn applist_caps() { let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}")); 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); + 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 @@ -605,7 +623,10 @@ fn launch_params() -> http::LaunchParams { 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 }, + 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, } diff --git a/crates/domistream/tests/hygiene.rs b/crates/domistream/tests/hygiene.rs index 642da98..1e2b82f 100644 --- a/crates/domistream/tests/hygiene.rs +++ b/crates/domistream/tests/hygiene.rs @@ -216,11 +216,17 @@ fn debug_never_prints_keys() { ("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), - })), + ( + "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}"); diff --git a/crates/domistream/tests/input.rs b/crates/domistream/tests/input.rs index 7dc29b2..4bbf2ef 100644 --- a/crates/domistream/tests/input.rs +++ b/crates/domistream/tests/input.rs @@ -93,7 +93,9 @@ fn builder_matches_the_protocol_md_examples() { 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") + 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" + ) ); } @@ -101,7 +103,9 @@ fn vectors() -> Vec<(InputEvent, Vec)> { let full = GamepadState { controller: 15, active_mask: 0x8001, - buttons: ButtonFlags(ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::HOME | ButtonFlags::PADDLE1 | ButtonFlags::MISC), + buttons: ButtonFlags( + ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::HOME | ButtonFlags::PADDLE1 | ButtonFlags::MISC, + ), left_trigger: 0x80, right_trigger: 0xFF, left_stick_x: i16::MIN, @@ -122,7 +126,10 @@ fn vectors() -> Vec<(InputEvent, Vec)> { (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::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)), @@ -149,11 +156,21 @@ fn vectors() -> Vec<(InputEvent, Vec)> { arrival(0, 0, 0x02, 0), ), ( - InputEvent::ControllerArrival { controller: 15, kind: ControllerKind::Nintendo, capabilities: ControllerCapabilities(0), supported_buttons: ButtonFlags(ButtonFlags::A) }, + 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) }, + InputEvent::ControllerArrival { + controller: 3, + kind: ControllerKind::Xbox, + capabilities: ControllerCapabilities(0x23), + supported_buttons: ButtonFlags(0xFFFF), + }, arrival(3, 1, 0x23, 0xFFFF), ), ] @@ -210,13 +227,28 @@ fn unknown_and_unsupported_types() { #[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 (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})"); + assert_err!( + parse_input(&input_message(code, &data)), + Error::Malformed { .. }, + "type {code:#x} with {wrong} bytes (wants {len})" + ); } } } @@ -225,15 +257,78 @@ fn wrong_data_lengths() { fn lying_length_and_size_fields() { let good = rel(5, 5); let cases: Vec<(Vec, &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"), + ( + { + 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 { @@ -246,7 +341,11 @@ 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"); + 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]); @@ -276,39 +375,61 @@ fn bad_field_values() { 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) }, + 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 { - 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::(), any::(), any::(), any::(), 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], - }); + 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::(), any::(), any::(), any::(), 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::(), any::()).prop_map(|(dx, dy)| InputEvent::MouseMoveRel { dx, dy }), - (any::(), any::(), any::(), any::()).prop_map(|(x, y, width, height)| InputEvent::MouseMoveAbs { x, y, width, height }), + (any::(), any::(), any::(), any::()) + .prop_map(|(x, y, width, height)| InputEvent::MouseMoveAbs { x, y, width, height }), (any::(), button).prop_map(|(pressed, button)| InputEvent::MouseButton { pressed, button }), - (any::(), any::(), any::(), any::()).prop_map(|(pressed, flags, key_code, modifiers)| InputEvent::Key { pressed, flags, key_code, modifiers }), + (any::(), any::(), any::(), any::()) + .prop_map(|(pressed, flags, key_code, modifiers)| InputEvent::Key { pressed, flags, key_code, modifiers }), any::().prop_map(|amount| InputEvent::Scroll { amount }), any::().prop_map(|amount| InputEvent::HScroll { amount }), gamepad.prop_map(InputEvent::Gamepad), - (0u8..=15, kind, any::(), any::()).prop_map(|(controller, kind, c, b)| InputEvent::ControllerArrival { - controller, - kind, - capabilities: ControllerCapabilities(c), - supported_buttons: ButtonFlags(b), + (0u8..=15, kind, any::(), any::()).prop_map(|(controller, kind, c, b)| { + InputEvent::ControllerArrival { + controller, + kind, + capabilities: ControllerCapabilities(c), + supported_buttons: ButtonFlags(b), + } }), ] } diff --git a/crates/domistream/tests/media.rs b/crates/domistream/tests/media.rs index ee4fa1a..43fdd6c 100644 --- a/crates/domistream/tests/media.rs +++ b/crates/domistream/tests/media.rs @@ -78,7 +78,11 @@ fn video_packet_hostile_sizes() { 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(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); } @@ -95,7 +99,11 @@ fn video_packet_inconsistent_fec_fields() { ((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}"); + 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; @@ -107,8 +115,17 @@ 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!( + (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. @@ -157,7 +174,10 @@ fn audio_packets() { 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!( + (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:?}"), @@ -171,20 +191,33 @@ fn audio_packet_hostile() { 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(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] { + 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(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); } @@ -197,7 +230,11 @@ 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}"); + assert_eq!( + c.decrypt(&v.bytes(&format!("{name}_packet"))).unwrap(), + v.bytes(&format!("{name}_plain")), + "{name}" + ); } } @@ -205,8 +242,14 @@ fn video_decrypt_matches_dotnet_vectors() { 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}"); + 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}" + ); } } @@ -248,8 +291,16 @@ 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}"); + 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}" + ); } } @@ -259,7 +310,11 @@ fn audio_oracle_matches_openssl_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}"); + assert_eq!( + common::audio_encrypt(&v.arr16("key"), rikeyid, seq, &v.bytes(&format!("{name}_plain"))), + v.bytes(&format!("{name}_cipher")), + "{name}" + ); } } @@ -277,7 +332,9 @@ fn audio_decrypt_refuses() { let mut block = [0x41u8; 16]; block[16 - last.len()..].copy_from_slice(last); let mut buf = block; - cbc::Encryptor::::new((&v.arr16("key")).into(), &iv.into()).encrypt_padded::(&mut buf, 16).unwrap(); + cbc::Encryptor::::new((&v.arr16("key")).into(), &iv.into()) + .encrypt_padded::(&mut buf, 16) + .unwrap(); assert_err!(c.decrypt(seq, &buf), Error::Crypto, "padding ending {last:?}"); } } diff --git a/crates/domistream/tests/pairing.rs b/crates/domistream/tests/pairing.rs index 17e2936..64dbc66 100644 --- a/crates/domistream/tests/pairing.rs +++ b/crates/domistream/tests/pairing.rs @@ -115,7 +115,14 @@ fn hex_param(req: &HttpRequest, name: &str) -> Vec { } /// Feeds `body` and checks the session fails into `Failed(reason)`. -fn expect_failure(s: &mut PairingSession, id: &ClientIdentity, rng: &mut ScriptedRng, status: u16, body: &[u8], reason: PairingFailure) { +fn expect_failure( + s: &mut PairingSession, + id: &ClientIdentity, + rng: &mut ScriptedRng, + status: u16, + body: &[u8], + reason: PairingFailure, +) { let r = s.handle_response(id, status, body, rng); assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}"); assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}"); @@ -136,7 +143,11 @@ fn recorded_transcript_walks_every_state() { // Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout. assert_eq!(req1.scheme, Scheme::Http); - assert!(req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)), "step 1 timeout {:?}", req1.timeout); + assert!( + req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)), + "step 1 timeout {:?}", + req1.timeout + ); let (path, q) = parse_query(&req1.path_and_query); assert_eq!(path, "/pair"); assert_eq!(param(&q, "uniqueid"), UID); @@ -247,14 +258,8 @@ fn a_bare_paired_answer_cannot_skip_any_step() { #[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)> = vec![ - (0, resp2()), - (0, resp3()), - (1, resp1()), - (1, resp3()), - (2, resp1()), - (2, resp2()), - ]; + let cases: Vec<(usize, Vec)> = + 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); @@ -319,8 +324,14 @@ fn malformed_answers_at_every_step() { b"1".to_vec(), xml_root(200, ""), xml_root(200, "yes"), - xml_root(200, "1zzzzzz"), - xml_root(200, "1abcabcabc"), + xml_root( + 200, + "1zzzzzz", + ), + xml_root( + 200, + "1abcabcabc", + ), ]; for steps in 0..3 { for body in &bodies { @@ -334,8 +345,13 @@ fn malformed_answers_at_every_step() { 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(); + 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)); @@ -386,7 +402,14 @@ fn wrong_challenge_response_sizes() { ]; 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); + expect_failure( + &mut s, + &id, + &mut rng, + 200, + &answer(true, Some(("challengeresponse", &cr))), + PairingFailure::MalformedAnswer, + ); } } @@ -395,7 +418,12 @@ fn bad_host_signatures() { let v = v(); // 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); + 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)); @@ -416,7 +444,10 @@ fn bad_host_signatures() { 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_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) @@ -427,9 +458,18 @@ fn bad_host_signatures() { 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![]] { + 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); + expect_failure( + &mut s, + &id, + &mut rng, + 200, + &answer(true, Some(("pairingsecret", &ps))), + PairingFailure::MalformedAnswer, + ); } } @@ -449,7 +489,14 @@ fn bad_host_certificates() { 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); + expect_failure( + &mut s, + &id, + &mut rng, + 200, + &answer(true, Some(("plaincert", pem.as_bytes()))), + PairingFailure::MalformedAnswer, + ); } } @@ -529,9 +576,11 @@ fn proof_hash_vectors() { .unwrap(); assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}"); } - let h = crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret")); + let h = + crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret")); assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof")); - let h = crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret")); + let h = + crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret")); assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof")); assert_too_large!( crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]), @@ -646,11 +695,14 @@ fn server_cert_hostile_der() { (vec![0x30], "one byte"), (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"), + ( + { + 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}"); } @@ -666,7 +718,11 @@ fn client_identity_from_recorded_keys() { assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice()); assert_eq!(id.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("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")]); @@ -679,7 +735,11 @@ fn client_identity_refuses() { 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(&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 { .. }); @@ -715,7 +775,20 @@ fn client_identity_generate() { 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"] { + 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:?}"); } } @@ -751,7 +824,8 @@ fn pair_response_parser() { 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, "0aBcD")).unwrap(); + let r = + parse_pair_response(&xml_root(200, "0aBcD")).unwrap(); assert!(!r.paired); assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..])); let r = parse_pair_response(&xml_root(200, "100ff")).unwrap(); diff --git a/crates/domistream/tests/rtsp.rs b/crates/domistream/tests/rtsp.rs index 36e919a..0afb75c 100644 --- a/crates/domistream/tests/rtsp.rs +++ b/crates/domistream/tests/rtsp.rs @@ -106,7 +106,11 @@ fn response_lying_content_length() { // 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:?}"); + assert_err!( + parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")), + Error::Malformed { .. }, + "{cl:?}" + ); } // Two different lengths. assert_err!( @@ -125,7 +129,10 @@ fn response_lying_content_length() { fn response_header_flood() { let names: Vec = (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::>(); - assert_eq!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(), MAX_RTSP_HEADERS); + assert_eq!( + parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(), + MAX_RTSP_HEADERS + ); assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS); // A flood of empty-valued headers in under 64 KiB. let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect(); @@ -139,7 +146,10 @@ fn response_line_cap() { let value = |line: usize| "v".repeat(line - 3); let 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); + 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); } @@ -150,7 +160,11 @@ fn response_size_boundaries() { 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(&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); } @@ -183,7 +197,8 @@ fn request_parse_and_encode() { (Method::Announce, "ANNOUNCE"), (Method::Play, "PLAY"), ] { - let req = RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] }; + let req = + RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] }; assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes())); } } @@ -194,15 +209,26 @@ fn request_refuses_unknown_methods_and_bad_lines() { let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n"); assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}"); } - for bad in [&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"] { + for bad in + [&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"] + { assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad)); } - assert_too_large!(parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1); + assert_too_large!( + parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]), + MAX_RTSP_MESSAGE_BYTES, + MAX_RTSP_MESSAGE_BYTES + 1 + ); } #[test] fn encode_refuses_header_injection() { - let base = || RtspRequest { method: Method::Setup, target: "streamid=video/0/0".into(), headers: vec![("CSeq".into(), "4".into())], body: vec![] }; + let base = || RtspRequest { + method: Method::Setup, + target: "streamid=video/0/0".into(), + headers: vec![("CSeq".into(), "4".into())], + body: vec![], + }; let mut cases = Vec::new(); for evil in ["a\r\nX: y", "a\ny", "a\rb"] { cases.push(RtspRequest { target: evil.into(), ..base() }); @@ -220,7 +246,13 @@ fn encode_refuses_header_injection() { } fn method() -> impl Strategy { - prop_oneof![Just(Method::Options), Just(Method::Describe), Just(Method::Setup), Just(Method::Announce), Just(Method::Play)] + prop_oneof![ + Just(Method::Options), + Just(Method::Describe), + Just(Method::Setup), + Just(Method::Announce), + Just(Method::Play) + ] } proptest! { @@ -331,7 +363,11 @@ fn framer_cap_64k_plus_one() { // 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); + 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(); @@ -355,10 +391,17 @@ fn framer_refuses_lying_content_length_early() { 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); + 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}"); + assert_err!( + push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")), + Error::Malformed { .. }, + "{cl}" + ); } } @@ -509,7 +552,10 @@ fn host_capabilities() { let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1); 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); + assert_eq!( + HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(), + MAX_OPUS_CONFIGS + ); } fn config() -> StreamConfig { @@ -557,7 +603,10 @@ fn announce_refuses_what_the_host_lacks() { 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_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()); } @@ -572,7 +621,11 @@ fn describe_answer(cseq: u32, sdp: &str) -> Vec { fn setup_answer(cseq: u32, port: &str) -> Vec { response( "200 OK", - &[("CSeq", &cseq.to_string()), ("Session", "DEADBEEFCAFE;timeout = 90"), ("Transport", &format!("server_port={port}"))], + &[ + ("CSeq", &cseq.to_string()), + ("Session", "DEADBEEFCAFE;timeout = 90"), + ("Transport", &format!("server_port={port}")), + ], b"", ) } @@ -676,7 +729,10 @@ fn client_refuses_hostile_answers() { 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) }); + 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); @@ -712,7 +768,9 @@ fn client_answer_without_request() { #[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"] { + 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 [ diff --git a/crates/domistream/tests/video.rs b/crates/domistream/tests/video.rs index 61fea61..9610997 100644 --- a/crates/domistream/tests/video.rs +++ b/crates/domistream/tests/video.rs @@ -116,7 +116,13 @@ fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: 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!( + 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); @@ -143,7 +149,9 @@ fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: 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::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"), } } @@ -151,7 +159,12 @@ fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: /// 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, Vec, Vec, Vec>) { +fn scenario( + seed: u64, + n: usize, + percentages: &[u8], + keep: impl Fn(&mut SeqRng, usize, usize, &VPkt) -> bool, +) -> (Vec, Vec, Vec, Vec>) { let mut rng = SeqRng::new(seed); let mut host = VideoHost::new(PACKET_SIZE); let fs = frames(&mut rng, &mut host, 0, n, percentages); @@ -199,7 +212,15 @@ fn random_loss() { 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::()); + assert!( + r.stats.shards_recovered + >= rec + .iter() + .zip(&out) + .filter(|(_, o)| **o == Outcome::Deliver) + .map(|(r, _)| u64::from(*r)) + .sum::() + ); } } @@ -260,7 +281,8 @@ fn last_packet_lost() { 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(); + 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())); @@ -314,7 +336,11 @@ fn duplicated() { } 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); + assert!( + r.stats.packets_dropped >= dups / 2, + "duplicates are counted as dropped: {} of {dups}", + r.stats.packets_dropped + ); } } @@ -323,7 +349,10 @@ 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> = dg.iter().flat_map(|g| if rng.below(5) == 0 { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect(); + let mut mixed: Vec> = 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() { @@ -355,7 +384,9 @@ fn recovered_shard_headers_are_not_trusted() { 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))) + .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)); @@ -379,7 +410,8 @@ fn rtp_sequence_wraps_inside_frames() { 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(); + 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())); } @@ -396,7 +428,8 @@ fn frame_index_wraps() { 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() }; + 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())); } @@ -509,19 +542,30 @@ fn encrypted_stream_with_loss_and_tampering() { #[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}"); + 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_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; 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(())); diff --git a/fuzz/fuzz_targets/audio_depacketizer.rs b/fuzz/fuzz_targets/audio_depacketizer.rs index 5dde58e..795a0cb 100644 --- a/fuzz/fuzz_targets/audio_depacketizer.rs +++ b/fuzz/fuzz_targets/audio_depacketizer.rs @@ -17,7 +17,12 @@ use domistream::audio::{AudioConfig, AudioDepacketizer, AudioEvent, AudioFec}; 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 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; diff --git a/fuzz/fuzz_targets/video_packet.rs b/fuzz/fuzz_targets/video_packet.rs index 9864d88..8602887 100644 --- a/fuzz/fuzz_targets/video_packet.rs +++ b/fuzz/fuzz_targets/video_packet.rs @@ -14,7 +14,8 @@ fuzz_target!(|data: &[u8]| { 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"); + 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); } diff --git a/fuzz/fuzz_targets/xml.rs b/fuzz/fuzz_targets/xml.rs index c4d42ba..310a971 100644 --- a/fuzz/fuzz_targets/xml.rs +++ b/fuzz/fuzz_targets/xml.rs @@ -7,7 +7,9 @@ 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}; +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;