Skip to main content

exarch_core/security/
fs_view.rs

1//! Filesystem view used by path, symlink and hardlink validation.
2//!
3//! Extraction validates against the real destination ([`HostFs`]); `verify`
4//! validates against an in-memory model of what extraction would create
5//! ([`VirtualTree`]) so that an untrusted archive never causes a write.
6//!
7//! # Limitations
8//!
9//! [`VirtualTree`] models only the archive's own entries. It cannot account
10//! for files, directories or links already present in the extraction
11//! destination, so a verification PASS does not guarantee that extraction into
12//! a non-empty destination succeeds. Further differences from the host
13//! filesystem:
14//!
15//! - symlink chains are cut off after [`MAX_SYMLINK_HOPS`] hops, a per-OS
16//!   constant that matches `std::fs::canonicalize` on the supported hosts
17//!   (macOS 33, glibc 40, musl 39, Windows 63 unverified, other Unix 32); a
18//!   different filesystem or kernel configuration can still disagree;
19//! - name lengths use per-OS limits ([`MAX_COMPONENT_LEN`], [`MAX_PATH_LEN`]:
20//!   Linux 4095, macOS and other Unix 1023, Windows 32767 UTF-16 units); a
21//!   symlink target is checked against [`MAX_SYMLINK_TARGET_LEN`] only (Windows
22//!   4091 UTF-16 units). A filesystem with tighter limits can still refuse a
23//!   name the model accepts;
24//! - on macOS names are compared after NFD and a per-character
25//!   upper/lower/upper case fold, on Windows after the same fold without
26//!   normalisation, and elsewhere exactly. The fold is an approximation of the
27//!   host's table: two names it merges but the host keeps apart (for example
28//!   `i` and dotless `ı`) are reported as a name collision, never silently
29//!   merged;
30//! - [`PathModel::Portable`] replaces the per-OS rules with the strictest of
31//!   them on every host (see its docs). `zip.rs` still strips drive-relative
32//!   names under `allow_absolute_paths` by the host's rules, so a Portable sink
33//!   on Linux refuses what Windows would strip: it fails closed;
34//! - a path that leaves the root and re-enters it is reported as an escape
35//!   (`Containment::Escapes`), although the host would resolve it inside;
36//! - only extraction that skips an existing entry is modelled; with overwrite
37//!   semantics extraction keeps the last entry at a path, which cannot be
38//!   modelled here;
39//! - the first entry at a path wins, mirroring extraction that skips an
40//!   existing file; the one exception is a symlink over an earlier file, which
41//!   replaces it so that verification stays conservative for extraction that
42//!   overwrites existing files.
43
44use std::borrow::Cow;
45use std::collections::HashMap;
46use std::collections::VecDeque;
47use std::ffi::OsStr;
48use std::ffi::OsString;
49use std::io;
50use std::path::Component;
51use std::path::Path;
52use std::path::PathBuf;
53
54use crate::ArchiveError;
55use crate::QuotaResource;
56use crate::SecurityConfig;
57use crate::closed_enum::closed_enum;
58use crate::types::DestDir;
59
60/// Maximum number of symlinks followed while resolving a single path, as the
61/// host's `realpath` allows it.
62#[cfg(target_os = "macos")]
63pub const MAX_SYMLINK_HOPS: usize = 33;
64
65/// Maximum number of symlinks followed while resolving a single path, as the
66/// host's `realpath` allows it.
67#[cfg(all(target_os = "linux", target_env = "musl"))]
68pub const MAX_SYMLINK_HOPS: usize = 39;
69
70/// Maximum number of symlinks followed while resolving a single path, as the
71/// host's `realpath` allows it.
72#[cfg(all(target_os = "linux", not(target_env = "musl")))]
73pub const MAX_SYMLINK_HOPS: usize = 40;
74
75/// Maximum number of symlinks followed while resolving a single path, as the
76/// host's `realpath` allows it.
77#[cfg(target_os = "windows")]
78pub const MAX_SYMLINK_HOPS: usize = 63;
79
80/// Maximum number of symlinks followed while resolving a single path. A low
81/// guess can only turn a PASS into a false FAIL.
82#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
83pub const MAX_SYMLINK_HOPS: usize = 32;
84
85/// Longest single path component the host accepts (`NAME_MAX`), in bytes, or
86/// in UTF-16 units on Windows.
87pub const MAX_COMPONENT_LEN: usize = 255;
88
89/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
90/// bytes.
91#[cfg(target_os = "linux")]
92pub const MAX_PATH_LEN: usize = 4095;
93
94/// Longest relative path the host accepts, in UTF-16 units.
95///
96/// 32767 is the documented limit of an extended-length path. A symlink target
97/// is bounded much lower, see [`MAX_SYMLINK_TARGET_LEN`].
98#[cfg(target_os = "windows")]
99pub const MAX_PATH_LEN: usize = 32767;
100
101/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
102/// bytes. A low guess can only turn a PASS into a false FAIL.
103#[cfg(not(any(target_os = "linux", target_os = "windows")))]
104pub const MAX_PATH_LEN: usize = 1023;
105
106/// Longest symlink target the host accepts, in UTF-16 units.
107///
108/// `CreateSymbolicLinkW` stores the substitute and print names in a 16 KiB
109/// reparse buffer after a 20-byte header. Extraction only creates relative
110/// targets (a `Prefix` or `RootDir` component is rejected), where both names
111/// are equal, so `2 * 2n <= 16384 - 20` gives `n <= 4091`. Absolute targets
112/// (`\??\` prefix) would allow fewer units but are never created.
113#[cfg(target_os = "windows")]
114pub const MAX_SYMLINK_TARGET_LEN: usize = 4091;
115
116/// Longest symlink target the host accepts (`PATH_MAX` less the terminator),
117/// in bytes.
118#[cfg(not(target_os = "windows"))]
119pub const MAX_SYMLINK_TARGET_LEN: usize = MAX_PATH_LEN;
120
121/// Longest symlink target in bytes that can pass the
122/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
123/// stored as bytes.
124///
125/// On Windows a UTF-16 unit takes at most 3 UTF-8 bytes, so a byte cap never
126/// rejects a target the unit check accepts.
127#[cfg(target_os = "windows")]
128pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN * 3;
129
130/// Longest symlink target in bytes that can pass the
131/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
132/// stored as bytes.
133#[cfg(not(target_os = "windows"))]
134pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN;
135
136closed_enum! {
137    /// The kind of link a target belongs to; the host limits them differently.
138    ///
139    /// # Examples
140    ///
141    /// ```
142    /// use exarch_core::LinkKind;
143    ///
144    /// assert_eq!(LinkKind::Symlink.as_str(), "symlink");
145    /// ```
146    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
147    #[non_exhaustive]
148    pub enum LinkKind {
149        /// A symbolic link; `symlink(2)` bounds only the whole target
150        Symlink => "symlink",
151        /// A hard link; the target is resolved as a path, so components count too
152        Hardlink => "hardlink",
153    }
154}
155
156closed_enum! {
157    /// The path semantics an [`EntrySink`](crate::EntrySink) is validated
158    /// against.
159    ///
160    /// `Host` applies the rules of the platform running the extraction. On a
161    /// Windows host that means the component rules of `Portable` (every
162    /// character Windows refuses, reserved names, `:`, trailing dot or space);
163    /// on other hosts component names are not restricted.
164    /// `Portable` applies the strictest rules of every supported platform, on
165    /// every host, for a sink whose storage is read elsewhere:
166    ///
167    /// - names fold as on macOS (canonical decomposition plus a case fold), so
168    ///   two spellings of one name are one name;
169    /// - a component with a backslash, one of `<>"|?*`, a control character, a
170    ///   `:`, a trailing dot or space, a reserved Windows device name (unless
171    ///   `windows_reserved_names` is allowed) or bytes that are not UTF-8 is
172    ///   refused;
173    /// - a component is at most 255 and a path or symlink target at most 1023,
174    ///   counted in UTF-8 bytes and in UTF-16 units alike, and a symlink chain
175    ///   is cut off after 32 hops.
176    ///
177    /// On a Windows host `\` already separates the components of an entry
178    /// name when the path is parsed, so it is split there and not refused as a
179    /// backslash; every other host refuses it. Not modelled: 8.3 short names
180    /// and the legacy 260-unit `MAX_PATH`.
181    ///
182    /// # Examples
183    ///
184    /// ```
185    /// use exarch_core::PathModel;
186    ///
187    /// assert_eq!(PathModel::default(), PathModel::Host);
188    /// assert_eq!(PathModel::Portable.as_str(), "portable");
189    /// ```
190    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
191    #[non_exhaustive]
192    pub enum PathModel {
193        /// The rules of the platform running the extraction.
194        #[default]
195        Host => "host",
196        /// The strictest rules of every supported platform.
197        Portable => "portable",
198    }
199}
200
201/// The length limits of a [`PathModel`].
202#[derive(Debug, Clone, Copy)]
203struct NameLimits {
204    component: usize,
205    path: usize,
206    symlink_target: usize,
207    hops: usize,
208}
209
210impl PathModel {
211    const fn limits(self) -> NameLimits {
212        match self {
213            Self::Host => NameLimits {
214                component: MAX_COMPONENT_LEN,
215                path: MAX_PATH_LEN,
216                symlink_target: MAX_SYMLINK_TARGET_LEN,
217                hops: MAX_SYMLINK_HOPS,
218            },
219            Self::Portable => NameLimits {
220                component: 255,
221                path: 1023,
222                symlink_target: 1023,
223                hops: 32,
224            },
225        }
226    }
227
228    fn name_len(self, name: &OsStr) -> usize {
229        match self {
230            Self::Host => name_len(name),
231            Self::Portable => portable_name_len(name),
232        }
233    }
234
235    /// Rejects entry names this model refuses with `ENAMETOOLONG`.
236    ///
237    /// # Errors
238    ///
239    /// Returns an error if the path or any of its components is too long.
240    pub(crate) fn check_name_lengths(self, path: &Path) -> io::Result<()> {
241        let limits = self.limits();
242        let too_long = self.name_len(path.as_os_str()) > limits.path
243            || path
244                .components()
245                .any(|c| self.name_len(c.as_os_str()) > limits.component);
246        if too_long {
247            return Err(name_too_long());
248        }
249        Ok(())
250    }
251
252    /// Rejects a link target this model refuses with `ENAMETOOLONG`.
253    ///
254    /// # Errors
255    ///
256    /// Returns an error if the target is too long for `kind`.
257    pub(crate) fn check_link_target_length(self, target: &Path, kind: LinkKind) -> io::Result<()> {
258        match kind {
259            LinkKind::Symlink
260                if self.name_len(target.as_os_str()) > self.limits().symlink_target =>
261            {
262                Err(name_too_long())
263            }
264            LinkKind::Symlink => Ok(()),
265            LinkKind::Hardlink => self.check_name_lengths(target),
266        }
267    }
268}
269
270/// A name's length in UTF-8 bytes, which is never below its length in UTF-16
271/// units, so one limit holds in both.
272fn portable_name_len(name: &OsStr) -> usize {
273    name.to_string_lossy().len()
274}
275
276#[cfg(windows)]
277fn name_len(name: &OsStr) -> usize {
278    std::os::windows::ffi::OsStrExt::encode_wide(name).count()
279}
280
281#[cfg(not(windows))]
282fn name_len(name: &OsStr) -> usize {
283    name.as_encoded_bytes().len()
284}
285
286/// Rejects entry names the host would refuse with `ENAMETOOLONG`.
287///
288/// # Errors
289///
290/// Returns an error if the path or any of its components is too long.
291pub fn check_name_lengths(path: &Path) -> io::Result<()> {
292    PathModel::Host.check_name_lengths(path)
293}
294
295/// Rejects a link target the host would refuse with `ENAMETOOLONG`.
296///
297/// A symlink target is checked against [`MAX_SYMLINK_TARGET_LEN`] only, as
298/// `symlink(2)` does; a hardlink target is checked like an entry name.
299///
300/// # Errors
301///
302/// Returns an error if the target is too long for `kind`.
303pub fn check_link_target_length(target: &Path, kind: LinkKind) -> io::Result<()> {
304    PathModel::Host.check_link_target_length(target, kind)
305}
306
307/// The error for a name beyond the host's limits.
308#[must_use]
309pub fn name_too_long() -> io::Error {
310    io::Error::new(io::ErrorKind::InvalidFilename, "file name too long")
311}
312
313/// A root directory that a validator resolves entry paths against.
314///
315/// Implemented only by [`DestDir`] (the real destination) and [`VirtualRoot`]
316/// (the in-memory model), and tied to its [`FsView`] through
317/// [`FsView::Root`], so a root can never be paired with the wrong view.
318pub trait ModelRoot {
319    /// The root as a path.
320    fn as_path(&self) -> &Path;
321}
322
323impl ModelRoot for DestDir {
324    fn as_path(&self) -> &Path {
325        Self::as_path(self)
326    }
327}
328
329#[cfg(windows)]
330const VIRTUAL_ROOT: &str = r"C:\exarch-virtual-root";
331#[cfg(not(windows))]
332const VIRTUAL_ROOT: &str = "/exarch-virtual-root";
333
334/// The root of a [`VirtualTree`]: a fixed path that is never touched on disk.
335///
336/// Distinct from [`DestDir`], which promises an existing, canonical, writable
337/// directory, so a virtual root can never reach a helper that writes to the
338/// host filesystem.
339#[derive(Debug, Clone, PartialEq, Eq)]
340pub struct VirtualRoot(PathBuf);
341
342impl VirtualRoot {
343    /// Creates the fixed virtual root.
344    #[must_use]
345    pub fn new() -> Self {
346        Self(PathBuf::from(VIRTUAL_ROOT))
347    }
348
349    #[cfg(test)]
350    pub(crate) fn at(path: &str) -> Self {
351        Self(PathBuf::from(path))
352    }
353}
354
355impl Default for VirtualRoot {
356    fn default() -> Self {
357        Self::new()
358    }
359}
360
361impl ModelRoot for VirtualRoot {
362    fn as_path(&self) -> &Path {
363        &self.0
364    }
365}
366
367/// Where a canonicalized path ended up relative to the root of its view.
368#[derive(Debug, Clone, PartialEq, Eq)]
369pub enum Containment {
370    /// Inside the root, at this canonical path.
371    Within(PathBuf),
372    /// Outside the root, or not provably inside it.
373    Escapes,
374}
375
376/// Filesystem probes needed while validating archive entries.
377pub trait FsView {
378    /// The root type a validator resolves paths against in this view.
379    type Root: ModelRoot;
380
381    /// The path semantics validation applies in this view.
382    fn path_model(&self) -> PathModel;
383
384    /// Returns `true` if `path` exists, following symlinks.
385    fn exists(&self, path: &Path) -> bool;
386
387    /// Returns `true` if `path` exists and is a directory, following symlinks.
388    fn is_dir(&self, path: &Path) -> bool;
389
390    /// Returns whether `path` itself is a symlink, without following it.
391    ///
392    /// # Errors
393    ///
394    /// Returns an error if `path` cannot be inspected (for example, it does
395    /// not exist).
396    fn is_symlink(&self, path: &Path) -> io::Result<bool>;
397
398    /// Resolves `path` to its canonical form and says whether that lies inside
399    /// `root`.
400    ///
401    /// # Errors
402    ///
403    /// Returns an error if a component is missing or the chain cannot be
404    /// resolved.
405    fn canonicalize(&self, path: &Path, root: &Self::Root) -> io::Result<Containment>;
406}
407
408/// Case-insensitive path prefix check for macOS/Windows.
409///
410/// On case-insensitive filesystems (macOS, Windows), attackers can bypass
411/// path validation using different case (e.g., `../../USERS/victim/.ssh/`).
412///
413/// Compares `path` and `base` component-by-component rather than as raw
414/// strings, so a shared name prefix without a component boundary (e.g. base
415/// `/tmp/dest` against sibling `/tmp/destevil`) is correctly rejected. See
416/// GHSA-wcmx-7f9h-5mv5.
417#[cfg(any(target_os = "macos", target_os = "windows"))]
418pub fn paths_start_with(path: &Path, base: &Path) -> bool {
419    let mut path_components = path.components();
420    for base_component in base.components() {
421        let Some(path_component) = path_components.next() else {
422            return false;
423        };
424        let path_str = path_component.as_os_str().to_string_lossy().to_lowercase();
425        let base_str = base_component.as_os_str().to_string_lossy().to_lowercase();
426        if path_str != base_str {
427            return false;
428        }
429    }
430    true
431}
432
433/// Case-sensitive path prefix check for Unix (not macOS).
434#[cfg(not(any(target_os = "macos", target_os = "windows")))]
435pub fn paths_start_with(path: &Path, base: &Path) -> bool {
436    path.starts_with(base)
437}
438
439/// The real filesystem.
440#[derive(Debug, Clone, Copy, Default)]
441pub struct HostFs;
442
443impl FsView for HostFs {
444    type Root = DestDir;
445
446    fn path_model(&self) -> PathModel {
447        PathModel::Host
448    }
449
450    fn exists(&self, path: &Path) -> bool {
451        path.exists()
452    }
453
454    fn is_dir(&self, path: &Path) -> bool {
455        path.is_dir()
456    }
457
458    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
459        std::fs::symlink_metadata(path).map(|m| m.file_type().is_symlink())
460    }
461
462    fn canonicalize(&self, path: &Path, root: &DestDir) -> io::Result<Containment> {
463        let canonical = std::fs::canonicalize(path)?;
464        Ok(if paths_start_with(&canonical, root.as_path()) {
465            Containment::Within(canonical)
466        } else {
467            Containment::Escapes
468        })
469    }
470}
471
472/// How two colliding names differ, which sets how serious the collision is.
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474pub enum CollisionKind {
475    /// Both are directories and neither holds anything in the archive, so the
476    /// merge changes nothing
477    Directories,
478    /// Both are directories and at least one holds entries, which then land in
479    /// one directory and can overwrite each other
480    DirectoriesWithContents,
481    /// Both are files, so one silently replaces or is skipped for the other
482    Files,
483    /// The kinds differ or a symlink is involved, so later entries can
484    /// resolve differently than the archive intends
485    Mixed,
486}
487
488/// Two entry names that differ exactly but are one name on the host.
489#[derive(Debug, Clone, PartialEq, Eq)]
490pub struct NameCollision {
491    /// Path of the node that was there first
492    pub existing: PathBuf,
493    /// Path of the entry that hit it
494    pub incoming: PathBuf,
495    /// How the two differ
496    pub kind: CollisionKind,
497}
498
499impl CollisionKind {
500    fn of(existing: &Node, incoming: &Node, existing_has_contents: bool) -> Self {
501        match (existing, incoming) {
502            (Node::Dir, Node::Dir) if existing_has_contents => Self::DirectoriesWithContents,
503            (Node::Dir, Node::Dir) => Self::Directories,
504            (Node::File, Node::File) => Self::Files,
505            _ => Self::Mixed,
506        }
507    }
508}
509
510/// What already occupies a path an insert collided with.
511#[derive(Debug, Clone, Copy, PartialEq, Eq)]
512pub enum Occupant {
513    /// A regular file or materialized hardlink.
514    File,
515    /// A directory.
516    Directory,
517    /// A symlink, readable or opaque.
518    Symlink,
519}
520
521impl Occupant {
522    /// The noun used in reports.
523    pub(crate) const fn noun(self) -> &'static str {
524        match self {
525            Self::File => "file",
526            Self::Directory => "directory",
527            Self::Symlink => "symlink",
528        }
529    }
530
531    /// The text of a refusal to replace this occupant at `rel`, shared by the
532    /// host extraction error and the `verify` model so both name the entry and
533    /// the occupant in the same words.
534    pub(crate) fn refusal(self, rel: &Path) -> String {
535        format!(
536            "refusing to replace the existing {} at {}",
537            self.noun(),
538            rel.components().collect::<PathBuf>().display()
539        )
540    }
541}
542
543/// A failed [`VirtualTree::try_insert`].
544#[derive(Debug)]
545pub struct Conflict {
546    /// The error `insert` would report.
547    pub(crate) error: io::Error,
548    /// `None` when the failure is in the parent chain, not at the path itself.
549    pub(crate) occupant: Option<Occupant>,
550}
551
552impl Conflict {
553    pub(crate) fn already_exists(occupant: Occupant) -> Self {
554        Self {
555            error: io::Error::from(io::ErrorKind::AlreadyExists),
556            occupant: Some(occupant),
557        }
558    }
559
560    /// [`already_exists`](Self::already_exists) whose error names `rel` and
561    /// the occupant.
562    pub(crate) fn already_exists_at(occupant: Occupant, rel: &Path) -> Self {
563        Self {
564            error: io::Error::new(io::ErrorKind::AlreadyExists, occupant.refusal(rel)),
565            occupant: Some(occupant),
566        }
567    }
568}
569
570impl From<io::Error> for Conflict {
571    fn from(error: io::Error) -> Self {
572        Self {
573            error,
574            occupant: None,
575        }
576    }
577}
578
579/// Bound on the names a [`VirtualTree`] stores.
580///
581/// A name is charged when a node is added and when a differently spelled
582/// alias of a node is remembered, whatever the kind of the entry, so a flood
583/// of directory entries or case variants cannot grow the tree without limit.
584#[derive(Debug, Clone, Copy, PartialEq, Eq)]
585pub struct NodeBudget {
586    max: usize,
587    used: usize,
588}
589
590impl NodeBudget {
591    /// A budget of `max_file_count * max_path_depth + 1` names: enough for
592    /// `max_file_count` files, each at the deepest allowed path with no name
593    /// shared. Explicit directory entries and aliases spend it too although
594    /// `max_file_count` does not count directories, so an archive of many
595    /// directories can exhaust it while within the file limit; raise
596    /// `max_file_count` or `max_path_depth` to allow more. Unbounded if either
597    /// is `usize::MAX`.
598    #[must_use]
599    pub fn from_config<State>(config: &SecurityConfig<State>) -> Self {
600        let max = if config.max_file_count == usize::MAX || config.max_path_depth == usize::MAX {
601            usize::MAX
602        } else {
603            config
604                .max_file_count
605                .saturating_mul(config.max_path_depth)
606                .saturating_add(1)
607        };
608        Self { max, used: 0 }
609    }
610
611    #[cfg(test)]
612    pub(crate) const fn unbounded() -> Self {
613        Self {
614            max: usize::MAX,
615            used: 0,
616        }
617    }
618
619    #[cfg(test)]
620    pub(crate) const fn with_max(max: usize) -> Self {
621        Self { max, used: 0 }
622    }
623
624    fn charge(&mut self) -> Result<(), NodeBudgetExceeded> {
625        if self.used >= self.max {
626            return Err(NodeBudgetExceeded { max: self.max });
627        }
628        self.used += 1;
629        Ok(())
630    }
631}
632
633/// A [`NodeBudget`] that ran out.
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635pub struct NodeBudgetExceeded {
636    max: usize,
637}
638
639impl From<NodeBudgetExceeded> for ArchiveError {
640    fn from(exceeded: NodeBudgetExceeded) -> Self {
641        Self::QuotaExceeded {
642            resource: QuotaResource::TreeNodes { max: exceeded.max },
643        }
644    }
645}
646
647/// Whether a [`VirtualTree`] keeps the name collisions it detects.
648///
649/// `verify` reports them; a sink only needs the merged path, so recording
650/// there would grow memory with every case variant for nothing.
651#[derive(Debug, Clone, Copy, PartialEq, Eq)]
652pub enum CollisionRecording {
653    /// Keep collisions for [`VirtualTree::take_collisions`] and
654    /// [`VirtualTree::take_empty_merges`].
655    Record,
656    /// Merge the names and forget that they collided.
657    Discard,
658}
659
660/// Why a [`VirtualTree`] refused to place a node.
661#[derive(Debug)]
662pub enum PlaceError {
663    /// Extraction would fail or change what a path resolves to.
664    Conflict(Conflict),
665    /// The tree is full.
666    Budget(NodeBudgetExceeded),
667}
668
669impl PlaceError {
670    #[cfg(test)]
671    pub(crate) fn into_conflict(self) -> Conflict {
672        match self {
673            Self::Conflict(conflict) => conflict,
674            Self::Budget(exceeded) => panic!("unexpected budget error: {exceeded:?}"),
675        }
676    }
677}
678
679impl From<Conflict> for PlaceError {
680    fn from(conflict: Conflict) -> Self {
681        Self::Conflict(conflict)
682    }
683}
684
685impl From<io::Error> for PlaceError {
686    fn from(error: io::Error) -> Self {
687        Self::Conflict(error.into())
688    }
689}
690
691impl From<NodeBudgetExceeded> for PlaceError {
692    fn from(exceeded: NodeBudgetExceeded) -> Self {
693        Self::Budget(exceeded)
694    }
695}
696
697type FoldFn = for<'a> fn(&'a OsStr) -> Cow<'a, OsStr>;
698
699/// The kind of a node in the in-memory tree.
700#[derive(Debug, Clone, PartialEq, Eq)]
701pub enum Node {
702    /// A directory.
703    Dir,
704    /// A regular file or materialized hardlink.
705    File,
706    /// A symlink with its target exactly as stored in the archive.
707    Symlink(PathBuf),
708    /// A symlink whose target was not read, so nothing can be resolved through
709    /// it: it exists, but a path that runs through it or lands on it while
710    /// being resolved is an error.
711    OpaqueSymlink,
712}
713
714#[derive(Debug)]
715struct TreeNode {
716    kind: Node,
717    /// The component exactly as the archive spells it.
718    name: OsString,
719    /// The directory holding this node; the root is its own parent.
720    parent: usize,
721    /// Only populated for directories; every spelling seen so far (the node's
722    /// own and its aliases) mapped to the child, so a repeated spelling is
723    /// found without folding it.
724    children: HashMap<OsString, usize>,
725    /// Folded component to child; empty on hosts that compare names exactly.
726    folded: HashMap<OsString, usize>,
727    /// Pairs of spellings of this directory that merged while it was empty: if
728    /// it later gains an entry the merge stops being harmless.
729    empty_merges: Vec<(PathBuf, PathBuf)>,
730}
731
732impl TreeNode {
733    fn new(kind: Node, name: &OsStr, parent: usize) -> Self {
734        Self {
735            kind,
736            name: name.to_os_string(),
737            parent,
738            children: HashMap::new(),
739            folded: HashMap::new(),
740            empty_merges: Vec::new(),
741        }
742    }
743}
744
745const ROOT: usize = 0;
746
747enum Resolved {
748    Inside { rel: PathBuf, id: usize },
749    Outside,
750}
751
752/// Where an insert put its node.
753struct Landed {
754    parent: usize,
755    /// The node that already held the name, if any.
756    existing: Option<usize>,
757}
758
759/// A child found by name.
760#[derive(Clone, Copy)]
761struct Found {
762    id: usize,
763    /// Found only through the fold: the archive spells it differently.
764    alias: bool,
765}
766
767/// In-memory model of the destination directory built from archive entries.
768///
769/// Stored as a per-directory component trie, so a lookup or insert costs
770/// O(bytes of the path) regardless of how many entries share a prefix. A name
771/// is folded only the first time it is seen; repeats, such as the parents of
772/// every entry in a directory, hit the exact-spelling map.
773///
774/// Every name it stores is charged to a [`NodeBudget`].
775pub struct VirtualTree {
776    root: PathBuf,
777    nodes: Vec<TreeNode>,
778    model: PathModel,
779    fold: FoldFn,
780    budget: NodeBudget,
781    recording: CollisionRecording,
782    collisions: Vec<NameCollision>,
783    /// Directories holding at least one empty merge.
784    empty_merge_nodes: Vec<usize>,
785}
786
787impl VirtualTree {
788    /// Creates an empty tree rooted at `root` that applies `model`.
789    pub fn new(
790        root: &VirtualRoot,
791        model: PathModel,
792        budget: NodeBudget,
793        recording: CollisionRecording,
794    ) -> Self {
795        let fold = match model {
796            PathModel::Host => fold,
797            PathModel::Portable => portable_fold,
798        };
799        Self::build(root, model, fold, budget, recording)
800    }
801
802    #[cfg(test)]
803    pub(crate) fn for_test(root: &VirtualRoot) -> Self {
804        Self::with_fold(root, fold)
805    }
806
807    #[cfg(test)]
808    pub(crate) fn with_fold(root: &VirtualRoot, fold: FoldFn) -> Self {
809        Self::build(
810            root,
811            PathModel::Host,
812            fold,
813            NodeBudget::unbounded(),
814            CollisionRecording::Record,
815        )
816    }
817
818    fn build(
819        root: &VirtualRoot,
820        model: PathModel,
821        fold: FoldFn,
822        budget: NodeBudget,
823        recording: CollisionRecording,
824    ) -> Self {
825        Self {
826            root: root.as_path().to_path_buf(),
827            nodes: vec![TreeNode::new(Node::Dir, OsStr::new(""), ROOT)],
828            model,
829            fold,
830            budget,
831            recording,
832            collisions: Vec::new(),
833            empty_merge_nodes: Vec::new(),
834        }
835    }
836
837    /// Records `node` at `rel` (relative to the root), creating missing
838    /// parents as directories and following in-root symlinked parents the way
839    /// `create_dir_all` does.
840    ///
841    /// Names that differ exactly but fold to one key are one name on the host.
842    /// Each such pair is recorded once as a [`NameCollision`] (see
843    /// [`take_collisions`](Self::take_collisions)) and then handled like an
844    /// exact repeat, so a merge is never silent.
845    ///
846    /// The first node at a path wins, matching extraction that skips an
847    /// existing entry. A symlink over a file is ambiguous (extraction skips
848    /// it by default but replaces the file when overwriting): the file is
849    /// replaced so later entries are checked against the riskier tree, and an
850    /// error is returned so the archive is never reported as safe. A symlink
851    /// over a directory or a symlink with a different target is refused the
852    /// same way, but the existing node stays; a symlink with the same target is
853    /// an unchanged duplicate.
854    ///
855    /// # Errors
856    ///
857    /// Returns a conflict where extraction can fail: a parent that is a file or
858    /// a dangling symlink, a parent chain that loops or leaves the root, a
859    /// directory entry over an existing non-directory, a symlink over an
860    /// earlier file, directory or symlink with another target, or a file over
861    /// an earlier directory (`IsADirectory`) or symlink.
862    ///
863    /// A failure also names what already occupies the path, so a caller can
864    /// tell what overwriting would do. A tree that is out of budget refuses
865    /// with [`PlaceError::Budget`].
866    pub(crate) fn try_insert(&mut self, rel: &Path, node: Node) -> Result<(), PlaceError> {
867        self.insert_node(rel, node).map(drop)
868    }
869
870    /// [`try_insert`](Self::try_insert) that also returns where the node
871    /// landed: the path relative to the root with every symlinked parent
872    /// resolved and every component spelled as the tree first stored it, so two
873    /// spellings of one name give one path.
874    pub(crate) fn place(&mut self, rel: &Path, node: Node) -> Result<PathBuf, PlaceError> {
875        Ok(self
876            .insert_node(rel, node)?
877            .map_or_else(PathBuf::new, |landed| {
878                let leaf = landed.existing.map_or_else(
879                    || rel.file_name(),
880                    |id| Some(self.node(id).name.as_os_str()),
881                );
882                let mut resolved = self.path_of(landed.parent);
883                resolved.extend(leaf);
884                resolved
885            }))
886    }
887
888    /// The path of node `id` relative to the root, spelled by the stored names.
889    fn path_of(&self, mut id: usize) -> PathBuf {
890        let mut names = Vec::new();
891        while id != ROOT {
892            let node = self.node(id);
893            names.push(node.name.as_os_str());
894            id = node.parent;
895        }
896        names.into_iter().rev().collect()
897    }
898
899    fn insert_node(&mut self, rel: &Path, node: Node) -> Result<Option<Landed>, PlaceError> {
900        let Some(name) = rel.file_name() else {
901            return Ok(None);
902        };
903        let parent = self.ensure_dir(rel.parent().unwrap_or_else(|| Path::new("")))?;
904        let existing = self.lookup(parent, name);
905        if let Some(found) = existing {
906            self.settle_alias(parent, found, name, &node, rel, false)?;
907        }
908        let existing = existing.map(|f| f.id);
909        let outcome = match (existing, node) {
910            (None, node) => {
911                self.add_child(parent, name, node)?;
912                Ok(())
913            }
914            (Some(id), Node::Dir) => match self.node(id).kind {
915                Node::Dir => Ok(()),
916                Node::File => Err(Conflict::already_exists_at(Occupant::File, rel)),
917                Node::OpaqueSymlink => Err(Conflict::already_exists_at(Occupant::Symlink, rel)),
918                Node::Symlink(_) => {
919                    if self.resolves_to_dir(&self.root.join(rel)) {
920                        Ok(())
921                    } else {
922                        Err(Conflict::already_exists_at(Occupant::Symlink, rel))
923                    }
924                }
925            },
926            (Some(id), node @ (Node::Symlink(_) | Node::OpaqueSymlink)) => {
927                match self.node(id).kind {
928                    Node::File => {
929                        self.node_mut(id).kind = node;
930                        Err(Conflict::already_exists(Occupant::File))
931                    }
932                    Node::Dir => Err(Conflict::already_exists(Occupant::Directory)),
933                    Node::Symlink(ref kept) if matches!(&node, Node::Symlink(t) if t == kept) => {
934                        Ok(())
935                    }
936                    Node::Symlink(_) | Node::OpaqueSymlink => {
937                        Err(Conflict::already_exists(Occupant::Symlink))
938                    }
939                }
940            }
941            (Some(id), Node::File) => match self.node(id).kind {
942                Node::File => Ok(()),
943                Node::Dir => Err(Conflict {
944                    error: io::Error::from(io::ErrorKind::IsADirectory),
945                    occupant: Some(Occupant::Directory),
946                }),
947                Node::Symlink(_) | Node::OpaqueSymlink => {
948                    Err(Conflict::already_exists(Occupant::Symlink))
949                }
950            },
951        };
952        outcome
953            .map(|()| Some(Landed { parent, existing }))
954            .map_err(PlaceError::Conflict)
955    }
956
957    #[cfg(test)]
958    pub(crate) fn insert(&mut self, rel: &Path, node: Node) -> io::Result<()> {
959        self.try_insert(rel, node)
960            .map_err(|err| err.into_conflict().error)
961    }
962
963    /// What an earlier entry left at `rel`, without following a link at the
964    /// path itself; a parent link is followed as extraction would.
965    pub(crate) fn occupant(&self, rel: &Path) -> Option<Occupant> {
966        let name = rel.file_name()?;
967        let parent = match self.resolve(&self.root.join(rel.parent()?)) {
968            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir => id,
969            _ => return None,
970        };
971        let found = self.lookup(parent, name)?;
972        Some(match self.node(found.id).kind {
973            Node::Dir => Occupant::Directory,
974            Node::File => Occupant::File,
975            Node::Symlink(_) | Node::OpaqueSymlink => Occupant::Symlink,
976        })
977    }
978
979    /// Returns `true` if `path` resolves, through symlinks, to a directory.
980    pub fn resolves_to_dir(&self, path: &Path) -> bool {
981        matches!(
982            self.resolve(path),
983            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir
984        )
985    }
986
987    /// Drains the name collisions recorded by inserts since the last call.
988    ///
989    /// Merges of directories that hold nothing are not included: they are
990    /// harmless unless an entry lands in the directory later, so they wait for
991    /// [`take_empty_merges`](Self::take_empty_merges).
992    pub(crate) fn take_collisions(&mut self) -> Vec<NameCollision> {
993        std::mem::take(&mut self.collisions)
994    }
995
996    /// Drains the merges of directories that are still empty.
997    pub(crate) fn take_empty_merges(&mut self) -> Vec<NameCollision> {
998        let nodes = std::mem::take(&mut self.empty_merge_nodes);
999        nodes
1000            .into_iter()
1001            .flat_map(|id| std::mem::take(&mut self.node_mut(id).empty_merges))
1002            .map(|(existing, incoming)| NameCollision {
1003                existing,
1004                incoming,
1005                kind: CollisionKind::Directories,
1006            })
1007            .collect()
1008    }
1009
1010    /// Handles a child found by a differently spelled name: remembers the
1011    /// spelling, so the pair is reported once, and records the collision.
1012    ///
1013    /// `incoming_has_contents` is true when the spelling is used as the parent
1014    /// of an entry, which makes a directory merge harmful at once; an empty
1015    /// merge is flagged so it is upgraded if the directory gains an entry.
1016    fn settle_alias(
1017        &mut self,
1018        parent: usize,
1019        found: Found,
1020        name: &OsStr,
1021        incoming_node: &Node,
1022        incoming: &Path,
1023        incoming_has_contents: bool,
1024    ) -> Result<(), NodeBudgetExceeded> {
1025        if !found.alias {
1026            return Ok(());
1027        }
1028        self.budget.charge()?;
1029        self.node_mut(parent)
1030            .children
1031            .insert(name.to_os_string(), found.id);
1032        if self.recording == CollisionRecording::Discard {
1033            return Ok(());
1034        }
1035        let existing = self.node(found.id);
1036        let has_contents = incoming_has_contents || !existing.children.is_empty();
1037        let kind = CollisionKind::of(&existing.kind, incoming_node, has_contents);
1038        let existing_path = incoming.with_file_name(&existing.name);
1039        if kind == CollisionKind::Directories {
1040            let node = self.node_mut(found.id);
1041            node.empty_merges
1042                .push((existing_path, incoming.to_path_buf()));
1043            self.empty_merge_nodes.push(found.id);
1044            return Ok(());
1045        }
1046        self.collisions.push(NameCollision {
1047            existing: existing_path,
1048            incoming: incoming.to_path_buf(),
1049            kind,
1050        });
1051        Ok(())
1052    }
1053
1054    fn node(&self, id: usize) -> &TreeNode {
1055        &self.nodes[id]
1056    }
1057
1058    fn node_mut(&mut self, id: usize) -> &mut TreeNode {
1059        &mut self.nodes[id]
1060    }
1061
1062    fn lookup(&self, parent: usize, name: &OsStr) -> Option<Found> {
1063        if self.model.name_len(name) > self.model.limits().component {
1064            return None;
1065        }
1066        let node = self.node(parent);
1067        if let Some(&id) = node.children.get(name) {
1068            return Some(Found { id, alias: false });
1069        }
1070        match (self.fold)(name) {
1071            Cow::Borrowed(_) => None,
1072            Cow::Owned(key) => node.folded.get(&key).map(|&id| Found { id, alias: true }),
1073        }
1074    }
1075
1076    fn child(&self, parent: usize, name: &OsStr) -> Option<usize> {
1077        self.lookup(parent, name).map(|found| found.id)
1078    }
1079
1080    /// Adds a node under `parent`.
1081    fn add_child(
1082        &mut self,
1083        parent: usize,
1084        name: &OsStr,
1085        kind: Node,
1086    ) -> Result<usize, NodeBudgetExceeded> {
1087        self.budget.charge()?;
1088        let id = self.nodes.len();
1089        self.nodes.push(TreeNode::new(kind, name, parent));
1090        let key = match (self.fold)(name) {
1091            Cow::Borrowed(_) => None,
1092            Cow::Owned(key) => Some(key),
1093        };
1094        let upgrade = {
1095            let parent_node = self.node_mut(parent);
1096            parent_node.children.insert(name.to_os_string(), id);
1097            if let Some(key) = key {
1098                parent_node.folded.insert(key, id);
1099            }
1100            std::mem::take(&mut parent_node.empty_merges)
1101        };
1102        for (existing, incoming) in upgrade {
1103            self.collisions.push(NameCollision {
1104                existing,
1105                incoming,
1106                kind: CollisionKind::DirectoriesWithContents,
1107            });
1108        }
1109        Ok(id)
1110    }
1111
1112    fn ensure_dir(&mut self, rel: &Path) -> Result<usize, PlaceError> {
1113        let mut current = ROOT;
1114        let mut walked = PathBuf::new();
1115        for component in rel.components() {
1116            let name = match component {
1117                Component::Normal(name) => name,
1118                Component::CurDir => continue,
1119                _ => return Err(io::Error::from(io::ErrorKind::InvalidInput).into()),
1120            };
1121            walked.push(name);
1122            current = match self.lookup(current, name) {
1123                None => self.add_child(current, name, Node::Dir)?,
1124                Some(found) => {
1125                    self.settle_alias(current, found, name, &Node::Dir, &walked, true)?;
1126                    match self.node(found.id).kind {
1127                        Node::Dir => found.id,
1128                        Node::File => {
1129                            return Err(io::Error::from(io::ErrorKind::NotADirectory).into());
1130                        }
1131                        Node::OpaqueSymlink => return Err(unread_target_error().into()),
1132                        Node::Symlink(_) => match self.resolve(&self.root.join(&walked))? {
1133                            Resolved::Inside { id, .. } if self.node(id).kind == Node::Dir => id,
1134                            Resolved::Inside { .. } => {
1135                                return Err(io::Error::from(io::ErrorKind::NotADirectory).into());
1136                            }
1137                            Resolved::Outside => {
1138                                return Err(
1139                                    io::Error::other("path leaves the extraction root").into()
1140                                );
1141                            }
1142                        },
1143                    }
1144                }
1145            };
1146        }
1147        Ok(current)
1148    }
1149
1150    fn resolve(&self, path: &Path) -> io::Result<Resolved> {
1151        let Ok(rel) = path.strip_prefix(&self.root) else {
1152            return Ok(Resolved::Outside);
1153        };
1154        let mut pending: VecDeque<Component<'_>> = rel.components().collect();
1155        let mut stack = vec![ROOT];
1156        let mut current = PathBuf::new();
1157        let mut hops = 0;
1158
1159        while let Some(component) = pending.pop_front() {
1160            match component {
1161                Component::CurDir => {}
1162                Component::ParentDir => {
1163                    if stack.len() == 1 {
1164                        return Ok(Resolved::Outside);
1165                    }
1166                    stack.pop();
1167                    current.pop();
1168                }
1169                Component::Normal(name) => {
1170                    let top = stack.last().copied().unwrap_or(ROOT);
1171                    let Some(id) = self.child(top, name) else {
1172                        return Err(io::Error::from(io::ErrorKind::NotFound));
1173                    };
1174                    match &self.node(id).kind {
1175                        Node::Dir => {
1176                            stack.push(id);
1177                            current.push(&self.node(id).name);
1178                        }
1179                        Node::File => {
1180                            if !pending.is_empty() {
1181                                return Err(io::Error::from(io::ErrorKind::NotADirectory));
1182                            }
1183                            stack.push(id);
1184                            current.push(&self.node(id).name);
1185                        }
1186                        Node::OpaqueSymlink => {
1187                            if !pending.is_empty() {
1188                                return Err(unread_target_error());
1189                            }
1190                            stack.push(id);
1191                            current.push(&self.node(id).name);
1192                        }
1193                        Node::Symlink(target) => {
1194                            hops += 1;
1195                            if hops > self.model.limits().hops {
1196                                return Err(io::Error::other("too many levels of symbolic links"));
1197                            }
1198                            if target.has_root()
1199                                || target.components().next().is_some_and(is_prefix)
1200                            {
1201                                return Ok(Resolved::Outside);
1202                            }
1203                            for part in target.components().rev() {
1204                                pending.push_front(part);
1205                            }
1206                        }
1207                    }
1208                }
1209                Component::RootDir | Component::Prefix(_) => {
1210                    return Ok(Resolved::Outside);
1211                }
1212            }
1213        }
1214        Ok(Resolved::Inside {
1215            rel: current,
1216            id: stack.last().copied().unwrap_or(ROOT),
1217        })
1218    }
1219}
1220
1221impl FsView for VirtualTree {
1222    type Root = VirtualRoot;
1223
1224    fn path_model(&self) -> PathModel {
1225        self.model
1226    }
1227
1228    fn exists(&self, path: &Path) -> bool {
1229        matches!(self.resolve(path), Ok(Resolved::Inside { .. }))
1230    }
1231
1232    fn is_dir(&self, path: &Path) -> bool {
1233        self.resolves_to_dir(path)
1234    }
1235
1236    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
1237        let not_found = || io::Error::from(io::ErrorKind::NotFound);
1238        let Ok(rel) = path.strip_prefix(&self.root) else {
1239            return Err(not_found());
1240        };
1241        let Some(name) = rel.file_name() else {
1242            return Ok(false);
1243        };
1244        let parent = self
1245            .root
1246            .join(rel.parent().unwrap_or_else(|| Path::new("")));
1247        let Resolved::Inside { id: parent, .. } = self.resolve(&parent)? else {
1248            return Err(not_found());
1249        };
1250        let id = self.child(parent, name).ok_or_else(not_found)?;
1251        Ok(matches!(
1252            self.node(id).kind,
1253            Node::Symlink(_) | Node::OpaqueSymlink
1254        ))
1255    }
1256
1257    fn canonicalize(&self, path: &Path, _: &VirtualRoot) -> io::Result<Containment> {
1258        match self.resolve(path)? {
1259            Resolved::Inside { id, .. } if self.node(id).kind == Node::OpaqueSymlink => {
1260                Err(unread_target_error())
1261            }
1262            Resolved::Inside { rel, .. } => Ok(Containment::Within(self.root.join(rel))),
1263            Resolved::Outside => Ok(Containment::Escapes),
1264        }
1265    }
1266}
1267
1268fn unread_target_error() -> io::Error {
1269    io::Error::other("path runs through a symlink whose target was not read")
1270}
1271
1272fn is_prefix(component: Component<'_>) -> bool {
1273    matches!(component, Component::Prefix(_))
1274}
1275
1276/// Compares names the way the host does, as far as it can be modelled.
1277///
1278/// Non-UTF-8 names are folded lossily, which can only merge more names, and a
1279/// merge of differently spelled names is always reported.
1280#[cfg(target_os = "macos")]
1281fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1282    portable_fold(name)
1283}
1284
1285#[cfg(target_os = "windows")]
1286fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1287    let text = name.to_string_lossy();
1288    let folded = if text.is_ascii() {
1289        text.to_ascii_uppercase()
1290    } else {
1291        fold_unicode(&text)
1292    };
1293    Cow::Owned(OsString::from(folded))
1294}
1295
1296#[cfg(not(any(target_os = "macos", target_os = "windows")))]
1297fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1298    Cow::Borrowed(name)
1299}
1300
1301/// The fold of [`PathModel::Portable`], the same on every host: the key
1302/// macOS uses.
1303fn portable_fold(name: &OsStr) -> Cow<'_, OsStr> {
1304    let text = name.to_string_lossy();
1305    let folded = if text.is_ascii() {
1306        text.to_ascii_uppercase()
1307    } else {
1308        decomposed_fold(&text)
1309    };
1310    Cow::Owned(OsString::from(folded))
1311}
1312
1313/// APFS compares canonically decomposed names case-insensitively.
1314fn decomposed_fold(text: &str) -> String {
1315    use unicode_normalization::UnicodeNormalization;
1316    upper_lower_upper(text.nfd())
1317}
1318
1319/// NTFS compares names case-insensitively without normalisation.
1320#[cfg(target_os = "windows")]
1321fn fold_unicode(text: &str) -> String {
1322    upper_lower_upper(text.chars())
1323}
1324
1325/// Full per-character case folding built from the standard library only.
1326///
1327/// Upper-casing first merges `ß` with `ẞ`, lower-casing merges the final
1328/// sigma and `ϴ` with `θ`, and the last upper-casing makes the key stable.
1329fn upper_lower_upper(chars: impl Iterator<Item = char>) -> String {
1330    chars
1331        .flat_map(char::to_uppercase)
1332        .flat_map(char::to_lowercase)
1333        .flat_map(char::to_uppercase)
1334        .collect()
1335}
1336
1337#[cfg(test)]
1338#[allow(clippy::unwrap_used, clippy::expect_used)]
1339mod tests {
1340    use super::*;
1341    use std::assert_matches;
1342
1343    fn tree() -> VirtualTree {
1344        VirtualTree::with_fold(&VirtualRoot::at("/dest"), fold)
1345    }
1346
1347    fn put(t: &mut VirtualTree, path: &str, node: Node) {
1348        t.insert(Path::new(path), node).unwrap();
1349    }
1350
1351    fn canon(t: &VirtualTree, path: &str) -> io::Result<Containment> {
1352        t.canonicalize(Path::new(path), &VirtualRoot::at("/dest"))
1353    }
1354
1355    fn within(t: &VirtualTree, path: &str) -> PathBuf {
1356        match canon(t, path).unwrap() {
1357            Containment::Within(p) => p,
1358            Containment::Escapes => panic!("{path} escapes"),
1359        }
1360    }
1361
1362    fn sym(target: &str) -> Node {
1363        Node::Symlink(PathBuf::from(target))
1364    }
1365
1366    #[test]
1367    fn insert_creates_implicit_parents() {
1368        let mut t = tree();
1369        put(&mut t, "a/b/c.txt", Node::File);
1370        assert!(t.exists(Path::new("/dest/a/b")));
1371        assert!(t.exists(Path::new("/dest/a/b/c.txt")));
1372        assert!(!t.exists(Path::new("/dest/a/x")));
1373    }
1374
1375    #[test]
1376    fn missing_component_is_not_found() {
1377        let t = tree();
1378        let err = canon(&t, "/dest/nope").unwrap_err();
1379        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1380    }
1381
1382    #[test]
1383    fn in_root_chain_resolves_to_final_location() {
1384        let mut t = tree();
1385        put(&mut t, "real", Node::Dir);
1386        put(&mut t, "b", sym("real"));
1387        put(&mut t, "a", sym("b"));
1388        assert_eq!(within(&t, "/dest/a"), PathBuf::from("/dest/real"));
1389    }
1390
1391    #[test]
1392    fn chain_leaving_root_escapes() {
1393        let mut t = tree();
1394        put(&mut t, "y", sym("."));
1395        put(&mut t, "d", sym("y/.."));
1396        put(&mut t, "e", sym("d/.."));
1397        assert_eq!(canon(&t, "/dest/e/secret").unwrap(), Containment::Escapes);
1398    }
1399
1400    #[test]
1401    fn a_path_that_leaves_the_root_and_reenters_it_still_escapes() {
1402        let mut t = VirtualTree::for_test(&VirtualRoot::new());
1403        put(&mut t, "up", sym(".."));
1404        put(&mut t, "abs", sym("/exarch-virtual-root/x"));
1405        let root = VirtualRoot::new();
1406        for target in [
1407            "/exarch-virtual-root/up/exarch-virtual-root/x",
1408            "/exarch-virtual-root/abs",
1409        ] {
1410            assert_eq!(
1411                t.canonicalize(Path::new(target), &root).unwrap(),
1412                Containment::Escapes,
1413                "{target}"
1414            );
1415        }
1416    }
1417
1418    #[test]
1419    fn symlink_loop_is_an_error() {
1420        let mut t = tree();
1421        put(&mut t, "a", sym("b"));
1422        put(&mut t, "b", sym("a"));
1423        assert!(canon(&t, "/dest/a").is_err());
1424    }
1425
1426    #[test]
1427    fn long_chain_hits_hop_limit() {
1428        let mut t = tree();
1429        put(&mut t, "l0", Node::Dir);
1430        for i in 1..=MAX_SYMLINK_HOPS + 1 {
1431            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
1432        }
1433        let over = format!("/dest/l{}", MAX_SYMLINK_HOPS + 1);
1434        let at = format!("/dest/l{MAX_SYMLINK_HOPS}");
1435        assert!(canon(&t, &over).is_err());
1436        assert!(canon(&t, &at).is_ok());
1437    }
1438
1439    #[cfg(any(unix, windows))]
1440    fn make_symlink(target: &str, link: &Path) -> io::Result<()> {
1441        #[cfg(unix)]
1442        return std::os::unix::fs::symlink(target, link);
1443        #[cfg(windows)]
1444        return std::os::windows::fs::symlink_dir(target, link);
1445    }
1446
1447    #[cfg(any(unix, windows))]
1448    #[test]
1449    fn hop_limit_matches_host_canonicalize() {
1450        let temp = tempfile::TempDir::new().unwrap();
1451        // The temp dir itself may sit behind a symlink (/var on macOS), which
1452        // would spend one hop of the chain below.
1453        let root = temp.path().canonicalize().unwrap();
1454        std::fs::create_dir(root.join("l0")).unwrap();
1455
1456        let mut resolvable = 0;
1457        for i in 1..=MAX_SYMLINK_HOPS + 8 {
1458            let linked = make_symlink(&format!("l{}", i - 1), &root.join(format!("l{i}")));
1459            assert!(linked.is_ok(), "cannot create symlinks here: {linked:?}");
1460            if std::fs::canonicalize(root.join(format!("l{i}"))).is_err() {
1461                break;
1462            }
1463            resolvable = i;
1464        }
1465        assert_eq!(resolvable, MAX_SYMLINK_HOPS, "host and model limits differ");
1466
1467        let mut t = tree();
1468        put(&mut t, "l0", Node::Dir);
1469        for i in 1..=resolvable + 1 {
1470            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
1471        }
1472        assert!(canon(&t, &format!("/dest/l{resolvable}")).is_ok());
1473        assert!(canon(&t, &format!("/dest/l{}", resolvable + 1)).is_err());
1474    }
1475
1476    fn ascii_upper(name: &OsStr) -> Cow<'_, OsStr> {
1477        Cow::Owned(OsString::from(name.to_string_lossy().to_ascii_uppercase()))
1478    }
1479
1480    fn folding_tree() -> VirtualTree {
1481        VirtualTree::with_fold(&VirtualRoot::at("/dest"), ascii_upper)
1482    }
1483
1484    #[test]
1485    fn place_resolves_in_root_symlinked_parents() {
1486        let mut t = tree();
1487        put(&mut t, "real", Node::Dir);
1488        put(&mut t, "alias", sym("real"));
1489        let placed = t.place(Path::new("alias/f"), Node::File).unwrap();
1490        assert_eq!(placed, PathBuf::from("real/f"));
1491    }
1492
1493    #[test]
1494    fn place_spells_a_folded_name_as_first_stored() {
1495        let mut t = folding_tree();
1496        assert_eq!(
1497            t.place(Path::new("a/x"), Node::File).unwrap(),
1498            PathBuf::from("a/x")
1499        );
1500        assert_eq!(
1501            t.place(Path::new("A/x"), Node::File).unwrap(),
1502            PathBuf::from("a/x")
1503        );
1504        assert_eq!(within(&t, "/dest/A/X"), PathBuf::from("/dest/a/x"));
1505    }
1506
1507    #[test]
1508    fn place_of_the_root_is_empty_and_conflicts_leave_no_path() {
1509        let mut t = tree();
1510        assert_eq!(t.place(Path::new(""), Node::Dir).unwrap(), PathBuf::new());
1511        put(&mut t, "f", Node::File);
1512        assert!(t.place(Path::new("f"), Node::Dir).is_err());
1513        assert!(t.place(Path::new("f/g"), Node::File).is_err());
1514    }
1515
1516    fn budgeted(max: usize, recording: CollisionRecording) -> VirtualTree {
1517        VirtualTree::build(
1518            &VirtualRoot::at("/dest"),
1519            PathModel::Host,
1520            ascii_upper,
1521            NodeBudget::with_max(max),
1522            recording,
1523        )
1524    }
1525
1526    #[test]
1527    fn node_budget_refuses_the_key_after_the_last() {
1528        let mut t = budgeted(3, CollisionRecording::Record);
1529        for name in ["a", "b", "c"] {
1530            put(&mut t, name, Node::Dir);
1531        }
1532        let err = t.try_insert(Path::new("d"), Node::Dir).unwrap_err();
1533        assert_matches!(err, PlaceError::Budget(NodeBudgetExceeded { max: 3 }));
1534        assert!(!t.exists(Path::new("/dest/d")));
1535    }
1536
1537    #[test]
1538    fn node_budget_charges_implicit_parents() {
1539        let mut t = budgeted(2, CollisionRecording::Record);
1540        let err = t.try_insert(Path::new("a/b/c"), Node::File).unwrap_err();
1541        assert_matches!(err, PlaceError::Budget(_));
1542    }
1543
1544    #[test]
1545    fn node_budget_charges_alias_spellings_once() {
1546        let mut t = budgeted(3, CollisionRecording::Discard);
1547        put(&mut t, "dir", Node::Dir);
1548        put(&mut t, "Dir", Node::Dir);
1549        put(&mut t, "Dir", Node::Dir);
1550        put(&mut t, "DIR", Node::Dir);
1551        let err = t.try_insert(Path::new("dIr"), Node::Dir).unwrap_err();
1552        assert_matches!(err, PlaceError::Budget(_));
1553    }
1554
1555    #[test]
1556    fn discard_keeps_no_collision_records_after_a_flood() {
1557        let mut t = budgeted(usize::MAX, CollisionRecording::Discard);
1558        put(&mut t, "d/f", Node::File);
1559        for spelling in ["D", "d", "Dd"] {
1560            let _ = t.insert(Path::new(spelling), Node::Dir);
1561        }
1562        put(&mut t, "D/g", Node::File);
1563        put(&mut t, "Dir", Node::Dir);
1564        put(&mut t, "dir", Node::Dir);
1565        put(&mut t, "dir/x", Node::File);
1566        assert!(t.take_collisions().is_empty());
1567        assert!(t.take_empty_merges().is_empty());
1568        assert!(t.exists(Path::new("/dest/D/f")));
1569    }
1570
1571    #[test]
1572    fn unbounded_config_budget_never_trips() {
1573        let config = crate::SecurityConfig::default()
1574            .with_max_file_count(usize::MAX)
1575            .with_max_path_depth(8);
1576        let mut t = VirtualTree::build(
1577            &VirtualRoot::at("/dest"),
1578            PathModel::Host,
1579            fold,
1580            NodeBudget::from_config(&config),
1581            CollisionRecording::Discard,
1582        );
1583        for i in 0..1000 {
1584            put(&mut t, &format!("d{i}"), Node::Dir);
1585        }
1586    }
1587
1588    #[test]
1589    fn config_budget_is_files_times_depth_plus_one() {
1590        let config = crate::SecurityConfig::default()
1591            .with_max_file_count(10)
1592            .with_max_path_depth(4);
1593        assert_eq!(NodeBudget::from_config(&config).max, 41);
1594    }
1595
1596    fn collisions_of(t: &mut VirtualTree) -> Vec<(String, String, CollisionKind)> {
1597        t.take_collisions()
1598            .into_iter()
1599            .map(|c| {
1600                (
1601                    c.existing.display().to_string().replace('\\', "/"),
1602                    c.incoming.display().to_string().replace('\\', "/"),
1603                    c.kind,
1604                )
1605            })
1606            .collect()
1607    }
1608
1609    #[test]
1610    fn exact_repeat_is_not_a_collision() {
1611        let mut t = folding_tree();
1612        put(&mut t, "a/f", Node::File);
1613        put(&mut t, "a/f", Node::File);
1614        assert!(t.take_collisions().is_empty());
1615    }
1616
1617    #[test]
1618    fn differently_spelled_files_collide() {
1619        let mut t = folding_tree();
1620        put(&mut t, "d/a.txt", Node::File);
1621        put(&mut t, "d/A.txt", Node::File);
1622        assert_eq!(
1623            collisions_of(&mut t),
1624            [("d/a.txt".into(), "d/A.txt".into(), CollisionKind::Files)]
1625        );
1626        assert!(t.take_collisions().is_empty());
1627    }
1628
1629    #[test]
1630    fn differently_spelled_parent_directories_collide() {
1631        let mut t = folding_tree();
1632        put(&mut t, "Images/x", Node::File);
1633        put(&mut t, "images/y", Node::File);
1634        assert_eq!(
1635            collisions_of(&mut t),
1636            [(
1637                "Images".into(),
1638                "images".into(),
1639                CollisionKind::DirectoriesWithContents
1640            )]
1641        );
1642    }
1643
1644    #[test]
1645    fn a_spelling_is_reported_once_however_many_entries_use_it() {
1646        let mut t = folding_tree();
1647        put(&mut t, "Images/a", Node::File);
1648        for i in 0..100 {
1649            put(&mut t, &format!("images/f{i}"), Node::File);
1650        }
1651        assert_eq!(collisions_of(&mut t).len(), 1);
1652    }
1653
1654    #[test]
1655    fn empty_directories_merge_harmlessly_until_one_gains_an_entry() {
1656        let mut t = folding_tree();
1657        put(&mut t, "Dir", Node::Dir);
1658        put(&mut t, "dir", Node::Dir);
1659        assert!(collisions_of(&mut t).is_empty());
1660        put(&mut t, "Dir/f", Node::File);
1661        put(&mut t, "dir/g", Node::File);
1662        assert_eq!(
1663            collisions_of(&mut t),
1664            [(
1665                "Dir".into(),
1666                "dir".into(),
1667                CollisionKind::DirectoriesWithContents
1668            )]
1669        );
1670    }
1671
1672    #[test]
1673    fn empty_merges_are_reported_once_when_nothing_lands_in_them() {
1674        let mut t = folding_tree();
1675        put(&mut t, "Dir", Node::Dir);
1676        put(&mut t, "dir", Node::Dir);
1677        put(&mut t, "other", Node::File);
1678        let merges: Vec<_> = t
1679            .take_empty_merges()
1680            .into_iter()
1681            .map(|c| {
1682                (
1683                    c.existing.display().to_string(),
1684                    c.incoming.display().to_string(),
1685                    c.kind,
1686                )
1687            })
1688            .collect();
1689        assert_eq!(
1690            merges,
1691            [("Dir".into(), "dir".into(), CollisionKind::Directories)]
1692        );
1693        assert!(t.take_empty_merges().is_empty());
1694    }
1695
1696    #[test]
1697    fn directory_entry_over_a_directory_with_contents_is_not_harmless() {
1698        let mut t = folding_tree();
1699        put(&mut t, "Dir/f", Node::File);
1700        put(&mut t, "dir", Node::Dir);
1701        assert_eq!(
1702            collisions_of(&mut t),
1703            [(
1704                "Dir".into(),
1705                "dir".into(),
1706                CollisionKind::DirectoriesWithContents
1707            )]
1708        );
1709    }
1710
1711    #[test]
1712    fn names_are_folded_once_however_often_they_repeat() {
1713        use std::sync::atomic::AtomicUsize;
1714        use std::sync::atomic::Ordering;
1715
1716        static CALLS: AtomicUsize = AtomicUsize::new(0);
1717        fn counting(name: &OsStr) -> Cow<'_, OsStr> {
1718            CALLS.fetch_add(1, Ordering::Relaxed);
1719            ascii_upper(name)
1720        }
1721
1722        let mut t = VirtualTree::with_fold(&VirtualRoot::at("/dest"), counting);
1723        for i in 0..500 {
1724            put(&mut t, &format!("a/b/c/d/file{i}"), Node::File);
1725        }
1726        // Four directories and 500 files, each folded to look up and to store;
1727        // a fold per parent per entry would be about 2500 calls.
1728        assert!(CALLS.load(Ordering::Relaxed) <= 2 * 504 + 8);
1729    }
1730
1731    #[test]
1732    fn collision_across_kinds_or_with_a_symlink_is_mixed() {
1733        let mut t = folding_tree();
1734        put(&mut t, "a", Node::File);
1735        let _ = t.insert(Path::new("A"), Node::Dir);
1736        put(&mut t, "link", sym("a"));
1737        let _ = t.insert(Path::new("LINK"), Node::File);
1738        assert_eq!(
1739            collisions_of(&mut t),
1740            [
1741                ("a".into(), "A".into(), CollisionKind::Mixed),
1742                ("link".into(), "LINK".into(), CollisionKind::Mixed)
1743            ]
1744        );
1745    }
1746
1747    #[test]
1748    fn symlink_over_an_existing_dir_is_refused_and_keeps_the_dir() {
1749        let mut t = folding_tree();
1750        put(&mut t, "d/f", Node::File);
1751        let err = t.insert(Path::new("d"), sym("sub")).unwrap_err();
1752        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
1753        let err = t.insert(Path::new("d"), Node::OpaqueSymlink).unwrap_err();
1754        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
1755        assert!(t.resolves_to_dir(&t.root.join("d")));
1756    }
1757
1758    #[test]
1759    fn collision_is_recorded_when_insert_fails() {
1760        let mut t = folding_tree();
1761        put(&mut t, "y", Node::File);
1762        let err = t.insert(Path::new("Y"), sym(".")).unwrap_err();
1763        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
1764        assert_eq!(
1765            collisions_of(&mut t),
1766            [("y".into(), "Y".into(), CollisionKind::Mixed)]
1767        );
1768    }
1769
1770    #[cfg(target_os = "macos")]
1771    mod macos {
1772        use super::super::fold;
1773        use super::*;
1774
1775        fn key(s: &str) -> OsString {
1776            fold(OsStr::new(s)).into_owned()
1777        }
1778
1779        #[test]
1780        fn special_case_pairs_fold_equal() {
1781            assert_eq!(key("\u{df}"), key("\u{1e9e}"));
1782            assert_eq!(key("\u{3b8}"), key("\u{3f4}"));
1783            assert_eq!(key("\u{3b8}"), key("\u{3d1}"));
1784            assert_eq!(key("\u{3c2}"), key("\u{3a3}"));
1785        }
1786
1787        #[test]
1788        fn canonically_equivalent_names_fold_equal() {
1789            assert_eq!(key("caf\u{e9}"), key("cafe\u{301}"));
1790            assert_eq!(key("\u{ac00}"), key("\u{1100}\u{1161}"));
1791        }
1792
1793        #[test]
1794        fn nfc_and_nfd_spellings_collide_in_the_tree() {
1795            let mut t = tree();
1796            put(&mut t, "caf\u{e9}", Node::File);
1797            put(&mut t, "cafe\u{301}", Node::File);
1798            assert_eq!(t.take_collisions().len(), 1);
1799        }
1800
1801        #[test]
1802        fn fold_never_under_merges_what_apfs_treats_as_equal() {
1803            let temp = tempfile::TempDir::new().unwrap();
1804            let root = temp.path().canonicalize().unwrap();
1805            let mut seen = std::collections::HashSet::new();
1806            let mut under = Vec::new();
1807            // Blocks with case or normalisation behaviour; the Hangul block is
1808            // sampled because it decomposes algorithmically.
1809            let candidates = (0x1..=0x3000)
1810                .chain((0xAC00..=0xD7A3).step_by(11))
1811                .chain(0xF900..=0xFFFF)
1812                .chain(0x1_0400..=0x1_044F)
1813                .chain(0x1_E900..=0x1_E943);
1814            for code in candidates {
1815                let Some(c) = char::from_u32(code).filter(|c| !matches!(c, '/' | '.')) else {
1816                    continue;
1817                };
1818                let name = c.to_string();
1819                let path = root.join(&name);
1820                let host_equal = path.symlink_metadata().is_ok();
1821                if !host_equal && std::fs::File::create_new(&path).is_err() {
1822                    continue;
1823                }
1824                let model_seen = !seen.insert(key(&name));
1825                if host_equal && !model_seen {
1826                    under.push(format!("U+{code:04X}"));
1827                }
1828            }
1829            assert!(under.is_empty(), "under-merged: {under:?}");
1830        }
1831    }
1832
1833    #[cfg(target_os = "windows")]
1834    #[test]
1835    fn fold_covers_ntfs_simple_uppercase() {
1836        use std::collections::HashMap;
1837
1838        let mut by_upper: HashMap<char, OsString> = HashMap::new();
1839        for code in 0x1..=0x1_FFFFu32 {
1840            let Some(c) = char::from_u32(code) else {
1841                continue;
1842            };
1843            let mut upper = c.to_uppercase();
1844            let simple = match (upper.next(), upper.next()) {
1845                (Some(u), None) => u,
1846                _ => c,
1847            };
1848            let key = fold(OsStr::new(&c.to_string())).into_owned();
1849            let expected = by_upper.entry(simple).or_insert_with(|| key.clone());
1850            assert_eq!(*expected, key, "U+{code:04X}");
1851        }
1852    }
1853
1854    #[test]
1855    fn dangling_symlink_does_not_exist_but_is_a_symlink() {
1856        let mut t = tree();
1857        put(&mut t, "d", sym("missing"));
1858        assert!(!t.exists(Path::new("/dest/d")));
1859        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
1860    }
1861
1862    #[test]
1863    fn opaque_symlink_exists_and_is_a_symlink_but_not_a_directory() {
1864        let mut t = tree();
1865        put(&mut t, "d", Node::OpaqueSymlink);
1866        assert!(t.exists(Path::new("/dest/d")));
1867        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
1868        assert!(!t.resolves_to_dir(Path::new("/dest/d")));
1869    }
1870
1871    #[test]
1872    fn nothing_resolves_through_an_opaque_symlink() {
1873        let mut t = tree();
1874        put(&mut t, "d", Node::OpaqueSymlink);
1875        assert!(canon(&t, "/dest/d").is_err());
1876        assert!(canon(&t, "/dest/d/x").is_err());
1877        assert!(t.insert(Path::new("d/f"), Node::File).is_err());
1878    }
1879
1880    #[test]
1881    fn a_chain_ending_at_an_opaque_symlink_does_not_resolve() {
1882        let mut t = tree();
1883        put(&mut t, "d", Node::OpaqueSymlink);
1884        put(&mut t, "l", sym("d"));
1885        assert!(canon(&t, "/dest/l").is_err());
1886    }
1887
1888    #[test]
1889    fn opaque_symlink_keeps_its_place_like_a_symlink() {
1890        let mut t = tree();
1891        put(&mut t, "d", Node::OpaqueSymlink);
1892        assert_eq!(
1893            t.insert(Path::new("d"), Node::Dir).unwrap_err().kind(),
1894            io::ErrorKind::AlreadyExists
1895        );
1896        assert_eq!(
1897            t.insert(Path::new("d"), Node::File).unwrap_err().kind(),
1898            io::ErrorKind::AlreadyExists
1899        );
1900        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
1901
1902        put(&mut t, "f", Node::File);
1903        assert!(t.insert(Path::new("f"), Node::OpaqueSymlink).is_err());
1904        assert!(t.is_symlink(Path::new("/dest/f")).unwrap());
1905    }
1906
1907    #[test]
1908    fn opaque_symlink_collision_is_mixed() {
1909        let mut t = folding_tree();
1910        put(&mut t, "link", Node::OpaqueSymlink);
1911        let _ = t.insert(Path::new("LINK"), Node::File);
1912        assert_eq!(
1913            collisions_of(&mut t),
1914            [("link".into(), "LINK".into(), CollisionKind::Mixed)]
1915        );
1916    }
1917
1918    #[test]
1919    fn is_symlink_follows_symlinked_parents() {
1920        let mut t = tree();
1921        put(&mut t, "real/inner", sym("x"));
1922        put(&mut t, "alias", sym("real"));
1923        assert!(t.is_symlink(Path::new("/dest/alias/inner")).unwrap());
1924        assert!(!t.is_symlink(Path::new("/dest/real")).unwrap());
1925        assert!(t.is_symlink(Path::new("/dest/none")).is_err());
1926    }
1927
1928    #[test]
1929    fn insert_through_symlinked_parent_lands_at_resolved_location() {
1930        let mut t = tree();
1931        put(&mut t, "real", Node::Dir);
1932        put(&mut t, "alias", sym("real"));
1933        put(&mut t, "alias/f", Node::File);
1934        assert!(t.exists(Path::new("/dest/real/f")));
1935    }
1936
1937    #[test]
1938    fn insert_dir_keeps_existing_symlink() {
1939        let mut t = tree();
1940        put(&mut t, "real", Node::Dir);
1941        put(&mut t, "alias", sym("real"));
1942        put(&mut t, "alias", Node::Dir);
1943        assert!(t.is_symlink(Path::new("/dest/alias")).unwrap());
1944    }
1945
1946    #[test]
1947    fn file_never_replaces_existing_symlink() {
1948        let mut t = tree();
1949        put(&mut t, "y", sym("."));
1950        let err = t.insert(Path::new("y"), Node::File).unwrap_err();
1951        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
1952        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
1953    }
1954
1955    #[test]
1956    fn symlink_over_symlink_is_refused_and_keeps_the_first() {
1957        let mut t = tree();
1958        put(&mut t, "real", Node::Dir);
1959        put(&mut t, "d", sym("real"));
1960        for node in [sym("other"), Node::OpaqueSymlink] {
1961            let conflict = t
1962                .try_insert(Path::new("d"), node)
1963                .unwrap_err()
1964                .into_conflict();
1965            assert_eq!(conflict.error.kind(), io::ErrorKind::AlreadyExists);
1966            assert_eq!(conflict.occupant, Some(Occupant::Symlink));
1967        }
1968        assert_eq!(within(&t, "/dest/d"), PathBuf::from("/dest/real"));
1969    }
1970
1971    #[test]
1972    fn symlink_repeating_the_same_target_is_an_unchanged_duplicate() {
1973        let mut t = tree();
1974        put(&mut t, "d", sym("real"));
1975        put(&mut t, "d", sym("real"));
1976        assert!(t.try_insert(Path::new("d"), Node::OpaqueSymlink).is_err());
1977    }
1978
1979    #[test]
1980    fn file_over_dir_is_refused_with_is_a_directory() {
1981        let mut t = tree();
1982        put(&mut t, "d/f", Node::File);
1983        let conflict = t
1984            .try_insert(Path::new("d"), Node::File)
1985            .unwrap_err()
1986            .into_conflict();
1987        assert_eq!(conflict.error.kind(), io::ErrorKind::IsADirectory);
1988        assert_eq!(conflict.occupant, Some(Occupant::Directory));
1989    }
1990
1991    #[test]
1992    fn file_over_file_is_kept_silently() {
1993        let mut t = tree();
1994        put(&mut t, "f", Node::File);
1995        put(&mut t, "f", Node::File);
1996        assert_eq!(t.occupant(Path::new("f")), Some(Occupant::File));
1997    }
1998
1999    #[test]
2000    fn occupant_names_what_sits_at_the_path_itself() {
2001        let mut t = tree();
2002        put(&mut t, "real/f", Node::File);
2003        put(&mut t, "alias", sym("real"));
2004        assert_eq!(t.occupant(Path::new("real")), Some(Occupant::Directory));
2005        assert_eq!(t.occupant(Path::new("alias")), Some(Occupant::Symlink));
2006        assert_eq!(t.occupant(Path::new("alias/f")), Some(Occupant::File));
2007        assert_eq!(t.occupant(Path::new("none")), None);
2008    }
2009
2010    #[test]
2011    fn symlink_replaces_earlier_file() {
2012        let mut t = tree();
2013        put(&mut t, "y", Node::File);
2014        let err = t.insert(Path::new("y"), sym(".")).unwrap_err();
2015        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2016        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
2017    }
2018
2019    #[test]
2020    fn dir_over_file_is_an_error() {
2021        let mut t = tree();
2022        put(&mut t, "f", Node::File);
2023        let err = t.insert(Path::new("f"), Node::Dir).unwrap_err();
2024        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2025    }
2026
2027    #[test]
2028    fn insert_under_file_is_an_error() {
2029        let mut t = tree();
2030        put(&mut t, "f", Node::File);
2031        let err = t.insert(Path::new("f/g"), Node::File).unwrap_err();
2032        assert_eq!(err.kind(), io::ErrorKind::NotADirectory);
2033    }
2034
2035    #[test]
2036    fn insert_under_chain_leaving_root_is_an_error() {
2037        let mut t = tree();
2038        put(&mut t, "out", sym(".."));
2039        assert!(t.insert(Path::new("out/f"), Node::File).is_err());
2040        assert!(!t.exists(Path::new("/dest/out/f")));
2041    }
2042
2043    #[test]
2044    fn resolves_to_dir_distinguishes_files_and_directories() {
2045        let mut t = tree();
2046        put(&mut t, "d/f", Node::File);
2047        put(&mut t, "alias", sym("d"));
2048        assert!(t.resolves_to_dir(Path::new("/dest/d")));
2049        assert!(t.resolves_to_dir(Path::new("/dest/alias")));
2050        assert!(!t.resolves_to_dir(Path::new("/dest/d/f")));
2051    }
2052
2053    #[test]
2054    fn overlong_component_is_never_found() {
2055        let mut t = tree();
2056        put(&mut t, "d", Node::Dir);
2057        let long = "a".repeat(1 << 20);
2058        let err = canon(&t, &format!("/dest/d/{long}")).unwrap_err();
2059        assert_eq!(err.kind(), io::ErrorKind::NotFound);
2060    }
2061
2062    #[test]
2063    fn name_length_limits() {
2064        assert!(check_name_lengths(Path::new("a/b")).is_ok());
2065        let long_name = "a".repeat(255 + 1);
2066        assert!(check_name_lengths(Path::new(&long_name)).is_err());
2067        let long_path = path_of_len(HOST_PATH_LIMIT + 1);
2068        assert!(check_name_lengths(Path::new(&long_path)).is_err());
2069        assert!(check_name_lengths(Path::new(&path_of_len(HOST_PATH_LIMIT))).is_ok());
2070    }
2071
2072    use crate::test_utils::HOST_PATH_LIMIT;
2073    use crate::test_utils::path_of_len;
2074
2075    #[test]
2076    fn link_target_length_boundaries() {
2077        let symlink_limit = path_of_len(MAX_SYMLINK_TARGET_LEN);
2078        let symlink_over = path_of_len(MAX_SYMLINK_TARGET_LEN + 1);
2079        assert!(check_link_target_length(Path::new(&symlink_limit), LinkKind::Symlink).is_ok());
2080        assert!(check_link_target_length(Path::new(&symlink_over), LinkKind::Symlink).is_err());
2081
2082        let at_limit = path_of_len(HOST_PATH_LIMIT);
2083        assert_eq!(at_limit.len(), HOST_PATH_LIMIT);
2084        let over = path_of_len(HOST_PATH_LIMIT + 1);
2085        assert!(check_link_target_length(Path::new(&at_limit), LinkKind::Hardlink).is_ok());
2086        assert!(check_link_target_length(Path::new(&over), LinkKind::Hardlink).is_err());
2087    }
2088
2089    #[test]
2090    fn symlink_target_limits_match_the_host() {
2091        assert_eq!(
2092            MAX_SYMLINK_TARGET_LEN,
2093            if cfg!(windows) { 4091 } else { HOST_PATH_LIMIT }
2094        );
2095        assert_eq!(
2096            MAX_SYMLINK_TARGET_BYTES,
2097            if cfg!(windows) {
2098                4091 * 3
2099            } else {
2100                HOST_PATH_LIMIT
2101            }
2102        );
2103    }
2104
2105    /// Finds the longest relative symlink target the host creates and checks
2106    /// that [`MAX_SYMLINK_TARGET_LEN`] does not exceed it.
2107    #[cfg(windows)]
2108    #[test]
2109    fn symlink_target_limit_is_accepted_by_the_host() {
2110        use std::os::windows::fs::symlink_file;
2111
2112        let temp = tempfile::TempDir::new().unwrap();
2113        let mut counter = 0_u32;
2114        let mut creates = |len: usize| -> io::Result<bool> {
2115            counter += 1;
2116            let link = temp.path().join(format!("l{counter}"));
2117            let mut target = "abcdefg\\".repeat((len - 1) / 8);
2118            target.push_str(&"a".repeat(len - target.len()));
2119            match symlink_file(&target, &link) {
2120                Ok(()) => Ok(true),
2121                Err(e) if e.raw_os_error() == Some(1314) => Err(e),
2122                Err(_) => Ok(false),
2123            }
2124        };
2125
2126        match creates(1) {
2127            Ok(_) => {}
2128            Err(e) => {
2129                assert!(
2130                    std::env::var_os("CI").is_none(),
2131                    "symlink creation needs a privilege on CI: {e}"
2132                );
2133                eprintln!("skipped: symlink creation is not permitted: {e}");
2134                return;
2135            }
2136        }
2137
2138        let (mut ok, mut bad) = (1_usize, 32767_usize);
2139        while bad - ok > 1 {
2140            let mid = ok + (bad - ok) / 2;
2141            if creates(mid).unwrap() {
2142                ok = mid;
2143            } else {
2144                bad = mid;
2145            }
2146        }
2147        eprintln!("largest relative symlink target: {ok} UTF-16 units");
2148        assert!(MAX_SYMLINK_TARGET_LEN <= ok, "host limit is {ok}");
2149    }
2150
2151    #[test]
2152    fn symlink_target_ignores_component_limit() {
2153        let long_component = "a".repeat(255 + 45);
2154        let target = Path::new(&long_component);
2155        assert!(check_link_target_length(target, LinkKind::Symlink).is_ok());
2156        assert!(check_link_target_length(target, LinkKind::Hardlink).is_err());
2157        assert!(check_name_lengths(target).is_err());
2158    }
2159
2160    #[cfg(any(target_os = "macos", target_os = "windows"))]
2161    #[test]
2162    fn keys_are_case_insensitive_on_case_folding_hosts() {
2163        let mut t = tree();
2164        put(&mut t, "Dir/File", Node::File);
2165        assert!(t.exists(Path::new("/dest/dir/file")));
2166    }
2167
2168    #[test]
2169    fn host_fs_probes_the_real_filesystem() {
2170        let temp = tempfile::TempDir::new().unwrap();
2171        assert!(HostFs.exists(temp.path()));
2172        assert!(!HostFs.is_symlink(temp.path()).unwrap());
2173        let root = DestDir::new(temp.path().to_path_buf()).unwrap();
2174        assert!(
2175            HostFs
2176                .canonicalize(&temp.path().join("nope"), &root)
2177                .is_err()
2178        );
2179    }
2180}