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