Files
DomiStream/tools/lab-relay/src/record.rs
T

388 lines
13 KiB
Rust

//! The record file: everything the relay sees, framed so it can be read back exactly.
//!
//! ```text
//! file = header record*
//! header = "DSLR" version:u8(=1) reserved:[u8;3](=0) start_unix_micros:u64le
//! record = kind:u8 protocol:u8 direction:u8 reserved:u8(=0) connection:u32le time_micros:u64le len:u32le bytes[len]
//! ```
//!
//! `time_micros` counts from the start of the capture. A record never holds more than [`MAX_PAYLOAD`] bytes.
use std::fmt;
use std::io::{self, Read, Write};
/// File magic.
pub const MAGIC: [u8; 4] = *b"DSLR";
/// Format version.
pub const VERSION: u8 = 1;
/// Header length in bytes.
pub const HEADER_LEN: usize = 16;
/// Record header length in bytes.
pub const RECORD_HEADER_LEN: usize = 20;
/// Largest payload of one record (a UDP datagram is at most 64 KiB; TCP reads are split to fit).
pub const MAX_PAYLOAD: usize = 1 << 20;
/// What a record says.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
/// A connection or UDP flow opened.
Open,
/// Bytes seen.
Data,
/// A connection or flow closed.
Close,
/// A UTF-8 note from the relay (TLS details, rewrites, errors).
Note,
}
/// Which protocol the bytes belong to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Protocol {
/// Relay-level notes.
Meta,
/// HTTP, port 47989.
Http,
/// Raw TLS bytes on 47984 (when not terminated).
HttpsTls,
/// Decrypted HTTPS plaintext on 47984.
HttpsPlain,
/// RTSP, port 48010.
Rtsp,
/// Video RTP, port 47998.
Video,
/// Control ENet, port 47999.
Control,
/// Audio RTP, port 48000.
Audio,
/// Microphone, port 48002.
Mic,
}
/// Which way the bytes went.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
/// Not a transfer (notes, opens, closes).
None,
/// Moonlight to Sunshine.
ClientToHost,
/// Sunshine to Moonlight.
HostToClient,
}
macro_rules! codes {
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
impl $t {
/// Wire code.
pub const fn code(self) -> u8 {
match self { $(Self::$v => $c),* }
}
/// From a wire code.
pub const fn from_code(code: u8) -> Option<Self> {
match code { $($c => Some(Self::$v),)* _ => None }
}
}
};
}
codes!(Kind { Open = 1, Data = 2, Close = 3, Note = 4 });
codes!(Protocol {
Meta = 0, Http = 1, HttpsTls = 2, HttpsPlain = 3, Rtsp = 4, Video = 5, Control = 6, Audio = 7, Mic = 8,
});
codes!(Direction { None = 0, ClientToHost = 1, HostToClient = 2 });
/// The file header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
/// Wall-clock start of the capture, Unix microseconds.
pub start_unix_micros: u64,
}
/// One record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
/// What it is.
pub kind: Kind,
/// Protocol.
pub protocol: Protocol,
/// Direction.
pub direction: Direction,
/// Connection or flow id, unique per capture.
pub connection: u32,
/// Microseconds since the capture started.
pub time_micros: u64,
/// The bytes (UTF-8 text for notes).
pub payload: Vec<u8>,
}
/// Why a file could not be read.
#[derive(Debug)]
pub enum RecordError {
/// I/O failure.
Io(io::Error),
/// Not a record file, or another version.
BadHeader,
/// The file ends inside a record.
Truncated,
/// A field holds a value this version does not know.
BadField(&'static str, u64),
/// A payload over [`MAX_PAYLOAD`].
TooLarge(usize),
}
impl fmt::Display for RecordError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "i/o: {e}"),
Self::BadHeader => f.write_str("not a DSLR v1 file"),
Self::Truncated => f.write_str("file ends inside a record"),
Self::BadField(name, v) => write!(f, "bad {name}: {v}"),
Self::TooLarge(n) => write!(f, "payload of {n} bytes is over the limit"),
}
}
}
impl std::error::Error for RecordError {}
impl From<io::Error> for RecordError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
/// Writes the file header.
///
/// # Errors
/// I/O errors.
pub fn write_header(out: &mut impl Write, header: Header) -> io::Result<()> {
let mut buf = [0u8; HEADER_LEN];
buf[..4].copy_from_slice(&MAGIC);
buf[4] = VERSION;
buf[8..16].copy_from_slice(&header.start_unix_micros.to_le_bytes());
out.write_all(&buf)
}
/// Writes one record.
///
/// # Errors
/// [`io::ErrorKind::InvalidInput`] for a payload over [`MAX_PAYLOAD`]; I/O errors.
pub fn write_record(out: &mut impl Write, record: &Record) -> io::Result<()> {
let len = record.payload.len();
if len > MAX_PAYLOAD {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "record payload over MAX_PAYLOAD"));
}
let mut head = [0u8; RECORD_HEADER_LEN];
head[0] = record.kind.code();
head[1] = record.protocol.code();
head[2] = record.direction.code();
head[4..8].copy_from_slice(&record.connection.to_le_bytes());
head[8..16].copy_from_slice(&record.time_micros.to_le_bytes());
// `len <= MAX_PAYLOAD < u32::MAX`, checked above.
head[16..20].copy_from_slice(&(len as u32).to_le_bytes());
out.write_all(&head)?;
out.write_all(&record.payload)
}
/// Reads exactly `buf.len()` bytes; `Ok(false)` at a clean end before the first byte.
fn read_full(input: &mut impl Read, buf: &mut [u8]) -> Result<bool, RecordError> {
let mut filled = 0;
while filled < buf.len() {
match input.read(&mut buf[filled..]) {
Ok(0) if filled == 0 => return Ok(false),
Ok(0) => return Err(RecordError::Truncated),
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.into()),
}
}
Ok(true)
}
/// Reads and checks the file header.
///
/// # Errors
/// [`RecordError::BadHeader`] for a wrong magic, version or reserved bytes; [`RecordError::Truncated`].
pub fn read_header(input: &mut impl Read) -> Result<Header, RecordError> {
let mut buf = [0u8; HEADER_LEN];
if !read_full(input, &mut buf)? {
return Err(RecordError::Truncated);
}
if buf[..4] != MAGIC || buf[4] != VERSION || buf[5..8] != [0, 0, 0] {
return Err(RecordError::BadHeader);
}
let mut start = [0u8; 8];
start.copy_from_slice(&buf[8..16]);
Ok(Header { start_unix_micros: u64::from_le_bytes(start) })
}
/// Reads the next record; `Ok(None)` at the end of the file.
///
/// # Errors
/// [`RecordError::Truncated`] inside a record, [`RecordError::BadField`] for unknown codes or a non-zero reserved
/// byte, [`RecordError::TooLarge`] before allocating an oversized payload.
pub fn read_record(input: &mut impl Read) -> Result<Option<Record>, RecordError> {
let mut head = [0u8; RECORD_HEADER_LEN];
if !read_full(input, &mut head)? {
return Ok(None);
}
let kind = Kind::from_code(head[0]).ok_or(RecordError::BadField("kind", head[0].into()))?;
let protocol = Protocol::from_code(head[1]).ok_or(RecordError::BadField("protocol", head[1].into()))?;
let direction = Direction::from_code(head[2]).ok_or(RecordError::BadField("direction", head[2].into()))?;
if head[3] != 0 {
return Err(RecordError::BadField("reserved", head[3].into()));
}
let word = |r: std::ops::Range<usize>| {
let mut b = [0u8; 8];
b[..r.len()].copy_from_slice(&head[r]);
u64::from_le_bytes(b)
};
let connection = word(4..8) as u32;
let time_micros = word(8..16);
let len = word(16..20) as usize;
if len > MAX_PAYLOAD {
return Err(RecordError::TooLarge(len));
}
let mut payload = vec![0u8; len];
if len > 0 && !read_full(input, &mut payload)? {
return Err(RecordError::Truncated);
}
Ok(Some(Record { kind, protocol, direction, connection, time_micros, payload }))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(payload: &[u8]) -> Record {
Record {
kind: Kind::Data,
protocol: Protocol::Control,
direction: Direction::HostToClient,
connection: 0x0102_0304,
time_micros: 0x1122_3344_5566_7788,
payload: payload.to_vec(),
}
}
fn file(records: &[Record]) -> Vec<u8> {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 42 }).unwrap();
for r in records {
write_record(&mut out, r).unwrap();
}
out
}
#[test]
fn header_layout_is_fixed() {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 0x0807_0605_0403_0201 }).unwrap();
assert_eq!(out, b"DSLR\x01\0\0\0\x01\x02\x03\x04\x05\x06\x07\x08");
}
#[test]
fn record_layout_is_fixed() {
let mut out = Vec::new();
write_record(&mut out, &sample(b"ab")).unwrap();
let mut want = vec![2, 6, 2, 0, 4, 3, 2, 1, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 2, 0, 0, 0];
want.extend_from_slice(b"ab");
assert_eq!(out, want);
}
#[test]
fn round_trip_of_every_code() {
let mut records = Vec::new();
for k in 1..=4 {
for p in 0..=8 {
for d in 0..=2 {
records.push(Record {
kind: Kind::from_code(k).unwrap(),
protocol: Protocol::from_code(p).unwrap(),
direction: Direction::from_code(d).unwrap(),
connection: u32::from(k) * 100 + u32::from(p),
time_micros: u64::from(d),
payload: vec![k, p, d],
});
}
}
}
records.push(sample(&[]));
records.push(sample(&vec![0xAB; MAX_PAYLOAD]));
let bytes = file(&records);
let mut input = bytes.as_slice();
assert_eq!(read_header(&mut input).unwrap(), Header { start_unix_micros: 42 });
for want in &records {
assert_eq!(read_record(&mut input).unwrap().as_ref(), Some(want));
}
assert!(read_record(&mut input).unwrap().is_none());
}
#[test]
fn oversized_payload_is_refused_on_write() {
let err = write_record(&mut Vec::new(), &sample(&vec![0; MAX_PAYLOAD + 1])).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn oversized_length_is_refused_before_allocating() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"")).unwrap();
bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::TooLarge(_))));
}
#[test]
fn every_cut_inside_a_record_is_truncated() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"payload")).unwrap();
for cut in 1..bytes.len() {
let r = read_record(&mut &bytes[..cut]);
assert!(matches!(r, Err(RecordError::Truncated)), "cut at {cut}");
}
}
#[test]
fn unknown_codes_and_reserved_bytes_are_refused() {
for (offset, value) in [(0, 0u8), (0, 5), (1, 9), (2, 3), (3, 1)] {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"x")).unwrap();
bytes[offset] = value;
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::BadField(..))), "{offset}");
}
}
#[test]
fn bad_headers_are_refused() {
let good = file(&[]);
for (offset, value) in [(0, b'X'), (4, 2), (5, 1)] {
let mut bytes = good.clone();
bytes[offset] = value;
assert!(matches!(read_header(&mut bytes.as_slice()), Err(RecordError::BadHeader)));
}
assert!(matches!(read_header(&mut &good[..10]), Err(RecordError::Truncated)));
}
/// A reader that hands out one byte per call, like a slow pipe.
struct Trickle<'a>(&'a [u8]);
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.0.split_first(), buf.first_mut()) {
(Some((&b, rest)), Some(slot)) => {
*slot = b;
self.0 = rest;
Ok(1)
}
_ => Ok(0),
}
}
}
#[test]
fn short_reads_are_reassembled() {
let bytes = file(&[sample(b"one"), sample(b"two")]);
let mut input = Trickle(&bytes);
read_header(&mut input).unwrap();
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"one");
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"two");
assert!(read_record(&mut input).unwrap().is_none());
}
}