use crate::host::{Listed, Process};
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
pub(super) fn processes(program: &str) -> Option<Vec<Process>> {
let me = std::fs::metadata("/proc/self").ok()?.uid();
let mut found: Vec<Process> = std::fs::read_dir("/proc")
.ok()?
.flatten()
.filter_map(|entry| {
let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
if entry.metadata().ok()?.uid() != me {
return None;
}
let name = std::fs::read_to_string(entry.path().join("comm")).ok()?;
(name.trim() == program).then(|| Process {
pid,
path: std::fs::read_link(entry.path().join("exe"))
.unwrap_or_else(|_| PathBuf::from(program)),
package: None,
})
})
.collect();
found.sort_unstable_by_key(|p| p.pid);
Some(found)
}
pub(super) fn listing() -> Result<Vec<Listed>, String> {
let me = std::fs::metadata("/proc/self")
.map_err(|e| format!("/proc could not be read ({e})"))?
.uid();
let entries =
std::fs::read_dir("/proc").map_err(|e| format!("/proc could not be read ({e})"))?;
let mut listed: Vec<Listed> = entries
.flatten()
.filter_map(|entry| {
let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
if entry.metadata().ok()?.uid() != me {
return None;
}
let stat = std::fs::read_to_string(entry.path().join("stat")).ok()?;
let parent = parent_in(&stat)?;
let (path, placed) = match std::fs::read_link(entry.path().join("exe")) {
Ok(path) => (path, true),
Err(_) => {
let name = std::fs::read_to_string(entry.path().join("comm")).ok()?;
(PathBuf::from(name.trim()), false)
}
};
Some(Listed {
pid,
parent,
path,
package: None,
placed,
})
})
.collect();
listed.sort_unstable_by_key(|one| one.pid);
Ok(listed)
}
fn parent_in(stat: &str) -> Option<u32> {
let (_, after) = stat.rsplit_once(')')?;
after.split_whitespace().nth(1)?.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn this_users_processes_can_be_read() {
assert_eq!(processes("definitely-not-a-program-name"), Some(Vec::new()));
let me = std::env::current_exe().expect("this test's own binary");
let name: String = me
.file_name()
.unwrap()
.to_string_lossy()
.chars()
.take(15)
.collect();
let found = processes(&name).expect("readable");
let mine = found
.iter()
.find(|p| p.pid == std::process::id())
.unwrap_or_else(|| panic!("{name} is running: {found:?}"));
assert_eq!(mine.path.file_name(), me.file_name());
}
#[test]
fn the_listing_holds_this_test_with_the_process_that_started_it() {
let listed = listing().expect("readable");
let mine = listed
.iter()
.find(|one| one.pid == std::process::id())
.expect("this test");
assert_eq!(mine.parent, std::os::unix::process::parent_id());
assert!(mine.placed);
assert_eq!(
mine.path.file_name(),
std::env::current_exe().unwrap().file_name()
);
assert_eq!(parent_in("42 (a (b) c) S 7 42 42"), Some(7));
}
#[test]
fn another_users_processes_are_not_listed() {
let uid = |pid: &str| std::fs::metadata(format!("/proc/{pid}")).map(|m| m.uid());
if uid("1").ok() == uid("self").ok() {
return;
}
let first = std::fs::read_to_string("/proc/1/comm")
.expect("the first process")
.trim()
.to_string();
let found = processes(&first).expect("readable");
assert!(found.iter().all(|p| p.pid != 1), "{first}: {found:?}");
}
}