Round 5: reject a degenerate fixed lace, bound the pending buffer by bytes

Five fixes. Three are real defects with regression tests; two are bounds
that were expressible but not expressed.

A fixed-size lace (RFC 9559 §10.3.4) whose body is empty declared n
frames and carried none. The divisibility check passed, because 0 % n is
0, and `chunks` yields nothing on an empty slice whatever width it is
given — so the clamp that existed to avoid chunks(0) returned zero frames
where the Lacing Head said n. The whole lace vanished with no error
raised and the caller saw a clean short block. A zero-size frame cannot
be a valid frame, so it is now malformed.

A disc read failure while fetching a directory entry's ICB became a file
size of zero rather than an error. Zero is indistinguishable from a
genuinely empty file, so an unreadable ICB on a damaged disc silently
changed which titles a caller saw as present — read_directory already
fails hard on its entry-budget guard, so propagating is also what the
surrounding code does. read_file_size still returns Ok(0) for an ICB
whose tag is neither File Entry nor Extended File Entry, which is a real
zero and not a failure.

The pending-frame buffer was capped at 4096 frames, which does not bound
memory: frames are arbitrarily large and a UHD video frame runs to a few
hundred KB, so the existing cap permitted over a gigabyte. Now bounded by
bytes as well, at 64 MiB.

round_up_grain overflowed for inputs within one grain of u64::MAX —
div_ceil then multiply — and the wrapped product is small, turning the
largest possible estimate into a negligible reserve. It saturates, and
the reserve is clamped to what a `free` box's 32-bit size field can
actually hold, since writing a larger one truncated the size and left
mdat beyond a box claiming to be far shorter. No real title comes close;
a 90 GB UHD title estimates a few MiB.

The AC-3 resync guard now advances the PTS cadence like both of its
sibling branches, so the three paths out of that block cannot disagree.
This one is defensive and has NO test: reaching it needs input that both
parses frames and leaves a megabyte of residue, and the parser's own
carry rules drop pre-sync junk and cap a partial frame at 8192 bytes, so
no such input was found. Stated here rather than covered by a test that
would pass either way.

Two findings from this round were rejected on inspection. A reported
panic in the .mpls suffix check does not exist: the `.get(..)` on the
line above returns None off a char boundary and `filter` never runs its
closure, so the byte index is unreachable. A test written for it passed
against the unfixed code, which is what surfaced the error.
This commit is contained in:
Matthew Jackson
2026-07-29 22:28:43 -07:00
parent f5e169efb3
commit 5c6a6d0785
4 changed files with 165 additions and 8 deletions
+52 -4
View File
@@ -98,6 +98,11 @@ struct ReadState {
/// stream — past it we build with no measured field order (logged) rather than
/// buffer unbounded.
const MAX_PENDING_FRAMES: usize = 4096;
/// Companion byte cap on the same pending buffer. The frame count alone does not
/// bound memory: frames are arbitrarily large, and a UHD video frame runs to a
/// few hundred KB, so 4096 of them is over a gigabyte. 64 MiB is far more than
/// the handful of frames a real audio-only prefix produces, and finite.
const MAX_PENDING_BYTES: usize = 64 << 20;
enum Mode {
Write(WriteMode),
@@ -140,6 +145,10 @@ struct PendingMux {
/// carries an optional MVC dependent-view `BlockAdditional` (present only
/// for a 3D base-view frame that was already paired before activation).
buffered: Vec<(crate::pes::PesFrame, Option<Vec<u8>>)>,
/// Running payload total of `buffered`, so the cap can bound bytes and not
/// only frame count. Maintained on push; `buffered` is drained exactly once,
/// at activation, after which neither field is consulted again.
buffered_bytes: usize,
}
/// Matroska container stream.
@@ -439,6 +448,7 @@ impl MkvStream {
video_track,
opening_capture_path: output_path.map(|p| p.to_path_buf()),
buffered: Vec::new(),
buffered_bytes: 0,
}))),
})
}
@@ -535,7 +545,9 @@ impl MkvStream {
// No video track: nothing to wait for — build on frame one.
None => true,
};
(is_video || p.buffered.len() >= MAX_PENDING_FRAMES, is_video)
let capped =
p.buffered.len() >= MAX_PENDING_FRAMES || p.buffered_bytes >= MAX_PENDING_BYTES;
(is_video || capped, is_video)
}
_ => unreachable!("guarded above"),
};
@@ -550,8 +562,11 @@ impl MkvStream {
Ok(())
} else {
if let Mode::Write(WriteMode::Pending(p)) = &mut self.mode {
p.buffered
.push((frame.clone(), additional.map(|a| a.to_vec())));
let add = additional.map(|a| a.to_vec());
p.buffered_bytes = p
.buffered_bytes
.saturating_add(frame.data.len() + add.as_ref().map_or(0, |a| a.len()));
p.buffered.push((frame.clone(), add));
}
Ok(())
}
@@ -1393,7 +1408,17 @@ fn split_lacing(lacing: u8, body: &[u8]) -> Option<Vec<&[u8]>> {
return None;
}
let each = rest.len() / n;
return Some(rest.chunks(each.max(1)).take(n).collect());
// A zero-size frame carries no data and cannot be a valid frame, so
// `each == 0` is malformed rather than "n empty frames". It has to be
// rejected explicitly: 0 % n == 0 passes the divisibility check above,
// and `chunks` on an empty slice yields nothing whatever its argument,
// so clamping the chunk width instead returned Some(vec![]) — zero
// frames where the Lacing Head declared n, dropping the whole lace
// silently with no error raised.
if each == 0 {
return None;
}
return Some(rest.chunks(each).take(n).collect());
}
LACING_XIPH => {
// §10.3.2: each size is a run of 0xFF octets (255 each) terminated
@@ -1610,6 +1635,29 @@ fn block_vint(d: &[u8]) -> (u64, usize) {
#[cfg(test)]
mod tests {
/// A fixed lace whose body is empty declares n frames and carries none. It is
/// malformed, and must be rejected rather than silently yielding zero frames:
/// 0 % n == 0 passes the divisibility check, and `chunks` on an empty slice
/// yields nothing whatever width it is given, so the whole lace vanished with
/// no error raised and the caller saw a clean short block.
#[test]
fn fixed_lacing_with_an_empty_body_is_malformed_not_zero_frames() {
// Lacing Head only: count_minus_one = 2, i.e. three frames declared,
// followed by no payload at all.
assert_eq!(super::split_lacing(super::LACING_FIXED, &[2u8]), None);
// Same shape for a single declared frame.
assert_eq!(super::split_lacing(super::LACING_FIXED, &[0u8]), None);
}
/// The non-degenerate fixed lace still splits evenly, so the guard above did
/// not tighten the valid case.
#[test]
fn fixed_lacing_splits_an_evenly_divisible_body() {
let laced = super::split_lacing(super::LACING_FIXED, &[2u8, 1, 2, 3, 4, 5, 6])
.expect("three 2-byte frames is a well-formed fixed lace");
assert_eq!(laced, vec![&[1u8, 2][..], &[3, 4][..], &[5, 6][..]]);
}
use super::*;
use crate::pes::Stream as _;
use std::io::Cursor;