//! Safe filesystem access: every operation resolves //! `//`, canonicalizes it and verifies //! the result is still inside the user's root (blocks `..` and symlink escapes). use std::io::Read; use std::path::{Component, Path, PathBuf}; use std::time::UNIX_EPOCH; use chrono::DateTime; use api_types::{Entry, FileKind}; use crate::error::ApiError; #[derive(Debug, thiserror::Error)] pub enum FsError { #[error("folder not found")] NotFound, #[error("not a folder")] NotADirectory, #[error("access denied")] Forbidden, #[error("the configured folder no longer exists")] RootMissing, #[error("already exists")] Conflict, #[error("{0}")] Invalid(String), } impl From for ApiError { fn from(e: FsError) -> Self { use axum::http::StatusCode as S; match &e { FsError::NotFound => { ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_not_found") } FsError::NotADirectory => { ApiError::localized(S::BAD_REQUEST, e.to_string(), "err_fs_not_a_dir") } FsError::Forbidden => { ApiError::localized(S::FORBIDDEN, e.to_string(), "err_fs_forbidden") } FsError::RootMissing => { ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_root_missing") } FsError::Conflict => ApiError::localized(S::CONFLICT, e.to_string(), "err_fs_conflict"), // Dynamic message (e.g. an invalid name), not a fixed string. FsError::Invalid(_) => ApiError::new(S::BAD_REQUEST, e.to_string()), } } } /// Resolve a user root (path relative to the server root) to a canonical /// absolute path, verified to be inside the server root. pub fn resolve_root(server_root: &Path, root_rel: &str) -> Result { let candidate = server_root.join(root_rel); let canonical = candidate.canonicalize().map_err(|_| FsError::RootMissing)?; ensure_within(server_root, &canonical)?; if !canonical.is_dir() { return Err(FsError::RootMissing); } Ok(canonical) } /// Resolve a requested path (relative to a user root) safely. pub fn resolve_path(server_root: &Path, root_rel: &str, req_rel: &str) -> Result { let root_abs = resolve_root(server_root, root_rel)?; let req = Path::new(req_rel); for c in req.components() { if matches!(c, Component::ParentDir) { return Err(FsError::Forbidden); } } let full = root_abs.join(req); let full = full.canonicalize().map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => FsError::NotFound, _ => FsError::Forbidden, })?; ensure_within(&root_abs, &full)?; Ok(full) } /// Resolve a share target that is a single file (relative to the server root). /// Unlike [`resolve_path`], the target itself is the file — there is no /// directory root beneath it. pub fn resolve_file(server_root: &Path, rel: &str) -> Result { let full = server_root.join(rel); let full = full.canonicalize().map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => FsError::NotFound, _ => FsError::Forbidden, })?; ensure_within(server_root, &full)?; Ok(full) } /// Whether the entry at `p` is itself a directory. A symlink is not, however /// its target looks: an operation on the name must not recurse into a tree the /// request never named. fn entry_is_dir(p: &Path) -> bool { std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir()) } /// Whether a name is taken. Unlike `Path::exists`, a dangling symlink counts: /// it still occupies the name. fn entry_exists(p: &Path) -> bool { std::fs::symlink_metadata(p).is_ok() } fn ensure_within(base: &Path, p: &Path) -> Result<(), FsError> { if p == base || p.starts_with(base) { Ok(()) } else { Err(FsError::Forbidden) } } /// List a directory (blocking — call via spawn_blocking). The `bool` is true /// when the listing was cut to [`api_types::MAX_LIST_ENTRIES`]. pub fn list_dir(dir: &Path) -> Result<(Vec, bool), FsError> { let rd = std::fs::read_dir(dir).map_err(|e| match e.kind() { std::io::ErrorKind::NotFound => FsError::NotFound, std::io::ErrorKind::NotADirectory => FsError::NotADirectory, _ => FsError::Forbidden, })?; // Pass 1: names only. Walking the directory stream is inherently // sequential, but it is also the only part that has to be: every field // below comes from a per-entry syscall, which pass 2 can do in parallel. // The values here are the fallbacks used when that syscall fails. let mut rows: Vec<(Entry, PathBuf)> = Vec::new(); for e in rd.flatten() { let entry = Entry { name: e.file_name().to_string_lossy().into_owned(), is_dir: false, size: 0, mtime: EPOCH_MTIME.to_string(), kind: FileKind::Binary, }; rows.push((entry, e.path())); } // Pass 2: metadata, which the sort needs (folders first). describe_rows(&mut rows, fill_meta); // Folders first, then case-insensitive name. Sorting after pass 2 means // the parallel fan-out cannot affect the order. rows.sort_by_cached_key(|(e, _)| (!e.is_dir, e.name.to_lowercase(), e.name.clone())); // Cut over-long listings here, so the sniff below never sees the tail. // The client cannot render that many rows anyway. let truncated = rows.len() > api_types::MAX_LIST_ENTRIES; rows.truncate(api_types::MAX_LIST_ENTRIES); // Pass 3: the content sniff, the expensive per-entry syscall. describe_rows(&mut rows, fill_kind); Ok((rows.into_iter().map(|(e, _)| e).collect(), truncated)) } // --------------------------------------------------------------------------- // Content sniffing // --------------------------------------------------------------------------- /// How many leading bytes we read to classify a file. Every magic number /// `infer` knows lives in the first few dozen bytes; 256 also gives the /// text/binary heuristic enough to work with. Measured at ~4.6 µs per file, /// against ~1.4 µs for the `metadata` call in the same pass. const SNIFF_BYTES: usize = 256; /// Entries per thread, and the point below which parallelism is not worth it. /// Measured on a 22-core machine: at 50 entries fan-out is a wash (thread /// spawn costs about as much as the work), at 200 it is already 2x. const SNIFF_CHUNK: usize = 256; /// Process-wide ceiling on threads spawned for sniffing, so many concurrent /// listings of large directories cannot multiply into a thread explosion. /// One listing alone can use the whole budget; the next one degrades to fewer /// threads, and eventually to serial, instead of queueing. static SNIFF_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); fn sniff_budget_total() -> usize { static TOTAL: std::sync::LazyLock = std::sync::LazyLock::new(|| { std::thread::available_parallelism() .map(|n| n.get()) .unwrap_or(1) }); *TOTAL } /// Claimed helper threads, returned to [`SNIFF_BUDGET`] on drop. struct SniffPermit(usize); impl SniffPermit { /// Claim up to `want` helper threads, or fewer when the budget is thin. fn claim(want: usize) -> Self { use std::sync::atomic::Ordering; let total = sniff_budget_total(); let mut granted = 0; let _ = SNIFF_BUDGET.fetch_update(Ordering::AcqRel, Ordering::Acquire, |in_flight| { granted = want.min(total.saturating_sub(in_flight)); (granted > 0).then_some(in_flight + granted) }); Self(granted) } } impl Drop for SniffPermit { fn drop(&mut self) { if self.0 > 0 { SNIFF_BUDGET.fetch_sub(self.0, std::sync::atomic::Ordering::AcqRel); } } } /// Metadata for one row. Follows symlinks; a broken link keeps the caller's /// fallbacks and so shows up as an empty file. fn fill_meta(entry: &mut Entry, path: &Path) { if let Ok(m) = std::fs::metadata(path) { entry.is_dir = m.is_dir(); entry.size = m.len(); entry.mtime = mtime_str(&m); } } /// The content sniff for one row. Needs `is_dir`, so it runs after /// [`fill_meta`]. fn fill_kind(entry: &mut Entry, path: &Path) { entry.kind = detect_kind(path, entry.is_dir); } /// Apply `one` to each row, fanning the work out across threads for big /// directories. /// /// The calling thread takes a chunk too, so `n` helper threads process `n + 1` /// chunks and a zero-thread grant is simply the serial path. fn describe_rows(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) { fn describe(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) { for (entry, path) in rows { one(entry, path); } } if rows.len() < SNIFF_CHUNK { describe(rows, one); return; } // One chunk per helper thread plus one for this thread. let want = rows.len().div_ceil(SNIFF_CHUNK).saturating_sub(1); let permit = SniffPermit::claim(want); if permit.0 == 0 { describe(rows, one); return; } let chunk = rows.len().div_ceil(permit.0 + 1); std::thread::scope(|s| { let mut rest = rows; // Hand every chunk but the last to a helper thread. while rest.len() > chunk { let (head, tail) = rest.split_at_mut(chunk); s.spawn(move || describe(head, one)); rest = tail; } describe(rest, one); }); } /// Classify a directory entry by reading its first [`SNIFF_BYTES`] bytes. /// /// Blocking — called from `list_dir` (itself under `spawn_blocking`), on /// several threads at once for large directories. An unreadable file is /// reported as [`FileKind::Binary`] rather than failing the whole listing. /// // ponytail: one open() per entry, fanned out but not cached. Measured warm on // 22 cores: 5000 entries take 29 ms serially and 6.9 ms across threads. The // remaining ceiling is a cold cache or a network filesystem (NFS/SMB), where // each entry costs a round trip. If that shows up: cache by (dev, ino, mtime), // or skip the sniff for zero-byte files. pub fn detect_kind(path: &Path, is_dir: bool) -> FileKind { if is_dir { return FileKind::Dir; } let mut head = [0u8; SNIFF_BYTES]; // A read error is *not* the same as an empty file: an empty file is text // (it opens in the editor), an unreadable one gets no viewer offered. match std::fs::File::open(path).and_then(|mut f| f.read(&mut head)) { Ok(n) => kind_from_bytes(&head[..n], path), Err(_) => FileKind::Binary, } } /// The pure half of [`detect_kind`], so it can be unit-tested without a disk. /// /// `path` is consulted only for the SVG case: SVG is XML text with no magic /// number, but browsers render it as an image, so the extension is the only /// thing that can tell us to offer an image preview. fn kind_from_bytes(head: &[u8], path: &Path) -> FileKind { if let Some(t) = infer::get(head) { // PDF is filed under `Archive` by `infer`, so match the MIME first. if t.mime_type() == "application/pdf" { return FileKind::Pdf; } return match t.matcher_type() { infer::MatcherType::Image => FileKind::Image, infer::MatcherType::Video => FileKind::Video, infer::MatcherType::Audio => FileKind::Audio, infer::MatcherType::Archive => FileKind::Archive, infer::MatcherType::Text => FileKind::Text, // App / Book / Font / Doc / Custom: recognized, but nothing we // can show in the browser. _ => FileKind::Binary, }; } if !looks_like_text(head) { return FileKind::Binary; } let ext = path .extension() .map(|e| e.to_string_lossy().to_lowercase()) .unwrap_or_default(); if ext == "svg" { FileKind::Image } else { FileKind::Text } } /// Text heuristic for the files `infer` has no signature for (plain text, /// source code, most config formats): no NUL byte, and the head decodes as /// UTF-8 once a truncated trailing character is discounted. /// /// An empty file counts as text — it opens in the editor, which is what you /// want for a file you just created. fn looks_like_text(head: &[u8]) -> bool { if head.contains(&0) { return false; } match std::str::from_utf8(head) { Ok(_) => true, // A multi-byte character cut in half by the read boundary is fine; // anything else is not text. `error_len() == None` means "unexpected // end of input", i.e. truncation. Err(e) => e.error_len().is_none() && e.valid_up_to() + 4 > head.len(), } } /// Reported when a file's modification time is unavailable or unrepresentable. const EPOCH_MTIME: &str = "1970-01-01T00:00:00Z"; /// A file's modification time in whole unix seconds, or `None` when the /// platform cannot report one. The single place that converts a `SystemTime`. pub fn mtime_secs(m: &std::fs::Metadata) -> Option { m.modified() .ok() .and_then(|t| t.duration_since(UNIX_EPOCH).ok()) .map(|d| d.as_secs() as i64) } fn mtime_str(m: &std::fs::Metadata) -> String { let dt: Option> = mtime_secs(m).and_then(|s| DateTime::from_timestamp(s, 0)); dt.map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)) .unwrap_or_else(|| EPOCH_MTIME.to_string()) } // --------------------------------------------------------------------------- // Mutations (milestone 3): mkdir, rename, remove, move, copy, upload // --------------------------------------------------------------------------- /// Resolve a directory that must exist (relative to a user root). Used as the /// base for operations that target the *parent* of the item. pub fn resolve_dir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result { let full = resolve_path(server_root, root_rel, req_rel)?; if !full.is_dir() { return Err(FsError::NotADirectory); } Ok(full) } /// Validate a new single-component name (for rename / new folder). fn validate_component(name: &str) -> Result<(), FsError> { let p = Path::new(name); if name.is_empty() || p.components().count() != 1 || name == "." || name == ".." || name.contains(['/', '\\', '\0']) { return Err(FsError::Invalid("invalid name".to_string())); } Ok(()) } /// Create a directory (and any missing parents) inside a user root. pub fn mkdir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> { let full = resolve_entry(server_root, root_rel, req_rel)?; if full.exists() { return Err(FsError::Conflict); } std::fs::create_dir_all(&full).map_err(|e| io_err(e, &full))?; Ok(()) } /// Create an empty file. The parent must exist; the file must not. pub fn create_file(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> { let full = resolve_entry(server_root, root_rel, req_rel)?; // create_new = O_EXCL: fails on an existing path, does not follow a symlink. std::fs::File::create_new(&full).map_err(|e| match e.kind() { std::io::ErrorKind::AlreadyExists => FsError::Conflict, _ => io_err(e, &full), })?; Ok(()) } /// Resolve a path that names an *entry*, not the file that entry may point at. /// /// The last component is never followed and need not exist. The parent must, /// and is canonicalized and checked against the root. /// /// This is the resolver for operations that act on the name: create, delete, /// rename, the source of a move, the destination of a move or copy. Following /// a symlink there would delete a file the request never mentioned, or rename /// one into a different directory. Reads and content writes use /// [`resolve_path`] instead and do follow, contained by `ensure_within`. pub(crate) fn resolve_entry( server_root: &Path, root_rel: &str, req_rel: &str, ) -> Result { let root_abs = resolve_root(server_root, root_rel)?; let req = Path::new(req_rel); for c in req.components() { if matches!(c, Component::ParentDir) { return Err(FsError::Forbidden); } } let full = root_abs.join(req); // The parent must exist and stay inside the root. let parent = full .parent() .filter(|p| !p.as_os_str().is_empty()) .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?; let parent = parent.canonicalize().map_err(|e| io_err(e, parent))?; ensure_within(&root_abs, &parent)?; // Re-join onto the *canonical* parent. `full` may still spell a symlinked // directory, and a caller comparing it against another resolved path (see // [`move_to`]) would then compare two different spellings of one place. let name = full .file_name() .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?; Ok(parent.join(name)) } /// Rename (or move within the same directory) an item. /// Returns the path the item was renamed *away from*, so the caller can /// revoke anything (a share) that still names it. pub fn rename_item( server_root: &Path, root_rel: &str, req_rel: &str, new_name: &str, overwrite: bool, ) -> Result { validate_component(new_name)?; let from = resolve_entry(server_root, root_rel, req_rel)?; let parent = from .parent() .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?; let to = parent.join(new_name); // Renaming onto itself is a no-op (the overwrite path below would // delete the file before the rename). Nothing was vacated. if to == from { return Ok(to); } // `rename` replaces a file target atomically; no remove-then-rename gap. if entry_exists(&to) && (!overwrite || entry_is_dir(&to) || entry_is_dir(&from)) { return Err(FsError::Conflict); } std::fs::rename(&from, &to).map_err(|e| io_err(e, &to))?; Ok(from) } /// Delete a file or a directory tree. Returns whether it was a directory, and /// the path that is now gone (so the caller can revoke shares naming it). pub fn remove_item( server_root: &Path, root_rel: &str, req_rel: &str, ) -> Result<(bool, PathBuf), FsError> { let full = resolve_entry(server_root, root_rel, req_rel)?; // A symlink is unlinked, never followed: deleting it must not delete the // file it names. A dangling link is deletable for the same reason. let is_dir = entry_is_dir(&full); if is_dir { std::fs::remove_dir_all(&full).map_err(|e| io_err(e, &full))?; } else { std::fs::remove_file(&full).map_err(|e| io_err(e, &full))?; } Ok((is_dir, full)) } /// Overwrite an existing file's contents (the editor's save path). /// /// The file must already exist and be a regular file. If `expected_mtime` /// (whole unix seconds) is provided and differs from the file's current mtime, /// the file changed on disk since it was read → `Conflict` (409). Returns the /// file's new mtime (unix seconds) after a successful write. pub fn save_file( server_root: &Path, root_rel: &str, req_rel: &str, content: &[u8], expected_mtime: Option, ) -> Result { let full = resolve_path(server_root, root_rel, req_rel)?; // must exist write_checked(&full, content, expected_mtime) } /// The share-aware variant of [`save_file`]: for a *file* share the root is /// the file itself, so `target` (relative to `server_root`) points at the /// file — there is no directory root beneath it. pub fn save_file_at( server_root: &Path, target: &str, content: &[u8], expected_mtime: Option, ) -> Result { let full = resolve_file(server_root, target)?; // must exist write_checked(&full, content, expected_mtime) } fn write_checked(full: &Path, content: &[u8], expected_mtime: Option) -> Result { let meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?; if meta.is_dir() { return Err(FsError::NotADirectory); } if let Some(expected) = expected_mtime { // No readable mtime means the check cannot pass: -1 never matches. if mtime_secs(&meta).unwrap_or(-1) != expected { return Err(FsError::Conflict); } } std::fs::write(full, content).map_err(|e| io_err(e, full))?; // Read the new mtime so the client can anchor the next conflict check. let new_meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?; Ok(mtime_secs(&new_meta).unwrap_or(0)) } fn io_err(e: std::io::Error, p: &Path) -> FsError { tracing::warn!(error = %e, path = %p.display(), "filesystem error"); match e.kind() { std::io::ErrorKind::NotFound => FsError::NotFound, _ => FsError::Forbidden, } } /// True if `a` is `b` or a descendant of `b` (both canonical). pub(crate) fn is_within_or_eq(base: &Path, p: &Path) -> bool { p == base || p.starts_with(base) } /// Move an item (possibly across roots). `dst_dir_rel` is the destination /// directory (relative to `dst_root_rel`); the item keeps its base name. /// /// Returns the path the item was moved *away from*, like [`rename_item`]. pub fn move_item( server_root: &Path, src_root_rel: &str, src_rel: &str, dst_root_rel: &str, dst_dir_rel: &str, overwrite: bool, ) -> Result { let from = resolve_entry(server_root, src_root_rel, src_rel)?; let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?; let name = from .file_name() .ok_or_else(|| FsError::Invalid("invalid path".to_string()))? .to_owned(); let to = dst_dir.join(&name); // A no-op (item already at the destination) — treat as success. Nothing // was vacated. if to == from { return Ok(to); } // Refuse moving a directory into itself or a descendant. if entry_is_dir(&from) && is_within_or_eq(&from, &dst_dir) { return Err(FsError::Invalid( "cannot move a folder into itself".to_string(), )); } check_move_conflict(&to, &from, overwrite)?; rename_or_copy(&from, &to)?; Ok(from) } /// Copy an item (possibly across roots). pub fn copy_item( server_root: &Path, src_root_rel: &str, src_rel: &str, dst_root_rel: &str, dst_dir_rel: &str, overwrite: bool, ) -> Result<(), FsError> { // Two resolutions of one path, because a copy of a symlink wants both // halves: the bytes of the file it names, under the name of the link // itself. `cp` does the same. let from = resolve_path(server_root, src_root_rel, src_rel)?; let entry = resolve_entry(server_root, src_root_rel, src_rel)?; let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?; let name = entry .file_name() .ok_or_else(|| FsError::Invalid("invalid path".to_string()))? .to_owned(); let to = dst_dir.join(&name); // A no-op (item already at the destination) — treat as success. if to == from { return Ok(()); } if from.is_dir() && is_within_or_eq(&from, &dst_dir) { return Err(FsError::Invalid( "cannot copy a folder into itself".to_string(), )); } check_move_conflict(&to, &from, overwrite)?; copy_recursive(&from, &to)?; Ok(()) } /// Move an item to an explicit destination path (the WebDAV `MOVE` shape). /// /// Unlike [`move_item`], the destination names the item itself, so this also /// renames. There is no overwrite check here: the WebDAV layer has already /// refused, or deleted, an existing destination by the time this runs. pub fn move_to( server_root: &Path, src_root_rel: &str, src_rel: &str, dst_root_rel: &str, dst_rel: &str, ) -> Result<(), FsError> { // An entry, not its target: moving a symlink moves the link. let from = resolve_entry(server_root, src_root_rel, src_rel)?; let to = resolve_dest(server_root, &from, dst_root_rel, dst_rel)?; if from == to { return Ok(()); } rename_or_copy(&from, &to) } /// `rename`, falling back to copy-then-remove when the two paths are on /// different filesystems. /// /// A symlink is refused on the fallback path. `copy_recursive` stats with /// `metadata`, which follows, so it would replace the link with a copy of its /// target, and that target may be outside the root. Plain `rename` moves the /// link itself and needs no such guard. fn rename_or_copy(from: &Path, to: &Path) -> Result<(), FsError> { match std::fs::rename(from, to) { Ok(()) => Ok(()), Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => { if std::fs::symlink_metadata(from).is_ok_and(|m| m.file_type().is_symlink()) { return Err(FsError::Forbidden); } copy_recursive(from, to)?; if entry_is_dir(from) { std::fs::remove_dir_all(from).map_err(|e| io_err(e, from))?; } else { std::fs::remove_file(from).map_err(|e| io_err(e, from))?; } Ok(()) } Err(e) => Err(io_err(e, to)), } } /// Copy to an explicit destination path (the WebDAV `COPY` shape). The WebDAV /// layer only ever asks for a single file: it walks a tree itself, one /// `create_dir` and one `copy` per entry. pub fn copy_file_to( server_root: &Path, src_root_rel: &str, src_rel: &str, dst_root_rel: &str, dst_rel: &str, ) -> Result<(), FsError> { // The source *is* followed: a copy wants the file's bytes, the way `cp` // does. `resolve_path` still refuses a link that leaves the root. let from = resolve_path(server_root, src_root_rel, src_rel)?; let to = resolve_dest(server_root, &from, dst_root_rel, dst_rel)?; if from == to { return Ok(()); } copy_recursive(&from, &to) } /// Copy one file, replacing a symlink at the destination instead of writing /// through it. /// /// `std::fs::copy` follows a destination symlink, so a link out of the root /// makes the copy land outside it with every path check passing. Every caller /// here has already decided the destination may be overwritten, so unlinking /// first is also the semantics they wanted. `rename` needs no such guard; it /// replaces the link rather than following it. fn copy_file(src: &Path, dst: &Path) -> Result<(), FsError> { if std::fs::symlink_metadata(dst).is_ok_and(|m| m.file_type().is_symlink()) { std::fs::remove_file(dst).map_err(|e| io_err(e, dst))?; } std::fs::copy(src, dst).map_err(|e| io_err(e, dst))?; Ok(()) } /// Resolve the destination of a move or copy that names it in full. /// /// A destination *inside* `from` is refused, which is what stops /// `MOVE /a /a/b` from eating itself. The source is the caller's to resolve: a /// move relocates the entry, a copy wants the bytes, so the two follow a /// symlink differently. fn resolve_dest( server_root: &Path, from: &Path, dst_root_rel: &str, dst_rel: &str, ) -> Result { let to = resolve_entry(server_root, dst_root_rel, dst_rel)?; if from != to && entry_is_dir(from) && is_within_or_eq(&to, from) { return Err(FsError::Invalid( "cannot move a folder into itself".to_string(), )); } Ok(to) } /// Conflict rules shared by move and copy: /// - target is a directory → always conflict (no silent merge) /// - target is a file → conflict unless overwriting a file with a file fn check_move_conflict(to: &Path, from: &Path, overwrite: bool) -> Result<(), FsError> { if entry_exists(to) { let to_dir = entry_is_dir(to); let from_dir = entry_is_dir(from); if to_dir || from_dir || !overwrite { return Err(FsError::Conflict); } } Ok(()) } /// Recursively copy a file or directory tree, preserving mtime. fn copy_recursive(src: &Path, dst: &Path) -> Result<(), FsError> { let meta = std::fs::metadata(src).map_err(|e| io_err(e, src))?; if meta.is_dir() { std::fs::create_dir(dst).map_err(|e| io_err(e, dst))?; for e in std::fs::read_dir(src) .map_err(|e| io_err(e, src))? .flatten() { copy_recursive(&e.path(), &dst.join(e.file_name()))?; } } else { copy_file(src, dst)?; } set_mtime(dst, meta.modified().ok()); Ok(()) } fn set_mtime(p: &Path, t: Option) { if let (Some(t), Ok(f)) = (t, std::fs::File::open(p)) { let _ = f.set_modified(t); } } // --------------------------------------------------------------------------- // Tests // --------------------------------------------------------------------------- #[cfg(test)] mod tests { use super::*; /// A temp dir used as the "server root" with a small fixture tree: /// /// ```text /// root/ /// docs/ /// inner/ /// hello.txt /// a.txt /// src/ /// main.rs /// file.txt /// ``` struct T { tmp: tempfile::TempDir, root: PathBuf, } impl T { fn new() -> Self { let tmp = tempfile::tempdir().unwrap(); let root = tmp.path().to_path_buf(); std::fs::create_dir_all(root.join("docs/inner")).unwrap(); std::fs::create_dir_all(root.join("src")).unwrap(); std::fs::write(root.join("docs/inner/hello.txt"), "hello").unwrap(); std::fs::write(root.join("docs/a.txt"), "a").unwrap(); std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap(); std::fs::write(root.join("file.txt"), "top file").unwrap(); Self { tmp, root } } /// A directory that lives *next to* the root (outside of it), for /// symlink/escape tests. The tempdir name is unique, so the sibling /// name is unique too. fn sibling(&self, name: &str) -> PathBuf { let base = self .tmp .path() .file_name() .unwrap() .to_string_lossy() .into_owned(); let p = self.tmp.path().with_file_name(format!("{base}-{name}")); std::fs::create_dir_all(&p).unwrap(); p } } // ---------- validate_component ---------- #[test] fn validate_name_accepts_simple_names() { for ok in ["a", "file.txt", "my folder", "Ünïcödé", "with-dash_1.2.3"] { assert!(validate_component(ok).is_ok(), "{ok:?} should be valid"); } } #[test] fn validate_name_rejects_traversal_and_paths() { for bad in [ "", ".", "..", "a/b", "a\\b", "a\0b", "/abs", "../x", "x/../y", "x/", "/x", ] { assert!( validate_component(bad).is_err(), "{bad:?} should be invalid" ); } } // ---------- resolve_root ---------- #[test] fn resolve_root_whole_root_and_subdir() { let t = T::new(); let root = t.root.canonicalize().unwrap(); // "." means the whole root. assert_eq!(resolve_root(&root, ".").unwrap(), root); assert_eq!(resolve_root(&root, "docs").unwrap(), root.join("docs")); assert_eq!( resolve_root(&root, "docs/inner").unwrap(), root.join("docs/inner") ); } #[test] fn resolve_root_rejects_escape_and_missing() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let sib = t.sibling("escape"); let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned(); // Escapes that land on *existing* paths outside the root. for esc in [ "..".to_string(), "docs/../..".to_string(), format!("../{sib_rel}"), ] { assert!( matches!(resolve_root(&root, &esc), Err(FsError::Forbidden)), "{esc:?} should be forbidden" ); } // Escapes to non-existing paths simply don't exist. for esc in ["../no-such-dir", "a/b/../../..", "nope"] { assert!( matches!(resolve_root(&root, esc), Err(FsError::RootMissing)), "{esc:?} should be missing" ); } // A file is not a valid root. assert!(matches!( resolve_root(&root, "file.txt"), Err(FsError::RootMissing) )); } #[cfg(unix)] #[test] fn resolve_root_rejects_symlink_escape() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let outside = t.sibling("outside"); std::os::unix::fs::symlink(&outside, root.join("link")).unwrap(); assert!(matches!( resolve_root(&root, "link"), Err(FsError::Forbidden) )); } // ---------- resolve_path ---------- #[test] fn resolve_path_traverses_inside_root() { let t = T::new(); let root = t.root.canonicalize().unwrap(); // Empty relative path → the root itself. assert_eq!(resolve_path(&root, ".", "").unwrap(), root); assert_eq!( resolve_path(&root, "docs", "inner/hello.txt").unwrap(), root.join("docs/inner/hello.txt") ); assert_eq!( resolve_path(&root, ".", "file.txt").unwrap(), root.join("file.txt") ); } #[test] fn resolve_path_rejects_parent_traversal() { let t = T::new(); let root = t.root.canonicalize().unwrap(); for p in ["..", "../file.txt", "docs/../../file.txt", "a/../../b"] { assert!( matches!(resolve_path(&root, ".", p), Err(FsError::Forbidden)), "{p:?} should be forbidden" ); } } #[test] fn resolve_path_missing_is_not_found() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert!(matches!( resolve_path(&root, "docs", "nope.txt"), Err(FsError::NotFound) )); assert!(matches!( resolve_path(&root, "missing-root", ""), Err(FsError::RootMissing) )); } #[cfg(unix)] #[test] fn resolve_path_rejects_symlink_escape() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let outside = t.sibling("outside"); let secret = outside.join("secret.txt"); std::fs::write(&secret, "top secret").unwrap(); std::os::unix::fs::symlink(&secret, root.join("evil")).unwrap(); assert!(matches!( resolve_path(&root, ".", "evil"), Err(FsError::Forbidden) )); // A symlink that stays inside the root is fine. std::os::unix::fs::symlink(root.join("file.txt"), root.join("alias")).unwrap(); assert_eq!( resolve_path(&root, ".", "alias").unwrap(), root.join("file.txt") ); } // ---------- resolve_file / resolve_dir ---------- #[test] fn resolve_file_targets_files() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert_eq!( resolve_file(&root, "file.txt").unwrap(), root.join("file.txt") ); assert!(matches!( resolve_file(&root, "nope.txt"), Err(FsError::NotFound) )); // Escape to an existing sibling file. let sib = t.sibling("escape"); let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned(); std::fs::write(sib.join("s.txt"), "x").unwrap(); assert!(matches!( resolve_file(&root, &format!("../{sib_rel}/s.txt")), Err(FsError::Forbidden) )); } #[test] fn resolve_dir_requires_existing_directory() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert_eq!(resolve_dir(&root, ".", "docs").unwrap(), root.join("docs")); assert!(matches!( resolve_dir(&root, ".", "file.txt"), Err(FsError::NotADirectory) )); assert!(matches!( resolve_dir(&root, ".", "nope"), Err(FsError::NotFound) )); } // ---------- list_dir ---------- #[test] fn list_dir_sorts_folders_first_then_case_insensitive() { let t = T::new(); let d = t.root.join("sortme"); std::fs::create_dir_all(d.join("Zeta")).unwrap(); std::fs::create_dir_all(d.join("alpha-dir")).unwrap(); std::fs::write(d.join("b.txt"), "x").unwrap(); std::fs::write(d.join("A.txt"), "x").unwrap(); std::fs::write(d.join("C.md"), "x").unwrap(); let (entries, _) = list_dir(&d).unwrap(); let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect(); // Folders first (alpha-dir, Zeta), then files case-insensitively. assert_eq!(names, vec!["alpha-dir", "Zeta", "A.txt", "b.txt", "C.md"]); let a = &entries[2]; assert!(!a.is_dir); assert_eq!(a.size, 1); assert!(!a.mtime.is_empty()); } #[test] fn list_dir_error_cases() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert!(matches!( list_dir(&root.join("missing")), Err(FsError::NotFound) )); assert!(matches!( list_dir(&root.join("file.txt")), Err(FsError::NotADirectory) )); } #[cfg(unix)] #[test] fn list_dir_reports_broken_symlink_as_empty_file() { let t = T::new(); let d = t.root.join("withlink"); std::fs::create_dir_all(&d).unwrap(); std::os::unix::fs::symlink(d.join("does-not-exist"), d.join("broken")).unwrap(); let (entries, _) = list_dir(&d).unwrap(); assert_eq!(entries.len(), 1); assert_eq!(entries[0].name, "broken"); assert!(!entries[0].is_dir); assert_eq!(entries[0].size, 0); } // ---------- mkdir ---------- #[test] fn mkdir_creates_nested_dirs() { let t = T::new(); let root = t.root.canonicalize().unwrap(); // The parent must exist; "new" first, then "new/sub". mkdir(&root, ".", "new").unwrap(); assert!(root.join("new").is_dir()); mkdir(&root, ".", "new/sub").unwrap(); assert!(root.join("new/sub").is_dir()); } #[test] fn mkdir_rejects_conflict_and_bad_names() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert!(matches!(mkdir(&root, ".", "docs"), Err(FsError::Conflict))); assert!(matches!( mkdir(&root, ".", "a/b/../../c"), Err(FsError::Forbidden) )); assert!(matches!( mkdir(&root, ".", "file.txt/x"), Err(FsError::Forbidden) // parent is a file → ENOTDIR )); } // ---------- rename ---------- #[test] fn rename_moves_file_and_dir() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let vacated = rename_item(&root, ".", "file.txt", "renamed.txt", false).unwrap(); assert_eq!(vacated, root.join("file.txt")); assert!(!root.join("file.txt").exists()); assert_eq!( std::fs::read_to_string(root.join("renamed.txt")).unwrap(), "top file" ); rename_item(&root, ".", "docs", "docs2", false).unwrap(); assert!(root.join("docs2/inner/hello.txt").exists()); } #[test] fn rename_conflicts_and_overwrite() { let t = T::new(); let root = t.root.canonicalize().unwrap(); std::fs::write(root.join("other.txt"), "other").unwrap(); // Target file exists, no overwrite → conflict. assert!(matches!( rename_item(&root, ".", "file.txt", "other.txt", false), Err(FsError::Conflict) )); // Overwrite a file target → replaces it. rename_item(&root, ".", "file.txt", "other.txt", true).unwrap(); assert_eq!( std::fs::read_to_string(root.join("other.txt")).unwrap(), "top file" ); // A dir target is never overwritten, even with the flag. assert!(matches!( rename_item(&root, ".", "other.txt", "docs", true), Err(FsError::Conflict) )); // Renaming into a free slot works, then onto itself is a no-op. rename_item(&root, ".", "other.txt", "free.txt", false).unwrap(); assert!(root.join("free.txt").exists()); rename_item(&root, ".", "free.txt", "free.txt", false).unwrap(); assert!(root.join("free.txt").exists()); assert!(root.join("free.txt").is_file()); } #[test] fn rename_validates_new_name() { let t = T::new(); let root = t.root.canonicalize().unwrap(); for bad in ["a/b", "", ".", ".."] { assert!(matches!( rename_item(&root, ".", "file.txt", bad, false), Err(FsError::Invalid(_)) )); } assert!(matches!( rename_item(&root, ".", "missing", "x", false), Err(FsError::NotFound) )); } // ---------- remove ---------- #[test] fn remove_file_and_dir() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let (is_dir, gone) = remove_item(&root, ".", "file.txt").unwrap(); assert!(!is_dir); assert_eq!(gone, root.join("file.txt")); assert!(!root.join("file.txt").exists()); let (is_dir, gone) = remove_item(&root, ".", "docs").unwrap(); assert!(is_dir); assert_eq!(gone, root.join("docs")); assert!(!root.join("docs").exists()); assert!(matches!( remove_item(&root, ".", "file.txt"), Err(FsError::NotFound) )); } // ---------- save_file ---------- fn mtime_of(p: &Path) -> i64 { std::fs::metadata(p) .unwrap() .modified() .unwrap() .duration_since(std::time::UNIX_EPOCH) .unwrap() .as_secs() as i64 } #[test] fn save_file_updates_content_and_returns_new_mtime() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let before = mtime_of(&root.join("file.txt")); // Sleep so the mtime actually advances (filesystem granularity). std::thread::sleep(std::time::Duration::from_millis(1100)); let new = save_file(&root, ".", "file.txt", b"brand new", Some(before)).unwrap(); assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"brand new"); assert!(new >= before); // A second save with the *returned* mtime succeeds. let new2 = save_file(&root, ".", "file.txt", b"again", Some(new)).unwrap(); assert!(new2 >= new); // Without an expected mtime, always saves. let _ = save_file(&root, ".", "file.txt", b"force", None).unwrap(); assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"force"); } #[test] fn save_file_conflict_on_stale_mtime() { let t = T::new(); let root = t.root.canonicalize().unwrap(); std::thread::sleep(std::time::Duration::from_millis(1100)); // The mtime we pass is older than the file's real mtime → conflict. assert!(matches!( save_file(&root, ".", "file.txt", b"x", Some(1)), Err(FsError::Conflict) )); } #[test] fn save_file_error_cases() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert!(matches!( save_file(&root, ".", "nope.txt", b"x", None), Err(FsError::NotFound) )); assert!(matches!( save_file(&root, ".", "docs", b"x", None), Err(FsError::NotADirectory) )); assert!(matches!( save_file(&root, ".", "../evil.txt", b"x", None), Err(FsError::Forbidden) )); } // ---------- move / copy ---------- #[test] fn move_file_and_dir_across_dirs() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let vacated = move_item(&root, ".", "file.txt", ".", "src", false).unwrap(); assert_eq!(vacated, root.join("file.txt")); assert!(!root.join("file.txt").exists()); assert!(root.join("src/file.txt").exists()); move_item(&root, ".", "src", ".", "docs", false).unwrap(); assert!(root.join("docs/src/main.rs").exists()); assert!(!root.join("src").exists()); } #[test] fn move_refuses_into_self_and_conflicts() { let t = T::new(); let root = t.root.canonicalize().unwrap(); // A dir cannot be moved into itself or a descendant. assert!(matches!( move_item(&root, ".", "docs", ".", "docs", false), Err(FsError::Invalid(_)) )); assert!(matches!( move_item(&root, ".", "docs", ".", "docs/inner", false), Err(FsError::Invalid(_)) )); // A dir target always conflicts, even with overwrite: move the file // "x" into a folder that already contains a subfolder "x". std::fs::create_dir_all(root.join("mv/case/x")).unwrap(); std::fs::create_dir_all(root.join("mv/out")).unwrap(); std::fs::write(root.join("mv/out/x"), "a file named x").unwrap(); assert!(matches!( move_item(&root, ".", "mv/out/x", ".", "mv/case", true), Err(FsError::Conflict) )); // File onto file: conflict without overwrite, replaced with. std::fs::write(root.join("tmp-x.txt"), "x").unwrap(); std::fs::write(root.join("tmp-y.txt"), "y").unwrap(); std::fs::rename(root.join("tmp-x.txt"), root.join("tmp-target.txt")).unwrap(); std::fs::rename(root.join("tmp-y.txt"), root.join("tmp-target2.txt")).unwrap(); // Two distinct files with the same name in one folder. std::fs::create_dir_all(root.join("mv/dst")).unwrap(); std::fs::create_dir_all(root.join("mv/out2")).unwrap(); std::fs::write(root.join("mv/dst/dup.txt"), "old").unwrap(); std::fs::write(root.join("mv/out2/dup.txt"), "new").unwrap(); assert!(matches!( move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", false), Err(FsError::Conflict) )); move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", true).unwrap(); assert_eq!( std::fs::read_to_string(root.join("mv/dst/dup.txt")).unwrap(), "new" ); // Moving onto itself is a no-op success. move_item(&root, ".", "tmp-target.txt", ".", ".", false).unwrap(); assert!(root.join("tmp-target.txt").exists()); // Missing destination dir. assert!(matches!( move_item(&root, ".", "file.txt", ".", "nope", false), Err(FsError::NotFound) )); } #[test] fn copy_file_and_dir_preserves_mtime() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let before = mtime_of(&root.join("file.txt")); copy_item(&root, ".", "file.txt", ".", "src", false).unwrap(); let copy = root.join("src/file.txt"); assert_eq!(std::fs::read(©).unwrap(), b"top file"); assert_eq!(mtime_of(©), before); // Dir copy. copy_item(&root, ".", "docs", ".", "src", false).unwrap(); assert_eq!( std::fs::read_to_string(root.join("src/docs/inner/hello.txt")).unwrap(), "hello" ); // Originals still there. assert!(root.join("file.txt").exists()); assert!(root.join("docs/a.txt").exists()); } #[test] fn copy_refuses_into_self_and_handles_conflict() { let t = T::new(); let root = t.root.canonicalize().unwrap(); assert!(matches!( copy_item(&root, ".", "docs", ".", "docs", false), Err(FsError::Invalid(_)) )); assert!(matches!( copy_item(&root, ".", "docs", ".", "docs/inner", false), Err(FsError::Invalid(_)) )); // First copy is fine, the second one conflicts, overwrite replaces. copy_item(&root, ".", "file.txt", ".", "src", false).unwrap(); assert!(matches!( copy_item(&root, ".", "file.txt", ".", "src", false), Err(FsError::Conflict) )); std::fs::write(root.join("file.txt"), "v2").unwrap(); copy_item(&root, ".", "file.txt", ".", "src", true).unwrap(); assert_eq!( std::fs::read_to_string(root.join("src/file.txt")).unwrap(), "v2" ); // Copying onto itself is a no-op success. copy_item(&root, ".", "src/file.txt", ".", "src", false).unwrap(); assert_eq!( std::fs::read_to_string(root.join("src/file.txt")).unwrap(), "v2" ); // Missing destination dir. assert!(matches!( copy_item(&root, ".", "file.txt", ".", "nope", false), Err(FsError::NotFound) )); } #[test] fn copy_recursive_missing_source() { let t = T::new(); let dst = t.tmp.path().join("dst"); assert!(matches!( copy_recursive(&t.root.join("nope"), &dst), Err(FsError::NotFound) )); } // ---------- is_within_or_eq ---------- #[test] fn is_within_or_eq_matrix() { let t = T::new(); let root = t.root.canonicalize().unwrap(); let docs = root.join("docs"); assert!(is_within_or_eq(&docs, &docs)); assert!(is_within_or_eq(&docs, &root.join("docs/inner"))); assert!(!is_within_or_eq(&docs, &root)); assert!(!is_within_or_eq(&docs, &root.join("src"))); } // ---------- content sniffing ---------- fn kind(bytes: &[u8], name: &str) -> FileKind { kind_from_bytes(bytes, Path::new(name)) } #[test] fn magic_numbers_classify_by_content() { let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0]; // The name is a lie in every case: the bytes decide. assert_eq!(kind(&png, "notes.txt"), FileKind::Image); assert_eq!(kind(b"%PDF-1.7\n%aaa\n", "x.bin"), FileKind::Pdf); assert_eq!( kind(b"PK\x03\x04\x14\x00\x00\x00", "x.png"), FileKind::Archive ); assert_eq!( kind(&[0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0], "x"), FileKind::Archive ); assert_eq!( kind( &[ 0, 0, 0, 0x20, b'f', b't', b'y', b'p', b'i', b's', b'o', b'm' ], "x" ), FileKind::Video ); assert_eq!( kind(b"ID3\x04\x00\x00\x00\x00\x00\x00", "x"), FileKind::Audio ); assert_eq!(kind(b"RIFF\x24\x00\x00\x00WAVEfmt ", "x"), FileKind::Audio); assert_eq!(kind(b"

hi", "x"), FileKind::Text); // Recognized but not viewable in a browser. assert_eq!( kind(&[0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0], "x.wasm"), FileKind::Binary ); } #[test] fn unsigned_files_fall_back_to_the_text_heuristic() { // No magic number: plain text, source, config. assert_eq!(kind(b"hello world\n", "notes"), FileKind::Text); assert_eq!(kind(b"fn main() {}\n", "main.rs"), FileKind::Text); assert_eq!( kind("# über\nkey: wert\n".as_bytes(), "c.yaml"), FileKind::Text ); // Extensionless text files work, which the old extension list missed. assert_eq!(kind(b"all:\n\tcargo build\n", "Makefile"), FileKind::Text); // Empty file → editable. assert_eq!(kind(b"", "new.txt"), FileKind::Text); // A NUL byte means binary, whatever the name says. (ELF has no // `infer` signature, so this is the path that catches it.) assert_eq!( kind(&[0x7F, b'E', b'L', b'F', 2, 1, 1, 0, 0], "run.txt"), FileKind::Binary ); assert_eq!(kind(&[0xC3, 0x28, 0xFF, 0xFE], "x.txt"), FileKind::Binary); } #[test] fn svg_is_offered_as_an_image() { // SVG is XML text with no magic number, but browsers draw it, so the // extension is the only signal available. let svg = b""; assert_eq!(kind(svg, "logo.svg"), FileKind::Image); assert_eq!(kind(svg, "logo.txt"), FileKind::Text); } #[test] fn truncated_utf8_at_the_read_boundary_is_still_text() { // 255 ASCII bytes plus the first byte of a 2-byte character: the read // cut a character in half, which must not read as binary. let mut b = vec![b'a'; SNIFF_BYTES - 1]; b.push(0xC3); assert_eq!(kind(&b, "x.txt"), FileKind::Text); } #[test] fn detect_kind_reads_from_disk() { let t = T::new(); assert_eq!(detect_kind(&t.root.join("docs"), true), FileKind::Dir); assert_eq!(detect_kind(&t.root.join("file.txt"), false), FileKind::Text); // Unreadable / missing → Binary, never a failed listing. assert_eq!(detect_kind(&t.root.join("nope"), false), FileKind::Binary); } /// `SNIFF_BUDGET` is process-wide, so the two tests that assert on it must /// not run at the same time as each other. static BUDGET_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(()); /// A directory big enough to take the fan-out path must produce exactly /// what the serial path would. Pass 2 fills `is_dir`, `size`, `mtime` and /// `kind`, all on worker threads, so a chunk-boundary mistake would show up /// as a row carrying another row's metadata or the untouched placeholders. #[test] fn parallel_rows_match_serial() { use std::sync::atomic::Ordering; let _guard = BUDGET_TESTS.lock().unwrap(); let t = T::new(); let big = t.root.join("big"); std::fs::create_dir_all(&big).unwrap(); // Well over SNIFF_CHUNK, so several chunks are handed out. let n = SNIFF_CHUNK * 3 + 7; for i in 0..n { let p = big.join(format!("f{i:05}")); // Every file gets a distinct length, so `size` pins the row identity. let pad = vec![b'A'; i]; let mut body = match i % 3 { 0 => vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A], 1 => b"plain text\n".to_vec(), _ => vec![0u8, 1, 2, 3], }; body.extend_from_slice(&pad); std::fs::write(&p, &body).unwrap(); } std::fs::create_dir(big.join("a-subdir")).unwrap(); let (entries, _) = list_dir(&big).unwrap(); assert_eq!(entries.len(), n + 1); // Every row must agree with what a single-threaded read of that same // file reports: kind, size and directory flag. for e in &entries { let p = big.join(&e.name); let m = std::fs::metadata(&p).unwrap(); assert_eq!(e.is_dir, m.is_dir(), "{}", e.name); assert_eq!(e.size, m.len(), "size mismatch on {}", e.name); assert_eq!(e.mtime, mtime_str(&m), "mtime mismatch on {}", e.name); assert_eq!( e.kind, detect_kind(&p, e.is_dir), "kind mismatch on {}", e.name ); } // Sanity: several kinds are actually present, so the loop above is not // trivially true, and the directory sorts first. let kinds: Vec = entries.iter().map(|e| e.kind).collect(); assert!(kinds.contains(&FileKind::Image)); assert!(kinds.contains(&FileKind::Text)); assert!(kinds.contains(&FileKind::Binary)); assert_eq!(entries[0].name, "a-subdir"); assert_eq!(entries[0].kind, FileKind::Dir); // The thread budget is fully returned once the listing is done. assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0); } #[test] fn sniff_permit_never_exceeds_the_budget() { use std::sync::atomic::Ordering; let _guard = BUDGET_TESTS.lock().unwrap(); let total = sniff_budget_total(); let a = SniffPermit::claim(total * 2); assert_eq!(a.0, total, "a single claim is capped at the total"); // Nothing left: the next listing runs serially rather than queueing. let b = SniffPermit::claim(4); assert_eq!(b.0, 0); drop(a); drop(b); assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0); } #[test] fn list_dir_reports_kinds() { let t = T::new(); std::fs::write( t.root.join("docs/pic.dat"), [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A], ) .unwrap(); let (entries, _) = list_dir(&t.root.join("docs")).unwrap(); let kind_of = |n: &str| entries.iter().find(|e| e.name == n).unwrap().kind; assert_eq!(kind_of("inner"), FileKind::Dir); assert_eq!(kind_of("a.txt"), FileKind::Text); assert_eq!(kind_of("pic.dat"), FileKind::Image); } }