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::Violation;
58use crate::closed_enum::closed_enum;
59#[cfg(any(unix, target_os = "wasi"))]
60use crate::formats::handle_resolution::LinkCursor;
61use crate::formats::pinned_dir::PinnedRoot;
62use crate::types::DestDir;
63use crate::types::SafePath;
64use crate::types::safe_path::ParentCheck;
65
66/// Maximum number of symlinks followed while resolving a single path, as the
67/// host's `realpath` allows it.
68#[cfg(target_os = "macos")]
69pub const MAX_SYMLINK_HOPS: usize = 33;
70
71/// Maximum number of symlinks followed while resolving a single path, as the
72/// host's `realpath` allows it.
73#[cfg(all(target_os = "linux", target_env = "musl"))]
74pub const MAX_SYMLINK_HOPS: usize = 39;
75
76/// Maximum number of symlinks followed while resolving a single path, as the
77/// host's `realpath` allows it.
78#[cfg(all(target_os = "linux", not(target_env = "musl")))]
79pub const MAX_SYMLINK_HOPS: usize = 40;
80
81/// Maximum number of symlinks followed while resolving a single path, as the
82/// host's `realpath` allows it.
83#[cfg(target_os = "windows")]
84pub const MAX_SYMLINK_HOPS: usize = 63;
85
86/// Maximum number of symlinks followed while resolving a single path. A low
87/// guess can only turn a PASS into a false FAIL.
88#[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
89pub const MAX_SYMLINK_HOPS: usize = 32;
90
91/// Longest single path component the host accepts (`NAME_MAX`), in bytes, or
92/// in UTF-16 units on Windows.
93pub const MAX_COMPONENT_LEN: usize = 255;
94
95/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
96/// bytes.
97#[cfg(target_os = "linux")]
98pub const MAX_PATH_LEN: usize = 4095;
99
100/// Longest relative path the host accepts, in UTF-16 units.
101///
102/// 32767 is the documented limit of an extended-length path. A symlink target
103/// is bounded much lower, see [`MAX_SYMLINK_TARGET_LEN`].
104#[cfg(target_os = "windows")]
105pub const MAX_PATH_LEN: usize = 32767;
106
107/// Longest relative path the host accepts (`PATH_MAX` less the terminator), in
108/// bytes. A low guess can only turn a PASS into a false FAIL.
109#[cfg(not(any(target_os = "linux", target_os = "windows")))]
110pub const MAX_PATH_LEN: usize = 1023;
111
112/// Longest symlink target the host accepts, in UTF-16 units.
113///
114/// `CreateSymbolicLinkW` stores the substitute and print names in a 16 KiB
115/// reparse buffer after a 20-byte header. Extraction only creates relative
116/// targets (a `Prefix` or `RootDir` component is rejected), where both names
117/// are equal, so `2 * 2n <= 16384 - 20` gives `n <= 4091`. Absolute targets
118/// (`\??\` prefix) would allow fewer units but are never created.
119#[cfg(target_os = "windows")]
120pub const MAX_SYMLINK_TARGET_LEN: usize = 4091;
121
122/// Longest symlink target the host accepts (`PATH_MAX` less the terminator),
123/// in bytes.
124#[cfg(not(target_os = "windows"))]
125pub const MAX_SYMLINK_TARGET_LEN: usize = MAX_PATH_LEN;
126
127/// Longest symlink target in bytes that can pass the
128/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
129/// stored as bytes.
130///
131/// On Windows a UTF-16 unit takes at most 3 UTF-8 bytes, so a byte cap never
132/// rejects a target the unit check accepts.
133#[cfg(target_os = "windows")]
134pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN * 3;
135
136/// Longest symlink target in bytes that can pass the
137/// [`MAX_SYMLINK_TARGET_LEN`] check; the read and allocation cap for targets
138/// stored as bytes.
139#[cfg(not(target_os = "windows"))]
140pub const MAX_SYMLINK_TARGET_BYTES: usize = MAX_SYMLINK_TARGET_LEN;
141
142closed_enum! {
143    /// The kind of link a target belongs to; the host limits them differently.
144    ///
145    /// # Examples
146    ///
147    /// ```
148    /// use exarch_core::LinkKind;
149    ///
150    /// assert_eq!(LinkKind::Symlink.as_str(), "symlink");
151    /// ```
152    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
153    #[non_exhaustive]
154    pub enum LinkKind {
155        /// A symbolic link; `symlink(2)` bounds only the whole target
156        Symlink => "symlink",
157        /// A hard link; the target is resolved as a path, so components count too
158        Hardlink => "hardlink",
159    }
160}
161
162closed_enum! {
163    /// The path semantics an [`EntrySink`](crate::EntrySink) is validated
164    /// against.
165    ///
166    /// `Host` applies the rules of the platform running the extraction. On a
167    /// Windows host that means the component rules of `Portable` (every
168    /// character Windows refuses, reserved names, `:`, trailing dot or space);
169    /// on other hosts component names are not restricted.
170    /// `Portable` applies the strictest rules of every supported platform, on
171    /// every host, for a sink whose storage is read elsewhere:
172    ///
173    /// - names fold as on macOS (canonical decomposition plus a case fold), so
174    ///   two spellings of one name are one name;
175    /// - a component with a backslash, one of `<>"|?*`, a control character, a
176    ///   `:`, a trailing dot or space, a reserved Windows device name (unless
177    ///   `windows_reserved_names` is allowed) or bytes that are not UTF-8 is
178    ///   refused;
179    /// - a component is at most 255 and a path or symlink target at most 1023,
180    ///   counted in UTF-8 bytes and in UTF-16 units alike, and a symlink chain
181    ///   is cut off after 32 hops.
182    ///
183    /// On a Windows host `\` already separates the components of an entry
184    /// name when the path is parsed, so it is split there and not refused as a
185    /// backslash; every other host refuses it. Not modelled: 8.3 short names
186    /// and the legacy 260-unit `MAX_PATH`.
187    ///
188    /// # Examples
189    ///
190    /// ```
191    /// use exarch_core::PathModel;
192    ///
193    /// assert_eq!(PathModel::default(), PathModel::Host);
194    /// assert_eq!(PathModel::Portable.as_str(), "portable");
195    /// ```
196    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
197    #[non_exhaustive]
198    pub enum PathModel {
199        /// The rules of the platform running the extraction.
200        #[default]
201        Host => "host",
202        /// The strictest rules of every supported platform.
203        Portable => "portable",
204    }
205}
206
207/// The length limits of a [`PathModel`].
208#[derive(Debug, Clone, Copy)]
209struct NameLimits {
210    component: usize,
211    path: usize,
212    symlink_target: usize,
213    hops: usize,
214}
215
216impl PathModel {
217    const fn limits(self) -> NameLimits {
218        match self {
219            Self::Host => NameLimits {
220                component: MAX_COMPONENT_LEN,
221                path: MAX_PATH_LEN,
222                symlink_target: MAX_SYMLINK_TARGET_LEN,
223                hops: MAX_SYMLINK_HOPS,
224            },
225            Self::Portable => NameLimits {
226                component: 255,
227                path: 1023,
228                symlink_target: 1023,
229                hops: 32,
230            },
231        }
232    }
233
234    fn name_len(self, name: &OsStr) -> usize {
235        match self {
236            Self::Host => name_len(name),
237            Self::Portable => portable_name_len(name),
238        }
239    }
240
241    /// Rejects entry names this model refuses with `ENAMETOOLONG`.
242    ///
243    /// # Errors
244    ///
245    /// Returns an error if the path or any of its components is too long.
246    pub(crate) fn check_name_lengths(self, path: &Path) -> io::Result<()> {
247        let limits = self.limits();
248        let too_long = self.name_len(path.as_os_str()) > limits.path
249            || path
250                .components()
251                .any(|c| self.name_len(c.as_os_str()) > limits.component);
252        if too_long {
253            return Err(name_too_long());
254        }
255        Ok(())
256    }
257
258    /// Rejects a link target this model refuses with `ENAMETOOLONG`.
259    ///
260    /// # Errors
261    ///
262    /// Returns an error if the target is too long for `kind`.
263    pub(crate) fn check_link_target_length(self, target: &Path, kind: LinkKind) -> io::Result<()> {
264        match kind {
265            LinkKind::Symlink
266                if self.name_len(target.as_os_str()) > self.limits().symlink_target =>
267            {
268                Err(name_too_long())
269            }
270            LinkKind::Symlink => Ok(()),
271            LinkKind::Hardlink => self.check_name_lengths(target),
272        }
273    }
274}
275
276/// `base` extended by `tail`; an empty `tail` adds no trailing separator, which
277/// would count one byte against the host path limit.
278pub fn joined(base: &Path, tail: &Path) -> PathBuf {
279    if tail.as_os_str().is_empty() {
280        base.to_path_buf()
281    } else {
282        base.join(tail)
283    }
284}
285
286/// Refuses a landing that `model` cannot hold once `tail` is appended.
287///
288/// The single length rule for a projected landing, shared by the virtual tree
289/// and the directory walker so `verify`, the sinks and host extraction cannot
290/// disagree.
291///
292/// # Errors
293///
294/// Returns the name-too-long error when the joined path or a component exceeds
295/// the model's limits.
296pub fn projected_landing_within_limits(
297    model: PathModel,
298    landing: &Path,
299    tail: &Path,
300) -> io::Result<()> {
301    model.check_name_lengths(&joined(landing, tail))
302}
303
304/// A name's length in UTF-8 bytes, which is never below its length in UTF-16
305/// units, so one limit holds in both.
306fn portable_name_len(name: &OsStr) -> usize {
307    name.to_string_lossy().len()
308}
309
310#[cfg(windows)]
311fn name_len(name: &OsStr) -> usize {
312    std::os::windows::ffi::OsStrExt::encode_wide(name).count()
313}
314
315#[cfg(not(windows))]
316fn name_len(name: &OsStr) -> usize {
317    name.as_encoded_bytes().len()
318}
319
320/// Rejects entry names the host would refuse with `ENAMETOOLONG`.
321///
322/// # Errors
323///
324/// Returns an error if the path or any of its components is too long.
325#[cfg(test)]
326pub fn check_name_lengths(path: &Path) -> io::Result<()> {
327    PathModel::Host.check_name_lengths(path)
328}
329
330/// Rejects a link target the host would refuse with `ENAMETOOLONG`.
331///
332/// A symlink target is checked against [`MAX_SYMLINK_TARGET_LEN`] only, as
333/// `symlink(2)` does; a hardlink target is checked like an entry name.
334///
335/// # Errors
336///
337/// Returns an error if the target is too long for `kind`.
338pub fn check_link_target_length(target: &Path, kind: LinkKind) -> io::Result<()> {
339    PathModel::Host.check_link_target_length(target, kind)
340}
341
342/// The error for a name beyond the host's limits.
343#[must_use]
344pub fn name_too_long() -> io::Error {
345    io::Error::new(io::ErrorKind::InvalidFilename, "file name too long")
346}
347
348/// A root directory that a validator resolves entry paths against.
349///
350/// Implemented only by [`DestDir`] (the real destination) and [`VirtualRoot`]
351/// (the in-memory model), and tied to its [`FsView`] through
352/// [`FsView::Root`], so a root can never be paired with the wrong view.
353pub trait ModelRoot {
354    /// The root as a path.
355    fn as_path(&self) -> &Path;
356}
357
358impl ModelRoot for DestDir {
359    fn as_path(&self) -> &Path {
360        Self::as_path(self)
361    }
362}
363
364#[cfg(windows)]
365const VIRTUAL_ROOT: &str = r"C:\exarch-virtual-root";
366#[cfg(not(windows))]
367const VIRTUAL_ROOT: &str = "/exarch-virtual-root";
368
369/// The root of a [`VirtualTree`]: a fixed path that is never touched on disk.
370///
371/// Distinct from [`DestDir`], which promises an existing, canonical, writable
372/// directory, so a virtual root can never reach a helper that writes to the
373/// host filesystem.
374#[derive(Debug, Clone, PartialEq, Eq)]
375pub struct VirtualRoot(PathBuf);
376
377impl VirtualRoot {
378    /// Creates the fixed virtual root.
379    #[must_use]
380    pub fn new() -> Self {
381        Self(PathBuf::from(VIRTUAL_ROOT))
382    }
383
384    #[cfg(test)]
385    pub(crate) fn at(path: &str) -> Self {
386        Self(PathBuf::from(path))
387    }
388}
389
390impl Default for VirtualRoot {
391    fn default() -> Self {
392        Self::new()
393    }
394}
395
396impl ModelRoot for VirtualRoot {
397    fn as_path(&self) -> &Path {
398        &self.0
399    }
400}
401
402/// Where a canonicalized path ended up relative to the root of its view.
403#[derive(Debug, Clone, PartialEq, Eq)]
404pub enum Containment {
405    /// Inside the root, at this canonical path.
406    Within(PathBuf),
407    /// Outside the root, or not provably inside it.
408    Escapes,
409}
410
411/// What the target of a link is relative to.
412#[derive(Debug, Clone, Copy, PartialEq, Eq)]
413pub enum LinkBase {
414    /// The directory the link sits in (a symlink target); the parents of the
415    /// link are vetted as well.
416    LinkDirectory,
417    /// The root itself (a hardlink target).
418    Destination,
419}
420
421/// Filesystem probes needed while validating archive entries.
422pub trait FsView {
423    /// The root type a validator resolves paths against in this view.
424    type Root: ModelRoot;
425
426    /// The path semantics validation applies in this view.
427    fn path_model(&self) -> PathModel;
428
429    /// Returns `true` if `path` exists, following symlinks.
430    fn exists(&self, path: &Path) -> bool;
431
432    /// Returns `true` if `path` exists and is a directory, following symlinks.
433    fn is_dir(&self, path: &Path) -> bool;
434
435    /// Returns whether `path` itself is a symlink, without following it.
436    ///
437    /// # Errors
438    ///
439    /// Returns an error if `path` cannot be inspected (for example, it does
440    /// not exist).
441    fn is_symlink(&self, path: &Path) -> io::Result<bool>;
442
443    /// Resolves `path` to its canonical form and says whether that lies inside
444    /// `root`.
445    ///
446    /// # Errors
447    ///
448    /// Returns an error if a component is missing or the chain cannot be
449    /// resolved.
450    fn canonicalize(&self, path: &Path, root: &Self::Root) -> io::Result<Containment>;
451
452    /// Resolves the target of the link at `link` (relative to `root`) through
453    /// the links this view already holds, and returns where it lands.
454    ///
455    /// For [`LinkBase::LinkDirectory`] the parents of `link` are vetted first:
456    /// an existing symlink among them is refused. Every probe that fails for a
457    /// reason other than absence refuses the link.
458    ///
459    /// The default resolves by path through [`FsView::is_symlink`] and
460    /// [`FsView::canonicalize`]; a view that can hold directory handles
461    /// overrides it.
462    ///
463    /// # Errors
464    ///
465    /// Returns `SymlinkEscape` when the target leaves `root`, runs through a
466    /// link that dangles or loops, or cannot be inspected, and an I/O error for
467    /// a name past the host's limits.
468    fn resolve_link_target(
469        &self,
470        link: &Path,
471        target: &Path,
472        base: LinkBase,
473        root: &Self::Root,
474    ) -> crate::Result<PathBuf>
475    where
476        Self: Sized,
477    {
478        crate::types::safe_symlink::resolve_link_target_by_path(self, link, target, base, root)
479    }
480}
481
482/// Case-insensitive path prefix check for macOS/Windows.
483///
484/// On case-insensitive filesystems (macOS, Windows), attackers can bypass
485/// path validation using different case (e.g., `../../USERS/victim/.ssh/`).
486///
487/// Compares `path` and `base` component-by-component rather than as raw
488/// strings, so a shared name prefix without a component boundary (e.g. base
489/// `/tmp/dest` against sibling `/tmp/destevil`) is correctly rejected. See
490/// GHSA-wcmx-7f9h-5mv5.
491#[cfg(any(target_os = "macos", target_os = "windows"))]
492pub fn paths_start_with(path: &Path, base: &Path) -> bool {
493    let mut path_components = path.components();
494    for base_component in base.components() {
495        let Some(path_component) = path_components.next() else {
496            return false;
497        };
498        let path_str = path_component.as_os_str().to_string_lossy().to_lowercase();
499        let base_str = base_component.as_os_str().to_string_lossy().to_lowercase();
500        if path_str != base_str {
501            return false;
502        }
503    }
504    true
505}
506
507/// Case-sensitive path prefix check for Unix (not macOS).
508#[cfg(not(any(target_os = "macos", target_os = "windows")))]
509pub fn paths_start_with(path: &Path, base: &Path) -> bool {
510    path.starts_with(base)
511}
512
513/// The real filesystem.
514#[derive(Debug, Clone, Copy, Default)]
515pub struct HostFs;
516
517impl FsView for HostFs {
518    type Root = DestDir;
519
520    fn path_model(&self) -> PathModel {
521        PathModel::Host
522    }
523
524    fn exists(&self, path: &Path) -> bool {
525        path.exists()
526    }
527
528    fn is_dir(&self, path: &Path) -> bool {
529        path.is_dir()
530    }
531
532    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
533        std::fs::symlink_metadata(path).map(|m| m.file_type().is_symlink())
534    }
535
536    fn canonicalize(&self, path: &Path, root: &DestDir) -> io::Result<Containment> {
537        std::fs::canonicalize(path).map(|canonical| contain(canonical, root.as_path()))
538    }
539
540    #[cfg(any(unix, target_os = "wasi"))]
541    fn resolve_link_target(
542        &self,
543        link: &Path,
544        target: &Path,
545        base: LinkBase,
546        root: &DestDir,
547    ) -> crate::Result<PathBuf> {
548        resolve_pinned(&PinnedRoot::open(root.clone())?, link, target, base)
549    }
550}
551
552#[cfg(any(unix, target_os = "wasi"))]
553fn resolve_pinned(
554    root: &PinnedRoot,
555    link: &Path,
556    target: &Path,
557    base: LinkBase,
558) -> crate::Result<PathBuf> {
559    LinkCursor::for_target(root, link, base, target)
560        .map(|resolved| root.dest().as_path().join(resolved))
561        .map_err(|refusal| refusal.into_error(link))
562}
563
564/// The real filesystem, with link targets resolved against the destination
565/// handle an extraction already holds.
566///
567/// Behaves like [`HostFs`] except that, on Unix and WASI, links are resolved
568/// handle-relatively from the extraction's [`PinnedRoot`], the same descriptor
569/// every write goes through. [`HostFs`] opens the destination by path on every
570/// call instead, so only an extraction should rely on the pinned form.
571#[derive(Debug, Clone, Copy)]
572pub struct PinnedHostFs<'r> {
573    #[cfg_attr(
574        not(any(unix, target_os = "wasi")),
575        expect(dead_code, reason = "only the handle-relative resolver reads the root")
576    )]
577    root: &'r PinnedRoot,
578}
579
580impl<'r> PinnedHostFs<'r> {
581    /// Resolves link targets against `root`, the handle the extraction writes
582    /// through.
583    pub const fn new(root: &'r PinnedRoot) -> Self {
584        Self { root }
585    }
586}
587
588impl FsView for PinnedHostFs<'_> {
589    type Root = DestDir;
590
591    fn path_model(&self) -> PathModel {
592        HostFs.path_model()
593    }
594
595    fn exists(&self, path: &Path) -> bool {
596        HostFs.exists(path)
597    }
598
599    fn is_dir(&self, path: &Path) -> bool {
600        HostFs.is_dir(path)
601    }
602
603    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
604        HostFs.is_symlink(path)
605    }
606
607    fn canonicalize(&self, path: &Path, root: &DestDir) -> io::Result<Containment> {
608        HostFs.canonicalize(path, root)
609    }
610
611    #[cfg(any(unix, target_os = "wasi"))]
612    fn resolve_link_target(
613        &self,
614        link: &Path,
615        target: &Path,
616        base: LinkBase,
617        _root: &DestDir,
618    ) -> crate::Result<PathBuf> {
619        resolve_pinned(self.root, link, target, base)
620    }
621}
622
623/// Classifies a canonical path against the canonical `root` by exact,
624/// case-sensitive components.
625///
626/// Both come from `realpath`, which reports the on-disk case, so a
627/// case-insensitive comparison is never needed and would let a sibling that
628/// differs only in case (`out` and `OUT` on a case-sensitive volume) pass as
629/// inside.
630fn contain(canonical: PathBuf, root: &Path) -> Containment {
631    #[cfg(unix)]
632    let inside = canonical.starts_with(root);
633    #[cfg(not(unix))]
634    let inside = paths_start_with(&canonical, root);
635    if inside {
636        Containment::Within(canonical)
637    } else {
638        Containment::Escapes
639    }
640}
641
642/// How two colliding names differ, which sets how serious the collision is.
643#[derive(Debug, Clone, Copy, PartialEq, Eq)]
644pub enum CollisionKind {
645    /// Both are directories and neither holds anything in the archive, so the
646    /// merge changes nothing
647    Directories,
648    /// Both are directories and at least one holds entries, which then land in
649    /// one directory and can overwrite each other
650    DirectoriesWithContents,
651    /// Both are files, so one silently replaces or is skipped for the other
652    Files,
653    /// The kinds differ or a symlink is involved, so later entries can
654    /// resolve differently than the archive intends
655    Mixed,
656}
657
658/// Two entry names that differ exactly but are one name on the host.
659#[derive(Debug, Clone, PartialEq, Eq)]
660pub struct NameCollision {
661    /// Path of the node that was there first
662    pub existing: PathBuf,
663    /// Path of the entry that hit it
664    pub incoming: PathBuf,
665    /// How the two differ
666    pub kind: CollisionKind,
667}
668
669impl CollisionKind {
670    fn of(existing: &Node, incoming: &Node, existing_has_contents: bool) -> Self {
671        match (existing, incoming) {
672            (Node::Dir, Node::Dir) if existing_has_contents => Self::DirectoriesWithContents,
673            (Node::Dir, Node::Dir) => Self::Directories,
674            (Node::File, Node::File) => Self::Files,
675            _ => Self::Mixed,
676        }
677    }
678}
679
680/// What already occupies a path an insert collided with.
681#[derive(Debug, Clone, Copy, PartialEq, Eq)]
682pub enum Occupant {
683    /// A regular file or materialized hardlink.
684    File,
685    /// A directory.
686    Directory,
687    /// A symlink, readable or opaque.
688    Symlink,
689}
690
691impl Occupant {
692    /// The noun used in reports.
693    pub(crate) const fn noun(self) -> &'static str {
694        match self {
695            Self::File => "file",
696            Self::Directory => "directory",
697            Self::Symlink => "symlink",
698        }
699    }
700
701    /// The text of a refusal to replace this occupant at `rel`, shared by the
702    /// host extraction error and the `verify` model so both name the entry and
703    /// the occupant in the same words.
704    pub(crate) fn refusal(self, rel: &Path) -> String {
705        format!(
706            "refusing to replace the existing {} at {}",
707            self.noun(),
708            normalized_display(rel)
709        )
710    }
711}
712
713/// Spells `path` with its components re-joined, so `./a//b` reads `a/b`, and
714/// injectively ([`crate::path_text`]), so two names never read alike.
715pub fn normalized_display(path: &Path) -> String {
716    crate::path_text(&path.components().collect::<PathBuf>())
717}
718
719/// What stops an entry's parent chain from being a directory.
720#[derive(Debug, Clone, Copy, PartialEq, Eq)]
721pub enum ParentBlocker {
722    /// A parent component is a file.
723    File,
724    /// A parent component is a symlink that dangles, loops or does not resolve
725    /// to a directory.
726    Symlink,
727    /// A parent component is a symlink that resolves outside the root.
728    Escape,
729}
730
731impl ParentBlocker {
732    /// The error for creating `entry` under the blocking component `parent`;
733    /// the single source of text and category for extraction and `verify`.
734    pub(crate) fn error(self, entry: &Path, parent: &Path) -> ArchiveError {
735        let parent: PathBuf = parent.components().collect();
736        let refusal = |noun: &str| {
737            format!(
738                "refusing to create {} under the existing {noun} at {}",
739                normalized_display(entry),
740                normalized_display(&parent)
741            )
742        };
743        match self {
744            Self::File => ArchiveError::Io(io::Error::new(
745                io::ErrorKind::NotADirectory,
746                refusal(Occupant::File.noun()),
747            )),
748            Self::Symlink => ArchiveError::from(Violation::SymlinkParent {
749                entry: normalized_display(entry).into(),
750                parent: normalized_display(&parent).into(),
751            }),
752            Self::Escape => ArchiveError::SymlinkEscape { path: parent },
753        }
754    }
755}
756
757/// A parent component that stopped an entry from being placed.
758#[derive(Debug, Clone, PartialEq, Eq)]
759pub struct BlockedParent {
760    entry: PathBuf,
761    parent: PathBuf,
762    blocker: ParentBlocker,
763}
764
765impl BlockedParent {
766    pub(crate) fn error(&self) -> ArchiveError {
767        self.blocker.error(&self.entry, &self.parent)
768    }
769}
770
771/// What a symlink at some path turns out to be.
772#[derive(Debug, Clone, PartialEq, Eq)]
773pub enum LinkClass {
774    /// A link to a directory inside the root, at this canonical path.
775    InsideDir(PathBuf),
776    /// A link nothing may be written through.
777    Blocked(ParentBlocker),
778}
779
780/// Classifies the symlink at `link` by resolving it.
781///
782/// Resolving the link can trigger an automount lookup, so callers apply it
783/// only to a path already known to be a symlink.
784pub fn classify_link<V: FsView>(view: &V, link: &Path, root: &V::Root) -> LinkClass {
785    match view.canonicalize(link, root) {
786        Ok(Containment::Within(resolved)) if view.is_dir(&resolved) => {
787            LinkClass::InsideDir(resolved)
788        }
789        Ok(Containment::Escapes) => LinkClass::Blocked(ParentBlocker::Escape),
790        Ok(Containment::Within(_)) | Err(_) => LinkClass::Blocked(ParentBlocker::Symlink),
791    }
792}
793
794/// The first parent of `rel` that is not a directory `rel` can be created in,
795/// looked up through `view`. `None` when no parent is to blame, including a
796/// parent that cannot be inspected.
797pub fn first_blocking_ancestor<V: FsView>(
798    view: &V,
799    root: &V::Root,
800    rel: &Path,
801) -> Option<(PathBuf, ParentBlocker)> {
802    let mut prefix = PathBuf::new();
803    for component in rel.parent()?.components() {
804        prefix.push(component);
805        let full = root.as_path().join(&prefix);
806        let blocker = if view.is_symlink(&full).ok()? {
807            match classify_link(view, &full, root) {
808                LinkClass::InsideDir(_) => continue,
809                LinkClass::Blocked(blocker) => blocker,
810            }
811        } else if view.is_dir(&full) {
812            continue;
813        } else if view.exists(&full) {
814            ParentBlocker::File
815        } else {
816            return None;
817        };
818        return Some((prefix, blocker));
819    }
820    None
821}
822
823/// The refusal for `rel` when [`first_blocking_ancestor`] finds a parent to
824/// blame for a failed probe of `rel`.
825pub fn blocked_parent_error<V: FsView>(
826    view: &V,
827    root: &V::Root,
828    rel: &Path,
829) -> Option<ArchiveError> {
830    first_blocking_ancestor(view, root, rel).map(|(parent, blocker)| blocker.error(rel, &parent))
831}
832
833/// Whether a projected landing is held to the model's name limits.
834#[derive(Debug, Clone, Copy, PartialEq, Eq)]
835pub enum LandingLimits {
836    /// The landing must fit the model.
837    Enforced,
838    /// The entry is never created (a regular file the extension allowlist
839    /// skips), so its name cannot be refused.
840    Exempt,
841}
842
843/// A failed [`VirtualTree::project_landing`].
844#[derive(Debug)]
845pub struct Conflict {
846    /// The error `insert` would report.
847    pub(crate) error: io::Error,
848    /// `None` when the failure is in the parent chain, not at the path itself.
849    pub(crate) occupant: Option<Occupant>,
850    /// Set when a parent component blocks the entry.
851    pub(crate) blocked: Option<BlockedParent>,
852}
853
854impl Conflict {
855    pub(crate) fn already_exists(occupant: Occupant) -> Self {
856        Self {
857            error: io::Error::from(io::ErrorKind::AlreadyExists),
858            occupant: Some(occupant),
859            blocked: None,
860        }
861    }
862
863    /// [`already_exists`](Self::already_exists) whose error names `rel` and
864    /// the occupant.
865    pub(crate) fn already_exists_at(occupant: Occupant, rel: &Path) -> Self {
866        Self {
867            error: io::Error::new(io::ErrorKind::AlreadyExists, occupant.refusal(rel)),
868            occupant: Some(occupant),
869            blocked: None,
870        }
871    }
872
873    fn blocked_parent(
874        error: io::Error,
875        entry: &Path,
876        parent: &Path,
877        blocker: ParentBlocker,
878    ) -> Self {
879        Self {
880            error,
881            occupant: None,
882            blocked: Some(BlockedParent {
883                entry: entry.to_path_buf(),
884                parent: parent.to_path_buf(),
885                blocker,
886            }),
887        }
888    }
889
890    /// The error extraction reports: the entry-naming refusal for a blocked
891    /// parent, the plain I/O error otherwise.
892    pub(crate) fn into_archive_error(self) -> ArchiveError {
893        match self.blocked {
894            Some(blocked) => blocked.error(),
895            None => ArchiveError::Io(self.error),
896        }
897    }
898}
899
900impl From<io::Error> for Conflict {
901    fn from(error: io::Error) -> Self {
902        Self {
903            error,
904            occupant: None,
905            blocked: None,
906        }
907    }
908}
909
910/// Bound on the names a [`VirtualTree`] stores.
911///
912/// A name is charged when a node is added and when a differently spelled
913/// alias of a node is remembered, whatever the kind of the entry, so a flood
914/// of directory entries or case variants cannot grow the tree without limit.
915#[derive(Debug, Clone, Copy, PartialEq, Eq)]
916pub struct NodeBudget {
917    max: usize,
918    used: usize,
919}
920
921impl NodeBudget {
922    /// A budget of `max_file_count * max_path_depth + 1` names: enough for
923    /// `max_file_count` files, each at the deepest allowed path with no name
924    /// shared. Explicit directory entries and aliases spend it too although
925    /// `max_file_count` does not count directories, so an archive of many
926    /// directories can exhaust it while within the file limit; raise
927    /// `max_file_count` or `max_path_depth` to allow more. Unbounded when
928    /// `max_file_count` is [`Limit::Unbounded`](crate::Limit::Unbounded); a
929    /// product that overflows saturates at `usize::MAX`.
930    #[must_use]
931    pub fn from_config(config: &SecurityConfig) -> Self {
932        let max = match config.max_file_count {
933            crate::Limit::Bounded(count) => count
934                .get()
935                .saturating_mul(config.max_path_depth.get())
936                .saturating_add(1),
937            crate::Limit::Unbounded => usize::MAX,
938        };
939        Self { max, used: 0 }
940    }
941
942    #[cfg(test)]
943    pub(crate) const fn unbounded() -> Self {
944        Self {
945            max: usize::MAX,
946            used: 0,
947        }
948    }
949
950    #[cfg(test)]
951    pub(crate) const fn with_max(max: usize) -> Self {
952        Self { max, used: 0 }
953    }
954
955    fn charge(&mut self) -> Result<(), NodeBudgetExceeded> {
956        if self.used >= self.max {
957            return Err(NodeBudgetExceeded { max: self.max });
958        }
959        self.used += 1;
960        Ok(())
961    }
962}
963
964/// A [`NodeBudget`] that ran out.
965#[derive(Debug, Clone, Copy, PartialEq, Eq)]
966pub struct NodeBudgetExceeded {
967    max: usize,
968}
969
970impl From<NodeBudgetExceeded> for ArchiveError {
971    fn from(exceeded: NodeBudgetExceeded) -> Self {
972        Self::QuotaExceeded {
973            resource: QuotaResource::TreeNodes { max: exceeded.max },
974        }
975    }
976}
977
978/// Whether a [`VirtualTree`] keeps the name collisions it detects.
979///
980/// `verify` reports them; a sink only needs the merged path, so recording
981/// there would grow memory with every case variant for nothing.
982#[derive(Debug, Clone, Copy, PartialEq, Eq)]
983pub enum CollisionRecording {
984    /// Keep collisions for [`VirtualTree::take_collisions`] and
985    /// [`VirtualTree::take_empty_merges`].
986    Record,
987    /// Merge the names and forget that they collided.
988    Discard,
989}
990
991/// Why a [`VirtualTree`] refused to place a node.
992#[derive(Debug)]
993pub enum PlaceError {
994    /// Extraction would fail or change what a path resolves to.
995    Conflict(Conflict),
996    /// The tree is full.
997    Budget(NodeBudgetExceeded),
998    /// The node landed at a path the model cannot hold.
999    LandingTooLong,
1000}
1001
1002impl PlaceError {
1003    #[cfg(test)]
1004    pub(crate) fn into_conflict(self) -> Conflict {
1005        match self {
1006            Self::Conflict(conflict) => conflict,
1007            other => panic!("unexpected placement error: {other:?}"),
1008        }
1009    }
1010}
1011
1012impl From<Conflict> for PlaceError {
1013    fn from(conflict: Conflict) -> Self {
1014        Self::Conflict(conflict)
1015    }
1016}
1017
1018impl From<io::Error> for PlaceError {
1019    fn from(error: io::Error) -> Self {
1020        Self::Conflict(error.into())
1021    }
1022}
1023
1024impl From<NodeBudgetExceeded> for PlaceError {
1025    fn from(exceeded: NodeBudgetExceeded) -> Self {
1026        Self::Budget(exceeded)
1027    }
1028}
1029
1030type FoldFn = for<'a> fn(&'a OsStr) -> Cow<'a, OsStr>;
1031
1032/// The kind of a node in the in-memory tree.
1033#[derive(Debug, Clone, PartialEq, Eq)]
1034pub enum Node {
1035    /// A directory.
1036    Dir,
1037    /// A regular file or materialized hardlink.
1038    File,
1039    /// A symlink with its target exactly as stored in the archive.
1040    Symlink(PathBuf),
1041    /// A symlink whose target was not read, so nothing can be resolved through
1042    /// it: it exists, but a path that runs through it or lands on it while
1043    /// being resolved is an error.
1044    OpaqueSymlink,
1045}
1046
1047#[derive(Debug)]
1048struct TreeNode {
1049    kind: Node,
1050    /// The component exactly as the archive spells it.
1051    name: OsString,
1052    /// The directory holding this node; the root is its own parent.
1053    parent: usize,
1054    /// Only populated for directories; every spelling seen so far (the node's
1055    /// own and its aliases) mapped to the child, so a repeated spelling is
1056    /// found without folding it.
1057    children: HashMap<OsString, usize>,
1058    /// Folded component to child; empty on hosts that compare names exactly.
1059    folded: HashMap<OsString, usize>,
1060    /// Pairs of spellings of this directory that merged while it was empty: if
1061    /// it later gains an entry the merge stops being harmless.
1062    empty_merges: Vec<(PathBuf, PathBuf)>,
1063}
1064
1065impl TreeNode {
1066    fn new(kind: Node, name: &OsStr, parent: usize) -> Self {
1067        Self {
1068            kind,
1069            name: name.to_os_string(),
1070            parent,
1071            children: HashMap::new(),
1072            folded: HashMap::new(),
1073            empty_merges: Vec::new(),
1074        }
1075    }
1076}
1077
1078const ROOT: usize = 0;
1079
1080enum Resolved {
1081    Inside { rel: PathBuf, id: usize },
1082    Outside,
1083}
1084
1085/// Where an insert put its node.
1086struct Landed {
1087    parent: usize,
1088    /// The node that already held the name, if any.
1089    existing: Option<usize>,
1090}
1091
1092/// A child found by name.
1093#[derive(Clone, Copy)]
1094struct Found {
1095    id: usize,
1096    /// Found only through the fold: the archive spells it differently.
1097    alias: bool,
1098}
1099
1100/// In-memory model of the destination directory built from archive entries.
1101///
1102/// Stored as a per-directory component trie, so a lookup or insert costs
1103/// O(bytes of the path) regardless of how many entries share a prefix. A name
1104/// is folded only the first time it is seen; repeats, such as the parents of
1105/// every entry in a directory, hit the exact-spelling map.
1106///
1107/// Every name it stores is charged to a [`NodeBudget`].
1108pub struct VirtualTree {
1109    root: PathBuf,
1110    nodes: Vec<TreeNode>,
1111    model: PathModel,
1112    fold: FoldFn,
1113    budget: NodeBudget,
1114    recording: CollisionRecording,
1115    collisions: Vec<NameCollision>,
1116    /// Directories holding at least one empty merge.
1117    empty_merge_nodes: Vec<usize>,
1118    /// Whether any symlink was ever stored: until one is, no path can land
1119    /// anywhere but where it is spelled.
1120    links_seen: bool,
1121    /// Whether any name was ever found under another spelling.
1122    aliases_seen: bool,
1123}
1124
1125impl VirtualTree {
1126    /// Creates an empty tree rooted at `root` that applies `model`.
1127    pub fn new(
1128        root: &VirtualRoot,
1129        model: PathModel,
1130        budget: NodeBudget,
1131        recording: CollisionRecording,
1132    ) -> Self {
1133        let fold = match model {
1134            PathModel::Host => fold,
1135            PathModel::Portable => portable_fold,
1136        };
1137        Self::build(root, model, fold, budget, recording)
1138    }
1139
1140    #[cfg(test)]
1141    pub(crate) fn for_test(root: &VirtualRoot) -> Self {
1142        Self::with_fold(root, fold)
1143    }
1144
1145    #[cfg(test)]
1146    pub(crate) fn with_fold(root: &VirtualRoot, fold: FoldFn) -> Self {
1147        Self::build(
1148            root,
1149            PathModel::Host,
1150            fold,
1151            NodeBudget::unbounded(),
1152            CollisionRecording::Record,
1153        )
1154    }
1155
1156    fn build(
1157        root: &VirtualRoot,
1158        model: PathModel,
1159        fold: FoldFn,
1160        budget: NodeBudget,
1161        recording: CollisionRecording,
1162    ) -> Self {
1163        Self {
1164            root: root.as_path().to_path_buf(),
1165            nodes: vec![TreeNode::new(Node::Dir, OsStr::new(""), ROOT)],
1166            model,
1167            fold,
1168            budget,
1169            recording,
1170            collisions: Vec::new(),
1171            empty_merge_nodes: Vec::new(),
1172            links_seen: false,
1173            aliases_seen: false,
1174        }
1175    }
1176
1177    /// Records `node` at `rel` (relative to the root), creating missing
1178    /// parents as directories and following in-root symlinked parents the way
1179    /// `create_dir_all` does.
1180    ///
1181    /// Names that differ exactly but fold to one key are one name on the host.
1182    /// Each such pair is recorded once as a [`NameCollision`] (see
1183    /// [`take_collisions`](Self::take_collisions)) and then handled like an
1184    /// exact repeat, so a merge is never silent.
1185    ///
1186    /// The first node at a path wins, matching extraction that skips an
1187    /// existing entry. A symlink over a file is ambiguous (extraction skips
1188    /// it by default but replaces the file when overwriting): the file is
1189    /// replaced so later entries are checked against the riskier tree, and an
1190    /// error is returned so the archive is never reported as safe. A symlink
1191    /// over a directory or a symlink with a different target is refused the
1192    /// same way, but the existing node stays; a symlink with the same target is
1193    /// an unchanged duplicate.
1194    ///
1195    /// # Errors
1196    ///
1197    /// Returns a conflict where extraction can fail: a parent that is a file or
1198    /// a dangling symlink, a parent chain that loops or leaves the root, a
1199    /// directory entry over an existing non-directory, a symlink over an
1200    /// earlier file, directory or symlink with another target, or a file over
1201    /// an earlier directory (`IsADirectory`) or symlink.
1202    ///
1203    /// A failure also names what already occupies the path, so a caller can
1204    /// tell what overwriting would do. A tree that is out of budget refuses
1205    /// with [`PlaceError::Budget`].
1206    #[cfg(test)]
1207    pub(crate) fn try_insert(&mut self, rel: &Path, node: Node) -> Result<(), PlaceError> {
1208        self.insert_node(rel, node).map(drop)
1209    }
1210
1211    /// Places `node` at `rel` and returns where it landed, with every symlinked
1212    /// parent resolved and every component spelled as the tree first stored it,
1213    /// so two spellings of one name give one path.
1214    ///
1215    /// The one projection of a landing: the sink and `verify` both judge an
1216    /// entry by it. The entry's own name was checked before it was resolved
1217    /// through earlier symlinks, and the path it lands at can be longer, so the
1218    /// landing is checked against the model's name limits here.
1219    ///
1220    /// The returned path is relative, normalized and built only from names the
1221    /// tree stored from validated entries. It is not re-checked against
1222    /// `max_path_depth`: a landing reached through a link can be deeper than
1223    /// the entry's own path.
1224    ///
1225    /// # Errors
1226    ///
1227    /// Returns a conflict where extraction can fail (a parent that is a file or
1228    /// a dangling symlink, a chain that loops or leaves the root, or an
1229    /// occupant the node cannot replace; the failure names what occupies the
1230    /// path), [`PlaceError::Budget`] when the tree is full, or
1231    /// [`PlaceError::LandingTooLong`] when the landing exceeds the model's
1232    /// limits and `limits` is [`LandingLimits::Enforced`].
1233    pub(crate) fn project_landing<P: ParentCheck>(
1234        &mut self,
1235        rel: &SafePath<P>,
1236        node: Node,
1237        limits: LandingLimits,
1238    ) -> Result<SafePath, PlaceError> {
1239        self.guard_landing(rel.as_path(), limits)?;
1240        let landed = self.place_path(rel.as_path(), node)?;
1241        if limits == LandingLimits::Enforced {
1242            self.model
1243                .check_name_lengths(&landed)
1244                .map_err(|_| PlaceError::LandingTooLong)?;
1245        }
1246        Ok(SafePath::from_normalized(landed)?)
1247    }
1248
1249    /// [`project_landing`](Self::project_landing) for a caller that only needs
1250    /// the verdict, such as `verify`.
1251    ///
1252    /// While no symlink was ever stored and no name was found under another
1253    /// spelling, every path lands where it is spelled, so the one walk of the
1254    /// path by the length check before the insert settles it and the landing is
1255    /// never built. Any symlink or alias in the tree takes the full projection.
1256    ///
1257    /// # Errors
1258    ///
1259    /// Same as [`project_landing`](Self::project_landing).
1260    pub(crate) fn check_landing<P: ParentCheck>(
1261        &mut self,
1262        rel: &SafePath<P>,
1263        node: Node,
1264        limits: LandingLimits,
1265    ) -> Result<(), PlaceError> {
1266        let links_before = self.links_seen;
1267        self.guard_landing(rel.as_path(), limits)?;
1268        let landed = self.insert_node(rel.as_path(), node)?;
1269        if limits == LandingLimits::Enforced && (links_before || self.aliases_seen) {
1270            let landing = self.landing_path(rel.as_path(), landed);
1271            self.model
1272                .check_name_lengths(&landing)
1273                .map_err(|_| PlaceError::LandingTooLong)?;
1274        }
1275        Ok(())
1276    }
1277
1278    /// Refuses, before anything is inserted, a landing the model cannot hold.
1279    fn guard_landing(&self, rel: &Path, limits: LandingLimits) -> Result<(), PlaceError> {
1280        if limits != LandingLimits::Enforced {
1281            return Ok(());
1282        }
1283        let too_long = if self.links_seen {
1284            self.projected_landing(rel)
1285                .is_some_and(|landing| self.model.check_name_lengths(&landing).is_err())
1286        } else {
1287            self.model.check_name_lengths(rel).is_err()
1288        };
1289        if too_long {
1290            return Err(PlaceError::LandingTooLong);
1291        }
1292        Ok(())
1293    }
1294
1295    /// Where `rel` would land, read from the tree without inserting anything:
1296    /// the longest existing parent resolved through its links, then the rest of
1297    /// the path as spelled. `None` when the parents do not resolve (a conflict
1298    /// the insert reports itself).
1299    ///
1300    /// Names are taken as `rel` spells them, so a folded alias of different
1301    /// byte length is only caught by the check after the insert.
1302    fn projected_landing(&self, rel: &Path) -> Option<PathBuf> {
1303        let name = rel.file_name()?;
1304        let parent = rel.parent().unwrap_or_else(|| Path::new(""));
1305        let mut missing = Vec::new();
1306        let mut existing = parent;
1307        loop {
1308            match self.resolve(&self.root.join(existing)) {
1309                Ok(Resolved::Inside { rel: base, .. }) => {
1310                    let mut landing = base;
1311                    landing.extend(missing.iter().rev());
1312                    landing.push(name);
1313                    return Some(landing);
1314                }
1315                Err(error) if error.kind() == io::ErrorKind::NotFound => {
1316                    missing.push(existing.file_name()?);
1317                    existing = existing.parent()?;
1318                }
1319                Ok(Resolved::Outside) | Err(_) => return None,
1320            }
1321        }
1322    }
1323
1324    fn place_path(&mut self, rel: &Path, node: Node) -> Result<PathBuf, PlaceError> {
1325        let landed = self.insert_node(rel, node)?;
1326        Ok(self.landing_path(rel, landed))
1327    }
1328
1329    /// The path an insert landed at, spelled by the stored names.
1330    fn landing_path(&self, rel: &Path, landed: Option<Landed>) -> PathBuf {
1331        landed.map_or_else(PathBuf::new, |landed| {
1332            let leaf = landed.existing.map_or_else(
1333                || rel.file_name(),
1334                |id| Some(self.node(id).name.as_os_str()),
1335            );
1336            let mut resolved = self.path_of(landed.parent);
1337            resolved.extend(leaf);
1338            resolved
1339        })
1340    }
1341
1342    /// The path of node `id` relative to the root, spelled by the stored names.
1343    fn path_of(&self, mut id: usize) -> PathBuf {
1344        let mut names = Vec::new();
1345        while id != ROOT {
1346            let node = self.node(id);
1347            names.push(node.name.as_os_str());
1348            id = node.parent;
1349        }
1350        names.into_iter().rev().collect()
1351    }
1352
1353    fn insert_node(&mut self, rel: &Path, node: Node) -> Result<Option<Landed>, PlaceError> {
1354        let Some(name) = rel.file_name() else {
1355            return Ok(None);
1356        };
1357        let parent = self.ensure_dir(rel.parent().unwrap_or_else(|| Path::new("")), rel)?;
1358        let existing = self.lookup(parent, name);
1359        if let Some(found) = existing {
1360            self.settle_alias(parent, found, name, &node, rel, false)?;
1361        }
1362        let existing = existing.map(|f| f.id);
1363        let outcome = match (existing, node) {
1364            (None, node) => {
1365                self.add_child(parent, name, node)?;
1366                Ok(())
1367            }
1368            (Some(id), Node::Dir) => match self.node(id).kind {
1369                Node::Dir => Ok(()),
1370                Node::File => Err(Conflict::already_exists_at(Occupant::File, rel)),
1371                Node::OpaqueSymlink => Err(Conflict::already_exists_at(Occupant::Symlink, rel)),
1372                Node::Symlink(_) => self
1373                    .resolves_to_dir(&self.root.join(rel))
1374                    .ok_or_else(|| Conflict::already_exists_at(Occupant::Symlink, rel)),
1375            },
1376            (Some(id), node @ (Node::Symlink(_) | Node::OpaqueSymlink)) => {
1377                match self.node(id).kind {
1378                    Node::File => {
1379                        self.node_mut(id).kind = node;
1380                        self.links_seen = true;
1381                        Err(Conflict::already_exists(Occupant::File))
1382                    }
1383                    Node::Dir => Err(Conflict::already_exists(Occupant::Directory)),
1384                    Node::Symlink(ref kept) if matches!(&node, Node::Symlink(t) if t == kept) => {
1385                        Ok(())
1386                    }
1387                    Node::Symlink(_) | Node::OpaqueSymlink => {
1388                        Err(Conflict::already_exists(Occupant::Symlink))
1389                    }
1390                }
1391            }
1392            (Some(id), Node::File) => match self.node(id).kind {
1393                Node::File => Ok(()),
1394                Node::Dir => Err(Conflict {
1395                    error: io::Error::from(io::ErrorKind::IsADirectory),
1396                    occupant: Some(Occupant::Directory),
1397                    blocked: None,
1398                }),
1399                Node::Symlink(_) | Node::OpaqueSymlink => {
1400                    Err(Conflict::already_exists(Occupant::Symlink))
1401                }
1402            },
1403        };
1404        outcome
1405            .map(|()| Some(Landed { parent, existing }))
1406            .map_err(PlaceError::Conflict)
1407    }
1408
1409    #[cfg(test)]
1410    pub(crate) fn insert(&mut self, rel: &Path, node: Node) -> io::Result<()> {
1411        self.try_insert(rel, node)
1412            .map_err(|err| err.into_conflict().error)
1413    }
1414
1415    /// What an earlier entry left at `rel`, without following a link at the
1416    /// path itself; a parent link is followed as extraction would.
1417    pub(crate) fn occupant(&self, rel: &Path) -> Option<Occupant> {
1418        let name = rel.file_name()?;
1419        let parent = match self.resolve(&self.root.join(rel.parent()?)) {
1420            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir => id,
1421            _ => return None,
1422        };
1423        let found = self.lookup(parent, name)?;
1424        Some(match self.node(found.id).kind {
1425            Node::Dir => Occupant::Directory,
1426            Node::File => Occupant::File,
1427            Node::Symlink(_) | Node::OpaqueSymlink => Occupant::Symlink,
1428        })
1429    }
1430
1431    /// Returns `true` if `path` resolves, through symlinks, to a directory.
1432    pub fn resolves_to_dir(&self, path: &Path) -> bool {
1433        matches!(
1434            self.resolve(path),
1435            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir
1436        )
1437    }
1438
1439    /// Drains the name collisions recorded by inserts since the last call.
1440    ///
1441    /// Merges of directories that hold nothing are not included: they are
1442    /// harmless unless an entry lands in the directory later, so they wait for
1443    /// [`take_empty_merges`](Self::take_empty_merges).
1444    pub(crate) fn take_collisions(&mut self) -> Vec<NameCollision> {
1445        std::mem::take(&mut self.collisions)
1446    }
1447
1448    /// Drains the merges of directories that are still empty.
1449    pub(crate) fn take_empty_merges(&mut self) -> Vec<NameCollision> {
1450        let nodes = std::mem::take(&mut self.empty_merge_nodes);
1451        nodes
1452            .into_iter()
1453            .flat_map(|id| std::mem::take(&mut self.node_mut(id).empty_merges))
1454            .map(|(existing, incoming)| NameCollision {
1455                existing,
1456                incoming,
1457                kind: CollisionKind::Directories,
1458            })
1459            .collect()
1460    }
1461
1462    /// Handles a child found by a differently spelled name: remembers the
1463    /// spelling, so the pair is reported once, and records the collision.
1464    ///
1465    /// `incoming_has_contents` is true when the spelling is used as the parent
1466    /// of an entry, which makes a directory merge harmful at once; an empty
1467    /// merge is flagged so it is upgraded if the directory gains an entry.
1468    fn settle_alias(
1469        &mut self,
1470        parent: usize,
1471        found: Found,
1472        name: &OsStr,
1473        incoming_node: &Node,
1474        incoming: &Path,
1475        incoming_has_contents: bool,
1476    ) -> Result<(), NodeBudgetExceeded> {
1477        if !found.alias {
1478            return Ok(());
1479        }
1480        self.aliases_seen = true;
1481        self.budget.charge()?;
1482        self.node_mut(parent)
1483            .children
1484            .insert(name.to_os_string(), found.id);
1485        if self.recording == CollisionRecording::Discard {
1486            return Ok(());
1487        }
1488        let existing = self.node(found.id);
1489        let has_contents = incoming_has_contents || !existing.children.is_empty();
1490        let kind = CollisionKind::of(&existing.kind, incoming_node, has_contents);
1491        let existing_path = incoming.with_file_name(&existing.name);
1492        if kind == CollisionKind::Directories {
1493            let node = self.node_mut(found.id);
1494            node.empty_merges
1495                .push((existing_path, incoming.to_path_buf()));
1496            self.empty_merge_nodes.push(found.id);
1497            return Ok(());
1498        }
1499        self.collisions.push(NameCollision {
1500            existing: existing_path,
1501            incoming: incoming.to_path_buf(),
1502            kind,
1503        });
1504        Ok(())
1505    }
1506
1507    fn node(&self, id: usize) -> &TreeNode {
1508        &self.nodes[id]
1509    }
1510
1511    fn node_mut(&mut self, id: usize) -> &mut TreeNode {
1512        &mut self.nodes[id]
1513    }
1514
1515    fn lookup(&self, parent: usize, name: &OsStr) -> Option<Found> {
1516        if self.model.name_len(name) > self.model.limits().component {
1517            return None;
1518        }
1519        let node = self.node(parent);
1520        if let Some(&id) = node.children.get(name) {
1521            return Some(Found { id, alias: false });
1522        }
1523        match (self.fold)(name) {
1524            Cow::Borrowed(_) => None,
1525            Cow::Owned(key) => node.folded.get(&key).map(|&id| Found { id, alias: true }),
1526        }
1527    }
1528
1529    fn child(&self, parent: usize, name: &OsStr) -> Option<usize> {
1530        self.lookup(parent, name).map(|found| found.id)
1531    }
1532
1533    /// Adds a node under `parent`.
1534    fn add_child(
1535        &mut self,
1536        parent: usize,
1537        name: &OsStr,
1538        kind: Node,
1539    ) -> Result<usize, NodeBudgetExceeded> {
1540        self.budget.charge()?;
1541        self.links_seen |= matches!(kind, Node::Symlink(_) | Node::OpaqueSymlink);
1542        let id = self.nodes.len();
1543        self.nodes.push(TreeNode::new(kind, name, parent));
1544        let key = match (self.fold)(name) {
1545            Cow::Borrowed(_) => None,
1546            Cow::Owned(key) => Some(key),
1547        };
1548        let upgrade = {
1549            let parent_node = self.node_mut(parent);
1550            parent_node.children.insert(name.to_os_string(), id);
1551            if let Some(key) = key {
1552                parent_node.folded.insert(key, id);
1553            }
1554            std::mem::take(&mut parent_node.empty_merges)
1555        };
1556        for (existing, incoming) in upgrade {
1557            self.collisions.push(NameCollision {
1558                existing,
1559                incoming,
1560                kind: CollisionKind::DirectoriesWithContents,
1561            });
1562        }
1563        Ok(id)
1564    }
1565
1566    fn ensure_dir(&mut self, dir: &Path, entry: &Path) -> Result<usize, PlaceError> {
1567        let mut current = ROOT;
1568        let mut walked = PathBuf::new();
1569        for component in dir.components() {
1570            let name = match component {
1571                Component::Normal(name) => name,
1572                Component::CurDir => continue,
1573                _ => return Err(io::Error::from(io::ErrorKind::InvalidInput).into()),
1574            };
1575            walked.push(name);
1576            let blocked = |kind: io::ErrorKind, blocker: ParentBlocker| {
1577                PlaceError::Conflict(Conflict::blocked_parent(
1578                    io::Error::from(kind),
1579                    entry,
1580                    &walked,
1581                    blocker,
1582                ))
1583            };
1584            current = match self.lookup(current, name) {
1585                None => self.add_child(current, name, Node::Dir)?,
1586                Some(found) => {
1587                    self.settle_alias(current, found, name, &Node::Dir, &walked, true)?;
1588                    match self.node(found.id).kind {
1589                        Node::Dir => found.id,
1590                        Node::File => {
1591                            return Err(blocked(io::ErrorKind::NotADirectory, ParentBlocker::File));
1592                        }
1593                        Node::OpaqueSymlink => return Err(unread_target_error().into()),
1594                        Node::Symlink(_) => match self.resolve(&self.root.join(&walked)) {
1595                            Ok(Resolved::Inside { id, .. }) if self.node(id).kind == Node::Dir => {
1596                                id
1597                            }
1598                            Ok(Resolved::Inside { .. }) => {
1599                                return Err(blocked(
1600                                    io::ErrorKind::NotADirectory,
1601                                    ParentBlocker::Symlink,
1602                                ));
1603                            }
1604                            Err(e) => return Err(blocked(e.kind(), ParentBlocker::Symlink)),
1605                            Ok(Resolved::Outside) => {
1606                                return Err(
1607                                    io::Error::other("path leaves the extraction root").into()
1608                                );
1609                            }
1610                        },
1611                    }
1612                }
1613            };
1614        }
1615        Ok(current)
1616    }
1617
1618    fn resolve(&self, path: &Path) -> io::Result<Resolved> {
1619        let Ok(rel) = path.strip_prefix(&self.root) else {
1620            return Ok(Resolved::Outside);
1621        };
1622        let mut pending: VecDeque<Component<'_>> = rel.components().collect();
1623        let mut stack = vec![ROOT];
1624        let mut current = PathBuf::new();
1625        let mut hops = 0;
1626
1627        while let Some(component) = pending.pop_front() {
1628            match component {
1629                Component::CurDir => {}
1630                Component::ParentDir => {
1631                    if stack.len() == 1 {
1632                        return Ok(Resolved::Outside);
1633                    }
1634                    stack.pop();
1635                    current.pop();
1636                }
1637                Component::Normal(name) => {
1638                    let top = stack.last().copied().unwrap_or(ROOT);
1639                    let Some(id) = self.child(top, name) else {
1640                        return Err(io::Error::from(io::ErrorKind::NotFound));
1641                    };
1642                    match &self.node(id).kind {
1643                        Node::Dir => {
1644                            stack.push(id);
1645                            current.push(&self.node(id).name);
1646                        }
1647                        Node::File => {
1648                            if !pending.is_empty() {
1649                                return Err(io::Error::from(io::ErrorKind::NotADirectory));
1650                            }
1651                            stack.push(id);
1652                            current.push(&self.node(id).name);
1653                        }
1654                        Node::OpaqueSymlink => {
1655                            if !pending.is_empty() {
1656                                return Err(unread_target_error());
1657                            }
1658                            stack.push(id);
1659                            current.push(&self.node(id).name);
1660                        }
1661                        Node::Symlink(target) => {
1662                            hops += 1;
1663                            if hops > self.model.limits().hops {
1664                                return Err(io::Error::other("too many levels of symbolic links"));
1665                            }
1666                            if target.has_root()
1667                                || target.components().next().is_some_and(is_prefix)
1668                            {
1669                                return Ok(Resolved::Outside);
1670                            }
1671                            for part in target.components().rev() {
1672                                pending.push_front(part);
1673                            }
1674                        }
1675                    }
1676                }
1677                Component::RootDir | Component::Prefix(_) => {
1678                    return Ok(Resolved::Outside);
1679                }
1680            }
1681        }
1682        Ok(Resolved::Inside {
1683            rel: current,
1684            id: stack.last().copied().unwrap_or(ROOT),
1685        })
1686    }
1687}
1688
1689impl FsView for VirtualTree {
1690    type Root = VirtualRoot;
1691
1692    fn path_model(&self) -> PathModel {
1693        self.model
1694    }
1695
1696    fn exists(&self, path: &Path) -> bool {
1697        matches!(self.resolve(path), Ok(Resolved::Inside { .. }))
1698    }
1699
1700    fn is_dir(&self, path: &Path) -> bool {
1701        self.resolves_to_dir(path)
1702    }
1703
1704    fn is_symlink(&self, path: &Path) -> io::Result<bool> {
1705        let not_found = || io::Error::from(io::ErrorKind::NotFound);
1706        let Ok(rel) = path.strip_prefix(&self.root) else {
1707            return Err(not_found());
1708        };
1709        let Some(name) = rel.file_name() else {
1710            return Ok(false);
1711        };
1712        let parent = self
1713            .root
1714            .join(rel.parent().unwrap_or_else(|| Path::new("")));
1715        let Resolved::Inside { id: parent, .. } = self.resolve(&parent)? else {
1716            return Err(not_found());
1717        };
1718        let id = self.child(parent, name).ok_or_else(not_found)?;
1719        Ok(matches!(
1720            self.node(id).kind,
1721            Node::Symlink(_) | Node::OpaqueSymlink
1722        ))
1723    }
1724
1725    fn canonicalize(&self, path: &Path, _: &VirtualRoot) -> io::Result<Containment> {
1726        match self.resolve(path)? {
1727            Resolved::Inside { id, .. } if self.node(id).kind == Node::OpaqueSymlink => {
1728                Err(unread_target_error())
1729            }
1730            Resolved::Inside { rel, .. } => Ok(Containment::Within(self.root.join(rel))),
1731            Resolved::Outside => Ok(Containment::Escapes),
1732        }
1733    }
1734}
1735
1736fn unread_target_error() -> io::Error {
1737    io::Error::other("path runs through a symlink whose target was not read")
1738}
1739
1740fn is_prefix(component: Component<'_>) -> bool {
1741    matches!(component, Component::Prefix(_))
1742}
1743
1744/// Compares names the way the host does, as far as it can be modelled.
1745///
1746/// A name that is not valid UTF-8 is kept as it is: a lossy fold would give two
1747/// different byte strings one key and report a collision that is not one.
1748#[cfg(target_os = "macos")]
1749fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1750    portable_fold(name)
1751}
1752
1753#[cfg(target_os = "windows")]
1754fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1755    let Some(text) = name.to_str() else {
1756        return Cow::Borrowed(name);
1757    };
1758    let folded = if text.is_ascii() {
1759        text.to_ascii_uppercase()
1760    } else {
1761        fold_unicode(text)
1762    };
1763    Cow::Owned(OsString::from(folded))
1764}
1765
1766#[cfg(not(any(target_os = "macos", target_os = "windows")))]
1767fn fold(name: &OsStr) -> Cow<'_, OsStr> {
1768    Cow::Borrowed(name)
1769}
1770
1771/// The fold of [`PathModel::Portable`], the same on every host: the key
1772/// macOS uses.
1773fn portable_fold(name: &OsStr) -> Cow<'_, OsStr> {
1774    let Some(text) = name.to_str() else {
1775        return Cow::Borrowed(name);
1776    };
1777    let folded = if text.is_ascii() {
1778        text.to_ascii_uppercase()
1779    } else {
1780        decomposed_fold(text)
1781    };
1782    Cow::Owned(OsString::from(folded))
1783}
1784
1785/// APFS compares canonically decomposed names case-insensitively.
1786fn decomposed_fold(text: &str) -> String {
1787    use unicode_normalization::UnicodeNormalization;
1788    upper_lower_upper(text.nfd())
1789}
1790
1791/// NTFS compares names case-insensitively without normalisation.
1792#[cfg(target_os = "windows")]
1793fn fold_unicode(text: &str) -> String {
1794    upper_lower_upper(text.chars())
1795}
1796
1797/// Full per-character case folding built from the standard library only.
1798///
1799/// Upper-casing first merges `ß` with `ẞ`, lower-casing merges the final
1800/// sigma and `ϴ` with `θ`, and the last upper-casing makes the key stable.
1801fn upper_lower_upper(chars: impl Iterator<Item = char>) -> String {
1802    chars
1803        .flat_map(char::to_uppercase)
1804        .flat_map(char::to_lowercase)
1805        .flat_map(char::to_uppercase)
1806        .collect()
1807}
1808
1809#[cfg(test)]
1810#[allow(clippy::unwrap_used, clippy::expect_used)]
1811mod tests {
1812    use super::*;
1813    use std::assert_matches;
1814
1815    fn tree() -> VirtualTree {
1816        VirtualTree::with_fold(&VirtualRoot::at("/dest"), fold)
1817    }
1818
1819    fn put(t: &mut VirtualTree, path: &str, node: Node) {
1820        t.insert(Path::new(path), node).unwrap();
1821    }
1822
1823    fn canon(t: &VirtualTree, path: &str) -> io::Result<Containment> {
1824        t.canonicalize(Path::new(path), &VirtualRoot::at("/dest"))
1825    }
1826
1827    fn within(t: &VirtualTree, path: &str) -> PathBuf {
1828        match canon(t, path).unwrap() {
1829            Containment::Within(p) => p,
1830            Containment::Escapes => panic!("{path} escapes"),
1831        }
1832    }
1833
1834    fn sym(target: &str) -> Node {
1835        Node::Symlink(PathBuf::from(target))
1836    }
1837
1838    #[test]
1839    fn insert_creates_implicit_parents() {
1840        let mut t = tree();
1841        put(&mut t, "a/b/c.txt", Node::File);
1842        assert!(t.exists(Path::new("/dest/a/b")));
1843        assert!(t.exists(Path::new("/dest/a/b/c.txt")));
1844        assert!(!t.exists(Path::new("/dest/a/x")));
1845    }
1846
1847    #[test]
1848    fn missing_component_is_not_found() {
1849        let t = tree();
1850        let err = canon(&t, "/dest/nope").unwrap_err();
1851        assert_eq!(err.kind(), io::ErrorKind::NotFound);
1852    }
1853
1854    #[test]
1855    fn in_root_chain_resolves_to_final_location() {
1856        let mut t = tree();
1857        put(&mut t, "real", Node::Dir);
1858        put(&mut t, "b", sym("real"));
1859        put(&mut t, "a", sym("b"));
1860        assert_eq!(within(&t, "/dest/a"), PathBuf::from("/dest/real"));
1861    }
1862
1863    #[test]
1864    fn chain_leaving_root_escapes() {
1865        let mut t = tree();
1866        put(&mut t, "y", sym("."));
1867        put(&mut t, "d", sym("y/.."));
1868        put(&mut t, "e", sym("d/.."));
1869        assert_eq!(canon(&t, "/dest/e/secret").unwrap(), Containment::Escapes);
1870    }
1871
1872    #[test]
1873    fn a_path_that_leaves_the_root_and_reenters_it_still_escapes() {
1874        let mut t = VirtualTree::for_test(&VirtualRoot::new());
1875        put(&mut t, "up", sym(".."));
1876        put(&mut t, "abs", sym("/exarch-virtual-root/x"));
1877        let root = VirtualRoot::new();
1878        for target in [
1879            "/exarch-virtual-root/up/exarch-virtual-root/x",
1880            "/exarch-virtual-root/abs",
1881        ] {
1882            assert_eq!(
1883                t.canonicalize(Path::new(target), &root).unwrap(),
1884                Containment::Escapes,
1885                "{target}"
1886            );
1887        }
1888    }
1889
1890    #[test]
1891    fn symlink_loop_is_an_error() {
1892        let mut t = tree();
1893        put(&mut t, "a", sym("b"));
1894        put(&mut t, "b", sym("a"));
1895        assert!(canon(&t, "/dest/a").is_err());
1896    }
1897
1898    #[test]
1899    fn long_chain_hits_hop_limit() {
1900        let mut t = tree();
1901        put(&mut t, "l0", Node::Dir);
1902        for i in 1..=MAX_SYMLINK_HOPS + 1 {
1903            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
1904        }
1905        let over = format!("/dest/l{}", MAX_SYMLINK_HOPS + 1);
1906        let at = format!("/dest/l{MAX_SYMLINK_HOPS}");
1907        assert!(canon(&t, &over).is_err());
1908        assert!(canon(&t, &at).is_ok());
1909    }
1910
1911    #[cfg(any(unix, windows))]
1912    fn make_symlink(target: &str, link: &Path) -> io::Result<()> {
1913        #[cfg(unix)]
1914        return std::os::unix::fs::symlink(target, link);
1915        #[cfg(windows)]
1916        return std::os::windows::fs::symlink_dir(target, link);
1917    }
1918
1919    #[cfg(any(unix, windows))]
1920    #[test]
1921    fn hop_limit_matches_host_canonicalize() {
1922        let temp = tempfile::TempDir::new().unwrap();
1923        // The temp dir itself may sit behind a symlink (/var on macOS), which
1924        // would spend one hop of the chain below.
1925        let root = temp.path().canonicalize().unwrap();
1926        std::fs::create_dir(root.join("l0")).unwrap();
1927
1928        let mut resolvable = 0;
1929        for i in 1..=MAX_SYMLINK_HOPS + 8 {
1930            let linked = make_symlink(&format!("l{}", i - 1), &root.join(format!("l{i}")));
1931            assert!(linked.is_ok(), "cannot create symlinks here: {linked:?}");
1932            if std::fs::canonicalize(root.join(format!("l{i}"))).is_err() {
1933                break;
1934            }
1935            resolvable = i;
1936        }
1937        assert_eq!(resolvable, MAX_SYMLINK_HOPS, "host and model limits differ");
1938
1939        let mut t = tree();
1940        put(&mut t, "l0", Node::Dir);
1941        for i in 1..=resolvable + 1 {
1942            put(&mut t, &format!("l{i}"), sym(&format!("l{}", i - 1)));
1943        }
1944        assert!(canon(&t, &format!("/dest/l{resolvable}")).is_ok());
1945        assert!(canon(&t, &format!("/dest/l{}", resolvable + 1)).is_err());
1946    }
1947
1948    fn ascii_upper(name: &OsStr) -> Cow<'_, OsStr> {
1949        Cow::Owned(OsString::from(name.to_string_lossy().to_ascii_uppercase()))
1950    }
1951
1952    #[cfg(unix)]
1953    #[test]
1954    fn names_that_are_not_utf8_keep_distinct_fold_keys() {
1955        use std::os::unix::ffi::OsStrExt;
1956
1957        let a = OsStr::from_bytes(b"a\xffb");
1958        let b = OsStr::from_bytes(b"a\xfeb");
1959        assert_ne!(portable_fold(a), portable_fold(b));
1960        assert_eq!(portable_fold(a), portable_fold(a));
1961    }
1962
1963    #[cfg(unix)]
1964    #[test]
1965    fn parent_refusals_of_names_differing_in_invalid_bytes_differ() {
1966        use std::os::unix::ffi::OsStrExt;
1967
1968        let name = |bytes: &[u8]| PathBuf::from(OsStr::from_bytes(bytes));
1969        for blocker in [ParentBlocker::File, ParentBlocker::Symlink] {
1970            let message = |entry: &[u8]| {
1971                let parent = name(entry);
1972                blocker.error(&parent.join("f"), &parent).to_string()
1973            };
1974            let (a, b) = (message(b"d\xe9"), message(b"d\xe8"));
1975            assert_ne!(a, b, "{blocker:?}");
1976            assert!(!a.contains('\u{FFFD}'), "{a}");
1977        }
1978    }
1979
1980    fn folding_tree() -> VirtualTree {
1981        VirtualTree::with_fold(&VirtualRoot::at("/dest"), ascii_upper)
1982    }
1983
1984    #[test]
1985    fn place_resolves_in_root_symlinked_parents() {
1986        let mut t = tree();
1987        put(&mut t, "real", Node::Dir);
1988        put(&mut t, "alias", sym("real"));
1989        let placed = t.place_path(Path::new("alias/f"), Node::File).unwrap();
1990        assert_eq!(placed, PathBuf::from("real/f"));
1991    }
1992
1993    #[test]
1994    fn place_spells_a_folded_name_as_first_stored() {
1995        let mut t = folding_tree();
1996        assert_eq!(
1997            t.place_path(Path::new("a/x"), Node::File).unwrap(),
1998            PathBuf::from("a/x")
1999        );
2000        assert_eq!(
2001            t.place_path(Path::new("A/x"), Node::File).unwrap(),
2002            PathBuf::from("a/x")
2003        );
2004        assert_eq!(within(&t, "/dest/A/X"), PathBuf::from("/dest/a/x"));
2005    }
2006
2007    #[test]
2008    fn place_of_the_root_is_empty_and_conflicts_leave_no_path() {
2009        let mut t = tree();
2010        assert_eq!(
2011            t.place_path(Path::new(""), Node::Dir).unwrap(),
2012            PathBuf::new()
2013        );
2014        put(&mut t, "f", Node::File);
2015        assert!(t.place_path(Path::new("f"), Node::Dir).is_err());
2016        assert!(t.place_path(Path::new("f/g"), Node::File).is_err());
2017    }
2018
2019    fn lowercase_fold(name: &OsStr) -> Cow<'_, OsStr> {
2020        let text = name.to_string_lossy();
2021        let lowered = text.to_lowercase();
2022        if lowered == text {
2023            Cow::Borrowed(name)
2024        } else {
2025            Cow::Owned(OsString::from(lowered))
2026        }
2027    }
2028
2029    /// What the tree decided and left behind, for either entry point.
2030    fn decision(
2031        setup: fn(&mut VirtualTree),
2032        rel: &str,
2033        verdict_only: bool,
2034    ) -> (&'static str, Option<Occupant>) {
2035        let mut t = VirtualTree::with_fold(&VirtualRoot::at("/dest"), lowercase_fold);
2036        setup(&mut t);
2037        let safe = SafePath::for_test(rel);
2038        let outcome = if verdict_only {
2039            t.check_landing(&safe, Node::File, LandingLimits::Enforced)
2040                .map(drop)
2041        } else {
2042            t.project_landing(&safe, Node::File, LandingLimits::Enforced)
2043                .map(drop)
2044        };
2045        let tag = match outcome {
2046            Ok(()) => "accepted",
2047            Err(PlaceError::LandingTooLong) => "too long",
2048            Err(PlaceError::Conflict(_)) => "conflict",
2049            Err(PlaceError::Budget(_)) => "budget",
2050        };
2051        (tag, t.occupant(Path::new(rel)))
2052    }
2053
2054    type Setup = fn(&mut VirtualTree);
2055
2056    #[cfg(not(windows))]
2057    const KELVIN: &str = "\u{212A}";
2058
2059    #[cfg(not(windows))]
2060    fn components(spelling: &str, count: usize) -> String {
2061        vec![spelling.repeat(80); count].join("/")
2062    }
2063
2064    /// The entry points are one decision: `check_landing` may skip building
2065    /// the landing, never change what is accepted, refused or left behind.
2066    #[test]
2067    fn check_landing_and_project_landing_decide_alike() {
2068        let long = "n".repeat(MAX_PATH_LEN);
2069        let cases: Vec<(&str, Setup, String)> = vec![
2070            ("no link, short", |_| {}, "a/b".to_owned()),
2071            ("no link, long", |_| {}, format!("a/{long}")),
2072            (
2073                "link, short through it",
2074                |t| {
2075                    put(t, "real", Node::Dir);
2076                    put(t, "alias", sym("real"));
2077                },
2078                "alias/f".to_owned(),
2079            ),
2080            (
2081                "link, long through it",
2082                |t| {
2083                    put(t, "real", Node::Dir);
2084                    put(t, "alias", sym("real"));
2085                },
2086                format!("alias/{long}"),
2087            ),
2088            (
2089                "link elsewhere, long beside it",
2090                |t| put(t, "real", Node::Dir),
2091                format!("real/{long}"),
2092            ),
2093            (
2094                "file replaced by a link, then through it",
2095                |t| {
2096                    put(t, "real", Node::Dir);
2097                    put(t, "x", Node::File);
2098                    let _ = t.insert(Path::new("x"), sym("real"));
2099                },
2100                format!("x/{long}"),
2101            ),
2102        ];
2103        for (name, setup, rel) in cases {
2104            assert_eq!(
2105                decision(setup, &rel, true),
2106                decision(setup, &rel, false),
2107                "{name}"
2108            );
2109        }
2110        // Windows counts UTF-16 units, and no fold changes the unit count of
2111        // a name, so a longer spelling of a shorter stored one exists only
2112        // where the limit counts bytes.
2113        #[cfg(not(windows))]
2114        {
2115            let count = MAX_PATH_LEN / (KELVIN.len() * 80) + 1;
2116            let stored = components("k", count);
2117            let alias = components(KELVIN, count);
2118            assert!(stored.len() <= MAX_PATH_LEN && alias.len() > MAX_PATH_LEN);
2119            // A spelling that folds onto a shorter stored one: both entry
2120            // points judge it by the spelling the entry uses.
2121            let setup: fn(&mut VirtualTree) = |t| {
2122                let count = MAX_PATH_LEN / (KELVIN.len() * 80) + 1;
2123                put(t, &components("k", count), Node::Dir);
2124            };
2125            let rel = format!("{alias}/f");
2126            assert_eq!(
2127                decision(setup, &rel, true),
2128                decision(setup, &rel, false),
2129                "alias of another byte length"
2130            );
2131            assert_eq!(decision(setup, &rel, true).0, "too long");
2132            assert_eq!(
2133                decision(setup, &format!("{stored}/f"), true).0,
2134                decision(setup, &format!("{stored}/f"), false).0
2135            );
2136        }
2137    }
2138
2139    #[test]
2140    fn a_tree_without_links_checks_the_spelled_path_before_inserting() {
2141        let mut t = tree();
2142        put(&mut t, "dir", Node::Dir);
2143        let name = format!("dir/{}", "n".repeat(MAX_PATH_LEN));
2144        let long = SafePath::for_test(&name);
2145
2146        let refused = t.check_landing(&long, Node::File, LandingLimits::Enforced);
2147
2148        assert_matches!(refused, Err(PlaceError::LandingTooLong));
2149        assert_eq!(t.occupant(Path::new(&name)), None);
2150        let fits = SafePath::for_test("dir/ok");
2151        assert!(
2152            t.check_landing(&fits, Node::File, LandingLimits::Enforced)
2153                .is_ok()
2154        );
2155        assert_eq!(t.occupant(Path::new("dir/ok")), Some(Occupant::File));
2156        // Once a link is stored, the landing is projected through it.
2157        put(&mut t, "alias", sym("dir"));
2158        let through = SafePath::for_test(&format!("alias/{}", "n".repeat(MAX_PATH_LEN)));
2159        assert_matches!(
2160            t.check_landing(&through, Node::File, LandingLimits::Enforced),
2161            Err(PlaceError::LandingTooLong)
2162        );
2163    }
2164
2165    #[test]
2166    fn project_landing_resolves_through_a_link_and_enforces_the_name_limits() {
2167        let mut t = tree();
2168        put(&mut t, "real", Node::Dir);
2169        put(&mut t, "alias", sym("real"));
2170
2171        let landed = t
2172            .project_landing(
2173                &SafePath::for_test("alias/f"),
2174                Node::File,
2175                LandingLimits::Enforced,
2176            )
2177            .unwrap();
2178        assert_eq!(landed.as_path(), Path::new("real/f"));
2179
2180        let long = SafePath::for_test(&format!("alias/{}", "n".repeat(MAX_PATH_LEN)));
2181        let refused = t.project_landing(&long, Node::File, LandingLimits::Enforced);
2182        assert_matches!(refused, Err(PlaceError::LandingTooLong));
2183        let name = format!("real/{}", "n".repeat(MAX_PATH_LEN));
2184        assert_eq!(
2185            t.occupant(Path::new(&name)),
2186            None,
2187            "a refused landing leaves no node behind"
2188        );
2189        let missing_parents =
2190            SafePath::for_test(&format!("alias/p/q/{}", "n".repeat(MAX_PATH_LEN)));
2191        assert_matches!(
2192            t.project_landing(&missing_parents, Node::File, LandingLimits::Enforced),
2193            Err(PlaceError::LandingTooLong)
2194        );
2195        assert_eq!(t.occupant(Path::new("real/p")), None);
2196        let exempt = t.project_landing(
2197            &SafePath::for_test(&format!("alias/{}", "m".repeat(MAX_PATH_LEN))),
2198            Node::File,
2199            LandingLimits::Exempt,
2200        );
2201        assert!(exempt.is_ok());
2202    }
2203
2204    #[test]
2205    fn projected_landing_limit_is_exact_and_an_empty_tail_adds_no_separator() {
2206        let at_limit = crate::test_utils::path_of_len(MAX_PATH_LEN);
2207        let landing = Path::new(&at_limit);
2208        let check = |landing: &Path, tail: &str| {
2209            projected_landing_within_limits(PathModel::Host, landing, Path::new(tail))
2210        };
2211        assert!(check(landing, "").is_ok());
2212        assert!(check(landing, "x").is_err());
2213        let shorter = crate::test_utils::path_of_len(MAX_PATH_LEN - 2);
2214        assert!(check(Path::new(&shorter), "x").is_ok());
2215        assert!(check(Path::new(&shorter), "xx").is_err());
2216    }
2217
2218    fn budgeted(max: usize, recording: CollisionRecording) -> VirtualTree {
2219        VirtualTree::build(
2220            &VirtualRoot::at("/dest"),
2221            PathModel::Host,
2222            ascii_upper,
2223            NodeBudget::with_max(max),
2224            recording,
2225        )
2226    }
2227
2228    #[test]
2229    fn node_budget_refuses_the_key_after_the_last() {
2230        let mut t = budgeted(3, CollisionRecording::Record);
2231        for name in ["a", "b", "c"] {
2232            put(&mut t, name, Node::Dir);
2233        }
2234        let err = t.try_insert(Path::new("d"), Node::Dir).unwrap_err();
2235        assert_matches!(err, PlaceError::Budget(NodeBudgetExceeded { max: 3 }));
2236        assert!(!t.exists(Path::new("/dest/d")));
2237    }
2238
2239    #[test]
2240    fn node_budget_charges_implicit_parents() {
2241        let mut t = budgeted(2, CollisionRecording::Record);
2242        let err = t.try_insert(Path::new("a/b/c"), Node::File).unwrap_err();
2243        assert_matches!(err, PlaceError::Budget(_));
2244    }
2245
2246    #[test]
2247    fn node_budget_charges_alias_spellings_once() {
2248        let mut t = budgeted(3, CollisionRecording::Discard);
2249        put(&mut t, "dir", Node::Dir);
2250        put(&mut t, "Dir", Node::Dir);
2251        put(&mut t, "Dir", Node::Dir);
2252        put(&mut t, "DIR", Node::Dir);
2253        let err = t.try_insert(Path::new("dIr"), Node::Dir).unwrap_err();
2254        assert_matches!(err, PlaceError::Budget(_));
2255    }
2256
2257    #[test]
2258    fn discard_keeps_no_collision_records_after_a_flood() {
2259        let mut t = budgeted(usize::MAX, CollisionRecording::Discard);
2260        put(&mut t, "d/f", Node::File);
2261        for spelling in ["D", "d", "Dd"] {
2262            let _ = t.insert(Path::new(spelling), Node::Dir);
2263        }
2264        put(&mut t, "D/g", Node::File);
2265        put(&mut t, "Dir", Node::Dir);
2266        put(&mut t, "dir", Node::Dir);
2267        put(&mut t, "dir/x", Node::File);
2268        assert!(t.take_collisions().is_empty());
2269        assert!(t.take_empty_merges().is_empty());
2270        assert!(t.exists(Path::new("/dest/D/f")));
2271    }
2272
2273    #[test]
2274    fn unbounded_config_budget_never_trips() {
2275        let config = crate::SecurityConfig::default()
2276            .with_max_file_count(crate::Limit::Unbounded)
2277            .with_max_path_depth(crate::non_zero!(8));
2278        let mut t = VirtualTree::build(
2279            &VirtualRoot::at("/dest"),
2280            PathModel::Host,
2281            fold,
2282            NodeBudget::from_config(&config),
2283            CollisionRecording::Discard,
2284        );
2285        for i in 0..1000 {
2286            put(&mut t, &format!("d{i}"), Node::Dir);
2287        }
2288    }
2289
2290    #[test]
2291    fn config_budget_is_files_times_depth_plus_one() {
2292        let config = crate::SecurityConfig::default()
2293            .with_max_file_count(crate::non_zero!(10))
2294            .with_max_path_depth(crate::non_zero!(4));
2295        assert_eq!(NodeBudget::from_config(&config).max, 41);
2296    }
2297
2298    fn collisions_of(t: &mut VirtualTree) -> Vec<(String, String, CollisionKind)> {
2299        t.take_collisions()
2300            .into_iter()
2301            .map(|c| {
2302                (
2303                    c.existing.display().to_string().replace('\\', "/"),
2304                    c.incoming.display().to_string().replace('\\', "/"),
2305                    c.kind,
2306                )
2307            })
2308            .collect()
2309    }
2310
2311    #[test]
2312    fn exact_repeat_is_not_a_collision() {
2313        let mut t = folding_tree();
2314        put(&mut t, "a/f", Node::File);
2315        put(&mut t, "a/f", Node::File);
2316        assert!(t.take_collisions().is_empty());
2317    }
2318
2319    #[test]
2320    fn differently_spelled_files_collide() {
2321        let mut t = folding_tree();
2322        put(&mut t, "d/a.txt", Node::File);
2323        put(&mut t, "d/A.txt", Node::File);
2324        assert_eq!(
2325            collisions_of(&mut t),
2326            [("d/a.txt".into(), "d/A.txt".into(), CollisionKind::Files)]
2327        );
2328        assert!(t.take_collisions().is_empty());
2329    }
2330
2331    #[test]
2332    fn differently_spelled_parent_directories_collide() {
2333        let mut t = folding_tree();
2334        put(&mut t, "Images/x", Node::File);
2335        put(&mut t, "images/y", Node::File);
2336        assert_eq!(
2337            collisions_of(&mut t),
2338            [(
2339                "Images".into(),
2340                "images".into(),
2341                CollisionKind::DirectoriesWithContents
2342            )]
2343        );
2344    }
2345
2346    #[test]
2347    fn a_spelling_is_reported_once_however_many_entries_use_it() {
2348        let mut t = folding_tree();
2349        put(&mut t, "Images/a", Node::File);
2350        for i in 0..100 {
2351            put(&mut t, &format!("images/f{i}"), Node::File);
2352        }
2353        assert_eq!(collisions_of(&mut t).len(), 1);
2354    }
2355
2356    #[test]
2357    fn empty_directories_merge_harmlessly_until_one_gains_an_entry() {
2358        let mut t = folding_tree();
2359        put(&mut t, "Dir", Node::Dir);
2360        put(&mut t, "dir", Node::Dir);
2361        assert!(collisions_of(&mut t).is_empty());
2362        put(&mut t, "Dir/f", Node::File);
2363        put(&mut t, "dir/g", Node::File);
2364        assert_eq!(
2365            collisions_of(&mut t),
2366            [(
2367                "Dir".into(),
2368                "dir".into(),
2369                CollisionKind::DirectoriesWithContents
2370            )]
2371        );
2372    }
2373
2374    #[test]
2375    fn empty_merges_are_reported_once_when_nothing_lands_in_them() {
2376        let mut t = folding_tree();
2377        put(&mut t, "Dir", Node::Dir);
2378        put(&mut t, "dir", Node::Dir);
2379        put(&mut t, "other", Node::File);
2380        let merges: Vec<_> = t
2381            .take_empty_merges()
2382            .into_iter()
2383            .map(|c| {
2384                (
2385                    c.existing.display().to_string(),
2386                    c.incoming.display().to_string(),
2387                    c.kind,
2388                )
2389            })
2390            .collect();
2391        assert_eq!(
2392            merges,
2393            [("Dir".into(), "dir".into(), CollisionKind::Directories)]
2394        );
2395        assert!(t.take_empty_merges().is_empty());
2396    }
2397
2398    #[test]
2399    fn directory_entry_over_a_directory_with_contents_is_not_harmless() {
2400        let mut t = folding_tree();
2401        put(&mut t, "Dir/f", Node::File);
2402        put(&mut t, "dir", Node::Dir);
2403        assert_eq!(
2404            collisions_of(&mut t),
2405            [(
2406                "Dir".into(),
2407                "dir".into(),
2408                CollisionKind::DirectoriesWithContents
2409            )]
2410        );
2411    }
2412
2413    #[test]
2414    fn names_are_folded_once_however_often_they_repeat() {
2415        use std::sync::atomic::AtomicUsize;
2416        use std::sync::atomic::Ordering;
2417
2418        static CALLS: AtomicUsize = AtomicUsize::new(0);
2419        fn counting(name: &OsStr) -> Cow<'_, OsStr> {
2420            CALLS.fetch_add(1, Ordering::Relaxed);
2421            ascii_upper(name)
2422        }
2423
2424        let mut t = VirtualTree::with_fold(&VirtualRoot::at("/dest"), counting);
2425        for i in 0..500 {
2426            put(&mut t, &format!("a/b/c/d/file{i}"), Node::File);
2427        }
2428        // Four directories and 500 files, each folded to look up and to store;
2429        // a fold per parent per entry would be about 2500 calls.
2430        assert!(CALLS.load(Ordering::Relaxed) <= 2 * 504 + 8);
2431    }
2432
2433    #[test]
2434    fn collision_across_kinds_or_with_a_symlink_is_mixed() {
2435        let mut t = folding_tree();
2436        put(&mut t, "a", Node::File);
2437        let _ = t.insert(Path::new("A"), Node::Dir);
2438        put(&mut t, "link", sym("a"));
2439        let _ = t.insert(Path::new("LINK"), Node::File);
2440        assert_eq!(
2441            collisions_of(&mut t),
2442            [
2443                ("a".into(), "A".into(), CollisionKind::Mixed),
2444                ("link".into(), "LINK".into(), CollisionKind::Mixed)
2445            ]
2446        );
2447    }
2448
2449    #[test]
2450    fn symlink_over_an_existing_dir_is_refused_and_keeps_the_dir() {
2451        let mut t = folding_tree();
2452        put(&mut t, "d/f", Node::File);
2453        let err = t.insert(Path::new("d"), sym("sub")).unwrap_err();
2454        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2455        let err = t.insert(Path::new("d"), Node::OpaqueSymlink).unwrap_err();
2456        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2457        assert!(t.resolves_to_dir(&t.root.join("d")));
2458    }
2459
2460    #[test]
2461    fn collision_is_recorded_when_insert_fails() {
2462        let mut t = folding_tree();
2463        put(&mut t, "y", Node::File);
2464        let err = t.insert(Path::new("Y"), sym(".")).unwrap_err();
2465        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2466        assert_eq!(
2467            collisions_of(&mut t),
2468            [("y".into(), "Y".into(), CollisionKind::Mixed)]
2469        );
2470    }
2471
2472    #[cfg(target_os = "macos")]
2473    mod macos {
2474        use super::super::fold;
2475        use super::*;
2476
2477        fn key(s: &str) -> OsString {
2478            fold(OsStr::new(s)).into_owned()
2479        }
2480
2481        #[test]
2482        fn special_case_pairs_fold_equal() {
2483            assert_eq!(key("\u{df}"), key("\u{1e9e}"));
2484            assert_eq!(key("\u{3b8}"), key("\u{3f4}"));
2485            assert_eq!(key("\u{3b8}"), key("\u{3d1}"));
2486            assert_eq!(key("\u{3c2}"), key("\u{3a3}"));
2487        }
2488
2489        #[test]
2490        fn canonically_equivalent_names_fold_equal() {
2491            assert_eq!(key("caf\u{e9}"), key("cafe\u{301}"));
2492            assert_eq!(key("\u{ac00}"), key("\u{1100}\u{1161}"));
2493        }
2494
2495        #[test]
2496        fn nfc_and_nfd_spellings_collide_in_the_tree() {
2497            let mut t = tree();
2498            put(&mut t, "caf\u{e9}", Node::File);
2499            put(&mut t, "cafe\u{301}", Node::File);
2500            assert_eq!(t.take_collisions().len(), 1);
2501        }
2502
2503        #[test]
2504        fn fold_never_under_merges_what_apfs_treats_as_equal() {
2505            let temp = tempfile::TempDir::new().unwrap();
2506            let root = temp.path().canonicalize().unwrap();
2507            let mut seen = std::collections::HashSet::new();
2508            let mut under = Vec::new();
2509            // Blocks with case or normalisation behaviour; the Hangul block is
2510            // sampled because it decomposes algorithmically.
2511            let candidates = (0x1..=0x3000)
2512                .chain((0xAC00..=0xD7A3).step_by(11))
2513                .chain(0xF900..=0xFFFF)
2514                .chain(0x1_0400..=0x1_044F)
2515                .chain(0x1_E900..=0x1_E943);
2516            for code in candidates {
2517                let Some(c) = char::from_u32(code).filter(|c| !matches!(c, '/' | '.')) else {
2518                    continue;
2519                };
2520                let name = c.to_string();
2521                let path = root.join(&name);
2522                let host_equal = path.symlink_metadata().is_ok();
2523                if !host_equal && std::fs::File::create_new(&path).is_err() {
2524                    continue;
2525                }
2526                let model_seen = !seen.insert(key(&name));
2527                if host_equal && !model_seen {
2528                    under.push(format!("U+{code:04X}"));
2529                }
2530            }
2531            assert!(under.is_empty(), "under-merged: {under:?}");
2532        }
2533    }
2534
2535    #[cfg(target_os = "windows")]
2536    #[test]
2537    fn fold_covers_ntfs_simple_uppercase() {
2538        use std::collections::HashMap;
2539
2540        let mut by_upper: HashMap<char, OsString> = HashMap::new();
2541        for code in 0x1..=0x1_FFFFu32 {
2542            let Some(c) = char::from_u32(code) else {
2543                continue;
2544            };
2545            let mut upper = c.to_uppercase();
2546            let simple = match (upper.next(), upper.next()) {
2547                (Some(u), None) => u,
2548                _ => c,
2549            };
2550            let key = fold(OsStr::new(&c.to_string())).into_owned();
2551            let expected = by_upper.entry(simple).or_insert_with(|| key.clone());
2552            assert_eq!(*expected, key, "U+{code:04X}");
2553        }
2554    }
2555
2556    #[test]
2557    fn dangling_symlink_does_not_exist_but_is_a_symlink() {
2558        let mut t = tree();
2559        put(&mut t, "d", sym("missing"));
2560        assert!(!t.exists(Path::new("/dest/d")));
2561        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
2562    }
2563
2564    #[test]
2565    fn opaque_symlink_exists_and_is_a_symlink_but_not_a_directory() {
2566        let mut t = tree();
2567        put(&mut t, "d", Node::OpaqueSymlink);
2568        assert!(t.exists(Path::new("/dest/d")));
2569        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
2570        assert!(!t.resolves_to_dir(Path::new("/dest/d")));
2571    }
2572
2573    #[test]
2574    fn nothing_resolves_through_an_opaque_symlink() {
2575        let mut t = tree();
2576        put(&mut t, "d", Node::OpaqueSymlink);
2577        assert!(canon(&t, "/dest/d").is_err());
2578        assert!(canon(&t, "/dest/d/x").is_err());
2579        assert!(t.insert(Path::new("d/f"), Node::File).is_err());
2580    }
2581
2582    #[test]
2583    fn a_chain_ending_at_an_opaque_symlink_does_not_resolve() {
2584        let mut t = tree();
2585        put(&mut t, "d", Node::OpaqueSymlink);
2586        put(&mut t, "l", sym("d"));
2587        assert!(canon(&t, "/dest/l").is_err());
2588    }
2589
2590    #[test]
2591    fn opaque_symlink_keeps_its_place_like_a_symlink() {
2592        let mut t = tree();
2593        put(&mut t, "d", Node::OpaqueSymlink);
2594        assert_eq!(
2595            t.insert(Path::new("d"), Node::Dir).unwrap_err().kind(),
2596            io::ErrorKind::AlreadyExists
2597        );
2598        assert_eq!(
2599            t.insert(Path::new("d"), Node::File).unwrap_err().kind(),
2600            io::ErrorKind::AlreadyExists
2601        );
2602        assert!(t.is_symlink(Path::new("/dest/d")).unwrap());
2603
2604        put(&mut t, "f", Node::File);
2605        assert!(t.insert(Path::new("f"), Node::OpaqueSymlink).is_err());
2606        assert!(t.is_symlink(Path::new("/dest/f")).unwrap());
2607    }
2608
2609    #[test]
2610    fn opaque_symlink_collision_is_mixed() {
2611        let mut t = folding_tree();
2612        put(&mut t, "link", Node::OpaqueSymlink);
2613        let _ = t.insert(Path::new("LINK"), Node::File);
2614        assert_eq!(
2615            collisions_of(&mut t),
2616            [("link".into(), "LINK".into(), CollisionKind::Mixed)]
2617        );
2618    }
2619
2620    #[test]
2621    fn is_symlink_follows_symlinked_parents() {
2622        let mut t = tree();
2623        put(&mut t, "real/inner", sym("x"));
2624        put(&mut t, "alias", sym("real"));
2625        assert!(t.is_symlink(Path::new("/dest/alias/inner")).unwrap());
2626        assert!(!t.is_symlink(Path::new("/dest/real")).unwrap());
2627        assert!(t.is_symlink(Path::new("/dest/none")).is_err());
2628    }
2629
2630    #[test]
2631    fn insert_through_symlinked_parent_lands_at_resolved_location() {
2632        let mut t = tree();
2633        put(&mut t, "real", Node::Dir);
2634        put(&mut t, "alias", sym("real"));
2635        put(&mut t, "alias/f", Node::File);
2636        assert!(t.exists(Path::new("/dest/real/f")));
2637    }
2638
2639    #[test]
2640    fn insert_dir_keeps_existing_symlink() {
2641        let mut t = tree();
2642        put(&mut t, "real", Node::Dir);
2643        put(&mut t, "alias", sym("real"));
2644        put(&mut t, "alias", Node::Dir);
2645        assert!(t.is_symlink(Path::new("/dest/alias")).unwrap());
2646    }
2647
2648    #[test]
2649    fn file_never_replaces_existing_symlink() {
2650        let mut t = tree();
2651        put(&mut t, "y", sym("."));
2652        let err = t.insert(Path::new("y"), Node::File).unwrap_err();
2653        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2654        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
2655    }
2656
2657    #[test]
2658    fn symlink_over_symlink_is_refused_and_keeps_the_first() {
2659        let mut t = tree();
2660        put(&mut t, "real", Node::Dir);
2661        put(&mut t, "d", sym("real"));
2662        for node in [sym("other"), Node::OpaqueSymlink] {
2663            let conflict = t
2664                .try_insert(Path::new("d"), node)
2665                .unwrap_err()
2666                .into_conflict();
2667            assert_eq!(conflict.error.kind(), io::ErrorKind::AlreadyExists);
2668            assert_eq!(conflict.occupant, Some(Occupant::Symlink));
2669        }
2670        assert_eq!(within(&t, "/dest/d"), PathBuf::from("/dest/real"));
2671    }
2672
2673    #[test]
2674    fn symlink_repeating_the_same_target_is_an_unchanged_duplicate() {
2675        let mut t = tree();
2676        put(&mut t, "d", sym("real"));
2677        put(&mut t, "d", sym("real"));
2678        assert!(t.try_insert(Path::new("d"), Node::OpaqueSymlink).is_err());
2679    }
2680
2681    #[test]
2682    fn file_over_dir_is_refused_with_is_a_directory() {
2683        let mut t = tree();
2684        put(&mut t, "d/f", Node::File);
2685        let conflict = t
2686            .try_insert(Path::new("d"), Node::File)
2687            .unwrap_err()
2688            .into_conflict();
2689        assert_eq!(conflict.error.kind(), io::ErrorKind::IsADirectory);
2690        assert_eq!(conflict.occupant, Some(Occupant::Directory));
2691    }
2692
2693    #[test]
2694    fn file_over_file_is_kept_silently() {
2695        let mut t = tree();
2696        put(&mut t, "f", Node::File);
2697        put(&mut t, "f", Node::File);
2698        assert_eq!(t.occupant(Path::new("f")), Some(Occupant::File));
2699    }
2700
2701    #[test]
2702    fn occupant_names_what_sits_at_the_path_itself() {
2703        let mut t = tree();
2704        put(&mut t, "real/f", Node::File);
2705        put(&mut t, "alias", sym("real"));
2706        assert_eq!(t.occupant(Path::new("real")), Some(Occupant::Directory));
2707        assert_eq!(t.occupant(Path::new("alias")), Some(Occupant::Symlink));
2708        assert_eq!(t.occupant(Path::new("alias/f")), Some(Occupant::File));
2709        assert_eq!(t.occupant(Path::new("none")), None);
2710    }
2711
2712    #[test]
2713    fn symlink_replaces_earlier_file() {
2714        let mut t = tree();
2715        put(&mut t, "y", Node::File);
2716        let err = t.insert(Path::new("y"), sym(".")).unwrap_err();
2717        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2718        assert!(t.is_symlink(Path::new("/dest/y")).unwrap());
2719    }
2720
2721    #[test]
2722    fn dir_over_file_is_an_error() {
2723        let mut t = tree();
2724        put(&mut t, "f", Node::File);
2725        let err = t.insert(Path::new("f"), Node::Dir).unwrap_err();
2726        assert_eq!(err.kind(), io::ErrorKind::AlreadyExists);
2727    }
2728
2729    #[test]
2730    fn insert_under_file_is_an_error() {
2731        let mut t = tree();
2732        put(&mut t, "f", Node::File);
2733        let err = t.insert(Path::new("f/g"), Node::File).unwrap_err();
2734        assert_eq!(err.kind(), io::ErrorKind::NotADirectory);
2735    }
2736
2737    #[test]
2738    fn insert_under_chain_leaving_root_is_an_error() {
2739        let mut t = tree();
2740        put(&mut t, "out", sym(".."));
2741        assert!(t.insert(Path::new("out/f"), Node::File).is_err());
2742        assert!(!t.exists(Path::new("/dest/out/f")));
2743    }
2744
2745    #[test]
2746    fn resolves_to_dir_distinguishes_files_and_directories() {
2747        let mut t = tree();
2748        put(&mut t, "d/f", Node::File);
2749        put(&mut t, "alias", sym("d"));
2750        assert!(t.resolves_to_dir(Path::new("/dest/d")));
2751        assert!(t.resolves_to_dir(Path::new("/dest/alias")));
2752        assert!(!t.resolves_to_dir(Path::new("/dest/d/f")));
2753    }
2754
2755    #[test]
2756    fn overlong_component_is_never_found() {
2757        let mut t = tree();
2758        put(&mut t, "d", Node::Dir);
2759        let long = "a".repeat(1 << 20);
2760        let err = canon(&t, &format!("/dest/d/{long}")).unwrap_err();
2761        assert_eq!(err.kind(), io::ErrorKind::NotFound);
2762    }
2763
2764    #[test]
2765    fn name_length_limits() {
2766        assert!(check_name_lengths(Path::new("a/b")).is_ok());
2767        let long_name = "a".repeat(255 + 1);
2768        assert!(check_name_lengths(Path::new(&long_name)).is_err());
2769        let long_path = path_of_len(HOST_PATH_LIMIT + 1);
2770        assert!(check_name_lengths(Path::new(&long_path)).is_err());
2771        assert!(check_name_lengths(Path::new(&path_of_len(HOST_PATH_LIMIT))).is_ok());
2772    }
2773
2774    use crate::test_utils::HOST_PATH_LIMIT;
2775    use crate::test_utils::path_of_len;
2776
2777    #[test]
2778    fn link_target_length_boundaries() {
2779        let symlink_limit = path_of_len(MAX_SYMLINK_TARGET_LEN);
2780        let symlink_over = path_of_len(MAX_SYMLINK_TARGET_LEN + 1);
2781        assert!(check_link_target_length(Path::new(&symlink_limit), LinkKind::Symlink).is_ok());
2782        assert!(check_link_target_length(Path::new(&symlink_over), LinkKind::Symlink).is_err());
2783
2784        let at_limit = path_of_len(HOST_PATH_LIMIT);
2785        assert_eq!(at_limit.len(), HOST_PATH_LIMIT);
2786        let over = path_of_len(HOST_PATH_LIMIT + 1);
2787        assert!(check_link_target_length(Path::new(&at_limit), LinkKind::Hardlink).is_ok());
2788        assert!(check_link_target_length(Path::new(&over), LinkKind::Hardlink).is_err());
2789    }
2790
2791    #[test]
2792    fn symlink_target_limits_match_the_host() {
2793        assert_eq!(
2794            MAX_SYMLINK_TARGET_LEN,
2795            if cfg!(windows) { 4091 } else { HOST_PATH_LIMIT }
2796        );
2797        assert_eq!(
2798            MAX_SYMLINK_TARGET_BYTES,
2799            if cfg!(windows) {
2800                4091 * 3
2801            } else {
2802                HOST_PATH_LIMIT
2803            }
2804        );
2805    }
2806
2807    /// Finds the longest relative symlink target the host creates and checks
2808    /// that [`MAX_SYMLINK_TARGET_LEN`] does not exceed it.
2809    #[cfg(windows)]
2810    #[test]
2811    fn symlink_target_limit_is_accepted_by_the_host() {
2812        use std::os::windows::fs::symlink_file;
2813
2814        let temp = tempfile::TempDir::new().unwrap();
2815        let mut counter = 0_u32;
2816        let mut creates = |len: usize| -> io::Result<bool> {
2817            counter += 1;
2818            let link = temp.path().join(format!("l{counter}"));
2819            let mut target = "abcdefg\\".repeat((len - 1) / 8);
2820            target.push_str(&"a".repeat(len - target.len()));
2821            match symlink_file(&target, &link) {
2822                Ok(()) => Ok(true),
2823                Err(e) if e.raw_os_error() == Some(1314) => Err(e),
2824                Err(_) => Ok(false),
2825            }
2826        };
2827
2828        match creates(1) {
2829            Ok(_) => {}
2830            Err(e) => {
2831                assert!(
2832                    std::env::var_os("CI").is_none(),
2833                    "symlink creation needs a privilege on CI: {e}"
2834                );
2835                eprintln!("skipped: symlink creation is not permitted: {e}");
2836                return;
2837            }
2838        }
2839
2840        let (mut ok, mut bad) = (1_usize, 32767_usize);
2841        while bad - ok > 1 {
2842            let mid = ok + (bad - ok) / 2;
2843            if creates(mid).unwrap() {
2844                ok = mid;
2845            } else {
2846                bad = mid;
2847            }
2848        }
2849        eprintln!("largest relative symlink target: {ok} UTF-16 units");
2850        assert!(MAX_SYMLINK_TARGET_LEN <= ok, "host limit is {ok}");
2851    }
2852
2853    #[test]
2854    fn symlink_target_ignores_component_limit() {
2855        let long_component = "a".repeat(255 + 45);
2856        let target = Path::new(&long_component);
2857        assert!(check_link_target_length(target, LinkKind::Symlink).is_ok());
2858        assert!(check_link_target_length(target, LinkKind::Hardlink).is_err());
2859        assert!(check_name_lengths(target).is_err());
2860    }
2861
2862    #[cfg(any(target_os = "macos", target_os = "windows"))]
2863    #[test]
2864    fn keys_are_case_insensitive_on_case_folding_hosts() {
2865        let mut t = tree();
2866        put(&mut t, "Dir/File", Node::File);
2867        assert!(t.exists(Path::new("/dest/dir/file")));
2868    }
2869
2870    #[test]
2871    fn host_fs_probes_the_real_filesystem() {
2872        let temp = tempfile::TempDir::new().unwrap();
2873        assert!(HostFs.exists(temp.path()));
2874        assert!(!HostFs.is_symlink(temp.path()).unwrap());
2875        let root = DestDir::new(temp.path().to_path_buf()).unwrap();
2876        assert!(
2877            HostFs
2878                .canonicalize(&temp.path().join("nope"), &root)
2879                .is_err()
2880        );
2881    }
2882
2883    fn classified(err: ArchiveError) -> (&'static str, String) {
2884        match err {
2885            ArchiveError::Io(e) => ("io", e.to_string()),
2886            ArchiveError::SecurityViolation { kind } => ("violation", kind.to_string()),
2887            ArchiveError::SymlinkEscape { path } => ("escape", path.display().to_string()),
2888            other => panic!("unexpected {other:?}"),
2889        }
2890    }
2891
2892    #[test]
2893    fn blocker_text_and_category_are_shared() {
2894        let entry = Path::new("x/./y/z");
2895        let parent = Path::new("x");
2896
2897        let (kind, text) = classified(ParentBlocker::File.error(entry, parent));
2898        assert_eq!(kind, "io");
2899        assert!(
2900            text.replace('\\', "/")
2901                .ends_with("refusing to create x/y/z under the existing file at x")
2902        );
2903        let (kind, text) = classified(ParentBlocker::Symlink.error(entry, parent));
2904        assert_eq!(kind, "violation");
2905        assert!(
2906            text.replace('\\', "/")
2907                .contains("refusing to create x/y/z under the existing symlink at x")
2908        );
2909        assert_eq!(
2910            classified(ParentBlocker::Escape.error(entry, parent)),
2911            ("escape", "x".to_owned())
2912        );
2913    }
2914
2915    fn blocked_conflict(t: &mut VirtualTree, path: &str) -> Conflict {
2916        t.try_insert(Path::new(path), Node::File)
2917            .unwrap_err()
2918            .into_conflict()
2919    }
2920
2921    #[test]
2922    fn tree_names_a_file_parent() {
2923        let mut t = tree();
2924        put(&mut t, "x", Node::File);
2925
2926        let conflict = blocked_conflict(&mut t, "x/a/f");
2927
2928        assert_eq!(conflict.occupant, None);
2929        let (kind, text) = classified(conflict.into_archive_error());
2930        assert_eq!(kind, "io");
2931        assert!(
2932            text.replace('\\', "/")
2933                .ends_with("refusing to create x/a/f under the existing file at x")
2934        );
2935    }
2936
2937    #[test]
2938    fn tree_names_a_symlink_parent_that_dangles_loops_or_hits_a_file() {
2939        for (target, file) in [("t", None), ("x", None), ("t", Some("t"))] {
2940            let mut t = tree();
2941            if let Some(file) = file {
2942                put(&mut t, file, Node::File);
2943            }
2944            put(&mut t, "x", sym(target));
2945
2946            let conflict = blocked_conflict(&mut t, "x/f");
2947
2948            let (kind, text) = classified(conflict.into_archive_error());
2949            assert_eq!(kind, "violation", "{target}");
2950            assert!(
2951                text.replace('\\', "/")
2952                    .contains("refusing to create x/f under the existing symlink at x")
2953            );
2954        }
2955    }
2956
2957    #[test]
2958    fn tree_keeps_a_parent_that_leaves_the_root_out_of_the_blocker() {
2959        let mut t = tree();
2960        put(&mut t, "up", sym(".."));
2961
2962        assert!(blocked_conflict(&mut t, "up/f").blocked.is_none());
2963    }
2964
2965    #[test]
2966    fn plain_conflict_converts_to_its_io_error() {
2967        let conflict = Conflict::already_exists(Occupant::File);
2968
2969        assert_eq!(classified(conflict.into_archive_error()).0, "io");
2970    }
2971
2972    #[cfg(unix)]
2973    mod host_ancestors {
2974        use super::*;
2975        use std::os::unix::fs::symlink;
2976
2977        fn host() -> (tempfile::TempDir, DestDir, PathBuf) {
2978            let temp = tempfile::TempDir::new().unwrap();
2979            let dest = temp.path().join("dest");
2980            let outside = temp.path().join("outside");
2981            std::fs::create_dir(&dest).unwrap();
2982            std::fs::create_dir(&outside).unwrap();
2983            std::fs::write(outside.join("f"), b"x").unwrap();
2984            let root = DestDir::new(dest).unwrap();
2985            (temp, root, outside.canonicalize().unwrap())
2986        }
2987
2988        fn blocker(root: &DestDir, rel: &str) -> Option<(PathBuf, ParentBlocker)> {
2989            first_blocking_ancestor(&HostFs, root, Path::new(rel))
2990        }
2991
2992        fn found(name: &str, blocker: ParentBlocker) -> (PathBuf, ParentBlocker) {
2993            (PathBuf::from(name), blocker)
2994        }
2995
2996        #[test]
2997        fn finds_each_kind_of_blocker() {
2998            let (_temp, root, outside) = host();
2999            let dest = root.as_path();
3000            std::fs::write(dest.join("file"), b"x").unwrap();
3001            std::fs::create_dir(dest.join("real")).unwrap();
3002            symlink("missing", dest.join("dangling")).unwrap();
3003            symlink("loop", dest.join("loop")).unwrap();
3004            symlink("file", dest.join("to_file")).unwrap();
3005            symlink("real", dest.join("ok")).unwrap();
3006            symlink(outside.join("f"), dest.join("out_file")).unwrap();
3007            symlink(&outside, dest.join("out_dir")).unwrap();
3008
3009            assert_eq!(
3010                blocker(&root, "file/a/b"),
3011                Some(found("file", ParentBlocker::File))
3012            );
3013            assert_eq!(
3014                blocker(&root, "dangling/a"),
3015                Some(found("dangling", ParentBlocker::Symlink))
3016            );
3017            assert_eq!(
3018                blocker(&root, "loop/a/b"),
3019                Some(found("loop", ParentBlocker::Symlink))
3020            );
3021            assert_eq!(
3022                blocker(&root, "to_file/a"),
3023                Some(found("to_file", ParentBlocker::Symlink))
3024            );
3025            assert_eq!(
3026                blocker(&root, "out_file/a/b"),
3027                Some(found("out_file", ParentBlocker::Escape))
3028            );
3029            assert_eq!(
3030                blocker(&root, "out_dir/a/b"),
3031                Some(found("out_dir", ParentBlocker::Escape))
3032            );
3033            assert_eq!(blocker(&root, "ok/a/b"), None);
3034            assert_eq!(blocker(&root, "real/missing/b"), None);
3035            assert_eq!(blocker(&root, "missing/a/b"), None);
3036            assert_eq!(blocker(&root, "top"), None);
3037        }
3038
3039        #[test]
3040        fn an_uninspectable_prefix_blames_nobody() {
3041            use std::os::unix::fs::PermissionsExt;
3042
3043            let (_temp, root, _) = host();
3044            let locked = root.as_path().join("locked");
3045            std::fs::create_dir(&locked).unwrap();
3046            std::fs::write(locked.join("f"), b"x").unwrap();
3047            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o000)).unwrap();
3048            let readable = std::fs::metadata(locked.join("f")).is_ok();
3049
3050            let result = blocker(&root, "locked/f/x");
3051
3052            std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o700)).unwrap();
3053            if !readable {
3054                assert_eq!(result, None);
3055            }
3056        }
3057    }
3058}
3059
3060#[cfg(test)]
3061mod host_fs_tests {
3062    use super::*;
3063    use std::assert_matches;
3064
3065    #[test]
3066    fn containment_is_by_whole_components() {
3067        let root = Path::new("/mnt/out");
3068
3069        assert_matches!(
3070            contain(PathBuf::from("/mnt/out/a"), root),
3071            Containment::Within(_)
3072        );
3073        assert_matches!(
3074            contain(PathBuf::from("/mnt/outx"), root),
3075            Containment::Escapes
3076        );
3077    }
3078
3079    #[test]
3080    #[cfg(unix)]
3081    fn containment_is_case_sensitive_on_unix() {
3082        let root = Path::new("/mnt/out");
3083
3084        assert_matches!(
3085            contain(PathBuf::from("/mnt/OUT"), root),
3086            Containment::Escapes
3087        );
3088        assert_matches!(
3089            contain(PathBuf::from("/mnt/OUT/a"), root),
3090            Containment::Escapes
3091        );
3092    }
3093
3094    #[test]
3095    #[cfg(not(unix))]
3096    fn containment_folds_case_off_unix() {
3097        let root = Path::new("/mnt/out");
3098
3099        assert_matches!(
3100            contain(PathBuf::from("/mnt/OUT/a"), root),
3101            Containment::Within(_)
3102        );
3103    }
3104}