cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Whether this process's `/proc` is the pid namespace its own pids live in — the divergence
//! [`ProcessId::current`](super::super::ProcessId::current)'s doc explains for `/proc/self` vs
//! `getpid()`, generalised to any bare-pid lookup through `/proc`.
//!
//! A pid namespace without `--mount-proc`, an `nsenter --mount` into another mount namespace's
//! `/proc`, or no `/proc` at all: this task's `/proc` then describes a DIFFERENT pid namespace
//! than its own `getpid()` and every pid a caller hands it. A `/proc/<pid>` lookup can resolve an
//! unrelated process, so what it says about `<pid>` must not be read as an answer about the
//! caller's `<pid>`, `Gone` included.
//!
//! Two ways to establish that the mounted `/proc` describes a given target, each through ONE
//! [`ProcDir`] so nothing re-resolves `/proc` by path between the check and the read:
//!
//! - **With a pidfd** ([`pidfd_pid_in`]): a pidfd's fdinfo `Pid:` line is printed
//!   unconditionally, relative to the pid namespace of the procfs that printed it (`0` when the
//!   target is not visible there, `-1` when it was reaped). Equal to the pid the caller holds
//!   means this procfs names the target under that number.
//! - **Without one** ([`proc_view_with`]): the `NSpid` line of `self/status`, which has one entry per
//!   pid namespace from the procfs's down to the reader's. One entry means the same namespace.
//!   Where `NSpid` is absent but pid namespaces exist (gVisor), the procfs's pid 1 namespace
//!   link must name this thread's own pid namespace ([`cross_check_with_init_ns`]).
//!
//! [`ProcDir`] is proven procfs's root and reads only with `openat2` (Linux 5.6), so a mount
//! placed over `/proc`, or over a file below it, after the check is refused, not read.

use std::io::{self, Read};
use std::os::fd::{AsRawFd, BorrowedFd, OwnedFd};

use rustix::fs::{openat2, Mode, OFlags, ResolveFlags, CWD, PROC_SUPER_MAGIC};

use super::kernel::Kernel;
use crate::error::Error;

/// What this process's `/proc` says about its own pid namespace.
#[derive(Debug)]
pub(crate) enum ProcView {
    /// The `/proc` is this task's own pid namespace's. The dirfd is that `/proc`: read through
    /// it (`openat`), never through a fresh `/proc/...` path.
    Same(ProcDir),
    /// The `/proc` belongs to an outer pid namespace.
    Diverged,
    /// The view could not be established; [`ViewUnreadable`] says why. Never treated as
    /// [`Same`](Self::Same).
    Unassessable(ViewUnreadable),
}

/// Why a [`ProcView::Diverged`] `/proc` cannot answer questions about the caller's pids.
pub(crate) const DIVERGED_REASON: &str = "this process's /proc is an outer pid namespace's";

/// Why a [`ProcView::Unassessable`] `/proc` could not say which namespace it is: reading
/// `self/status` failed, as I/O or as invalid UTF-8.
pub(crate) const UNREADABLE_STATUS_REASON: &str = "self/status could not be read";

impl ProcView {
    /// The `/proc` directory of a [`Same`](Self::Same) view; any other view is why not.
    pub(crate) fn into_dir(self) -> Result<ProcDir, ViewUnreadable> {
        match self {
            ProcView::Same(dir) => Ok(dir),
            ProcView::Diverged => Err(ViewUnreadable::new(DIVERGED_REASON, None)),
            ProcView::Unassessable(why) => Err(why),
        }
    }
}

/// Why a `/proc` view or pidfd cross-check could not be established.
#[derive(Debug)]
pub(crate) struct ViewUnreadable {
    pub(crate) reason: String,
    /// The OS error behind `reason`, when there was one.
    pub(crate) source: Option<io::Error>,
    /// `openat2` itself is refused (kernel older than 5.6, or a seccomp filter that answers it
    /// `ENOSYS`/`EPERM`), so no `/proc` view can ever be established here: the errno's name.
    openat2_refused: Option<&'static str>,
}

impl ViewUnreadable {
    fn new(reason: impl Into<String>, source: Option<io::Error>) -> Self {
        ViewUnreadable {
            reason: reason.into(),
            source,
            openat2_refused: None,
        }
    }

    /// The view that `openat2` of `/proc` failing with `errno` leaves.
    pub(crate) fn from_open_errno(errno: rustix::io::Errno) -> Self {
        ViewUnreadable {
            openat2_refused: match errno {
                rustix::io::Errno::NOSYS => Some("ENOSYS"),
                rustix::io::Errno::PERM => Some("EPERM"),
                _ => None,
            },
            ..ViewUnreadable::new("/proc could not be opened", Some(errno.into()))
        }
    }

    /// [`Error::Unsupported`] naming the `openat2` requirement, when that is why the view
    /// could not be established. `op` is what could not be done.
    pub(crate) fn unsupported(&self, op: impl Into<String>) -> Option<Error> {
        self.openat2_requirement().map(|detail| Error::Unsupported {
            op: op.into(),
            platform: "linux",
            detail,
        })
    }

    /// The `openat2` requirement text, when `openat2` being refused is why the view could not be
    /// established. For callers whose error type is not [`Error`].
    pub(crate) fn openat2_requirement(&self) -> Option<String> {
        self.openat2_refused.map(openat2_refused_message)
    }
}

/// The requirement text for an `openat2` refused with the errno named `errno`. The one place the
/// wording lives: tests build their expectation with it.
pub(crate) fn openat2_refused_message(errno: &str) -> String {
    format!("cosca requires openat2 (Linux ≥ 5.6), refused here: openat2 answered {errno}")
}

impl std::fmt::Display for ViewUnreadable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.source {
            Some(e) => write!(f, "{}: {e}", self.reason),
            None => f.write_str(&self.reason),
        }
    }
}

/// A `/proc` directory fd proven to be procfs's root, and the only way to read `/proc`: every
/// read is an `openat2` beneath it that cannot cross a mount, so nothing mounted over `/proc`
/// or below it after the check is ever read. Needs `openat2` (Linux 5.6, and not filtered by
/// seccomp): [`open`](Self::open) fails, flagged so [`ViewUnreadable::unsupported`] names it.
#[derive(Debug)]
pub(crate) struct ProcDir(OwnedFd);

impl ProcDir {
    /// Open `/proc` and prove it is procfs's root: `PROC_SUPER_MAGIC`, and inode 1.
    pub(crate) fn open() -> Result<ProcDir, ViewUnreadable> {
        let fd = open_proc_root().map_err(ViewUnreadable::from_open_errno)?;
        let fs =
            rustix::fs::fstatfs(&fd).map_err(|e| ViewUnreadable::new("/proc could not be checked", Some(e.into())))?;
        if fs.f_type != PROC_SUPER_MAGIC {
            return Err(ViewUnreadable::new(
                format!("/proc is not procfs (filesystem type {:#x})", fs.f_type),
                None,
            ));
        }
        let ino = rustix::fs::fstat(&fd)
            .map_err(|e| ViewUnreadable::new("/proc could not be checked", Some(e.into())))?
            .st_ino;
        if ino != PROC_ROOT_INO {
            return Err(ViewUnreadable::new(
                format!("/proc is not the root of procfs (inode {ino})"),
                None,
            ));
        }
        Ok(ProcDir(fd))
    }

    /// Open `path` under this `/proc`, refusing to leave it, cross a mount, or follow a magic link.
    fn open_beneath(&self, path: &str, oflags: OFlags) -> io::Result<OwnedFd> {
        openat2(
            &self.0,
            path,
            oflags | OFlags::CLOEXEC,
            Mode::empty(),
            ResolveFlags::BENEATH | ResolveFlags::NO_XDEV | ResolveFlags::NO_MAGICLINKS,
        )
        .map_err(io::Error::from)
    }

    /// This process's `self/fd` directory under this `/proc`, opened as
    /// [`open_beneath`](Self::open_beneath) opens. Async-signal-safe (one `openat2`, no allocation);
    /// in a forked child `self` is the child.
    pub(crate) fn open_own_fd_dir(&self) -> rustix::io::Result<OwnedFd> {
        openat2(
            &self.0,
            c"self/fd",
            OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
            Mode::empty(),
            ResolveFlags::BENEATH | ResolveFlags::NO_XDEV | ResolveFlags::NO_MAGICLINKS,
        )
    }

    /// Read the file at `path` under this `/proc`.
    pub(crate) fn read(&self, path: &str) -> io::Result<Vec<u8>> {
        let mut bytes = Vec::new();
        std::fs::File::from(self.open_beneath(path, OFlags::RDONLY)?).read_to_end(&mut bytes)?;
        Ok(bytes)
    }

    /// [`read`](Self::read) as UTF-8 text.
    pub(crate) fn read_to_string(&self, path: &str) -> io::Result<String> {
        utf8(self.read(path)?)
    }

    /// The target of the symlink at `path` under this `/proc`, without following it.
    fn read_link(&self, path: &str) -> io::Result<Vec<u8>> {
        let link = self.open_beneath(path, OFlags::PATH | OFlags::NOFOLLOW)?;
        Ok(rustix::fs::readlinkat(&link, "", Vec::new())?.into_bytes())
    }

    /// The pids listed under this `/proc`: its decimal-named entries.
    pub(super) fn pids(&self) -> io::Result<Vec<u32>> {
        let dir = rustix::fs::Dir::new(self.open_beneath(".", OFlags::RDONLY | OFlags::DIRECTORY)?)?;
        collect_pids(dir.map(|entry| Ok(entry?.file_name().to_bytes().to_vec())))
    }

    /// Whether the symlink at `path` under this `/proc` exists, without following it.
    fn link_exists(&self, path: &str) -> io::Result<bool> {
        match self.open_beneath(path, OFlags::PATH | OFlags::NOFOLLOW) {
            Ok(_) => Ok(true),
            Err(e) if e.raw_os_error() == Some(libc::ENOENT) => Ok(false),
            Err(e) => Err(e),
        }
    }
}

/// The inode of procfs's root directory (`PROC_ROOT_INO`).
const PROC_ROOT_INO: u64 = 1;

/// The `openat2` of `/proc` itself.
fn open_proc_root() -> Result<OwnedFd, rustix::io::Errno> {
    openat2(
        CWD,
        "/proc",
        OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
        Mode::empty(),
        ResolveFlags::NO_MAGICLINKS,
    )
}

/// `bytes` as UTF-8 text.
pub(crate) fn utf8(bytes: Vec<u8>) -> io::Result<String> {
    String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}

/// This process's [`ProcView`], from `self/status`'s `NSpid` read through one `/proc` dirfd that
/// `kernel` opens.
pub(crate) fn proc_view_with(kernel: &dyn Kernel) -> ProcView {
    let dir = match kernel.open_proc() {
        Ok(dir) => dir,
        Err(why) => return ProcView::Unassessable(why),
    };
    let status = match kernel.read(&dir, "self/status").and_then(utf8) {
        Ok(text) => text,
        Err(e) => {
            return ProcView::Unassessable(ViewUnreadable::new(UNREADABLE_STATUS_REASON, Some(e)));
        }
    };
    let verdict = match classify_status(&status, || ns_pid_exists(&dir)) {
        Verdict::NoNspid => cross_check_with_init_ns(&dir),
        decided => decided,
    };
    match verdict {
        Verdict::Same | Verdict::NoNspid => ProcView::Same(dir),
        Verdict::Diverged => ProcView::Diverged,
        Verdict::Unassessable(why) => ProcView::Unassessable(why),
    }
}

/// [`ProcView`] before the dirfd is attached; the pure part, so every arm runs without a
/// namespace.
#[derive(Debug)]
enum Verdict {
    Same,
    /// `NSpid` is absent although pid namespaces exist; only [`cross_check_with_init_ns`] can
    /// decide. Never leaves [`proc_view_with`].
    NoNspid,
    Diverged,
    Unassessable(ViewUnreadable),
}

/// Classify `self/status`. `ns_pid_exists` answers whether `self/ns/pid` exists, and is asked
/// only when `NSpid` is absent.
///
/// `NSpid` exists only under `CONFIG_PID_NS`, and gVisor omits it. Absent, the kernel either
/// has no pid namespaces at all (then `self/ns/pid` does not exist and the view is trivially
/// `Same`), or does and this status file cannot say (gVisor): [`Verdict::NoNspid`].
fn classify_status(status: &str, ns_pid_exists: impl FnOnce() -> io::Result<bool>) -> Verdict {
    let Some(line) = status.lines().find_map(|l| l.strip_prefix("NSpid:")) else {
        return match ns_pid_exists() {
            Ok(false) => Verdict::Same,
            Ok(true) => Verdict::NoNspid,
            Err(e) => Verdict::Unassessable(ViewUnreadable::new(
                "self/status has no NSpid line and self/ns/pid could not be checked",
                Some(e),
            )),
        };
    };
    match line.split_whitespace().count() {
        0 => Verdict::Unassessable(ViewUnreadable::new("self/status has an empty NSpid line", None)),
        1 => Verdict::Same,
        _ => Verdict::Diverged,
    }
}

/// Decide [`Verdict::NoNspid`] by pid namespace identity. `thread-self/ns/pid` names this
/// thread's pid namespace (a namespace link names its task's namespace, whichever procfs shows
/// it), and `1/ns/pid` names the procfs's own, since its pid 1 is that namespace's init. Equal
/// links: `Same`.
///
/// Numbers cannot decide it: an outer procfs can number this thread exactly as `gettid()` does.
/// Nor can our own pidfd's fdinfo `Pid:`: Linux prints it in the procfs's namespace, where it
/// coincides with `getpid()` just as the thread id does, and gVisor prints it in the fd owner's.
///
/// No Linux kernel reaches this arm (it prints `NSpid` whenever it has pid namespaces). "pid 1 is
/// the init" holds on gVisor, whose allocator wraps to 2 and refuses a namespace whose init has
/// exited. Reading this thread's own link needs no ptrace right, even non-dumpable. Linux lets
/// only a reader with ptrace-read access to that pid 1 read its link (else `EACCES`:
/// `Unassessable`); gVisor does not check. gVisor printed a fake, per-link `pid:[…]` until
/// 2023-06 (commit 94bf4b6), but the arm needs `openat2` ([`ProcDir`]), which it gained in 2026-08.
fn cross_check_with_init_ns(dir: &ProcDir) -> Verdict {
    classify_ns_links(dir.read_link("thread-self/ns/pid"), || dir.read_link("1/ns/pid"))
}

/// Classify this thread's pid namespace link `own` against the procfs's pid 1's, which `init`
/// reads only once `own` has been read.
fn classify_ns_links(own: io::Result<Vec<u8>>, init: impl FnOnce() -> io::Result<Vec<u8>>) -> Verdict {
    let links = pid_ns_link(own, "thread-self/ns/pid")
        .and_then(|own| Ok((own, pid_ns_link(init(), "1/ns/pid (this /proc's pid 1)")?)));
    match links {
        Ok((own, init)) if own == init => Verdict::Same,
        Ok(_) => Verdict::Diverged,
        Err(why) => Verdict::Unassessable(why),
    }
}

/// `link`, the target read from `path`, if it names a pid namespace (`pid:[<inode>]`).
fn pid_ns_link(link: io::Result<Vec<u8>>, path: &str) -> Result<Vec<u8>, ViewUnreadable> {
    match link {
        Ok(target) if target.starts_with(b"pid:[") && target.ends_with(b"]") => Ok(target),
        Ok(target) => Err(ViewUnreadable::new(
            format!(
                "self/status has no NSpid line and {path} is not a pid namespace link ({:?})",
                String::from_utf8_lossy(&target)
            ),
            None,
        )),
        Err(e) => Err(ViewUnreadable::new(
            format!("self/status has no NSpid line and {path} could not be read"),
            Some(e),
        )),
    }
}

fn ns_pid_exists(dir: &ProcDir) -> io::Result<bool> {
    dir.link_exists("self/ns/pid")
}

/// What a pidfd's fdinfo `Pid:` says about its target.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PidfdTarget {
    /// The target's pid as the procfs's pid namespace numbers it; `0` when not visible there.
    Pid(u32),
    /// The target was reaped.
    Reaped,
}

/// The `Pid:` of `pidfd`'s fdinfo, read through the procfs at `dir`.
pub(crate) fn pidfd_pid_in(
    kernel: &dyn Kernel,
    dir: &ProcDir,
    pidfd: BorrowedFd<'_>,
) -> Result<PidfdTarget, ViewUnreadable> {
    let fdinfo = kernel
        .read(dir, &format!("thread-self/fdinfo/{}", pidfd.as_raw_fd()))
        .and_then(utf8)
        .map_err(|e| ViewUnreadable::new("the pidfd's fdinfo could not be read", Some(e)))?;
    parse_fdinfo_pid(&fdinfo).ok_or_else(|| ViewUnreadable::new("the pidfd's fdinfo has no parseable Pid line", None))
}

/// The `Pid:` the kernel prints for a pidfd whose target no longer has a task (`pidfd_show_fdinfo`).
const REAPED: i64 = -1;

fn parse_fdinfo_pid(fdinfo: &str) -> Option<PidfdTarget> {
    fdinfo
        .lines()
        .find_map(|l| l.strip_prefix("Pid:"))?
        .trim()
        .parse::<i64>()
        .ok()
        .and_then(|p| match p {
            REAPED => Some(PidfdTarget::Reaped),
            _ => u32::try_from(p).ok().map(PidfdTarget::Pid),
        })
}

/// The pids among directory entry `names`: the all-digit ones. `self`, `thread-self`, `net`, ...
/// are not pids. An all-digit name that is no `u32` is a corrupt listing, so an error: a live
/// process dropped from the list would read as one that is not there.
fn collect_pids(names: impl IntoIterator<Item = io::Result<Vec<u8>>>) -> io::Result<Vec<u32>> {
    /// The kernel's `PID_MAX_LIMIT` on 64-bit.
    const PID_MAX_LIMIT: u32 = 1 << 22;
    let mut pids = Vec::new();
    for name in names {
        let name = name?;
        if name.is_empty() || !name.iter().all(u8::is_ascii_digit) {
            continue;
        }
        // All ASCII digits, so UTF-8; the only way to fail is overflow.
        let text = String::from_utf8_lossy(&name);
        let pid = text.parse::<u32>().map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("the /proc entry {text:?} is all digits but not a pid: {e}"),
            )
        })?;
        debug_assert!(
            pid <= PID_MAX_LIMIT,
            "/proc lists pid {pid} beyond the kernel's PID_MAX_LIMIT"
        );
        pids.push(pid);
    }
    Ok(pids)
}

#[cfg(test)]
#[path = "proc_view_tests.rs"]
mod proc_view_tests;