use crate::fidelity::{Property, Synthesis};
use crate::finding::Family;
use crate::source::{Darwin, Metadata};
use crate::xattr::Xattr;
#[cfg(any(
feature = "tar",
all(feature = "dir", any(target_os = "linux", target_os = "android"))
))]
pub(crate) const BODY_WINDOW: usize = 1 << 20;
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum TreeError {
#[error("i/o error: {message}")]
#[non_exhaustive]
Io {
kind: std::io::ErrorKind,
message: String,
},
#[error("malformed {family} filesystem: {detail}", family = .family.as_str())]
#[non_exhaustive]
Malformed {
family: Family,
detail: String,
},
#[error("unsupported {family} filesystem: {detail}", family = .family.as_str())]
#[non_exhaustive]
Unsupported {
family: Family,
detail: String,
},
#[error("{family} read exceeded a limit: {detail}", family = .family.as_str())]
#[non_exhaustive]
LimitExceeded {
family: Family,
bound: Bound,
detail: String,
},
#[error(
"no such path in the {family} filesystem: {}",
crate::escape::printable(.path),
family = .family.as_str()
)]
#[non_exhaustive]
NotFound {
family: Family,
path: Vec<u8>,
},
}
impl TreeError {
pub(crate) fn limit(family: Family, bound: Bound, reason: &impl std::fmt::Display) -> Self {
TreeError::LimitExceeded {
family,
bound,
detail: reason.to_string(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum Bound {
FileBytes,
Entries,
PathBytes,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum NodeKind {
Directory,
File {
size: u64,
},
Symlink,
CharDevice {
major: u32,
minor: u32,
},
BlockDevice {
major: u32,
minor: u32,
},
Fifo,
Socket,
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Child<N> {
pub name: Vec<u8>,
pub kind: NodeKind,
pub node: N,
}
impl<N> Child<N> {
pub fn new(name: Vec<u8>, kind: NodeKind, node: N) -> Self {
Self { name, kind, node }
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Usage {
pub unit: u64,
pub total: u64,
pub free: u64,
}
impl Usage {
pub fn new(unit: u64, total: u64, free: u64) -> Self {
Self { unit, total, free }
}
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) fn listed<T>(
family: Family,
entries: impl IntoIterator<Item = (Vec<u8>, T)>,
) -> Result<Vec<(Vec<u8>, T)>, TreeError> {
let mut out = Vec::new();
for (name, keep) in entries {
if crate::path::is_dot_entry(&name) {
continue;
}
if crate::path::is_hostile_component(&name) {
return Err(TreeError::Malformed {
family,
detail: format!(
"a directory entry carries a name no directory can hold: {}",
crate::escape::printable(&name)
),
});
}
out.push((name, keep));
}
out.sort_by(|a, b| a.0.cmp(&b.0));
Ok(out)
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) fn last_name(path: &[u8]) -> Vec<u8> {
crate::path::canonical_parts(path)
.last()
.map_or_else(Vec::new, |name| name.to_vec())
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) fn not_a_directory(family: Family) -> TreeError {
TreeError::Malformed {
family,
detail: "the node is not a directory".to_string(),
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct TreeEntry<N> {
pub path: Vec<u8>,
pub kind: NodeKind,
pub shared: Option<u64>,
pub node: N,
}
impl<N> TreeEntry<N> {
#[must_use]
pub fn new(path: Vec<u8>, kind: NodeKind, node: N) -> Self {
Self {
path,
kind,
shared: None,
node,
}
}
#[must_use]
pub fn shared(mut self, id: u64) -> Self {
self.shared = Some(id);
self
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct Attributes {
pub meta: Metadata,
pub xattrs: Vec<Xattr>,
pub synthesized: Vec<Property>,
}
impl Attributes {
#[must_use]
pub fn read(meta: Metadata, xattrs: Vec<Xattr>) -> Self {
Self {
meta,
xattrs,
synthesized: Vec::new(),
}
}
#[cfg(any(feature = "fat", feature = "exfat"))]
pub(crate) fn from_read_only_bit(
synthesis: &Synthesis,
is_dir: bool,
read_only: bool,
times: Option<(
Option<crate::time::Timestamp>,
crate::time::Timestamp,
Option<crate::time::Timestamp>,
)>,
) -> Self {
let mut mode = if is_dir {
synthesis.dir_mode
} else {
synthesis.file_mode
};
if read_only {
mode &= !crate::fidelity::WRITE_BITS;
}
let zero = crate::time::Timestamp::from_secs(0);
let (atime, mtime, btime) = times.unwrap_or((None, zero, None));
let mut synthesized = vec![
Property::Ownership,
Property::Permissions,
Property::ChangeTime,
];
if atime.is_none() {
synthesized.push(Property::AccessTime);
}
if times.is_none() {
synthesized.push(Property::ModificationTime);
}
let atime = atime.unwrap_or(mtime);
Self {
meta: Metadata {
mode,
uid: synthesis.uid,
gid: synthesis.gid,
atime,
ctime: mtime,
mtime,
btime,
},
xattrs: Vec::new(),
synthesized,
}
}
}
pub trait FsTree {
type Node;
fn family(&self) -> Family;
fn max_file_bytes(&self) -> u64;
fn walk_tree<E, F>(&mut self, visit: F) -> Result<(), E>
where
E: From<TreeError>,
F: FnMut(&mut Self, TreeEntry<Self::Node>) -> Result<(), E>;
fn stat(&mut self, node: &Self::Node, synthesis: &Synthesis) -> Result<Attributes, TreeError>;
fn read_bytes(
&mut self,
node: &Self::Node,
offset: u64,
buf: &mut [u8],
) -> Result<usize, TreeError>;
fn darwin(&mut self, node: &Self::Node) -> Result<Option<Darwin>, TreeError> {
let _ = node;
Ok(None)
}
fn bsd_flags(&mut self, node: &Self::Node) -> Result<u32, TreeError> {
Ok(self.darwin(node)?.map_or(0, |darwin| darwin.bsd_flags))
}
fn link_target(&mut self, node: &Self::Node) -> Result<Vec<u8>, TreeError>;
fn find(&mut self, path: &[u8]) -> Result<Child<Self::Node>, TreeError>;
fn list(&mut self, dir: &Self::Node) -> Result<Vec<Child<Self::Node>>, TreeError>;
fn usage(&mut self) -> Result<Usage, TreeError>;
#[cfg_attr(
not(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
)),
allow(unreachable_code, unused_variables)
)]
fn check_file_size(&self, path: &[u8], size: u64) -> Result<(), TreeError> {
let cap = self.max_file_bytes();
if size > cap {
return Err(TreeError::limit(
self.family(),
Bound::FileBytes,
&format_args!(
"{}: the file is {size} bytes, more than the {cap}-byte cap this read is \
held to",
crate::escape::printable(path)
),
));
}
Ok(())
}
}
pub(crate) fn made_by_the_format(path: &[u8], family: Family) -> bool {
#[cfg(feature = "ext")]
if family == Family::Ext {
return path == b"/lost+found" || path.starts_with(b"/lost+found/");
}
let _ = (family, path);
false
}
#[cfg(any(
feature = "tar",
all(feature = "dir", any(target_os = "linux", target_os = "android"))
))]
pub(crate) fn flags_not_carried<T: FsTree>(tree: &mut T, node: &T::Node) -> Result<u32, TreeError> {
Ok(Darwin::new(tree.bsd_flags(node)?).stated_flags())
}
#[cfg(any(
feature = "ext",
feature = "fat",
feature = "exfat",
feature = "btrfs",
feature = "apfs"
))]
pub(crate) enum WalkFail<R, E> {
Read(R),
#[cfg_attr(
not(any(feature = "ext", feature = "btrfs", feature = "apfs")),
allow(dead_code)
)]
Tree(TreeError),
Visitor(E),
}
#[cfg(test)]
mod tests {
use super::{NodeKind, TreeEntry};
#[test]
fn an_entry_has_no_second_name_until_one_is_declared() {
let entry = TreeEntry::new(b"/etc/hostname".to_vec(), NodeKind::File { size: 9 }, 12u32);
assert_eq!(entry.shared, None);
assert_eq!(entry.node, 12);
assert_eq!(entry.shared(12).shared, Some(12));
}
#[cfg(all(
feature = "ext",
any(
feature = "tar",
all(feature = "dir", any(target_os = "linux", target_os = "android"))
)
))]
#[test]
fn lost_and_found_is_the_formats_own_on_ext_with_its_contents() {
use super::made_by_the_format;
use crate::finding::Family;
assert!(made_by_the_format(b"/lost+found", Family::Ext));
assert!(made_by_the_format(b"/lost+found/17", Family::Ext));
assert!(!made_by_the_format(b"/lost+found-old", Family::Ext));
assert!(!made_by_the_format(b"/etc/lost+found", Family::Ext));
}
#[cfg(all(
any(feature = "fat", feature = "exfat", feature = "btrfs"),
any(
feature = "tar",
all(feature = "dir", any(target_os = "linux", target_os = "android"))
)
))]
#[test]
fn lost_and_found_is_the_volumes_own_where_the_format_makes_none() {
use super::made_by_the_format;
use crate::finding::Family;
#[cfg(feature = "fat")]
assert!(!made_by_the_format(b"/lost+found", Family::Fat));
#[cfg(feature = "exfat")]
assert!(!made_by_the_format(b"/lost+found/kept", Family::ExFat));
#[cfg(feature = "btrfs")]
assert!(!made_by_the_format(b"/lost+found", Family::Btrfs));
}
}