use std::io::{ErrorKind, Read, Seek, SeekFrom};
use crate::detect::{DetectError, DetectOptions, Filesystem};
use crate::fat::geometry::{FatType, layout_from_boot};
use crate::fat::ondisk::BootSector;
use crate::io::read_exact_at;
pub(crate) fn claim<R: Read + Seek>(
mut src: R,
options: &DetectOptions,
) -> Result<Option<Filesystem>, DetectError> {
let end = src.seek(SeekFrom::End(0))?;
let Some(available) = end.checked_sub(options.base) else {
return Ok(None);
};
let sector = match read_exact_at(&mut src, options.base, BootSector::SIZE) {
Ok(sector) => sector,
Err(e) if e.kind() == ErrorKind::UnexpectedEof => return Ok(None),
Err(e) => return Err(e.into()),
};
Ok(classify(§or, available).map(Filesystem::Fat))
}
fn classify(sector: &[u8], available: u64) -> Option<FatType> {
let boot = BootSector::read_from(sector).ok()?;
layout_from_boot(&boot, available).ok().map(|l| l.fat_type)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::fat::geometry::{
ClusterSize, FatTypeRequest, MAX_CLUSTERS_FAT16, MIN_CLUSTERS_FAT32, PlanRequest,
ReservedSectors, RootEntries, plan_layout,
};
use crate::fat::ondisk::{BootSectorTail, Fat32Params, VolumeInfo};
fn sector_for(request: &PlanRequest) -> ([u8; BootSector::SIZE], u64) {
let layout = plan_layout(request).expect("plan");
let volume = VolumeInfo {
drive_number: 0x80,
reserved: 0,
ext_boot_signature: crate::fat::ondisk::EXTENDED_BOOT_SIGNATURE,
volume_id: 0x1234_abcd,
label: VolumeInfo::NO_NAME,
fs_type: layout.fat_type.label(),
};
let tail = match layout.fat32 {
Some(f) => BootSectorTail::Fat32 {
params: Fat32Params {
fat_sectors: layout.fat_sectors,
ext_flags: 0,
version: 0,
root_cluster: f.root_cluster,
fs_info_sector: f.fs_info_sector,
backup_boot_sector: f.backup_boot_sector.unwrap_or(0),
},
volume,
},
None => BootSectorTail::Fat1216 { volume },
};
let boot = BootSector {
jump: [0xEB, 0x3C, 0x90],
oem_name: *b"ferrosys",
bytes_per_sector: layout.bytes_per_sector as u16,
sectors_per_cluster: layout.sectors_per_cluster as u8,
reserved_sectors: layout.reserved_sectors as u16,
fats: layout.fats as u8,
root_entries: layout.root_entries as u16,
total_sectors_16: u16::try_from(layout.total_sectors).unwrap_or(0),
media: 0xF8,
fat_sectors_16: match layout.fat32 {
Some(_) => 0,
None => layout.fat_sectors as u16,
},
sectors_per_track: 32,
heads: 2,
hidden_sectors: 0,
total_sectors_32: if u16::try_from(layout.total_sectors).is_ok() {
0
} else {
layout.total_sectors
},
tail,
};
let mut sector = [0u8; BootSector::SIZE];
boot.write_to(&mut sector).expect("write");
(sector, layout.total_bytes())
}
fn fat12() -> ([u8; BootSector::SIZE], u64) {
sector_for(
&PlanRequest::new(4160 * 512)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(20))
.root_entries(RootEntries::Count(512)),
)
}
fn fat16() -> ([u8; BootSector::SIZE], u64) {
sector_for(&PlanRequest::new(64 << 20))
}
fn fat32() -> ([u8; BootSector::SIZE], u64) {
sector_for(&PlanRequest::new(256 << 20).fat_type(FatTypeRequest::Exactly(FatType::Fat32)))
}
#[test]
fn a_planned_volume_of_each_type_is_classified_as_that_type() {
for (expected, (sector, size)) in [
(FatType::Fat12, fat12()),
(FatType::Fat16, fat16()),
(FatType::Fat32, fat32()),
] {
assert_eq!(
classify(§or, size),
Some(expected),
"a planned {expected} was not classified as one"
);
}
}
#[test]
fn the_boot_signature_alone_is_not_evidence() {
let mut mbr = [0u8; BootSector::SIZE];
mbr[510] = 0x55;
mbr[511] = 0xAA;
assert_eq!(classify(&mbr, 1 << 30), None);
mbr[0..3].copy_from_slice(&[0xEB, 0x3C, 0x90]);
assert_eq!(classify(&mbr, 1 << 30), None);
}
#[test]
fn every_field_the_classifier_checks_can_refuse_the_image_on_its_own() {
let (clean, size) = fat16();
assert!(classify(&clean, size).is_some());
type Damage<'a> = (&'a str, &'a dyn Fn(&mut [u8; BootSector::SIZE]));
let cases: &[Damage<'_>] = &[
("the jump instruction", &|s| s[0] = 0x00),
("the jump's trailing no-op", &|s| s[2] = 0x00),
("the sector size", &|s| {
s[11..13].copy_from_slice(&768u16.to_le_bytes())
}),
("a sector size past the format's range", &|s| {
s[11..13].copy_from_slice(&8192u16.to_le_bytes());
}),
("the cluster size", &|s| s[13] = 3),
("a zero cluster size", &|s| s[13] = 0),
("the table count", &|s| s[16] = 0),
("an implausible table count", &|s| s[16] = 16),
("the reserved count", &|s| {
s[14..16].copy_from_slice(&0u16.to_le_bytes())
}),
("the media byte", &|s| s[21] = 0x42),
("the root entry count", &|s| {
s[17..19].copy_from_slice(&0u16.to_le_bytes())
}),
("the table size", &|s| {
s[22..24].copy_from_slice(&0u16.to_le_bytes())
}),
("a table that leaves no data region", &|s| {
s[22..24].copy_from_slice(&u16::MAX.to_le_bytes());
}),
("a table too small to index its own clusters", &|s| {
s[22..24].copy_from_slice(&1u16.to_le_bytes());
}),
];
for (what, damage) in cases {
let mut sector = clean;
damage(&mut sector);
assert_eq!(
classify(§or, size),
None,
"{what} was damaged and the image was still claimed as FAT"
);
}
}
#[test]
fn a_volume_larger_than_its_source_is_refused() {
let (sector, size) = fat16();
assert!(classify(§or, size).is_some());
assert_eq!(classify(§or, size - 512), None);
assert!(classify(§or, size + (1 << 20)).is_some());
}
#[test]
fn an_undersized_fat32_is_classified_as_fat32_and_not_by_its_count() {
let (sector, size) = sector_for(
&PlanRequest::new(8 << 20)
.cluster_size(ClusterSize::Sectors(1))
.reserved_sectors(ReservedSectors::Count(32))
.fat_type(FatTypeRequest::UndersizedFat32),
);
let boot = BootSector::read_from(§or).expect("parse");
let clusters = (boot.total_sectors()
- u32::from(boot.reserved_sectors)
- u32::from(boot.fats) * boot.fat_sectors())
/ u32::from(boot.sectors_per_cluster);
assert!(
clusters < crate::fat::MIN_CLUSTERS_FAT32,
"this fixture is meant to be below the FAT32 minimum"
);
assert_eq!(FatType::of_cluster_count(clusters), FatType::Fat16);
assert_eq!(classify(§or, size), Some(FatType::Fat32));
}
#[test]
fn the_two_tails_check_each_other() {
let (mut sector, size) = fat32();
sector[17..19].copy_from_slice(&512u16.to_le_bytes());
assert_eq!(classify(§or, size), None);
let (mut sector, size) = fat32();
sector[44..48].copy_from_slice(&0u32.to_le_bytes());
assert_eq!(classify(§or, size), None);
let (mut sector, size) = fat32();
sector[44..48].copy_from_slice(&50_000_000u32.to_le_bytes());
assert_eq!(classify(§or, size), None);
}
#[test]
fn a_source_too_short_to_hold_a_boot_sector_is_not_ours_rather_than_an_error() {
use std::io::Cursor;
for len in [0usize, 1, 511] {
assert_eq!(
claim(Cursor::new(vec![0u8; len]), &DetectOptions::new()).expect("no i/o error"),
None
);
}
assert_eq!(
claim(
Cursor::new(vec![0u8; 4096]),
&DetectOptions::new().base(1 << 20)
)
.expect("no i/o error"),
None
);
}
#[test]
fn a_twelve_or_sixteen_shape_is_never_claimed_as_fat32() {
let (mut sector, _) = fat16();
let root_dir_sectors = 512u32 * 32 / 512;
let overhead = 1 + 512 + root_dir_sectors;
sector[11..13].copy_from_slice(&512u16.to_le_bytes()); sector[13] = 1; sector[14..16].copy_from_slice(&1u16.to_le_bytes()); sector[16] = 1; sector[17..19].copy_from_slice(&512u16.to_le_bytes()); sector[19..21].copy_from_slice(&0u16.to_le_bytes()); sector[22..24].copy_from_slice(&512u16.to_le_bytes());
for (clusters, expected) in [
(MAX_CLUSTERS_FAT16, Some(FatType::Fat16)),
(MIN_CLUSTERS_FAT32, None),
] {
let total = overhead + clusters;
sector[32..36].copy_from_slice(&total.to_le_bytes()); assert_eq!(
classify(§or, u64::from(total) * 512),
expected,
"{clusters} clusters under a 12/16 tail",
);
}
}
#[test]
fn claim_answers_at_the_offset_it_is_given() {
use std::io::Cursor;
const BASE: u64 = 1 << 20;
let (sector, size) = fat16();
let mut disk = vec![0u8; BASE as usize];
disk.extend_from_slice(§or);
disk.resize(BASE as usize + size as usize, 0);
assert_eq!(
claim(Cursor::new(&disk), &DetectOptions::new()).expect("no i/o error"),
None
);
assert_eq!(
claim(Cursor::new(&disk), &DetectOptions::new().base(BASE)).expect("no i/o error"),
Some(Filesystem::Fat(FatType::Fat16))
);
}
}