use std::io::{self, Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
use cap_std::ambient_authority;
use cap_std::fs::{Dir, DirBuilder, File, Metadata, OpenOptions};
use super::backend::{Backend, Caps, Entry, Kind, Stat, Version, WatchKind, WriteOp};
use super::error::{InputReason, NsError, NsErrorKind, NsResult};
use super::path::{case_fold_key, validate_name, NsPath, TEMP_PREFIX};
use super::watch::{spawn_poller, Fingerprint, ScanOutcome, Snapshot, Watch, WatchOpts};
#[cfg(unix)]
use cap_std::fs::{DirBuilderExt, OpenOptionsExt};
#[cfg(all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "loongarch64",
target_arch = "s390x",
target_arch = "powerpc",
target_arch = "powerpc64"
)
))]
const O_NONBLOCK: i32 = 0o4000;
#[cfg(any(
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
))]
const O_NONBLOCK: i32 = 0x4;
#[cfg(all(
unix,
not(any(
all(
target_os = "linux",
any(
target_arch = "x86",
target_arch = "x86_64",
target_arch = "arm",
target_arch = "aarch64",
target_arch = "riscv32",
target_arch = "riscv64",
target_arch = "loongarch64",
target_arch = "s390x",
target_arch = "powerpc",
target_arch = "powerpc64"
)
),
target_os = "macos",
target_os = "ios",
target_os = "freebsd",
target_os = "openbsd",
target_os = "netbsd",
target_os = "dragonfly"
))
))]
const O_NONBLOCK: i32 = 0;
#[cfg(unix)]
mod sys {
use cap_std::fs::{Dir, Metadata, MetadataExt};
pub fn identity(md: &Metadata) -> Option<(u64, u64)> {
Some((md.dev(), md.ino()))
}
pub fn links(md: &Metadata) -> Option<u64> {
Some(md.nlink())
}
pub fn owner(md: &Metadata) -> Option<u32> {
Some(md.uid())
}
pub fn mode(md: &Metadata) -> Option<u32> {
Some(md.mode() & 0o7777)
}
pub fn scan_inode(md: &Metadata) -> u64 {
md.ino()
}
pub fn device_of(dir: &Dir) -> Option<u64> {
dir.dir_metadata().ok().map(|md| md.dev())
}
}
#[cfg(not(unix))]
mod sys {
use cap_primitives::fs::_WindowsByHandle;
use cap_std::fs::{Dir, Metadata};
pub fn identity(md: &Metadata) -> Option<(u64, u64)> {
Some((u64::from(md.volume_serial_number()?), md.file_index()?))
}
pub fn links(md: &Metadata) -> Option<u64> {
md.number_of_links().map(u64::from)
}
pub fn owner(_: &Metadata) -> Option<u32> {
None
}
pub fn mode(_: &Metadata) -> Option<u32> {
None
}
pub fn scan_inode(_: &Metadata) -> u64 {
0
}
pub fn device_of(_: &Dir) -> Option<u64> {
None
}
}
pub struct HostDir {
root: Dir,
caps: Caps,
identity: Option<(u64, u64)>,
}
impl std::fmt::Debug for HostDir {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HostDir").field("caps", &self.caps).finish()
}
}
impl HostDir {
pub fn open_ambient(path: impl AsRef<Path>) -> NsResult<Self> {
let dir = Dir::open_ambient_dir(path.as_ref(), ambient_authority())
.map_err(|e| NsError::from_io_nopath(&e))?;
Self::checked(dir)
}
pub fn from_dir(dir: Dir) -> NsResult<Self> {
Self::checked(dir)
}
fn checked(dir: Dir) -> NsResult<Self> {
let md = dir
.dir_metadata()
.map_err(|e| NsError::from_io_nopath(&e))?;
if !md.is_dir() {
return Err(NsError::new(NsErrorKind::NotADirectory));
}
let caps = Caps {
writable: true,
atomic_replace: true,
exact_if_version: false,
watch: WatchKind::Polling,
owner_mode: cfg!(unix),
case_sensitive: probe_case_sensitive(&dir),
strict_confinement: cfg!(unix),
};
let identity = sys::identity(&md);
Ok(HostDir {
root: dir,
caps,
identity,
})
}
}
fn probe_case_sensitive(root: &Dir) -> bool {
let default = cfg!(target_os = "linux");
let Ok(entries) = root.entries() else {
return default;
};
for entry in entries.flatten().take(64) {
let name = entry.file_name();
let Some(name) = name.to_str() else { continue };
let swapped: String = name
.chars()
.map(|c| {
if c.is_lowercase() {
c.to_uppercase().next().unwrap_or(c)
} else if c.is_uppercase() {
c.to_lowercase().next().unwrap_or(c)
} else {
c
}
})
.collect();
if swapped == name {
continue;
}
let Ok(original) = root.symlink_metadata(name) else {
continue;
};
return match root.symlink_metadata(&swapped) {
Ok(other) => match (sys::identity(&other), sys::identity(&original)) {
(Some(a), Some(b)) => a != b,
_ => continue,
},
Err(e) if e.kind() == io::ErrorKind::NotFound => true,
Err(_) => continue,
};
}
default
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Want {
Dir,
File,
}
fn explain_open_failure(
parent: &Dir,
name: &str,
err: &io::Error,
path: &NsPath,
want: Want,
) -> NsError {
match parent.symlink_metadata(name) {
Ok(md) => {
let ft = md.file_type();
if ft.is_symlink() {
NsError::at(NsErrorKind::Escapes, path)
} else if ft.is_dir() {
match want {
Want::Dir => NsError::from_io(err, path),
Want::File => NsError::at(NsErrorKind::IsADirectory, path),
}
} else if ft.is_file() {
match want {
Want::Dir => NsError::at(NsErrorKind::NotADirectory, path),
Want::File => NsError::from_io(err, path),
}
} else {
NsError::at(NsErrorKind::NotRegular, path)
}
}
Err(_) => NsError::from_io(err, path),
}
}
fn open_dir_at(root: &Dir, path: &NsPath) -> NsResult<Dir> {
let mut current = root.try_clone().map_err(|e| NsError::from_io(&e, path))?;
for name in path.components() {
let next = match current.open_dir_nofollow(name) {
Ok(d) => d,
Err(e) => return Err(explain_open_failure(¤t, name, &e, path, Want::Dir)),
};
current = next;
}
Ok(current)
}
fn same_directory(a: &Dir, b: &Dir) -> bool {
match (a.dir_metadata(), b.dir_metadata()) {
(Ok(x), Ok(y)) => match (sys::identity(&x), sys::identity(&y)) {
(Some(x), Some(y)) => x == y,
_ => false,
},
_ => false,
}
}
fn open_parent<'p>(root: &Dir, path: &'p NsPath) -> NsResult<(Dir, &'p str)> {
let name = path
.file_name()
.ok_or_else(|| NsError::at(NsErrorKind::InvalidInput(InputReason::MountRoot), path))?;
let parent = path.parent().unwrap_or_else(NsPath::root);
Ok((open_dir_at(root, &parent)?, name))
}
fn kind_of(md: &Metadata, path: &NsPath) -> NsResult<Kind> {
let ft = md.file_type();
if ft.is_symlink() {
Err(NsError::at(NsErrorKind::Escapes, path))
} else if ft.is_dir() {
Ok(Kind::Dir)
} else if ft.is_file() {
Ok(Kind::File)
} else {
Err(NsError::at(NsErrorKind::NotRegular, path))
}
}
fn lookup(parent: &Dir, name: &str, path: &NsPath) -> NsResult<Option<(Kind, Metadata)>> {
match parent.symlink_metadata(name) {
Ok(md) => Ok(Some((kind_of(&md, path)?, md))),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
Err(e) => Err(NsError::from_io(&e, path)),
}
}
fn exists_raw(parent: &Dir, name: &str, path: &NsPath) -> NsResult<bool> {
match parent.symlink_metadata(name) {
Ok(_) => Ok(true),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
Err(e) => Err(NsError::from_io(&e, path)),
}
}
fn open_regular(parent: &Dir, name: &str, path: &NsPath) -> NsResult<(File, Metadata)> {
match lookup(parent, name, path)? {
None => return Err(NsError::at(NsErrorKind::NotFound, path)),
Some((Kind::Dir, _)) => return Err(NsError::at(NsErrorKind::IsADirectory, path)),
Some((Kind::File, _)) => {}
}
let mut opts = OpenOptions::new();
opts.read(true).follow(FollowSymlinks::No);
#[cfg(unix)]
opts.custom_flags(O_NONBLOCK);
let file = parent
.open_with(name, &opts)
.map_err(|e| explain_open_failure(parent, name, &e, path, Want::File))?;
let md = file.metadata().map_err(|e| NsError::from_io(&e, path))?;
if md.is_dir() {
return Err(NsError::at(NsErrorKind::IsADirectory, path));
}
if !md.is_file() {
return Err(NsError::at(NsErrorKind::NotRegular, path));
}
Ok((file, md))
}
fn mtime_ns(md: &Metadata) -> u128 {
md.modified()
.ok()
.map(|t| t.into_std())
.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos())
}
fn version_of(md: &Metadata) -> Version {
let mut bytes = Vec::with_capacity(2 + 16 + 24);
bytes.extend_from_slice(b"h1");
bytes.extend_from_slice(&mtime_ns(md).to_le_bytes());
bytes.extend_from_slice(&md.len().to_le_bytes());
let (device, inode) = sys::identity(md).unwrap_or((0, 0));
bytes.extend_from_slice(&inode.to_le_bytes());
bytes.extend_from_slice(&device.to_le_bytes());
Version::from_bytes(&bytes)
}
fn stat_of(md: &Metadata, kind: Kind) -> Stat {
Stat {
kind,
size: if kind == Kind::File { md.len() } else { 0 },
version: version_of(md),
owner: sys::owner(md),
mode: sys::mode(md),
links: sys::links(md),
modified: md.modified().ok().map(|t| t.into_std()),
}
}
fn check_version(md: &Metadata, if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
match if_version {
Some(v) if *v != version_of(md) => Err(NsError::at(NsErrorKind::VersionMismatch, path)),
_ => Ok(()),
}
}
fn refuse_hard_linked(md: &Metadata, path: &NsPath) -> NsResult<()> {
match sys::links(md) {
Some(n) if n > 1 => Err(NsError::at(NsErrorKind::HardLinked, path)),
_ => Ok(()),
}
}
fn no_data(data: &[u8], path: &NsPath) -> NsResult<()> {
if data.is_empty() {
Ok(())
} else {
Err(NsError::at(
NsErrorKind::InvalidInput(InputReason::UnexpectedData),
path,
))
}
}
fn no_version(if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
if if_version.is_none() {
Ok(())
} else {
Err(NsError::at(
NsErrorKind::InvalidInput(InputReason::VersionOnCreate),
path,
))
}
}
enum Conflict {
Same,
Fold,
}
fn list_names(dir: &Dir, path: &NsPath) -> NsResult<Vec<String>> {
let entries = dir.entries().map_err(|e| NsError::from_io(&e, path))?;
let mut names = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| NsError::from_io(&e, path))?;
if let Some(name) = entry.file_name().to_str() {
names.push(name.to_string());
}
}
Ok(names)
}
fn conflict_in(names: &[String], name: &str, ignore: Option<&str>) -> Option<Conflict> {
let key = case_fold_key(name);
let mut fold = false;
for existing in names {
if Some(existing.as_str()) == ignore {
continue;
}
if existing == name {
return Some(Conflict::Same);
}
if case_fold_key(existing) == key {
fold = true;
}
}
fold.then_some(Conflict::Fold)
}
fn stored_name<'a>(names: &'a [String], name: &str) -> Option<&'a str> {
names
.iter()
.find(|n| n.as_str() == name)
.or_else(|| {
let key = case_fold_key(name);
names.iter().find(|n| case_fold_key(n) == key)
})
.map(String::as_str)
}
fn conflict_error(c: Conflict, path: &NsPath) -> NsError {
match c {
Conflict::Same => NsError::at(NsErrorKind::AlreadyExists, path),
Conflict::Fold => NsError::at(NsErrorKind::CaseCollision, path),
}
}
fn sync_dir(dir: &Dir) -> io::Result<()> {
#[cfg(unix)]
{
dir.open(".")?.sync_all()
}
#[cfg(not(unix))]
{
let _ = dir;
Ok(())
}
}
fn temp_name() -> String {
static COUNTER: AtomicU64 = AtomicU64::new(0);
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
format!("{TEMP_PREFIX}{:x}-{:x}-{:x}", std::process::id(), n, nanos)
}
fn create_options() -> OpenOptions {
let mut opts = OpenOptions::new();
opts.write(true).create_new(true).follow(FollowSymlinks::No);
#[cfg(unix)]
opts.mode(0o600);
opts
}
fn create_filled(parent: &Dir, name: &str, data: &[u8], path: &NsPath) -> NsResult<Metadata> {
let mut file = parent
.open_with(name, &create_options())
.map_err(|e| NsError::from_io(&e, path))?;
let result = file
.write_all(data)
.and_then(|()| file.sync_all())
.and_then(|()| file.metadata());
match result {
Ok(md) => Ok(md),
Err(e) => {
drop(file);
let _ = parent.remove_file(name);
Err(NsError::from_io(&e, path))
}
}
}
impl HostDir {
fn create_exclusive(
&self,
path: &NsPath,
data: &[u8],
if_version: Option<&Version>,
) -> NsResult<Version> {
no_version(if_version, path)?;
let (parent, name) = open_parent(&self.root, path)?;
if let Some(c) = conflict_in(&list_names(&parent, path)?, name, None) {
return Err(conflict_error(c, path));
}
if exists_raw(&parent, name, path)? {
return Err(NsError::at(NsErrorKind::AlreadyExists, path));
}
let md = create_filled(&parent, name, data, path)?;
sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
Ok(version_of(&md))
}
fn replace(
&self,
path: &NsPath,
data: &[u8],
if_version: Option<&Version>,
) -> NsResult<Version> {
let (parent, name) = open_parent(&self.root, path)?;
if let Some(Conflict::Fold) = conflict_in(&list_names(&parent, path)?, name, None) {
return Err(NsError::at(NsErrorKind::CaseCollision, path));
}
match lookup(&parent, name, path)? {
Some((Kind::Dir, _)) => return Err(NsError::at(NsErrorKind::IsADirectory, path)),
Some((Kind::File, md)) => {
refuse_hard_linked(&md, path)?;
check_version(&md, if_version, path)?;
}
None => {
if if_version.is_some() {
return Err(NsError::at(NsErrorKind::NotFound, path));
}
}
}
let tmp = temp_name();
let md = create_filled(&parent, &tmp, data, path)?;
if let Err(e) = parent.rename(&tmp, &parent, name) {
let _ = parent.remove_file(&tmp);
return Err(NsError::from_io(&e, path));
}
sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
Ok(version_of(&md))
}
fn remove(&self, path: &NsPath, if_version: Option<&Version>) -> NsResult<Version> {
let (parent, name) = open_parent(&self.root, path)?;
let Some((kind, md)) = lookup(&parent, name, path)? else {
return Err(NsError::at(NsErrorKind::NotFound, path));
};
check_version(&md, if_version, path)?;
let result = match kind {
Kind::File => parent.remove_file(name),
Kind::Dir => parent.remove_dir(name),
};
result.map_err(|e| NsError::from_io(&e, path))?;
sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
Ok(version_of(&md))
}
fn rename(
&self,
from: &NsPath,
to: &NsPath,
if_version: Option<&Version>,
) -> NsResult<Version> {
if to != from && to.starts_with(from) {
return Err(NsError::at(
NsErrorKind::InvalidInput(InputReason::MoveIntoSelf),
to,
));
}
let (from_dir, from_name) = open_parent(&self.root, from)?;
let (to_dir, to_name) = open_parent(&self.root, to)?;
let Some((_, md)) = lookup(&from_dir, from_name, from)? else {
return Err(NsError::at(NsErrorKind::NotFound, from));
};
check_version(&md, if_version, from)?;
if from == to {
return Err(NsError::at(NsErrorKind::AlreadyExists, to));
}
let same_dir = same_directory(&from_dir, &to_dir);
let names = list_names(&to_dir, to)?;
let ignore = if same_dir {
stored_name(&names, from_name)
} else {
None
};
if let Some(c) = conflict_in(&names, to_name, ignore) {
return Err(conflict_error(c, to));
}
from_dir
.rename(from_name, &to_dir, to_name)
.map_err(|e| NsError::from_io(&e, to))?;
sync_dir(&to_dir).map_err(|e| NsError::from_io(&e, to))?;
if !same_dir {
sync_dir(&from_dir).map_err(|e| NsError::from_io(&e, from))?;
}
match lookup(&to_dir, to_name, to)? {
Some((_, md)) => Ok(version_of(&md)),
None => Ok(version_of(&md)),
}
}
fn make_dir(&self, path: &NsPath, if_version: Option<&Version>) -> NsResult<Version> {
no_version(if_version, path)?;
let (parent, name) = open_parent(&self.root, path)?;
if let Some(c) = conflict_in(&list_names(&parent, path)?, name, None) {
return Err(conflict_error(c, path));
}
if exists_raw(&parent, name, path)? {
return Err(NsError::at(NsErrorKind::AlreadyExists, path));
}
#[cfg(unix)]
let builder = {
let mut b = DirBuilder::new();
b.mode(0o700);
b
};
#[cfg(not(unix))]
let builder = DirBuilder::new();
parent
.create_dir_with(name, &builder)
.map_err(|e| NsError::from_io(&e, path))?;
sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
match lookup(&parent, name, path)? {
Some((_, md)) => Ok(version_of(&md)),
None => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
}
fn scan(
root: &Dir,
path: &NsPath,
recursive: bool,
max_tracked: usize,
max_depth: usize,
) -> ScanOutcome {
let Ok(top) = open_dir_at(root, path) else {
return ScanOutcome::Unavailable;
};
let top_dev = sys::device_of(&top);
if cfg!(unix) && top_dev.is_none() {
return ScanOutcome::Unavailable;
}
let mut snapshot = Snapshot::new();
let subdirs = match read_level(&top, path, true, recursive, max_tracked, &mut snapshot) {
Ok(subdirs) => subdirs,
Err(outcome) => return outcome,
};
struct Frame {
dir: Dir,
path: NsPath,
subdirs: Vec<String>,
}
let mut stack = vec![Frame {
dir: top,
path: path.clone(),
subdirs,
}];
loop {
let depth = stack.len();
let Some(frame) = stack.last_mut() else {
break;
};
let Some(name) = frame.subdirs.pop() else {
stack.pop();
continue;
};
if depth > max_depth {
return ScanOutcome::Incomplete;
}
let Some(child_path) = frame.path.child(&name) else {
continue;
};
let child = match frame.dir.open_dir_nofollow(&name) {
Ok(d) => d,
Err(e) => {
match explain_open_failure(&frame.dir, &name, &e, &child_path, Want::Dir).kind() {
NsErrorKind::NotFound
| NsErrorKind::NotADirectory
| NsErrorKind::Escapes
| NsErrorKind::PermissionDenied => continue,
_ => return ScanOutcome::Incomplete,
}
}
};
if let Some(top_dev) = top_dev {
match sys::device_of(&child) {
Some(dev) if dev == top_dev => {}
Some(_) => continue,
None => return ScanOutcome::Incomplete,
}
}
match read_level(
&child,
&child_path,
false,
recursive,
max_tracked,
&mut snapshot,
) {
Ok(subdirs) => stack.push(Frame {
dir: child,
path: child_path,
subdirs,
}),
Err(outcome) => return outcome,
}
}
ScanOutcome::Complete(snapshot)
}
fn read_level(
dir: &Dir,
dir_path: &NsPath,
is_top: bool,
recursive: bool,
max_tracked: usize,
snapshot: &mut Snapshot,
) -> Result<Vec<String>, ScanOutcome> {
let entries = match dir.entries() {
Ok(e) => e,
Err(_) if is_top => return Err(ScanOutcome::Unavailable),
Err(e)
if e.kind() == io::ErrorKind::PermissionDenied
|| e.kind() == io::ErrorKind::NotFound =>
{
return Ok(Vec::new());
}
Err(_) => return Err(ScanOutcome::Incomplete),
};
let mut subdirs = Vec::new();
for entry in entries {
let Ok(entry) = entry else {
return Err(ScanOutcome::Incomplete);
};
let file_name = entry.file_name();
let Some(name) = file_name.to_str() else {
continue;
};
if validate_name(name).is_err() {
continue;
}
let Some(child) = dir_path.child(name) else {
continue;
};
let Ok(md) = entry.metadata() else { continue };
let kind = if md.file_type().is_dir() {
Kind::Dir
} else if md.file_type().is_file() {
Kind::File
} else {
continue;
};
if snapshot.len() >= max_tracked {
return Err(ScanOutcome::Incomplete);
}
snapshot.insert(
child,
Fingerprint {
kind,
len: if kind == Kind::File { md.len() } else { 0 },
mtime_ns: mtime_ns(&md),
inode: sys::scan_inode(&md),
},
);
if recursive && kind == Kind::Dir {
subdirs.push(name.to_string());
}
}
Ok(subdirs)
}
impl Backend for HostDir {
fn caps(&self) -> Caps {
self.caps
}
fn root_identity(&self) -> Option<(u64, u64)> {
self.identity
}
fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
let dir = open_dir_at(&self.root, path)?;
let entries = dir.entries().map_err(|e| NsError::from_io(&e, path))?;
let mut out = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| NsError::from_io(&e, path))?;
let file_name = entry.file_name();
let Some(name) = file_name.to_str() else {
continue;
};
if validate_name(name).is_err() {
continue;
}
let Ok(ft) = entry.file_type() else { continue };
let kind = if ft.is_dir() {
Kind::Dir
} else if ft.is_file() {
Kind::File
} else {
continue;
};
out.push(Entry {
name: name.to_string(),
kind,
});
}
out.sort_by(|a, b| a.name.cmp(&b.name));
Ok(out)
}
fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
if path.is_root() {
return Err(NsError::at(NsErrorKind::IsADirectory, path));
}
let (parent, name) = open_parent(&self.root, path)?;
let (mut file, md) = open_regular(&parent, name, path)?;
let version = version_of(&md);
if md.len() > max {
return Err(NsError::at(NsErrorKind::TooLarge, path));
}
let mut buf = Vec::new();
(&mut file)
.take(max.saturating_add(1))
.read_to_end(&mut buf)
.map_err(|e| NsError::from_io(&e, path))?;
if buf.len() as u64 > max {
return Err(NsError::at(NsErrorKind::TooLarge, path));
}
Ok((buf, version))
}
fn stat(&self, path: &NsPath) -> NsResult<Stat> {
if path.is_root() {
let md = self
.root
.dir_metadata()
.map_err(|e| NsError::from_io(&e, path))?;
return Ok(stat_of(&md, Kind::Dir));
}
let (parent, name) = open_parent(&self.root, path)?;
match lookup(&parent, name, path)? {
Some((kind, md)) => Ok(stat_of(&md, kind)),
None => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
fn write(
&self,
path: &NsPath,
op: WriteOp,
data: &[u8],
if_version: Option<&Version>,
) -> NsResult<Version> {
match op {
WriteOp::CreateExclusive => {
if path.is_root() {
return Err(NsError::at(NsErrorKind::AlreadyExists, path));
}
self.create_exclusive(path, data, if_version)
}
WriteOp::Replace => {
if path.is_root() {
return Err(NsError::at(NsErrorKind::IsADirectory, path));
}
self.replace(path, data, if_version)
}
WriteOp::Remove => {
no_data(data, path)?;
self.remove(path, if_version)
}
WriteOp::RenameWithinMount { to } => {
no_data(data, path)?;
self.rename(path, &to, if_version)
}
WriteOp::MakeDir => {
no_data(data, path)?;
if path.is_root() {
return Err(NsError::at(NsErrorKind::AlreadyExists, path));
}
self.make_dir(path, if_version)
}
}
}
fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
drop(open_dir_at(&self.root, path)?);
let (recursive, max_tracked, max_depth) =
(opts.recursive, opts.max_tracked, opts.max_depth);
let baseline = match scan(&self.root, path, recursive, max_tracked, max_depth) {
ScanOutcome::Complete(s) => s,
ScanOutcome::Unavailable => return Err(NsError::at(NsErrorKind::NotFound, path)),
ScanOutcome::Incomplete => return Err(NsError::at(NsErrorKind::TooLarge, path)),
};
let root = self
.root
.try_clone()
.map_err(|e| NsError::from_io(&e, path))?;
let watched = path.clone();
spawn_poller(
baseline,
move || scan(&root, &watched, recursive, max_tracked, max_depth),
&opts,
)
.map_err(|e| NsError::from_io(&e, path))
}
}
#[cfg(test)]
mod tests {
#[cfg(unix)]
use std::time::{Duration, Instant};
use super::*;
fn p(s: &str) -> NsPath {
NsPath::parse(s).unwrap()
}
fn open(path: &Path) -> Dir {
Dir::open_ambient_dir(path, ambient_authority()).unwrap()
}
fn chain(root: &Dir, depth: usize) {
let mut cur = root.try_clone().unwrap();
for _ in 0..depth {
cur.create_dir("d").unwrap();
cur = cur.open_dir("d").unwrap();
}
cur.write("leaf", b"x").unwrap();
}
fn complete(outcome: ScanOutcome) -> Snapshot {
match outcome {
ScanOutcome::Complete(s) => s,
ScanOutcome::Incomplete => panic!("expected a complete scan, got Incomplete"),
ScanOutcome::Unavailable => panic!("expected a complete scan, got Unavailable"),
}
}
fn is_incomplete(outcome: &ScanOutcome) -> bool {
matches!(outcome, ScanOutcome::Incomplete)
}
#[test]
fn identity_accessors_never_panic_on_metadata_that_did_not_come_from_a_handle() {
let tmp = tempfile::tempdir().unwrap();
std::fs::write(tmp.path().join("f"), b"x").unwrap();
std::fs::create_dir(tmp.path().join("sub")).unwrap();
let dir = open(tmp.path());
let mut seen = 0;
for entry in dir.entries().unwrap() {
let md = entry.unwrap().metadata().unwrap();
let identity = sys::identity(&md);
let links = sys::links(&md);
let _ = (sys::owner(&md), sys::mode(&md), sys::scan_inode(&md));
let _ = version_of(&md);
let _ = stat_of(&md, Kind::File);
#[cfg(unix)]
{
assert!(identity.is_some() && links.is_some());
}
#[cfg(not(unix))]
{
let _ = (identity, links);
}
seen += 1;
}
assert_eq!(seen, 2);
let md = dir.dir_metadata().unwrap();
assert!(
sys::identity(&md).is_some(),
"a directory handle has an identity"
);
let md = dir.symlink_metadata("f").unwrap();
assert!(sys::identity(&md).is_some() && sys::links(&md) == Some(1));
let a = HostDir::open_ambient(tmp.path()).unwrap();
let b = HostDir::from_dir(dir).unwrap();
assert!(
a.root_identity().is_some(),
"a host directory has an identity"
);
assert_eq!(
a.root_identity(),
b.root_identity(),
"two handles on one directory report one identity"
);
}
#[test]
fn a_scan_stops_at_the_depth_cap_with_incomplete_not_a_partial_picture() {
let tmp = tempfile::tempdir().unwrap();
let root = open(tmp.path());
chain(&root, 200);
let all = complete(scan(&root, &NsPath::root(), true, 1 << 20, 256));
assert_eq!(all.len(), 201);
assert!(is_incomplete(&scan(
&root,
&NsPath::root(),
true,
1 << 20,
64
)));
}
#[test]
fn the_cap_counts_levels_below_the_watched_directory() {
let tmp = tempfile::tempdir().unwrap();
let root = open(tmp.path());
chain(&root, 3); for (cap, fits) in [(0, false), (2, false), (3, true), (4, true)] {
let out = scan(&root, &NsPath::root(), true, 1 << 20, cap);
assert_eq!(!is_incomplete(&out), fits, "cap {cap}");
if fits {
assert_eq!(complete(out).len(), 4, "cap {cap}");
}
}
let from_d = scan(&root, &p("/d"), true, 1 << 20, 2);
assert_eq!(complete(from_d).len(), 3);
assert_eq!(
complete(scan(&root, &NsPath::root(), false, 1 << 20, 0)).len(),
1
);
let empty = tempfile::tempdir().unwrap();
assert!(complete(scan(&open(empty.path()), &NsPath::root(), true, 1 << 20, 0)).is_empty());
}
#[cfg(unix)]
#[test]
fn a_chain_two_thousand_levels_deep_is_one_quick_incomplete_scan() {
let tmp = tempfile::tempdir().unwrap();
let root = open(tmp.path());
chain(&root, 2000);
let started = Instant::now();
let out = scan(&root, &NsPath::root(), true, 262_144, 64);
let took = started.elapsed();
assert!(
is_incomplete(&out),
"deeper than the cap must be Incomplete"
);
assert!(
took < Duration::from_millis(500),
"a scan of a too-deep tree took {took:?}"
);
}
#[test]
fn the_scan_holds_one_handle_per_level_and_a_tree_within_the_cap_is_fully_reported() {
let tmp = tempfile::tempdir().unwrap();
let root = open(tmp.path());
fn grow(dir: &Dir, levels: usize) {
dir.write("f", b"x").unwrap();
if levels > 0 {
for n in ["a", "b"] {
dir.create_dir(n).unwrap();
grow(&dir.open_dir(n).unwrap(), levels - 1);
}
}
}
grow(&root, 5);
let snap = complete(scan(&root, &NsPath::root(), true, 1 << 20, 5));
assert_eq!(snap.len(), 63 + 62);
assert!(snap.contains_key(&p("/b/a/b/a/b/f")));
assert!(is_incomplete(&scan(
&root,
&NsPath::root(),
true,
1 << 20,
4
)));
}
#[cfg(target_os = "linux")]
#[test]
fn a_recursive_scan_does_not_descend_into_another_filesystem() {
use std::os::unix::fs::MetadataExt;
let (Ok(dev), Ok(shm)) = (std::fs::metadata("/dev"), std::fs::metadata("/dev/shm")) else {
eprintln!("skipped: /dev or /dev/shm is not there");
return;
};
if dev.dev() == shm.dev() {
eprintln!("skipped: /dev/shm is not a separate filesystem here");
return;
}
let Ok(inside) = tempfile::Builder::new()
.prefix("skns-dev-")
.tempdir_in("/dev/shm")
else {
eprintln!("skipped: /dev/shm is not writable here");
return;
};
std::fs::write(inside.path().join("deep"), b"x").unwrap();
let name = inside
.path()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
let root = open(Path::new("/dev"));
let ScanOutcome::Complete(snap) = scan(&root, &NsPath::root(), true, 1 << 20, 64) else {
eprintln!("skipped: /dev could not be scanned completely here");
return;
};
assert_eq!(
snap.get(&p("/shm")).map(|f| f.kind),
Some(Kind::Dir),
"the mount point is listed as a directory"
);
let below: Vec<_> = snap
.keys()
.filter(|k| k.as_str().starts_with("/shm/"))
.collect();
assert!(
below.is_empty(),
"the scan crossed into the tmpfs ({name}): {below:?}"
);
let shm_root = open(Path::new("/dev/shm"));
let ScanOutcome::Complete(inner) = scan(&shm_root, &NsPath::root(), true, 1 << 20, 64)
else {
panic!("/dev/shm itself must be scannable");
};
assert!(inner.contains_key(&p(&format!("/{name}/deep"))));
}
}