fs.rs
⎇
Raw
1//! Safe filesystem access: every operation resolves
2//! `<server-root>/<user-root>/<requested-path>`, canonicalizes it and verifies
3//! the result is still inside the user's root (blocks `..` and symlink escapes).
4
5use std::cmp::Ordering;
6use std::io::Read;
7use std::path::{Component, Path, PathBuf};
8use std::time::UNIX_EPOCH;
9
10use chrono::DateTime;
11
12use api_types::{Entry, FileKind, FilesResp, SortKey};
13
14use crate::error::ApiError;
15
16#[derive(Debug, thiserror::Error)]
17pub enum FsError {
18 #[error("folder not found")]
19 NotFound,
20 #[error("not a folder")]
21 NotADirectory,
22 #[error("access denied")]
23 Forbidden,
24 #[error("the configured folder no longer exists")]
25 RootMissing,
26 #[error("already exists")]
27 Conflict,
28 #[error("{0}")]
29 Invalid(String),
30}
31
32impl From<FsError> for ApiError {
33 fn from(e: FsError) -> Self {
34 use axum::http::StatusCode as S;
35 match &e {
36 FsError::NotFound => {
37 ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_not_found")
38 }
39 FsError::NotADirectory => {
40 ApiError::localized(S::BAD_REQUEST, e.to_string(), "err_fs_not_a_dir")
41 }
42 FsError::Forbidden => {
43 ApiError::localized(S::FORBIDDEN, e.to_string(), "err_fs_forbidden")
44 }
45 FsError::RootMissing => {
46 ApiError::localized(S::NOT_FOUND, e.to_string(), "err_fs_root_missing")
47 }
48 FsError::Conflict => ApiError::localized(S::CONFLICT, e.to_string(), "err_fs_conflict"),
49 // Dynamic message (e.g. an invalid name), not a fixed string.
50 FsError::Invalid(_) => ApiError::new(S::BAD_REQUEST, e.to_string()),
51 }
52 }
53}
54
55/// Resolve a user root (path relative to the server root) to a canonical
56/// absolute path, verified to be inside the server root.
57pub fn resolve_root(server_root: &Path, root_rel: &str) -> Result<PathBuf, FsError> {
58 let candidate = server_root.join(root_rel);
59 let canonical = candidate.canonicalize().map_err(|_| FsError::RootMissing)?;
60 ensure_within(server_root, &canonical)?;
61 if !canonical.is_dir() {
62 return Err(FsError::RootMissing);
63 }
64 Ok(canonical)
65}
66
67/// Resolve a requested path (relative to a user root) safely.
68pub fn resolve_path(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
69 let root_abs = resolve_root(server_root, root_rel)?;
70 let req = Path::new(req_rel);
71 for c in req.components() {
72 if matches!(c, Component::ParentDir) {
73 return Err(FsError::Forbidden);
74 }
75 }
76 let full = root_abs.join(req);
77 let full = full.canonicalize().map_err(|e| match e.kind() {
78 std::io::ErrorKind::NotFound => FsError::NotFound,
79 _ => FsError::Forbidden,
80 })?;
81 ensure_within(&root_abs, &full)?;
82 Ok(full)
83}
84
85/// Resolve a share target that is a single file (relative to the server root).
86/// Unlike [`resolve_path`], the target itself is the file — there is no
87/// directory root beneath it.
88pub fn resolve_file(server_root: &Path, rel: &str) -> Result<PathBuf, FsError> {
89 let full = server_root.join(rel);
90 let full = full.canonicalize().map_err(|e| match e.kind() {
91 std::io::ErrorKind::NotFound => FsError::NotFound,
92 _ => FsError::Forbidden,
93 })?;
94 ensure_within(server_root, &full)?;
95 Ok(full)
96}
97
98/// Whether the entry at `p` is itself a directory. A symlink is not, however
99/// its target looks: an operation on the name must not recurse into a tree the
100/// request never named.
101fn entry_is_dir(p: &Path) -> bool {
102 std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir())
103}
104
105/// Whether a name is taken. Unlike `Path::exists`, a dangling symlink counts:
106/// it still occupies the name.
107fn entry_exists(p: &Path) -> bool {
108 std::fs::symlink_metadata(p).is_ok()
109}
110
111fn ensure_within(base: &Path, p: &Path) -> Result<(), FsError> {
112 if p == base || p.starts_with(base) {
113 Ok(())
114 } else {
115 Err(FsError::Forbidden)
116 }
117}
118
119/// Which slice of a folder [`list_dir`] returns, and in what order.
120#[derive(Clone, Copy, Debug, Default)]
121pub struct ListOpts {
122 pub sort: SortKey,
123 pub desc: bool,
124 pub offset: usize,
125 /// Clamped to `1..=MAX_LIST_ENTRIES`; `None` = the cap.
126 pub limit: Option<usize>,
127 pub dirs_only: bool,
128}
129
130/// List one page of a directory (blocking — call via spawn_blocking).
131pub fn list_dir(dir: &Path, opts: ListOpts) -> Result<FilesResp, FsError> {
132 let rd = std::fs::read_dir(dir).map_err(|e| match e.kind() {
133 std::io::ErrorKind::NotFound => FsError::NotFound,
134 std::io::ErrorKind::NotADirectory => FsError::NotADirectory,
135 _ => FsError::Forbidden,
136 })?;
137
138 // Pass 1: names only. Walking the directory stream is inherently
139 // sequential, but it is also the only part that has to be: every field
140 // below comes from a per-entry syscall, which pass 2 can do in parallel.
141 // The values here are the fallbacks used when that syscall fails.
142 let mut rows: Vec<(Entry, PathBuf)> = Vec::new();
143 for e in rd.flatten() {
144 let entry = Entry {
145 name: e.file_name().to_string_lossy().into_owned(),
146 is_dir: false,
147 size: 0,
148 mtime: EPOCH_MTIME.to_string(),
149 kind: FileKind::Binary,
150 };
151 rows.push((entry, e.path()));
152 }
153
154 // Pass 2: metadata, which the sort needs.
155 describe_rows(&mut rows, fill_meta);
156 if opts.dirs_only {
157 rows.retain(|(e, _)| e.is_dir);
158 }
159 // After pass 2, so the parallel fan-out cannot affect the order.
160 rows.sort_by(|(a, _), (b, _)| cmp_entries(a, b, opts.sort, opts.desc));
161
162 let total = rows.len();
163 let limit = opts
164 .limit
165 .unwrap_or(api_types::MAX_LIST_ENTRIES)
166 .clamp(1, api_types::MAX_LIST_ENTRIES);
167 // Past the end happens when a delete empties the last page.
168 let offset = if opts.offset < total {
169 opts.offset
170 } else {
171 total.saturating_sub(1) / limit * limit
172 };
173 let mut page: Vec<(Entry, PathBuf)> = rows.into_iter().skip(offset).take(limit).collect();
174
175 // Pass 3: the content sniff, only for the page. It reads file data, which
176 // on a spinning disk costs a seek per file.
177 describe_rows(&mut page, fill_kind);
178
179 Ok(FilesResp {
180 entries: page.into_iter().map(|(e, _)| e).collect(),
181 total,
182 offset,
183 })
184}
185
186/// The listing order: folders first, then `key`. Folders have no
187/// meaningful size, so a size order keeps them in name order.
188fn cmp_entries(a: &Entry, b: &Entry, key: SortKey, desc: bool) -> Ordering {
189 let dir = |o: Ordering| if desc { o.reverse() } else { o };
190 b.is_dir.cmp(&a.is_dir).then_with(|| match key {
191 SortKey::Name => dir(cmp_name(a, b)),
192 SortKey::Size if a.is_dir => cmp_name(a, b),
193 SortKey::Size => dir(a.size.cmp(&b.size)).then_with(|| cmp_name(a, b)),
194 // RFC 3339 UTC with a fixed width, so bytewise order is
195 // chronological order.
196 SortKey::Modified => dir(a.mtime.cmp(&b.mtime)).then_with(|| cmp_name(a, b)),
197 })
198}
199
200/// Case-insensitive, with the raw name as the tie-breaker so two names that
201/// differ only in case keep a stable order.
202fn cmp_name(a: &Entry, b: &Entry) -> Ordering {
203 fn lower(s: &str) -> impl Iterator<Item = char> + '_ {
204 s.chars().flat_map(char::to_lowercase)
205 }
206 lower(&a.name)
207 .cmp(lower(&b.name))
208 .then_with(|| a.name.cmp(&b.name))
209}
210
211// ---------------------------------------------------------------------------
212// Content sniffing
213// ---------------------------------------------------------------------------
214
215/// How many leading bytes we read to classify a file. Every magic number
216/// `infer` knows lives in the first few dozen bytes; 256 also gives the
217/// text/binary heuristic enough to work with. Measured at ~4.6 µs per file,
218/// against ~1.4 µs for the `metadata` call in the same pass.
219const SNIFF_BYTES: usize = 256;
220
221/// Entries per thread, and the point below which parallelism is not worth it.
222/// Measured on a 22-core machine: at 50 entries fan-out is a wash (thread
223/// spawn costs about as much as the work), at 200 it is already 2x.
224const SNIFF_CHUNK: usize = 256;
225
226/// Process-wide ceiling on threads spawned for sniffing, so many concurrent
227/// listings of large directories cannot multiply into a thread explosion.
228/// One listing alone can use the whole budget; the next one degrades to fewer
229/// threads, and eventually to serial, instead of queueing.
230static SNIFF_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
231
232fn sniff_budget_total() -> usize {
233 static TOTAL: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
234 std::thread::available_parallelism()
235 .map(|n| n.get())
236 .unwrap_or(1)
237 });
238 *TOTAL
239}
240
241/// Claimed helper threads, returned to [`SNIFF_BUDGET`] on drop.
242struct SniffPermit(usize);
243
244impl SniffPermit {
245 /// Claim up to `want` helper threads, or fewer when the budget is thin.
246 fn claim(want: usize) -> Self {
247 use std::sync::atomic::Ordering;
248 let total = sniff_budget_total();
249 let mut granted = 0;
250 let _ = SNIFF_BUDGET.fetch_update(Ordering::AcqRel, Ordering::Acquire, |in_flight| {
251 granted = want.min(total.saturating_sub(in_flight));
252 (granted > 0).then_some(in_flight + granted)
253 });
254 Self(granted)
255 }
256}
257
258impl Drop for SniffPermit {
259 fn drop(&mut self) {
260 if self.0 > 0 {
261 SNIFF_BUDGET.fetch_sub(self.0, std::sync::atomic::Ordering::AcqRel);
262 }
263 }
264}
265
266/// Metadata for one row. Follows symlinks; a broken link keeps the caller's
267/// fallbacks and so shows up as an empty file.
268fn fill_meta(entry: &mut Entry, path: &Path) {
269 if let Ok(m) = std::fs::metadata(path) {
270 entry.is_dir = m.is_dir();
271 entry.size = m.len();
272 entry.mtime = mtime_str(&m);
273 }
274}
275
276/// The content sniff for one row. Needs `is_dir`, so it runs after
277/// [`fill_meta`].
278fn fill_kind(entry: &mut Entry, path: &Path) {
279 entry.kind = detect_kind(path, entry.is_dir);
280}
281
282/// Apply `one` to each row, fanning the work out across threads for big
283/// directories.
284///
285/// The calling thread takes a chunk too, so `n` helper threads process `n + 1`
286/// chunks and a zero-thread grant is simply the serial path.
287fn describe_rows(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) {
288 fn describe(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) {
289 for (entry, path) in rows {
290 one(entry, path);
291 }
292 }
293
294 if rows.len() < SNIFF_CHUNK {
295 describe(rows, one);
296 return;
297 }
298 // One chunk per helper thread plus one for this thread.
299 let want = rows.len().div_ceil(SNIFF_CHUNK).saturating_sub(1);
300 let permit = SniffPermit::claim(want);
301 if permit.0 == 0 {
302 describe(rows, one);
303 return;
304 }
305 let chunk = rows.len().div_ceil(permit.0 + 1);
306 std::thread::scope(|s| {
307 let mut rest = rows;
308 // Hand every chunk but the last to a helper thread.
309 while rest.len() > chunk {
310 let (head, tail) = rest.split_at_mut(chunk);
311 s.spawn(move || describe(head, one));
312 rest = tail;
313 }
314 describe(rest, one);
315 });
316}
317
318/// Classify a directory entry by reading its first [`SNIFF_BYTES`] bytes.
319///
320/// Blocking — called from `list_dir` (itself under `spawn_blocking`), on
321/// several threads at once for large directories. An unreadable file is
322/// reported as [`FileKind::Binary`] rather than failing the whole listing.
323///
324// ponytail: one open() per entry, fanned out but not cached. Measured warm on
325// 22 cores: 5000 entries take 29 ms serially and 6.9 ms across threads. The
326// remaining ceiling is a cold cache or a network filesystem (NFS/SMB), where
327// each entry costs a round trip. If that shows up: cache by (dev, ino, mtime),
328// or skip the sniff for zero-byte files.
329pub fn detect_kind(path: &Path, is_dir: bool) -> FileKind {
330 if is_dir {
331 return FileKind::Dir;
332 }
333 let mut head = [0u8; SNIFF_BYTES];
334 // A read error is *not* the same as an empty file: an empty file is text
335 // (it opens in the editor), an unreadable one gets no viewer offered.
336 match std::fs::File::open(path).and_then(|mut f| f.read(&mut head)) {
337 Ok(n) => kind_from_bytes(&head[..n], path),
338 Err(_) => FileKind::Binary,
339 }
340}
341
342/// The pure half of [`detect_kind`], so it can be unit-tested without a disk.
343///
344/// `path` is consulted only for the SVG case: SVG is XML text with no magic
345/// number, but browsers render it as an image, so the extension is the only
346/// thing that can tell us to offer an image preview.
347fn kind_from_bytes(head: &[u8], path: &Path) -> FileKind {
348 if let Some(t) = infer::get(head) {
349 // PDF is filed under `Archive` by `infer`, so match the MIME first.
350 if t.mime_type() == "application/pdf" {
351 return FileKind::Pdf;
352 }
353 return match t.matcher_type() {
354 infer::MatcherType::Image => FileKind::Image,
355 infer::MatcherType::Video => FileKind::Video,
356 infer::MatcherType::Audio => FileKind::Audio,
357 infer::MatcherType::Archive => FileKind::Archive,
358 infer::MatcherType::Text => FileKind::Text,
359 // App / Book / Font / Doc / Custom: recognized, but nothing we
360 // can show in the browser.
361 _ => FileKind::Binary,
362 };
363 }
364 if !looks_like_text(head) {
365 return FileKind::Binary;
366 }
367 let ext = path
368 .extension()
369 .map(|e| e.to_string_lossy().to_lowercase())
370 .unwrap_or_default();
371 if ext == "svg" {
372 FileKind::Image
373 } else {
374 FileKind::Text
375 }
376}
377
378/// Text heuristic for the files `infer` has no signature for (plain text,
379/// source code, most config formats): no NUL byte, and the head decodes as
380/// UTF-8 once a truncated trailing character is discounted.
381///
382/// An empty file counts as text — it opens in the editor, which is what you
383/// want for a file you just created.
384fn looks_like_text(head: &[u8]) -> bool {
385 if head.contains(&0) {
386 return false;
387 }
388 match std::str::from_utf8(head) {
389 Ok(_) => true,
390 // A multi-byte character cut in half by the read boundary is fine;
391 // anything else is not text. `error_len() == None` means "unexpected
392 // end of input", i.e. truncation.
393 Err(e) => e.error_len().is_none() && e.valid_up_to() + 4 > head.len(),
394 }
395}
396
397/// Reported when a file's modification time is unavailable or unrepresentable.
398const EPOCH_MTIME: &str = "1970-01-01T00:00:00Z";
399
400/// A file's modification time in whole unix seconds, or `None` when the
401/// platform cannot report one. The single place that converts a `SystemTime`.
402pub fn mtime_secs(m: &std::fs::Metadata) -> Option<i64> {
403 m.modified()
404 .ok()
405 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
406 .map(|d| d.as_secs() as i64)
407}
408
409fn mtime_str(m: &std::fs::Metadata) -> String {
410 let dt: Option<DateTime<chrono::Utc>> =
411 mtime_secs(m).and_then(|s| DateTime::from_timestamp(s, 0));
412 dt.map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
413 .unwrap_or_else(|| EPOCH_MTIME.to_string())
414}
415
416// ---------------------------------------------------------------------------
417// Mutations (milestone 3): mkdir, rename, remove, move, copy, upload
418// ---------------------------------------------------------------------------
419
420/// Resolve a directory that must exist (relative to a user root). Used as the
421/// base for operations that target the *parent* of the item.
422pub fn resolve_dir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
423 let full = resolve_path(server_root, root_rel, req_rel)?;
424 if !full.is_dir() {
425 return Err(FsError::NotADirectory);
426 }
427 Ok(full)
428}
429
430/// Validate a new single-component name (for rename / new folder).
431fn validate_component(name: &str) -> Result<(), FsError> {
432 let p = Path::new(name);
433 if name.is_empty()
434 || p.components().count() != 1
435 || name == "."
436 || name == ".."
437 || name.contains(['/', '\\', '\0'])
438 {
439 return Err(FsError::Invalid("invalid name".to_string()));
440 }
441 Ok(())
442}
443
444/// Create a directory (and any missing parents) inside a user root.
445pub fn mkdir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
446 let full = resolve_entry(server_root, root_rel, req_rel)?;
447 if full.exists() {
448 return Err(FsError::Conflict);
449 }
450 std::fs::create_dir_all(&full).map_err(|e| io_err(e, &full))?;
451 Ok(())
452}
453
454/// Create an empty file. The parent must exist; the file must not.
455pub fn create_file(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
456 let full = resolve_entry(server_root, root_rel, req_rel)?;
457 // create_new = O_EXCL: fails on an existing path, does not follow a symlink.
458 std::fs::File::create_new(&full).map_err(|e| match e.kind() {
459 std::io::ErrorKind::AlreadyExists => FsError::Conflict,
460 _ => io_err(e, &full),
461 })?;
462 Ok(())
463}
464
465/// Resolve a path that names an *entry*, not the file that entry may point at.
466///
467/// The last component is never followed and need not exist. The parent must,
468/// and is canonicalized and checked against the root.
469///
470/// This is the resolver for operations that act on the name: create, delete,
471/// rename, the source of a move, the destination of a move or copy. Following
472/// a symlink there would delete a file the request never mentioned, or rename
473/// one into a different directory. Reads and content writes use
474/// [`resolve_path`] instead and do follow, contained by `ensure_within`.
475pub(crate) fn resolve_entry(
476 server_root: &Path,
477 root_rel: &str,
478 req_rel: &str,
479) -> Result<PathBuf, FsError> {
480 let root_abs = resolve_root(server_root, root_rel)?;
481 let req = Path::new(req_rel);
482 for c in req.components() {
483 if matches!(c, Component::ParentDir) {
484 return Err(FsError::Forbidden);
485 }
486 }
487 let full = root_abs.join(req);
488 // The parent must exist and stay inside the root.
489 let parent = full
490 .parent()
491 .filter(|p| !p.as_os_str().is_empty())
492 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
493 let parent = parent.canonicalize().map_err(|e| io_err(e, parent))?;
494 ensure_within(&root_abs, &parent)?;
495 // Re-join onto the *canonical* parent. `full` may still spell a symlinked
496 // directory, and a caller comparing it against another resolved path (see
497 // [`move_to`]) would then compare two different spellings of one place.
498 let name = full
499 .file_name()
500 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
501 Ok(parent.join(name))
502}
503
504/// Rename (or move within the same directory) an item.
505/// Returns the path the item was renamed *away from*, so the caller can
506/// revoke anything (a share) that still names it.
507pub fn rename_item(
508 server_root: &Path,
509 root_rel: &str,
510 req_rel: &str,
511 new_name: &str,
512 overwrite: bool,
513) -> Result<PathBuf, FsError> {
514 validate_component(new_name)?;
515 let from = resolve_entry(server_root, root_rel, req_rel)?;
516 let parent = from
517 .parent()
518 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
519 let to = parent.join(new_name);
520 // Renaming onto itself is a no-op (the overwrite path below would
521 // delete the file before the rename). Nothing was vacated.
522 if to == from {
523 return Ok(to);
524 }
525 // `rename` replaces a file target atomically; no remove-then-rename gap.
526 if entry_exists(&to) && (!overwrite || entry_is_dir(&to) || entry_is_dir(&from)) {
527 return Err(FsError::Conflict);
528 }
529 std::fs::rename(&from, &to).map_err(|e| io_err(e, &to))?;
530 Ok(from)
531}
532
533/// Delete a file or a directory tree. Returns whether it was a directory, and
534/// the path that is now gone (so the caller can revoke shares naming it).
535pub fn remove_item(
536 server_root: &Path,
537 root_rel: &str,
538 req_rel: &str,
539) -> Result<(bool, PathBuf), FsError> {
540 let full = resolve_entry(server_root, root_rel, req_rel)?;
541 // A symlink is unlinked, never followed: deleting it must not delete the
542 // file it names. A dangling link is deletable for the same reason.
543 let is_dir = entry_is_dir(&full);
544 if is_dir {
545 std::fs::remove_dir_all(&full).map_err(|e| io_err(e, &full))?;
546 } else {
547 std::fs::remove_file(&full).map_err(|e| io_err(e, &full))?;
548 }
549 Ok((is_dir, full))
550}
551
552/// Overwrite an existing file's contents (the editor's save path).
553///
554/// The file must already exist and be a regular file. If `expected_mtime`
555/// (whole unix seconds) is provided and differs from the file's current mtime,
556/// the file changed on disk since it was read → `Conflict` (409). Returns the
557/// file's new mtime (unix seconds) after a successful write.
558pub fn save_file(
559 server_root: &Path,
560 root_rel: &str,
561 req_rel: &str,
562 content: &[u8],
563 expected_mtime: Option<i64>,
564) -> Result<i64, FsError> {
565 let full = resolve_path(server_root, root_rel, req_rel)?; // must exist
566 write_checked(&full, content, expected_mtime)
567}
568
569/// The share-aware variant of [`save_file`]: for a *file* share the root is
570/// the file itself, so `target` (relative to `server_root`) points at the
571/// file — there is no directory root beneath it.
572pub fn save_file_at(
573 server_root: &Path,
574 target: &str,
575 content: &[u8],
576 expected_mtime: Option<i64>,
577) -> Result<i64, FsError> {
578 let full = resolve_file(server_root, target)?; // must exist
579 write_checked(&full, content, expected_mtime)
580}
581
582fn write_checked(full: &Path, content: &[u8], expected_mtime: Option<i64>) -> Result<i64, FsError> {
583 let meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
584 if meta.is_dir() {
585 return Err(FsError::NotADirectory);
586 }
587 if let Some(expected) = expected_mtime {
588 // No readable mtime means the check cannot pass: -1 never matches.
589 if mtime_secs(&meta).unwrap_or(-1) != expected {
590 return Err(FsError::Conflict);
591 }
592 }
593 std::fs::write(full, content).map_err(|e| io_err(e, full))?;
594 // Read the new mtime so the client can anchor the next conflict check.
595 let new_meta = std::fs::metadata(full).map_err(|_| FsError::NotFound)?;
596 Ok(mtime_secs(&new_meta).unwrap_or(0))
597}
598
599fn io_err(e: std::io::Error, p: &Path) -> FsError {
600 tracing::warn!(error = %e, path = %p.display(), "filesystem error");
601 match e.kind() {
602 std::io::ErrorKind::NotFound => FsError::NotFound,
603 _ => FsError::Forbidden,
604 }
605}
606
607/// True if `a` is `b` or a descendant of `b` (both canonical).
608pub(crate) fn is_within_or_eq(base: &Path, p: &Path) -> bool {
609 p == base || p.starts_with(base)
610}
611
612/// Move an item (possibly across roots). `dst_dir_rel` is the destination
613/// directory (relative to `dst_root_rel`); the item keeps its base name.
614///
615/// Returns the path the item was moved *away from*, like [`rename_item`].
616pub fn move_item(
617 server_root: &Path,
618 src_root_rel: &str,
619 src_rel: &str,
620 dst_root_rel: &str,
621 dst_dir_rel: &str,
622 overwrite: bool,
623) -> Result<PathBuf, FsError> {
624 let from = resolve_entry(server_root, src_root_rel, src_rel)?;
625 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
626 let name = from
627 .file_name()
628 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
629 .to_owned();
630 let to = dst_dir.join(&name);
631
632 // A no-op (item already at the destination) — treat as success. Nothing
633 // was vacated.
634 if to == from {
635 return Ok(to);
636 }
637
638 // Refuse moving a directory into itself or a descendant.
639 if entry_is_dir(&from) && is_within_or_eq(&from, &dst_dir) {
640 return Err(FsError::Invalid(
641 "cannot move a folder into itself".to_string(),
642 ));
643 }
644 check_move_conflict(&to, &from, overwrite)?;
645 rename_or_copy(&from, &to)?;
646 Ok(from)
647}
648
649/// Copy an item (possibly across roots).
650pub fn copy_item(
651 server_root: &Path,
652 src_root_rel: &str,
653 src_rel: &str,
654 dst_root_rel: &str,
655 dst_dir_rel: &str,
656 overwrite: bool,
657) -> Result<(), FsError> {
658 // Two resolutions of one path, because a copy of a symlink wants both
659 // halves: the bytes of the file it names, under the name of the link
660 // itself. `cp` does the same.
661 let from = resolve_path(server_root, src_root_rel, src_rel)?;
662 let entry = resolve_entry(server_root, src_root_rel, src_rel)?;
663 let dst_dir = resolve_dir(server_root, dst_root_rel, dst_dir_rel)?;
664 let name = entry
665 .file_name()
666 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?
667 .to_owned();
668 let to = dst_dir.join(&name);
669
670 // A no-op (item already at the destination) — treat as success.
671 if to == from {
672 return Ok(());
673 }
674
675 if from.is_dir() && is_within_or_eq(&from, &dst_dir) {
676 return Err(FsError::Invalid(
677 "cannot copy a folder into itself".to_string(),
678 ));
679 }
680 check_move_conflict(&to, &from, overwrite)?;
681 copy_recursive(&from, &to)?;
682 Ok(())
683}
684
685/// Move an item to an explicit destination path (the WebDAV `MOVE` shape).
686///
687/// Unlike [`move_item`], the destination names the item itself, so this also
688/// renames. There is no overwrite check here: the WebDAV layer has already
689/// refused, or deleted, an existing destination by the time this runs.
690pub fn move_to(
691 server_root: &Path,
692 src_root_rel: &str,
693 src_rel: &str,
694 dst_root_rel: &str,
695 dst_rel: &str,
696) -> Result<(), FsError> {
697 // An entry, not its target: moving a symlink moves the link.
698 let from = resolve_entry(server_root, src_root_rel, src_rel)?;
699 let to = resolve_dest(server_root, &from, dst_root_rel, dst_rel)?;
700 if from == to {
701 return Ok(());
702 }
703 rename_or_copy(&from, &to)
704}
705
706/// `rename`, falling back to copy-then-remove when the two paths are on
707/// different filesystems.
708///
709/// A symlink is refused on the fallback path. `copy_recursive` stats with
710/// `metadata`, which follows, so it would replace the link with a copy of its
711/// target, and that target may be outside the root. Plain `rename` moves the
712/// link itself and needs no such guard.
713fn rename_or_copy(from: &Path, to: &Path) -> Result<(), FsError> {
714 match std::fs::rename(from, to) {
715 Ok(()) => Ok(()),
716 Err(e) if e.kind() == std::io::ErrorKind::CrossesDevices => {
717 if std::fs::symlink_metadata(from).is_ok_and(|m| m.file_type().is_symlink()) {
718 return Err(FsError::Forbidden);
719 }
720 copy_recursive(from, to)?;
721 if entry_is_dir(from) {
722 std::fs::remove_dir_all(from).map_err(|e| io_err(e, from))?;
723 } else {
724 std::fs::remove_file(from).map_err(|e| io_err(e, from))?;
725 }
726 Ok(())
727 }
728 Err(e) => Err(io_err(e, to)),
729 }
730}
731
732/// Copy to an explicit destination path (the WebDAV `COPY` shape). The WebDAV
733/// layer only ever asks for a single file: it walks a tree itself, one
734/// `create_dir` and one `copy` per entry.
735pub fn copy_file_to(
736 server_root: &Path,
737 src_root_rel: &str,
738 src_rel: &str,
739 dst_root_rel: &str,
740 dst_rel: &str,
741) -> Result<(), FsError> {
742 // The source *is* followed: a copy wants the file's bytes, the way `cp`
743 // does. `resolve_path` still refuses a link that leaves the root.
744 let from = resolve_path(server_root, src_root_rel, src_rel)?;
745 let to = resolve_dest(server_root, &from, dst_root_rel, dst_rel)?;
746 if from == to {
747 return Ok(());
748 }
749 copy_recursive(&from, &to)
750}
751
752/// Copy one file, replacing a symlink at the destination instead of writing
753/// through it.
754///
755/// `std::fs::copy` follows a destination symlink, so a link out of the root
756/// makes the copy land outside it with every path check passing. Every caller
757/// here has already decided the destination may be overwritten, so unlinking
758/// first is also the semantics they wanted. `rename` needs no such guard; it
759/// replaces the link rather than following it.
760fn copy_file(src: &Path, dst: &Path) -> Result<(), FsError> {
761 if std::fs::symlink_metadata(dst).is_ok_and(|m| m.file_type().is_symlink()) {
762 std::fs::remove_file(dst).map_err(|e| io_err(e, dst))?;
763 }
764 std::fs::copy(src, dst).map_err(|e| io_err(e, dst))?;
765 Ok(())
766}
767
768/// Resolve the destination of a move or copy that names it in full.
769///
770/// A destination *inside* `from` is refused, which is what stops
771/// `MOVE /a /a/b` from eating itself. The source is the caller's to resolve: a
772/// move relocates the entry, a copy wants the bytes, so the two follow a
773/// symlink differently.
774fn resolve_dest(
775 server_root: &Path,
776 from: &Path,
777 dst_root_rel: &str,
778 dst_rel: &str,
779) -> Result<PathBuf, FsError> {
780 let to = resolve_entry(server_root, dst_root_rel, dst_rel)?;
781 if from != to && entry_is_dir(from) && is_within_or_eq(&to, from) {
782 return Err(FsError::Invalid(
783 "cannot move a folder into itself".to_string(),
784 ));
785 }
786 Ok(to)
787}
788
789/// Conflict rules shared by move and copy:
790/// - target is a directory → always conflict (no silent merge)
791/// - target is a file → conflict unless overwriting a file with a file
792fn check_move_conflict(to: &Path, from: &Path, overwrite: bool) -> Result<(), FsError> {
793 if entry_exists(to) {
794 let to_dir = entry_is_dir(to);
795 let from_dir = entry_is_dir(from);
796 if to_dir || from_dir || !overwrite {
797 return Err(FsError::Conflict);
798 }
799 }
800 Ok(())
801}
802
803/// Recursively copy a file or directory tree, preserving mtime.
804fn copy_recursive(src: &Path, dst: &Path) -> Result<(), FsError> {
805 let meta = std::fs::metadata(src).map_err(|e| io_err(e, src))?;
806 if meta.is_dir() {
807 std::fs::create_dir(dst).map_err(|e| io_err(e, dst))?;
808 for e in std::fs::read_dir(src)
809 .map_err(|e| io_err(e, src))?
810 .flatten()
811 {
812 copy_recursive(&e.path(), &dst.join(e.file_name()))?;
813 }
814 } else {
815 copy_file(src, dst)?;
816 }
817 set_mtime(dst, meta.modified().ok());
818 Ok(())
819}
820
821fn set_mtime(p: &Path, t: Option<std::time::SystemTime>) {
822 if let (Some(t), Ok(f)) = (t, std::fs::File::open(p)) {
823 let _ = f.set_modified(t);
824 }
825}
826
827// ---------------------------------------------------------------------------
828// Tests
829// ---------------------------------------------------------------------------
830
831#[cfg(test)]
832mod tests {
833 use super::*;
834
835 /// A temp dir used as the "server root" with a small fixture tree:
836 ///
837 /// ```text
838 /// root/
839 /// docs/
840 /// inner/
841 /// hello.txt
842 /// a.txt
843 /// src/
844 /// main.rs
845 /// file.txt
846 /// ```
847 struct T {
848 tmp: tempfile::TempDir,
849 root: PathBuf,
850 }
851
852 impl T {
853 fn new() -> Self {
854 let tmp = tempfile::tempdir().unwrap();
855 let root = tmp.path().to_path_buf();
856 std::fs::create_dir_all(root.join("docs/inner")).unwrap();
857 std::fs::create_dir_all(root.join("src")).unwrap();
858 std::fs::write(root.join("docs/inner/hello.txt"), "hello").unwrap();
859 std::fs::write(root.join("docs/a.txt"), "a").unwrap();
860 std::fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();
861 std::fs::write(root.join("file.txt"), "top file").unwrap();
862 Self { tmp, root }
863 }
864
865 /// A directory that lives *next to* the root (outside of it), for
866 /// symlink/escape tests. The tempdir name is unique, so the sibling
867 /// name is unique too.
868 fn sibling(&self, name: &str) -> PathBuf {
869 let base = self
870 .tmp
871 .path()
872 .file_name()
873 .unwrap()
874 .to_string_lossy()
875 .into_owned();
876 let p = self.tmp.path().with_file_name(format!("{base}-{name}"));
877 std::fs::create_dir_all(&p).unwrap();
878 p
879 }
880 }
881
882 // ---------- validate_component ----------
883
884 #[test]
885 fn validate_name_accepts_simple_names() {
886 for ok in ["a", "file.txt", "my folder", "Ünïcödé", "with-dash_1.2.3"] {
887 assert!(validate_component(ok).is_ok(), "{ok:?} should be valid");
888 }
889 }
890
891 #[test]
892 fn validate_name_rejects_traversal_and_paths() {
893 for bad in [
894 "", ".", "..", "a/b", "a\\b", "a\0b", "/abs", "../x", "x/../y", "x/", "/x",
895 ] {
896 assert!(
897 validate_component(bad).is_err(),
898 "{bad:?} should be invalid"
899 );
900 }
901 }
902
903 // ---------- resolve_root ----------
904
905 #[test]
906 fn resolve_root_whole_root_and_subdir() {
907 let t = T::new();
908 let root = t.root.canonicalize().unwrap();
909 // "." means the whole root.
910 assert_eq!(resolve_root(&root, ".").unwrap(), root);
911 assert_eq!(resolve_root(&root, "docs").unwrap(), root.join("docs"));
912 assert_eq!(
913 resolve_root(&root, "docs/inner").unwrap(),
914 root.join("docs/inner")
915 );
916 }
917
918 #[test]
919 fn resolve_root_rejects_escape_and_missing() {
920 let t = T::new();
921 let root = t.root.canonicalize().unwrap();
922 let sib = t.sibling("escape");
923 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
924 // Escapes that land on *existing* paths outside the root.
925 for esc in [
926 "..".to_string(),
927 "docs/../..".to_string(),
928 format!("../{sib_rel}"),
929 ] {
930 assert!(
931 matches!(resolve_root(&root, &esc), Err(FsError::Forbidden)),
932 "{esc:?} should be forbidden"
933 );
934 }
935 // Escapes to non-existing paths simply don't exist.
936 for esc in ["../no-such-dir", "a/b/../../..", "nope"] {
937 assert!(
938 matches!(resolve_root(&root, esc), Err(FsError::RootMissing)),
939 "{esc:?} should be missing"
940 );
941 }
942 // A file is not a valid root.
943 assert!(matches!(
944 resolve_root(&root, "file.txt"),
945 Err(FsError::RootMissing)
946 ));
947 }
948
949 #[cfg(unix)]
950 #[test]
951 fn resolve_root_rejects_symlink_escape() {
952 let t = T::new();
953 let root = t.root.canonicalize().unwrap();
954 let outside = t.sibling("outside");
955 std::os::unix::fs::symlink(&outside, root.join("link")).unwrap();
956 assert!(matches!(
957 resolve_root(&root, "link"),
958 Err(FsError::Forbidden)
959 ));
960 }
961
962 // ---------- resolve_path ----------
963
964 #[test]
965 fn resolve_path_traverses_inside_root() {
966 let t = T::new();
967 let root = t.root.canonicalize().unwrap();
968 // Empty relative path → the root itself.
969 assert_eq!(resolve_path(&root, ".", "").unwrap(), root);
970 assert_eq!(
971 resolve_path(&root, "docs", "inner/hello.txt").unwrap(),
972 root.join("docs/inner/hello.txt")
973 );
974 assert_eq!(
975 resolve_path(&root, ".", "file.txt").unwrap(),
976 root.join("file.txt")
977 );
978 }
979
980 #[test]
981 fn resolve_path_rejects_parent_traversal() {
982 let t = T::new();
983 let root = t.root.canonicalize().unwrap();
984 for p in ["..", "../file.txt", "docs/../../file.txt", "a/../../b"] {
985 assert!(
986 matches!(resolve_path(&root, ".", p), Err(FsError::Forbidden)),
987 "{p:?} should be forbidden"
988 );
989 }
990 }
991
992 #[test]
993 fn resolve_path_missing_is_not_found() {
994 let t = T::new();
995 let root = t.root.canonicalize().unwrap();
996 assert!(matches!(
997 resolve_path(&root, "docs", "nope.txt"),
998 Err(FsError::NotFound)
999 ));
1000 assert!(matches!(
1001 resolve_path(&root, "missing-root", ""),
1002 Err(FsError::RootMissing)
1003 ));
1004 }
1005
1006 #[cfg(unix)]
1007 #[test]
1008 fn resolve_path_rejects_symlink_escape() {
1009 let t = T::new();
1010 let root = t.root.canonicalize().unwrap();
1011 let outside = t.sibling("outside");
1012 let secret = outside.join("secret.txt");
1013 std::fs::write(&secret, "top secret").unwrap();
1014 std::os::unix::fs::symlink(&secret, root.join("evil")).unwrap();
1015 assert!(matches!(
1016 resolve_path(&root, ".", "evil"),
1017 Err(FsError::Forbidden)
1018 ));
1019 // A symlink that stays inside the root is fine.
1020 std::os::unix::fs::symlink(root.join("file.txt"), root.join("alias")).unwrap();
1021 assert_eq!(
1022 resolve_path(&root, ".", "alias").unwrap(),
1023 root.join("file.txt")
1024 );
1025 }
1026
1027 // ---------- resolve_file / resolve_dir ----------
1028
1029 #[test]
1030 fn resolve_file_targets_files() {
1031 let t = T::new();
1032 let root = t.root.canonicalize().unwrap();
1033 assert_eq!(
1034 resolve_file(&root, "file.txt").unwrap(),
1035 root.join("file.txt")
1036 );
1037 assert!(matches!(
1038 resolve_file(&root, "nope.txt"),
1039 Err(FsError::NotFound)
1040 ));
1041 // Escape to an existing sibling file.
1042 let sib = t.sibling("escape");
1043 let sib_rel = sib.file_name().unwrap().to_string_lossy().into_owned();
1044 std::fs::write(sib.join("s.txt"), "x").unwrap();
1045 assert!(matches!(
1046 resolve_file(&root, &format!("../{sib_rel}/s.txt")),
1047 Err(FsError::Forbidden)
1048 ));
1049 }
1050
1051 #[test]
1052 fn resolve_dir_requires_existing_directory() {
1053 let t = T::new();
1054 let root = t.root.canonicalize().unwrap();
1055 assert_eq!(resolve_dir(&root, ".", "docs").unwrap(), root.join("docs"));
1056 assert!(matches!(
1057 resolve_dir(&root, ".", "file.txt"),
1058 Err(FsError::NotADirectory)
1059 ));
1060 assert!(matches!(
1061 resolve_dir(&root, ".", "nope"),
1062 Err(FsError::NotFound)
1063 ));
1064 }
1065
1066 // ---------- list_dir ----------
1067
1068 #[test]
1069 fn list_dir_sorts_folders_first_then_case_insensitive() {
1070 let t = T::new();
1071 let d = t.root.join("sortme");
1072 std::fs::create_dir_all(d.join("Zeta")).unwrap();
1073 std::fs::create_dir_all(d.join("alpha-dir")).unwrap();
1074 std::fs::write(d.join("b.txt"), "x").unwrap();
1075 std::fs::write(d.join("A.txt"), "x").unwrap();
1076 std::fs::write(d.join("C.md"), "x").unwrap();
1077 let entries = list_dir(&d, ListOpts::default()).unwrap().entries;
1078 let names: Vec<&str> = entries.iter().map(|e| e.name.as_str()).collect();
1079 // Folders first (alpha-dir, Zeta), then files case-insensitively.
1080 assert_eq!(names, vec!["alpha-dir", "Zeta", "A.txt", "b.txt", "C.md"]);
1081 let a = &entries[2];
1082 assert!(!a.is_dir);
1083 assert_eq!(a.size, 1);
1084 assert!(!a.mtime.is_empty());
1085 }
1086
1087 #[test]
1088 fn list_dir_error_cases() {
1089 let t = T::new();
1090 let root = t.root.canonicalize().unwrap();
1091 assert!(matches!(
1092 list_dir(&root.join("missing"), ListOpts::default()),
1093 Err(FsError::NotFound)
1094 ));
1095 assert!(matches!(
1096 list_dir(&root.join("file.txt"), ListOpts::default()),
1097 Err(FsError::NotADirectory)
1098 ));
1099 }
1100
1101 fn entry(name: &str, is_dir: bool, size: u64, mtime: &str) -> Entry {
1102 Entry {
1103 name: name.to_string(),
1104 is_dir,
1105 size,
1106 mtime: mtime.to_string(),
1107 kind: FileKind::Binary,
1108 }
1109 }
1110
1111 fn sorted(mut v: Vec<Entry>, key: SortKey, desc: bool) -> Vec<String> {
1112 v.sort_by(|a, b| cmp_entries(a, b, key, desc));
1113 v.into_iter().map(|e| e.name).collect()
1114 }
1115
1116 /// Paging slices this order, so a wrong order puts a file on the wrong
1117 /// page.
1118 #[test]
1119 fn sort_keeps_folders_first_in_every_order() {
1120 let v = vec![
1121 entry("b.txt", false, 10, "2026-01-02T00:00:00Z"),
1122 entry("Zdir", true, 0, "2026-01-01T00:00:00Z"),
1123 entry("a.txt", false, 30, "2026-01-03T00:00:00Z"),
1124 ];
1125 for key in [SortKey::Name, SortKey::Size, SortKey::Modified] {
1126 for desc in [false, true] {
1127 assert_eq!(
1128 sorted(v.clone(), key, desc)[0],
1129 "Zdir",
1130 "{key:?} desc={desc}"
1131 );
1132 }
1133 }
1134 }
1135
1136 #[test]
1137 fn sort_orders_by_the_chosen_key() {
1138 let v = vec![
1139 entry("b.txt", false, 10, "2026-01-02T00:00:00Z"),
1140 entry("a.txt", false, 30, "2026-01-03T00:00:00Z"),
1141 entry("c.txt", false, 20, "2026-01-01T00:00:00Z"),
1142 ];
1143 let s = |key, desc| sorted(v.clone(), key, desc);
1144 assert_eq!(s(SortKey::Name, false), ["a.txt", "b.txt", "c.txt"]);
1145 assert_eq!(s(SortKey::Name, true), ["c.txt", "b.txt", "a.txt"]);
1146 assert_eq!(s(SortKey::Size, false), ["b.txt", "c.txt", "a.txt"]);
1147 assert_eq!(s(SortKey::Modified, false), ["c.txt", "b.txt", "a.txt"]);
1148 }
1149
1150 #[test]
1151 fn list_dir_pages_the_sorted_listing() {
1152 let t = T::new();
1153 let d = t.root.join("paged");
1154 std::fs::create_dir_all(d.join("sub")).unwrap();
1155 for i in 0..7 {
1156 std::fs::write(d.join(format!("f{i}")), vec![b'x'; i]).unwrap();
1157 }
1158 let page = |offset, limit, dirs_only| {
1159 let opts = ListOpts {
1160 sort: SortKey::Size,
1161 desc: true,
1162 offset,
1163 limit: Some(limit),
1164 dirs_only,
1165 };
1166 let r = list_dir(&d, opts).unwrap();
1167 let names: Vec<String> = r.entries.into_iter().map(|e| e.name).collect();
1168 (names, r.total, r.offset)
1169 };
1170 assert_eq!(
1171 page(0, 3, false),
1172 (vec!["sub".into(), "f6".into(), "f5".into()], 8, 0)
1173 );
1174 assert_eq!(
1175 page(3, 3, false),
1176 (vec!["f4".into(), "f3".into(), "f2".into()], 8, 3)
1177 );
1178 // Past the end: the last page.
1179 assert_eq!(page(50, 3, false), (vec!["f1".into(), "f0".into()], 8, 6));
1180 // Exactly one past a full last page, as after deleting its entries.
1181 assert_eq!(page(8, 4, false).2, 4);
1182 assert_eq!(page(0, 3, true), (vec!["sub".into()], 1, 0));
1183 // A zero limit is one entry, not a division by zero.
1184 assert_eq!(page(2, 0, false), (vec!["f5".into()], 8, 2));
1185 assert_eq!(page(0, usize::MAX, false).0.len(), 8);
1186
1187 let empty = t.root.join("empty");
1188 std::fs::create_dir_all(&empty).unwrap();
1189 let opts = ListOpts {
1190 offset: 30,
1191 limit: Some(10),
1192 ..ListOpts::default()
1193 };
1194 let r = list_dir(&empty, opts).unwrap();
1195 assert_eq!((r.entries.len(), r.total, r.offset), (0, 0, 0));
1196 }
1197
1198 #[cfg(unix)]
1199 #[test]
1200 fn list_dir_reports_broken_symlink_as_empty_file() {
1201 let t = T::new();
1202 let d = t.root.join("withlink");
1203 std::fs::create_dir_all(&d).unwrap();
1204 std::os::unix::fs::symlink(d.join("does-not-exist"), d.join("broken")).unwrap();
1205 let entries = list_dir(&d, ListOpts::default()).unwrap().entries;
1206 assert_eq!(entries.len(), 1);
1207 assert_eq!(entries[0].name, "broken");
1208 assert!(!entries[0].is_dir);
1209 assert_eq!(entries[0].size, 0);
1210 }
1211
1212 // ---------- mkdir ----------
1213
1214 #[test]
1215 fn mkdir_creates_nested_dirs() {
1216 let t = T::new();
1217 let root = t.root.canonicalize().unwrap();
1218 // The parent must exist; "new" first, then "new/sub".
1219 mkdir(&root, ".", "new").unwrap();
1220 assert!(root.join("new").is_dir());
1221 mkdir(&root, ".", "new/sub").unwrap();
1222 assert!(root.join("new/sub").is_dir());
1223 }
1224
1225 #[test]
1226 fn mkdir_rejects_conflict_and_bad_names() {
1227 let t = T::new();
1228 let root = t.root.canonicalize().unwrap();
1229 assert!(matches!(mkdir(&root, ".", "docs"), Err(FsError::Conflict)));
1230 assert!(matches!(
1231 mkdir(&root, ".", "a/b/../../c"),
1232 Err(FsError::Forbidden)
1233 ));
1234 assert!(matches!(
1235 mkdir(&root, ".", "file.txt/x"),
1236 Err(FsError::Forbidden) // parent is a file → ENOTDIR
1237 ));
1238 }
1239
1240 // ---------- rename ----------
1241
1242 #[test]
1243 fn rename_moves_file_and_dir() {
1244 let t = T::new();
1245 let root = t.root.canonicalize().unwrap();
1246 let vacated = rename_item(&root, ".", "file.txt", "renamed.txt", false).unwrap();
1247 assert_eq!(vacated, root.join("file.txt"));
1248 assert!(!root.join("file.txt").exists());
1249 assert_eq!(
1250 std::fs::read_to_string(root.join("renamed.txt")).unwrap(),
1251 "top file"
1252 );
1253 rename_item(&root, ".", "docs", "docs2", false).unwrap();
1254 assert!(root.join("docs2/inner/hello.txt").exists());
1255 }
1256
1257 #[test]
1258 fn rename_conflicts_and_overwrite() {
1259 let t = T::new();
1260 let root = t.root.canonicalize().unwrap();
1261 std::fs::write(root.join("other.txt"), "other").unwrap();
1262 // Target file exists, no overwrite → conflict.
1263 assert!(matches!(
1264 rename_item(&root, ".", "file.txt", "other.txt", false),
1265 Err(FsError::Conflict)
1266 ));
1267 // Overwrite a file target → replaces it.
1268 rename_item(&root, ".", "file.txt", "other.txt", true).unwrap();
1269 assert_eq!(
1270 std::fs::read_to_string(root.join("other.txt")).unwrap(),
1271 "top file"
1272 );
1273 // A dir target is never overwritten, even with the flag.
1274 assert!(matches!(
1275 rename_item(&root, ".", "other.txt", "docs", true),
1276 Err(FsError::Conflict)
1277 ));
1278 // Renaming into a free slot works, then onto itself is a no-op.
1279 rename_item(&root, ".", "other.txt", "free.txt", false).unwrap();
1280 assert!(root.join("free.txt").exists());
1281 rename_item(&root, ".", "free.txt", "free.txt", false).unwrap();
1282 assert!(root.join("free.txt").exists());
1283 assert!(root.join("free.txt").is_file());
1284 }
1285
1286 #[test]
1287 fn rename_validates_new_name() {
1288 let t = T::new();
1289 let root = t.root.canonicalize().unwrap();
1290 for bad in ["a/b", "", ".", ".."] {
1291 assert!(matches!(
1292 rename_item(&root, ".", "file.txt", bad, false),
1293 Err(FsError::Invalid(_))
1294 ));
1295 }
1296 assert!(matches!(
1297 rename_item(&root, ".", "missing", "x", false),
1298 Err(FsError::NotFound)
1299 ));
1300 }
1301
1302 // ---------- remove ----------
1303
1304 #[test]
1305 fn remove_file_and_dir() {
1306 let t = T::new();
1307 let root = t.root.canonicalize().unwrap();
1308 let (is_dir, gone) = remove_item(&root, ".", "file.txt").unwrap();
1309 assert!(!is_dir);
1310 assert_eq!(gone, root.join("file.txt"));
1311 assert!(!root.join("file.txt").exists());
1312 let (is_dir, gone) = remove_item(&root, ".", "docs").unwrap();
1313 assert!(is_dir);
1314 assert_eq!(gone, root.join("docs"));
1315 assert!(!root.join("docs").exists());
1316 assert!(matches!(
1317 remove_item(&root, ".", "file.txt"),
1318 Err(FsError::NotFound)
1319 ));
1320 }
1321
1322 // ---------- save_file ----------
1323
1324 fn mtime_of(p: &Path) -> i64 {
1325 std::fs::metadata(p)
1326 .unwrap()
1327 .modified()
1328 .unwrap()
1329 .duration_since(std::time::UNIX_EPOCH)
1330 .unwrap()
1331 .as_secs() as i64
1332 }
1333
1334 #[test]
1335 fn save_file_updates_content_and_returns_new_mtime() {
1336 let t = T::new();
1337 let root = t.root.canonicalize().unwrap();
1338 let before = mtime_of(&root.join("file.txt"));
1339 // Sleep so the mtime actually advances (filesystem granularity).
1340 std::thread::sleep(std::time::Duration::from_millis(1100));
1341 let new = save_file(&root, ".", "file.txt", b"brand new", Some(before)).unwrap();
1342 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"brand new");
1343 assert!(new >= before);
1344 // A second save with the *returned* mtime succeeds.
1345 let new2 = save_file(&root, ".", "file.txt", b"again", Some(new)).unwrap();
1346 assert!(new2 >= new);
1347 // Without an expected mtime, always saves.
1348 let _ = save_file(&root, ".", "file.txt", b"force", None).unwrap();
1349 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"force");
1350 }
1351
1352 #[test]
1353 fn save_file_conflict_on_stale_mtime() {
1354 let t = T::new();
1355 let root = t.root.canonicalize().unwrap();
1356 std::thread::sleep(std::time::Duration::from_millis(1100));
1357 // The mtime we pass is older than the file's real mtime → conflict.
1358 assert!(matches!(
1359 save_file(&root, ".", "file.txt", b"x", Some(1)),
1360 Err(FsError::Conflict)
1361 ));
1362 }
1363
1364 #[test]
1365 fn save_file_error_cases() {
1366 let t = T::new();
1367 let root = t.root.canonicalize().unwrap();
1368 assert!(matches!(
1369 save_file(&root, ".", "nope.txt", b"x", None),
1370 Err(FsError::NotFound)
1371 ));
1372 assert!(matches!(
1373 save_file(&root, ".", "docs", b"x", None),
1374 Err(FsError::NotADirectory)
1375 ));
1376 assert!(matches!(
1377 save_file(&root, ".", "../evil.txt", b"x", None),
1378 Err(FsError::Forbidden)
1379 ));
1380 }
1381
1382 // ---------- move / copy ----------
1383
1384 #[test]
1385 fn move_file_and_dir_across_dirs() {
1386 let t = T::new();
1387 let root = t.root.canonicalize().unwrap();
1388 let vacated = move_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1389 assert_eq!(vacated, root.join("file.txt"));
1390 assert!(!root.join("file.txt").exists());
1391 assert!(root.join("src/file.txt").exists());
1392 move_item(&root, ".", "src", ".", "docs", false).unwrap();
1393 assert!(root.join("docs/src/main.rs").exists());
1394 assert!(!root.join("src").exists());
1395 }
1396
1397 #[test]
1398 fn move_refuses_into_self_and_conflicts() {
1399 let t = T::new();
1400 let root = t.root.canonicalize().unwrap();
1401 // A dir cannot be moved into itself or a descendant.
1402 assert!(matches!(
1403 move_item(&root, ".", "docs", ".", "docs", false),
1404 Err(FsError::Invalid(_))
1405 ));
1406 assert!(matches!(
1407 move_item(&root, ".", "docs", ".", "docs/inner", false),
1408 Err(FsError::Invalid(_))
1409 ));
1410 // A dir target always conflicts, even with overwrite: move the file
1411 // "x" into a folder that already contains a subfolder "x".
1412 std::fs::create_dir_all(root.join("mv/case/x")).unwrap();
1413 std::fs::create_dir_all(root.join("mv/out")).unwrap();
1414 std::fs::write(root.join("mv/out/x"), "a file named x").unwrap();
1415 assert!(matches!(
1416 move_item(&root, ".", "mv/out/x", ".", "mv/case", true),
1417 Err(FsError::Conflict)
1418 ));
1419 // File onto file: conflict without overwrite, replaced with.
1420 std::fs::write(root.join("tmp-x.txt"), "x").unwrap();
1421 std::fs::write(root.join("tmp-y.txt"), "y").unwrap();
1422 std::fs::rename(root.join("tmp-x.txt"), root.join("tmp-target.txt")).unwrap();
1423 std::fs::rename(root.join("tmp-y.txt"), root.join("tmp-target2.txt")).unwrap();
1424 // Two distinct files with the same name in one folder.
1425 std::fs::create_dir_all(root.join("mv/dst")).unwrap();
1426 std::fs::create_dir_all(root.join("mv/out2")).unwrap();
1427 std::fs::write(root.join("mv/dst/dup.txt"), "old").unwrap();
1428 std::fs::write(root.join("mv/out2/dup.txt"), "new").unwrap();
1429 assert!(matches!(
1430 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", false),
1431 Err(FsError::Conflict)
1432 ));
1433 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", true).unwrap();
1434 assert_eq!(
1435 std::fs::read_to_string(root.join("mv/dst/dup.txt")).unwrap(),
1436 "new"
1437 );
1438 // Moving onto itself is a no-op success.
1439 move_item(&root, ".", "tmp-target.txt", ".", ".", false).unwrap();
1440 assert!(root.join("tmp-target.txt").exists());
1441 // Missing destination dir.
1442 assert!(matches!(
1443 move_item(&root, ".", "file.txt", ".", "nope", false),
1444 Err(FsError::NotFound)
1445 ));
1446 }
1447
1448 #[test]
1449 fn copy_file_and_dir_preserves_mtime() {
1450 let t = T::new();
1451 let root = t.root.canonicalize().unwrap();
1452 let before = mtime_of(&root.join("file.txt"));
1453 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1454 let copy = root.join("src/file.txt");
1455 assert_eq!(std::fs::read(&copy).unwrap(), b"top file");
1456 assert_eq!(mtime_of(&copy), before);
1457 // Dir copy.
1458 copy_item(&root, ".", "docs", ".", "src", false).unwrap();
1459 assert_eq!(
1460 std::fs::read_to_string(root.join("src/docs/inner/hello.txt")).unwrap(),
1461 "hello"
1462 );
1463 // Originals still there.
1464 assert!(root.join("file.txt").exists());
1465 assert!(root.join("docs/a.txt").exists());
1466 }
1467
1468 #[test]
1469 fn copy_refuses_into_self_and_handles_conflict() {
1470 let t = T::new();
1471 let root = t.root.canonicalize().unwrap();
1472 assert!(matches!(
1473 copy_item(&root, ".", "docs", ".", "docs", false),
1474 Err(FsError::Invalid(_))
1475 ));
1476 assert!(matches!(
1477 copy_item(&root, ".", "docs", ".", "docs/inner", false),
1478 Err(FsError::Invalid(_))
1479 ));
1480 // First copy is fine, the second one conflicts, overwrite replaces.
1481 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1482 assert!(matches!(
1483 copy_item(&root, ".", "file.txt", ".", "src", false),
1484 Err(FsError::Conflict)
1485 ));
1486 std::fs::write(root.join("file.txt"), "v2").unwrap();
1487 copy_item(&root, ".", "file.txt", ".", "src", true).unwrap();
1488 assert_eq!(
1489 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1490 "v2"
1491 );
1492 // Copying onto itself is a no-op success.
1493 copy_item(&root, ".", "src/file.txt", ".", "src", false).unwrap();
1494 assert_eq!(
1495 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1496 "v2"
1497 );
1498 // Missing destination dir.
1499 assert!(matches!(
1500 copy_item(&root, ".", "file.txt", ".", "nope", false),
1501 Err(FsError::NotFound)
1502 ));
1503 }
1504
1505 #[test]
1506 fn copy_recursive_missing_source() {
1507 let t = T::new();
1508 let dst = t.tmp.path().join("dst");
1509 assert!(matches!(
1510 copy_recursive(&t.root.join("nope"), &dst),
1511 Err(FsError::NotFound)
1512 ));
1513 }
1514
1515 // ---------- is_within_or_eq ----------
1516
1517 #[test]
1518 fn is_within_or_eq_matrix() {
1519 let t = T::new();
1520 let root = t.root.canonicalize().unwrap();
1521 let docs = root.join("docs");
1522 assert!(is_within_or_eq(&docs, &docs));
1523 assert!(is_within_or_eq(&docs, &root.join("docs/inner")));
1524 assert!(!is_within_or_eq(&docs, &root));
1525 assert!(!is_within_or_eq(&docs, &root.join("src")));
1526 }
1527
1528 // ---------- content sniffing ----------
1529
1530 fn kind(bytes: &[u8], name: &str) -> FileKind {
1531 kind_from_bytes(bytes, Path::new(name))
1532 }
1533
1534 #[test]
1535 fn magic_numbers_classify_by_content() {
1536 let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
1537 // The name is a lie in every case: the bytes decide.
1538 assert_eq!(kind(&png, "notes.txt"), FileKind::Image);
1539 assert_eq!(kind(b"%PDF-1.7\n%aaa\n", "x.bin"), FileKind::Pdf);
1540 assert_eq!(
1541 kind(b"PK\x03\x04\x14\x00\x00\x00", "x.png"),
1542 FileKind::Archive
1543 );
1544 assert_eq!(
1545 kind(&[0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0], "x"),
1546 FileKind::Archive
1547 );
1548 assert_eq!(
1549 kind(
1550 &[
1551 0, 0, 0, 0x20, b'f', b't', b'y', b'p', b'i', b's', b'o', b'm'
1552 ],
1553 "x"
1554 ),
1555 FileKind::Video
1556 );
1557 assert_eq!(
1558 kind(b"ID3\x04\x00\x00\x00\x00\x00\x00", "x"),
1559 FileKind::Audio
1560 );
1561 assert_eq!(kind(b"RIFF\x24\x00\x00\x00WAVEfmt ", "x"), FileKind::Audio);
1562 assert_eq!(kind(b"<!doctype html><p>hi", "x"), FileKind::Text);
1563 // Recognized but not viewable in a browser.
1564 assert_eq!(
1565 kind(&[0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0], "x.wasm"),
1566 FileKind::Binary
1567 );
1568 }
1569
1570 #[test]
1571 fn unsigned_files_fall_back_to_the_text_heuristic() {
1572 // No magic number: plain text, source, config.
1573 assert_eq!(kind(b"hello world\n", "notes"), FileKind::Text);
1574 assert_eq!(kind(b"fn main() {}\n", "main.rs"), FileKind::Text);
1575 assert_eq!(
1576 kind("# über\nkey: wert\n".as_bytes(), "c.yaml"),
1577 FileKind::Text
1578 );
1579 // Extensionless text files work, which the old extension list missed.
1580 assert_eq!(kind(b"all:\n\tcargo build\n", "Makefile"), FileKind::Text);
1581 // Empty file → editable.
1582 assert_eq!(kind(b"", "new.txt"), FileKind::Text);
1583 // A NUL byte means binary, whatever the name says. (ELF has no
1584 // `infer` signature, so this is the path that catches it.)
1585 assert_eq!(
1586 kind(&[0x7F, b'E', b'L', b'F', 2, 1, 1, 0, 0], "run.txt"),
1587 FileKind::Binary
1588 );
1589 assert_eq!(kind(&[0xC3, 0x28, 0xFF, 0xFE], "x.txt"), FileKind::Binary);
1590 }
1591
1592 #[test]
1593 fn svg_is_offered_as_an_image() {
1594 // SVG is XML text with no magic number, but browsers draw it, so the
1595 // extension is the only signal available.
1596 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
1597 assert_eq!(kind(svg, "logo.svg"), FileKind::Image);
1598 assert_eq!(kind(svg, "logo.txt"), FileKind::Text);
1599 }
1600
1601 #[test]
1602 fn truncated_utf8_at_the_read_boundary_is_still_text() {
1603 // 255 ASCII bytes plus the first byte of a 2-byte character: the read
1604 // cut a character in half, which must not read as binary.
1605 let mut b = vec![b'a'; SNIFF_BYTES - 1];
1606 b.push(0xC3);
1607 assert_eq!(kind(&b, "x.txt"), FileKind::Text);
1608 }
1609
1610 #[test]
1611 fn detect_kind_reads_from_disk() {
1612 let t = T::new();
1613 assert_eq!(detect_kind(&t.root.join("docs"), true), FileKind::Dir);
1614 assert_eq!(detect_kind(&t.root.join("file.txt"), false), FileKind::Text);
1615 // Unreadable / missing → Binary, never a failed listing.
1616 assert_eq!(detect_kind(&t.root.join("nope"), false), FileKind::Binary);
1617 }
1618
1619 /// `SNIFF_BUDGET` is process-wide, so the two tests that assert on it must
1620 /// not run at the same time as each other.
1621 static BUDGET_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
1622
1623 /// A directory big enough to take the fan-out path must produce exactly
1624 /// what the serial path would. Pass 2 fills `is_dir`, `size`, `mtime` and
1625 /// `kind`, all on worker threads, so a chunk-boundary mistake would show up
1626 /// as a row carrying another row's metadata or the untouched placeholders.
1627 #[test]
1628 fn parallel_rows_match_serial() {
1629 use std::sync::atomic::Ordering;
1630 let _guard = BUDGET_TESTS.lock().unwrap();
1631 let t = T::new();
1632 let big = t.root.join("big");
1633 std::fs::create_dir_all(&big).unwrap();
1634 // Well over SNIFF_CHUNK, so several chunks are handed out.
1635 let n = SNIFF_CHUNK * 3 + 7;
1636 for i in 0..n {
1637 let p = big.join(format!("f{i:05}"));
1638 // Every file gets a distinct length, so `size` pins the row identity.
1639 let pad = vec![b'A'; i];
1640 let mut body = match i % 3 {
1641 0 => vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1642 1 => b"plain text\n".to_vec(),
1643 _ => vec![0u8, 1, 2, 3],
1644 };
1645 body.extend_from_slice(&pad);
1646 std::fs::write(&p, &body).unwrap();
1647 }
1648 std::fs::create_dir(big.join("a-subdir")).unwrap();
1649
1650 let entries = list_dir(&big, ListOpts::default()).unwrap().entries;
1651 assert_eq!(entries.len(), n + 1);
1652
1653 // Every row must agree with what a single-threaded read of that same
1654 // file reports: kind, size and directory flag.
1655 for e in &entries {
1656 let p = big.join(&e.name);
1657 let m = std::fs::metadata(&p).unwrap();
1658 assert_eq!(e.is_dir, m.is_dir(), "{}", e.name);
1659 assert_eq!(e.size, m.len(), "size mismatch on {}", e.name);
1660 assert_eq!(e.mtime, mtime_str(&m), "mtime mismatch on {}", e.name);
1661 assert_eq!(
1662 e.kind,
1663 detect_kind(&p, e.is_dir),
1664 "kind mismatch on {}",
1665 e.name
1666 );
1667 }
1668
1669 // Sanity: several kinds are actually present, so the loop above is not
1670 // trivially true, and the directory sorts first.
1671 let kinds: Vec<FileKind> = entries.iter().map(|e| e.kind).collect();
1672 assert!(kinds.contains(&FileKind::Image));
1673 assert!(kinds.contains(&FileKind::Text));
1674 assert!(kinds.contains(&FileKind::Binary));
1675 assert_eq!(entries[0].name, "a-subdir");
1676 assert_eq!(entries[0].kind, FileKind::Dir);
1677
1678 // The thread budget is fully returned once the listing is done.
1679 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1680 }
1681
1682 #[test]
1683 fn sniff_permit_never_exceeds_the_budget() {
1684 use std::sync::atomic::Ordering;
1685 let _guard = BUDGET_TESTS.lock().unwrap();
1686 let total = sniff_budget_total();
1687 let a = SniffPermit::claim(total * 2);
1688 assert_eq!(a.0, total, "a single claim is capped at the total");
1689 // Nothing left: the next listing runs serially rather than queueing.
1690 let b = SniffPermit::claim(4);
1691 assert_eq!(b.0, 0);
1692 drop(a);
1693 drop(b);
1694 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1695 }
1696
1697 #[test]
1698 fn list_dir_reports_kinds() {
1699 let t = T::new();
1700 std::fs::write(
1701 t.root.join("docs/pic.dat"),
1702 [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1703 )
1704 .unwrap();
1705 let entries = list_dir(&t.root.join("docs"), ListOpts::default())
1706 .unwrap()
1707 .entries;
1708 let kind_of = |n: &str| entries.iter().find(|e| e.name == n).unwrap().kind;
1709 assert_eq!(kind_of("inner"), FileKind::Dir);
1710 assert_eq!(kind_of("a.txt"), FileKind::Text);
1711 assert_eq!(kind_of("pic.dat"), FileKind::Image);
1712 }
1713}
1714