raf-source 0.0.0

Workspace source index: a Tree file seam with disk and memory backends under canonical path containment.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
// SPDX-FileCopyrightText: 2026 Blackcat Informatics® Inc. <paudley@blackcatinformatics.ca>
// SPDX-License-Identifier: MIT OR Apache-2.0 OR MulanPSL-2.0

//! The handle-contained disk backend. The separate committed Git host backend
//! uses the native read-only Git object library rather than this filesystem strategy.
//!
//! A read, a listing and an entry lookup each open a handle (the file to read,
//! the directory to list, or the directory that holds the entry), verify it
//! against the root, use it, and verify it again after the use. How the handle
//! is opened and verified is the platform's [`Strategy`]:
//!
//! * Linux ([`linux`]): the canonical path is taken as an `O_PATH` reference,
//!   which performs no I/O; the kernel's own path for it must lie under the
//!   root before it is opened for reading or listed through that path.
//! * Other Unix systems ([`other_unix`]): the path is walked one component at
//!   a time from a descriptor of the root, with `openat` and without following
//!   any symlink; an in-root symlink is resolved by reading it and continuing
//!   the walk. A walk outside the root may only descend back into it, never
//!   climb, and opens nothing outside but directories, so an outside
//!   non-directory is never opened. No path is resolved by name.
//! * Windows ([`handle_path`]): the canonical path is opened as a handle and
//!   the path the system gives for that handle must lie under the root.
//!
//! On Windows a segment that Windows would not read as the name it spells (a
//! reserved device name, a name that ends in a dot or a space, or one that
//! names an alternate data stream) is refused before anything else. A read
//! takes at most `max_bytes + 1` bytes and refuses the file when the extra byte
//! arrives.
//!
//! A platform with neither Unix nor Windows has no strategy: [`DiskTree::new`]
//! fails there, and the calls below it are never reached.

#![cfg_attr(
    not(any(unix, windows)),
    allow(
        unused_variables,
        dead_code,
        reason = "with no strategy no tree is built, so the calls are compiled but never reached"
    )
)]

use std::fs::Metadata;
use std::io::Read;
use std::path::{Path, PathBuf};

use super::{Entry, EntryKind, FileId, Opened, Tree};
use crate::error::TreeError;
use crate::path::RelPath;

mod capture;
pub use capture::{CapturedDirectory, CapturedFile, CapturedLink};

/// Resolve a supplied host root locator; each backend owns its access strategy.
pub(super) fn canonical_root(root: &Path) -> std::io::Result<PathBuf> {
    std::fs::canonicalize(root)
}

/// A callback that a test runs at one point of a call.
#[cfg(test)]
type Hook = Box<dyn Fn() + Send + Sync>;

/// Run the test hook `$hook` of `$tree`; outside test builds, nothing.
macro_rules! hook {
    ($tree:expr, $hook:ident) => {
        #[cfg(test)]
        if let Some(hook) = &$tree.$hook {
            hook();
        }
    };
}

/// Apply `$body` to the strategy's own handle inside a [`Handle`].
macro_rules! each {
    ($handle:expr, $inner:ident => $body:expr) => {
        match *$handle {
            #[cfg(target_os = "linux")]
            Handle::Linux(ref $inner) => $body,
            #[cfg(all(unix, not(target_os = "linux")))]
            Handle::OtherUnix(ref $inner) => $body,
            #[cfg(windows)]
            Handle::Windows(ref $inner) => $body,
        }
    };
}

#[cfg(windows)]
mod final_path;
#[cfg(windows)]
mod handle_path;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(all(unix, not(target_os = "linux")))]
mod other_unix;
#[cfg(unix)]
mod unix_root;
// Without a strategy no tree can be built, so there is nothing to test.
#[cfg(all(test, any(unix, windows)))]
mod tests;

/// How a handle is opened and verified against the root.
///
/// The platform selects its native variant in production and test builds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Strategy {
    /// An `O_PATH` reference verified through `/proc/self/fd`, then reopened.
    #[cfg(target_os = "linux")]
    Linux,
    /// A walk beneath a descriptor of the root, one `openat` per component.
    #[cfg(all(unix, not(target_os = "linux")))]
    OtherUnix,
    /// A handle opened by path and verified by the path the system gives for
    /// it: `GetFinalPathNameByHandleW` on Windows.
    #[cfg(windows)]
    Windows,
}

impl Strategy {
    /// The strategy of the platform the crate is built for.
    #[cfg(target_os = "linux")]
    #[expect(
        clippy::unnecessary_wraps,
        reason = "the signature is shared with the platforms that have no strategy"
    )]
    fn native(_shown: &str) -> Result<Self, TreeError> {
        Ok(Self::Linux)
    }

    /// The strategy of the platform the crate is built for.
    #[cfg(all(unix, not(target_os = "linux")))]
    #[expect(
        clippy::unnecessary_wraps,
        reason = "the signature is shared with the platforms that have no strategy"
    )]
    fn native(_shown: &str) -> Result<Self, TreeError> {
        Ok(Self::OtherUnix)
    }

    /// The strategy of the platform the crate is built for.
    #[cfg(windows)]
    #[expect(
        clippy::unnecessary_wraps,
        reason = "the signature is shared with the platforms that have no strategy"
    )]
    fn native(_shown: &str) -> Result<Self, TreeError> {
        Ok(Self::Windows)
    }

    /// Without Unix or Windows no handle can be verified, so no tree opens.
    #[cfg(not(any(unix, windows)))]
    fn native(shown: &str) -> Result<Self, TreeError> {
        Err(TreeError::Io {
            path: shown.to_owned(),
            source: std::io::Error::new(
                std::io::ErrorKind::Unsupported,
                "this platform cannot verify a handle against the root",
            ),
        })
    }
}

/// What a handle must be.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Want {
    /// A regular file, to be read; a final symlink is followed.
    File,
    /// A directory that holds an entry; a final symlink is followed.
    Dir,
    /// A directory to be listed; a final symlink is refused.
    Listing,
}

impl Want {
    /// Refuse `metadata` of a handle that is not what is wanted.
    fn require(self, metadata: &Metadata, shown: &str) -> Result<(), TreeError> {
        let file_type = metadata.file_type();
        let fits = match self {
            Self::File => file_type.is_file(),
            Self::Dir | Self::Listing => file_type.is_dir(),
        };
        if fits {
            Ok(())
        } else {
            Err(not_regular(shown))
        }
    }
}

/// A verified handle, of the strategy that opened it.
enum Handle {
    #[cfg(target_os = "linux")]
    Linux(linux::Handle),
    #[cfg(all(unix, not(target_os = "linux")))]
    OtherUnix(other_unix::Handle),
    #[cfg(windows)]
    Windows(handle_path::Handle),
}

impl Handle {
    /// Read current metadata from the verified handle, without resolving a name.
    fn metadata(&self, shown: &str) -> Result<Metadata, TreeError> {
        each!(self, inner => inner.metadata(shown))
    }

    /// Capture a lexical link relative to this verified directory.
    fn link(
        &self,
        name: &str,
        shown: &str,
        between: impl FnOnce(),
    ) -> Result<(FileId, PathBuf), TreeError> {
        each!(self, inner => inner.link(name, shown, between))
    }

    /// The identity of the verified file.
    fn identity(&self, root: &Path, shown: &str) -> Result<FileId, TreeError> {
        each!(self, inner => inner.identity(root, shown))
    }

    /// At most `max_bytes` bytes of the verified file.
    fn read(&self, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
        each!(self, inner => inner.read(max_bytes, shown))
    }

    /// The entries of the verified directory, in the order the system gives.
    fn entries(&self, shown: &str) -> Result<Vec<Entry>, TreeError> {
        self.entries_bounded(shown, usize::MAX)
    }

    fn entries_bounded(&self, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
        each!(self, inner => inner.entries(shown, max_entries))
    }

    /// What `name` is in the verified directory, without following it.
    fn lookup(&self, name: &str, shown: &str) -> Result<Option<EntryKind>, TreeError> {
        each!(self, inner => inner.lookup(name, shown))
    }

    /// Verify the handle again, after a use.
    fn recheck(&self, tree: &DiskTree, shown: &str) -> Result<(), TreeError> {
        match *self {
            #[cfg(target_os = "linux")]
            Handle::Linux(ref inner) => inner.recheck(tree, shown),
            #[cfg(all(unix, not(target_os = "linux")))]
            Handle::OtherUnix(ref inner) => inner.recheck(&tree.root_directory, shown),
            #[cfg(windows)]
            Handle::Windows(ref inner) => inner.recheck(&tree.root, shown),
        }
    }
}

/// True when an open with `flags` returns at once on a FIFO: an `O_PATH`
/// reference performs no I/O, and an `O_NONBLOCK` open does not wait for the
/// other end.
#[cfg(all(test, unix))]
fn never_blocks(flags: u32) -> bool {
    #[cfg(target_os = "linux")]
    let path = libc::O_PATH.cast_unsigned();
    #[cfg(not(target_os = "linux"))]
    let path = 0;
    flags & (path | libc::O_NONBLOCK.cast_unsigned()) != 0
}

/// A tree read from a directory on disk.
///
/// The root is canonicalised once, in [`DiskTree::new`]. Unix retains its
/// original directory description. Linux refuses relocation outside the
/// canonical scope; replacement at that pathname cannot retarget the tree.
/// A symlink inside the tree is followed only when its target is also inside it.
pub struct DiskTree {
    root: PathBuf,
    strategy: Strategy,
    /// The original directory description shared by all Unix operations.
    #[cfg(unix)]
    root_directory: unix_root::Root,
    /// Runs after the containment check and before the open.
    #[cfg(test)]
    before_open: Option<Hook>,
    /// Runs after the open and before the handle is verified.
    #[cfg(test)]
    after_open: Option<Hook>,
    /// Runs after the handle is verified and before it is used.
    #[cfg(test)]
    after_verify: Option<Hook>,
    /// Runs between the first capture observation and its comparison.
    #[cfg(test)]
    after_observation: Option<Hook>,
    /// Runs inside one step of the other-Unix walk, after an open failed and
    /// before the status of the entry is read.
    #[cfg(all(test, unix, not(target_os = "linux")))]
    mid_step: Option<Hook>,
    /// The flags of every open that resolves a name below the root.
    #[cfg(all(test, unix))]
    opens: std::sync::Mutex<Vec<u32>>,
}

impl std::fmt::Debug for DiskTree {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DiskTree")
            .field("root", &self.root)
            .finish_non_exhaustive()
    }
}

impl DiskTree {
    /// Host-locator size for admitting a structural cross-root path check.
    pub(crate) fn root_path_bytes(&self) -> usize {
        self.root.as_os_str().len()
    }

    fn directory_identity(&self, path: &RelPath) -> Result<FileId, TreeError> {
        let shown = path.to_string();
        let handle = self.open(path, Want::Dir, &shown)?;
        self.used(&handle, &shown, |handle| {
            handle.identity(&self.root, &shown)
        })
    }

    /// Compare package directories, never merely their manifest-file identities.
    pub(crate) fn dependency_directory_matches(
        &self,
        base_manifest: &RelPath,
        relative: &str,
        destination: &Self,
        destination_manifest: &RelPath,
    ) -> Result<bool, TreeError> {
        super::require_first_party(base_manifest)?;
        super::require_first_party(destination_manifest)?;
        let missing_parent = |path: &RelPath| TreeError::NotRegular {
            path: path.to_string(),
        };
        let base = base_manifest
            .parent()
            .ok_or_else(|| missing_parent(base_manifest))?;
        let target = destination_manifest
            .parent()
            .ok_or_else(|| missing_parent(destination_manifest))?;
        let before = self.directory_identity(&base)?;
        let declared = self.directory_tree_at(&PathBuf::from(base.as_str()).join(relative))?;
        let expected = declared.directory_identity(&RelPath::root())?;
        let target_identity = destination.directory_identity(&target)?;
        let actual = destination.directory_tree_at(Path::new(target.as_str()))?;
        let same_directory = actual.directory_identity(&RelPath::root())? == target_identity
            && expected == target_identity
            && declared.root == actual.root;
        if self.directory_identity(&base)? != before {
            return Err(TreeError::from_io(
                &base_manifest.to_string(),
                std::io::Error::other("owning directory changed while checking a reference path"),
            ));
        }
        Ok(same_directory)
    }

    /// Open a tree rooted at `root`, canonicalising it once.
    ///
    /// A symlinked root is followed: the tree is rooted at its target.
    ///
    /// # Errors
    ///
    /// Returns [`TreeError::NotFound`] when the root does not exist,
    /// [`TreeError::NotRegular`] when it is not a directory, and
    /// [`TreeError::SymlinkLoop`] or [`TreeError::Io`] when the operating
    /// system fails or cannot verify a handle against the root.
    pub fn new(root: impl AsRef<Path>) -> Result<Self, TreeError> {
        let given = root.as_ref();
        let shown = given.display().to_string();
        let root = canonical_root(given).map_err(|e| TreeError::from_io(&shown, e))?;
        let metadata = std::fs::metadata(&root).map_err(|e| TreeError::from_io(&shown, e))?;
        Self::from_observed_root(root, &metadata, &shown)
    }

    fn from_observed_root(
        root: PathBuf,
        metadata: &Metadata,
        shown: &str,
    ) -> Result<Self, TreeError> {
        if !metadata.is_dir() {
            return Err(TreeError::NotRegular { path: shown.into() });
        }
        let strategy = Strategy::native(shown)?;
        #[cfg(unix)]
        let root_directory = unix_root::Root::open(&root, shown)?;
        #[cfg(target_os = "linux")]
        if root_directory.identity() != device_identity(metadata) {
            return Err(outside(shown));
        }
        let tree = Self::from_parts(
            root,
            strategy,
            #[cfg(unix)]
            root_directory,
        );
        #[cfg(target_os = "linux")]
        linux::verify_root(&tree, shown)?;
        Ok(tree)
    }

    fn from_parts(
        root: PathBuf,
        strategy: Strategy,
        #[cfg(unix)] root_directory: unix_root::Root,
    ) -> Self {
        Self {
            root,
            strategy,
            #[cfg(unix)]
            root_directory,
            #[cfg(test)]
            before_open: None,
            #[cfg(test)]
            after_open: None,
            #[cfg(test)]
            after_verify: None,
            #[cfg(test)]
            after_observation: None,
            #[cfg(all(test, unix, not(target_os = "linux")))]
            mid_step: None,
            #[cfg(all(test, unix))]
            opens: std::sync::Mutex::new(Vec::new()),
        }
    }

    /// Clone the original Linux workspace directory description.
    ///
    /// This is a path-only handle, suitable for descriptor-relative operations.
    /// An explicit metadata publisher can share it with this Tree rather than
    /// reopening a pathname that could now name another directory. Directory
    /// synchronization requires a separately opened, verified readable handle.
    /// Returning this handle does not make the inspected source immutable.
    ///
    /// # Errors
    /// Refuses a root outside its admitted canonical scope or a failure to
    /// inspect or clone the directory descriptor.
    #[cfg(target_os = "linux")]
    pub fn directory_handle(&self) -> Result<std::fs::File, TreeError> {
        linux::verify_root(self, &self.root.display().to_string())?;
        self.root_directory
            .dir
            .try_clone()
            .map(std::fs::File::from)
            .map_err(|e| TreeError::from_io(&self.root.display().to_string(), e))
    }

    fn directory_tree_at(&self, path: &Path) -> Result<Self, TreeError> {
        #[cfg(target_os = "linux")]
        {
            let shown = path.display().to_string();
            // The empty relative path denotes this root; openat requires `.`.
            let relative = if path.as_os_str().is_empty() {
                Path::new(".")
            } else {
                path
            };
            let root_directory =
                unix_root::Root::open_at(&self.root_directory.dir, relative, &shown)?;
            let root = std::fs::read_link(descriptor_path(&root_directory.dir))
                .map_err(|e| link_read_error(&shown, e))?;
            Ok(Self::from_parts(root, self.strategy, root_directory))
        }
        #[cfg(not(target_os = "linux"))]
        Self::new(self.root.join(path))
    }

    /// Inspect a regular file's byte length through a verified handle.
    pub(crate) fn byte_len(&self, path: &RelPath) -> Result<u64, TreeError> {
        super::require_first_party(path)?;
        let shown = path.to_string();
        let handle = self.open(path, Want::File, &shown)?;
        self.used(&handle, &shown, |handle| Ok(handle.metadata(&shown)?.len()))
    }

    /// Take the actual file identity and read bytes from that same verified open.
    ///
    /// An identity accepted by `seen` returns [`super::OpenedBytes::Seen`]
    /// without reading its payload or applying the byte ceiling to that payload.
    /// Otherwise the complete bytes obey [`Tree::read_bytes`].
    ///
    /// # Errors
    /// As [`Tree::read_bytes`], including identity and handle verification failures.
    pub fn read_unseen_bytes(
        &self,
        path: &RelPath,
        max_bytes: u64,
        seen: &dyn Fn(&FileId) -> bool,
    ) -> Result<super::OpenedBytes, TreeError> {
        super::require_first_party(path)?;
        let shown = path.to_string();
        let handle = self.open(path, Want::File, &shown)?;
        let id = handle.identity(&self.root, &shown)?;
        if seen(&id) {
            return Ok(super::OpenedBytes::Seen(id));
        }
        let bytes = self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))?;
        Ok(super::OpenedBytes::Read { id, bytes })
    }

    /// Record the flags of an open that is about to resolve a name below the
    /// root, and require that it cannot wait. The check runs before the open,
    /// so a regression that drops the flag fails here and never reaches a
    /// FIFO that would block it.
    #[cfg(all(test, unix))]
    fn note_open(&self, flags: u32) {
        assert!(
            never_blocks(flags),
            "an open of a name below the root could block: flags {flags:#o}"
        );
        self.opens.lock().expect("the open record").push(flags);
    }

    /// The flags of every open recorded so far, oldest first.
    #[cfg(all(test, unix))]
    fn recorded_opens(&self) -> Vec<u32> {
        self.opens.lock().expect("the open record").clone()
    }

    /// The path on disk that `path` names, before any symlink is followed.
    #[cfg(any(target_os = "linux", windows))]
    fn candidate(&self, path: &RelPath) -> PathBuf {
        #[cfg(target_os = "linux")]
        let root = descriptor_path(&self.root_directory.dir).join(".");
        #[cfg(windows)]
        let root = self.root.clone();
        if path.is_root() {
            root
        } else {
            root.join(path.as_str())
        }
    }

    /// Canonicalise `candidate` and require the canonical root as its prefix.
    #[cfg(any(target_os = "linux", windows))]
    fn contain(&self, candidate: &Path, shown: &str) -> Result<PathBuf, TreeError> {
        let canonical =
            std::fs::canonicalize(candidate).map_err(|e| TreeError::from_io(shown, e))?;
        if canonical.starts_with(&self.root) {
            Ok(canonical)
        } else {
            Err(outside(shown))
        }
    }

    /// Open `path` as `want` and verify the handle against the root.
    fn open(&self, path: &RelPath, want: Want, shown: &str) -> Result<Handle, TreeError> {
        refuse_windows_names(path, shown)?;
        match self.strategy {
            #[cfg(target_os = "linux")]
            Strategy::Linux => linux::open(self, path, want, shown).map(Handle::Linux),
            #[cfg(all(unix, not(target_os = "linux")))]
            Strategy::OtherUnix => other_unix::open(self, path, want, shown).map(Handle::OtherUnix),
            #[cfg(windows)]
            Strategy::Windows => handle_path::open(self, path, want, shown).map(Handle::Windows),
        }
    }

    /// Use the verified `handle` with `work`, then verify it again; a handle
    /// that no longer passes discards what the use returned.
    fn used<T>(
        &self,
        handle: &Handle,
        shown: &str,
        work: impl FnOnce(&Handle) -> Result<T, TreeError>,
    ) -> Result<T, TreeError> {
        hook!(self, after_verify);
        let result = work(handle);
        handle.recheck(self, shown)?;
        result
    }

    /// Exercise a source change at a deterministic observation boundary.
    #[cfg(test)]
    fn observed(&self) {
        hook!(self, after_observation);
    }
}

impl Tree for DiskTree {
    fn read(&self, path: &RelPath, max_bytes: u64) -> Result<String, TreeError> {
        text(self.read_bytes(path, max_bytes)?, path)
    }

    /// The file is checked against the root before and after reading. At most
    /// `max_bytes + 1` bytes are read, and the extra byte makes the read
    /// refuse. No UTF-8 validation or text conversion is applied.
    fn read_bytes(&self, path: &RelPath, max_bytes: u64) -> Result<Vec<u8>, TreeError> {
        super::require_first_party(path)?;
        let shown = path.to_string();
        let handle = self.open(path, Want::File, &shown)?;
        self.used(&handle, &shown, |handle| handle.read(max_bytes, &shown))
    }

    /// The identity is, on Unix, the device and inode of the verified handle,
    /// and on Windows the path the system gives for it, below the root; the
    /// text, when it is read, comes from the same handle.
    fn read_unseen(
        &self,
        path: &RelPath,
        max_bytes: u64,
        seen: &dyn Fn(&FileId) -> bool,
    ) -> Result<Opened, TreeError> {
        match self.read_unseen_bytes(path, max_bytes, seen)? {
            super::OpenedBytes::Seen(id) => Ok(Opened::Seen(id)),
            super::OpenedBytes::Read { id, bytes } => Ok(Opened::Read {
                id,
                text: text(bytes, path)?,
            }),
        }
    }

    fn list(&self, path: &RelPath) -> Result<Vec<Entry>, TreeError> {
        super::require_first_party(path)?;
        let shown = path.to_string();
        let handle = self.open(path, Want::Listing, &shown)?;
        let mut entries = self.used(&handle, &shown, |handle| handle.entries(&shown))?;
        entries.sort();
        Ok(entries)
    }

    fn entry(&self, path: &RelPath) -> Result<Option<EntryKind>, TreeError> {
        super::require_first_party(path)?;
        let shown = path.to_string();
        refuse_windows_names(path, &shown)?;
        let (Some(name), Some(parent)) = (path.file_name(), path.parent()) else {
            return Ok(Some(EntryKind::Dir));
        };
        // `x/..` is the directory the path itself leads to, which may lie
        // outside the root even when `x` does not, so it is opened whole.
        let climbs = name == "..";
        let directory = if climbs { path } else { &parent };
        let handle = match self.open(directory, Want::Dir, &shown) {
            Ok(handle) => handle,
            Err(TreeError::NotFound { .. } | TreeError::NotRegular { .. }) => return Ok(None),
            Err(other) => return Err(other),
        };
        self.used(&handle, &shown, |handle| {
            if climbs {
                Ok(Some(EntryKind::Dir))
            } else {
                handle.lookup(name, &shown)
            }
        })
    }
}

/// What a file type from the standard library is.
#[cfg(any(target_os = "linux", windows))]
fn kind_of(file_type: std::fs::FileType) -> EntryKind {
    if file_type.is_symlink() {
        EntryKind::Symlink
    } else if file_type.is_dir() {
        EntryKind::Dir
    } else if file_type.is_file() {
        EntryKind::File
    } else {
        EntryKind::Other
    }
}

/// What is at `path`, without following a final symlink.
#[cfg(any(target_os = "linux", windows))]
fn lookup(path: &Path, shown: &str) -> Result<Option<EntryKind>, TreeError> {
    match std::fs::symlink_metadata(path) {
        Ok(metadata) => Ok(Some(kind_of(metadata.file_type()))),
        Err(e)
            if matches!(
                e.kind(),
                std::io::ErrorKind::NotFound | std::io::ErrorKind::NotADirectory
            ) =>
        {
            Ok(None)
        }
        Err(e) => Err(TreeError::from_io(shown, e)),
    }
}

/// The entries of the directory at `listing`, in the order the system gives.
#[cfg(any(target_os = "linux", windows))]
fn read_entries(listing: &Path, shown: &str, max_entries: usize) -> Result<Vec<Entry>, TreeError> {
    let mut entries = Vec::new();
    for item in std::fs::read_dir(listing).map_err(|e| TreeError::from_io(shown, e))? {
        let item = item.map_err(|e| TreeError::from_io(shown, e))?;
        entry_room(entries.len(), max_entries, shown)?;
        let name = item
            .file_name()
            .into_string()
            .map_err(|raw| TreeError::NonUtf8Name {
                path: shown.to_owned(),
                name: raw.to_string_lossy().into_owned(),
            })?;
        let file_type = item.file_type().map_err(|e| TreeError::from_io(shown, e))?;
        entries.push(Entry {
            name,
            kind: kind_of(file_type),
        });
    }
    Ok(entries)
}

fn entry_room(count: usize, max_entries: usize, shown: &str) -> Result<(), TreeError> {
    if count < max_entries {
        Ok(())
    } else {
        Err(TreeError::from_io(
            shown,
            std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!(
                    "directory entry limit {max_entries} exceeded; increase the admitted capture budget"
                ),
            ),
        ))
    }
}

/// A listing refuses a path whose final component is not a real directory,
/// a symlink included, judged without following it.
#[cfg(any(target_os = "linux", windows))]
fn refuse_unless_directory(candidate: &Path, shown: &str) -> Result<(), TreeError> {
    let own = std::fs::symlink_metadata(candidate).map_err(|e| TreeError::from_io(shown, e))?;
    if own.is_dir() {
        Ok(())
    } else {
        Err(not_regular(shown))
    }
}

/// Classify a failure to open: a symlink in the final position (the canonical
/// path was swapped for a link after it was checked) is not a regular file.
#[cfg(any(target_os = "linux", windows))]
fn open_error(shown: &str, error: std::io::Error) -> TreeError {
    if crate::error::is_symlink_loop(&error) {
        not_regular(shown)
    } else {
        TreeError::from_io(shown, error)
    }
}

/// A failure to learn the path of a handle. A missing descriptor link (no
/// `/proc`) is an operating-system failure, never absence of the file.
#[cfg(any(target_os = "linux", windows))]
fn link_read_error(shown: &str, source: std::io::Error) -> TreeError {
    TreeError::Io {
        path: shown.to_owned(),
        source,
    }
}

/// The path the system gives for an open handle must lie under the root.
#[cfg(any(target_os = "linux", windows))]
fn verify_handle_path(root: &Path, handle_path: &Path, shown: &str) -> Result<(), TreeError> {
    if handle_path.starts_with(root) {
        Ok(())
    } else {
        Err(outside(shown))
    }
}

/// Linux: the kernel's own path for an open handle must lie under the root.
///
/// `handle_link` is `/proc/self/fd/<fd>`. This reads what the handle really
/// is, so no rename of a path can change the answer.
#[cfg(target_os = "linux")]
fn verify_linux_link(root: &Path, handle_link: &Path, shown: &str) -> Result<(), TreeError> {
    let target = std::fs::read_link(handle_link).map_err(|e| link_read_error(shown, e))?;
    verify_handle_path(root, &target, shown)
}

/// `/proc/self/fd/<fd>`: the kernel's own path for an open handle.
#[cfg(target_os = "linux")]
fn descriptor_path(handle: &impl std::os::fd::AsRawFd) -> PathBuf {
    PathBuf::from(format!("/proc/self/fd/{}", handle.as_raw_fd()))
}

/// Read at most `max_bytes` raw bytes from a verified handle.
fn read_capped(source: impl Read, max_bytes: u64, shown: &str) -> Result<Vec<u8>, TreeError> {
    let mut bytes = Vec::new();
    source
        .take(max_bytes.saturating_add(1))
        .read_to_end(&mut bytes)
        .map_err(|e| TreeError::from_io(shown, e))?;
    if u64::try_from(bytes.len()).map_or(true, |len| len > max_bytes) {
        return Err(TreeError::TooLarge {
            path: shown.to_owned(),
            limit: max_bytes,
        });
    }
    Ok(bytes)
}

fn text(bytes: Vec<u8>, path: &RelPath) -> Result<String, TreeError> {
    String::from_utf8(bytes).map_err(|_| TreeError::NotUtf8 {
        path: path.to_string(),
    })
}

fn outside(shown: &str) -> TreeError {
    TreeError::OutsideRoot {
        path: shown.to_owned(),
    }
}

fn not_regular(shown: &str) -> TreeError {
    TreeError::NotRegular {
        path: shown.to_owned(),
    }
}

/// Unix: the identity of a file is the device and inode of its handle.
#[cfg(unix)]
fn device_identity(metadata: &Metadata) -> FileId {
    use std::os::unix::fs::MetadataExt as _;
    FileId::from_device(metadata.dev(), metadata.ino())
}

/// Windows: refuse a path with a segment that Windows would not read as the
/// name it spells. Such a path is never canonicalised.
#[cfg(windows)]
fn refuse_windows_names(path: &RelPath, shown: &str) -> Result<(), TreeError> {
    if path.segments().any(is_ambiguous_on_windows) {
        Err(outside(shown))
    } else {
        Ok(())
    }
}

/// Elsewhere every segment names itself.
#[cfg(not(windows))]
#[expect(
    clippy::unnecessary_wraps,
    reason = "the signature is shared with Windows, where the call can refuse"
)]
fn refuse_windows_names(_path: &RelPath, _shown: &str) -> Result<(), TreeError> {
    Ok(())
}

/// True for a segment that is a reserved device name, bare or with any
/// extension and in any case; for one that ends in a dot or a space, which
/// Windows strips; and for one that holds a colon, which names an alternate
/// data stream. A `..` segment climbs and names no file.
#[cfg(windows)]
fn is_ambiguous_on_windows(segment: &str) -> bool {
    if segment == ".." {
        return false;
    }
    if segment.ends_with(['.', ' ']) || segment.contains(':') {
        return true;
    }
    let stem = segment
        .split('.')
        .next()
        .unwrap_or(segment)
        .trim_end_matches(' ')
        .to_ascii_uppercase();
    let numbered = |prefix: &str| {
        stem.strip_prefix(prefix).is_some_and(|digit| {
            matches!(
                digit,
                "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" | "¹" | "²" | "³"
            )
        })
    };
    matches!(
        stem.as_str(),
        "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$"
    ) || numbered("COM")
        || numbered("LPT")
}