use std::ffi::OsString;
use std::io;
use std::os::unix::fs::MetadataExt as _;
use std::path::{Path, PathBuf};
use super::instance::{PathVerdict, path_verdict};
use super::process::exe_name_at;
use super::{DaemonDescriptor, LifecycleError, StoppedSignal, lock_is_free};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProcessTable {
root: PathBuf,
}
impl ProcessTable {
pub fn system() -> Self {
Self::at("/proc")
}
pub fn at(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
pub fn root(&self) -> &Path {
&self.root
}
fn entry(&self, pid: u32, file: &str) -> PathBuf {
self.root.join(pid.to_string()).join(file)
}
}
impl Default for ProcessTable {
fn default() -> Self {
Self::system()
}
}
pub(crate) fn refuse_unserved_daemon(
desc: &DaemonDescriptor,
table: &ProcessTable,
) -> Result<(), LifecycleError> {
if let StoppedSignal::LockFree(lock) = &desc.stopped_signal
&& !lock_is_free(lock)?
{
return Err(LifecycleError::Unidentified {
socket: desc.socket.clone(),
lock: lock.clone(),
});
}
let pids = matching_processes(desc, &[], table)?;
if pids.is_empty() {
return Ok(());
}
Err(LifecycleError::RunningUnserved {
socket: desc.socket.clone(),
binary: desc.binary.clone(),
pids,
})
}
pub(crate) fn refuse_other_instances(
desc: &DaemonDescriptor,
serving: &[u32],
table: &ProcessTable,
) -> Result<(), LifecycleError> {
let others = matching_processes(desc, serving, table)?;
if others.is_empty() {
return Ok(());
}
Err(LifecycleError::RestartBlocked {
serving: serving.to_vec(),
binary: desc.binary.clone(),
others,
})
}
fn matching_processes(
desc: &DaemonDescriptor,
exclude: &[u32],
table: &ProcessTable,
) -> Result<Vec<u32>, LifecycleError> {
let me = std::process::id();
let euid = effective_uid();
let io_err = |context: &str, source| LifecycleError::Io {
context: context.to_string(),
source,
};
let mut found = Vec::new();
let root = table.root.display();
let entries = std::fs::read_dir(&table.root).map_err(|e| io_err(&format!("read {root}"), e))?;
for entry in entries {
let entry = entry.map_err(|e| io_err(&format!("read {root} entry"), e))?;
let Some(pid) = entry.file_name().to_str().and_then(|s| s.parse().ok()) else {
continue;
};
if pid != me
&& !exclude.contains(&pid)
&& process_instance(pid, euid, desc, table)? != Instance::Not
{
found.push(pid);
}
}
found.sort_unstable();
Ok(found)
}
pub(crate) fn effective_uid() -> u32 {
unsafe { libc::geteuid() }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Instance<'a> {
Not,
This,
Undecided(&'a str),
}
pub(crate) fn process_instance<'d>(
pid: u32,
euid: u32,
desc: &'d DaemonDescriptor,
table: &ProcessTable,
) -> Result<Instance<'d>, LifecycleError> {
let status_path = table.entry(pid, "status");
let status = match std::fs::read(&status_path) {
Ok(s) => s,
Err(e) if skippable(&e, table, pid, euid) => return Ok(Instance::Not),
Err(source) => {
return Err(LifecycleError::Io {
context: format!("read {}", status_path.display()),
source,
});
}
};
if !status_admits(&status, pid, euid)? {
return Ok(Instance::Not);
}
let cmdline = match std::fs::read(table.entry(pid, "cmdline")) {
Ok(c) => c,
Err(e) if vanished(&e) => return Ok(Instance::Not),
Err(source) => return Err(LifecycleError::IdentityUnreadable { pid, source }),
};
if !argv_matches(&cmdline, &desc.liveness_args) {
return Ok(Instance::Not);
}
let name = match exe_name_at(&table.entry(pid, "exe")) {
Ok(name) => name,
Err(e) if vanished(&e) => return Ok(Instance::Not),
Err(e) if e.kind() == io::ErrorKind::PermissionDenied => argv0_name(&cmdline),
Err(source) => return Err(LifecycleError::IdentityUnreadable { pid, source }),
};
if name != desc.binary {
return Ok(Instance::Not);
}
let path = match path_verdict(&cmdline, &desc.instance_path_args) {
PathVerdict::Other => return Ok(Instance::Not),
PathVerdict::Same => Instance::This,
PathVerdict::Undecided(flag) => Instance::Undecided(flag),
};
if desc.instance_env.is_empty() {
return Ok(path);
}
match std::fs::read(table.entry(pid, "environ")) {
Ok(environ) if environ_matches(&environ, &desc.instance_env) => Ok(path),
Ok(_) => Ok(Instance::Not),
Err(e) if vanished(&e) => Ok(Instance::Not),
Err(source) => Err(LifecycleError::InstanceUnreadable {
pid,
binary: desc.binary.clone(),
source,
}),
}
}
pub(crate) fn status_admits(status: &[u8], pid: u32, euid: u32) -> Result<bool, LifecycleError> {
let Some((state, uid)) = parse_status(status) else {
return Err(LifecycleError::Io {
context: format!("/proc/{pid}/status: unparsable"),
source: io::Error::new(io::ErrorKind::InvalidData, "no State: or Uid: field"),
});
};
Ok(uid == euid && !matches!(state, 'Z' | 'X'))
}
fn vanished(e: &io::Error) -> bool {
e.kind() == io::ErrorKind::NotFound || e.raw_os_error() == Some(libc::ESRCH)
}
pub(crate) fn skippable(e: &io::Error, table: &ProcessTable, pid: u32, euid: u32) -> bool {
if vanished(e) {
return true;
}
if e.kind() != io::ErrorKind::PermissionDenied {
return false;
}
match std::fs::metadata(table.root.join(pid.to_string())) {
Ok(meta) => meta.uid() != euid,
Err(stat) => vanished(&stat),
}
}
pub(crate) fn argv_matches(cmdline: &[u8], wanted: &[String]) -> bool {
let args: Vec<&[u8]> = cmdline.split(|b| *b == 0).skip(1).collect();
wanted.iter().all(|w| args.contains(&w.as_bytes()))
}
pub(crate) fn environ_matches(environ: &[u8], wanted: &[(String, Option<OsString>)]) -> bool {
wanted.iter().all(|(name, value)| {
let found = environ
.split(|b| *b == 0)
.find_map(|entry| entry.strip_prefix(name.as_bytes())?.strip_prefix(b"="));
found == value.as_ref().map(|v| v.as_encoded_bytes())
})
}
fn argv0_name(cmdline: &[u8]) -> String {
let argv0 = cmdline.split(|b| *b == 0).next().unwrap_or_default();
Path::new(&*String::from_utf8_lossy(argv0))
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default()
}
pub(crate) fn parse_status(status: &[u8]) -> Option<(char, u32)> {
let field = |key: &[u8]| {
let value = status
.split(|b| *b == b'\n')
.find_map(|l| l.strip_prefix(key))?;
std::str::from_utf8(value).ok().map(str::trim_start)
};
let state = field(b"State:")?.chars().next()?;
let euid = field(b"Uid:")?.split_whitespace().nth(1)?.parse().ok()?;
Some((state, euid))
}