Skip to main content

common/
safedir.rs

1//! Safe, race-resistant directory traversal primitives.
2//!
3//! This module provides `O_NOFOLLOW`-based directory and file handle types that
4//! prevent TOCTOU races by using file-descriptor-relative syscalls (`openat`,
5//! `fstatat`) rather than path-based lookups. Every `open_dir`/`child` call
6//! refuses to follow symlinks, so an attacker who races a directory walk cannot
7//! redirect operations outside the intended tree.
8
9use std::ffi::{CStr, OsStr};
10use std::num::NonZeroUsize;
11use std::os::fd::{AsFd, BorrowedFd, IntoRawFd, OwnedFd};
12use std::os::unix::ffi::OsStrExt;
13use std::path::Path;
14use std::sync::Arc;
15
16use std::os::unix::io::{AsRawFd, RawFd};
17
18use nix::fcntl::{AT_FDCWD, AtFlags, OFlag, openat, readlinkat};
19use nix::sys::stat::{FileStat, Mode, fchmod, fstat, fstatat, futimens, mkdirat};
20use nix::sys::time::TimeSpec;
21use nix::unistd::{Gid, Uid, UnlinkatFlags, fchown, fchownat, linkat, symlinkat, unlinkat};
22
23use crate::timing::metadata::{Phase as MetadataTimingPhase, scope as metadata_timing_scope};
24use crate::walk::EntryKind;
25
26pub(crate) mod overlap;
27
28#[cfg(test)]
29mod resource_tests;
30#[cfg(test)]
31mod timing_tests;
32
33// ── Destination creation modes ───────────────────────────────────────────────
34
35/// The mode a destination FILE is created with, before it has any contents.
36///
37/// Owner-only. The source mode is applied by [`set_file_metadata_owned`] once the last byte has been
38/// written, so the file is never visible to anyone but the copier while it is being filled in —
39/// the file counterpart of the directory split-chmod (see [`DST_DIR_CREATE_MODE`]).
40///
41/// Creating at the *final* mode instead would publish the destination before its contents exist,
42/// giving a half-written file the audience its finished form was meant to have — at the default
43/// `0o0777` mask, a world-readable source yields a world-readable destination from creation onward.
44/// The sharper case needs the special bits preserved: a root copier holds `CAP_FSETID`, so writing
45/// does not clear `S_ISUID`, and the destination carries `setuid` root while the source's owner is
46/// still authoring its contents. That is not an exec window while the copy *runs* — our own write
47/// descriptor is open, and `execve` refuses a file any process holds open for writing with
48/// `ETXTBSY`. If the copier dies, closing that descriptor drops the protection; creation at the
49/// final mode would leave a finished-looking setuid binary (see `docs/tocttou.md`). Withholding the
50/// owner execute bit is deliberate too — a half-written executable should not be executable.
51///
52/// This is a constant rather than a [`Dir::create_file`] parameter so that no call site, present or
53/// future, can create a destination file at a wide mode. Like any creation mode it is subject to
54/// the umask, which can only narrow it further.
55pub const DST_FILE_CREATE_MODE: u32 = 0o600;
56
57/// The mode a destination DIRECTORY is created with, before it has any children.
58///
59/// Owner-only, plus the execute bit the copier needs to populate it. The source mode is applied
60/// after every child has been written — by `CopyVisitor::dir_post` locally, and on directory
61/// completion remotely.
62pub const DST_DIR_CREATE_MODE: u32 = 0o700;
63
64// ── Strict operand resolution (--require-toctou-safe) ────────────────────────
65//
66// A process-global, one-way switch armed by the TOCTOU linter (see
67// `crate::toctou_check::run_linter`) when `--require-toctou-safe` proceeds. When
68// armed, the two multi-component path resolutions in this module —
69// `Dir::open_root_dir` and `Dir::open_parent_dir`, the only places an operand
70// path is resolved — use `openat2(2)` with `RESOLVE_NO_SYMLINKS` instead of a
71// plain `openat`, so a symlink in ANY component of an operand path fails closed
72// with `ELOOP` at the open itself (not in a racy pre-check). This is a global
73// rather than a threaded setting because it is per-process security policy that
74// must cover every operand open in every engine (copy/link/rm/chmod, local and
75// rcpd) without widening each Settings struct and the rcpd spawn contract; it is
76// armed once before the async runtime starts and never unset.
77
78static STRICT_OPERAND_RESOLUTION: std::sync::atomic::AtomicBool =
79    std::sync::atomic::AtomicBool::new(false);
80
81tokio::task_local! {
82    /// The weak admission reference inherited by fd-owning blocking metadata work in this task.
83    static FD_ADMISSION: throttle::FdAdmission;
84}
85
86/// Run `future` with a weak admission reference available to safedir blocking work.
87///
88/// Tokio cannot cancel a `spawn_blocking` closure after it starts. Without this scope, cancelling
89/// the async waiter drops its operation guard even though the detached closure may still own a
90/// duplicated directory or entry fd. [`run_metadata_probed_blocking`] upgrades the reference for
91/// each such closure, keeping the original admission slot occupied until that fd-owning owner
92/// finishes. The ambient reference is deliberately weak: dropping the concrete guard before
93/// directory recursion still releases capacity even while this scope remains on the stack.
94/// Tokio task locals are not inherited by `tokio::spawn`; every spawned entry worker must install
95/// its own scope after it receives admission.
96pub async fn with_fd_admission<F>(admission: throttle::FdAdmission, future: F) -> F::Output
97where
98    F: std::future::Future,
99{
100    FD_ADMISSION.scope(admission, future).await
101}
102
103/// Run `future` under `admission` when this traversal uses an fd-admission pool.
104pub(crate) async fn with_optional_fd_admission<F>(
105    admission: Option<throttle::FdAdmission>,
106    future: F,
107) -> F::Output
108where
109    F: std::future::Future,
110{
111    match admission {
112        Some(admission) => with_fd_admission(admission, future).await,
113        None => future.await,
114    }
115}
116
117/// Arm strict operand resolution for the rest of this process (one-way).
118///
119/// Called by the TOCTOU linter when `--require-toctou-safe` proceeds; not
120/// intended to be called from anywhere else.
121pub fn enable_strict_operand_resolution() {
122    STRICT_OPERAND_RESOLUTION.store(true, std::sync::atomic::Ordering::Release);
123}
124
125/// Whether strict operand resolution is armed for this process.
126#[must_use]
127pub fn strict_operand_resolution() -> bool {
128    STRICT_OPERAND_RESOLUTION.load(std::sync::atomic::Ordering::Acquire)
129}
130
131/// Open `path` with `openat2(2)`, refusing to resolve ANY symlink component
132/// (`RESOLVE_NO_SYMLINKS`, which also implies `RESOLVE_NO_MAGICLINKS`). A
133/// symlink anywhere in the path fails with `ELOOP`.
134#[cfg(target_os = "linux")]
135fn openat2_no_symlinks(path: &Path, flags: OFlag) -> nix::Result<OwnedFd> {
136    use nix::fcntl::{OpenHow, ResolveFlag, openat2};
137    let how = OpenHow::new()
138        .flags(flags)
139        .resolve(ResolveFlag::RESOLVE_NO_SYMLINKS);
140    // bounded retry: with resolve restrictions openat2 can return EAGAIN when the
141    // kernel detects a rename race during resolution (see openat2(2)); retrying a
142    // handful of times resolves transient races without risking an unbounded loop.
143    let mut attempts = 0;
144    loop {
145        match openat2(AT_FDCWD, path, how) {
146            Err(nix::errno::Errno::EAGAIN) if attempts < 4 => attempts += 1,
147            other => return other,
148        }
149    }
150}
151
152/// Whether this kernel supports `openat2(2)` (Linux 5.6+), probed once.
153///
154/// Strict operand resolution is impossible without it, so
155/// `--require-toctou-safe` refuses to run when this returns `false`.
156#[cfg(target_os = "linux")]
157#[must_use]
158pub fn openat2_available() -> bool {
159    static PROBE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
160    *PROBE.get_or_init(|| {
161        // "/" always exists and is a directory; ENOSYS is the only expected failure
162        !matches!(
163            openat2_no_symlinks(Path::new("/"), OFlag::O_PATH | OFlag::O_CLOEXEC),
164            Err(nix::errno::Errno::ENOSYS)
165        )
166    })
167}
168
169/// Non-Linux builds have no `openat2`; `--require-toctou-safe` already refuses
170/// to run there (the hardened walk is Linux-only), so this is only consulted to
171/// render an accurate `--toctou-check` note.
172#[cfg(not(target_os = "linux"))]
173#[must_use]
174pub fn openat2_available() -> bool {
175    false
176}
177
178// ── FileMeta ──────────────────────────────────────────────────────────────────
179
180/// A snapshot of filesystem metadata obtained via `fstat`/`fstatat`.
181///
182/// Implements [`crate::preserve::Metadata`] so callers can apply these fields
183/// to another entry with the existing `set_*_metadata` helpers.
184#[derive(Clone, Debug)]
185pub struct FileMeta {
186    uid: u32,
187    gid: u32,
188    atime: i64,
189    atime_nsec: i64,
190    mtime: i64,
191    mtime_nsec: i64,
192    ctime: i64,
193    ctime_nsec: i64,
194    mode: u32,
195    size: u64,
196    dev: u64,
197    ino: u64,
198}
199
200impl FileMeta {
201    fn from_stat(st: &FileStat) -> Self {
202        Self {
203            uid: st.st_uid,
204            gid: st.st_gid,
205            atime: st.st_atime,
206            atime_nsec: st.st_atime_nsec,
207            mtime: st.st_mtime,
208            mtime_nsec: st.st_mtime_nsec,
209            ctime: st.st_ctime,
210            ctime_nsec: st.st_ctime_nsec,
211            mode: st.st_mode,
212            size: st.st_size as u64,
213            dev: st.st_dev,
214            ino: st.st_ino,
215        }
216    }
217
218    /// The device number of the filesystem this entry lives on.
219    #[must_use]
220    pub fn dev(&self) -> u64 {
221        self.dev
222    }
223
224    /// The entry's inode number.
225    #[must_use]
226    pub fn ino(&self) -> u64 {
227        self.ino
228    }
229}
230
231impl crate::preserve::Metadata for FileMeta {
232    fn uid(&self) -> u32 {
233        self.uid
234    }
235    fn gid(&self) -> u32 {
236        self.gid
237    }
238    fn atime(&self) -> i64 {
239        self.atime
240    }
241    fn atime_nsec(&self) -> i64 {
242        self.atime_nsec
243    }
244    fn mtime(&self) -> i64 {
245        self.mtime
246    }
247    fn mtime_nsec(&self) -> i64 {
248        self.mtime_nsec
249    }
250    fn permissions(&self) -> std::fs::Permissions {
251        use std::os::unix::fs::PermissionsExt;
252        std::fs::Permissions::from_mode(self.mode)
253    }
254    fn ctime(&self) -> i64 {
255        self.ctime
256    }
257    fn ctime_nsec(&self) -> i64 {
258        self.ctime_nsec
259    }
260    fn size(&self) -> u64 {
261        self.size
262    }
263}
264
265// ── EntryKind classification ───────────────────────────────────────────────────
266
267fn kind_from_stat(st: &FileStat) -> EntryKind {
268    let mode = st.st_mode;
269    // use libc mode-classification macros via their bit patterns (POSIX S_IFMT)
270    // S_IFREG = 0o0100000, S_IFDIR = 0o0040000, S_IFLNK = 0o0120000
271    let ifmt = mode & libc::S_IFMT;
272    match ifmt {
273        libc::S_IFREG => EntryKind::File,
274        libc::S_IFDIR => EntryKind::Dir,
275        libc::S_IFLNK => EntryKind::Symlink,
276        _ => EntryKind::Special,
277    }
278}
279
280// ── Handle ────────────────────────────────────────────────────────────────────
281
282/// An open, classified handle to a filesystem entry obtained via `O_PATH|O_NOFOLLOW`.
283///
284/// The fd is opened with `O_PATH`, so it cannot be used for reading; it exists
285/// solely to identify the entry (for further `openat` calls relative to it) and
286/// to carry the stat snapshot. A symlink entry is never followed: it yields a
287/// `Handle` with `kind() == EntryKind::Symlink`.
288#[derive(Debug)]
289pub struct Handle {
290    fd: OwnedFd,
291    kind: EntryKind,
292    dev: u64,
293    ino: u64,
294    meta: FileMeta,
295}
296
297/// The classification, identity, and size needed to remove an occupied destination slot.
298///
299/// Unlike [`Handle`], this snapshot does not keep an inode pinned. Overwrite removal operates by
300/// name through a pinned parent directory, so retaining the entry fd cannot bind the later by-name
301/// removal to that inode. Converting to this snapshot closes the classification fd while preserving
302/// the input-overlap and accounting data the removal path needs.
303#[derive(Clone, Copy, Debug)]
304pub struct RemovalSnapshot {
305    kind: EntryKind,
306    identity: (u64, u64),
307    size: u64,
308}
309
310impl RemovalSnapshot {
311    /// The entry classification captured during overwrite planning.
312    #[must_use]
313    pub fn kind(self) -> EntryKind {
314        self.kind
315    }
316
317    pub(crate) fn identity(self) -> (u64, u64) {
318        self.identity
319    }
320
321    /// The entry size captured during overwrite planning.
322    #[must_use]
323    pub fn size(self) -> u64 {
324        self.size
325    }
326}
327
328impl Handle {
329    /// The entry's classification (File / Dir / Symlink / Special).
330    #[must_use]
331    pub fn kind(&self) -> EntryKind {
332        self.kind
333    }
334
335    /// The device number of the entry.
336    #[must_use]
337    pub fn dev(&self) -> u64 {
338        self.dev
339    }
340
341    /// The inode number of the entry.
342    #[must_use]
343    pub fn ino(&self) -> u64 {
344        self.ino
345    }
346
347    /// A snapshot of the entry's metadata at the time the handle was opened.
348    #[must_use]
349    pub fn meta(&self) -> &FileMeta {
350        &self.meta
351    }
352
353    /// Consume this handle and retain only the data needed for overwrite removal.
354    #[must_use]
355    pub fn into_removal_snapshot(self) -> RemovalSnapshot {
356        RemovalSnapshot {
357            kind: self.kind,
358            identity: (self.dev, self.ino),
359            size: self.meta.size,
360        }
361    }
362
363    /// Borrow the underlying file descriptor.
364    #[must_use]
365    pub fn as_fd(&self) -> BorrowedFd<'_> {
366        self.fd.as_fd()
367    }
368
369    /// Duplicate this handle, sharing the same pinned inode via a `dup`'d
370    /// (`F_DUPFD_CLOEXEC`) `O_PATH` file descriptor and copying the cached
371    /// classification + stat snapshot.
372    ///
373    /// This is a pure fd dup — it opens nothing, follows nothing, and stats
374    /// nothing on the filesystem, so it preserves every TOCTOU property of the
375    /// original `O_PATH|O_NOFOLLOW` handle (the clone pins the exact same inode and
376    /// cannot be redirected by a concurrent rename/symlink swap). It lets a walk
377    /// that classifies an entry once hand an owned handle to a deferred (post-order)
378    /// step without a second `openat`/`fstatat` on the entry.
379    pub fn try_clone(&self) -> std::io::Result<Handle> {
380        Ok(Handle {
381            fd: self.fd.try_clone()?,
382            kind: self.kind,
383            dev: self.dev,
384            ino: self.ino,
385            meta: self.meta.clone(),
386        })
387    }
388
389    /// Read this symlink's target and metadata from the one pinned `O_PATH` fd: the target via the
390    /// empty-path `readlinkat` ([`read_link_handle`]) and the metadata from this handle's `fstat`
391    /// snapshot. Both describe the same pinned inode, so they are a faithful pair (the symlink
392    /// analogue of [`Dir::open_file_read`]'s `(File, FileMeta)`). Errors if the handle is not a
393    /// symlink (the empty-path read requires a symlink fd).
394    pub async fn read_symlink(
395        &self,
396        side: congestion::Side,
397    ) -> std::io::Result<(std::path::PathBuf, FileMeta)> {
398        let target = read_link_handle(self, side).await?;
399        Ok((target, self.meta.clone()))
400    }
401}
402
403// ── Dir ───────────────────────────────────────────────────────────────────────
404
405/// A directory file descriptor opened `O_RDONLY|O_DIRECTORY|O_NOFOLLOW|O_CLOEXEC`.
406///
407/// All entry-level operations are relative to this fd, preventing TOCTOU races
408/// that path-based lookups are vulnerable to.
409///
410/// The fd is held behind an `Arc` so per-entry operations can move an owned
411/// reference into their `spawn_blocking` closure. Once a closure starts it is
412/// not cancellable: if the surrounding future is then dropped (timeout,
413/// `fail_early` abort, Ctrl-C) the closure keeps running detached. User work
414/// still queued at `run_fd_admitted_blocking`'s handoff is instead reclaimed
415/// synchronously with its captures; the Tokio wrapper does nothing if scheduled
416/// later. Cloning the `Arc` (a refcount bump, no syscall) keeps the open file
417/// description alive for a started closure's full duration even if the
418/// originating `Dir` is dropped mid-flight, preserving the `openat` TOCTOU
419/// guarantee. Later fd-relative methods (`open_file_read`, `create_file`,
420/// `make_dir`, `entries`, `read_entries`, …) must follow this same clone-Arc-into-closure
421/// shape.
422#[derive(Debug)]
423pub struct Dir {
424    // immutable identity sampled from this exact held fd; mutable metadata is never cached
425    captured_identity: Option<(u64, u64)>,
426    fd: Arc<DirectoryDescriptor>,
427    /// Which filesystem side this directory lives on, for congestion gating.
428    side: congestion::Side,
429    /// Whether a file created in THIS directory may inherit an access ACL that rcp has not
430    /// sanitized — i.e. whether the directory may still carry a default ACL rcp took no
431    /// responsibility for.
432    ///
433    /// `true` for every directory rcp merely OPENED: the ambient parent above a named operand
434    /// (`open_parent_dir` / `open_root_dir`) and any reused directory before its lockdown. `false`
435    /// only once rcp has made inheritance impossible: a `make_dir` (which strips both ACLs at
436    /// creation under strict operand resolution) or a [`lockdown_reused_dir`] (which removes the
437    /// default ACL for the copy's duration) — the ONLY two sites that clear it, via
438    /// `Self::mark_children_cannot_inherit`.
439    ///
440    /// Consulted ONLY by the file-creation helpers, ONLY under `--require-toctou-safe`. The polarity is
441    /// deliberately fail-safe: a stale `true` on an already-sanitized parent costs one wasted
442    /// `fremovexattr` per created file; a wrong `false` would silently reopen the containment hole
443    /// (docs/acls.md, "containment"), so nothing but the two sanitizing sites may clear it — and
444    /// the ONE re-arming site may set it back: [`ReusedDirLock`]'s rollback restores the
445    /// directory's original default ACL, so it stores `true` (before the restore syscall) or a
446    /// file created after the rollback would inherit that ACL with the strip skipped. `Arc`d so
447    /// `create_file`'s blocking closure can consult it AFTER its `openat` (a pre-closure snapshot
448    /// races the rollback: the closure can run after the restore with a stale `false`).
449    children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
450}
451
452/// Owns the directory fd before the shared credit that accounts for its lifetime.
453///
454/// Field order makes the descriptor close before its last admission reference is released.
455#[derive(Debug)]
456struct DirectoryDescriptor {
457    fd: OwnedFd,
458    credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
459}
460
461impl DirectoryDescriptor {
462    fn reopen(&self) -> std::io::Result<OwnedFd> {
463        self.reopen_with_proc_open(|path, flags| openat(AT_FDCWD, path, flags, Mode::empty()))
464    }
465
466    fn reopen_with_proc_open(
467        &self,
468        open_proc: impl FnOnce(&str, OFlag) -> nix::Result<OwnedFd>,
469    ) -> std::io::Result<OwnedFd> {
470        let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
471        match openat(self.as_fd(), c".", flags, Mode::empty()) {
472            Err(permission @ nix::errno::Errno::EACCES) => {
473                // opening "." also needs search permission; the proc magic link opens the held
474                // inode without that extra requirement, but still checks read permission.
475                // self keeps the fd owned throughout the open, and following this trusted magic
476                // link is intentional: O_NOFOLLOW would reject it
477                let path = format!("/proc/self/fd/{}", self.as_raw_fd());
478                open_proc(&path, flags).map_err(|error| match error {
479                    // an unavailable proc path must not make the held directory appear missing.
480                    // retain resource and backend errors from an otherwise usable retry
481                    nix::errno::Errno::ENOENT
482                    | nix::errno::Errno::ENOTDIR
483                    | nix::errno::Errno::ELOOP => permission,
484                    error => error,
485                })
486            }
487            result => result,
488        }
489        .map_err(nix_to_io)
490    }
491
492    fn listing_fd_with_seek(
493        &self,
494        seek: impl FnOnce(BorrowedFd<'_>) -> nix::Result<libc::off_t>,
495    ) -> std::io::Result<OwnedFd> {
496        match seek(self.as_fd()) {
497            Ok(_) => self.fd.try_clone(),
498            Err(nix::errno::Errno::ESPIPE) => {
499                // nonseekable FUSE directories need a fresh description for each listing.
500                // reopen stays on the held inode, including when "." lacks search permission.
501                // each fallback adds an open/close pair
502                self.reopen()
503            }
504            Err(error) => Err(nix_to_io(error)),
505        }
506    }
507}
508
509impl AsFd for DirectoryDescriptor {
510    fn as_fd(&self) -> BorrowedFd<'_> {
511        self.fd.as_fd()
512    }
513}
514
515impl AsRawFd for DirectoryDescriptor {
516    fn as_raw_fd(&self) -> RawFd {
517        self.fd.as_raw_fd()
518    }
519}
520
521/// A directory entry read by a listing or streaming cursor.
522///
523/// The type hint comes from `d_type` and must be checked before acting on the entry.
524#[derive(Debug)]
525pub struct DirectoryEntry {
526    pub name: std::ffi::OsString,
527    pub kind_hint: Option<EntryKind>,
528}
529
530#[cfg(test)]
531type CursorReadHook = Box<dyn FnMut(usize, RawFd) -> std::io::Result<()> + Send>;
532
533/// An independently opened directory stream whose offset survives batch boundaries.
534pub struct DirectoryCursor {
535    iterator: Option<OwnedDirectoryStream>,
536    first_read: bool,
537    exhausted: bool,
538    #[cfg(test)]
539    read_hook: Option<CursorReadHook>,
540}
541
542impl DirectoryCursor {
543    fn new(iterator: OwnedDirectoryStream) -> Self {
544        Self {
545            iterator: Some(iterator),
546            first_read: true,
547            exhausted: false,
548            #[cfg(test)]
549            read_hook: None,
550        }
551    }
552
553    /// Read access and default ACLs from this cursor's open directory.
554    ///
555    /// The stream moves through the gated reads without opening or duplicating a descriptor.
556    /// An error or cancellation ends this cursor; started work owns its stream and credit.
557    pub async fn read_acls(&mut self, side: congestion::Side) -> std::io::Result<Acls> {
558        let iterator = self
559            .iterator
560            .take()
561            .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
562        let (iterator, acls) = read_acls_owned(iterator, side, true).await?;
563        self.iterator = Some(iterator);
564        Ok(acls)
565    }
566
567    /// Open a directory cursor by path, following symlinks for explicit dereferencing callers.
568    pub async fn open_following_symlinks(
569        path: &Path,
570        side: congestion::Side,
571        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
572    ) -> std::io::Result<Self> {
573        let path = path.to_owned();
574        let iterator = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
575            if strict_operand_resolution() {
576                return Err(std::io::Error::new(
577                    std::io::ErrorKind::InvalidInput,
578                    "following directory symlinks is incompatible with strict operand resolution",
579                ));
580            }
581            let fd = openat(
582                AT_FDCWD,
583                &path,
584                OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC,
585                Mode::empty(),
586            )
587            .map_err(nix_to_io)?;
588            let iterator = OwnedDirectoryStream::from_fd(fd, Some(credit))?;
589            #[cfg(test)]
590            let _visit = resource_tests::gate_opened_descriptor(iterator.as_raw_fd())?;
591            Ok(iterator)
592        })
593        .await?;
594        Ok(Self::new(iterator))
595    }
596
597    /// Read at most `limit` entries, excluding `.` and `..`; an empty batch means EOF.
598    ///
599    /// The first batch refreshes the description's position immediately before reading. Later
600    /// batches preserve it; this is not a snapshot of a concurrently changing directory.
601    ///
602    /// While the cursor remains live, observed EOF makes later batches empty without admission
603    /// or blocking work. EOF alone does not close the stream; a full batch does not establish EOF.
604    ///
605    /// An error or cancellation after admission ends this cursor. The blocking job then owns and
606    /// closes its iterator, so a later call cannot rewind or duplicate already yielded entries.
607    pub async fn next_batch(
608        &mut self,
609        limit: NonZeroUsize,
610    ) -> std::io::Result<Vec<DirectoryEntry>> {
611        self.next_batch_with_seek(limit, |fd| {
612            nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
613        })
614        .await
615    }
616
617    async fn next_batch_with_seek(
618        &mut self,
619        limit: NonZeroUsize,
620        seek: impl FnOnce(BorrowedFd<'_>) -> nix::Result<libc::off_t> + Send + 'static,
621    ) -> std::io::Result<Vec<DirectoryEntry>> {
622        // a later ACL failure or cancellation leaves no iterator and must not look like EOF
623        if self.exhausted && self.iterator.is_some() {
624            return Ok(Vec::new());
625        }
626        throttle::get_ops_token().await;
627        let mut iterator = self
628            .iterator
629            .take()
630            .ok_or_else(|| std::io::Error::other("directory cursor was interrupted or failed"))?;
631        let first_read = std::mem::take(&mut self.first_read);
632        #[cfg(test)]
633        let mut read_hook = self.read_hook.take();
634        let (returned, entries, exhausted) = run_fd_admitted_blocking(move || {
635            if first_read {
636                // refresh btrfs's open-time cutoff after all waits, before libc buffers entries.
637                // a FUSE seek need not refresh the server's separately held backing description
638                match seek(iterator.as_fd()) {
639                    Ok(_) => {}
640                    // this independent stream has never been read, so ESPIPE needs no reopen
641                    Err(nix::errno::Errno::ESPIPE) => {}
642                    Err(error) => return Err(nix_to_io(error)),
643                }
644            }
645            let mut entries = Vec::with_capacity(limit.get());
646            let mut exhausted = false;
647            while entries.len() < limit.get() {
648                #[cfg(test)]
649                if let Some(read_hook) = read_hook.as_mut() {
650                    read_hook(entries.len(), iterator.as_raw_fd())?;
651                }
652                let Some(entry) = iterator.next_raw_entry()? else {
653                    exhausted = true;
654                    break;
655                };
656                if entry.name == "." || entry.name == ".." {
657                    continue;
658                }
659                entries.push(entry);
660            }
661            Ok((iterator, entries, exhausted))
662        })
663        .await?;
664        self.iterator = Some(returned);
665        self.exhausted = exhausted;
666        Ok(entries)
667    }
668}
669
670/// Owns one `DIR*` and its fd for a listing or a movable cursor.
671#[derive(Debug)]
672struct OwnedDirectoryStream {
673    dir: std::ptr::NonNull<libc::DIR>,
674    // closedir runs in Drop before fields release this shared descriptor credit
675    _credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
676}
677
678// SAFETY: ownership is exclusive; the stream moves into one blocking job at a time, and no
679// `readdir` call or entry reference can overlap a move to another thread.
680unsafe impl Send for OwnedDirectoryStream {}
681
682impl OwnedDirectoryStream {
683    fn from_fd(
684        fd: OwnedFd,
685        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
686    ) -> std::io::Result<Self> {
687        let owner = DirectoryDescriptor { fd, credit };
688        // SAFETY: fd is valid and held exclusively. On failure fdopendir leaves it open, so
689        // the owner closes it before releasing credit; on success closedir takes over the fd.
690        let dir = std::ptr::NonNull::new(unsafe { libc::fdopendir(owner.as_raw_fd()) })
691            .ok_or_else(std::io::Error::last_os_error)?;
692        let _ = owner.fd.into_raw_fd();
693        Ok(Self {
694            dir,
695            _credit: owner.credit,
696        })
697    }
698
699    fn next_raw_entry(&mut self) -> std::io::Result<Option<DirectoryEntry>> {
700        nix::errno::Errno::clear();
701        // SAFETY: self exclusively owns the live stream, and the returned dirent is copied
702        // before another readdir call or the stream's Drop can invalidate it.
703        let raw = unsafe { libc::readdir(self.dir.as_ptr()) };
704        if raw.is_null() {
705            let errno = nix::errno::Errno::last_raw();
706            return if errno == 0 {
707                Ok(None)
708            } else {
709                Err(std::io::Error::from_raw_os_error(errno))
710            };
711        }
712        // keep all record field access in the helper exercised by the focused Miri tests
713        // SAFETY: readdir returns an aligned record in one live allocation, with initialized
714        // d_type and a NUL-terminated d_name. Exclusive stream ownership keeps the record
715        // unchanged until the helper has copied the fields
716        Ok(Some(unsafe { directory_entry_from_raw(raw) }))
717    }
718}
719
720/// Copy the name and advisory type from a directory record.
721///
722/// # Safety
723///
724/// `raw` must be non-null, aligned for `libc::dirent`, and point to the start of a directory record
725/// with an initialized `d_type` and a NUL-terminated name at `d_name`'s offset. The entire byte range
726/// from `raw` through the name's NUL must lie within one live allocation. The type and name bytes
727/// must remain readable and unchanged until this returns.
728unsafe fn directory_entry_from_raw(raw: *const libc::dirent) -> DirectoryEntry {
729    // SAFETY: the caller guarantees the readable type field and NUL-terminated name. libc records
730    // can be smaller or larger than dirent, so borrow neither the struct nor its d_name array
731    let name = unsafe { CStr::from_ptr((&raw const (*raw).d_name).cast()) };
732    let dtype = unsafe { (*raw).d_type };
733    DirectoryEntry {
734        name: OsStr::from_bytes(name.to_bytes()).to_owned(),
735        kind_hint: kind_hint_from_dtype(dtype),
736    }
737}
738
739fn kind_hint_from_dtype(dtype: libc::c_uchar) -> Option<EntryKind> {
740    match dtype {
741        libc::DT_DIR => Some(EntryKind::Dir),
742        libc::DT_LNK => Some(EntryKind::Symlink),
743        libc::DT_REG => Some(EntryKind::File),
744        libc::DT_FIFO | libc::DT_CHR | libc::DT_BLK | libc::DT_SOCK => Some(EntryKind::Special),
745        _ => None,
746    }
747}
748
749impl AsRawFd for OwnedDirectoryStream {
750    fn as_raw_fd(&self) -> RawFd {
751        // SAFETY: self owns the live DIR stream until Drop.
752        unsafe { libc::dirfd(self.dir.as_ptr()) }
753    }
754}
755
756impl AsFd for OwnedDirectoryStream {
757    fn as_fd(&self) -> BorrowedFd<'_> {
758        // SAFETY: this stream owns the descriptor until Drop, after the borrow ends
759        unsafe { BorrowedFd::borrow_raw(self.as_raw_fd()) }
760    }
761}
762
763impl Drop for OwnedDirectoryStream {
764    fn drop(&mut self) {
765        // SAFETY: fdopendir transferred this one stream to self on success.
766        unsafe { libc::closedir(self.dir.as_ptr()) };
767    }
768}
769
770impl Dir {
771    /// Wrap a directory fd rcp merely OPENED (as opposed to created): its inherited-ACL state is
772    /// unknown, so files created in it must assume the worst — see `children_may_inherit`.
773    fn opened(fd: OwnedFd, side: congestion::Side) -> Dir {
774        Self::opened_with_credit(fd, side, None)
775    }
776
777    fn opened_with_credit(
778        fd: OwnedFd,
779        side: congestion::Side,
780        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
781    ) -> Dir {
782        Dir {
783            captured_identity: None,
784            fd: Arc::new(DirectoryDescriptor { fd, credit }),
785            side,
786            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
787        }
788    }
789
790    /// Record that nothing created in this directory can inherit an ACL anymore — called by the
791    /// two sanitizing sites (`make_dir`'s creation strip and [`lockdown_reused_dir`]'s default-ACL
792    /// removal) and nothing else; see `children_may_inherit`.
793    fn mark_children_cannot_inherit(&self) {
794        self.children_may_inherit
795            .store(false, std::sync::atomic::Ordering::Relaxed);
796    }
797
798    /// Which filesystem side this directory lives on (for congestion gating).
799    #[must_use]
800    pub fn side(&self) -> congestion::Side {
801        self.side
802    }
803
804    /// Open `path` as a directory fd.
805    ///
806    /// The final component is always opened with `O_NOFOLLOW`. If `dereference`
807    /// is `false` and the final component is a symlink, the call fails with
808    /// `ELOOP`. If `dereference` is `true` and the final component is a symlink,
809    /// the call is retried without `O_NOFOLLOW` so the symlink is followed.
810    ///
811    /// The parent prefix is resolved normally (it is trusted) — unless strict
812    /// operand resolution is armed (`--require-toctou-safe`), in which case the
813    /// whole path is resolved `RESOLVE_NO_SYMLINKS` and a symlink in ANY
814    /// component fails closed with `ELOOP`.
815    pub async fn open_root_dir(
816        path: &Path,
817        dereference: bool,
818        side: congestion::Side,
819    ) -> std::io::Result<Dir> {
820        let path = path.to_owned();
821        // run the blocking openat inside spawn_blocking, gated by the congestion
822        // controller, matching the per-metadata-syscall pattern used across the crate.
823        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
824            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
825            let mode = Mode::empty();
826            #[cfg(target_os = "linux")]
827            {
828                if strict_operand_resolution() {
829                    // --require-toctou-safe: `-L` is refused by the linter before strict
830                    // mode can arm, so a dereference request here is an internal
831                    // inconsistency; fail closed rather than follow a symlink.
832                    if dereference {
833                        return Err(std::io::Error::new(
834                            std::io::ErrorKind::InvalidInput,
835                            "--dereference cannot be combined with strict operand resolution",
836                        ));
837                    }
838                    return openat2_no_symlinks(&path, flags)
839                        .map(|fd| Dir::opened(fd, side))
840                        .map_err(nix_to_io);
841                }
842            }
843            match openat(AT_FDCWD, &path, flags, mode) {
844                Ok(fd) => Ok(Dir::opened(fd, side)),
845                Err(nix::errno::Errno::ELOOP) if dereference => {
846                    // final component is a symlink; follow it only when dereference=true
847                    let follow_flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
848                    openat(AT_FDCWD, &path, follow_flags, mode)
849                        .map(|fd| Dir::opened(fd, side))
850                        .map_err(nix_to_io)
851                }
852                Err(e) => Err(nix_to_io(e)),
853            }
854        })
855        .await
856    }
857
858    /// Open a TRUSTED command-line parent-prefix directory, resolving symlinks
859    /// normally (the final component IS followed if it is a symlink).
860    ///
861    /// The trusted-boundary model (docs/tocttou.md, "Trusted boundary") trusts the directory named on
862    /// the command line up to and including itself; only entries strictly BELOW
863    /// it are hardened with `O_NOFOLLOW`. The parent prefix that CONTAINS the
864    /// operand is therefore resolved like a normal path open — a symlinked parent
865    /// (e.g. `rcp file symlink_to_dir/out`, where `symlink_to_dir` is a symlink to
866    /// a real directory) must be followed into the real directory, not rejected
867    /// with `ELOOP`/`ENOTDIR`.
868    ///
869    /// This differs from [`Self::open_root_dir`], which `O_NOFOLLOW`s the final
870    /// component (the named operand itself) and only follows it when
871    /// `dereference` is set. Use `open_parent_dir` for the operand's CONTAINER
872    /// directory; use `open_root_dir` for the operand entry. Every descendant
873    /// `openat` during the walk still uses `O_NOFOLLOW`, so the hardening below
874    /// the named root is unaffected.
875    ///
876    /// Returns a [`TrustedDir`], the only retained/exposed symlink-following transition used by
877    /// ordinary callers. The private dry-run preview parent opener follows the trusted prefix
878    /// internally before beginning its nofollow descent. Crossing into the hardened tree below the
879    /// named root is the explicit [`TrustedDir::into_tree`] step.
880    ///
881    /// Under strict operand resolution (`--require-toctou-safe`) the prefix must
882    /// already be symlink-free: it is resolved `RESOLVE_NO_SYMLINKS`, and a
883    /// symlink in any component fails closed with `ELOOP` instead of being
884    /// followed. Pass fully-resolved operands (`realpath` output) in that mode.
885    pub async fn open_parent_dir(
886        path: &Path,
887        side: congestion::Side,
888    ) -> std::io::Result<TrustedDir> {
889        let path = path.to_owned();
890        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
891            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
892            #[cfg(target_os = "linux")]
893            {
894                if strict_operand_resolution() {
895                    return openat2_no_symlinks(&path, flags)
896                        .map(|fd| TrustedDir(Dir::opened(fd, side)))
897                        .map_err(nix_to_io);
898                }
899            }
900            // a normal directory open: the kernel resolves the whole path following
901            // symlinks, including the final (trusted parent) component. No O_NOFOLLOW.
902            openat(AT_FDCWD, &path, flags, Mode::empty())
903                .map(|fd| TrustedDir(Dir::opened(fd, side)))
904                .map_err(nix_to_io)
905        })
906        .await
907    }
908
909    /// Open a child directory entry by name, refusing to follow symlinks.
910    ///
911    /// Fails with `ELOOP` if `name` refers to a symlink, or `ENOTDIR` if it
912    /// refers to a non-directory entry. The returned `Dir` carries the same
913    /// congestion side as `self`.
914    pub async fn open_dir(&self, name: &OsStr) -> std::io::Result<Dir> {
915        self.open_dir_with_credit(name, None, Ok).await
916    }
917
918    /// Open a child and read its held metadata in the same blocking job.
919    ///
920    /// The snapshot describes the returned directory even if its name is replaced. Later metadata
921    /// changes remain observable through [`Self::meta`]. Ordinary opens do not pay for this stat.
922    pub(crate) async fn open_dir_with_meta(
923        &self,
924        name: &OsStr,
925    ) -> std::io::Result<(Dir, FileMeta)> {
926        self.open_dir_with_credit(name, None, Self::with_metadata_snapshot)
927            .await
928    }
929
930    /// Open a child directory while retaining its caller's shared descriptor credit.
931    ///
932    /// The credit moves into blocking work before opening and remains owned by the returned
933    /// directory, its independent cursors, and any fd-owning jobs that outlive cancellation.
934    pub async fn open_dir_admitted(
935        &self,
936        name: &OsStr,
937        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
938    ) -> std::io::Result<Dir> {
939        self.open_dir_with_credit(name, Some(credit), Ok).await
940    }
941
942    async fn open_dir_with_credit<T, F>(
943        &self,
944        name: &OsStr,
945        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
946        finish: F,
947    ) -> std::io::Result<T>
948    where
949        T: Send + 'static,
950        F: FnOnce(Dir) -> std::io::Result<T> + Send + 'static,
951    {
952        // `O_NOFOLLOW`/`O_PATH` only guard the final path component, so a `name`
953        // containing `/` could let openat traverse an intermediate symlink. Reject
954        // multi-component names at runtime (debug_assert is compiled out in release).
955        if !is_single_component(name) {
956            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
957        }
958        // clone the Arc (refcount bump, no syscall) and move it into the blocking
959        // closure so the open file description stays alive for the closure's full
960        // duration even if this Dir is dropped after the closure starts (started
961        // spawn_blocking work is not cancellable). see the Dir doc comment.
962        let dir = self.fd.clone();
963        let side = self.side;
964        let name = name.to_owned();
965        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
966            let flags = OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
967            let fd =
968                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
969            let opened = Dir::opened_with_credit(fd, side, credit);
970            #[cfg(test)]
971            let _visit = resource_tests::gate_opened_descriptor(opened.fd.as_raw_fd())?;
972            finish(opened)
973        })
974        .await
975    }
976
977    fn with_metadata_snapshot(mut self) -> std::io::Result<(Dir, FileMeta)> {
978        let meta = snapshot_directory_meta(self.fd.as_fd())?;
979        self.captured_identity = Some((meta.dev(), meta.ino()));
980        Ok((self, meta))
981    }
982
983    /// Open a child regular file for reading, refusing to follow symlinks and never
984    /// blocking on a FIFO. Returns the open file plus its metadata snapshot.
985    ///
986    /// `O_NONBLOCK` is included so that if an attacker races the directory entry to
987    /// a FIFO between `getdents` and this `open`, the open returns immediately
988    /// (`O_RDONLY|O_NONBLOCK` on a FIFO never blocks on Linux) rather than blocking
989    /// forever waiting for a writer. `O_NOFOLLOW` prevents symlink following but
990    /// does not catch FIFOs (they are not symlinks); the subsequent `fstat` +
991    /// `S_ISREG` check rejects any non-regular file (FIFO, device, directory) with
992    /// `EINVAL`. `O_NONBLOCK` persists on the returned `File`, which is harmless for
993    /// regular-file I/O on a local fs.
994    ///
995    /// Fails with `EINVAL` if `name` is not a single path component, `ELOOP` if
996    /// `name` is a symlink, or `EINVAL` (after open, via the `fstat`+`S_ISREG`
997    /// check) if the entry is any non-regular type such as a FIFO, device, or
998    /// directory.
999    ///
1000    /// This is the canonical regular-file payload+metadata read: the returned `FileMeta` (not the
1001    /// classify [`Handle`]'s metadata) is what callers must apply/send, so bytes and metadata come
1002    /// from the same fd (read-side fidelity, see docs/tocttou.md).
1003    pub async fn open_file_read(&self, name: &OsStr) -> std::io::Result<(std::fs::File, FileMeta)> {
1004        if !is_single_component(name) {
1005            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1006        }
1007        let dir = self.fd.clone();
1008        let side = self.side;
1009        let name = name.to_owned();
1010        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1011            let flags = OFlag::O_RDONLY | OFlag::O_NOFOLLOW | OFlag::O_NONBLOCK | OFlag::O_CLOEXEC;
1012            let fd =
1013                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
1014            // fstat the open fd to confirm the entry is a regular file; this is the
1015            // safety check — O_NOFOLLOW does not catch FIFOs or other special files.
1016            let st = fstat(&fd).map_err(nix_to_io)?;
1017            if kind_from_stat(&st) != EntryKind::File {
1018                // fd is dropped here, closing it
1019                return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1020            }
1021            let meta = FileMeta::from_stat(&st);
1022            let file = std::fs::File::from(fd);
1023            Ok((file, meta))
1024        })
1025        .await
1026    }
1027
1028    /// `fstat` this directory's own held fd, returning its metadata snapshot.
1029    ///
1030    /// Lets a caller apply/send metadata from the held directory whose `read_entries` produced
1031    /// its contents (read-side fidelity, see docs/tocttou.md). A nonseekable listing reopens the
1032    /// held fd's directory inode. A separately opened classify [`Handle`] could instead refer to
1033    /// an inode swapped out before enumeration.
1034    /// Gated as `Stat`.
1035    pub async fn meta(&self) -> std::io::Result<FileMeta> {
1036        let dir = self.fd.clone();
1037        let side = self.side;
1038        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1039            let st = fstat(dir.as_fd()).map_err(nix_to_io)?;
1040            Ok(FileMeta::from_stat(&st))
1041        })
1042        .await
1043    }
1044
1045    /// Read this directory's own access and default POSIX ACLs from its held fd.
1046    ///
1047    /// The directory counterpart of [`Self::meta`], and paired with it for the same reason: the
1048    /// ACLs a caller applies to the destination come from the held directory inode whose
1049    /// `read_entries` produced the contents being copied, including when a nonseekable listing
1050    /// reopens that fd's directory inode. Callers gate this on `d:acl` — see [`read_acls_fd`] for
1051    /// what the probe costs.
1052    pub async fn read_acls(&self) -> std::io::Result<Acls> {
1053        #[cfg(test)]
1054        let _visit = resource_tests::gate_directory_acl(self.fd.as_raw_fd())?;
1055        read_acls_owned(self.fd.clone(), self.side, true)
1056            .await
1057            .map(|(_, acls)| acls)
1058    }
1059
1060    /// Read a child's current kind without opening it or following symlinks.
1061    ///
1062    /// This is a snapshot through the held parent, not a handle binding a later action to the
1063    /// entry. In particular, a missing name may appear immediately after this lookup.
1064    pub(crate) async fn child_kind(&self, name: &OsStr) -> std::io::Result<EntryKind> {
1065        if !is_single_component(name) {
1066            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1067        }
1068        let dir = self.fd.clone();
1069        let side = self.side;
1070        let name = name.to_owned();
1071        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1072            let st = fstatat(dir.as_fd(), name.as_bytes(), AtFlags::AT_SYMLINK_NOFOLLOW)
1073                .map_err(nix_to_io)?;
1074            Ok(kind_from_stat(&st))
1075        })
1076        .await
1077    }
1078
1079    /// Open a child entry by name, classifying it without following symlinks.
1080    ///
1081    /// Uses `O_PATH|O_NOFOLLOW`, which yields a valid fd even for symlinks. The
1082    /// stat is then obtained via `fstatat` with `AT_EMPTY_PATH` on the resulting
1083    /// fd so the classification is always consistent with the opened entry.
1084    pub async fn child(&self, name: &OsStr) -> std::io::Result<Handle> {
1085        // see open_dir: `O_NOFOLLOW`/`O_PATH` only guard the final component, so a
1086        // `name` containing `/` could traverse an intermediate symlink. Reject
1087        // multi-component names at runtime (debug_assert is compiled out in release).
1088        if !is_single_component(name) {
1089            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1090        }
1091        // clone the Arc (refcount bump, no syscall) and move it into the blocking
1092        // closure so the open file description stays alive for the closure's full
1093        // duration even if this Dir is dropped after the closure starts (started
1094        // spawn_blocking work is not cancellable). see the Dir doc comment.
1095        let dir = self.fd.clone();
1096        let side = self.side;
1097        let name = name.to_owned();
1098        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1099            let flags = OFlag::O_PATH | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
1100            let fd =
1101                openat(dir.as_fd(), name.as_bytes(), flags, Mode::empty()).map_err(nix_to_io)?;
1102            // stat the fd itself (empty path + AT_EMPTY_PATH): works for symlinks too
1103            let st = fstatat(&fd, "", AtFlags::AT_EMPTY_PATH).map_err(nix_to_io)?;
1104            let kind = kind_from_stat(&st);
1105            let dev = st.st_dev;
1106            let ino = st.st_ino;
1107            let meta = FileMeta::from_stat(&st);
1108            #[cfg(test)]
1109            let _gate = resource_tests::gate_classified_entry(fd.as_raw_fd())?;
1110            Ok(Handle {
1111                fd,
1112                kind,
1113                dev,
1114                ino,
1115                meta,
1116            })
1117        })
1118        .await
1119    }
1120
1121    /// Confirm this directory's own held fd still refers to the same inode as
1122    /// `handle` (same `dev` + `ino`), returning `ESTALE` on mismatch.
1123    ///
1124    /// This compares the identity captured when this exact held directory was opened, or samples
1125    /// it through [`Self::meta`] when no identity was captured, against a classification [`Handle`].
1126    /// It closes the classify-to-`open_dir` window in the
1127    /// reused-destination-directory lockdown: `open_dir` re-resolves the name, so a concurrent
1128    /// rename could substitute a different directory between classification and the open.
1129    /// Comparing the opened fd's identity to the pinned classification handle catches that swap.
1130    /// The handle keeps the classified inode number from being recycled during the comparison.
1131    pub async fn verify_same_inode(&self, handle: &Handle) -> std::io::Result<()> {
1132        let identity = self.identity().await?;
1133        if identity == (handle.dev(), handle.ino()) {
1134            Ok(())
1135        } else {
1136            Err(std::io::Error::from_raw_os_error(libc::ESTALE))
1137        }
1138    }
1139
1140    /// Reuse immutable identity captured from this fd, or read it when none was captured.
1141    pub(crate) async fn identity(&self) -> std::io::Result<(u64, u64)> {
1142        Ok(match self.captured_identity {
1143            Some(identity) => identity,
1144            None => {
1145                let meta = self.meta().await?;
1146                (meta.dev(), meta.ino())
1147            }
1148        })
1149    }
1150
1151    /// Take uid ownership of this directory as the copier and restrict it to `mode`,
1152    /// atomically and verified. Used by the reused-destination-directory lockdown under
1153    /// [`strict_operand_resolution`]: taking ownership first means the directory's PRIOR
1154    /// owner can no longer `chmod` it back open while children are written.
1155    ///
1156    /// The sequence — inside ONE `spawn_blocking` closure (which runs to completion once it
1157    /// starts) — is ordered so that **every failure exit leaves the directory no wider than a
1158    /// successful copy would**:
1159    ///
1160    /// 1. `fchown` the owner to the effective uid (lock the prior owner out). Failing here
1161    ///    leaves the directory untouched — transparent, fail-safe.
1162    /// 2. `fchmod` to a plain `0o700` IMMEDIATELY. From here on any failure leaves the
1163    ///    directory owner-only, i.e. no wider than success. If this `fchmod` fails, roll the
1164    ///    ownership back to `orig_uid` and CHECK the rollback: a clean rollback fully restores
1165    ///    the pre-lockdown state (the failed `chmod` changed nothing); a rollback that ALSO
1166    ///    fails is a genuinely stuck state (a read-only/failing backend) reported with both
1167    ///    errnos — the caller fails closed, so no child is ever written there.
1168    /// 3. Reset the gid to `orig_gid` **only if it differs** (a prior owner raced a `chgrp`
1169    ///    between classification and step 1). This matters for a **setgid** directory:
1170    ///    children inherit the directory's gid, and finalization cannot repair children
1171    ///    already created. Writing only-when-different keeps the common case a no-op — never
1172    ///    an EPERM for a non-root copier that owns the directory but is not in its group — and
1173    ///    a difference implies a foreign-owned directory, so the copier took ownership in step
1174    ///    1 as root and can set any gid.
1175    /// 4. Re-add the setgid bit (`fchmod` to `mode`) when wanted, now that the gid is
1176    ///    `orig_gid`. Doing this AFTER the gid reset stops a non-privileged copier's `chmod`
1177    ///    from silently dropping `S_ISGID`.
1178    /// 5. Final `fstat` verifies the directory is owned by the effective uid, carries gid
1179    ///    `orig_gid`, and carries exactly `mode`. A filesystem that reports a successful
1180    ///    `chown`/`chmod` without honoring it (e.g. CIFS without unix extensions), or a
1181    ///    dropped `S_ISGID`, is caught here rather than descending into a still-exposed
1182    ///    directory. A verify failure still leaves the directory at the restrictive interim
1183    ///    mode from step 2/4.
1184    ///
1185    /// `orig_uid`/`orig_gid` are the owner/group captured at classification. Fails (typically
1186    /// `EPERM`) when the copier neither owns the directory nor is privileged — caller fails closed.
1187    pub async fn secure_as_copier(
1188        &self,
1189        mode: u32,
1190        orig_uid: u32,
1191        orig_gid: u32,
1192    ) -> std::io::Result<()> {
1193        self.secure_as_copier_with(mode, orig_uid, orig_gid, || {})
1194            .await
1195    }
1196
1197    async fn secure_as_copier_with(
1198        &self,
1199        mode: u32,
1200        orig_uid: u32,
1201        orig_gid: u32,
1202        on_mutation: impl FnOnce() + Send + 'static,
1203    ) -> std::io::Result<()> {
1204        let fd = self.fd.clone();
1205        let euid = nix::unistd::geteuid().as_raw();
1206        run_metadata_probed_blocking(self.side, congestion::MetadataOp::Chmod, move || {
1207            let raw = fd.as_fd();
1208            #[cfg(test)]
1209            let _gate = resource_tests::gate_directory_lockdown(raw.as_raw_fd())?;
1210            // Take uid ownership — this locks the prior owner out of any further chown/chmod. If it
1211            // fails the directory is left untouched (transparent), which is fail-safe.
1212            fchown(raw, Some(Uid::from_raw(euid)), None).map_err(nix_to_io)?;
1213            // the closure owns tentative admission through queued/started work. Only a successful
1214            // mutation makes history permanent, including if the async waiter was cancelled.
1215            on_mutation();
1216            // Restrict to owner-only IMMEDIATELY, so EVERY later failure leaves the directory no wider
1217            // than a successful copy would. Drop to a plain 0o700 first — there is no special bit to
1218            // lose yet; the setgid bit (if wanted) is re-added below, once the gid is correct. If the
1219            // chmod fails, roll the ownership back AND CHECK the rollback, so we never silently leave
1220            // the directory copier-owned at its original (possibly permissive) mode.
1221            if let Err(chmod_err) = fchmod(raw, Mode::from_bits_truncate(0o700)).map_err(nix_to_io)
1222            {
1223                // roll the ownership back AND VERIFY it landed with an fstat: a non-honoring backend
1224                // can report a false chown success, so we must never claim a restore that did not
1225                // happen.
1226                match fchown(raw, Some(Uid::from_raw(orig_uid)), None)
1227                    .map_err(nix_to_io)
1228                    .and_then(|()| fstat(raw).map_err(nix_to_io))
1229                {
1230                    // rollback landed: back to the prior owner at its original mode (the failed chmod
1231                    // changed nothing). Report the chmod cause.
1232                    Ok(st) if st.st_uid == orig_uid => return Err(chmod_err),
1233                    // rollback reported success but did not take effect (non-honoring backend).
1234                    Ok(st) => {
1235                        return Err(std::io::Error::new(
1236                            std::io::ErrorKind::PermissionDenied,
1237                            format!(
1238                                "reused-directory lockdown could not restrict the directory (chmod: \
1239                                 {chmod_err}); the ownership rollback did not take effect (directory \
1240                                 shows uid={}, expected {orig_uid}) — it is left copier-owned at its \
1241                                 original mode, refusing to descend (the filesystem may not honor \
1242                                 chown/chmod)",
1243                                st.st_uid,
1244                            ),
1245                        ));
1246                    }
1247                    Err(rb) => {
1248                        return Err(std::io::Error::new(
1249                            std::io::ErrorKind::PermissionDenied,
1250                            format!(
1251                                "reused-directory lockdown could not restrict the directory (chmod: \
1252                                 {chmod_err}) and could not roll ownership back (chown/stat: {rb}); \
1253                                 it is left owned by the copier at its original mode — refusing to \
1254                                 descend (the destination filesystem may be read-only or failing)"
1255                            ),
1256                        ));
1257                    }
1258                }
1259            }
1260            // VERIFY the takeover landed NOW — uid == copier and mode == exactly 0o700 — BEFORE the
1261            // fallible gid/setgid steps below run on a possibly-unverified directory. A backend that
1262            // reports a false chown/chmod success (e.g. CIFS without unix extensions) is thus caught
1263            // here rather than after more operations, and the directory is never descended into while
1264            // it might still be permissive.
1265            let st = fstat(raw).map_err(nix_to_io)?;
1266            if st.st_uid != euid || (st.st_mode & 0o7777) != 0o700 {
1267                return Err(std::io::Error::new(
1268                    std::io::ErrorKind::PermissionDenied,
1269                    format!(
1270                        "reused-directory lockdown could not be verified: after chown+chmod the \
1271                         directory shows uid={} mode={:#o} (expected uid={} mode={:#o}); the \
1272                         filesystem may not honor chown/chmod (e.g. CIFS without unix extensions) — \
1273                         refusing to descend",
1274                        st.st_uid,
1275                        st.st_mode & 0o7777,
1276                        euid,
1277                        0o700,
1278                    ),
1279                ));
1280            }
1281            // The directory is now VERIFIED copier-owned at 0o700 (restrictive); every exit below
1282            // leaves it at least that restrictive. Reset the gid if a prior owner raced a `chgrp`
1283            // before the take — only when it differs, so the unchanged common case issues no gid write
1284            // (never an EPERM for a non-root copier that owns the directory but is not in its group).
1285            // A setgid directory's children must inherit the captured gid, not the raced one.
1286            if st.st_gid != orig_gid {
1287                fchown(raw, None, Some(Gid::from_raw(orig_gid))).map_err(nix_to_io)?;
1288            }
1289            // Re-add the setgid bit now that the gid is orig_gid (skipped when the interim mode is a
1290            // plain 0o700). Doing this AFTER the gid reset means a non-privileged copier's chmod
1291            // cannot silently drop S_ISGID — the kernel keeps it because the directory's gid is now
1292            // one the copier is in (or the copier is root, with CAP_FSETID).
1293            if mode != 0o700 {
1294                fchmod(raw, Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
1295            }
1296            // verify the whole takeover actually landed (uid, gid, mode); fail closed otherwise.
1297            let st = fstat(raw).map_err(nix_to_io)?;
1298            if st.st_uid != euid || st.st_gid != orig_gid || (st.st_mode & 0o7777) != mode {
1299                return Err(std::io::Error::new(
1300                    std::io::ErrorKind::PermissionDenied,
1301                    format!(
1302                        "reused-directory lockdown could not be verified: after takeover the \
1303                         directory shows uid={} gid={} mode={:#o} (expected uid={} gid={} \
1304                         mode={:#o}); the filesystem may not honor chown/chmod (e.g. CIFS without \
1305                         unix extensions), or the copier is not in the directory's group and lacks \
1306                         CAP_FSETID to keep setgid — refusing to descend",
1307                        st.st_uid,
1308                        st.st_gid,
1309                        st.st_mode & 0o7777,
1310                        euid,
1311                        orig_gid,
1312                        mode,
1313                    ),
1314                ));
1315            }
1316            Ok(())
1317        })
1318        .await
1319    }
1320
1321    /// Create a child directory and return an open `Dir` handle to it (same side as self).
1322    ///
1323    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST` if
1324    /// a directory (or any other entry) at `name` already exists.
1325    ///
1326    /// The `mkdirat`, the re-open, and (under strict operand resolution) the inherited-ACL strip
1327    /// all run inside ONE blocking closure, gated once as `MkDir`. That is a cancellation-safety
1328    /// requirement, not packaging: a queued job can be reclaimed before doing anything, while a
1329    /// closure that takes it runs every step to completion, so there is NO await point at which the
1330    /// directory exists but its sanitization has not happened. Splitting the steps across separate
1331    /// gated calls (as an earlier version did) leaves windows a `--fail-early` sibling abort can
1332    /// land in, abandoning an rcp-created directory that still carries the destination's inherited
1333    /// default ACL — inert at that moment (created owner-only, `ACL_MASK` empty), but poisoning the
1334    /// containment invariant for anything created under it later, including a rerun that cannot
1335    /// tell such an orphan from a user's own directory. For the same reason, a directory whose open
1336    /// or strip FAILS is removed (best-effort; it is empty and just created) inside the same closure
1337    /// rather than left behind unsanitized.
1338    ///
1339    /// # Inherited ACLs, and why the strip lives here
1340    ///
1341    /// A directory created under a parent that carries a DEFAULT ACL inherits both an access and a
1342    /// default ACL from it, and its own children then inherit in turn — so a destination tree's
1343    /// inheritance policy reaches straight through the directories rcp creates itself. Under
1344    /// [`strict_operand_resolution`] (`--require-toctou-safe`) that is contained by removing both
1345    /// ACLs from the new directory, which stops the chain for the directory's ENTIRE subtree:
1346    /// nothing created inside a stripped directory inherits anything. This is the containment half
1347    /// of the `--require-toctou-safe` invariant — *no destination entry that rcp CREATES carries an
1348    /// ACL entry that did not come from its source* — and stripping per DIRECTORY is what makes it
1349    /// 2 syscalls per directory and none per file created beneath one ([`Self::create_file`] pays
1350    /// its own single strip only in a parent rcp did NOT sanitize — the ambient parent of a direct
1351    /// file operand; see `children_may_inherit`).
1352    ///
1353    /// The strip belongs HERE rather than at each caller because this is the only `mkdirat` in the
1354    /// crate, and therefore the single creation site for both the local (`copy`/`link`) and remote
1355    /// (`rcpd`) destinations — a caller-side strip is one forgotten exit path away from leaving the
1356    /// hole open. The default path is untouched: it pays nothing, which is the whole point of making
1357    /// containment a strict-mode concern.
1358    ///
1359    /// `ENODATA` and `EOPNOTSUPP` are success for the strip (see `apply_one_acl`) — a directory
1360    /// with no inherited ACL, or on a filesystem that cannot hold one, already satisfies the
1361    /// post-condition. Any other errno fails the create (after the best-effort removal above), and
1362    /// the caller must fail closed rather than descend: an un-strippable default ACL is one every
1363    /// child written afterwards would inherit.
1364    ///
1365    /// **A consequence, deliberately taken.** Under `--require-toctou-safe` WITHOUT `d:acl` a fresh
1366    /// destination directory ends with NO ACL, even where the parent's default ACL would ordinarily
1367    /// have given it one. An administrator who set a default ACL on a destination tree expecting new
1368    /// subdirectories to inherit it does not get that under this flag. The flag's contract is that
1369    /// the destination reflects its source and nothing else, so containment beats inheritance;
1370    /// `d:acl` is the escape for a caller who wants the SOURCE's ACLs instead of none, and a caller
1371    /// who wants the destination tree's inheritance policy honored should not be using this flag on
1372    /// that tree.
1373    pub async fn make_dir(&self, name: &OsStr, mode: u32) -> std::io::Result<Dir> {
1374        self.make_dir_with_credit(name, mode, None, |_| Ok(()))
1375            .await
1376    }
1377
1378    /// Create a child and check its held metadata in the same blocking job.
1379    ///
1380    /// The check runs before strict-mode ACL sanitation. A metadata or check failure triggers the
1381    /// same best-effort empty-directory cleanup as an open or ACL failure. Existing creation APIs
1382    /// perform no extra metadata read.
1383    pub(crate) async fn make_dir_checked(
1384        &self,
1385        name: &OsStr,
1386        mode: u32,
1387        check: impl FnOnce(&FileMeta) -> std::io::Result<()> + Send + 'static,
1388    ) -> std::io::Result<Dir> {
1389        self.make_dir_with_credit(name, mode, None, move |dir| {
1390            let meta = snapshot_directory_meta(dir.fd.as_fd())?;
1391            dir.captured_identity = Some((meta.dev(), meta.ino()));
1392            check(&meta)
1393        })
1394        .await
1395    }
1396
1397    /// Create a child while retaining its descriptor lifetime guard through blocking work.
1398    pub async fn make_dir_admitted(
1399        &self,
1400        name: &OsStr,
1401        mode: u32,
1402        credit: Arc<dyn std::fmt::Debug + Send + Sync>,
1403    ) -> std::io::Result<Dir> {
1404        self.make_dir_with_credit(name, mode, Some(credit), |_| Ok(()))
1405            .await
1406    }
1407
1408    async fn make_dir_with_credit(
1409        &self,
1410        name: &OsStr,
1411        mode: u32,
1412        credit: Option<Arc<dyn std::fmt::Debug + Send + Sync>>,
1413        check: impl FnOnce(&mut Dir) -> std::io::Result<()> + Send + 'static,
1414    ) -> std::io::Result<Dir> {
1415        if !is_single_component(name) {
1416            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1417        }
1418        let dir = self.fd.clone();
1419        let side = self.side;
1420        let name_owned = name.to_owned();
1421        let strict = strict_operand_resolution();
1422        run_metadata_probed_blocking(side, congestion::MetadataOp::MkDir, move || {
1423            mkdirat(
1424                dir.as_fd(),
1425                name_owned.as_bytes(),
1426                Mode::from_bits_truncate(mode),
1427            )
1428            .map_err(nix_to_io)?;
1429            let result = (|| {
1430                let open_flags =
1431                    OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
1432                let fd = openat(
1433                    dir.as_fd(),
1434                    name_owned.as_bytes(),
1435                    open_flags,
1436                    Mode::empty(),
1437                )
1438                .map_err(nix_to_io)?;
1439                // own the descriptor before any fallible ACL/stat action or task handoff can
1440                // outlive the awaiting caller; failure closes it before releasing its credit
1441                let mut created = Dir {
1442                    captured_identity: None,
1443                    fd: Arc::new(DirectoryDescriptor { fd, credit }),
1444                    side,
1445                    children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(!strict)),
1446                };
1447                #[cfg(test)]
1448                let _visit = resource_tests::gate_opened_descriptor(created.fd.as_raw_fd())?;
1449                check(&mut created)?;
1450                if strict {
1451                    // strip the inheritance-carrying default ACL before the access ACL
1452                    apply_one_acl(created.fd.as_raw_fd(), ACL_DEFAULT_XATTR, None)?;
1453                    apply_one_acl(created.fd.as_raw_fd(), ACL_ACCESS_XATTR, None)?;
1454                }
1455                Ok(created)
1456            })();
1457            if result.is_err() {
1458                // open, sanitation, or metadata failure: remove the slot best-effort. rmdir
1459                // cannot follow a symlink or remove a populated replacement; an earlier identity
1460                // observation would not bind this by-name removal
1461                let _ = unlinkat(dir.as_fd(), name_owned.as_bytes(), UnlinkatFlags::RemoveDir);
1462            }
1463            result
1464        })
1465        .await
1466    }
1467
1468    /// Open an independent stream over this held directory.
1469    ///
1470    /// Reopening `.` relative to the held fd creates a new open file description, so its offset is
1471    /// independent from both this `Dir` and every other cursor. On `EACCES`, reopening through
1472    /// `/proc/self/fd` avoids requiring search permission while still checking read permission.
1473    /// Both paths remain anchored to this already held directory.
1474    pub async fn entries(&self) -> std::io::Result<DirectoryCursor> {
1475        let dir = Arc::clone(&self.fd);
1476        let iterator = run_fd_admitted_blocking(move || {
1477            OwnedDirectoryStream::from_fd(dir.reopen()?, dir.credit.clone())
1478        })
1479        .await?;
1480        Ok(DirectoryCursor::new(iterator))
1481    }
1482
1483    /// Enumerate the directory's entries (excluding `.` and `..`).
1484    ///
1485    /// Returns each entry's name and its `getdents` `d_type` as a best-effort
1486    /// `EntryKind` hint (`None` for `DT_UNKNOWN` or unrecognized values). The
1487    /// hint is advisory only — callers MUST confirm type via `child`/`fstat`
1488    /// before acting (TOCTOU safety).
1489    ///
1490    /// This method acquires only the static ops rate gate (not the congestion
1491    /// probe). Directory enumeration is deliberately not probed because buffered
1492    /// `getdents` produces bimodal latency (cache hit vs. real kernel call) that
1493    /// would pollute the congestion controller's baseline — see
1494    /// `walk::next_entry_probed` for the full rationale.
1495    pub async fn read_entries(
1496        &self,
1497    ) -> std::io::Result<Vec<(std::ffi::OsString, Option<EntryKind>)>> {
1498        Ok(self
1499            .read_entries_capped(usize::MAX)
1500            .await?
1501            .expect("an unbounded listing cannot exceed usize::MAX entries"))
1502    }
1503
1504    /// Enumerate at most `cap` entries (excluding `.` and `..`), or report the directory as
1505    /// over-cap. Returns `Ok(None)` as soon as a `cap + 1`-th entry is seen, so callers that
1506    /// discard an over-cap listing do not pay for a full enumeration. Each call refreshes its
1507    /// position before reading, including after an earlier error or over-cap return.
1508    /// Calls on the same `Dir` or its clones must not overlap: seekable listings share an offset.
1509    pub async fn read_entries_capped(
1510        &self,
1511        cap: usize,
1512    ) -> std::io::Result<Option<Vec<(std::ffi::OsString, Option<EntryKind>)>>> {
1513        throttle::get_ops_token().await;
1514        let dir = self.fd.clone();
1515        run_fd_admitted_blocking(move || {
1516            // refresh the held description's offset and btrfs entry cutoff before duplicating.
1517            // this includes the first listing after creating children through the held directory.
1518            // a FUSE seek need not refresh the server's separately held backing description
1519            let fd = dir.listing_fd_with_seek(|fd| {
1520                nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
1521            })?;
1522            // this owner closes the descriptor even if fdopendir fails and never rewinds on drop
1523            let mut stream = OwnedDirectoryStream::from_fd(fd, dir.credit.clone())?;
1524            let mut entries = Vec::new();
1525            while let Some(entry) = stream.next_raw_entry()? {
1526                if entry.name == "." || entry.name == ".." {
1527                    continue;
1528                }
1529                if entries.len() >= cap {
1530                    return Ok(None);
1531                }
1532                entries.push((entry.name, entry.kind_hint));
1533            }
1534            Ok(Some(entries))
1535        })
1536        .await
1537    }
1538
1539    /// Remove a child non-directory entry by name, gated on this directory's own congestion side.
1540    ///
1541    /// For a symlink, this unlinks the link itself — never its target.
1542    ///
1543    /// Fails with `EINVAL` if `name` is not a single path component, or `EISDIR`
1544    /// if `name` refers to a directory.
1545    pub async fn unlink_at(&self, name: &OsStr) -> std::io::Result<()> {
1546        self.unlink_at_on(name, self.side).await
1547    }
1548
1549    /// Remove a non-directory child and record success in the same blocking job.
1550    ///
1551    /// The callback is not invoked on error. Once the job starts it retains the callback's owners
1552    /// through the syscall and callback, even when the awaiting future is cancelled.
1553    pub(crate) async fn unlink_at_with(
1554        &self,
1555        name: &OsStr,
1556        after_unlink: impl FnOnce() + Send + 'static,
1557    ) -> std::io::Result<()> {
1558        self.unlink_at_on_with(name, self.side, after_unlink).await
1559    }
1560
1561    /// Like [`Self::unlink_at`], but gates the `unlinkat` on an explicitly chosen congestion
1562    /// `side` rather than the directory's own side.
1563    ///
1564    /// `rm` reads its tree on the `Source` side because its `Dir` handles are source-sided, but the
1565    /// destructive `unlinkat` is bucketed on `Destination` so it competes for the same metadata cwnd
1566    /// as other destructive work. The fd-relative TOCTOU guarantee is unaffected: the syscall is
1567    /// still resolved against this directory's pinned fd.
1568    pub(crate) async fn unlink_at_on(
1569        &self,
1570        name: &OsStr,
1571        side: congestion::Side,
1572    ) -> std::io::Result<()> {
1573        self.unlink_at_on_with(name, side, || {}).await
1574    }
1575
1576    async fn unlink_at_on_with(
1577        &self,
1578        name: &OsStr,
1579        side: congestion::Side,
1580        after_unlink: impl FnOnce() + Send + 'static,
1581    ) -> std::io::Result<()> {
1582        if !is_single_component(name) {
1583            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1584        }
1585        let dir = self.fd.clone();
1586        let name = name.to_owned();
1587        run_metadata_probed_blocking(side, congestion::MetadataOp::Unlink, move || {
1588            #[cfg(test)]
1589            let _visit = tests::gate_unlink(dir.as_raw_fd(), &name)?;
1590            unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir)
1591                .map_err(nix_to_io)?;
1592            after_unlink();
1593            Ok(())
1594        })
1595        .await
1596    }
1597
1598    /// Remove a child empty directory by name, gated on this directory's own congestion side.
1599    ///
1600    /// Fails with `EINVAL` if `name` is not a single path component, `ENOTEMPTY`
1601    /// if the directory is not empty, or `ENOTDIR` if `name` is not a directory.
1602    pub async fn rmdir_at(&self, name: &OsStr) -> std::io::Result<()> {
1603        self.rmdir_at_on(name, self.side).await
1604    }
1605
1606    /// Like [`Self::rmdir_at`], but gates the `rmdir` on an explicitly chosen congestion `side`
1607    /// rather than the directory's own side. See [`Self::unlink_at_on`] for why `rm` needs this
1608    /// (`Destination`-sided removal from a `Source`-sided read walk).
1609    pub(crate) async fn rmdir_at_on(
1610        &self,
1611        name: &OsStr,
1612        side: congestion::Side,
1613    ) -> std::io::Result<()> {
1614        if !is_single_component(name) {
1615            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1616        }
1617        let dir = self.fd.clone();
1618        let name = name.to_owned();
1619        run_metadata_probed_blocking(side, congestion::MetadataOp::RmDir, move || {
1620            unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::RemoveDir).map_err(nix_to_io)
1621        })
1622        .await
1623    }
1624
1625    /// Create a symlink `name` → `target` in this directory, returning a
1626    /// fd-pinned `Handle` to the just-created link.
1627    ///
1628    /// The returned handle has `kind() == EntryKind::Symlink` and can be used to
1629    /// apply metadata to the link race-free. `target` is the link contents — it
1630    /// is an arbitrary path and is not restricted to a single component.
1631    ///
1632    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST`
1633    /// if an entry at `name` already exists.
1634    pub async fn symlink_at(&self, name: &OsStr, target: &Path) -> std::io::Result<Handle> {
1635        if !is_single_component(name) {
1636            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1637        }
1638        let dir = self.fd.clone();
1639        let side = self.side;
1640        let name = name.to_owned();
1641        let target = target.to_owned();
1642        // clone `name` so we can call self.child() after the closure consumes it
1643        let name_for_child = name.clone();
1644        run_metadata_probed_blocking(side, congestion::MetadataOp::Symlink, move || {
1645            // symlinkat(target, dirfd, name): creates `name` → `target`
1646            symlinkat(target.as_os_str().as_bytes(), dir.as_fd(), name.as_bytes())
1647                .map_err(nix_to_io)
1648        })
1649        .await?;
1650        // open the just-created link with O_PATH|O_NOFOLLOW so we get a Handle
1651        // that is pinned to the symlink inode itself (not its target).
1652        let handle = self.child(&name_for_child).await?;
1653        if handle.kind() != EntryKind::Symlink {
1654            // should never happen — we just created a symlink; if it somehow
1655            // changed underneath us, report ENOENT to signal the caller.
1656            return Err(std::io::Error::from_raw_os_error(libc::ENOENT));
1657        }
1658        Ok(handle)
1659    }
1660
1661    /// Read the target of a child symlink.
1662    ///
1663    /// Fails with `EINVAL` if `name` is not a single path component, or `EINVAL`
1664    /// (from `readlinkat`) if `name` is not a symlink.
1665    pub async fn read_link_at(&self, name: &OsStr) -> std::io::Result<std::path::PathBuf> {
1666        if !is_single_component(name) {
1667            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1668        }
1669        let dir = self.fd.clone();
1670        let side = self.side;
1671        let name = name.to_owned();
1672        run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
1673            readlinkat(dir.as_fd(), name.as_bytes())
1674                .map(std::path::PathBuf::from)
1675                .map_err(nix_to_io)
1676        })
1677        .await
1678    }
1679
1680    /// Create a hard link at `dst`/`dst_name` pointing to this directory's `name`.
1681    ///
1682    /// Uses `AtFlags::empty()` (flags=0, no `AT_SYMLINK_FOLLOW`), so if `name` is a
1683    /// symlink, the link target is the symlink inode itself — the target file
1684    /// gains no new hard link.
1685    ///
1686    /// Fails with `EINVAL` if either `name` or `dst_name` is not a single path
1687    /// component.
1688    pub async fn hard_link_at(
1689        &self,
1690        name: &OsStr,
1691        dst: &Dir,
1692        dst_name: &OsStr,
1693    ) -> std::io::Result<()> {
1694        if !is_single_component(name) {
1695            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1696        }
1697        if !is_single_component(dst_name) {
1698            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1699        }
1700        let src_dir = self.fd.clone();
1701        let dst_dir = dst.fd.clone();
1702        let side = dst.side;
1703        let name = name.to_owned();
1704        let dst_name = dst_name.to_owned();
1705        run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1706            linkat(
1707                src_dir.as_fd(),
1708                name.as_bytes(),
1709                dst_dir.as_fd(),
1710                dst_name.as_bytes(),
1711                AtFlags::empty(),
1712            )
1713            .map_err(nix_to_io)
1714        })
1715        .await
1716    }
1717
1718    /// Create a hard link at `self`/`dst_name` pointing to the EXACT inode that
1719    /// `src_handle` pins — never re-resolving the source by name.
1720    ///
1721    /// `self` is the DESTINATION directory. The source is identified solely by
1722    /// `src_handle`'s `O_PATH` file descriptor: the link is made via
1723    /// `linkat(AT_FDCWD, "/proc/self/fd/N", dst_fd, dst_name, AT_SYMLINK_FOLLOW)`,
1724    /// where `N` is the handle's fd. `AT_SYMLINK_FOLLOW` makes `linkat` follow the
1725    /// `/proc` magic symlink to the handle's pinned inode, so the new hard link
1726    /// targets that exact inode regardless of any concurrent rename / symlink swap
1727    /// of the original directory entry.
1728    ///
1729    /// # Why /proc and not the source-name `linkat` or `AT_EMPTY_PATH`
1730    ///
1731    /// `Dir::hard_link_at` re-resolves the source by `name`, which is a TOCTOU
1732    /// window: an attacker who controls the source tree can replace `name` with a
1733    /// different inode (symlink, FIFO, another file) between classification and the
1734    /// `linkat`, so the link would target the replacement. Linking the pinned fd
1735    /// closes that window. `linkat(fd, "", .., AT_EMPTY_PATH)` would also be
1736    /// inode-exact but requires `CAP_DAC_READ_SEARCH`; the `/proc/self/fd` form does
1737    /// not, mirroring `chmod_via_proc_fd`.
1738    ///
1739    /// # Behavior
1740    ///
1741    /// - Inode-exact happy path: a stable regular-file handle links exactly as the
1742    ///   by-name path did (same inode, same content).
1743    /// - Fail-closed under attack: if the pinned inode's last directory entry was
1744    ///   removed (link count 0, e.g. the attacker renamed `name` away), the kernel
1745    ///   refuses to resurrect it and `linkat` fails with `ENOENT`. It never links a
1746    ///   swapped-in replacement.
1747    /// - Directories: `linkat` refuses to hard-link a directory (`EPERM`), exactly
1748    ///   as the by-name path did. Callers must only pass a regular-file handle.
1749    ///
1750    /// # Errors
1751    ///
1752    /// `EINVAL` if `dst_name` is not a single path component; `ENOENT` if the pinned
1753    /// inode has no remaining links (fail-closed); `EEXIST` if an entry at
1754    /// `dst_name` already exists; `EPERM` if the handle refers to a directory.
1755    /// Requires `/proc` mounted (same precondition as `chmod_via_proc_fd`).
1756    pub async fn hard_link_handle_at(
1757        &self,
1758        src_handle: &Handle,
1759        dst_name: &OsStr,
1760    ) -> std::io::Result<()> {
1761        if !is_single_component(dst_name) {
1762            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1763        }
1764        // clone the source O_PATH fd into an owned fd the blocking closure can hold,
1765        // keeping the pinned inode alive for the syscall's full duration even if the
1766        // originating Handle is dropped after the closure starts. started spawn_blocking work is
1767        // not cancellable.
1768        let src_owned = src_handle.as_fd().try_clone_to_owned()?;
1769        let dst_dir = self.fd.clone();
1770        let side = self.side;
1771        let dst_name = dst_name.to_owned();
1772        run_metadata_probed_blocking(side, congestion::MetadataOp::HardLink, move || {
1773            let proc_path = format!("/proc/self/fd/{}", src_owned.as_raw_fd());
1774            // AT_SYMLINK_FOLLOW: the /proc entry is a magic symlink that must be
1775            // dereferenced to reach the pinned inode (without the flag, linkat would
1776            // try to hard-link the magic symlink itself, which is not permitted).
1777            linkat(
1778                AT_FDCWD,
1779                proc_path.as_str(),
1780                dst_dir.as_fd(),
1781                dst_name.as_bytes(),
1782                AtFlags::AT_SYMLINK_FOLLOW,
1783            )
1784            .map_err(nix_to_io)
1785        })
1786        .await
1787    }
1788
1789    /// Create a new child file, failing if it already exists and never following a symlink.
1790    ///
1791    /// The file is ALWAYS created at [`DST_FILE_CREATE_MODE`] — there is deliberately no mode
1792    /// parameter, so a caller cannot publish a destination file at its final (possibly setuid)
1793    /// mode before its contents exist. [`set_file_metadata_owned`] widens it to the source mode after
1794    /// the last byte. Returns the open writable `File` on success; the returned fd is writable
1795    /// whatever the mode says, having been opened `O_WRONLY` at creation.
1796    ///
1797    /// `O_EXCL` is the primary guard: combined with `O_CREAT`, it fails with
1798    /// `EEXIST` on any pre-existing entry — including a symlink — without
1799    /// following it. `O_NOFOLLOW` is the fallback that would still refuse to
1800    /// follow a symlink (with `ELOOP`) should `O_EXCL` ever be bypassed.
1801    ///
1802    /// # The ambient-parent ACL strip
1803    ///
1804    /// Under [`strict_operand_resolution`] a file created in a parent rcp did NOT sanitize — the
1805    /// ambient parent of a direct file operand, the one directory kind rcp neither creates nor
1806    /// locks down (`children_may_inherit`) — has its inherited access ACL removed in the SAME
1807    /// blocking closure as the create. Without it, a parent's default ACL hands the fresh file
1808    /// named `user:`/`group:` entries; they are inert at [`DST_FILE_CREATE_MODE`] (the create mode
1809    /// leaves `ACL_MASK` empty), but the final `fchmod` to the source mode re-derives the mask
1810    /// from the group bits and ACTIVATES them — a strict copy of a plain `0640` file granting a
1811    /// named user read access its source never did. Files created beneath a sanitized directory
1812    /// pay nothing: the parent-side strip already broke the inheritance chain, which is the flag's
1813    /// whole point. A strip failure fails the create (after a best-effort unlink of the empty
1814    /// file), because the caller's later chmod would otherwise publish the inherited entries.
1815    ///
1816    /// Fails with `EINVAL` if `name` is not a single path component, or `EEXIST`
1817    /// if a file or symlink at `name` already exists.
1818    pub async fn create_file(&self, name: &OsStr) -> std::io::Result<std::fs::File> {
1819        let operation = self.file_create_operation(name, strict_operand_resolution())?;
1820        run_metadata_probed_blocking(self.side, congestion::MetadataOp::OpenCreate, operation).await
1821    }
1822
1823    /// Create a file and claim an unprobed continuation on the same blocking worker.
1824    ///
1825    /// Creation errors are passed to `continuation`, which can return any held source descriptor
1826    /// for conflict recovery. Invalid names invoke it inline without submitting blocking work.
1827    /// The outer error reports a blocking-worker failure. Cancelling before
1828    /// the continuation claim destroys its captures without running it; a claimed continuation
1829    /// retains the canonical blocking job's descriptor admission through completion and output drop.
1830    pub(crate) async fn create_file_and_then<C, T>(
1831        &self,
1832        name: &OsStr,
1833        continuation: C,
1834    ) -> std::io::Result<T>
1835    where
1836        C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
1837        T: Send + 'static,
1838    {
1839        let operation = match self.file_create_operation(name, strict_operand_resolution()) {
1840            Ok(operation) => operation,
1841            Err(error) => return Ok(continuation(Err(error))),
1842        };
1843        run_file_create_and_then(self.side, operation, continuation).await
1844    }
1845
1846    fn file_create_operation(
1847        &self,
1848        name: &OsStr,
1849        strict: bool,
1850    ) -> std::io::Result<impl FnOnce() -> std::io::Result<std::fs::File> + Send + 'static + use<>>
1851    {
1852        if !is_single_component(name) {
1853            return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
1854        }
1855        let dir = self.fd.clone();
1856        let name = name.to_owned();
1857        // the flag travels INTO the closure and is read AFTER the openat: a pre-submit snapshot
1858        // races the reused-dir rollback — a fail-early abort can restore the parent's default ACL
1859        // between this submit and the queued openat, and the file created then DOES inherit. The
1860        // rollback stores `true` before its restore syscall and this load runs after the openat;
1861        // syscalls order as full fences, so an openat that observed the restored ACL cannot then
1862        // load a stale `false`. A wasted strip on a not-yet-restored parent remains harmless.
1863        let may_inherit = Arc::clone(&self.children_may_inherit);
1864        Ok(move || {
1865            let flags = OFlag::O_CREAT
1866                | OFlag::O_EXCL
1867                | OFlag::O_WRONLY
1868                | OFlag::O_NOFOLLOW
1869                | OFlag::O_CLOEXEC;
1870            let file_mode = Mode::from_bits_truncate(DST_FILE_CREATE_MODE);
1871            let file = openat(dir.as_fd(), name.as_bytes(), flags, file_mode)
1872                .map(std::fs::File::from)
1873                .map_err(nix_to_io)?;
1874            #[cfg(test)]
1875            let _visit = tests::gate_file_create_stage(file.as_raw_fd(), "before-sanitation");
1876            if strict && may_inherit.load(std::sync::atomic::Ordering::SeqCst) {
1877                // same-closure for the same reason as `make_dir`: queued work creates nothing,
1878                // while work that starts runs to completion, so cancellation cannot abandon a
1879                // created-but-unsanitized file. cleanup is a single unlink relative to the ambient
1880                // operand parent; it never follows a symlink or removes a directory, and a prior
1881                // identity observation would not bind the by-name removal
1882                if let Err(err) = apply_one_acl(file.as_raw_fd(), ACL_ACCESS_XATTR, None) {
1883                    let _ = unlinkat(dir.as_fd(), name.as_bytes(), UnlinkatFlags::NoRemoveDir);
1884                    return Err(err);
1885                }
1886            }
1887            Ok(file)
1888        })
1889    }
1890}
1891
1892// ── TrustedDir ──────────────────────────────────────────────────────────────────
1893
1894/// A directory opened by FOLLOWING symlinks normally — the command-line-named
1895/// path's trusted parent prefix.
1896///
1897/// The trusted-boundary model (docs/tocttou.md, "Trusted boundary") trusts the path named on the
1898/// command line up to and including its container directory; only entries
1899/// strictly BELOW the named root are hardened with `O_NOFOLLOW`. A `TrustedDir`
1900/// is that trusted container, and it is the only retained/exposed follow-open transition used by
1901/// ordinary callers. The private dry-run preview parent opener follows the trusted prefix
1902/// internally before its nofollow descent. Every other ordinary directory open ([`Dir::open_dir`],
1903/// [`Dir::child`], [`Dir::open_file_read`], [`Dir::create_file`],
1904/// [`Dir::make_dir`], …) is `O_NOFOLLOW`.
1905///
1906/// Because the trusted/hardened distinction is a type rather than a convention,
1907/// the compiler enforces it: a parent-prefix slot typed `TrustedDir` can only be
1908/// filled by the follow-open, and a hardened `Dir` cannot be used where a trusted
1909/// parent is required. Crossing from the trusted prefix into the hardened tree is
1910/// the single explicit [`Self::into_tree`] step.
1911///
1912/// Under strict operand resolution (`--require-toctou-safe`) the "trusted"
1913/// prefix is additionally required to be symlink-free: the open resolves it
1914/// `RESOLVE_NO_SYMLINKS`, so a symlink component fails closed with `ELOOP`
1915/// rather than being followed (see [`enable_strict_operand_resolution`]).
1916#[derive(Debug)]
1917pub struct TrustedDir(Dir);
1918
1919impl TrustedDir {
1920    /// Cross from the trusted parent prefix into the hardened tree, consuming the `TrustedDir` and
1921    /// handing back the owned hardened `Dir` (e.g. to wrap it in an `Arc` for the walk). Every open
1922    /// below the returned `Dir` is `O_NOFOLLOW`, so nothing below the named root can be redirected
1923    /// by a symlink swap. This is the one explicit trusted→hardened transition.
1924    #[must_use]
1925    pub fn into_tree(self) -> Dir {
1926        self.0
1927    }
1928}
1929
1930// ── Operand probes and contained preview opens ───────────────────────────────
1931//
1932// dry-run preview scans resolve the trusted operand parent with the active default/strict policy,
1933// then open the named operand and every scan-relative component fd-relative without following
1934// symlinks. The strict existence/kind probes below similarly decompose an operand into parent +
1935// final component: strict mode resolves the parent through `openat2(RESOLVE_NO_SYMLINKS)` and
1936// touches only the final component fd-relative, while default-mode callers retain their existing
1937// path-based probes.
1938
1939/// Split a lexically-normal absolute operand into `(parent, final_component)` for
1940/// an fd-relative probe. Strict operands are already absolute + normal (the linter
1941/// enforced it), so a plain `parent()`/`file_name()` split is correct. Returns
1942/// `None` when the path has no distinct parent+name (e.g. `/`), where there is
1943/// nothing to probe fd-relative.
1944pub(crate) fn split_parent_and_name(path: &Path) -> Option<(&Path, &OsStr)> {
1945    let name = path.file_name()?;
1946    let parent = match path.parent() {
1947        Some(parent) if !parent.as_os_str().is_empty() => parent,
1948        // a single-component relative path means the current directory
1949        _ => Path::new("."),
1950    };
1951    Some((parent, name))
1952}
1953
1954/// Open the trusted parent of a destination operand for a contained preview scan.
1955///
1956/// `O_PATH` is load-bearing in default mode: a searchable-but-unreadable parent may contain an
1957/// operand that is itself readable, and preview containment must not add a parent read-permission
1958/// requirement. Strict mode applies the same flag through `openat2(RESOLVE_NO_SYMLINKS)`.
1959pub(crate) async fn open_preview_operand_parent(
1960    path: &Path,
1961    side: congestion::Side,
1962) -> std::io::Result<Dir> {
1963    let path = path.to_owned();
1964    run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
1965        let flags = OFlag::O_PATH | OFlag::O_DIRECTORY | OFlag::O_CLOEXEC;
1966        #[cfg(target_os = "linux")]
1967        if strict_operand_resolution() {
1968            return openat2_no_symlinks(&path, flags)
1969                .map(|fd| Dir::opened(fd, side))
1970                .map_err(nix_to_io);
1971        }
1972        openat(AT_FDCWD, &path, flags, Mode::empty())
1973            .map(|fd| Dir::opened(fd, side))
1974            .map_err(nix_to_io)
1975    })
1976    .await
1977}
1978
1979fn snapshot_directory_meta(fd: BorrowedFd<'_>) -> std::io::Result<FileMeta> {
1980    let result = (|| {
1981        #[cfg(test)]
1982        let _visit = resource_tests::gate_directory_stat(fd.as_raw_fd())?;
1983        let stat = fstat(fd).map_err(nix_to_io)?;
1984        Ok(FileMeta::from_stat(&stat))
1985    })();
1986    result.map_err(|error: std::io::Error| {
1987        std::io::Error::new(error.kind(), DirectoryStatError(error))
1988    })
1989}
1990
1991#[derive(Debug)]
1992struct DirectoryStatError(std::io::Error);
1993
1994impl std::fmt::Display for DirectoryStatError {
1995    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1996        f.write_str("cannot fstat opened directory")
1997    }
1998}
1999
2000impl std::error::Error for DirectoryStatError {
2001    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2002        Some(&self.0)
2003    }
2004}
2005
2006/// A preview's held identity, with optional enumeration authority acquired at the same open.
2007#[derive(Debug)]
2008pub(crate) struct PreviewDirectory {
2009    dir: Arc<Dir>,
2010    pub(crate) meta: FileMeta,
2011    readable: bool,
2012}
2013
2014#[derive(Clone, Debug)]
2015pub(crate) enum PreviewEntry {
2016    Directory(Arc<PreviewDirectory>),
2017    Missing,
2018    NonDirectory,
2019    Unavailable,
2020}
2021
2022impl PreviewDirectory {
2023    pub(crate) fn readable(&self) -> Option<Arc<Dir>> {
2024        self.readable.then(|| Arc::clone(&self.dir))
2025    }
2026
2027    pub(crate) async fn child(
2028        &self,
2029        name: &OsStr,
2030        readable: bool,
2031    ) -> std::io::Result<PreviewEntry> {
2032        open_preview_entry(&self.dir, name, readable).await
2033    }
2034}
2035
2036#[cfg(test)]
2037pub(crate) async fn preview_from_readable(dir: Arc<Dir>) -> std::io::Result<PreviewEntry> {
2038    let meta = dir.meta().await?;
2039    Ok(PreviewEntry::Directory(Arc::new(PreviewDirectory {
2040        dir,
2041        meta,
2042        readable: true,
2043    })))
2044}
2045
2046/// Resolve identity without read access; delete previews open readably through the same parent.
2047/// Only opening can yield unavailable evidence. A failed fstat is always an error.
2048pub(crate) async fn open_preview_entry(
2049    parent: &Dir,
2050    name: &OsStr,
2051    readable: bool,
2052) -> std::io::Result<PreviewEntry> {
2053    if !is_single_component(name) {
2054        return Err(std::io::Error::from_raw_os_error(libc::EINVAL));
2055    }
2056    let parent_fd = Arc::clone(&parent.fd);
2057    let side = parent.side;
2058    let name = name.to_owned();
2059    run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2060        let access = if readable {
2061            OFlag::O_RDONLY
2062        } else {
2063            OFlag::O_PATH
2064        };
2065        let flags = access | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC;
2066        let fd = match openat(parent_fd.as_fd(), name.as_bytes(), flags, Mode::empty()) {
2067            Ok(fd) => fd,
2068            Err(nix::errno::Errno::ENOENT) => return Ok(PreviewEntry::Missing),
2069            Err(nix::errno::Errno::ENOTDIR | nix::errno::Errno::ELOOP) => {
2070                return Ok(PreviewEntry::NonDirectory);
2071            }
2072            Err(nix::errno::Errno::EACCES) if !readable => return Ok(PreviewEntry::Unavailable),
2073            Err(error) => return Err(nix_to_io(error)),
2074        };
2075        let dir = Dir::opened_with_credit(fd, side, parent_fd.credit.clone());
2076        #[cfg(test)]
2077        let _visit = resource_tests::gate_opened_descriptor(dir.fd.as_raw_fd())?;
2078        let (dir, meta) = dir.with_metadata_snapshot()?;
2079        Ok(PreviewEntry::Directory(Arc::new(PreviewDirectory {
2080            dir: Arc::new(dir),
2081            meta,
2082            readable,
2083        })))
2084    })
2085    .await
2086}
2087
2088/// Probe an operand's existence and kind fd-relative under strict operand
2089/// resolution: open its parent with `open_parent_dir` (`RESOLVE_NO_SYMLINKS`
2090/// while armed) and classify the final component via `child` (`O_NOFOLLOW`).
2091///
2092/// - `Ok(Some(kind))` — the entry exists (a final-component symlink counts as
2093///   existing, classified `Symlink`, and is never followed, matching
2094///   `symlink_metadata`).
2095/// - `Ok(None)` — the entry, or its parent, does not exist (`ENOENT`/`ENOTDIR`).
2096/// - `Err(ELOOP)` — a directory component of the operand path is a symlink; the
2097///   caller must fail closed.
2098pub async fn strict_probe_dst_kind(
2099    path: &Path,
2100    side: congestion::Side,
2101) -> std::io::Result<Option<EntryKind>> {
2102    let Some((parent, name)) = split_parent_and_name(path) else {
2103        return Ok(None);
2104    };
2105    match Dir::open_parent_dir(parent, side).await {
2106        Ok(parent) => match parent.into_tree().child(name).await {
2107            Ok(handle) => Ok(Some(handle.kind())),
2108            Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
2109            Err(err) => Err(err),
2110        },
2111        Err(err)
2112            if err.kind() == std::io::ErrorKind::NotFound
2113                || err.raw_os_error() == Some(libc::ENOTDIR) =>
2114        {
2115            Ok(None)
2116        }
2117        Err(err) => Err(err),
2118    }
2119}
2120
2121/// What a strict-mode reused-directory lockdown changed and finalize must put back.
2122///
2123/// # This type is an RAII guard, and that is the point
2124///
2125/// The snapshotted default ACL is the ONLY copy of those bytes in existence — the lockdown removed
2126/// them from the filesystem. If this value were ever dropped without the restore running, the
2127/// destination directory would permanently lose an ACL it had before the copy: unrecoverable, and
2128/// invisible, since nothing else reports it.
2129///
2130/// There are many ways to drop it. A `--fail-early` copy returns `Err` from the walk driver without
2131/// ever reaching `dir_post`, and aborts its in-flight siblings by dropping their `JoinSet` — so one
2132/// failed leaf can end a dozen directories' lockdowns at once. A failed `read_entries` in
2133/// `link_dir_contents` also aborts under `--fail-early`; keep-going instead drains its workers and
2134/// reaches directory finalization. The remote destination can fail between locking a directory and
2135/// registering it, or shut down with directories still pending. Restoring at
2136/// each of those sites is the shape `CLAUDE.md` warns about — a missed exit path is the recurring
2137/// finding here, and there were six-plus of them.
2138///
2139/// So the restore lives in [`Drop`] instead, and holds on every exit path that drops the value: an
2140/// early return, a `?`, a `break`, and — the case the abort paths above actually need — a cancelled
2141/// task, since dropping a future drops its locals. [`set_reused_dir_metadata_fd`] disarms the guard
2142/// once the default ACL has been dealt with deliberately AND nothing after it can fail, which is
2143/// why the state is private: nothing outside this module can arm, disarm, or duplicate it. The
2144/// armed/disarmed distinction is an explicit enum (`DefaultAclGuard`) rather than the emptiness
2145/// of the snapshot, because a directory that HAD no default ACL still needs an armed rollback: a
2146/// partial finalize may have installed the source's, and only an armed guard removes it. `Clone`
2147/// is deliberately NOT derived — exactly one of these exists per lockdown, and a copy would
2148/// restore twice.
2149///
2150/// **The guard must exist before anything is destroyed, not after.** "Dropped on every exit path"
2151/// says nothing about the window in which the value does not exist. [`lockdown_reused_dir`] arms
2152/// the guard before removing the ACL synchronously, with no cancellation point in between.
2153///
2154/// # Exits it does NOT cover
2155///
2156/// A panic (the workspace builds `panic = "abort"`, so nothing unwinds and no destructor runs), a
2157/// signal, and `std::process::exit` — which, unlike the first two, is ordinary control flow in
2158/// shipped code. Every `process::exit` call site runs either before a copy starts (the TOCTOU
2159/// linter, config validation) or after `common::run` has dropped the tokio runtime, which drops every
2160/// task and therefore every guard; `rcpd`'s stdin watchdog follows the same lifetime rule. A call
2161/// that exits mid-copy would reintroduce the hole. Closing it for panic and signal would need the
2162/// snapshot on disk rather than in memory — out of proportion to the risk, but worth knowing rather
2163/// than assuming this is total.
2164///
2165/// # The `Drop` restore is best-effort recovery, not a guarantee
2166///
2167/// A destructor cannot await, so it issues a synchronous `fsetxattr` that bypasses the congestion
2168/// throttle every other metadata write here goes through, and it cannot return an error. A failure
2169/// is logged at `warn!` naming the directory — resolved from the held fd through `/proc/self/fd`,
2170/// one cheap syscall, because on a mass abort an operator otherwise gets N indistinguishable
2171/// warnings and no target — along with the ACL bytes to rebuild it from. A SUCCESSFUL restore is
2172/// logged at `debug!` so that "did the guard fire?" is observable rather than inferred. This is the
2173/// backstop for an aborted copy; the finalize path is where a successful one restores.
2174///
2175/// # What is deliberately NOT restored here
2176///
2177/// Only the default ACL. An aborted lockdown still leaves the directory owned by the copier at
2178/// `0o700` — that outcome is already documented in `docs/tocttou.md`, and unlike ACL loss it is
2179/// narrow, visible, and repairable: an operator sees the mode and fixes it. Nothing is destroyed.
2180/// The armed/disarmed state of a [`ReusedDirLock`]'s default-ACL rollback, shared (behind one
2181/// mutex) between the guard's `Drop` restore and every finalize write to the guarded attribute.
2182///
2183/// Two conflations this enum exists to prevent:
2184///
2185/// - **"Had no original ACL" is not "nothing to undo".** With `d:acl` on, finalize INSTALLS the
2186///   source's default ACL before later steps that can still fail; a directory that originally had
2187///   none must then get that installation REMOVED on rollback, or a failed copy leaves it carrying
2188///   an ACL the destination never had. A bare `Option<Vec<u8>>` cannot express that arm because its
2189///   `None` would have to mean both "no original ACL" and "disarmed".
2190/// - **A detached write must not undo the restore.** A finalize ACL write still queued when its
2191///   waiter is dropped is reclaimed before it starts, but one already taken by a blocking worker
2192///   cannot be cancelled and may land AFTER the guard's `Drop` has put the original back.
2193///   Serializing every guarded write and the restore through this one mutex, with a write that
2194///   observes [`Self::Disarmed`] SKIPPING, closes the race in both directions: a write mid-syscall
2195///   holds the mutex, so the restore waits and then lands over it (correct — the copy is
2196///   aborting); a write not yet started finds the guard disarmed and never lands.
2197#[derive(Debug)]
2198enum DefaultAclGuard {
2199    /// The lockdown is live. On abort, put the directory's default ACL back to `original`:
2200    /// `Some` bytes are restored; `None` means the directory had no default ACL, so whatever a
2201    /// partial finalize may have installed is REMOVED.
2202    Armed { original: Option<Vec<u8>> },
2203    /// Finalize resolved the default ACL deliberately (or the restore already ran). Nothing is
2204    /// left to undo, and any still-queued guarded write must NOT land.
2205    Disarmed,
2206}
2207
2208#[derive(Debug)]
2209pub struct ReusedDirLock {
2210    /// The directory's original `(uid, gid)`, taken from the classify handle before the takeover.
2211    pub restore_owner: (u32, u32),
2212    /// The rollback state plus the original default ACL, shared (`Arc`) with in-flight guarded
2213    /// writes so the `Drop` restore serializes against them — see `DefaultAclGuard`.
2214    state: Arc<std::sync::Mutex<DefaultAclGuard>>,
2215    /// The locked directory's fd, shared with the `Dir` it came from. An `Arc` rather than a `dup`:
2216    /// it costs no descriptor and no syscall, and it keeps the fd open for exactly as long as the
2217    /// guard can still need it, so `Drop` writes to the pinned inode rather than re-resolving a path
2218    /// an attacker may have swapped.
2219    fd: Arc<DirectoryDescriptor>,
2220    /// The locked `Dir`'s inherit flag, shared so the rollback can RE-ARM it (`store(true)` before
2221    /// the restore syscall): restoring the original default ACL makes inheritance possible again,
2222    /// and a file created in the window after the rollback must strip what it inherited — see
2223    /// `Dir::children_may_inherit` and `Dir::create_file`.
2224    children_may_inherit: Arc<std::sync::atomic::AtomicBool>,
2225}
2226
2227impl ReusedDirLock {
2228    /// The original default ACL the lockdown snapshotted (`None` when the directory had none).
2229    /// Peeks without disarming; a caller restores it via [`Self::write_default_acl_guarded`].
2230    fn original_default_acl(&self) -> Option<Vec<u8>> {
2231        match &*self.state.lock().unwrap() {
2232            DefaultAclGuard::Armed { original } => original.clone(),
2233            DefaultAclGuard::Disarmed => None,
2234        }
2235    }
2236
2237    /// Declare the default ACL deliberately resolved: the `Drop` restore becomes a no-op and any
2238    /// still-queued guarded write is refused. Only called once every finalize step that could
2239    /// still fail has succeeded.
2240    fn disarm(&self) {
2241        *self.state.lock().unwrap() = DefaultAclGuard::Disarmed;
2242    }
2243
2244    /// Install `blob` as the locked directory's DEFAULT ACL, serialized against the guard's
2245    /// rollback (see `DefaultAclGuard`): the state mutex is held across the syscall, and a write
2246    /// that finds the guard already disarmed is SKIPPED — landing it would silently undo a restore
2247    /// that already ran. Every finalize-path write to this attribute MUST go through here; an
2248    /// unguarded `set_or_remove_acl_fd` on the blocking pool is exactly the detached-write hazard
2249    /// the guard exists to close. Only ever needs to SET: after the lockdown the directory
2250    /// provably carries no default ACL, so "remove" cases have nothing to do.
2251    ///
2252    /// Gated as `MetadataOp::Chmod`, like every other single-inode permission write.
2253    async fn write_default_acl_guarded(
2254        &self,
2255        side: congestion::Side,
2256        blob: Vec<u8>,
2257    ) -> std::io::Result<()> {
2258        let state = Arc::clone(&self.state);
2259        let fd = Arc::clone(&self.fd);
2260        run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2261            let guard = state.lock().unwrap();
2262            match &*guard {
2263                DefaultAclGuard::Armed { .. } => {
2264                    apply_one_acl(fd.as_raw_fd(), ACL_DEFAULT_XATTR, Some(&blob))
2265                }
2266                DefaultAclGuard::Disarmed => {
2267                    // this write's owner was cancelled and the dropped guard already restored;
2268                    // landing the write now would silently overwrite that restore
2269                    tracing::debug!(
2270                        "skipped a default-ACL write that lost its race against the lockdown \
2271                         guard's restore ({} bytes)",
2272                        blob.len(),
2273                    );
2274                    Ok(())
2275                }
2276            }
2277        })
2278        .await
2279    }
2280}
2281
2282impl Drop for ReusedDirLock {
2283    fn drop(&mut self) {
2284        // re-arm the inherit flag BEFORE the restore syscall (which may run detached below): once
2285        // the original default ACL is back, a file created in this directory inherits it and must
2286        // strip — `create_file` loads the flag after its openat, so this ordering (store, then
2287        // restore; openat, then load) leaves no interleaving where the openat sees the restored
2288        // ACL but the load sees `false`
2289        self.children_may_inherit
2290            .store(true, std::sync::atomic::Ordering::SeqCst);
2291        // Taking the mutex is what serializes this restore against an in-flight guarded write: a
2292        // write mid-syscall holds it, so the restore must wait and then deliberately land OVER
2293        // it. But WAITING here would block whatever thread runs this destructor — on the
2294        // cancellation paths that is an EXECUTOR thread (`--fail-early` dropping tracker state, a
2295        // watchdog dropping the operation), and the wait is bounded only by the write's
2296        // `fsetxattr`, which on dead network storage is unbounded. So: uncontended (the ordinary
2297        // case — no write in flight) restores inline; contended detaches the SAME serialized
2298        // wait-then-restore to its own thread. The `Arc`s keep the state and fd alive for it, and
2299        // process exit may abandon the thread exactly as it abandons the stalled write itself.
2300        let state = match self.state.try_lock() {
2301            Ok(guard) => guard,
2302            Err(std::sync::TryLockError::WouldBlock) => {
2303                let state = Arc::clone(&self.state);
2304                let fd = Arc::clone(&self.fd);
2305                let flag_note = "detached (a guarded write held the rollback mutex)";
2306                std::thread::spawn(move || {
2307                    // a poisoned mutex is unreachable under panic = "abort"; fail toward doing
2308                    // the restore anyway rather than silently dropping it
2309                    let guard = state
2310                        .lock()
2311                        .unwrap_or_else(|poisoned| poisoned.into_inner());
2312                    rollback_default_acl(guard, &fd, flag_note);
2313                });
2314                return;
2315            }
2316            // unreachable under panic = "abort"; restore anyway rather than skip
2317            Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
2318        };
2319        rollback_default_acl(state, &self.fd, "inline");
2320    }
2321}
2322
2323/// The rollback itself, run with the guard's mutex HELD (see `DefaultAclGuard`): flips the state
2324/// to `Disarmed` and puts the directory's original default ACL back (or removes what a partial
2325/// finalize installed, when there was none). Split from `ReusedDirLock::drop` so the contended
2326/// path can run it on a detached thread with the same serialization.
2327fn rollback_default_acl(
2328    mut state: std::sync::MutexGuard<'_, DefaultAclGuard>,
2329    fd: &DirectoryDescriptor,
2330    how: &str,
2331) {
2332    {
2333        let DefaultAclGuard::Armed { original } =
2334            std::mem::replace(&mut *state, DefaultAclGuard::Disarmed)
2335        else {
2336            return;
2337        };
2338        let raw = fd.as_raw_fd();
2339        let _ = how;
2340        // name the directory rather than the descriptor: a mass abort restores many at once, and
2341        // "fd 47" tells an operator nothing about which tree to repair. Best-effort — a fd whose
2342        // target is gone falls back to the raw number rather than failing the restore.
2343        let path = std::fs::read_link(format!("/proc/self/fd/{raw}"))
2344            .map_or_else(|_| format!("<fd {raw}>"), |p| p.display().to_string());
2345        let restore = apply_one_acl(raw, ACL_DEFAULT_XATTR, original.as_deref());
2346        match (restore, &original) {
2347            (Ok(()), Some(blob)) => tracing::debug!(
2348                "restored the default ACL of reused destination directory {} after an aborted \
2349                 copy ({} bytes)",
2350                path,
2351                blob.len(),
2352            ),
2353            (Ok(()), None) => tracing::debug!(
2354                "ensured reused destination directory {} carries no default ACL after an aborted \
2355                 copy (it had none before it)",
2356                path,
2357            ),
2358            (Err(error), Some(blob)) => tracing::warn!(
2359                "could not restore the default ACL of reused destination directory {} after an \
2360                 aborted copy: {:#}. It is left with NO default ACL; it had {} bytes ({:02x?}), \
2361                 which must be re-applied by hand to restore what entries created beneath it \
2362                 inherit.",
2363                path,
2364                &error,
2365                blob.len(),
2366                blob,
2367            ),
2368            (Err(error), None) => tracing::warn!(
2369                "could not remove a partially-applied default ACL from reused destination \
2370                 directory {} after an aborted copy: {:#}. The directory had NO default ACL \
2371                 before the copy; whatever the aborted finalize installed remains and must be \
2372                 removed by hand.",
2373                path,
2374                &error,
2375            ),
2376        }
2377    }
2378}
2379
2380/// Lock down a REUSED destination directory under strict operand resolution, returning what finalize
2381/// must restore — `Some` when locked, `None` (a pure no-op) when strict mode is off.
2382///
2383/// `dir` is the freshly `open_dir`'d handle to the reused directory; `handle` is the `O_PATH`
2384/// classify [`Handle`] taken for the same entry BEFORE the open (still held, pinning the classified
2385/// inode). While strict operand resolution is armed the lockdown:
2386///
2387/// 1. captures `handle`'s original `(uid, gid)` as the restore owner;
2388/// 2. [`Dir::verify_same_inode`] — confirms `dir` is still that exact inode, failing closed
2389///    (`ESTALE`) on a classify→open swap;
2390/// 3. [`Dir::secure_as_copier`] — takes ownership as the copier then restricts to `0o700`, so no
2391///    child is written while the directory is world-readable/writable and the prior owner cannot
2392///    re-widen it mid-copy;
2393/// 4. [`read_acls_fd`] — snapshots the DEFAULT ACL, and
2394/// 5. removes it, so nothing created during the copy inherits it.
2395///
2396/// Steps 4 and 5 both run AFTER the takeover, and both for the same reason: only an owner (or a
2397/// `CAP_FOWNER` copier) may write these attributes, so a strip issued before step 3 would leave the
2398/// prior owner free to put the default ACL straight back, and a snapshot read before it could be
2399/// raced by that same owner. `chmod` does not touch a default ACL (verified), so nothing about the
2400/// recorded value depends on reading it first.
2401///
2402/// # Why only the DEFAULT ACL
2403///
2404/// The *access* ACL is deliberately left alone, and this is a narrowing of what an earlier version
2405/// did. It buys no containment: step 3's `chmod` rewrites `ACL_MASK` from the new group bits, so at
2406/// `0o700` the mask is `---` and every named `user:`/`group:` entry — and the owning group — grants
2407/// nothing, while `OTHER` is `---` too. Only the copier, who now owns the directory, has any access
2408/// at all (verified). And it needs no restoring, because finalize resolves it either way: with
2409/// `d:acl` the source's ACL is set or cleared over it, and without `d:acl` the finalize `chmod`
2410/// re-derives its mask from the source's mode — which is exactly what an unhardened copy's single
2411/// `chmod` does to a pre-existing ACL, so the end state is identical either way.
2412///
2413/// Leaving it alone therefore costs nothing and means an aborted copy can destroy at most the
2414/// default ACL rather than both. (A freshly CREATED directory is the opposite case and still strips
2415/// both — see [`Dir::make_dir`]: what it inherited is not its own, and with `d:acl` off nothing at
2416/// finalize would remove an inherited access ACL, so the finalize `chmod` would make it effective.)
2417///
2418/// Distinct destination paths can alias the same directory inode and create overlapping lockdowns:
2419/// one guard can restore the ACL while another copy is still active. `--require-toctou-safe`
2420/// refuses byte-equal duplicate destinations up front and serializes strict multi-source copies;
2421/// filesystem-level aliasing (casefold, bind mount) is not detected. The remote tracker rejects
2422/// duplicate directory paths but does not coordinate distinct paths by inode identity.
2423///
2424/// Everything the lockdown changed is put back at finalize by [`set_reused_dir_metadata_fd`] (the
2425/// owner component-wise, so no transient window hands the directory back to a hostile prior owner)
2426/// along with the source mode, so a successful copy leaves the directory byte-identical to a copy
2427/// without this hardening. A recheck mismatch, an `fchown`/`fchmod` `EPERM` (non-owner,
2428/// non-privileged copier), or an ACL snapshot/strip that fails propagates as `Err`; callers fail
2429/// closed and skip descent, so no child is written into an unsecured directory. Failing closed on
2430/// the snapshot is why it is read before the strip: removing an ACL we could not record would
2431/// permanently destroy the destination directory's own. This is the single lockdown used by BOTH the
2432/// local (`copy`/`link`) and remote (`rcpd`) reuse sites.
2433pub async fn lockdown_reused_dir(
2434    dir: &Dir,
2435    handle: &Handle,
2436) -> std::io::Result<Option<ReusedDirLock>> {
2437    lockdown_reused_dir_with(dir, handle, || {}).await
2438}
2439
2440/// Keep admission ownership tentative through verification and queued work, then notify after the
2441/// first successful mutation. The blocking closure owns the callback if its waiter is cancelled.
2442/// Outside strict mode no mutation occurs and the callback is dropped without being invoked.
2443pub(crate) async fn lockdown_reused_dir_with(
2444    dir: &Dir,
2445    handle: &Handle,
2446    on_mutation: impl FnOnce() + Send + 'static,
2447) -> std::io::Result<Option<ReusedDirLock>> {
2448    if !strict_operand_resolution() {
2449        return Ok(None);
2450    }
2451    use crate::preserve::Metadata as _;
2452    use std::os::unix::fs::PermissionsExt as _;
2453    let orig_meta = handle.meta();
2454    let restore_owner = (orig_meta.uid(), orig_meta.gid());
2455    dir.verify_same_inode(handle).await?;
2456    // Restrict to 0o700 (owner-only) for the copy's duration, PRESERVING the setgid bit if the reused
2457    // directory had it (0o700 already denies all group/other access, so keeping setgid costs nothing
2458    // security-wise). Unlike the source mode applied at finalize, this INTERIM setgid bit governs the
2459    // group that every child created during the copy inherits — and finalization cannot repair those
2460    // children's GIDs under `preserve_none`. So a setgid directory must be locked down with BOTH its
2461    // gid value and its S_ISGID bit intact: `secure_as_copier` (given the classified gid) resets the
2462    // gid if a prior owner raced a `chgrp`, and re-stats to fail closed if `chmod` cleared S_ISGID (a
2463    // non-privileged copier not in the directory's group, lacking `CAP_FSETID`) or if the filesystem
2464    // did not honor the takeover at all. Root has `CAP_FSETID`, keeps the bit, and never trips this.
2465    let want_setgid = orig_meta.permissions().mode() & 0o2000 != 0;
2466    let interim_mode = if want_setgid { 0o2700 } else { 0o700 };
2467    dir.secure_as_copier_with(interim_mode, orig_meta.uid(), orig_meta.gid(), on_mutation)
2468        .await?;
2469    // snapshot the default ACL, now that the directory is ours and the prior owner can no longer
2470    // race the read (step 4). Mode-neutral. `read_acls_fd` also reads the access ACL when one is
2471    // present, which is one wasted `fgetxattr` on a reused directory that has one — not worth a
2472    // second read path for. Nothing is destroyed yet, so a cancellation here loses nothing.
2473    let original = read_acls_fd(dir.fd.as_fd(), dir.side, true).await?.default;
2474    let needs_strip = original.is_some();
2475    // ARM THE GUARD BEFORE DESTROYING ANYTHING (step 5). The snapshot is the only copy of these
2476    // bytes once the removal lands, so it must already be inside a value whose `Drop` puts it back
2477    // before the removal is issued — otherwise a task cancelled between the two loses it as a bare
2478    // `Option<Vec<u8>>` with no destructor. Armed even when the directory has no default ACL: the
2479    // rollback then means "keep it that way" — removing whatever a partial finalize installs.
2480    let lock = ReusedDirLock {
2481        restore_owner,
2482        state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed { original })),
2483        fd: Arc::clone(&dir.fd),
2484        children_may_inherit: Arc::clone(&dir.children_may_inherit),
2485    };
2486    if needs_strip {
2487        let raw = dir.fd.as_raw_fd();
2488        // The removal is issued SYNCHRONOUSLY, inside the gate rather than on the blocking pool,
2489        // and this is load-bearing rather than an optimization. the shared blocking boundary can
2490        // reclaim user work before a worker takes it, but a closure cannot be stopped after that
2491        // handoff, so an `.await` on it is a cancellation point at which the `fremovexattr` may
2492        // still run — the exact hazard the arming above closes. Running it in-line means there is
2493        // no cancellation point between arming and destroying at all: polling this future runs the
2494        // syscall to completion.
2495        //
2496        // Arming first while KEEPING `spawn_blocking` would be strictly worse than either: a pool
2497        // thread's `fremovexattr` could land after this task's `Drop` restore and silently undo it.
2498        //
2499        // The cost is one `fremovexattr` (microseconds) on an async worker, the same call `Drop`
2500        // already makes, and only for a reused directory that actually has a default ACL. The gate
2501        // still applies — `run_metadata_probed` takes the ops token and cwnd permit and feeds the
2502        // latency probe exactly as `set_or_remove_acl_fd` would.
2503        crate::walk::run_metadata_probed(dir.side, congestion::MetadataOp::Chmod, async {
2504            apply_one_acl(raw, ACL_DEFAULT_XATTR, None)
2505        })
2506        .await?;
2507        // NB: on `Err` the guard is still armed and `Drop` re-writes the snapshot. `fremovexattr`
2508        // is atomic, so the ACL is either gone (the restore puts it back) or never left (the
2509        // restore is a no-op) — never a partial state.
2510    }
2511    // the directory now provably has no default ACL (either it never had one, or the strip above
2512    // succeeded), so files created in it during the copy cannot inherit — `create_file` need not
2513    // pay the ambient-parent strip here
2514    dir.mark_children_cannot_inherit();
2515    Ok(Some(lock))
2516}
2517
2518// ── POSIX ACLs ──────────────────────────────────────────────────────────────────
2519//
2520// POSIX.1e ACLs live in two extended attributes and are read and written here as
2521// OPAQUE kernel blobs: `system.posix_acl_access` (on any inode) and
2522// `system.posix_acl_default` (directories only, governing what children inherit).
2523// Using the raw xattrs rather than libacl keeps this to plain fd syscalls with no
2524// new dependency, and the on-disk format is defined little-endian, so the bytes
2525// are portable verbatim. The blobs are never interpreted: rcp carries what the
2526// source kernel produced and lets the destination kernel validate it on
2527// `fsetxattr`.
2528
2529/// The access ACL: the entry's own permissions. Present on any inode kind.
2530const ACL_ACCESS_XATTR: &CStr = c"system.posix_acl_access";
2531
2532/// The default ACL: what a directory's freshly created CHILDREN inherit. Directories only, and
2533/// mode-neutral — setting or clearing it never moves the directory's own mode.
2534const ACL_DEFAULT_XATTR: &CStr = c"system.posix_acl_default";
2535
2536/// A source entry's POSIX.1e ACLs, as opaque kernel bytes.
2537///
2538/// `None` means the source has no such ACL — which a destination applier reproduces by REMOVING
2539/// the attribute, not by leaving it alone. A destination directory's default ACL is inherited by
2540/// every child created beneath it, so "do nothing when the source has no ACL" hands the copy
2541/// permissions the source never granted. See [`apply_acls_fd`].
2542#[derive(Clone, Debug, Default, PartialEq, Eq)]
2543pub struct Acls {
2544    /// `system.posix_acl_access`.
2545    pub access: Option<Vec<u8>>,
2546    /// `system.posix_acl_default`; only ever read or applied for a directory.
2547    pub default: Option<Vec<u8>>,
2548}
2549
2550/// Read an entry's POSIX ACLs through an fd it is already open on.
2551///
2552/// `want_default` is `true` for directories only — files have no default ACL, so asking for one
2553/// would spend a syscall that can only miss.
2554///
2555/// `flistxattr` runs FIRST and an `fgetxattr` is issued only for a name actually present. There is
2556/// no bit in `stat` saying an entry has an ACL, so this probe is what ACL preservation costs per
2557/// entry, and the shape is chosen to make the common case cheap: measured on ext4, a `getxattr`
2558/// that misses costs ~1057ns against ~591ns for the whole `listxattr`, and missing is the
2559/// overwhelming majority. Each syscall is gated through the module's `run_metadata_probed_blocking`
2560/// as `MetadataOp::Stat`, like every other metadata read here — an ACL probe that bypassed the
2561/// throttle would be the one metadata operation in rcp that does.
2562///
2563/// A filesystem that cannot hold ACLs (`EOPNOTSUPP`) and an entry that simply has none (`ENODATA`)
2564/// both yield `None`: neither has an ACL to preserve.
2565pub async fn read_acls_fd(
2566    fd: BorrowedFd<'_>,
2567    side: congestion::Side,
2568    want_default: bool,
2569) -> std::io::Result<Acls> {
2570    // dup once and move the owner through the (up to three) gated syscalls. Each blocking
2571    // closure owns its descriptor until its returned output is consumed or dropped.
2572    let owned = fd.try_clone_to_owned()?;
2573    read_acls_owned(owned, side, want_default)
2574        .await
2575        .map(|(_, acls)| acls)
2576}
2577
2578/// Read ACLs without duplicating the descriptor, returning the same owner on success.
2579///
2580/// Errors and cancellation drop the owner through the existing blocking-job lifetime rules.
2581pub(crate) async fn read_acls_owned<F: AsRawFd + Send + 'static>(
2582    owned: F,
2583    side: congestion::Side,
2584    want_default: bool,
2585) -> std::io::Result<(F, Acls)> {
2586    let (owned, names) =
2587        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2588            #[cfg(test)]
2589            let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
2590            let names = flistxattr_names(owned.as_raw_fd())?;
2591            Ok((owned, names))
2592        })
2593        .await?;
2594    let (owned, access) = if names_contain(&names, ACL_ACCESS_XATTR) {
2595        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2596            let access = fgetxattr_blob(owned.as_raw_fd(), ACL_ACCESS_XATTR)?;
2597            Ok((owned, access))
2598        })
2599        .await?
2600    } else {
2601        (owned, None)
2602    };
2603    let (owned, default) = if want_default && names_contain(&names, ACL_DEFAULT_XATTR) {
2604        run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2605            let default = fgetxattr_blob(owned.as_raw_fd(), ACL_DEFAULT_XATTR)?;
2606            Ok((owned, default))
2607        })
2608        .await?
2609    } else {
2610        (owned, None)
2611    };
2612    Ok((owned, Acls { access, default }))
2613}
2614
2615/// Apply `acls` to a destination entry through an fd it is already open on, SETTING each attribute
2616/// the source had and REMOVING each one it did not.
2617///
2618/// Clearing is not an optimization to skip: a destination directory's default ACL is inherited by
2619/// every child created beneath it, including children rcp itself creates, so a source with no ACL
2620/// needs an explicit removal or the copy silently ends up more permissive than what it copied.
2621///
2622/// The access ACL is applied LAST because it is the step that WIDENS the destination — see
2623/// [`set_file_metadata_owned`]. The default ACL is mode-neutral, so it goes first and constrains
2624/// nothing.
2625///
2626/// Gated as `MetadataOp::Chmod`, the bucket for single-inode permission writes.
2627pub async fn apply_acls_fd(
2628    fd: BorrowedFd<'_>,
2629    side: congestion::Side,
2630    acls: &Acls,
2631    want_default: bool,
2632) -> std::io::Result<()> {
2633    if want_default {
2634        set_or_remove_acl_fd(fd, side, ACL_DEFAULT_XATTR, acls.default.clone()).await?;
2635    }
2636    set_or_remove_acl_fd(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await
2637}
2638
2639/// Install `blob` as `name` on `fd`, or REMOVE `name` when `blob` is `None`, through the module's
2640/// metadata gate.
2641///
2642/// The async half of `apply_one_acl`, at single-attribute granularity: [`apply_acls_fd`] (its
2643/// one caller) resolves the two ACLs one at a time through it. A LOCKED reused directory's
2644/// default ACL must NOT come through here — that write has to serialize against the lockdown
2645/// guard's rollback; `ReusedDirLock::write_default_acl_guarded` is the only correct writer.
2646///
2647/// Gated as `MetadataOp::Chmod`, the bucket for single-inode permission writes.
2648async fn set_or_remove_acl_fd(
2649    fd: BorrowedFd<'_>,
2650    side: congestion::Side,
2651    name: &'static CStr,
2652    blob: Option<Vec<u8>>,
2653) -> std::io::Result<()> {
2654    set_or_remove_acl_owned(fd.try_clone_to_owned()?, side, name, blob)
2655        .await
2656        .map(drop)
2657}
2658
2659async fn set_or_remove_acl_owned(
2660    owned: OwnedFd,
2661    side: congestion::Side,
2662    name: &'static CStr,
2663    blob: Option<Vec<u8>>,
2664) -> std::io::Result<OwnedFd> {
2665    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
2666        apply_one_acl(owned.as_raw_fd(), name, blob.as_deref())?;
2667        Ok(owned)
2668    })
2669    .await
2670}
2671
2672/// Resolve the ACL payload an applier should install: `None` when ACL preservation is off for this
2673/// entry kind, `Some(acls)` when it is on and the caller carried the source's ACLs.
2674///
2675/// The third combination — preservation on, but the call site did not read the source's ACLs — is
2676/// an ERROR rather than either silent alternative. Treating it as "leave the destination alone"
2677/// keeps whatever the destination inherited, and treating it as an empty [`Acls`] CLEARS what the
2678/// source had; both produce a destination whose ACLs did not come from its source, which is exactly
2679/// the quiet lie ACL preservation exists to remove. Consolidated here so a reader verifies it once
2680/// rather than at each applier.
2681///
2682/// No caller reaches that arm today: the local copy reads the source's ACLs from the fd it is about
2683/// to copy, and the remote destination gets them from the wire header. It is kept as a fail-closed
2684/// backstop for a future applier that forgets to — which would otherwise be silent.
2685fn acls_to_apply(want: bool, acls: Option<&Acls>) -> std::io::Result<Option<&Acls>> {
2686    match (want, acls) {
2687        (false, _) => Ok(None),
2688        (true, Some(acls)) => Ok(Some(acls)),
2689        (true, None) => Err(std::io::Error::new(
2690            std::io::ErrorKind::Unsupported,
2691            "ACL preservation was requested but this copy path does not carry the source's ACLs",
2692        )),
2693    }
2694}
2695
2696/// The `listxattr` family's two-step protocol, shared by the fd and path forms: try a stack
2697/// buffer, and only on `ERANGE` ask the kernel for the current size and retry on the heap.
2698///
2699/// `call(buf, len)` issues one syscall; `call(null, 0)` asks for the size without writing.
2700///
2701/// An `EOPNOTSUPP` filesystem yields an empty list: it holds no xattrs, so it holds no ACL either.
2702fn listxattr_retry(
2703    mut call: impl FnMut(*mut libc::c_char, usize) -> isize,
2704) -> std::io::Result<Vec<u8>> {
2705    // a name list is well under 256 bytes even with `security.selinux` and a couple of user
2706    // attributes present; the ERANGE path below covers anything larger.
2707    let mut buf = [0u8; 256];
2708    let n = call(buf.as_mut_ptr().cast(), buf.len());
2709    if n >= 0 {
2710        return Ok(buf[..n as usize].to_vec());
2711    }
2712    let err = std::io::Error::last_os_error();
2713    match err.raw_os_error() {
2714        Some(libc::EOPNOTSUPP) => Ok(Vec::new()),
2715        Some(libc::ERANGE) => {
2716            let size = call(std::ptr::null_mut(), 0);
2717            if size < 0 {
2718                return Err(std::io::Error::last_os_error());
2719            }
2720            let mut heap = vec![0u8; size as usize];
2721            if heap.is_empty() {
2722                return Ok(heap);
2723            }
2724            let n = call(heap.as_mut_ptr().cast(), heap.len());
2725            if n < 0 {
2726                // a concurrent writer grew the list between the two calls; report it rather than
2727                // looping against a live competing writer.
2728                return Err(std::io::Error::last_os_error());
2729            }
2730            heap.truncate(n as usize);
2731            Ok(heap)
2732        }
2733        _ => Err(err),
2734    }
2735}
2736
2737/// `flistxattr`, returning the raw NUL-separated name list the kernel produced.
2738fn flistxattr_names(fd: RawFd) -> std::io::Result<Vec<u8>> {
2739    // SAFETY: `fd` is a valid open descriptor for the duration of the call and the kernel writes
2740    // at most `len` bytes into `buf` (or nothing at all when `buf` is null and `len` is 0).
2741    listxattr_retry(|buf, len| unsafe { libc::flistxattr(fd, buf, len) })
2742}
2743
2744/// `listxattr` on a PATH, following symlinks — used only for the `/proc/self/fd/N` magic symlink,
2745/// which must be dereferenced to reach the inode an `O_PATH` handle pins.
2746///
2747/// See [`has_acl_via_proc_fd`] for why the probe cannot go through the handle's fd directly.
2748fn listxattr_names_at_path(path: &CStr) -> std::io::Result<Vec<u8>> {
2749    // SAFETY: `path` is a NUL-terminated C string that outlives the call and the kernel writes at
2750    // most `len` bytes into `buf` (or nothing at all when `buf` is null and `len` is 0).
2751    // the only caller passes /proc/self/fd/N for an fd it already holds, so this resolves to that
2752    // PINNED inode: inode-exact, not a by-name lookup a swap could redirect.
2753    let probe = |buf, len| {
2754        unsafe { libc::listxattr(path.as_ptr(), buf, len) } // rcp-toctou-allow: /proc/self/fd magic symlink to a held fd
2755    };
2756    listxattr_retry(probe)
2757}
2758
2759/// Whether the NUL-separated `list` produced by [`flistxattr_names`] contains `name`.
2760fn names_contain(list: &[u8], name: &CStr) -> bool {
2761    list.split(|byte| *byte == 0).any(|n| n == name.to_bytes())
2762}
2763
2764/// `fgetxattr` one attribute, retrying on a larger buffer if the stack one did not fit.
2765///
2766/// `Ok(None)` for both "the entry has no such attribute" (`ENODATA`) and "this filesystem cannot
2767/// hold one" (`EOPNOTSUPP`) — neither has an ACL to preserve.
2768fn fgetxattr_blob(fd: RawFd, name: &CStr) -> std::io::Result<Option<Vec<u8>>> {
2769    // a POSIX.1e ACL blob is `4 + 8n` bytes, so 512 holds 63 entries — every realistic ACL in a
2770    // single syscall.
2771    let mut buf = [0u8; 512];
2772    // SAFETY: `fd` is a valid open descriptor for the duration of the call, `name` is a
2773    // NUL-terminated C string, and the kernel writes at most `buf.len()` bytes into `buf`.
2774    let n = unsafe { libc::fgetxattr(fd, name.as_ptr(), buf.as_mut_ptr().cast(), buf.len()) };
2775    if n >= 0 {
2776        return Ok(Some(buf[..n as usize].to_vec()));
2777    }
2778    let err = std::io::Error::last_os_error();
2779    match err.raw_os_error() {
2780        Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(None),
2781        Some(libc::ERANGE) => {
2782            // SAFETY: as above; a null buffer with size 0 asks the kernel for the current size
2783            // without writing anything.
2784            let size = unsafe { libc::fgetxattr(fd, name.as_ptr(), std::ptr::null_mut(), 0) };
2785            if size < 0 {
2786                return Err(std::io::Error::last_os_error());
2787            }
2788            let mut heap = vec![0u8; size as usize];
2789            if heap.is_empty() {
2790                return Ok(Some(heap));
2791            }
2792            // SAFETY: as above; `heap` has `len()` writable bytes.
2793            let n =
2794                unsafe { libc::fgetxattr(fd, name.as_ptr(), heap.as_mut_ptr().cast(), heap.len()) };
2795            if n < 0 {
2796                // a concurrent writer grew the attribute between the two calls; report it rather
2797                // than looping against a live competing writer.
2798                return Err(std::io::Error::last_os_error());
2799            }
2800            heap.truncate(n as usize);
2801            Ok(Some(heap))
2802        }
2803        _ => Err(err),
2804    }
2805}
2806
2807/// Install `blob` as `name`, or REMOVE `name` when `blob` is `None`.
2808///
2809/// The error handling is asymmetric, and the asymmetry is the point:
2810///
2811/// - A failing SET fails the entry, `EOPNOTSUPP` included. A destination that cannot hold the
2812///   source's ACL ends up MORE PERMISSIVE than its source — a named entry narrower than `other`
2813///   acts as a deny in effect, so dropping it grants exactly what the source withheld. Dropping it
2814///   quietly is the bug this feature exists to remove; a destination filesystem without ACL support
2815///   is a failure, not a shrug.
2816/// - A failing REMOVE with `ENODATA` or `EOPNOTSUPP` is SUCCESS. Both say there is no ACL on the
2817///   destination to clear, so nothing can have widened — the post-condition the caller asked for
2818///   already holds.
2819fn apply_one_acl(fd: RawFd, name: &CStr, blob: Option<&[u8]>) -> std::io::Result<()> {
2820    let Some(blob) = blob else {
2821        // SAFETY: `fd` is a valid open descriptor for the duration of the call and `name` is a
2822        // NUL-terminated C string.
2823        if unsafe { libc::fremovexattr(fd, name.as_ptr()) } == 0 {
2824            return Ok(());
2825        }
2826        let err = std::io::Error::last_os_error();
2827        return match err.raw_os_error() {
2828            Some(libc::ENODATA | libc::EOPNOTSUPP) => Ok(()),
2829            _ => Err(err),
2830        };
2831    };
2832    // SAFETY: as above; `blob` points at `blob.len()` readable bytes. Flags 0 means "create or
2833    // replace", which is what preserving a source's ACL onto a fresh destination needs.
2834    let rc = unsafe {
2835        libc::fsetxattr(
2836            fd,
2837            name.as_ptr(),
2838            blob.as_ptr().cast(),
2839            blob.len(),
2840            0, // neither XATTR_CREATE nor XATTR_REPLACE: set it whatever the destination holds
2841        )
2842    };
2843    if rc == 0 {
2844        Ok(())
2845    } else {
2846        Err(std::io::Error::last_os_error())
2847    }
2848}
2849
2850// ── The source-root ACL warning ─────────────────────────────────────────────────
2851//
2852// `all` does not preserve ACLs, and a user who asked for it and does not know
2853// that gets a silently wider destination. Telling them costs one `listxattr` on
2854// the SOURCE ROOT per run — a constant, not a per-entry probe, so it is
2855// affordable on the very path whose whole point is that it pays nothing per
2856// entry.
2857//
2858// armed by ASKING (`RootAclNotice`), not by an ACL merely existing: a run left at
2859// the shipped default already drops uid, gid, timestamps and the special mode bits
2860// without a word, so it is not the place to be loud about one more attribute it
2861// also does not carry — and it pays nothing to find that out.
2862//
2863// It is a HEURISTIC and must be read as one: a root without an ACL says nothing
2864// about its children. The alternative — probing enough entries to be sure — IS
2865// the per-entry cost that made `acl` opt-in in the first place.
2866
2867/// Guards the probe so it runs at most once per process, no matter how many source operands (or
2868/// `--dereference` recursions into `copy`) reach a call site.
2869static ROOT_ACL_PROBED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
2870
2871/// What a run's settings say about the source-root ACL notice: whether it is wanted at all, and
2872/// which kinds are already covered.
2873///
2874/// The single home of the rule, so the two entry points below, the cheap pre-check a caller uses to
2875/// skip work, and the remote source all decide the same way.
2876#[derive(Copy, Clone, Debug, PartialEq, Eq)]
2877pub struct RootAclNotice {
2878    /// Whether this run asked for the kind of fidelity a dropped ACL would undermine, normally
2879    /// [`crate::preserve::Settings::requests_preservation`].
2880    ///
2881    /// `false` silences the notice outright — probe included, so a run that did not ask pays
2882    /// nothing at all. A copy left at the shipped default already drops uid, gid, timestamps and
2883    /// the setuid/setgid/sticky bits without a word; singling ACLs out there would be advice about
2884    /// permission completeness nobody claimed. It is also independent of
2885    /// [`strict_operand_resolution`], which arms the notice on its own: `--require-toctou-safe` is
2886    /// a request about permissions whatever the preserve settings say, and it gets its own wording.
2887    pub wanted: bool,
2888    /// Whether a FILE root's ACL is already safe — normally the `acl` preserve setting for files,
2889    /// but `true` also covers a kind whose ACL cannot be lost by construction (`rlink` passes it
2890    /// for files without `--update`, which share the source inode through the hard link).
2891    pub file_acl_preserved: bool,
2892    /// Whether a DIRECTORY root's ACLs (access and default) are already safe.
2893    pub dir_acl_preserved: bool,
2894}
2895
2896impl RootAclNotice {
2897    /// The notice a copy governed by `preserve` wants.
2898    #[must_use]
2899    pub fn for_preserve(preserve: &crate::preserve::Settings) -> Self {
2900        Self {
2901            wanted: preserve.requests_preservation(),
2902            file_acl_preserved: preserve.file.acl,
2903            dir_acl_preserved: preserve.dir.acl,
2904        }
2905    }
2906
2907    /// Whether a root of `kind` could produce a notice: the run wants one and that kind's ACLs are
2908    /// not already being carried across.
2909    ///
2910    /// Symlinks and special files answer `false` without consulting anything — the kernel has no
2911    /// symlink ACL (the settings parser rejects `l:acl`), and a special file is not copied as an
2912    /// object whose permissions rcp reproduces.
2913    ///
2914    /// Reads the process-global strict flag, so it must not be called before
2915    /// [`enable_strict_operand_resolution`] has run — every call site is well past the linter that
2916    /// sets it.
2917    fn could_warn_for(self, kind: EntryKind) -> bool {
2918        self.could_warn_for_strict(kind, strict_operand_resolution())
2919    }
2920
2921    /// [`could_warn_for`](Self::could_warn_for) with the strict flag passed in rather than read, so
2922    /// the rule itself can be pinned without a process-global to arrange.
2923    fn could_warn_for_strict(self, kind: EntryKind, strict: bool) -> bool {
2924        (self.wanted || strict)
2925            && match kind {
2926                EntryKind::File => !self.file_acl_preserved,
2927                EntryKind::Dir => !self.dir_acl_preserved,
2928                EntryKind::Symlink | EntryKind::Special => false,
2929            }
2930    }
2931
2932    /// Whether ANY root could produce a notice — [`could_warn_for`](Self::could_warn_for) with the
2933    /// root's kind not yet known, which is the only thing a caller holding just a path can ask.
2934    fn could_warn(self) -> bool {
2935        self.could_warn_for(EntryKind::File) || self.could_warn_for(EntryKind::Dir)
2936    }
2937}
2938
2939/// Whether the inode an `O_PATH` [`Handle`] pins carries either POSIX ACL, probed through its
2940/// `/proc/self/fd/N` magic symlink.
2941///
2942/// The `/proc` detour is not decoration: `flistxattr` on an `O_PATH` descriptor fails with `EBADF`,
2943/// so the classify handle — the one fd every engine already holds for its root, whatever the entry
2944/// kind — cannot answer the probe directly. Resolving the magic symlink reaches the pinned inode
2945/// while staying inode-exact, exactly as [`chmod_via_proc_fd`] and [`stat_meta_via_proc_fd`] do,
2946/// and it needs neither read permission on the entry nor a second `openat`. Requires `/proc`
2947/// mounted (same precondition as [`chmod_via_proc_fd`]); a caller treats failure as "don't know"
2948/// rather than as an error, since this only ever produces a warning.
2949///
2950/// Gated as `MetadataOp::Stat` like every other metadata read here.
2951async fn has_acl_via_proc_fd(handle: &Handle, side: congestion::Side) -> std::io::Result<bool> {
2952    // clone the O_PATH fd into an owned fd the blocking closure can hold, keeping the pinned inode
2953    // alive for the syscall's full duration even if the originating Handle is dropped.
2954    let owned = handle.as_fd().try_clone_to_owned()?;
2955    let names = run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
2956        let proc_path = std::ffi::CString::new(format!("/proc/self/fd/{}", owned.as_raw_fd()))
2957            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
2958        listxattr_names_at_path(&proc_path)
2959    })
2960    .await?;
2961    Ok(names_contain(&names, ACL_ACCESS_XATTR) || names_contain(&names, ACL_DEFAULT_XATTR))
2962}
2963
2964/// Whether it is worth *reaching* for the probe: something could still be warned about, and the
2965/// one per-process run has not been taken yet.
2966///
2967/// Advisory only — it claims nothing, so the probe itself still goes through
2968/// [`warn_if_root_acl_unpreserved`] / [`warn_if_root_acl_unpreserved_at`], which claim internally.
2969/// Its job is to let a caller skip work it would otherwise do just to reach the probe: the two
2970/// entry points below use it to skip an `openat`, and `rcp`'s remote `-L` source uses it to skip
2971/// resolving and opening the root's parent, which it does not otherwise need.
2972#[must_use]
2973pub fn root_acl_probe_worth_reaching(notice: RootAclNotice) -> bool {
2974    if !notice.could_warn() {
2975        return false;
2976    }
2977    !ROOT_ACL_PROBED.load(std::sync::atomic::Ordering::Relaxed)
2978}
2979
2980/// Claim the single per-process probe run, returning `false` if someone already has it.
2981///
2982/// Called as LATE as possible — after the root's kind is known and after the per-kind settings
2983/// check — so that a root which cannot produce a warning does not consume the budget and silence
2984/// a later operand that could have. Two operands racing here can both pass
2985/// [`root_acl_probe_worth_reaching`] and both open their root; only one wins the swap, and the
2986/// loser has wasted one `openat`. Which one wins is therefore unspecified for concurrent operands;
2987/// see the note on [`warn_if_root_acl_unpreserved`].
2988fn claim_root_acl_probe() -> bool {
2989    !ROOT_ACL_PROBED.swap(true, std::sync::atomic::Ordering::Relaxed)
2990}
2991
2992/// Probe `handle` and warn if it carries an ACL this copy will not carry across. The shared body
2993/// of the two entry points below, so the message and the kind rule live in one place.
2994///
2995/// The root's kind is the LAST thing the rule needs, and the only one a caller cannot supply, so
2996/// this is where [`RootAclNotice::could_warn_for`] is asked authoritatively — a symlink or special
2997/// root, and a kind whose ACLs are already carried across, are turned away without a syscall.
2998/// Failure to probe is logged at `debug!` and nothing else: this produces advice, so a missing
2999/// `/proc` or an exotic filesystem must not turn into a copy error.
3000async fn warn_root_acl(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
3001    if !notice.could_warn_for(handle.kind()) {
3002        return;
3003    }
3004    // claim LAST. A root that could not have warned returns above without spending the one
3005    // per-process run, so it cannot silence a later operand that had something to say.
3006    if !claim_root_acl_probe() {
3007        return;
3008    }
3009    // Both arms go to `crate::NOTICE_TARGET`, which the verbose filter renders at every verbosity
3010    // INCLUDING the default: a notice about `all` silently dropping ACLs is useless if only a user
3011    // who already passed `-v` — and therefore already suspects something — can see it.
3012    match has_acl_via_proc_fd(handle, congestion::Side::Source).await {
3013        Ok(false) => {}
3014        Ok(true) if strict_operand_resolution() => tracing::warn!(
3015            target: crate::NOTICE_TARGET,
3016            "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
3017             (`--preserve-settings` does not request `acl`). --require-toctou-safe stops the \
3018             DESTINATION tree's ACLs from being inherited, but it does not carry the SOURCE's \
3019             across, so the copy can still end up more permissive than what it copied. Use \
3020             `--preserve-settings=all+acl`. Only the root was checked - entries beneath it may \
3021             carry ACLs this says nothing about."
3022        ),
3023        Ok(true) => tracing::warn!(
3024            target: crate::NOTICE_TARGET,
3025            "Source root {src_root:?} carries a POSIX ACL that this copy will NOT preserve \
3026             (`--preserve-settings` does not request `acl`), so the destination may end up more \
3027             permissive than its source. Use `--preserve-settings=all+acl`. Only the root was \
3028             checked - entries beneath it may carry ACLs this says nothing about."
3029        ),
3030        Err(err) => {
3031            tracing::debug!("cannot probe {src_root:?} for a POSIX ACL: {err:#}");
3032        }
3033    }
3034}
3035
3036/// Warn once per run when the source ROOT carries a POSIX ACL that this copy will not carry across.
3037///
3038/// `handle` is the root's `O_PATH` classify handle and `src_root` its path, for the message;
3039/// `notice` is what the run's settings say (see [`RootAclNotice`]). The probe consults whichever of
3040/// its per-kind flags matches the root's own kind, so `f:acl` does not silence a directory root.
3041///
3042/// "Once" is per PROCESS, which is what makes this affordable: a `--dereference` walk recurses into
3043/// `copy` per resolved symlink, and a multi-operand run has several roots. The first root that can
3044/// carry an ACL spends the probe; the rest are silent even if they would have warned. That is the
3045/// heuristic being cheap on purpose — the alternative is the per-entry cost that made `acl` opt-in.
3046pub async fn warn_if_root_acl_unpreserved(handle: &Handle, src_root: &Path, notice: RootAclNotice) {
3047    if !root_acl_probe_worth_reaching(notice) {
3048        return;
3049    }
3050    warn_root_acl(handle, src_root, notice).await;
3051}
3052
3053/// [`warn_if_root_acl_unpreserved`] for a caller that holds the root's PARENT rather than the root
3054/// itself — the shape of the local `rcp`/`rlink` entry points, which open the root only inside the
3055/// walk.
3056///
3057/// The `openat` is skipped when nothing could be warned about and when the per-process run is
3058/// already spent, so a copy that did not ask for the notice or already preserves ACLs — and every
3059/// call after the first — costs nothing at all. Two operands racing can both pass that check and
3060/// both open their root; the loser of the claim has then spent one `openat` and nothing more. A
3061/// root that cannot be opened is left to the walk to diagnose.
3062pub async fn warn_if_root_acl_unpreserved_at(
3063    parent: &Dir,
3064    name: &OsStr,
3065    src_root: &Path,
3066    notice: RootAclNotice,
3067) {
3068    if !root_acl_probe_worth_reaching(notice) {
3069        return;
3070    }
3071    match parent.child(name).await {
3072        Ok(handle) => warn_root_acl(&handle, src_root, notice).await,
3073        Err(err) => {
3074            tracing::debug!("cannot open source root {src_root:?} for a POSIX ACL probe: {err:#}");
3075        }
3076    }
3077}
3078
3079// ── fd-based metadata application ───────────────────────────────────────────────
3080//
3081// These primitives apply ownership / mode / timestamps to an entry through a
3082// file descriptor we already hold, rather than re-resolving a path. That closes
3083// the TOCTOU window a path-based applier would have between opening/creating the
3084// entry and re-touching it by name (which is why the fd-based appliers replaced
3085// the path-based ones entirely).
3086//
3087// Every applier does chown BEFORE chmod: an unprivileged `fchown` clears
3088// setuid/setgid on a regular file, so the chmod has to come after to restore
3089// them. `set_file_metadata_owned` additionally puts the widening step LAST, after
3090// utimens — it is what takes a destination file from the owner-only mode it was
3091// created at (`DST_FILE_CREATE_MODE`) to the source mode, so it must not land
3092// until every other fallible step has succeeded. Ordering the two is free:
3093// `fchmod` touches ctime only, never atime/mtime, so the timestamps `futimens`
3094// installs are the same either way. All syscalls are gated through
3095// `run_metadata_probed_blocking` with `MetadataOp::Chmod`, bucketing
3096// chown/chmod/utimens/ACL together.
3097
3098/// `fchown` on a real (readable/writable) file descriptor.
3099///
3100/// No-op is the caller's responsibility: this always issues the syscall. Pass
3101/// `None` for a component that must not change.
3102async fn fchown_fd(
3103    fd: BorrowedFd<'_>,
3104    side: congestion::Side,
3105    uid: Option<u32>,
3106    gid: Option<u32>,
3107) -> std::io::Result<()> {
3108    fchown_owned(fd.try_clone_to_owned()?, side, uid, gid)
3109        .await
3110        .map(drop)
3111}
3112
3113async fn fchown_owned(
3114    owned: OwnedFd,
3115    side: congestion::Side,
3116    uid: Option<u32>,
3117    gid: Option<u32>,
3118) -> std::io::Result<OwnedFd> {
3119    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3120        #[cfg(test)]
3121        let _visit = resource_tests::gate_opened_descriptor(owned.as_raw_fd())?;
3122        fchown(
3123            owned.as_fd(),
3124            uid.map(Uid::from_raw),
3125            gid.map(Gid::from_raw),
3126        )
3127        .map_err(nix_to_io)?;
3128        Ok(owned)
3129    })
3130    .await
3131}
3132
3133/// `fchmod` on a real file descriptor. `mode` is masked to the permission bits
3134/// (`0o7777`); file-type bits, if present, are dropped by `from_bits_truncate`.
3135///
3136/// `fd` must be a real (not `O_PATH`) descriptor — `fchmod` returns `EBADF` on an
3137/// `O_PATH` fd. This is used by the copy path, which holds the destination's own
3138/// writable file / directory fd. For an `O_PATH` [`Handle`] (e.g. rchm's classified
3139/// entry), use [`chmod_via_proc_fd`] instead.
3140async fn fchmod_fd(fd: BorrowedFd<'_>, side: congestion::Side, mode: u32) -> std::io::Result<()> {
3141    fchmod_owned(fd.try_clone_to_owned()?, side, mode)
3142        .await
3143        .map(drop)
3144}
3145
3146async fn fchmod_owned(
3147    owned: OwnedFd,
3148    side: congestion::Side,
3149    mode: u32,
3150) -> std::io::Result<OwnedFd> {
3151    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3152        fchmod(owned.as_fd(), Mode::from_bits_truncate(mode)).map_err(nix_to_io)?;
3153        Ok(owned)
3154    })
3155    .await
3156}
3157
3158/// `futimens` on a real file descriptor.
3159async fn futimens_fd(
3160    fd: BorrowedFd<'_>,
3161    side: congestion::Side,
3162    atime: i64,
3163    atime_nsec: i64,
3164    mtime: i64,
3165    mtime_nsec: i64,
3166) -> std::io::Result<()> {
3167    futimens_owned(
3168        fd.try_clone_to_owned()?,
3169        side,
3170        atime,
3171        atime_nsec,
3172        mtime,
3173        mtime_nsec,
3174    )
3175    .await
3176    .map(drop)
3177}
3178
3179async fn futimens_owned(
3180    owned: OwnedFd,
3181    side: congestion::Side,
3182    atime: i64,
3183    atime_nsec: i64,
3184    mtime: i64,
3185    mtime_nsec: i64,
3186) -> std::io::Result<OwnedFd> {
3187    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3188        let atime_spec = TimeSpec::new(atime, atime_nsec);
3189        let mtime_spec = TimeSpec::new(mtime, mtime_nsec);
3190        futimens(owned.as_fd(), &atime_spec, &mtime_spec).map_err(nix_to_io)?;
3191        Ok(owned)
3192    })
3193    .await
3194}
3195
3196/// Inode-exact `fchownat` on any [`Handle`]'s `O_PATH` fd, operating on the entry
3197/// the fd points at — file, directory, or symlink — never following a symlink.
3198///
3199/// Uses `AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW` so the empty pathname resolves to
3200/// the fd's own pinned inode: no path re-resolution by `name` happens, so a
3201/// concurrent rename/symlink-swap of the directory entry cannot redirect the
3202/// chown to a different target. `AT_SYMLINK_NOFOLLOW` makes a symlink `Handle`
3203/// chown the link itself rather than its target. Pass `None` for a component
3204/// that must not change (the caller decides when to issue the syscall at all).
3205pub(crate) async fn fchown_handle(
3206    handle: &Handle,
3207    side: congestion::Side,
3208    uid: Option<u32>,
3209    gid: Option<u32>,
3210) -> std::io::Result<()> {
3211    let owned = handle.as_fd().try_clone_to_owned()?;
3212    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3213        fchownat(
3214            owned.as_fd(),
3215            "",
3216            uid.map(Uid::from_raw),
3217            gid.map(Gid::from_raw),
3218            AtFlags::AT_EMPTY_PATH | AtFlags::AT_SYMLINK_NOFOLLOW,
3219        )
3220        .map_err(nix_to_io)
3221    })
3222    .await
3223}
3224
3225/// `chmod` any non-symlink entry (file, directory, or special) through an `O_PATH`
3226/// [`Handle`] by going via the `/proc/self/fd/N` magic symlink, changing the mode
3227/// of the EXACT inode the handle pins — never re-resolving the entry by name.
3228///
3229/// (Symlink mode bits are not settable on Linux, so callers never invoke this on a
3230/// symlink handle.)
3231///
3232/// # Why /proc and not `fchmod`/`fchmodat`
3233///
3234/// The `Handle` fd is `O_PATH`, which is the only way to pin an arbitrary entry's
3235/// inode without read/write/search rights on it. But `O_PATH` rules out the
3236/// obvious chmod paths:
3237///
3238/// - `fchmod(fd, mode)` returns `EBADF` on an `O_PATH` fd (it requires a real
3239///   open file description).
3240/// - `fchmodat(dirfd, name, mode, AT_SYMLINK_NOFOLLOW)` re-resolves `name`
3241///   relative to a directory fd — that re-resolution is exactly the TOCTOU window
3242///   we are closing, and the `AT_SYMLINK_NOFOLLOW` flag is only honored on Linux
3243///   6.6+ for `fchmodat` (older kernels reject it with `ENOTSUP`).
3244///
3245/// `chmod("/proc/self/fd/N", mode)` follows the kernel's per-fd magic symlink,
3246/// which resolves to the open file description's pinned inode regardless of what
3247/// the original `name` now refers to. Because the `O_PATH` handle keeps that
3248/// inode alive (the kernel cannot recycle an inode with an open reference), this
3249/// is inode-exact and immune to a concurrent rename/symlink swap. It also works
3250/// regardless of the file's own permission bits — e.g. a non-root owner's
3251/// `0000`-mode file — because the operation authorizes against the caller's
3252/// ownership, not the path's mode, and needs no traversal/read rights on the
3253/// target. (`fchmodat(.., FollowSymlink)` on the magic symlink is used because
3254/// the magic link must be dereferenced to reach the pinned inode.)
3255///
3256/// # Precondition
3257///
3258/// Requires `/proc` to be mounted (the standard Linux default). Without `/proc`
3259/// the call fails with `ENOENT`; this is a documented operational precondition of
3260/// the fd-based chmod path.
3261pub(crate) async fn chmod_via_proc_fd(
3262    handle: &Handle,
3263    side: congestion::Side,
3264    mode: u32,
3265) -> std::io::Result<()> {
3266    // clone the O_PATH fd into an owned fd the blocking closure can hold, keeping
3267    // the pinned inode alive for the syscall's full duration even if the
3268    // originating Handle is dropped after the closure starts. started spawn_blocking work is not
3269    // cancellable.
3270    let owned = handle.as_fd().try_clone_to_owned()?;
3271    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3272        let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3273        // FollowSymlink: the /proc entry is a magic symlink that must be
3274        // dereferenced to reach the pinned inode (NoFollowSymlink would chmod the
3275        // magic link itself, a silent no-op).
3276        nix::sys::stat::fchmodat(
3277            AT_FDCWD,
3278            proc_path.as_str(),
3279            Mode::from_bits_truncate(mode),
3280            nix::sys::stat::FchmodatFlags::FollowSymlink,
3281        )
3282        .map_err(nix_to_io)
3283    })
3284    .await
3285}
3286
3287/// Read full [`std::fs::Metadata`] for the exact inode an `O_PATH` [`Handle`] pins,
3288/// via the `/proc/self/fd/N` magic symlink.
3289///
3290/// The fd-pinned [`FileMeta`] snapshot ([`Handle::meta`]) covers uid/gid/mode and
3291/// the a/m/ctime timestamps, but NOT the birth time (`btime`) — `fstat` does not
3292/// return it. Callers that need `Metadata::created()` (the `--created-before`
3293/// time filter) get it here while staying inode-exact: the open `O_PATH` handle
3294/// keeps the inode alive, so resolving `/proc/self/fd/N` lands on that same inode
3295/// regardless of a concurrent rename/symlink swap of the original name. Gated as
3296/// `Stat`. Requires `/proc` mounted (same precondition as [`chmod_via_proc_fd`]).
3297pub(crate) async fn stat_meta_via_proc_fd(
3298    handle: &Handle,
3299    side: congestion::Side,
3300) -> std::io::Result<std::fs::Metadata> {
3301    let owned = handle.as_fd().try_clone_to_owned()?;
3302    run_metadata_probed_blocking(side, congestion::MetadataOp::Stat, move || {
3303        let proc_path = format!("/proc/self/fd/{}", owned.as_raw_fd());
3304        std::fs::metadata(proc_path)
3305    })
3306    .await
3307}
3308
3309/// Read the target of a symlink [`Handle`] inode-exact, via `readlinkat(fd, "")` on the pinned
3310/// `O_PATH | O_NOFOLLOW` fd.
3311///
3312/// The empty-pathname form of `readlinkat` (Linux 2.6.39+) operates on the symlink the fd itself
3313/// refers to, so the target comes from the *same* pinned inode as [`Handle::meta`] — there is no
3314/// path re-resolution by name that a concurrent same-name swap could redirect. This is the symlink
3315/// analogue of reading a regular file's bytes and metadata from one [`Dir::open_file_read`] fd: it
3316/// lets a caller send/apply a symlink's target and metadata as a faithful pair. Fails if the handle
3317/// does not refer to a symlink (the empty-path form requires a symlink fd); callers only invoke it
3318/// on a `Symlink`-classified handle. Gated as `ReadLink`.
3319///
3320/// Raw `libc::readlinkat` is required: nix's wrapper rejects the empty pathname that selects the
3321/// fd's own link (the same reason `symlink_utimes_fd` uses raw `utimensat`).
3322pub async fn read_link_handle(
3323    handle: &Handle,
3324    side: congestion::Side,
3325) -> std::io::Result<std::path::PathBuf> {
3326    use std::os::unix::ffi::OsStringExt;
3327    let owned = handle.as_fd().try_clone_to_owned()?;
3328    run_metadata_probed_blocking(side, congestion::MetadataOp::ReadLink, move || {
3329        // a symlink target is bounded by PATH_MAX, so a single buffer of that size never truncates.
3330        let mut buf = vec![0u8; libc::PATH_MAX as usize];
3331        // SAFETY: `owned` is a valid open fd for the duration of this call; the empty C string
3332        // selects the fd's own symlink (it was opened O_PATH|O_NOFOLLOW); `buf` has `len()` bytes.
3333        let n = unsafe {
3334            libc::readlinkat(
3335                owned.as_raw_fd(),
3336                c"".as_ptr(),
3337                buf.as_mut_ptr().cast::<libc::c_char>(),
3338                buf.len(),
3339            )
3340        };
3341        if n < 0 {
3342            return Err(std::io::Error::last_os_error());
3343        }
3344        buf.truncate(n as usize);
3345        Ok(std::path::PathBuf::from(std::ffi::OsString::from_vec(buf)))
3346    })
3347    .await
3348}
3349
3350/// Set timestamps on a symlink `Handle`'s `O_PATH` fd, operating on the link
3351/// itself, via a raw `utimensat(fd, "", times, AT_EMPTY_PATH)`.
3352///
3353/// Raw libc is required here: nix's `utimensat` wrapper cannot pass
3354/// `AT_EMPTY_PATH`, and `futimens` on an `O_PATH` fd returns `EBADF`. The
3355/// `/proc/self/fd` form silently no-ops under `NOFOLLOW`, so it must not be used.
3356async fn symlink_utimes_fd(
3357    handle: &Handle,
3358    side: congestion::Side,
3359    atime: i64,
3360    atime_nsec: i64,
3361    mtime: i64,
3362    mtime_nsec: i64,
3363) -> std::io::Result<()> {
3364    let owned = handle.as_fd().try_clone_to_owned()?;
3365    run_metadata_probed_blocking(side, congestion::MetadataOp::Chmod, move || {
3366        let times: [libc::timespec; 2] = [
3367            libc::timespec {
3368                tv_sec: atime,
3369                tv_nsec: atime_nsec,
3370            },
3371            libc::timespec {
3372                tv_sec: mtime,
3373                tv_nsec: mtime_nsec,
3374            },
3375        ];
3376        // SAFETY: `owned` is a valid open fd for the duration of this call; the
3377        // pathname is the empty C string and `times` points to a 2-element array.
3378        let res = unsafe {
3379            libc::utimensat(
3380                owned.as_raw_fd(),
3381                c"".as_ptr(),
3382                times.as_ptr(),
3383                libc::AT_EMPTY_PATH,
3384            )
3385        };
3386        if res == 0 {
3387            Ok(())
3388        } else {
3389            Err(std::io::Error::last_os_error())
3390        }
3391    })
3392    .await
3393}
3394
3395/// Apply file metadata (owner, timestamps, mode, ACL) while consuming the destination's
3396/// existing writable descriptor, in the chown → utimens → mode order.
3397///
3398/// `fd` must be the destination file's own fd (typically the write fd returned by
3399/// [`Dir::create_file`]). The same descriptor moves through individually gated metadata
3400/// operations, without duplication or reopening. Each blocking output owns it until consumed
3401/// or dropped, including cancellation. Callers must finish pending writes and check their errors
3402/// before transferring the descriptor so later writes cannot overwrite the applied timestamps.
3403/// Gating on `settings.file`: chown only when uid or gid is requested, chmod
3404/// always (the masked mode honors `mode_mask`), timestamps only when requested, ACLs only when
3405/// `settings.file.acl` is on — in which case `acls` must carry what was read from the source, or
3406/// the call fails rather than guessing (see `acls_to_apply`).
3407///
3408/// # The widening invariant
3409///
3410/// > EXACTLY ONE step widens the destination from its owner-only create mode, and it is the LAST
3411/// > fallible step here. Without a source access ACL that step is the `fchmod`; with one it is the
3412/// > `fsetxattr`, and the `fchmod` before it is narrowed to `(mode & 0o7000) | DST_FILE_CREATE_MODE`
3413/// > so that it cannot widen.
3414///
3415/// This is what makes [`DST_FILE_CREATE_MODE`] safe to use for every destination file: a failure
3416/// part-way through metadata application must not publish the final mode on a file the copy is
3417/// about to report as failed. The mode is also decided UNCONDITIONALLY here — this call is the
3418/// single place it happens, so no `--preserve` setting can leave a successfully copied file
3419/// owner-only.
3420///
3421/// An access ACL has to take that slot because applying one IS a mode-changing operation: the ACL's
3422/// `MASK` entry becomes the mode's group bits, so `fsetxattr` widens, and a `chmod` AFTER it would
3423/// re-derive `MASK` from the mode and destroy the ACL's fidelity. The two want the same slot, and
3424/// the resolution is verified kernel behavior: `fsetxattr` sets the rwx bits exactly (`USER_OBJ`,
3425/// `MASK`, `OTHER`) and PRESERVES setuid/setgid/sticky, so the preceding `fchmod` can carry the
3426/// special bits alone. Its result — special bits over an owner-only, non-executable mode — grants
3427/// nothing on its own, so a failing `fsetxattr` leaves a file no one else can reach.
3428///
3429/// Clearing an ACL, by contrast, is mode-neutral and can only narrow, so when the source has none
3430/// the removal is safe to run BEFORE the widening chmod (verified: a `0o600` file stays `0o600`
3431/// across `fremovexattr`).
3432///
3433/// A file whose copy fails anywhere before that widening step therefore stays owner-only —
3434/// deliberately. It is reported as an error, and its size/mtime then *normally* differ from the
3435/// source so a later run re-copies it. Two cases where they do not, leaving the file owner-only
3436/// until something else re-copies it: a failure at the widening step ITSELF, which comes after the
3437/// timestamps have been applied, so the destination matches its source on both size and mtime; and
3438/// the nanosecond concession in [`metadata_equal`], which skips that comparison when either side's
3439/// `mtime_nsec` is zero, so even a file that never reached `futimens` compares equal when its write
3440/// and the source's mtime land in the same whole second. See `docs/tocttou.md`.
3441///
3442/// [`metadata_equal`]: crate::filecmp::metadata_equal
3443pub async fn set_file_metadata_owned<Meta: crate::preserve::Metadata>(
3444    settings: &crate::preserve::Settings,
3445    meta: &Meta,
3446    acls: Option<&Acls>,
3447    fd: OwnedFd,
3448    side: congestion::Side,
3449) -> std::io::Result<()> {
3450    let ut = &settings.file.user_and_time;
3451    let fd = if ut.uid || ut.gid {
3452        let uid = if ut.uid { Some(meta.uid()) } else { None };
3453        let gid = if ut.gid { Some(meta.gid()) } else { None };
3454        fchown_owned(fd, side, uid, gid).await?
3455    } else {
3456        fd
3457    };
3458    let fd = if ut.time {
3459        futimens_owned(
3460            fd,
3461            side,
3462            meta.atime(),
3463            meta.atime_nsec(),
3464            meta.mtime(),
3465            meta.mtime_nsec(),
3466        )
3467        .await?
3468    } else {
3469        fd
3470    };
3471    let acls = acls_to_apply(settings.file.acl, acls)?;
3472    let mode = crate::preserve::masked_mode(settings.file.mode_mask, meta);
3473    if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3474        // the ACL is the widening step; this chmod carries only the special bits
3475        let fd = fchmod_owned(fd, side, (mode & 0o7000) | DST_FILE_CREATE_MODE).await?;
3476        set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?;
3477    } else {
3478        // clearing an inherited ACL can only narrow, so it is safe before the widening chmod
3479        let fd = if let Some(acls) = acls {
3480            set_or_remove_acl_owned(fd, side, ACL_ACCESS_XATTR, acls.access.clone()).await?
3481        } else {
3482            fd
3483        };
3484        fchmod_owned(fd, side, mode).await?;
3485    }
3486    Ok(())
3487}
3488
3489/// Apply directory metadata (owner, mode, ACLs, timestamps) to an open [`Dir`] fd,
3490/// following the chown → mode → utimens ordering. Gates on `settings.dir` and
3491/// uses the directory's own congestion side.
3492///
3493/// The mode step is the same two-branch shape as [`set_file_metadata_owned`] — see the widening
3494/// invariant there — with [`DST_DIR_CREATE_MODE`] as the create mode. It stays in the directory
3495/// applier's existing chmod slot rather than moving to the end: `futimens` is last for a directory
3496/// because a directory's mtime is bumped by every child created in it, and unlike a file's mode a
3497/// directory's is applied post-order, once its children exist. The DEFAULT ACL rides along with the
3498/// access one; being mode-neutral, it constrains nothing.
3499///
3500/// # One asymmetry a directory has and a file does not
3501///
3502/// A destination file is always freshly created, so the ACL branch's narrowed `fchmod` only ever
3503/// holds it at the mode it already had. A destination DIRECTORY may be REUSED — an existing `dst/`
3504/// that rcp is copying into — and there that same `fchmod` actively NARROWS it, to `0o700` plus its
3505/// special bits, for the moment between the chmod and the `fsetxattr`. If the `fsetxattr` then
3506/// fails, the copy is reported failed and a long-lived directory is left at `0o700`, which is not
3507/// the mode it started at.
3508///
3509/// That is fail-closed, and deliberately so: the alternative is publishing the source's mode on a
3510/// directory whose ACL never landed, which is the wider outcome. But it means an operator whose
3511/// destination directory comes back owner-only after a failed `d:acl` copy is looking at this step,
3512/// not at a bug. Branch 2 has no such window — it only ever chmods once, to the final mode.
3513pub async fn set_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3514    settings: &crate::preserve::Settings,
3515    meta: &Meta,
3516    acls: Option<&Acls>,
3517    dir: &Dir,
3518) -> std::io::Result<()> {
3519    set_dir_metadata_fd_inner(settings, meta, acls, dir, true).await
3520}
3521
3522/// The body of [`set_dir_metadata_fd`], parameterized over whether the DEFAULT ACL is applied
3523/// here. `apply_default` is `false` for exactly one caller — [`set_reused_dir_metadata_fd`]'s
3524/// locked path, which owns the default ACL through the lockdown guard: that write must serialize
3525/// against the guard's rollback, and an unguarded write from here is precisely the detached-write
3526/// hazard the guard closes (see `DefaultAclGuard`). Everything else — including the access ACL's
3527/// claim on the widening slot — is identical in both modes.
3528async fn set_dir_metadata_fd_inner<Meta: crate::preserve::Metadata>(
3529    settings: &crate::preserve::Settings,
3530    meta: &Meta,
3531    acls: Option<&Acls>,
3532    dir: &Dir,
3533    apply_default: bool,
3534) -> std::io::Result<()> {
3535    let side = dir.side();
3536    let fd = dir.fd.as_fd();
3537    let ut = &settings.dir.user_and_time;
3538    if ut.uid || ut.gid {
3539        let uid = if ut.uid { Some(meta.uid()) } else { None };
3540        let gid = if ut.gid { Some(meta.gid()) } else { None };
3541        fchown_fd(fd, side, uid, gid).await?;
3542    }
3543    let acls = acls_to_apply(settings.dir.acl, acls)?;
3544    let mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3545    if let Some(acls) = acls.filter(|acls| acls.access.is_some()) {
3546        // the ACL is the widening step; this chmod carries only the special bits
3547        fchmod_fd(fd, side, (mode & 0o7000) | DST_DIR_CREATE_MODE).await?;
3548        apply_acls_fd(fd, side, acls, apply_default).await?;
3549    } else {
3550        // no source access ACL, so the chmod is the widening step and stays last. Both applies that
3551        // can run here are safe before it: clearing an inherited ACL can only narrow, and SETTING a
3552        // default ACL is mode-neutral — it governs what children inherit, never this directory's
3553        // own mode (a source can have a default ACL and no access one).
3554        if let Some(acls) = acls {
3555            apply_acls_fd(fd, side, acls, apply_default).await?;
3556        }
3557        fchmod_fd(fd, side, mode).await?;
3558    }
3559    if ut.time {
3560        futimens_fd(
3561            fd,
3562            side,
3563            meta.atime(),
3564            meta.atime_nsec(),
3565            meta.mtime(),
3566            meta.mtime_nsec(),
3567        )
3568        .await?;
3569    }
3570    Ok(())
3571}
3572
3573/// Apply directory metadata to a REUSED destination directory that may have been locked down under
3574/// [`strict_operand_resolution`], restoring the original owner correctly and WITHOUT a transient
3575/// window in which a hostile prior owner regains control.
3576///
3577/// `lock` is what [`lockdown_reused_dir`] recorded, or `None` for a freshly created directory
3578/// (nothing to restore). When present, this restores ONLY the owner components that are NOT being
3579/// preserved to the source — leaving each preserved component as the copier for
3580/// [`set_dir_metadata_fd`] to set to the source owner. So the directory's transient owner is always
3581/// the copier (for a preserved uid) or the final owner (a non-preserved uid equals the original) —
3582/// NEVER a prior owner who will not own the final directory. This closes the brief re-grant window
3583/// that a plain "chown to the original, then chown the preserved components to source" sequence
3584/// would open for a preserving copy, and removes the "left owned by the original if the second chown
3585/// fails" case. The non-preserved gid write, when issued, targets the directory's unchanged gid — a
3586/// kernel-permitted set-to-current no-op, safe even for a non-root copier not in that group.
3587///
3588/// # Resolving the two ACLs
3589///
3590/// The ACCESS ACL keeps its usual applier semantics (set or cleared by the inner applier when
3591/// `d:acl` is on, untouched otherwise). The DEFAULT ACL of a LOCKED directory is different: it is
3592/// resolved HERE, first, through the lockdown guard, and the inner applier is told to leave it
3593/// alone (`set_dir_metadata_fd_inner(…, apply_default: false)`):
3594///
3595/// 1. `settings.dir.acl` on → the SOURCE's default ACL is installed. When the source has none
3596///    there is nothing to write: the lockdown already left the directory without one, which is the
3597///    correct end state. The copy is preserving ACLs, so what the destination carried before is
3598///    not what it should end with.
3599/// 2. otherwise → the directory's ORIGINAL default ACL is restored (nothing to do when there was
3600///    none). rcp was not asked to change this directory's ACLs; the lockdown removed it only so
3601///    children created during the copy could not inherit it, and failing to put it back would
3602///    permanently destroy an ACL the destination had before the copy. That makes a failure here an
3603///    ERROR, unlike the lockdown strip, where `EOPNOTSUPP` is tolerated (a filesystem that cannot
3604///    hold an ACL cannot have had one).
3605///
3606/// Both writes go through `ReusedDirLock::write_default_acl_guarded`, which serializes them
3607/// against the guard's `Drop` rollback: this future can be cancelled with the write already
3608/// detached on the blocking pool, and an unserialized write could land AFTER the rollback and
3609/// silently undo it (see `DefaultAclGuard`). The guard stays armed through every remaining
3610/// fallible step — INCLUDING the final re-stat verification and every cancellation point up to
3611/// the successful return — and is disarmed only immediately before `Ok(())`, so a failure or a
3612/// cancellation anywhere in between rolls the directory back to ITS OWN original default ACL —
3613/// including the case where that original is "none" and the rollback must REMOVE a source ACL
3614/// that was just installed.
3615///
3616/// The guarded write runs FIRST, unwinding the lockdown in the reverse of the order it was applied
3617/// (ACL removed last, so resolved first; then the owner; then the mode, via the chmod inside the
3618/// inner applier). Two things make that placement deliberate:
3619///
3620/// - **It runs while the copier still owns the directory**, before the owner is handed back. Only
3621///   an owner or a `CAP_FOWNER` copier may write these attributes.
3622/// - **It fails toward *unchanged*.** If a later step fails, the armed guard leaves the directory
3623///   holding (or rolled back to) the default ACL it had before the copy. Deferring it past the
3624///   chmod would instead fail toward *damaged* — a directory permanently stripped of an ACL it
3625///   owned before rcp touched it, which is the one outcome this function is required to treat as
3626///   an error rather than produce.
3627///
3628/// The guarded write is mode-neutral, so unlike the SOURCE-ACL applies in the inner applier it
3629/// does not compete with the finalize chmod for the widening slot: only a DEFAULT ACL ever goes
3630/// through it, and a default ACL never moves its own directory's mode. That is a consequence of
3631/// the lockdown narrowing to the default ACL alone (see [`lockdown_reused_dir`]) and is worth
3632/// stating, because it was not always true: while the lockdown also stripped the ACCESS ACL, the
3633/// restore had to precede the chmod or it would install the DESTINATION's original rwx bits over
3634/// the source's mode — the snapshot's `USER_OBJ`/`MASK`/`OTHER` agree with the directory's
3635/// original mode, not the source's — and the re-stat verify below would then reject the copy.
3636/// Anything that reintroduces an access-ACL restore here inherits that constraint.
3637pub async fn set_reused_dir_metadata_fd<Meta: crate::preserve::Metadata>(
3638    settings: &crate::preserve::Settings,
3639    meta: &Meta,
3640    acls: Option<&Acls>,
3641    lock: Option<ReusedDirLock>,
3642    dir: &Dir,
3643) -> std::io::Result<()> {
3644    // A fresh / non-strict directory (lock == None) uses the shared best-effort applier UNVERIFIED —
3645    // verifying it would regress legitimate non-root `--preserve` copies (which the kernel silently
3646    // strips setgid from, best-effort). Only a strict-mode LOCKED reused directory (lock == Some)
3647    // gets the restore + final verify below.
3648    // NB: `ReusedDirLock` is an RAII guard, so it cannot be destructured by move — and must not be,
3649    // since dropping its parts separately is exactly the bug it exists to prevent. It stays whole
3650    // until it is deliberately disarmed below.
3651    let Some(lock) = lock else {
3652        return set_dir_metadata_fd(settings, meta, acls, dir).await;
3653    };
3654    let (orig_uid, orig_gid) = lock.restore_owner;
3655    // resolve the default ACL first, through the guard — see "Resolving the two ACLs" above for
3656    // the two cases, the serialization against the guard's rollback, and why a failure must leave
3657    // the guard armed (`Drop` then gets one synchronous rollback attempt rather than the bytes
3658    // dying with the error)
3659    let final_default = if settings.dir.acl {
3660        // fail closed exactly as the applier does when the call site carried no ACLs
3661        acls_to_apply(true, acls)?.and_then(|acls| acls.default.clone())
3662    } else {
3663        lock.original_default_acl()
3664    };
3665    if let Some(blob) = final_default {
3666        lock.write_default_acl_guarded(dir.side, blob).await?;
3667    }
3668    let ut = &settings.dir.user_and_time;
3669    {
3670        let uid = (!ut.uid).then_some(orig_uid);
3671        let gid = (!ut.gid).then_some(orig_gid);
3672        if uid.is_some() || gid.is_some() {
3673            fchown_fd(dir.fd.as_fd(), dir.side, uid, gid).await?;
3674        }
3675    }
3676    // the default ACL is excluded (`apply_default: false`): it was resolved through the guard
3677    // above, and only the guard's serialized writer may touch it while the lockdown is live
3678    set_dir_metadata_fd_inner(settings, meta, acls, dir, false).await?;
3679    // The guard stays ARMED through the verify below: a re-stat error, a verification failure, or
3680    // this future being cancelled at the `meta()` await all mean the copy of this directory FAILED,
3681    // and failure must leave the directory as it was — the armed guard's `Drop` rolls the default
3682    // ACL back to the destination's original (REMOVING a just-installed source ACL when the
3683    // original was "none") rather than leaving the directory half-converted to the source.
3684    // Disarming any earlier reopens exactly that window; see the disarm at the end.
3685    //
3686    // Re-stat and verify the finalize actually landed. A backend that reports chown/chmod success
3687    // without honoring it (e.g. CIFS without unix extensions) would otherwise leave a strict reused
3688    // directory silently owned by the copier or at the wrong mode. A lone dropped S_ISGID bit is a
3689    // WARNING, not a failure: it is narrower than the source, child safety was already ensured by the
3690    // INTERIM setgid held during the copy, and failing here would regress a legitimate non-root
3691    // `--preserve` of a setgid directory (the kernel strips setgid when the copier is not in the
3692    // group and lacks CAP_FSETID) — matching the best-effort behavior of a non-strict copy.
3693    //
3694    // `want_mode` stays `masked_mode` even when an access ACL was applied. The kernel derives the
3695    // source's rwx bits from its ACL, so these agree when source permissions stay stable during
3696    // capture. Metadata and ACL reads use the same held inode but are separately gated, not atomic;
3697    // concurrent changes during capture can still make this verification fail. The destination's
3698    // rwx bits come from the applied ACL (USER_OBJ/MASK/OTHER), and its special bits from chmod,
3699    // so both are checked against the captured mode without double-counting
3700    use crate::preserve::Metadata as _;
3701    use std::os::unix::fs::PermissionsExt as _;
3702    let want_uid = if ut.uid { meta.uid() } else { orig_uid };
3703    let want_gid = if ut.gid { meta.gid() } else { orig_gid };
3704    let want_mode = crate::preserve::masked_mode(settings.dir.mode_mask, meta);
3705    let got = dir.meta().await?;
3706    let got_mode = got.permissions().mode() & 0o7777;
3707    if got.uid() != want_uid || got.gid() != want_gid {
3708        return Err(std::io::Error::new(
3709            std::io::ErrorKind::PermissionDenied,
3710            format!(
3711                "reused-directory finalize could not be verified: the directory shows uid={} gid={} \
3712                 (expected uid={} gid={}); the filesystem may not honor chown/chmod",
3713                got.uid(),
3714                got.gid(),
3715                want_uid,
3716                want_gid,
3717            ),
3718        ));
3719    }
3720    if got_mode != want_mode {
3721        if want_mode & 0o2000 != 0 && want_mode & !0o2000 == got_mode {
3722            // the ONLY difference is a dropped setgid bit — warn, do not fail.
3723            tracing::warn!(
3724                "setgid not applied to reused directory (final mode {:#o} vs source {:#o}): the \
3725                 copier is not in the directory's group and lacks CAP_FSETID",
3726                got_mode,
3727                want_mode,
3728            );
3729        } else {
3730            return Err(std::io::Error::new(
3731                std::io::ErrorKind::PermissionDenied,
3732                format!(
3733                    "reused-directory finalize could not be verified: the directory shows \
3734                     mode={:#o} (expected {:#o}); the filesystem may not honor chmod",
3735                    got_mode, want_mode,
3736                ),
3737            ));
3738        }
3739    }
3740    // Disarm only here, with the finalize verified and nothing fallible (or cancellable) left
3741    // before the successful return: every earlier exit — error or cancellation — leaves the guard
3742    // armed so its `Drop` restores the destination's original default ACL.
3743    lock.disarm();
3744    Ok(())
3745}
3746
3747/// Apply symlink metadata (owner and timestamps only — never mode) to a symlink
3748/// [`Handle`], operating on the link itself via `AT_EMPTY_PATH`.
3749///
3750/// Symlinks have no meaningful permission bits, so there is no chmod step;
3751/// ordering is chown → utimens. Gates on `settings.symlink`.
3752pub async fn set_symlink_metadata_fd<Meta: crate::preserve::Metadata>(
3753    settings: &crate::preserve::Settings,
3754    meta: &Meta,
3755    handle: &Handle,
3756    side: congestion::Side,
3757) -> std::io::Result<()> {
3758    let ut = &settings.symlink.user_and_time;
3759    if ut.uid || ut.gid {
3760        let uid = if ut.uid { Some(meta.uid()) } else { None };
3761        let gid = if ut.gid { Some(meta.gid()) } else { None };
3762        // chown the link itself: fchown_handle already operates inode-exact on the O_PATH handle
3763        // via AT_EMPTY_PATH | AT_SYMLINK_NOFOLLOW.
3764        fchown_handle(handle, side, uid, gid).await?;
3765    }
3766    if ut.time {
3767        symlink_utimes_fd(
3768            handle,
3769            side,
3770            meta.atime(),
3771            meta.atime_nsec(),
3772            meta.mtime(),
3773            meta.mtime_nsec(),
3774        )
3775        .await?;
3776    }
3777    Ok(())
3778}
3779
3780// ── helpers ───────────────────────────────────────────────────────────────────
3781
3782/// One blocking job whose queued resources have a defined destruction order.
3783///
3784/// Field order is load-bearing: queued user work may own fds, so it must be dropped before the
3785/// strong admission lease that accounts for them.
3786struct BlockingJob<F> {
3787    work: F,
3788    admission: Option<throttle::BlockingFdAdmissionLease>,
3789}
3790
3791type BlockingJobOutput<T> = (
3792    std::io::Result<T>,
3793    Option<throttle::BlockingFdAdmissionLease>,
3794);
3795
3796impl<F> BlockingJob<F> {
3797    fn run<T>(self) -> BlockingJobOutput<T>
3798    where
3799        F: FnOnce() -> std::io::Result<T>,
3800    {
3801        let Self { work, admission } = self;
3802        (work(), admission)
3803    }
3804}
3805
3806fn take_blocking_job<F>(
3807    shared_job: &std::sync::Mutex<Option<BlockingJob<F>>>,
3808) -> Option<BlockingJob<F>> {
3809    shared_job
3810        .lock()
3811        .unwrap_or_else(std::sync::PoisonError::into_inner)
3812        .take()
3813}
3814
3815/// Wait for a blocking job while retaining control of work that has not started.
3816struct BlockingJobWaiter<F, T> {
3817    shared_job: Arc<std::sync::Mutex<Option<BlockingJob<F>>>>,
3818    handle: tokio::task::JoinHandle<Option<BlockingJobOutput<T>>>,
3819}
3820
3821impl<F, T> std::future::Future for BlockingJobWaiter<F, T> {
3822    type Output = Result<Option<BlockingJobOutput<T>>, tokio::task::JoinError>;
3823
3824    fn poll(
3825        self: std::pin::Pin<&mut Self>,
3826        cx: &mut std::task::Context<'_>,
3827    ) -> std::task::Poll<Self::Output> {
3828        let this = self.get_mut();
3829        std::future::Future::poll(std::pin::Pin::new(&mut this.handle), cx)
3830    }
3831}
3832
3833impl<F, T> Drop for BlockingJobWaiter<F, T> {
3834    fn drop(&mut self) {
3835        let queued_job = take_blocking_job(&self.shared_job);
3836        drop(queued_job);
3837        self.handle.abort();
3838    }
3839}
3840
3841/// Internal entry point for work that inherits any live task-scoped admission.
3842pub(crate) async fn run_fd_admitted_blocking<F, T>(f: F) -> std::io::Result<T>
3843where
3844    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3845    T: Send + 'static,
3846{
3847    // upgrade immediately before submission. if the ambient weak reference has expired (ordinary
3848    // directory recursion dropped its provisional guard), this remains an unadmitted directory
3849    // operation; an admitted outer leaf such as copy -> recursive rm stays represented.
3850    let blocking_admission = FD_ADMISSION
3851        .try_with(throttle::FdAdmission::blocking_lease)
3852        .ok();
3853    run_blocking_job(BlockingJob {
3854        work: f,
3855        admission: blocking_admission,
3856    })
3857    .await
3858}
3859
3860/// Run fd-owning blocking work with an explicitly borrowed OpenFile admission guard.
3861///
3862/// The borrow ensures the guard is live when its blocking lease is acquired. No ambient admission
3863/// scope is needed. Unlimited admission remains a no-op, matching the guard's configured policy.
3864/// The strong lease lives in the blocking task's output, after `result`, so an abandoned returned
3865/// descriptor owner is dropped before the admission slot is released. This boundary adds no rate
3866/// or congestion gating.
3867///
3868/// Until the worker takes the shared job, dropping the waiter synchronously destroys its user work
3869/// before its lease. Once the worker takes it, the job is considered started and runs detached if
3870/// the waiter is cancelled.
3871pub async fn run_fd_admitted_blocking_with<F, T>(
3872    admission: &throttle::OpenFileGuard,
3873    f: F,
3874) -> std::io::Result<T>
3875where
3876    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3877    T: Send + 'static,
3878{
3879    run_blocking_job(BlockingJob {
3880        work: f,
3881        admission: Some(admission.admission().blocking_lease()),
3882    })
3883    .await
3884}
3885
3886async fn run_blocking_job<F, T>(job: BlockingJob<F>) -> std::io::Result<T>
3887where
3888    F: FnOnce() -> std::io::Result<T> + Send + 'static,
3889    T: Send + 'static,
3890{
3891    let shared_job = Arc::new(std::sync::Mutex::new(Some(job)));
3892    let worker_job = Arc::clone(&shared_job);
3893    #[cfg(test)]
3894    crate::testutils::record_blocking_submission();
3895    let handle =
3896        tokio::task::spawn_blocking(move || take_blocking_job(&worker_job).map(BlockingJob::run));
3897    let (result, _blocking_admission) = BlockingJobWaiter { shared_job, handle }
3898        .await
3899        .map_err(std::io::Error::other)?
3900        .expect("blocking job disappeared while its waiter was alive");
3901    result
3902}
3903
3904/// Owns one unclaimed continuation until the worker claims it or either owner cancels it.
3905struct PendingContinuation<C>(Option<Arc<std::sync::Mutex<Option<C>>>>);
3906
3907impl<C> PendingContinuation<C> {
3908    fn claim(&mut self) -> Option<C> {
3909        let shared = self
3910            .0
3911            .take()
3912            .expect("continuation already claimed or cancelled");
3913        shared
3914            .lock()
3915            .unwrap_or_else(std::sync::PoisonError::into_inner)
3916            .take()
3917    }
3918
3919    fn cancel(&mut self) {
3920        let Some(shared) = self.0.take() else {
3921            return;
3922        };
3923        let mut pending = shared
3924            .lock()
3925            .unwrap_or_else(std::sync::PoisonError::into_inner);
3926        // keep the lock until captured descriptors close. A worker that observes cancellation
3927        // can then return without releasing its admission lease ahead of those descriptors.
3928        drop(pending.take());
3929    }
3930
3931    fn disarm(&mut self) {
3932        self.0 = None;
3933    }
3934}
3935
3936impl<C> Drop for PendingContinuation<C> {
3937    fn drop(&mut self) {
3938        self.cancel();
3939    }
3940}
3941
3942pin_project_lite::pin_project! {
3943    /// Cancels pending captures before the canonical waiter's queued-job lease can be released.
3944    struct ContinuationWaiter<F, C> {
3945        continuation: PendingContinuation<C>,
3946        #[pin]
3947        future: F,
3948    }
3949
3950    impl<F, C> PinnedDrop for ContinuationWaiter<F, C> {
3951        fn drop(this: Pin<&mut Self>) {
3952            this.project().continuation.cancel();
3953        }
3954    }
3955}
3956
3957impl<F, C> std::future::Future for ContinuationWaiter<F, C>
3958where
3959    F: std::future::Future,
3960{
3961    type Output = F::Output;
3962
3963    fn poll(
3964        self: std::pin::Pin<&mut Self>,
3965        cx: &mut std::task::Context<'_>,
3966    ) -> std::task::Poll<Self::Output> {
3967        let this = self.project();
3968        let output = this.future.poll(cx);
3969        if output.is_ready() {
3970            // a completed worker has claimed or destroyed the continuation, including unwind
3971            this.continuation.disarm();
3972        }
3973        output
3974    }
3975}
3976
3977async fn run_file_create_and_then<F, C, T>(
3978    side: congestion::Side,
3979    operation: F,
3980    continuation: C,
3981) -> std::io::Result<T>
3982where
3983    F: FnOnce() -> std::io::Result<std::fs::File> + Send + 'static,
3984    C: FnOnce(std::io::Result<std::fs::File>) -> T + Send + 'static,
3985    T: Send + 'static,
3986{
3987    let operation =
3988        prepare_metadata_operation(side, congestion::MetadataOp::OpenCreate, operation).await;
3989    let pending = Arc::new(std::sync::Mutex::new(Some(continuation)));
3990    // the worker owns a second cancellation guard so a panic during creation destroys unclaimed
3991    // captures before the canonical job unwinds and releases its descriptor-admission lease.
3992    let mut worker_continuation = PendingContinuation(Some(Arc::clone(&pending)));
3993    let future = run_fd_admitted_blocking(move || {
3994        let created = operation();
3995        #[cfg(test)]
3996        let _visit = created.as_ref().ok().and_then(|file| {
3997            tests::gate_file_create_stage(file.as_raw_fd(), "before-continuation")
3998        });
3999        // the operation's probe, permit, and execution timing have all finished before this claim
4000        Ok(worker_continuation
4001            .claim()
4002            .map(|continuation| continuation(created)))
4003    });
4004    ContinuationWaiter {
4005        continuation: PendingContinuation(Some(pending)),
4006        future,
4007    }
4008    .await
4009    .map(|output| output.expect("continuation disappeared while its waiter was alive"))
4010}
4011
4012/// Run a blocking metadata syscall closure on the blocking pool, gated by the
4013/// congestion controller for the given side and operation kind.
4014///
4015/// Each per-entry `openat`/`fstatat` is rate-gated, counted against the cwnd permit, and feeds the
4016/// latency probe — the same per-metadata-syscall gating shape used throughout this crate. The cwnd
4017/// guard and probe move into the blocking closure because cancelling the async waiter cannot stop
4018/// a syscall that has started; releasing either in the waiter would undercount the actual in-flight
4019/// work and its latency.
4020pub async fn run_metadata_probed_blocking<F, T>(
4021    side: congestion::Side,
4022    op: congestion::MetadataOp,
4023    f: F,
4024) -> std::io::Result<T>
4025where
4026    F: FnOnce() -> std::io::Result<T> + Send + 'static,
4027    T: Send + 'static,
4028{
4029    let operation = prepare_metadata_operation(side, op, f).await;
4030    run_fd_admitted_blocking(operation).await
4031}
4032
4033async fn prepare_metadata_operation<F, T>(
4034    side: congestion::Side,
4035    op: congestion::MetadataOp,
4036    f: F,
4037) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
4038where
4039    F: FnOnce() -> std::io::Result<T> + Send + 'static,
4040    T: Send + 'static,
4041{
4042    let rate = metadata_timing_scope(side, op, MetadataTimingPhase::Rate);
4043    throttle::get_ops_token().await;
4044    rate.finish();
4045    prepare_metadata_operation_no_rate(side, op, f).await
4046}
4047
4048/// Variant of [`run_metadata_probed_blocking`] for a caller that already consumed the static
4049/// operations-rate token before spawning its task.
4050pub async fn run_metadata_probed_blocking_no_rate<F, T>(
4051    side: congestion::Side,
4052    op: congestion::MetadataOp,
4053    f: F,
4054) -> std::io::Result<T>
4055where
4056    F: FnOnce() -> std::io::Result<T> + Send + 'static,
4057    T: Send + 'static,
4058{
4059    let operation = prepare_metadata_operation_no_rate(side, op, f).await;
4060    run_fd_admitted_blocking(operation).await
4061}
4062
4063async fn prepare_metadata_operation_no_rate<F, T>(
4064    side: congestion::Side,
4065    op: congestion::MetadataOp,
4066    f: F,
4067) -> impl FnOnce() -> std::io::Result<T> + Send + 'static
4068where
4069    F: FnOnce() -> std::io::Result<T> + Send + 'static,
4070    T: Send + 'static,
4071{
4072    let admission = metadata_timing_scope(side, op, MetadataTimingPhase::Admission);
4073    let ops_permit = throttle::ops_in_flight_permit(crate::walk::meta_resource(side, op)).await;
4074    admission.finish();
4075    let probe = congestion::Probe::start_metadata(side, op);
4076    // worker threads do not inherit a task-local subscriber. Retain it only for constructing the
4077    // execution scope; rooted metadata spans own their dispatcher without retaining contextual
4078    // parents whose release would otherwise depend on the worker's ambient subscriber.
4079    let timing_dispatch = tracing::enabled!(target: "rcp::timing", tracing::Level::TRACE)
4080        .then(|| tracing::dispatcher::get_default(Clone::clone));
4081    let queue = metadata_timing_scope(side, op, MetadataTimingPhase::Queue);
4082    move || {
4083        queue.finish();
4084        let execution = timing_dispatch.as_ref().map(|dispatch| {
4085            tracing::dispatcher::with_default(dispatch, || {
4086                metadata_timing_scope(side, op, MetadataTimingPhase::Execute)
4087            })
4088        });
4089        let result = f();
4090        match &result {
4091            Ok(_) => probe.complete_ok(0),
4092            Err(_) => probe.discard(),
4093        }
4094        // the cwnd models syscall concurrency, so release it when `f` finishes. The shared blocking
4095        // boundary keeps admission in the task output because `f` can return an fd that an
4096        // abandoned waiter never receives.
4097        drop(ops_permit);
4098        if let Some(execution) = execution {
4099            execution.finish();
4100        }
4101        result
4102    }
4103}
4104
4105/// Convert a `nix::errno::Errno` to `std::io::Error`.
4106fn nix_to_io(e: nix::errno::Errno) -> std::io::Error {
4107    std::io::Error::from_raw_os_error(e as i32)
4108}
4109
4110/// Return `true` when `name` is a single non-empty path component (no `/`,
4111/// not `.` or `..`).
4112fn is_single_component(name: &OsStr) -> bool {
4113    if name.is_empty() || name == "." || name == ".." {
4114        return false;
4115    }
4116    !name.as_bytes().contains(&b'/')
4117}
4118
4119// ── tests ─────────────────────────────────────────────────────────────────────
4120
4121#[cfg(test)]
4122mod tests {
4123    use super::*;
4124    use crate::preserve::Metadata;
4125    use crate::testutils;
4126    use std::io::Read;
4127    use std::num::NonZeroUsize;
4128
4129    fn read_directory_record(name: &[u8], dtype: libc::c_uchar) -> (DirectoryEntry, usize) {
4130        let name_offset = std::mem::offset_of!(libc::dirent, d_name);
4131        let words = (name_offset + name.len() + 1).div_ceil(std::mem::size_of::<u64>());
4132        let mut storage = vec![0_u64; words].into_boxed_slice();
4133        let allocation_len = std::mem::size_of_val(storage.as_ref());
4134        const { assert!(std::mem::align_of::<u64>() >= std::mem::align_of::<libc::dirent>()) };
4135        let raw = storage.as_mut_ptr().cast::<libc::dirent>();
4136        // SAFETY: aligned, zeroed storage covers the record through the name's NUL. The field
4137        // accesses do not borrow the nominal struct or fixed-size name array
4138        let entry = unsafe {
4139            (*raw).d_type = dtype;
4140            std::ptr::copy_nonoverlapping(
4141                name.as_ptr(),
4142                (&raw mut (*raw).d_name).cast::<u8>(),
4143                name.len(),
4144            );
4145            directory_entry_from_raw(raw)
4146        };
4147        // storage drops before the caller inspects the owned name
4148        (entry, allocation_len)
4149    }
4150
4151    #[test]
4152    fn raw_directory_entry_accepts_short_records() {
4153        let (entry, allocation_len) = read_directory_record(b"f\xff", libc::DT_REG);
4154        assert!(allocation_len < std::mem::size_of::<libc::dirent>());
4155        assert_eq!(entry.name.as_bytes(), b"f\xff");
4156        assert_eq!(entry.kind_hint, Some(EntryKind::File));
4157    }
4158
4159    #[test]
4160    fn raw_directory_entry_accepts_names_beyond_declared_array() {
4161        let mut name = vec![b'x'; 300];
4162        name[7] = 0xff;
4163        let (entry, allocation_len) = read_directory_record(&name, libc::DT_DIR);
4164        assert!(allocation_len > std::mem::size_of::<libc::dirent>());
4165        assert_eq!(entry.name.as_bytes(), name);
4166        assert_eq!(entry.kind_hint, Some(EntryKind::Dir));
4167    }
4168
4169    #[test]
4170    fn failed_stream_construction_closes_the_owned_fd() -> anyhow::Result<()> {
4171        let root_path = tempfile::tempdir()?;
4172        let file_path = root_path.path().join("regular-file");
4173        std::fs::write(&file_path, b"x")?;
4174        let fd: OwnedFd = std::fs::File::open(file_path)?.into();
4175        let raw_fd = fd.as_raw_fd();
4176        let error = OwnedDirectoryStream::from_fd(fd, None).unwrap_err();
4177        assert_eq!(error.raw_os_error(), Some(libc::ENOTDIR));
4178        assert_eq!(unsafe { libc::fcntl(raw_fd, libc::F_GETFD) }, -1);
4179        assert_eq!(
4180            std::io::Error::last_os_error().raw_os_error(),
4181            Some(libc::EBADF)
4182        );
4183        Ok(())
4184    }
4185
4186    #[test]
4187    fn cursor_refreshes_after_waiting_for_the_blocking_pool() -> anyhow::Result<()> {
4188        static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4189            std::sync::LazyLock::new(crate::progress::Progress::new);
4190        tokio::runtime::Builder::new_current_thread()
4191            .enable_all()
4192            .max_blocking_threads(1)
4193            .build()?
4194            .block_on(async {
4195                let tmp = tempfile::tempdir()?;
4196                crate::filegen::write_file(&PROGRESS, tmp.path().join("entry"), 1, 1, 0)
4197                    .await
4198                    .map_err(|error| error.source)?;
4199                let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4200                for dereference in [false, true] {
4201                    let mut cursor = if dereference {
4202                        DirectoryCursor::open_following_symlinks(
4203                            tmp.path(),
4204                            congestion::Side::Source,
4205                            Arc::new(()),
4206                        )
4207                        .await?
4208                    } else {
4209                        root.entries().await?
4210                    };
4211                    let stream = cursor.iterator.as_ref().unwrap();
4212                    let fd = stream.as_fd().try_clone_to_owned()?;
4213                    // a nonseekable stream cannot model an advanced position that must rewind
4214                    match nix::unistd::lseek(&fd, 0, nix::unistd::Whence::SeekCur) {
4215                        Err(nix::errno::Errno::ESPIPE) => continue,
4216                        result => {
4217                            result?;
4218                        }
4219                    }
4220                    let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4221                    let (release_tx, release_rx) = std::sync::mpsc::channel();
4222                    let blocker = tokio::task::spawn_blocking(move || {
4223                        let _ = started_tx.send(());
4224                        let _ = release_rx.recv();
4225                    });
4226                    started_rx.await?;
4227                    let limit = NonZeroUsize::new(1).unwrap();
4228                    let mut read = Box::pin(cursor.next_batch(limit));
4229                    assert!(futures::poll!(read.as_mut()).is_pending());
4230                    // advance the shared kernel position while the read is queued, without
4231                    // filling this cursor's libc buffer or rewinding the duplicate on drop
4232                    assert_eq!(stream_names(fd.try_clone()?)?, ["entry"]);
4233                    assert_ne!(nix::unistd::lseek(&fd, 0, nix::unistd::Whence::SeekCur)?, 0);
4234                    release_tx.send(())?;
4235                    let batch = read.await?;
4236                    blocker.await?;
4237                    assert_eq!(batch.len(), 1, "dereference={dereference}");
4238                    assert_eq!(batch[0].name, "entry");
4239                    assert!(cursor.next_batch(limit).await?.is_empty());
4240                }
4241                anyhow::Ok(())
4242            })
4243    }
4244
4245    #[tokio::test]
4246    async fn cursor_sees_replacement_before_first_batch() -> anyhow::Result<()> {
4247        static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4248            std::sync::LazyLock::new(crate::progress::Progress::new);
4249        let tmp = tempfile::tempdir()?;
4250        let source = tmp.path().join("source");
4251        std::fs::create_dir(&source)?;
4252        let entry = source.join("entry");
4253        crate::filegen::write_file(&PROGRESS, entry.clone(), 1, 1, 0)
4254            .await
4255            .map_err(|error| error.source)?;
4256        let root = Dir::open_root_dir(&source, false, congestion::Side::Source).await?;
4257        for dereference in [false, true] {
4258            let mut cursor = if dereference {
4259                DirectoryCursor::open_following_symlinks(
4260                    &source,
4261                    congestion::Side::Source,
4262                    Arc::new(()),
4263                )
4264                .await?
4265            } else {
4266                root.entries().await?
4267            };
4268            cursor.read_acls(congestion::Side::Source).await?;
4269            let replacement = tmp.path().join("replacement");
4270            crate::filegen::write_file(&PROGRESS, replacement.clone(), 2, 2, 0)
4271                .await
4272                .map_err(|error| error.source)?;
4273            std::fs::rename(replacement, &entry)?;
4274            let batch = cursor.next_batch(NonZeroUsize::new(64).unwrap()).await?;
4275            assert_eq!(batch.len(), 1, "dereference={dereference}");
4276            assert_eq!(batch[0].name, "entry");
4277        }
4278        Ok(())
4279    }
4280
4281    #[tokio::test]
4282    async fn cursor_reads_nonseekable_stream_without_reopening_or_restarting() -> anyhow::Result<()>
4283    {
4284        static PROGRESS: std::sync::LazyLock<crate::progress::Progress> =
4285            std::sync::LazyLock::new(crate::progress::Progress::new);
4286        let tmp = tempfile::tempdir()?;
4287        for name in ["first", "second"] {
4288            crate::filegen::write_file(&PROGRESS, tmp.path().join(name), 1, 1, 0)
4289                .await
4290                .map_err(|error| error.source)?;
4291        }
4292        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4293        let mut cursor = root.entries().await?;
4294        let held_fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4295        let limit = NonZeroUsize::new(1).unwrap();
4296        let first = cursor
4297            .next_batch_with_seek(limit, move |fd| {
4298                assert_eq!(fd.as_raw_fd(), held_fd);
4299                Err(nix::errno::Errno::ESPIPE)
4300            })
4301            .await?;
4302        assert_eq!(cursor.iterator.as_ref().unwrap().as_raw_fd(), held_fd);
4303        let second = cursor
4304            .next_batch_with_seek(limit, |_| panic!("continuing a cursor must not seek again"))
4305            .await?;
4306        let mut names: Vec<_> = first
4307            .into_iter()
4308            .chain(second)
4309            .map(|entry| entry.name)
4310            .collect();
4311        names.sort();
4312        assert_eq!(names, ["first", "second"]);
4313        assert!(
4314            cursor
4315                .next_batch_with_seek(limit, |_| {
4316                    panic!("reaching EOF must not restart the cursor")
4317                })
4318                .await?
4319                .is_empty()
4320        );
4321        Ok(())
4322    }
4323
4324    #[tokio::test]
4325    async fn cursor_seek_failure_releases_credit_and_prevents_restart() -> anyhow::Result<()> {
4326        let tmp = tempfile::tempdir()?;
4327        let credit = Arc::new(());
4328        let remaining = Arc::downgrade(&credit);
4329        let mut cursor =
4330            DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4331                .await?;
4332        let limit = NonZeroUsize::new(1).unwrap();
4333        assert_eq!(
4334            cursor
4335                .next_batch_with_seek(limit, |_| Err(nix::errno::Errno::EIO))
4336                .await
4337                .unwrap_err()
4338                .raw_os_error(),
4339            Some(libc::EIO)
4340        );
4341        assert!(
4342            remaining.upgrade().is_none(),
4343            "failed seek retained descriptor credit"
4344        );
4345        assert!(
4346            cursor.next_batch(limit).await.is_err(),
4347            "failed cursor restarted"
4348        );
4349        Ok(())
4350    }
4351
4352    #[tokio::test]
4353    async fn cursor_eof_never_reads_again_after_empty_short_or_full_batches() -> anyhow::Result<()>
4354    {
4355        for (count, limit, sizes) in [
4356            (0, 3, vec![0]),
4357            (1, 3, vec![1]),
4358            (3, 3, vec![3, 0]),
4359            (4, 3, vec![3, 1]),
4360            (6, 3, vec![3, 3, 0]),
4361            (7, 3, vec![3, 3, 1]),
4362            (150, 64, vec![64, 64, 22]),
4363        ] {
4364            let tmp = tempfile::tempdir()?;
4365            let expected: Vec<_> = (0..count)
4366                .map(|index| std::ffi::OsString::from(format!("file-{index:03}")))
4367                .collect();
4368            for name in &expected {
4369                crate::filegen::write_file(crate::get_progress(), tmp.path().join(name), 1, 1, 0)
4370                    .await
4371                    .map_err(|error| error.source)?;
4372            }
4373            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4374            let mut cursor = root.entries().await?;
4375            let limit = NonZeroUsize::new(limit).unwrap();
4376            let mut names = Vec::new();
4377            for size in sizes {
4378                let batch = cursor.next_batch(limit).await?;
4379                assert_eq!(batch.len(), size, "entry count={count}");
4380                names.extend(batch.into_iter().map(|entry| entry.name));
4381            }
4382            names.sort();
4383            assert_eq!(names, expected);
4384            cursor.read_hook = Some(Box::new(|_, _| {
4385                Err(std::io::Error::other(
4386                    "an EOF cursor issued another directory read",
4387                ))
4388            }));
4389            let submissions = testutils::BlockingSubmissions::start();
4390            for _ in 0..3 {
4391                assert!(cursor.next_batch(limit).await?.is_empty());
4392            }
4393            assert_eq!(submissions.count(), 0, "entry count={count}, limit={limit}");
4394        }
4395        Ok(())
4396    }
4397
4398    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
4399    #[tokio::test]
4400    async fn cursor_eof_retains_its_descriptor_and_credit_for_acl_reads() -> anyhow::Result<()> {
4401        let tmp = tempfile::tempdir()?;
4402        let access = restrictive_access_acl();
4403        let default = permissive_acl();
4404        set_xattr_at(tmp.path(), ACL_ACCESS_XATTR, &access);
4405        set_xattr_at(tmp.path(), ACL_DEFAULT_XATTR, &default);
4406        let credit = Arc::new(());
4407        let remaining = Arc::downgrade(&credit);
4408        let mut cursor =
4409            DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4410                .await?;
4411        let fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4412        let identity = testutils::FdIdentityProbe::capture(fd)?;
4413        let limit = NonZeroUsize::new(64).unwrap();
4414        assert!(cursor.next_batch(limit).await?.is_empty());
4415        assert!(!identity.original_is_closed()?);
4416        assert!(remaining.upgrade().is_some());
4417        let acls = cursor.read_acls(congestion::Side::Source).await?;
4418        assert_eq!(acls.access, Some(access));
4419        assert_eq!(acls.default, Some(default));
4420        assert_eq!(cursor.iterator.as_ref().unwrap().as_raw_fd(), fd);
4421        cursor.read_hook = Some(Box::new(|_, _| {
4422            Err(std::io::Error::other(
4423                "an ACL read cleared the cursor's EOF",
4424            ))
4425        }));
4426        assert!(cursor.next_batch(limit).await?.is_empty());
4427        drop(cursor);
4428        assert!(identity.original_is_closed()?);
4429        assert!(remaining.upgrade().is_none());
4430        Ok(())
4431    }
4432
4433    #[tokio::test]
4434    async fn cursor_eof_does_not_hide_a_later_acl_failure() -> anyhow::Result<()> {
4435        let tmp = tempfile::tempdir()?;
4436        let credit = Arc::new(());
4437        let remaining = Arc::downgrade(&credit);
4438        let mut cursor =
4439            DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4440                .await?;
4441        let identity =
4442            testutils::FdIdentityProbe::capture(cursor.iterator.as_ref().unwrap().as_raw_fd())?;
4443        let limit = NonZeroUsize::new(64).unwrap();
4444        assert!(cursor.next_batch(limit).await?.is_empty());
4445        let _failure = testutils::BlockingPathGate::fail_once(tmp.path(), libc::EIO);
4446        assert_eq!(
4447            cursor
4448                .read_acls(congestion::Side::Source)
4449                .await
4450                .unwrap_err()
4451                .raw_os_error(),
4452            Some(libc::EIO)
4453        );
4454        assert!(identity.original_is_closed()?);
4455        assert!(remaining.upgrade().is_none());
4456        assert!(
4457            cursor.next_batch(limit).await.is_err(),
4458            "failed cursor became successful EOF"
4459        );
4460        Ok(())
4461    }
4462
4463    #[tokio::test]
4464    async fn cursor_eof_does_not_hide_a_cancelled_acl_read() -> anyhow::Result<()> {
4465        let tmp = tempfile::tempdir()?;
4466        let credits = Arc::new(tokio::sync::Semaphore::new(1));
4467        let credit = Arc::new(credits.clone().acquire_owned().await?);
4468        let mut cursor =
4469            DirectoryCursor::open_following_symlinks(tmp.path(), congestion::Side::Source, credit)
4470                .await?;
4471        let identity =
4472            testutils::FdIdentityProbe::capture(cursor.iterator.as_ref().unwrap().as_raw_fd())?;
4473        let limit = NonZeroUsize::new(64).unwrap();
4474        assert!(cursor.next_batch(limit).await?.is_empty());
4475        let mut gate = testutils::BlockingPathGate::install(tmp.path());
4476        let mut read = Box::pin(cursor.read_acls(congestion::Side::Source));
4477        assert!(futures::poll!(read.as_mut()).is_pending());
4478        tokio::time::timeout(std::time::Duration::from_secs(20), gate.wait_started()).await??;
4479        drop(read);
4480        let descriptor_retained = !identity.original_is_closed()?;
4481        let credit_retained = credits.available_permits() == 0;
4482        let result = cursor.next_batch(limit).await;
4483        gate.release_all();
4484        let returned =
4485            tokio::time::timeout(std::time::Duration::from_secs(20), credits.acquire()).await??;
4486        assert!(descriptor_retained, "started ACL read lost its descriptor");
4487        assert!(credit_retained, "started ACL read lost its credit");
4488        assert!(result.is_err(), "cancelled cursor became successful EOF");
4489        assert!(identity.original_is_closed()?);
4490        drop(returned);
4491        Ok(())
4492    }
4493
4494    #[tokio::test]
4495    async fn cursor_handles_empty_and_non_utf8_names() -> anyhow::Result<()> {
4496        use std::os::unix::ffi::OsStringExt;
4497
4498        let root_path = testutils::create_temp_dir().await?;
4499        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4500        let mut empty = root.entries().await?;
4501        assert!(
4502            empty
4503                .next_batch(NonZeroUsize::new(1).unwrap())
4504                .await?
4505                .is_empty()
4506        );
4507
4508        let name = std::ffi::OsString::from_vec(vec![b'n', 0xff]);
4509        tokio::fs::write(root_path.join(&name), b"x").await?;
4510        let mut cursor = root.entries().await?;
4511        let batch = cursor.next_batch(NonZeroUsize::new(1).unwrap()).await?;
4512        assert_eq!(batch.len(), 1);
4513        assert_eq!(batch[0].name, name);
4514        assert_eq!(batch[0].kind_hint, Some(EntryKind::File));
4515        assert!(
4516            cursor
4517                .next_batch(NonZeroUsize::new(1).unwrap())
4518                .await?
4519                .is_empty()
4520        );
4521        Ok(())
4522    }
4523
4524    struct RestoreDirectoryAccess<'a>(&'a Dir);
4525
4526    impl Drop for RestoreDirectoryAccess<'_> {
4527        fn drop(&mut self) {
4528            // allow fixture cleanup even after an assertion fails or its path was renamed
4529            let _ = fchmod(self.0.fd.as_fd(), Mode::from_bits_truncate(0o700));
4530        }
4531    }
4532
4533    fn directory_search_permission_is_enforced(dir: &Dir) -> anyhow::Result<bool> {
4534        match openat(
4535            dir.fd.as_fd(),
4536            c".",
4537            OFlag::O_RDONLY | OFlag::O_DIRECTORY | OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC,
4538            Mode::empty(),
4539        ) {
4540            Err(nix::errno::Errno::EACCES) => Ok(true),
4541            Err(error) => Err(error.into()),
4542            Ok(_) => {
4543                eprintln!("skipping: capability overrides bypass directory search permission");
4544                Ok(false)
4545            }
4546        }
4547    }
4548
4549    #[tokio::test]
4550    async fn reopen_fails_when_read_permission_is_revoked() -> anyhow::Result<()> {
4551        let tmp = tempfile::tempdir()?;
4552        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4553        let _restore = RestoreDirectoryAccess(&root);
4554        fchmod(root.fd.as_fd(), Mode::empty())?;
4555        if !directory_search_permission_is_enforced(&root)? {
4556            return Ok(());
4557        }
4558        let error = root
4559            .entries()
4560            .await
4561            .err()
4562            .expect("unreadable directory reopened");
4563        assert_eq!(error.raw_os_error(), Some(libc::EACCES));
4564        let error = root
4565            .fd
4566            .listing_fd_with_seek(|_| Err(nix::errno::Errno::ESPIPE))
4567            .unwrap_err();
4568        assert_eq!(error.raw_os_error(), Some(libc::EACCES));
4569        Ok(())
4570    }
4571
4572    #[tokio::test]
4573    async fn reopen_distinguishes_unusable_proc_from_operational_failures() -> anyhow::Result<()> {
4574        use nix::errno::Errno;
4575
4576        let tmp = tempfile::tempdir()?;
4577        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4578        let _restore = RestoreDirectoryAccess(&root);
4579        fchmod(root.fd.as_fd(), Mode::from_bits_truncate(0o444))?;
4580        if !directory_search_permission_is_enforced(&root)? {
4581            return Ok(());
4582        }
4583        // inject the proc open failure without requiring a private mount namespace;
4584        // the initial dot open still exercises the real directory permission check
4585        for (proc_error, expected) in [
4586            (Errno::ENOENT, Errno::EACCES),
4587            (Errno::ENOTDIR, Errno::EACCES),
4588            (Errno::ELOOP, Errno::EACCES),
4589            (Errno::EACCES, Errno::EACCES),
4590            (Errno::EMFILE, Errno::EMFILE),
4591            (Errno::ENFILE, Errno::ENFILE),
4592            (Errno::ENOMEM, Errno::ENOMEM),
4593            (Errno::EIO, Errno::EIO),
4594        ] {
4595            let error = root
4596                .fd
4597                .reopen_with_proc_open(|_, _| Err(proc_error))
4598                .unwrap_err();
4599            assert_eq!(error.raw_os_error(), Some(expected as i32), "{proc_error}");
4600        }
4601        Ok(())
4602    }
4603
4604    #[tokio::test]
4605    async fn independent_cursors_do_not_share_directory_offsets() -> anyhow::Result<()> {
4606        let expected: Vec<_> = (0..80)
4607            .map(|index| std::ffi::OsString::from(format!("file-{index:02}")))
4608            .collect();
4609        for mode in [None, Some(0o444)] {
4610            let tmp = tempfile::tempdir()?;
4611            for name in &expected {
4612                std::fs::write(tmp.path().join(name), b"content")?;
4613            }
4614            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
4615            let _restore = RestoreDirectoryAccess(&root);
4616            exhaust_shared_directory_offset(&root)?;
4617            let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
4618            if let Some(mode) = mode {
4619                fchmod(root.fd.as_fd(), Mode::from_bits_truncate(mode))?;
4620                if !directory_search_permission_is_enforced(&root)? {
4621                    continue;
4622                }
4623            }
4624            let mut first = root.entries().await?;
4625            let mut second = root.entries().await?;
4626            // inspect kernel positions before first-read seeks and buffering can hide sharing
4627            let position = |cursor: &DirectoryCursor| {
4628                nix::unistd::lseek(
4629                    cursor.iterator.as_ref().unwrap().as_fd(),
4630                    0,
4631                    nix::unistd::Whence::SeekCur,
4632                )
4633            };
4634            let first_start = position(&first);
4635            let second_start = position(&second);
4636            for (name, start) in [("first", first_start), ("second", second_start)] {
4637                if start != Err(nix::errno::Errno::ESPIPE) {
4638                    assert_eq!(
4639                        start,
4640                        Ok(0),
4641                        "{name} cursor inherited an offset, mode={mode:?}"
4642                    );
4643                }
4644            }
4645            let limit = NonZeroUsize::new(64).unwrap();
4646            let first_batch = first.next_batch(limit).await?;
4647            assert_eq!(
4648                position(&second),
4649                second_start,
4650                "reading the first cursor moved the second, mode={mode:?}"
4651            );
4652            let second_batch = second.next_batch(limit).await?;
4653            for (mut cursor, batch) in [(first, first_batch), (second, second_batch)] {
4654                let rest = cursor.next_batch(limit).await?;
4655                let mut names: Vec<_> = batch
4656                    .into_iter()
4657                    .chain(rest)
4658                    .map(|entry| entry.name)
4659                    .collect();
4660                names.sort();
4661                assert_eq!(names, expected, "mode={mode:?}");
4662                assert!(cursor.next_batch(limit).await?.is_empty());
4663            }
4664            assert_eq!(
4665                nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
4666                end
4667            );
4668        }
4669        Ok(())
4670    }
4671
4672    #[tokio::test]
4673    async fn cursor_failure_after_a_partial_read_does_not_restart() -> anyhow::Result<()> {
4674        let root_path = testutils::create_temp_dir().await?;
4675        for index in 0..3 {
4676            tokio::fs::write(root_path.join(format!("file-{index}")), b"x").await?;
4677        }
4678        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4679        let mut cursor = root.entries().await?;
4680        let fd = cursor.iterator.as_ref().unwrap().as_raw_fd();
4681        cursor.read_hook = Some(Box::new(|accepted, _| {
4682            if accepted == 1 {
4683                Err(std::io::Error::from_raw_os_error(libc::EIO))
4684            } else {
4685                Ok(())
4686            }
4687        }));
4688        let limit = NonZeroUsize::new(64).unwrap();
4689        assert_eq!(
4690            cursor.next_batch(limit).await.unwrap_err().raw_os_error(),
4691            Some(libc::EIO)
4692        );
4693        assert!(
4694            cursor.next_batch(limit).await.is_err(),
4695            "a failed cursor restarted"
4696        );
4697        assert_eq!(
4698            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4699            -1,
4700            "failed cursor leaked its fd"
4701        );
4702
4703        let mut independent = root.entries().await?;
4704        assert_eq!(independent.next_batch(limit).await?.len(), 3);
4705        Ok(())
4706    }
4707
4708    #[tokio::test]
4709    async fn cancelled_admitted_batch_retains_its_fd_and_admission_until_exit() -> anyhow::Result<()>
4710    {
4711        use anyhow::Context;
4712        use std::time::Duration;
4713
4714        let root_path = testutils::create_temp_dir().await?;
4715        let root = Dir::open_root_dir(&root_path, false, congestion::Side::Source).await?;
4716        let mut inspect = root.entries().await?;
4717        let mut raw_names = [
4718            inspect
4719                .iterator
4720                .as_mut()
4721                .unwrap()
4722                .next_raw_entry()?
4723                .unwrap()
4724                .name,
4725            inspect
4726                .iterator
4727                .as_mut()
4728                .unwrap()
4729                .next_raw_entry()?
4730                .unwrap()
4731                .name,
4732        ];
4733        raw_names.sort();
4734        assert_eq!(
4735            raw_names,
4736            [
4737                std::ffi::OsString::from("."),
4738                std::ffi::OsString::from("..")
4739            ]
4740        );
4741        assert!(
4742            inspect
4743                .iterator
4744                .as_mut()
4745                .unwrap()
4746                .next_raw_entry()?
4747                .is_none()
4748        );
4749        let mut cursor = root.entries().await?;
4750        let admission = testutils::AdmissionLimit::new().await;
4751        admission.set_files_in_flight(1);
4752        let guard = throttle::open_file_permit().await;
4753        let fd_admission = guard.admission();
4754        let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4755        let (release_tx, release_rx) = std::sync::mpsc::channel();
4756        let mut started_tx = Some(started_tx);
4757        let raw_reads = Arc::new(std::sync::atomic::AtomicUsize::new(0));
4758        let observed_raw_reads = Arc::clone(&raw_reads);
4759        cursor.read_hook = Some(Box::new(move |_, fd| {
4760            observed_raw_reads.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
4761            if let Some(started_tx) = started_tx.take() {
4762                let _ = started_tx.send(fd);
4763                release_rx.recv().map_err(std::io::Error::other)?;
4764            }
4765            Ok(())
4766        }));
4767        let task = tokio::spawn(async move {
4768            with_fd_admission(fd_admission, async move {
4769                let _guard = guard;
4770                cursor.next_batch(NonZeroUsize::new(1).unwrap()).await
4771            })
4772            .await
4773        });
4774        let fd = started_rx.await.context("blocking batch did not start")?;
4775        task.abort();
4776        assert!(task.await.unwrap_err().is_cancelled());
4777        assert_ne!(
4778            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4779            -1,
4780            "cancelled batch lost its owned fd"
4781        );
4782        let mut second = Box::pin(throttle::open_file_permit());
4783        assert!(
4784            futures::poll!(second.as_mut()).is_pending(),
4785            "admission released before read exited"
4786        );
4787        release_tx
4788            .send(())
4789            .context("blocking batch ended before release")?;
4790        let permit = admission
4791            .run_with_timeout(Duration::from_secs(20), second)
4792            .await
4793            .context("admission was not released after blocking batch exited")?;
4794        drop(permit);
4795        assert_eq!(
4796            unsafe { libc::fcntl(fd, libc::F_GETFD) },
4797            -1,
4798            "cancelled batch leaked its fd"
4799        );
4800        assert!(
4801            raw_reads.load(std::sync::atomic::Ordering::SeqCst) >= 3,
4802            "the blocking job stopped before reading past dot entries; raw reads: {}",
4803            raw_reads.load(std::sync::atomic::Ordering::SeqCst)
4804        );
4805        Ok(())
4806    }
4807
4808    const EVERY_KIND: [EntryKind; 4] = [
4809        EntryKind::File,
4810        EntryKind::Dir,
4811        EntryKind::Symlink,
4812        EntryKind::Special,
4813    ];
4814
4815    pub(super) fn gate_file_create_stage(
4816        fd: RawFd,
4817        stage: &str,
4818    ) -> Option<testutils::BlockingPathGateVisit> {
4819        let path = std::fs::read_link(format!("/proc/self/fd/{fd}")).ok()?;
4820        testutils::wait_on_blocking_path_gate(&path.join(stage), fd)
4821    }
4822
4823    pub(super) fn gate_unlink(
4824        fd: RawFd,
4825        name: &OsStr,
4826    ) -> std::io::Result<Option<testutils::BlockingPathGateVisit>> {
4827        let path = std::fs::read_link(format!("/proc/self/fd/{fd}"))?;
4828        testutils::wait_on_blocking_path_gate(&path.join(name).join(".rcp-unlink"), fd)
4829            .map(testutils::BlockingPathGateVisit::into_result)
4830            .transpose()
4831    }
4832
4833    mod max_files_in_flight_tests {
4834        use super::*;
4835        use anyhow::Context as _;
4836        use futures::FutureExt as _;
4837
4838        struct BlockingDropFd {
4839            _file: std::fs::File,
4840            drop_started: Option<tokio::sync::oneshot::Sender<()>>,
4841            release_drop: std::sync::mpsc::Receiver<()>,
4842            _completion: crate::testutils::CompletionSignal,
4843        }
4844
4845        impl AsRawFd for BlockingDropFd {
4846            fn as_raw_fd(&self) -> RawFd {
4847                self._file.as_raw_fd()
4848            }
4849        }
4850
4851        impl Drop for BlockingDropFd {
4852            fn drop(&mut self) {
4853                if let Some(drop_started) = self.drop_started.take() {
4854                    let _ = drop_started.send(());
4855                }
4856                self.release_drop
4857                    .recv()
4858                    .expect("drop release sender must stay alive");
4859            }
4860        }
4861
4862        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
4863        struct QueuedFdDropObservation {
4864            fd_was_closed: bool,
4865            admission_was_retained: bool,
4866        }
4867
4868        struct QueuedFdCapture {
4869            file: Option<std::fs::File>,
4870            probe: crate::testutils::FdIdentityProbe,
4871            observation: Arc<std::sync::Mutex<Option<std::io::Result<QueuedFdDropObservation>>>>,
4872        }
4873
4874        impl AsRawFd for QueuedFdCapture {
4875            fn as_raw_fd(&self) -> RawFd {
4876                self.file
4877                    .as_ref()
4878                    .expect("captured file must be present")
4879                    .as_raw_fd()
4880            }
4881        }
4882
4883        impl Drop for QueuedFdCapture {
4884            fn drop(&mut self) {
4885                drop(self.file.take());
4886                let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
4887                *self
4888                    .observation
4889                    .lock()
4890                    .expect("queued fd drop observation lock poisoned") =
4891                    Some(self.probe.original_is_closed().map(|fd_was_closed| {
4892                        QueuedFdDropObservation {
4893                            fd_was_closed,
4894                            admission_was_retained,
4895                        }
4896                    }));
4897            }
4898        }
4899
4900        async fn assert_queued_owner_closes_before_admission<Fut>(
4901            operation: impl FnOnce(QueuedFdCapture) -> Fut,
4902        ) -> anyhow::Result<()>
4903        where
4904            Fut: std::future::Future,
4905        {
4906            let source = tempfile::tempfile()?;
4907            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
4908            let observation = Arc::new(std::sync::Mutex::new(None));
4909            let capture = QueuedFdCapture {
4910                file: Some(source),
4911                probe,
4912                observation: Arc::clone(&observation),
4913            };
4914            let limits = testutils::AdmissionLimit::new().await;
4915            limits.set_files_in_flight(1);
4916            let guard = throttle::open_file_permit().await;
4917            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
4918            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
4919            let blocker = tokio::task::spawn_blocking(move || {
4920                let _ = started_tx.send(());
4921                let _ = release_rx.recv();
4922            });
4923            started_rx.await?;
4924            let mut work = Box::pin(with_fd_admission(guard.admission(), operation(capture)));
4925            let queued = futures::poll!(work.as_mut()).is_pending();
4926            // leave the queued job as the only strong admission owner before dropping it
4927            drop(guard);
4928            drop(work);
4929            let closed_before_release = probe.original_is_closed();
4930            let drop_observation = observation.lock().unwrap().take().transpose();
4931            let mut next_file = Box::pin(throttle::open_file_permit());
4932            let returned = next_file.as_mut().now_or_never();
4933            let capacity_returned_before_release = returned.is_some();
4934            // collect failures only after releasing and joining the occupied worker
4935            drop(release_tx);
4936            blocker.await?;
4937            tokio::task::spawn_blocking(|| ()).await?;
4938            let permit = match returned {
4939                Some(permit) => permit,
4940                None => tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?,
4941            };
4942            drop(permit);
4943            assert!(
4944                queued,
4945                "the operation must queue behind the occupied worker"
4946            );
4947            assert!(
4948                closed_before_release?,
4949                "queued cancellation retained its fd"
4950            );
4951            assert!(capacity_returned_before_release);
4952            assert_eq!(
4953                drop_observation?,
4954                Some(QueuedFdDropObservation {
4955                    fd_was_closed: true,
4956                    admission_was_retained: true,
4957                }),
4958                "queued cancellation must close its fd before returning admission"
4959            );
4960            Ok(())
4961        }
4962
4963        #[test]
4964        fn cancelled_queued_owned_acl_read_closes_source_before_returning_admission()
4965        -> anyhow::Result<()> {
4966            tokio::runtime::Builder::new_current_thread()
4967                .max_blocking_threads(1)
4968                .enable_all()
4969                .build()?
4970                .block_on(assert_queued_owner_closes_before_admission(|owner| {
4971                    read_acls_owned(owner, congestion::Side::Source, false)
4972                }))
4973        }
4974
4975        async fn assert_abandoned_output_closes_before_admission<Fut, T>(
4976            operation: impl FnOnce(BlockingDropFd) -> Fut + Send + 'static,
4977        ) -> anyhow::Result<()>
4978        where
4979            Fut: std::future::Future<Output = T> + Send + 'static,
4980            T: Send + 'static,
4981        {
4982            let tmp = tempfile::tempdir()?;
4983            let path = tmp.path().join("returned-owner");
4984            std::fs::write(&path, b"payload")?;
4985            let file = std::fs::File::open(&path)?;
4986            let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
4987            let mut gate = testutils::BlockingPathGate::install(&path);
4988            let limits = testutils::AdmissionLimit::new().await;
4989            limits.set_files_in_flight(1);
4990            let guard = throttle::open_file_permit().await;
4991            let (drop_started_tx, drop_started_rx) = tokio::sync::oneshot::channel();
4992            let (release_drop_tx, release_drop_rx) = std::sync::mpsc::channel();
4993            let (completion, completion_rx) = testutils::CompletionSignal::new();
4994            let owner = BlockingDropFd {
4995                _file: file,
4996                drop_started: Some(drop_started_tx),
4997                release_drop: release_drop_rx,
4998                _completion: completion,
4999            };
5000            let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
5001                let _guard = guard;
5002                operation(owner).await
5003            }));
5004            let started = gate.wait_started().await;
5005            task.abort();
5006            let cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5007            gate.release_all();
5008            let dropping = drop_started_rx.await;
5009            let admission_retained = throttle::open_file_permit().now_or_never().is_none();
5010            let fd_retained = probe.original_is_closed().map(|closed| !closed);
5011            let released = release_drop_tx.send(());
5012            let (completed, permit) = testutils::await_completion_and_capacity(
5013                completion_rx,
5014                throttle::open_file_permit(),
5015            )
5016            .await;
5017            drop(permit);
5018            started?;
5019            dropping?;
5020            released?;
5021            completed?;
5022            assert!(cancelled, "the async waiter must observe cancellation");
5023            assert!(
5024                admission_retained,
5025                "admission was released before the abandoned returned fd was dropped"
5026            );
5027            assert!(fd_retained?);
5028            assert!(probe.original_is_closed()?);
5029            Ok(())
5030        }
5031
5032        #[tokio::test]
5033        async fn abandoned_owned_acl_output_closes_source_before_returning_admission()
5034        -> anyhow::Result<()> {
5035            assert_abandoned_output_closes_before_admission(|owner| {
5036                read_acls_owned(owner, congestion::Side::Source, false)
5037            })
5038            .await
5039        }
5040
5041        #[test]
5042        fn cancelled_queued_file_creation_drops_payload_before_admission_without_creating()
5043        -> anyhow::Result<()> {
5044            let runtime = tokio::runtime::Builder::new_current_thread()
5045                .max_blocking_threads(1)
5046                .enable_all()
5047                .build()?;
5048            runtime.block_on(async {
5049                let tmp = tempfile::tempdir()?;
5050                let root =
5051                    Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5052                let destination = tmp.path().join("destination");
5053                let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5054                let continuation_called = Arc::clone(&called);
5055                assert_queued_owner_closes_before_admission(|owner| async move {
5056                    root.create_file_and_then(OsStr::new("destination"), move |created| {
5057                        let _owner = owner;
5058                        continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5059                        created
5060                    })
5061                    .await
5062                })
5063                .await?;
5064                assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5065                assert!(
5066                    !destination.exists(),
5067                    "cancelled queued work created a destination"
5068                );
5069                Ok(())
5070            })
5071        }
5072
5073        async fn cancelled_unclaimed_file_continuation_case(
5074            stage: &str,
5075            strict: bool,
5076        ) -> anyhow::Result<()> {
5077            use std::os::unix::fs::PermissionsExt as _;
5078            let tmp = tempfile::tempdir()?;
5079            if strict {
5080                set_xattr_at(tmp.path(), ACL_DEFAULT_XATTR, &permissive_acl());
5081            }
5082            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5083            let destination = tmp.path().join("destination");
5084            let source = tempfile::tempfile()?;
5085            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5086            let observation = Arc::new(std::sync::Mutex::new(None));
5087            let capture = QueuedFdCapture {
5088                file: Some(source),
5089                probe: source_probe,
5090                observation: Arc::clone(&observation),
5091            };
5092            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5093            let continuation_called = Arc::clone(&called);
5094            let gate = testutils::BlockingPathGate::install(destination.join(stage));
5095            let limits = testutils::AdmissionLimit::new().await;
5096            limits.set_files_in_flight(1);
5097            let resource = throttle::Resource::meta(
5098                throttle::Side::Destination,
5099                throttle::MetadataOp::OpenCreate,
5100            );
5101            limits.set_max_ops_in_flight(resource, 1);
5102            let samples = Arc::new(congestion::testing::CollectingSink::new());
5103            congestion::install_sample_sink(samples.clone());
5104            let guard = throttle::open_file_permit().await;
5105            let admission = guard.admission();
5106            let task = tokio::spawn(with_fd_admission(admission, async move {
5107                let _guard = guard;
5108                let continuation = move |created| {
5109                    let _capture = capture;
5110                    continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5111                    created
5112                };
5113                if strict {
5114                    let operation = root.file_create_operation(OsStr::new("destination"), true)?;
5115                    run_file_create_and_then(congestion::Side::Destination, operation, continuation)
5116                        .await
5117                } else {
5118                    root.create_file_and_then(OsStr::new("destination"), continuation)
5119                        .await
5120                }
5121            }));
5122            let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
5123            let (
5124                cancelled,
5125                (
5126                    created_probe,
5127                    source_closed,
5128                    mode,
5129                    acquired_operation,
5130                    sample_count,
5131                    inherited_acl,
5132                ),
5133            ) = testutils::cancel_at_blocking_path(
5134                limits,
5135                gate,
5136                task,
5137                std::time::Duration::from_secs(20),
5138                |fd| {
5139                    (
5140                        testutils::FdIdentityProbe::capture(fd),
5141                        source_probe.original_is_closed(),
5142                        std::fs::metadata(&destination)
5143                            .map(|meta| meta.permissions().mode() & 0o7777),
5144                        next_operation.as_mut().now_or_never(),
5145                        samples.metadata_count(),
5146                        strict.then(|| get_xattr_at(&destination, ACL_ACCESS_XATTR).is_some()),
5147                    )
5148                },
5149            )
5150            .await?;
5151            let operation_was_finished = acquired_operation.is_some();
5152            let permit = match acquired_operation {
5153                Some(permit) => permit,
5154                None => {
5155                    tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?
5156                }
5157            };
5158            drop(permit);
5159            assert!(cancelled.waiter_was_cancelled);
5160            assert!(cancelled.admission_was_retained_while_work_gated);
5161            assert!(cancelled.fd_was_open_while_work_gated);
5162            assert!(
5163                source_closed?,
5164                "unclaimed payload retained its captured source after cancellation"
5165            );
5166            assert_eq!(mode?, DST_FILE_CREATE_MODE);
5167            assert_eq!(operation_was_finished, stage == "before-continuation");
5168            assert_eq!(sample_count, usize::from(stage == "before-continuation"));
5169            assert_eq!(samples.metadata_count(), 1);
5170            assert!(created_probe?.original_is_closed()?);
5171            assert_eq!(
5172                observation.lock().unwrap().take().transpose()?,
5173                Some(QueuedFdDropObservation {
5174                    fd_was_closed: true,
5175                    admission_was_retained: true,
5176                })
5177            );
5178            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5179            assert_eq!(cancelled.final_hit_count, 1);
5180            assert_eq!(
5181                std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
5182                DST_FILE_CREATE_MODE
5183            );
5184            assert_eq!(std::fs::metadata(&destination)?.len(), 0);
5185            if strict {
5186                assert_eq!(inherited_acl, Some(stage == "before-sanitation"));
5187                assert_eq!(get_xattr_at(&destination, ACL_ACCESS_XATTR), None);
5188            }
5189            Ok(())
5190        }
5191
5192        #[tokio::test]
5193        async fn cancelled_created_file_never_starts_an_unclaimed_payload() -> anyhow::Result<()> {
5194            for stage in ["before-sanitation", "before-continuation"] {
5195                cancelled_unclaimed_file_continuation_case(stage, false).await?;
5196            }
5197            Ok(())
5198        }
5199
5200        #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
5201        #[tokio::test]
5202        async fn cancelled_file_creation_finishes_acl_sanitation_without_starting_payload()
5203        -> anyhow::Result<()> {
5204            for stage in ["before-sanitation", "before-continuation"] {
5205                cancelled_unclaimed_file_continuation_case(stage, true).await?;
5206            }
5207            Ok(())
5208        }
5209
5210        async fn cancelled_claimed_file_continuation_case(
5211            fail_payload: bool,
5212        ) -> anyhow::Result<()> {
5213            use std::io::{Seek as _, Write as _};
5214            use std::os::unix::fs::PermissionsExt as _;
5215            let tmp = tempfile::tempdir()?;
5216            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5217            let destination = tmp.path().join("destination");
5218            let mut source = tempfile::tempfile()?;
5219            source.write_all(b"complete payload")?;
5220            source.rewind()?;
5221            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5222            let gate = testutils::BlockingPathGate::install(&destination);
5223            let limits = testutils::AdmissionLimit::new().await;
5224            limits.set_files_in_flight(1);
5225            let resource = throttle::Resource::meta(
5226                throttle::Side::Destination,
5227                throttle::MetadataOp::OpenCreate,
5228            );
5229            limits.set_max_ops_in_flight(resource, 1);
5230            let samples = Arc::new(congestion::testing::CollectingSink::new());
5231            congestion::install_sample_sink(samples.clone());
5232            let guard = throttle::open_file_permit().await;
5233            let admission = guard.admission();
5234            let data_path = destination.clone();
5235            let task = tokio::spawn(with_fd_admission(admission, async move {
5236                let _guard = guard;
5237                root.create_file_and_then(OsStr::new("destination"), move |created| {
5238                    let mut file = created?;
5239                    let visit = testutils::wait_on_blocking_path_gate(&data_path, file.as_raw_fd());
5240                    let copied = if fail_payload {
5241                        file.write_all(b"partial")
5242                            .and_then(|()| Err(std::io::Error::from_raw_os_error(libc::EIO)))
5243                    } else {
5244                        std::io::copy(&mut source, &mut file).map(|_| ())
5245                    };
5246                    std::io::Result::Ok((copied, source, file, visit))
5247                })
5248                .await
5249            }));
5250            let (cancelled, (source_open, mode, operation_available, sample_count)) =
5251                testutils::cancel_at_blocking_path(
5252                    limits,
5253                    gate,
5254                    task,
5255                    std::time::Duration::from_secs(20),
5256                    |_| {
5257                        (
5258                            source_probe.original_is_closed().map(|closed| !closed),
5259                            std::fs::metadata(&destination)
5260                                .map(|meta| meta.permissions().mode() & 0o7777),
5261                            throttle::ops_in_flight_permit(resource)
5262                                .now_or_never()
5263                                .is_some(),
5264                            samples.metadata_count(),
5265                        )
5266                    },
5267                )
5268                .await?;
5269            assert!(cancelled.waiter_was_cancelled);
5270            assert!(cancelled.admission_was_retained_while_work_gated);
5271            assert!(cancelled.fd_was_open_while_work_gated && source_open?);
5272            assert!(cancelled.fd_was_closed_at_output_drop_start);
5273            assert!(cancelled.admission_was_retained_at_output_drop_start);
5274            assert!(source_probe.original_is_closed()?);
5275            assert!(
5276                operation_available,
5277                "payload retained the OpenCreate operation permit"
5278            );
5279            assert_eq!(
5280                sample_count, 1,
5281                "payload started before its metadata probe finished"
5282            );
5283            assert_eq!(samples.metadata_count(), 1);
5284            assert_eq!(cancelled.final_hit_count, 1);
5285            assert_eq!(mode?, DST_FILE_CREATE_MODE);
5286            assert_eq!(
5287                std::fs::metadata(&destination)?.permissions().mode() & 0o7777,
5288                DST_FILE_CREATE_MODE
5289            );
5290            assert_eq!(
5291                std::fs::read(destination)?,
5292                if fail_payload {
5293                    b"partial".as_slice()
5294                } else {
5295                    b"complete payload".as_slice()
5296                }
5297            );
5298            Ok(())
5299        }
5300
5301        #[tokio::test]
5302        async fn cancelled_started_file_continuation_keeps_fds_until_abandoned_output_drops()
5303        -> anyhow::Result<()> {
5304            cancelled_claimed_file_continuation_case(false).await
5305        }
5306
5307        #[tokio::test]
5308        async fn cancelled_failed_file_continuation_keeps_fds_until_abandoned_output_drops()
5309        -> anyhow::Result<()> {
5310            cancelled_claimed_file_continuation_case(true).await
5311        }
5312
5313        #[tokio::test]
5314        async fn panicking_file_create_closes_unclaimed_payload_before_its_admission_lease()
5315        -> anyhow::Result<()> {
5316            let source = tempfile::tempfile()?;
5317            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5318            let observation = Arc::new(std::sync::Mutex::new(None));
5319            let capture = QueuedFdCapture {
5320                file: Some(source),
5321                probe,
5322                observation: Arc::clone(&observation),
5323            };
5324            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5325            let continuation_called = Arc::clone(&called);
5326            let limits = testutils::AdmissionLimit::new().await;
5327            limits.set_files_in_flight(1);
5328            let guard = throttle::open_file_permit().await;
5329            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5330            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
5331            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5332                run_file_create_and_then(
5333                    congestion::Side::Destination,
5334                    move || -> std::io::Result<std::fs::File> {
5335                        let _ = started_tx.send(());
5336                        let _ = release_rx.recv();
5337                        panic!("injected file-create panic");
5338                    },
5339                    move |_created| {
5340                        let _capture = capture;
5341                        continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5342                    },
5343                )
5344                .await
5345            }));
5346            let pending = futures::poll!(work.as_mut()).is_pending();
5347            drop(guard);
5348            let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
5349            drop(release_tx);
5350            let result = work.await;
5351            assert!(pending);
5352            started??;
5353            assert!(result.is_err(), "worker panic must fail the create waiter");
5354            assert!(probe.original_is_closed()?);
5355            assert_eq!(
5356                observation.lock().unwrap().take().transpose()?,
5357                Some(QueuedFdDropObservation {
5358                    fd_was_closed: true,
5359                    admission_was_retained: true,
5360                })
5361            );
5362            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5363            let permit = tokio::time::timeout(
5364                std::time::Duration::from_secs(5),
5365                throttle::open_file_permit(),
5366            )
5367            .await?;
5368            drop(permit);
5369            Ok(())
5370        }
5371
5372        #[tokio::test]
5373        async fn cancelled_file_creation_waiting_for_opencreate_never_submits_or_runs_payload()
5374        -> anyhow::Result<()> {
5375            let tmp = tempfile::tempdir()?;
5376            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5377            let destination = tmp.path().join("destination");
5378            let source = tempfile::tempfile()?;
5379            let probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5380            let observation = Arc::new(std::sync::Mutex::new(None));
5381            let capture = QueuedFdCapture {
5382                file: Some(source),
5383                probe,
5384                observation: Arc::clone(&observation),
5385            };
5386            let called = Arc::new(std::sync::atomic::AtomicBool::new(false));
5387            let continuation_called = Arc::clone(&called);
5388            let limits = testutils::AdmissionLimit::new().await;
5389            limits.set_files_in_flight(1);
5390            let resource = throttle::Resource::meta(
5391                throttle::Side::Destination,
5392                throttle::MetadataOp::OpenCreate,
5393            );
5394            limits.set_max_ops_in_flight(resource, 1);
5395            let occupied = throttle::ops_in_flight_permit(resource).await;
5396            let guard = throttle::open_file_permit().await;
5397            let submissions = testutils::BlockingSubmissions::start();
5398            let samples = Arc::new(congestion::testing::CollectingSink::new());
5399            congestion::install_sample_sink(samples.clone());
5400            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5401                root.create_file_and_then(OsStr::new("destination"), move |created| {
5402                    let _capture = capture;
5403                    continuation_called.store(true, std::sync::atomic::Ordering::SeqCst);
5404                    created
5405                })
5406                .await
5407            }));
5408            let waiting = futures::poll!(work.as_mut()).is_pending();
5409            let source_was_open = probe.original_is_closed().map(|closed| !closed);
5410            drop(work);
5411            let source_closed_while_outer_admitted = probe.original_is_closed();
5412            let outer_admission_retained = throttle::open_file_permit().now_or_never().is_none();
5413            let drop_observation = observation.lock().unwrap().take().transpose();
5414            drop(occupied);
5415            drop(guard);
5416            let permit = tokio::time::timeout(
5417                std::time::Duration::from_secs(5),
5418                throttle::open_file_permit(),
5419            )
5420            .await?;
5421            drop(permit);
5422            assert!(waiting && source_was_open?);
5423            assert!(source_closed_while_outer_admitted?);
5424            assert!(outer_admission_retained);
5425            assert_eq!(
5426                drop_observation?,
5427                Some(QueuedFdDropObservation {
5428                    fd_was_closed: true,
5429                    admission_was_retained: true,
5430                })
5431            );
5432            assert_eq!(submissions.count(), 0);
5433            assert_eq!(samples.metadata_count(), 0);
5434            assert!(!called.load(std::sync::atomic::Ordering::SeqCst));
5435            assert!(!destination.exists());
5436            Ok(())
5437        }
5438
5439        #[tokio::test]
5440        async fn panicking_claimed_file_continuation_closes_both_fds_before_admission()
5441        -> anyhow::Result<()> {
5442            use std::os::unix::fs::PermissionsExt as _;
5443            let tmp = tempfile::tempdir()?;
5444            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5445            let destination = tmp.path().join("destination");
5446            let source = tempfile::tempfile()?;
5447            let source_probe = testutils::FdIdentityProbe::capture(source.as_raw_fd())?;
5448            let source_observation = Arc::new(std::sync::Mutex::new(None));
5449            let destination_observation = Arc::new(std::sync::Mutex::new(None));
5450            let payload_destination_observation = Arc::clone(&destination_observation);
5451            let source_capture = QueuedFdCapture {
5452                file: Some(source),
5453                probe: source_probe,
5454                observation: Arc::clone(&source_observation),
5455            };
5456            let limits = testutils::AdmissionLimit::new().await;
5457            limits.set_files_in_flight(1);
5458            let guard = throttle::open_file_permit().await;
5459            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5460            let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
5461            let mut work = Box::pin(with_fd_admission(guard.admission(), async move {
5462                root.create_file_and_then(
5463                    OsStr::new("destination"),
5464                    move |created| -> std::io::Result<()> {
5465                        let _source = source_capture;
5466                        let file = created?;
5467                        let probe = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
5468                        let _destination = QueuedFdCapture {
5469                            file: Some(file),
5470                            probe,
5471                            observation: payload_destination_observation,
5472                        };
5473                        let _ = started_tx.send(probe);
5474                        let _ = release_rx.recv();
5475                        panic!("injected claimed file-continuation panic");
5476                    },
5477                )
5478                .await
5479            }));
5480            let pending = futures::poll!(work.as_mut()).is_pending();
5481            drop(guard);
5482            let started = tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await;
5483            let source_was_open = source_probe.original_is_closed().map(|closed| !closed);
5484            let destination_was_open = match &started {
5485                Ok(Ok(probe)) => Some(probe.original_is_closed().map(|closed| !closed)),
5486                _ => None,
5487            };
5488            let admission_was_retained = throttle::open_file_permit().now_or_never().is_none();
5489            drop(release_tx);
5490            let result = work.await;
5491            let destination_probe = started??;
5492            assert!(pending);
5493            assert!(source_was_open? && destination_was_open.transpose()?.unwrap());
5494            assert!(admission_was_retained);
5495            assert!(
5496                result.is_err(),
5497                "claimed continuation panic must fail the waiter"
5498            );
5499            assert!(source_probe.original_is_closed()? && destination_probe.original_is_closed()?);
5500            for observation in [source_observation, destination_observation] {
5501                assert_eq!(
5502                    observation.lock().unwrap().take().transpose()?,
5503                    Some(QueuedFdDropObservation {
5504                        fd_was_closed: true,
5505                        admission_was_retained: true,
5506                    })
5507                );
5508            }
5509            assert_eq!(
5510                std::fs::metadata(destination)?.permissions().mode() & 0o7777,
5511                DST_FILE_CREATE_MODE
5512            );
5513            let permit = tokio::time::timeout(
5514                std::time::Duration::from_secs(5),
5515                throttle::open_file_permit(),
5516            )
5517            .await?;
5518            drop(permit);
5519            Ok(())
5520        }
5521
5522        /// Dropping a queued blocking waiter must synchronously close its captured fd and return
5523        /// admission before the occupied worker is released, without ever running user work.
5524        #[test]
5525        fn dropping_queued_blocking_work_closes_fd_before_returning_admission() -> anyhow::Result<()>
5526        {
5527            let runtime = tokio::runtime::Builder::new_multi_thread()
5528                .worker_threads(1)
5529                .max_blocking_threads(1)
5530                .enable_all()
5531                .build()?;
5532            runtime.block_on(async {
5533                let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5534                assert_queued_owner_closes_before_admission(|owner| async move {
5535                    run_fd_admitted_blocking(move || {
5536                        let _owner = owner;
5537                        let _ = started_tx.send(());
5538                        Ok(())
5539                    })
5540                    .await
5541                })
5542                .await?;
5543                assert!(
5544                    matches!(
5545                        tokio::time::timeout(std::time::Duration::from_secs(5), started_rx).await,
5546                        Ok(Err(_))
5547                    ),
5548                    "the dropped queued blocking work started"
5549                );
5550                Ok(())
5551            })
5552        }
5553
5554        /// Cancelling an unprobed blocking waiter must retain any ambient fd admission until its
5555        /// detached closure releases the descriptor it owns. Directory enumeration uses this
5556        /// lower-level boundary because `getdents` is deliberately excluded from congestion
5557        /// probing.
5558        #[tokio::test]
5559        async fn cancelled_unprobed_waiter_keeps_admission_until_fd_owner_finishes()
5560        -> anyhow::Result<()> {
5561            let root = crate::testutils::create_temp_dir().await?;
5562            let file_path = root.join("held-unprobed");
5563            tokio::fs::write(&file_path, b"x").await?;
5564            let admission = crate::testutils::AdmissionLimit::new().await;
5565            admission.set_files_in_flight(1);
5566            let open_file_guard = throttle::open_file_permit().await;
5567            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5568            let (release_tx, release_rx) = std::sync::mpsc::channel();
5569            let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
5570            let task = tokio::spawn(async move {
5571                let admission = open_file_guard.admission();
5572                with_fd_admission(admission, async move {
5573                    let _open_file_guard = open_file_guard;
5574                    run_fd_admitted_blocking(move || {
5575                        let _completion = completion;
5576                        let _file = std::fs::File::open(file_path)?;
5577                        let _ = started_tx.send(());
5578                        release_rx.recv().map_err(std::io::Error::other)?;
5579                        Ok(())
5580                    })
5581                    .await
5582                })
5583                .await
5584            });
5585            let started_result = started_rx.await;
5586            task.abort();
5587            let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5588
5589            let mut second_permit = Box::pin(throttle::open_file_permit());
5590            let admission_was_retained =
5591                started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
5592            let release_result = release_tx.send(());
5593            let (completion_result, permit) = crate::testutils::await_completion_and_capacity(
5594                completion_rx,
5595                second_permit.as_mut(),
5596            )
5597            .await;
5598            started_result.context("detached unprobed work did not start")?;
5599            release_result.context("detached unprobed work ended before its release")?;
5600            completion_result.context("detached unprobed work did not report completion")?;
5601            drop(permit);
5602            assert!(waiter_was_cancelled);
5603            assert!(
5604                admission_was_retained,
5605                "cancelling the waiter released admission while detached work held an fd"
5606            );
5607            Ok(())
5608        }
5609
5610        /// Cancelling a metadata waiter must not release admission while its detached blocking
5611        /// closure still owns a file descriptor.
5612        #[tokio::test]
5613        async fn cancelled_metadata_waiter_keeps_admission_until_fd_owner_finishes()
5614        -> anyhow::Result<()> {
5615            let root = crate::testutils::create_temp_dir().await?;
5616            let file_path = root.join("held");
5617            tokio::fs::write(&file_path, b"x").await?;
5618            let admission = crate::testutils::AdmissionLimit::new().await;
5619            admission.set_files_in_flight(1);
5620            let stat_resource =
5621                throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat);
5622            admission.set_max_ops_in_flight(stat_resource, 1);
5623            let open_file_guard = throttle::open_file_permit().await;
5624            let (started_tx, started_rx) = tokio::sync::oneshot::channel();
5625            let (release_tx, release_rx) = std::sync::mpsc::channel();
5626            let (completion, completion_rx) = crate::testutils::CompletionSignal::new();
5627            let task = tokio::spawn(async move {
5628                let admission = open_file_guard.admission();
5629                with_fd_admission(admission, async move {
5630                    let _open_file_guard = open_file_guard;
5631                    run_metadata_probed_blocking(
5632                        congestion::Side::Source,
5633                        congestion::MetadataOp::Stat,
5634                        move || {
5635                            let _completion = completion;
5636                            let _file = std::fs::File::open(file_path)?;
5637                            let _ = started_tx.send(());
5638                            release_rx.recv().map_err(std::io::Error::other)?;
5639                            Ok(())
5640                        },
5641                    )
5642                    .await
5643                })
5644                .await
5645            });
5646            let started_result = started_rx.await;
5647            task.abort();
5648            let waiter_was_cancelled = matches!(task.await, Err(error) if error.is_cancelled());
5649
5650            let second_permit = throttle::open_file_permit();
5651            tokio::pin!(second_permit);
5652            let admission_was_retained =
5653                started_result.is_ok() && futures::poll!(second_permit.as_mut()).is_pending();
5654            let second_stat_permit = throttle::ops_in_flight_permit(stat_resource);
5655            tokio::pin!(second_stat_permit);
5656            let metadata_was_retained =
5657                started_result.is_ok() && futures::poll!(second_stat_permit.as_mut()).is_pending();
5658            let release_result = release_tx.send(());
5659            let (completion_result, (permit, stat_permit)) =
5660                crate::testutils::await_completion_and_capacity(
5661                    completion_rx,
5662                    futures::future::join(second_permit.as_mut(), second_stat_permit.as_mut()),
5663                )
5664                .await;
5665            started_result.context("detached metadata work did not start")?;
5666            release_result.context("detached metadata work ended before its release")?;
5667            completion_result.context("detached metadata work did not report completion")?;
5668            drop(permit);
5669            drop(stat_permit);
5670            assert!(waiter_was_cancelled);
5671            assert!(
5672                admission_was_retained,
5673                "cancelling the waiter released admission while detached work held an fd"
5674            );
5675            assert!(
5676                metadata_was_retained,
5677                "cancelling the waiter released metadata capacity while its syscall was live"
5678            );
5679            Ok(())
5680        }
5681
5682        /// A detached blocking task's returned fd must be dropped before its admission lease. The
5683        /// fd lives in the abandoned task output rather than inside the syscall closure itself.
5684        #[tokio::test]
5685        async fn abandoned_metadata_output_keeps_admission_until_returned_fd_drops()
5686        -> anyhow::Result<()> {
5687            assert_abandoned_output_closes_before_admission(|owner| async move {
5688                run_metadata_probed_blocking(
5689                    congestion::Side::Source,
5690                    congestion::MetadataOp::Stat,
5691                    move || {
5692                        let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5693                        Ok(owner)
5694                    },
5695                )
5696                .await
5697            })
5698            .await
5699        }
5700
5701        /// An abandoned unprobed blocking result must drop its fd owner before returning the
5702        /// strong admission lease. The data-copy path uses this lower-level runner directly.
5703        #[tokio::test]
5704        async fn abandoned_unprobed_output_keeps_admission_until_returned_fd_drops()
5705        -> anyhow::Result<()> {
5706            assert_abandoned_output_closes_before_admission(|owner| async move {
5707                run_fd_admitted_blocking(move || {
5708                    let _visit = resource_tests::gate_opened_descriptor(owner.as_raw_fd())?;
5709                    Ok(owner)
5710                })
5711                .await
5712            })
5713            .await
5714        }
5715    }
5716
5717    #[test]
5718    fn a_run_that_asked_for_nothing_wants_no_root_acl_notice() {
5719        // the gate this whole type exists for: a copy at the shipped default already drops uid,
5720        // gid, timestamps and the special mode bits silently, so an ACL notice there is advice
5721        // about a completeness nobody claimed — and it must cost nothing, kind unknown included.
5722        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5723        assert!(!notice.wanted);
5724        for kind in EVERY_KIND {
5725            assert!(
5726                !notice.could_warn_for_strict(kind, false),
5727                "a {kind:?} root warned under settings that asked for no preservation"
5728            );
5729        }
5730    }
5731
5732    #[test]
5733    fn strict_resolution_arms_the_notice_on_its_own() {
5734        // `--require-toctou-safe` is a request ABOUT permissions whatever `--preserve-settings`
5735        // says, and the two flags deliberately do not imply each other, so it must arm the notice
5736        // by itself — with its own wording, which `warn_root_acl` picks the same way.
5737        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_none());
5738        assert!(notice.could_warn_for_strict(EntryKind::Dir, true));
5739        assert!(notice.could_warn_for_strict(EntryKind::File, true));
5740    }
5741
5742    #[test]
5743    fn the_notice_consults_the_setting_for_the_roots_own_kind() {
5744        // `f:acl` and `d:acl` are independent. Getting this wrong is silent in both directions:
5745        // one way it warns about an ACL the copy is carrying across, the other it stays quiet
5746        // about one being dropped.
5747        let file_only = RootAclNotice {
5748            wanted: true,
5749            file_acl_preserved: true,
5750            dir_acl_preserved: false,
5751        };
5752        assert!(!file_only.could_warn_for_strict(EntryKind::File, false));
5753        assert!(file_only.could_warn_for_strict(EntryKind::Dir, false));
5754        assert!(
5755            file_only.could_warn(),
5756            "a directory root can still warn, so the kind-unknown pre-check must not skip the probe"
5757        );
5758    }
5759
5760    #[test]
5761    fn a_root_that_cannot_carry_an_acl_never_warns() {
5762        // the kernel has no symlink ACL, and a special file is not copied as an object whose
5763        // permissions rcp reproduces — so neither reaches the probe, armed or not
5764        let armed = RootAclNotice {
5765            wanted: true,
5766            file_acl_preserved: false,
5767            dir_acl_preserved: false,
5768        };
5769        for kind in [EntryKind::Symlink, EntryKind::Special] {
5770            assert!(!armed.could_warn_for_strict(kind, true));
5771        }
5772    }
5773
5774    #[test]
5775    fn preserving_both_kinds_acls_leaves_nothing_to_warn_about() {
5776        let notice = RootAclNotice::for_preserve(&crate::preserve::preserve_all_with_acls());
5777        assert!(notice.wanted, "`all+acl` did ask for preservation");
5778        assert!(
5779            !notice.could_warn(),
5780            "both kinds' ACLs are carried across, so even an armed run has nothing to say — and \
5781             must not pay the probe to find that out"
5782        );
5783    }
5784
5785    #[tokio::test]
5786    async fn child_classifies_file_dir_symlink_and_rejects_nofollow() -> anyhow::Result<()> {
5787        let tmp = testutils::setup_test_dir().await?;
5788        // setup_test_dir() returns the temp dir; the fixture lives at tmp/foo/
5789        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5790        assert_eq!(
5791            root.child(OsStr::new("0.txt")).await?.kind(),
5792            EntryKind::File
5793        );
5794        assert_eq!(root.child(OsStr::new("bar")).await?.kind(), EntryKind::Dir);
5795        tokio::fs::symlink("0.txt", tmp.join("foo/lnk")).await?;
5796        assert_eq!(
5797            root.child(OsStr::new("lnk")).await?.kind(),
5798            EntryKind::Symlink
5799        );
5800        // open_dir on a symlinked "dir" must fail closed (ELOOP/ENOTDIR), never follow
5801        tokio::fs::symlink("/etc", tmp.join("foo/evil")).await?;
5802        assert!(root.open_dir(OsStr::new("evil")).await.is_err());
5803        Ok(())
5804    }
5805
5806    #[tokio::test]
5807    async fn open_dir_succeeds_on_real_directory() -> anyhow::Result<()> {
5808        let tmp = testutils::setup_test_dir().await?;
5809        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5810        // bar is a real directory; open_dir must succeed and yield a usable Dir
5811        let bar = root.open_dir(OsStr::new("bar")).await?;
5812        // and the resulting Dir is functional: it can classify its own children
5813        assert_eq!(
5814            bar.child(OsStr::new("1.txt")).await?.kind(),
5815            EntryKind::File
5816        );
5817        Ok(())
5818    }
5819
5820    #[tokio::test]
5821    async fn directory_metadata_snapshot_uses_the_opened_inode_after_a_name_swap()
5822    -> anyhow::Result<()> {
5823        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
5824        for create in [false, true] {
5825            let tmp = tempfile::tempdir()?;
5826            let path = tmp.path().join("child");
5827            let moved = tmp.path().join("moved");
5828            if !create {
5829                std::fs::create_dir(&path)?;
5830                std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o700))?;
5831            }
5832            let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
5833            let mut gate = testutils::BlockingPathGate::install(&path);
5834            let task = tokio::spawn(async move {
5835                if create {
5836                    let (sender, snapshot) = tokio::sync::oneshot::channel();
5837                    let dir = root
5838                        .make_dir_checked(OsStr::new("child"), 0o700, move |meta| {
5839                            let _ = sender.send(meta.clone());
5840                            Ok(())
5841                        })
5842                        .await?;
5843                    Ok((dir, snapshot.await.map_err(std::io::Error::other)?))
5844                } else {
5845                    root.open_dir_with_meta(OsStr::new("child")).await
5846                }
5847            });
5848            tokio::time::timeout(std::time::Duration::from_secs(5), gate.wait_started()).await??;
5849            let before = std::fs::metadata(&path)?;
5850            std::fs::rename(&path, &moved)?;
5851            std::fs::create_dir(&path)?;
5852            let replacement = std::fs::metadata(&path)?;
5853            gate.release_all();
5854            let (dir, snapshot) = task.await??;
5855            assert_eq!(
5856                (snapshot.dev(), snapshot.ino()),
5857                (before.dev(), before.ino())
5858            );
5859            assert_ne!(
5860                (snapshot.dev(), snapshot.ino()),
5861                (replacement.dev(), replacement.ino())
5862            );
5863            assert_eq!(snapshot.permissions().mode() & 0o7777, 0o700);
5864            std::fs::set_permissions(&moved, std::fs::Permissions::from_mode(0o500))?;
5865            let live = dir.meta().await?;
5866            assert_eq!((live.dev(), live.ino()), (snapshot.dev(), snapshot.ino()));
5867            assert_eq!(live.permissions().mode() & 0o7777, 0o500);
5868            assert_eq!(snapshot.permissions().mode() & 0o7777, 0o700);
5869        }
5870        Ok(())
5871    }
5872
5873    #[tokio::test]
5874    async fn rejected_created_directory_removes_the_empty_slot() -> anyhow::Result<()> {
5875        let tmp = tempfile::tempdir()?;
5876        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
5877        let error = root
5878            .make_dir_checked(OsStr::new("child"), 0o700, |_meta| {
5879                Err(std::io::Error::from_raw_os_error(libc::EIO))
5880            })
5881            .await
5882            .unwrap_err();
5883        assert_eq!(error.raw_os_error(), Some(libc::EIO));
5884        assert!(!tmp.path().join("child").exists());
5885        Ok(())
5886    }
5887
5888    #[cfg_attr(
5889        rcp_nix_sandbox,
5890        ignore = "Nix sandbox cannot change ownership or set-id modes"
5891    )]
5892    #[tokio::test]
5893    async fn secure_as_copier_takes_ownership_restricts_mode_and_preserves_gid()
5894    -> anyhow::Result<()> {
5895        use std::os::unix::fs::PermissionsExt as _;
5896        let tmp = testutils::setup_test_dir().await?;
5897        let root =
5898            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
5899
5900        // a plain reused subdir locked down to 0o700: ownership becomes the copier, the mode is
5901        // exactly 0o700, and the gid is unchanged (no race means no gid write at all).
5902        let plain = root.make_dir(OsStr::new("reused_plain"), 0o755).await?;
5903        let before = plain.meta().await?;
5904        plain
5905            .secure_as_copier(0o700, before.uid(), before.gid())
5906            .await?;
5907        let after = plain.meta().await?;
5908        assert_eq!(
5909            after.permissions().mode() & 0o7777,
5910            0o700,
5911            "mode restricted"
5912        );
5913        assert_eq!(
5914            after.uid(),
5915            nix::unistd::geteuid().as_raw(),
5916            "owned by copier"
5917        );
5918        assert_eq!(after.gid(), before.gid(), "gid unchanged when it matches");
5919
5920        // a setgid reused subdir: BOTH the S_ISGID bit and the gid value must survive the
5921        // lockdown, since children created during the copy inherit the directory's group.
5922        let sg = root.make_dir(OsStr::new("reused_setgid"), 0o755).await?;
5923        std::fs::set_permissions(
5924            tmp.join("foo/reused_setgid"),
5925            std::fs::Permissions::from_mode(0o2755),
5926        )?;
5927        let sg_before = sg.meta().await?;
5928        assert_eq!(
5929            sg_before.permissions().mode() & 0o2000,
5930            0o2000,
5931            "test setup: S_ISGID is set before lockdown"
5932        );
5933        sg.secure_as_copier(0o2700, sg_before.uid(), sg_before.gid())
5934            .await?;
5935        let sg_after = sg.meta().await?;
5936        assert_eq!(
5937            sg_after.permissions().mode() & 0o7777,
5938            0o2700,
5939            "S_ISGID + 0o700 both preserved"
5940        );
5941        assert_eq!(
5942            sg_after.gid(),
5943            sg_before.gid(),
5944            "gid preserved under setgid"
5945        );
5946        Ok(())
5947    }
5948
5949    // FIX A (PR #247 review): `open_parent_dir` resolves a TRUSTED command-line parent prefix
5950    // following symlinks (the final component IS followed), while `open_root_dir` keeps the operand
5951    // entry `O_NOFOLLOW` and descendants stay hardened. This pins the parent-prefix-vs-operand
5952    // distinction and proves the hardening below the followed prefix is unchanged.
5953    #[tokio::test]
5954    async fn open_parent_dir_follows_symlinked_prefix_but_descendants_stay_hardened()
5955    -> anyhow::Result<()> {
5956        let tmp = testutils::setup_test_dir().await?;
5957        // a symlink-to-dir standing in for a trusted parent prefix component.
5958        tokio::fs::symlink("foo", tmp.join("foo_link")).await?;
5959        // open_parent_dir FOLLOWS the symlinked final component into the real `foo` directory,
5960        // yielding a TrustedDir; into_tree() crosses into the hardened tree below it.
5961        let parent = Dir::open_parent_dir(&tmp.join("foo_link"), congestion::Side::Source).await?;
5962        let tree = parent.into_tree();
5963        // the followed dir is functional: it sees `foo`'s real children.
5964        assert_eq!(
5965            tree.child(OsStr::new("0.txt")).await?.kind(),
5966            EntryKind::File
5967        );
5968        // open_root_dir on the SAME symlinked path (dereference=false) must instead fail closed —
5969        // it `O_NOFOLLOW`s the final component (the operand-entry contract), proving the two entry
5970        // points differ exactly at the final-component follow decision.
5971        assert!(
5972            Dir::open_root_dir(&tmp.join("foo_link"), false, congestion::Side::Source)
5973                .await
5974                .is_err()
5975        );
5976        // hardening below the followed prefix is UNCHANGED: a symlinked child reached via the
5977        // followed parent still fails closed (O_NOFOLLOW) rather than being followed.
5978        tokio::fs::symlink("/etc", tmp.join("foo/evil_below")).await?;
5979        assert!(tree.open_dir(OsStr::new("evil_below")).await.is_err());
5980        Ok(())
5981    }
5982
5983    #[tokio::test]
5984    async fn rejects_multi_component_names() -> anyhow::Result<()> {
5985        let tmp = testutils::setup_test_dir().await?;
5986        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
5987        // names with a path separator could traverse an intermediate symlink, so
5988        // they are rejected with EINVAL before any syscall (release-safe check)
5989        for bad in ["bar/1.txt", "..", ".", ""] {
5990            let child_err = root.child(OsStr::new(bad)).await.unwrap_err();
5991            assert_eq!(child_err.raw_os_error(), Some(libc::EINVAL));
5992            let dir_err = root.open_dir(OsStr::new(bad)).await.unwrap_err();
5993            assert_eq!(dir_err.raw_os_error(), Some(libc::EINVAL));
5994            let file_err = root.open_file_read(OsStr::new(bad)).await.unwrap_err();
5995            assert_eq!(file_err.raw_os_error(), Some(libc::EINVAL));
5996            let create_err = root.create_file(OsStr::new(bad)).await.unwrap_err();
5997            assert_eq!(create_err.raw_os_error(), Some(libc::EINVAL));
5998        }
5999        Ok(())
6000    }
6001
6002    // Regression for the spawn_blocking cancellation soundness bug: the Dir's fd
6003    // lives behind an Arc that each operation clones into its closure, so an op
6004    // stays sound even after the originating Dir is dropped. We model the
6005    // detached-closure case by cloning a Dir, dropping the original, and
6006    // confirming the clone still opens children correctly.
6007    #[tokio::test]
6008    async fn operations_remain_valid_after_original_dir_dropped() -> anyhow::Result<()> {
6009        let tmp = testutils::setup_test_dir().await?;
6010        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6011        // clone the underlying Arc-held fd into a second Dir, then drop the original
6012        let shared = Dir {
6013            captured_identity: root.captured_identity,
6014            fd: root.fd.clone(),
6015            side: root.side,
6016            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(true)),
6017        };
6018        drop(root);
6019        // the shared handle's open file description is still alive; ops succeed
6020        assert_eq!(
6021            shared.child(OsStr::new("0.txt")).await?.kind(),
6022            EntryKind::File
6023        );
6024        let bar = shared.open_dir(OsStr::new("bar")).await?;
6025        assert_eq!(
6026            bar.child(OsStr::new("2.txt")).await?.kind(),
6027            EntryKind::File
6028        );
6029        Ok(())
6030    }
6031
6032    // open_file_read: verify that a regular file can be opened, metadata size is
6033    // correct, and the returned File is readable.
6034    #[tokio::test]
6035    async fn open_file_read_reads_regular_file() -> anyhow::Result<()> {
6036        let tmp = testutils::setup_test_dir().await?;
6037        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6038        let (mut file, meta) = root.open_file_read(OsStr::new("0.txt")).await?;
6039        // "0.txt" contains the single byte "0"
6040        assert_eq!(meta.size(), 1);
6041        let mut buf = String::new();
6042        file.read_to_string(&mut buf)?;
6043        assert_eq!(buf, "0");
6044        Ok(())
6045    }
6046
6047    // open_file_read: a FIFO must not cause open to block (O_NONBLOCK) AND the
6048    // S_ISREG check must reject it, so the call returns Err without hanging.
6049    #[tokio::test]
6050    async fn open_file_read_rejects_fifo_without_blocking() -> anyhow::Result<()> {
6051        let tmp = testutils::setup_test_dir().await?;
6052        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6053        let fifo_path = tmp.join("foo/test.fifo");
6054        nix::unistd::mkfifo(
6055            &fifo_path,
6056            nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
6057        )?;
6058        // the call must return (not block) within the timeout, and must be an Err
6059        let result = tokio::time::timeout(
6060            std::time::Duration::from_secs(5),
6061            root.open_file_read(OsStr::new("test.fifo")),
6062        )
6063        .await;
6064        assert!(result.is_ok(), "open_file_read blocked on FIFO (timed out)");
6065        assert!(
6066            result.unwrap().is_err(),
6067            "open_file_read must reject a FIFO"
6068        );
6069        Ok(())
6070    }
6071
6072    // open_file_read: a symlink must be rejected (ELOOP from O_NOFOLLOW).
6073    #[tokio::test]
6074    async fn open_file_read_rejects_symlink() -> anyhow::Result<()> {
6075        let tmp = testutils::setup_test_dir().await?;
6076        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6077        // create a symlink pointing to a real file
6078        tokio::fs::symlink("0.txt", tmp.join("foo/link_to_0")).await?;
6079        let result = root.open_file_read(OsStr::new("link_to_0")).await;
6080        assert!(result.is_err(), "open_file_read must reject a symlink");
6081        Ok(())
6082    }
6083
6084    // create_file: successfully creates a new writable file.
6085    #[tokio::test]
6086    async fn create_file_creates_new_writable_file() -> anyhow::Result<()> {
6087        let tmp = testutils::setup_test_dir().await?;
6088        // use a dest-side dir for the write target
6089        let root =
6090            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6091        let mut file = root.create_file(OsStr::new("new.txt")).await?;
6092        use std::io::Write;
6093        file.write_all(b"hello safedir")?;
6094        drop(file);
6095        // re-open via std and verify the content
6096        let content = std::fs::read(tmp.join("foo/new.txt"))?;
6097        assert_eq!(content, b"hello safedir");
6098        Ok(())
6099    }
6100
6101    // create_file: fails with EEXIST when the file already exists.
6102    #[tokio::test]
6103    async fn create_file_fails_if_exists() -> anyhow::Result<()> {
6104        let tmp = testutils::setup_test_dir().await?;
6105        let root =
6106            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6107        // "0.txt" already exists in the fixture
6108        let err = root.create_file(OsStr::new("0.txt")).await.unwrap_err();
6109        assert_eq!(
6110            err.raw_os_error(),
6111            Some(libc::EEXIST),
6112            "expected EEXIST, got {err:#}"
6113        );
6114        Ok(())
6115    }
6116
6117    // make_dir: creates the directory and returns a usable Dir handle.
6118    #[tokio::test]
6119    async fn make_dir_creates_and_returns_usable_dir() -> anyhow::Result<()> {
6120        let tmp = testutils::setup_test_dir().await?;
6121        let root =
6122            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6123        let sub = root.make_dir(OsStr::new("sub"), 0o755).await?;
6124        // the returned Dir must be usable: create a file inside it
6125        sub.create_file(OsStr::new("child.txt")).await?;
6126        // and read_entries on the sub dir must show that file
6127        let entries = sub.read_entries().await?;
6128        let names: Vec<_> = entries
6129            .iter()
6130            .map(|(n, _)| n.to_string_lossy().into_owned())
6131            .collect();
6132        assert!(
6133            names.contains(&"child.txt".to_string()),
6134            "child.txt not found in {names:?}"
6135        );
6136        Ok(())
6137    }
6138
6139    // make_dir: multi-component names must be rejected with EINVAL.
6140    #[tokio::test]
6141    async fn make_dir_rejects_multi_component_names() -> anyhow::Result<()> {
6142        let tmp = testutils::setup_test_dir().await?;
6143        let root =
6144            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6145        for bad in ["a/b", "..", ".", ""] {
6146            let err = root.make_dir(OsStr::new(bad), 0o755).await.unwrap_err();
6147            assert_eq!(
6148                err.raw_os_error(),
6149                Some(libc::EINVAL),
6150                "expected EINVAL for {:?}, got {err:#}",
6151                bad
6152            );
6153        }
6154        Ok(())
6155    }
6156
6157    #[test]
6158    fn dtype_hints_only_classify_named_types() {
6159        let named = [
6160            (libc::DT_DIR, EntryKind::Dir),
6161            (libc::DT_LNK, EntryKind::Symlink),
6162            (libc::DT_REG, EntryKind::File),
6163            (libc::DT_FIFO, EntryKind::Special),
6164            (libc::DT_CHR, EntryKind::Special),
6165            (libc::DT_BLK, EntryKind::Special),
6166            (libc::DT_SOCK, EntryKind::Special),
6167        ];
6168        for dtype in libc::c_uchar::MIN..=libc::c_uchar::MAX {
6169            let expected = named
6170                .iter()
6171                .find(|(value, _)| *value == dtype)
6172                .map(|(_, kind)| *kind);
6173            assert_eq!(kind_hint_from_dtype(dtype), expected, "d_type={dtype}");
6174        }
6175    }
6176
6177    // read_entries: returns all entries with correct d_type hints
6178    #[tokio::test]
6179    async fn read_entries_lists_children_with_dtype_hints() -> anyhow::Result<()> {
6180        use std::collections::HashMap;
6181        let tmp = testutils::setup_test_dir().await?;
6182        // baz contains: 4.txt (file), 5.txt (symlink), 6.txt (symlink)
6183        // use bar which has only files; instead build a custom fixture in foo
6184        let fixture = tmp.join("foo/fixture_dir");
6185        tokio::fs::create_dir(&fixture).await?;
6186        tokio::fs::write(fixture.join("afile.txt"), "x").await?;
6187        tokio::fs::create_dir(fixture.join("asubdir")).await?;
6188        tokio::fs::symlink("afile.txt", fixture.join("alink")).await?;
6189
6190        let root = Dir::open_root_dir(&fixture, false, congestion::Side::Source).await?;
6191        let entries = root.read_entries().await?;
6192        let map: HashMap<String, Option<EntryKind>> = entries
6193            .into_iter()
6194            .map(|(n, k)| (n.to_string_lossy().into_owned(), k))
6195            .collect();
6196
6197        assert_eq!(map.len(), 3, "expected 3 entries, got {map:?}");
6198        assert_eq!(
6199            map.get("afile.txt"),
6200            Some(&Some(EntryKind::File)),
6201            "afile.txt wrong"
6202        );
6203        assert_eq!(
6204            map.get("asubdir"),
6205            Some(&Some(EntryKind::Dir)),
6206            "asubdir wrong"
6207        );
6208        assert_eq!(
6209            map.get("alink"),
6210            Some(&Some(EntryKind::Symlink)),
6211            "alink wrong"
6212        );
6213        Ok(())
6214    }
6215
6216    #[tokio::test]
6217    async fn read_entries_sees_children_created_after_open_and_between_reads() -> anyhow::Result<()>
6218    {
6219        let tmp = tempfile::tempdir()?;
6220        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6221        for name in ["first", "second"] {
6222            std::fs::write(tmp.path().join(name), b"content")?;
6223            let names = sorted_names(root.read_entries().await?);
6224            let expected = if name == "first" {
6225                vec!["first"]
6226            } else {
6227                vec!["first", "second"]
6228            };
6229            assert_eq!(names, expected);
6230        }
6231        Ok(())
6232    }
6233
6234    fn exhaust_shared_directory_offset(root: &Dir) -> anyhow::Result<()> {
6235        let mut stream = OwnedDirectoryStream::from_fd(root.fd.fd.try_clone()?, None)?;
6236        while stream.next_raw_entry()?.is_some() {}
6237        // independently check that closing the stream leaves a seekable description at EOF.
6238        // nonseekable FUSE descriptions reject SEEK_CUR too
6239        let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
6240        if let Ok(offset) = end {
6241            assert_ne!(
6242                offset, 0,
6243                "exhausting the stream did not advance its offset"
6244            );
6245        } else {
6246            assert_eq!(end, Err(nix::errno::Errno::ESPIPE));
6247        }
6248        drop(stream);
6249        assert_eq!(
6250            nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
6251            end,
6252            "closing the stream changed the shared offset"
6253        );
6254        Ok(())
6255    }
6256
6257    fn sorted_names(
6258        entries: Vec<(std::ffi::OsString, Option<EntryKind>)>,
6259    ) -> Vec<std::ffi::OsString> {
6260        let mut names: Vec<_> = entries.into_iter().map(|(name, _)| name).collect();
6261        names.sort();
6262        names
6263    }
6264
6265    fn stream_names(fd: OwnedFd) -> anyhow::Result<Vec<std::ffi::OsString>> {
6266        let mut stream = OwnedDirectoryStream::from_fd(fd, None)?;
6267        let mut names = Vec::new();
6268        while let Some(entry) = stream.next_raw_entry()? {
6269            if entry.name != "." && entry.name != ".." {
6270                names.push(entry.name);
6271            }
6272        }
6273        names.sort();
6274        Ok(names)
6275    }
6276
6277    #[tokio::test]
6278    async fn listing_fd_shares_the_refreshed_description_on_seek_success() -> anyhow::Result<()> {
6279        let tmp = tempfile::tempdir()?;
6280        std::fs::write(tmp.path().join("entry"), b"content")?;
6281        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6282        exhaust_shared_directory_offset(&root)?;
6283        let fd = root.fd.listing_fd_with_seek(|fd| {
6284            assert_eq!(fd.as_raw_fd(), root.fd.as_raw_fd());
6285            nix::unistd::lseek(fd, 0, nix::unistd::Whence::SeekSet)
6286        })?;
6287        assert_eq!(
6288            nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur)?,
6289            0
6290        );
6291        assert_eq!(stream_names(fd)?, ["entry"]);
6292        assert_ne!(
6293            nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur)?,
6294            0
6295        );
6296        Ok(())
6297    }
6298
6299    #[tokio::test]
6300    async fn listing_fd_reopens_the_held_directory_on_espipe() -> anyhow::Result<()> {
6301        for mode in [None, Some(0o444)] {
6302            let tmp = tempfile::tempdir()?;
6303            let parent = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6304            let _restore_parent = RestoreDirectoryAccess(&parent);
6305            let source = tmp.path().join("source");
6306            std::fs::create_dir(&source)?;
6307            std::fs::write(source.join("entry"), b"content")?;
6308            let root = Dir::open_root_dir(&source, false, congestion::Side::Source).await?;
6309            let _restore = RestoreDirectoryAccess(&root);
6310            exhaust_shared_directory_offset(&root)?;
6311            let end = nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur);
6312            if let Some(mode) = mode {
6313                fchmod(root.fd.as_fd(), Mode::from_bits_truncate(mode))?;
6314                if !directory_search_permission_is_enforced(&root)? {
6315                    continue;
6316                }
6317            }
6318            // a replacement at the old path must not redirect the reopened listing
6319            std::fs::rename(&source, tmp.path().join("moved"))?;
6320            let replacement = tmp.path().join("replacement");
6321            std::fs::create_dir(&replacement)?;
6322            std::fs::write(replacement.join("sentinel"), b"other")?;
6323            std::os::unix::fs::symlink(&replacement, &source)?;
6324            if mode.is_some() {
6325                // following the proc magic link works even when reopening its readlink text
6326                // cannot traverse the directory's parent
6327                fchmod(parent.fd.as_fd(), Mode::empty())?;
6328                let path = std::fs::read_link(format!("/proc/self/fd/{}", root.fd.as_raw_fd()))?;
6329                assert_eq!(
6330                    std::fs::File::open(path).unwrap_err().raw_os_error(),
6331                    Some(libc::EACCES)
6332                );
6333            }
6334            for _ in 0..2 {
6335                let fd = root.fd.listing_fd_with_seek(|fd| {
6336                    assert_eq!(fd.as_raw_fd(), root.fd.as_raw_fd());
6337                    Err(nix::errno::Errno::ESPIPE)
6338                })?;
6339                assert_eq!(stream_names(fd)?, ["entry"], "mode={mode:?}");
6340                assert_eq!(
6341                    nix::unistd::lseek(root.fd.as_fd(), 0, nix::unistd::Whence::SeekCur),
6342                    end
6343                );
6344            }
6345        }
6346        Ok(())
6347    }
6348
6349    #[tokio::test]
6350    async fn listing_fd_propagates_other_seek_errors() -> anyhow::Result<()> {
6351        let tmp = tempfile::tempdir()?;
6352        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6353        for error in [
6354            nix::errno::Errno::EIO,
6355            nix::errno::Errno::EACCES,
6356            nix::errno::Errno::EINVAL,
6357        ] {
6358            let result = root.fd.listing_fd_with_seek(|_| Err(error));
6359            assert_eq!(result.unwrap_err().raw_os_error(), Some(error as i32));
6360        }
6361        assert!(root.read_entries().await?.is_empty());
6362        Ok(())
6363    }
6364
6365    #[tokio::test]
6366    async fn read_entries_refreshes_an_exhausted_shared_offset() -> anyhow::Result<()> {
6367        let tmp = tempfile::tempdir()?;
6368        for name in ["first", "second"] {
6369            std::fs::write(tmp.path().join(name), b"content")?;
6370        }
6371        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6372        exhaust_shared_directory_offset(&root)?;
6373        let names = sorted_names(root.read_entries().await?);
6374        assert_eq!(names, ["first", "second"]);
6375        Ok(())
6376    }
6377
6378    #[tokio::test]
6379    async fn capped_entries_refreshes_an_exhausted_shared_offset() -> anyhow::Result<()> {
6380        let tmp = tempfile::tempdir()?;
6381        for name in ["first", "second", "third"] {
6382            std::fs::write(tmp.path().join(name), b"content")?;
6383        }
6384        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6385        exhaust_shared_directory_offset(&root)?;
6386        assert!(root.read_entries_capped(2).await?.is_none());
6387        let names = sorted_names(
6388            root.read_entries_capped(3)
6389                .await?
6390                .expect("three entries fit the cap"),
6391        );
6392        assert_eq!(names, ["first", "second", "third"]);
6393        Ok(())
6394    }
6395
6396    #[tokio::test]
6397    async fn capped_entries_refresh_after_creation_and_over_cap_reads() -> anyhow::Result<()> {
6398        let tmp = tempfile::tempdir()?;
6399        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Source).await?;
6400        assert_eq!(root.read_entries_capped(0).await?, Some(Vec::new()));
6401        std::fs::write(tmp.path().join("first"), b"content")?;
6402        let first = root
6403            .read_entries_capped(1)
6404            .await?
6405            .expect("one entry fits the cap");
6406        assert_eq!(
6407            first.into_iter().map(|(name, _)| name).collect::<Vec<_>>(),
6408            ["first"]
6409        );
6410        std::fs::write(tmp.path().join("second"), b"content")?;
6411        assert!(root.read_entries_capped(1).await?.is_none());
6412        std::fs::write(tmp.path().join("third"), b"content")?;
6413        let names = sorted_names(
6414            root.read_entries_capped(3)
6415                .await?
6416                .expect("three entries fit the cap"),
6417        );
6418        assert_eq!(names, ["first", "second", "third"]);
6419        assert!(root.read_entries_capped(0).await?.is_none());
6420        Ok(())
6421    }
6422
6423    // read_entries: calling it twice on the same Dir must succeed (fd not consumed)
6424    #[tokio::test]
6425    async fn read_entries_does_not_close_self_fd() -> anyhow::Result<()> {
6426        let tmp = testutils::setup_test_dir().await?;
6427        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6428        // first call
6429        let first = root.read_entries().await?;
6430        assert!(!first.is_empty(), "first read_entries returned empty");
6431        // the first stream leaves the shared description at EOF without rewinding.
6432        // the second call must refresh it and return the same complete entry set
6433        let second = root.read_entries().await?;
6434        let mut first_names: Vec<_> = first.iter().map(|(name, _)| name.clone()).collect();
6435        let mut second_names: Vec<_> = second.iter().map(|(name, _)| name.clone()).collect();
6436        first_names.sort();
6437        second_names.sort();
6438        assert_eq!(
6439            first_names, second_names,
6440            "second read_entries differs from first"
6441        );
6442        // also prove child() still works on the same Dir
6443        root.child(OsStr::new("0.txt")).await?;
6444        Ok(())
6445    }
6446
6447    // create_file: refuses to follow or clobber an existing symlink.
6448    #[tokio::test]
6449    async fn create_file_refuses_existing_symlink() -> anyhow::Result<()> {
6450        let tmp = testutils::setup_test_dir().await?;
6451        let root =
6452            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6453        // plant a symlink pointing at a non-existent target
6454        let link_path = tmp.join("foo/evil_link");
6455        let target_path = tmp.join("foo/should_not_be_created");
6456        tokio::fs::symlink(&target_path, &link_path).await?;
6457        // create_file must fail, not follow the symlink and create the target
6458        let err = root.create_file(OsStr::new("evil_link")).await.unwrap_err();
6459        // O_CREAT|O_EXCL returns EEXIST on an existing symlink without following it
6460        assert_eq!(
6461            err.raw_os_error(),
6462            Some(libc::EEXIST),
6463            "expected EEXIST, got {err:#}"
6464        );
6465        // the symlink target must NOT have been created
6466        assert!(
6467            !target_path.exists(),
6468            "symlink target was unexpectedly created"
6469        );
6470        Ok(())
6471    }
6472
6473    // unlink_at: removes a regular file and confirms it is gone.
6474    #[tokio::test]
6475    async fn unlink_at_removes_file() -> anyhow::Result<()> {
6476        let tmp = testutils::setup_test_dir().await?;
6477        let root =
6478            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6479        // "0.txt" exists in the fixture
6480        root.unlink_at(OsStr::new("0.txt")).await?;
6481        // afterwards child() must fail with ENOENT
6482        let err = root.child(OsStr::new("0.txt")).await.unwrap_err();
6483        assert_eq!(
6484            err.raw_os_error(),
6485            Some(libc::ENOENT),
6486            "expected ENOENT after unlink, got {err:#}"
6487        );
6488        Ok(())
6489    }
6490
6491    // unlink_at: removes the symlink itself, not its target.
6492    #[tokio::test]
6493    async fn unlink_at_on_symlink_removes_link_not_target() -> anyhow::Result<()> {
6494        let tmp = testutils::setup_test_dir().await?;
6495        let root =
6496            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6497        // create a sentinel file with content, then symlink to it
6498        tokio::fs::write(tmp.join("foo/sentinel.txt"), b"alive").await?;
6499        tokio::fs::symlink("sentinel.txt", tmp.join("foo/lnk")).await?;
6500        // unlink the link
6501        root.unlink_at(OsStr::new("lnk")).await?;
6502        // link is gone
6503        let err = root.child(OsStr::new("lnk")).await.unwrap_err();
6504        assert_eq!(
6505            err.raw_os_error(),
6506            Some(libc::ENOENT),
6507            "expected ENOENT for removed link, got {err:#}"
6508        );
6509        // sentinel target still exists with content
6510        let content = tokio::fs::read(tmp.join("foo/sentinel.txt")).await?;
6511        assert_eq!(content, b"alive", "sentinel.txt was unexpectedly removed");
6512        Ok(())
6513    }
6514
6515    // rmdir_at: removes an empty directory; rejects non-empty (ENOTEMPTY) and a
6516    // regular file (ENOTDIR).
6517    #[tokio::test]
6518    async fn rmdir_at_removes_empty_dir_and_rejects_nonempty() -> anyhow::Result<()> {
6519        let tmp = testutils::setup_test_dir().await?;
6520        let root =
6521            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6522        // create an empty subdirectory and remove it
6523        tokio::fs::create_dir(tmp.join("foo/empty_sub")).await?;
6524        root.rmdir_at(OsStr::new("empty_sub")).await?;
6525        let err = root.child(OsStr::new("empty_sub")).await.unwrap_err();
6526        assert_eq!(
6527            err.raw_os_error(),
6528            Some(libc::ENOENT),
6529            "expected ENOENT after rmdir, got {err:#}"
6530        );
6531        // "bar" is non-empty in the fixture → ENOTEMPTY
6532        let err = root.rmdir_at(OsStr::new("bar")).await.unwrap_err();
6533        assert_eq!(
6534            err.raw_os_error(),
6535            Some(libc::ENOTEMPTY),
6536            "expected ENOTEMPTY for non-empty dir, got {err:#}"
6537        );
6538        // "0.txt" is a regular file → ENOTDIR
6539        let err = root.rmdir_at(OsStr::new("0.txt")).await.unwrap_err();
6540        assert_eq!(
6541            err.raw_os_error(),
6542            Some(libc::ENOTDIR),
6543            "expected ENOTDIR for regular file, got {err:#}"
6544        );
6545        Ok(())
6546    }
6547
6548    // symlink_at: creates a symlink and returns a Handle with kind Symlink;
6549    // read_link_at then returns the original target path.
6550    #[tokio::test]
6551    async fn symlink_at_creates_link_and_returns_pinned_handle() -> anyhow::Result<()> {
6552        let tmp = testutils::setup_test_dir().await?;
6553        let root =
6554            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
6555        let target = std::path::Path::new("some/arbitrary/target");
6556        let handle = root.symlink_at(OsStr::new("mylink"), target).await?;
6557        assert_eq!(
6558            handle.kind(),
6559            EntryKind::Symlink,
6560            "symlink_at must return a Symlink handle"
6561        );
6562        // read_link_at must return the same target
6563        let read_back = root.read_link_at(OsStr::new("mylink")).await?;
6564        assert_eq!(
6565            read_back, target,
6566            "read_link_at returned wrong target: {read_back:?}"
6567        );
6568        Ok(())
6569    }
6570
6571    // read_link_handle reads the target inode-exact from the pinned O_PATH symlink handle (the
6572    // empty-path readlinkat form), so the target pairs with `handle.meta()` from the SAME fd. A
6573    // non-symlink handle is rejected (EINVAL).
6574    #[tokio::test]
6575    async fn read_link_handle_reads_target_from_pinned_handle() -> anyhow::Result<()> {
6576        let tmp = testutils::setup_test_dir().await?;
6577        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6578        let target = std::path::Path::new("some/arbitrary/target");
6579        tokio::fs::symlink(target, tmp.join("foo/mylink")).await?;
6580        // classify the link, then read its target through that same pinned handle.
6581        let handle = root.child(OsStr::new("mylink")).await?;
6582        assert_eq!(handle.kind(), EntryKind::Symlink);
6583        let read_back = read_link_handle(&handle, congestion::Side::Source).await?;
6584        assert_eq!(read_back, target, "wrong target: {read_back:?}");
6585        // a non-symlink handle (a regular file) is rejected (the empty-path readlinkat form requires
6586        // a symlink fd; the kernel returns an error rather than a target). Callers only ever invoke
6587        // this on a Symlink-classified handle, so this is the defensive path.
6588        let file_handle = root.child(OsStr::new("0.txt")).await?;
6589        assert!(
6590            read_link_handle(&file_handle, congestion::Side::Source)
6591                .await
6592                .is_err(),
6593            "read_link_handle on a non-symlink must fail"
6594        );
6595        Ok(())
6596    }
6597
6598    // Handle::read_symlink returns target AND metadata from the one pinned O_PATH fd, so they are a
6599    // faithful pair (the symlink analogue of open_file_read).
6600    #[tokio::test]
6601    async fn read_symlink_returns_target_and_meta_from_one_handle() -> anyhow::Result<()> {
6602        use crate::preserve::Metadata as _;
6603        let tmp = testutils::setup_test_dir().await?;
6604        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
6605        let target = std::path::Path::new("some/target");
6606        tokio::fs::symlink(target, tmp.join("foo/lnk")).await?;
6607        let handle = root.child(OsStr::new("lnk")).await?;
6608        let (read_target, meta) = handle.read_symlink(congestion::Side::Source).await?;
6609        assert_eq!(read_target, target);
6610        // metadata is the symlink's own, from the same handle.
6611        assert_eq!(meta.uid(), handle.meta().uid());
6612        assert_eq!(meta.mtime(), handle.meta().mtime());
6613        Ok(())
6614    }
6615
6616    // Dir::meta fstats the directory's own held fd (the fd whose contents we enumerate).
6617    #[tokio::test]
6618    async fn dir_meta_returns_opened_dir_fstat() -> anyhow::Result<()> {
6619        use crate::preserve::Metadata as _;
6620        let tmp = testutils::setup_test_dir().await?;
6621        let bar = Dir::open_root_dir(&tmp.join("foo/bar"), false, congestion::Side::Source).await?;
6622        let meta = bar.meta().await?;
6623        let std_meta = std::fs::metadata(tmp.join("foo/bar"))?;
6624        // `meta.uid()` resolves via preserve::Metadata (the only trait FileMeta implements);
6625        // fully-qualify the std::fs::Metadata side, which implements both that trait and MetadataExt.
6626        assert_eq!(meta.uid(), std::os::unix::fs::MetadataExt::uid(&std_meta));
6627        assert_eq!(meta.gid(), std::os::unix::fs::MetadataExt::gid(&std_meta));
6628        Ok(())
6629    }
6630
6631    // hard_link_at: creates a hard link sharing the same inode.
6632    #[tokio::test]
6633    async fn hard_link_at_creates_hardlink() -> anyhow::Result<()> {
6634        let tmp = testutils::setup_test_dir().await?;
6635        // use two subdirs as src and dst Dir handles
6636        tokio::fs::create_dir(tmp.join("foo/src_sub")).await?;
6637        tokio::fs::create_dir(tmp.join("foo/dst_sub")).await?;
6638        tokio::fs::write(tmp.join("foo/src_sub/orig.txt"), b"hardlink test").await?;
6639
6640        let src =
6641            Dir::open_root_dir(&tmp.join("foo/src_sub"), false, congestion::Side::Source).await?;
6642        let dst = Dir::open_root_dir(
6643            &tmp.join("foo/dst_sub"),
6644            false,
6645            congestion::Side::Destination,
6646        )
6647        .await?;
6648
6649        src.hard_link_at(OsStr::new("orig.txt"), &dst, OsStr::new("link.txt"))
6650            .await?;
6651
6652        // both handles must exist and share the same inode
6653        let orig_handle = src.child(OsStr::new("orig.txt")).await?;
6654        let link_handle = dst.child(OsStr::new("link.txt")).await?;
6655        assert_eq!(orig_handle.kind(), EntryKind::File, "orig must be a file");
6656        assert_eq!(link_handle.kind(), EntryKind::File, "link must be a file");
6657        assert_eq!(
6658            orig_handle.ino(),
6659            link_handle.ino(),
6660            "hard link must share the inode"
6661        );
6662        Ok(())
6663    }
6664
6665    // hard_link_at: when the source name is a symlink, linkat with flags=0 does
6666    // NOT follow it — it links the symlink inode itself, so the new entry is also
6667    // a symlink.
6668    #[tokio::test]
6669    async fn hard_link_at_does_not_follow_source_symlink() -> anyhow::Result<()> {
6670        let tmp = testutils::setup_test_dir().await?;
6671        tokio::fs::create_dir(tmp.join("foo/src_hl")).await?;
6672        tokio::fs::create_dir(tmp.join("foo/dst_hl")).await?;
6673        // create a real file and a symlink to it in src_hl
6674        tokio::fs::write(tmp.join("foo/src_hl/real.txt"), b"target").await?;
6675        tokio::fs::symlink("real.txt", tmp.join("foo/src_hl/sym.txt")).await?;
6676
6677        let src =
6678            Dir::open_root_dir(&tmp.join("foo/src_hl"), false, congestion::Side::Source).await?;
6679        let dst = Dir::open_root_dir(
6680            &tmp.join("foo/dst_hl"),
6681            false,
6682            congestion::Side::Destination,
6683        )
6684        .await?;
6685
6686        // Linux does not allow hard-linking a symlink without AT_EMPTY_PATH or
6687        // special capabilities; linkat with flags=0 on a symlink yields EPERM.
6688        // Verify that the call does NOT silently follow the symlink into real.txt.
6689        let result = src
6690            .hard_link_at(OsStr::new("sym.txt"), &dst, OsStr::new("new_link.txt"))
6691            .await;
6692        match result {
6693            Ok(()) => {
6694                // If it succeeded (some kernels/configs allow it), the new entry
6695                // must be a symlink — NOT a hard link to the underlying file.
6696                let new_handle = dst.child(OsStr::new("new_link.txt")).await?;
6697                assert_eq!(
6698                    new_handle.kind(),
6699                    EntryKind::Symlink,
6700                    "hard_link_at must link the symlink itself, not its target"
6701                );
6702                // and real.txt must still have link-count 1 (no new hard link)
6703                let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
6704                use std::os::unix::fs::MetadataExt;
6705                assert_eq!(
6706                    real_meta.nlink(),
6707                    1,
6708                    "real.txt must not gain a new hard link"
6709                );
6710            }
6711            Err(ref e) if e.raw_os_error() == Some(libc::EPERM) => {
6712                // expected on most Linux configurations; the important thing is
6713                // that it did NOT follow the symlink and link real.txt.
6714                // real.txt must still have exactly 1 hard link.
6715                let real_meta = std::fs::metadata(tmp.join("foo/src_hl/real.txt"))?;
6716                use std::os::unix::fs::MetadataExt;
6717                assert_eq!(
6718                    real_meta.nlink(),
6719                    1,
6720                    "real.txt must not gain a new hard link"
6721                );
6722            }
6723            Err(e) => {
6724                return Err(anyhow::anyhow!(
6725                    "unexpected error from hard_link_at on symlink: {e:#}"
6726                ));
6727            }
6728        }
6729        Ok(())
6730    }
6731
6732    // hard_link_handle_at links the exact inode the classified Handle pins, immune to a concurrent
6733    // source-name swap. The deterministic swap occurs after classification but before the link.
6734    //
6735    // the decoy is a different regular file with different content placed at the same name. A
6736    // by-name link would re-resolve `name` and link the decoy; `hard_link_handle_at` links the pinned
6737    // original inode regardless.
6738    #[tokio::test]
6739    async fn hard_link_handle_at_links_pinned_inode_after_name_swap() -> anyhow::Result<()> {
6740        use std::os::unix::fs::MetadataExt;
6741        let tmp = testutils::create_temp_dir().await?;
6742        tokio::fs::create_dir(tmp.join("src")).await?;
6743        tokio::fs::create_dir(tmp.join("dst")).await?;
6744        tokio::fs::write(tmp.join("src/entry"), b"ORIGINAL").await?;
6745        let orig_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
6746
6747        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6748        let dst =
6749            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6750        // classify `entry` — pins the ORIGINAL regular-file inode via O_PATH.
6751        let handle = src.child(OsStr::new("entry")).await?;
6752        assert_eq!(handle.kind(), EntryKind::File);
6753
6754        // SWAP `entry` to a DIFFERENT regular file (the decoy) before linking. We keep
6755        // the original inode alive only through `handle` (its directory entry is gone),
6756        // mimicking an attacker renaming a decoy over the source name.
6757        tokio::fs::write(tmp.join("src/decoy"), b"DECOY_SECRET").await?;
6758        tokio::fs::rename(tmp.join("src/decoy"), tmp.join("src/entry")).await?;
6759        let decoy_ino = tokio::fs::metadata(tmp.join("src/entry")).await?.ino();
6760        assert_ne!(orig_ino, decoy_ino, "decoy must be a different inode");
6761
6762        // inode-exact link: either links the ORIGINAL pinned inode, or fails closed.
6763        match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
6764            Ok(()) => {
6765                let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
6766                assert!(
6767                    lm.file_type().is_file(),
6768                    "linked entry must be a regular file"
6769                );
6770                assert_eq!(
6771                    lm.ino(),
6772                    orig_ino,
6773                    "hard_link_handle_at must link the PINNED original inode, never the \
6774                     swapped-in decoy (the by-name link would have linked the decoy here)"
6775                );
6776                let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
6777                assert_eq!(
6778                    content, "ORIGINAL",
6779                    "must reflect the original inode's content"
6780                );
6781                assert_ne!(content, "DECOY_SECRET");
6782            }
6783            Err(e) => {
6784                // fail-closed is acceptable (e.g. the pinned inode's last link was
6785                // already gone). It must NEVER have linked the decoy.
6786                assert!(
6787                    !tmp.join("dst/linked").exists(),
6788                    "no destination entry may exist when the link failed closed (got {e:#})"
6789                );
6790            }
6791        }
6792        Ok(())
6793    }
6794
6795    // hard_link_handle_at must refuse to hard-link a DIRECTORY (linkat returns EPERM),
6796    // matching the by-name path — a hard link to a directory is never created.
6797    #[tokio::test]
6798    async fn hard_link_handle_at_refuses_directory() -> anyhow::Result<()> {
6799        let tmp = testutils::create_temp_dir().await?;
6800        tokio::fs::create_dir(tmp.join("src")).await?;
6801        tokio::fs::create_dir(tmp.join("dst")).await?;
6802        tokio::fs::create_dir(tmp.join("src/adir")).await?;
6803        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6804        let dst =
6805            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6806        let dir_handle = src.child(OsStr::new("adir")).await?;
6807        assert_eq!(dir_handle.kind(), EntryKind::Dir);
6808        let result = dst
6809            .hard_link_handle_at(&dir_handle, OsStr::new("linked_dir"))
6810            .await;
6811        assert!(
6812            result.is_err(),
6813            "hard_link_handle_at must refuse to hard-link a directory"
6814        );
6815        assert!(
6816            !tmp.join("dst/linked_dir").exists(),
6817            "no destination entry may be created for a directory hard link"
6818        );
6819        Ok(())
6820    }
6821
6822    // classify a regular file, then swap the source name to a FIFO before linking. A by-name
6823    // `linkat(flags=0)` would re-resolve the name and hard-link the FIFO, surfacing a special at the
6824    // destination that rlink reports as a hard-linked file. The inode-exact link must instead link
6825    // the pinned regular file or fail closed, so the destination is never special.
6826    #[tokio::test]
6827    async fn hard_link_handle_at_never_links_swapped_in_fifo() -> anyhow::Result<()> {
6828        use std::os::unix::fs::FileTypeExt;
6829        let tmp = testutils::create_temp_dir().await?;
6830        tokio::fs::create_dir(tmp.join("src")).await?;
6831        tokio::fs::create_dir(tmp.join("dst")).await?;
6832        tokio::fs::write(tmp.join("src/entry"), b"REALFILE").await?;
6833        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6834        let dst =
6835            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6836        // classify `entry` — pins the regular-file inode.
6837        let handle = src.child(OsStr::new("entry")).await?;
6838        assert_eq!(handle.kind(), EntryKind::File);
6839        // swap `entry` to a FIFO (keep the regular inode alive only via the handle).
6840        tokio::fs::remove_file(tmp.join("src/entry")).await?;
6841        nix::unistd::mkfifo(
6842            &tmp.join("src/entry"),
6843            nix::sys::stat::Mode::S_IRUSR | nix::sys::stat::Mode::S_IWUSR,
6844        )?;
6845        match dst.hard_link_handle_at(&handle, OsStr::new("linked")).await {
6846            Ok(()) => {
6847                let lm = tokio::fs::symlink_metadata(tmp.join("dst/linked")).await?;
6848                assert!(
6849                    lm.file_type().is_file(),
6850                    "linked entry must be the pinned regular file, never the swapped-in FIFO"
6851                );
6852                assert!(
6853                    !lm.file_type().is_fifo(),
6854                    "the destination must never be a special (the by-name link would link the FIFO)"
6855                );
6856                let content = tokio::fs::read_to_string(tmp.join("dst/linked")).await?;
6857                assert_eq!(content, "REALFILE");
6858            }
6859            Err(_) => {
6860                // fail-closed is acceptable; nothing may be left at the destination.
6861                assert!(
6862                    !tmp.join("dst/linked").exists(),
6863                    "no destination entry may exist when the link failed closed"
6864                );
6865            }
6866        }
6867        Ok(())
6868    }
6869
6870    // hard_link_handle_at on a STABLE regular file links exactly like the by-name path
6871    // did (same inode, same content) — the happy path is unchanged.
6872    #[tokio::test]
6873    async fn hard_link_handle_at_stable_file_happy_path() -> anyhow::Result<()> {
6874        let tmp = testutils::create_temp_dir().await?;
6875        tokio::fs::create_dir(tmp.join("src")).await?;
6876        tokio::fs::create_dir(tmp.join("dst")).await?;
6877        tokio::fs::write(tmp.join("src/f"), b"STABLE").await?;
6878        let src = Dir::open_root_dir(&tmp.join("src"), false, congestion::Side::Source).await?;
6879        let dst =
6880            Dir::open_root_dir(&tmp.join("dst"), false, congestion::Side::Destination).await?;
6881        let handle = src.child(OsStr::new("f")).await?;
6882        dst.hard_link_handle_at(&handle, OsStr::new("f_link"))
6883            .await?;
6884        let orig = src.child(OsStr::new("f")).await?;
6885        let linked = dst.child(OsStr::new("f_link")).await?;
6886        assert_eq!(linked.kind(), EntryKind::File);
6887        assert_eq!(orig.ino(), linked.ino(), "hard link must share the inode");
6888        let content = tokio::fs::read_to_string(tmp.join("dst/f_link")).await?;
6889        assert_eq!(content, "STABLE");
6890        Ok(())
6891    }
6892
6893    // ── fd-based metadata application ───────────────────────────────────────
6894
6895    #[tokio::test]
6896    async fn owned_file_metadata_follows_the_created_inode_after_name_replacement()
6897    -> anyhow::Result<()> {
6898        use std::io::Write as _;
6899        use std::os::unix::fs::{MetadataExt as _, PermissionsExt as _};
6900        let tmp = tempfile::tempdir()?;
6901        let source = tmp.path().join("source");
6902        std::fs::write(&source, b"source")?;
6903        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o751))?;
6904        filetime::set_file_times(
6905            &source,
6906            filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789),
6907            filetime::FileTime::from_unix_time(1_000_000_500, 987_654_321),
6908        )?;
6909        let source_meta = std::fs::metadata(&source)?;
6910        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
6911        let path = tmp.path().join("destination");
6912        let saved = tmp.path().join("saved-destination");
6913        let mut file = root.create_file(OsStr::new("destination")).await?;
6914        file.write_all(b"copied payload")?;
6915        let created = file.metadata()?;
6916        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6917        std::fs::rename(&path, &saved)?;
6918        std::fs::write(&path, b"replacement")?;
6919        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o640))?;
6920        let replacement_before = std::fs::metadata(&path)?;
6921        set_file_metadata_owned(
6922            &crate::preserve::preserve_all(),
6923            &source_meta,
6924            None,
6925            file.into(),
6926            congestion::Side::Destination,
6927        )
6928        .await?;
6929        assert!(
6930            identity.original_is_closed()?,
6931            "metadata retained its consumed descriptor"
6932        );
6933        let applied = std::fs::metadata(&saved)?;
6934        assert_eq!(
6935            (applied.dev(), applied.ino()),
6936            (created.dev(), created.ino())
6937        );
6938        assert_eq!(applied.permissions().mode() & 0o7777, 0o751);
6939        assert_eq!(
6940            std::os::unix::fs::MetadataExt::uid(&applied),
6941            std::os::unix::fs::MetadataExt::uid(&source_meta)
6942        );
6943        assert_eq!(
6944            std::os::unix::fs::MetadataExt::gid(&applied),
6945            std::os::unix::fs::MetadataExt::gid(&source_meta)
6946        );
6947        assert_eq!(
6948            std::os::unix::fs::MetadataExt::atime(&applied),
6949            1_000_000_000
6950        );
6951        assert_eq!(
6952            std::os::unix::fs::MetadataExt::atime_nsec(&applied),
6953            123_456_789
6954        );
6955        assert_eq!(
6956            std::os::unix::fs::MetadataExt::mtime(&applied),
6957            1_000_000_500
6958        );
6959        assert_eq!(
6960            std::os::unix::fs::MetadataExt::mtime_nsec(&applied),
6961            987_654_321
6962        );
6963        let replacement_after = std::fs::metadata(&path)?;
6964        assert_eq!(
6965            (replacement_after.dev(), replacement_after.ino()),
6966            (replacement_before.dev(), replacement_before.ino())
6967        );
6968        assert_eq!(
6969            replacement_after.permissions().mode(),
6970            replacement_before.permissions().mode()
6971        );
6972        assert_eq!(
6973            std::os::unix::fs::MetadataExt::mtime(&replacement_after),
6974            std::os::unix::fs::MetadataExt::mtime(&replacement_before)
6975        );
6976        assert_eq!(
6977            std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_after),
6978            std::os::unix::fs::MetadataExt::mtime_nsec(&replacement_before)
6979        );
6980        assert_eq!(std::fs::read(&saved)?, b"copied payload");
6981        assert_eq!(std::fs::read(&path)?, b"replacement");
6982        Ok(())
6983    }
6984
6985    async fn assert_cancelled_owned_operation_keeps_resources<Fut, T, O>(
6986        file: std::fs::File,
6987        path: &Path,
6988        resource: throttle::Resource,
6989        operation: impl FnOnce(std::fs::File) -> Fut + Send + 'static,
6990        observe_while_gated: impl FnOnce() -> O,
6991    ) -> anyhow::Result<O>
6992    where
6993        Fut: std::future::Future<Output = T> + Send + 'static,
6994        T: Send + 'static,
6995    {
6996        use futures::FutureExt as _;
6997        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
6998        let gate = testutils::BlockingPathGate::install(path);
6999        let limits = testutils::AdmissionLimit::new().await;
7000        limits.set_files_in_flight(1);
7001        limits.set_max_ops_in_flight(resource, 1);
7002        let guard = throttle::open_file_permit().await;
7003        let task = tokio::spawn(with_fd_admission(guard.admission(), async move {
7004            let _guard = guard;
7005            operation(file).await
7006        }));
7007        let mut next_operation = Box::pin(throttle::ops_in_flight_permit(resource));
7008        let (observations, (acquired_operation, observed)) = testutils::cancel_at_blocking_path(
7009            limits,
7010            gate,
7011            task,
7012            std::time::Duration::from_secs(20),
7013            |_| {
7014                (
7015                    next_operation.as_mut().now_or_never(),
7016                    observe_while_gated(),
7017                )
7018            },
7019        )
7020        .await?;
7021        let operation_retained = acquired_operation.is_none();
7022        let permit = match acquired_operation {
7023            Some(permit) => permit,
7024            None => tokio::time::timeout(std::time::Duration::from_secs(5), next_operation).await?,
7025        };
7026        drop(permit);
7027        assert!(observations.waiter_was_cancelled);
7028        assert!(observations.admission_was_retained_while_work_gated);
7029        assert!(observations.fd_was_open_while_work_gated);
7030        assert!(
7031            operation_retained,
7032            "started work released its operation permit after cancellation"
7033        );
7034        assert_eq!(observations.final_hit_count, 1);
7035        assert!(
7036            identity.original_is_closed()?,
7037            "started work returned capacity before closing its owned descriptor"
7038        );
7039        Ok(observed)
7040    }
7041
7042    #[tokio::test]
7043    async fn cancelled_owned_acl_read_retains_source_and_permits_until_started_work_finishes()
7044    -> anyhow::Result<()> {
7045        let tmp = tempfile::tempdir()?;
7046        let path = tmp.path().join("source");
7047        std::fs::write(&path, b"payload")?;
7048        let file = std::fs::File::open(&path)?;
7049        assert_cancelled_owned_operation_keeps_resources(
7050            file,
7051            &path,
7052            throttle::Resource::meta(throttle::Side::Source, throttle::MetadataOp::Stat),
7053            |file| read_acls_owned(file, congestion::Side::Source, false),
7054            || (),
7055        )
7056        .await
7057    }
7058
7059    #[tokio::test]
7060    async fn cancelled_owned_metadata_waiting_for_admission_closes_the_file_without_widening()
7061    -> anyhow::Result<()> {
7062        use std::os::unix::fs::PermissionsExt as _;
7063        let tmp = tempfile::tempdir()?;
7064        let source = tmp.path().join("source");
7065        std::fs::write(&source, b"source")?;
7066        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
7067        let source_meta = std::fs::metadata(&source)?;
7068        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
7069        let path = tmp.path().join("destination");
7070        let file = root.create_file(OsStr::new("destination")).await?;
7071        let identity = testutils::FdIdentityProbe::capture(file.as_raw_fd())?;
7072        let limits = testutils::AdmissionLimit::new().await;
7073        limits.set_files_in_flight(1);
7074        let resource =
7075            throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod);
7076        limits.set_max_ops_in_flight(resource, 1);
7077        let occupied = throttle::ops_in_flight_permit(resource).await;
7078        let guard = throttle::open_file_permit().await;
7079        let admission = guard.admission();
7080        let mut work = Box::pin(with_fd_admission(admission, async move {
7081            let _guard = guard;
7082            set_file_metadata_owned(
7083                &crate::preserve::preserve_all(),
7084                &source_meta,
7085                None,
7086                file.into(),
7087                congestion::Side::Destination,
7088            )
7089            .await
7090        }));
7091        let waiting = futures::poll!(work.as_mut()).is_pending();
7092        let fd_retained = !identity.original_is_closed()?;
7093        let mut next_file = Box::pin(throttle::open_file_permit());
7094        assert!(
7095            futures::poll!(next_file.as_mut()).is_pending(),
7096            "waiting metadata released file admission"
7097        );
7098        drop(work);
7099        let closed = identity.original_is_closed()?;
7100        let file_permit =
7101            tokio::time::timeout(std::time::Duration::from_secs(5), next_file).await?;
7102        drop(file_permit);
7103        drop(occupied);
7104        assert!(
7105            waiting,
7106            "metadata did not wait for its occupied operation permit"
7107        );
7108        assert!(fd_retained);
7109        assert!(
7110            closed,
7111            "cancelled metadata admission retained its owned descriptor"
7112        );
7113        assert_eq!(
7114            std::fs::metadata(path)?.permissions().mode() & 0o7777,
7115            DST_FILE_CREATE_MODE
7116        );
7117        Ok(())
7118    }
7119
7120    #[tokio::test]
7121    async fn cancelled_owned_metadata_retains_the_file_and_permits_until_started_work_finishes()
7122    -> anyhow::Result<()> {
7123        use std::os::unix::fs::PermissionsExt as _;
7124        let tmp = tempfile::tempdir()?;
7125        let source = tmp.path().join("source");
7126        std::fs::write(&source, b"source")?;
7127        std::fs::set_permissions(&source, std::fs::Permissions::from_mode(0o755))?;
7128        let source_meta = std::fs::metadata(&source)?;
7129        let root = Dir::open_root_dir(tmp.path(), false, congestion::Side::Destination).await?;
7130        let path = tmp.path().join("destination");
7131        let file = root.create_file(OsStr::new("destination")).await?;
7132        let mode_while_gated = assert_cancelled_owned_operation_keeps_resources(
7133            file,
7134            &path,
7135            throttle::Resource::meta(throttle::Side::Destination, throttle::MetadataOp::Chmod),
7136            |file| async move {
7137                set_file_metadata_owned(
7138                    &crate::preserve::preserve_all(),
7139                    &source_meta,
7140                    None,
7141                    file.into(),
7142                    congestion::Side::Destination,
7143                )
7144                .await
7145            },
7146            || std::fs::metadata(&path).map(|meta| meta.permissions().mode() & 0o7777),
7147        )
7148        .await?;
7149        assert_eq!(mode_while_gated?, DST_FILE_CREATE_MODE);
7150        assert_eq!(
7151            std::fs::metadata(path)?.permissions().mode() & 0o7777,
7152            DST_FILE_CREATE_MODE
7153        );
7154        Ok(())
7155    }
7156
7157    // set_file_metadata_owned: applying owner/mode/time from a source FileMeta to an
7158    // already-open destination fd must reflect on the destination file: masked
7159    // mode, mtime, and (where testable) uid/gid all match the source.
7160    #[tokio::test]
7161    async fn set_file_metadata_owned_applies_owner_mode_time() -> anyhow::Result<()> {
7162        use std::io::Write;
7163        use std::os::unix::fs::PermissionsExt;
7164        let tmp = testutils::setup_test_dir().await?;
7165        // source file with a distinctive mode and a known, old mtime
7166        let src_path = tmp.join("foo/src_meta.txt");
7167        tokio::fs::write(&src_path, b"source").await?;
7168        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o741))?;
7169        let src_mtime = filetime::FileTime::from_unix_time(1_000_000_000, 123_456_789);
7170        filetime::set_file_mtime(&src_path, src_mtime)?;
7171        filetime::set_file_atime(
7172            &src_path,
7173            filetime::FileTime::from_unix_time(1_000_000_500, 0),
7174        )?;
7175
7176        let root =
7177            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7178        // snapshot the source metadata via a Handle (the realistic source flow)
7179        let src_handle = root.child(OsStr::new("src_meta.txt")).await?;
7180        let src_meta = src_handle.meta().clone();
7181
7182        // create the destination file and write some content into it
7183        let mut dst_file = root.create_file(OsStr::new("dst_meta.txt")).await?;
7184        dst_file.write_all(b"destination")?;
7185        dst_file.flush()?;
7186
7187        // apply source metadata to the already-open dst fd; preserve everything
7188        let settings = crate::preserve::preserve_all();
7189        set_file_metadata_owned(
7190            &settings,
7191            &src_meta,
7192            None,
7193            dst_file.into(),
7194            congestion::Side::Destination,
7195        )
7196        .await?;
7197
7198        // re-stat the destination and assert mode (masked to 0o7777), mtime
7199        let dst_md = std::fs::metadata(tmp.join("foo/dst_meta.txt"))?;
7200        assert_eq!(
7201            dst_md.permissions().mode() & 0o7777,
7202            0o741,
7203            "destination mode mismatch"
7204        );
7205        // disambiguate: both preserve::Metadata and std MetadataExt are in scope
7206        use std::os::unix::fs::MetadataExt;
7207        assert_eq!(
7208            MetadataExt::mtime(&dst_md),
7209            1_000_000_000,
7210            "mtime seconds mismatch"
7211        );
7212        assert_eq!(
7213            MetadataExt::mtime_nsec(&dst_md),
7214            123_456_789,
7215            "mtime nanos mismatch"
7216        );
7217        // uid/gid: chown to source's uid/gid (same as current user here) must hold
7218        assert_eq!(MetadataExt::uid(&dst_md), src_meta.uid(), "uid mismatch");
7219        assert_eq!(MetadataExt::gid(&dst_md), src_meta.gid(), "gid mismatch");
7220        Ok(())
7221    }
7222
7223    // set_file_metadata_owned: chown before chmod must preserve a setuid bit.
7224    // An unprivileged fchown (even to the current uid) clears setuid/setgid; doing
7225    // chown FIRST and chmod AFTER restores it. This test proves that ordering.
7226    #[cfg_attr(
7227        rcp_nix_sandbox,
7228        ignore = "Nix sandbox cannot change ownership or set-id modes"
7229    )]
7230    #[tokio::test]
7231    async fn set_file_metadata_owned_ordering_preserves_setuid() -> anyhow::Result<()> {
7232        use std::io::Write;
7233        use std::os::unix::fs::PermissionsExt;
7234        let tmp = testutils::setup_test_dir().await?;
7235        // source file with the setuid bit set (0o4755)
7236        let src_path = tmp.join("foo/setuid_src");
7237        tokio::fs::write(&src_path, b"x").await?;
7238        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7239
7240        let root =
7241            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7242        let src_handle = root.child(OsStr::new("setuid_src")).await?;
7243        let src_meta = src_handle.meta().clone();
7244        assert_eq!(
7245            src_meta.permissions().mode() & 0o7777,
7246            0o4755,
7247            "source setuid bit was not set up correctly"
7248        );
7249
7250        // destination starts without the setuid bit
7251        let mut dst_file = root.create_file(OsStr::new("setuid_dst")).await?;
7252        dst_file.write_all(b"x")?;
7253        dst_file.flush()?;
7254
7255        // preserve_all keeps the full mode (mask 0o7777) AND preserves uid/gid, so
7256        // the chown runs before the chmod; the setuid bit must survive.
7257        let settings = crate::preserve::preserve_all();
7258        set_file_metadata_owned(
7259            &settings,
7260            &src_meta,
7261            None,
7262            dst_file.into(),
7263            congestion::Side::Destination,
7264        )
7265        .await?;
7266
7267        let dst_md = std::fs::metadata(tmp.join("foo/setuid_dst"))?;
7268        assert_eq!(
7269            dst_md.permissions().mode() & 0o7777,
7270            0o4755,
7271            "setuid bit was lost — chown must run before chmod"
7272        );
7273        Ok(())
7274    }
7275
7276    // set_file_metadata_owned: the widening chmod must be the LAST step. A destination file is created
7277    // owner-only and this call is the only thing that widens it to the source mode, so a fallible
7278    // step running AFTER the chmod would publish that final mode — here a setuid one — on a file the
7279    // copy is about to report as failed. `futimens` is that step. An out-of-range nanosecond field
7280    // makes it fail deterministically, with no privileged uid or hostile filesystem needed.
7281    #[tokio::test]
7282    async fn set_file_metadata_owned_keeps_the_file_owner_only_when_utimens_fails()
7283    -> anyhow::Result<()> {
7284        use std::os::unix::fs::PermissionsExt;
7285
7286        struct RejectedTimestamps;
7287        impl crate::preserve::Metadata for RejectedTimestamps {
7288            fn uid(&self) -> u32 {
7289                // SAFETY: `getuid` has no preconditions and cannot fail.
7290                unsafe { libc::getuid() }
7291            }
7292            fn gid(&self) -> u32 {
7293                // SAFETY: `getgid` has no preconditions and cannot fail.
7294                unsafe { libc::getgid() }
7295            }
7296            fn atime(&self) -> i64 {
7297                0
7298            }
7299            fn atime_nsec(&self) -> i64 {
7300                0
7301            }
7302            fn mtime(&self) -> i64 {
7303                0
7304            }
7305            // utimensat rejects a nanosecond field outside [0, 999999999] that is neither UTIME_NOW
7306            // nor UTIME_OMIT with EINVAL.
7307            fn mtime_nsec(&self) -> i64 {
7308                2_000_000_000
7309            }
7310            fn permissions(&self) -> std::fs::Permissions {
7311                std::fs::Permissions::from_mode(0o4755)
7312            }
7313        }
7314
7315        let tmp = testutils::setup_test_dir().await?;
7316        let root =
7317            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7318        let dst_file = root.create_file(OsStr::new("late_chmod")).await?;
7319        let dst_path = tmp.join("foo/late_chmod");
7320        assert_eq!(
7321            std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
7322            DST_FILE_CREATE_MODE,
7323            "every destination file starts owner-only"
7324        );
7325
7326        // preserve_all: uid/gid so the chown runs first, time so the futimens is reached, and
7327        // mode_mask 0o7777 so the chmod that must NOT run would have set the setuid bit.
7328        let error = set_file_metadata_owned(
7329            &crate::preserve::preserve_all(),
7330            &RejectedTimestamps,
7331            None,
7332            dst_file.into(),
7333            congestion::Side::Destination,
7334        )
7335        .await
7336        .expect_err("an out-of-range nanosecond field must fail futimens");
7337        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
7338
7339        assert_eq!(
7340            std::fs::metadata(&dst_path)?.permissions().mode() & 0o7777,
7341            DST_FILE_CREATE_MODE,
7342            "a failure during metadata application must not leave the final mode behind"
7343        );
7344        Ok(())
7345    }
7346
7347    // set_dir_metadata_fd: applying mode/time to a freshly made directory via its
7348    // Dir fd must reflect on the directory.
7349    #[cfg_attr(
7350        rcp_nix_sandbox,
7351        ignore = "Nix sandbox cannot change ownership or set-id modes"
7352    )]
7353    #[tokio::test]
7354    async fn set_dir_metadata_fd_applies() -> anyhow::Result<()> {
7355        use std::os::unix::fs::{MetadataExt, PermissionsExt};
7356        let tmp = testutils::setup_test_dir().await?;
7357        // source directory with a distinctive mode and known mtime
7358        let src_dir_path = tmp.join("foo/src_dir");
7359        tokio::fs::create_dir(&src_dir_path).await?;
7360        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2750))?;
7361        filetime::set_file_mtime(
7362            &src_dir_path,
7363            filetime::FileTime::from_unix_time(1_111_111_111, 222_000_000),
7364        )?;
7365
7366        let root =
7367            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7368        let src_handle = root.child(OsStr::new("src_dir")).await?;
7369        let src_meta = src_handle.meta().clone();
7370
7371        // create the destination directory and apply metadata via its Dir fd
7372        let dst_dir = root.make_dir(OsStr::new("dst_dir"), 0o700).await?;
7373        let settings = crate::preserve::preserve_all();
7374        set_dir_metadata_fd(&settings, &src_meta, None, &dst_dir).await?;
7375
7376        let dst_md = std::fs::metadata(tmp.join("foo/dst_dir"))?;
7377        assert_eq!(
7378            dst_md.permissions().mode() & 0o7777,
7379            0o2750,
7380            "destination dir mode mismatch"
7381        );
7382        assert_eq!(
7383            MetadataExt::mtime(&dst_md),
7384            1_111_111_111,
7385            "dir mtime seconds mismatch"
7386        );
7387        assert_eq!(
7388            MetadataExt::mtime_nsec(&dst_md),
7389            222_000_000,
7390            "dir mtime nanos mismatch"
7391        );
7392        Ok(())
7393    }
7394
7395    // set_symlink_metadata_fd: applying time (and owner) to a symlink via its
7396    // O_PATH Handle must change the LINK's own atime/mtime — NOT the target's
7397    // mtime. This is the key proof that utimensat(AT_EMPTY_PATH) hit the link.
7398    #[tokio::test]
7399    async fn set_symlink_metadata_fd_changes_link_not_target() -> anyhow::Result<()> {
7400        use std::os::unix::fs::MetadataExt;
7401        let tmp = testutils::setup_test_dir().await?;
7402        let root =
7403            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7404
7405        // sentinel target file with a known mtime we must NOT disturb
7406        let target_path = tmp.join("foo/sentinel_target.txt");
7407        tokio::fs::write(&target_path, b"keep my mtime").await?;
7408        let target_mtime = filetime::FileTime::from_unix_time(1_500_000_000, 0);
7409        filetime::set_file_mtime(&target_path, target_mtime)?;
7410        let target_before = std::fs::metadata(&target_path)?;
7411
7412        // the link to apply metadata to
7413        let link = root
7414            .symlink_at(
7415                OsStr::new("the_link"),
7416                std::path::Path::new("sentinel_target.txt"),
7417            )
7418            .await?;
7419
7420        // desired link timestamps come from a source FileMeta; build one by
7421        // stating a second symlink we set up with a distinctive mtime.
7422        let src_link_path = tmp.join("foo/src_link");
7423        tokio::fs::symlink("sentinel_target.txt", &src_link_path).await?;
7424        let src_link_mtime = filetime::FileTime::from_unix_time(1_234_567_890, 0);
7425        // set the LINK's own mtime (symlink=true) — not the target's
7426        filetime::set_symlink_file_times(
7427            &src_link_path,
7428            filetime::FileTime::from_unix_time(1_234_500_000, 0),
7429            src_link_mtime,
7430        )?;
7431        let src_meta = root.child(OsStr::new("src_link")).await?.meta().clone();
7432
7433        let settings = crate::preserve::preserve_all();
7434        set_symlink_metadata_fd(&settings, &src_meta, &link, congestion::Side::Destination).await?;
7435
7436        // the LINK's own mtime must now equal the source link's mtime
7437        let link_md = std::fs::symlink_metadata(tmp.join("foo/the_link"))?;
7438        assert_eq!(
7439            MetadataExt::mtime(&link_md),
7440            1_234_567_890,
7441            "link's own mtime was not applied"
7442        );
7443        // the TARGET file's mtime must be UNCHANGED
7444        let target_after = std::fs::metadata(&target_path)?;
7445        assert_eq!(
7446            MetadataExt::mtime(&target_after),
7447            MetadataExt::mtime(&target_before),
7448            "target mtime changed — utimensat followed the symlink!"
7449        );
7450        assert_eq!(
7451            MetadataExt::mtime_nsec(&target_after),
7452            MetadataExt::mtime_nsec(&target_before),
7453            "target mtime_nsec changed — utimensat followed the symlink!"
7454        );
7455        Ok(())
7456    }
7457
7458    // rejects_multi_component_names: cover every by-name helper added with fd-relative mutation.
7459    #[tokio::test]
7460    async fn new_methods_reject_multi_component_names() -> anyhow::Result<()> {
7461        let tmp = testutils::setup_test_dir().await?;
7462        let root =
7463            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7464        // a second Dir for hard_link_at's dst parameter
7465        let dst =
7466            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7467        for bad in ["a/b", "..", ".", ""] {
7468            let bad_os = OsStr::new(bad);
7469
7470            let err = root.unlink_at(bad_os).await.unwrap_err();
7471            assert_eq!(
7472                err.raw_os_error(),
7473                Some(libc::EINVAL),
7474                "unlink_at: expected EINVAL for {bad:?}, got {err:#}"
7475            );
7476
7477            let err = root.rmdir_at(bad_os).await.unwrap_err();
7478            assert_eq!(
7479                err.raw_os_error(),
7480                Some(libc::EINVAL),
7481                "rmdir_at: expected EINVAL for {bad:?}, got {err:#}"
7482            );
7483
7484            // symlink_at: only `name` is guarded; target is arbitrary
7485            let err = root
7486                .symlink_at(bad_os, std::path::Path::new("irrelevant"))
7487                .await
7488                .unwrap_err();
7489            assert_eq!(
7490                err.raw_os_error(),
7491                Some(libc::EINVAL),
7492                "symlink_at(name): expected EINVAL for {bad:?}, got {err:#}"
7493            );
7494
7495            let err = root.read_link_at(bad_os).await.unwrap_err();
7496            assert_eq!(
7497                err.raw_os_error(),
7498                Some(libc::EINVAL),
7499                "read_link_at: expected EINVAL for {bad:?}, got {err:#}"
7500            );
7501
7502            // hard_link_at: both `name` and `dst_name` are guarded
7503            let err = root
7504                .hard_link_at(bad_os, &dst, OsStr::new("good"))
7505                .await
7506                .unwrap_err();
7507            assert_eq!(
7508                err.raw_os_error(),
7509                Some(libc::EINVAL),
7510                "hard_link_at(name): expected EINVAL for {bad:?}, got {err:#}"
7511            );
7512
7513            let err = root
7514                .hard_link_at(OsStr::new("good"), &dst, bad_os)
7515                .await
7516                .unwrap_err();
7517            assert_eq!(
7518                err.raw_os_error(),
7519                Some(libc::EINVAL),
7520                "hard_link_at(dst_name): expected EINVAL for {bad:?}, got {err:#}"
7521            );
7522        }
7523        Ok(())
7524    }
7525
7526    // chmod_via_proc_fd: changing the mode of a 0000-mode file through its O_PATH
7527    // handle must succeed (the /proc magic-symlink path does not need any rights on
7528    // the target itself) and the new mode must be observable on disk. This is the
7529    // case `fchmod` (EBADF on O_PATH) and a bare path chmod under restrictive modes
7530    // would struggle with; the pinned inode makes it inode-exact and permission-free.
7531    #[tokio::test]
7532    async fn chmod_via_proc_fd_changes_mode_of_zero_mode_file() -> anyhow::Result<()> {
7533        use std::os::unix::fs::PermissionsExt;
7534        let tmp = testutils::setup_test_dir().await?;
7535        let root =
7536            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7537        // a file with no permission bits at all (0000).
7538        let path = tmp.join("foo/locked.txt");
7539        tokio::fs::write(&path, b"locked").await?;
7540        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000))?;
7541        // O_PATH handle pins the inode even though the file is 0000.
7542        let handle = root.child(OsStr::new("locked.txt")).await?;
7543        assert_eq!(handle.kind(), EntryKind::File, "fixture must be a file");
7544        // chmod it to 0o640 via the /proc magic symlink.
7545        chmod_via_proc_fd(&handle, congestion::Side::Destination, 0o640).await?;
7546        // the mode change must be visible on disk.
7547        let md = std::fs::symlink_metadata(&path)?;
7548        assert_eq!(
7549            md.permissions().mode() & 0o7777,
7550            0o640,
7551            "chmod_via_proc_fd must change the mode of a 0000-mode file"
7552        );
7553        Ok(())
7554    }
7555
7556    // stat_meta_via_proc_fd: on a symlink Handle (opened O_PATH|O_NOFOLLOW), resolving
7557    // /proc/self/fd/N must land on the LINK's own inode — never the target's. This is
7558    // load-bearing for symlink time-filtering (rm/rrm reads a symlink's own mtime/btime to
7559    // decide removal). We give the link and its target DISTINCT mtimes and assert the metadata
7560    // returned is the link's (is_symlink + the link's mtime), proving the magic-symlink resolve
7561    // is pinned to the O_PATH inode and does not follow the link to the target.
7562    #[tokio::test]
7563    async fn stat_meta_via_proc_fd_on_symlink_resolves_link_not_target() -> anyhow::Result<()> {
7564        use std::os::unix::fs::MetadataExt;
7565        let tmp = testutils::setup_test_dir().await?;
7566        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7567
7568        // target file with one mtime ...
7569        let target_path = tmp.join("foo/stat_target.txt");
7570        tokio::fs::write(&target_path, b"target body").await?;
7571        filetime::set_file_mtime(
7572            &target_path,
7573            filetime::FileTime::from_unix_time(1_700_000_000, 0),
7574        )?;
7575
7576        // ... and a symlink to it with a DISTINCT mtime set on the LINK itself (not the target).
7577        let link_path = tmp.join("foo/stat_link");
7578        tokio::fs::symlink("stat_target.txt", &link_path).await?;
7579        filetime::set_symlink_file_times(
7580            &link_path,
7581            filetime::FileTime::from_unix_time(1_600_000_000, 0),
7582            filetime::FileTime::from_unix_time(1_600_000_123, 0),
7583        )?;
7584
7585        // open the symlink via child() — an O_PATH|O_NOFOLLOW handle pinned to the link inode.
7586        let handle = root.child(OsStr::new("stat_link")).await?;
7587        assert_eq!(
7588            handle.kind(),
7589            EntryKind::Symlink,
7590            "fixture must classify as a symlink"
7591        );
7592
7593        let md = stat_meta_via_proc_fd(&handle, congestion::Side::Source).await?;
7594        // the returned metadata must be the LINK's, not the dereferenced target's.
7595        assert!(
7596            md.file_type().is_symlink(),
7597            "stat_meta_via_proc_fd followed the symlink to its target (got a non-symlink)"
7598        );
7599        assert_eq!(
7600            MetadataExt::mtime(&md),
7601            1_600_000_123,
7602            "expected the LINK's own mtime; a target-following stat would return 1_700_000_000"
7603        );
7604        Ok(())
7605    }
7606
7607    // NOTE: the test that ARMS strict operand resolution and exercises the strict
7608    // (openat2) open path lives in tests/strict_resolution.rs — its own integration
7609    // binary and therefore its own process. The switch is one-way, and under the
7610    // plain `cargo test` harness (used by the nix checkPhase) a lib's unit tests
7611    // share one process, so arming here would leak into the symlink-following
7612    // default-behavior tests above.
7613
7614    #[test]
7615    fn openat2_probe_is_stable() {
7616        // the probe is memoized; both calls must agree. On kernels without openat2 a
7617        // `false` result is the correct answer (the linter then refuses strict mode),
7618        // so no hard assertion on availability itself.
7619        let first = openat2_available();
7620        assert_eq!(first, openat2_available(), "probe must be stable");
7621        if !first {
7622            eprintln!("this kernel lacks openat2(2); strict-mode tests skip themselves");
7623        }
7624    }
7625
7626    // ── POSIX ACLs ──────────────────────────────────────────────────────────
7627
7628    use crate::testutils::acl::*;
7629
7630    fn mode_of(path: &std::path::Path) -> u32 {
7631        use std::os::unix::fs::PermissionsExt as _;
7632        std::fs::metadata(path).unwrap().permissions().mode() & 0o7777
7633    }
7634
7635    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7636    #[tokio::test]
7637    async fn read_acls_owned_returns_the_same_source_descriptor_after_name_replacement()
7638    -> anyhow::Result<()> {
7639        use std::io::Read as _;
7640        let tmp = tempfile::tempdir()?;
7641        let path = tmp.path().join("source");
7642        std::fs::write(&path, b"original")?;
7643        let blob = restrictive_access_acl();
7644        set_xattr_at(&path, ACL_ACCESS_XATTR, &blob);
7645        let file = std::fs::File::open(&path)?;
7646        let raw_fd = file.as_raw_fd();
7647        std::fs::rename(&path, tmp.path().join("original"))?;
7648        std::fs::write(&path, b"replacement")?;
7649        set_xattr_at(&path, ACL_ACCESS_XATTR, &permissive_acl());
7650        let (mut file, acls) = read_acls_owned(file, congestion::Side::Source, false).await?;
7651        assert_eq!(file.as_raw_fd(), raw_fd);
7652        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7653        assert_eq!(acls.default, None);
7654        let mut bytes = Vec::new();
7655        file.read_to_end(&mut bytes)?;
7656        assert_eq!(bytes, b"original");
7657        Ok(())
7658    }
7659
7660    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7661    #[tokio::test]
7662    async fn read_acls_fd_round_trips_an_access_acl() -> anyhow::Result<()> {
7663        let tmp = testutils::setup_test_dir().await?;
7664        let src_path = tmp.join("foo/acl_src");
7665        tokio::fs::write(&src_path, b"x").await?;
7666        let blob = restrictive_access_acl();
7667        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7668        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7669        let (file, _) = root.open_file_read(OsStr::new("acl_src")).await?;
7670        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7671        // byte-identical: the blob is carried opaquely, never re-encoded
7672        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7673        assert_eq!(acls.default, None, "a file has no default ACL to read");
7674        Ok(())
7675    }
7676
7677    // An ACL far larger than the stack buffers, so BOTH `ERANGE` fallbacks run: the name list is
7678    // padded past 256 bytes with `user.*` attributes, and the blob past 512 by entry count (a blob
7679    // is `4 + 8n` bytes, so 64 entries fill the buffer exactly and 80 overflow it). Without the
7680    // retry paths this fails rather than silently truncating — `fgetxattr` refuses a short buffer.
7681    // tmpfs gained user.* xattr support in Linux 6.6, so older sandbox kernels cannot construct the
7682    // padded name list even apart from the POSIX ACL restriction
7683    #[cfg_attr(
7684        rcp_nix_sandbox,
7685        ignore = "Nix sandbox cannot provide both POSIX ACL and user xattrs this test requires"
7686    )]
7687    #[tokio::test]
7688    async fn read_acls_fd_reads_an_acl_larger_than_the_stack_buffers() -> anyhow::Result<()> {
7689        let tmp = testutils::setup_test_dir().await?;
7690        let src_path = tmp.join("foo/big_acl");
7691        tokio::fs::write(&src_path, b"x").await?;
7692        // canonical POSIX.1e order — USER_OBJ, named users by ascending uid, GROUP_OBJ, MASK,
7693        // OTHER. The kernel validates it and rejects anything else with EINVAL.
7694        let mut entries = vec![(ACL_USER_OBJ, 7, ACL_UNDEFINED_ID)];
7695        entries.extend((0..80).map(|i| (ACL_USER, 5, 100_000 + i)));
7696        entries.extend([
7697            (ACL_GROUP_OBJ, 0, ACL_UNDEFINED_ID),
7698            (ACL_MASK, 5, ACL_UNDEFINED_ID),
7699            (ACL_OTHER, 0, ACL_UNDEFINED_ID),
7700        ]);
7701        let blob = encode_acl(&entries);
7702        assert!(blob.len() > 512, "fixture must overflow the read buffer");
7703        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7704        // push the NAME list past its own 256-byte buffer too
7705        for i in 0..30 {
7706            let name = std::ffi::CString::new(format!("user.padding_attribute_number_{i:03}"))?;
7707            set_xattr_at(&src_path, &name, b"v");
7708        }
7709        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7710        let (file, _) = root.open_file_read(OsStr::new("big_acl")).await?;
7711        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7712        assert_eq!(acls.access.as_deref(), Some(blob.as_slice()));
7713        Ok(())
7714    }
7715
7716    #[tokio::test]
7717    async fn read_acls_fd_reports_no_acl_when_there_is_none() -> anyhow::Result<()> {
7718        let tmp = testutils::setup_test_dir().await?;
7719        let root = Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Source).await?;
7720        let (file, _) = root.open_file_read(OsStr::new("0.txt")).await?;
7721        let acls = read_acls_fd(file.as_fd(), congestion::Side::Source, false).await?;
7722        assert_eq!(acls, Acls::default(), "an entry with no xattrs has no ACL");
7723        Ok(())
7724    }
7725
7726    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7727    #[tokio::test]
7728    async fn read_acls_fd_reads_a_directorys_default_acl_only_when_asked() -> anyhow::Result<()> {
7729        let tmp = testutils::setup_test_dir().await?;
7730        let dir_path = tmp.join("foo/acl_dir");
7731        tokio::fs::create_dir(&dir_path).await?;
7732        let access = restrictive_access_acl();
7733        let default = permissive_acl();
7734        set_xattr_at(&dir_path, ACL_ACCESS_XATTR, &access);
7735        set_xattr_at(&dir_path, ACL_DEFAULT_XATTR, &default);
7736        let dir = Dir::open_root_dir(&dir_path, false, congestion::Side::Source).await?;
7737        let both = dir.read_acls().await?;
7738        assert_eq!(both.access.as_deref(), Some(access.as_slice()));
7739        assert_eq!(both.default.as_deref(), Some(default.as_slice()));
7740        // `want_default: false` is what the file path passes; it must not spend the extra syscall
7741        let access_only = read_acls_fd(dir.fd.as_fd(), congestion::Side::Source, false).await?;
7742        assert_eq!(access_only.access.as_deref(), Some(access.as_slice()));
7743        assert_eq!(access_only.default, None);
7744        Ok(())
7745    }
7746
7747    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
7748    #[tokio::test]
7749    async fn apply_acls_fd_installs_the_source_acl_and_clears_what_the_source_lacked()
7750    -> anyhow::Result<()> {
7751        let tmp = testutils::setup_test_dir().await?;
7752        let dst_path = tmp.join("foo/applied");
7753        tokio::fs::write(&dst_path, b"x").await?;
7754        let root =
7755            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7756        let (file, _) = root.open_file_read(OsStr::new("applied")).await?;
7757        let blob = restrictive_access_acl();
7758        apply_acls_fd(
7759            file.as_fd(),
7760            congestion::Side::Destination,
7761            &Acls {
7762                access: Some(blob.clone()),
7763                default: None,
7764            },
7765            false,
7766        )
7767        .await?;
7768        assert_eq!(
7769            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7770            Some(blob.as_slice())
7771        );
7772        // an all-`None` payload is a request to CLEAR, not to do nothing
7773        apply_acls_fd(
7774            file.as_fd(),
7775            congestion::Side::Destination,
7776            &Acls::default(),
7777            false,
7778        )
7779        .await?;
7780        assert_eq!(get_xattr_at(&dst_path, ACL_ACCESS_XATTR), None);
7781        // and clearing again, with nothing there, still succeeds (ENODATA is not a failure)
7782        apply_acls_fd(
7783            file.as_fd(),
7784            congestion::Side::Destination,
7785            &Acls::default(),
7786            false,
7787        )
7788        .await?;
7789        Ok(())
7790    }
7791
7792    #[tokio::test]
7793    async fn apply_acls_fd_fails_a_set_the_filesystem_cannot_hold_but_not_a_remove()
7794    -> anyhow::Result<()> {
7795        // `/proc` holds no xattrs at all, so both operations get EOPNOTSUPP — the asymmetry under
7796        // test is entirely in how each is interpreted.
7797        let probe = std::fs::File::open("/proc/self/environ")?;
7798        let error = apply_acls_fd(
7799            probe.as_fd(),
7800            congestion::Side::Destination,
7801            &Acls {
7802                access: Some(restrictive_access_acl()),
7803                default: None,
7804            },
7805            false,
7806        )
7807        .await
7808        .expect_err("a destination that cannot hold the source's ACL must fail the entry");
7809        assert_eq!(error.raw_os_error(), Some(libc::EOPNOTSUPP));
7810        // the same errno on a REMOVE says there is nothing to clear and nothing can have widened
7811        apply_acls_fd(
7812            probe.as_fd(),
7813            congestion::Side::Destination,
7814            &Acls::default(),
7815            false,
7816        )
7817        .await
7818        .expect("clearing an ACL a filesystem cannot hold is already satisfied");
7819        Ok(())
7820    }
7821
7822    // ORDERING, branch 1 (the source HAS an access ACL): the narrowed chmod carries the special
7823    // bits, the `fsetxattr` lands the rwx bits, and both survive together.
7824    #[cfg_attr(
7825        rcp_nix_sandbox,
7826        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7827    )]
7828    #[tokio::test]
7829    async fn set_file_metadata_owned_applies_a_setuid_source_mode_and_its_acl() -> anyhow::Result<()>
7830    {
7831        use std::io::Write;
7832        use std::os::unix::fs::PermissionsExt;
7833        let tmp = testutils::setup_test_dir().await?;
7834        let src_path = tmp.join("foo/acl_setuid_src");
7835        tokio::fs::write(&src_path, b"x").await?;
7836        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4700))?;
7837        let blob = restrictive_access_acl();
7838        set_xattr_at(&src_path, ACL_ACCESS_XATTR, &blob);
7839        // writing the ACL moved the source's own rwx bits to match it (USER_OBJ / MASK / OTHER);
7840        // that equality is exactly what the destination has to reproduce.
7841        assert_eq!(mode_of(&src_path), 0o4755, "fixture source mode");
7842        let root =
7843            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7844        let src_handle = root.child(OsStr::new("acl_setuid_src")).await?;
7845        let src_meta = src_handle.meta().clone();
7846        let mut dst_file = root.create_file(OsStr::new("acl_setuid_dst")).await?;
7847        dst_file.write_all(b"x")?;
7848        dst_file.flush()?;
7849        set_file_metadata_owned(
7850            &crate::preserve::preserve_all_with_acls(),
7851            &src_meta,
7852            Some(&Acls {
7853                access: Some(blob.clone()),
7854                default: None,
7855            }),
7856            dst_file.into(),
7857            congestion::Side::Destination,
7858        )
7859        .await?;
7860        let dst_path = tmp.join("foo/acl_setuid_dst");
7861        assert_eq!(
7862            mode_of(&dst_path),
7863            mode_of(&src_path),
7864            "the special bits come from the chmod and the rwx bits from the ACL; both must land"
7865        );
7866        assert_eq!(mode_of(&dst_path), 0o4755);
7867        assert_eq!(
7868            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7869            Some(blob.as_slice()),
7870            "the destination must not be more permissive than its source"
7871        );
7872        Ok(())
7873    }
7874
7875    // ORDERING, branch 1 under failure: the `fsetxattr` IS the widening step, so when it fails the
7876    // file must be left unreachable by anyone but the copier. This is what pins the preceding chmod
7877    // to `(mode & 0o7000) | DST_FILE_CREATE_MODE`: widening there and failing here would publish a
7878    // setuid-root file whose copy is about to be reported as failed (PR #287's regression).
7879    #[cfg_attr(
7880        rcp_nix_sandbox,
7881        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7882    )]
7883    #[tokio::test]
7884    async fn set_file_metadata_owned_keeps_the_file_owner_only_when_the_acl_fails()
7885    -> anyhow::Result<()> {
7886        use std::os::unix::fs::PermissionsExt;
7887        let tmp = testutils::setup_test_dir().await?;
7888        let src_path = tmp.join("foo/acl_fail_src");
7889        tokio::fs::write(&src_path, b"x").await?;
7890        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7891        let root =
7892            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7893        let src_meta = root.child(OsStr::new("acl_fail_src")).await?.meta().clone();
7894        let dst_file = root.create_file(OsStr::new("acl_fail_dst")).await?;
7895        let dst_path = tmp.join("foo/acl_fail_dst");
7896        let error = set_file_metadata_owned(
7897            &crate::preserve::preserve_all_with_acls(),
7898            &src_meta,
7899            Some(&Acls {
7900                access: Some(rejected_access_acl()),
7901                default: None,
7902            }),
7903            dst_file.into(),
7904            congestion::Side::Destination,
7905        )
7906        .await
7907        .expect_err("an ACL the kernel rejects must fail the entry");
7908        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
7909        assert_eq!(
7910            mode_of(&dst_path),
7911            0o4000 | DST_FILE_CREATE_MODE,
7912            "the chmod preceding a source ACL must carry the special bits ALONE — a failed ACL \
7913             application left the file at a mode it had not earned"
7914        );
7915        Ok(())
7916    }
7917
7918    // ORDERING, branch 2 (the source has NO access ACL): the chmod is the widening step and stays
7919    // last, and the clear that precedes it is mode-neutral. Inverting the branch condition sends
7920    // this case down the narrowed-chmod path and leaves the file at 0o4600.
7921    #[cfg_attr(
7922        rcp_nix_sandbox,
7923        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7924    )]
7925    #[tokio::test]
7926    async fn set_file_metadata_owned_clears_an_inherited_acl_and_still_applies_the_full_mode()
7927    -> anyhow::Result<()> {
7928        use std::io::Write;
7929        use std::os::unix::fs::PermissionsExt;
7930        let tmp = testutils::setup_test_dir().await?;
7931        let src_path = tmp.join("foo/plain_setuid_src");
7932        tokio::fs::write(&src_path, b"x").await?;
7933        std::fs::set_permissions(&src_path, std::fs::Permissions::from_mode(0o4755))?;
7934        let root =
7935            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7936        let src_meta = root
7937            .child(OsStr::new("plain_setuid_src"))
7938            .await?
7939            .meta()
7940            .clone();
7941        let mut dst_file = root.create_file(OsStr::new("plain_setuid_dst")).await?;
7942        dst_file.write_all(b"x")?;
7943        dst_file.flush()?;
7944        let dst_path = tmp.join("foo/plain_setuid_dst");
7945        // stand in for what a permissive destination directory's default ACL would have left here
7946        set_xattr_at(&dst_path, ACL_ACCESS_XATTR, &permissive_acl());
7947        set_file_metadata_owned(
7948            &crate::preserve::preserve_all_with_acls(),
7949            &src_meta,
7950            Some(&Acls::default()),
7951            dst_file.into(),
7952            congestion::Side::Destination,
7953        )
7954        .await?;
7955        assert_eq!(
7956            get_xattr_at(&dst_path, ACL_ACCESS_XATTR),
7957            None,
7958            "a source with no ACL must leave the destination with no ACL"
7959        );
7960        assert_eq!(
7961            mode_of(&dst_path),
7962            0o4755,
7963            "without a source ACL the chmod is the widening step and applies the FULL mode"
7964        );
7965        Ok(())
7966    }
7967
7968    #[cfg_attr(
7969        rcp_nix_sandbox,
7970        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
7971    )]
7972    #[tokio::test]
7973    async fn set_dir_metadata_fd_installs_access_and_default_acls() -> anyhow::Result<()> {
7974        let tmp = testutils::setup_test_dir().await?;
7975        let root =
7976            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
7977        let src_dir_path = tmp.join("foo/acl_src_dir");
7978        tokio::fs::create_dir(&src_dir_path).await?;
7979        let access = restrictive_access_acl();
7980        let default = permissive_acl();
7981        set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
7982        set_xattr_at(&src_dir_path, ACL_DEFAULT_XATTR, &default);
7983        let src_meta = root.child(OsStr::new("acl_src_dir")).await?.meta().clone();
7984        let dst_dir = root.make_dir(OsStr::new("acl_dst_dir"), 0o700).await?;
7985        let dst_path = tmp.join("foo/acl_dst_dir");
7986        set_dir_metadata_fd(
7987            &crate::preserve::preserve_all_with_acls(),
7988            &src_meta,
7989            Some(&Acls {
7990                access: Some(access.clone()),
7991                default: Some(default.clone()),
7992            }),
7993            &dst_dir,
7994        )
7995        .await?;
7996        assert_eq!(
7997            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
7998            Some(access.as_slice())
7999        );
8000        assert_eq!(
8001            get_xattr_at(&dst_path, ACL_DEFAULT_XATTR).as_deref(),
8002            Some(default.as_slice()),
8003            "the default ACL decides what CHILDREN inherit; dropping it changes the destination \
8004             tree's inheritance policy"
8005        );
8006        assert_eq!(mode_of(&dst_path), mode_of(&src_dir_path));
8007        assert_eq!(mode_of(&dst_path), 0o755);
8008        Ok(())
8009    }
8010
8011    // The access ACL is applied LAST inside `apply_acls_fd` for the same reason it is applied last
8012    // in the file applier: it is the step that WIDENS. A default ACL the kernel rejects must
8013    // therefore fail while the directory is still at its owner-only create mode.
8014    #[cfg_attr(
8015        rcp_nix_sandbox,
8016        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
8017    )]
8018    #[tokio::test]
8019    async fn set_dir_metadata_fd_keeps_the_dir_owner_only_when_the_default_acl_fails()
8020    -> anyhow::Result<()> {
8021        use std::os::unix::fs::PermissionsExt;
8022        let tmp = testutils::setup_test_dir().await?;
8023        let root =
8024            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8025        let src_dir_path = tmp.join("foo/acl_dfail_src");
8026        tokio::fs::create_dir(&src_dir_path).await?;
8027        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o755))?;
8028        let src_meta = root
8029            .child(OsStr::new("acl_dfail_src"))
8030            .await?
8031            .meta()
8032            .clone();
8033        let dst_dir = root.make_dir(OsStr::new("acl_dfail_dst"), 0o700).await?;
8034        let error = set_dir_metadata_fd(
8035            &crate::preserve::preserve_all_with_acls(),
8036            &src_meta,
8037            Some(&Acls {
8038                access: Some(permissive_acl()),
8039                default: Some(rejected_access_acl()),
8040            }),
8041            &dst_dir,
8042        )
8043        .await
8044        .expect_err("a default ACL the kernel rejects must fail the entry");
8045        assert_eq!(error.raw_os_error(), Some(libc::EINVAL));
8046        assert_eq!(
8047            mode_of(&tmp.join("foo/acl_dfail_dst")),
8048            DST_DIR_CREATE_MODE,
8049            "the access ACL must be applied LAST: a failing default apply left the directory wider"
8050        );
8051        Ok(())
8052    }
8053
8054    // The reused-directory finalize re-stats and verifies the mode it applied. Its `want_mode` is
8055    // still `masked_mode`, which stays correct with an ACL in play only because the source's own
8056    // rwx bits and its ACL are the same fact — worth a test rather than a comment, and worth doing
8057    // it on a SETGID directory, where the special bit comes from the chmod and the rwx bits from
8058    // the ACL.
8059    #[cfg_attr(
8060        rcp_nix_sandbox,
8061        ignore = "Nix sandbox cannot write POSIX ACL xattrs or set-id modes"
8062    )]
8063    #[tokio::test]
8064    async fn set_reused_dir_metadata_fd_verifies_a_setgid_source_with_an_acl() -> anyhow::Result<()>
8065    {
8066        use std::os::unix::fs::PermissionsExt;
8067        let tmp = testutils::setup_test_dir().await?;
8068        let root =
8069            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8070        let src_dir_path = tmp.join("foo/setgid_acl_src");
8071        tokio::fs::create_dir(&src_dir_path).await?;
8072        std::fs::set_permissions(&src_dir_path, std::fs::Permissions::from_mode(0o2700))?;
8073        let access = restrictive_access_acl();
8074        set_xattr_at(&src_dir_path, ACL_ACCESS_XATTR, &access);
8075        let src_meta = root
8076            .child(OsStr::new("setgid_acl_src"))
8077            .await?
8078            .meta()
8079            .clone();
8080        assert_eq!(
8081            mode_of(&src_dir_path),
8082            0o2755,
8083            "fixture must keep setgid alongside the ACL (whose MASK set the group bits)"
8084        );
8085        let dst_dir = root.make_dir(OsStr::new("setgid_acl_dst"), 0o700).await?;
8086        let (uid, gid) = {
8087            let meta = dst_dir.meta().await?;
8088            use crate::preserve::Metadata as _;
8089            (meta.uid(), meta.gid())
8090        };
8091        // `Some(lock)` is the strict-mode locked path — the one that verifies. The snapshot is
8092        // empty and irrelevant here: `d:acl` is on, so the SOURCE's ACL wins and the snapshot is
8093        // discarded.
8094        set_reused_dir_metadata_fd(
8095            &crate::preserve::preserve_all_with_acls(),
8096            &src_meta,
8097            Some(&Acls {
8098                access: Some(access.clone()),
8099                default: None,
8100            }),
8101            Some(ReusedDirLock {
8102                restore_owner: (uid, gid),
8103                state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Armed {
8104                    original: None,
8105                })),
8106                fd: Arc::clone(&dst_dir.fd),
8107                children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
8108            }),
8109            &dst_dir,
8110        )
8111        .await?;
8112        let dst_path = tmp.join("foo/setgid_acl_dst");
8113        assert_eq!(
8114            mode_of(&dst_path),
8115            0o2755,
8116            "setgid from the chmod, rwx from the ACL"
8117        );
8118        assert_eq!(
8119            get_xattr_at(&dst_path, ACL_ACCESS_XATTR).as_deref(),
8120            Some(access.as_slice())
8121        );
8122        Ok(())
8123    }
8124
8125    #[tokio::test]
8126    async fn appliers_refuse_a_call_site_that_did_not_carry_acls() -> anyhow::Result<()> {
8127        let tmp = testutils::setup_test_dir().await?;
8128        let root =
8129            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8130        let src_meta = root.child(OsStr::new("0.txt")).await?.meta().clone();
8131        let dst_file = root.create_file(OsStr::new("no_acls_carried")).await?;
8132        // `acl` on but no payload: neither "leave it alone" nor "clear it" reproduces the source,
8133        // so the applier must refuse rather than silently pick one.
8134        let error = set_file_metadata_owned(
8135            &crate::preserve::preserve_all_with_acls(),
8136            &src_meta,
8137            None,
8138            dst_file.into(),
8139            congestion::Side::Destination,
8140        )
8141        .await
8142        .expect_err("requesting ACL preservation on a path that carries no ACLs must fail");
8143        assert_eq!(error.kind(), std::io::ErrorKind::Unsupported);
8144        // with `acl` off the same call site is correct and must stay silent
8145        let dst_file = root.create_file(OsStr::new("acls_not_requested")).await?;
8146        set_file_metadata_owned(
8147            &crate::preserve::preserve_all(),
8148            &src_meta,
8149            None,
8150            dst_file.into(),
8151            congestion::Side::Destination,
8152        )
8153        .await?;
8154        Ok(())
8155    }
8156
8157    #[cfg_attr(rcp_nix_sandbox, ignore = "Nix sandbox cannot write POSIX ACL xattrs")]
8158    #[tokio::test]
8159    async fn guarded_default_acl_write_is_skipped_once_disarmed() -> anyhow::Result<()> {
8160        let tmp = testutils::setup_test_dir().await?;
8161        let root =
8162            Dir::open_root_dir(&tmp.join("foo"), false, congestion::Side::Destination).await?;
8163        let dir = root.make_dir(OsStr::new("locked"), 0o700).await?;
8164        // a guard whose restore has already run (the owning future was cancelled and the guard
8165        // dropped): a finalize write that already started on the blocking pool must observe that
8166        // and SKIP — landing it would silently overwrite the restore
8167        let lock = ReusedDirLock {
8168            restore_owner: (0, 0),
8169            state: Arc::new(std::sync::Mutex::new(DefaultAclGuard::Disarmed)),
8170            fd: Arc::clone(&dir.fd),
8171            children_may_inherit: Arc::new(std::sync::atomic::AtomicBool::new(false)),
8172        };
8173        lock.write_default_acl_guarded(congestion::Side::Destination, restrictive_access_acl())
8174            .await?;
8175        assert_eq!(
8176            get_xattr_at(&tmp.join("foo/locked"), ACL_DEFAULT_XATTR),
8177            None,
8178            "a disarmed guard must refuse the write — landing it would undo the restore"
8179        );
8180        Ok(())
8181    }
8182}