use std::io::{self, Read};
use std::os::fd::{AsRawFd, BorrowedFd, OwnedFd};
use rustix::fs::{openat2, Mode, OFlags, ResolveFlags, CWD, PROC_SUPER_MAGIC};
use crate::error::Error;
#[derive(Debug)]
pub(crate) enum ProcView {
Same(ProcDir),
Diverged,
Unassessable(ViewUnreadable),
}
pub(crate) const DIVERGED_REASON: &str = "this process's /proc is an outer pid namespace's";
impl ProcView {
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),
}
}
}
#[derive(Debug)]
pub(crate) struct ViewUnreadable {
pub(crate) reason: String,
pub(crate) source: Option<io::Error>,
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,
}
}
pub(crate) fn unsupported(&self, op: impl Into<String>) -> Option<Error> {
self.openat2_requirement().map(|detail| Error::Unsupported {
op: op.into(),
platform: "linux",
detail,
})
}
pub(crate) fn openat2_requirement(&self) -> Option<String> {
self.openat2_refused.map(openat2_refused_message)
}
}
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),
}
}
}
#[derive(Debug)]
pub(crate) struct ProcDir(OwnedFd);
impl ProcDir {
pub(crate) fn open() -> Result<ProcDir, ViewUnreadable> {
let fd = open_proc_root().map_err(|e| ViewUnreadable {
openat2_refused: match e {
rustix::io::Errno::NOSYS => Some("ENOSYS"),
rustix::io::Errno::PERM => Some("EPERM"),
_ => None,
},
..ViewUnreadable::new("/proc could not be opened", Some(e.into()))
})?;
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))
}
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)
}
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)
}
pub(crate) fn read_to_string(&self, path: &str) -> io::Result<String> {
String::from_utf8(self.read(path)?).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
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())
}
pub(crate) fn pids(&self) -> io::Result<Vec<u32>> {
#[cfg(test)]
if let Some(errno) = fault::forced_pids_errno() {
return Err(io::Error::from_raw_os_error(errno));
}
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())))
}
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),
}
}
}
const PROC_ROOT_INO: u64 = 1;
fn open_proc_root() -> Result<OwnedFd, rustix::io::Errno> {
#[cfg(test)]
if let Some(errno) = fault::forced_openat2_errno() {
return Err(errno);
}
openat2(
CWD,
"/proc",
OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_MAGICLINKS,
)
}
pub(crate) fn proc_view() -> ProcView {
#[cfg(test)]
let forced = fault::take_forced_proc_view();
#[cfg(test)]
match forced {
Some(fault::ForcedView::Diverged) => return ProcView::Diverged,
Some(fault::ForcedView::Unassessable) => {
return ProcView::Unassessable(ViewUnreadable::new("forced by a test", None));
}
Some(fault::ForcedView::Same) => {
return match ProcDir::open() {
Ok(dir) => ProcView::Same(dir),
Err(why) => ProcView::Unassessable(why),
};
}
None => {}
}
let dir = match ProcDir::open() {
Ok(dir) => dir,
Err(why) => return ProcView::Unassessable(why),
};
#[cfg(test)]
let forced_status = fault::take_forced_status();
#[cfg(not(test))]
let forced_status: Option<String> = None;
let status = match forced_status.map_or_else(|| dir.read_to_string("self/status"), Ok) {
Ok(text) => text,
Err(e) => {
return ProcView::Unassessable(ViewUnreadable::new("self/status could not be read", 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),
}
}
#[derive(Debug)]
enum Verdict {
Same,
NoNspid,
Diverged,
Unassessable(ViewUnreadable),
}
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,
}
}
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"))
}
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),
}
}
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")
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum PidfdTarget {
Pid(u32),
Reaped,
}
pub(crate) fn pidfd_pid_in_view(dir: &ProcDir, pidfd: BorrowedFd<'_>) -> Result<PidfdTarget, ViewUnreadable> {
#[cfg(test)]
if let Some(forced) = fault::take_forced_fdinfo() {
return forced.map_err(|errno| {
ViewUnreadable::new(
"the pidfd's fdinfo could not be read",
Some(io::Error::from_raw_os_error(errno)),
)
});
}
let fdinfo = dir
.read_to_string(&format!("thread-self/fdinfo/{}", pidfd.as_raw_fd()))
.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))
}
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),
})
}
fn collect_pids(names: impl IntoIterator<Item = io::Result<Vec<u8>>>) -> io::Result<Vec<u32>> {
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;
}
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)]
pub(crate) mod fault {
use std::cell::{Cell, RefCell};
#[derive(Debug, Clone, Copy)]
pub(crate) enum ForcedView {
Same,
Diverged,
Unassessable,
}
thread_local! {
static FORCE_PROC_VIEW: Cell<Option<ForcedView>> = const { Cell::new(None) };
static FORCE_PROC_VIEW_SKIP: Cell<u32> = const { Cell::new(0) };
static PROC_VIEW_CALLS: Cell<u32> = const { Cell::new(0) };
static PROC_VIEW_FIRED_AT: Cell<Option<u32>> = const { Cell::new(None) };
static FORCE_PIDS_ERRNO: Cell<Option<i32>> = const { Cell::new(None) };
static FORCE_IDENTITY_STAT: RefCell<Vec<(u32, i32)>> = const { RefCell::new(Vec::new()) };
static FORCE_STATUS: RefCell<Option<String>> = const { RefCell::new(None) };
static FORCE_FDINFO: Cell<Option<Result<super::PidfdTarget, i32>>> = const { Cell::new(None) };
static FORCE_OPENAT2_ERRNO: Cell<Option<rustix::io::Errno>> = const { Cell::new(None) };
static FORCE_SELF_STAT: RefCell<Option<Vec<u8>>> = const { RefCell::new(None) };
}
#[must_use = "dropping this immediately disarms the forced values; bind it for the probe's duration"]
pub(crate) struct Forced(());
impl Drop for Forced {
fn drop(&mut self) {
FORCE_PROC_VIEW.with(|f| f.set(None));
FORCE_PROC_VIEW_SKIP.with(|f| f.set(0));
PROC_VIEW_CALLS.with(|f| f.set(0));
PROC_VIEW_FIRED_AT.with(|f| f.set(None));
FORCE_PIDS_ERRNO.with(|f| f.set(None));
FORCE_IDENTITY_STAT.with(|f| f.borrow_mut().clear());
FORCE_FDINFO.with(|f| f.set(None));
FORCE_STATUS.with(|f| f.take());
FORCE_OPENAT2_ERRNO.with(|f| f.set(None));
FORCE_SELF_STAT.with(|f| f.take());
}
}
pub(crate) fn force_openat2_errno(errno: rustix::io::Errno) -> Forced {
FORCE_OPENAT2_ERRNO.with(|f| f.set(Some(errno)));
Forced(())
}
pub(crate) fn forced_openat2_errno() -> Option<rustix::io::Errno> {
FORCE_OPENAT2_ERRNO.with(|f| f.get())
}
pub(crate) fn force_pids_errno(errno: i32) -> Forced {
FORCE_PIDS_ERRNO.with(|f| f.set(Some(errno)));
Forced(())
}
pub(crate) fn forced_pids_errno() -> Option<i32> {
FORCE_PIDS_ERRNO.with(|f| f.get())
}
pub(crate) fn force_identity_stat_errno(pid: u32, errno: i32) -> Forced {
FORCE_IDENTITY_STAT.with(|f| f.borrow_mut().push((pid, errno)));
Forced(())
}
pub(crate) fn forced_identity_stat_errno(pid: u32) -> Option<i32> {
FORCE_IDENTITY_STAT.with(|f| f.borrow().iter().find(|&&(p, _)| p == pid).map(|&(_, e)| e))
}
pub(crate) fn force_self_stat_once(bytes: &[u8]) -> Forced {
FORCE_SELF_STAT.with(|f| *f.borrow_mut() = Some(bytes.to_vec()));
Forced(())
}
pub(crate) fn take_forced_self_stat() -> Option<Vec<u8>> {
FORCE_SELF_STAT.with(|f| f.take())
}
pub(crate) fn force_status_once(text: &str) -> Forced {
FORCE_STATUS.with(|f| *f.borrow_mut() = Some(text.to_owned()));
Forced(())
}
pub(crate) fn take_forced_status() -> Option<String> {
FORCE_STATUS.with(|f| f.take())
}
pub(crate) fn force_proc_view_once(view: ForcedView) -> Forced {
PROC_VIEW_CALLS.with(|f| f.set(0));
PROC_VIEW_FIRED_AT.with(|f| f.set(None));
FORCE_PROC_VIEW.with(|f| f.set(Some(view)));
Forced(())
}
pub(crate) fn force_proc_view_after(skip: u32, view: ForcedView) -> Forced {
FORCE_PROC_VIEW_SKIP.with(|f| f.set(skip));
force_proc_view_once(view)
}
pub(crate) fn force_fdinfo_once(answer: Result<super::PidfdTarget, i32>) -> Forced {
FORCE_FDINFO.with(|f| f.set(Some(answer)));
Forced(())
}
pub(crate) fn proc_view_fired_at() -> Option<u32> {
PROC_VIEW_FIRED_AT.with(|f| f.get())
}
pub(crate) fn take_forced_proc_view() -> Option<ForcedView> {
let index = PROC_VIEW_CALLS.with(|f| {
let n = f.get();
f.set(n + 1);
n
});
let skipped = FORCE_PROC_VIEW_SKIP.with(|f| {
let n = f.get();
f.set(n.saturating_sub(1));
n > 0
});
if skipped {
return None;
}
let forced = FORCE_PROC_VIEW.with(|f| f.take());
if forced.is_some() {
PROC_VIEW_FIRED_AT.with(|f| f.set(Some(index)));
}
forced
}
pub(crate) fn take_forced_fdinfo() -> Option<Result<super::PidfdTarget, i32>> {
FORCE_FDINFO.with(|f| f.take())
}
}
#[cfg(test)]
#[path = "proc_view_tests.rs"]
mod proc_view_tests;