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;
#[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";
pub(crate) const UNREADABLE_STATUS_REASON: &str = "self/status could not be read";
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 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()))
}
}
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(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))
}
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 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,
)
}
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> {
utf8(self.read(path)?)
}
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(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())))
}
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> {
openat2(
CWD,
"/proc",
OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_MAGICLINKS,
)
}
pub(crate) fn utf8(bytes: Vec<u8>) -> io::Result<String> {
String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
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),
}
}
#[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(
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))
}
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)]
#[path = "proc_view_tests.rs"]
mod proc_view_tests;