//! The capability's file operations: each gates its path, passes //! admission, where an access that checks claims makes its claim, and //! fires its event before it reaches the backend. One [`VfsOp`] runs as //! the operation it names. use super::Access; use super::claims::Claims; use super::lines::{LineNumbers, read_lines}; use super::store_view::{strip_root, validate_store_path}; use crate::error::{PathReason, VfsError}; use crate::glob::validate_glob_pattern; use crate::stat::{Entry, Stat}; use crate::traits::Op; use crate::vfs_op::{VfsOp, VfsOutcome}; impl Access { /// Runs `op`, one operation of the list, and returns its outcome. /// /// Each operation is one method of this access, under the checks that /// method makes. `Read` and `ReadNumbered` read the file as UTF-8 /// text and apply their line bounds. `Delete` succeeds on an absent /// path, and `Remove` fails on one. /// /// # Errors /// Returns the error of the method the operation names. A `Read` or a /// `ReadNumbered` also returns [`VfsError::InvalidRange`] for a /// `start` below 1, an `end` before `start`, or an `end` given with no /// `start`. A `Remove` returns [`VfsError::NotFound`] when the path is /// absent. pub fn perform(&self, op: &VfsOp) -> Result { let done = |()| VfsOutcome::Unit; match op { VfsOp::Write { path, contents } => self.write(path, contents).map(done), VfsOp::Append { path, contents } => self.append(path, contents).map(done), VfsOp::Read { path, start, end } => { read_lines(self, path, *start, *end, LineNumbers::Omitted).map(VfsOutcome::Text) } VfsOp::ReadNumbered { path, start, end } => { read_lines(self, path, *start, *end, LineNumbers::Prefixed).map(VfsOutcome::Text) } VfsOp::StrReplace { path, old, new } => self.str_replace(path, old, new).map(done), VfsOp::Delete { path } => self.remove(path, false).map(|_| VfsOutcome::Unit), VfsOp::Glob { pattern } => self.glob(pattern).map(VfsOutcome::Paths), VfsOp::Exists { path } => self.exists(path).map(VfsOutcome::Bool), VfsOp::Stat { path } => self.stat(path).map(VfsOutcome::Stat), VfsOp::List { path } => self.list(path).map(VfsOutcome::Entries), VfsOp::ReadRange { path, offset, len } => { self.read_range(path, *offset, *len).map(VfsOutcome::Bytes) } VfsOp::Mkdir { path, recursive } => self.mkdir(path, *recursive).map(done), VfsOp::Remove { path, recursive } => self.remove_present(path, *recursive).map(done), VfsOp::Rename { from, to } => self.rename(from, to).map(done), VfsOp::Copy { from, to } => self.copy(from, to).map(done), } } /// Reads the bytes of the file at `path`, exactly as stored. /// /// # Errors /// Returns an error when the policy denies the read, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn read(&self, path: &str) -> Result, VfsError> { let path = self.gate(Op::Read, path)?; self.admit(Claims::claim_read, &path)?; self.fire(Op::Read, &path); self.inner().read(&path) } /// Reads the file at `path` as UTF-8 text. /// /// # Errors /// Returns an error under the same conditions as `Access::read`, or /// when the file's contents are not UTF-8. pub fn read_string(&self, path: &str) -> Result { let bytes = self.read(path)?; String::from_utf8(bytes).map_err(|err| VfsError::NotUtf8 { path: path.to_owned(), valid_up_to: err.utf8_error().valid_up_to(), }) } /// Reads up to `len` bytes of the file at `path`, starting at byte /// `offset`. /// /// It returns fewer than `len` bytes when the file ends first, and /// nothing when `offset` is at or past the end. `RealBackend` seeks /// and reads only the requested bytes. A backend without an override /// reads the whole file and slices it, so the read is not bounded /// there. /// /// # Errors /// Returns an error when the policy denies the read, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn read_range(&self, path: &str, offset: u64, len: u64) -> Result, VfsError> { let path = self.gate(Op::Read, path)?; self.admit(Claims::claim_read, &path)?; self.fire(Op::Read, &path); self.inner().read_range(&path, offset, len) } /// Creates or overwrites the file at `path` with `contents`. /// /// # Errors /// Returns an error when the policy denies the write, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn write(&self, path: &str, contents: &[u8]) -> Result<(), VfsError> { let path = self.gate(Op::Write, path)?; self.admit(Claims::claim_write, &path)?; self.fire(Op::Write, &path); self.inner().write(&path, contents) } /// Appends `contents` to the file at `path`, creating the file if it /// is absent. /// /// # Errors /// Returns an error when the policy denies the append, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn append(&self, path: &str, contents: &[u8]) -> Result<(), VfsError> { let path = self.gate(Op::Append, path)?; self.admit(Claims::claim_write, &path)?; self.fire(Op::Append, &path); self.inner().append(&path, contents) } /// Replaces the single occurrence of `old` with `new` in the file at /// `path`. /// /// # Errors /// Returns an error when `old` is empty, when the policy denies the /// write, when this access checks claims and another access holds a /// conflicting claim on `path` that is not ordered before this /// operation, when `old` occurs zero times or more than once, or /// when the backend fails. pub fn str_replace(&self, path: &str, old: &str, new: &str) -> Result<(), VfsError> { // The store view validates the path before the anchor, in the // store contract's order. if self.store_view { validate_store_path(path)?; } if old.is_empty() { return Err(VfsError::Anchor { path: path.to_owned(), anchor: String::new(), count: 0, }); } let path = self.gate(Op::Write, path)?; self.admit(Claims::claim_write, &path)?; self.fire(Op::Write, &path); self.inner().str_replace(&path, old, new) } /// Removes the file, link, or directory at `path`. /// /// Set `recursive` to also remove a directory that holds entries, /// along with everything under it. Returns `Ok(true)` when the /// removal succeeds and `Ok(false)` when `path` is absent, so /// removing the same path twice succeeds. /// /// # Errors /// Returns an error when the policy denies the delete, when this /// access checks claims and another access holds a conflicting claim /// that is not ordered before this operation, or when the backend /// fails. A recursive removal claims the whole subtree under `path`. pub fn remove(&self, path: &str, recursive: bool) -> Result { match self.remove_present(path, recursive) { Ok(()) => Ok(true), // The backend trait reports an absent path as NotFound; the // public capability confirms the absence instead. Err(VfsError::NotFound { .. }) => Ok(false), Err(err) => Err(err), } } /// Removes the file, link, or directory at `path` under the checks of /// [`Access::remove`], and reports an absent path as the backend /// does, with [`VfsError::NotFound`]. fn remove_present(&self, path: &str, recursive: bool) -> Result<(), VfsError> { let path = self.gate(Op::Delete, path)?; if recursive { self.admit(Claims::claim_subtree, &path)?; } else { self.admit(Claims::claim_write, &path)?; } self.fire(Op::Delete, &path); self.inner().remove(&path, recursive) } /// Reports whether anything exists at `path`. /// /// Returns `Ok(false)` only when the path is confirmed absent. /// /// # Errors /// Returns an error when the policy denies the check, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn exists(&self, path: &str) -> Result { let path = self.gate(Op::Exists, path)?; self.admit(Claims::claim_read, &path)?; self.fire(Op::Exists, &path); self.inner().exists(&path) } /// Returns the sorted paths of the files, or of the directories, that /// match `pattern`. /// /// A pattern that ends in `/` matches only directories. Any other /// pattern matches only files. A pattern that starts with `/` is /// absolute. Any other pattern is relative to `/`, and its results /// come back relative too, without their leading `/`. No pattern /// matches the root itself. /// /// The raw pattern is validated before it is canonicalized. Because /// of this, a backslash or a control character is refused, and a /// backslash never becomes a path separator. /// /// # Errors /// Returns an error when the pattern is malformed: empty, too long, /// containing a control character or a backslash, or breaking the /// glob grammar. On a store view, an access from `Store::view`, the /// pattern is also malformed when the store's strict path rules /// refuse it. Each malformed pattern /// reports the rule it broke as a [`PathReason`] in the /// [`VfsError::InvalidPath`]. It also returns an error when the /// policy denies the glob, when this access checks claims and /// another access holds a conflicting claim that is not ordered /// before this operation, or when the backend fails. One claim /// covers the pattern as a whole. pub fn glob(&self, pattern: &str) -> Result, VfsError> { if pattern.is_empty() { return Err(VfsError::InvalidPath { path: pattern.to_owned(), reason: PathReason::Empty, }); } if let Err(reason) = validate_glob_pattern(pattern) { return Err(VfsError::InvalidPath { path: pattern.to_owned(), reason, }); } // A trailing `/` asks for directories only; matching and the // claim key use the pattern without it. let dirs_only = pattern.ends_with('/'); let stripped = pattern.trim_end_matches('/'); let pattern = if stripped.is_empty() { "/" } else { stripped }; self.glob_pattern(pattern, dirs_only) } /// The canonical-pattern half of [`Access::glob`]: gates, claims, /// fires, and matches one pattern whose trailing `/` was already /// split off into `dirs_only`. Crate-private so the mounted-handle /// forward can preserve the flag it received. pub(super) fn glob_pattern( &self, pattern: &str, dirs_only: bool, ) -> Result, VfsError> { let relative = !pattern.starts_with('/'); // The claim key is the canonicalized pattern; the backend // receives it canonical too. let claimed = self.gate(Op::Glob, pattern)?; self.admit(Claims::claim_glob, &claimed)?; self.fire(Op::Glob, &claimed); let mut matches = self.inner().glob_kind(claimed.as_str(), dirs_only)?; if relative { for matched in &mut matches { if let Some(rest) = strip_root(matched) { *matched = rest; } } } Ok(matches) } /// Lists the entries of the directory at `path`. /// /// # Errors /// Returns an error when the policy denies the list, when this /// access checks claims and another access holds a conflicting claim /// on the directory's children that is not ordered before this /// operation, or when the backend fails. pub fn list(&self, path: &str) -> Result, VfsError> { let path = self.gate(Op::List, path)?; self.admit(Claims::claim_list, &path)?; self.fire(Op::List, &path); self.inner().list(&path) } /// Returns metadata for `path`. /// /// # Errors /// Returns an error when the policy denies the stat, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn stat(&self, path: &str) -> Result { let path = self.gate(Op::Stat, path)?; self.admit(Claims::claim_read, &path)?; self.fire(Op::Stat, &path); self.inner().stat(&path) } /// Creates the directory at `path`. /// /// Set `recursive` to also create any missing parent directories. /// /// # Errors /// Returns an error when the policy denies the mkdir, when this /// access checks claims and another access holds a conflicting claim /// on `path` that is not ordered before this operation, or when the /// backend fails. pub fn mkdir(&self, path: &str, recursive: bool) -> Result<(), VfsError> { let path = self.gate(Op::Mkdir, path)?; self.admit(Claims::claim_write, &path)?; self.fire(Op::Mkdir, &path); self.inner().mkdir(&path, recursive) } /// Renames or moves `from` to `to`. /// /// The move is atomic where the backend allows it. An access that /// checks claims claims the source as the whole subtree it moves, /// and the destination as a write. /// /// # Errors /// Returns an error when the policy denies the rename, when this /// access checks claims and another access holds a conflicting claim /// on either path that is not ordered before this operation, or when /// the backend fails. pub fn rename(&self, from: &str, to: &str) -> Result<(), VfsError> { let from = self.gate(Op::Rename, from)?; let to = self.gate(Op::Rename, to)?; // Both paths gated, so the operation is admitted: the source // subtree and the destination are claimed, then one event per // canonical path. let to_key = self.claim_key(&to); self.admit( |claims, scope, id, from| claims.claim_rename(scope, id, from, &to_key), &from, )?; self.fire(Op::Rename, &from); self.fire(Op::Rename, &to); self.inner().rename(&from, &to) } /// Copies the file at `from` to `to`. /// /// An access that checks claims claims the source as a read and the /// destination as a write. /// /// # Errors /// Returns an error when the policy denies the copy, when this /// access checks claims and another access holds a conflicting claim /// on either path that is not ordered before this operation, or when /// the backend fails. pub fn copy(&self, from: &str, to: &str) -> Result<(), VfsError> { let from = self.gate(Op::Copy, from)?; let to = self.gate(Op::Copy, to)?; let to_key = self.claim_key(&to); self.admit( |claims, scope, id, from| claims.claim_copy(scope, id, from, &to_key), &from, )?; self.fire(Op::Copy, &from); self.fire(Op::Copy, &to); self.inner().copy(&from, &to) } }