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