Skip to main content

raf_source/tree/
disk.rs

1// SPDX-FileCopyrightText: 2026 Blackcat Informatics® Inc. <paudley@blackcatinformatics.ca>
2// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0
3
4//! The handle-contained disk backend. The separate committed Git host backend
5//! uses the native read-only Git object library rather than this filesystem strategy.
6//!
7//! A read, a listing and an entry lookup each open a handle (the file to read,
8//! the directory to list, or the directory that holds the entry), verify it
9//! against the root, use it, and verify it again after the use. How the handle
10//! is opened and verified is the platform's [`Strategy`]:
11//!
12//! * Linux ([`linux`]): the canonical path is taken as an `O_PATH` reference,
13//!   which performs no I/O; the kernel's own path for it must lie under the
14//!   root before it is opened for reading or listed through that path.
15//! * Other Unix systems ([`other_unix`]): the path is walked one component at
16//!   a time from a descriptor of the root, with `openat` and without following
17//!   any symlink; an in-root symlink is resolved by reading it and continuing
18//!   the walk. A walk outside the root may only descend back into it, never
19//!   climb, and opens nothing outside but directories, so an outside
20//!   non-directory is never opened. No path is resolved by name.
21//! * Windows ([`handle_path`]): the canonical path is opened as a handle and
22//!   the path the system gives for that handle must lie under the root.
23//!
24//! On Windows a segment that Windows would not read as the name it spells (a
25//! reserved device name, a name that ends in a dot or a space, or one that
26//! names an alternate data stream) is refused before anything else. A read
27//! takes at most `max_bytes + 1` bytes and refuses the file when the extra byte
28//! arrives.
29//!
30//! A platform with neither Unix nor Windows has no strategy: [`DiskTree::new`]
31//! fails there, and the calls below it are never reached.
32
33#![cfg_attr(
34    not(any(unix, windows)),
35    allow(
36        unused_variables,
37        dead_code,
38        reason = "with no strategy no tree is built, so the calls are compiled but never reached"
39    )
40)]
41
42use std::fs::Metadata;
43use std::io::Read;
44use std::path::{Path, PathBuf};
45
46use super::{Entry, EntryKind, FileId, Opened, Tree};
47use crate::error::TreeError;
48use crate::path::RelPath;
49
50mod capture;
51pub use capture::{CapturedDirectory, CapturedFile, CapturedLink};
52
53/// Resolve a supplied host root locator; each backend owns its access strategy.
54pub(super) fn canonical_root(root: &Path) -> std::io::Result<PathBuf> {
55    std::fs::canonicalize(root)
56}
57
58/// A callback that a test runs at one point of a call.
59#[cfg(test)]
60type Hook = Box<dyn Fn() + Send + Sync>;
61
62/// Run the test hook `$hook` of `$tree`; outside test builds, nothing.
63macro_rules! hook {
64    ($tree:expr, $hook:ident) => {
65        #[cfg(test)]
66        if let Some(hook) = &$tree.$hook {
67            hook();
68        }
69    };
70}
71
72/// Apply `$body` to the strategy's own handle inside a [`Handle`].
73macro_rules! each {
74    ($handle:expr, $inner:ident => $body:expr) => {
75        match *$handle {
76            #[cfg(target_os = "linux")]
77            Handle::Linux(ref $inner) => $body,
78            #[cfg(all(unix, not(target_os = "linux")))]
79            Handle::OtherUnix(ref $inner) => $body,
80            #[cfg(windows)]
81            Handle::Windows(ref $inner) => $body,
82        }
83    };
84}
85
86#[cfg(windows)]
87mod final_path;
88#[cfg(windows)]
89mod handle_path;
90#[cfg(target_os = "linux")]
91mod linux;
92#[cfg(all(unix, not(target_os = "linux")))]
93mod other_unix;
94#[cfg(unix)]
95mod unix_root;
96// Without a strategy no tree can be built, so there is nothing to test.
97#[cfg(all(test, any(unix, windows)))]
98mod tests;
99
100/// How a handle is opened and verified against the root.
101///
102/// The platform selects its native variant in production and test builds.
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104enum Strategy {
105    /// An `O_PATH` reference verified through `/proc/self/fd`, then reopened.
106    #[cfg(target_os = "linux")]
107    Linux,
108    /// A walk beneath a descriptor of the root, one `openat` per component.
109    #[cfg(all(unix, not(target_os = "linux")))]
110    OtherUnix,
111    /// A handle opened by path and verified by the path the system gives for
112    /// it: `GetFinalPathNameByHandleW` on Windows.
113    #[cfg(windows)]
114    Windows,
115}
116
117impl Strategy {
118    /// The strategy of the platform the crate is built for.
119    #[cfg(target_os = "linux")]
120    #[expect(
121        clippy::unnecessary_wraps,
122        reason = "the signature is shared with the platforms that have no strategy"
123    )]
124    fn native(_shown: &str) -> Result<Self, TreeError> {
125        Ok(Self::Linux)
126    }
127
128    /// The strategy of the platform the crate is built for.
129    #[cfg(all(unix, not(target_os = "linux")))]
130    #[expect(
131        clippy::unnecessary_wraps,
132        reason = "the signature is shared with the platforms that have no strategy"
133    )]
134    fn native(_shown: &str) -> Result<Self, TreeError> {
135        Ok(Self::OtherUnix)
136    }
137
138    /// The strategy of the platform the crate is built for.
139    #[cfg(windows)]
140    #[expect(
141        clippy::unnecessary_wraps,
142        reason = "the signature is shared with the platforms that have no strategy"
143    )]
144    fn native(_shown: &str) -> Result<Self, TreeError> {
145        Ok(Self::Windows)
146    }
147
148    /// Without Unix or Windows no handle can be verified, so no tree opens.
149    #[cfg(not(any(unix, windows)))]
150    fn native(shown: &str) -> Result<Self, TreeError> {
151        Err(TreeError::Io {
152            path: shown.to_owned(),
153            source: std::io::Error::new(
154                std::io::ErrorKind::Unsupported,
155                "this platform cannot verify a handle against the root",
156            ),
157        })
158    }
159}
160
161/// What a handle must be.
162#[derive(Debug, Clone, Copy, PartialEq, Eq)]
163enum Want {
164    /// A regular file, to be read; a final symlink is followed.
165    File,
166    /// A directory that holds an entry; a final symlink is followed.
167    Dir,
168    /// A directory to be listed; a final symlink is refused.
169    Listing,
170}
171
172impl Want {
173    /// Refuse `metadata` of a handle that is not what is wanted.
174    fn require(self, metadata: &Metadata, shown: &str) -> Result<(), TreeError> {
175        let file_type = metadata.file_type();
176        let fits = match self {
177            Self::File => file_type.is_file(),
178            Self::Dir | Self::Listing => file_type.is_dir(),
179        };
180        if fits {
181            Ok(())
182        } else {
183            Err(not_regular(shown))
184        }
185    }
186}
187
188/// A verified handle, of the strategy that opened it.
189enum Handle {
190    #[cfg(target_os = "linux")]
191    Linux(linux::Handle),
192    #[cfg(all(unix, not(target_os = "linux")))]
193    OtherUnix(other_unix::Handle),
194    #[cfg(windows)]
195    Windows(handle_path::Handle),
196}
197
198impl Handle {
199    /// Read current metadata from the verified handle, without resolving a name.
200    fn metadata(&self, shown: &str) -> Result<Metadata, TreeError> {
201        each!(self, inner => inner.metadata(shown))
202    }
203
204    /// Capture a lexical link relative to this verified directory.
205    fn link(
206        &self,
207        name: &str,
208        shown: &str,
209        between: impl FnOnce(),
210    ) -> Result<(FileId, PathBuf), TreeError> {
211        each!(self, inner => inner.link(name, shown, between))
212    }
213
214    /// The identity of the verified file.
215    fn identity(&self, root: &Path, shown: &str) -> Result<FileId, TreeError> {
216        each!(self, inner => inner.identity(root, shown))
217    }
218
219    /// At most `max_bytes` bytes of the verified file.
220    fn read(&self, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
221        each!(self, inner => inner.read(max_bytes, shown))
222    }
223
224    /// The entries of the verified directory, in the order the system gives.
225    fn entries(&self, shown: &str) -> Result<Vec<Entry>, TreeError> {
226        self.entries_bounded(shown, usize::MAX)
227    }
228
229    fn entries_bounded(&self, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
230        each!(self, inner => inner.entries(shown, max_entries))
231    }
232
233    /// What `name` is in the verified directory, without following it.
234    fn lookup(&self, name: &str, shown: &str) -> Result<Option<EntryKind>, TreeError> {
235        each!(self, inner => inner.lookup(name, shown))
236    }
237
238    /// Verify the handle again, after a use.
239    fn recheck(&self, tree: &DiskTree, shown: &str) -> Result<(), TreeError> {
240        match *self {
241            #[cfg(target_os = "linux")]
242            Handle::Linux(ref inner) => inner.recheck(tree, shown),
243            #[cfg(all(unix, not(target_os = "linux")))]
244            Handle::OtherUnix(ref inner) => inner.recheck(&tree.root_directory, shown),
245            #[cfg(windows)]
246            Handle::Windows(ref inner) => inner.recheck(&tree.root, shown),
247        }
248    }
249}
250
251/// True when an open with `flags` returns at once on a FIFO: an `O_PATH`
252/// reference performs no I/O, and an `O_NONBLOCK` open does not wait for the
253/// other end.
254#[cfg(all(test, unix))]
255fn never_blocks(flags: u32) -> bool {
256    #[cfg(target_os = "linux")]
257    let path = libc::O_PATH.cast_unsigned();
258    #[cfg(not(target_os = "linux"))]
259    let path = 0;
260    flags & (path | libc::O_NONBLOCK.cast_unsigned()) != 0
261}
262
263/// A tree read from a directory on disk.
264///
265/// The root is canonicalised once, in [`DiskTree::new`]. Unix retains its
266/// original directory description. Linux refuses relocation outside the
267/// canonical scope; replacement at that pathname cannot retarget the tree.
268/// A symlink inside the tree is followed only when its target is also inside it.
269pub struct DiskTree {
270    root: PathBuf,
271    strategy: Strategy,
272    /// The original directory description shared by all Unix operations.
273    #[cfg(unix)]
274    root_directory: unix_root::Root,
275    /// Runs after the containment check and before the open.
276    #[cfg(test)]
277    before_open: Option<Hook>,
278    /// Runs after the open and before the handle is verified.
279    #[cfg(test)]
280    after_open: Option<Hook>,
281    /// Runs after the handle is verified and before it is used.
282    #[cfg(test)]
283    after_verify: Option<Hook>,
284    /// Runs between the first capture observation and its comparison.
285    #[cfg(test)]
286    after_observation: Option<Hook>,
287    /// Runs inside one step of the other-Unix walk, after an open failed and
288    /// before the status of the entry is read.
289    #[cfg(all(test, unix, not(target_os = "linux")))]
290    mid_step: Option<Hook>,
291    /// The flags of every open that resolves a name below the root.
292    #[cfg(all(test, unix))]
293    opens: std::sync::Mutex<Vec<u32>>,
294}
295
296impl std::fmt::Debug for DiskTree {
297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
298        f.debug_struct("DiskTree")
299            .field("root", &self.root)
300            .finish_non_exhaustive()
301    }
302}
303
304impl DiskTree {
305    /// Host-locator size for admitting a structural cross-root path check.
306    pub(crate) fn root_path_bytes(&self) -> usize {
307        self.root.as_os_str().len()
308    }
309
310    fn directory_identity(&self, path: &RelPath) -> Result<FileId, TreeError> {
311        let shown = path.to_string();
312        let handle = self.open(path, Want::Dir, &shown)?;
313        self.used(&handle, &shown, |handle| {
314            handle.identity(&self.root, &shown)
315        })
316    }
317
318    /// Compare package directories, never merely their manifest-file identities.
319    pub(crate) fn dependency_directory_matches(
320        &self,
321        base_manifest: &RelPath,
322        relative: &str,
323        destination: &Self,
324        destination_manifest: &RelPath,
325    ) -> Result<bool, TreeError> {
326        super::require_first_party(base_manifest)?;
327        super::require_first_party(destination_manifest)?;
328        let missing_parent = |path: &RelPath| TreeError::NotRegular {
329            path: path.to_string(),
330        };
331        let base = base_manifest
332            .parent()
333            .ok_or_else(|| missing_parent(base_manifest))?;
334        let target = destination_manifest
335            .parent()
336            .ok_or_else(|| missing_parent(destination_manifest))?;
337        let before = self.directory_identity(&base)?;
338        let declared = self.directory_tree_at(&PathBuf::from(base.as_str()).join(relative))?;
339        let expected = declared.directory_identity(&RelPath::root())?;
340        let target_identity = destination.directory_identity(&target)?;
341        let actual = destination.directory_tree_at(Path::new(target.as_str()))?;
342        let same_directory = actual.directory_identity(&RelPath::root())? == target_identity
343            && expected == target_identity
344            && declared.root == actual.root;
345        if self.directory_identity(&base)? != before {
346            return Err(TreeError::from_io(
347                &base_manifest.to_string(),
348                std::io::Error::other("owning directory changed while checking a reference path"),
349            ));
350        }
351        Ok(same_directory)
352    }
353
354    /// Open a tree rooted at `root`, canonicalising it once.
355    ///
356    /// A symlinked root is followed: the tree is rooted at its target.
357    ///
358    /// # Errors
359    ///
360    /// Returns [`TreeError::NotFound`] when the root does not exist,
361    /// [`TreeError::NotRegular`] when it is not a directory, and
362    /// [`TreeError::SymlinkLoop`] or [`TreeError::Io`] when the operating
363    /// system fails or cannot verify a handle against the root.
364    pub fn new(root: impl AsRef<Path>) -> Result<Self, TreeError> {
365        let given = root.as_ref();
366        let shown = given.display().to_string();
367        let root = canonical_root(given).map_err(|e| TreeError::from_io(&shown, e))?;
368        let metadata = std::fs::metadata(&root).map_err(|e| TreeError::from_io(&shown, e))?;
369        Self::from_observed_root(root, &metadata, &shown)
370    }
371
372    fn from_observed_root(
373        root: PathBuf,
374        metadata: &Metadata,
375        shown: &str,
376    ) -> Result<Self, TreeError> {
377        if !metadata.is_dir() {
378            return Err(TreeError::NotRegular { path: shown.into() });
379        }
380        let strategy = Strategy::native(shown)?;
381        #[cfg(unix)]
382        let root_directory = unix_root::Root::open(&root, shown)?;
383        #[cfg(target_os = "linux")]
384        if root_directory.identity() != device_identity(metadata) {
385            return Err(outside(shown));
386        }
387        let tree = Self::from_parts(
388            root,
389            strategy,
390            #[cfg(unix)]
391            root_directory,
392        );
393        #[cfg(target_os = "linux")]
394        linux::verify_root(&tree, shown)?;
395        Ok(tree)
396    }
397
398    fn from_parts(
399        root: PathBuf,
400        strategy: Strategy,
401        #[cfg(unix)] root_directory: unix_root::Root,
402    ) -> Self {
403        Self {
404            root,
405            strategy,
406            #[cfg(unix)]
407            root_directory,
408            #[cfg(test)]
409            before_open: None,
410            #[cfg(test)]
411            after_open: None,
412            #[cfg(test)]
413            after_verify: None,
414            #[cfg(test)]
415            after_observation: None,
416            #[cfg(all(test, unix, not(target_os = "linux")))]
417            mid_step: None,
418            #[cfg(all(test, unix))]
419            opens: std::sync::Mutex::new(Vec::new()),
420        }
421    }
422
423    /// Clone the original Linux workspace directory description.
424    ///
425    /// This is a path-only handle, suitable for descriptor-relative operations.
426    /// An explicit metadata publisher can share it with this Tree rather than
427    /// reopening a pathname that could now name another directory. Directory
428    /// synchronization requires a separately opened, verified readable handle.
429    /// Returning this handle does not make the inspected source immutable.
430    ///
431    /// # Errors
432    /// Refuses a root outside its admitted canonical scope or a failure to
433    /// inspect or clone the directory descriptor.
434    #[cfg(target_os = "linux")]
435    pub fn directory_handle(&self) -> Result<std::fs::File, TreeError> {
436        linux::verify_root(self, &self.root.display().to_string())?;
437        self.root_directory
438            .dir
439            .try_clone()
440            .map(std::fs::File::from)
441            .map_err(|e| TreeError::from_io(&self.root.display().to_string(), e))
442    }
443
444    fn directory_tree_at(&self, path: &Path) -> Result<Self, TreeError> {
445        #[cfg(target_os = "linux")]
446        {
447            let shown = path.display().to_string();
448            // The empty relative path denotes this root; openat requires `.`.
449            let relative = if path.as_os_str().is_empty() {
450                Path::new(".")
451            } else {
452                path
453            };
454            let root_directory =
455                unix_root::Root::open_at(&self.root_directory.dir, relative, &shown)?;
456            let root = std::fs::read_link(descriptor_path(&root_directory.dir))
457                .map_err(|e| link_read_error(&shown, e))?;
458            Ok(Self::from_parts(root, self.strategy, root_directory))
459        }
460        #[cfg(not(target_os = "linux"))]
461        Self::new(self.root.join(path))
462    }
463
464    /// Inspect a regular file's byte length through a verified handle.
465    pub(crate) fn byte_len(&self, path: &RelPath) -> Result<u64, TreeError> {
466        super::require_first_party(path)?;
467        let shown = path.to_string();
468        let handle = self.open(path, Want::File, &shown)?;
469        self.used(&handle, &shown, |handle| Ok(handle.metadata(&shown)?.len()))
470    }
471
472    /// Take the actual file identity and read bytes from that same verified open.
473    ///
474    /// An identity accepted by `seen` returns [`super::OpenedBytes::Seen`]
475    /// without reading its payload or applying the byte ceiling to that payload.
476    /// Otherwise the complete bytes obey [`Tree::read_bytes`].
477    ///
478    /// # Errors
479    /// As [`Tree::read_bytes`], including identity and handle verification failures.
480    pub fn read_unseen_bytes(
481        &self,
482        path: &RelPath,
483        max_bytes: u64,
484        seen: &dyn Fn(&FileId) -> bool,
485    ) -> Result<super::OpenedBytes, TreeError> {
486        super::require_first_party(path)?;
487        let shown = path.to_string();
488        let handle = self.open(path, Want::File, &shown)?;
489        let id = handle.identity(&self.root, &shown)?;
490        if seen(&id) {
491            return Ok(super::OpenedBytes::Seen(id));
492        }
493        let bytes = self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))?;
494        Ok(super::OpenedBytes::Read { id, bytes })
495    }
496
497    /// Record the flags of an open that is about to resolve a name below the
498    /// root, and require that it cannot wait. The check runs before the open,
499    /// so a regression that drops the flag fails here and never reaches a
500    /// FIFO that would block it.
501    #[cfg(all(test, unix))]
502    fn note_open(&self, flags: u32) {
503        assert!(
504            never_blocks(flags),
505            "an open of a name below the root could block: flags {flags:#o}"
506        );
507        self.opens.lock().expect("the open record").push(flags);
508    }
509
510    /// The flags of every open recorded so far, oldest first.
511    #[cfg(all(test, unix))]
512    fn recorded_opens(&self) -> Vec<u32> {
513        self.opens.lock().expect("the open record").clone()
514    }
515
516    /// The path on disk that `path` names, before any symlink is followed.
517    #[cfg(any(target_os = "linux", windows))]
518    fn candidate(&self, path: &RelPath) -> PathBuf {
519        #[cfg(target_os = "linux")]
520        let root = descriptor_path(&self.root_directory.dir).join(".");
521        #[cfg(windows)]
522        let root = self.root.clone();
523        if path.is_root() {
524            root
525        } else {
526            root.join(path.as_str())
527        }
528    }
529
530    /// Canonicalise `candidate` and require the canonical root as its prefix.
531    #[cfg(any(target_os = "linux", windows))]
532    fn contain(&self, candidate: &Path, shown: &str) -> Result<PathBuf, TreeError> {
533        let canonical =
534            std::fs::canonicalize(candidate).map_err(|e| TreeError::from_io(shown, e))?;
535        if canonical.starts_with(&self.root) {
536            Ok(canonical)
537        } else {
538            Err(outside(shown))
539        }
540    }
541
542    /// Open `path` as `want` and verify the handle against the root.
543    fn open(&self, path: &RelPath, want: Want, shown: &str) -> Result<Handle, TreeError> {
544        refuse_windows_names(path, shown)?;
545        match self.strategy {
546            #[cfg(target_os = "linux")]
547            Strategy::Linux => linux::open(self, path, want, shown).map(Handle::Linux),
548            #[cfg(all(unix, not(target_os = "linux")))]
549            Strategy::OtherUnix => other_unix::open(self, path, want, shown).map(Handle::OtherUnix),
550            #[cfg(windows)]
551            Strategy::Windows => handle_path::open(self, path, want, shown).map(Handle::Windows),
552        }
553    }
554
555    /// Use the verified `handle` with `work`, then verify it again; a handle
556    /// that no longer passes discards what the use returned.
557    fn used<T>(
558        &self,
559        handle: &Handle,
560        shown: &str,
561        work: impl FnOnce(&Handle) -> Result<T, TreeError>,
562    ) -> Result<T, TreeError> {
563        hook!(self, after_verify);
564        let result = work(handle);
565        handle.recheck(self, shown)?;
566        result
567    }
568
569    /// Exercise a source change at a deterministic observation boundary.
570    #[cfg(test)]
571    fn observed(&self) {
572        hook!(self, after_observation);
573    }
574}
575
576impl Tree for DiskTree {
577    fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
578        text(self.read_bytes(path, max_bytes)?, path)
579    }
580
581    /// The file is checked against the root before and after reading. At most
582    /// `max_bytes + 1` bytes are read, and the extra byte makes the read
583    /// refuse. No UTF-8 validation or text conversion is applied.
584    fn read_bytes(&self, path: &RelPath, max_bytes: u64) -> Result<Vec<u8>, TreeError> {
585        super::require_first_party(path)?;
586        let shown = path.to_string();
587        let handle = self.open(path, Want::File, &shown)?;
588        self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))
589    }
590
591    /// The identity is, on Unix, the device and inode of the verified handle,
592    /// and on Windows the path the system gives for it, below the root; the
593    /// text, when it is read, comes from the same handle.
594    fn read_unseen(
595        &self,
596        path: &RelPath,
597        max_bytes: u64,
598        seen: &dyn Fn(&FileId) -> bool,
599    ) -> Result<Opened, TreeError> {
600        match self.read_unseen_bytes(path, max_bytes, seen)? {
601            super::OpenedBytes::Seen(id) => Ok(Opened::Seen(id)),
602            super::OpenedBytes::Read { id, bytes } => Ok(Opened::Read {
603                id,
604                text: text(bytes, path)?,
605            }),
606        }
607    }
608
609    fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
610        super::require_first_party(path)?;
611        let shown = path.to_string();
612        let handle = self.open(path, Want::Listing, &shown)?;
613        let mut entries = self.used(&handle, &shown, |handle| handle.entries(&shown))?;
614        entries.sort();
615        Ok(entries)
616    }
617
618    fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
619        super::require_first_party(path)?;
620        let shown = path.to_string();
621        refuse_windows_names(path, &shown)?;
622        let (Some(name), Some(parent)) = (path.file_name(), path.parent()) else {
623            return Ok(Some(EntryKind::Dir));
624        };
625        // `x/..` is the directory the path itself leads to, which may lie
626        // outside the root even when `x` does not, so it is opened whole.
627        let climbs = name == "..";
628        let directory = if climbs { path } else { &parent };
629        let handle = match self.open(directory, Want::Dir, &shown) {
630            Ok(handle) => handle,
631            Err(TreeError::NotFound { .. } | TreeError::NotRegular { .. }) => return Ok(None),
632            Err(other) => return Err(other),
633        };
634        self.used(&handle, &shown, |handle| {
635            if climbs {
636                Ok(Some(EntryKind::Dir))
637            } else {
638                handle.lookup(name, &shown)
639            }
640        })
641    }
642}
643
644/// What a file type from the standard library is.
645#[cfg(any(target_os = "linux", windows))]
646fn kind_of(file_type: std::fs::FileType) -> EntryKind {
647    if file_type.is_symlink() {
648        EntryKind::Symlink
649    } else if file_type.is_dir() {
650        EntryKind::Dir
651    } else if file_type.is_file() {
652        EntryKind::File
653    } else {
654        EntryKind::Other
655    }
656}
657
658/// What is at `path`, without following a final symlink.
659#[cfg(any(target_os = "linux", windows))]
660fn lookup(path: &Path, shown: &str) -> Result<Option<EntryKind>, TreeError> {
661    match std::fs::symlink_metadata(path) {
662        Ok(metadata) => Ok(Some(kind_of(metadata.file_type()))),
663        Err(e)
664            if matches!(
665                e.kind(),
666                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
667            ) =>
668        {
669            Ok(None)
670        }
671        Err(e) => Err(TreeError::from_io(shown, e)),
672    }
673}
674
675/// The entries of the directory at `listing`, in the order the system gives.
676#[cfg(any(target_os = "linux", windows))]
677fn read_entries(listing: &Path, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
678    let mut entries = Vec::new();
679    for item in std::fs::read_dir(listing).map_err(|e| TreeError::from_io(shown, e))? {
680        let item = item.map_err(|e| TreeError::from_io(shown, e))?;
681        entry_room(entries.len(), max_entries, shown)?;
682        let name = item
683            .file_name()
684            .into_string()
685            .map_err(|raw| TreeError::NonUtf8Name {
686                path: shown.to_owned(),
687                name: raw.to_string_lossy().into_owned(),
688            })?;
689        let file_type = item.file_type().map_err(|e| TreeError::from_io(shown, e))?;
690        entries.push(Entry {
691            name,
692            kind: kind_of(file_type),
693        });
694    }
695    Ok(entries)
696}
697
698fn entry_room(count: usize, max_entries: usize, shown: &str) -> Result<(), TreeError> {
699    if count < max_entries {
700        Ok(())
701    } else {
702        Err(TreeError::from_io(
703            shown,
704            std::io::Error::new(
705                std::io::ErrorKind::InvalidData,
706                format!(
707                    "directory entry limit {max_entries} exceeded; increase the admitted capture budget"
708                ),
709            ),
710        ))
711    }
712}
713
714/// A listing refuses a path whose final component is not a real directory,
715/// a symlink included, judged without following it.
716#[cfg(any(target_os = "linux", windows))]
717fn refuse_unless_directory(candidate: &Path, shown: &str) -> Result<(), TreeError> {
718    let own = std::fs::symlink_metadata(candidate).map_err(|e| TreeError::from_io(shown, e))?;
719    if own.is_dir() {
720        Ok(())
721    } else {
722        Err(not_regular(shown))
723    }
724}
725
726/// Classify a failure to open: a symlink in the final position (the canonical
727/// path was swapped for a link after it was checked) is not a regular file.
728#[cfg(any(target_os = "linux", windows))]
729fn open_error(shown: &str, error: std::io::Error) -> TreeError {
730    if crate::error::is_symlink_loop(&error) {
731        not_regular(shown)
732    } else {
733        TreeError::from_io(shown, error)
734    }
735}
736
737/// A failure to learn the path of a handle. A missing descriptor link (no
738/// `/proc`) is an operating-system failure, never absence of the file.
739#[cfg(any(target_os = "linux", windows))]
740fn link_read_error(shown: &str, source: std::io::Error) -> TreeError {
741    TreeError::Io {
742        path: shown.to_owned(),
743        source,
744    }
745}
746
747/// The path the system gives for an open handle must lie under the root.
748#[cfg(any(target_os = "linux", windows))]
749fn verify_handle_path(root: &Path, handle_path: &Path, shown: &str) -> Result<(), TreeError> {
750    if handle_path.starts_with(root) {
751        Ok(())
752    } else {
753        Err(outside(shown))
754    }
755}
756
757/// Linux: the kernel's own path for an open handle must lie under the root.
758///
759/// `handle_link` is `/proc/self/fd/<fd>`. This reads what the handle really
760/// is, so no rename of a path can change the answer.
761#[cfg(target_os = "linux")]
762fn verify_linux_link(root: &Path, handle_link: &Path, shown: &str) -> Result<(), TreeError> {
763    let target = std::fs::read_link(handle_link).map_err(|e| link_read_error(shown, e))?;
764    verify_handle_path(root, &target, shown)
765}
766
767/// `/proc/self/fd/<fd>`: the kernel's own path for an open handle.
768#[cfg(target_os = "linux")]
769fn descriptor_path(handle: &impl std::os::fd::AsRawFd) -> PathBuf {
770    PathBuf::from(format!("/proc/self/fd/{}", handle.as_raw_fd()))
771}
772
773/// Read at most `max_bytes` raw bytes from a verified handle.
774fn read_capped(source: impl Read, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
775    let mut bytes = Vec::new();
776    source
777        .take(max_bytes.saturating_add(1))
778        .read_to_end(&mut bytes)
779        .map_err(|e| TreeError::from_io(shown, e))?;
780    if u64::try_from(bytes.len()).map_or(true, |len| len > max_bytes) {
781        return Err(TreeError::TooLarge {
782            path: shown.to_owned(),
783            limit: max_bytes,
784        });
785    }
786    Ok(bytes)
787}
788
789fn text(bytes: Vec<u8>, path: &RelPath) -> Result<String, TreeError> {
790    String::from_utf8(bytes).map_err(|_| TreeError::NotUtf8 {
791        path: path.to_string(),
792    })
793}
794
795fn outside(shown: &str) -> TreeError {
796    TreeError::OutsideRoot {
797        path: shown.to_owned(),
798    }
799}
800
801fn not_regular(shown: &str) -> TreeError {
802    TreeError::NotRegular {
803        path: shown.to_owned(),
804    }
805}
806
807/// Unix: the identity of a file is the device and inode of its handle.
808#[cfg(unix)]
809fn device_identity(metadata: &Metadata) -> FileId {
810    use std::os::unix::fs::MetadataExt as _;
811    FileId::from_device(metadata.dev(), metadata.ino())
812}
813
814/// Windows: refuse a path with a segment that Windows would not read as the
815/// name it spells. Such a path is never canonicalised.
816#[cfg(windows)]
817fn refuse_windows_names(path: &RelPath, shown: &str) -> Result<(), TreeError> {
818    if path.segments().any(is_ambiguous_on_windows) {
819        Err(outside(shown))
820    } else {
821        Ok(())
822    }
823}
824
825/// Elsewhere every segment names itself.
826#[cfg(not(windows))]
827#[expect(
828    clippy::unnecessary_wraps,
829    reason = "the signature is shared with Windows, where the call can refuse"
830)]
831fn refuse_windows_names(_path: &RelPath, _shown: &str) -> Result<(), TreeError> {
832    Ok(())
833}
834
835/// True for a segment that is a reserved device name, bare or with any
836/// extension and in any case; for one that ends in a dot or a space, which
837/// Windows strips; and for one that holds a colon, which names an alternate
838/// data stream. A `..` segment climbs and names no file.
839#[cfg(windows)]
840fn is_ambiguous_on_windows(segment: &str) -> bool {
841    if segment == ".." {
842        return false;
843    }
844    if segment.ends_with(['.', ' ']) || segment.contains(':') {
845        return true;
846    }
847    let stem = segment
848        .split('.')
849        .next()
850        .unwrap_or(segment)
851        .trim_end_matches(' ')
852        .to_ascii_uppercase();
853    let numbered = |prefix: &str| {
854        stem.strip_prefix(prefix).is_some_and(|digit| {
855            matches!(
856                digit,
857                "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
858            )
859        })
860    };
861    matches!(
862        stem.as_str(),
863        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
864    ) || numbered("COM")
865        || numbered("LPT")
866}