storage_kit/ns/hostdir.rs
1//! [`HostDir`]: a mount over an operating-system directory, confined with `cap-std`.
2//!
3//! # The confinement model: open once, check the handle, never the path
4//!
5//! `HostDir` holds **one** directory handle, opened once from an ambient path ([`HostDir::open_ambient`]) or handed in
6//! ([`HostDir::from_dir`]). Every later operation walks from that handle one component at a time with
7//! `openat`-style calls that do **not** follow a final symlink (`O_NOFOLLOW`), and `cap-std` independently refuses any
8//! resolution that would leave the root. The host path of the root is never stored, so it cannot be echoed back.
9//!
10//! What that gives, on **Linux and macOS** (both run the test suite in CI):
11//!
12//! - **No symlink is followed, anywhere on the way.** A symlink met as an intermediate directory or as the final entry
13//! is refused with `Escapes`, whether it points outside the root or inside it. The check is the atomic `open`
14//! itself, not a `lstat` beforehand, so swapping a symlink in between a check and a use does not help an attacker:
15//! the worst outcome is an error. (`lstat` is used only afterwards, to choose the *error kind*.)
16//! - **Only regular files and directories are ever opened.** A FIFO, socket or device is classified with `lstat`
17//! first and never opened (opening a FIFO can block forever), and the opened handle's `fstat` is checked again. Where
18//! the non-blocking flag (`O_NONBLOCK`) is known (Linux on x86, x86-64, arm, aarch64, riscv, loongarch64, s390x and
19//! powerpc, and macOS, iOS and the BSDs) the open is also non-blocking, so a hostile swap to a FIFO between the two
20//! steps cannot hang a read. On any other Unix target the flag is 0, the open is a plain one, and such a swap can
21//! hang that one read (a denial of service of one call, not a confinement problem).
22//! - **`Replace` of a file with more than one hard link is refused** (`HardLinked`). `Remove` and `RenameWithinMount` act
23//! on the *name*, not on the contents, and are allowed on such a file. No operation opens an existing file for
24//! writing (the only write-open is the exclusive create of a new file, and `Replace` renames a new file over the
25//! name), so the contents of a file reachable by another name are never changed. The `Replace` refusal is therefore a
26//! *belt*: without it, another name for the same inode would keep the old content anyway. It is kept for the day an
27//! in-place write (`append`, `at_offset`) exists, when it becomes the thing that stops a write through one name from
28//! changing a file reachable by another. **Reads are not refused**: a file with more than one link is read like any
29//! other (see "What it does not guarantee" below).
30//! - **Names are checked against the portable grammar** and creating a name that case-folds to an existing sibling is
31//! refused (`CaseCollision`) even on a case-sensitive volume. The decision is made on a **listing of the directory**,
32//! comparing the names as stored: an exact match is `AlreadyExists`, a match that differs only by case or by Unicode
33//! normalisation form is `CaseCollision`. `lstat` is never used for it, because on a case-insensitive volume (the
34//! macOS and Windows default) `lstat` answers "exists" to any spelling. Costs one directory listing per create,
35//! replace and rename. A rename that only respells its own entry (`a` to `A`) is allowed; a rename onto itself is not.
36//! Entries whose names are outside the grammar are not listed, so they cannot be named.
37//! - Files are created `0600` and directories `0700`.
38//!
39//! # What it does not guarantee (read before relying on it)
40//!
41//! - **The root itself.** `open_ambient` follows whatever the OS resolves the given path to, including a symlink in
42//! its last component. Which host directories may be mounted is the embedder's policy and the embedder's resolver;
43//! the Kit confines to the root it is given and has no opinion on whether that root was a good choice. Pass a
44//! canonical path.
45//! - **Version checks are best effort.** `if_version` on `HostDir` is check-then-act ([`Caps::exact_if_version`] is
46//! `false`): another process can change the file between the check and the rename. A stale version is caught when
47//! the change happened before the check; a change *during* the window is not. A version is the file's mtime, size,
48//! inode (file index on Windows) and device, so it also misses an edit **in place that keeps the size and lands in the
49//! same timestamp tick as the previous write**, on every platform (the tick is the clock granularity of the kernel and
50//! filesystem: coarse on Windows, on the order of 10 ms; it can also be several milliseconds on Unix). A replaced
51//! file (a new inode) is *normally* told apart, but not always: two replaces in a row can reuse a freed inode number,
52//! and with the same size and the same tick the versions are equal. An in-place rewrite of the same length right
53//! after the last write may not be told apart either.
54//! Do not build on a version to detect a same-size, same-instant edit.
55//! - **`RenameWithinMount`'s "destination must not exist"** is likewise a check followed by a rename, and the rename
56//! replaces a destination that appeared in the window.
57//! - **Rights of whoever else can write the directory.** A process that can already write inside the root can cause
58//! `Io` errors and denial of service (for example by filling the disk), and can race the best-effort checks above.
59//! It cannot make the Kit *write* outside the root, and no path or symlink it creates lets a read leave the root. It
60//! *can* hard-link a file from elsewhere on the same filesystem into the root (see the hard-link bullet below), and
61//! the namespace then serves that file's contents on a read. It *can* (it is the same user, or has write access)
62//! rename or replace a directory, including one the Kit holds a handle to or one a mount point hangs from, so what a
63//! path names can change between two calls, and a rename of the mount's own root directory by someone outside the
64//! Kit leaves the held handle pointing at the moved directory. The renames give them nothing they did not already have,
65//! but the Kit does not defend against them: confinement is "never outside the handle it holds", not "the directory stays
66//! where it was".
67//! - **Polling watch** sees a change only on the poll after it happens, and fingerprints `(name, kind, len, mtime,
68//! inode)`: two in-place writes of the same length inside one filesystem timestamp tick can be missed. A watched
69//! tree is held in memory, bounded by [`WatchOpts::max_tracked`](super::WatchOpts::max_tracked) (a bigger tree is
70//! refused at the start, and degrades to a single `rescan` if it grows past it). A recursive scan walks depth first and
71//! opens each subdirectory from its parent's handle (so a scan costs one open per directory, not one per directory per
72//! level), holding one handle per level on the way down: at most [`WatchOpts::max_depth`](super::WatchOpts::max_depth)
73//! plus one (default 64) however wide the tree is. A tree deeper than that is an incomplete scan, handled like
74//! `max_tracked`: refused at the start, one `rescan` if it grows past it. A scan that cannot finish (depth, entries,
75//! descriptors, I/O error) is reported as one `rescan`, not compared as a partial picture.
76//! - **Hard links are refused by `Replace`, not by `read`.** `Replace` checks the link count of the file it would change
77//! and refuses if it is above 1, but only at the moment of the call. `read` and `stat` do **not** refuse a file with
78//! more than one link. A process that can write inside the root can hard-link a file from elsewhere on the same
79//! filesystem into it, and a read through the namespace then returns that file's contents. No `..`, symlink or
80//! other path leaves the root, so this is not a path escape; but it is not confinement of the *data*. Whether the
81//! linking process needs read access to the target depends on the OS. Linux restricts it when `fs.protected_hardlinks`
82//! is on (the default on most distributions): the linker must then own the file or have both read and write access
83//! to it. macOS has no such protection. Windows has its own rules for creating a hard link, and that path is untested
84//! here. Where it is not restricted, a less-privileged writer of the directory can make the Kit, running with more
85//! privilege, serve a file that user could not read itself. [`Stat::links`](super::Stat::links) reports the count, but
86//! there is **no race-free check** through this API: `stat` looks at the name and `read` opens the name again, so a
87//! link can be swapped or added in between (comparing the [`Version`] that `read` returns with the one
88//! from `stat` catches a swapped-in different file, not a link added to the same one). The dependable defence is not
89//! to mount a directory that less-privileged users can write.
90//! - **Access is the mount's, not the directory's.** `HostDir` itself is always writable; whether a mount may write is
91//! the grant the [`Namespace`](super::Namespace) holds ([`Access`](super::Access)), enforced per mount. Two mounts
92//! over directories that overlap share files: a write through a `ReadWrite` mount of `D` changes what a `ReadOnly`
93//! mount of `D/locked` (or of `D` itself) reads, and so does any other process. The embedder chooses the directories
94//! and must keep them disjoint. [`Backend::root_identity`] lets `build()` refuse the same directory mounted twice
95//! (device and inode of the root handle); it **cannot** see an ancestor and a descendant, because the Kit keeps no
96//! host path to compare.
97//! - **A recursive watch stops at another filesystem (Unix).** Reads, writes and `walk` through a mount are not
98//! confined to the root's device: a filesystem mounted *inside* the directory is reachable like any subdirectory. The
99//! polling scan is different, by choice. A directory on a different device than the watched one (found by comparing
100//! `st_dev` on the opened handle) is listed as an entry, so a mount appearing or disappearing at that name is
101//! reported as a change to it, but it is **not entered**: nothing beneath it is tracked or reported. Descending into
102//! it would make the scan's cost and memory depend on a filesystem the embedder did not mean to watch (a network or
103//! pseudo filesystem), and its tree can change without the root's mtime moving. A bind mount of the same filesystem
104//! has the same device and is followed like a directory. Windows does not check this (a volume mount point is a
105//! reparse point, refused as far as `std` reports it as a symlink).
106//!
107//! ## Windows is the weakest platform, and says so
108//!
109//! It compiles, and it is as strict as `cap-std` and `std` allow, but [`Caps::strict_confinement`] is `false` there and
110//! the following are **not** guaranteed:
111//!
112//! - **Hard links and file identity** come from the by-handle information `cap-std` reads when it opens a file to stat it
113//! (volume serial number, file index, link count), so the hard-link refusal and the identity part of versions should work.
114//! This is the least-tested path: the hard-link and identity code is compiled on the Windows CI leg, but no test
115//! creates a hard link on Windows, so the `Replace` refusal there has not been exercised; the cheap directory-entry
116//! metadata the watch scan uses carries no identity, so on Windows a polling watch cannot see an atomic replace that
117//! keeps the same size and timestamp.
118//! - **Alternate data streams** (`name:stream`): `:` is refused in names, which blocks naming one through this API, but
119//! a stream already on a file is not detected.
120//! - **Case-insensitive volumes**: the default NTFS volume is case-insensitive; collisions are still refused by the
121//! grammar, but the volume itself will treat `A` and `a` as one name.
122//! - **Reparse points**: symlinks and junctions are refused as far as `std` classifies them as symlinks; other reparse
123//! kinds (cloud placeholders, dedup) are not distinguished.
124//! - **Versions** are mtime, size, file index and volume serial number. File timestamps tick coarsely (on the order of
125//! 10 ms), so an edit in place that keeps the size and lands in the same tick as the previous one is not told apart;
126//! a replaced *file* (new file index) is. Ownership and mode are not reported. **A matching version can be wrong on
127//! some volumes**, which is why `if_version` is best effort ([`Caps::exact_if_version`] is `false`): **FAT** reuses file
128//! indexes (they come from where the directory entry sits, so a new file can inherit a deleted one's) and stores
129//! timestamps to 2 seconds; **ReFS** file ids are 128 bits and the file index is 64, so two files can share an index.
130//! On those a replaced file of the same size can compare equal and a stale `if_version` be accepted. Directory `fsync` is not available, so
131//! `Replace` is atomic but its durability across a power loss is the OS's.
132//!
133//! Treat a Windows `HostDir` as "no escape through a path, no more".
134
135use std::io::{self, Read, Write};
136use std::path::Path;
137use std::sync::atomic::{AtomicU64, Ordering};
138use std::time::{SystemTime, UNIX_EPOCH};
139
140use cap_fs_ext::{DirExt, FollowSymlinks, OpenOptionsFollowExt};
141use cap_std::ambient_authority;
142use cap_std::fs::{Dir, DirBuilder, File, Metadata, OpenOptions};
143
144use super::backend::{Backend, Caps, Entry, Kind, Stat, Version, WatchKind, WriteOp};
145use super::error::{InputReason, NsError, NsErrorKind, NsResult};
146use super::path::{case_fold_key, validate_name, NsPath, TEMP_PREFIX};
147use super::watch::{spawn_poller, Fingerprint, ScanOutcome, Snapshot, Watch, WatchOpts};
148
149#[cfg(unix)]
150use cap_std::fs::{DirBuilderExt, OpenOptionsExt};
151
152/// `O_NONBLOCK`, so opening a FIFO that was swapped in after the `lstat` cannot hang. Spelled out because the crate
153/// takes no `libc` dependency; only targets whose value is certain are listed, the rest get 0 (no flag), which leaves
154/// that one swap race as a hang of a single read rather than a confinement problem.
155#[cfg(all(
156 target_os = "linux",
157 any(
158 target_arch = "x86",
159 target_arch = "x86_64",
160 target_arch = "arm",
161 target_arch = "aarch64",
162 target_arch = "riscv32",
163 target_arch = "riscv64",
164 target_arch = "loongarch64",
165 target_arch = "s390x",
166 target_arch = "powerpc",
167 target_arch = "powerpc64"
168 )
169))]
170const O_NONBLOCK: i32 = 0o4000;
171#[cfg(any(
172 target_os = "macos",
173 target_os = "ios",
174 target_os = "freebsd",
175 target_os = "openbsd",
176 target_os = "netbsd",
177 target_os = "dragonfly"
178))]
179const O_NONBLOCK: i32 = 0x4;
180#[cfg(all(
181 unix,
182 not(any(
183 all(
184 target_os = "linux",
185 any(
186 target_arch = "x86",
187 target_arch = "x86_64",
188 target_arch = "arm",
189 target_arch = "aarch64",
190 target_arch = "riscv32",
191 target_arch = "riscv64",
192 target_arch = "loongarch64",
193 target_arch = "s390x",
194 target_arch = "powerpc",
195 target_arch = "powerpc64"
196 )
197 ),
198 target_os = "macos",
199 target_os = "ios",
200 target_os = "freebsd",
201 target_os = "openbsd",
202 target_os = "netbsd",
203 target_os = "dragonfly"
204 ))
205))]
206const O_NONBLOCK: i32 = 0;
207
208/// Per-platform facts about a file that `std` exposes on Unix only (on stable Rust).
209///
210/// Every accessor here is total: where the platform cannot say, it answers `None` rather than panicking.
211#[cfg(unix)]
212mod sys {
213 use cap_std::fs::{Dir, Metadata, MetadataExt};
214
215 /// `(device, inode)`: what makes two handles "the same file" on this platform.
216 pub fn identity(md: &Metadata) -> Option<(u64, u64)> {
217 Some((md.dev(), md.ino()))
218 }
219 pub fn links(md: &Metadata) -> Option<u64> {
220 Some(md.nlink())
221 }
222 pub fn owner(md: &Metadata) -> Option<u32> {
223 Some(md.uid())
224 }
225 pub fn mode(md: &Metadata) -> Option<u32> {
226 Some(md.mode() & 0o7777)
227 }
228 pub fn scan_inode(md: &Metadata) -> u64 {
229 md.ino()
230 }
231 /// The device (filesystem) an open directory lives on; the recursive scan stops where it changes.
232 pub fn device_of(dir: &Dir) -> Option<u64> {
233 dir.dir_metadata().ok().map(|md| md.dev())
234 }
235}
236
237/// Windows: file identity and link count are the by-handle information `cap-std` reads when it opens a file to stat it
238/// (volume serial number, file index, link count). A `Metadata` that did **not** come from an open handle (the cheap
239/// `DirEntry::metadata` the watch scan uses) does not carry it. `cap-fs-ext`'s `MetadataExt` accessors `expect()` it and
240/// panic on such metadata, so they are not used: these go through the `Option` accessors, and "not there" is `None`.
241/// A later change that hands the wrong kind of metadata to any of them gets a missing identity, not a crash.
242#[cfg(not(unix))]
243mod sys {
244 use cap_primitives::fs::_WindowsByHandle;
245 use cap_std::fs::{Dir, Metadata};
246
247 /// `(volume serial number, file index)`. The file index is 64 bits: on `ReFS`, whose file ids are 128 bits, it is a
248 /// truncation and may not be unique (see the module docs).
249 pub fn identity(md: &Metadata) -> Option<(u64, u64)> {
250 Some((u64::from(md.volume_serial_number()?), md.file_index()?))
251 }
252 pub fn links(md: &Metadata) -> Option<u64> {
253 md.number_of_links().map(u64::from)
254 }
255 pub fn owner(_: &Metadata) -> Option<u32> {
256 None
257 }
258 pub fn mode(_: &Metadata) -> Option<u32> {
259 None
260 }
261 /// For metadata that may not carry by-handle information (a directory entry's): no identity on Windows.
262 pub fn scan_inode(_: &Metadata) -> u64 {
263 0
264 }
265 /// No device boundary is checked on Windows (see the module docs).
266 pub fn device_of(_: &Dir) -> Option<u64> {
267 None
268 }
269}
270
271/// A mount over an OS directory. See the [module docs](self) for the guarantees and, as important, the limits.
272///
273/// ```no_run
274/// # #[cfg(feature = "ns")] {
275/// use storage_kit::ns::{Backend, HostDir, NsPath, WriteOp};
276/// let dir = HostDir::open_ambient("/home/me/.config/myapp")?;
277/// let path = NsPath::parse("/apps.toml")?;
278/// let v = dir.write(&path, WriteOp::Replace, b"x = 1\n", None)?;
279/// let (bytes, _) = dir.read(&path, 1 << 20)?;
280/// assert_eq!(bytes, b"x = 1\n");
281/// # let _ = v;
282/// # }
283/// # Ok::<(), storage_kit::ns::NsError>(())
284/// ```
285pub struct HostDir {
286 root: Dir,
287 caps: Caps,
288 /// `(device, inode)` of the root, read from the handle when it was opened. See [`Backend::root_identity`].
289 identity: Option<(u64, u64)>,
290}
291
292impl std::fmt::Debug for HostDir {
293 // The root's host path is not stored; the capabilities are all there is to show.
294 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
295 f.debug_struct("HostDir").field("caps", &self.caps).finish()
296 }
297}
298
299impl HostDir {
300 /// Open `path` as the root. This is the **one** ambient (path-based) open; everything afterwards is relative to the
301 /// resulting handle. See the module docs: the OS resolves `path` as it likes (including a final symlink), so the
302 /// embedder must give a path it has already decided to trust.
303 pub fn open_ambient(path: impl AsRef<Path>) -> NsResult<Self> {
304 let dir = Dir::open_ambient_dir(path.as_ref(), ambient_authority())
305 .map_err(|e| NsError::from_io_nopath(&e))?;
306 Self::checked(dir)
307 }
308
309 /// Use an already-open directory as the root (the embedder opened it, e.g. from a granted handle).
310 pub fn from_dir(dir: Dir) -> NsResult<Self> {
311 Self::checked(dir)
312 }
313
314 fn checked(dir: Dir) -> NsResult<Self> {
315 // Check the handle, not the path it came from.
316 let md = dir
317 .dir_metadata()
318 .map_err(|e| NsError::from_io_nopath(&e))?;
319 if !md.is_dir() {
320 return Err(NsError::new(NsErrorKind::NotADirectory));
321 }
322 let caps = Caps {
323 writable: true,
324 atomic_replace: true,
325 // Best effort, and on Windows weaker than it looks (see "Windows" in the module docs): a file's identity
326 // there is its volume serial number and 64-bit file index, and a match can be wrong. FAT reuses file
327 // indexes (they derive from the directory entry's position) and keeps 2-second timestamps, so a file
328 // replaced by another of the same size can compare equal; ReFS file ids are 128 bits and are truncated to
329 // 64, so two files can share an index.
330 exact_if_version: false,
331 watch: WatchKind::Polling,
332 owner_mode: cfg!(unix),
333 case_sensitive: probe_case_sensitive(&dir),
334 strict_confinement: cfg!(unix),
335 };
336 let identity = sys::identity(&md);
337 Ok(HostDir {
338 root: dir,
339 caps,
340 identity,
341 })
342 }
343}
344
345/// Is the volume under `root` case-sensitive? Looks for an existing entry with a letter in its name and asks for the
346/// same entry under swapped case; falls back to the platform's usual default when there is nothing to learn from.
347fn probe_case_sensitive(root: &Dir) -> bool {
348 let default = cfg!(target_os = "linux");
349 let Ok(entries) = root.entries() else {
350 return default;
351 };
352 for entry in entries.flatten().take(64) {
353 let name = entry.file_name();
354 let Some(name) = name.to_str() else { continue };
355 let swapped: String = name
356 .chars()
357 .map(|c| {
358 if c.is_lowercase() {
359 c.to_uppercase().next().unwrap_or(c)
360 } else if c.is_uppercase() {
361 c.to_lowercase().next().unwrap_or(c)
362 } else {
363 c
364 }
365 })
366 .collect();
367 if swapped == name {
368 continue;
369 }
370 let Ok(original) = root.symlink_metadata(name) else {
371 continue;
372 };
373 return match root.symlink_metadata(&swapped) {
374 // The swapped name resolves to the very same entry: case-insensitive.
375 Ok(other) => match (sys::identity(&other), sys::identity(&original)) {
376 (Some(a), Some(b)) => a != b,
377 // No identity to compare: this entry cannot tell, try another.
378 _ => continue,
379 },
380 Err(e) if e.kind() == io::ErrorKind::NotFound => true,
381 Err(_) => continue,
382 };
383 }
384 default
385}
386
387// ---------------------------------------------------------------------------------------------------------------
388// Resolution: walk from the root handle, never from a path string.
389// ---------------------------------------------------------------------------------------------------------------
390
391/// What the caller wanted at the end of a resolution; only used to pick an error kind after a failure.
392#[derive(Clone, Copy, PartialEq, Eq)]
393enum Want {
394 Dir,
395 File,
396}
397
398/// Turn a failed no-follow open into the most useful error kind. This runs *after* the security decision (the open
399/// already refused), so a race here can only change which error is reported, never what was opened.
400fn explain_open_failure(
401 parent: &Dir,
402 name: &str,
403 err: &io::Error,
404 path: &NsPath,
405 want: Want,
406) -> NsError {
407 match parent.symlink_metadata(name) {
408 Ok(md) => {
409 let ft = md.file_type();
410 if ft.is_symlink() {
411 NsError::at(NsErrorKind::Escapes, path)
412 } else if ft.is_dir() {
413 match want {
414 Want::Dir => NsError::from_io(err, path),
415 Want::File => NsError::at(NsErrorKind::IsADirectory, path),
416 }
417 } else if ft.is_file() {
418 match want {
419 Want::Dir => NsError::at(NsErrorKind::NotADirectory, path),
420 Want::File => NsError::from_io(err, path),
421 }
422 } else {
423 NsError::at(NsErrorKind::NotRegular, path)
424 }
425 }
426 Err(_) => NsError::from_io(err, path),
427 }
428}
429
430/// Open the directory at `path` by walking every component with no-follow opens.
431fn open_dir_at(root: &Dir, path: &NsPath) -> NsResult<Dir> {
432 let mut current = root.try_clone().map_err(|e| NsError::from_io(&e, path))?;
433 for name in path.components() {
434 let next = match current.open_dir_nofollow(name) {
435 Ok(d) => d,
436 Err(e) => return Err(explain_open_failure(¤t, name, &e, path, Want::Dir)),
437 };
438 current = next;
439 }
440 Ok(current)
441}
442
443/// Are these two open handles the same directory? Unknown (no identity on this platform) is "no": the callers treat a
444/// different directory as the stricter case.
445fn same_directory(a: &Dir, b: &Dir) -> bool {
446 match (a.dir_metadata(), b.dir_metadata()) {
447 (Ok(x), Ok(y)) => match (sys::identity(&x), sys::identity(&y)) {
448 (Some(x), Some(y)) => x == y,
449 _ => false,
450 },
451 _ => false,
452 }
453}
454
455/// The parent directory handle and final name of `path`. The root has no parent: callers handle it first.
456fn open_parent<'p>(root: &Dir, path: &'p NsPath) -> NsResult<(Dir, &'p str)> {
457 let name = path
458 .file_name()
459 .ok_or_else(|| NsError::at(NsErrorKind::InvalidInput(InputReason::MountRoot), path))?;
460 let parent = path.parent().unwrap_or_else(NsPath::root);
461 Ok((open_dir_at(root, &parent)?, name))
462}
463
464/// Classify what `lstat` found. Symlinks are `Escapes`, anything but a file or directory is `NotRegular`.
465fn kind_of(md: &Metadata, path: &NsPath) -> NsResult<Kind> {
466 let ft = md.file_type();
467 if ft.is_symlink() {
468 Err(NsError::at(NsErrorKind::Escapes, path))
469 } else if ft.is_dir() {
470 Ok(Kind::Dir)
471 } else if ft.is_file() {
472 Ok(Kind::File)
473 } else {
474 Err(NsError::at(NsErrorKind::NotRegular, path))
475 }
476}
477
478/// `lstat` the final component. `Ok(None)` if absent.
479fn lookup(parent: &Dir, name: &str, path: &NsPath) -> NsResult<Option<(Kind, Metadata)>> {
480 match parent.symlink_metadata(name) {
481 Ok(md) => Ok(Some((kind_of(&md, path)?, md))),
482 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(None),
483 Err(e) => Err(NsError::from_io(&e, path)),
484 }
485}
486
487/// Does *anything* exist under this name (a symlink or FIFO counts)?
488fn exists_raw(parent: &Dir, name: &str, path: &NsPath) -> NsResult<bool> {
489 match parent.symlink_metadata(name) {
490 Ok(_) => Ok(true),
491 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
492 Err(e) => Err(NsError::from_io(&e, path)),
493 }
494}
495
496/// Open a regular file for reading, atomically refusing a symlink, and check the handle afterwards.
497fn open_regular(parent: &Dir, name: &str, path: &NsPath) -> NsResult<(File, Metadata)> {
498 // Classify first (cheap, and keeps a FIFO from ever being opened) ...
499 match lookup(parent, name, path)? {
500 None => return Err(NsError::at(NsErrorKind::NotFound, path)),
501 Some((Kind::Dir, _)) => return Err(NsError::at(NsErrorKind::IsADirectory, path)),
502 Some((Kind::File, _)) => {}
503 }
504 // ... then the open that actually decides, atomic and non-following ...
505 let mut opts = OpenOptions::new();
506 opts.read(true).follow(FollowSymlinks::No);
507 #[cfg(unix)]
508 opts.custom_flags(O_NONBLOCK);
509 let file = parent
510 .open_with(name, &opts)
511 .map_err(|e| explain_open_failure(parent, name, &e, path, Want::File))?;
512 // ... then check what we actually hold.
513 let md = file.metadata().map_err(|e| NsError::from_io(&e, path))?;
514 if md.is_dir() {
515 return Err(NsError::at(NsErrorKind::IsADirectory, path));
516 }
517 if !md.is_file() {
518 return Err(NsError::at(NsErrorKind::NotRegular, path));
519 }
520 Ok((file, md))
521}
522
523// ---------------------------------------------------------------------------------------------------------------
524// Versions and stats
525// ---------------------------------------------------------------------------------------------------------------
526
527fn mtime_ns(md: &Metadata) -> u128 {
528 md.modified()
529 .ok()
530 .map(|t| t.into_std())
531 .and_then(|t| t.duration_since(UNIX_EPOCH).ok())
532 .map_or(0, |d| d.as_nanos())
533}
534
535fn version_of(md: &Metadata) -> Version {
536 let mut bytes = Vec::with_capacity(2 + 16 + 24);
537 bytes.extend_from_slice(b"h1");
538 bytes.extend_from_slice(&mtime_ns(md).to_le_bytes());
539 bytes.extend_from_slice(&md.len().to_le_bytes());
540 // Identity is absent only for metadata that did not come from a handle; it then contributes nothing.
541 let (device, inode) = sys::identity(md).unwrap_or((0, 0));
542 bytes.extend_from_slice(&inode.to_le_bytes());
543 bytes.extend_from_slice(&device.to_le_bytes());
544 Version::from_bytes(&bytes)
545}
546
547fn stat_of(md: &Metadata, kind: Kind) -> Stat {
548 Stat {
549 kind,
550 size: if kind == Kind::File { md.len() } else { 0 },
551 version: version_of(md),
552 owner: sys::owner(md),
553 mode: sys::mode(md),
554 links: sys::links(md),
555 modified: md.modified().ok().map(|t| t.into_std()),
556 }
557}
558
559fn check_version(md: &Metadata, if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
560 match if_version {
561 Some(v) if *v != version_of(md) => Err(NsError::at(NsErrorKind::VersionMismatch, path)),
562 _ => Ok(()),
563 }
564}
565
566fn refuse_hard_linked(md: &Metadata, path: &NsPath) -> NsResult<()> {
567 match sys::links(md) {
568 Some(n) if n > 1 => Err(NsError::at(NsErrorKind::HardLinked, path)),
569 _ => Ok(()),
570 }
571}
572
573fn no_data(data: &[u8], path: &NsPath) -> NsResult<()> {
574 if data.is_empty() {
575 Ok(())
576 } else {
577 Err(NsError::at(
578 NsErrorKind::InvalidInput(InputReason::UnexpectedData),
579 path,
580 ))
581 }
582}
583
584fn no_version(if_version: Option<&Version>, path: &NsPath) -> NsResult<()> {
585 if if_version.is_none() {
586 Ok(())
587 } else {
588 Err(NsError::at(
589 NsErrorKind::InvalidInput(InputReason::VersionOnCreate),
590 path,
591 ))
592 }
593}
594
595// ---------------------------------------------------------------------------------------------------------------
596// Names in a directory
597// ---------------------------------------------------------------------------------------------------------------
598
599enum Conflict {
600 /// A sibling with exactly this name.
601 Same,
602 /// A sibling that differs only by case or normalisation form.
603 Fold,
604}
605
606/// The names in `dir`, as UTF-8 (a name that is not UTF-8 cannot collide with a namespace name). Every kind of entry
607/// counts, symlinks and FIFOs included: they occupy the name.
608///
609/// The collision decision is made on this listing and nowhere else. `lstat` is not used for it: on a case-insensitive
610/// volume (the default on macOS and Windows) it answers "exists" for a differently-cased spelling, which would turn a
611/// `CaseCollision` into an `AlreadyExists`. The listing carries the names as stored, so exact equality and
612/// case-fold equality can be told apart on every platform.
613fn list_names(dir: &Dir, path: &NsPath) -> NsResult<Vec<String>> {
614 let entries = dir.entries().map_err(|e| NsError::from_io(&e, path))?;
615 let mut names = Vec::new();
616 for entry in entries {
617 let entry = entry.map_err(|e| NsError::from_io(&e, path))?;
618 if let Some(name) = entry.file_name().to_str() {
619 names.push(name.to_string());
620 }
621 }
622 Ok(names)
623}
624
625/// Look through `names` for a sibling that is, or folds to, `name`. `ignore` is the stored name of the entry being
626/// renamed (it does not conflict with itself).
627fn conflict_in(names: &[String], name: &str, ignore: Option<&str>) -> Option<Conflict> {
628 let key = case_fold_key(name);
629 let mut fold = false;
630 for existing in names {
631 if Some(existing.as_str()) == ignore {
632 continue;
633 }
634 if existing == name {
635 return Some(Conflict::Same);
636 }
637 if case_fold_key(existing) == key {
638 fold = true;
639 }
640 }
641 fold.then_some(Conflict::Fold)
642}
643
644/// The stored name of the entry that `name` refers to: the exact match if there is one, otherwise the single entry
645/// with the same fold key (a case-insensitive volume answering to a different spelling).
646fn stored_name<'a>(names: &'a [String], name: &str) -> Option<&'a str> {
647 names
648 .iter()
649 .find(|n| n.as_str() == name)
650 .or_else(|| {
651 let key = case_fold_key(name);
652 names.iter().find(|n| case_fold_key(n) == key)
653 })
654 .map(String::as_str)
655}
656
657fn conflict_error(c: Conflict, path: &NsPath) -> NsError {
658 match c {
659 Conflict::Same => NsError::at(NsErrorKind::AlreadyExists, path),
660 Conflict::Fold => NsError::at(NsErrorKind::CaseCollision, path),
661 }
662}
663
664// ---------------------------------------------------------------------------------------------------------------
665// Writing
666// ---------------------------------------------------------------------------------------------------------------
667
668fn sync_dir(dir: &Dir) -> io::Result<()> {
669 #[cfg(unix)]
670 {
671 // Not `Dir::into_std_file`: cap-std opens directory handles with O_PATH where it can, and fsync on an O_PATH
672 // descriptor is EBADF. Re-opening "." relative to the handle gives a descriptor fsync accepts, and cannot leave
673 // the directory.
674 dir.open(".")?.sync_all()
675 }
676 #[cfg(not(unix))]
677 {
678 // Windows cannot open a directory for fsync through std; see the module docs.
679 let _ = dir;
680 Ok(())
681 }
682}
683
684fn temp_name() -> String {
685 static COUNTER: AtomicU64 = AtomicU64::new(0);
686 let n = COUNTER.fetch_add(1, Ordering::Relaxed);
687 let nanos = SystemTime::now()
688 .duration_since(UNIX_EPOCH)
689 .map_or(0, |d| d.subsec_nanos());
690 format!("{TEMP_PREFIX}{:x}-{:x}-{:x}", std::process::id(), n, nanos)
691}
692
693fn create_options() -> OpenOptions {
694 let mut opts = OpenOptions::new();
695 opts.write(true).create_new(true).follow(FollowSymlinks::No);
696 #[cfg(unix)]
697 opts.mode(0o600);
698 opts
699}
700
701/// Create `name` exclusively, fill it, sync it. On any failure the half-written file is removed.
702fn create_filled(parent: &Dir, name: &str, data: &[u8], path: &NsPath) -> NsResult<Metadata> {
703 let mut file = parent
704 .open_with(name, &create_options())
705 .map_err(|e| NsError::from_io(&e, path))?;
706 let result = file
707 .write_all(data)
708 .and_then(|()| file.sync_all())
709 .and_then(|()| file.metadata());
710 match result {
711 Ok(md) => Ok(md),
712 Err(e) => {
713 drop(file);
714 let _ = parent.remove_file(name);
715 Err(NsError::from_io(&e, path))
716 }
717 }
718}
719
720impl HostDir {
721 fn create_exclusive(
722 &self,
723 path: &NsPath,
724 data: &[u8],
725 if_version: Option<&Version>,
726 ) -> NsResult<Version> {
727 no_version(if_version, path)?;
728 let (parent, name) = open_parent(&self.root, path)?;
729 if let Some(c) = conflict_in(&list_names(&parent, path)?, name, None) {
730 return Err(conflict_error(c, path));
731 }
732 // Not in the listing but present anyway (a name the listing could not show): still taken.
733 if exists_raw(&parent, name, path)? {
734 return Err(NsError::at(NsErrorKind::AlreadyExists, path));
735 }
736 let md = create_filled(&parent, name, data, path)?;
737 sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
738 Ok(version_of(&md))
739 }
740
741 fn replace(
742 &self,
743 path: &NsPath,
744 data: &[u8],
745 if_version: Option<&Version>,
746 ) -> NsResult<Version> {
747 let (parent, name) = open_parent(&self.root, path)?;
748 // The listing decides case and normalisation clashes (see `list_names`); an exact match is the file we replace.
749 if let Some(Conflict::Fold) = conflict_in(&list_names(&parent, path)?, name, None) {
750 return Err(NsError::at(NsErrorKind::CaseCollision, path));
751 }
752 match lookup(&parent, name, path)? {
753 Some((Kind::Dir, _)) => return Err(NsError::at(NsErrorKind::IsADirectory, path)),
754 Some((Kind::File, md)) => {
755 refuse_hard_linked(&md, path)?;
756 check_version(&md, if_version, path)?;
757 }
758 None => {
759 if if_version.is_some() {
760 return Err(NsError::at(NsErrorKind::NotFound, path));
761 }
762 }
763 }
764
765 // Temp file in the SAME directory (so the rename cannot cross a filesystem), fsync, rename, fsync the directory.
766 let tmp = temp_name();
767 let md = create_filled(&parent, &tmp, data, path)?;
768 if let Err(e) = parent.rename(&tmp, &parent, name) {
769 let _ = parent.remove_file(&tmp);
770 return Err(NsError::from_io(&e, path));
771 }
772 sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
773 Ok(version_of(&md))
774 }
775
776 fn remove(&self, path: &NsPath, if_version: Option<&Version>) -> NsResult<Version> {
777 let (parent, name) = open_parent(&self.root, path)?;
778 let Some((kind, md)) = lookup(&parent, name, path)? else {
779 return Err(NsError::at(NsErrorKind::NotFound, path));
780 };
781 check_version(&md, if_version, path)?;
782 let result = match kind {
783 Kind::File => parent.remove_file(name),
784 Kind::Dir => parent.remove_dir(name),
785 };
786 result.map_err(|e| NsError::from_io(&e, path))?;
787 sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
788 Ok(version_of(&md))
789 }
790
791 fn rename(
792 &self,
793 from: &NsPath,
794 to: &NsPath,
795 if_version: Option<&Version>,
796 ) -> NsResult<Version> {
797 if to != from && to.starts_with(from) {
798 return Err(NsError::at(
799 NsErrorKind::InvalidInput(InputReason::MoveIntoSelf),
800 to,
801 ));
802 }
803 let (from_dir, from_name) = open_parent(&self.root, from)?;
804 let (to_dir, to_name) = open_parent(&self.root, to)?;
805 let Some((_, md)) = lookup(&from_dir, from_name, from)? else {
806 return Err(NsError::at(NsErrorKind::NotFound, from));
807 };
808 check_version(&md, if_version, from)?;
809 // A rename onto itself is not a no-op: the name is taken. Only a rename that changes the spelling of its own
810 // name (case or normalisation form) may "collide" with the entry being renamed.
811 if from == to {
812 return Err(NsError::at(NsErrorKind::AlreadyExists, to));
813 }
814 // The same directory is decided on the two open handles, not on the spelling of their paths. Comparing paths
815 // is wrong both ways: on a case-insensitive volume `/A/x` and `/a/X` are one directory (comparing exactly
816 // would refuse a respelling as a collision), and on a case-sensitive one `/A` and `/a` can be two (comparing
817 // folded would skip the collision check against the other directory's entries and replace one of them).
818 let same_dir = same_directory(&from_dir, &to_dir);
819 let names = list_names(&to_dir, to)?;
820 let ignore = if same_dir {
821 stored_name(&names, from_name)
822 } else {
823 None
824 };
825 if let Some(c) = conflict_in(&names, to_name, ignore) {
826 return Err(conflict_error(c, to));
827 }
828 from_dir
829 .rename(from_name, &to_dir, to_name)
830 .map_err(|e| NsError::from_io(&e, to))?;
831 sync_dir(&to_dir).map_err(|e| NsError::from_io(&e, to))?;
832 if !same_dir {
833 sync_dir(&from_dir).map_err(|e| NsError::from_io(&e, from))?;
834 }
835 match lookup(&to_dir, to_name, to)? {
836 Some((_, md)) => Ok(version_of(&md)),
837 None => Ok(version_of(&md)),
838 }
839 }
840
841 fn make_dir(&self, path: &NsPath, if_version: Option<&Version>) -> NsResult<Version> {
842 no_version(if_version, path)?;
843 let (parent, name) = open_parent(&self.root, path)?;
844 if let Some(c) = conflict_in(&list_names(&parent, path)?, name, None) {
845 return Err(conflict_error(c, path));
846 }
847 if exists_raw(&parent, name, path)? {
848 return Err(NsError::at(NsErrorKind::AlreadyExists, path));
849 }
850 #[cfg(unix)]
851 let builder = {
852 let mut b = DirBuilder::new();
853 b.mode(0o700);
854 b
855 };
856 #[cfg(not(unix))]
857 let builder = DirBuilder::new();
858 parent
859 .create_dir_with(name, &builder)
860 .map_err(|e| NsError::from_io(&e, path))?;
861 sync_dir(&parent).map_err(|e| NsError::from_io(&e, path))?;
862 match lookup(&parent, name, path)? {
863 Some((_, md)) => Ok(version_of(&md)),
864 None => Err(NsError::at(NsErrorKind::NotFound, path)),
865 }
866 }
867}
868
869// ---------------------------------------------------------------------------------------------------------------
870// Polling snapshot
871// ---------------------------------------------------------------------------------------------------------------
872
873/// Fingerprint the directory at `path` (and below, if `recursive`).
874///
875/// The walk is depth first and descends **from the handle it already holds**: a subdirectory is opened with a
876/// no-follow open relative to its parent's handle, so reaching a directory `n` levels down costs one open, not `n`
877/// (reopening each pending directory from the root made a scan quadratic in depth). The handles of the directories on
878/// the way down stay open until the walk returns past them, so a scan holds at most `max_depth + 1` directory handles
879/// however wide the tree is (plus the one being listed).
880///
881/// What ends a scan early, and how:
882///
883/// - **Deeper than `max_depth`**, or more than `max_tracked` entries, or a failure that is about *us* (descriptors
884/// exhausted, an I/O error): [`ScanOutcome::Incomplete`], so no half-picture is compared against the last good one.
885/// Never an error, and never a silent skip.
886/// - **A subdirectory that has vanished, became a link, or is unreadable** is simply not there (its entries show up as
887/// removed).
888/// - **Another filesystem** (Unix): a directory on a different device than the watched one is listed as an entry but
889/// not entered. See [`WatchOpts::max_depth`](super::WatchOpts::max_depth) and the module docs.
890fn scan(
891 root: &Dir,
892 path: &NsPath,
893 recursive: bool,
894 max_tracked: usize,
895 max_depth: usize,
896) -> ScanOutcome {
897 let Ok(top) = open_dir_at(root, path) else {
898 return ScanOutcome::Unavailable;
899 };
900 let top_dev = sys::device_of(&top);
901 if cfg!(unix) && top_dev.is_none() {
902 return ScanOutcome::Unavailable;
903 }
904 let mut snapshot = Snapshot::new();
905 let subdirs = match read_level(&top, path, true, recursive, max_tracked, &mut snapshot) {
906 Ok(subdirs) => subdirs,
907 Err(outcome) => return outcome,
908 };
909 // One frame per directory on the way down: its handle, its path, and the subdirectories not yet visited.
910 // `stack.len()` is the depth of the directory a frame's child would be (the watched directory is depth 0).
911 struct Frame {
912 dir: Dir,
913 path: NsPath,
914 subdirs: Vec<String>,
915 }
916 let mut stack = vec![Frame {
917 dir: top,
918 path: path.clone(),
919 subdirs,
920 }];
921 loop {
922 let depth = stack.len();
923 let Some(frame) = stack.last_mut() else {
924 break;
925 };
926 let Some(name) = frame.subdirs.pop() else {
927 stack.pop();
928 continue;
929 };
930 if depth > max_depth {
931 return ScanOutcome::Incomplete;
932 }
933 let Some(child_path) = frame.path.child(&name) else {
934 continue;
935 };
936 let child = match frame.dir.open_dir_nofollow(&name) {
937 Ok(d) => d,
938 Err(e) => {
939 match explain_open_failure(&frame.dir, &name, &e, &child_path, Want::Dir).kind() {
940 NsErrorKind::NotFound
941 | NsErrorKind::NotADirectory
942 | NsErrorKind::Escapes
943 | NsErrorKind::PermissionDenied => continue,
944 _ => return ScanOutcome::Incomplete,
945 }
946 }
947 };
948 if let Some(top_dev) = top_dev {
949 match sys::device_of(&child) {
950 Some(dev) if dev == top_dev => {}
951 // Another filesystem is mounted here: the entry is in the snapshot, its contents are not.
952 Some(_) => continue,
953 None => return ScanOutcome::Incomplete,
954 }
955 }
956 match read_level(
957 &child,
958 &child_path,
959 false,
960 recursive,
961 max_tracked,
962 &mut snapshot,
963 ) {
964 Ok(subdirs) => stack.push(Frame {
965 dir: child,
966 path: child_path,
967 subdirs,
968 }),
969 Err(outcome) => return outcome,
970 }
971 }
972 ScanOutcome::Complete(snapshot)
973}
974
975/// List one directory into `snapshot` and return the names of its subdirectories (empty unless `recursive`). The
976/// listing handle is dropped before this returns, so only `dir` itself stays open.
977///
978/// For the watched directory (`is_top`) an unreadable listing is `Unavailable`; for a subdirectory that is unreadable
979/// or has vanished it is an empty directory (its entries show up as removed).
980fn read_level(
981 dir: &Dir,
982 dir_path: &NsPath,
983 is_top: bool,
984 recursive: bool,
985 max_tracked: usize,
986 snapshot: &mut Snapshot,
987) -> Result<Vec<String>, ScanOutcome> {
988 let entries = match dir.entries() {
989 Ok(e) => e,
990 Err(_) if is_top => return Err(ScanOutcome::Unavailable),
991 Err(e)
992 if e.kind() == io::ErrorKind::PermissionDenied
993 || e.kind() == io::ErrorKind::NotFound =>
994 {
995 return Ok(Vec::new());
996 }
997 Err(_) => return Err(ScanOutcome::Incomplete),
998 };
999 let mut subdirs = Vec::new();
1000 for entry in entries {
1001 let Ok(entry) = entry else {
1002 return Err(ScanOutcome::Incomplete);
1003 };
1004 let file_name = entry.file_name();
1005 let Some(name) = file_name.to_str() else {
1006 continue;
1007 };
1008 if validate_name(name).is_err() {
1009 continue;
1010 }
1011 let Some(child) = dir_path.child(name) else {
1012 continue;
1013 };
1014 let Ok(md) = entry.metadata() else { continue };
1015 let kind = if md.file_type().is_dir() {
1016 Kind::Dir
1017 } else if md.file_type().is_file() {
1018 Kind::File
1019 } else {
1020 // Symlinks (a loop included), FIFOs, sockets, devices: not part of the namespace, never followed.
1021 continue;
1022 };
1023 if snapshot.len() >= max_tracked {
1024 return Err(ScanOutcome::Incomplete);
1025 }
1026 snapshot.insert(
1027 child,
1028 Fingerprint {
1029 kind,
1030 len: if kind == Kind::File { md.len() } else { 0 },
1031 mtime_ns: mtime_ns(&md),
1032 inode: sys::scan_inode(&md),
1033 },
1034 );
1035 if recursive && kind == Kind::Dir {
1036 subdirs.push(name.to_string());
1037 }
1038 }
1039 Ok(subdirs)
1040}
1041
1042// ---------------------------------------------------------------------------------------------------------------
1043// The Backend impl
1044// ---------------------------------------------------------------------------------------------------------------
1045
1046impl Backend for HostDir {
1047 fn caps(&self) -> Caps {
1048 self.caps
1049 }
1050
1051 fn root_identity(&self) -> Option<(u64, u64)> {
1052 self.identity
1053 }
1054
1055 fn walk(&self, path: &NsPath) -> NsResult<Vec<Entry>> {
1056 let dir = open_dir_at(&self.root, path)?;
1057 let entries = dir.entries().map_err(|e| NsError::from_io(&e, path))?;
1058 let mut out = Vec::new();
1059 for entry in entries {
1060 let entry = entry.map_err(|e| NsError::from_io(&e, path))?;
1061 let file_name = entry.file_name();
1062 let Some(name) = file_name.to_str() else {
1063 continue;
1064 };
1065 if validate_name(name).is_err() {
1066 continue;
1067 }
1068 let Ok(ft) = entry.file_type() else { continue };
1069 let kind = if ft.is_dir() {
1070 Kind::Dir
1071 } else if ft.is_file() {
1072 Kind::File
1073 } else {
1074 // Symlinks, FIFOs, sockets, devices: not addressable, so not listed.
1075 continue;
1076 };
1077 out.push(Entry {
1078 name: name.to_string(),
1079 kind,
1080 });
1081 }
1082 out.sort_by(|a, b| a.name.cmp(&b.name));
1083 Ok(out)
1084 }
1085
1086 fn read(&self, path: &NsPath, max: u64) -> NsResult<(Vec<u8>, Version)> {
1087 if path.is_root() {
1088 return Err(NsError::at(NsErrorKind::IsADirectory, path));
1089 }
1090 let (parent, name) = open_parent(&self.root, path)?;
1091 let (mut file, md) = open_regular(&parent, name, path)?;
1092 let version = version_of(&md);
1093 if md.len() > max {
1094 return Err(NsError::at(NsErrorKind::TooLarge, path));
1095 }
1096 // Read at most max + 1 bytes: enough to know it was too large, never an unbounded read of a growing file.
1097 let mut buf = Vec::new();
1098 (&mut file)
1099 .take(max.saturating_add(1))
1100 .read_to_end(&mut buf)
1101 .map_err(|e| NsError::from_io(&e, path))?;
1102 if buf.len() as u64 > max {
1103 return Err(NsError::at(NsErrorKind::TooLarge, path));
1104 }
1105 Ok((buf, version))
1106 }
1107
1108 fn stat(&self, path: &NsPath) -> NsResult<Stat> {
1109 if path.is_root() {
1110 let md = self
1111 .root
1112 .dir_metadata()
1113 .map_err(|e| NsError::from_io(&e, path))?;
1114 return Ok(stat_of(&md, Kind::Dir));
1115 }
1116 let (parent, name) = open_parent(&self.root, path)?;
1117 match lookup(&parent, name, path)? {
1118 Some((kind, md)) => Ok(stat_of(&md, kind)),
1119 None => Err(NsError::at(NsErrorKind::NotFound, path)),
1120 }
1121 }
1122
1123 fn write(
1124 &self,
1125 path: &NsPath,
1126 op: WriteOp,
1127 data: &[u8],
1128 if_version: Option<&Version>,
1129 ) -> NsResult<Version> {
1130 match op {
1131 WriteOp::CreateExclusive => {
1132 if path.is_root() {
1133 return Err(NsError::at(NsErrorKind::AlreadyExists, path));
1134 }
1135 self.create_exclusive(path, data, if_version)
1136 }
1137 WriteOp::Replace => {
1138 if path.is_root() {
1139 return Err(NsError::at(NsErrorKind::IsADirectory, path));
1140 }
1141 self.replace(path, data, if_version)
1142 }
1143 WriteOp::Remove => {
1144 no_data(data, path)?;
1145 self.remove(path, if_version)
1146 }
1147 WriteOp::RenameWithinMount { to } => {
1148 no_data(data, path)?;
1149 self.rename(path, &to, if_version)
1150 }
1151 WriteOp::MakeDir => {
1152 no_data(data, path)?;
1153 if path.is_root() {
1154 return Err(NsError::at(NsErrorKind::AlreadyExists, path));
1155 }
1156 self.make_dir(path, if_version)
1157 }
1158 }
1159 }
1160
1161 fn watch(&self, path: &NsPath, opts: WatchOpts) -> NsResult<Watch> {
1162 // Validate now, synchronously, so a bad path is an error here and not a thread that quietly reports nothing.
1163 drop(open_dir_at(&self.root, path)?);
1164 let (recursive, max_tracked, max_depth) =
1165 (opts.recursive, opts.max_tracked, opts.max_depth);
1166 let baseline = match scan(&self.root, path, recursive, max_tracked, max_depth) {
1167 ScanOutcome::Complete(s) => s,
1168 ScanOutcome::Unavailable => return Err(NsError::at(NsErrorKind::NotFound, path)),
1169 // Too many entries or too deep to track (or the scan could not finish): refuse rather than watch half a
1170 // tree.
1171 ScanOutcome::Incomplete => return Err(NsError::at(NsErrorKind::TooLarge, path)),
1172 };
1173 let root = self
1174 .root
1175 .try_clone()
1176 .map_err(|e| NsError::from_io(&e, path))?;
1177 let watched = path.clone();
1178 spawn_poller(
1179 baseline,
1180 move || scan(&root, &watched, recursive, max_tracked, max_depth),
1181 &opts,
1182 )
1183 .map_err(|e| NsError::from_io(&e, path))
1184 }
1185}
1186
1187#[cfg(test)]
1188mod tests {
1189 #[cfg(unix)]
1190 use std::time::{Duration, Instant};
1191
1192 use super::*;
1193
1194 fn p(s: &str) -> NsPath {
1195 NsPath::parse(s).unwrap()
1196 }
1197
1198 fn open(path: &Path) -> Dir {
1199 Dir::open_ambient_dir(path, ambient_authority()).unwrap()
1200 }
1201
1202 /// `/d/d/d/...`, `depth` levels, one directory per level, built through open handles (a path this long would not be
1203 /// accepted by the OS), with a file at the bottom. Returns nothing: the tree is the point.
1204 fn chain(root: &Dir, depth: usize) {
1205 let mut cur = root.try_clone().unwrap();
1206 for _ in 0..depth {
1207 cur.create_dir("d").unwrap();
1208 cur = cur.open_dir("d").unwrap();
1209 }
1210 cur.write("leaf", b"x").unwrap();
1211 }
1212
1213 fn complete(outcome: ScanOutcome) -> Snapshot {
1214 match outcome {
1215 ScanOutcome::Complete(s) => s,
1216 ScanOutcome::Incomplete => panic!("expected a complete scan, got Incomplete"),
1217 ScanOutcome::Unavailable => panic!("expected a complete scan, got Unavailable"),
1218 }
1219 }
1220
1221 fn is_incomplete(outcome: &ScanOutcome) -> bool {
1222 matches!(outcome, ScanOutcome::Incomplete)
1223 }
1224
1225 /// The identity accessors must answer for a `Metadata` that did not come from an open handle (a directory entry's),
1226 /// not panic. On Windows that metadata has no by-handle information and the `cap-fs-ext` accessors used to
1227 /// `expect()` it; on Unix every answer is `Some`. Either way, nothing here may panic, including the version a
1228 /// careless caller would derive from it.
1229 #[test]
1230 fn identity_accessors_never_panic_on_metadata_that_did_not_come_from_a_handle() {
1231 let tmp = tempfile::tempdir().unwrap();
1232 std::fs::write(tmp.path().join("f"), b"x").unwrap();
1233 std::fs::create_dir(tmp.path().join("sub")).unwrap();
1234 let dir = open(tmp.path());
1235 let mut seen = 0;
1236 for entry in dir.entries().unwrap() {
1237 let md = entry.unwrap().metadata().unwrap();
1238 let identity = sys::identity(&md);
1239 let links = sys::links(&md);
1240 let _ = (sys::owner(&md), sys::mode(&md), sys::scan_inode(&md));
1241 let _ = version_of(&md);
1242 let _ = stat_of(&md, Kind::File);
1243 #[cfg(unix)]
1244 {
1245 assert!(identity.is_some() && links.is_some());
1246 }
1247 #[cfg(not(unix))]
1248 {
1249 let _ = (identity, links);
1250 }
1251 seen += 1;
1252 }
1253 assert_eq!(seen, 2);
1254
1255 // And from handles, which is where identity is promised.
1256 let md = dir.dir_metadata().unwrap();
1257 assert!(
1258 sys::identity(&md).is_some(),
1259 "a directory handle has an identity"
1260 );
1261 let md = dir.symlink_metadata("f").unwrap();
1262 assert!(sys::identity(&md).is_some() && sys::links(&md) == Some(1));
1263 let a = HostDir::open_ambient(tmp.path()).unwrap();
1264 let b = HostDir::from_dir(dir).unwrap();
1265 assert!(
1266 a.root_identity().is_some(),
1267 "a host directory has an identity"
1268 );
1269 assert_eq!(
1270 a.root_identity(),
1271 b.root_identity(),
1272 "two handles on one directory report one identity"
1273 );
1274 }
1275
1276 #[test]
1277 fn a_scan_stops_at_the_depth_cap_with_incomplete_not_a_partial_picture() {
1278 let tmp = tempfile::tempdir().unwrap();
1279 let root = open(tmp.path());
1280 chain(&root, 200);
1281 // 200 levels fit a cap of 256 and are all there: 200 directories and the leaf.
1282 let all = complete(scan(&root, &NsPath::root(), true, 1 << 20, 256));
1283 assert_eq!(all.len(), 201);
1284 // A cap of 64 is exceeded: no snapshot at all, not the first 64 levels.
1285 assert!(is_incomplete(&scan(
1286 &root,
1287 &NsPath::root(),
1288 true,
1289 1 << 20,
1290 64
1291 )));
1292 }
1293
1294 #[test]
1295 fn the_cap_counts_levels_below_the_watched_directory() {
1296 let tmp = tempfile::tempdir().unwrap();
1297 let root = open(tmp.path());
1298 chain(&root, 3); // /d, /d/d, /d/d/d, and /d/d/d/leaf
1299 for (cap, fits) in [(0, false), (2, false), (3, true), (4, true)] {
1300 let out = scan(&root, &NsPath::root(), true, 1 << 20, cap);
1301 assert_eq!(!is_incomplete(&out), fits, "cap {cap}");
1302 if fits {
1303 assert_eq!(complete(out).len(), 4, "cap {cap}");
1304 }
1305 }
1306 // The watched directory is level 0 wherever it sits in the mount: from /d, the same tree is two levels deep.
1307 let from_d = scan(&root, &p("/d"), true, 1 << 20, 2);
1308 assert_eq!(complete(from_d).len(), 3);
1309 // A flat watch never looks at depth.
1310 assert_eq!(
1311 complete(scan(&root, &NsPath::root(), false, 1 << 20, 0)).len(),
1312 1
1313 );
1314 // An empty tree under cap 0 is complete.
1315 let empty = tempfile::tempdir().unwrap();
1316 assert!(complete(scan(&open(empty.path()), &NsPath::root(), true, 1 << 20, 0)).is_empty());
1317 }
1318
1319 /// The scan that used to reopen every pending directory from the root took 48 s on a 2,047-level chain (debug).
1320 /// Unix only: the chain's host path is far past what Windows path APIs accept and its teardown is not the point.
1321 #[cfg(unix)]
1322 #[test]
1323 fn a_chain_two_thousand_levels_deep_is_one_quick_incomplete_scan() {
1324 let tmp = tempfile::tempdir().unwrap();
1325 let root = open(tmp.path());
1326 chain(&root, 2000);
1327 let started = Instant::now();
1328 let out = scan(&root, &NsPath::root(), true, 262_144, 64);
1329 let took = started.elapsed();
1330 assert!(
1331 is_incomplete(&out),
1332 "deeper than the cap must be Incomplete"
1333 );
1334 assert!(
1335 took < Duration::from_millis(500),
1336 "a scan of a too-deep tree took {took:?}"
1337 );
1338 }
1339
1340 #[test]
1341 fn the_scan_holds_one_handle_per_level_and_a_tree_within_the_cap_is_fully_reported() {
1342 let tmp = tempfile::tempdir().unwrap();
1343 let root = open(tmp.path());
1344 // A bushy tree 5 levels deep: every directory has two subdirectories and a file.
1345 fn grow(dir: &Dir, levels: usize) {
1346 dir.write("f", b"x").unwrap();
1347 if levels > 0 {
1348 for n in ["a", "b"] {
1349 dir.create_dir(n).unwrap();
1350 grow(&dir.open_dir(n).unwrap(), levels - 1);
1351 }
1352 }
1353 }
1354 grow(&root, 5);
1355 let snap = complete(scan(&root, &NsPath::root(), true, 1 << 20, 5));
1356 // 1 + 2 + 4 + 8 + 16 + 32 files, and 2 + 4 + 8 + 16 + 32 directories.
1357 assert_eq!(snap.len(), 63 + 62);
1358 assert!(snap.contains_key(&p("/b/a/b/a/b/f")));
1359 assert!(is_incomplete(&scan(
1360 &root,
1361 &NsPath::root(),
1362 true,
1363 1 << 20,
1364 4
1365 )));
1366 }
1367
1368 /// The scan does not cross onto another filesystem. `/dev/shm` is a tmpfs under `/dev` (a devtmpfs) on every
1369 /// ordinary Linux; where it is not a separate device the premise is missing and the test says so and passes.
1370 #[cfg(target_os = "linux")]
1371 #[test]
1372 fn a_recursive_scan_does_not_descend_into_another_filesystem() {
1373 use std::os::unix::fs::MetadataExt;
1374 let (Ok(dev), Ok(shm)) = (std::fs::metadata("/dev"), std::fs::metadata("/dev/shm")) else {
1375 eprintln!("skipped: /dev or /dev/shm is not there");
1376 return;
1377 };
1378 if dev.dev() == shm.dev() {
1379 eprintln!("skipped: /dev/shm is not a separate filesystem here");
1380 return;
1381 }
1382 let Ok(inside) = tempfile::Builder::new()
1383 .prefix("skns-dev-")
1384 .tempdir_in("/dev/shm")
1385 else {
1386 eprintln!("skipped: /dev/shm is not writable here");
1387 return;
1388 };
1389 std::fs::write(inside.path().join("deep"), b"x").unwrap();
1390 let name = inside
1391 .path()
1392 .file_name()
1393 .unwrap()
1394 .to_str()
1395 .unwrap()
1396 .to_string();
1397
1398 let root = open(Path::new("/dev"));
1399 let ScanOutcome::Complete(snap) = scan(&root, &NsPath::root(), true, 1 << 20, 64) else {
1400 eprintln!("skipped: /dev could not be scanned completely here");
1401 return;
1402 };
1403 assert_eq!(
1404 snap.get(&p("/shm")).map(|f| f.kind),
1405 Some(Kind::Dir),
1406 "the mount point is listed as a directory"
1407 );
1408 let below: Vec<_> = snap
1409 .keys()
1410 .filter(|k| k.as_str().starts_with("/shm/"))
1411 .collect();
1412 assert!(
1413 below.is_empty(),
1414 "the scan crossed into the tmpfs ({name}): {below:?}"
1415 );
1416 // Watching the tmpfs itself is fine: it is the watched directory, so its own device is the reference.
1417 let shm_root = open(Path::new("/dev/shm"));
1418 let ScanOutcome::Complete(inner) = scan(&shm_root, &NsPath::root(), true, 1 << 20, 64)
1419 else {
1420 panic!("/dev/shm itself must be scannable");
1421 };
1422 assert!(inner.contains_key(&p(&format!("/{name}/deep"))));
1423 }
1424}