use std::path::Path;
use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System, UpdateKind};
use super::{ProcInfo, ProcessTable, lineage, liveness};
use crate::engine::note::ProcessRef;
use crate::engine::rules::Liveness;
pub struct SystemTable {
system: System,
}
impl SystemTable {
pub fn snapshot() -> Self {
let mut system = System::new();
system.refresh_processes_specifics(
ProcessesToUpdate::All,
true,
ProcessRefreshKind::nothing(),
);
SystemTable { system }
}
pub fn lineage(&mut self, pid: u32) -> Vec<ProcInfo> {
let pids: Vec<Pid> = lineage(self, pid)
.iter()
.map(|process| Pid::from_u32(process.pid))
.collect();
self.system.refresh_processes_specifics(
ProcessesToUpdate::Some(&pids),
false,
ProcessRefreshKind::nothing()
.with_exe(UpdateKind::Always)
.with_cmd(UpdateKind::Always),
);
lineage(self, pid)
}
pub fn find(&mut self, wanted: impl Fn(&str) -> bool) -> Vec<ProcInfo> {
let pids: Vec<Pid> = self
.system
.processes()
.iter()
.filter(|(_, process)| wanted(&process.name().to_string_lossy()))
.map(|(&pid, _)| pid)
.collect();
self.system.refresh_processes_specifics(
ProcessesToUpdate::Some(&pids),
false,
ProcessRefreshKind::nothing()
.with_exe(UpdateKind::Always)
.with_cmd(UpdateKind::Always)
.with_cwd(UpdateKind::Always),
);
pids.iter()
.filter_map(|pid| self.get(pid.as_u32()))
.collect()
}
}
impl SystemTable {
pub fn details(&mut self, pids: &[u32]) -> Vec<ProcInfo> {
let ids: Vec<Pid> = pids.iter().map(|&pid| Pid::from_u32(pid)).collect();
self.system.refresh_processes_specifics(
ProcessesToUpdate::Some(&ids),
false,
ProcessRefreshKind::nothing()
.with_exe(UpdateKind::Always)
.with_cmd(UpdateKind::Always)
.with_cwd(UpdateKind::Always),
);
pids.iter().filter_map(|&pid| self.get(pid)).collect()
}
pub fn environment(&mut self, pid: u32) -> Vec<(String, String)> {
let id = Pid::from_u32(pid);
self.system.refresh_processes_specifics(
ProcessesToUpdate::Some(&[id]),
false,
ProcessRefreshKind::nothing().with_environ(UpdateKind::Always),
);
self.system
.process(id)
.map(|process| {
process
.environ()
.iter()
.filter_map(|pair| {
let pair = pair.to_string_lossy();
let (name, value) = pair.split_once('=')?;
(!name.is_empty()).then(|| (name.to_string(), value.to_string()))
})
.collect()
})
.unwrap_or_default()
}
pub fn end(&self, process: &ProcessRef) -> bool {
liveness(self, process) == Liveness::Running
&& self
.system
.process(Pid::from_u32(process.pid))
.is_some_and(sysinfo::Process::kill)
}
}
impl ProcessTable for SystemTable {
fn get(&self, pid: u32) -> Option<ProcInfo> {
let process = self.system.process(Pid::from_u32(pid))?;
let arguments: Vec<String> = process
.cmd()
.iter()
.map(|argument| argument.to_string_lossy().into_owned())
.collect();
let parent = process.parent().map(Pid::as_u32);
let (parent, started_ms) = match process.start_time() {
0 => not_inspected(pid).unwrap_or((parent, None)),
seconds => (parent, Some(seconds * 1000)),
};
Some(ProcInfo {
pid,
parent,
name: process.name().to_string_lossy().into_owned(),
exe: process.exe().map(Path::to_path_buf),
started_ms,
command_line: (!arguments.is_empty()).then(|| arguments.join(" ")),
arguments,
cwd: process.cwd().map(Path::to_path_buf),
})
}
}
#[cfg(target_os = "macos")]
fn not_inspected(pid: u32) -> Option<(Option<u32>, Option<u64>)> {
crate::os::process_basics(pid).map(|basics| (basics.parent, basics.started_ms))
}
#[cfg(not(target_os = "macos"))]
fn not_inspected(_pid: u32) -> Option<(Option<u32>, Option<u64>)> {
None
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_process_s_environment_and_folder_can_be_read() {
let mut table = SystemTable::snapshot();
let environment = table.environment(std::process::id());
assert!(environment.iter().any(|(name, _)| name == "CARGO_PKG_NAME"));
let me = table.details(&[std::process::id()]);
assert_eq!(me[0].cwd, Some(std::env::current_dir().unwrap()));
}
#[test]
fn finds_this_test_process() {
let me = SystemTable::snapshot().get(std::process::id()).unwrap();
assert!(me.started_ms.is_some());
assert!(me.parent.is_some());
}
#[test]
fn the_lineage_has_details() {
let chain = SystemTable::snapshot().lineage(std::process::id());
let me = chain.first().unwrap();
assert_eq!(me.pid, std::process::id());
assert!(me.exe.is_some());
assert!(me.command_line.is_some());
assert!(!me.arguments.is_empty());
}
#[cfg(target_os = "macos")]
#[test]
fn processes_of_other_users_have_a_parent_and_a_start_time() {
let table = SystemTable::snapshot();
assert!(table.get(1).unwrap().started_ms.is_some());
for (pid, process) in table.system.processes() {
let pid = pid.as_u32();
if pid > 1 && process.start_time() == 0 && crate::os::process_basics(pid).is_some() {
let found = table.get(pid).unwrap();
assert!(found.parent.is_some(), "{found:?}");
assert!(found.started_ms.is_some(), "{found:?}");
}
}
}
#[test]
fn found_processes_have_their_working_folder() {
let mut table = SystemTable::snapshot();
let me = table.get(std::process::id()).unwrap();
let found = table.find(|name| name == me.name);
let me = found
.iter()
.find(|process| process.pid == std::process::id())
.unwrap();
assert_eq!(me.cwd, Some(std::env::current_dir().unwrap()));
}
}