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