use std::collections::{BTreeMap, HashMap};
use crate::acl::Acl;
use crate::feature::{FeatureSet, LARGE_FILE_MIN_SIZE};
use crate::ondisk::{
FileType, Inode, has_empty_name, longest_stored_name, split_for_storage, xattr_block_len,
};
use crate::path::canonical_parts;
use crate::source::{
Darwin, EntryKind, FileContent, MODE_TYPE_MASK, Metadata, Source, SourceEntry,
};
use crate::time::Timestamp;
use crate::xattr::Xattr;
const MAX_DEVICE_MAJOR: u32 = (1 << 12) - 1;
const MAX_DEVICE_MINOR: u32 = (1 << 20) - 1;
pub const ROOT_INO: u32 = 2;
pub const LOST_FOUND_INO: u32 = 11;
pub const FIRST_USER_INO: u32 = 12;
const FAST_SYMLINK_MAX: usize = 60;
const MAX_LINKS: u16 = 65000;
fn validate_darwin(path: &[u8], darwin: Option<&Darwin>) -> Result<(), ModelError> {
match darwin.map(Darwin::stated_flags) {
Some(flags) if flags != 0 => Err(ModelError::BsdFlagsNotHeld {
path: path.to_vec(),
flags,
}),
_ => Ok(()),
}
}
fn validate_mode(path: &[u8], mode: u16) -> Result<(), ModelError> {
if mode & MODE_TYPE_MASK != 0 {
return Err(ModelError::ModeCarriesFileType {
path: path.to_vec(),
mode,
});
}
Ok(())
}
#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ModelError {
#[error(
"{}: its contents are declared by length alone, and this writer reads a file's bytes \
itself",
crate::escape::printable(.path)
)]
#[non_exhaustive]
ContentsNotHeld {
path: Vec<u8>,
},
#[error("path is empty or names the root, where a name is required")]
EmptyPath,
#[error(
"entry {} has an invalid ACL: {source}",
crate::escape::printable(.path)
)]
#[non_exhaustive]
Acl {
path: Vec<u8>,
#[source]
source: crate::acl::AclError,
},
#[error("entry {} names the root but is not a directory", crate::escape::printable(.path))]
#[non_exhaustive]
RootNotDirectory {
path: Vec<u8>,
},
#[error("the first user inode {given} is below {floor}, the first non-reserved inode")]
#[non_exhaustive]
FirstUserInodeReserved {
given: u32,
floor: u32,
},
#[error(
"path {} has an invalid component {}",
crate::escape::printable(.path),
crate::escape::printable(.component)
)]
#[non_exhaustive]
InvalidComponent {
path: Vec<u8>,
component: Vec<u8>,
},
#[error("path {} is used by more than one entry", crate::escape::printable(.path))]
#[non_exhaustive]
Duplicate {
path: Vec<u8>,
},
#[error("path {} has no parent directory", crate::escape::printable(.path))]
#[non_exhaustive]
ParentMissing {
path: Vec<u8>,
},
#[error("path {} has a parent that is not a directory", crate::escape::printable(.path))]
#[non_exhaustive]
ParentNotDir {
path: Vec<u8>,
},
#[error("path {} is reserved", crate::escape::printable(.path))]
#[non_exhaustive]
ReservedPath {
path: Vec<u8>,
},
#[error(
"{}: mode {mode:#o} carries file-type bits, which the entry's kind supplies",
crate::escape::printable(.path)
)]
#[non_exhaustive]
ModeCarriesFileType {
path: Vec<u8>,
mode: u16,
},
#[error(
"{}: BSD flags {flags:#x} are a Darwin filesystem's, and this one holds none",
crate::escape::printable(.path)
)]
#[non_exhaustive]
BsdFlagsNotHeld {
path: Vec<u8>,
flags: u32,
},
#[error(
"{}: a 128-byte inode has no field for the birth time the entry states",
crate::escape::printable(.path)
)]
#[non_exhaustive]
BirthTimeNotHeld {
path: Vec<u8>,
},
#[error(
"hard link {} targets {}, which does not exist",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
HardlinkTargetMissing {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"hard link {} states extended attributes other than its target's, and attributes \
belong to the target",
crate::escape::printable(.path)
)]
#[non_exhaustive]
LinkCarriesXattrs {
path: Vec<u8>,
},
#[error(
"hard link {} targets {}, which is a directory",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
HardlinkTargetIsDirectory {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"hard link {} targets {} through a cycle of links",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
HardlinkCycle {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"hard link {} targets {}, which already holds the maximum links",
crate::escape::printable(.path),
crate::escape::printable(.target)
)]
#[non_exhaustive]
TooManyLinks {
path: Vec<u8>,
target: Vec<u8>,
},
#[error(
"symlink {} has a target of {len} bytes, more than a block holds",
crate::escape::printable(.path)
)]
#[non_exhaustive]
SymlinkTargetTooLong {
path: Vec<u8>,
len: usize,
},
#[error("symlink {} has an empty target", crate::escape::printable(.path))]
#[non_exhaustive]
EmptySymlinkTarget {
path: Vec<u8>,
},
#[error(
"symlink {} has a target containing an embedded NUL",
crate::escape::printable(.path)
)]
#[non_exhaustive]
SymlinkTargetHasNul {
path: Vec<u8>,
},
#[error(
"directory {} has {subdirs} subdirectories, past the {limit} a link count holds \
without the dir_nlink feature",
crate::escape::printable(.path)
)]
#[non_exhaustive]
DirectoryLinkCountOverflow {
path: Vec<u8>,
subdirs: u64,
limit: u16,
},
#[error(
"device {} has out-of-range numbers {major}:{minor}",
crate::escape::printable(.path)
)]
#[non_exhaustive]
DeviceNumberTooLarge {
path: Vec<u8>,
major: u32,
minor: u32,
},
#[error(
"entry {} has an extended attribute name longer than 255 bytes",
crate::escape::printable(.path)
)]
#[non_exhaustive]
XattrNameTooLong {
path: Vec<u8>,
},
#[error(
"entry {} has an invalid extended attribute name ({reason}): {}",
crate::escape::printable(.path),
crate::escape::printable(.name)
)]
#[non_exhaustive]
InvalidXattrName {
path: Vec<u8>,
name: Vec<u8>,
reason: &'static str,
},
#[error(
"entry {} has extended attributes spilling {needed} bytes past the inode, more than a block holds",
crate::escape::printable(.path)
)]
#[non_exhaustive]
XattrsTooLarge {
path: Vec<u8>,
needed: usize,
},
#[error(
"entry {} carries extended attributes, which the feature set cannot hold without \
ext_attr",
crate::escape::printable(.path)
)]
#[non_exhaustive]
XattrsWithoutFeature {
path: Vec<u8>,
},
#[error(
"file {} is {size} bytes, past the {limit} a regular file may reach without the \
large_file feature",
crate::escape::printable(.path)
)]
#[non_exhaustive]
FileTooLargeWithoutFeature {
path: Vec<u8>,
size: u64,
limit: u64,
},
#[error(
"entry {} has a timestamp of {secs}s + {nanos}ns outside the representable range",
crate::escape::printable(.path)
)]
#[non_exhaustive]
TimestampOutOfRange {
path: Vec<u8>,
secs: i64,
nanos: u32,
},
#[error(
"entry {} has a time of {secs}s + {nanos}ns, and a 128-byte inode holds whole seconds \
alone",
crate::escape::printable(.path)
)]
#[non_exhaustive]
FractionNotHeld {
path: Vec<u8>,
secs: i64,
nanos: u32,
},
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct DirChild {
pub name: Vec<u8>,
pub inode: u32,
pub file_type: FileType,
}
#[derive(Clone, PartialEq, Eq, Debug)]
pub enum Content {
Directory(Vec<DirChild>),
File(FileContent),
FastSymlink(Vec<u8>),
SlowSymlink(Vec<u8>),
Device {
major: u32,
minor: u32,
},
Special,
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct ModelInode {
pub number: u32,
pub mode: u16,
pub uid: u32,
pub gid: u32,
pub links_count: u16,
pub atime: Timestamp,
pub ctime: Timestamp,
pub mtime: Timestamp,
pub crtime: Timestamp,
pub xattrs: Vec<Xattr>,
pub content: Content,
}
impl ModelInode {
#[must_use]
pub fn is_dir(&self) -> bool {
matches!(self.content, Content::Directory(_))
}
fn file_type(&self) -> FileType {
match self.content {
Content::Directory(_) => FileType::Dir,
Content::File(_) => FileType::RegFile,
Content::FastSymlink(_) | Content::SlowSymlink(_) => FileType::Symlink,
Content::Device { .. } => match self.mode & MODE_TYPE_MASK {
0o020000 => FileType::CharDev,
_ => FileType::BlockDev,
},
Content::Special => match self.mode & MODE_TYPE_MASK {
0o140000 => FileType::Socket,
_ => FileType::Fifo,
},
}
}
}
#[derive(Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub struct FsModel {
pub inodes: BTreeMap<u32, ModelInode>,
pub first_free_inode: u32,
}
impl FsModel {
#[must_use]
pub fn used_inode_count(&self) -> u32 {
self.first_free_inode - 1
}
#[must_use]
pub fn root(&self) -> &ModelInode {
&self.inodes[&ROOT_INO]
}
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct ModelConfig {
pub block_size: u32,
pub inode_size: u16,
pub first_user_inode: u32,
pub default_time: Timestamp,
pub fixed_time: Option<Timestamp>,
pub dir_nlink: bool,
pub ext_attr: bool,
pub large_file: bool,
}
#[derive(Clone, Copy, Debug)]
struct Times {
atime: Timestamp,
ctime: Timestamp,
mtime: Timestamp,
crtime: Timestamp,
}
impl Times {
fn validate(&self, path: &[u8], inode_size: u16) -> Result<(), ModelError> {
let extra = crate::ondisk::extra_isize_for(inode_size);
let stored = if crate::ondisk::Inode::has_crtime(inode_size, extra) {
&[self.atime, self.ctime, self.mtime, self.crtime][..]
} else {
&[self.atime, self.ctime, self.mtime][..]
};
for &t in stored {
if crate::ondisk::time_is_representable(t, inode_size) {
continue;
}
let whole = Timestamp::from_secs(t.secs);
if t.nanos != 0 && crate::ondisk::time_is_representable(whole, inode_size) {
return Err(ModelError::FractionNotHeld {
path: path.to_vec(),
secs: t.secs,
nanos: t.nanos,
});
}
return Err(ModelError::TimestampOutOfRange {
path: path.to_vec(),
secs: t.secs,
nanos: t.nanos,
});
}
Ok(())
}
}
impl ModelConfig {
#[must_use]
pub fn new(feature: FeatureSet, first_user_inode: u32, default_time: Timestamp) -> Self {
Self {
block_size: feature.block_size,
inode_size: feature.inode_size,
first_user_inode,
default_time,
fixed_time: None,
dir_nlink: feature.has_dir_nlink(),
ext_attr: feature.has_ext_attr(),
large_file: feature.has_large_file(),
}
}
fn times(&self, meta: &Metadata, path: &[u8]) -> Result<Times, ModelError> {
let times = match self.fixed_time {
Some(t) => Times {
atime: t,
ctime: t,
mtime: t,
crtime: t,
},
None => {
let extra = crate::ondisk::extra_isize_for(self.inode_size);
if meta.btime.is_some() && !crate::ondisk::Inode::has_crtime(self.inode_size, extra)
{
return Err(ModelError::BirthTimeNotHeld {
path: path.to_vec(),
});
}
Times {
atime: meta.atime,
ctime: meta.ctime,
mtime: meta.mtime,
crtime: meta.btime.unwrap_or(meta.mtime),
}
}
};
times.validate(path, self.inode_size)?;
Ok(times)
}
fn base_time(&self) -> Times {
let t = self.fixed_time.unwrap_or(self.default_time);
Times {
atime: t,
ctime: t,
mtime: t,
crtime: t,
}
}
}
fn stored_xattrs(path: &[u8], xattrs: &[Xattr]) -> Result<Vec<Xattr>, ModelError> {
xattrs
.iter()
.map(|x| {
if x.name != Acl::ACCESS_NAME && x.name != Acl::DEFAULT_NAME {
return Ok(x.clone());
}
let acl = Acl::decode(&x.value).map_err(|source| ModelError::Acl {
path: path.to_vec(),
source,
})?;
Ok(Xattr {
name: x.name.clone(),
value: crate::ondisk::encode_acl(&acl),
})
})
.collect()
}
fn validate_xattrs(path: &[u8], xattrs: &[Xattr], config: &ModelConfig) -> Result<(), ModelError> {
if xattrs.is_empty() {
return Ok(());
}
if !config.ext_attr {
return Err(ModelError::XattrsWithoutFeature {
path: path.to_vec(),
});
}
for x in xattrs {
let reason = if has_empty_name(&x.name) {
Some("empty")
} else if x.name.contains(&0) {
Some("embedded NUL")
} else {
None
};
if let Some(reason) = reason {
return Err(ModelError::InvalidXattrName {
path: path.to_vec(),
name: x.name.clone(),
reason,
});
}
}
if let Some(name) = crate::xattr::repeated_name(xattrs) {
return Err(ModelError::InvalidXattrName {
path: path.to_vec(),
name: name.to_vec(),
reason: "duplicate",
});
}
if longest_stored_name(xattrs) > 255 {
return Err(ModelError::XattrNameTooLong {
path: path.to_vec(),
});
}
let region_len = Inode::inline_xattr_capacity_for(config.inode_size);
let (_, spilled) = split_for_storage(xattrs, region_len);
let needed = xattr_block_len(&spilled);
if !spilled.is_empty() && needed > config.block_size as usize {
return Err(ModelError::XattrsTooLarge {
path: path.to_vec(),
needed,
});
}
Ok(())
}
fn validate_file_size(path: &[u8], size: u64, config: &ModelConfig) -> Result<(), ModelError> {
if size >= LARGE_FILE_MIN_SIZE && !config.large_file {
return Err(ModelError::FileTooLargeWithoutFeature {
path: path.to_vec(),
size,
limit: LARGE_FILE_MIN_SIZE,
});
}
Ok(())
}
fn names_the_root(path: &[u8]) -> bool {
canonical_parts(path).is_empty()
}
fn components(path: &[u8]) -> Result<Vec<Vec<u8>>, ModelError> {
let mut out = Vec::new();
for part in canonical_parts(path) {
if part == b".." || part.len() > 255 || part.contains(&0) {
return Err(ModelError::InvalidComponent {
path: path.to_vec(),
component: part.to_vec(),
});
}
out.push(part.to_vec());
}
if out.is_empty() {
return Err(ModelError::EmptyPath);
}
Ok(out)
}
fn key(parts: &[Vec<u8>]) -> Vec<u8> {
parts.join(&b'/')
}
struct Normalized {
parts: Vec<Vec<u8>>,
entry: SourceEntry,
}
struct DirBuild {
parent: u32,
children: Vec<DirChild>,
path: Vec<u8>,
}
pub fn build_model(source: impl Source, config: ModelConfig) -> Result<FsModel, ModelError> {
let mut inodes: BTreeMap<u32, ModelInode> = BTreeMap::new();
let mut path_ino: BTreeMap<Vec<u8>, u32> = BTreeMap::new();
let mut dirs: BTreeMap<u32, DirBuild> = BTreeMap::new();
if config.first_user_inode < FIRST_USER_INO {
return Err(ModelError::FirstUserInodeReserved {
given: config.first_user_inode,
floor: FIRST_USER_INO,
});
}
config.base_time().validate(b"/", config.inode_size)?;
let mut root_entry: Option<SourceEntry> = None;
let mut normalized: Vec<Normalized> = Vec::new();
for entry in source.into_entries() {
if names_the_root(&entry.path) {
if root_entry.is_some() {
return Err(ModelError::Duplicate { path: entry.path });
}
if !matches!(entry.kind, EntryKind::Directory) {
return Err(ModelError::RootNotDirectory { path: entry.path });
}
root_entry = Some(entry);
continue;
}
let parts = components(&entry.path)?;
normalized.push(Normalized { parts, entry });
}
normalized.sort_by_key(|a| key(&a.parts));
let root = match &root_entry {
Some(entry) => {
let times = config.times(&entry.meta, &entry.path)?;
validate_mode(&entry.path, entry.meta.mode)?;
validate_darwin(&entry.path, entry.darwin.as_ref())?;
let xattrs = stored_xattrs(&entry.path, &entry.xattrs)?;
validate_xattrs(&entry.path, &xattrs, &config)?;
let mut root = dir_inode(ROOT_INO, 0o040000 | entry.meta.mode, times, xattrs);
root.uid = entry.meta.uid;
root.gid = entry.meta.gid;
root
}
None => dir_inode(ROOT_INO, 0o040755, config.base_time(), Vec::new()),
};
inodes.insert(ROOT_INO, root);
dirs.insert(
ROOT_INO,
DirBuild {
parent: ROOT_INO,
children: Vec::new(),
path: b"/".to_vec(),
},
);
path_ino.insert(Vec::new(), ROOT_INO);
inodes.insert(
LOST_FOUND_INO,
dir_inode(LOST_FOUND_INO, 0o040700, config.base_time(), Vec::new()),
);
dirs.insert(
LOST_FOUND_INO,
DirBuild {
parent: ROOT_INO,
children: Vec::new(),
path: b"/lost+found".to_vec(),
},
);
path_ino.insert(b"lost+found".to_vec(), LOST_FOUND_INO);
dirs.get_mut(&ROOT_INO)
.expect("root was just inserted")
.children
.push(DirChild {
name: b"lost+found".to_vec(),
inode: LOST_FOUND_INO,
file_type: FileType::Dir,
});
let mut next_ino = config.first_user_inode;
for n in &normalized {
if n.parts.first().map(Vec::as_slice) == Some(b"lost+found".as_slice()) {
return Err(ModelError::ReservedPath {
path: n.entry.path.clone(),
});
}
if matches!(n.entry.kind, EntryKind::HardLink { .. }) {
continue;
}
let path_key = key(&n.parts);
if path_ino.contains_key(&path_key) {
return Err(ModelError::Duplicate {
path: n.entry.path.clone(),
});
}
let (parent_ino, name) = resolve_parent(&n.parts, &path_ino, &dirs, &n.entry.path)?;
let ino = next_ino;
next_ino += 1;
let meta = &n.entry.meta;
let times = config.times(meta, &n.entry.path)?;
validate_mode(&n.entry.path, meta.mode)?;
validate_darwin(&n.entry.path, n.entry.darwin.as_ref())?;
let xattrs = stored_xattrs(&n.entry.path, &n.entry.xattrs)?;
validate_xattrs(&n.entry.path, &xattrs, &config)?;
let leaf = |mode: u16, content: Content| ModelInode {
number: ino,
mode,
uid: meta.uid,
gid: meta.gid,
links_count: 1,
atime: times.atime,
ctime: times.ctime,
mtime: times.mtime,
crtime: times.crtime,
xattrs: xattrs.clone(),
content,
};
match &n.entry.kind {
EntryKind::Directory => {
let mut dir = dir_inode(ino, 0o040000 | meta.mode, times, xattrs.clone());
dir.uid = meta.uid;
dir.gid = meta.gid;
inodes.insert(ino, dir);
dirs.insert(
ino,
DirBuild {
parent: parent_ino,
children: Vec::new(),
path: n.entry.path.clone(),
},
);
}
EntryKind::File(content) => {
if matches!(content, FileContent::Declared { .. }) {
return Err(ModelError::ContentsNotHeld {
path: n.entry.path.clone(),
});
}
validate_file_size(&n.entry.path, content.len(), &config)?;
inodes.insert(
ino,
leaf(0o100000 | meta.mode, Content::File(content.clone())),
);
}
EntryKind::Symlink(target) => {
if target.is_empty() {
return Err(ModelError::EmptySymlinkTarget {
path: n.entry.path.clone(),
});
}
if target.contains(&0) {
return Err(ModelError::SymlinkTargetHasNul {
path: n.entry.path.clone(),
});
}
if target.len() >= config.block_size as usize {
return Err(ModelError::SymlinkTargetTooLong {
path: n.entry.path.clone(),
len: target.len(),
});
}
let content = if target.len() < FAST_SYMLINK_MAX {
Content::FastSymlink(target.clone())
} else {
Content::SlowSymlink(target.clone())
};
inodes.insert(ino, leaf(0o120777, content));
}
EntryKind::CharDevice { major, minor } => {
check_device(&n.entry.path, *major, *minor)?;
let content = Content::Device {
major: *major,
minor: *minor,
};
inodes.insert(ino, leaf(0o020000 | meta.mode, content));
}
EntryKind::BlockDevice { major, minor } => {
check_device(&n.entry.path, *major, *minor)?;
let content = Content::Device {
major: *major,
minor: *minor,
};
inodes.insert(ino, leaf(0o060000 | meta.mode, content));
}
EntryKind::Fifo => {
inodes.insert(ino, leaf(0o010000 | meta.mode, Content::Special));
}
EntryKind::Socket => {
inodes.insert(ino, leaf(0o140000 | meta.mode, Content::Special));
}
EntryKind::HardLink { .. } => unreachable!("hard links handled in the second pass"),
}
let file_type = inodes[&ino].file_type();
path_ino.insert(path_key, ino);
dirs.get_mut(&parent_ino)
.expect("parent verified to be a directory")
.children
.push(DirChild {
name,
inode: ino,
file_type,
});
}
let mut links: BTreeMap<Vec<u8>, &Normalized> = BTreeMap::new();
for n in &normalized {
if !matches!(n.entry.kind, EntryKind::HardLink { .. }) {
continue;
}
let path_key = key(&n.parts);
if path_ino.contains_key(&path_key) || links.contains_key(&path_key) {
return Err(ModelError::Duplicate {
path: n.entry.path.clone(),
});
}
links.insert(path_key, n);
}
let mut resolved: HashMap<Vec<u8>, u32> = HashMap::new();
for (path_key, n) in &links {
let EntryKind::HardLink { target } = &n.entry.kind else {
unreachable!("only hard links were collected");
};
let target_ino = resolve_link(&n.entry.path, target, &path_ino, &links, &mut resolved)?;
if inodes[&target_ino].is_dir() {
return Err(ModelError::HardlinkTargetIsDirectory {
path: n.entry.path.clone(),
target: target.clone(),
});
}
if !n.entry.xattrs.is_empty() {
let stated = stored_xattrs(&n.entry.path, &n.entry.xattrs)?;
if !crate::xattr::same_xattrs(&stated, &inodes[&target_ino].xattrs) {
return Err(ModelError::LinkCarriesXattrs {
path: n.entry.path.clone(),
});
}
}
let (parent_ino, name) = resolve_parent(&n.parts, &path_ino, &dirs, &n.entry.path)?;
let target_inode = inodes
.get_mut(&target_ino)
.expect("hard-link target verified to exist");
if target_inode.links_count >= MAX_LINKS {
return Err(ModelError::TooManyLinks {
path: n.entry.path.clone(),
target: target.clone(),
});
}
target_inode.links_count += 1;
let file_type = target_inode.file_type();
path_ino.insert(path_key.clone(), target_ino);
dirs.get_mut(&parent_ino)
.expect("parent verified to be a directory")
.children
.push(DirChild {
name,
inode: target_ino,
file_type,
});
}
for (ino, build) in dirs {
let subdirs = build
.children
.iter()
.filter(|c| c.file_type == FileType::Dir)
.count();
let mut children = build.children;
children.sort_by(|a, b| a.name.cmp(&b.name));
let mut entries = Vec::with_capacity(children.len() + 2);
entries.push(DirChild {
name: b".".to_vec(),
inode: ino,
file_type: FileType::Dir,
});
entries.push(DirChild {
name: b"..".to_vec(),
inode: build.parent,
file_type: FileType::Dir,
});
entries.extend(children);
let links = 2 + subdirs as u64;
let links_count = if links > u64::from(MAX_LINKS) {
if !config.dir_nlink {
return Err(ModelError::DirectoryLinkCountOverflow {
path: build.path.clone(),
subdirs: subdirs as u64,
limit: MAX_LINKS,
});
}
1
} else {
links as u16
};
let inode = inodes
.get_mut(&ino)
.expect("inode inserted for this directory");
inode.links_count = links_count;
inode.content = Content::Directory(entries);
}
Ok(FsModel {
inodes,
first_free_inode: next_ino,
})
}
fn dir_inode(number: u32, mode: u16, times: Times, xattrs: Vec<Xattr>) -> ModelInode {
ModelInode {
number,
mode,
uid: 0,
gid: 0,
links_count: 2,
atime: times.atime,
ctime: times.ctime,
mtime: times.mtime,
crtime: times.crtime,
xattrs,
content: Content::Directory(Vec::new()),
}
}
fn check_device(path: &[u8], major: u32, minor: u32) -> Result<(), ModelError> {
if major > MAX_DEVICE_MAJOR || minor > MAX_DEVICE_MINOR {
return Err(ModelError::DeviceNumberTooLarge {
path: path.to_vec(),
major,
minor,
});
}
Ok(())
}
fn resolve_link(
path: &[u8],
target: &[u8],
path_ino: &BTreeMap<Vec<u8>, u32>,
links: &BTreeMap<Vec<u8>, &Normalized>,
resolved: &mut HashMap<Vec<u8>, u32>,
) -> Result<u32, ModelError> {
let mut trail: Vec<Vec<u8>> = Vec::new();
let mut hop = key(&components(target)?);
for _ in 0..=links.len() {
if let Some(&ino) = resolved.get(&hop).or_else(|| path_ino.get(&hop)) {
for walked in trail {
resolved.insert(walked, ino);
}
return Ok(ino);
}
let next = links
.get(&hop)
.ok_or_else(|| ModelError::HardlinkTargetMissing {
path: path.to_vec(),
target: target.to_vec(),
})?;
let EntryKind::HardLink { target: onward } = &next.entry.kind else {
unreachable!("only hard links were collected");
};
let onward = key(&components(onward)?);
trail.push(std::mem::replace(&mut hop, onward));
}
Err(ModelError::HardlinkCycle {
path: path.to_vec(),
target: target.to_vec(),
})
}
fn resolve_parent(
parts: &[Vec<u8>],
path_ino: &BTreeMap<Vec<u8>, u32>,
dirs: &BTreeMap<u32, DirBuild>,
path: &[u8],
) -> Result<(u32, Vec<u8>), ModelError> {
let (name, parent_parts) = parts
.split_last()
.expect("components() rejects empty paths");
let parent_ino =
*path_ino
.get(&key(parent_parts))
.ok_or_else(|| ModelError::ParentMissing {
path: path.to_vec(),
})?;
if !dirs.contains_key(&parent_ino) {
return Err(ModelError::ParentNotDir {
path: path.to_vec(),
});
}
Ok((parent_ino, name.clone()))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::source::{Metadata, TreeBuilder};
fn config() -> ModelConfig {
let cfg = ModelConfig::new(
FeatureSet::DEFAULT,
FIRST_USER_INO,
Timestamp::from_secs(1_700_000_000),
);
assert!(cfg.dir_nlink && cfg.ext_attr && cfg.large_file);
assert_eq!((cfg.block_size, cfg.inode_size), (4096, 256));
cfg
}
fn meta(mode: u16) -> Metadata {
Metadata::new(mode, Timestamp::from_secs(1_700_000_000))
}
fn minimal_acl() -> Vec<u8> {
use crate::acl::{AclEntry, AclQualifier};
Acl::new(vec![
AclEntry {
who: AclQualifier::UserObj,
perm: Acl::READ | Acl::WRITE,
},
AclEntry {
who: AclQualifier::GroupObj,
perm: Acl::READ,
},
AclEntry {
who: AclQualifier::Other,
perm: Acl::READ,
},
])
.expect("a well-formed ACL")
.encode()
}
fn model(src: TreeBuilder) -> FsModel {
build_model(src, config()).expect("model")
}
#[test]
fn the_canonical_key_is_the_key_the_model_itself_uses() {
for path in [
&b"/etc/hostname"[..],
b"//etc//hostname",
b"etc/./hostname",
b"etc/hostname/",
b"/a",
b"a/b/c/d/e",
b"/var/log/./messages",
] {
let theirs = key(&components(path).expect("the model accepts this path"));
assert_eq!(
crate::path::canonical_key(path),
theirs,
"{}: the shared key must be the model's",
String::from_utf8_lossy(path)
);
}
for root in [&b"/"[..], b"", b".", b"./", b"///"] {
assert!(names_the_root(root));
assert!(crate::path::canonical_key(root).is_empty());
}
}
#[test]
fn empty_source_has_root_and_lost_found() {
let m = model(TreeBuilder::new());
assert_eq!(m.inodes.len(), 2);
assert_eq!(m.first_free_inode, FIRST_USER_INO);
let root = m.root();
assert_eq!(root.mode, 0o040755);
assert_eq!(root.links_count, 3);
let lf = &m.inodes[&LOST_FOUND_INO];
assert_eq!(lf.mode, 0o040700);
assert_eq!(lf.links_count, 2);
}
#[test]
fn a_hard_link_stating_attributes_other_than_its_targets_is_refused() {
let time = Timestamp::from_secs(1_700_000_000);
let src = TreeBuilder::new()
.file(
b"/target".to_vec(),
b"x".to_vec(),
Metadata::new(0o644, time),
)
.hardlink(
b"/link".to_vec(),
b"/target".to_vec(),
Metadata::new(0o644, time),
)
.xattr(b"user.note".to_vec(), b"v".to_vec());
let err = build_model(src, config()).unwrap_err();
assert!(
matches!(err, ModelError::LinkCarriesXattrs { .. }),
"{err:?}"
);
let src = TreeBuilder::new()
.file(
b"/target".to_vec(),
b"x".to_vec(),
Metadata::new(0o644, time),
)
.xattr(b"user.note".to_vec(), b"v".to_vec())
.hardlink(
b"/link".to_vec(),
b"/target".to_vec(),
Metadata::new(0o644, time),
)
.xattr(b"user.note".to_vec(), b"v".to_vec());
let m = build_model(src, config()).expect("a repeated set states nothing new");
let target = m
.inodes
.values()
.find(|inode| inode.links_count == 2 && !inode.is_dir())
.expect("the target has two names");
assert_eq!(target.xattrs.len(), 1, "the one attribute, held once");
}
#[test]
fn a_mode_carrying_file_type_bits_is_rejected() {
let time = Timestamp::from_secs(1_700_000_000);
let src = TreeBuilder::new().file(
b"/f".to_vec(),
b"x".to_vec(),
Metadata::new(0o100_644, time),
);
let err = build_model(src, config()).unwrap_err();
assert!(
matches!(
err,
ModelError::ModeCarriesFileType {
mode: 0o100_644,
..
}
),
"expected ModeCarriesFileType, got {err:?}"
);
let src = TreeBuilder::new().directory(b"/".to_vec(), Metadata::new(0o040_755, time));
let err = build_model(src, config()).unwrap_err();
assert!(
matches!(err, ModelError::ModeCarriesFileType { .. }),
"expected ModeCarriesFileType for the root entry, got {err:?}"
);
}
#[test]
fn an_unrepresentable_entry_timestamp_is_rejected() {
let mut m = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000));
m.mtime = Timestamp::from_secs(crate::ondisk::TIME_SECS_MAX + 1);
let src = TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m);
let err = build_model(src, config()).unwrap_err();
assert!(
matches!(err, ModelError::TimestampOutOfRange { secs, .. } if secs == crate::ondisk::TIME_SECS_MAX + 1),
"expected TimestampOutOfRange, got {err:?}"
);
}
#[test]
fn a_birth_time_a_small_inode_has_no_field_for_is_refused() {
let born = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000))
.with_birth_time(Timestamp::from_secs(1_600_000_000));
let file = || TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), born);
let small = ModelConfig {
inode_size: 128,
..config()
};
assert!(matches!(
build_model(file(), small),
Err(ModelError::BirthTimeNotHeld { path }) if path == b"/f"
));
let fixed = ModelConfig {
fixed_time: Some(Timestamp::from_secs(1_500_000_000)),
..small
};
build_model(file(), fixed).expect("the fixed time over it");
let m = build_model(file(), config()).expect("held");
let crtime = m
.inodes
.values()
.find(|i| matches!(i.content, Content::File(_)))
.expect("the file")
.crtime;
assert_eq!(crtime, Timestamp::from_secs(1_600_000_000));
}
#[test]
fn a_time_a_small_inode_holds_no_field_for_is_rejected() {
let small = ModelConfig {
inode_size: 128,
..config()
};
let at = |mtime: Timestamp| {
let m = Metadata::new(0o644, Timestamp::from_secs(1_700_000_000));
let m = m.with_times(m.atime, m.ctime, mtime);
build_model(
TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m),
small,
)
};
let past = Timestamp::from_secs(i64::from(i32::MAX) + 1);
assert!(matches!(
at(past),
Err(ModelError::TimestampOutOfRange { secs, .. }) if secs == past.secs
));
let fraction = Timestamp {
secs: 1_700_000_000,
nanos: 1,
};
assert!(matches!(
at(fraction),
Err(ModelError::FractionNotHeld {
secs: 1_700_000_000,
nanos: 1,
..
})
));
at(Timestamp::from_secs(i64::from(i32::MAX))).expect("the field's last second");
let large = ModelConfig {
inode_size: 256,
..config()
};
let m = Metadata::new(0o644, past).with_times(fraction, fraction, past);
build_model(
TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), m),
large,
)
.expect("held");
let cfg = ModelConfig {
default_time: fraction,
..small
};
assert!(matches!(
build_model(TreeBuilder::new(), cfg),
Err(ModelError::FractionNotHeld { path, .. }) if path == b"/"
));
}
#[test]
fn an_unrepresentable_default_time_is_rejected() {
let cfg = ModelConfig {
default_time: Timestamp::from_secs(crate::ondisk::TIME_SECS_MIN - 1),
..config()
};
let err = build_model(TreeBuilder::new(), cfg).unwrap_err();
assert!(matches!(err, ModelError::TimestampOutOfRange { .. }));
}
#[test]
fn root_entries_begin_with_dot_and_dotdot() {
let m = model(TreeBuilder::new());
let Content::Directory(children) = &m.root().content else {
panic!("root is a directory");
};
assert_eq!(children[0].name, b".");
assert_eq!(children[0].inode, ROOT_INO);
assert_eq!(children[1].name, b"..");
assert_eq!(children[1].inode, ROOT_INO, "root's .. points at itself");
assert_eq!(children[2].name, b"lost+found");
}
#[test]
fn inode_numbers_are_deterministic_in_sorted_path_order() {
let m = model(
TreeBuilder::new()
.directory(b"/b".to_vec(), meta(0o755))
.directory(b"/a".to_vec(), meta(0o755))
.file(b"/a/z".to_vec(), b"z".to_vec(), meta(0o644))
.file(b"/a/y".to_vec(), b"y".to_vec(), meta(0o644)),
);
assert_eq!(*m.inodes.keys().max().unwrap(), 15);
let a = m.inodes.values().find(|i| i.number == 12).unwrap();
assert!(a.is_dir());
}
#[test]
fn subdirectories_raise_the_parent_link_count() {
let m = model(
TreeBuilder::new()
.directory(b"/a".to_vec(), meta(0o755))
.directory(b"/a/sub1".to_vec(), meta(0o755))
.directory(b"/a/sub2".to_vec(), meta(0o755)),
);
let a = m.inodes.values().find(|i| matches!(&i.content, Content::Directory(c) if c.iter().any(|e| e.name == b"sub1"))).unwrap();
assert_eq!(a.links_count, 4);
assert_eq!(m.root().links_count, 4);
}
#[test]
fn hardlinks_coalesce_onto_one_inode() {
let m = model(
TreeBuilder::new()
.file(b"/a".to_vec(), b"data".to_vec(), meta(0o644))
.hardlink(b"/b".to_vec(), b"/a".to_vec(), meta(0o644)),
);
let files: Vec<_> = m
.inodes
.values()
.filter(|i| matches!(i.content, Content::File(_)))
.collect();
assert_eq!(files.len(), 1);
assert_eq!(files[0].links_count, 2);
let Content::Directory(root) = &m.root().content else {
unreachable!()
};
let a = root.iter().find(|e| e.name == b"a").unwrap().inode;
let b = root.iter().find(|e| e.name == b"b").unwrap().inode;
assert_eq!(a, b);
}
#[test]
fn symlink_form_follows_target_length() {
let short = vec![b'x'; 59];
let long = vec![b'x'; 60];
let m = model(
TreeBuilder::new()
.symlink(b"/short".to_vec(), short.clone(), meta(0o777))
.symlink(b"/long".to_vec(), long.clone(), meta(0o777)),
);
let s = m
.inodes
.values()
.find(|i| matches!(&i.content, Content::FastSymlink(t) if *t == short));
let l = m
.inodes
.values()
.find(|i| matches!(&i.content, Content::SlowSymlink(t) if *t == long));
assert!(s.is_some(), "59-byte target is a fast symlink");
assert!(l.is_some(), "60-byte target is a slow symlink");
assert_eq!(s.unwrap().mode, 0o120777);
}
#[test]
fn a_symlink_target_with_an_embedded_nul_is_rejected() {
let err = build_model(
TreeBuilder::new().symlink(b"/link".to_vec(), b"a\0b".to_vec(), meta(0o777)),
config(),
)
.unwrap_err();
assert!(
matches!(err, ModelError::SymlinkTargetHasNul { .. }),
"an embedded NUL must be a typed error, got {err:?}"
);
}
#[test]
fn a_directory_past_the_link_limit_requires_dir_nlink() {
let build = || {
let mut b = TreeBuilder::new().directory(b"/d".to_vec(), meta(0o755));
for i in 0..64_999u32 {
b = b.directory(format!("/d/{i:05}").into_bytes(), meta(0o755));
}
b
};
let cfg_off = ModelConfig {
dir_nlink: false,
..config()
};
let err = build_model(build(), cfg_off).unwrap_err();
assert!(
matches!(
err,
ModelError::DirectoryLinkCountOverflow { subdirs, limit, .. }
if subdirs == 64_999 && limit == 65_000
),
"without dir_nlink the overflow must be a typed error, got {err:?}"
);
let m = build_model(build(), config()).expect("dir_nlink permits the overflow");
let d = m
.inodes
.values()
.find(|i| matches!(&i.content, Content::Directory(e) if e.len() > 65_000))
.expect("the large directory is present");
assert_eq!(d.links_count, 1, "the dir_nlink sentinel");
}
#[test]
fn ownership_and_mode_are_preserved() {
let m = model(TreeBuilder::new().file(
b"/f".to_vec(),
b"x".to_vec(),
meta(0o4755).owned_by(1000, 2000),
));
let f = m
.inodes
.values()
.find(|i| matches!(i.content, Content::File(_)))
.unwrap();
assert_eq!(f.mode, 0o104755, "setuid bit and perms preserved");
assert_eq!(f.uid, 1000);
assert_eq!(f.gid, 2000);
}
#[test]
fn missing_parent_is_rejected() {
let err = build_model(
TreeBuilder::new().file(b"/nodir/f".to_vec(), b"x".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert!(matches!(err, ModelError::ParentMissing { .. }));
}
#[test]
fn parent_that_is_a_file_is_rejected() {
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"x".to_vec(), meta(0o644))
.file(b"/f/child".to_vec(), b"y".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert!(matches!(err, ModelError::ParentNotDir { .. }));
}
#[test]
fn reserved_and_duplicate_and_dotdot_paths_are_rejected() {
assert!(matches!(
build_model(
TreeBuilder::new().directory(b"/lost+found".to_vec(), meta(0o700)),
config()
),
Err(ModelError::ReservedPath { .. })
));
assert!(matches!(
build_model(
TreeBuilder::new()
.file(b"/a".to_vec(), b"1".to_vec(), meta(0o644))
.hardlink(b"/lost+found/x".to_vec(), b"/a".to_vec(), meta(0o644)),
config()
),
Err(ModelError::ReservedPath { .. })
));
assert!(matches!(
build_model(
TreeBuilder::new()
.file(b"/a".to_vec(), b"1".to_vec(), meta(0o644))
.file(b"/a".to_vec(), b"2".to_vec(), meta(0o644)),
config()
),
Err(ModelError::Duplicate { .. })
));
assert!(matches!(
build_model(
TreeBuilder::new().file(b"/a/../b".to_vec(), b"x".to_vec(), meta(0o644)),
config()
),
Err(ModelError::InvalidComponent { .. })
));
}
#[test]
fn hardlink_to_a_directory_is_rejected() {
let err = build_model(
TreeBuilder::new()
.directory(b"/d".to_vec(), meta(0o755))
.hardlink(b"/l".to_vec(), b"/d".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert!(matches!(err, ModelError::HardlinkTargetIsDirectory { .. }));
}
#[test]
fn hardlink_resolves_regardless_of_order() {
let m = model(
TreeBuilder::new()
.hardlink(b"/aaa".to_vec(), b"/zzz".to_vec(), meta(0o644))
.file(b"/zzz".to_vec(), b"data".to_vec(), meta(0o644)),
);
let files: Vec<_> = m
.inodes
.values()
.filter(|i| matches!(i.content, Content::File(_)))
.collect();
assert_eq!(files.len(), 1);
assert_eq!(files[0].links_count, 2);
}
#[test]
fn a_hardlink_names_any_kind_but_a_directory() {
let m = model(
TreeBuilder::new()
.symlink(b"/sym".to_vec(), b"/target".to_vec(), meta(0o777))
.hardlink(b"/sym-link".to_vec(), b"/sym".to_vec(), meta(0o777))
.char_device(b"/null".to_vec(), 1, 3, meta(0o666))
.hardlink(b"/null-link".to_vec(), b"/null".to_vec(), meta(0o666))
.fifo(b"/pipe".to_vec(), meta(0o644))
.hardlink(b"/pipe-link".to_vec(), b"/pipe".to_vec(), meta(0o644)),
);
let Content::Directory(root) = &m.root().content else {
unreachable!()
};
let child = |name: &[u8]| root.iter().find(|e| e.name == name).expect("entry");
for (link, target, file_type) in [
(&b"/sym-link"[..], &b"/sym"[..], FileType::Symlink),
(b"/null-link", b"/null", FileType::CharDev),
(b"/pipe-link", b"/pipe", FileType::Fifo),
] {
let link = child(&link[1..]);
let target = child(&target[1..]);
assert_eq!(link.inode, target.inode, "the link shares the inode");
assert_eq!(link.file_type, file_type);
assert_eq!(m.inodes[&link.inode].links_count, 2);
}
}
#[test]
fn a_hardlink_to_a_hardlink_resolves_to_the_inode_beneath_both() {
let m = model(
TreeBuilder::new()
.hardlink(b"/a".to_vec(), b"/b".to_vec(), meta(0o644))
.hardlink(b"/b".to_vec(), b"/c".to_vec(), meta(0o644))
.file(b"/c".to_vec(), b"data".to_vec(), meta(0o644)),
);
let files: Vec<_> = m
.inodes
.values()
.filter(|i| matches!(i.content, Content::File(_)))
.collect();
assert_eq!(files.len(), 1, "all three names share one inode");
assert_eq!(files[0].links_count, 3);
}
#[test]
fn a_cycle_of_hardlinks_is_rejected() {
let err = build_model(
TreeBuilder::new()
.hardlink(b"/a".to_vec(), b"/b".to_vec(), meta(0o644))
.hardlink(b"/b".to_vec(), b"/a".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert!(
matches!(err, ModelError::HardlinkCycle { .. }),
"expected HardlinkCycle, got {err:?}"
);
}
#[test]
fn an_empty_nul_or_duplicate_xattr_name_is_rejected() {
for (name, reason) in [
(&b""[..], "empty"),
(b"user.", "empty"),
(b"user.a\0b", "embedded NUL"),
] {
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(name.to_vec(), b"v".to_vec()),
config(),
)
.unwrap_err();
assert!(
matches!(&err, ModelError::InvalidXattrName { reason: r, .. } if *r == reason),
"name {:?} should be rejected as {reason}, got {err:?}",
String::from_utf8_lossy(name)
);
}
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(b"user.a".to_vec(), b"1".to_vec())
.xattr(b"user.a".to_vec(), b"2".to_vec()),
config(),
)
.unwrap_err();
assert!(
matches!(
err,
ModelError::InvalidXattrName {
reason: "duplicate",
..
}
),
"a duplicate xattr name should be rejected, got {err:?}"
);
}
#[test]
fn a_xattr_set_larger_than_one_block_is_accepted_when_it_splits() {
let m = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(b"user.huge".to_vec(), vec![0xAA; 4040])
.xattr(b"user.tiny".to_vec(), vec![0xBB; 60]),
config(),
)
.expect("a set that fits split across the inode and one block");
let f = m
.inodes
.values()
.find(|i| matches!(i.content, Content::File(_)))
.unwrap();
assert_eq!(f.xattrs.len(), 2, "both attributes reach the inode");
}
#[test]
fn a_xattr_spill_no_block_holds_is_rejected() {
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(b"user.huge".to_vec(), vec![0xAA; 4041])
.xattr(b"user.tiny".to_vec(), vec![0xBB; 60]),
config(),
)
.unwrap_err();
assert!(
matches!(err, ModelError::XattrsTooLarge { needed: 4100, .. }),
"the spill alone overflows a block, got {err:?}"
);
}
#[test]
fn attributes_on_a_profile_without_ext_attr_are_refused() {
let cfg = ModelConfig {
ext_attr: false,
..config()
};
let src = || {
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(b"user.a".to_vec(), b"1".to_vec())
};
let err = build_model(src(), cfg).unwrap_err();
assert!(
matches!(
err,
ModelError::XattrsWithoutFeature { ref path } if path == b"/f"
),
"expected XattrsWithoutFeature naming the entry, got {err:?}"
);
build_model(src(), config()).expect("ext_attr holds the same set");
build_model(
TreeBuilder::new().file(b"/f".to_vec(), b"data".to_vec(), meta(0o644)),
cfg,
)
.expect("an entry with no attributes needs no feature");
}
#[test]
fn a_regular_file_past_the_large_file_bound_requires_the_feature() {
let with = config();
let without = ModelConfig {
large_file: false,
..config()
};
let at = LARGE_FILE_MIN_SIZE;
assert!(validate_file_size(b"/f", at - 1, &without).is_ok());
let err = validate_file_size(b"/f", at, &without).unwrap_err();
assert!(
matches!(
err,
ModelError::FileTooLargeWithoutFeature { size, limit, ref path }
if size == LARGE_FILE_MIN_SIZE && limit == LARGE_FILE_MIN_SIZE && path == b"/f"
),
"expected FileTooLargeWithoutFeature naming the file, got {err:?}"
);
assert!(validate_file_size(b"/f", at, &with).is_ok());
}
#[test]
fn an_acl_xattr_name_with_an_empty_stored_name_is_accepted() {
build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(b"system.posix_acl_access".to_vec(), minimal_acl()),
config(),
)
.expect("a whole-name ACL attribute is a valid, non-empty name");
}
#[test]
fn an_acl_attribute_is_narrowed_to_the_form_ext_stores() {
let m = model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(Acl::ACCESS_NAME.to_vec(), minimal_acl()),
);
let stored = &m
.inodes
.values()
.find(|i| i.xattrs.iter().any(|x| x.name == Acl::ACCESS_NAME))
.expect("the file carries the ACL")
.xattrs[0];
assert_eq!(
stored.value,
crate::ondisk::encode_acl(&Acl::decode(&minimal_acl()).expect("the stated ACL"))
);
assert!(
stored.value.len() < minimal_acl().len(),
"the stored form is the narrower one"
);
}
#[test]
fn an_acl_attribute_already_in_the_stored_form_is_refused_rather_than_narrowed_twice() {
let compact = crate::ondisk::encode_acl(&Acl::decode(&minimal_acl()).expect("an ACL"));
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(Acl::ACCESS_NAME.to_vec(), compact),
config(),
)
.expect_err("the stored form is not a value a source may state");
assert!(matches!(err, ModelError::Acl { .. }), "{err:?}");
}
#[test]
fn an_acl_attribute_that_is_not_an_acl_is_refused() {
let err = build_model(
TreeBuilder::new()
.file(b"/f".to_vec(), b"data".to_vec(), meta(0o644))
.xattr(Acl::ACCESS_NAME.to_vec(), b"not an ACL".to_vec()),
config(),
)
.expect_err("a value that is not an ACL is refused");
assert!(matches!(err, ModelError::Acl { .. }), "{err:?}");
}
#[test]
fn a_root_entry_supplies_the_root_directorys_metadata() {
let m = model(
TreeBuilder::new()
.root(meta(0o700).owned_by(1000, 2000))
.xattr(b"user.label".to_vec(), b"rootfs".to_vec())
.file(b"/f".to_vec(), b"x".to_vec(), meta(0o644)),
);
let root = m.root();
assert_eq!(root.mode, 0o040700);
assert_eq!((root.uid, root.gid), (1000, 2000));
assert_eq!(root.xattrs[0].name, b"user.label");
assert_eq!(root.links_count, 3, "., lost+found's .., and its own");
assert_eq!(
m.first_free_inode, 13,
"the root entry consumed no inode number"
);
}
#[test]
fn entries_begin_at_the_configured_first_user_inode() {
let cfg = ModelConfig {
first_user_inode: FIRST_USER_INO + 1,
..config()
};
let src = TreeBuilder::new().file(b"/f".to_vec(), b"x".to_vec(), meta(0o644));
let m = build_model(src, cfg).expect("model");
let f = m
.inodes
.values()
.find(|i| matches!(i.content, Content::File(_)))
.unwrap();
assert_eq!(f.number, 13, "the entry sits above the claimed inode");
assert_eq!(m.first_free_inode, 14);
assert_eq!(
m.used_inode_count(),
13,
"the claimed inode is counted as in use, though the model never holds it"
);
}
#[test]
fn a_first_user_inode_inside_the_reserved_range_is_rejected() {
let cfg = ModelConfig {
first_user_inode: LOST_FOUND_INO,
..config()
};
let err = build_model(TreeBuilder::new(), cfg).unwrap_err();
assert!(matches!(
err,
ModelError::FirstUserInodeReserved { given, floor }
if given == LOST_FOUND_INO && floor == FIRST_USER_INO
));
}
#[test]
fn a_root_entry_that_is_not_a_directory_is_rejected() {
let err = build_model(
TreeBuilder::new().file(b"/".to_vec(), b"x".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert!(matches!(err, ModelError::RootNotDirectory { .. }));
}
#[test]
fn a_second_root_entry_is_a_duplicate() {
let err = build_model(
TreeBuilder::new()
.root(meta(0o755))
.directory(b".".to_vec(), meta(0o700)),
config(),
)
.unwrap_err();
assert!(matches!(err, ModelError::Duplicate { .. }));
}
#[test]
fn an_error_message_names_the_path_as_text() {
let err = build_model(
TreeBuilder::new().file(b"/etc/hostname".to_vec(), b"x".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert_eq!(
err.to_string(),
"path /etc/hostname has no parent directory"
);
let err = build_model(
TreeBuilder::new().file(b"/\xff\xfe/x".to_vec(), b"x".to_vec(), meta(0o644)),
config(),
)
.unwrap_err();
assert_eq!(
err.to_string(),
"path /\u{fffd}\u{fffd}/x has no parent directory"
);
}
}