Skip to main content

reverie_process/
mount.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 * All rights reserved.
4 *
5 * This source code is licensed under the BSD-style license found in the
6 * LICENSE file in the root directory of this source tree.
7 */
8
9use core::convert::Infallible;
10use core::fmt;
11use core::ptr;
12use core::str::FromStr;
13use std::collections::HashMap;
14use std::ffi::CString;
15use std::ffi::OsStr;
16use std::mem::MaybeUninit;
17use std::os::fd::AsRawFd;
18use std::os::unix::ffi::OsStrExt;
19use std::path::Path;
20
21pub use nix::mount::MsFlags as MountFlags;
22use syscalls::Errno;
23
24use super::fd::Fd;
25use super::fd::FileType;
26use super::fd::create_dir_all;
27use super::fd::touch_path;
28use super::pinned_mount::PinnedMountSource;
29use super::pinned_mount::descriptor_path;
30
31/// Additional restrictions on the top mount of a checked bind. Recursive
32/// binds retain the existing policy of their descendant mounts.
33pub(super) const BIND_RESTRICTIONS: MountFlags = MountFlags::from_bits_retain(
34    MountFlags::MS_RDONLY.bits()
35        | MountFlags::MS_NOSUID.bits()
36        | MountFlags::MS_NODEV.bits()
37        | MountFlags::MS_NOEXEC.bits(),
38);
39
40/// A mount.
41#[derive(Clone, Debug, Eq, PartialEq)]
42pub struct Mount {
43    source: Option<CString>,
44    target: CString,
45    fstype: Option<CString>,
46    flags: MountFlags,
47    data: Option<CString>,
48    touch_target: bool,
49    allow_readonly_fallback: bool,
50    pinned_source: Option<PinnedMountSource>,
51    /// A path, fstype or data string that could not be represented as a C
52    /// string, recorded at BUILD time and reported at [`Mount::mount`] time.
53    ///
54    /// ⚠️ WHY A FLAG AND NOT A `Result` FROM THE BUILDER. `mount()` runs AFTER
55    /// FORK, where this module documents that it cannot allocate -- so the
56    /// failure cannot be discovered or described there. And making the builder
57    /// fallible would change `Mount::new(..) -> Self` into
58    /// `-> Result<Self, _>` for every caller, including hermit, to report a
59    /// condition none of them can do anything about except refuse the mount.
60    /// Recording one bool costs nothing after fork and turns a panic into the
61    /// `Errno` the caller already handles.
62    unrepresentable: bool,
63}
64
65/// Represents a bind mount. Can be converted into a [`Mount`].
66#[derive(Clone, Debug, Eq, PartialEq)]
67pub struct Bind {
68    /// The source path of the bind mount. This path must exist. It can be either
69    /// a file or directory.
70    pub source: CString,
71
72    /// The target of the bind mount. This does not need to exist and can be
73    /// created when performing the bind mount.
74    pub target: CString,
75}
76
77/// `util::to_cstring` panics on an interior NUL. Every mount path, source,
78/// fstype and data string went through it, so a recoverable "this is not a
79/// valid C string" was a panic inside the builder. Measured on reverie main
80/// 200439dc8de9:
81///
82/// ```text
83/// Mount::new(OsStr::from_bytes(b"/test/work\0dir"))
84///   panicked at reverie-process/src/util.rs:17:41:
85///   called `Result::unwrap()` on an `Err` value: NulError(10, [...])
86/// ```
87///
88/// This returns the empty string on failure and says so, letting the caller
89/// record it and refuse the mount instead of aborting the process.
90fn checked_cstring<S: AsRef<OsStr>>(s: S) -> (CString, bool) {
91    match CString::new(s.as_ref().as_bytes()) {
92        Ok(c) => (c, true),
93        Err(_) => (CString::default(), false),
94    }
95}
96
97impl Mount {
98    /// Creates a new mount at the path `target`.
99    pub fn new<S: AsRef<OsStr>>(target: S) -> Self {
100        let (t, ok) = checked_cstring(target);
101        Self {
102            unrepresentable: !ok,
103            source: None,
104            target: t,
105            fstype: None,
106            flags: MountFlags::empty(),
107            data: None,
108            touch_target: false,
109            allow_readonly_fallback: false,
110            pinned_source: None,
111        }
112    }
113
114    /// Creates a bind mount. This effectively creates hardlink of a directory,
115    /// making the contents accessible at both places.
116    ///
117    /// By default, none of the mounts in the `source` directory are visible in
118    /// `destination`. To make all mounts recursively visible, combine this with
119    /// [`Mount::recursive`]. Can also be used with [`Mount::readonly`] to make
120    /// the contents of `destination` read-only.
121    pub fn bind<S: AsRef<OsStr>, D: AsRef<OsStr>>(source: S, destination: D) -> Self {
122        Self::new(destination)
123            .source(source)
124            .flags(MountFlags::MS_BIND)
125    }
126
127    /// Binds a held source object after checking its child-namespace identity.
128    ///
129    /// Perform this ordered mount before covering the source path. The object,
130    /// symlink bytes and complete mount flags must match the parent pin; missing
131    /// or changed sources refuse. Unlike a pathname bind, a final symlink is
132    /// installed as the link object. Target parents must not redirect through
133    /// symlinks. Only recursive binding and an explicit readonly seal may be
134    /// added; propagation isolation is a separate preceding operation.
135    ///
136    /// Keep the source's parent guard until reaping and retire all local source
137    /// handles in the child after setup, before starting any workers. Pinned
138    /// mounts refuse shared-memory or shared-descriptor clone configurations.
139    pub fn bind_pinned<S: AsRef<OsStr>>(source: &PinnedMountSource, destination: S) -> Self {
140        let mut mount = Self::bind(OsStr::from_bytes(source.path().to_bytes()), destination);
141        mount.pinned_source = Some(source.clone());
142        mount
143    }
144
145    pub(super) fn has_pinned_source(&self) -> bool {
146        self.pinned_source.is_some()
147    }
148
149    /// Move/rename a mount.
150    pub fn rename<S: AsRef<OsStr>, D: AsRef<OsStr>>(source: S, destination: D) -> Self {
151        Self::new(destination)
152            .source(source)
153            .flags(MountFlags::MS_MOVE)
154    }
155
156    /// Mount a fresh devpts file system. The target is usually `/dev/pts`.
157    ///
158    /// In order for this devpts to be private and independent of other devpts
159    /// (i.e., for containers), use:
160    /// ```no_compile
161    /// Mount::devpts("/dev/pts").data("newinstance,ptmxmode=0666")
162    /// ```
163    /// And either make `/dev/ptmx` a symlink pointing to `/dev/pts/ptmx` or
164    /// bind-mount it.
165    ///
166    /// See also: <https://www.kernel.org/doc/Documentation/filesystems/devpts.txt>
167    pub fn devpts<S: AsRef<OsStr>>(target: S) -> Self {
168        Self::new(target).fstype("devpts")
169    }
170
171    /// Mount a fresh proc file system at `/proc`.
172    pub fn proc() -> Self {
173        Self::new("/proc").fstype("proc")
174    }
175
176    /// Mount an overlay file system.
177    ///
178    /// NOTE: This only works in Linux 5.11 or newer when mounted from a user
179    /// namespace. Otherwise, you need real root privileges to mount an
180    /// overlayfs.
181    ///
182    /// An overlay filesystem combines two filesystems - an upper filesystem and
183    /// a lower filesystem. When a name exists in both filesystems, the object
184    /// in the upper filesystem is visible while the object in the lower
185    /// filesystem is either hidden or, in the case of directories, merged with
186    /// the upper object.
187    ///
188    /// In other words, the `lowerdir` and `upperdir` are combined into a
189    /// directory `merged` using `workdir` as a temporary work area.
190    ///
191    /// The lower filesystem can be any filesystem supported by Linux and does
192    /// not need to be writable. The lower filesystem can even be another
193    /// overlayfs. The upper filesystem should be writable.
194    ///
195    /// See <https://www.kernel.org/doc/html/latest/filesystems/overlayfs.html> for
196    /// more information.
197    ///
198    /// # Arguments
199    ///
200    /// * `lowerdir` - The lower directory of the overlay. Can be any filesystem
201    ///   and does not need to be writable. This directory is never
202    ///   modified by writes to `merged`.
203    /// * `upperdir` - The upper directory of the overlay. This is where all
204    ///   changes to `merged` are collected. Does not need to be
205    ///   empty, but should be when starting a new overlay from
206    ///   scratch.
207    /// * `workdir`  - The work directory. This should always be empty.
208    /// * `merged`   - The combination of `lowerdir` and `upperdir`.
209    pub fn overlay(lowerdir: &Path, upperdir: &Path, workdir: &Path, merged: &Path) -> Self {
210        // TODO: Since there can actually be multiple lowerdirs, it might be
211        // more ergonomic to return an `OverlayBuilder` instead.
212        let options = format!(
213            "lowerdir={},upperdir={},workdir={}",
214            lowerdir.display(),
215            upperdir.display(),
216            workdir.display()
217        );
218
219        Self::new(merged)
220            .fstype("overlay")
221            .source("overlay")
222            .data(options)
223    }
224
225    /// Creates a temporary file system at the location specified.
226    pub fn tmpfs<S: AsRef<OsStr>>(target: S) -> Self {
227        Self::new(target).fstype("tmpfs")
228    }
229
230    /// Creates a sys file system at the location specified. The target directory
231    /// is usually `/sys`. This is useful when creating a network namespace.
232    pub fn sysfs<S: AsRef<OsStr>>(target: S) -> Self {
233        Self::new(target).fstype("sysfs")
234    }
235
236    /// Sets the mount point target.
237    pub fn target<S: AsRef<OsStr>>(mut self, target: S) -> Self {
238        let (t, ok) = checked_cstring(target);
239        self.target = t;
240        self.unrepresentable |= !ok;
241        self
242    }
243
244    /// Returns the mount point target path.
245    pub fn get_target(&self) -> &Path {
246        Path::new(OsStr::from_bytes(self.target.to_bytes()))
247    }
248
249    /// Sets the source of the mount.
250    pub fn source<S: AsRef<OsStr>>(mut self, path: S) -> Self {
251        let (v, ok) = checked_cstring(path);
252        self.source = Some(v);
253        self.unrepresentable |= !ok;
254        // A new lexical source cannot silently replace a pinned object.
255        self.unrepresentable |= self.pinned_source.is_some();
256        self
257    }
258
259    /// Returns the mount point source path (if any).
260    pub fn get_source(&self) -> Option<&Path> {
261        self.source
262            .as_ref()
263            .map(|s| Path::new(OsStr::from_bytes(s.to_bytes())))
264    }
265
266    /// Creates a missing target for a bind mount or a new tmpfs mount.
267    ///
268    /// New tmpfs targets must be absolute directories with no symlink path
269    /// components. Creation happens after preceding mounts, so a nested target
270    /// can live in a fresh filesystem. Tmpfs remount, move, recursive and
271    /// propagation operations do not create targets. Bind behavior is unchanged.
272    pub fn touch_target(mut self) -> Self {
273        self.touch_target = true;
274        self
275    }
276
277    /// Adds mount flags.
278    pub fn flags(mut self, flags: MountFlags) -> Self {
279        self.flags |= flags;
280        self
281    }
282
283    /// Make the file system read-only.
284    pub fn readonly(mut self) -> Self {
285        self.flags |= MountFlags::MS_RDONLY;
286        self
287    }
288
289    // TODO-HUMAN-REVIEW(PR-615)
290    /// Allows a new writable proc mount that fails with `EPERM` to retry read-only.
291    ///
292    /// This explicitly permits the resulting mount to be less capable than
293    /// requested. It has no effect on non-proc or already-read-only mounts,
294    /// remounts, bind mounts, moves, or propagation changes.
295    pub fn allow_readonly_fallback(mut self) -> Self {
296        self.allow_readonly_fallback = true;
297        self
298    }
299
300    /// Makes a bind mount recursive.
301    pub fn recursive(mut self) -> Self {
302        self.flags |= MountFlags::MS_REC;
303        self
304    }
305
306    /// Makes this mount point private. Mount and unmount events do not propagate
307    /// into or out of this mount point.
308    pub fn private(mut self) -> Self {
309        self.flags |= MountFlags::MS_PRIVATE;
310        self
311    }
312
313    /// Make this mount point shared. Mount and unmount events immediately under
314    /// this mount point will propagate to the other mount points that are
315    /// members of this mount's peer group. Propagation here means that the same
316    /// mount or unmount will automatically occur under all of the other mount
317    /// points in the peer group. Conversely, mount and unmount events that take
318    /// place under peer mount points will propagate to this mount point.
319    pub fn shared(mut self) -> Self {
320        self.flags |= MountFlags::MS_SHARED;
321        self
322    }
323
324    /// Same as specifying both [`Mount::recursive`] and [`Mount::private`].
325    pub fn rprivate(mut self) -> Self {
326        self.flags |= MountFlags::MS_REC | MountFlags::MS_PRIVATE;
327        self
328    }
329
330    /// Same as specifying both [`Mount::recursive`] and [`Mount::shared`].
331    pub fn rshared(mut self) -> Self {
332        self.flags |= MountFlags::MS_REC | MountFlags::MS_SHARED;
333        self
334    }
335
336    /// Sets the filesystem type.
337    pub fn fstype<S: AsRef<OsStr>>(mut self, fstype: S) -> Self {
338        let (v, ok) = checked_cstring(fstype);
339        self.fstype = Some(v);
340        self.unrepresentable |= !ok;
341        self
342    }
343
344    /// Sets any additional data required by the mount.
345    pub fn data<S: AsRef<OsStr>>(mut self, data: S) -> Self {
346        let (v, ok) = checked_cstring(data);
347        self.data = Some(v);
348        self.unrepresentable |= !ok;
349        self
350    }
351
352    fn source_ptr(&self) -> *const libc::c_char {
353        self.source.as_ref().map_or(ptr::null(), |s| s.as_ptr())
354    }
355
356    fn target_ptr(&self) -> *const libc::c_char {
357        self.target.as_ptr()
358    }
359
360    fn fstype_ptr(&self) -> *const libc::c_char {
361        self.fstype.as_ref().map_or(ptr::null(), |s| s.as_ptr())
362    }
363
364    fn data_ptr(&self) -> *const libc::c_void {
365        self.data
366            .as_ref()
367            .map_or(ptr::null(), |s| s.as_ptr() as *const libc::c_void)
368    }
369
370    /// Performs the mount. For bind-mount operations, the target directory or
371    /// file is created if [`touch_target`] was used.
372    ///
373    /// NOTE: This function *must* not allocate since it is called after `fork`
374    /// (or `clone`) and before `execve`. Any allocations could cause deadlocks
375    /// (which are hard to track down).
376    /// The flags the kernel will not let a read-only bind remount drop, read back
377    /// from the mount that now exists at our target.
378    ///
379    /// ⚠️ WITHOUT THIS, A READ-ONLY BIND OF A `nosuid` OR `nodev` SOURCE FAILS
380    /// WITH EPERM AND THE WHOLE CONTAINER NEVER SPAWNS. Inside a user namespace
381    /// the kernel locks these flags, and `do_remount` refuses any remount that
382    /// would clear one; passing only `MS_RDONLY` asks to clear every other flag
383    /// the source had. Re-supplying them asks for exactly what is already there,
384    /// which is permitted.
385    ///
386    /// Measured 2026-08-27: this cost a whole validate arm. Hermit places its
387    /// frozen `/etc/group` and empty nscd directory in TMPDIR and binds each
388    /// read-only, so a TMPDIR on `/run/user/<uid>` -- `nosuid,nodev` on any
389    /// systemd host -- failed every container spawn. 610 of that arm's 612 e2e
390    /// rows came from this single mount, each one reading as a test result while
391    /// measuring nothing. `nosuid` alone and `nodev` alone were each sufficient.
392    ///
393    /// ⚠️ `statfs` RATHER THAN `/proc/self/mountinfo` BECAUSE THIS RUNS AFTER
394    /// FORK, where the surrounding contract forbids allocation. `statfs` is one
395    /// syscall onto a caller-owned buffer and parses nothing.
396    ///
397    /// ⚠️ AND ONLY THE FLAGS WHOSE `ST_` AND `MS_` VALUES COINCIDE. That is true
398    /// for `NOSUID`, `NODEV`, `NOEXEC`, `NOATIME` and `NODIRATIME`, and FALSE for
399    /// `RELATIME`: `ST_RELATIME` is 0x1000 while `MS_RELATIME` is 0x200000, so
400    /// copying the raw bits across would set `MS_SYNCHRONOUS`-adjacent garbage
401    /// rather than the flag intended. Relatime is therefore left out; the kernel
402    /// keeps the existing atime policy when a remount names none.
403    fn locked_source_flags(&self) -> MountFlags {
404        // SAFETY: `statfs` writes only into `buffer`, and `target_ptr` is a
405        // NUL-terminated C string owned by `self` for the whole call.
406        let mut buffer = std::mem::MaybeUninit::<libc::statvfs>::uninit();
407        let flags = unsafe {
408            if libc::statvfs(self.target_ptr(), buffer.as_mut_ptr()) != 0 {
409                // Cannot read the source, so add nothing: the remount then
410                // behaves exactly as it did before this function existed.
411                return MountFlags::empty();
412            }
413            buffer.assume_init().f_flag
414        };
415        let mut preserved = MountFlags::empty();
416        for (probe, flag) in [
417            (libc::ST_NOSUID, MountFlags::MS_NOSUID),
418            (libc::ST_NODEV, MountFlags::MS_NODEV),
419            (libc::ST_NOEXEC, MountFlags::MS_NOEXEC),
420            (libc::ST_NOATIME, MountFlags::MS_NOATIME),
421            (libc::ST_NODIRATIME, MountFlags::MS_NODIRATIME),
422        ] {
423            if flags & probe != 0 {
424                preserved |= flag;
425            }
426        }
427        preserved
428    }
429
430    fn mount_with_flags(&self, flags: MountFlags) -> Result<(), Errno> {
431        // SAFETY: Every non-null pointer comes from a live `CString` owned by
432        // `self`, and `target` is always present. `mount` only borrows these
433        // buffers for the duration of the syscall.
434        Errno::result(unsafe {
435            libc::mount(
436                self.source_ptr(),
437                self.target_ptr(),
438                self.fstype_ptr(),
439                flags.bits(),
440                self.data_ptr(),
441            )
442        })?;
443
444        Ok(())
445    }
446
447    fn readonly_proc_fallback(&self, error: Errno) -> Option<MountFlags> {
448        let is_proc = self
449            .fstype
450            .as_ref()
451            .is_some_and(|fstype| fstype.as_bytes() == b"proc");
452        // These operations ignore the filesystem type, so `proc` does not
453        // identify the filesystem being changed. Only a new mount can retry.
454        let other_operations = MountFlags::MS_REMOUNT
455            | MountFlags::MS_BIND
456            | MountFlags::MS_MOVE
457            | MountFlags::MS_SHARED
458            | MountFlags::MS_PRIVATE
459            | MountFlags::MS_SLAVE
460            | MountFlags::MS_UNBINDABLE;
461        (self.allow_readonly_fallback
462            && error == Errno::EPERM
463            && is_proc
464            && !self.flags.intersects(other_operations)
465            && !self.flags.contains(MountFlags::MS_RDONLY))
466        .then_some(self.flags | MountFlags::MS_RDONLY)
467    }
468
469    fn mount_pinned(&self, source: &PinnedMountSource) -> Result<(), Errno> {
470        let allowed = MountFlags::MS_BIND | MountFlags::MS_REC | BIND_RESTRICTIONS;
471        if !self.flags.contains(MountFlags::MS_BIND)
472            || !(self.flags - allowed).is_empty()
473            || self.fstype.is_some()
474            || self.data.is_some()
475        {
476            return Err(Errno::EINVAL);
477        }
478        // This nonblocking ownership lease remains alive through all mount
479        // effects and destination validation. A concurrent retire must refuse.
480        let lease = source.lease()?;
481        let reopened = lease.reopen()?;
482        self.prepare_pinned_target(lease.identity().is_dir())?;
483        let mut path = [0; 64];
484        let path = descriptor_path(b"/proc/self/fd/", reopened.as_raw_fd(), &mut path)?;
485        // SAFETY: both paths are live NUL-terminated buffers, and reopened owns
486        // the verified current-namespace object for this entire operation.
487        Errno::result(unsafe {
488            libc::mount(
489                path.as_ptr(),
490                self.target_ptr(),
491                ptr::null(),
492                self.flags.bits(),
493                ptr::null(),
494            )
495        })?;
496        let destination = Fd::open_c(
497            self.target_ptr(),
498            libc::O_PATH | libc::O_NOFOLLOW | libc::O_CLOEXEC,
499        )?;
500        lease.validate(destination.as_raw_fd(), MountFlags::empty())?;
501        let restrictions = self.flags & BIND_RESTRICTIONS;
502        if !restrictions.is_empty() {
503            // Use the destination descriptor so a bound symlink's referent is
504            // never mistaken for the mount being sealed.
505            let mut path = [0; 64];
506            let path = descriptor_path(b"/proc/self/fd/", destination.as_raw_fd(), &mut path)?;
507            let mut flags = MountFlags::MS_BIND | MountFlags::MS_REMOUNT | restrictions;
508            for (probe, flag) in [
509                (libc::ST_RDONLY, MountFlags::MS_RDONLY),
510                (libc::ST_NOSUID, MountFlags::MS_NOSUID),
511                (libc::ST_NODEV, MountFlags::MS_NODEV),
512                (libc::ST_NOEXEC, MountFlags::MS_NOEXEC),
513                (libc::ST_NOATIME, MountFlags::MS_NOATIME),
514                (libc::ST_NODIRATIME, MountFlags::MS_NODIRATIME),
515            ] {
516                if lease.identity().flags & probe != 0 {
517                    flags |= flag;
518                }
519            }
520            // SAFETY: the descriptor's magic path names the actual bound mount.
521            Errno::result(unsafe {
522                libc::mount(
523                    ptr::null(),
524                    path.as_ptr(),
525                    ptr::null(),
526                    flags.bits(),
527                    ptr::null(),
528                )
529            })?;
530        }
531        lease.validate(destination.as_raw_fd(), restrictions)?;
532        // The final bound link was checked through its nofollow descriptor.
533        // Parent components must still be directories, including for links.
534        self.verify_pinned_target(None, false)?;
535        Ok(())
536    }
537
538    fn prepare_pinned_target(&self, directory: bool) -> Result<(), Errno> {
539        self.verify_pinned_target(Some(directory), self.touch_target)?;
540        if self.touch_target {
541            if directory {
542                create_dir_all(&self.target, 0o777)?;
543            } else {
544                touch_path(&self.target, 0o666, 0o777)?;
545            }
546        }
547        self.verify_pinned_target(Some(directory), false)
548    }
549
550    fn verify_pinned_target(&self, directory: Option<bool>, missing: bool) -> Result<(), Errno> {
551        let bytes = self.target.as_bytes_with_nul();
552        if bytes.first() != Some(&b'/') {
553            return Err(Errno::EINVAL);
554        }
555        let mut path = [0 as libc::c_char; libc::PATH_MAX as usize];
556        if bytes.len() > path.len() {
557            return Err(Errno::ENAMETOOLONG);
558        }
559        for (target, source) in path.iter_mut().zip(bytes) {
560            *target = *source as libc::c_char;
561        }
562        for index in 1..bytes.len() {
563            let final_component = index == bytes.len() - 1;
564            if !final_component && bytes[index] != b'/' {
565                continue;
566            }
567            if final_component && directory.is_none() {
568                continue;
569            }
570            let saved = path[index];
571            path[index] = 0;
572            let mut object = MaybeUninit::<libc::stat>::uninit();
573            // SAFETY: this prefix is NUL-terminated and the output is local.
574            let result = unsafe { libc::lstat(path.as_ptr(), object.as_mut_ptr()) };
575            path[index] = saved;
576            if result != 0 {
577                let error = Errno::last();
578                if missing && error == Errno::ENOENT {
579                    continue;
580                }
581                return Err(error);
582            }
583            // SAFETY: lstat succeeded and initialized object.
584            let kind = unsafe { object.assume_init() }.st_mode & libc::S_IFMT;
585            if kind == libc::S_IFLNK {
586                return Err(Errno::ELOOP);
587            }
588            if !final_component || directory == Some(true) {
589                if kind != libc::S_IFDIR {
590                    return Err(Errno::ENOTDIR);
591                }
592            } else if kind == libc::S_IFDIR {
593                return Err(Errno::EISDIR);
594            }
595        }
596        Ok(())
597    }
598
599    pub(super) fn mount(&mut self) -> Result<(), Errno> {
600        // ⚠️ REFUSE, DO NOT PANIC. A path/fstype/data string that is not a valid
601        // C string was recorded at build time (see `unrepresentable`). This is
602        // the first point that can report it, and it is a plain flag test
603        // because this runs after fork where allocation is not available.
604        // EINVAL is what the kernel returns for a malformed mount argument, so
605        // the caller's existing error path already knows what to do with it.
606        if self.unrepresentable {
607            return Err(Errno::EINVAL);
608        }
609        if let Some(source) = &self.pinned_source {
610            return self.mount_pinned(source);
611        }
612        let other_operations = MountFlags::MS_BIND
613            | MountFlags::MS_REMOUNT
614            | MountFlags::MS_MOVE
615            | MountFlags::MS_SHARED
616            | MountFlags::MS_PRIVATE
617            | MountFlags::MS_SLAVE
618            | MountFlags::MS_UNBINDABLE
619            | MountFlags::MS_REC;
620        if self.touch_target
621            && self
622                .fstype
623                .as_ref()
624                .is_some_and(|fstype| fstype.as_bytes() == b"tmpfs")
625            && !self.flags.intersects(other_operations)
626        {
627            // The same allocation-free nofollow checks used for pinned targets
628            // refuse links and non-directories before and after creation.
629            self.prepare_pinned_target(true)?;
630        }
631        // NOTE: Although we can't allocate here, we can safely *modify* `self`.
632        // When this function is called, we have forked virtual memory and any
633        // modifications we make are copy-on-write and lost when `execve` is
634        // called. Thus, this function takes `self` by mutable reference.
635        if self.flags.contains(MountFlags::MS_BIND) && self.touch_target {
636            // Bind mounts will fail unless the destination path exists, so it
637            // is convenient to create it automatically.
638            //
639            // One reason for doing this here instead of the parent process is
640            // because the target may not yet exist until we mount it. For
641            // example, if we want to create a `/tmp` (tmpfs) folder and then
642            // bind-mount some files or directories into it, pre-creating the
643            // destination directories won't work because they'll get created in
644            // a different tmpfs.
645            if let Some(src) = &self.source {
646                if FileType::new(src.as_ptr())?.is_dir() {
647                    create_dir_all(&self.target, 0o777)?;
648                } else {
649                    touch_path(&self.target, 0o666, 0o777)?;
650                }
651            }
652        }
653
654        match self.mount_with_flags(self.flags) {
655            Err(error) => match self.readonly_proc_fallback(error) {
656                Some(flags) => self.mount_with_flags(flags),
657                None => Err(error),
658            },
659            result => result,
660        }?;
661
662        // Linux ignores MS_RDONLY on the initial bind mount. Apply per-mount flags with the
663        // required bind remount so a read-only bind cannot mutate its source inode.
664        if self.flags.contains(MountFlags::MS_BIND) && self.flags.contains(MountFlags::MS_RDONLY) {
665            Errno::result(unsafe {
666                libc::mount(
667                    ptr::null(),
668                    self.target_ptr(),
669                    ptr::null(),
670                    (self.flags | MountFlags::MS_REMOUNT | self.locked_source_flags()).bits(),
671                    ptr::null(),
672                )
673            })?;
674        }
675
676        Ok(())
677    }
678}
679
680impl Bind {
681    /// Creates a new bind mount. The `target` is optional because it is often
682    /// convenient to use an identical `source` and `target` directory. If
683    /// `target` is `None`, then it is interpretted as being the same as
684    /// `source`.
685    pub fn new<S, T>(source: S, target: T) -> Self
686    where
687        S: AsRef<OsStr>,
688        T: AsRef<OsStr>,
689    {
690        let (src, src_ok) = checked_cstring(source);
691        let (tgt, tgt_ok) = checked_cstring(target);
692        debug_assert!(
693            src_ok && tgt_ok,
694            "Bind path not representable as a C string; the Mount it converts \
695             into is marked unrepresentable and its mount() will fail EINVAL"
696        );
697        Self {
698            source: src,
699            target: tgt,
700        }
701    }
702}
703
704impl From<Bind> for Mount {
705    fn from(b: Bind) -> Self {
706        let src_empty = b.source.as_bytes().is_empty();
707        let tgt_empty = b.target.as_bytes().is_empty();
708        Self {
709            source: Some(b.source),
710            target: b.target,
711            fstype: None,
712            flags: MountFlags::MS_BIND,
713            data: None,
714            touch_target: false,
715            allow_readonly_fallback: false,
716            pinned_source: None,
717            // A Bind built from a path that was not representable as a C string
718            // holds an EMPTY CString (see `checked_cstring`). Empty source or
719            // target is never a valid bind mount, so it carries the refusal
720            // forward rather than attempting mount(2) with "".
721            unrepresentable: src_empty || tgt_empty,
722        }
723    }
724}
725
726impl From<&str> for Bind {
727    fn from(s: &str) -> Self {
728        if let Some((source, target)) = s.split_once(':') {
729            Self {
730                source: checked_cstring(source).0,
731                target: checked_cstring(target).0,
732            }
733        } else {
734            // A Rust `&str` may contain an interior NUL, so this path panicked
735            // too. An unrepresentable path becomes empty here and the Mount it
736            // converts into refuses with EINVAL.
737            let source = checked_cstring(s).0;
738            let target = source.clone();
739            Self { source, target }
740        }
741    }
742}
743
744impl FromStr for Bind {
745    type Err = Infallible;
746
747    /// Parses bind mounts of the following forms:
748    ///  1. "path/to/source"
749    ///  2. "path/to/source:path/to/dest"
750    fn from_str(s: &str) -> Result<Self, Self::Err> {
751        Ok(Self::from(s))
752    }
753}
754
755/// An error from parsing a mount.
756#[derive(thiserror::Error, Debug, Eq, PartialEq)]
757pub enum MountParseError {
758    /// The `target` key is missing. This is always required.
759    MissingTarget,
760
761    /// An invalid mount option was specified.
762    Invalid(String, Option<String>),
763}
764
765impl fmt::Display for MountParseError {
766    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
767        match self {
768            Self::MissingTarget => write!(f, "missing mount target"),
769            Self::Invalid(k, v) => match v {
770                Some(v) => write!(f, "invalid mount option '{}={}'", k, v),
771                None => write!(f, "invalid mount option '{}'", k),
772            },
773        }
774    }
775}
776
777impl FromStr for Mount {
778    type Err = MountParseError;
779
780    /// Parses a [`Mount`]. This accepts the same syntax as Docker mounts where
781    /// each mount consists of a comma-separated key-value list.
782    ///
783    /// See <https://docs.docker.com/storage/bind-mounts/> for more information.
784    fn from_str(s: &str) -> Result<Self, Self::Err> {
785        let mut map: HashMap<&str, Option<&str>> = HashMap::new();
786
787        for item in s.split(',') {
788            let item = item.trim();
789
790            if item.is_empty() {
791                continue;
792            }
793
794            let (key, value) = match item.split_once('=') {
795                Some((key, value)) => (key, Some(value)),
796                None => (item, None),
797            };
798
799            map.insert(key, value);
800        }
801
802        // The mount target is always required.
803        let mut mount = match map
804            .remove("target")
805            .or_else(|| map.remove("destination"))
806            .or_else(|| map.remove("dest"))
807            .or_else(|| map.remove("dst"))
808            .flatten()
809        {
810            Some(target) => Mount::new(target),
811            None => {
812                return Err(MountParseError::MissingTarget);
813            }
814        };
815
816        if let Some(source) = map.remove("source").or_else(|| map.remove("src")).flatten() {
817            mount = mount.source(source);
818        }
819
820        let is_bind_mount = if let Some(fstype) = map.remove("type").flatten() {
821            if fstype == "bind" {
822                true
823            } else {
824                mount = mount.fstype(fstype);
825                false
826            }
827        } else {
828            true
829        };
830
831        if is_bind_mount {
832            mount = mount.flags(MountFlags::MS_BIND);
833        }
834
835        if let Some((key, value)) = map.remove_entry("readonly") {
836            if let Some(value) = value {
837                // No value should have been specified.
838                return Err(MountParseError::Invalid(key.into(), Some(value.to_owned())));
839            }
840
841            mount = mount.readonly();
842        }
843
844        if let Some(propagation) = map.remove("bind-propagation").flatten() {
845            if !is_bind_mount {
846                return Err(MountParseError::Invalid(
847                    "bind-propagation".into(),
848                    Some(propagation.into()),
849                ));
850            }
851            let flags = match propagation {
852                "shared" => MountFlags::MS_SHARED,
853                "slave" => MountFlags::MS_SLAVE,
854                "private" => MountFlags::MS_PRIVATE,
855                "rshared" => MountFlags::MS_REC | MountFlags::MS_SHARED,
856                "rslave" => MountFlags::MS_REC | MountFlags::MS_SLAVE,
857                "rprivate" => MountFlags::MS_REC | MountFlags::MS_PRIVATE,
858                _ => {
859                    return Err(MountParseError::Invalid(
860                        "bind-propagation".into(),
861                        Some(propagation.into()),
862                    ));
863                }
864            };
865
866            mount = mount.flags(flags);
867        } else if is_bind_mount {
868            // Bind mounts are private by default. Propagation flags are a
869            // separate mount operation and are invalid on a fresh tmpfs mount.
870            mount = mount.flags(MountFlags::MS_REC | MountFlags::MS_PRIVATE);
871        }
872
873        // Any left over keys are invalid.
874        if let Some((k, v)) = map.into_iter().next() {
875            return Err(MountParseError::Invalid(k.into(), v.map(ToOwned::to_owned)));
876        }
877
878        Ok(mount)
879    }
880}
881
882#[cfg(test)]
883mod tests {
884    use super::*;
885
886    #[test]
887    fn getters_and_setters() {
888        let m = Mount::bind("/foo", "/bar");
889        assert_eq!(m.get_target(), Path::new("/bar"));
890        assert_eq!(m.get_source(), Some(Path::new("/foo")));
891
892        let m = m.target("/baz");
893        assert_eq!(m.get_target(), Path::new("/baz"));
894    }
895
896    #[test]
897    fn proc_mount_retries_readonly_only_after_permission_denial() {
898        let proc_mount = Mount::proc();
899        assert_eq!(proc_mount.readonly_proc_fallback(Errno::EPERM), None);
900        assert_eq!(
901            proc_mount
902                .clone()
903                .allow_readonly_fallback()
904                .readonly_proc_fallback(Errno::EPERM),
905            Some(MountFlags::MS_RDONLY)
906        );
907        assert_eq!(
908            proc_mount
909                .clone()
910                .allow_readonly_fallback()
911                .readonly_proc_fallback(Errno::ENOENT),
912            None
913        );
914        assert_eq!(
915            Mount::proc()
916                .readonly()
917                .allow_readonly_fallback()
918                .readonly_proc_fallback(Errno::EPERM),
919            None
920        );
921        assert_eq!(
922            Mount::tmpfs("/tmp")
923                .allow_readonly_fallback()
924                .readonly_proc_fallback(Errno::EPERM),
925            None
926        );
927    }
928
929    #[test]
930    fn proc_mount_readonly_fallback_excludes_other_mount_operations() {
931        let mount = Mount::proc().allow_readonly_fallback();
932        let ordinary_flags = MountFlags::MS_NOSUID | MountFlags::MS_NODEV | MountFlags::MS_NOEXEC;
933        assert_eq!(
934            mount
935                .clone()
936                .flags(ordinary_flags)
937                .readonly_proc_fallback(Errno::EPERM),
938            Some(ordinary_flags | MountFlags::MS_RDONLY)
939        );
940        for flags in [
941            MountFlags::MS_REMOUNT,
942            MountFlags::MS_BIND,
943            MountFlags::MS_MOVE,
944            MountFlags::MS_SHARED,
945            MountFlags::MS_PRIVATE,
946            MountFlags::MS_SLAVE,
947            MountFlags::MS_UNBINDABLE,
948            MountFlags::MS_REMOUNT | MountFlags::MS_BIND,
949            MountFlags::MS_BIND | MountFlags::MS_REC,
950            MountFlags::MS_SHARED | MountFlags::MS_REC,
951            MountFlags::MS_PRIVATE | MountFlags::MS_REC,
952            MountFlags::MS_SLAVE | MountFlags::MS_REC,
953            MountFlags::MS_UNBINDABLE | MountFlags::MS_REC,
954        ] {
955            assert_eq!(
956                mount
957                    .clone()
958                    .flags(flags)
959                    .readonly_proc_fallback(Errno::EPERM),
960                None,
961                "must not retry a non-creation mount operation: {flags:?}"
962            );
963        }
964    }
965
966    #[test]
967    fn parse_mount() {
968        assert_eq!(
969            Mount::from_str("type=bind,source=/foo,target=/bar,readonly"),
970            Ok(Mount::bind("/foo", "/bar").readonly().rprivate())
971        );
972        assert_eq!(
973            Mount::from_str("src=/foo,target=/bar,readonly"),
974            Ok(Mount::bind("/foo", "/bar").readonly().rprivate())
975        );
976        assert_eq!(
977            Mount::from_str("src=/foo,target=/bar,bind-propagation=rshared"),
978            Ok(Mount::bind("/foo", "/bar").rshared())
979        );
980        assert_eq!(
981            Mount::from_str("type=tmpfs,target=/tmp"),
982            Ok(Mount::tmpfs("/tmp"))
983        );
984        assert_eq!(
985            Mount::from_str("type=tmpfs,target=/tmp,bind-propagation=rprivate"),
986            Err(MountParseError::Invalid(
987                "bind-propagation".into(),
988                Some("rprivate".into())
989            ))
990        );
991        assert_eq!(
992            Mount::from_str("target=foo, ,,,"),
993            Ok(Mount::new("foo").flags(MountFlags::MS_BIND).rprivate())
994        );
995
996        assert_eq!(Mount::from_str(""), Err(MountParseError::MissingTarget));
997        assert_eq!(
998            Mount::from_str("type=bind,source=/foo,readonly"),
999            Err(MountParseError::MissingTarget)
1000        );
1001        assert_eq!(
1002            Mount::from_str("type=tmpfs,target=/foo,wat"),
1003            Err(MountParseError::Invalid("wat".into(), None))
1004        );
1005        assert_eq!(
1006            Mount::from_str("type=tmpfs,target=/foo,readonly=wat"),
1007            Err(MountParseError::Invalid(
1008                "readonly".into(),
1009                Some("wat".into())
1010            ))
1011        );
1012    }
1013
1014    #[test]
1015    fn parse_bind() {
1016        assert_eq!(Bind::from("source:target"), Bind::new("source", "target"));
1017        assert_eq!(Bind::from("source"), Bind::new("source", "source"));
1018
1019        assert_eq!(
1020            Mount::from(Bind::from("source:target")),
1021            Mount::bind("source", "target")
1022        );
1023    }
1024}
1025
1026#[cfg(test)]
1027mod unrepresentable_paths_are_refused_not_panics {
1028    use std::ffi::OsStr;
1029    use std::os::unix::ffi::OsStrExt;
1030
1031    use syscalls::Errno;
1032
1033    use super::Bind;
1034    use super::Mount;
1035
1036    /// ⚠️ THIS PANICKED BEFORE, AND THE PANIC WAS THE WHOLE DEFECT. Every mount
1037    /// path went through `util::to_cstring`, which unwraps `CString::new`.
1038    /// Measured on reverie main 200439dc8de9:
1039    ///   panicked at reverie-process/src/util.rs:17:41:
1040    ///   called `Result::unwrap()` on an `Err` value: NulError(10, [...])
1041    /// A recoverable "this path is not a valid C string" aborted the process.
1042    #[test]
1043    fn a_target_with_an_interior_nul_refuses_instead_of_panicking() {
1044        let bad = OsStr::from_bytes(b"/test/work\0dir");
1045        let mut m = Mount::new(bad);
1046        assert_eq!(m.mount(), Err(Errno::EINVAL));
1047    }
1048
1049    #[test]
1050    fn an_unrepresentable_source_fstype_or_data_also_refuses() {
1051        let bad = OsStr::from_bytes(b"bad\0value");
1052        for m in [
1053            Mount::new("/test").source(bad),
1054            Mount::new("/test").fstype(bad),
1055            Mount::new("/test").data(bad),
1056        ] {
1057            let mut m = m;
1058            assert_eq!(m.mount(), Err(Errno::EINVAL));
1059        }
1060    }
1061
1062    /// ⚠️ THE CONTROL, WITHOUT WHICH THE THREE ABOVE PROVE NOTHING. A refusal
1063    /// that fired on every mount would pass them and break every real mount.
1064    /// A representable path must NOT be marked unrepresentable -- it must get
1065    /// past the flag test and fail (or succeed) on the real syscall instead.
1066    #[test]
1067    fn a_representable_path_is_not_refused_by_this_check() {
1068        let mut m = Mount::new("/test/workdir").fstype("tmpfs");
1069        let got = m.mount();
1070        assert_ne!(
1071            got,
1072            Err(Errno::EINVAL),
1073            "a valid path must reach mount(2); EINVAL here means the refusal \
1074             over-fired and no mount would ever work"
1075        );
1076    }
1077
1078    #[test]
1079    fn a_bind_from_a_str_with_an_interior_nul_refuses() {
1080        let b = Bind::from("/test/a\0b");
1081        let mut m: Mount = b.into();
1082        assert_eq!(m.mount(), Err(Errno::EINVAL));
1083    }
1084}