cosca 0.6.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
//! The channel the forked child reports its placement outcome through (see [`ReportChannel`]).

use std::io;
use std::os::fd::{AsRawFd, OwnedFd, RawFd};

use super::*;

/// A report of a successful placement. Negative so it can never collide with an errno, which
/// `write(2)` only ever reports as positive.
#[cfg(target_os = "linux")]
pub(super) const REPORT_PLACED: i32 = -1;

/// A message's length: its tag, its value, and — in an intent — the kind of handle it carries.
#[cfg(target_os = "linux")]
const MESSAGE_LEN: usize = 16;

/// An intent's handle on its sender: none.
#[cfg(target_os = "linux")]
const HANDLE_NONE: u64 = 0;
/// An intent's handle on its sender: a pidfd.
#[cfg(target_os = "linux")]
const HANDLE_PIDFD: u64 = 1;
/// An intent's handle on its sender: its `/proc/<pid>` directory, open — for when `pidfd_open` is
/// denied. It names that process, not its number: once the process is reaped, nothing opens
/// through it, whatever process the number names by then.
#[cfg(target_os = "linux")]
const HANDLE_PROC_DIR: u64 = 2;

/// The tag of a child's intent message; its value is the child's pid.
#[cfg(target_os = "linux")]
pub(super) const TAG_INTENT: i32 = 1;
/// The tag of a child's report message; its value is [`REPORT_PLACED`] or the write's errno.
#[cfg(target_os = "linux")]
const TAG_REPORT: i32 = 2;
/// The parent's one message: it has decided without the rest of the exchange.
#[cfg(target_os = "linux")]
const PROCEED: u8 = b'P';

/// The channel of the placement exchange (see the module's contract): a `SOCK_SEQPACKET` socket
/// pair. The child sends two messages of two native-endian `i32`s — its *intent* (with its pid,
/// and its pidfd as `SCM_RIGHTS` when it can open one), then its *report* (the write's errno or
/// [`REPORT_PLACED`]). The parent may send one byte back: *proceed*.
///
/// `pre_exec` runs after `fork`, where async-signal-safety forbids allocating, formatting or
/// locking, and nothing the child computes survives its `exec`. A `sendmsg(2)` from a buffer on
/// the stack is all a message needs. It is sent with `MSG_NOSIGNAL`: a parent that has stopped
/// listening makes it fail with `EPIPE` instead of killing the child with `SIGPIPE`.
///
/// # When the report is final
/// Not when `spawn` returns. `std`'s Unix spawn returns once its own close-on-exec error channel
/// reads EOF, normally at the child's `exec`. But that channel takes the lowest free fds: with two
/// of this process's 0, 1 and 2 closed, its child end is one of them. When `std` `dup2`s the
/// child's stdio for that slot into place, before any `pre_exec` runs, it closes that end, and
/// `spawn` returns before the child has placed itself.
///
/// [`ReportChannel::wait`] therefore waits for the child itself: for the report, or for the
/// child's exit, watched through the child's own pidfd, which it handed over at the spawn handshake
/// from before `exec`. That pidfd names the child whoever reaps it and whoever takes its number: a
/// reaped child's pidfd is readable, so the wait ends. The report is always sent before `exec`, so
/// a child that exits without one never exec'd, so nothing of its is in the leaf, and
/// `NotReported` says so. The channel's EOF is no substitute for the pidfd: every process this one
/// forks while the channel is open inherits the child's end, so EOF would also wait for other
/// threads' children to exec or exit — and forever on one that never execs.
///
/// Both ends sit at fd 3 or above. The child's stdio `dup2` cannot close its end there. The only
/// later `dup2` is fd_map's mapping of fds 3 and up, whose hook the spawn registers after the
/// placement hook: it can replace the child's end only once the report is sent.
///
/// The wait is no longer than the one `std` intends: the child reaches its report on `std`'s own
/// path from `fork` to `exec`, all of which `spawn` normally waits out.
///
/// **One child per channel.** A caller that routes several children through one channel reads
/// the last intent and the first report sent, whoever sent them.
///
/// # What this costs, and what it can cost a spawn
/// Two fds per contained spawn in flight, held from the leaf's creation until `attach` takes the
/// placement verdict; a live contained child costs the supervisor none. A channel that cannot be
/// opened (`EMFILE`, `ENFILE`) DEGRADES the spawn — it keeps its process group and loses the
/// fork-proof kill — rather than failing it. `LeafError::OpenReportChannel` is what makes that
/// audible.
#[cfg(target_os = "linux")]
pub(crate) struct ReportChannel {
    /// The parent's end.
    pub(super) read: OwnedFd,
    /// The parent's copy of the child's end. Closed before waiting.
    pub(super) write: Option<OwnedFd>,
    /// What the child has sent so far.
    received: Received,
}

/// What the child has sent over a [`ReportChannel`].
#[cfg(target_os = "linux")]
#[derive(Debug, Default)]
pub(crate) struct Received {
    /// Its report, once sent.
    pub(crate) report: Option<PlacementReport>,
    /// Its pid, once its intent is sent: it reached cosca's hook and may enter the leaf.
    pub(crate) pid: Option<u32>,
    /// The pidfd its intent carried, when it could open one.
    pub(crate) pidfd: Option<OwnedFd>,
    /// Its `/proc/<pid>` directory, open, when it had no pidfd to send.
    pub(crate) proc_dir: Option<OwnedFd>,
}

#[cfg(target_os = "linux")]
impl Received {
    /// The report, where nothing received reads as `NotReported`.
    pub(crate) fn placement(&self) -> PlacementReport {
        self.report.unwrap_or(PlacementReport::NotReported)
    }
}

#[cfg(target_os = "linux")]
impl ReportChannel {
    pub(crate) fn new() -> io::Result<ReportChannel> {
        use rustix::net::{socketpair, AddressFamily, SocketFlags, SocketType};

        // Test-only fault seam: fail the channel (take semantics — see `fault`).
        #[cfg(test)]
        if fault::take_force_report_channel_failure() {
            return Err(io::Error::from_raw_os_error(libc::EMFILE));
        }
        // Both ends close-on-exec: the child needs its end only until `exec`, and no program this
        // process starts may inherit either. Both at fd 3 or above: the child's end so the child's
        // stdio cannot replace it, and the parent's so it takes no std slot this process left
        // closed — that gap is the host's, not cosca's to fill.
        let (read, write) = socketpair(AddressFamily::UNIX, SocketType::SEQPACKET, SocketFlags::CLOEXEC, None)?;
        Ok(ReportChannel {
            read: crate::above_stdio::above_stdio(read)?,
            write: Some(crate::above_stdio::above_stdio(write)?),
            received: Received::default(),
        })
    }

    /// A duplicate of the child's end, so a test can keep the channel open past the child's exit.
    #[cfg(test)]
    pub(crate) fn dup_child_end_for_test(&self) -> std::os::fd::OwnedFd {
        self.write
            .as_ref()
            .expect("the child's end is open until the wait")
            .try_clone()
            .expect("dup the child's end")
    }

    /// A `Copy` handle to the child's end for capture by the `pre_exec` closure (which must not
    /// capture the owning `ReportChannel`: the leaf keeps it).
    pub(crate) fn slot(&self) -> ReportSlot {
        ReportSlot {
            fd: self
                .write
                .as_ref()
                .expect("the child's end is open until the wait")
                .as_raw_fd(),
            parent_fd: self.read.as_raw_fd(),
        }
    }

    /// Block until the report of the child `pidfd` names, spawned with this channel's slot, is
    /// final, and return it. See [`ReportChannel`] for why `spawn` returning is not enough, and for
    /// why the wait goes through `pidfd`.
    pub(crate) fn wait(&mut self, pidfd: std::os::fd::BorrowedFd<'_>) -> PlacementReport {
        use rustix::event::{poll, PollFd, PollFlags};

        // The parent's own copy would otherwise keep the channel open forever.
        self.write = None;
        #[cfg(test)]
        fault::notify_wait_entry(std::os::fd::AsRawFd::as_raw_fd(&pidfd));
        loop {
            // An intent alone is not final: the report, or the child's exit, is.
            let closed = self.drain();
            if let Some(report) = self.received.report {
                return report;
            }
            if closed {
                return PlacementReport::NotReported;
            }
            let mut fds = [
                PollFd::new(&self.read, PollFlags::IN),
                PollFd::new(&pidfd, PollFlags::IN),
            ];
            #[cfg(test)]
            fault::notify_wait_polling();
            // No timeout: the child reports or exits on its way to `exec`, like `std`'s own wait.
            loop {
                match poll(&mut fds, None) {
                    Ok(_) => break,
                    // `ENOMEM` is the kernel's transient shortage, not an answer.
                    Err(rustix::io::Errno::INTR | rustix::io::Errno::NOMEM) => continue,
                    Err(e) => panic!("poll on the placement report channel failed: {e}"),
                }
            }
            if !fds[1].revents().is_empty() {
                // The child has exited: whatever it sent is queued.
                self.drain();
                return self.received.placement();
            }
        }
    }

    /// Read every message queued, without blocking, into what was received. `true` once the
    /// channel can deliver no more: shut for reading, or every copy of the child's end closed.
    fn drain(&mut self) -> bool {
        use std::mem::MaybeUninit;

        use rustix::net::{recvmsg, RecvAncillaryBuffer, RecvAncillaryMessage, RecvFlags};

        loop {
            let mut message = [0u8; MESSAGE_LEN];
            let mut space = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
            let mut control = RecvAncillaryBuffer::new(&mut space);
            let received = recvmsg(
                &self.read,
                &mut [std::io::IoSliceMut::new(&mut message)],
                &mut control,
                RecvFlags::DONTWAIT | RecvFlags::CMSG_CLOEXEC,
            );
            let bytes = match received {
                Ok(received) => received.bytes,
                // `ENOMEM` is the kernel's transient shortage, not an answer.
                Err(rustix::io::Errno::INTR | rustix::io::Errno::NOMEM) => continue,
                Err(rustix::io::Errno::AGAIN) => return false,
                Err(e) => panic!("recvmsg on the placement report channel failed: {e}"),
            };
            if bytes == 0 {
                return true;
            }
            debug_assert_eq!(bytes, message.len(), "a message is two i32s and a u64");
            let tag = i32::from_ne_bytes(message[..4].try_into().expect("four bytes"));
            let value = i32::from_ne_bytes(message[4..8].try_into().expect("four bytes"));
            let handle = u64::from_ne_bytes(message[8..].try_into().expect("eight bytes"));
            let mut pidfd = None;
            for ancillary in control.drain() {
                if let RecvAncillaryMessage::ScmRights(fds) = ancillary {
                    for fd in fds {
                        pidfd.get_or_insert(fd);
                    }
                }
            }
            match tag {
                TAG_INTENT => {
                    self.received.pid = u32::try_from(value).ok();
                    match handle {
                        HANDLE_PIDFD => self.received.pidfd = pidfd,
                        HANDLE_PROC_DIR => self.received.proc_dir = pidfd,
                        _ => {}
                    }
                }
                TAG_REPORT => {
                    self.received.report.get_or_insert(match value {
                        REPORT_PLACED => PlacementReport::Placed,
                        errno => {
                            debug_assert!(errno > 0, "a failed write reports its positive errno, got {errno}");
                            PlacementReport::WriteFailed(errno)
                        }
                    });
                }
                tag => debug_assert!(false, "unknown placement message tag {tag}"),
            }
        }
    }

    /// End the exchange by deciding: send *proceed*, then close. A child whose send then fails
    /// finds *proceed* queued, and carries on to `exec`.
    pub(super) fn proceed(mut self) {
        // Drained first: closing with messages unread gives the child `ECONNRESET`, not `EPIPE`.
        self.drain();
        // Nothing to do if nobody holds the child's end any more.
        _ = rustix::net::send(
            &self.read,
            &[PROCEED],
            rustix::net::SendFlags::NOSIGNAL | rustix::net::SendFlags::DONTWAIT,
        );
    }

    /// End the exchange by abandoning it: shut the channel for reading, then read everything sent
    /// before. Every later send fails with no *proceed* queued, and the child exits without
    /// `exec` — so what this returns is all the child will ever have said.
    pub(super) fn shut(mut self) -> Received {
        self.write = None;
        rustix::net::shutdown(&self.read, rustix::net::Shutdown::Read)
            .expect("shut the placement report channel for reading");
        self.drain();
        // Test-only fault seam: a child's send landing after the read, before the close.
        #[cfg(test)]
        fault::run_after_shut_read();
        self.received
    }
}

#[cfg(all(target_os = "linux", test))]
impl ReportChannel {
    /// The report of a child that has already been reaped, or of reports sent from this process.
    pub(crate) fn report_for_test(mut self) -> PlacementReport {
        self.write = None;
        self.drain();
        self.received.placement()
    }
}

/// How a child's message fared.
#[cfg(target_os = "linux")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Delivery {
    /// It was queued for the parent.
    Queued,
    /// The parent has decided without it: carry on.
    Decided,
    /// The parent has abandoned the spawn: exit without `exec`.
    Abandoned,
}

/// The child-side half of a [`ReportChannel`]: its end's number, with async-signal-safe sends.
/// Owns nothing — the parent's `ReportChannel` closes the channel.
///
/// The closure holding it can OUTLIVE the channel: `attach` closes the channel once the spawn has
/// returned, and on the spawn-FAILURE path `Prepared` (and with it the leaf) drops first — both
/// before the `Command` that still owns the closure. The number is stale from then on, which is
/// sound only because nothing ever invokes the closure again: each `Command` is spawned once.
#[cfg(target_os = "linux")]
#[derive(Clone, Copy)]
pub(crate) struct ReportSlot {
    pub(super) fd: RawFd,
    /// The parent's end, which a forked child inherits a copy of until `exec`: see
    /// [`ReportSlot::close_parents_end`].
    pub(super) parent_fd: RawFd,
}

#[cfg(target_os = "linux")]
impl ReportSlot {
    /// Send the intent: this process's pid, and a handle on this process — a pidfd, or, when
    /// `pidfd_open` is denied, its `/proc/self` directory.
    ///
    /// # Safety
    /// As [`ReportSlot::send`].
    pub(super) unsafe fn send_intent(self) -> io::Result<Delivery> {
        // A raw syscall, so async-signal-safe.
        let pid = rustix::process::getpid();
        #[cfg(test)]
        let (pidfd_denied, proc_denied) = (
            fault::take_force_child_pidfd_failure(),
            fault::take_force_child_proc_dir_failure(),
        );
        #[cfg(not(test))]
        let (pidfd_denied, proc_denied) = (false, false);
        let pidfd = if pidfd_denied {
            -1
        } else {
            rustix::process::pidfd_open(pid, rustix::process::PidfdFlags::empty())
                .map_or(-1, std::os::fd::IntoRawFd::into_raw_fd)
        };
        let (handle, kind) = if pidfd >= 0 {
            (pidfd, HANDLE_PIDFD)
        } else {
            // Safety: a NUL-terminated path; the result is checked.
            let dir = if proc_denied {
                -1
            } else {
                unsafe {
                    libc::open(
                        c"/proc/self".as_ptr(),
                        libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC,
                    )
                }
            };
            (dir, if dir >= 0 { HANDLE_PROC_DIR } else { HANDLE_NONE })
        };
        // Safety: the caller's guarantee; `handle` is this process's own or -1.
        let sent = unsafe { self.send(TAG_INTENT, pid.as_raw_nonzero().get(), kind, handle) };
        if handle >= 0 {
            // Safety: the descriptor opened above, closed once.
            unsafe { libc::close(handle) };
        }
        sent
    }

    /// Close this child's inherited copy of the parent's end, before anything else in the hook.
    ///
    /// Until `exec` the child holds that copy, so the parent's own close would not end the
    /// socket, and a decided parent's close would never reach the child as `EPIPE`. It also
    /// frees a descriptor for the `pidfd_open` that follows, in a table that may be full.
    ///
    /// # Safety
    /// Only in a forked child, where `parent_fd` is its own inherited copy — never in the parent,
    /// whose end it would close.
    pub(crate) unsafe fn close_parents_end(self) {
        // Safety: the caller's guarantee; close is async-signal-safe.
        unsafe { libc::close(self.parent_fd) };
    }

    /// Send the report: [`REPORT_PLACED`] or the placement write's errno.
    ///
    /// # Safety
    /// As [`ReportSlot::send`].
    pub(super) unsafe fn send_report(self, value: i32) -> io::Result<Delivery> {
        // Safety: the caller's guarantee.
        unsafe { self.send(TAG_REPORT, value, 0, -1) }
    }

    /// Send one message, with `pidfd` attached as `SCM_RIGHTS` unless it is -1. Async-signal-safe:
    /// one `sendmsg(2)` from buffers on the stack, then at most one `recv(2)`.
    ///
    /// `EPIPE` (or `ECONNRESET`) means the parent has ended the exchange (see the module's
    /// contract): *proceed* queued means it decided, and this child carries on; none means it
    /// abandoned the spawn.
    ///
    /// # Safety
    /// The child's end must still be open at this number, which holds from the leaf's creation
    /// until the parent has taken the verdict.
    pub(super) unsafe fn send(self, tag: i32, value: i32, handle: u64, pidfd: RawFd) -> io::Result<Delivery> {
        #[repr(C, align(8))]
        struct Control([u8; 64]);

        let mut message = [0u8; MESSAGE_LEN];
        message[..4].copy_from_slice(&tag.to_ne_bytes());
        message[4..8].copy_from_slice(&value.to_ne_bytes());
        message[8..].copy_from_slice(&handle.to_ne_bytes());
        let mut iov = libc::iovec {
            iov_base: message.as_mut_ptr().cast(),
            iov_len: message.len(),
        };
        let mut control = Control([0; 64]);
        // Safety: plain data; zeroed is a valid empty header.
        let mut header: libc::msghdr = unsafe { std::mem::zeroed() };
        header.msg_iov = &mut iov;
        header.msg_iovlen = 1;
        if pidfd >= 0 {
            let fd_len = std::mem::size_of::<RawFd>() as libc::c_uint;
            header.msg_control = control.0.as_mut_ptr().cast();
            // Safety: arithmetic on a length.
            let space = unsafe { libc::CMSG_SPACE(fd_len) } as usize;
            debug_assert!(
                space <= control.0.len(),
                "one descriptor's control message fits `control`, needs {space}"
            );
            header.msg_controllen = space as _;
            // Safety: `control` is aligned and large enough for one descriptor's header and data.
            unsafe {
                let cmsg = libc::CMSG_FIRSTHDR(&header);
                debug_assert!(!cmsg.is_null(), "`msg_controllen` leaves room for one header");
                (*cmsg).cmsg_level = libc::SOL_SOCKET;
                (*cmsg).cmsg_type = libc::SCM_RIGHTS;
                (*cmsg).cmsg_len = libc::CMSG_LEN(fd_len) as _;
                std::ptr::write_unaligned(libc::CMSG_DATA(cmsg).cast::<RawFd>(), pidfd);
            }
        }
        loop {
            // Safety: every pointer in `header` is to this frame; the caller guarantees the fd.
            let sent = unsafe { libc::sendmsg(self.fd, &header, libc::MSG_NOSIGNAL) };
            if sent == message.len() as isize {
                return Ok(Delivery::Queued);
            }
            // Safety: errno is this thread's own; `__errno_location` is async-signal-safe.
            let errno = unsafe { *libc::__errno_location() };
            return match (sent, errno) {
                (-1, libc::EINTR) => continue,
                // Safety: the caller's guarantee.
                // `ECONNRESET` is the same close, made with a message still unread.
                (-1, libc::EPIPE | libc::ECONNRESET) => Ok(if unsafe { self.proceed_queued() } {
                    Delivery::Decided
                } else {
                    Delivery::Abandoned
                }),
                (-1, errno) => Err(io::Error::from_raw_os_error(errno)),
                // SOCK_SEQPACKET sends a message whole or not at all.
                _ => Err(io::Error::from_raw_os_error(libc::EMSGSIZE)),
            };
        }
    }

    /// Whether the parent left *proceed* for this child before closing its end.
    ///
    /// # Safety
    /// As [`ReportSlot::send`].
    unsafe fn proceed_queued(self) -> bool {
        let mut byte = 0u8;
        loop {
            // Safety: a one-byte buffer on this frame; the caller guarantees the fd.
            let got = unsafe { libc::recv(self.fd, (&raw mut byte).cast(), 1, libc::MSG_DONTWAIT) };
            // Safety: as in `send`.
            if got == -1 && unsafe { *libc::__errno_location() } == libc::EINTR {
                continue;
            }
            return got == 1 && byte == PROCEED;
        }
    }
}

#[cfg(all(target_os = "linux", test))]
impl ReportSlot {
    /// Report `Placed` without a `cgroup.procs` write, for tests of what cosca does with a report.
    ///
    /// # Safety
    /// As [`ReportSlot::send`].
    pub(crate) unsafe fn report_placed_for_test(self) {
        // Safety: the caller guarantees the channel is open.
        let sent = unsafe { self.send_report(REPORT_PLACED) }.expect("send the report");
        assert_eq!(sent, Delivery::Queued, "the parent must still be listening");
    }
}

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