Skip to main content

ant_node/devnet/
run_dir.rs

1//! A devnet run's own data directory, and the one rule for deleting one: a
2//! devnet deletes only a directory it can show it created (ant-node#261).
3//!
4//! Each run creates a fresh `{pid}-{random}` directory inside the configured
5//! parent, exclusively, and claims it only if, once opened, it is still empty
6//! and, on Unix, owned by the run's user, so it never adopts something that
7//! was already there or that another user put in its place. (A process of
8//! the run's own user could put an empty directory there, but it could as
9//! well delete whatever the run keeps: no check could hold that line. On
10//! Windows, which has no owner check without unsafe code, the parent's
11//! permissions decide who could.) Before anything else goes in, it takes an exclusive lock on
12//! [`LOCK_FILE`], held for as long as the run lasts, and then writes
13//! [`MARKER_FILE`] naming the run, the directory itself and the lock file,
14//! by their file numbers (inode, or file index on Windows): a copy of the
15//! marker in any other directory does not match, nor does a lock file put
16//! in place of the one the run holds. The parent itself is never deleted.
17//!
18//! - On shutdown a run deletes its directory through the handle it opened
19//!   when it created it, and only if the name still refers to that directory
20//!   and the marker there still names the run.
21//! - Anything else, a later run included, may delete a run directory only if
22//!   it belongs to the user (on Unix), is on the parent's filesystem and
23//!   mount, its marker names that very directory and does not ask to keep it
24//!   (`--no-cleanup`), and the lock file the
25//!   marker names is there and free. The OS releases the lock however the
26//!   process ends, SIGKILL included, and only a run's own process ever takes
27//!   it, so a free lock means the run is over. A directory without such a
28//!   marker is never touched. (The marker keeps no device number: on some
29//!   filesystems, btrfs and NFS among them, that changes when they are
30//!   mounted again.)
31//! - Deletion first checks that the name still refers to the directory it
32//!   has open, then removes the data, and the marker and lock last, so one
33//!   that stops part-way leaves a directory the next run still recognises as
34//!   a finished run, and finishes. It does not cross into another mount: on
35//!   Linux mounts are told apart by their mount ids, which tell a bind mount
36//!   from the filesystem it shows, and where the kernel cannot give one (it
37//!   is older than 5.8, or a sandbox refuses `statx`) nothing is deleted.
38//!   macOS has no bind mounts, so there the device tells them apart.
39//!
40//! On Unix every step after the parent is opened goes through a handle on the
41//! parent or the run directory, and deletion walks the tree through handles
42//! opened without following links. The handles do not keep the paths still,
43//! though. Whoever can write to a directory can rename what is in it: swap a
44//! directory above the run directory for a link to another tree, which
45//! writes through [`RunDir::path`] would then follow, or move the run
46//! directory away while it is being deleted. So the parent must be one no
47//! other user can change: it, and every directory above it, must belong to
48//! the user or root, and be one no one else can write to, or sticky, as
49//! `/tmp` is, which lets no one rename what they do not own. (On Linux, one
50//! its group can write to passes if the group is the user's own, as with
51//! Ubuntu's user private groups, and no ACL lets anyone else in. On macOS,
52//! where every user shares a group, it does not.) A run refuses to start in
53//! any other parent. Windows has no such calls in the standard library.
54//! There, links in the parent's path are resolved once, and the
55//! parent and the run directory are held open without delete sharing: while
56//! they are, neither they nor any directory above them can be renamed or
57//! removed, so the paths built on them keep naming the same directories, and
58//! [`std::fs::remove_dir_all`] does not follow links inside the tree. Either
59//! way, retargeting a link above the run directory mid-run redirects nothing:
60//! not the deletion, and not what is written through [`RunDir::path`], which
61//! has the links in the parent's path resolved.
62
63use crate::logging::{debug, info, warn};
64use rand::Rng;
65use serde::{Deserialize, Serialize};
66use std::fs::{File, TryLockError};
67use std::io::{self, Read, Write};
68use std::path::{Path, PathBuf};
69use std::time::{SystemTime, UNIX_EPOCH};
70
71/// File in a run directory naming the run it belongs to (JSON).
72pub const MARKER_FILE: &str = ".ant-devnet-run.json";
73
74/// File in a run directory whose exclusive lock the run holds while it lasts.
75pub const LOCK_FILE: &str = ".ant-devnet-run.lock";
76
77/// The marker is written here first and renamed into place, so a reader sees
78/// either no marker or a whole one.
79const MARKER_TEMP_FILE: &str = ".ant-devnet-run.json.tmp";
80
81/// A marker is a few hundred bytes. Anything larger is not one.
82const MAX_MARKER_LEN: usize = 4096;
83
84/// Names tried before giving up when a random name is already taken.
85const CREATE_ATTEMPTS: usize = 8;
86
87/// What [`MARKER_FILE`] holds.
88#[derive(Debug, Serialize, Deserialize)]
89struct Marker {
90    /// Random and unique to the run.
91    run_id: String,
92    /// The run directory's file number on its filesystem ([`FileId::file`]).
93    file_id: u64,
94    /// The lock file's, so that one put in its place does not pass for it.
95    lock_id: u64,
96    /// The process that ran the devnet.
97    pid: u32,
98    /// When the run started, in seconds since the Unix epoch.
99    started_at: u64,
100    /// The ant-node version that wrote the marker.
101    version: String,
102    /// Set by `--no-cleanup`: nothing but the user deletes this directory.
103    keep: bool,
104}
105
106/// Which directory or file a handle or a name refers to.
107#[derive(Debug, PartialEq, Eq)]
108struct FileId {
109    /// Its device (Unix) or volume serial number (Windows). Compared only
110    /// between handles open at the same time, never kept.
111    device: String,
112    /// Its inode (Unix) or file index (Windows).
113    file: u64,
114}
115
116/// This run's directory: created, locked and marked by [`RunDir::create`].
117///
118/// Dropping it releases the lock and leaves the directory, which a later run
119/// then removes unless it is kept.
120pub struct RunDir {
121    path: PathBuf,
122    name: String,
123    run_id: String,
124    parent: Parent,
125    /// The directory as created, held open until it is deleted.
126    run: Run,
127    lock: File,
128}
129
130impl RunDir {
131    /// Create a fresh run directory inside `parent`, creating `parent` first
132    /// if it does not exist. Run directories that earlier runs left in
133    /// `parent`, and that are over and not kept, are removed first.
134    ///
135    /// `keep` marks the directory as one that nothing but the user deletes.
136    ///
137    /// # Errors
138    ///
139    /// Fails if `parent` cannot be created or opened, or, on Unix, another
140    /// user could change it or a directory above it (see the module docs); or
141    /// if the run directory cannot be created, locked or marked.
142    pub fn create(parent: &Path, keep: bool) -> io::Result<Self> {
143        let parent = Parent::open(parent)?;
144        sweep(&parent);
145
146        let pid = std::process::id();
147        let mut rng = rand::thread_rng();
148        let mut attempt = 0;
149        let name = loop {
150            let name = format!("{pid}-{:08x}", rng.gen::<u32>());
151            match parent.create_run(&name) {
152                Ok(()) => break name,
153                Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
154                    attempt += 1;
155                    if attempt == CREATE_ATTEMPTS {
156                        return Err(e);
157                    }
158                }
159                Err(e) => return Err(e),
160            }
161        };
162
163        #[cfg(test)]
164        after_create(&parent.path.join(&name))?;
165        let run = parent.open_run(&name)?;
166        // Between its creation and its opening, something else could have put
167        // a directory of its own in place of this one. If what was opened has
168        // anything in it, or another user owns it, it is not this run's:
169        // leave it as it is.
170        #[cfg(unix)]
171        let replaced = !run.is_empty()? || !run.is_owned_by_this_user()?;
172        #[cfg(windows)]
173        let replaced = !run.is_empty()?;
174        if replaced {
175            return Err(io::Error::new(
176                io::ErrorKind::AlreadyExists,
177                format!(
178                    "{} was replaced before this run could open it",
179                    parent.path.join(&name).display()
180                ),
181            ));
182        }
183        let claimed = run.id().and_then(|id| {
184            let mut marker = Marker {
185                run_id: hex::encode(rng.gen::<[u8; 16]>()),
186                file_id: id.file,
187                // Set by `claim`, once the lock file exists.
188                lock_id: 0,
189                pid,
190                started_at: SystemTime::now()
191                    .duration_since(UNIX_EPOCH)
192                    .map_or(0, |since| since.as_secs()),
193                version: env!("CARGO_PKG_VERSION").to_string(),
194                keep,
195            };
196            let lock = claim(&run, &mut marker)?;
197            Ok((marker.run_id, lock))
198        });
199        let (run_id, lock) = match claimed {
200            Ok(claimed) => claimed,
201            Err(e) => {
202                // Unmarked, it would be left alone for good, so remove it, but
203                // only if it is empty: claiming has removed what it created,
204                // and anything else in it is not known to be this run's.
205                if let Err(cleanup) =
206                    same_dir(&parent, &name, &run).and_then(|()| parent.remove_empty(&name, run))
207                {
208                    warn!("Could not remove half-created devnet run directory {name}: {cleanup}");
209                }
210                return Err(e);
211            }
212        };
213
214        Ok(Self {
215            path: parent.path.join(&name),
216            name,
217            run_id,
218            parent,
219            run,
220            lock,
221        })
222    }
223
224    /// The run directory, with any link in the parent's path resolved, so
225    /// that retargeting one does not redirect what is written through it.
226    pub fn path(&self) -> &Path {
227        &self.path
228    }
229
230    /// Delete the run directory, if its name still refers to the directory
231    /// this run created and the marker there still names this run.
232    ///
233    /// # Errors
234    ///
235    /// Fails, deleting nothing, if the directory is no longer this run's:
236    /// moved, replaced, or marked by another run. Otherwise fails if the
237    /// deletion does, leaving the marker and lock for the next run's sweep.
238    pub fn remove(self) -> io::Result<()> {
239        let Self {
240            path,
241            name,
242            run_id,
243            parent,
244            run,
245            lock,
246        } = self;
247        let marker = read_marker(&run)?;
248        if marker.run_id != run_id || marker.file_id != run.id()?.file {
249            return Err(io::Error::new(
250                io::ErrorKind::InvalidData,
251                format!(
252                    "{} is no longer this run's directory: its marker names another run",
253                    path.display()
254                ),
255            ));
256        }
257        delete(&parent, &name, run, lock)
258    }
259
260    /// Leave the directory, and keep it locked until the process exits, when
261    /// the OS releases the lock. For a run that may still have nodes writing
262    /// into it: no sweep deletes it while it is locked.
263    pub fn keep_locked_until_exit(self) {
264        let Self { lock, .. } = self;
265        std::mem::forget(lock);
266    }
267}
268
269/// Lock `run`, then mark it, recording the lock file in `marker`. Marking
270/// second is what lets a free lock mean the run is over: a marked run has
271/// always taken its lock already. Should it fail, it removes what it created,
272/// and nothing else.
273fn claim(run: &Run, marker: &mut Marker) -> io::Result<File> {
274    let lock = run.create_file(LOCK_FILE)?;
275    let outcome = lock.try_lock().map_err(io::Error::from).and_then(|()| {
276        marker.lock_id = file_id(&lock)?.file;
277        write_marker(run, marker)
278    });
279    match outcome {
280        Ok(()) => Ok(lock),
281        Err(e) => {
282            drop(lock);
283            if let Err(cleanup) = run.remove_file(LOCK_FILE) {
284                warn!("Could not remove the lock file of a devnet run that failed to start: {cleanup}");
285            }
286            Err(e)
287        }
288    }
289}
290
291/// Write `marker` under a temporary name, then rename it into place.
292fn write_marker(run: &Run, marker: &Marker) -> io::Result<()> {
293    let json = serde_json::to_vec_pretty(marker).map_err(io::Error::other)?;
294    let mut temp = run.create_file(MARKER_TEMP_FILE)?;
295    let written = temp.write_all(&json).and_then(|()| temp.sync_all());
296    drop(temp);
297    let renamed = written.and_then(|()| run.rename(MARKER_TEMP_FILE, MARKER_FILE));
298    if renamed.is_err() {
299        if let Err(cleanup) = run.remove_file(MARKER_TEMP_FILE) {
300            warn!("Could not remove the marker of a devnet run that failed to start: {cleanup}");
301        }
302    }
303    renamed
304}
305
306fn read_marker(run: &Run) -> io::Result<Marker> {
307    let mut json = Vec::new();
308    run.open_file(MARKER_FILE)?
309        .take(MAX_MARKER_LEN as u64 + 1)
310        .read_to_end(&mut json)?;
311    if json.len() > MAX_MARKER_LEN {
312        return Err(io::Error::new(
313            io::ErrorKind::InvalidData,
314            "the marker is too large to be one",
315        ));
316    }
317    serde_json::from_slice(&json).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
318}
319
320/// Fail unless `name` in `parent` is still the directory `run` has open.
321fn same_dir(parent: &Parent, name: &str, run: &Run) -> io::Result<()> {
322    if parent.id_of(name)? == run.id()? {
323        Ok(())
324    } else {
325        Err(io::Error::new(
326            io::ErrorKind::InvalidData,
327            "it has been moved or replaced since it was opened",
328        ))
329    }
330}
331
332/// Delete the run directory `name`, which `run` has open and whose `lock` is
333/// held, if `name` still refers to it: the data first, then the marker, then
334/// the lock, then the directory, empty by then. Should it stop before the
335/// marker goes, the marker and the free lock make the rest a finished run
336/// that the next sweep removes. After that, only an empty directory and an
337/// empty lock file can be left.
338fn delete(parent: &Parent, name: &str, run: Run, lock: File) -> io::Result<()> {
339    // Moved since it was opened, it would be emptied through `run` wherever
340    // it went. Once this has passed, only the user or root can still move it:
341    // no one else can change the parent (see the module docs), and on Windows
342    // the handle keeps it where it is.
343    same_dir(parent, name, &run)?;
344    run.remove_all_but(&[MARKER_FILE, LOCK_FILE])?;
345    run.remove_file(MARKER_FILE)?;
346    // Windows removes no directory with a file open in it.
347    drop(lock);
348    run.remove_file(LOCK_FILE)?;
349    // Only an empty directory is removed, so should `name` be swapped between
350    // this check and the removal, nothing with data in it goes.
351    same_dir(parent, name, &run)?;
352    parent.remove_empty(name, run)
353}
354
355/// Whether `name` has the shape of a run directory's: `{pid}-{8 hex digits}`.
356fn is_run_name(name: &str) -> bool {
357    name.split_once('-').is_some_and(|(pid, random)| {
358        !pid.is_empty()
359            && pid.bytes().all(|b| b.is_ascii_digit())
360            && random.len() == 8
361            && random
362                .bytes()
363                .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
364    })
365}
366
367/// Remove the run directories in `parent` that are over and not kept. Never
368/// fails: whatever it cannot read or remove, it leaves.
369fn sweep(parent: &Parent) {
370    let names = match parent.names() {
371        Ok(names) => names,
372        Err(e) => {
373            warn!(
374                "Could not list {} for finished devnet runs: {e}",
375                parent.path.display()
376            );
377            return;
378        }
379    };
380    let mut removed = 0_usize;
381    for name in names.iter().filter(|name| is_run_name(name)) {
382        match finished_run(parent, name) {
383            Ok(Some((run, lock))) => {
384                #[cfg(test)]
385                after_found(&parent.path.join(name));
386                match delete(parent, name, run, lock) {
387                    Ok(()) => removed += 1,
388                    Err(e) => warn!(
389                        "Could not remove the finished devnet run directory {}: {e}",
390                        parent.path.join(name).display()
391                    ),
392                }
393            }
394            Ok(None) => {}
395            Err(e) => debug!("Leaving {}: {e}", parent.path.join(name).display()),
396        }
397    }
398    if removed > 0 {
399        info!(
400            "Removed {removed} directories left by earlier devnet runs from {}",
401            parent.path.display()
402        );
403    }
404}
405
406/// `Some`, with its lock taken, if `name` is a run that is over and not kept,
407/// so may be deleted.
408fn finished_run(parent: &Parent, name: &str) -> io::Result<Option<(Run, File)>> {
409    let run = parent.open_run(name)?;
410    // Another user's is theirs, whatever is in it, and in a parent anyone can
411    // make directories in, a sticky one, they could still move it.
412    #[cfg(unix)]
413    if !run.is_owned_by_this_user()? {
414        return Ok(None);
415    }
416    let marker = read_marker(&run)?;
417    let pid_in_name = name.split_once('-').map(|(pid, _)| pid);
418    let id = run.id()?;
419    if marker.keep
420        || pid_in_name != Some(marker.pid.to_string().as_str())
421        || marker.file_id != id.file
422        || id.device != parent.id()?.device
423    {
424        return Ok(None);
425    }
426    // Not a mount wearing a run's name, a bind mount of a finished run's
427    // directory kept elsewhere for one: deleting through it would empty what
428    // it shows. (On Windows a mounted folder is a link, which `open_run`
429    // refuses.)
430    #[cfg(unix)]
431    if run.mount()? != parent.mount()? {
432        return Ok(None);
433    }
434    let lock = run.open_file(LOCK_FILE)?;
435    // The run's lock stays held under whatever name its file is moved to, so
436    // a free lock means something only if it is that file.
437    let lock_id = file_id(&lock)?;
438    let the_runs_lock = lock_id.file == marker.lock_id;
439    if !the_runs_lock || lock_id.device != id.device {
440        return Ok(None);
441    }
442    match lock.try_lock() {
443        // Held while the directory is deleted. No run takes this lock again:
444        // a run only ever locks a directory it has just created.
445        Ok(()) => Ok(Some((run, lock))),
446        Err(TryLockError::WouldBlock) => Ok(None),
447        Err(TryLockError::Error(e)) => Err(e),
448    }
449}
450
451#[cfg(test)]
452thread_local! {
453    /// Tests set this to make a deletion fail after removing this many
454    /// entries, as one interrupted part-way would.
455    static FAIL_AFTER: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
456    /// Tests set this to act on a new run directory, by its path, between
457    /// its creation and its opening, as something else could.
458    static AFTER_CREATE: std::cell::RefCell<Option<AfterCreate>> =
459        const { std::cell::RefCell::new(None) };
460    /// Tests set this to act on a finished run's directory, by its path,
461    /// once the sweep has found it finished and before it deletes it.
462    static AFTER_FOUND: std::cell::RefCell<Option<AfterFound>> =
463        const { std::cell::RefCell::new(None) };
464    /// Tests set this to have a directory of this name inside a run
465    /// directory count as a mount point.
466    #[cfg(unix)]
467    static MOUNT_POINT: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
468}
469
470#[cfg(test)]
471type AfterCreate = Box<dyn FnOnce(&Path) -> io::Result<()>>;
472
473#[cfg(test)]
474type AfterFound = Box<dyn FnOnce(&Path)>;
475
476#[cfg(test)]
477fn after_create(path: &Path) -> io::Result<()> {
478    AFTER_CREATE
479        .with(|act| act.borrow_mut().take())
480        .map_or(Ok(()), |act| act(path))
481}
482
483#[cfg(test)]
484fn after_found(path: &Path) {
485    if let Some(act) = AFTER_FOUND.with(|act| act.borrow_mut().take()) {
486        act(path);
487    }
488}
489
490#[cfg(all(test, unix))]
491fn is_test_mount_point(name: &std::ffi::CStr) -> bool {
492    MOUNT_POINT.with(|mount| mount.borrow().as_deref().map(str::as_bytes) == Some(name.to_bytes()))
493}
494
495/// Called before each entry a deletion removes, to fail where a test asks.
496#[cfg(test)]
497fn injected_failure() -> io::Result<()> {
498    FAIL_AFTER.with(|left| match left.get() {
499        Some(0) => Err(io::Error::other("injected failure")),
500        Some(n) => {
501            left.set(Some(n - 1));
502            Ok(())
503        }
504        None => Ok(()),
505    })
506}
507
508#[cfg(unix)]
509use unix::{file_id, Parent, Run};
510
511#[cfg(windows)]
512use windows::{file_id, Parent, Run};
513
514/// Every operation relative to a directory handle, never following a link.
515#[cfg(unix)]
516mod unix {
517    use super::FileId;
518    use rustix::fs::{AtFlags, Dev, FileType, Mode, OFlags, Stat};
519    use rustix::io::Errno;
520    use std::ffi::{CStr, CString};
521    use std::fs::File;
522    use std::io;
523    use std::os::fd::OwnedFd;
524    use std::path::{Path, PathBuf};
525
526    const DIR_FLAGS: OFlags = OFlags::RDONLY
527        .union(OFlags::DIRECTORY)
528        .union(OFlags::NOFOLLOW)
529        .union(OFlags::CLOEXEC);
530
531    /// The directory run directories are created in, opened once.
532    pub struct Parent {
533        /// The path it was opened by, with every link in it resolved.
534        pub path: PathBuf,
535        fd: OwnedFd,
536    }
537
538    /// A run directory, opened without following a link.
539    pub struct Run {
540        fd: OwnedFd,
541    }
542
543    impl Parent {
544        pub fn open(path: &Path) -> io::Result<Self> {
545            std::fs::create_dir_all(path)?;
546            let real = std::fs::canonicalize(path)?;
547            no_one_else_can_change(&real)?;
548            let fd = rustix::fs::open(
549                &real,
550                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
551                Mode::empty(),
552            )?;
553            // The run directory's path is built on `real`, so it must still
554            // be free of links, and name the directory just opened.
555            if std::fs::canonicalize(&real)? != real
556                || id(&rustix::fs::stat(&real)?) != id(&rustix::fs::fstat(&fd)?)
557            {
558                return Err(io::Error::new(
559                    io::ErrorKind::InvalidData,
560                    format!("{} changed while it was being opened", path.display()),
561                ));
562            }
563            Ok(Self { path: real, fd })
564        }
565
566        pub fn mount(&self) -> io::Result<Mount> {
567            mount_of(&self.fd)
568        }
569
570        pub fn create_run(&self, name: &str) -> io::Result<()> {
571            Ok(rustix::fs::mkdirat(
572                &self.fd,
573                name,
574                Mode::from_raw_mode(0o755),
575            )?)
576        }
577
578        pub fn open_run(&self, name: &str) -> io::Result<Run> {
579            let fd = rustix::fs::openat(&self.fd, name, DIR_FLAGS, Mode::empty())?;
580            Ok(Run { fd })
581        }
582
583        pub fn names(&self) -> io::Result<Vec<String>> {
584            Ok(read_names(&self.fd)?
585                .into_iter()
586                .filter_map(|name| name.into_string().ok())
587                .collect())
588        }
589
590        pub fn id(&self) -> io::Result<FileId> {
591            Ok(id(&rustix::fs::fstat(&self.fd)?))
592        }
593
594        /// The directory `name`, not following a link.
595        pub fn id_of(&self, name: &str) -> io::Result<FileId> {
596            let stat = rustix::fs::statat(&self.fd, name, AtFlags::SYMLINK_NOFOLLOW)?;
597            if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
598                return Err(io::Error::new(
599                    io::ErrorKind::InvalidData,
600                    format!("{name} is not a directory"),
601                ));
602            }
603            Ok(id(&stat))
604        }
605
606        /// Close `run`, then remove the entry `name` if it is an empty
607        /// directory.
608        pub fn remove_empty(&self, name: &str, run: Run) -> io::Result<()> {
609            drop(run);
610            gone_is_fine(rustix::fs::unlinkat(&self.fd, name, AtFlags::REMOVEDIR))
611        }
612    }
613
614    impl Run {
615        pub fn id(&self) -> io::Result<FileId> {
616            Ok(id(&rustix::fs::fstat(&self.fd)?))
617        }
618
619        pub fn is_empty(&self) -> io::Result<bool> {
620            Ok(read_names(&self.fd)?.is_empty())
621        }
622
623        pub fn is_owned_by_this_user(&self) -> io::Result<bool> {
624            Ok(rustix::fs::fstat(&self.fd)?.st_uid == rustix::process::geteuid().as_raw())
625        }
626
627        pub fn mount(&self) -> io::Result<Mount> {
628            mount_of(&self.fd)
629        }
630
631        pub fn create_file(&self, name: &str) -> io::Result<File> {
632            let fd = rustix::fs::openat(
633                &self.fd,
634                name,
635                OFlags::RDWR | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC,
636                Mode::from_raw_mode(0o644),
637            )?;
638            Ok(File::from(fd))
639        }
640
641        /// Open an existing regular file for reading and locking. `NONBLOCK`
642        /// so that a FIFO wearing the name cannot stall the open.
643        pub fn open_file(&self, name: &str) -> io::Result<File> {
644            let fd = rustix::fs::openat(
645                &self.fd,
646                name,
647                OFlags::RDWR | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
648                Mode::empty(),
649            )?;
650            if FileType::from_raw_mode(rustix::fs::fstat(&fd)?.st_mode) != FileType::RegularFile {
651                return Err(io::Error::new(
652                    io::ErrorKind::InvalidData,
653                    format!("{name} is not a regular file"),
654                ));
655            }
656            Ok(File::from(fd))
657        }
658
659        pub fn rename(&self, from: &str, to: &str) -> io::Result<()> {
660            Ok(rustix::fs::renameat(&self.fd, from, &self.fd, to)?)
661        }
662
663        pub fn remove_file(&self, name: &str) -> io::Result<()> {
664            gone_is_fine(rustix::fs::unlinkat(&self.fd, name, AtFlags::empty()))
665        }
666
667        /// Delete everything in the directory but the entries named in `keep`.
668        pub fn remove_all_but(&self, keep: &[&str]) -> io::Result<()> {
669            let mount = mount_of(&self.fd)?;
670            for name in read_names(&self.fd)? {
671                if keep.iter().any(|keep| keep.as_bytes() == name.as_bytes()) {
672                    continue;
673                }
674                #[cfg(test)]
675                super::injected_failure()?;
676                remove_entry(&self.fd, &name, &mount)?;
677            }
678            Ok(())
679        }
680    }
681
682    pub fn file_id(file: &File) -> io::Result<FileId> {
683        Ok(id(&rustix::fs::fstat(file)?))
684    }
685
686    fn id(stat: &Stat) -> FileId {
687        FileId {
688            device: stat.st_dev.to_string(),
689            file: stat.st_ino,
690        }
691    }
692
693    /// Fail unless only the user and root can change `real`: neither it nor
694    /// any directory above it may belong to another user, or be one another
695    /// user can write to, unless it is sticky, which lets no one rename what
696    /// they do not own. Whoever could write to one could move what is in it,
697    /// a run directory or a directory above one.
698    fn no_one_else_can_change(real: &Path) -> io::Result<()> {
699        let uid = rustix::process::geteuid().as_raw();
700        for dir in real.ancestors() {
701            let stat = rustix::fs::lstat(dir)?;
702            if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
703                return Err(io::Error::new(
704                    io::ErrorKind::InvalidData,
705                    format!("{} changed while it was being opened", real.display()),
706                ));
707            }
708            let mode = Mode::from_raw_mode(stat.st_mode);
709            let who = if stat.st_uid != 0 && stat.st_uid != uid {
710                Some(format!("belongs to user {}", stat.st_uid))
711            } else if mode.contains(Mode::SVTX) {
712                None
713            } else if mode.contains(Mode::WOTH) {
714                Some("can be written to by every user".to_string())
715            } else if mode.contains(Mode::WGRP) {
716                group_writers(dir, &stat)?
717            } else {
718                None
719            };
720            if let Some(who) = who {
721                return Err(io::Error::new(
722                    io::ErrorKind::PermissionDenied,
723                    format!(
724                        "{} {who}, so another user could move or redirect a devnet's \
725                         data under it: use a data directory that only you and root \
726                         can change, with only such directories above it",
727                        dir.display()
728                    ),
729                ));
730            }
731        }
732        Ok(())
733    }
734
735    /// Who but the user can write to `dir`, which its group can write to.
736    fn group_writers(dir: &Path, stat: &Stat) -> io::Result<Option<String>> {
737        // On Linux, the user's own group, which with user private groups,
738        // Ubuntu's default, is the user alone. macOS has none: every user's
739        // group there is `staff`.
740        #[cfg(target_os = "linux")]
741        if stat.st_gid == rustix::process::getegid().as_raw() {
742            // An ACL shows in the group bits only as its mask, the most it
743            // grants anyone it names.
744            return match rustix::fs::lgetxattr(dir, "system.posix_acl_access", &mut [0_u8; 0]) {
745                Ok(_) => Ok(Some(
746                    "has an ACL, which can let other users write to it".to_string(),
747                )),
748                Err(Errno::NODATA | Errno::OPNOTSUPP) => Ok(None),
749                Err(e) => Err(e.into()),
750            };
751        }
752        #[cfg(not(target_os = "linux"))]
753        let _ = dir;
754        Ok(Some(format!("can be written to by group {}", stat.st_gid)))
755    }
756
757    /// Where a directory is mounted: its device and, on Linux, the mount
758    /// itself, which also tells a bind mount from the filesystem it shows.
759    #[derive(Debug, PartialEq, Eq)]
760    pub struct Mount {
761        device: Dev,
762        #[cfg(target_os = "linux")]
763        id: u64,
764    }
765
766    /// Fails where mounts cannot be told apart, so that nothing is deleted
767    /// there.
768    pub(super) fn mount_of(dir: &OwnedFd) -> io::Result<Mount> {
769        let device = rustix::fs::fstat(dir)?.st_dev;
770        #[cfg(target_os = "linux")]
771        {
772            use rustix::fs::StatxFlags;
773            let unsupported = || {
774                io::Error::new(
775                    io::ErrorKind::Unsupported,
776                    "cannot tell a bind mount from the directory it is in: that needs \
777                     mount ids, from Linux 5.8, and `statx` allowed",
778                )
779            };
780            let statx = match rustix::fs::statx(dir, c"", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID) {
781                Ok(statx) => statx,
782                Err(Errno::NOSYS | Errno::PERM) => return Err(unsupported()),
783                Err(e) => return Err(e.into()),
784            };
785            if statx.stx_mask & StatxFlags::MNT_ID.bits() == 0 {
786                return Err(unsupported());
787            }
788            Ok(Mount {
789                device,
790                id: statx.stx_mnt_id,
791            })
792        }
793        // No bind mounts on macOS: another mount is another device.
794        #[cfg(target_os = "macos")]
795        {
796            Ok(Mount { device })
797        }
798        #[cfg(not(any(target_os = "linux", target_os = "macos")))]
799        {
800            let _ = device;
801            Err(io::Error::new(
802                io::ErrorKind::Unsupported,
803                "cannot tell mounts apart on this system",
804            ))
805        }
806    }
807
808    /// Delete the entry `name` in `dir`, descending only through handles
809    /// opened without following a link, and only on `mount`: a link is
810    /// removed, never entered, and a mount point is left, with all in it.
811    fn remove_entry(dir: &OwnedFd, name: &CStr, mount: &Mount) -> io::Result<()> {
812        let stat = match rustix::fs::statat(dir, name, AtFlags::SYMLINK_NOFOLLOW) {
813            Ok(stat) => stat,
814            Err(Errno::NOENT) => return Ok(()),
815            Err(e) => return Err(e.into()),
816        };
817        if FileType::from_raw_mode(stat.st_mode) != FileType::Directory {
818            return gone_is_fine(rustix::fs::unlinkat(dir, name, AtFlags::empty()));
819        }
820        let child = match rustix::fs::openat(dir, name, DIR_FLAGS, Mode::empty()) {
821            Ok(child) => child,
822            Err(Errno::NOENT) => return Ok(()),
823            Err(e) => return Err(e.into()),
824        };
825        #[cfg(not(test))]
826        let mount_point = mount_of(&child)? != *mount;
827        #[cfg(test)]
828        let mount_point = mount_of(&child)? != *mount || super::is_test_mount_point(name);
829        if mount_point {
830            return Err(io::Error::new(
831                io::ErrorKind::InvalidData,
832                format!(
833                    "{} is a mount point, so it and what is in it are left",
834                    name.to_string_lossy()
835                ),
836            ));
837        }
838        for entry in read_names(&child)? {
839            remove_entry(&child, &entry, mount)?;
840        }
841        gone_is_fine(rustix::fs::unlinkat(dir, name, AtFlags::REMOVEDIR))
842    }
843
844    /// Every name in `dir` but `.` and `..`. Collected before anything is
845    /// deleted: unlinking while a directory stream is open is not something
846    /// every filesystem keeps coherent.
847    fn read_names(dir: &OwnedFd) -> io::Result<Vec<CString>> {
848        let mut names = Vec::new();
849        for entry in rustix::fs::Dir::read_from(dir)? {
850            let name = entry?.file_name().to_owned();
851            if name.as_bytes() != b"." && name.as_bytes() != b".." {
852                names.push(name);
853            }
854        }
855        Ok(names)
856    }
857
858    /// Something else, another run's sweep for one, may delete first.
859    fn gone_is_fine(result: rustix::io::Result<()>) -> io::Result<()> {
860        match result {
861            Ok(()) | Err(Errno::NOENT) => Ok(()),
862            Err(e) => Err(e.into()),
863        }
864    }
865}
866
867/// Paths built on directories held open without delete sharing, which keeps
868/// them, and every directory above them, from being renamed or removed.
869#[cfg(windows)]
870mod windows {
871    use super::FileId;
872    use std::fs::{File, OpenOptions};
873    use std::io;
874    use std::os::windows::fs::{MetadataExt, OpenOptionsExt};
875    use std::path::{Path, PathBuf};
876
877    /// Lets `CreateFileW` open a directory.
878    const FILE_FLAG_BACKUP_SEMANTICS: u32 = 0x0200_0000;
879    /// Opens a link itself rather than what it points at.
880    const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x0020_0000;
881    const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;
882    const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
883    /// `FILE_SHARE_READ | FILE_SHARE_WRITE`, without `FILE_SHARE_DELETE`.
884    const SHARE_ALL_BUT_DELETE: u32 = 0x1 | 0x2;
885
886    /// The directory run directories are created in, held open.
887    pub struct Parent {
888        /// `real`, without the `\\?\` prefix where it means the same.
889        pub path: PathBuf,
890        /// The path it was opened by, with every link in it resolved.
891        real: PathBuf,
892        held: File,
893    }
894
895    /// A run directory, held open.
896    pub struct Run {
897        path: PathBuf,
898        held: File,
899    }
900
901    impl Parent {
902        pub fn open(path: &Path) -> io::Result<Self> {
903            std::fs::create_dir_all(path)?;
904            let real = std::fs::canonicalize(path)?;
905            let held = hold_dir(&real)?;
906            // Held, none of its directories can be renamed or removed any
907            // more, so if `real` has no link in it now, it never will.
908            if std::fs::canonicalize(&real)? != real {
909                return Err(io::Error::new(
910                    io::ErrorKind::InvalidData,
911                    format!("{} changed while it was being opened", path.display()),
912                ));
913            }
914            Ok(Self {
915                path: plain(&real),
916                real,
917                held,
918            })
919        }
920
921        pub fn create_run(&self, name: &str) -> io::Result<()> {
922            std::fs::create_dir(self.real.join(name))
923        }
924
925        pub fn open_run(&self, name: &str) -> io::Result<Run> {
926            let path = self.real.join(name);
927            let held = hold_dir(&path)?;
928            Ok(Run { path, held })
929        }
930
931        pub fn names(&self) -> io::Result<Vec<String>> {
932            let mut names = Vec::new();
933            for entry in std::fs::read_dir(&self.real)? {
934                if let Ok(name) = entry?.file_name().into_string() {
935                    names.push(name);
936                }
937            }
938            Ok(names)
939        }
940
941        pub fn id(&self) -> io::Result<FileId> {
942            file_id(&self.held)
943        }
944
945        /// The directory `name`, not following a link.
946        pub fn id_of(&self, name: &str) -> io::Result<FileId> {
947            file_id(&hold_dir(&self.real.join(name))?)
948        }
949
950        /// Close `run`, then remove the entry `name` if it is an empty
951        /// directory or a link.
952        pub fn remove_empty(&self, name: &str, run: Run) -> io::Result<()> {
953            drop(run);
954            gone_is_fine(std::fs::remove_dir(self.real.join(name)))
955        }
956    }
957
958    impl Run {
959        pub fn id(&self) -> io::Result<FileId> {
960            file_id(&self.held)
961        }
962
963        pub fn is_empty(&self) -> io::Result<bool> {
964            Ok(std::fs::read_dir(&self.path)?.next().is_none())
965        }
966
967        pub fn create_file(&self, name: &str) -> io::Result<File> {
968            OpenOptions::new()
969                .read(true)
970                .write(true)
971                .create_new(true)
972                .open(self.path.join(name))
973        }
974
975        /// Open an existing regular file for reading and locking, not
976        /// following a link.
977        pub fn open_file(&self, name: &str) -> io::Result<File> {
978            let file = OpenOptions::new()
979                .read(true)
980                .write(true)
981                .custom_flags(FILE_FLAG_OPEN_REPARSE_POINT)
982                .open(self.path.join(name))?;
983            let meta = file.metadata()?;
984            if !meta.is_file() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
985                return Err(io::Error::new(
986                    io::ErrorKind::InvalidData,
987                    format!("{name} is not a regular file"),
988                ));
989            }
990            Ok(file)
991        }
992
993        pub fn rename(&self, from: &str, to: &str) -> io::Result<()> {
994            std::fs::rename(self.path.join(from), self.path.join(to))
995        }
996
997        pub fn remove_file(&self, name: &str) -> io::Result<()> {
998            gone_is_fine(std::fs::remove_file(self.path.join(name)))
999        }
1000
1001        /// Delete everything in the directory but the entries named in `keep`.
1002        pub fn remove_all_but(&self, keep: &[&str]) -> io::Result<()> {
1003            for entry in std::fs::read_dir(&self.path)? {
1004                let entry = entry?;
1005                if keep.iter().any(|keep| entry.file_name() == *keep) {
1006                    continue;
1007                }
1008                #[cfg(test)]
1009                super::injected_failure()?;
1010                // An entry's metadata describes a link, not what it points
1011                // at. A link to a directory counts as a directory, and
1012                // `remove_dir_all` removes the link itself.
1013                let path = entry.path();
1014                gone_is_fine(
1015                    if entry.metadata()?.file_attributes() & FILE_ATTRIBUTE_DIRECTORY == 0 {
1016                        std::fs::remove_file(path)
1017                    } else {
1018                        std::fs::remove_dir_all(path)
1019                    },
1020                )?;
1021            }
1022            Ok(())
1023        }
1024    }
1025
1026    /// `real` without its `\\?\` prefix, if it names the same without it,
1027    /// as a path on a drive does: [`super::RunDir::path`] is shown in logs and
1028    /// the manifest, and read by other programs.
1029    fn plain(real: &Path) -> PathBuf {
1030        real.to_str()
1031            .and_then(|text| text.strip_prefix(r"\\?\"))
1032            .map(PathBuf::from)
1033            .filter(|plain| std::fs::canonicalize(plain).is_ok_and(|again| again == real))
1034            .unwrap_or_else(|| real.to_path_buf())
1035    }
1036
1037    /// Open the directory `path` to hold it, refusing a link.
1038    fn hold_dir(path: &Path) -> io::Result<File> {
1039        let dir = OpenOptions::new()
1040            .read(true)
1041            .share_mode(SHARE_ALL_BUT_DELETE)
1042            .custom_flags(FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT)
1043            .open(path)?;
1044        let meta = dir.metadata()?;
1045        if !meta.is_dir() || meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
1046            return Err(io::Error::new(
1047                io::ErrorKind::InvalidData,
1048                format!("{} is not a directory", path.display()),
1049            ));
1050        }
1051        Ok(dir)
1052    }
1053
1054    pub fn file_id(file: &File) -> io::Result<FileId> {
1055        let info = winapi_util::file::information(file)?;
1056        Ok(FileId {
1057            device: info.volume_serial_number().to_string(),
1058            file: info.file_index(),
1059        })
1060    }
1061
1062    /// Something else, another run's sweep for one, may delete first.
1063    fn gone_is_fine(result: io::Result<()>) -> io::Result<()> {
1064        match result {
1065            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
1066            result => result,
1067        }
1068    }
1069}
1070
1071#[cfg(test)]
1072mod tests {
1073    use super::*;
1074
1075    type TestResult = std::result::Result<(), Box<dyn std::error::Error>>;
1076
1077    fn marker_in(dir: &Path) -> std::result::Result<Marker, Box<dyn std::error::Error>> {
1078        Ok(serde_json::from_slice(&std::fs::read(
1079            dir.join(MARKER_FILE),
1080        )?)?)
1081    }
1082
1083    /// Whether another handle can take `dir`'s lock: false while its run lasts.
1084    fn lock_is_free(dir: &Path) -> std::result::Result<bool, Box<dyn std::error::Error>> {
1085        let lock = File::options()
1086            .read(true)
1087            .write(true)
1088            .open(dir.join(LOCK_FILE))?;
1089        match lock.try_lock() {
1090            Ok(()) => Ok(true),
1091            Err(TryLockError::WouldBlock) => Ok(false),
1092            Err(TryLockError::Error(e)) => Err(e.into()),
1093        }
1094    }
1095
1096    fn file_id_of(path: &Path) -> std::result::Result<u64, Box<dyn std::error::Error>> {
1097        Ok(file_id(&File::open(path)?)?.file)
1098    }
1099
1100    /// A finished run's directory, as a run killed by `SIGKILL` leaves it.
1101    fn finished(
1102        parent: &Path,
1103        keep: bool,
1104    ) -> std::result::Result<PathBuf, Box<dyn std::error::Error>> {
1105        let run = RunDir::create(parent, keep)?;
1106        let path = run.path().to_path_buf();
1107        std::fs::create_dir_all(path.join("nodes").join("peer"))?;
1108        std::fs::write(path.join("nodes").join("peer").join("chunk"), b"data")?;
1109        drop(run);
1110        Ok(path)
1111    }
1112
1113    /// A directory `name` in `parent` carrying a free lock and a marker that
1114    /// names it, for this process, as a finished run would, then `edit`ed;
1115    /// and a sentinel file.
1116    fn forged(
1117        parent: &Path,
1118        name: &str,
1119        edit: impl FnOnce(&mut Marker),
1120    ) -> std::result::Result<PathBuf, Box<dyn std::error::Error>> {
1121        let dir = parent.join(name);
1122        std::fs::create_dir_all(&dir)?;
1123        let file_id = Parent::open(parent)?.open_run(name)?.id()?.file;
1124        std::fs::write(dir.join(LOCK_FILE), b"")?;
1125        let lock_id = file_id_of(&dir.join(LOCK_FILE))?;
1126        let mut marker = Marker {
1127            run_id: "forged".to_string(),
1128            file_id,
1129            lock_id,
1130            pid: std::process::id(),
1131            started_at: 0,
1132            version: env!("CARGO_PKG_VERSION").to_string(),
1133            keep: false,
1134        };
1135        edit(&mut marker);
1136        std::fs::write(dir.join(MARKER_FILE), serde_json::to_vec(&marker)?)?;
1137        std::fs::write(dir.join("sentinel"), b"keep")?;
1138        Ok(dir)
1139    }
1140
1141    #[test]
1142    fn create_makes_a_locked_marked_directory_inside_the_parent() -> TestResult {
1143        let temp = tempfile::tempdir()?;
1144        let parent = temp.path().join("not").join("there").join("yet");
1145
1146        let run = RunDir::create(&parent, false)?;
1147
1148        assert_eq!(
1149            run.path().parent().map(std::fs::canonicalize).transpose()?,
1150            Some(std::fs::canonicalize(&parent)?)
1151        );
1152        #[cfg(windows)]
1153        assert!(
1154            !run.path().to_string_lossy().starts_with(r"\\?\"),
1155            "{}",
1156            run.path().display()
1157        );
1158        let name = run
1159            .path()
1160            .file_name()
1161            .and_then(|name| name.to_str())
1162            .ok_or("no name")?;
1163        assert!(is_run_name(name), "{name}");
1164        let marker = marker_in(run.path())?;
1165        assert_eq!(marker.pid, std::process::id());
1166        assert_eq!(marker.run_id, run.run_id);
1167        assert_eq!(marker.file_id, run.run.id()?.file);
1168        assert_eq!(marker.lock_id, file_id(&run.lock)?.file);
1169        assert!(!marker.keep);
1170        assert!(!run.path().join(MARKER_TEMP_FILE).exists());
1171        assert!(
1172            !lock_is_free(run.path())?,
1173            "the lock is free while the run lasts"
1174        );
1175        Ok(())
1176    }
1177
1178    #[test]
1179    fn remove_deletes_the_run_directory_and_nothing_beside_it() -> TestResult {
1180        let temp = tempfile::tempdir()?;
1181        let parent = temp.path().join("devnets");
1182        std::fs::create_dir_all(parent.join("mine"))?;
1183        std::fs::write(parent.join("mine").join("sentinel"), b"keep")?;
1184        std::fs::write(temp.path().join("sentinel"), b"keep")?;
1185
1186        let run = RunDir::create(&parent, false)?;
1187        let path = run.path().to_path_buf();
1188        std::fs::create_dir_all(path.join("nodes").join("peer").join("deeper"))?;
1189        std::fs::write(
1190            path.join("nodes").join("peer").join("deeper").join("f"),
1191            b"x",
1192        )?;
1193        run.remove()?;
1194
1195        assert!(!path.exists());
1196        assert!(parent.is_dir(), "the parent is not the run's to delete");
1197        assert!(parent.join("mine").join("sentinel").is_file());
1198        assert!(temp.path().join("sentinel").is_file());
1199        Ok(())
1200    }
1201
1202    #[test]
1203    fn remove_refuses_a_directory_another_run_has_marked() -> TestResult {
1204        let temp = tempfile::tempdir()?;
1205        let run = RunDir::create(temp.path(), false)?;
1206        let path = run.path().to_path_buf();
1207        let mut marker = marker_in(&path)?;
1208        marker.run_id = "someone-else".to_string();
1209        std::fs::write(path.join(MARKER_FILE), serde_json::to_vec(&marker)?)?;
1210
1211        assert!(run.remove().is_err());
1212        assert!(path.join(MARKER_FILE).is_file());
1213        Ok(())
1214    }
1215
1216    /// Hermes round 3 on #263: once the run directory has been moved away, a
1217    /// directory put in its place, with copies of its marker and lock, is not
1218    /// the run's, and nothing is deleted.
1219    #[cfg(unix)]
1220    #[test]
1221    fn remove_refuses_a_replacement_carrying_a_copy_of_the_marker() -> TestResult {
1222        let temp = tempfile::tempdir()?;
1223        let run = RunDir::create(temp.path(), false)?;
1224        let path = run.path().to_path_buf();
1225        std::fs::write(path.join("data"), b"the run's")?;
1226        let moved = temp.path().join("moved");
1227        std::fs::rename(&path, &moved)?;
1228        std::fs::create_dir(&path)?;
1229        std::fs::copy(moved.join(MARKER_FILE), path.join(MARKER_FILE))?;
1230        std::fs::copy(moved.join(LOCK_FILE), path.join(LOCK_FILE))?;
1231        std::fs::write(path.join("sentinel"), b"not the run's")?;
1232
1233        assert!(run.remove().is_err());
1234        assert!(path.join("sentinel").is_file());
1235        assert!(path.join(MARKER_FILE).is_file());
1236        assert!(moved.join("data").is_file());
1237        Ok(())
1238    }
1239
1240    /// On Windows the same replacement cannot even be set up: while a run
1241    /// lasts, neither its directory nor the parent can be moved.
1242    /// Hermes round 6 on #263: nor can any directory above the parent, so
1243    /// `RunDir::path` keeps naming the run directory.
1244    #[cfg(windows)]
1245    #[test]
1246    fn a_run_directory_and_every_directory_above_it_cannot_be_moved_while_the_run_lasts(
1247    ) -> TestResult {
1248        let temp = tempfile::tempdir()?;
1249        let above = temp.path().join("above");
1250        let parent = above.join("devnets");
1251        let run = RunDir::create(&parent, false)?;
1252        let path = run.path().to_path_buf();
1253
1254        assert!(std::fs::rename(&path, parent.join("moved")).is_err());
1255        assert!(std::fs::rename(&parent, above.join("moved")).is_err());
1256        assert!(std::fs::rename(&above, temp.path().join("moved")).is_err());
1257        let temp_moved = temp.path().with_extension("moved");
1258        assert!(std::fs::rename(temp.path(), &temp_moved).is_err());
1259
1260        run.remove()?;
1261        assert!(!path.exists());
1262        Ok(())
1263    }
1264
1265    #[test]
1266    fn the_next_run_sweeps_a_finished_run() -> TestResult {
1267        let temp = tempfile::tempdir()?;
1268        let old = finished(temp.path(), false)?;
1269        assert!(old.is_dir());
1270
1271        let run = RunDir::create(temp.path(), false)?;
1272
1273        assert!(!old.exists(), "{} was not swept", old.display());
1274        assert!(run.path().is_dir());
1275        Ok(())
1276    }
1277
1278    /// Hermes round 3 on #263: a deletion that stops part-way leaves the
1279    /// marker and the lock, so the next run still knows the rest is a
1280    /// finished run's, and removes it.
1281    #[test]
1282    fn a_removal_that_stops_part_way_is_finished_by_the_next_run() -> TestResult {
1283        let temp = tempfile::tempdir()?;
1284        let run = RunDir::create(temp.path(), false)?;
1285        let path = run.path().to_path_buf();
1286        for i in 0..4 {
1287            std::fs::create_dir_all(path.join(format!("node-{i}")))?;
1288            std::fs::write(path.join(format!("node-{i}")).join("chunk"), b"data")?;
1289        }
1290
1291        FAIL_AFTER.with(|left| left.set(Some(2)));
1292        let stopped = run.remove();
1293        FAIL_AFTER.with(|left| left.set(None));
1294
1295        assert!(stopped.is_err());
1296        assert!(path.join(MARKER_FILE).is_file());
1297        assert!(path.join(LOCK_FILE).is_file());
1298        let _next = RunDir::create(temp.path(), false)?;
1299        assert!(!path.exists(), "{} was not swept", path.display());
1300        Ok(())
1301    }
1302
1303    #[test]
1304    fn a_live_run_is_never_swept() -> TestResult {
1305        let temp = tempfile::tempdir()?;
1306        let first = RunDir::create(temp.path(), false)?;
1307        let second = RunDir::create(temp.path(), false)?;
1308
1309        assert!(first.path().join(MARKER_FILE).is_file());
1310        assert!(second.path().join(MARKER_FILE).is_file());
1311        assert_ne!(first.path(), second.path());
1312        Ok(())
1313    }
1314
1315    #[test]
1316    fn a_run_kept_locked_until_exit_is_never_swept() -> TestResult {
1317        let temp = tempfile::tempdir()?;
1318        let run = RunDir::create(temp.path(), false)?;
1319        let path = run.path().to_path_buf();
1320        run.keep_locked_until_exit();
1321
1322        let _next = RunDir::create(temp.path(), false)?;
1323
1324        assert!(path.join(MARKER_FILE).is_file());
1325        assert!(!lock_is_free(&path)?);
1326        Ok(())
1327    }
1328
1329    /// Hermes round 4 on #263: a live run's lock file moved aside and
1330    /// another put in its place. That one is free, but it is not the lock the
1331    /// run holds.
1332    #[test]
1333    fn a_live_run_whose_lock_file_is_replaced_is_never_swept() -> TestResult {
1334        let temp = tempfile::tempdir()?;
1335        let run = RunDir::create(temp.path(), false)?;
1336        let path = run.path().to_path_buf();
1337        std::fs::write(path.join("data"), b"the run's")?;
1338        std::fs::rename(path.join(LOCK_FILE), path.join("moved.lock"))?;
1339        std::fs::write(path.join(LOCK_FILE), b"")?;
1340        assert!(lock_is_free(&path)?);
1341
1342        let _next = RunDir::create(temp.path(), false)?;
1343
1344        assert!(path.join("data").is_file(), "{} was swept", path.display());
1345        drop(run);
1346        Ok(())
1347    }
1348
1349    /// Hermes round 4 on #263: a directory put in place of a new run
1350    /// directory before the run opens it is not the run's, so the run neither
1351    /// claims it nor deletes anything in it, whether or not claiming it would
1352    /// have failed.
1353    #[test]
1354    fn a_directory_put_in_place_of_a_new_run_directory_is_left_alone() -> TestResult {
1355        for with_lock in [false, true] {
1356            let temp = tempfile::tempdir()?;
1357            let parent = temp.path().join("devnets");
1358            let moved = temp.path().join("moved");
1359            let replaced = std::rc::Rc::new(std::cell::RefCell::new(None));
1360            let record = std::rc::Rc::clone(&replaced);
1361            AFTER_CREATE.with(|act| {
1362                *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1363                    std::fs::rename(path, &moved)?;
1364                    std::fs::create_dir(path)?;
1365                    std::fs::write(path.join("sentinel"), b"not the run's")?;
1366                    if with_lock {
1367                        std::fs::write(path.join(LOCK_FILE), b"not the run's")?;
1368                    }
1369                    *record.borrow_mut() = Some(path.to_path_buf());
1370                    Ok(())
1371                }));
1372            });
1373
1374            let created = RunDir::create(&parent, false);
1375            AFTER_CREATE.with(|act| act.borrow_mut().take());
1376
1377            assert!(created.is_err(), "with_lock: {with_lock}");
1378            let path = replaced.borrow_mut().take().ok_or("never replaced")?;
1379            assert!(path.join("sentinel").is_file(), "with_lock: {with_lock}");
1380            assert!(!path.join(MARKER_FILE).exists(), "with_lock: {with_lock}");
1381            assert_eq!(path.join(LOCK_FILE).is_file(), with_lock);
1382        }
1383        Ok(())
1384    }
1385
1386    #[test]
1387    fn a_kept_run_is_never_swept() -> TestResult {
1388        let temp = tempfile::tempdir()?;
1389        let kept = finished(temp.path(), true)?;
1390        assert!(marker_in(&kept)?.keep);
1391
1392        let _run = RunDir::create(temp.path(), false)?;
1393
1394        assert!(kept.join("nodes").join("peer").join("chunk").is_file());
1395        Ok(())
1396    }
1397
1398    /// Hermes round 3 on #263: a finished run's directory moved away, and
1399    /// another put in its place with a copy of its marker and its very lock
1400    /// file. The copy names the moved directory, not this one.
1401    #[test]
1402    fn a_copy_of_a_finished_runs_marker_is_never_swept() -> TestResult {
1403        let temp = tempfile::tempdir()?;
1404        let old = finished(temp.path(), false)?;
1405        let moved = temp.path().join("moved");
1406        std::fs::rename(&old, &moved)?;
1407        std::fs::create_dir(&old)?;
1408        std::fs::copy(moved.join(MARKER_FILE), old.join(MARKER_FILE))?;
1409        std::fs::rename(moved.join(LOCK_FILE), old.join(LOCK_FILE))?;
1410        std::fs::write(old.join("sentinel"), b"keep")?;
1411
1412        let _run = RunDir::create(temp.path(), false)?;
1413
1414        assert!(old.join("sentinel").is_file());
1415        assert!(moved.join("nodes").join("peer").join("chunk").is_file());
1416        Ok(())
1417    }
1418
1419    /// Hermes round 6 on #263: a finished run's directory moved out of its
1420    /// name once the sweep has found it finished is not emptied where it went.
1421    /// On Windows the sweep holds it, and it cannot be moved.
1422    #[test]
1423    fn a_finished_run_moved_once_it_is_found_is_left() -> TestResult {
1424        let temp = tempfile::tempdir()?;
1425        let old = finished(temp.path(), false)?;
1426        let moved = temp.path().join("moved");
1427        let to = moved.clone();
1428        let outcome = std::rc::Rc::new(std::cell::RefCell::new(None));
1429        let record = std::rc::Rc::clone(&outcome);
1430        AFTER_FOUND.with(|act| {
1431            *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1432                *record.borrow_mut() = Some(std::fs::rename(path, &to).is_ok());
1433            }));
1434        });
1435
1436        let created = RunDir::create(temp.path(), false);
1437        AFTER_FOUND.with(|act| act.borrow_mut().take());
1438        let _run = created?;
1439
1440        let was_moved = outcome.borrow_mut().take().ok_or("never found")?;
1441        if cfg!(windows) {
1442            assert!(!was_moved, "moved while the sweep held it");
1443            assert!(!old.exists(), "{} was not swept", old.display());
1444        } else {
1445            assert!(was_moved);
1446            assert!(
1447                moved.join("nodes").join("peer").join("chunk").is_file(),
1448                "emptied where it was moved to"
1449            );
1450            assert!(moved.join(MARKER_FILE).is_file());
1451        }
1452        Ok(())
1453    }
1454
1455    #[test]
1456    fn directories_without_a_matching_marker_are_never_swept() -> TestResult {
1457        let temp = tempfile::tempdir()?;
1458        let parent = temp.path();
1459        let pid = std::process::id();
1460        let survivors = [
1461            // The right shape but no marker.
1462            {
1463                let dir = parent.join("1-deadbeef");
1464                std::fs::create_dir_all(&dir)?;
1465                std::fs::write(dir.join("sentinel"), b"keep")?;
1466                dir
1467            },
1468            // A marker, but not a run directory's name.
1469            forged(parent, "other", |_| {})?,
1470            forged(parent, &format!("{pid}-DEADBEEF"), |_| {})?,
1471            forged(parent, &format!("{pid}-deadbeef0"), |_| {})?,
1472            // A marker naming another process than the name does.
1473            forged(parent, &format!("{}-deadbeef", pid.wrapping_add(1)), |_| {})?,
1474            // A marker naming another directory.
1475            forged(parent, &format!("{pid}-d1ffe4e7"), |marker| {
1476                marker.file_id = marker.file_id.wrapping_add(1);
1477            })?,
1478            // A marker naming another lock file than the one there.
1479            forged(parent, &format!("{pid}-10c4ed00"), |marker| {
1480                marker.lock_id = marker.lock_id.wrapping_add(1);
1481            })?,
1482            // A marker asking to keep it.
1483            forged(parent, &format!("{pid}-cee9cee9"), |marker| {
1484                marker.keep = true;
1485            })?,
1486            // A marker that is not one.
1487            {
1488                let dir = forged(parent, &format!("{pid}-0badf00d"), |_| {})?;
1489                std::fs::write(dir.join(MARKER_FILE), b"{ not json")?;
1490                dir
1491            },
1492            {
1493                let dir = forged(parent, &format!("{pid}-0ddba11a"), |_| {})?;
1494                let mut big = std::fs::read(dir.join(MARKER_FILE))?;
1495                big.resize(MAX_MARKER_LEN + 1, b' ');
1496                std::fs::write(dir.join(MARKER_FILE), big)?;
1497                dir
1498            },
1499            // A marker but no lock: a run never marks before it has locked.
1500            {
1501                let dir = forged(parent, &format!("{pid}-ca11ab1e"), |_| {})?;
1502                std::fs::remove_file(dir.join(LOCK_FILE))?;
1503                dir
1504            },
1505        ];
1506        // Unedited, the same forgery is swept: each survivor survives for
1507        // its one difference alone.
1508        let control = forged(parent, &format!("{pid}-c0ffee00"), |_| {})?;
1509
1510        let _run = RunDir::create(parent, false)?;
1511
1512        for dir in &survivors {
1513            assert!(
1514                dir.join("sentinel").is_file(),
1515                "{} was swept",
1516                dir.display()
1517            );
1518        }
1519        assert!(!control.exists(), "{} was not swept", control.display());
1520        Ok(())
1521    }
1522
1523    #[test]
1524    fn run_names() {
1525        assert!(is_run_name("1-deadbeef"));
1526        assert!(is_run_name("123456-0000000a"));
1527        for name in [
1528            "",
1529            "-deadbeef",
1530            "1-",
1531            "1-deadbee",
1532            "1-deadbeef0",
1533            "1-DEADBEEF",
1534            "a-deadbeef",
1535            "1_deadbeef",
1536            "1-deadbeeg",
1537            "1-dead-bee",
1538        ] {
1539            assert!(!is_run_name(name), "{name}");
1540        }
1541    }
1542
1543    /// Hermes round 4 on #263: a deletion does not cross into another mount
1544    /// inside the run directory. It stops, leaving the mount point, what is
1545    /// in it, and the marker.
1546    #[cfg(unix)]
1547    #[test]
1548    fn removal_does_not_cross_into_another_mount() -> TestResult {
1549        let temp = tempfile::tempdir()?;
1550        let run = RunDir::create(temp.path(), false)?;
1551        let path = run.path().to_path_buf();
1552        let mounted = path.join("nodes").join("mounted");
1553        std::fs::create_dir_all(&mounted)?;
1554        std::fs::write(mounted.join("data"), b"not the run's")?;
1555
1556        MOUNT_POINT.with(|mount| *mount.borrow_mut() = Some("mounted".to_string()));
1557        let removed = run.remove();
1558        MOUNT_POINT.with(|mount| mount.borrow_mut().take());
1559
1560        assert!(removed.is_err());
1561        assert!(mounted.join("data").is_file());
1562        assert!(path.join(MARKER_FILE).is_file());
1563        Ok(())
1564    }
1565
1566    /// Run `sudo -n`, with `args` and then `path`.
1567    #[cfg(target_os = "linux")]
1568    fn sudo(args: &[&std::ffi::OsStr], path: &Path) -> io::Result<()> {
1569        let status = std::process::Command::new("sudo")
1570            .arg("-n")
1571            .args(args)
1572            .arg(path)
1573            .status()?;
1574        if status.success() {
1575            Ok(())
1576        } else {
1577            Err(io::Error::other(format!(
1578                "sudo {args:?} {} failed",
1579                path.display()
1580            )))
1581        }
1582    }
1583
1584    /// A mount made through `sudo`, undone when dropped.
1585    #[cfg(target_os = "linux")]
1586    struct Mounted(PathBuf);
1587
1588    #[cfg(target_os = "linux")]
1589    impl Mounted {
1590        fn new(at: &Path, how: &[&std::ffi::OsStr]) -> io::Result<Self> {
1591            sudo(&[&[std::ffi::OsStr::new("mount")], how].concat(), at)?;
1592            Ok(Self(at.to_path_buf()))
1593        }
1594    }
1595
1596    #[cfg(target_os = "linux")]
1597    impl Drop for Mounted {
1598        fn drop(&mut self) {
1599            if let Err(e) = sudo(&[std::ffi::OsStr::new("umount")], &self.0) {
1600                eprintln!("{e}");
1601            }
1602        }
1603    }
1604
1605    /// Whether `mv from to`, run as `nobody` through `sudo -n`, succeeds.
1606    #[cfg(target_os = "linux")]
1607    fn nobody_moves(from: &Path, to: &Path) -> io::Result<bool> {
1608        Ok(std::process::Command::new("sudo")
1609            .args(["-n", "-u", "nobody", "mv"])
1610            .arg(from)
1611            .arg(to)
1612            .stderr(std::process::Stdio::null())
1613            .status()?
1614            .success())
1615    }
1616
1617    /// Hermes round 5 on #263, with real mounts: neither a tmpfs nor a bind
1618    /// mount of a directory on the same filesystem, which only the mount id
1619    /// tells apart, is crossed. The `with_sudo_` tests need root, through
1620    /// `sudo -n`; CI runs them in a step of their own.
1621    #[cfg(target_os = "linux")]
1622    #[test]
1623    #[ignore = "mounts through sudo; CI runs it"]
1624    fn with_sudo_mounts_inside_a_run_directory_are_not_crossed() -> TestResult {
1625        use std::ffi::OsStr;
1626        for bind in [false, true] {
1627            let temp = tempfile::tempdir()?;
1628            let source = temp.path().join("source");
1629            std::fs::create_dir(&source)?;
1630            std::fs::write(source.join("data"), b"not the run's")?;
1631            let run = RunDir::create(&temp.path().join("devnets"), false)?;
1632            let path = run.path().to_path_buf();
1633            let at = path.join("nodes").join("mounted");
1634            std::fs::create_dir_all(&at)?;
1635            let _mounted = if bind {
1636                Mounted::new(&at, &[OsStr::new("--bind"), source.as_os_str()])?
1637            } else {
1638                let tmpfs = ["-t", "tmpfs", "-o", "mode=1777", "none"].map(OsStr::new);
1639                let mounted = Mounted::new(&at, &tmpfs)?;
1640                std::fs::write(at.join("data"), b"not the run's")?;
1641                mounted
1642            };
1643
1644            assert!(run.remove().is_err(), "bind: {bind}");
1645            assert!(at.join("data").is_file(), "bind: {bind}");
1646            assert!(source.join("data").is_file(), "bind: {bind}");
1647            assert!(path.join(MARKER_FILE).is_file(), "bind: {bind}");
1648        }
1649        Ok(())
1650    }
1651
1652    /// Hermes round 5 on #263: a bind mount of a finished run's directory,
1653    /// kept elsewhere on the same filesystem, put in the parent under the
1654    /// run's name. Everything about it matches but its mount, and the sweep
1655    /// would delete through it what it shows.
1656    #[cfg(target_os = "linux")]
1657    #[test]
1658    #[ignore = "mounts through sudo; CI runs it"]
1659    fn with_sudo_a_mount_wearing_a_finished_runs_name_is_not_swept() -> TestResult {
1660        let temp = tempfile::tempdir()?;
1661        let outside = finished(&temp.path().join("outside"), false)?;
1662        let parent = temp.path().join("devnets");
1663        let at = parent.join(outside.file_name().ok_or("no name")?);
1664        std::fs::create_dir_all(&at)?;
1665        let _mounted = Mounted::new(&at, &[std::ffi::OsStr::new("--bind"), outside.as_os_str()])?;
1666        assert!(at.join(MARKER_FILE).is_file());
1667
1668        let _run = RunDir::create(&parent, false)?;
1669
1670        assert!(
1671            outside.join("nodes").join("peer").join("chunk").is_file(),
1672            "swept through the mount"
1673        );
1674        Ok(())
1675    }
1676
1677    /// Hermes round 5 on #263: an empty directory another user owns, put in
1678    /// place of a new run directory before the run opens it, is not claimed,
1679    /// though the run could write in it.
1680    #[cfg(target_os = "linux")]
1681    #[test]
1682    #[ignore = "makes a directory another user owns through sudo; CI runs it"]
1683    fn with_sudo_an_empty_directory_of_another_user_is_not_claimed() -> TestResult {
1684        let temp = tempfile::tempdir()?;
1685        let parent = temp.path().join("devnets");
1686        let moved = temp.path().join("moved");
1687        let replaced = std::rc::Rc::new(std::cell::RefCell::new(None));
1688        let record = std::rc::Rc::clone(&replaced);
1689        AFTER_CREATE.with(|act| {
1690            *act.borrow_mut() = Some(Box::new(move |path: &Path| {
1691                std::fs::rename(path, &moved)?;
1692                // root's, and open to anyone.
1693                sudo(&["mkdir", "-m", "0777"].map(std::ffi::OsStr::new), path)?;
1694                *record.borrow_mut() = Some(path.to_path_buf());
1695                Ok(())
1696            }));
1697        });
1698
1699        let created = RunDir::create(&parent, false);
1700        AFTER_CREATE.with(|act| act.borrow_mut().take());
1701
1702        assert!(created.is_err());
1703        let path = replaced.borrow_mut().take().ok_or("never replaced")?;
1704        assert!(!path.join(MARKER_FILE).exists());
1705        assert!(!path.join(LOCK_FILE).exists());
1706        Ok(())
1707    }
1708
1709    /// Hermes round 6 on #263, as another user: `nobody` can move what the
1710    /// user makes in a directory anyone can write to, and so could swap a
1711    /// directory above a run directory for a link; a run refuses to start
1712    /// below one. Below a sticky one, which a run does start in, `nobody`
1713    /// cannot, and writes through `RunDir::path` land in the run directory.
1714    #[cfg(target_os = "linux")]
1715    #[test]
1716    #[ignore = "acts as another user through sudo; CI runs it"]
1717    fn with_sudo_another_user_cannot_redirect_what_a_run_writes() -> TestResult {
1718        use std::ffi::OsStr;
1719        use std::os::unix::fs::PermissionsExt;
1720        let temp = tempfile::tempdir()?;
1721        // Within `nobody`'s reach.
1722        std::fs::set_permissions(temp.path(), std::fs::Permissions::from_mode(0o755))?;
1723
1724        // root's, open to anyone, not sticky.
1725        let open = temp.path().join("open");
1726        sudo(&["mkdir", "-m", "0777"].map(OsStr::new), &open)?;
1727        std::fs::create_dir(open.join("mine"))?;
1728        assert!(nobody_moves(&open.join("mine"), &open.join("moved"))?);
1729        let refused = RunDir::create(&open.join("moved").join("devnets"), false);
1730        assert_eq!(
1731            refused.err().map(|e| e.kind()),
1732            Some(io::ErrorKind::PermissionDenied)
1733        );
1734
1735        // root's, open to anyone, sticky.
1736        let sticky = temp.path().join("sticky");
1737        sudo(&["mkdir", "-m", "1777"].map(OsStr::new), &sticky)?;
1738        let mine = sticky.join("mine");
1739        let run = RunDir::create(&mine.join("devnets"), false)?;
1740        assert!(!nobody_moves(&mine, &sticky.join("moved"))?);
1741        std::fs::write(run.path().join("written"), b"the run's")?;
1742        let name = run.path().file_name().ok_or("no name")?;
1743        assert!(mine.join("devnets").join(name).join("written").is_file());
1744        run.remove()?;
1745        Ok(())
1746    }
1747
1748    /// Hermes round 6 on #263: nor below a directory another user owns, or
1749    /// one a group other than the user's own can write to.
1750    #[cfg(target_os = "linux")]
1751    #[test]
1752    #[ignore = "makes directories another user owns through sudo; CI runs it"]
1753    fn with_sudo_a_parent_below_another_users_or_groups_directory_is_refused() -> TestResult {
1754        use std::ffi::OsStr;
1755        let temp = tempfile::tempdir()?;
1756        let me = rustix::process::geteuid().as_raw().to_string();
1757        for (name, how) in [
1758            ("theirs", ["-o", "65534", "-m", "0755"]),
1759            ("their-group", ["-g", "65534", "-m", "0775"]),
1760        ] {
1761            let above = temp.path().join(name);
1762            let parent = above.join("devnets");
1763            let make: Vec<&OsStr> = ["install", "-d"]
1764                .into_iter()
1765                .chain(how)
1766                .map(OsStr::new)
1767                .collect();
1768            sudo(&make, &above)?;
1769            sudo(
1770                &["install", "-d", "-o", me.as_str()].map(OsStr::new),
1771                &parent,
1772            )?;
1773
1774            let refused = RunDir::create(&parent, false);
1775
1776            assert_eq!(
1777                refused.err().map(|e| e.kind()),
1778                Some(io::ErrorKind::PermissionDenied),
1779                "{name}"
1780            );
1781            assert!(std::fs::read_dir(&parent)?.next().is_none(), "{name}");
1782        }
1783        Ok(())
1784    }
1785
1786    /// Hermes round 6 on #263: a finished run's directory another user owns
1787    /// is theirs, whatever is in it, and in a sticky parent they could still
1788    /// move it once the sweep has found it. It is not swept, though the user
1789    /// could delete what is in it.
1790    #[cfg(target_os = "linux")]
1791    #[test]
1792    #[ignore = "hands a directory to another user through sudo; CI runs it"]
1793    fn with_sudo_another_users_finished_run_is_not_swept() -> TestResult {
1794        use std::ffi::OsStr;
1795        let temp = tempfile::tempdir()?;
1796        let old = finished(temp.path(), false)?;
1797        sudo(&["chown", "-R", "65534"].map(OsStr::new), &old)?;
1798        sudo(&["chmod", "-R", "a+rwX"].map(OsStr::new), &old)?;
1799
1800        let _run = RunDir::create(temp.path(), false)?;
1801
1802        assert!(old.join("nodes").join("peer").join("chunk").is_file());
1803        Ok(())
1804    }
1805
1806    /// What that rests on: a directory on another mount is told apart from
1807    /// one on the run's.
1808    #[cfg(any(target_os = "linux", target_os = "macos"))]
1809    #[test]
1810    fn a_directory_on_another_mount_is_told_apart() -> TestResult {
1811        use rustix::fs::{Mode, OFlags};
1812        let open = |path: &Path| {
1813            rustix::fs::open(
1814                path,
1815                OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
1816                Mode::empty(),
1817            )
1818        };
1819        let temp = tempfile::tempdir()?;
1820        std::fs::create_dir(temp.path().join("sub"))?;
1821        // procfs on Linux, devfs on macOS: always mounts of their own.
1822        let other = if cfg!(target_os = "linux") {
1823            "/proc"
1824        } else {
1825            "/dev"
1826        };
1827
1828        let here = unix::mount_of(&open(temp.path())?)?;
1829        assert_eq!(unix::mount_of(&open(&temp.path().join("sub"))?)?, here);
1830        assert_ne!(unix::mount_of(&open(Path::new(other))?)?, here);
1831        Ok(())
1832    }
1833
1834    /// Hermes round 2 on #263: a parent reached through a dangling symlink
1835    /// fails to start and deletes nothing.
1836    #[cfg(unix)]
1837    #[test]
1838    fn a_parent_behind_a_dangling_symlink_fails_closed() -> TestResult {
1839        let temp = tempfile::tempdir()?;
1840        let victim = temp.path().join("victim");
1841        std::fs::create_dir_all(&victim)?;
1842        std::fs::write(victim.join("sentinel"), b"keep")?;
1843        std::os::unix::fs::symlink(victim.join("not-yet"), temp.path().join("alias"))?;
1844
1845        assert!(RunDir::create(&temp.path().join("alias").join("devnets"), false).is_err());
1846
1847        assert!(victim.join("sentinel").is_file());
1848        assert!(!victim.join("not-yet").exists());
1849        Ok(())
1850    }
1851
1852    /// `parent` inside `above`, inside a fresh temporary directory, with
1853    /// `mode` set on whichever of the two `which` names.
1854    #[cfg(unix)]
1855    fn parent_with(
1856        which: &str,
1857        mode: u32,
1858    ) -> std::result::Result<(tempfile::TempDir, PathBuf), Box<dyn std::error::Error>> {
1859        use std::os::unix::fs::PermissionsExt;
1860        let temp = tempfile::tempdir()?;
1861        let above = temp.path().join("above");
1862        let parent = above.join("devnets");
1863        std::fs::create_dir_all(&parent)?;
1864        let dir = if which == "above" { &above } else { &parent };
1865        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(mode))?;
1866        Ok((temp, parent))
1867    }
1868
1869    /// Hermes round 6 on #263: another user who can write to the parent, or
1870    /// to a directory above it, can move what is in it. A run refuses to
1871    /// start there, and makes nothing there.
1872    #[cfg(unix)]
1873    #[test]
1874    fn a_parent_another_user_could_change_is_refused() -> TestResult {
1875        let mut cases = vec![("above", 0o777), ("parent", 0o777)];
1876        // No user private groups on macOS: a group there is shared.
1877        if cfg!(not(target_os = "linux")) {
1878            cases.push(("above", 0o775));
1879        }
1880        for (which, mode) in cases {
1881            let (_temp, parent) = parent_with(which, mode)?;
1882
1883            let refused = RunDir::create(&parent, false);
1884
1885            assert_eq!(
1886                refused.err().map(|e| e.kind()),
1887                Some(io::ErrorKind::PermissionDenied),
1888                "{which} {mode:o}"
1889            );
1890            assert!(
1891                std::fs::read_dir(&parent)?.next().is_none(),
1892                "{which} {mode:o}"
1893            );
1894        }
1895        Ok(())
1896    }
1897
1898    /// What a run does start in: a parent in, or below, a sticky directory
1899    /// anyone can write to, as `/tmp` is, which lets no one rename what they
1900    /// do not own; and on Linux, below one the user's own group can write to.
1901    #[cfg(unix)]
1902    #[test]
1903    fn a_parent_only_this_user_can_change_is_accepted() -> TestResult {
1904        let mut cases = vec![("above", 0o1777), ("parent", 0o1777)];
1905        if cfg!(target_os = "linux") {
1906            cases.push(("above", 0o775));
1907        }
1908        for (which, mode) in cases {
1909            let (_temp, parent) = parent_with(which, mode)?;
1910
1911            let run =
1912                RunDir::create(&parent, false).map_err(|e| format!("{which} {mode:o}: {e}"))?;
1913
1914            assert!(run.path().join(MARKER_FILE).is_file(), "{which} {mode:o}");
1915        }
1916        Ok(())
1917    }
1918
1919    /// With an ACL, a directory's group bits are only its mask, the most it
1920    /// grants anyone it names, so one the user's own group can write to does
1921    /// not pass if it has one.
1922    #[cfg(target_os = "linux")]
1923    #[test]
1924    fn a_parent_below_a_directory_with_an_acl_is_refused() -> TestResult {
1925        let (_temp, parent) = parent_with("above", 0o755)?;
1926        let above = parent.parent().ok_or("no parent")?;
1927        // user::rwx, user:65534:rwx, group::r-x, mask::rwx, other::r-x, in the
1928        // kernel's `system.posix_acl_access` format.
1929        let mut acl = 2_u32.to_le_bytes().to_vec();
1930        for (tag, perm, id) in [
1931            (0x01_u16, 7_u16, u32::MAX),
1932            (0x02, 7, 65534),
1933            (0x04, 5, u32::MAX),
1934            (0x10, 7, u32::MAX),
1935            (0x20, 5, u32::MAX),
1936        ] {
1937            acl.extend_from_slice(&tag.to_le_bytes());
1938            acl.extend_from_slice(&perm.to_le_bytes());
1939            acl.extend_from_slice(&id.to_le_bytes());
1940        }
1941        rustix::fs::lsetxattr(
1942            above,
1943            "system.posix_acl_access",
1944            &acl,
1945            rustix::fs::XattrFlags::empty(),
1946        )?;
1947        let mode = rustix::fs::Mode::from_raw_mode(rustix::fs::lstat(above)?.st_mode);
1948        assert!(mode.contains(rustix::fs::Mode::WGRP), "{mode:?}");
1949
1950        let refused = RunDir::create(&parent, false);
1951
1952        assert_eq!(
1953            refused.err().map(|e| e.kind()),
1954            Some(io::ErrorKind::PermissionDenied)
1955        );
1956        Ok(())
1957    }
1958
1959    /// A link wearing a finished run's name is removed, never followed.
1960    #[cfg(unix)]
1961    #[test]
1962    fn a_link_named_like_a_run_is_never_followed() -> TestResult {
1963        let temp = tempfile::tempdir()?;
1964        let parent = temp.path().join("devnets");
1965        let outside = finished(&temp.path().join("outside"), false)?;
1966        std::fs::write(outside.join("sentinel"), b"keep")?;
1967        std::fs::create_dir_all(&parent)?;
1968        let link = parent.join(outside.file_name().ok_or("no name")?);
1969        std::os::unix::fs::symlink(&outside, &link)?;
1970
1971        let _run = RunDir::create(&parent, false)?;
1972
1973        assert!(outside.join("sentinel").is_file());
1974        assert!(std::fs::symlink_metadata(&link)?.file_type().is_symlink());
1975        Ok(())
1976    }
1977
1978    /// Hermes round 2 on #263: retargeting a symlink above the run directory
1979    /// while the run lasts does not redirect its removal, even onto a copy of
1980    /// the run directory carrying the run's own marker.
1981    #[cfg(unix)]
1982    #[test]
1983    fn retargeting_a_symlink_above_the_run_does_not_redirect_removal() -> TestResult {
1984        let temp = tempfile::tempdir()?;
1985        let first = temp.path().join("first");
1986        let second = temp.path().join("second");
1987        std::fs::create_dir_all(&first)?;
1988        std::fs::create_dir_all(&second)?;
1989        let link = temp.path().join("link");
1990        std::os::unix::fs::symlink(&first, &link)?;
1991
1992        let run = RunDir::create(&link.join("devnets"), false)?;
1993        let name = run.path().file_name().ok_or("no name")?.to_owned();
1994        let decoy = second.join("devnets").join(&name);
1995        std::fs::create_dir_all(&decoy)?;
1996        std::fs::copy(run.path().join(MARKER_FILE), decoy.join(MARKER_FILE))?;
1997        std::fs::write(decoy.join("sentinel"), b"keep")?;
1998        std::fs::remove_file(&link)?;
1999        std::os::unix::fs::symlink(&second, &link)?;
2000
2001        // Hermes round 5: nor are writes through the path it hands out.
2002        std::fs::write(run.path().join("written"), b"the run's")?;
2003        assert!(first.join("devnets").join(&name).join("written").is_file());
2004        assert!(!decoy.join("written").exists(), "path() followed the link");
2005        run.remove()?;
2006
2007        assert!(!first.join("devnets").join(&name).exists());
2008        assert!(
2009            decoy.join("sentinel").is_file(),
2010            "the removal followed the retargeted link"
2011        );
2012        Ok(())
2013    }
2014
2015    /// `mklink /J`: a directory junction, which needs no privilege to make.
2016    /// The paths reach `cmd` through the environment and are expanded inside
2017    /// quotes, once, where none of its metacharacters act, and a Windows path
2018    /// cannot hold a quote: whatever they contain, they stay two paths.
2019    #[cfg(windows)]
2020    fn junction(link: &Path, target: &Path) -> TestResult {
2021        use std::os::windows::process::CommandExt;
2022        let status = std::process::Command::new("cmd")
2023            .raw_arg(r#"/D /V:OFF /S /C "mklink /J "%ANT_TEST_LINK%" "%ANT_TEST_TARGET%"""#)
2024            .env("ANT_TEST_LINK", link)
2025            .env("ANT_TEST_TARGET", target)
2026            .stdout(std::process::Stdio::null())
2027            .status()?;
2028        if status.success() {
2029            Ok(())
2030        } else {
2031            Err(format!("mklink /J {} {} failed", link.display(), target.display()).into())
2032        }
2033    }
2034
2035    /// The same on Windows, with a junction.
2036    #[cfg(windows)]
2037    #[test]
2038    fn retargeting_a_junction_above_the_run_does_not_redirect_removal() -> TestResult {
2039        let temp = tempfile::tempdir()?;
2040        // Names that mean something to `cmd`, which `junction` goes through.
2041        let first = temp.path().join("first & %USERNAME% ^(1)!");
2042        let second = temp.path().join("second ; %PATH% = ^&");
2043        std::fs::create_dir_all(&first)?;
2044        std::fs::create_dir_all(&second)?;
2045        let link = temp.path().join("link & %TEMP%");
2046        junction(&link, &first)?;
2047
2048        let run = RunDir::create(&link.join("devnets"), false)?;
2049        let name = run.path().file_name().ok_or("no name")?.to_owned();
2050        let decoy = second.join("devnets").join(&name);
2051        std::fs::create_dir_all(&decoy)?;
2052        std::fs::copy(run.path().join(MARKER_FILE), decoy.join(MARKER_FILE))?;
2053        std::fs::write(decoy.join("sentinel"), b"keep")?;
2054        std::fs::remove_dir(&link)?;
2055        junction(&link, &second)?;
2056
2057        std::fs::write(run.path().join("written"), b"the run's")?;
2058        assert!(first.join("devnets").join(&name).join("written").is_file());
2059        assert!(
2060            !decoy.join("written").exists(),
2061            "path() followed the junction"
2062        );
2063        run.remove()?;
2064
2065        assert!(!first.join("devnets").join(&name).exists());
2066        assert!(
2067            decoy.join("sentinel").is_file(),
2068            "the removal followed the retargeted junction"
2069        );
2070        Ok(())
2071    }
2072}