use std::io::{Read, Seek};
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Filesystem {
#[cfg(feature = "ext")]
Ext(crate::feature::Profile),
#[cfg(feature = "fat")]
Fat(crate::fat::FatType),
#[cfg(feature = "exfat")]
ExFat,
#[cfg(feature = "btrfs")]
Btrfs,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
#[non_exhaustive]
pub struct DetectOptions {
pub base: u64,
}
impl DetectOptions {
#[must_use]
pub const fn new() -> Self {
Self { base: 0 }
}
#[must_use]
pub const fn base(mut self, base: u64) -> Self {
self.base = base;
self
}
}
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DetectError {
#[error("i/o error: {message}")]
#[non_exhaustive]
Io {
kind: std::io::ErrorKind,
message: String,
},
#[error("unrecognized filesystem: no compiled-in family claims this image")]
Unrecognized,
}
crate::io::io_error!(DetectError);
pub fn detect<R: Read + Seek>(src: R) -> Result<Filesystem, DetectError> {
detect_with(src, &DetectOptions::new())
}
pub fn detect_with<R: Read + Seek>(
#[allow(unused_mut)] mut src: R,
options: &DetectOptions,
) -> Result<Filesystem, DetectError> {
#[cfg(feature = "ext")]
match ext_claim(&mut src, options) {
Ok(Some(fs)) => return Ok(fs),
Ok(None) => {}
Err(e) => return Err(e),
}
#[cfg(feature = "exfat")]
match crate::exfat::claim(&mut src, options) {
Ok(Some(fs)) => return Ok(fs),
Ok(None) => {}
Err(e) => return Err(e),
}
#[cfg(feature = "btrfs")]
match crate::btrfs::claim(&mut src, options) {
Ok(Some(fs)) => return Ok(fs),
Ok(None) => {}
Err(e) => return Err(e),
}
#[cfg(feature = "fat")]
match crate::fat::claim(&mut src, options) {
Ok(Some(fs)) => return Ok(fs),
Ok(None) => {}
Err(e) => return Err(e),
}
let _ = (&mut src, options);
Err(DetectError::Unrecognized)
}
#[cfg(feature = "ext")]
fn ext_claim<R: Read + Seek>(
src: R,
options: &DetectOptions,
) -> Result<Option<Filesystem>, DetectError> {
use crate::policy::ReadPolicy;
use crate::read::{OpenOptions, ReadError, Reader};
let open = OpenOptions::new()
.base(options.base)
.policy(ReadPolicy::Lenient);
match Reader::open_with(src, &open) {
Ok(reader) => Ok(Some(Filesystem::Ext(reader.profile()))),
Err(ReadError::Io {
kind: std::io::ErrorKind::UnexpectedEof,
..
}) => Ok(None),
Err(ReadError::Io { kind, message }) => Err(DetectError::Io { kind, message }),
Err(_) => Ok(None),
}
}
#[cfg(test)]
mod agnostic_tests {
use super::DetectOptions;
#[test]
fn options_carry_the_offset_they_were_given() {
assert_eq!(DetectOptions::new().base, 0);
assert_eq!(DetectOptions::new().base(1 << 20).base, 1 << 20);
assert_eq!(DetectOptions::default(), DetectOptions::new());
}
#[cfg(not(any(feature = "ext", feature = "fat", feature = "exfat", feature = "btrfs")))]
#[test]
fn a_build_with_no_family_recognizes_nothing() {
use super::{DetectError, detect, detect_with};
use std::io::Cursor;
for bytes in [vec![0u8; 4096], b"not a filesystem".to_vec(), Vec::new()] {
assert_eq!(
detect(Cursor::new(bytes)).unwrap_err(),
DetectError::Unrecognized
);
}
assert_eq!(
detect_with(
Cursor::new(vec![0u8; 1024]),
&DetectOptions::new().base(1 << 30)
)
.unwrap_err(),
DetectError::Unrecognized
);
}
}
#[cfg(all(
test,
any(feature = "ext", feature = "fat", feature = "exfat", feature = "btrfs")
))]
mod every_family {
use super::{DetectError, DetectOptions, Filesystem, detect, detect_with};
use std::io::Cursor;
fn images() -> Vec<(Filesystem, Vec<u8>)> {
let mut out = Vec::new();
#[cfg(feature = "ext")]
out.push((
Filesystem::Ext(crate::feature::Profile::Ext4),
super::tests::image(),
));
#[cfg(feature = "fat")]
{
use crate::fat::{FormatOptions, format};
let options = FormatOptions::new(
0x1234_abcd,
crate::time::Timestamp::from_secs(1_426_325_212),
);
let image = format(crate::source::TreeBuilder::new(), 8 << 20, options)
.expect("format a FAT volume");
out.push((Filesystem::Fat(image.layout().fat_type), image.into_bytes()));
}
#[cfg(feature = "exfat")]
out.push((
Filesystem::ExFat,
super::exfat_tests::image(&crate::exfat::PlanRequest::new(8 << 20)),
));
#[cfg(feature = "btrfs")]
{
use std::io::Read;
let mut src = crate::btrfs::forge::Forge::new().source();
let mut bytes = Vec::new();
src.read_to_end(&mut bytes).expect("the forged device");
out.push((Filesystem::Btrfs, bytes));
}
assert!(
!out.is_empty(),
"this module is compiled only where a family is"
);
out
}
#[test]
fn each_compiled_in_family_is_detected_as_itself() {
for (want, bytes) in images() {
assert_eq!(detect(Cursor::new(bytes)).expect("detect"), want);
}
}
#[test]
fn detection_answers_at_the_offset_it_is_given() {
const BASE: u64 = 1 << 20;
for (want, bytes) in images() {
let mut disk = vec![0u8; BASE as usize];
disk.extend_from_slice(&bytes);
assert!(
matches!(detect(Cursor::new(&disk)), Err(DetectError::Unrecognized)),
"{want:?} was claimed at an offset it does not begin at"
);
assert_eq!(
detect_with(Cursor::new(&disk), &DetectOptions::new().base(BASE)).expect("detect"),
want
);
}
}
#[test]
fn a_source_that_is_not_a_filesystem_is_claimed_by_nobody() {
for junk in [
vec![0u8; 64 << 10],
(0..64u32 << 10).map(|i| (i % 251) as u8).collect(),
] {
assert!(matches!(
detect(Cursor::new(junk)),
Err(DetectError::Unrecognized)
));
}
}
}
#[cfg(all(test, feature = "exfat"))]
mod exfat_tests {
use super::{Filesystem, detect};
use crate::exfat::ondisk::{FILE_SYSTEM_NAME, FILE_SYSTEM_REVISION, MainBootSector};
use crate::exfat::{PlanRequest, plan_layout};
use std::io::Cursor;
pub(super) fn image(request: &PlanRequest) -> Vec<u8> {
let layout = plan_layout(request).expect("plan");
let boot = MainBootSector {
jump_boot: MainBootSector::JUMP_BOOT,
file_system_name: FILE_SYSTEM_NAME,
partition_offset: 0,
volume_length: layout.volume_length,
fat_offset: layout.fat_offset,
fat_length: layout.fat_length,
cluster_heap_offset: layout.cluster_heap_offset,
cluster_count: layout.cluster_count,
first_cluster_of_root: layout.first_cluster_of_root,
volume_serial: 0x1234_5678,
file_system_revision: FILE_SYSTEM_REVISION,
volume_flags: 0,
bytes_per_sector_shift: layout.bytes_per_sector_shift(),
sectors_per_cluster_shift: layout.sectors_per_cluster_shift(),
number_of_fats: 1,
drive_select: 0x80,
percent_in_use: 0,
boot_code: [0; 390],
};
let mut bytes =
vec![0u8; usize::try_from(layout.total_bytes()).expect("a test-sized volume")];
boot.write_to(&mut bytes).expect("write");
bytes
}
#[test]
fn a_volume_this_crate_plans_is_detected_as_this_family() {
for request in [
PlanRequest::new(8 << 20),
PlanRequest::new(8 << 20).bytes_per_sector(4096),
PlanRequest::new(8 << 20).cluster_size(crate::exfat::ClusterSize::Bytes(512)),
] {
assert_eq!(
detect(Cursor::new(image(&request))).expect("detect"),
Filesystem::ExFat,
"{request:?}"
);
}
}
#[test]
#[cfg(feature = "fat")]
fn a_fat_volume_whose_oem_name_spells_this_magic_is_still_detected_as_fat() {
use crate::fat::{FormatOptions, format};
use crate::source::TreeBuilder;
let mut options = FormatOptions::new(
0x1234_abcd,
crate::time::Timestamp::from_secs(1_426_325_212),
);
options.oem_name = *b"EXFAT ";
let mut bytes = format(TreeBuilder::new(), 8 << 20, options)
.expect("format a FAT volume")
.into_bytes();
assert_eq!(
&bytes[3..11],
b"EXFAT ",
"the fixture must carry the collision"
);
assert!(
matches!(detect(Cursor::new(&bytes)), Ok(Filesystem::Fat(_))),
"a FAT volume spelling this family's magic was claimed by this family"
);
bytes[11..64].fill(0);
assert_eq!(detect(Cursor::new(&bytes)).ok(), None);
}
}
#[cfg(all(test, feature = "ext"))]
mod tests {
use std::io::Cursor;
use super::{DetectError, Filesystem, detect};
use crate::feature::Profile;
use crate::materialize::{FormatOptions, format};
use crate::source::TreeBuilder;
use crate::time::Timestamp;
pub(super) fn image() -> Vec<u8> {
let time = Timestamp::from_secs(1_700_000_000);
let options = FormatOptions::new([7; 16], time, [0; 16]);
format(TreeBuilder::new(), 32 << 20, options)
.expect("format")
.into_bytes()
}
#[test]
#[cfg(feature = "fat")]
fn a_source_too_short_for_an_ext_superblock_still_reaches_the_later_probes() {
let mut fragment = vec![0u8; 512];
fragment[510] = 0x55;
fragment[511] = 0xAA;
assert!(
!matches!(
detect(Cursor::new(fragment)),
Err(super::DetectError::Io { .. })
),
"a short source ended detection instead of failing the ext probe"
);
}
#[test]
fn a_quirk_a_strict_read_refuses_is_still_a_filesystem() {
let mut bytes = image();
let off = 1024 + 0x60;
let incompat = crate::bytes::get_u32(&bytes, off) | 0x8000_0000;
crate::bytes::put_u32(&mut bytes, off, incompat);
assert!(
crate::read::Reader::open(Cursor::new(&bytes)).is_err(),
"a strict read must refuse an incompat feature it does not interpret"
);
assert_eq!(
detect(Cursor::new(&bytes)).expect("detection is not strictness"),
Filesystem::Ext(Profile::Ext4)
);
}
#[test]
fn an_io_failure_records_its_kind_beside_its_message() {
let fault = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "no");
let err = DetectError::from(fault);
let DetectError::Io { kind, message } = &err else {
panic!("expected an i/o failure, got {err:?}");
};
assert_eq!(*kind, std::io::ErrorKind::PermissionDenied);
assert!(message.contains("no"), "the message is carried: {message}");
}
}