use std::collections::BTreeMap;
use std::collections::btree_map::Entry;
use std::ffi::{CStr, CString, OsStr};
use std::fs::File;
use std::os::fd::{AsFd, AsRawFd};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rustix::fs::{Mode, OFlags};
use rustix::io::Errno;
mod sink;
pub use sink::{DirectorySink, ExtractReport};
use crate::acl::Acl;
use crate::escape::{printable, printable_path};
use crate::path::canonical_parts;
use crate::source::{EntryKind, FileContent, FileRange, Metadata, Source, SourceEntry};
use crate::time::Timestamp;
use crate::xattr::Xattr;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum HostError {
#[error("{}: {source}", printable_path(.path))]
#[non_exhaustive]
Io {
path: PathBuf,
#[source]
source: std::io::Error,
},
#[error("{}: not a directory", printable_path(.path))]
#[non_exhaustive]
NotADirectory {
path: PathBuf,
},
#[error(
"{}: has a file type that cannot be written to a filesystem",
printable_path(.path)
)]
#[non_exhaustive]
Unsupported {
path: PathBuf,
},
#[error("{}: has an invalid ACL: {source}", printable_path(.path))]
#[non_exhaustive]
Acl {
path: PathBuf,
#[source]
source: crate::acl::AclError,
},
#[error(
"{}: the {} kept changing while it was read, across {attempts} attempts",
printable_path(.path),
unstable_subject(.name)
)]
#[non_exhaustive]
UnstableXattrs {
path: PathBuf,
name: Option<Vec<u8>>,
attempts: usize,
},
#[error(transparent)]
#[non_exhaustive]
Read {
source: crate::tree::TreeError,
},
#[error(
"{}: the image records {size} bytes and its storage yielded {got}",
crate::escape::printable(.path)
)]
#[non_exhaustive]
ShortRead {
path: Vec<u8>,
size: u64,
got: u64,
},
#[error("{}: is not empty", printable_path(.path))]
#[non_exhaustive]
NotEmpty {
path: PathBuf,
},
#[error(
"{}: is a name that cannot be written into a directory",
printable(.path)
)]
#[non_exhaustive]
HostileName {
path: Vec<u8>,
},
#[error(
"{}: arrived before the directory that holds it, so there is no directory to \
create it in",
printable(.path)
)]
#[non_exhaustive]
OutOfOrder {
path: Vec<u8>,
},
#[error(
"more than {limit} directories are waiting for their metadata: this filesystem \
defers a directory whose mode denies its owner search permission, and holds its \
handle until the walk is over"
)]
#[non_exhaustive]
TooManyDeferredDirectories {
limit: usize,
},
#[error(
"{}: this host will not hold {}, whatever privilege the process has: {why}",
printable(.path),
printable(.name)
)]
#[non_exhaustive]
UnsupportedAttribute {
path: Vec<u8>,
name: Vec<u8>,
why: &'static str,
},
#[error(
"{}: the destination will not hold {what}, whatever privilege the process has",
printable(.path)
)]
#[non_exhaustive]
NameTooLong {
path: Vec<u8>,
what: &'static str,
},
#[error("{}: {what}", printable(.path))]
#[non_exhaustive]
Unprivileged {
path: Vec<u8>,
what: &'static str,
},
#[error(
"{}: records owner {uid}:{gid}, which cannot be set",
printable(.path)
)]
#[non_exhaustive]
UnrepresentableOwner {
path: Vec<u8>,
uid: u32,
gid: u32,
},
#[error(
"{}: records device {major}:{minor}, which this host makes as another device",
printable(.path)
)]
#[non_exhaustive]
UnrepresentableDevice {
path: Vec<u8>,
major: u32,
minor: u32,
},
#[error(
"{}: records BSD flags {flags:#x}, which this destination does not hold",
printable(.path)
)]
#[non_exhaustive]
FlagsNotHeld {
path: Vec<u8>,
flags: u32,
},
#[error(
"{}: its {which} time is {} in the image, and this destination holds it as {}",
printable(.path),
seconds(.recorded),
seconds(.held)
)]
#[non_exhaustive]
TimeNotHeld {
path: Vec<u8>,
which: &'static str,
recorded: Timestamp,
held: Timestamp,
},
#[error(
"{}: is the same directory as {} — walking it again would write that subtree \
into the image a second time, and a mount of an ancestor would never end",
printable_path(.path),
printable_path(.first)
)]
#[non_exhaustive]
RepeatedDirectory {
path: PathBuf,
first: PathBuf,
},
#[error(
"{}: was replaced while the tree was walked",
printable_path(.path)
)]
#[non_exhaustive]
Replaced {
path: PathBuf,
},
}
fn unstable_subject(name: &Option<Vec<u8>>) -> String {
match name {
Some(name) => format!("extended attribute {}", printable(name)),
None => "list of extended attributes".to_string(),
}
}
fn seconds(t: &Timestamp) -> String {
format!("{} s {} ns", t.secs, t.nanos)
}
pub struct DirectorySource {
entries: Vec<SourceEntry>,
}
impl DirectorySource {
pub fn from_path(root: impl AsRef<Path>) -> Result<Self, HostError> {
let root = root.as_ref();
let root_dir = rustix::fs::open(
root,
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map(File::from)
.map_err(|e| match e {
Errno::NOTDIR => HostError::NotADirectory {
path: root.to_path_buf(),
},
e => io_at(root)(e.into()),
})?;
let meta = root_dir.metadata().map_err(io_at(root))?;
let xattrs = xattrs_of(&Attrs::Open(&root_dir), root)?;
let names = names_in(&root_dir).map_err(io_at(root))?;
let root_dir = Arc::new(root_dir);
let mut entered: BTreeMap<(u64, u64), PathBuf> =
BTreeMap::from([((meta.dev(), meta.ino()), root.to_path_buf())]);
let mut found = vec![Found {
image: b"/".to_vec(),
meta,
kind: EntryKind::Directory,
xattrs,
}];
let mut stack = vec![Frame {
dir: Arc::clone(&root_dir),
names: names.into_iter(),
image: b"/".to_vec(),
host: root.to_path_buf(),
relative: Vec::new(),
}];
while let Some(frame) = stack.last_mut() {
let Some(name) = frame.names.next() else {
stack.pop();
continue;
};
let host_path = frame.host.join(OsStr::from_bytes(name.to_bytes()));
let image_path = join(&frame.image, name.to_bytes());
let relative = if frame.relative.is_empty() {
name.to_bytes().to_vec()
} else {
join(&frame.relative, name.to_bytes())
};
let node = rustix::fs::openat(
&*frame.dir,
&*name,
OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)
.map(File::from)
.map_err(|e| io_at(&host_path)(e.into()))?;
let meta = node.metadata().map_err(io_at(&host_path))?;
let file_type = meta.file_type();
let mut child = None;
let (kind, xattrs) = if file_type.is_dir() {
match entered.entry((meta.dev(), meta.ino())) {
Entry::Occupied(first) => {
return Err(HostError::RepeatedDirectory {
path: host_path,
first: first.get().clone(),
});
}
Entry::Vacant(slot) => {
slot.insert(host_path.clone());
}
}
let dir = rustix::fs::openat(
&node,
c".",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
)
.map(File::from)
.map_err(|e| io_at(&host_path)(e.into()))?;
let xattrs = xattrs_of(&Attrs::Open(&dir), &host_path)?;
let names = names_in(&dir).map_err(io_at(&host_path))?;
child = Some(Frame {
dir: Arc::new(dir),
names: names.into_iter(),
image: image_path.clone(),
host: host_path.clone(),
relative: relative.clone(),
});
(EntryKind::Directory, xattrs)
} else if file_type.is_file() {
let xattrs = file_xattrs(&frame.dir, &name, &meta, &host_path)?;
let walked = Walked {
root: Arc::clone(&root_dir),
relative: relative.into(),
identity: (meta.dev(), meta.ino()),
};
let range = FileRange::walked(walked, &host_path, 0, meta.len());
(EntryKind::File(FileContent::Range(range)), xattrs)
} else {
let kind = kind_of(&node, &meta, &host_path)?;
let named = fd_path(&*frame.dir, name.to_bytes());
(kind, xattrs_of(&Attrs::Named(&named), &host_path)?)
};
found.push(Found {
image: image_path,
meta,
kind,
xattrs,
});
if let Some(child) = child {
stack.push(child);
}
}
found.sort_by(|a, b| a.image.cmp(&b.image));
let mut first_name: BTreeMap<(u64, u64), Vec<u8>> = BTreeMap::new();
let mut entries = Vec::with_capacity(found.len());
for Found {
image,
meta,
mut kind,
mut xattrs,
} in found
{
if !meta.is_dir() && meta.nlink() > 1 {
match first_name.entry((meta.dev(), meta.ino())) {
Entry::Occupied(held) => {
kind = EntryKind::HardLink {
target: held.get().clone(),
};
xattrs = Vec::new();
}
Entry::Vacant(slot) => {
slot.insert(image.clone());
}
}
}
entries.push(SourceEntry {
path: image,
kind,
meta: metadata_of(&meta),
xattrs,
darwin: None,
});
}
Ok(Self { entries })
}
#[must_use]
pub fn owner(mut self, uid: u32, gid: u32) -> Self {
for entry in &mut self.entries {
entry.meta.uid = uid;
entry.meta.gid = gid;
}
self
}
#[must_use]
pub fn times_from_modification(mut self) -> Self {
for entry in &mut self.entries {
entry.meta.atime = entry.meta.mtime;
entry.meta.ctime = entry.meta.mtime;
}
self
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl Source for DirectorySource {
fn into_entries(self) -> Vec<SourceEntry> {
self.entries
}
}
struct Frame {
dir: Arc<File>,
names: std::vec::IntoIter<CString>,
image: Vec<u8>,
host: PathBuf,
relative: Vec<u8>,
}
struct Found {
image: Vec<u8>,
meta: std::fs::Metadata,
kind: EntryKind,
xattrs: Vec<Xattr>,
}
#[derive(Clone)]
pub(crate) struct Walked {
root: Arc<File>,
relative: Arc<[u8]>,
identity: (u64, u64),
}
impl Walked {
pub(crate) fn open(&self) -> std::io::Result<File> {
let names = canonical_parts(&self.relative);
let Some((&last, parents)) = names.split_last() else {
return Err(std::io::ErrorKind::NotFound.into());
};
let mut dir: Option<File> = None;
for &name in parents {
let at = dir.as_ref().map_or(self.root.as_fd(), AsFd::as_fd);
let next = rustix::fs::openat(
at,
name,
OFlags::PATH | OFlags::DIRECTORY | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
dir = Some(File::from(next));
}
let at = dir.as_ref().map_or(self.root.as_fd(), AsFd::as_fd);
let node = rustix::fs::openat(
at,
last,
OFlags::PATH | OFlags::NOFOLLOW | OFlags::CLOEXEC,
Mode::empty(),
)?;
self.check(&File::from(node))?;
let file = File::from(rustix::fs::openat(
at,
last,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::NOCTTY | OFlags::CLOEXEC,
Mode::empty(),
)?);
self.check(&file)?;
Ok(file)
}
fn check(&self, file: &File) -> std::io::Result<()> {
let meta = file.metadata()?;
if meta.file_type().is_file() && (meta.dev(), meta.ino()) == self.identity {
Ok(())
} else {
Err(std::io::Error::other(
"the name holds a different file from the one the walk recorded, so it was \
replaced after the tree was walked",
))
}
}
}
fn names_in(dir: &File) -> std::io::Result<Vec<CString>> {
let mut names = Vec::new();
for entry in rustix::fs::Dir::read_from(dir)? {
let entry = entry?;
let name = entry.file_name();
if name != c"." && name != c".." {
names.push(name.to_owned());
}
}
Ok(names)
}
fn fd_path(dir: impl AsFd, name: &[u8]) -> PathBuf {
let mut path = PathBuf::from(format!("/proc/self/fd/{}", dir.as_fd().as_raw_fd()));
path.push(OsStr::from_bytes(name));
path
}
fn io_at(path: &Path) -> impl Fn(std::io::Error) -> HostError + '_ {
move |source| HostError::Io {
path: path.to_path_buf(),
source,
}
}
fn join(parent: &[u8], name: &[u8]) -> Vec<u8> {
let mut path = Vec::with_capacity(parent.len() + 1 + name.len());
path.extend_from_slice(parent);
if parent != b"/" {
path.push(b'/');
}
path.extend_from_slice(name);
path
}
fn kind_of(
node: &File,
meta: &std::fs::Metadata,
host_path: &Path,
) -> Result<EntryKind, HostError> {
use std::os::unix::fs::FileTypeExt;
let file_type = meta.file_type();
let kind = if file_type.is_symlink() {
let target = rustix::fs::readlinkat(node, c"", Vec::new())
.map_err(|e| io_at(host_path)(e.into()))?;
EntryKind::Symlink(target.into_bytes())
} else if file_type.is_char_device() {
let (major, minor) = device_numbers(meta.rdev());
EntryKind::CharDevice { major, minor }
} else if file_type.is_block_device() {
let (major, minor) = device_numbers(meta.rdev());
EntryKind::BlockDevice { major, minor }
} else if file_type.is_fifo() {
EntryKind::Fifo
} else if file_type.is_socket() {
EntryKind::Socket
} else {
return Err(HostError::Unsupported {
path: host_path.to_path_buf(),
});
};
Ok(kind)
}
fn metadata_of(meta: &std::fs::Metadata) -> Metadata {
let mode = (meta.mode() & 0o7777) as u16;
Metadata::new(mode, time_of(meta.mtime(), meta.mtime_nsec()))
.owned_by(meta.uid(), meta.gid())
.with_times(
time_of(meta.atime(), meta.atime_nsec()),
time_of(meta.ctime(), meta.ctime_nsec()),
time_of(meta.mtime(), meta.mtime_nsec()),
)
}
fn time_of(secs: i64, nanos: i64) -> Timestamp {
let nanos = nanos.clamp(0, 999_999_999) as u32;
Timestamp { secs, nanos }
}
fn device_numbers(rdev: u64) -> (u32, u32) {
let major = ((rdev >> 8) & 0xfff) | ((rdev >> 32) & !0xfff);
let minor = (rdev & 0xff) | ((rdev >> 12) & !0xff);
(major as u32, minor as u32)
}
enum Attrs<'a> {
Open(&'a File),
Named(&'a Path),
}
impl Attrs<'_> {
fn list(&self, buf: &mut [u8]) -> rustix::io::Result<usize> {
match self {
Self::Open(file) => rustix::fs::flistxattr(file, buf),
Self::Named(path) => rustix::fs::llistxattr(*path, buf),
}
}
fn get(&self, name: &CStr, buf: &mut [u8]) -> rustix::io::Result<usize> {
match self {
Self::Open(file) => rustix::fs::fgetxattr(file, name, buf),
Self::Named(path) => rustix::fs::lgetxattr(*path, name, buf),
}
}
}
fn file_xattrs(
dir: &File,
name: &CStr,
meta: &std::fs::Metadata,
host_path: &Path,
) -> Result<Vec<Xattr>, HostError> {
let opened = rustix::fs::openat(
dir,
name,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::NOCTTY | OFlags::CLOEXEC,
Mode::empty(),
);
match opened {
Ok(fd) => {
let file = File::from(fd);
let held = file.metadata().map_err(io_at(host_path))?;
if (held.dev(), held.ino()) != (meta.dev(), meta.ino()) {
return Err(HostError::Replaced {
path: host_path.to_path_buf(),
});
}
xattrs_of(&Attrs::Open(&file), host_path)
}
Err(Errno::ACCESS | Errno::PERM) => {
xattrs_of(&Attrs::Named(&fd_path(dir, name.to_bytes())), host_path)
}
Err(e) => Err(io_at(host_path)(e.into())),
}
}
fn xattrs_of(attrs: &Attrs<'_>, host_path: &Path) -> Result<Vec<Xattr>, HostError> {
let mut xattrs = Vec::new();
for name in list_xattrs(attrs, host_path)? {
let Some(value) = get_xattr(attrs, host_path, &name)? else {
continue;
};
if name == Acl::ACCESS_NAME || name == Acl::DEFAULT_NAME {
Acl::decode(&value).map_err(|source| HostError::Acl {
path: host_path.to_path_buf(),
source,
})?;
}
xattrs.push(Xattr { name, value });
}
xattrs.sort_by(|a, b| a.name.cmp(&b.name));
Ok(xattrs)
}
const XATTR_ATTEMPTS: usize = 4;
fn list_xattrs(attrs: &Attrs<'_>, host_path: &Path) -> Result<Vec<Vec<u8>>, HostError> {
for _ in 0..XATTR_ATTEMPTS {
let size = match attrs.list(&mut []) {
Ok(size) => size,
Err(e) if unsupported(e) => return Ok(Vec::new()),
Err(e) => return Err(io_at(host_path)(e.into())),
};
if size == 0 {
return Ok(Vec::new());
}
let mut buf = vec![0u8; size];
match attrs.list(&mut buf) {
Ok(len) => {
return Ok(buf[..len]
.split(|&b| b == 0)
.filter(|name| !name.is_empty())
.map(<[u8]>::to_vec)
.collect());
}
Err(Errno::RANGE) => continue,
Err(e) if unsupported(e) => return Ok(Vec::new()),
Err(e) => return Err(io_at(host_path)(e.into())),
}
}
Err(HostError::UnstableXattrs {
path: host_path.to_path_buf(),
name: None,
attempts: XATTR_ATTEMPTS,
})
}
fn get_xattr(
attrs: &Attrs<'_>,
host_path: &Path,
name: &[u8],
) -> Result<Option<Vec<u8>>, HostError> {
let name = CString::new(name).map_err(|_| HostError::Io {
path: host_path.to_path_buf(),
source: std::io::Error::other("an extended-attribute name holds a NUL byte"),
})?;
for _ in 0..XATTR_ATTEMPTS {
let size = match attrs.get(&name, &mut []) {
Ok(size) => size,
Err(e) if gone(e) => return Ok(None),
Err(e) if unsupported(e) => return Ok(None),
Err(e) => return Err(io_at(host_path)(e.into())),
};
if size == 0 {
return Ok(Some(Vec::new()));
}
let mut buf = vec![0u8; size];
match attrs.get(&name, &mut buf) {
Ok(len) => {
buf.truncate(len);
return Ok(Some(buf));
}
Err(Errno::RANGE) => continue,
Err(e) if gone(e) => return Ok(None),
Err(e) => return Err(io_at(host_path)(e.into())),
}
}
Err(HostError::UnstableXattrs {
path: host_path.to_path_buf(),
name: Some(name.as_bytes().to_vec()),
attempts: XATTR_ATTEMPTS,
})
}
fn unsupported(e: Errno) -> bool {
e == Errno::NOTSUP || e == Errno::OPNOTSUPP
}
fn gone(e: Errno) -> bool {
e == Errno::NODATA
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_child_path_joins_under_the_root() {
assert_eq!(join(b"/", b"etc"), b"/etc");
assert_eq!(join(b"/etc", b"hostname"), b"/etc/hostname");
assert_eq!(join(b"/", b"od\xffd"), b"/od\xffd");
}
#[test]
fn device_numbers_are_unpacked_from_the_interleaved_encoding() {
assert_eq!(device_numbers((1 << 8) | 3), (1, 3));
assert_eq!(device_numbers(8 << 8), (8, 0));
let rdev = ((259u64 & 0xfff) << 8) | (0x1_2345 & 0xff) | ((0x1_2345 & !0xffu64) << 12);
assert_eq!(device_numbers(rdev), (259, 0x1_2345));
}
#[test]
fn an_out_of_range_nanosecond_field_does_not_reach_the_encoding() {
assert_eq!(
time_of(5, 999_999_999),
Timestamp {
secs: 5,
nanos: 999_999_999,
}
);
assert_eq!(time_of(5, 2_000_000_000).nanos, 999_999_999);
assert_eq!(time_of(5, -1).nanos, 0);
assert_eq!(time_of(5, i64::from(u32::MAX) + 1).nanos, 999_999_999);
assert_eq!(time_of(5, i64::MAX).nanos, 999_999_999);
assert_eq!(time_of(5, i64::MIN).nanos, 0);
}
#[test]
fn a_churning_xattr_names_itself_and_a_churning_list_says_so() {
let one = HostError::UnstableXattrs {
path: PathBuf::from("/tree/file"),
name: Some(b"user.tag".to_vec()),
attempts: XATTR_ATTEMPTS,
};
assert_eq!(
one.to_string(),
format!(
"/tree/file: the extended attribute user.tag kept changing while it was \
read, across {XATTR_ATTEMPTS} attempts"
)
);
let all = HostError::UnstableXattrs {
path: PathBuf::from("/tree/file"),
name: None,
attempts: XATTR_ATTEMPTS,
};
assert_eq!(
all.to_string(),
format!(
"/tree/file: the list of extended attributes kept changing while it was \
read, across {XATTR_ATTEMPTS} attempts"
)
);
}
fn paths(source: &DirectorySource) -> Vec<String> {
source
.entries
.iter()
.map(|e| String::from_utf8_lossy(&e.path).into_owned())
.collect()
}
fn at<'a>(source: &'a DirectorySource, path: &[u8]) -> &'a SourceEntry {
source
.entries
.iter()
.find(|e| e.path == path)
.unwrap_or_else(|| panic!("{} was not walked", String::from_utf8_lossy(path)))
}
#[test]
fn a_tree_walks_to_the_root_and_everything_under_it_in_path_order() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path();
std::fs::create_dir(root.join("etc")).expect("etc");
std::fs::create_dir_all(root.join("var/log")).expect("var/log");
std::fs::write(root.join("etc/hostname"), b"ferrosys\n").expect("hostname");
std::os::unix::fs::symlink("/proc/mounts", root.join("etc/mtab")).expect("mtab");
let source = DirectorySource::from_path(root).expect("walk the tree");
assert_eq!(
paths(&source),
[
"/",
"/etc",
"/etc/hostname",
"/etc/mtab",
"/var",
"/var/log"
]
);
assert_eq!(source.len(), 6);
assert!(!source.is_empty());
assert!(matches!(at(&source, b"/").kind, EntryKind::Directory));
assert!(matches!(
at(&source, b"/var/log").kind,
EntryKind::Directory
));
match &at(&source, b"/etc/mtab").kind {
EntryKind::Symlink(target) => assert_eq!(target, b"/proc/mounts"),
other => panic!("expected a symlink, got {other:?}"),
}
}
#[test]
fn a_regular_files_contents_are_named_rather_than_read() {
let dir = tempfile::tempdir().expect("temp dir");
std::fs::write(dir.path().join("motd"), b"welcome\n").expect("motd");
let source = DirectorySource::from_path(dir.path()).expect("walk the tree");
match &at(&source, b"/motd").kind {
EntryKind::File(FileContent::Range(range)) => {
assert_eq!(range.len(), 8);
assert_eq!(range.offset(), 0);
assert_eq!(range.path(), dir.path().join("motd"));
assert_eq!(range.read().expect("read the file"), b"welcome\n");
}
other => panic!("expected a located file, got {other:?}"),
}
}
#[test]
fn several_names_for_one_inode_become_hard_links_to_the_first() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path();
std::fs::write(root.join("b-original"), b"shared\n").expect("write");
std::fs::hard_link(root.join("b-original"), root.join("a-link")).expect("hard link");
std::fs::hard_link(root.join("b-original"), root.join("c-link")).expect("hard link");
let source = DirectorySource::from_path(root).expect("walk the tree");
assert!(matches!(
at(&source, b"/a-link").kind,
EntryKind::File(FileContent::Range(_))
));
for name in [&b"/b-original"[..], b"/c-link"] {
match &at(&source, name).kind {
EntryKind::HardLink { target } => assert_eq!(target, b"/a-link"),
other => panic!(
"{} should be a hard link, got {other:?}",
String::from_utf8_lossy(name)
),
}
}
}
#[test]
fn a_directory_is_never_taken_for_a_hard_link() {
let dir = tempfile::tempdir().expect("temp dir");
std::fs::create_dir(dir.path().join("etc")).expect("etc");
std::fs::create_dir(dir.path().join("etc/ssl")).expect("ssl");
let source = DirectorySource::from_path(dir.path()).expect("walk the tree");
for entry in &source.entries {
assert!(
matches!(entry.kind, EntryKind::Directory),
"{} is not a directory",
String::from_utf8_lossy(&entry.path)
);
}
}
#[test]
fn metadata_and_ownership_come_from_the_host_until_owner_replaces_them() {
use std::os::unix::fs::PermissionsExt;
let dir = tempfile::tempdir().expect("temp dir");
let file = dir.path().join("sh");
std::fs::write(&file, b"#!/bin/sh\n").expect("write");
std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o4755)).expect("chmod");
let source = DirectorySource::from_path(dir.path()).expect("walk the tree");
let entry = at(&source, b"/sh");
assert_eq!(entry.meta.mode, 0o4755);
let meta = std::fs::symlink_metadata(&file).expect("stat");
assert_eq!(entry.meta.mtime, time_of(meta.mtime(), meta.mtime_nsec()));
assert_eq!(entry.meta.atime, time_of(meta.atime(), meta.atime_nsec()));
assert_eq!(entry.meta.ctime, time_of(meta.ctime(), meta.ctime_nsec()));
assert_eq!(entry.meta.uid, meta.uid());
let owned = DirectorySource::from_path(dir.path())
.expect("walk the tree")
.owner(0, 0);
assert!(
owned
.entries
.iter()
.all(|e| e.meta.uid == 0 && e.meta.gid == 0)
);
}
#[test]
fn a_fifo_and_a_socket_are_carried_as_themselves() {
let dir = tempfile::tempdir().expect("temp dir");
rustix::fs::mknodat(
rustix::fs::CWD,
dir.path().join("pipe"),
rustix::fs::FileType::Fifo,
rustix::fs::Mode::from_raw_mode(0o644),
0,
)
.expect("make a fifo");
let _socket =
std::os::unix::net::UnixListener::bind(dir.path().join("sock")).expect("bind a socket");
let source = DirectorySource::from_path(dir.path()).expect("walk the tree");
assert!(matches!(at(&source, b"/pipe").kind, EntryKind::Fifo));
assert!(matches!(at(&source, b"/sock").kind, EntryKind::Socket));
}
#[test]
fn a_root_that_is_not_a_directory_is_refused_by_name() {
let dir = tempfile::tempdir().expect("temp dir");
let file = dir.path().join("plain");
std::fs::write(&file, b"x").expect("write");
match DirectorySource::from_path(&file).err() {
Some(HostError::NotADirectory { path }) => assert_eq!(path, file),
other => panic!("expected a refusal, got {other:?}"),
}
let missing = dir.path().join("nowhere");
match DirectorySource::from_path(&missing).err() {
Some(HostError::Io { path, .. }) => assert_eq!(path, missing),
other => panic!("expected an I/O failure, got {other:?}"),
}
}
#[test]
fn extended_attributes_are_carried_in_name_order_and_an_acl_keeps_its_boundary_form() {
use crate::acl::{AclEntry, AclQualifier};
let dir = tempfile::tempdir().expect("temp dir");
let file = dir.path().join("ping");
std::fs::write(&file, b"elf").expect("write");
let set = |name: &str, value: &[u8]| {
rustix::fs::lsetxattr(&file, name, value, rustix::fs::XattrFlags::empty())
};
if let Err(e) = set("user.note", b"second") {
eprintln!(
"SKIPPED: {} holds no extended attributes: {e}",
file.display()
);
return;
}
set("security.capability", b"first")
.or_else(|e| {
eprintln!("note: security.capability not writable here: {e}");
Ok::<(), rustix::io::Errno>(())
})
.expect("the fallback cannot fail");
let acl = Acl::new(vec![
AclEntry {
who: AclQualifier::UserObj,
perm: Acl::READ | Acl::WRITE | Acl::EXEC,
},
AclEntry {
who: AclQualifier::User(1000),
perm: Acl::READ | Acl::WRITE,
},
AclEntry {
who: AclQualifier::GroupObj,
perm: Acl::READ | Acl::EXEC,
},
AclEntry {
who: AclQualifier::Mask,
perm: Acl::READ | Acl::WRITE | Acl::EXEC,
},
AclEntry {
who: AclQualifier::Other,
perm: Acl::READ,
},
])
.expect("a well-formed ACL");
let v2 = acl.encode();
let has_acl = set("system.posix_acl_access", &v2).is_ok();
let source = DirectorySource::from_path(dir.path()).expect("walk the tree");
let entry = at(&source, b"/ping");
let names: Vec<&[u8]> = entry.xattrs.iter().map(|x| x.name.as_slice()).collect();
assert!(
names.windows(2).all(|w| w[0] < w[1]),
"the attributes are in name order: {names:?}"
);
let note = entry
.xattrs
.iter()
.find(|x| x.name == b"user.note")
.expect("the attribute set on the file");
assert_eq!(note.value, b"second");
if has_acl {
let stored = entry
.xattrs
.iter()
.find(|x| x.name == Acl::ACCESS_NAME)
.expect("the ACL set on the file");
assert_eq!(
stored.value, v2,
"the walk carries the form the host handed over"
);
} else {
eprintln!("SKIPPED: {} holds no POSIX ACL", file.display());
}
}
#[test]
fn every_directory_in_an_ordinary_tree_is_its_own() {
let dir = tempfile::tempdir().expect("temp dir");
let root = dir.path();
std::fs::create_dir_all(root.join("a/log")).expect("a/log");
std::fs::create_dir_all(root.join("b/log")).expect("b/log");
std::fs::create_dir(root.join("empty")).expect("empty");
std::fs::write(root.join("a/log/messages"), b"\n").expect("messages");
let source = DirectorySource::from_path(root).expect("walk the tree");
assert_eq!(
paths(&source),
[
"/",
"/a",
"/a/log",
"/a/log/messages",
"/b",
"/b/log",
"/empty"
]
);
}
#[test]
fn one_directory_under_two_paths_names_both_of_them() {
let said = HostError::RepeatedDirectory {
path: PathBuf::from("/staging/rootfs/mnt"),
first: PathBuf::from("/staging/rootfs"),
}
.to_string();
assert!(said.contains("/staging/rootfs/mnt"), "{said}");
assert!(said.contains("/staging/rootfs"), "{said}");
}
}