use std::collections::BTreeMap;
use crate::finding::{Deviation, Family, Finding, Findings, Severity, project};
use super::btree::Census;
use super::container::ReadError;
use super::ondisk::record_kind;
pub type ScanReport = crate::ScanReport<Anomaly>;
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Category {
Source,
Checkpoint,
Tree,
Record,
Volume,
Space,
}
impl Category {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Category::Source => "source",
Category::Checkpoint => "checkpoint",
Category::Tree => "tree",
Category::Record => "record",
Category::Volume => "volume",
Category::Space => "space",
}
}
}
crate::naming::serialize_as_name!(Category);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Anomaly {
pub category: Category,
pub severity: Severity,
pub block: Option<u64>,
pub inode: Option<u64>,
pub detail: String,
}
impl Deviation for Anomaly {
fn severity(&self) -> Severity {
self.severity
}
fn is_source_failure(&self) -> bool {
self.category == Category::Source
}
fn to_finding(&self, unit: u32) -> Finding {
project(
self.severity,
Family::Apfs,
self.category.as_str(),
&[("block", self.block), ("inode", self.inode)],
self.block,
unit,
&self.detail,
)
}
}
pub(super) struct Scan {
pub(super) found: Findings<Anomaly>,
unknown: BTreeMap<u8, u64>,
fields: BTreeMap<u8, u64>,
undecoded: BTreeMap<u32, u64>,
block_size: u32,
}
impl Scan {
pub(super) fn new(cap: usize, block_size: u32) -> Self {
Self {
found: Findings::new(cap),
unknown: BTreeMap::new(),
fields: BTreeMap::new(),
undecoded: BTreeMap::new(),
block_size,
}
}
pub(super) fn at(
&mut self,
category: Category,
severity: Severity,
block: Option<u64>,
inode: Option<u64>,
detail: String,
) {
self.found.push(Anomaly {
category,
severity,
block,
inode,
detail,
});
}
pub(super) fn failed(&mut self, inode: Option<u64>, context: &str, err: &ReadError) {
let (category, severity, block) = classify(err);
self.at(
category,
severity,
block,
inode,
format!("{context}: {err}"),
);
}
pub(super) fn block_size(&self) -> u32 {
self.block_size
}
pub(super) fn census(&mut self, what: &str, census: &Census) {
let info = &census.info;
let mut deviation = |block: u64, detail: String| {
self.at(
Category::Tree,
Severity::Conformance,
Some(block),
None,
format!("the {what} tree: {detail}"),
);
};
if info.key_count != census.records {
deviation(
census.root,
format!(
"its root records {} records and it holds {}",
info.key_count, census.records
),
);
}
if info.node_count != census.nodes {
deviation(
census.root,
format!(
"its root records {} nodes and it has {}",
info.node_count, census.nodes
),
);
}
let (key, value) = census.longest;
if key > info.longest_key as usize {
deviation(
census.root,
format!(
"it holds a {key}-byte key and its root records {} as the longest",
info.longest_key
),
);
}
if value > info.longest_value as usize {
deviation(
census.root,
format!(
"it holds a {value}-byte value and its root records {} as the longest",
info.longest_value
),
);
}
for (block, area, said, held) in &census.free_lists {
deviation(
*block,
format!(
"the node's {area} free list records {said} bytes and {held} of the {area} \
area are unused"
),
);
}
}
pub(super) fn met(&mut self, kind: u8) {
if !INTERPRETED.contains(&kind) {
*self.unknown.entry(kind).or_default() += 1;
}
}
pub(super) fn field(&mut self, kind: u8) {
*self.fields.entry(kind).or_default() += 1;
}
pub(super) fn undecoded(&mut self, method: u32) {
*self.undecoded.entry(method).or_default() += 1;
}
pub(super) fn finish(mut self) -> ScanReport {
let unknown = std::mem::take(&mut self.unknown);
for (kind, count) in unknown {
self.at(
Category::Record,
Severity::Cosmetic,
None,
None,
format!(
"{count} record{} of kind {kind}, which this reader does not interpret; \
each was skipped",
if count == 1 { "" } else { "s" }
),
);
}
let fields = std::mem::take(&mut self.fields);
for (kind, count) in fields {
self.at(
Category::Record,
Severity::Cosmetic,
None,
None,
format!(
"{count} extended field{} of type {kind}, which this reader does not know; \
each was skipped",
if count == 1 { "" } else { "s" }
),
);
}
let undecoded = std::mem::take(&mut self.undecoded);
for (method, count) in undecoded {
self.at(
Category::Record,
Severity::Cosmetic,
None,
None,
format!(
"{count} file{} compressed by type {method}, which this build does not \
decode; {} content was not read",
if count == 1 { "" } else { "s" },
if count == 1 { "its" } else { "their" }
),
);
}
self.found.into_report(self.block_size)
}
}
const INTERPRETED: [u8; 7] = [
record_kind::INODE,
record_kind::XATTR,
record_kind::SIBLING_LINK,
record_kind::DATA_STREAM_ID,
record_kind::FILE_EXTENT,
record_kind::DIR_ENTRY,
record_kind::SIBLING_MAP,
];
fn classify(err: &ReadError) -> (Category, Severity, Option<u64>) {
match err {
ReadError::Io { kind, .. } if *kind != std::io::ErrorKind::UnexpectedEof => {
(Category::Source, Severity::Structural, None)
}
ReadError::BadChecksum { block, .. } => (Category::Tree, Severity::Integrity, Some(*block)),
ReadError::BadNode { block, .. }
| ReadError::BadTree { block, .. }
| ReadError::WrongObject { block, .. } => {
(Category::Tree, Severity::Structural, Some(*block))
}
ReadError::NoCheckpoint | ReadError::UnsupportedCheckpoint => {
(Category::Checkpoint, Severity::Structural, None)
}
ReadError::BlockZeroDisagrees { .. } => {
(Category::Checkpoint, Severity::Integrity, Some(0))
}
ReadError::BadExtent { block, .. } => (Category::Record, Severity::Structural, *block),
ReadError::RepeatedDirectory { .. } | ReadError::MisplacedDirectory { .. } => {
(Category::Record, Severity::Integrity, None)
}
_ => (Category::Record, Severity::Structural, None),
}
}