#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Property {
Ownership,
Permissions,
SpecialBits,
Kind,
ExtendedAttributes,
AccessTime,
ChangeTime,
ModificationTime,
TimePrecision,
Name,
BsdFlags,
}
impl Property {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Property::Ownership => "ownership",
Property::Permissions => "permissions",
Property::SpecialBits => "special bits",
Property::Kind => "kind",
Property::ExtendedAttributes => "extended attributes",
Property::AccessTime => "access time",
Property::ChangeTime => "change time",
Property::ModificationTime => "modification time",
Property::TimePrecision => "time precision",
Property::Name => "name",
Property::BsdFlags => "bsd flags",
}
}
const fn bit(self) -> u32 {
match self {
Property::Ownership => 1 << 0,
Property::Permissions => 1 << 1,
Property::SpecialBits => 1 << 2,
Property::Kind => 1 << 3,
Property::ExtendedAttributes => 1 << 4,
Property::AccessTime => 1 << 5,
Property::ChangeTime => 1 << 6,
Property::ModificationTime => 1 << 7,
Property::TimePrecision => 1 << 8,
Property::Name => 1 << 9,
Property::BsdFlags => 1 << 10,
}
}
}
crate::naming::serialize_as_name!(Property);
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
pub struct AcceptedLoss(u32);
impl AcceptedLoss {
pub const NONE: Self = Self(0);
pub const ALL: Self = Self(u32::MAX);
#[must_use]
pub const fn and(self, property: Property) -> Self {
Self(self.0 | property.bit())
}
#[must_use]
pub const fn without(self, property: Property) -> Self {
Self(self.0 & !property.bit())
}
#[must_use]
pub const fn contains(self, property: Property) -> bool {
self.0 & property.bit() != 0
}
#[must_use]
pub const fn is_empty(self) -> bool {
self.0 == 0
}
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[non_exhaustive]
pub enum Direction {
Dropped,
Synthesized,
}
impl Direction {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Direction::Dropped => "dropped",
Direction::Synthesized => "synthesized",
}
}
}
crate::naming::serialize_as_name!(Direction);
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FidelityRecord {
pub direction: Direction,
pub path: Vec<u8>,
pub property: Property,
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct FidelityReport {
records: Vec<FidelityRecord>,
counts: Vec<((Direction, Property), u64)>,
truncated: bool,
}
impl Default for FidelityReport {
fn default() -> Self {
Self::new()
}
}
impl FidelityReport {
pub const MAX_RECORDS: usize = 10_000;
#[must_use]
pub fn new() -> Self {
Self {
records: Vec::new(),
counts: Vec::new(),
truncated: false,
}
}
pub fn record(&mut self, direction: Direction, path: &[u8], property: Property) {
let key = (direction, property);
match self.counts.iter_mut().find(|(k, _)| *k == key) {
Some((_, n)) => *n += 1,
None => self.counts.push((key, 1)),
}
if self.records.len() < Self::MAX_RECORDS {
self.records.push(FidelityRecord {
direction,
path: path.to_vec(),
property,
});
} else {
self.truncated = true;
}
}
#[must_use]
pub fn is_faithful(&self) -> bool {
self.counts.is_empty()
}
#[must_use]
pub fn records(&self) -> &[FidelityRecord] {
&self.records
}
#[must_use]
pub fn is_truncated(&self) -> bool {
self.truncated
}
#[must_use]
pub fn count(&self, direction: Direction, property: Property) -> u64 {
self.counts
.iter()
.find(|(k, _)| *k == (direction, property))
.map_or(0, |(_, n)| *n)
}
#[must_use]
pub fn summary(&self) -> Vec<(Direction, Property, u64)> {
self.counts.iter().map(|((d, p), n)| (*d, *p, *n)).collect()
}
#[must_use]
pub fn to_table(&self) -> String {
if self.counts.is_empty() {
return "nothing dropped or synthesized\n".to_string();
}
let rows: Vec<(&str, &str, String)> = self
.summary()
.into_iter()
.map(|(d, p, n)| (d.as_str(), p.as_str(), n.to_string()))
.collect();
let mut dir_w = "DIRECTION".len();
let mut prop_w = "PROPERTY".len();
for (d, p, _) in &rows {
dir_w = dir_w.max(d.len());
prop_w = prop_w.max(p.len());
}
let mut out = format!(
"{:<dir_w$} {:<prop_w$} {}\n",
"DIRECTION", "PROPERTY", "ENTRIES"
);
for (d, p, n) in &rows {
out.push_str(&format!("{d:<dir_w$} {p:<prop_w$} {n}\n"));
}
out
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Synthesis {
pub uid: u32,
pub gid: u32,
pub file_mode: u16,
pub dir_mode: u16,
}
impl Synthesis {
#[must_use]
pub const fn new() -> Self {
Self {
uid: 0,
gid: 0,
file_mode: 0o644,
dir_mode: 0o755,
}
}
#[must_use]
pub const fn owner(mut self, uid: u32, gid: u32) -> Self {
self.uid = uid;
self.gid = gid;
self
}
#[must_use]
pub const fn modes(mut self, file_mode: u16, dir_mode: u16) -> Self {
self.file_mode = file_mode;
self.dir_mode = dir_mode;
self
}
}
impl Default for Synthesis {
fn default() -> Self {
Self::new()
}
}
#[cfg(any(feature = "fat", feature = "exfat"))]
pub(crate) const WRITE_BITS: u16 = 0o222;
#[cfg(any(feature = "fat", feature = "exfat"))]
const SPECIAL_BITS: u16 = 0o7000;
#[cfg(any(feature = "fat", feature = "exfat"))]
const PERMISSION_BITS: u16 = 0o777;
#[cfg(any(feature = "fat", feature = "exfat"))]
#[derive(Clone, Copy, Debug, Default)]
pub(crate) struct LossPolicy {
pub accepted: AcceptedLoss,
pub synthesis: Synthesis,
}
#[cfg(any(feature = "fat", feature = "exfat"))]
impl LossPolicy {
pub(crate) fn record_losses(
&self,
report: &mut FidelityReport,
meta: &crate::source::Metadata,
xattrs: &[crate::xattr::Xattr],
darwin: Option<&crate::source::Darwin>,
is_dir: bool,
path: &[u8],
) -> Result<(), Property> {
let mut lose = |property: Property| -> Result<(), Property> {
if !self.accepted.contains(property) {
return Err(property);
}
report.record(Direction::Dropped, path, property);
Ok(())
};
if meta.uid != self.synthesis.uid || meta.gid != self.synthesis.gid {
lose(Property::Ownership)?;
}
if meta.mode & SPECIAL_BITS != 0 {
lose(Property::SpecialBits)?;
}
let mut recovered = if is_dir {
self.synthesis.dir_mode
} else {
self.synthesis.file_mode
};
if meta.mode & WRITE_BITS == 0 {
recovered &= !WRITE_BITS;
}
if meta.mode & PERMISSION_BITS != recovered & PERMISSION_BITS {
lose(Property::Permissions)?;
}
if meta.ctime != meta.mtime {
lose(Property::ChangeTime)?;
}
if !xattrs.is_empty() {
lose(Property::ExtendedAttributes)?;
}
if darwin.is_some_and(|d| d.stated_flags() != 0) {
lose(Property::BsdFlags)?;
}
Ok(())
}
pub(crate) const fn accepts(&self, property: Property) -> bool {
self.accepted.contains(property)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_empty_report_is_faithful() {
let report = FidelityReport::new();
assert!(report.is_faithful());
assert!(!report.is_truncated());
assert!(report.records().is_empty());
assert_eq!(report.to_table(), "nothing dropped or synthesized\n");
assert_eq!(FidelityReport::default(), report);
}
#[test]
fn a_record_names_the_entry_and_counts_the_property() {
let mut report = FidelityReport::new();
report.record(Direction::Dropped, b"/bin/ping", Property::SpecialBits);
report.record(Direction::Dropped, b"/bin/ping", Property::Ownership);
report.record(Direction::Dropped, b"/etc/passwd", Property::Ownership);
report.record(Direction::Synthesized, b"/", Property::Permissions);
assert!(!report.is_faithful());
assert_eq!(report.records().len(), 4);
assert_eq!(report.records()[0].path, b"/bin/ping");
assert_eq!(report.records()[0].property, Property::SpecialBits);
assert_eq!(report.count(Direction::Dropped, Property::Ownership), 2);
assert_eq!(report.count(Direction::Dropped, Property::SpecialBits), 1);
assert_eq!(
report.count(Direction::Synthesized, Property::Permissions),
1
);
assert_eq!(report.count(Direction::Dropped, Property::Kind), 0);
assert_eq!(
report.summary(),
vec![
(Direction::Dropped, Property::SpecialBits, 1),
(Direction::Dropped, Property::Ownership, 2),
(Direction::Synthesized, Property::Permissions, 1),
]
);
}
#[test]
fn the_counts_survive_truncation() {
let mut report = FidelityReport::new();
for i in 0..FidelityReport::MAX_RECORDS + 5 {
report.record(
Direction::Dropped,
format!("/f{i}").as_bytes(),
Property::Ownership,
);
}
assert!(report.is_truncated());
assert_eq!(report.records().len(), FidelityReport::MAX_RECORDS);
assert_eq!(
report.count(Direction::Dropped, Property::Ownership),
FidelityReport::MAX_RECORDS as u64 + 5
);
}
#[test]
fn an_accepted_loss_set_names_properties_rather_than_switching_everything() {
let precise = AcceptedLoss::NONE
.and(Property::Ownership)
.and(Property::Permissions);
assert!(precise.contains(Property::Ownership));
assert!(precise.contains(Property::Permissions));
assert!(!precise.contains(Property::Kind));
assert!(!precise.is_empty());
assert!(AcceptedLoss::NONE.is_empty());
assert!(!AcceptedLoss::NONE.contains(Property::Ownership));
assert_eq!(AcceptedLoss::default(), AcceptedLoss::NONE);
let all_but_kind = AcceptedLoss::ALL.without(Property::Kind);
assert!(all_but_kind.contains(Property::Ownership));
assert!(!all_but_kind.contains(Property::Kind));
assert_eq!(precise.and(Property::Ownership), precise);
}
#[test]
fn every_property_has_a_bit_of_its_own_and_all_holds_every_one() {
const EVERY: [Property; 10] = [
Property::Ownership,
Property::Permissions,
Property::SpecialBits,
Property::Kind,
Property::ExtendedAttributes,
Property::AccessTime,
Property::ChangeTime,
Property::ModificationTime,
Property::TimePrecision,
Property::Name,
];
for (i, one) in EVERY.iter().enumerate() {
let only = AcceptedLoss::NONE.and(*one);
for (j, other) in EVERY.iter().enumerate() {
assert_eq!(
only.contains(*other),
i == j,
"{} and {} share a bit",
one.as_str(),
other.as_str()
);
}
assert!(AcceptedLoss::ALL.contains(*one));
}
}
#[test]
fn the_synthesis_defaults_are_the_conservative_ones() {
let s = Synthesis::new();
assert_eq!((s.uid, s.gid), (0, 0));
assert_eq!(s.file_mode, 0o644);
assert_eq!(s.dir_mode, 0o755);
assert_eq!(Synthesis::default(), s);
let named = Synthesis::new().owner(1000, 100).modes(0o600, 0o700);
assert_eq!((named.uid, named.gid), (1000, 100));
assert_eq!((named.file_mode, named.dir_mode), (0o600, 0o700));
}
}