use std::fmt;
use std::sync::Arc;
use super::backend::{Access, Backend, Caps, Entry, Kind, Stat, Version, WriteOp};
use super::error::{Feature, InputReason, NsError, NsErrorKind, NsResult};
use super::path::{case_fold_key, NsPath};
use super::watch::{Watch, WatchOpts};
#[derive(Clone)]
struct Mount {
point: NsPath,
key: Vec<String>,
backend: Arc<dyn Backend>,
access: Access,
}
#[derive(Default)]
pub struct NamespaceBuilder {
mounts: Vec<Mount>,
}
impl NamespaceBuilder {
#[must_use]
pub fn mount(mut self, point: NsPath, backend: Arc<dyn Backend>, access: Access) -> Self {
self.mounts.push(Mount {
key: point.fold_components(),
point,
backend,
access,
});
self
}
pub fn build(self) -> NsResult<Namespace> {
for (i, m) in self.mounts.iter().enumerate() {
for other in &self.mounts[..i] {
if other.key == m.key {
return Err(NsError::at(NsErrorKind::AlreadyExists, &m.point));
}
}
}
for (i, m) in self.mounts.iter().enumerate() {
let Some(id) = m.backend.root_identity() else {
continue;
};
if self.mounts[..i]
.iter()
.any(|other| other.backend.root_identity() == Some(id))
{
return Err(NsError::at(
NsErrorKind::InvalidInput(InputReason::DuplicateRoot),
&m.point,
));
}
}
for m in &self.mounts {
if m.access != Access::ReadOnly {
continue;
}
let under_writable = self.mounts.iter().any(|a| {
a.access == Access::ReadWrite
&& a.key.len() < m.key.len()
&& m.key.starts_with(&a.key)
});
if under_writable {
return Err(NsError::at(
NsErrorKind::InvalidInput(InputReason::ReadOnlyUnderReadWrite),
&m.point,
));
}
}
Ok(Namespace {
mounts: self.mounts,
})
}
}
#[derive(Clone)]
pub struct Namespace {
mounts: Vec<Mount>,
}
impl fmt::Debug for Namespace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut list = f.debug_list();
for m in &self.mounts {
list.entry(&format_args!("{} ({:?})", m.point, m.access));
}
list.finish()
}
}
enum Resolved<'a> {
Mount {
mount: &'a Mount,
index: usize,
rel: NsPath,
},
Ancestor { children: Vec<String> },
Nothing,
}
impl Namespace {
pub fn builder() -> NamespaceBuilder {
NamespaceBuilder::default()
}
pub fn mounts(&self) -> impl Iterator<Item = (&NsPath, Access, Caps)> + '_ {
self.mounts
.iter()
.map(|m| (&m.point, m.access, m.backend.caps()))
}
fn child_mount_names(&self, path: &NsPath) -> Vec<String> {
let key = path.fold_components();
let depth = key.len();
let mut names: Vec<(String, String)> = self
.mounts
.iter()
.filter(|m| m.key.len() > depth && m.key.starts_with(&key))
.filter_map(|m| {
m.point
.components()
.nth(depth)
.map(|c| (m.key[depth].clone(), c.to_string()))
})
.collect();
names.sort();
names.dedup_by(|a, b| a.0 == b.0);
names.into_iter().map(|(_, name)| name).collect()
}
fn resolve(&self, path: &NsPath) -> Resolved<'_> {
let key = path.fold_components();
let best = self
.mounts
.iter()
.enumerate()
.filter(|(_, m)| key.starts_with(&m.key))
.max_by_key(|(_, m)| m.key.len());
if let Some((index, mount)) = best {
let rel = path.tail_after(mount.key.len());
return Resolved::Mount { mount, index, rel };
}
let children = self.child_mount_names(path);
if children.is_empty() {
Resolved::Nothing
} else {
Resolved::Ancestor { children }
}
}
fn guard_nested(&self, index: usize) -> NsResult<()> {
let m = &self.mounts[index];
let Some(outer) = self
.mounts
.iter()
.filter(|o| o.key.len() < m.key.len() && m.key.starts_with(&o.key))
.max_by_key(|o| o.key.len())
else {
return Ok(());
};
if m.key.len() - outer.key.len() < 2 {
return Ok(()); }
let Some(parent) = m.point.parent() else {
return Ok(());
};
let rel = parent.tail_after(outer.key.len());
match outer.backend.stat(&rel) {
Ok(st) if st.kind == Kind::File => {
Err(NsError::at(NsErrorKind::NotADirectory, &parent))
}
Err(e) if e.kind() == NsErrorKind::NotADirectory => {
Err(NsError::at(NsErrorKind::NotADirectory, &parent))
}
_ => Ok(()),
}
}
pub fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
match self.resolve(path) {
Resolved::Mount { mount, index, rel } => {
self.guard_nested(index)?;
let synthetic = self.child_mount_names(path);
let mut entries = match mount.backend.walk(&rel) {
Ok(e) => e,
Err(e) if e.kind() == NsErrorKind::NotFound && !synthetic.is_empty() => {
Vec::new()
}
Err(e) => return Err(e.rebased(&mount.point).or_at(path)),
};
for name in synthetic {
let key = case_fold_key(&name);
if !entries.iter().any(|e| case_fold_key(&e.name) == key) {
entries.push(Entry::new(name, Kind::Dir));
}
}
entries.sort_by(|a, b| a.name.cmp(&b.name));
Ok(entries)
}
Resolved::Ancestor { children } => Ok(children
.into_iter()
.map(|name| Entry::new(name, Kind::Dir))
.collect()),
Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
pub fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
match self.resolve(path) {
Resolved::Mount { mount, index, rel } => {
self.guard_nested(index)?;
mount
.backend
.read(&rel, max)
.map_err(|e| e.rebased(&mount.point).or_at(path))
}
Resolved::Ancestor { .. } => Err(NsError::at(NsErrorKind::IsADirectory, path)),
Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
pub fn stat(&self, path: &NsPath) -> NsResult<Stat> {
match self.resolve(path) {
Resolved::Mount { mount, index, rel } => {
self.guard_nested(index)?;
match mount.backend.stat(&rel) {
Ok(s) => Ok(s),
Err(e)
if e.kind() == NsErrorKind::NotFound
&& !self.child_mount_names(path).is_empty() =>
{
Ok(synthetic_stat())
}
Err(e) => Err(e.rebased(&mount.point).or_at(path)),
}
}
Resolved::Ancestor { .. } => Ok(synthetic_stat()),
Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
pub fn write(
&self,
path: &NsPath,
op: WriteOp,
data: &[u8],
if_version: Option<&Version>,
) -> NsResult<Version> {
let (mount, index, rel) = match self.resolve(path) {
Resolved::Mount { mount, index, rel } => (mount, index, rel),
Resolved::Ancestor { .. } => {
return Err(NsError::at(NsErrorKind::PermissionDenied, path))
}
Resolved::Nothing => return Err(NsError::at(NsErrorKind::NotFound, path)),
};
if mount.access == Access::ReadOnly {
return Err(NsError::at(NsErrorKind::PermissionDenied, path));
}
self.guard_nested(index)?;
if !mount.backend.caps().writable {
return Err(NsError::at(NsErrorKind::Unsupported(Feature::Write), path));
}
let op = match op {
WriteOp::RenameWithinMount { to } => match self.resolve(&to) {
Resolved::Mount {
index: to_index,
rel: to_rel,
..
} if to_index == index => WriteOp::RenameWithinMount { to: to_rel },
Resolved::Mount { .. } => return Err(NsError::at(NsErrorKind::CrossMount, path)),
Resolved::Ancestor { .. } | Resolved::Nothing => {
return Err(NsError::at(NsErrorKind::NotFound, &to));
}
},
other => other,
};
mount
.backend
.write(&rel, op, data, if_version)
.map_err(|e| e.rebased(&mount.point).or_at(path))
}
pub fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
match self.resolve(path) {
Resolved::Mount { mount, index, rel } => {
self.guard_nested(index)?;
let point = mount.point.clone();
let watch = mount
.backend
.watch(&rel, opts)
.map_err(|e| e.rebased(&mount.point).or_at(path))?;
Ok(watch.map_paths(move |p| p.rebase(&point).ok()))
}
Resolved::Ancestor { .. } => Err(NsError::at(
NsErrorKind::Unsupported(Feature::WatchOnMountAncestor),
path,
)),
Resolved::Nothing => Err(NsError::at(NsErrorKind::NotFound, path)),
}
}
}
fn synthetic_stat() -> Stat {
Stat {
kind: Kind::Dir,
size: 0,
version: Version::from_bytes(b"ns:mount-ancestor"),
owner: None,
mode: None,
links: None,
modified: None,
}
}