artifactize-foundation 0.27.2

Native file, path and executable primitives for Artifactize.
Documentation
//! A Linux subreaper for one launch, not for every child of the artifactize process.

use std::{
    io,
    os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd},
    os::unix::process::ExitStatusExt,
    process::ExitStatus,
};
use tokio::io::unix::AsyncFd;

use super::{ProcessOutcome, ResolvedCommand};

pub(super) struct Reaper(AsyncFd<OwnedFd>);

impl Reaper {
    pub(super) fn spawn(mut command: ResolvedCommand) -> io::Result<(tokio::process::Child, Self)> {
        let (status, report) = socket_pair()?;
        let status = AsyncFd::new(status)?;
        // The child remaps stdio before pre_exec, even if an inherited stream was closed.
        let report = if report.as_raw_fd() <= libc::STDERR_FILENO {
            rustix::io::fcntl_dupfd_cloexec(&report, libc::STDERR_FILENO + 1)?
        } else {
            report
        };
        command.command.process_group(0).kill_on_drop(false);
        // SAFETY: the setup and reaper use only Linux syscalls, async-signal-safe libc
        // functions and stack data. The workload alone returns to std's normal exec path.
        unsafe {
            command
                .command
                .pre_exec(move || fork_workload(report.as_raw_fd()))
        };
        Ok((command.spawn()?, Self(status)))
    }

    pub(super) async fn wait(&self) -> io::Result<ProcessOutcome> {
        loop {
            let mut ready = self.0.readable().await?;
            match ready.try_io(|_| self.outcome()) {
                Ok(result) => return result,
                Err(_) => continue,
            }
        }
    }

    pub(super) fn try_wait(&self) -> io::Result<Option<ProcessOutcome>> {
        match self.outcome() {
            Ok(outcome) => Ok(Some(outcome)),
            Err(error) if error.kind() == io::ErrorKind::WouldBlock => Ok(None),
            Err(error) => Err(error),
        }
    }

    fn outcome(&self) -> io::Result<ProcessOutcome> {
        let mut bytes = [0; size_of::<libc::c_int>()];
        loop {
            // SAFETY: recv writes into `bytes`; the fd is owned by this reaper handle.
            // The one packet stays queued, so polling, waiting and cleanup see the same result.
            let read = unsafe {
                libc::recv(
                    self.0.get_ref().as_raw_fd(),
                    bytes.as_mut_ptr().cast(),
                    bytes.len(),
                    libc::MSG_PEEK | libc::MSG_DONTWAIT,
                )
            };
            match read {
                n if n == bytes.len() as isize => {
                    return Ok(ProcessOutcome::from_native(ExitStatus::from_raw(
                        libc::c_int::from_ne_bytes(bytes),
                    )));
                }
                0 => return Err(io::ErrorKind::BrokenPipe.into()),
                ..0 => {
                    let error = io::Error::last_os_error();
                    if error.kind() != io::ErrorKind::Interrupted {
                        return Err(error);
                    }
                }
                _ => return Err(io::ErrorKind::InvalidData.into()),
            }
        }
    }
}

fn socket_pair() -> io::Result<(OwnedFd, OwnedFd)> {
    let mut fds = [-1; 2];
    // SAFETY: socketpair initializes two descriptors on success; this call owns both.
    unsafe {
        if libc::socketpair(
            libc::AF_UNIX,
            libc::SOCK_SEQPACKET | libc::SOCK_CLOEXEC | libc::SOCK_NONBLOCK,
            0,
            fds.as_mut_ptr(),
        ) != 0
        {
            return Err(io::Error::last_os_error());
        }
        Ok((OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])))
    }
}

fn fork_workload(report: RawFd) -> io::Result<()> {
    // A plain clone with an inherited stack is fork without pthread_atfork callbacks.
    // The workload does not inherit the subreaper setting and can use waitpid normally.
    // SAFETY: a single-threaded pre-exec child calls this with a live socket descriptor;
    // these syscalls only change this process and clone private memory and descriptors.
    let pid = unsafe {
        if libc::prctl(
            libc::PR_SET_CHILD_SUBREAPER,
            1 as libc::c_ulong,
            0 as libc::c_ulong,
            0 as libc::c_ulong,
            0 as libc::c_ulong,
        ) != 0
            || libc::signal(libc::SIGCHLD, libc::SIG_DFL) == libc::SIG_ERR
        {
            return Err(io::Error::last_os_error());
        }
        let null = std::ptr::null_mut::<libc::c_void>();
        #[cfg(not(target_arch = "s390x"))]
        let pid = libc::syscall(libc::SYS_clone, libc::SIGCHLD, null, null, null, null);
        #[cfg(target_arch = "s390x")]
        let pid = libc::syscall(libc::SYS_clone, null, libc::SIGCHLD, null, null, null);
        pid as libc::pid_t
    };
    match pid {
        ..0 => Err(io::Error::last_os_error()),
        0 => {
            // SAFETY: only the workload's group changes, not its inherited session.
            if unsafe { libc::setpgid(0, 0) } == 0 {
                Ok(())
            } else {
                Err(io::Error::last_os_error())
            }
        }
        pid => reap(pid, report),
    }
}

fn reap(leader: libc::pid_t, report: RawFd) -> ! {
    // Before closing the inherited fd table, prevent inherited signal handlers from
    // running: they can still refer to old fd numbers. Restoring the original mask in
    // the workload is unnecessary because it never executes this branch.
    let mut blocked = std::mem::MaybeUninit::<libc::sigset_t>::uninit();
    // SAFETY: sigfillset writes a complete set; sigprocmask copies it into the kernel.
    unsafe {
        libc::sigfillset(blocked.as_mut_ptr());
        libc::sigprocmask(libc::SIG_SETMASK, blocked.as_ptr(), std::ptr::null_mut());
    }
    // Release std's exec-error pipe, the workload's stdio, and all unrelated descriptors.
    // The forked workload still owns its copies and reports exec errors normally.
    if super::descriptors::close_except(report).is_err() {
        // SAFETY: the workload is our own unreaped child. The reaper cannot safely run
        // with inherited descriptors after the exec-error pipe has been closed.
        unsafe {
            libc::kill(leader, libc::SIGKILL);
            while libc::waitpid(leader, std::ptr::null_mut(), 0) < 0
                && *libc::__errno_location() == libc::EINTR
            {}
            libc::_exit(1);
        }
    }
    // SAFETY: this process owns only the workload and its adopted descendants; waitpid
    // writes one status word and send reads only that word. No allocation or unwinding.
    unsafe {
        let mut unreported = Some(leader);
        loop {
            let mut status = 0;
            // Include clone children even if they don't use SIGCHLD to notify their parent.
            let pid = libc::waitpid(-1, &mut status, libc::__WALL);
            if pid < 0 {
                match *libc::__errno_location() {
                    libc::EINTR => continue,
                    libc::ECHILD => libc::_exit(0),
                    _ => libc::_exit(1),
                }
            }
            if unreported == Some(pid) && (libc::WIFEXITED(status) || libc::WIFSIGNALED(status)) {
                unreported = None;
                let bytes = status.to_ne_bytes();
                while libc::send(
                    report,
                    bytes.as_ptr().cast(),
                    bytes.len(),
                    libc::MSG_NOSIGNAL,
                ) < 0
                    && *libc::__errno_location() == libc::EINTR
                {}
            }
        }
    }
}