use std::io;
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
use std::sync::Arc;
use super::parse::{is_at_or_under, parse_v2_relative_path};
use super::KillRecord;
use crate::child::owned::teardown::Reach;
use crate::child::owned::{ChildWaitOutcome, OwnedChild};
use crate::error::Error;
use crate::os_process::child::{ExitRecord, PeekOutcome};
use crate::os_process::linux::fork::{fork_with_pidfd, CloneKind, Fork, Path};
use crate::signal::{Sent, Sig};
const PIDFD_GET_INFO_VER0: libc::Ioctl = libc::_IOWR::<[u8; libc::PIDFD_INFO_SIZE_VER0 as usize]>(0xFF, 11);
const _: () = assert!(size_of::<libc::pidfd_info>() >= libc::PIDFD_INFO_SIZE_VER0 as usize);
pub(crate) fn pidfd_cgroup_id(pidfd: BorrowedFd<'_>) -> io::Result<Option<u64>> {
#[cfg(test)]
if super::fault::pidfd_info_missing() {
return Ok(None);
}
#[cfg(test)]
if let Some(errno) = super::fault::pidfd_info_fails() {
return Err(io::Error::from_raw_os_error(errno));
}
#[cfg(test)]
if let Some(id) = super::fault::forced_pidfd_cgroup_id() {
return Ok(Some(id));
}
let mut info: libc::pidfd_info = unsafe { std::mem::zeroed() };
info.mask = u64::from(libc::PIDFD_INFO_CGROUPID);
let rc = unsafe {
libc::ioctl(
pidfd.as_raw_fd(),
PIDFD_GET_INFO_VER0,
&mut info as *mut libc::pidfd_info,
)
};
if rc == 0 {
if info.mask & u64::from(libc::PIDFD_INFO_CGROUPID) == 0 {
return Ok(None);
}
return Ok(Some(info.cgroupid));
}
let e = io::Error::last_os_error();
match e.raw_os_error() {
Some(libc::ENOTTY) | Some(libc::EINVAL) => Ok(None),
_ => Err(e),
}
}
pub(crate) fn proc_names(
kernel: &dyn crate::identity::Kernel,
leaf_path: &str,
pid: u32,
recorded: impl FnOnce() -> Option<bool>,
other_id: bool,
) -> Result<bool, Error> {
use crate::identity::pid_file::ReadOutcome;
let proc_dir = match crate::identity::proc_view_with(kernel) {
crate::identity::ProcView::Same(dir) => dir,
crate::identity::ProcView::Diverged => {
return Err(Error::Io(io::Error::other(format!(
"{}, so pid {pid}'s cgroup cannot be read",
crate::identity::DIVERGED_REASON
))));
}
crate::identity::ProcView::Unassessable(why) => return Err(view_unreadable(pid, why)),
};
let text = match crate::identity::pid_file::read(kernel, &proc_dir, pid, "cgroup") {
Ok(ReadOutcome::Read(bytes)) => crate::identity::utf8(bytes)?,
Ok(ReadOutcome::Exited(e) | ReadOutcome::Hidden(e)) => return Err(Error::Io(e)),
Ok(ReadOutcome::Refused(refusal)) => return Err(refusal.unsupported(format!("reading pid {pid}'s cgroup"))),
Err(unreadable) => return Err(Error::Io(unreadable.into_io())),
};
let path = parse_v2_relative_path(&text)
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no cgroup v2 `0::` line"))?;
names_leaf(path, leaf_path, other_id, recorded).map_err(Error::Io)
}
fn view_unreadable(pid: u32, why: crate::identity::ViewUnreadable) -> Error {
if let Some(refusal) = why.refusal() {
return refusal.unsupported(format!("reading pid {pid}'s cgroup"));
}
let context = format!(
"the /proc view could not be established, so pid {pid}'s cgroup cannot be read: {}",
why.reason
);
Error::Io(crate::error::io_context_or_other(context, why.source))
}
const DELETED: &str = " (deleted)";
pub(crate) fn names_leaf(
path: &str,
leaf_path: &str,
other_id: bool,
recorded: impl FnOnce() -> Option<bool>,
) -> io::Result<bool> {
if is_at_or_under(path, leaf_path) {
return Ok(true);
}
if path.strip_suffix(DELETED) != Some(leaf_path) || other_id {
return Ok(false);
}
recorded().ok_or_else(|| {
io::Error::other(format!(
"{path} is either the removed leaf or a live cgroup of that name, and the task's place was not \
recorded before the leaf's removal"
))
})
}
#[derive(Debug, Clone, Default)]
pub(crate) struct PlacedAtRemoval(Arc<std::sync::Mutex<Option<(u32, bool)>>>);
impl PlacedAtRemoval {
pub(crate) fn record(&self, pid: u32, inside: bool) {
*self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((pid, inside));
}
pub(crate) fn clear(&self) {
*self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
pub(crate) fn of(&self, pid: u32) -> Option<bool> {
match *self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner) {
Some((recorded, inside)) if recorded == pid => Some(inside),
_ => None,
}
}
}
#[derive(Debug)]
pub(crate) struct Subtree {
leaf_id: Option<u64>,
dir: Option<Arc<OwnedFd>>,
path: Option<String>,
swept: super::Swept,
placed: PlacedAtRemoval,
killed: Arc<KillRecord>,
}
impl Subtree {
pub(crate) fn new(
leaf_id: Option<u64>,
dir: Option<Arc<OwnedFd>>,
path: Option<String>,
swept: super::Swept,
placed: PlacedAtRemoval,
killed: Arc<KillRecord>,
) -> Subtree {
Subtree {
leaf_id,
dir,
path,
swept,
placed,
killed,
}
}
pub(crate) fn holds(
&self,
kernel: &dyn crate::identity::Kernel,
pid: u32,
pidfd: Option<BorrowedFd<'_>>,
) -> Result<bool, Error> {
self.holds_seen(kernel, pid, pidfd, None).map(|(inside, _)| inside)
}
pub(crate) fn holds_seen(
&self,
kernel: &dyn crate::identity::Kernel,
pid: u32,
pidfd: Option<BorrowedFd<'_>>,
seen: Option<u64>,
) -> Result<(bool, Option<u64>), Error> {
let mut elsewhere = false;
let id = match pidfd {
Some(pidfd) if self.leaf_id.is_some() || seen.is_some() || !self.swept.is_empty() => {
match pidfd_cgroup_id(pidfd) {
Ok(id) => id,
Err(e) if self.leaf_id.is_none() && e.raw_os_error() != Some(libc::ESRCH) => {
log::debug!(
"the cgroup id of pid {pid} could not be read ({report}), so it is placed through /proc",
report = crate::error::Report(&e)
);
None
}
Err(e) => return Err(Error::Io(e)),
}
}
_ => None,
};
if let Some(id) = id {
if self.leaf_id == Some(id) || self.swept.holds(id) || seen == Some(id) {
return Ok((true, Some(id)));
}
if self.leaf_id.is_some() {
if let Some(under) = self.walk_places(id) {
return Ok((under, under.then_some(id)));
}
elsewhere = true;
}
}
let Some(path) = &self.path else {
return Ok((false, None));
};
proc_names(kernel, path, pid, || self.placed.of(pid), elsewhere)
.map(|inside| (inside, None))
.map_err(|e| match e {
Error::Io(e) if elsewhere => Error::Io(crate::error::io_context(
format!(
"pid {pid} is in another cgroup than its leaf, maybe one under it, and that cgroup's path \
cannot be read"
),
e,
)),
other => other,
})
}
fn walk_places(&self, id: u64) -> Option<bool> {
let dir = self.dir.as_ref()?;
match super::find_descendant(dir.as_fd(), id) {
super::Walked::Found => Some(true),
super::Walked::Absent => match self.dying() {
Ok(Some(0)) => Some(false),
Ok(dying) => {
log::debug!(
"the cgroups under a leaf were all walked without finding cgroup {id}, but {} are removed \
and not yet freed, so it is not shown to be outside",
dying.map_or("an unknown number".to_owned(), |n| n.to_string())
);
None
}
Err(e) => {
log::debug!(
"the cgroups under a leaf were all walked without finding cgroup {id}, but its cgroup.stat \
cannot be read ({report}), so it is not shown to be outside",
report = crate::error::Report(&e)
);
None
}
},
super::Walked::Unknown(e) => {
log::debug!(
"the cgroups under a leaf could not all be walked ({report})",
report = crate::error::Report(&e)
);
None
}
}
}
fn dying(&self) -> io::Result<Option<u64>> {
let dir = self
.dir
.as_ref()
.ok_or_else(|| io::Error::other("the subtree holds no leaf directory"))?;
let file = rustix::fs::openat(
dir.as_fd(),
"cgroup.stat",
rustix::fs::OFlags::RDONLY | rustix::fs::OFlags::CLOEXEC,
rustix::fs::Mode::empty(),
)?;
let text = io::read_to_string(std::fs::File::from(file))?;
Ok(dying_in(&text))
}
pub(crate) fn reached_by(
&self,
kernel: &dyn crate::identity::Kernel,
pid: u32,
pidfd: Option<BorrowedFd<'_>>,
seen: Option<u64>,
) -> Result<bool, Error> {
if !self.killed.landed() {
return Ok(false);
}
self.holds_seen(kernel, pid, pidfd, seen).map(|(inside, _)| inside)
}
}
impl Reach for Subtree {
fn reached(&self, child: &crate::child::owned::OwnedChild) -> Result<bool, Error> {
match child.pid() {
Some(pid) => self.reached_by(child.kernel(), pid, child.pidfd(), None),
None => Err(Error::Io(io::Error::other(
"the child's pid is not known, so it cannot be placed",
))),
}
}
fn would_reach(&self, child: &crate::child::owned::OwnedChild) -> Result<bool, Error> {
match child.pid() {
Some(pid) => self.holds(child.kernel(), pid, child.pidfd()),
None => Err(Error::Io(io::Error::other(
"the child's pid is not known, so it cannot be placed",
))),
}
}
}
fn dying_in(text: &str) -> Option<u64> {
text.lines()
.find_map(|line| line.strip_prefix("nr_dying_descendants ")?.trim().parse::<u64>().ok())
}
pub(crate) fn front_placement(
kernel: &crate::identity::SpawnKernel,
leaf_id: impl FnOnce() -> io::Result<u64>,
) -> Result<(), crate::error::Error> {
use std::os::fd::AsFd;
if let Err(e) = leaf_id() {
return Err(match e.raw_os_error() {
Some(libc::ENOSYS | libc::EOPNOTSUPP | libc::EPERM) => unplaceable(
"this host gives no cgroup's id by name_to_handle_at, as a kernel without CONFIG_FHANDLE, a \
filesystem without export operations or a seccomp filter refuses it"
.to_owned(),
Some(e),
),
_ => crate::error::Error::Io(crate::error::io_context(
"the cgroup id of the elevated front's leaf",
e,
)),
});
}
let own = rustix::process::pidfd_open(rustix::process::getpid(), rustix::process::PidfdFlags::empty())
.map_err(|e| crate::error::Error::Io(crate::error::io_context("pidfd_open of this process", e.into())))?;
let own_id = pidfd_cgroup_id(own.as_fd());
drop(own);
match own_id {
Ok(Some(_)) => return Ok(()),
Ok(None) => {}
Err(e) => {
return Err(unplaceable(
"PIDFD_GET_INFO failed on this process's own pidfd".to_owned(),
Some(e),
))
}
}
untraceable_cgroup_readable(kernel).map_err(refusal)
}
const PROBING: &str = "probing whether /proc shows the cgroup of a process this one may not trace";
fn refusal(why: Unreadable) -> crate::error::Error {
match why {
Unreadable::Hidden(e) => unplaceable(
"this kernel has no PIDFD_GET_INFO (Linux 6.13 or later), and /proc hides the cgroup of a process \
this one may not trace, as a hidepid /proc does: it would hide the elevated front's too"
.to_owned(),
Some(e),
),
Unreadable::View(why, cause) => unplaceable(
format!("this kernel has no PIDFD_GET_INFO (Linux 6.13 or later), and {why}"),
cause,
),
Unreadable::Refused(refusal) => unplaceable_by(
format!(
"this kernel has no PIDFD_GET_INFO (Linux 6.13 or later), and {}",
refusal.requirement()
),
Some(Arc::new(refusal.cause())),
),
Unreadable::Read(unreadable) => {
crate::error::Error::Io(crate::error::io_context_over(PROBING, unreadable.into_cause()))
}
Unreadable::Probe(e) => crate::error::Error::Io(crate::error::io_context(PROBING, e)),
}
}
fn unplaceable(why: String, cause: Option<io::Error>) -> crate::error::Error {
unplaceable_by(why, cause.map(crate::error::Error::io_cause))
}
fn unplaceable_by(why: String, cause: Option<Arc<crate::error::Error>>) -> crate::error::Error {
crate::error::Error::Unsupported {
op: "contain() on an elevated command".into(),
platform: "linux",
detail: format!(
"{why}. cosca could not tell whether a cgroup kill reached the elevated front, so the spawn is \
refused before anything is spawned"
),
source: cause,
}
}
#[derive(Debug)]
enum Unreadable {
Hidden(io::Error),
Refused(crate::identity::Refusal),
View(String, Option<io::Error>),
Read(crate::identity::pid_file::Unreadable),
Probe(io::Error),
}
const RELEASED: i32 = 0;
const ABANDONED: i32 = 1;
const SETUP_FAILED: u8 = 0xFF;
const SETUP_FAILED_LEN: usize = 5;
struct Probe {
pid: libc::pid_t,
child: OwnedChild,
channel: Option<std::os::unix::net::UnixStream>,
}
impl Probe {
fn channel(&self) -> &std::os::unix::net::UnixStream {
self.channel.as_ref().expect("a probe is not ended while it is read")
}
fn end(mut self) -> io::Result<ProbeEnd> {
let channel = self.channel.take().expect("a probe is ended once");
kill_and_reap(self.pid, &self.child, channel)
}
}
impl Drop for Probe {
fn drop(&mut self) {
let Some(channel) = self.channel.take() else {
return;
};
if let Err(e) = kill_and_reap(self.pid, &self.child, channel) {
log::warn!(
"containment::cgroup: the placement probe's child {} could not be reaped ({report})",
self.pid,
report = crate::error::Report(&e)
);
}
}
}
fn fork_probe(
proc: &crate::identity::ProcDir,
parent: libc::pid_t,
dumpable: bool,
kernel: crate::identity::SpawnKernel,
) -> io::Result<Probe> {
use std::os::fd::AsRawFd;
let guard = crate::child::spawn::spawn_lock();
let (channel, child_end) = std::os::unix::net::UnixStream::pair()?;
let ends = Ends {
child: child_end.as_raw_fd(),
parent: channel.as_raw_fd(),
};
let forked = unsafe { fork_with_pidfd(CloneKind::Plain) }.map_err(io::Error::from_raw_os_error)?;
let new = match forked {
Fork::Child => unsafe { probe_child(proc, parent, dumpable, ends) },
Fork::Parent(new) => new,
};
drop(child_end);
drop(guard);
if new.path == Path::Clone {
log::debug!(
"containment::cgroup: the placement probe's child was made by clone(CLONE_PIDFD): clone3 was refused"
);
}
Ok(Probe {
pid: new.pid,
child: OwnedChild::over_pidfd(
kernel,
Some(u32::try_from(new.pid).expect("a forked child's pid is positive")),
new.pidfd,
crate::elevation::front::TrackedKind::Own,
),
channel: Some(channel),
})
}
#[derive(Clone, Copy)]
struct Ends {
child: libc::c_int,
parent: libc::c_int,
}
unsafe fn probe_child(proc: &crate::identity::ProcDir, parent: libc::pid_t, dumpable: bool, ends: Ends) -> ! {
unsafe {
if !keep_only_own(proc, ends) {
libc::_exit(ABANDONED);
}
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL, 0, 0, 0);
if libc::getppid() != parent {
libc::_exit(ABANDONED);
}
if !dumpable {
libc::prctl(libc::PR_SET_DUMPABLE, 0, 0, 0, 0);
}
let mut pdeathsig: libc::c_int = 0;
libc::prctl(libc::PR_GET_PDEATHSIG, (&raw mut pdeathsig) as libc::c_ulong, 0, 0, 0);
let report = [libc::prctl(libc::PR_GET_DUMPABLE, 0, 0, 0, 0) as u8, pdeathsig as u8];
libc::write(ends.child, report.as_ptr().cast(), report.len());
let mut byte = 0u8;
let read = loop {
let n = libc::read(ends.child, (&raw mut byte).cast(), 1);
if n < 0 && *libc::__errno_location() == libc::EINTR {
continue;
}
break n;
};
libc::_exit(if read == 1 { RELEASED } else { ABANDONED });
}
}
unsafe fn keep_only_own(proc: &crate::identity::ProcDir, ends: Ends) -> bool {
use std::os::fd::IntoRawFd;
unsafe {
libc::close(ends.parent);
#[cfg(test)]
let opened = match super::fault::probe_fd_dir_fails() {
Some(errno) => Err(rustix::io::Errno::from_raw_os_error(errno)),
None => proc.open_own_fd_dir(),
};
#[cfg(not(test))]
let opened = proc.open_own_fd_dir();
let dir = match opened {
Ok(dir) => dir.into_raw_fd(),
Err(errno) => {
report_setup_failed(ends.child, errno.raw_os_error());
return false;
}
};
let close_range = |first: libc::c_uint, last: libc::c_uint| {
#[cfg(test)]
if super::fault::probe_close_range_refused() {
return false;
}
libc::syscall(libc::SYS_close_range, first, last, 0 as libc::c_uint) == 0
};
let ranges = ranges_around(ends.child as libc::c_uint, dir as libc::c_uint);
if ranges.iter().flatten().all(|&(first, last)| close_range(first, last)) {
libc::close(dir);
return true;
}
close_by_walk(dir, ends.child)
}
}
unsafe fn report_setup_failed(fd: libc::c_int, errno: i32) {
let mut report = [0u8; SETUP_FAILED_LEN];
report[0] = SETUP_FAILED;
report[1..].copy_from_slice(&errno.to_ne_bytes());
unsafe {
libc::write(fd, report.as_ptr().cast(), report.len());
}
}
fn ranges_around(kept: libc::c_uint, dir: libc::c_uint) -> [Option<(libc::c_uint, libc::c_uint)>; 3] {
debug_assert_ne!(kept, dir, "the walk's directory is not the kept descriptor");
let (low, high) = (kept.min(dir), kept.max(dir));
[
low.checked_sub(1).map(|last| (0, last)),
(high - low > 1).then(|| (low + 1, high - 1)),
high.checked_add(1).map(|first| (first, libc::c_uint::MAX)),
]
}
unsafe fn close_by_walk(dir: libc::c_int, keep: libc::c_int) -> bool {
#[repr(C, align(8))]
struct Buf([u8; 1024]);
const RECLEN: usize = 16;
const NAME: usize = 19;
let mut buf = Buf([0; 1024]);
unsafe {
loop {
let n = libc::syscall(libc::SYS_getdents64, dir, buf.0.as_mut_ptr(), buf.0.len());
if n < 0 {
libc::close(dir);
return false;
}
if n == 0 {
break;
}
let mut closed = false;
let mut at = 0;
while at < n as usize {
let reclen = usize::from(u16::from_ne_bytes([buf.0[at + RECLEN], buf.0[at + RECLEN + 1]]));
let name = &buf.0[at + NAME..at + reclen];
at += reclen;
let mut fd: libc::c_int = 0;
let mut digits = 0;
for &b in name.iter().take_while(|&&b| b != 0) {
if !b.is_ascii_digit() {
digits = 0;
break;
}
fd = fd.wrapping_mul(10).wrapping_add(libc::c_int::from(b - b'0'));
digits += 1;
}
if digits == 0 || fd == dir || fd == keep {
continue;
}
libc::close(fd);
closed = true;
}
if closed && libc::lseek(dir, 0, libc::SEEK_SET) < 0 {
libc::close(dir);
return false;
}
}
libc::close(dir);
}
true
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum ProbeEnd {
Signal(i32),
Exit(i32),
Elsewhere,
}
fn kill_and_reap(
pid: libc::pid_t,
child: &OwnedChild,
channel: std::os::unix::net::UnixStream,
) -> io::Result<ProbeEnd> {
match child.signal(Sig::Kill) {
Ok(Sent::Delivered) => {}
Ok(Sent::Unverified) => debug_assert!(false, "a send through a pidfd always verifies its process"),
Ok(Sent::Gone) => log::debug!(
"containment::cgroup: the placement probe's child {pid} had already exited, or was reaped by another reaper in this process, when it was to be killed"
),
Err(e) => log::warn!(
"containment::cgroup: the kill of the placement probe's child {pid} failed ({report}); it is released to exit by itself",
report = crate::error::Report(&e)
),
}
release_probe(pid, channel);
reap_through(pid, child)
}
fn release_probe(pid: libc::pid_t, channel: std::os::unix::net::UnixStream) {
let sent = loop {
match rustix::net::send(&channel, &[0], rustix::net::SendFlags::NOSIGNAL) {
Err(rustix::io::Errno::INTR) => continue,
other => break other,
}
};
match sent {
Ok(_) | Err(rustix::io::Errno::PIPE | rustix::io::Errno::CONNRESET) => {}
Err(e) => log::warn!(
"containment::cgroup: the placement probe's child {pid} could not be released ({report}); it exits once every copy of its socket closes",
report = crate::error::Report(&e)
),
}
}
fn reap_through(pid: libc::pid_t, child: &OwnedChild) -> io::Result<ProbeEnd> {
use std::os::unix::process::ExitStatusExt as _;
let end = match child.wait(None).map_err(Error::into_io)? {
ChildWaitOutcome::Exited(ExitRecord::Status(status)) => match status.signal() {
Some(signo) => ProbeEnd::Signal(signo),
None => ProbeEnd::Exit(status.code().unwrap_or(-1)),
},
ChildWaitOutcome::Exited(ExitRecord::Unreadable { si_code }) => {
debug_assert!(
false,
"a look at the probe's pidfd returned si_code {si_code}, which is no exit record: \
a kernel contract, which no policy's errno breaks"
);
ProbeEnd::Exit(-1)
}
ChildWaitOutcome::Foreign(_) => {
reaped_elsewhere(pid);
ProbeEnd::Elsewhere
}
ChildWaitOutcome::DeadlinePassed => unreachable!("a wait with no deadline does not pass one"),
};
#[cfg(test)]
super::fault::record_probe_end(end);
Ok(end)
}
fn reaped_elsewhere(pid: libc::pid_t) {
log::debug!(
"containment::cgroup: the placement probe's child {pid} was reaped by another reaper in this process or, with SIGCHLD ignored, by the kernel as it exited"
);
}
fn describe_end(read: &ProbeRead, end: ProbeEnd) -> String {
let ended = match end {
ProbeEnd::Signal(signo) => format!("it was killed by signal {signo}"),
ProbeEnd::Exit(ABANDONED) if matches!(read, ProbeRead::SetupFailed(_)) => {
format!("it exited ABANDONED ({ABANDONED})")
}
ProbeEnd::Exit(ABANDONED) => format!(
"it exited ABANDONED ({ABANDONED}): it could not set up its descriptors, its socket closed with no release byte, or its parent was gone"
),
ProbeEnd::Exit(status) => format!("it exited with status {status}"),
ProbeEnd::Elsewhere => {
"it was reaped by another reaper or, with SIGCHLD ignored, by the kernel as it exited, so its status is lost"
.to_owned()
}
};
match read {
ProbeRead::SetupFailed(_) => format!(
"the probe's child could not open its /proc/self/fd (it reported the failure); it was ended: {ended}"
),
ProbeRead::Gone(why) => format!("{why}: {ended}"),
ProbeRead::Answer(_) => ended,
}
}
fn log_probe_end(pid: libc::pid_t, read: &ProbeRead, end: ProbeEnd) {
match (read, end) {
(ProbeRead::SetupFailed(_), _) | (_, ProbeEnd::Signal(libc::SIGKILL) | ProbeEnd::Exit(RELEASED)) => {
log::debug!(
"containment::cgroup: the placement probe's child {pid} ended: {}",
describe_end(read, end)
);
}
(_, ProbeEnd::Elsewhere) => {}
(_, other) => log::warn!(
"containment::cgroup: the placement probe's child {pid} ended on its own: {}",
describe_end(read, other)
),
}
}
enum ProbeRead {
Answer(Result<(), Unreadable>),
Gone(&'static str),
SetupFailed(i32),
}
fn confirmed(read: Result<(), Unreadable>, peeked: Result<PeekOutcome, Error>) -> ProbeRead {
match peeked {
Ok(PeekOutcome::Running) => ProbeRead::Answer(read),
Ok(PeekOutcome::Exit(_) | PeekOutcome::Foreign(_)) => ProbeRead::Gone(
"the probe's child had exited by the time its cgroup read was confirmed, so the read may describe another process",
),
Err(e) => ProbeRead::Answer(Err(Unreadable::Probe(e.into_io()))),
}
}
fn untraceable_cgroup_readable(kernel: &crate::identity::SpawnKernel) -> Result<(), Unreadable> {
let proc_dir = match crate::identity::proc_view_with(&**kernel) {
crate::identity::ProcView::Same(dir) => dir,
crate::identity::ProcView::Diverged => {
return Err(Unreadable::View(
format!(
"{}, so no process's cgroup can be read by its pid",
crate::identity::DIVERGED_REASON
),
None,
))
}
crate::identity::ProcView::Unassessable(why) => {
if let Some(refusal) = why.refusal() {
return Err(Unreadable::Refused(refusal));
}
return Err(Unreadable::View(
format!("this process's /proc view could not be established ({})", why.reason),
why.source,
));
}
};
#[cfg(test)]
let dumpable = super::fault::probe_kept_dumpable();
#[cfg(not(test))]
let dumpable = false;
let probe = fork_probe(
&proc_dir,
rustix::process::getpid().as_raw_nonzero().get(),
dumpable,
std::sync::Arc::clone(kernel),
)
.map_err(Unreadable::Probe)?;
let pid = probe.pid;
let mut ready = [0u8; SETUP_FAILED_LEN];
let readied = loop {
match std::io::Read::read(&mut probe.channel(), &mut ready) {
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
other => break other,
}
};
let read = match readied {
Ok(SETUP_FAILED_LEN) if ready[0] == SETUP_FAILED => {
ProbeRead::SetupFailed(i32::from_ne_bytes([ready[1], ready[2], ready[3], ready[4]]))
}
Ok(2) if ready[0] != 0 => ProbeRead::Answer(Err(Unreadable::Probe(io::Error::other(
"the probe's child could not make itself non-dumpable",
)))),
Ok(2) if i32::from(ready[1]) != libc::SIGKILL => ProbeRead::Answer(Err(Unreadable::Probe(io::Error::other(
"the probe's child could not ask to die with its parent",
)))),
Ok(2) => {
use crate::identity::pid_file::ReadOutcome;
let child = u32::try_from(pid).expect("a forked child's pid is positive");
let read = match crate::identity::pid_file::read(&**kernel, &proc_dir, child, "cgroup") {
Ok(ReadOutcome::Read(bytes)) => crate::identity::utf8(bytes).map(drop).map_err(Unreadable::Probe),
Ok(ReadOutcome::Hidden(e)) => Err(Unreadable::Hidden(e)),
Ok(ReadOutcome::Exited(e)) => Err(Unreadable::Probe(e)),
Ok(ReadOutcome::Refused(refusal)) => Err(Unreadable::Refused(refusal)),
Err(unreadable) => Err(Unreadable::Read(unreadable)),
};
confirmed(read, probe.child.peek())
}
Ok(_) => ProbeRead::Gone("the probe's child died before it was ready"),
Err(e) => ProbeRead::Answer(Err(Unreadable::Probe(e))),
};
let end = probe.end().map_err(Unreadable::Probe)?;
log_probe_end(pid, &read, end);
match read {
ProbeRead::Answer(answer) => answer,
ProbeRead::Gone(_) => Err(Unreadable::Probe(io::Error::other(describe_end(&read, end)))),
ProbeRead::SetupFailed(errno) => {
use crate::identity::OwnUnreadable;
Err(
match OwnUnreadable::opening(rustix::io::Errno::from_raw_os_error(errno)) {
OwnUnreadable::Refused(refusal) => Unreadable::Refused(refusal),
OwnUnreadable::Failed(e) => {
Unreadable::Probe(crate::error::io_context(describe_end(&read, end), e))
}
},
)
}
}
}
#[cfg(test)]
#[path = "reach_tests.rs"]
mod reach_tests;