Make five tests capable of failing, and stop the presence probe unmounting the disc
The worst of the five was a regression suite that never touched the code it guarded: nine batch-count tests called `safe_batch_count` and `buggy_batch_count`, both defined in the test file itself. The u16 truncation they exist to prevent could be reintroduced in sector/prefetched.rs with every one of them green. They now drive the real producer through the public API, and reinstating the truncation fails five of the nine. Worth recording that the symptom has changed since the original fix: the unit-alignment clamp below floors a zero batch at three sectors, so the bug is now a twenty-fold throughput cliff rather than the stall it once was. The MP4 reserve test's only numeric case was dominated by the floor and the buffer, so BYTES_PER_SAMPLE could be zeroed without failing it. It now has a case where the per-sample term dominates. The zero-count guard in FileSectorSource was likewise unfalsifiable — seek-past-EOF and a zero-length read both succeed — so the test now observes the file cursor. The AACS media-key ambiguity guard had no test at all; the pool scan is extracted so the verifier can be injected, because a genuine two-key collision needs one ciphertext decrypting under two AES-128 keys to plaintexts sharing a 64-bit magic, which is a 2^64 search and not a fixture. macOS implemented the documented cheap, side-effect-free presence probe by building a full exclusive transport — which force-unmounts the disc. Linux and Windows issue one TEST UNIT READY with no unmount; macOS was the outlier. It now walks the IOKit registry for the media object instead. The C shim's registry reads assumed CoreFoundation types the registry does not guarantee, so a driver publishing a CFNumber where a CFString was expected aborted the process from inside public API. Types are checked and a wrong type treated as absent. The unbounded waitpid on the unmount child is now a polled deadline, and the last-resort match gained the NULL check its two siblings already had. The empty-CDB guard existed only on Linux while a shared helper's comment claimed all three backends had it. Moved into the helper, so the comment is now true and macOS and Windows are covered. One finding was REJECTED with evidence rather than fixed. The TrueHD buffer-cap test was indeed bogus, but MAX_TRUEHD_BUF turns out to be unreachable by any input: the parser only retains data when the buffer is shorter than the declared AU, and that declaration is twelve bits, so the worst case is 8189 bytes against a 256 KiB cap. An exhaustive sweep over all 65536 AU headers confirmed it. The fixture now sits at the reachable ceiling and asserts that instead. The cap itself is left in place as defence, unreachable by construction, matching how the AC-3 resync guard was handled earlier in this audit. Two behaviour changes worth naming: Linux's empty-CDB error becomes InvalidCdbLength rather than a transport failure, and an unknown device now reports absent media rather than a not-found error, because the registry cannot tell an empty drive from a missing one. The latter is a conflation of the kind this audit has fixed three times; it is recorded for the next round rather than left silent.
This commit is contained in:
+8
-19
@@ -242,17 +242,14 @@ impl ScsiTransport for SgIoTransport {
|
||||
data: &mut [u8],
|
||||
timeout_ms: u32,
|
||||
) -> Result<ScsiResult> {
|
||||
// Guard the entry point: `ScsiTransport` is a pub trait, so an
|
||||
// external caller could pass an empty CDB. Indexing cdb[0] below
|
||||
// (and in the error paths) would panic. In-crate callers always
|
||||
// pass non-empty literal CDBs.
|
||||
if cdb.is_empty() {
|
||||
return Err(Error::ScsiError {
|
||||
opcode: 0,
|
||||
status: super::SCSI_STATUS_TRANSPORT_FAILURE,
|
||||
sense: None,
|
||||
});
|
||||
}
|
||||
// Validate the CDB length at the entry point, BEFORE `cdb[0]` below.
|
||||
// `ScsiTransport` is a pub trait, so an external caller could pass an
|
||||
// empty CDB and indexing it would panic; an over-length CDB must be
|
||||
// rejected rather than truncated (see `checked_cdb_len`). Both checks
|
||||
// live in the shared helper so they cannot drift per platform — this
|
||||
// backend used to carry its own bespoke empty-CDB guard, which macOS
|
||||
// and Windows never had.
|
||||
let cmd_len = super::checked_cdb_len(cdb, K_MAX_CDB_SIZE)?;
|
||||
let exec_t0 = std::time::Instant::now();
|
||||
let opcode = cdb[0];
|
||||
tracing::trace!(
|
||||
@@ -294,14 +291,6 @@ impl ScsiTransport for SgIoTransport {
|
||||
DataDirection::FromDevice => SG_DXFER_FROM_DEV,
|
||||
DataDirection::ToDevice => SG_DXFER_TO_DEV,
|
||||
};
|
||||
// Reject an over-length CDB rather than truncating it. This used to be
|
||||
// `cdb.len().min(16) as u8`, which silently dropped the tail: SPC-4
|
||||
// fixes a command's length by its opcode group code, so the shortened
|
||||
// CDB is a DIFFERENT command, which the drive executes and answers
|
||||
// with GOOD status and data for a request nobody made. Matches the
|
||||
// macOS and Windows backends (all three call the same helper).
|
||||
let cmd_len = super::checked_cdb_len(cdb, K_MAX_CDB_SIZE)?;
|
||||
|
||||
let mut sense = [0u8; 32];
|
||||
let mut hdr: sg_io_hdr = unsafe { std::mem::zeroed() };
|
||||
hdr.interface_id = b'S' as i32;
|
||||
|
||||
+101
-24
@@ -13,6 +13,9 @@
|
||||
//!
|
||||
//! Drive enumeration (`list_drives`) uses the IOKit registry directly via
|
||||
//! `shim_list_drives` — no exclusive access, no SCSI commands, no unmounts.
|
||||
//! The media-presence probe (`drive_has_disc`) does the same via
|
||||
//! `shim_media_present`: steps 1-5 above are the *transport* open path, and a
|
||||
//! probe documented as side-effect-free must not run any of them.
|
||||
|
||||
use super::{DataDirection, ScsiResult, ScsiTransport};
|
||||
use crate::error::{Error, Result};
|
||||
@@ -56,6 +59,21 @@ unsafe extern "C" {
|
||||
transfer_count: *mut u64,
|
||||
) -> i32;
|
||||
fn shim_list_drives(out: *mut ShimDriveInfo, max_entries: i32) -> i32;
|
||||
fn shim_media_present(bsd_name: *const u8) -> i32;
|
||||
}
|
||||
|
||||
/// Strip the `/dev/` (or raw-device `/dev/r`) prefix off a device path,
|
||||
/// yielding the BSD name the shim's IOKit lookups take. Shared by
|
||||
/// [`MacScsiTransport::open`] and [`drive_has_disc`] so the two cannot
|
||||
/// disagree about what device they are talking about.
|
||||
fn bsd_name_of(device: &Path) -> Result<&str> {
|
||||
let dev_str = device.to_str().ok_or_else(|| Error::DeviceNotFound {
|
||||
path: device.display().to_string(),
|
||||
})?;
|
||||
Ok(dev_str
|
||||
.strip_prefix("/dev/r")
|
||||
.or_else(|| dev_str.strip_prefix("/dev/"))
|
||||
.unwrap_or(dev_str))
|
||||
}
|
||||
|
||||
pub struct MacScsiTransport {
|
||||
@@ -66,17 +84,7 @@ unsafe impl Send for MacScsiTransport {}
|
||||
|
||||
impl MacScsiTransport {
|
||||
pub fn open(device: &Path) -> Result<Self> {
|
||||
let dev_str = device.to_str().ok_or_else(|| Error::DeviceNotFound {
|
||||
path: device.display().to_string(),
|
||||
})?;
|
||||
|
||||
let bsd_name = if let Some(rest) = dev_str.strip_prefix("/dev/r") {
|
||||
rest
|
||||
} else if let Some(rest) = dev_str.strip_prefix("/dev/") {
|
||||
rest
|
||||
} else {
|
||||
dev_str
|
||||
};
|
||||
let bsd_name = bsd_name_of(device)?;
|
||||
|
||||
// Enforce single-instance: the shim's global handle can't back two
|
||||
// live transports safely. Bail rather than corrupt shared state.
|
||||
@@ -256,26 +264,95 @@ fn cstr_to_str(bytes: &[u8]) -> &str {
|
||||
std::str::from_utf8(&bytes[..end]).unwrap_or("")
|
||||
}
|
||||
|
||||
/// Media-presence probe, via the IOKit registry only.
|
||||
///
|
||||
/// [`crate::scsi::drive_has_disc`] is documented as the cheap, side-effect-free
|
||||
/// "is there a disc?" question, suitable for a poll-loop tick. The Linux
|
||||
/// backend honours that: `open(O_RDWR|O_NONBLOCK)` + one TEST UNIT READY, no
|
||||
/// exclusive access, no unmount. The Windows backend likewise opens a shared
|
||||
/// handle and issues one TUR.
|
||||
///
|
||||
/// macOS could not: `MacScsiTransport::open` is the FULL exclusive-transport
|
||||
/// path, whose first act is `diskutil unmountDisk force` on the target device.
|
||||
/// So the probe documented as side-effect-free force-unmounted the user's disc
|
||||
/// — and on every poll tick, taking (and dropping) exclusive access each time.
|
||||
///
|
||||
/// The registry answers the same question with no side effect at all: the
|
||||
/// IOStorageFamily publishes an IOMedia object for a removable device only
|
||||
/// while media is present and removes it on eject, so a matching IOMedia is
|
||||
/// exactly "a disc is in the drive". No SCSI command is issued, which is why
|
||||
/// no timeout parameter is involved.
|
||||
///
|
||||
/// Trade-off, stated plainly: this reports what the OS has *enumerated*, so a
|
||||
/// disc that is inserted but still spinning up (no IOMedia published yet) reads
|
||||
/// as absent for the moment the enumeration takes — the same window in which a
|
||||
/// TUR would answer "not ready" and this function's contract already maps to
|
||||
/// `Ok(false)`.
|
||||
pub(super) fn drive_has_disc(path: &Path) -> Result<bool> {
|
||||
let mut transport = MacScsiTransport::open(path)?;
|
||||
let cdb = [crate::scsi::SCSI_TEST_UNIT_READY, 0, 0, 0, 0, 0];
|
||||
let mut buf = [0u8; 0];
|
||||
match transport.execute(
|
||||
&cdb,
|
||||
crate::scsi::DataDirection::None,
|
||||
&mut buf,
|
||||
crate::scsi::TUR_TIMEOUT_MS,
|
||||
) {
|
||||
Ok(_) => Ok(true),
|
||||
Err(ref e) if e.scsi_sense().is_some_and(|s| s.is_not_ready()) => Ok(false),
|
||||
Err(e) => Err(e),
|
||||
let bsd_name = bsd_name_of(path)?;
|
||||
let mut bsd_c = bsd_name.as_bytes().to_vec();
|
||||
bsd_c.push(0);
|
||||
match unsafe { shim_media_present(bsd_c.as_ptr()) } {
|
||||
1 => Ok(true),
|
||||
0 => Ok(false),
|
||||
// -1: IOKit itself is unavailable (IOMainPort / matching-dictionary
|
||||
// failure). That is not "no disc" — surface it rather than report a
|
||||
// false negative the caller would act on.
|
||||
_ => Err(Error::DeviceNotFound {
|
||||
path: bsd_name.to_string(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::K_MAX_CDB_SIZE;
|
||||
use super::{K_MAX_CDB_SIZE, OPEN, bsd_name_of, drive_has_disc};
|
||||
use crate::error::Error;
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
#[test]
|
||||
fn bsd_name_strips_dev_and_raw_dev_prefixes() {
|
||||
assert_eq!(bsd_name_of(Path::new("/dev/disk4")).unwrap(), "disk4");
|
||||
assert_eq!(bsd_name_of(Path::new("/dev/rdisk4")).unwrap(), "disk4");
|
||||
assert_eq!(bsd_name_of(Path::new("disk4")).unwrap(), "disk4");
|
||||
}
|
||||
|
||||
/// `drive_has_disc` is documented as a cheap, side-effect-free presence
|
||||
/// probe. It used to be implemented by constructing a FULL exclusive
|
||||
/// transport, whose first act is `diskutil unmountDisk force` on the target
|
||||
/// device followed by an unconditional `usleep(500000)` — so the probe
|
||||
/// force-unmounted the user's disc, on every poll tick.
|
||||
///
|
||||
/// Two observables separate the registry probe from the transport open,
|
||||
/// neither of which needs an optical drive to be attached:
|
||||
///
|
||||
/// 1. It ANSWERS. The transport path returned `Err(DeviceNotFound)` here;
|
||||
/// the registry path reports "no media" as `Ok(false)`.
|
||||
/// 2. It is FAST. The transport path's `usleep(500000)` after the spawn is
|
||||
/// unconditional, so it could not complete inside this budget even when
|
||||
/// the spawn itself failed.
|
||||
#[test]
|
||||
fn presence_probe_does_not_open_a_transport() {
|
||||
let path = Path::new("/dev/freemkv-no-such-device");
|
||||
let t0 = std::time::Instant::now();
|
||||
let r = drive_has_disc(path);
|
||||
let elapsed = t0.elapsed();
|
||||
|
||||
assert!(
|
||||
matches!(r, Ok(false)),
|
||||
"a device with no IOMedia must report absent media, got {r:?}"
|
||||
);
|
||||
assert!(
|
||||
elapsed < std::time::Duration::from_millis(250),
|
||||
"probe took {elapsed:?}: the transport path's unconditional 500 ms \
|
||||
post-unmount sleep means this budget can only be met without it"
|
||||
);
|
||||
assert!(
|
||||
!OPEN.load(Ordering::Acquire),
|
||||
"the probe must not leave the exclusive-transport lock held"
|
||||
);
|
||||
}
|
||||
|
||||
/// A CDB longer than K_MAX_CDB_SIZE must be rejected with
|
||||
/// `Error::InvalidCdbLength` before the shim is ever called. Exercises the
|
||||
|
||||
+117
-10
@@ -8,6 +8,7 @@
|
||||
#include <spawn.h>
|
||||
#include <sys/wait.h>
|
||||
#include <fcntl.h>
|
||||
#include <signal.h>
|
||||
|
||||
extern char **environ;
|
||||
|
||||
@@ -33,14 +34,27 @@ static ShimHandle g_handle = {NULL, NULL, NULL, 0};
|
||||
|
||||
// ── Registry helpers ──────────────────────────────────────────────────────
|
||||
|
||||
static int cfstring_to_cstr(CFStringRef cf, char *buf, size_t buflen) {
|
||||
// Convert a registry property to a C string.
|
||||
//
|
||||
// The value is taken as CFTypeRef, not CFStringRef, and its type is checked
|
||||
// before use. IORegistryEntryCreateCFProperty / CFDictionaryGetValue return
|
||||
// whatever the driver published: the IOKit registry contract (Apple, "Accessing
|
||||
// Hardware From Applications" — Device Access and the I/O Kit) fixes the
|
||||
// property KEYS, not the CoreFoundation type behind them, and a third-party
|
||||
// optical driver publishing a CFNumber or CFData for "BSD Name" or "Product
|
||||
// Revision Level" is legal. CFStringGetCString on a non-CFString aborts the
|
||||
// process (CFRuntime type assertion) — from inside the public
|
||||
// scsi::list_drives(), which is documented never to fail. Wrong type → treated
|
||||
// as absent.
|
||||
static int cfstring_to_cstr(CFTypeRef cf, char *buf, size_t buflen) {
|
||||
if (!cf) return 0;
|
||||
if (!CFStringGetCString(cf, buf, buflen, kCFStringEncodingUTF8)) return 0;
|
||||
if (CFGetTypeID(cf) != CFStringGetTypeID()) return 0;
|
||||
if (!CFStringGetCString((CFStringRef)cf, buf, buflen, kCFStringEncodingUTF8)) return 0;
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int registry_entry_bsd_name(io_registry_entry_t entry, char *buf, size_t buflen) {
|
||||
CFStringRef cf = IORegistryEntryCreateCFProperty(entry, CFSTR("BSD Name"),
|
||||
CFTypeRef cf = IORegistryEntryCreateCFProperty(entry, CFSTR("BSD Name"),
|
||||
kCFAllocatorDefault, 0);
|
||||
if (!cf) return 0;
|
||||
int ok = cfstring_to_cstr(cf, buf, buflen);
|
||||
@@ -119,19 +133,29 @@ static int bdsvc_to_bsd_name(io_registry_entry_t bdsvc, char *buf, size_t buflen
|
||||
|
||||
// Given an IOBDServices, extract Device Characteristics strings.
|
||||
static void bdsvc_device_info(io_registry_entry_t bdsvc, ShimDriveInfo *info) {
|
||||
CFDictionaryRef dc = IORegistryEntryCreateCFProperty(bdsvc,
|
||||
// "Device Characteristics" is declared a dictionary, but the value is
|
||||
// driver-published and the registry contract does not enforce the type.
|
||||
// CFDictionaryGetValue on a non-dictionary aborts the process, so the type
|
||||
// is checked before it is used as one. Each member string is type-checked
|
||||
// in turn by cfstring_to_cstr.
|
||||
CFTypeRef dc = IORegistryEntryCreateCFProperty(bdsvc,
|
||||
CFSTR("Device Characteristics"), kCFAllocatorDefault, 0);
|
||||
if (!dc) return;
|
||||
if (CFGetTypeID(dc) != CFDictionaryGetTypeID()) {
|
||||
CFRelease(dc);
|
||||
return;
|
||||
}
|
||||
CFDictionaryRef dict = (CFDictionaryRef)dc;
|
||||
|
||||
CFStringRef val;
|
||||
CFTypeRef val;
|
||||
|
||||
val = CFDictionaryGetValue(dc, CFSTR("Vendor Name"));
|
||||
val = CFDictionaryGetValue(dict, CFSTR("Vendor Name"));
|
||||
if (val) cfstring_to_cstr(val, info->vendor, sizeof(info->vendor));
|
||||
|
||||
val = CFDictionaryGetValue(dc, CFSTR("Product Name"));
|
||||
val = CFDictionaryGetValue(dict, CFSTR("Product Name"));
|
||||
if (val) cfstring_to_cstr(val, info->model, sizeof(info->model));
|
||||
|
||||
val = CFDictionaryGetValue(dc, CFSTR("Product Revision Level"));
|
||||
val = CFDictionaryGetValue(dict, CFSTR("Product Revision Level"));
|
||||
if (val) cfstring_to_cstr(val, info->firmware, sizeof(info->firmware));
|
||||
|
||||
CFRelease(dc);
|
||||
@@ -236,8 +260,41 @@ int shim_open_exclusive(const char *bsd_name) {
|
||||
};
|
||||
pid_t pid;
|
||||
if (posix_spawn(&pid, "/usr/sbin/diskutil", &fa, NULL, argv, environ) == 0) {
|
||||
// BOUNDED wait. A plain blocking waitpid() here hung the public
|
||||
// scsi::open() forever whenever the unmount wedged — diskutil
|
||||
// blocks indefinitely on a volume whose filesystem is stuck (a
|
||||
// hung network mount, a fs process not answering the unmount
|
||||
// notification), and there is no signal, timeout or cancellation
|
||||
// reaching this frame. Poll with WNOHANG to a deadline, then
|
||||
// SIGKILL and reap so no zombie is left behind.
|
||||
//
|
||||
// Continuing after a killed unmount is deliberate:
|
||||
// ObtainExclusiveAccess below is the real gate, and it reports the
|
||||
// still-mounted disc through the shim's -5 sentinel (mapped to
|
||||
// Error::DeviceLocked) — a typed error the caller can act on,
|
||||
// instead of a process that never returns.
|
||||
const int poll_us = 50000; // 50 ms
|
||||
const int max_polls = 400; // 400 x 50 ms = 20 s
|
||||
int status;
|
||||
waitpid(pid, &status, 0);
|
||||
int reaped = 0;
|
||||
for (int i = 0; i <= max_polls; i++) {
|
||||
pid_t r = waitpid(pid, &status, WNOHANG);
|
||||
if (r == pid) { reaped = 1; break; }
|
||||
// r < 0 means the child is already gone (ECHILD) — nothing to
|
||||
// wait for, and looping would spin to the deadline.
|
||||
if (r < 0) { reaped = 1; break; }
|
||||
if (i == max_polls) break;
|
||||
usleep(poll_us);
|
||||
}
|
||||
if (!reaped) {
|
||||
kill(pid, SIGKILL);
|
||||
// SIGKILL is uncatchable, so this reap converges; still poll
|
||||
// rather than block, so the shim has no unbounded wait at all.
|
||||
for (int i = 0; i < 100; i++) {
|
||||
if (waitpid(pid, &status, WNOHANG) != 0) break;
|
||||
usleep(10000); // 10 ms x 100 = 1 s
|
||||
}
|
||||
}
|
||||
}
|
||||
posix_spawn_file_actions_destroy(&fa);
|
||||
}
|
||||
@@ -254,8 +311,14 @@ int shim_open_exclusive(const char *bsd_name) {
|
||||
svc = find_bdsvc_from_iomedia(mp, bsd_name);
|
||||
}
|
||||
if (!svc) {
|
||||
// IOServiceMatching returns NULL on allocation failure. Both other call
|
||||
// sites in this file check it; this one did not, and
|
||||
// IOServiceGetMatchingService with a NULL matching dictionary is
|
||||
// undefined (it consumes the reference it is given).
|
||||
CFMutableDictionaryRef matching = IOServiceMatching("IOBDServices");
|
||||
svc = IOServiceGetMatchingService(mp, matching);
|
||||
if (matching) {
|
||||
svc = IOServiceGetMatchingService(mp, matching);
|
||||
}
|
||||
}
|
||||
if (!svc) return -1;
|
||||
|
||||
@@ -369,6 +432,50 @@ int shim_execute(const unsigned char *cdb, unsigned char cdb_len,
|
||||
return (int)kr;
|
||||
}
|
||||
|
||||
// ── Registry-based media-presence probe ───────────────────────────────────
|
||||
//
|
||||
// "Is a disc inserted?" answered from the IOKit registry alone: no exclusive
|
||||
// access, no unmount, no SCSI command, no state change of any kind.
|
||||
//
|
||||
// Apple's IOStorageFamily publishes an IOMedia object for a removable device
|
||||
// only while media is present, and tears it down on eject — that is the
|
||||
// documented media lifecycle (Apple, "Mass Storage Device Driver Programming
|
||||
// Guide": Media Objects / media arrival and removal). So the presence of an
|
||||
// IOMedia whose "BSD Name" is the requested device IS the presence of a disc.
|
||||
//
|
||||
// Returns 1 (media present), 0 (no media), or -1 (IOKit unavailable).
|
||||
int shim_media_present(const char *bsd_name) {
|
||||
mach_port_t mp;
|
||||
if (IOMainPort(0, &mp) != kIOReturnSuccess) return -1;
|
||||
|
||||
CFMutableDictionaryRef matching = IOServiceMatching("IOMedia");
|
||||
if (!matching) return -1;
|
||||
|
||||
io_iterator_t iter;
|
||||
// Consumes `matching` whether it succeeds or fails.
|
||||
if (IOServiceGetMatchingServices(mp, matching, &iter) != KERN_SUCCESS) return -1;
|
||||
|
||||
int found = 0;
|
||||
io_service_t media;
|
||||
while ((media = IOIteratorNext(iter)) != 0) {
|
||||
char name[64];
|
||||
if (registry_entry_bsd_name(media, name, sizeof(name))
|
||||
&& strcmp(name, bsd_name) == 0)
|
||||
{
|
||||
found = 1;
|
||||
}
|
||||
IOObjectRelease(media);
|
||||
if (found) break;
|
||||
}
|
||||
|
||||
// Drain the rest so no entry is leaked when we broke early.
|
||||
while ((media = IOIteratorNext(iter)) != 0) {
|
||||
IOObjectRelease(media);
|
||||
}
|
||||
IOObjectRelease(iter);
|
||||
return found;
|
||||
}
|
||||
|
||||
// ── Registry-based drive enumeration ──────────────────────────────────────
|
||||
//
|
||||
// Walks IOBDServices entries in the IOKit registry. No exclusive access,
|
||||
|
||||
+37
-4
@@ -41,6 +41,11 @@ pub const AACS_KEY_CLASS: u8 = 0x02;
|
||||
/// TUR is the cheapest SCSI op (no data transfer); 5 s is generous
|
||||
/// for any healthy bus and short enough that a hung device can't stall
|
||||
/// a poll-loop tick.
|
||||
///
|
||||
/// Used by the Linux and Windows backends. macOS answers the same question
|
||||
/// from the IOKit registry (no SCSI command is issued, so no timeout applies)
|
||||
/// — see `macos::drive_has_disc`.
|
||||
#[cfg_attr(target_os = "macos", allow(dead_code))]
|
||||
pub(crate) const TUR_TIMEOUT_MS: u32 = 5_000;
|
||||
|
||||
/// Timeout for content READ commands (READ_10 / READ_12) on the fast
|
||||
@@ -117,8 +122,14 @@ pub const SCSI_STATUS_TRANSPORT_FAILURE: u8 = 0xFF;
|
||||
/// Lives here, shared by all three platform backends, so the guard cannot
|
||||
/// drift per platform (it previously truncated on Linux and Windows while
|
||||
/// erroring on macOS — the "works on my platform, not theirs" class).
|
||||
/// An EMPTY CDB is rejected here too. `ScsiTransport` is a public trait, so an
|
||||
/// out-of-crate caller can pass one; every backend then either indexes `cdb[0]`
|
||||
/// (a panic out of a public API) or hands the driver a zero-length command
|
||||
/// descriptor, which under SPC-4 is not a command at all. That guard used to
|
||||
/// exist ONLY in the Linux backend — macOS and Windows had nothing — which is
|
||||
/// the same per-platform drift this helper exists to prevent.
|
||||
pub(crate) fn checked_cdb_len(cdb: &[u8], max: usize) -> Result<u8> {
|
||||
if cdb.len() > max {
|
||||
if cdb.is_empty() || cdb.len() > max {
|
||||
return Err(Error::InvalidCdbLength {
|
||||
len: cdb.len(),
|
||||
max,
|
||||
@@ -165,11 +176,10 @@ mod cdb_len_tests {
|
||||
}
|
||||
|
||||
/// Every real CDB length (SPC-4 groups 0-5: 6, 10, 12, 16 bytes) is
|
||||
/// accepted and reported verbatim, and an empty CDB reports 0 — the
|
||||
/// backends' own empty-CDB guards handle that case.
|
||||
/// accepted and reported verbatim.
|
||||
#[test]
|
||||
fn in_range_cdb_lengths_pass_through_verbatim() {
|
||||
for len in [0usize, 6, 10, 12, 16] {
|
||||
for len in [6usize, 10, 12, 16] {
|
||||
let cdb = vec![0u8; len];
|
||||
assert_eq!(
|
||||
checked_cdb_len(&cdb, MAX).ok(),
|
||||
@@ -178,6 +188,29 @@ mod cdb_len_tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// An EMPTY CDB must be rejected by the SHARED helper, not left to a
|
||||
/// per-backend guard. It previously reported `Ok(0)` and only the Linux
|
||||
/// backend caught it before `cdb[0]`; macOS and Windows passed a
|
||||
/// zero-length command descriptor straight to the driver.
|
||||
///
|
||||
/// This is the only place the property can be tested on every platform's
|
||||
/// CI — none of `linux.rs` / `macos.rs` / `windows.rs` compiles on more
|
||||
/// than one host.
|
||||
#[test]
|
||||
fn empty_cdb_is_rejected_by_the_shared_helper() {
|
||||
match checked_cdb_len(&[], MAX) {
|
||||
Err(Error::InvalidCdbLength { len, max }) => {
|
||||
assert_eq!(len, 0);
|
||||
assert_eq!(max, MAX);
|
||||
}
|
||||
Err(other) => panic!("expected InvalidCdbLength, got {other:?}"),
|
||||
Ok(n) => panic!(
|
||||
"empty CDB accepted with length {n} — every backend would then \
|
||||
index cdb[0] or issue a zero-length command descriptor"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── SPC-4 sense keys (§4.5.6 Table 28) ─────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user