[repo] Lab relay: record file format, loopback-only config, streaming rewriter, with unit tests (not yet compiled)

This commit is contained in:
2026-11-25 12:31:06 +01:00
parent 11c14b8cb6
commit 26ce712e82
4 changed files with 860 additions and 0 deletions
+21
View File
@@ -0,0 +1,21 @@
# lab-relay: our own logging relay for the one lab capture (docs/LAB_CAPTURE.md). A tool, never published, never part
# of the domistream crate. Its own workspace so it never joins the main build.
[package]
name = "lab-relay"
version = "0.1.0"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
publish = false
[workspace]
members = ["."]
[dependencies]
# TLS termination on the HTTPS port with lab-only keys. ring backend: pure Rust + asm, builds with MSVC.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pki-types = { version = "1", features = ["std"] }
ring = "0.17"
[lints.rust]
unsafe_code = "forbid"
+308
View File
@@ -0,0 +1,308 @@
//! Relay settings and the loopback-only rule.
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use crate::record::Protocol;
/// Where recordings go unless told otherwise.
pub const DEFAULT_CAPTURE_DIR: &str = r"F:\Akce\DomiStream-lab\captures";
/// Where lab keys live unless told otherwise.
pub const DEFAULT_KEY_DIR: &str = r"F:\Akce\DomiStream-lab\keys";
/// Transport of a relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport {
/// TCP, bytes copied (and rewritten host-to-client when the protocol is plaintext).
Tcp,
/// TCP with TLS terminated in the relay.
Tls,
/// UDP datagrams.
Udp,
}
/// One relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PortSpec {
/// Port the relay listens on.
pub listen_port: u16,
/// Port on the upstream (Sunshine) side.
pub upstream_port: u16,
/// Transport.
pub transport: Transport,
/// Protocol label for the records.
pub protocol: Protocol,
}
/// The GameStream default ports (PROTOCOL.md section 0, ArenaTV sunshine-api.md section 3).
pub const GAMESTREAM_PORTS: [(u16, Transport, Protocol); 7] = [
(47984, Transport::Tls, Protocol::HttpsPlain),
(47989, Transport::Tcp, Protocol::Http),
(48010, Transport::Tcp, Protocol::Rtsp),
(47998, Transport::Udp, Protocol::Video),
(47999, Transport::Udp, Protocol::Control),
(48000, Transport::Udp, Protocol::Audio),
(48002, Transport::Udp, Protocol::Mic),
];
/// TLS material, all lab-only PEM files.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsFiles {
/// Sunshine's lab certificate (presented to Moonlight, pinned towards Sunshine).
pub host_cert: PathBuf,
/// Sunshine's lab private key.
pub host_key: PathBuf,
/// Moonlight's lab client certificate (presented to Sunshine).
pub client_cert: PathBuf,
/// Moonlight's lab client key.
pub client_key: PathBuf,
}
impl TlsFiles {
/// The four default file names in `dir`.
pub fn in_dir(dir: &std::path::Path) -> Self {
Self {
host_cert: dir.join("sunshine-lab-cert.pem"),
host_key: dir.join("sunshine-lab-key.pem"),
client_cert: dir.join("moonlight-lab-cert.pem"),
client_key: dir.join("moonlight-lab-key.pem"),
}
}
}
/// An equal-length byte replacement applied to host-to-client plaintext.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rewrite {
/// Bytes to find.
pub from: Vec<u8>,
/// Bytes to put instead, same length.
pub to: Vec<u8>,
}
/// Everything the relay needs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
/// Address the relay listens on (Moonlight's "host"). Loopback only.
pub listen: IpAddr,
/// Address Sunshine listens on. Loopback only.
pub upstream: IpAddr,
/// Added to each default port on the upstream side (0, or 1000 in the fallback of LAB_CAPTURE.md section 4).
pub upstream_port_offset: u16,
/// Directory for the record file.
pub capture_dir: PathBuf,
/// TLS files; `None` = HTTPS passes through as raw TLS.
pub tls: Option<TlsFiles>,
/// How long an HTTPS connection waits for the TLS files to appear (Moonlight's key may appear only after
/// pairing step 1).
pub wait_for_keys: Duration,
/// Rewrites, applied in order of position in the stream.
pub rewrites: Vec<Rewrite>,
}
/// Why a configuration is refused.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigError {
/// An address that is not loopback.
NotLoopback(IpAddr),
/// Listen and upstream are the same address with no port offset: the relay would talk to itself.
SelfLoop,
/// A rewrite whose two sides differ in length, or are empty.
BadRewrite(String),
/// Ports overflow with the offset.
PortOverflow(u16),
/// A command-line argument that is not understood.
BadArgument(String),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotLoopback(ip) => write!(f, "{ip} is not a loopback address; the relay binds and connects only on loopback"),
Self::SelfLoop => f.write_str("listen and upstream are the same address and ports"),
Self::BadRewrite(s) => write!(f, "rewrite {s:?}: both sides must be non-empty and the same length"),
Self::PortOverflow(p) => write!(f, "port {p} plus the offset is over 65535"),
Self::BadArgument(s) => write!(f, "bad argument: {s}"),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
/// The lab defaults: Moonlight sees 127.0.0.1, Sunshine sits on 127.0.0.2, `127.0.0.2` is rewritten to
/// `127.0.0.1` in host-to-client plaintext, TLS files from [`DEFAULT_KEY_DIR`].
pub fn lab_default() -> Self {
Self {
listen: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
upstream: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)),
upstream_port_offset: 0,
capture_dir: PathBuf::from(DEFAULT_CAPTURE_DIR),
tls: Some(TlsFiles::in_dir(std::path::Path::new(DEFAULT_KEY_DIR))),
wait_for_keys: Duration::from_secs(60),
rewrites: vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }],
}
}
/// Checks the rules: loopback only, no self-loop, sane rewrites, ports in range.
///
/// # Errors
/// The first rule broken.
pub fn validate(&self) -> Result<(), ConfigError> {
for ip in [self.listen, self.upstream] {
if !ip.is_loopback() {
return Err(ConfigError::NotLoopback(ip));
}
}
if self.listen == self.upstream && self.upstream_port_offset == 0 {
return Err(ConfigError::SelfLoop);
}
for r in &self.rewrites {
if r.from.is_empty() || r.from.len() != r.to.len() {
return Err(ConfigError::BadRewrite(String::from_utf8_lossy(&r.from).into_owned()));
}
}
self.ports().map(|_| ())
}
/// The relayed ports with the upstream offset applied.
///
/// # Errors
/// [`ConfigError::PortOverflow`].
pub fn ports(&self) -> Result<Vec<PortSpec>, ConfigError> {
GAMESTREAM_PORTS
.iter()
.map(|&(port, transport, protocol)| {
let upstream_port = port.checked_add(self.upstream_port_offset).ok_or(ConfigError::PortOverflow(port))?;
let transport = if transport == Transport::Tls && self.tls.is_none() { Transport::Tcp } else { transport };
let protocol = if transport == Transport::Tcp && protocol == Protocol::HttpsPlain {
Protocol::HttpsTls
} else {
protocol
};
Ok(PortSpec { listen_port: port, upstream_port, transport, protocol })
})
.collect()
}
/// Socket address the relay listens on for `spec`.
pub fn listen_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.listen, spec.listen_port)
}
/// Upstream socket address for `spec`.
pub fn upstream_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.upstream, spec.upstream_port)
}
/// Applies command-line options to the lab defaults:
/// `--listen <ip>`, `--upstream <ip>`, `--upstream-port-offset <n>`, `--capture-dir <dir>`, `--key-dir <dir>`,
/// `--https-passthrough`, `--wait-for-keys-secs <n>`, `--rewrite <from>=<to>` (repeatable; the first one
/// replaces the default rewrite), `--no-rewrite`.
///
/// # Errors
/// [`ConfigError::BadArgument`] for an unknown option or value, then [`Config::validate`].
pub fn from_args(args: &[String]) -> Result<Self, ConfigError> {
let mut c = Self::lab_default();
let mut custom_rewrites = false;
let mut it = args.iter();
let bad = |s: &str| ConfigError::BadArgument(s.to_owned());
while let Some(a) = it.next() {
let mut value = || it.next().ok_or_else(|| bad(a));
match a.as_str() {
"--listen" => c.listen = value()?.parse().map_err(|_| bad(a))?,
"--upstream" => c.upstream = value()?.parse().map_err(|_| bad(a))?,
"--upstream-port-offset" => c.upstream_port_offset = value()?.parse().map_err(|_| bad(a))?,
"--capture-dir" => c.capture_dir = PathBuf::from(value()?),
"--key-dir" => {
let dir = PathBuf::from(value()?);
if c.tls.is_some() {
c.tls = Some(TlsFiles::in_dir(&dir));
}
}
"--https-passthrough" => c.tls = None,
"--wait-for-keys-secs" => {
c.wait_for_keys = Duration::from_secs(value()?.parse().map_err(|_| bad(a))?);
}
"--rewrite" => {
let v = value()?;
let (from, to) = v.split_once('=').ok_or_else(|| bad(v))?;
if !custom_rewrites {
c.rewrites.clear();
custom_rewrites = true;
}
c.rewrites.push(Rewrite { from: from.as_bytes().to_vec(), to: to.as_bytes().to_vec() });
}
"--no-rewrite" => {
c.rewrites.clear();
custom_rewrites = true;
}
other => return Err(bad(other)),
}
}
c.validate()?;
Ok(c)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_owned).collect()
}
#[test]
fn lab_default_is_valid() {
assert_eq!(Config::lab_default().validate(), Ok(()));
}
#[test]
fn non_loopback_listen_or_upstream_is_refused() {
for a in ["--listen 0.0.0.0", "--listen 192.168.100.140", "--upstream 192.168.100.217", "--listen ::", "--upstream 26.1.2.3"]
{
assert!(matches!(Config::from_args(&args(a)), Err(ConfigError::NotLoopback(_))), "{a}");
}
}
#[test]
fn other_loopback_addresses_are_accepted() {
let c = Config::from_args(&args("--listen 127.0.0.3 --upstream ::1")).unwrap();
assert!(c.listen.is_loopback() && c.upstream.is_loopback());
}
#[test]
fn self_loop_is_refused_unless_offset() {
assert_eq!(Config::from_args(&args("--upstream 127.0.0.1")), Err(ConfigError::SelfLoop));
let c = Config::from_args(&args("--upstream 127.0.0.1 --upstream-port-offset 1000")).unwrap();
let ports = c.ports().unwrap();
assert!(ports.iter().all(|p| p.upstream_port == p.listen_port + 1000));
}
#[test]
fn rewrites_must_keep_length() {
assert!(matches!(Config::from_args(&args("--rewrite 48984=7984")), Err(ConfigError::BadRewrite(_))));
assert!(matches!(Config::from_args(&args("--rewrite =")), Err(ConfigError::BadRewrite(_))));
let c = Config::from_args(&args("--rewrite 48984=47984 --rewrite 49010=48010")).unwrap();
assert_eq!(c.rewrites.len(), 2, "custom rewrites replace the default one");
}
#[test]
fn port_overflow_is_refused() {
assert!(matches!(Config::from_args(&args("--upstream-port-offset 20000")), Err(ConfigError::PortOverflow(_))));
}
#[test]
fn passthrough_turns_tls_into_raw_tcp() {
let c = Config::from_args(&args("--https-passthrough")).unwrap();
let https = c.ports().unwrap().into_iter().find(|p| p.listen_port == 47984).unwrap();
assert_eq!((https.transport, https.protocol), (Transport::Tcp, Protocol::HttpsTls));
}
#[test]
fn unknown_arguments_are_refused() {
assert!(matches!(Config::from_args(&args("--bind 0.0.0.0")), Err(ConfigError::BadArgument(_))));
assert!(matches!(Config::from_args(&args("--listen")), Err(ConfigError::BadArgument(_))));
}
}
+387
View File
@@ -0,0 +1,387 @@
//! 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:expr),* $(,)? }) => {
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());
}
}
+144
View File
@@ -0,0 +1,144 @@
//! Equal-length byte replacement over a stream, safe across read boundaries.
//!
//! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or
//! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP
//! `Content-Length` stays right.
use crate::config::Rewrite;
/// A streaming rewriter.
#[derive(Debug)]
pub struct Rewriter {
rules: Vec<Rewrite>,
held: Vec<u8>,
}
impl Rewriter {
/// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config).
pub fn new(rules: Vec<Rewrite>) -> Self {
Self { rules, held: Vec::new() }
}
/// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made.
pub fn push(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
if self.rules.is_empty() {
return (chunk.to_vec(), 0);
}
let mut data = std::mem::take(&mut self.held);
data.extend_from_slice(chunk);
let mut out = Vec::with_capacity(data.len());
let mut count = 0;
let mut i = 0;
'scan: while i < data.len() {
for r in &self.rules {
if data[i..].starts_with(&r.from) {
out.extend_from_slice(&r.to);
i += r.from.len();
count += 1;
continue 'scan;
}
}
// Could `data[i..]` be the beginning of a pattern that the next chunk completes?
let rest = &data[i..];
if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) {
self.held = rest.to_vec();
return (out, count);
}
out.push(data[i]);
i += 1;
}
(out, count)
}
/// Releases held bytes (end of stream, or a pause in it).
pub fn flush(&mut self) -> Vec<u8> {
std::mem::take(&mut self.held)
}
/// Bytes currently held back.
pub fn held(&self) -> usize {
self.held.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lab() -> Rewriter {
Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }])
}
fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec<u8>, usize) {
let mut out = Vec::new();
let mut n = 0;
for c in chunks {
let (o, k) = r.push(c);
out.extend(o);
n += k;
}
out.extend(r.flush());
(out, n)
}
const ANSWER: &[u8] = b"<root status_code=\"200\"><sessionUrl0>rtsp://127.0.0.2:48010</sessionUrl0></root>";
#[test]
fn replaces_in_one_chunk() {
let (out, n) = run(&mut lab(), &[ANSWER]);
assert_eq!(n, 1);
assert_eq!(out, ANSWER.to_vec().iter().copied().collect::<Vec<_>>().replace_all_for_test());
}
#[test]
fn replaces_across_every_split_point() {
let want = ANSWER.to_vec().replace_all_for_test();
for cut in 0..=ANSWER.len() {
let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]);
assert_eq!(n, 1, "cut {cut}");
assert_eq!(out, want, "cut {cut}");
}
}
#[test]
fn byte_by_byte_works() {
let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect();
let (out, n) = run(&mut lab(), &chunks);
assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1));
}
#[test]
fn length_never_changes_and_lookalikes_survive() {
let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3";
let (out, n) = run(&mut lab(), &[input]);
assert_eq!(out.len(), input.len());
assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3");
assert_eq!(n, 3);
}
#[test]
fn holds_only_a_possible_prefix() {
let mut r = lab();
let (out, _) = r.push(b"abc127.0.");
assert_eq!(out, b"abc");
assert_eq!(r.held(), 6);
let (out, n) = r.push(b"x");
assert_eq!((out, n), (b"127.0.x".to_vec(), 0));
assert_eq!(r.held(), 0);
}
#[test]
fn no_rules_is_a_pass_through() {
let mut r = Rewriter::new(Vec::new());
assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0));
}
trait ReplaceAll {
fn replace_all_for_test(self) -> Vec<u8>;
}
impl ReplaceAll for Vec<u8> {
fn replace_all_for_test(self) -> Vec<u8> {
String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes()
}
}
}