use std::ffi::OsString;
use std::io;
use std::os::unix::fs::MetadataExt as _;
use std::path::Path;
use super::process::exe_name;
use super::{DaemonDescriptor, LifecycleError, StoppedSignal, lock_is_free};
pub(crate) fn refuse_unserved_daemon(desc: &DaemonDescriptor) -> 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)?;
if pids.is_empty() {
return Ok(());
}
Err(LifecycleError::RunningUnserved {
socket: desc.socket.clone(),
binary: desc.binary.clone(),
pids,
})
}
fn matching_processes(desc: &DaemonDescriptor) -> Result<Vec<u32>, LifecycleError> {
let me = std::process::id();
let euid = unsafe { libc::geteuid() };
let io_err = |context: &str, source| LifecycleError::Io {
context: context.to_string(),
source,
};
let mut found = Vec::new();
for entry in std::fs::read_dir("/proc").map_err(|e| io_err("read /proc", e))? {
let entry = entry.map_err(|e| io_err("read /proc entry", e))?;
let Some(pid) = entry.file_name().to_str().and_then(|s| s.parse().ok()) else {
continue;
};
if pid != me && process_matches(pid, euid, desc)? {
found.push(pid);
}
}
found.sort_unstable();
Ok(found)
}
fn process_matches(pid: u32, euid: u32, desc: &DaemonDescriptor) -> Result<bool, LifecycleError> {
let status = match std::fs::read(format!("/proc/{pid}/status")) {
Ok(s) => s,
Err(e) if skippable(&e, pid, euid) => return Ok(false),
Err(source) => {
return Err(LifecycleError::Io {
context: format!("read /proc/{pid}/status"),
source,
});
}
};
if !status_admits(&status, pid, euid)? {
return Ok(false);
}
let cmdline = match std::fs::read(format!("/proc/{pid}/cmdline")) {
Ok(c) => c,
Err(e) if vanished(&e) => return Ok(false),
Err(source) => return Err(LifecycleError::IdentityUnreadable { pid, source }),
};
if !argv_matches(&cmdline, &desc.liveness_args) {
return Ok(false);
}
let name = match exe_name(pid) {
Ok(name) => name,
Err(e) if vanished(&e) => return Ok(false),
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(false);
}
if desc.instance_env.is_empty() {
return Ok(true);
}
match std::fs::read(format!("/proc/{pid}/environ")) {
Ok(environ) => Ok(environ_matches(&environ, &desc.instance_env)),
Err(e) if vanished(&e) => Ok(false),
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, pid: u32, euid: u32) -> bool {
if vanished(e) {
return true;
}
if e.kind() != io::ErrorKind::PermissionDenied {
return false;
}
match std::fs::metadata(format!("/proc/{pid}")) {
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))
}