#[cfg(target_os = "linux")]
pub mod linux;
#[cfg(target_os = "macos")]
mod macos;
#[cfg(target_os = "windows")]
mod windows;
#[allow(unused_imports)]
use crate::error::{Error, Result};
use std::path::Path;
pub const SCSI_TEST_UNIT_READY: u8 = 0x00;
pub const SCSI_INQUIRY: u8 = 0x12;
pub const SCSI_READ_CAPACITY: u8 = 0x25;
pub const SCSI_READ_10: u8 = 0x28;
pub const SCSI_READ_BUFFER: u8 = 0x3C;
pub const SCSI_READ_TOC: u8 = 0x43;
pub const SCSI_GET_CONFIGURATION: u8 = 0x46;
pub const SCSI_SET_CD_SPEED: u8 = 0xBB;
pub const SCSI_SEND_KEY: u8 = 0xA3;
pub const SCSI_REPORT_KEY: u8 = 0xA4;
pub const SCSI_READ_12: u8 = 0xA8;
pub const SCSI_READ_DISC_STRUCTURE: u8 = 0xAD;
pub const AACS_KEY_CLASS: u8 = 0x02;
pub(crate) const TUR_TIMEOUT_MS: u32 = 5_000;
pub(crate) const READ_TIMEOUT_MS: u32 = 10_000;
pub(crate) const READ_RECOVERY_TIMEOUT_MS: u32 = 60_000;
pub const SCSI_STATUS_GOOD: u8 = 0x00;
pub const SCSI_STATUS_CHECK_CONDITION: u8 = 0x02;
pub const SCSI_STATUS_TRANSPORT_FAILURE: u8 = 0xFF;
pub const SENSE_KEY_NO_SENSE: u8 = 0x00;
pub const SENSE_KEY_RECOVERED_ERROR: u8 = 0x01;
pub const SENSE_KEY_NOT_READY: u8 = 0x02;
pub const SENSE_KEY_MEDIUM_ERROR: u8 = 0x03;
pub const SENSE_KEY_HARDWARE_ERROR: u8 = 0x04;
pub const SENSE_KEY_ILLEGAL_REQUEST: u8 = 0x05;
pub const SENSE_KEY_UNIT_ATTENTION: u8 = 0x06;
pub const SENSE_KEY_DATA_PROTECT: u8 = 0x07;
pub const SENSE_KEY_BLANK_CHECK: u8 = 0x08;
pub const SENSE_KEY_ABORTED_COMMAND: u8 = 0x0B;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ScsiSense {
pub sense_key: u8,
pub asc: u8,
pub ascq: u8,
}
impl ScsiSense {
pub const NONE: ScsiSense = ScsiSense {
sense_key: 0,
asc: 0,
ascq: 0,
};
pub fn is_marginal(&self) -> bool {
matches!(
self.sense_key,
SENSE_KEY_NO_SENSE
| SENSE_KEY_RECOVERED_ERROR
| SENSE_KEY_NOT_READY
| SENSE_KEY_MEDIUM_ERROR
| SENSE_KEY_ABORTED_COMMAND
)
}
pub fn is_medium_error(&self) -> bool {
self.sense_key == SENSE_KEY_MEDIUM_ERROR
}
pub fn is_hardware_error(&self) -> bool {
self.sense_key == SENSE_KEY_HARDWARE_ERROR
}
pub fn is_not_ready(&self) -> bool {
self.sense_key == SENSE_KEY_NOT_READY
}
pub fn is_unit_attention(&self) -> bool {
self.sense_key == SENSE_KEY_UNIT_ATTENTION
}
pub fn is_data_protect(&self) -> bool {
self.sense_key == SENSE_KEY_DATA_PROTECT
}
pub fn is_illegal_request(&self) -> bool {
self.sense_key == SENSE_KEY_ILLEGAL_REQUEST
}
pub fn is_aborted_command(&self) -> bool {
self.sense_key == SENSE_KEY_ABORTED_COMMAND
}
}
pub(crate) fn parse_sense(sense: &[u8], sb_len_wr: u8) -> ScsiSense {
let n = (sb_len_wr as usize).min(sense.len());
if n < 3 {
return ScsiSense::NONE;
}
let response_code = sense[0] & 0x7F;
let descriptor = response_code == 0x72 || response_code == 0x73;
if descriptor {
let asc = sense[2];
let ascq = if n >= 4 { sense[3] } else { 0 };
ScsiSense {
sense_key: sense[1] & 0x0F,
asc,
ascq,
}
} else {
let asc = if n >= 13 { sense[12] } else { 0 };
let ascq = if n >= 14 { sense[13] } else { 0 };
ScsiSense {
sense_key: sense[2] & 0x0F,
asc,
ascq,
}
}
}
#[cfg(target_os = "linux")]
pub(crate) const DRIVER_SENSE: u16 = 0x08;
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum DataDirection {
None,
FromDevice,
ToDevice,
}
#[derive(Debug)]
pub struct ScsiResult {
pub status: u8,
pub bytes_transferred: usize,
pub sense: [u8; 32],
}
pub trait ScsiTransport: Send {
fn execute(
&mut self,
cdb: &[u8],
direction: DataDirection,
data: &mut [u8],
timeout_ms: u32,
) -> Result<ScsiResult>;
}
pub fn open(device: &Path) -> Result<Box<dyn ScsiTransport>> {
#[cfg(target_os = "linux")]
{
Ok(Box::new(linux::SgIoTransport::open(device)?))
}
#[cfg(target_os = "macos")]
{
Ok(Box::new(macos::MacScsiTransport::open(device)?))
}
#[cfg(target_os = "windows")]
{
Ok(Box::new(windows::SptiTransport::open(device)?))
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
Err(Error::UnsupportedPlatform {
target: std::env::consts::OS.to_string(),
})
}
}
#[derive(Debug, Clone)]
pub struct DriveInfo {
pub path: String,
pub vendor: String,
pub model: String,
pub firmware: String,
}
pub fn list_drives() -> Vec<DriveInfo> {
#[cfg(target_os = "linux")]
{
linux::list_drives()
}
#[cfg(target_os = "macos")]
{
macos::list_drives()
}
#[cfg(target_os = "windows")]
{
windows::list_drives()
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
Vec::new()
}
}
pub fn drive_has_disc(path: &Path) -> Result<bool> {
#[cfg(target_os = "linux")]
{
linux::drive_has_disc(path)
}
#[cfg(target_os = "macos")]
{
macos::drive_has_disc(path)
}
#[cfg(target_os = "windows")]
{
windows::drive_has_disc(path)
}
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
{
let _ = path;
Err(Error::UnsupportedPlatform {
target: std::env::consts::OS.to_string(),
})
}
}
#[derive(Debug, Clone)]
pub struct InquiryResult {
pub vendor_id: String,
pub model: String,
pub firmware: String,
pub raw: Vec<u8>,
}
pub fn inquiry(scsi: &mut dyn ScsiTransport) -> Result<InquiryResult> {
let cdb = [SCSI_INQUIRY, 0x00, 0x00, 0x00, 0x60, 0x00];
let mut buf = [0u8; 96];
scsi.execute(&cdb, DataDirection::FromDevice, &mut buf, 5_000)?;
Ok(InquiryResult {
vendor_id: String::from_utf8_lossy(&buf[8..16]).trim().to_string(),
model: String::from_utf8_lossy(&buf[16..32]).trim().to_string(),
firmware: String::from_utf8_lossy(&buf[32..36]).trim().to_string(),
raw: buf.to_vec(),
})
}
pub fn get_config_010c(scsi: &mut dyn ScsiTransport) -> Result<Vec<u8>> {
let cdb = [
SCSI_GET_CONFIGURATION,
0x02,
0x01,
0x0C,
0x00,
0x00,
0x00,
0x00,
0x10,
0x00,
];
let mut buf = [0u8; 16];
scsi.execute(&cdb, DataDirection::FromDevice, &mut buf, 5_000)?;
Ok(buf.to_vec())
}
pub fn build_read_buffer(mode: u8, buffer_id: u8, offset: u32, length: u32) -> [u8; 10] {
[
SCSI_READ_BUFFER,
mode,
buffer_id,
(offset >> 16) as u8,
(offset >> 8) as u8,
offset as u8,
(length >> 16) as u8,
(length >> 8) as u8,
length as u8,
0x00,
]
}
pub fn build_set_cd_speed(read_speed: u16) -> [u8; 12] {
[
SCSI_SET_CD_SPEED,
0x00,
(read_speed >> 8) as u8,
read_speed as u8,
0xFF,
0xFF,
0x00,
0x00,
0x00,
0x00,
0x00,
0x00,
]
}
pub fn build_read10_fua(lba: u32, count: u16) -> [u8; 10] {
[
SCSI_READ_10,
0x08,
(lba >> 24) as u8,
(lba >> 16) as u8,
(lba >> 8) as u8,
lba as u8,
0x00,
(count >> 8) as u8,
count as u8,
0x00,
]
}
#[cfg(test)]
mod parse_sense_tests {
use super::parse_sense;
fn parse_sense_key(sense: &[u8], sb_len_wr: u8) -> u8 {
parse_sense(sense, sb_len_wr).sense_key
}
fn buf(b0: u8, b1: u8, b2: u8) -> [u8; 32] {
let mut s = [0u8; 32];
s[0] = b0;
s[1] = b1;
s[2] = b2;
s
}
#[test]
fn descriptor_format_72_picks_byte_1() {
let s = buf(0x72, 0x05, 0x77); assert_eq!(parse_sense_key(&s, 8), 5);
}
#[test]
fn descriptor_format_73_picks_byte_1() {
let s = buf(0x73, 0x06, 0xFF); assert_eq!(parse_sense_key(&s, 8), 6);
}
#[test]
fn fixed_format_70_picks_byte_2() {
let s = buf(0x70, 0x77, 0x05); assert_eq!(parse_sense_key(&s, 18), 5);
}
#[test]
fn fixed_format_71_picks_byte_2() {
let s = buf(0x71, 0x77, 0x02); assert_eq!(parse_sense_key(&s, 18), 2);
}
#[test]
fn high_bit_in_byte_0_is_masked() {
let s = buf(0xF2, 0x05, 0x77);
assert_eq!(
parse_sense_key(&s, 8),
5,
"VALID-bit must not leak into format detection"
);
let s = buf(0xF0, 0x77, 0x02);
assert_eq!(parse_sense_key(&s, 18), 2);
}
#[test]
fn high_nibble_in_key_byte_is_masked() {
let s = buf(0x70, 0x00, 0xE5); assert_eq!(parse_sense_key(&s, 18), 5);
}
#[test]
fn sb_len_wr_zero_returns_no_sense() {
let s = buf(0x72, 0x05, 0x05);
assert_eq!(parse_sense_key(&s, 0), 0);
}
#[test]
fn sb_len_wr_below_three_returns_no_sense() {
let s = buf(0x72, 0x05, 0x05);
assert_eq!(parse_sense_key(&s, 1), 0);
assert_eq!(parse_sense_key(&s, 2), 0);
}
#[test]
fn slice_below_three_returns_no_sense() {
let s = [0x72u8, 0x05];
assert_eq!(parse_sense_key(&s, 8), 0);
}
#[test]
fn unknown_response_code_falls_through_to_fixed() {
let s = buf(0x7A, 0x77, 0x03); assert_eq!(parse_sense_key(&s, 18), 3);
}
fn buf32() -> [u8; 32] {
[0u8; 32]
}
#[test]
fn descriptor_format_reads_asc_byte2_ascq_byte3() {
let mut s = buf32();
s[0] = 0x72;
s[1] = 0x02; s[2] = 0x3E; s[3] = 0x01; let d = parse_sense(&s, 8);
assert_eq!(d.sense_key, 2);
assert_eq!(d.asc, 0x3E, "descriptor ASC is byte 2");
assert_eq!(d.ascq, 0x01, "descriptor ASCQ is byte 3");
}
#[test]
fn descriptor_format_key_nibble_masked() {
let mut s = buf32();
s[0] = 0x72;
s[1] = 0xF3; s[2] = 0x11;
s[3] = 0x05;
let d = parse_sense(&s, 8);
assert_eq!(d.sense_key, 3);
}
#[test]
fn descriptor_n_exactly_3_ascq_defaults_zero() {
let mut s = buf32();
s[0] = 0x72;
s[1] = 0x03;
s[2] = 0x11;
s[3] = 0x05; let d = parse_sense(&s, 3);
assert_eq!(d.sense_key, 3);
assert_eq!(d.asc, 0x11);
assert_eq!(d.ascq, 0, "n=3 must not reach descriptor ASCQ at offset 3");
}
#[test]
fn fixed_format_full_reads_asc_byte12_ascq_byte13() {
let mut s = buf32();
s[0] = 0x70;
s[2] = 0x03;
s[12] = 0x11;
s[13] = 0x05;
let d = parse_sense(&s, 18);
assert_eq!(d.sense_key, 3);
assert_eq!(d.asc, 0x11, "fixed ASC is byte 12");
assert_eq!(d.ascq, 0x05, "fixed ASCQ is byte 13");
}
#[test]
fn fixed_format_short_buffer_asc_ascq_default_zero() {
let mut s = buf32();
s[0] = 0x70;
s[2] = 0x04; s[12] = 0xAA; s[13] = 0xBB;
let d = parse_sense(&s, 8);
assert_eq!(d.sense_key, 4);
assert_eq!(d.asc, 0, "n=8 < 13: ASC must default 0");
assert_eq!(d.ascq, 0, "n=8 < 14: ASCQ must default 0");
}
#[test]
fn fixed_format_n13_reads_asc_but_not_ascq() {
let mut s = buf32();
s[0] = 0x70;
s[2] = 0x03;
s[12] = 0x11;
s[13] = 0x05; let d = parse_sense(&s, 13);
assert_eq!(d.asc, 0x11, "n=13 reaches ASC at offset 12");
assert_eq!(d.ascq, 0, "n=13 does not reach ASCQ at offset 13");
}
#[test]
fn fixed_format_n14_reads_both() {
let mut s = buf32();
s[0] = 0x70;
s[2] = 0x03;
s[12] = 0x11;
s[13] = 0x05;
let d = parse_sense(&s, 14);
assert_eq!(d.asc, 0x11);
assert_eq!(d.ascq, 0x05, "n=14 reaches ASCQ at offset 13");
}
#[test]
fn n_exactly_three_decodes_key_only() {
let s = buf(0x70, 0x77, 0x06); let d = parse_sense(&s, 3);
assert_eq!(d.sense_key, 6);
assert_eq!(d.asc, 0);
assert_eq!(d.ascq, 0);
}
#[test]
fn descriptor_high_bit_set_on_72_still_descriptor() {
let mut s = buf32();
s[0] = 0xF2;
s[1] = 0x03;
s[2] = 0x11; s[3] = 0x05;
s[12] = 0x99; let d = parse_sense(&s, 18);
assert_eq!(d.asc, 0x11, "VALID-bit masking must keep descriptor parse");
}
#[test]
fn empty_slice_returns_none() {
let s: [u8; 0] = [];
let d = parse_sense(&s, 32);
assert_eq!(d, super::ScsiSense::NONE);
}
}
#[cfg(test)]
mod scsi_sense_predicate_tests {
use super::*;
fn s(key: u8) -> ScsiSense {
ScsiSense {
sense_key: key,
asc: 0,
ascq: 0,
}
}
#[test]
fn is_marginal_matches_exactly_the_recoverable_keys() {
let marginal: [u8; 5] = [
SENSE_KEY_NO_SENSE,
SENSE_KEY_RECOVERED_ERROR,
SENSE_KEY_NOT_READY,
SENSE_KEY_MEDIUM_ERROR,
SENSE_KEY_ABORTED_COMMAND,
];
for key in 0u8..=0x0F {
let expect = marginal.contains(&key);
assert_eq!(
s(key).is_marginal(),
expect,
"key {key:#x} marginal classification"
);
}
}
#[test]
fn each_specific_predicate_is_exclusive() {
let cases: &[(u8, fn(&ScsiSense) -> bool)] = &[
(SENSE_KEY_MEDIUM_ERROR, ScsiSense::is_medium_error),
(SENSE_KEY_HARDWARE_ERROR, ScsiSense::is_hardware_error),
(SENSE_KEY_NOT_READY, ScsiSense::is_not_ready),
(SENSE_KEY_UNIT_ATTENTION, ScsiSense::is_unit_attention),
(SENSE_KEY_DATA_PROTECT, ScsiSense::is_data_protect),
(SENSE_KEY_ILLEGAL_REQUEST, ScsiSense::is_illegal_request),
(SENSE_KEY_ABORTED_COMMAND, ScsiSense::is_aborted_command),
];
for &(key, pred) in cases {
for other in 0u8..=0x0F {
let got = pred(&s(other));
assert_eq!(
got,
other == key,
"predicate for key {key:#x} fired on {other:#x}"
);
}
}
}
#[test]
fn none_constant_and_default_agree_and_are_no_sense() {
assert_eq!(ScsiSense::NONE, ScsiSense::default());
assert_eq!(ScsiSense::NONE.sense_key, SENSE_KEY_NO_SENSE);
assert!(ScsiSense::NONE.is_marginal());
}
}
#[cfg(test)]
mod cdb_builder_tests {
use super::*;
#[test]
fn read10_fua_opcode_and_fua_bit() {
let cdb = build_read10_fua(0, 1);
assert_eq!(cdb[0], SCSI_READ_10);
assert_eq!(cdb[0], 0x28);
assert_eq!(cdb[1], 0x08, "FUA bit (byte1 bit3) must be set");
}
#[test]
fn read10_fua_lba_big_endian_bytes_2_5() {
let cdb = build_read10_fua(0x1122_3344, 0);
assert_eq!(cdb[2], 0x11);
assert_eq!(cdb[3], 0x22);
assert_eq!(cdb[4], 0x33);
assert_eq!(cdb[5], 0x44);
}
#[test]
fn read10_fua_transfer_length_big_endian_bytes_7_8() {
let cdb = build_read10_fua(0, 0xABCD);
assert_eq!(cdb[6], 0x00, "byte 6 group number must be 0");
assert_eq!(cdb[7], 0xAB, "transfer length MSB");
assert_eq!(cdb[8], 0xCD, "transfer length LSB");
assert_eq!(cdb[9], 0x00, "byte 9 control must be 0");
}
#[test]
fn read10_fua_max_lba_and_count() {
let cdb = build_read10_fua(u32::MAX, u16::MAX);
assert_eq!(&cdb[2..6], &[0xFF, 0xFF, 0xFF, 0xFF]);
assert_eq!(&cdb[7..9], &[0xFF, 0xFF]);
}
#[test]
fn read_buffer_cdb_layout() {
let cdb = build_read_buffer(0x02, 0xF1, 0x010203, 0x040506);
assert_eq!(cdb[0], SCSI_READ_BUFFER);
assert_eq!(cdb[1], 0x02, "mode");
assert_eq!(cdb[2], 0xF1, "buffer id");
assert_eq!(&cdb[3..6], &[0x01, 0x02, 0x03], "offset 24-bit BE");
assert_eq!(&cdb[6..9], &[0x04, 0x05, 0x06], "length 24-bit BE");
assert_eq!(cdb[9], 0x00, "control");
}
#[test]
fn read_buffer_offset_truncates_to_24_bits_low() {
let cdb = build_read_buffer(0, 0, 0xFF01_0203, 0);
assert_eq!(&cdb[3..6], &[0x01, 0x02, 0x03]);
}
#[test]
fn set_cd_speed_cdb_layout() {
let cdb = build_set_cd_speed(0x1234);
assert_eq!(cdb[0], SCSI_SET_CD_SPEED);
assert_eq!(cdb[2], 0x12, "read speed MSB");
assert_eq!(cdb[3], 0x34, "read speed LSB");
assert_eq!(cdb[4], 0xFF, "write speed bytes set to 0xFFFF");
assert_eq!(cdb[5], 0xFF);
}
#[test]
fn set_cd_speed_zero_means_drive_default() {
let cdb = build_set_cd_speed(0);
assert_eq!(cdb[2], 0x00);
assert_eq!(cdb[3], 0x00);
}
}
#[cfg(test)]
mod inquiry_tests {
use super::*;
struct ScriptedTransport {
payload: Vec<u8>,
last_cdb: Vec<u8>,
}
impl ScsiTransport for ScriptedTransport {
fn execute(
&mut self,
cdb: &[u8],
_dir: DataDirection,
data: &mut [u8],
_timeout_ms: u32,
) -> Result<ScsiResult> {
self.last_cdb = cdb.to_vec();
let n = self.payload.len().min(data.len());
data[..n].copy_from_slice(&self.payload[..n]);
Ok(ScsiResult {
status: 0,
bytes_transferred: n,
sense: [0u8; 32],
})
}
}
fn inquiry_payload(vendor: &[u8], product: &[u8], rev: &[u8]) -> Vec<u8> {
let mut p = vec![0u8; 96];
p[0] = 0x05;
for b in &mut p[8..36] {
*b = b' ';
}
p[8..8 + vendor.len()].copy_from_slice(vendor);
p[16..16 + product.len()].copy_from_slice(product);
p[32..32 + rev.len()].copy_from_slice(rev);
p
}
#[test]
fn parses_vendor_product_revision_offsets() {
let payload = inquiry_payload(b"HL-DT-ST", b"BD-RE BU40N ", b"1.04");
let mut t = ScriptedTransport {
payload,
last_cdb: vec![],
};
let r = inquiry(&mut t).unwrap();
assert_eq!(r.vendor_id, "HL-DT-ST");
assert_eq!(r.model, "BD-RE BU40N");
assert_eq!(r.firmware, "1.04");
}
#[test]
fn fields_are_independent_no_bleed_across_offset_boundaries() {
let payload = inquiry_payload(b"VENDOR12", b"XPRODUCT", b"REV0");
let mut t = ScriptedTransport {
payload,
last_cdb: vec![],
};
let r = inquiry(&mut t).unwrap();
assert_eq!(r.vendor_id, "VENDOR12", "vendor must stop at byte 16");
assert!(
!r.vendor_id.contains('X'),
"product byte must not bleed into vendor"
);
assert_eq!(r.model, "XPRODUCT");
}
#[test]
fn whitespace_padded_fields_trimmed() {
let payload = inquiry_payload(b" ABC ", b" MODEL X ", b" R1 ");
let mut t = ScriptedTransport {
payload,
last_cdb: vec![],
};
let r = inquiry(&mut t).unwrap();
assert_eq!(r.vendor_id, "ABC");
assert_eq!(r.model, "MODEL X");
assert_eq!(r.firmware, "R1");
}
#[test]
fn cdb_is_standard_inquiry_96_bytes() {
let payload = inquiry_payload(b"V", b"M", b"R");
let mut t = ScriptedTransport {
payload,
last_cdb: vec![],
};
let _ = inquiry(&mut t).unwrap();
assert_eq!(t.last_cdb[0], SCSI_INQUIRY);
assert_eq!(t.last_cdb[4], 0x60, "allocation length must be 96 bytes");
}
#[test]
fn raw_response_preserved_full_96_bytes() {
let payload = inquiry_payload(b"HL-DT-ST", b"BD-RE BU40N", b"1.04");
let mut t = ScriptedTransport {
payload,
last_cdb: vec![],
};
let r = inquiry(&mut t).unwrap();
assert_eq!(r.raw.len(), 96);
assert_eq!(r.raw[0], 0x05, "peripheral device type byte preserved");
}
}