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)]
17pub enum FsError {
18 NotFound,
19 NotADirectory,
20 Forbidden,
21 RootMissing,
22 Conflict,
23 Invalid(String),
24}
25
26impl From<FsError> for ApiError {
27 fn from(e: FsError) -> Self {
28 use axum::http::StatusCode as S;
29 match e {
30 FsError::NotFound => {
31 ApiError::localized(S::NOT_FOUND, "folder not found", "err_fs_not_found")
32 }
33 FsError::NotADirectory => {
34 ApiError::localized(S::BAD_REQUEST, "not a folder", "err_fs_not_a_dir")
35 }
36 FsError::Forbidden => {
37 ApiError::localized(S::FORBIDDEN, "access denied", "err_fs_forbidden")
38 }
39 FsError::RootMissing => ApiError::localized(
40 S::NOT_FOUND,
41 "the configured folder no longer exists",
42 "err_fs_root_missing",
43 ),
44 FsError::Conflict => {
45 ApiError::localized(S::CONFLICT, "already exists", "err_fs_conflict")
46 }
47 // Dynamic message (e.g. an invalid name), not a fixed string.
48 FsError::Invalid(msg) => ApiError::new(S::BAD_REQUEST, msg),
49 }
50 }
51}
52
53/// Resolve a user root (path relative to the server root) to a canonical
54/// absolute path, verified to be inside the server root.
55pub fn resolve_root(server_root: &Path, root_rel: &str) -> Result<PathBuf, FsError> {
56 let candidate = server_root.join(root_rel);
57 let canonical = candidate.canonicalize().map_err(|_| FsError::RootMissing)?;
58 ensure_within(server_root, &canonical)?;
59 if !canonical.is_dir() {
60 return Err(FsError::RootMissing);
61 }
62 Ok(canonical)
63}
64
65/// Resolve a requested path (relative to a user root) safely.
66pub fn resolve_path(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
67 let root_abs = resolve_root(server_root, root_rel)?;
68 let req = Path::new(req_rel);
69 if req.components().any(|c| c == Component::ParentDir) {
70 return Err(FsError::Forbidden);
71 }
72 let full = root_abs.join(req);
73 let full = canonical(&full)?;
74 ensure_within(&root_abs, &full)?;
75 Ok(full)
76}
77
78/// Resolve a share target that is a single file (relative to the server root).
79/// Unlike [`resolve_path`], the target itself is the file — there is no
80/// directory root beneath it.
81pub fn resolve_file(server_root: &Path, rel: &str) -> Result<PathBuf, FsError> {
82 let full = server_root.join(rel);
83 let full = canonical(&full)?;
84 ensure_within(server_root, &full)?;
85 Ok(full)
86}
87
88/// Whether the entry at `p` is itself a directory. A symlink is not, however
89/// its target looks: an operation on the name must not recurse into a tree the
90/// request never named.
91fn entry_is_dir(p: &Path) -> bool {
92 std::fs::symlink_metadata(p).is_ok_and(|m| m.is_dir())
93}
94
95/// Whether a name is taken. Unlike `Path::exists`, a dangling symlink counts:
96/// it still occupies the name.
97fn entry_exists(p: &Path) -> bool {
98 std::fs::symlink_metadata(p).is_ok()
99}
100
101/// `canonicalize`, with a missing path as [`FsError::NotFound`] and every
102/// other failure as [`FsError::Forbidden`].
103fn canonical(p: &Path) -> Result<PathBuf, FsError> {
104 p.canonicalize().map_err(|e| match e.kind() {
105 std::io::ErrorKind::NotFound => FsError::NotFound,
106 _ => FsError::Forbidden,
107 })
108}
109
110fn ensure_within(base: &Path, p: &Path) -> Result<(), FsError> {
111 if is_within_or_eq(base, p) {
112 Ok(())
113 } else {
114 Err(FsError::Forbidden)
115 }
116}
117
118/// Which slice of a folder [`list_dir`] returns, and in what order.
119#[derive(Clone, Debug, Default)]
120pub struct ListOpts {
121 pub sort: SortKey,
122 pub desc: bool,
123 pub offset: usize,
124 /// Clamped to `1..=MAX_LIST_ENTRIES`; `None` = the cap.
125 pub limit: Option<usize>,
126 pub dirs_only: bool,
127 /// Return the page that holds this name; `offset` when it is missing.
128 pub around: Option<String>,
129}
130
131/// List one page of a directory (blocking — call via spawn_blocking).
132pub fn list_dir(dir: &Path, opts: ListOpts) -> Result<FilesResp, FsError> {
133 let rd = std::fs::read_dir(dir).map_err(|e| match e.kind() {
134 std::io::ErrorKind::NotFound => FsError::NotFound,
135 std::io::ErrorKind::NotADirectory => FsError::NotADirectory,
136 _ => FsError::Forbidden,
137 })?;
138
139 // Pass 1: names only. Walking the directory stream is inherently
140 // sequential, but it is also the only part that has to be: every field
141 // below comes from a per-entry syscall, which pass 2 can do in parallel.
142 // The values here are the fallbacks used when that syscall fails.
143 let mut rows: Vec<(Entry, PathBuf)> = Vec::new();
144 for e in rd.flatten() {
145 let entry = Entry {
146 name: e.file_name().to_string_lossy().into_owned(),
147 is_dir: false,
148 size: 0,
149 mtime: EPOCH_MTIME.to_string(),
150 kind: FileKind::Binary,
151 };
152 rows.push((entry, e.path()));
153 }
154
155 // Pass 2: metadata, which the sort needs.
156 describe_rows(&mut rows, fill_meta);
157 if opts.dirs_only {
158 rows.retain(|(e, _)| e.is_dir);
159 }
160 // After pass 2, so the parallel fan-out cannot affect the order.
161 rows.sort_by(|(a, _), (b, _)| cmp_entries(a, b, opts.sort, opts.desc));
162
163 let total = rows.len();
164 let limit = opts
165 .limit
166 .unwrap_or(api_types::MAX_LIST_ENTRIES)
167 .clamp(1, api_types::MAX_LIST_ENTRIES);
168 let at = opts
169 .around
170 .as_deref()
171 .and_then(|n| rows.iter().position(|(e, _)| e.name == n));
172 // Past the end happens when a delete empties the last page.
173 let offset = if let Some(i) = at {
174 i / limit * limit
175 } else if opts.offset < total {
176 opts.offset
177 } else {
178 total.saturating_sub(1) / limit * limit
179 };
180 let mut page: Vec<(Entry, PathBuf)> = rows.into_iter().skip(offset).take(limit).collect();
181
182 // Pass 3: the content sniff, only for the page. It reads file data, which
183 // on a spinning disk costs a seek per file.
184 describe_rows(&mut page, fill_kind);
185
186 Ok(FilesResp {
187 entries: page.into_iter().map(|(e, _)| e).collect(),
188 total,
189 offset,
190 })
191}
192
193/// The listing order: folders first, then `key`. Folders have no
194/// meaningful size, so a size order keeps them in name order.
195fn cmp_entries(a: &Entry, b: &Entry, key: SortKey, desc: bool) -> Ordering {
196 let dir = |o: Ordering| if desc { o.reverse() } else { o };
197 b.is_dir.cmp(&a.is_dir).then_with(|| match key {
198 SortKey::Name => dir(cmp_name(a, b)),
199 SortKey::Size if a.is_dir => cmp_name(a, b),
200 SortKey::Size => dir(a.size.cmp(&b.size)).then_with(|| cmp_name(a, b)),
201 // RFC 3339 UTC with a fixed width, so bytewise order is
202 // chronological order.
203 SortKey::Modified => dir(a.mtime.cmp(&b.mtime)).then_with(|| cmp_name(a, b)),
204 })
205}
206
207/// Case-insensitive, with the raw name as the tie-breaker so two names that
208/// differ only in case keep a stable order.
209fn cmp_name(a: &Entry, b: &Entry) -> Ordering {
210 fn lower(s: &str) -> impl Iterator<Item = char> + '_ {
211 s.chars().flat_map(char::to_lowercase)
212 }
213 lower(&a.name)
214 .cmp(lower(&b.name))
215 .then_with(|| a.name.cmp(&b.name))
216}
217
218// ---------------------------------------------------------------------------
219// Content sniffing
220// ---------------------------------------------------------------------------
221
222/// How many leading bytes we read to classify a file. Every magic number
223/// `infer` knows lives in the first few dozen bytes; 256 also gives the
224/// text/binary heuristic enough to work with. Measured at ~4.6 µs per file,
225/// against ~1.4 µs for the `metadata` call in the same pass.
226const SNIFF_BYTES: usize = 256;
227
228/// Entries per thread, and the point below which parallelism is not worth it.
229/// Measured on a 22-core machine: at 50 entries fan-out is a wash (thread
230/// spawn costs about as much as the work), at 200 it is already 2x.
231const SNIFF_CHUNK: usize = 256;
232
233/// Process-wide ceiling on threads spawned for sniffing, so many concurrent
234/// listings of large directories cannot multiply into a thread explosion.
235/// One listing alone can use the whole budget; the next one degrades to fewer
236/// threads, and eventually to serial, instead of queueing.
237static SNIFF_BUDGET: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
238
239fn sniff_budget_total() -> usize {
240 static TOTAL: std::sync::LazyLock<usize> = std::sync::LazyLock::new(|| {
241 std::thread::available_parallelism()
242 .map(|n| n.get())
243 .unwrap_or(1)
244 });
245 *TOTAL
246}
247
248/// Claimed helper threads, returned to [`SNIFF_BUDGET`] on drop.
249struct SniffPermit(usize);
250
251impl SniffPermit {
252 /// Claim up to `want` helper threads, or fewer when the budget is thin.
253 fn claim(want: usize) -> Self {
254 use std::sync::atomic::Ordering;
255 let total = sniff_budget_total();
256 let mut granted = 0;
257 let _ = SNIFF_BUDGET.fetch_update(Ordering::AcqRel, Ordering::Acquire, |in_flight| {
258 granted = want.min(total.saturating_sub(in_flight));
259 (granted > 0).then_some(in_flight + granted)
260 });
261 Self(granted)
262 }
263}
264
265impl Drop for SniffPermit {
266 fn drop(&mut self) {
267 if self.0 > 0 {
268 SNIFF_BUDGET.fetch_sub(self.0, std::sync::atomic::Ordering::AcqRel);
269 }
270 }
271}
272
273/// Metadata for one row. Follows symlinks; a broken link keeps the caller's
274/// fallbacks and so shows up as an empty file.
275fn fill_meta(entry: &mut Entry, path: &Path) {
276 if let Ok(m) = std::fs::metadata(path) {
277 entry.is_dir = m.is_dir();
278 entry.size = m.len();
279 entry.mtime = mtime_str(&m);
280 }
281}
282
283/// The content sniff for one row. Needs `is_dir`, so it runs after
284/// [`fill_meta`].
285fn fill_kind(entry: &mut Entry, path: &Path) {
286 entry.kind = detect_kind(path, entry.is_dir);
287}
288
289/// Apply `one` to each row, fanning the work out across threads for big
290/// directories.
291///
292/// The calling thread takes a chunk too, so `n` helper threads process `n + 1`
293/// chunks and a zero-thread grant is simply the serial path.
294fn describe_rows(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) {
295 fn describe(rows: &mut [(Entry, PathBuf)], one: fn(&mut Entry, &Path)) {
296 for (entry, path) in rows {
297 one(entry, path);
298 }
299 }
300
301 if rows.len() < SNIFF_CHUNK {
302 describe(rows, one);
303 return;
304 }
305 // One chunk per helper thread plus one for this thread.
306 let want = rows.len().div_ceil(SNIFF_CHUNK).saturating_sub(1);
307 let permit = SniffPermit::claim(want);
308 if permit.0 == 0 {
309 describe(rows, one);
310 return;
311 }
312 let chunk = rows.len().div_ceil(permit.0 + 1);
313 std::thread::scope(|s| {
314 let mut rest = rows;
315 // Hand every chunk but the last to a helper thread.
316 while rest.len() > chunk {
317 let (head, tail) = rest.split_at_mut(chunk);
318 s.spawn(move || describe(head, one));
319 rest = tail;
320 }
321 describe(rest, one);
322 });
323}
324
325/// Classify a directory entry by reading its first [`SNIFF_BYTES`] bytes.
326///
327/// Blocking — called from `list_dir` (itself under `spawn_blocking`), on
328/// several threads at once for large directories. An unreadable file is
329/// reported as [`FileKind::Binary`] rather than failing the whole listing.
330///
331// ponytail: one open() per entry, fanned out but not cached. Measured warm on
332// 22 cores: 5000 entries take 29 ms serially and 6.9 ms across threads. The
333// remaining ceiling is a cold cache or a network filesystem (NFS/SMB), where
334// each entry costs a round trip. If that shows up: cache by (dev, ino, mtime),
335// or skip the sniff for zero-byte files.
336pub fn detect_kind(path: &Path, is_dir: bool) -> FileKind {
337 if is_dir {
338 return FileKind::Dir;
339 }
340 let mut head = [0u8; SNIFF_BYTES];
341 // A read error is *not* the same as an empty file: an empty file is text
342 // (it opens in the editor), an unreadable one gets no viewer offered.
343 match std::fs::File::open(path).and_then(|mut f| f.read(&mut head)) {
344 Ok(n) => kind_from_bytes(&head[..n], path),
345 Err(_) => FileKind::Binary,
346 }
347}
348
349/// The pure half of [`detect_kind`], so it can be unit-tested without a disk.
350///
351/// `path` is consulted only for the SVG case: SVG is XML text with no magic
352/// number, but browsers render it as an image, so the extension is the only
353/// thing that can tell us to offer an image preview.
354fn kind_from_bytes(head: &[u8], path: &Path) -> FileKind {
355 if let Some(t) = infer::get(head) {
356 // PDF is filed under `Archive` by `infer`, so match the MIME first.
357 if t.mime_type() == "application/pdf" {
358 return FileKind::Pdf;
359 }
360 return match t.matcher_type() {
361 infer::MatcherType::Image => FileKind::Image,
362 infer::MatcherType::Video => FileKind::Video,
363 infer::MatcherType::Audio => FileKind::Audio,
364 infer::MatcherType::Archive => FileKind::Archive,
365 infer::MatcherType::Text => FileKind::Text,
366 // App / Book / Font / Doc / Custom: recognized, but nothing we
367 // can show in the browser.
368 _ => FileKind::Binary,
369 };
370 }
371 if !looks_like_text(head) {
372 return FileKind::Binary;
373 }
374 let ext = path
375 .extension()
376 .map(|e| e.to_string_lossy().to_lowercase())
377 .unwrap_or_default();
378 if ext == "svg" {
379 FileKind::Image
380 } else {
381 FileKind::Text
382 }
383}
384
385/// Text heuristic for the files `infer` has no signature for (plain text,
386/// source code, most config formats): no NUL byte, and the head decodes as
387/// UTF-8 once a truncated trailing character is discounted.
388///
389/// An empty file counts as text — it opens in the editor, which is what you
390/// want for a file you just created.
391fn looks_like_text(head: &[u8]) -> bool {
392 if head.contains(&0) {
393 return false;
394 }
395 match std::str::from_utf8(head) {
396 Ok(_) => true,
397 // A multi-byte character cut in half by the read boundary is fine;
398 // anything else is not text. `error_len() == None` means "unexpected
399 // end of input", i.e. truncation.
400 Err(e) => e.error_len().is_none() && e.valid_up_to() + 4 > head.len(),
401 }
402}
403
404/// Reported when a file's modification time is unavailable or unrepresentable.
405const EPOCH_MTIME: &str = "1970-01-01T00:00:00Z";
406
407/// A file's modification time in whole unix seconds, or `None` when the
408/// platform cannot report one. The single place that converts a `SystemTime`.
409pub fn mtime_secs(m: &std::fs::Metadata) -> Option<i64> {
410 m.modified()
411 .ok()
412 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
413 .map(|d| d.as_secs() as i64)
414}
415
416fn mtime_str(m: &std::fs::Metadata) -> String {
417 let dt: Option<DateTime<chrono::Utc>> =
418 mtime_secs(m).and_then(|s| DateTime::from_timestamp(s, 0));
419 dt.map(|d| d.to_rfc3339_opts(chrono::SecondsFormat::Secs, true))
420 .unwrap_or_else(|| EPOCH_MTIME.to_string())
421}
422
423// ---------------------------------------------------------------------------
424// Mutations (milestone 3): mkdir, rename, remove, move, copy, upload
425// ---------------------------------------------------------------------------
426
427/// Resolve a directory that must exist (relative to a user root). Used as the
428/// base for operations that target the *parent* of the item.
429pub fn resolve_dir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
430 let full = resolve_path(server_root, root_rel, req_rel)?;
431 if !full.is_dir() {
432 return Err(FsError::NotADirectory);
433 }
434 Ok(full)
435}
436
437/// Validate a new single-component name (for rename / new folder).
438fn validate_component(name: &str) -> Result<(), FsError> {
439 let p = Path::new(name);
440 if name.is_empty()
441 || p.components().count() != 1
442 || name == "."
443 || name == ".."
444 || name.contains(['/', '\\', '\0'])
445 {
446 return Err(FsError::Invalid("invalid name".to_string()));
447 }
448 Ok(())
449}
450
451/// Create a directory (and any missing parents) inside a user root.
452pub fn mkdir(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
453 let full = resolve_entry(server_root, root_rel, req_rel)?;
454 if full.exists() {
455 return Err(FsError::Conflict);
456 }
457 std::fs::create_dir_all(&full).map_err(|e| io_err(e, &full))?;
458 Ok(())
459}
460
461/// Create an empty file. The parent must exist; the file must not.
462pub fn create_file(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<(), FsError> {
463 let full = resolve_entry(server_root, root_rel, req_rel)?;
464 // create_new = O_EXCL: fails on an existing path, does not follow a symlink.
465 std::fs::File::create_new(&full).map_err(|e| match e.kind() {
466 std::io::ErrorKind::AlreadyExists => FsError::Conflict,
467 _ => io_err(e, &full),
468 })?;
469 Ok(())
470}
471
472/// Resolve a path that names an *entry*, not the file that entry may point at.
473///
474/// The last component is never followed and need not exist. The parent must,
475/// and is canonicalized and checked against the root.
476///
477/// This is the resolver for operations that act on the name: create, delete,
478/// rename, the source of a move, the destination of a move or copy. Following
479/// a symlink there would delete a file the request never mentioned, or rename
480/// one into a different directory. Reads and content writes use
481/// [`resolve_path`] instead and do follow, contained by `ensure_within`.
482pub(crate) fn resolve_entry(
483 server_root: &Path,
484 root_rel: &str,
485 req_rel: &str,
486) -> Result<PathBuf, FsError> {
487 let root_abs = resolve_root(server_root, root_rel)?;
488 let req = Path::new(req_rel);
489 if req.components().any(|c| c == Component::ParentDir) {
490 return Err(FsError::Forbidden);
491 }
492 let full = root_abs.join(req);
493 // The parent must exist and stay inside the root.
494 let parent = full
495 .parent()
496 .filter(|p| !p.as_os_str().is_empty())
497 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
498 let parent = parent.canonicalize().map_err(|e| io_err(e, parent))?;
499 ensure_within(&root_abs, &parent)?;
500 // Re-join onto the *canonical* parent. `full` may still spell a symlinked
501 // directory, and a caller comparing it against another resolved path (see
502 // [`move_to`]) would then compare two different spellings of one place.
503 let name = full
504 .file_name()
505 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
506 Ok(parent.join(name))
507}
508
509/// Rename (or move within the same directory) an item.
510/// Returns the path the item was renamed *away from*, so the caller can
511/// revoke anything (a share) that still names it.
512pub fn rename_item(
513 server_root: &Path,
514 root_rel: &str,
515 req_rel: &str,
516 new_name: &str,
517 overwrite: bool,
518) -> Result<PathBuf, FsError> {
519 validate_component(new_name)?;
520 let from = resolve_entry(server_root, root_rel, req_rel)?;
521 let parent = from
522 .parent()
523 .ok_or_else(|| FsError::Invalid("invalid path".to_string()))?;
524 let to = parent.join(new_name);
525 // Renaming onto itself is a no-op (the overwrite path below would
526 // delete the file before the rename). Nothing was vacated.
527 if to == from {
528 return Ok(to);
529 }
530 // `rename` replaces a file target atomically; no remove-then-rename gap.
531 if entry_exists(&to) && (!overwrite || entry_is_dir(&to) || entry_is_dir(&from)) {
532 return Err(FsError::Conflict);
533 }
534 std::fs::rename(&from, &to).map_err(|e| io_err(e, &to))?;
535 Ok(from)
536}
537
538/// Delete a file or a directory tree. Returns the path that is now gone (so
539/// the caller can revoke shares naming it).
540pub fn remove_item(server_root: &Path, root_rel: &str, req_rel: &str) -> Result<PathBuf, FsError> {
541 let full = resolve_entry(server_root, root_rel, req_rel)?;
542 // A symlink is unlinked, never followed: deleting it must not delete the
543 // file it names. A dangling link is deletable for the same reason.
544 if entry_is_dir(&full) {
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(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.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 around: None,
1166 };
1167 let r = list_dir(&d, opts).unwrap();
1168 let names: Vec<String> = r.entries.into_iter().map(|e| e.name).collect();
1169 (names, r.total, r.offset)
1170 };
1171 assert_eq!(
1172 page(0, 3, false),
1173 (vec!["sub".into(), "f6".into(), "f5".into()], 8, 0)
1174 );
1175 assert_eq!(
1176 page(3, 3, false),
1177 (vec!["f4".into(), "f3".into(), "f2".into()], 8, 3)
1178 );
1179 // Past the end: the last page.
1180 assert_eq!(page(50, 3, false), (vec!["f1".into(), "f0".into()], 8, 6));
1181 // Exactly one past a full last page, as after deleting its entries.
1182 assert_eq!(page(8, 4, false).2, 4);
1183 assert_eq!(page(0, 3, true), (vec!["sub".into()], 1, 0));
1184 // A zero limit is one entry, not a division by zero.
1185 assert_eq!(page(2, 0, false), (vec!["f5".into()], 8, 2));
1186 assert_eq!(page(0, usize::MAX, false).0.len(), 8);
1187 let around = |name: &str| {
1188 let opts = ListOpts {
1189 sort: SortKey::Size,
1190 desc: true,
1191 offset: 3,
1192 limit: Some(3),
1193 around: Some(name.into()),
1194 ..ListOpts::default()
1195 };
1196 list_dir(&d, opts).unwrap().offset
1197 };
1198 assert_eq!(around("f1"), 6);
1199 assert_eq!(around("sub"), 0);
1200 assert_eq!(around("missing"), 3);
1201
1202 let empty = t.root.join("empty");
1203 std::fs::create_dir_all(&empty).unwrap();
1204 let opts = ListOpts {
1205 offset: 30,
1206 limit: Some(10),
1207 ..ListOpts::default()
1208 };
1209 let r = list_dir(&empty, opts).unwrap();
1210 assert_eq!((r.entries.len(), r.total, r.offset), (0, 0, 0));
1211 }
1212
1213 #[cfg(unix)]
1214 #[test]
1215 fn list_dir_reports_broken_symlink_as_empty_file() {
1216 let t = T::new();
1217 let d = t.root.join("withlink");
1218 std::fs::create_dir_all(&d).unwrap();
1219 std::os::unix::fs::symlink(d.join("does-not-exist"), d.join("broken")).unwrap();
1220 let entries = list_dir(&d, ListOpts::default()).unwrap().entries;
1221 assert_eq!(entries.len(), 1);
1222 assert_eq!(entries[0].name, "broken");
1223 assert!(!entries[0].is_dir);
1224 assert_eq!(entries[0].size, 0);
1225 }
1226
1227 // ---------- mkdir ----------
1228
1229 #[test]
1230 fn mkdir_creates_nested_dirs() {
1231 let t = T::new();
1232 let root = t.root.canonicalize().unwrap();
1233 // The parent must exist; "new" first, then "new/sub".
1234 mkdir(&root, ".", "new").unwrap();
1235 assert!(root.join("new").is_dir());
1236 mkdir(&root, ".", "new/sub").unwrap();
1237 assert!(root.join("new/sub").is_dir());
1238 }
1239
1240 #[test]
1241 fn mkdir_rejects_conflict_and_bad_names() {
1242 let t = T::new();
1243 let root = t.root.canonicalize().unwrap();
1244 assert!(matches!(mkdir(&root, ".", "docs"), Err(FsError::Conflict)));
1245 assert!(matches!(
1246 mkdir(&root, ".", "a/b/../../c"),
1247 Err(FsError::Forbidden)
1248 ));
1249 assert!(matches!(
1250 mkdir(&root, ".", "file.txt/x"),
1251 Err(FsError::Forbidden) // parent is a file → ENOTDIR
1252 ));
1253 }
1254
1255 // ---------- rename ----------
1256
1257 #[test]
1258 fn rename_moves_file_and_dir() {
1259 let t = T::new();
1260 let root = t.root.canonicalize().unwrap();
1261 let vacated = rename_item(&root, ".", "file.txt", "renamed.txt", false).unwrap();
1262 assert_eq!(vacated, root.join("file.txt"));
1263 assert!(!root.join("file.txt").exists());
1264 assert_eq!(
1265 std::fs::read_to_string(root.join("renamed.txt")).unwrap(),
1266 "top file"
1267 );
1268 rename_item(&root, ".", "docs", "docs2", false).unwrap();
1269 assert!(root.join("docs2/inner/hello.txt").exists());
1270 }
1271
1272 #[test]
1273 fn rename_conflicts_and_overwrite() {
1274 let t = T::new();
1275 let root = t.root.canonicalize().unwrap();
1276 std::fs::write(root.join("other.txt"), "other").unwrap();
1277 // Target file exists, no overwrite → conflict.
1278 assert!(matches!(
1279 rename_item(&root, ".", "file.txt", "other.txt", false),
1280 Err(FsError::Conflict)
1281 ));
1282 // Overwrite a file target → replaces it.
1283 rename_item(&root, ".", "file.txt", "other.txt", true).unwrap();
1284 assert_eq!(
1285 std::fs::read_to_string(root.join("other.txt")).unwrap(),
1286 "top file"
1287 );
1288 // A dir target is never overwritten, even with the flag.
1289 assert!(matches!(
1290 rename_item(&root, ".", "other.txt", "docs", true),
1291 Err(FsError::Conflict)
1292 ));
1293 // Renaming into a free slot works, then onto itself is a no-op.
1294 rename_item(&root, ".", "other.txt", "free.txt", false).unwrap();
1295 assert!(root.join("free.txt").exists());
1296 rename_item(&root, ".", "free.txt", "free.txt", false).unwrap();
1297 assert!(root.join("free.txt").exists());
1298 assert!(root.join("free.txt").is_file());
1299 }
1300
1301 #[test]
1302 fn rename_validates_new_name() {
1303 let t = T::new();
1304 let root = t.root.canonicalize().unwrap();
1305 for bad in ["a/b", "", ".", ".."] {
1306 assert!(matches!(
1307 rename_item(&root, ".", "file.txt", bad, false),
1308 Err(FsError::Invalid(_))
1309 ));
1310 }
1311 assert!(matches!(
1312 rename_item(&root, ".", "missing", "x", false),
1313 Err(FsError::NotFound)
1314 ));
1315 }
1316
1317 // ---------- remove ----------
1318
1319 #[test]
1320 fn remove_file_and_dir() {
1321 let t = T::new();
1322 let root = t.root.canonicalize().unwrap();
1323 let gone = remove_item(&root, ".", "file.txt").unwrap();
1324 assert_eq!(gone, root.join("file.txt"));
1325 assert!(!root.join("file.txt").exists());
1326 let gone = remove_item(&root, ".", "docs").unwrap();
1327 assert_eq!(gone, root.join("docs"));
1328 assert!(!root.join("docs").exists());
1329 assert!(matches!(
1330 remove_item(&root, ".", "file.txt"),
1331 Err(FsError::NotFound)
1332 ));
1333 }
1334
1335 // ---------- save_file ----------
1336
1337 fn mtime_of(p: &Path) -> i64 {
1338 std::fs::metadata(p)
1339 .unwrap()
1340 .modified()
1341 .unwrap()
1342 .duration_since(std::time::UNIX_EPOCH)
1343 .unwrap()
1344 .as_secs() as i64
1345 }
1346
1347 #[test]
1348 fn save_file_updates_content_and_returns_new_mtime() {
1349 let t = T::new();
1350 let root = t.root.canonicalize().unwrap();
1351 let before = mtime_of(&root.join("file.txt"));
1352 // Sleep so the mtime actually advances (filesystem granularity).
1353 std::thread::sleep(std::time::Duration::from_millis(1100));
1354 let new = save_file(&root, ".", "file.txt", b"brand new", Some(before)).unwrap();
1355 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"brand new");
1356 assert!(new >= before);
1357 // A second save with the *returned* mtime succeeds.
1358 let new2 = save_file(&root, ".", "file.txt", b"again", Some(new)).unwrap();
1359 assert!(new2 >= new);
1360 // Without an expected mtime, always saves.
1361 let _ = save_file(&root, ".", "file.txt", b"force", None).unwrap();
1362 assert_eq!(std::fs::read(root.join("file.txt")).unwrap(), b"force");
1363 }
1364
1365 #[test]
1366 fn save_file_conflict_on_stale_mtime() {
1367 let t = T::new();
1368 let root = t.root.canonicalize().unwrap();
1369 std::thread::sleep(std::time::Duration::from_millis(1100));
1370 // The mtime we pass is older than the file's real mtime → conflict.
1371 assert!(matches!(
1372 save_file(&root, ".", "file.txt", b"x", Some(1)),
1373 Err(FsError::Conflict)
1374 ));
1375 }
1376
1377 #[test]
1378 fn save_file_error_cases() {
1379 let t = T::new();
1380 let root = t.root.canonicalize().unwrap();
1381 assert!(matches!(
1382 save_file(&root, ".", "nope.txt", b"x", None),
1383 Err(FsError::NotFound)
1384 ));
1385 assert!(matches!(
1386 save_file(&root, ".", "docs", b"x", None),
1387 Err(FsError::NotADirectory)
1388 ));
1389 assert!(matches!(
1390 save_file(&root, ".", "../evil.txt", b"x", None),
1391 Err(FsError::Forbidden)
1392 ));
1393 }
1394
1395 // ---------- move / copy ----------
1396
1397 #[test]
1398 fn move_file_and_dir_across_dirs() {
1399 let t = T::new();
1400 let root = t.root.canonicalize().unwrap();
1401 let vacated = move_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1402 assert_eq!(vacated, root.join("file.txt"));
1403 assert!(!root.join("file.txt").exists());
1404 assert!(root.join("src/file.txt").exists());
1405 move_item(&root, ".", "src", ".", "docs", false).unwrap();
1406 assert!(root.join("docs/src/main.rs").exists());
1407 assert!(!root.join("src").exists());
1408 }
1409
1410 #[test]
1411 fn move_refuses_into_self_and_conflicts() {
1412 let t = T::new();
1413 let root = t.root.canonicalize().unwrap();
1414 // A dir cannot be moved into itself or a descendant.
1415 assert!(matches!(
1416 move_item(&root, ".", "docs", ".", "docs", false),
1417 Err(FsError::Invalid(_))
1418 ));
1419 assert!(matches!(
1420 move_item(&root, ".", "docs", ".", "docs/inner", false),
1421 Err(FsError::Invalid(_))
1422 ));
1423 // A dir target always conflicts, even with overwrite: move the file
1424 // "x" into a folder that already contains a subfolder "x".
1425 std::fs::create_dir_all(root.join("mv/case/x")).unwrap();
1426 std::fs::create_dir_all(root.join("mv/out")).unwrap();
1427 std::fs::write(root.join("mv/out/x"), "a file named x").unwrap();
1428 assert!(matches!(
1429 move_item(&root, ".", "mv/out/x", ".", "mv/case", true),
1430 Err(FsError::Conflict)
1431 ));
1432 // File onto file: conflict without overwrite, replaced with.
1433 std::fs::write(root.join("tmp-x.txt"), "x").unwrap();
1434 std::fs::write(root.join("tmp-y.txt"), "y").unwrap();
1435 std::fs::rename(root.join("tmp-x.txt"), root.join("tmp-target.txt")).unwrap();
1436 std::fs::rename(root.join("tmp-y.txt"), root.join("tmp-target2.txt")).unwrap();
1437 // Two distinct files with the same name in one folder.
1438 std::fs::create_dir_all(root.join("mv/dst")).unwrap();
1439 std::fs::create_dir_all(root.join("mv/out2")).unwrap();
1440 std::fs::write(root.join("mv/dst/dup.txt"), "old").unwrap();
1441 std::fs::write(root.join("mv/out2/dup.txt"), "new").unwrap();
1442 assert!(matches!(
1443 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", false),
1444 Err(FsError::Conflict)
1445 ));
1446 move_item(&root, ".", "mv/out2/dup.txt", ".", "mv/dst", true).unwrap();
1447 assert_eq!(
1448 std::fs::read_to_string(root.join("mv/dst/dup.txt")).unwrap(),
1449 "new"
1450 );
1451 // Moving onto itself is a no-op success.
1452 move_item(&root, ".", "tmp-target.txt", ".", ".", false).unwrap();
1453 assert!(root.join("tmp-target.txt").exists());
1454 // Missing destination dir.
1455 assert!(matches!(
1456 move_item(&root, ".", "file.txt", ".", "nope", false),
1457 Err(FsError::NotFound)
1458 ));
1459 }
1460
1461 #[test]
1462 fn copy_file_and_dir_preserves_mtime() {
1463 let t = T::new();
1464 let root = t.root.canonicalize().unwrap();
1465 let before = mtime_of(&root.join("file.txt"));
1466 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1467 let copy = root.join("src/file.txt");
1468 assert_eq!(std::fs::read(&copy).unwrap(), b"top file");
1469 assert_eq!(mtime_of(&copy), before);
1470 // Dir copy.
1471 copy_item(&root, ".", "docs", ".", "src", false).unwrap();
1472 assert_eq!(
1473 std::fs::read_to_string(root.join("src/docs/inner/hello.txt")).unwrap(),
1474 "hello"
1475 );
1476 // Originals still there.
1477 assert!(root.join("file.txt").exists());
1478 assert!(root.join("docs/a.txt").exists());
1479 }
1480
1481 #[test]
1482 fn copy_refuses_into_self_and_handles_conflict() {
1483 let t = T::new();
1484 let root = t.root.canonicalize().unwrap();
1485 assert!(matches!(
1486 copy_item(&root, ".", "docs", ".", "docs", false),
1487 Err(FsError::Invalid(_))
1488 ));
1489 assert!(matches!(
1490 copy_item(&root, ".", "docs", ".", "docs/inner", false),
1491 Err(FsError::Invalid(_))
1492 ));
1493 // First copy is fine, the second one conflicts, overwrite replaces.
1494 copy_item(&root, ".", "file.txt", ".", "src", false).unwrap();
1495 assert!(matches!(
1496 copy_item(&root, ".", "file.txt", ".", "src", false),
1497 Err(FsError::Conflict)
1498 ));
1499 std::fs::write(root.join("file.txt"), "v2").unwrap();
1500 copy_item(&root, ".", "file.txt", ".", "src", true).unwrap();
1501 assert_eq!(
1502 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1503 "v2"
1504 );
1505 // Copying onto itself is a no-op success.
1506 copy_item(&root, ".", "src/file.txt", ".", "src", false).unwrap();
1507 assert_eq!(
1508 std::fs::read_to_string(root.join("src/file.txt")).unwrap(),
1509 "v2"
1510 );
1511 // Missing destination dir.
1512 assert!(matches!(
1513 copy_item(&root, ".", "file.txt", ".", "nope", false),
1514 Err(FsError::NotFound)
1515 ));
1516 }
1517
1518 #[test]
1519 fn copy_recursive_missing_source() {
1520 let t = T::new();
1521 let dst = t.tmp.path().join("dst");
1522 assert!(matches!(
1523 copy_recursive(&t.root.join("nope"), &dst),
1524 Err(FsError::NotFound)
1525 ));
1526 }
1527
1528 // ---------- is_within_or_eq ----------
1529
1530 #[test]
1531 fn is_within_or_eq_matrix() {
1532 let t = T::new();
1533 let root = t.root.canonicalize().unwrap();
1534 let docs = root.join("docs");
1535 assert!(is_within_or_eq(&docs, &docs));
1536 assert!(is_within_or_eq(&docs, &root.join("docs/inner")));
1537 assert!(!is_within_or_eq(&docs, &root));
1538 assert!(!is_within_or_eq(&docs, &root.join("src")));
1539 }
1540
1541 // ---------- content sniffing ----------
1542
1543 fn kind(bytes: &[u8], name: &str) -> FileKind {
1544 kind_from_bytes(bytes, Path::new(name))
1545 }
1546
1547 #[test]
1548 fn magic_numbers_classify_by_content() {
1549 let png = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A, 0, 0, 0, 0];
1550 // The name is a lie in every case: the bytes decide.
1551 assert_eq!(kind(&png, "notes.txt"), FileKind::Image);
1552 assert_eq!(kind(b"%PDF-1.7\n%aaa\n", "x.bin"), FileKind::Pdf);
1553 assert_eq!(
1554 kind(b"PK\x03\x04\x14\x00\x00\x00", "x.png"),
1555 FileKind::Archive
1556 );
1557 assert_eq!(
1558 kind(&[0x1F, 0x8B, 0x08, 0, 0, 0, 0, 0], "x"),
1559 FileKind::Archive
1560 );
1561 assert_eq!(
1562 kind(
1563 &[
1564 0, 0, 0, 0x20, b'f', b't', b'y', b'p', b'i', b's', b'o', b'm'
1565 ],
1566 "x"
1567 ),
1568 FileKind::Video
1569 );
1570 assert_eq!(
1571 kind(b"ID3\x04\x00\x00\x00\x00\x00\x00", "x"),
1572 FileKind::Audio
1573 );
1574 assert_eq!(kind(b"RIFF\x24\x00\x00\x00WAVEfmt ", "x"), FileKind::Audio);
1575 assert_eq!(kind(b"<!doctype html><p>hi", "x"), FileKind::Text);
1576 // Recognized but not viewable in a browser.
1577 assert_eq!(
1578 kind(&[0x00, 0x61, 0x73, 0x6d, 1, 0, 0, 0], "x.wasm"),
1579 FileKind::Binary
1580 );
1581 }
1582
1583 #[test]
1584 fn unsigned_files_fall_back_to_the_text_heuristic() {
1585 // No magic number: plain text, source, config.
1586 assert_eq!(kind(b"hello world\n", "notes"), FileKind::Text);
1587 assert_eq!(kind(b"fn main() {}\n", "main.rs"), FileKind::Text);
1588 assert_eq!(
1589 kind("# über\nkey: wert\n".as_bytes(), "c.yaml"),
1590 FileKind::Text
1591 );
1592 // Extensionless text files work, which the old extension list missed.
1593 assert_eq!(kind(b"all:\n\tcargo build\n", "Makefile"), FileKind::Text);
1594 // Empty file → editable.
1595 assert_eq!(kind(b"", "new.txt"), FileKind::Text);
1596 // A NUL byte means binary, whatever the name says. (ELF has no
1597 // `infer` signature, so this is the path that catches it.)
1598 assert_eq!(
1599 kind(&[0x7F, b'E', b'L', b'F', 2, 1, 1, 0, 0], "run.txt"),
1600 FileKind::Binary
1601 );
1602 assert_eq!(kind(&[0xC3, 0x28, 0xFF, 0xFE], "x.txt"), FileKind::Binary);
1603 }
1604
1605 #[test]
1606 fn svg_is_offered_as_an_image() {
1607 // SVG is XML text with no magic number, but browsers draw it, so the
1608 // extension is the only signal available.
1609 let svg = b"<svg xmlns=\"http://www.w3.org/2000/svg\"></svg>";
1610 assert_eq!(kind(svg, "logo.svg"), FileKind::Image);
1611 assert_eq!(kind(svg, "logo.txt"), FileKind::Text);
1612 }
1613
1614 #[test]
1615 fn truncated_utf8_at_the_read_boundary_is_still_text() {
1616 // 255 ASCII bytes plus the first byte of a 2-byte character: the read
1617 // cut a character in half, which must not read as binary.
1618 let mut b = vec![b'a'; SNIFF_BYTES - 1];
1619 b.push(0xC3);
1620 assert_eq!(kind(&b, "x.txt"), FileKind::Text);
1621 }
1622
1623 #[test]
1624 fn detect_kind_reads_from_disk() {
1625 let t = T::new();
1626 assert_eq!(detect_kind(&t.root.join("docs"), true), FileKind::Dir);
1627 assert_eq!(detect_kind(&t.root.join("file.txt"), false), FileKind::Text);
1628 // Unreadable / missing → Binary, never a failed listing.
1629 assert_eq!(detect_kind(&t.root.join("nope"), false), FileKind::Binary);
1630 }
1631
1632 /// `SNIFF_BUDGET` is process-wide, so the two tests that assert on it must
1633 /// not run at the same time as each other.
1634 static BUDGET_TESTS: std::sync::Mutex<()> = std::sync::Mutex::new(());
1635
1636 /// A directory big enough to take the fan-out path must produce exactly
1637 /// what the serial path would. Pass 2 fills `is_dir`, `size`, `mtime` and
1638 /// `kind`, all on worker threads, so a chunk-boundary mistake would show up
1639 /// as a row carrying another row's metadata or the untouched placeholders.
1640 #[test]
1641 fn parallel_rows_match_serial() {
1642 use std::sync::atomic::Ordering;
1643 let _guard = BUDGET_TESTS.lock().unwrap();
1644 let t = T::new();
1645 let big = t.root.join("big");
1646 std::fs::create_dir_all(&big).unwrap();
1647 // Well over SNIFF_CHUNK, so several chunks are handed out.
1648 let n = SNIFF_CHUNK * 3 + 7;
1649 for i in 0..n {
1650 let p = big.join(format!("f{i:05}"));
1651 // Every file gets a distinct length, so `size` pins the row identity.
1652 let pad = vec![b'A'; i];
1653 let mut body = match i % 3 {
1654 0 => vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1655 1 => b"plain text\n".to_vec(),
1656 _ => vec![0u8, 1, 2, 3],
1657 };
1658 body.extend_from_slice(&pad);
1659 std::fs::write(&p, &body).unwrap();
1660 }
1661 std::fs::create_dir(big.join("a-subdir")).unwrap();
1662
1663 let entries = list_dir(&big, ListOpts::default()).unwrap().entries;
1664 assert_eq!(entries.len(), n + 1);
1665
1666 // Every row must agree with what a single-threaded read of that same
1667 // file reports: kind, size and directory flag.
1668 for e in &entries {
1669 let p = big.join(&e.name);
1670 let m = std::fs::metadata(&p).unwrap();
1671 assert_eq!(e.is_dir, m.is_dir(), "{}", e.name);
1672 assert_eq!(e.size, m.len(), "size mismatch on {}", e.name);
1673 assert_eq!(e.mtime, mtime_str(&m), "mtime mismatch on {}", e.name);
1674 assert_eq!(
1675 e.kind,
1676 detect_kind(&p, e.is_dir),
1677 "kind mismatch on {}",
1678 e.name
1679 );
1680 }
1681
1682 // Sanity: several kinds are actually present, so the loop above is not
1683 // trivially true, and the directory sorts first.
1684 let kinds: Vec<FileKind> = entries.iter().map(|e| e.kind).collect();
1685 assert!(kinds.contains(&FileKind::Image));
1686 assert!(kinds.contains(&FileKind::Text));
1687 assert!(kinds.contains(&FileKind::Binary));
1688 assert_eq!(entries[0].name, "a-subdir");
1689 assert_eq!(entries[0].kind, FileKind::Dir);
1690
1691 // The thread budget is fully returned once the listing is done.
1692 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1693 }
1694
1695 #[test]
1696 fn sniff_permit_never_exceeds_the_budget() {
1697 use std::sync::atomic::Ordering;
1698 let _guard = BUDGET_TESTS.lock().unwrap();
1699 let total = sniff_budget_total();
1700 let a = SniffPermit::claim(total * 2);
1701 assert_eq!(a.0, total, "a single claim is capped at the total");
1702 // Nothing left: the next listing runs serially rather than queueing.
1703 let b = SniffPermit::claim(4);
1704 assert_eq!(b.0, 0);
1705 drop(a);
1706 drop(b);
1707 assert_eq!(SNIFF_BUDGET.load(Ordering::Acquire), 0);
1708 }
1709
1710 #[test]
1711 fn list_dir_reports_kinds() {
1712 let t = T::new();
1713 std::fs::write(
1714 t.root.join("docs/pic.dat"),
1715 [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A],
1716 )
1717 .unwrap();
1718 let entries = list_dir(&t.root.join("docs"), ListOpts::default())
1719 .unwrap()
1720 .entries;
1721 let kind_of = |n: &str| entries.iter().find(|e| e.name == n).unwrap().kind;
1722 assert_eq!(kind_of("inner"), FileKind::Dir);
1723 assert_eq!(kind_of("a.txt"), FileKind::Text);
1724 assert_eq!(kind_of("pic.dat"), FileKind::Image);
1725 }
1726}
1727