0.31.0: hardening and correctness pass across mux, codec, AACS/CSS, UDF/MPLS/CLPI, recovery, drive/SCSI, labels, and I/O

Library-wide review-and-fix pass: tightened AACS keydb/handshake/variant
handling and trailing-partial-unit policy, corrected MPLS mark offset and
added UDF allocation bounds, hardened the mux/codec framing and M2TS paths,
guarded SCSI READ CAPACITY short transfers and unified error mapping, added
overflow guards on untrusted disc input, and made prefetch shutdown
deterministic. Release profile now builds with thin LTO + single codegen unit.
This commit is contained in:
Matthew Jackson
2026-06-07 17:37:38 -07:00
parent 5b6ea8f5c4
commit 061f68594a
128 changed files with 11838 additions and 3831 deletions
+252 -10
View File
@@ -30,6 +30,7 @@ pub const E_IOKIT_PLUGIN_FAILED: u16 = 1006;
// Profile (2xxx)
pub const E_UNSUPPORTED_DRIVE: u16 = 2000;
// 2001: burned/retired — do not reuse.
pub const E_PROFILE_PARSE: u16 = 2002;
pub const E_UNSUPPORTED_PLATFORM: u16 = 2003;
pub const E_PLATFORM_NOT_IMPLEMENTED: u16 = 2004;
@@ -46,15 +47,18 @@ pub const E_IO_ERROR: u16 = 5000;
// Disc format (6xxx)
pub const E_DISC_READ: u16 = 6000;
pub const E_HALTED: u16 = 6010;
pub const E_MPLS_PARSE: u16 = 6001;
pub const E_CLPI_PARSE: u16 = 6002;
pub const E_UDF_NOT_FOUND: u16 = 6003;
// 6004: burned/retired — do not reuse.
pub const E_DISC_TITLE_RANGE: u16 = 6005;
// 6006: burned/retired — do not reuse.
pub const E_IFO_PARSE: u16 = 6007;
pub const E_MKV_INVALID: u16 = 6008;
pub const E_NO_STREAMS: u16 = 6009;
pub const E_HALTED: u16 = 6010;
pub const E_MAPFILE_INVALID: u16 = 6011;
pub const E_UDF_BUFFER_TOO_SMALL: u16 = 6012;
// AACS (7xxx)
pub const E_AACS_NO_KEYS: u16 = 7000;
@@ -69,6 +73,7 @@ pub const E_AACS_KEY_VERIFY: u16 = 7008;
pub const E_AACS_VID_READ: u16 = 7009;
pub const E_AACS_VID_MAC: u16 = 7010;
pub const E_AACS_DATA_KEY: u16 = 7011;
// 7012: burned/retired — do not reuse.
pub const E_DECRYPT_FAILED: u16 = 7013;
pub const E_CSS_AUTH_FAILED: u16 = 7014;
pub const E_AACS_HOST_CERT_REJECTED: u16 = 7015;
@@ -87,6 +92,8 @@ pub const E_KEYDB_INVALID: u16 = 8002;
pub const E_KEYDB_WRITE: u16 = 8003;
pub const E_KEYDB_PARSE: u16 = 8004;
pub const E_KEYDB_LOAD: u16 = 8005;
pub const E_KEYDB_UNSUPPORTED_SCHEME: u16 = 8006;
pub const E_KEYDB_TOO_MANY_REDIRECTS: u16 = 8007;
// Stream/mux (9xxx)
pub const E_STREAM_READ_ONLY: u16 = 9000;
@@ -99,11 +106,29 @@ pub const E_PES_INVALID_MAGIC: u16 = 9006;
pub const E_ISO_TOO_LARGE: u16 = 9007;
pub const E_NO_METADATA: u16 = 9008;
pub const E_DISC_URL_NOT_DIRECT: u16 = 9009;
pub const E_HEVC_PARAM_PARSE: u16 = 9010;
pub const E_MUX_TRACK_RANGE: u16 = 9011;
pub const E_FMP4_UNIMPLEMENTED: u16 = 9012;
pub const E_DEMUX_THREAD_PANICKED: u16 = 9013;
pub const E_PIPELINE_JOIN_TIMEOUT: u16 = 9014;
pub const E_PIPELINE_CONSUMER_PANICKED: u16 = 9015;
pub const E_SWEEP_CONSUMER_GONE: u16 = 9016;
pub const E_PES_TRACK_TOO_LARGE: u16 = 9017;
pub const E_PIPELINE_CONSUMER_GONE: u16 = 9018;
pub const E_DISC_CAPACITY_OVERFLOW: u16 = 9020;
pub const E_M2TS_PACKET_MALFORMED: u16 = 9021;
pub const E_EXTENT_NOT_UNIT_ALIGNED: u16 = 9030;
/// READ CAPACITY returned a short or overflowing transfer.
pub const E_DISC_CAPACITY_MALFORMED: u16 = 9047;
// ── Error enum ──────────────────────────────────────────────────────────────
/// Structured error with numeric code and context data. No English text.
///
/// Marked `#[non_exhaustive]`: downstream crates must not match it
/// exhaustively, so new variants can be added without a semver break.
#[derive(Debug)]
#[non_exhaustive]
pub enum Error {
// Device (1xxx)
DeviceNotFound {
@@ -201,6 +226,10 @@ pub enum Error {
UdfNotFound {
path: String,
},
/// A `SectorSource` caller passed a destination buffer smaller than one
/// 2048-byte sector. A contract violation on the public reader API —
/// returned instead of panicking on the slice.
UdfBufferTooSmall,
DiscTitleRange {
index: usize,
count: usize,
@@ -280,6 +309,14 @@ pub enum Error {
KeydbLoad {
path: String,
},
/// A redirect (or the configured URL) targets a scheme this
/// dependency-light HTTP client cannot fetch (e.g. `https://`).
/// Carries the offending scheme for diagnostics.
KeydbUnsupportedScheme {
scheme: String,
},
/// The redirect chain exceeded the follow limit.
KeydbTooManyRedirects,
// Stream/mux (9xxx)
StreamReadOnly,
@@ -297,6 +334,12 @@ pub enum Error {
size: usize,
},
PesInvalidMagic,
/// PES frame track index exceeds the 1-byte on-wire field (> 255).
/// Carries the offending index. Distinct from [`Error::PesInvalidMagic`],
/// which signals corrupt input on the read side.
PesTrackTooLarge {
track: usize,
},
IsoTooLarge {
path: String,
},
@@ -305,6 +348,65 @@ pub enum Error {
/// `Drive::open() + Disc::scan() + DiscStream::new()` directly. This
/// is a structural API constraint, not a parse failure.
DiscUrlNotDirect,
/// A non-empty `HEVCDecoderConfigurationRecord` (hvcC) was supplied to
/// a muxer but failed to parse into any VPS/SPS/PPS NAL — emitting the
/// stream without parameter sets would yield an undecodable result.
HevcParamParse,
/// A muxer `write_frame` / `set_codec_private` was given a track index
/// beyond the configured PID/track count.
MuxTrackRange {
track: usize,
tracks: usize,
},
/// The fragmented-MP4 sink cannot emit media — `moof`/`mdat` framing is
/// not implemented. Surfaced instead of silently discarding samples.
Fmp4Unimplemented,
/// A worker thread in the threaded mux pipeline terminated without
/// sending its terminal sentinel — i.e. it panicked or was dropped
/// mid-stream. Surfaced so a parser/demux panic is never silently
/// reported to the caller as a clean end-of-stream (which would
/// truncate output without any error).
DemuxThreadPanicked,
/// A pipeline `join()` exceeded its deadline while waiting for the
/// consumer thread to drain. The consumer is intentionally leaked;
/// the caller should fall back to a degraded path.
PipelineJoinTimeout,
/// The pipeline consumer thread panicked. The original panic
/// payload is not preserved (no English text in the library); it is
/// logged at the panic site instead.
PipelineConsumerPanicked,
/// A pipeline producer's `send` failed because the consumer thread
/// has already terminated (the receiver end is gone).
SweepConsumerGone,
/// A producer thread tried to hand work to its pipeline consumer
/// (sweep / patch sink) but the consumer thread had already
/// terminated (panicked or dropped the receiver). The producer
/// surfaces this so the outer pass can abort cleanly instead of
/// blocking on a dead channel.
PipelineConsumerGone,
/// READ CAPACITY(10) reported a last-LBA of `0xFFFFFFFF` — the SPC
/// sentinel meaning "capacity exceeds 32-bit addressing". Adding 1 to
/// derive the sector count would overflow `u32`. Reachable from
/// disc-reported bytes and synthetic [`crate::sector::SectorSource`]
/// fixtures.
DiscCapacityOverflow,
/// An extent fed to the prefetch producer has a `sector_count`
/// whose trailing 1-2 sectors cannot form a complete AACS aligned
/// unit (3 sectors / 6144 bytes). Emitting that tail as a
/// standalone batch would hand the decrypt step a sub-unit chunk
/// it silently leaves encrypted. The producer surfaces this rather
/// than emit still-encrypted bytes.
ExtentNotUnitAligned,
/// An MPEG-TS packet under construction violated the 188-byte fixed
/// size (over-long adaptation field, overflowing payload, or a
/// short/mis-assembled packet). Indicates a muxer invariant break,
/// not untrusted input — surfaced instead of writing a corrupt
/// transport stream.
M2tsPacketMalformed,
/// READ CAPACITY transferred fewer than 4 bytes, or the decoded
/// last-LBA + 1 overflowed `u32`. Either case means the capacity
/// response is unusable; no English commentary.
DiscCapacityMalformed,
}
impl Error {
@@ -330,6 +432,7 @@ impl Error {
Error::MplsParse => E_MPLS_PARSE,
Error::ClpiParse => E_CLPI_PARSE,
Error::UdfNotFound { .. } => E_UDF_NOT_FOUND,
Error::UdfBufferTooSmall => E_UDF_BUFFER_TOO_SMALL,
Error::DiscTitleRange { .. } => E_DISC_TITLE_RANGE,
Error::IfoParse => E_IFO_PARSE,
Error::MkvInvalid => E_MKV_INVALID,
@@ -363,6 +466,8 @@ impl Error {
Error::KeydbWrite { .. } => E_KEYDB_WRITE,
Error::KeydbParse => E_KEYDB_PARSE,
Error::KeydbLoad { .. } => E_KEYDB_LOAD,
Error::KeydbUnsupportedScheme { .. } => E_KEYDB_UNSUPPORTED_SCHEME,
Error::KeydbTooManyRedirects => E_KEYDB_TOO_MANY_REDIRECTS,
Error::StreamReadOnly => E_STREAM_READ_ONLY,
Error::StreamWriteOnly => E_STREAM_WRITE_ONLY,
Error::StreamUrlInvalid { .. } => E_STREAM_URL_INVALID,
@@ -370,9 +475,22 @@ impl Error {
Error::StreamUrlMissingPort { .. } => E_STREAM_URL_MISSING_PORT,
Error::PesFrameTooLarge { .. } => E_PES_FRAME_TOO_LARGE,
Error::PesInvalidMagic => E_PES_INVALID_MAGIC,
Error::PesTrackTooLarge { .. } => E_PES_TRACK_TOO_LARGE,
Error::IsoTooLarge { .. } => E_ISO_TOO_LARGE,
Error::NoMetadata => E_NO_METADATA,
Error::DiscUrlNotDirect => E_DISC_URL_NOT_DIRECT,
Error::HevcParamParse => E_HEVC_PARAM_PARSE,
Error::MuxTrackRange { .. } => E_MUX_TRACK_RANGE,
Error::Fmp4Unimplemented => E_FMP4_UNIMPLEMENTED,
Error::DemuxThreadPanicked => E_DEMUX_THREAD_PANICKED,
Error::PipelineJoinTimeout => E_PIPELINE_JOIN_TIMEOUT,
Error::PipelineConsumerPanicked => E_PIPELINE_CONSUMER_PANICKED,
Error::SweepConsumerGone => E_SWEEP_CONSUMER_GONE,
Error::PipelineConsumerGone => E_PIPELINE_CONSUMER_GONE,
Error::DiscCapacityOverflow => E_DISC_CAPACITY_OVERFLOW,
Error::ExtentNotUnitAligned => E_EXTENT_NOT_UNIT_ALIGNED,
Error::M2tsPacketMalformed => E_M2TS_PACKET_MALFORMED,
Error::DiscCapacityMalformed => E_DISC_CAPACITY_MALFORMED,
}
}
}
@@ -443,7 +561,13 @@ impl std::fmt::Display for Error {
),
None => write!(f, "E{}: 0x{:02x}/0x{:02x}", self.code(), opcode, status,),
},
Error::IoError { source } => write!(f, "E{}: {}", self.code(), source),
// Language-neutral: std::io::Error's Display is English
// ("permission denied"); emit the raw OS errno when present,
// else the ErrorKind debug name (an identifier, not prose).
Error::IoError { source } => match source.raw_os_error() {
Some(errno) => write!(f, "E{}: {}", self.code(), errno),
None => write!(f, "E{}: {:?}", self.code(), source.kind()),
},
Error::DiscRead {
sector,
status,
@@ -451,21 +575,23 @@ impl std::fmt::Display for Error {
} => match (status, sense) {
(Some(st), Some(s)) => write!(
f,
"E{}: {} 0x{:02x}/0x{:02x}/0x{:02x}",
"E{}: {} 0x{:02x}/0x{:02x}/0x{:02x}/0x{:02x}",
self.code(),
sector,
st,
s.sense_key,
s.asc,
s.ascq,
),
(Some(st), None) => write!(f, "E{}: {} 0x{:02x}", self.code(), sector, st,),
(None, Some(s)) => write!(
f,
"E{}: {} 0x{:02x}/0x{:02x}",
"E{}: {} 0x{:02x}/0x{:02x}/0x{:02x}",
self.code(),
sector,
s.sense_key,
s.asc,
s.ascq,
),
(None, None) => write!(f, "E{}: {}", self.code(), sector),
},
@@ -478,12 +604,25 @@ impl std::fmt::Display for Error {
Error::KeydbHttp { status } => write!(f, "E{}: {}", self.code(), status),
Error::KeydbWrite { path } => write!(f, "E{}: {}", self.code(), path),
Error::KeydbLoad { path } => write!(f, "E{}: {}", self.code(), path),
Error::KeydbUnsupportedScheme { scheme } => {
write!(f, "E{}: {}", self.code(), scheme)
}
Error::StreamUrlInvalid { url } => write!(f, "E{}: {}", self.code(), url),
Error::StreamUrlMissingPath { scheme } => write!(f, "E{}: {}", self.code(), scheme),
Error::StreamUrlMissingPort { addr } => write!(f, "E{}: {}", self.code(), addr),
Error::PesFrameTooLarge { size } => write!(f, "E{}: {}", self.code(), size),
Error::PesTrackTooLarge { track } => write!(f, "E{}: {}", self.code(), track),
Error::IsoTooLarge { path } => write!(f, "E{}: {}", self.code(), path),
Error::NoDiscKey { disc_hash } => write!(f, "E{}: {}", self.code(), disc_hash),
Error::NoDiscKey { disc_hash } => {
if disc_hash.is_empty() {
write!(f, "E{}", self.code())
} else {
write!(f, "E{}: {}", self.code(), disc_hash)
}
}
Error::MuxTrackRange { track, tracks } => {
write!(f, "E{}: {}/{}", self.code(), track, tracks)
}
_ => write!(f, "E{}", self.code()),
}
}
@@ -506,10 +645,21 @@ impl From<std::io::Error> for Error {
impl From<Error> for std::io::Error {
fn from(e: Error) -> Self {
// An `Error::IoError` is just a wrapper around an underlying
// `io::Error` that entered via `From<io::Error> for Error`.
// Round-trip it back unchanged so the original `ErrorKind` and
// raw OS error code survive instead of being flattened to
// `Other` with a stringified message.
if let Error::IoError { source } = e {
return source;
}
let code = e.code();
let msg = e.to_string();
// Map our error categories to io::ErrorKind
let kind = match code {
// Device access-denied semantics map to PermissionDenied;
// the rest of the 1xxx block is "device absent" -> NotFound.
E_DEVICE_PERMISSION | E_DEVICE_LOCKED => std::io::ErrorKind::PermissionDenied,
1000..=1999 => std::io::ErrorKind::NotFound,
2000..=2999 => std::io::ErrorKind::Unsupported,
3000..=3999 => std::io::ErrorKind::PermissionDenied,
@@ -523,6 +673,28 @@ impl From<Error> for std::io::Error {
// 9009 DiscUrlNotDirect: structurally unsupported entry point,
// not a parse failure — caller used the wrong API.
9009 => std::io::ErrorKind::Unsupported,
// 9010 HevcParamParse: malformed hvcC payload.
9010 => std::io::ErrorKind::InvalidData,
// 9011 MuxTrackRange: caller passed a bad track index.
9011 => std::io::ErrorKind::InvalidInput,
// 9012 Fmp4Unimplemented: sink can't emit media yet.
9012 => std::io::ErrorKind::Unsupported,
// 9014 PipelineJoinTimeout: consumer drain exceeded deadline.
E_PIPELINE_JOIN_TIMEOUT => std::io::ErrorKind::TimedOut,
// 9017 PesTrackTooLarge: out-of-range track index on serialize.
9017 => std::io::ErrorKind::InvalidInput,
// 9020 DiscCapacityOverflow: disc reported a capacity sentinel
// we can't represent — treat as bad/invalid device data.
9020 => std::io::ErrorKind::InvalidData,
// 9021 M2tsPacketMalformed: a muxer invariant break produced
// a non-188-byte packet — treat as invalid data.
9021 => std::io::ErrorKind::InvalidData,
// 9030 ExtentNotUnitAligned: a malformed/non-AACS-aligned
// extent was handed to the prefetch producer.
9030 => std::io::ErrorKind::InvalidInput,
// 9047 DiscCapacityMalformed: the drive returned an unusable
// READ CAPACITY response (short transfer / overflow).
9047 => std::io::ErrorKind::InvalidData,
_ => std::io::ErrorKind::Other,
};
std::io::Error::new(kind, msg)
@@ -590,6 +762,8 @@ impl Error {
///
/// - MEDIUM ERROR (sense key 3) — canonical bad-sector signal
/// - ABORTED COMMAND (sense key B) — transient; retry usually works
/// - NOT READY (sense key 2) — the dominant bad-sector response on
/// the BU40N (ASC 0x04/ASCQ 0x3E); a pause + retry often recovers
/// - RECOVERED ERROR (sense key 1) / NO SENSE (sense key 0) — not
/// classified as fatal; treat as recoverable
///
@@ -636,6 +810,9 @@ mod tests {
.code(),
Error::MapfileInvalid { kind: "hex" }.code(),
Error::DiscUrlNotDirect.code(),
Error::ExtentNotUnitAligned.code(),
Error::M2tsPacketMalformed.code(),
Error::DiscCapacityMalformed.code(),
];
let mut sorted = codes.to_vec();
sorted.sort();
@@ -680,6 +857,7 @@ mod tests {
),
(Error::MapfileInvalid { kind: "hex" }, E_MAPFILE_INVALID),
(Error::DiscUrlNotDirect, E_DISC_URL_NOT_DIRECT),
(Error::ExtentNotUnitAligned, E_EXTENT_NOT_UNIT_ALIGNED),
];
for (e, want_code) in cases {
let s = e.to_string();
@@ -695,9 +873,7 @@ mod tests {
// not).
for word in s.split(|c: char| !c.is_ascii_alphabetic()) {
assert!(
word.len() <= 8
|| word.eq_ignore_ascii_case("renesas")
|| word.eq_ignore_ascii_case("freebsd"),
word.len() <= 8,
"Display contains suspicious English-looking word `{word}` in `{s}`"
);
}
@@ -711,17 +887,26 @@ mod tests {
let io: std::io::Error = e.into();
io.kind()
};
// 1xxx range → NotFound
// 1xxx "device absent" → NotFound
assert_eq!(
mapped(Error::ScsiInterfaceUnavailable { path: "p".into() }),
ErrorKind::NotFound
);
assert_eq!(
mapped(Error::DeviceNotFound { path: "p".into() }),
ErrorKind::NotFound
);
// 1xxx access-denied semantics → PermissionDenied (not NotFound)
assert_eq!(
mapped(Error::DevicePermission { path: "p".into() }),
ErrorKind::PermissionDenied
);
assert_eq!(
mapped(Error::DeviceLocked {
path: "p".into(),
kr: 0
}),
ErrorKind::NotFound
ErrorKind::PermissionDenied
);
// 2xxx range → Unsupported
assert_eq!(
@@ -741,5 +926,62 @@ mod tests {
);
// 9009 special-cased to Unsupported
assert_eq!(mapped(Error::DiscUrlNotDirect), ErrorKind::Unsupported);
// 9021 special-cased to InvalidData
assert_eq!(mapped(Error::M2tsPacketMalformed), ErrorKind::InvalidData);
// 9047 DiscCapacityMalformed → InvalidData
assert_eq!(mapped(Error::DiscCapacityMalformed), ErrorKind::InvalidData);
}
/// `Error::IoError` must round-trip back to the *original*
/// `io::Error` — preserving its `ErrorKind` and raw OS error —
/// rather than being flattened to `Other` with a stringified
/// message.
#[test]
fn ioerror_roundtrips_preserving_kind_and_oscode() {
use std::io::ErrorKind;
let original = std::io::Error::from_raw_os_error(13); // EACCES
let original_kind = original.kind();
let wrapped: Error = original.into(); // From<io::Error> for Error
let back: std::io::Error = wrapped.into(); // From<Error> for io::Error
assert_eq!(back.kind(), original_kind);
assert_eq!(back.raw_os_error(), Some(13));
// A synthesized kind (no OS code) must also survive.
let timeout: Error = std::io::Error::from(ErrorKind::TimedOut).into();
let back2: std::io::Error = timeout.into();
assert_eq!(back2.kind(), ErrorKind::TimedOut);
}
/// `DiscRead` Display must include the ASCQ byte (the 5th field) so
/// NOT_READY substates (0x04/0x3E vs 0x04/0x01) are distinguishable
/// in logs and bug reports.
#[test]
fn discread_display_includes_ascq() {
let e = Error::DiscRead {
sector: 42,
status: Some(0x02),
sense: Some(crate::scsi::ScsiSense {
sense_key: 0x02,
asc: 0x04,
ascq: 0x3e,
}),
};
let s = e.to_string();
// sense_key/asc/ascq triple all present.
assert!(s.contains("0x02/0x04/0x3e"), "ascq missing from `{s}`");
}
/// `NoDiscKey` with an empty hash must not emit a dangling
/// "colon space" suffix.
#[test]
fn nodisckey_empty_hash_has_no_trailing_colon() {
let e = Error::NoDiscKey {
disc_hash: String::new(),
};
assert_eq!(e.to_string(), format!("E{}", E_NO_DISC_KEY));
let e2 = Error::NoDiscKey {
disc_hash: "abc".into(),
};
assert_eq!(e2.to_string(), format!("E{}: abc", E_NO_DISC_KEY));
}
}