use std::io;
use std::os::fd::{AsRawFd, BorrowedFd};
use super::kernel::Kernel;
use super::pid_file::{self, ReadOutcome};
use super::proc_read::{read_own, read_own_link, utf8, OwnUnreadable, ProcDir, ProcOpenFailure};
use super::refusal::Refusal;
use crate::error::{io_context, 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) enum ViewReadFailure {
Own(OwnUnreadable),
Pid1 {
source: io::Error,
refusal: Option<Refusal>,
},
}
impl From<OwnUnreadable> for ViewReadFailure {
fn from(own: OwnUnreadable) -> Self {
ViewReadFailure::Own(own)
}
}
#[derive(Debug)]
pub(crate) struct ViewUnreadable {
pub(crate) reason: String,
pub(crate) source: Option<io::Error>,
refusal: Option<Box<Refusal>>,
}
impl ViewUnreadable {
fn new(reason: impl Into<String>, source: Option<io::Error>) -> Self {
ViewUnreadable {
reason: reason.into(),
source,
refusal: None,
}
}
pub(crate) fn of_failure(reason: impl Into<String>, failure: impl Into<ViewReadFailure>) -> Self {
let (source, refusal) = match failure.into() {
ViewReadFailure::Own(OwnUnreadable::Refused(refusal)) => (refusal.cause_io(), Some(refusal)),
ViewReadFailure::Own(OwnUnreadable::Failed(e)) => (e, None),
ViewReadFailure::Pid1 { source, refusal } => (source, refusal),
};
ViewUnreadable {
refusal: refusal.map(Box::new),
..ViewUnreadable::new(reason, Some(source))
}
}
pub(crate) fn unsupported(&self, op: impl Into<String>) -> Option<Error> {
self.refusal.as_ref().map(|refusal| refusal.unsupported(op))
}
pub(crate) fn refusal(&self) -> Option<Refusal> {
self.refusal.as_deref().cloned()
}
}
impl From<ProcOpenFailure> for ViewUnreadable {
fn from(failure: ProcOpenFailure) -> Self {
match failure {
ProcOpenFailure::Open(own) => ViewUnreadable::of_failure("/proc could not be opened", own),
ProcOpenFailure::Check(e) => ViewUnreadable::new("/proc could not be checked", Some(e)),
ProcOpenFailure::NotProcfs { f_type } => {
ViewUnreadable::new(format!("/proc is not procfs (filesystem type {f_type:#x})"), None)
}
ProcOpenFailure::NotRoot { ino } => {
ViewUnreadable::new(format!("/proc is not the root of procfs (inode {ino})"), None)
}
}
}
}
impl std::fmt::Display for ViewUnreadable {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.reason)
}
}
impl std::error::Error for ViewUnreadable {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
self.source.as_ref().map(|e| e as _)
}
}
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.into()),
};
let status = match read_own(kernel, &dir, "self/status") {
Ok(bytes) => match utf8(bytes) {
Ok(text) => text,
Err(e) => return ProcView::Unassessable(ViewUnreadable::new(UNREADABLE_STATUS_REASON, Some(e))),
},
Err(own) => return ProcView::Unassessable(ViewUnreadable::of_failure(UNREADABLE_STATUS_REASON, own)),
};
let verdict = match classify_status(&status, || read_own_link(kernel, &dir, OWN_NS_LINK)) {
Verdict::NoNspid(own) => cross_check_with_init_ns(kernel, &dir, own),
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(Vec<u8>),
Diverged,
Unassessable(ViewUnreadable),
}
const OWN_NS_LINK: &str = "thread-self/ns/pid";
fn classify_status(status: &str, own_ns_link: impl FnOnce() -> Result<Option<Vec<u8>>, OwnUnreadable>) -> Verdict {
let Some(line) = status.lines().find_map(|l| l.strip_prefix("NSpid:")) else {
return match own_ns_link() {
Ok(None) => Verdict::Same,
Ok(Some(own)) => Verdict::NoNspid(own),
Err(own) => Verdict::Unassessable(ViewUnreadable::of_failure(
format!("self/status has no NSpid line and {OWN_NS_LINK} could not be checked"),
own,
)),
};
};
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(kernel: &dyn Kernel, dir: &ProcDir, own: Vec<u8>) -> Verdict {
classify_ns_links(own, || init_ns_link(kernel, dir))
}
fn init_ns_link(kernel: &dyn Kernel, dir: &ProcDir) -> Result<Vec<u8>, ViewReadFailure> {
let (source, refusal) = match pid_file::read_link(kernel, dir, 1, "ns/pid") {
Ok(ReadOutcome::Read(target)) => return Ok(target),
Ok(ReadOutcome::Refused(refusal)) => (refusal.cause_io(), Some(refusal)),
Ok(ReadOutcome::Exited(e)) => (io_context("pid 1 exited", e), None),
Ok(ReadOutcome::Hidden(e)) => (io_context("pid 1 is not shown to this process", e), None),
Err(unreadable) => (unreadable.into_io(), None),
};
Err(ViewReadFailure::Pid1 { source, refusal })
}
fn classify_ns_links(own: Vec<u8>, init: impl FnOnce() -> Result<Vec<u8>, ViewReadFailure>) -> Verdict {
let links = pid_ns_link(Ok(own), OWN_NS_LINK)
.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: Result<Vec<u8>, ViewReadFailure>, 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(failure) => Err(ViewUnreadable::of_failure(
format!("self/status has no NSpid line and {path} could not be read"),
failure,
)),
}
}
#[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> {
const UNREADABLE: &str = "the pidfd's fdinfo could not be read";
let bytes = read_own(kernel, dir, &format!("thread-self/fdinfo/{}", pidfd.as_raw_fd()))
.map_err(|own| ViewUnreadable::of_failure(UNREADABLE, own))?;
let fdinfo = utf8(bytes).map_err(|e| ViewUnreadable::new(UNREADABLE, 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),
})
}
#[cfg(test)]
#[path = "proc_view_tests.rs"]
mod proc_view_tests;