#[path = "linux/exit.rs"]
pub(crate) mod exit;
#[path = "linux/kernel.rs"]
pub(crate) mod kernel;
#[path = "linux/pid_file.rs"]
pub(crate) mod pid_file;
#[path = "linux/proc_read.rs"]
pub(crate) mod proc_read;
#[path = "linux/proc_view.rs"]
pub(crate) mod proc_view;
#[path = "linux/prove.rs"]
pub(crate) mod prove;
#[path = "linux/refusal.rs"]
pub(crate) mod refusal;
#[cfg(test)]
#[path = "linux/bracket_tests.rs"]
mod bracket_tests;
#[cfg(test)]
#[path = "linux/look_tests.rs"]
mod look_tests;
#[cfg(test)]
#[path = "linux/read_tests.rs"]
mod read_tests;
#[cfg(test)]
#[path = "linux/read_namespace_tests.rs"]
mod read_namespace_tests;
use std::os::fd::AsFd as _;
use std::time::{Duration, SystemTime};
use rustix::io::Errno;
use rustix::process::{Pid, PidfdFlags};
use self::kernel::Kernel;
use self::proc_read::ProcDir;
use self::prove::Proof;
use self::refusal::FailedCall;
use super::probe::{classify_unreadable, SignalProbe};
use super::stat_parse::{parse_ppid, parse_starttime_jiffies};
use super::{Existence, Liveness, OrderedRead, ParentRead, RawPid, Resolved, TokenKind, UnknownCause};
use crate::error::Error;
fn signal_probe(kernel: &dyn Kernel, pid: RawPid) -> SignalProbe {
let Some(target) = super::probe::signal_target(pid).and_then(Pid::from_raw) else {
return SignalProbe::NotAPid;
};
match kernel.signal_probe(target) {
Ok(()) => SignalProbe::Signalable,
Err(Errno::SRCH) => SignalProbe::NoSuchProcess,
Err(_) => SignalProbe::Denied,
}
}
fn read_stat(kernel: &dyn Kernel, pid: RawPid) -> Resolved<Vec<u8>> {
read_stat_explained(kernel, pid).0
}
fn read_stat_explained(kernel: &dyn Kernel, pid: RawPid) -> (Resolved<Vec<u8>>, UnknownCause) {
match proc_view::proc_view_with(kernel).into_dir() {
Ok(dir) => read_in(kernel, &dir, pid),
Err(why) => (
resolve_unreadable(
kernel,
pid,
format_args!(
"the /proc view could not be established: {report}",
report = crate::error::Report(&why)
),
),
UnknownCause::of_view(Some(why)),
),
}
}
fn read_in(kernel: &dyn Kernel, dir: &ProcDir, pid: RawPid) -> (Resolved<Vec<u8>>, UnknownCause) {
use pid_file::ReadOutcome;
let (resolved, cause) = match pid_file::read(kernel, dir, pid, "stat") {
Ok(ReadOutcome::Read(bytes)) => return (Resolved::Found(bytes), UnknownCause::default()),
Ok(ReadOutcome::Exited(e) | ReadOutcome::Hidden(e)) => (
resolve_unreadable(kernel, pid, crate::error::Report(&e)),
UnknownCause::default(),
),
Ok(ReadOutcome::Refused(refusal)) => (
resolve_unreadable(kernel, pid, refusal.requirement()),
UnknownCause::of_refusal(refusal),
),
Err(unreadable) => (
resolve_unreadable(kernel, pid, crate::error::Report(&unreadable)),
UnknownCause::of_unreadable(unreadable),
),
};
match resolved {
Resolved::Unknown => (Resolved::Unknown, cause),
resolved => (resolved, UnknownCause::default()),
}
}
fn resolve_unreadable(kernel: &dyn Kernel, pid: RawPid, why: impl std::fmt::Display) -> Resolved<Vec<u8>> {
match classify_unreadable(signal_probe(kernel, pid)) {
Resolved::Gone => Resolved::Gone,
_ => {
log::debug!("/proc/{pid}/stat not read ({why}) but the pid is not provably gone");
Resolved::Unknown
}
}
}
pub(super) fn signal_says_no_such_process(kernel: &dyn Kernel, pid: RawPid) -> bool {
signal_probe(kernel, pid) == SignalProbe::NoSuchProcess
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Key {
Pidfs(u64),
Ticks(u64),
}
impl Key {
pub(super) fn raw(self) -> u64 {
match self {
Key::Pidfs(v) | Key::Ticks(v) => v,
}
}
pub(super) fn restored(token: u64, kind: Option<&TokenKind>) -> Key {
debug_assert!(
matches!(kind, Some(TokenKind::Pidfs | TokenKind::Ticks)),
"a validated record names a kind of token, not {kind:?}"
);
match kind {
Some(TokenKind::Pidfs) => Key::Pidfs(token),
_ => Key::Ticks(token),
}
}
pub(super) fn wire_kind(self) -> Option<TokenKind> {
Some(match self {
Key::Pidfs(_) => TokenKind::Pidfs,
Key::Ticks(_) => TokenKind::Ticks,
})
}
#[cfg(test)]
pub(crate) fn for_test(v: u64) -> Key {
Key::Ticks(v)
}
#[cfg(test)]
pub(crate) fn ticks(self) -> u64 {
match self {
Key::Ticks(v) => v,
Key::Pidfs(_) => panic!("{self:?} has no ticks"),
}
}
#[cfg(test)]
pub(super) fn other_value(self) -> Key {
match self {
Key::Pidfs(v) => Key::Pidfs(v.wrapping_add(1)),
Key::Ticks(v) => Key::Ticks(v.wrapping_add(1)),
}
}
}
enum Look {
Pidfs(u64),
Ticks,
Gone,
Unknown(UnknownCause),
}
fn look(kernel: &dyn Kernel, pid: RawPid) -> Look {
let Some(target) = prove::target(pid) else {
return Look::Gone;
};
match prove::open(kernel, target) {
Ok(opened) => look_at(kernel, opened.fd.as_fd()),
Err(Errno::SRCH | Errno::NOENT) => Look::Gone,
Err(Errno::INVAL) => match own_pidfs_ino(kernel) {
Ok(Some(_)) => Look::Gone,
Ok(None) => Look::Ticks,
Err(failed) => Look::Unknown(UnknownCause::of_call(failed)),
},
Err(e) => Look::Unknown(UnknownCause::of_call(FailedCall::pidfd_open(e))),
}
}
fn look_at(kernel: &dyn Kernel, fd: std::os::fd::BorrowedFd<'_>) -> Look {
match kernel.pidfs_ino(fd) {
Ok(Some(ino)) => Look::Pidfs(ino),
Ok(None) => Look::Ticks,
Err(e) => Look::Unknown(UnknownCause::of_call(FailedCall::pidfs_ino(e))),
}
}
pub(super) fn of(kernel: &dyn Kernel, pid: RawPid) -> (Resolved<Key>, UnknownCause) {
key_of(kernel, pid, look(kernel, pid))
}
pub(super) fn of_held(
kernel: &dyn Kernel,
pid: RawPid,
held: std::os::fd::BorrowedFd<'_>,
) -> (Resolved<Key>, UnknownCause) {
debug_assert!(
!held_names_another_pid(kernel, pid, held),
"`held` is a pidfd of another process than {pid}"
);
key_of(kernel, pid, look_at(kernel, held))
}
fn held_names_another_pid(kernel: &dyn Kernel, pid: RawPid, held: std::os::fd::BorrowedFd<'_>) -> bool {
let Ok(dir) = proc_view::proc_view_with(kernel).into_dir() else {
return false;
};
matches!(
proc_view::pidfd_pid_in(kernel, &dir, held),
Ok(proc_view::PidfdTarget::Pid(shown)) if shown != 0 && shown != pid
)
}
fn key_of(kernel: &dyn Kernel, pid: RawPid, look: Look) -> (Resolved<Key>, UnknownCause) {
match look {
Look::Pidfs(ino) => (Resolved::Found(Key::Pidfs(ino)), UnknownCause::default()),
Look::Gone => (Resolved::Gone, UnknownCause::default()),
Look::Unknown(cause) => (Resolved::Unknown, cause),
Look::Ticks => {
let (stat, cause) = read_stat_explained(kernel, pid);
(ticks_from(pid, stat).map(Key::Ticks), cause)
}
}
}
pub(super) fn of_stat(
kernel: &dyn Kernel,
pid: RawPid,
expected: Option<Key>,
) -> (Resolved<(Key, Vec<u8>)>, UnknownCause) {
match look(kernel, pid) {
Look::Pidfs(ino) if expected.is_some_and(|expected| expected != Key::Pidfs(ino)) => {
(Resolved::Gone, UnknownCause::default())
}
Look::Ticks if matches!(expected, Some(Key::Pidfs(_))) => (Resolved::Gone, UnknownCause::default()),
Look::Pidfs(ino) => {
let (stat, cause) = bracketed_stat(kernel, pid, ino);
(stat.map(|stat| (Key::Pidfs(ino), stat)), cause)
}
Look::Gone => (Resolved::Gone, UnknownCause::default()),
Look::Unknown(cause) => (Resolved::Unknown, cause),
Look::Ticks => {
let (stat, cause) = read_stat_explained(kernel, pid);
let bytes = match &stat {
Resolved::Found(bytes) => bytes.clone(),
_ => Vec::new(),
};
(ticks_from(pid, stat).map(|ticks| (Key::Ticks(ticks), bytes)), cause)
}
}
}
pub(super) fn ordered_read(kernel: &dyn Kernel, pid: RawPid, expected: Option<Key>, ask_parent: bool) -> OrderedRead {
let (read, cause) = of_stat(kernel, pid, expected);
let (key, stat) = match read {
Resolved::Found(found) => found,
Resolved::Gone => return OrderedRead::missing(Resolved::Gone, cause, ask_parent),
Resolved::Unknown => return OrderedRead::missing(Resolved::Unknown, cause, ask_parent),
};
let parent = if !ask_parent {
ParentRead::NotAsked
} else if let Some(ppid) = parse_ppid(&stat) {
ParentRead::Is(ppid)
} else {
log::debug!("identity: the stat of pid {pid} has no readable ppid");
ParentRead::Unreadable
};
OrderedRead {
read: Resolved::Found((key, None)),
parent,
cause,
}
.against(expected)
}
pub(super) fn exists(kernel: &dyn Kernel, pid: RawPid, key: Key) -> (Existence, UnknownCause) {
match key {
Key::Ticks(ticks) => {
let (stat, cause) = read_stat_explained(kernel, pid);
(existence_of_ticks(ticks_from(pid, stat), ticks), cause)
}
Key::Pidfs(ino) => match prove::prove(kernel, pid, ino) {
Proof::Holds { .. } => (Existence::Present, UnknownCause::default()),
Proof::Lost => (Existence::Gone, UnknownCause::default()),
Proof::Unknown(call) => (Existence::Unknown, UnknownCause::of_call(call)),
},
}
}
pub(super) fn exists_in(kernel: &dyn Kernel, proc_dir: &ProcDir, pid: RawPid, key: Key) -> Existence {
exists_in_explained(kernel, proc_dir, pid, key).0
}
pub(super) fn exists_in_explained(
kernel: &dyn Kernel,
proc_dir: &ProcDir,
pid: RawPid,
key: Key,
) -> (Existence, UnknownCause) {
match key {
Key::Ticks(ticks) => {
let (stat, cause) = read_in(kernel, proc_dir, pid);
(existence_of_ticks(ticks_from(pid, stat), ticks), cause)
}
Key::Pidfs(_) => exists(kernel, pid, key),
}
}
fn existence_of_ticks(read: Resolved<u64>, ticks: u64) -> Existence {
match read {
Resolved::Found(now) if now == ticks => Existence::Present,
Resolved::Found(_) | Resolved::Gone => Existence::Gone,
Resolved::Unknown => Existence::Unknown,
}
}
fn ticks_from(pid: RawPid, stat: Resolved<Vec<u8>>) -> Resolved<u64> {
match stat {
Resolved::Found(stat) => match parse_starttime_jiffies(&stat) {
Some(j) => Resolved::Found(j),
None => {
log::debug!("/proc/{pid}/stat has no parseable starttime");
Resolved::Unknown
}
},
Resolved::Gone => Resolved::Gone,
Resolved::Unknown => Resolved::Unknown,
}
}
fn bracketed_stat(kernel: &dyn Kernel, pid: RawPid, ino: u64) -> (Resolved<Vec<u8>>, UnknownCause) {
let (stat, cause) = read_stat_explained(kernel, pid);
let stat = match stat {
Resolved::Found(stat) => stat,
Resolved::Gone => return (Resolved::Gone, cause),
Resolved::Unknown => return (Resolved::Unknown, cause),
};
match prove::prove(kernel, pid, ino) {
Proof::Holds { .. } => (Resolved::Found(stat), UnknownCause::default()),
Proof::Lost => (Resolved::Gone, UnknownCause::default()),
Proof::Unknown(call) => (Resolved::Unknown, UnknownCause::of_call(call)),
}
}
fn start_ticks(kernel: &dyn Kernel, pid: RawPid, key: Key) -> (Resolved<u64>, UnknownCause) {
match key {
Key::Ticks(ticks) => (Resolved::Found(ticks), UnknownCause::default()),
Key::Pidfs(ino) => {
let (stat, cause) = bracketed_stat(kernel, pid, ino);
(ticks_from(pid, stat), cause)
}
}
}
pub(super) fn is_running(kernel: &dyn Kernel, pid: RawPid, key: Key) -> Liveness {
match key {
Key::Ticks(ticks) => liveness_of(read_stat(kernel, pid), ticks),
Key::Pidfs(ino) => match prove::prove(kernel, pid, ino) {
Proof::Holds { fd, .. } => match crate::os_process::poll::is_readable(fd.as_fd()) {
Ok(true) => Liveness::Dead,
Ok(false) => Liveness::Alive,
Err(e) => {
log::debug!(
"the pidfd of pid {pid} could not be polled: {report}",
report = crate::error::Report(&e)
);
Liveness::Unknown
}
},
Proof::Lost => Liveness::Dead,
Proof::Unknown(call) => {
log::debug!(
"the pidfd of pid {pid} could not be opened or proved ({name}): {report}",
name = call.name(),
report = crate::error::Report(&std::io::Error::from(call.errno()))
);
Liveness::Unknown
}
},
}
}
pub(super) fn is_running_in(kernel: &dyn Kernel, proc_dir: &ProcDir, pid: RawPid, key: Key) -> Liveness {
match key {
Key::Ticks(ticks) => liveness_of(read_in(kernel, proc_dir, pid).0, ticks),
Key::Pidfs(_) => is_running(kernel, pid, key),
}
}
fn liveness_of(stat: Resolved<Vec<u8>>, ticks: u64) -> Liveness {
match stat {
Resolved::Found(stat) => super::stat_parse::running_from_stat(&stat, ticks),
Resolved::Gone => Liveness::Dead,
Resolved::Unknown => Liveness::Unknown,
}
}
pub(super) fn current_key(kernel: &dyn Kernel) -> Result<Key, Error> {
match own_pidfs_ino(kernel) {
Ok(Some(ino)) => Ok(Key::Pidfs(ino)),
Ok(None) => {
let stat = std::fs::read("/proc/self/stat").map_err(Error::Io)?;
match ticks_from(std::process::id(), Resolved::Found(stat)) {
Resolved::Found(ticks) => Ok(Key::Ticks(ticks)),
_ => Err(Error::Io(std::io::Error::other(
"/proc/self/stat has no parseable starttime",
))),
}
}
Err(failed) => Err(crate::os_process::linux::open::open_error(failed)),
}
}
pub(crate) fn view_error(subject: &str, why: proc_view::ViewUnreadable) -> Error {
why.unsupported(format!("identifying {subject}"))
.unwrap_or_else(|| unassessable_view(subject, &why.reason, why.source))
}
pub(crate) fn call_error(subject: &str, call: FailedCall) -> Error {
call.unsupported(format!("identifying {subject}"))
.unwrap_or_else(|| Error::Unassessable {
detail: format!("{subject} identity could not be read: {}", call.name()),
source: Some(Error::io_cause(std::io::Error::from(call.errno()))),
})
}
pub(crate) fn unreadable_error(subject: &str, unreadable: pid_file::Unreadable) -> Error {
Error::Unassessable {
detail: format!("{subject} identity could not be read"),
source: Some(std::sync::Arc::new(unreadable.into_cause())),
}
}
fn unassessable_view(subject: &str, reason: &str, source: Option<std::io::Error>) -> Error {
Error::Unassessable {
detail: format!("{subject} identity could not be read: {reason}"),
source: source.map(Error::io_cause),
}
}
pub(super) fn created_at(kernel: &dyn Kernel, pid: RawPid, key: Key) -> Option<SystemTime> {
let jiffies = start_ticks(kernel, pid, key).0.found()?;
let hz = clock_ticks_per_sec()?;
let btime = boot_time_secs()?;
let secs = btime + jiffies / hz;
let nanos = ((jiffies % hz) * 1_000_000_000 / hz) as u32;
Some(SystemTime::UNIX_EPOCH + Duration::new(secs, nanos))
}
fn clock_ticks_per_sec() -> Option<u64> {
let hz = unsafe { libc::sysconf(libc::_SC_CLK_TCK) };
(hz > 0).then_some(hz as u64)
}
fn boot_time_secs() -> Option<u64> {
std::fs::read_to_string("/proc/stat")
.ok()?
.lines()
.find_map(|l| l.strip_prefix("btime "))
.and_then(|v| v.trim().parse::<u64>().ok())
}
use super::persist::{Scope, ScopeReadError};
const BOOT_ID_PATH: &str = "/proc/sys/kernel/random/boot_id";
const PID_NS_PATH: &str = "/proc/self/ns/pid";
pub(super) fn session_scope() -> Result<Scope, ScopeReadError> {
session_scope_at(
&kernel::HostKernel,
std::path::Path::new(BOOT_ID_PATH),
std::path::Path::new(PID_NS_PATH),
)
}
pub(super) fn session_scope_at(
kernel: &dyn Kernel,
boot_id_path: &std::path::Path,
pid_ns_path: &std::path::Path,
) -> Result<Scope, ScopeReadError> {
use std::os::unix::fs::MetadataExt;
let boot_id = std::fs::read_to_string(boot_id_path).map_err(|source| ScopeReadError {
path: boot_id_path.display().to_string(),
source,
})?;
let boot_id = boot_id.trim();
if boot_id.is_empty() {
return Err(ScopeReadError {
path: boot_id_path.display().to_string(),
source: std::io::Error::new(std::io::ErrorKind::InvalidData, "boot_id is empty"),
});
}
let pid_ns = std::fs::metadata(pid_ns_path)
.map_err(|source| ScopeReadError {
path: pid_ns_path.display().to_string(),
source,
})?
.ino();
let token_kind = own_token_kind(kernel).map_err(|failed| ScopeReadError {
path: format!("{} of this process", failed.name()),
source: std::io::Error::from(failed.errno()),
})?;
Ok(Scope {
boot_id: Some(boot_id.to_owned()),
pid_ns: Some(pid_ns),
token_kind: Some(token_kind),
})
}
fn own_pidfs_ino(kernel: &dyn Kernel) -> Result<Option<u64>, FailedCall> {
let pidfd = kernel
.pidfd_open(rustix::process::getpid(), PidfdFlags::empty())
.map_err(FailedCall::pidfd_open)?;
kernel.pidfs_ino(pidfd.as_fd()).map_err(FailedCall::pidfs_ino)
}
fn own_token_kind(kernel: &dyn Kernel) -> Result<TokenKind, FailedCall> {
Ok(match own_pidfs_ino(kernel)? {
Some(_) => TokenKind::Pidfs,
None => TokenKind::Ticks,
})
}