2023-09-18 20:13:29 -07:00
|
|
|
use std::path::{Path, PathBuf};
|
2023-05-06 12:01:56 -07:00
|
|
|
|
2024-07-03 06:47:25 -04:00
|
|
|
use sysinfo::{
|
|
|
|
System,
|
|
|
|
SystemExt,
|
|
|
|
Pid,
|
|
|
|
PidExt,
|
2024-11-25 11:22:27 -05:00
|
|
|
ProcessExt,
|
|
|
|
UserExt,
|
2024-07-03 06:47:25 -04:00
|
|
|
};
|
2022-12-19 16:20:46 -08:00
|
|
|
use serde::{Serialize, Deserialize};
|
2023-09-18 20:13:29 -07:00
|
|
|
|
|
|
|
use crate::errors::*;
|
|
|
|
|
2022-12-19 16:20:46 -08:00
|
|
|
|
2022-12-22 16:36:32 -08:00
|
|
|
#[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, Hash)]
|
2022-12-19 16:20:46 -08:00
|
|
|
pub struct Client {
|
|
|
|
pub pid: u32,
|
2023-09-18 20:13:29 -07:00
|
|
|
pub exe: Option<PathBuf>,
|
2024-11-25 11:22:27 -05:00
|
|
|
pub username: Option<String>,
|
2022-12-19 16:20:46 -08:00
|
|
|
}
|
2022-12-03 21:47:09 -08:00
|
|
|
|
|
|
|
|
2024-07-03 06:33:58 -04:00
|
|
|
pub fn get_client(pid: u32, parent: bool) -> Result<Client, ClientInfoError> {
|
2023-09-18 20:13:29 -07:00
|
|
|
let sys_pid = Pid::from_u32(pid);
|
2024-11-25 11:22:27 -05:00
|
|
|
let mut sys = System::new();
|
2023-09-18 20:13:29 -07:00
|
|
|
sys.refresh_process(sys_pid);
|
2024-11-25 11:22:27 -05:00
|
|
|
sys.refresh_users_list();
|
|
|
|
|
2024-07-03 06:33:58 -04:00
|
|
|
let mut proc = sys.process(sys_pid)
|
2023-09-18 20:13:29 -07:00
|
|
|
.ok_or(ClientInfoError::ProcessNotFound)?;
|
|
|
|
|
2024-07-03 06:33:58 -04:00
|
|
|
if parent {
|
|
|
|
let parent_pid_sys = proc.parent()
|
|
|
|
.ok_or(ClientInfoError::ParentPidNotFound)?;
|
|
|
|
sys.refresh_process(parent_pid_sys);
|
|
|
|
proc = sys.process(parent_pid_sys)
|
|
|
|
.ok_or(ClientInfoError::ParentProcessNotFound)?;
|
|
|
|
}
|
2023-09-18 20:13:29 -07:00
|
|
|
|
2024-11-25 11:22:27 -05:00
|
|
|
let username = proc.user_id()
|
|
|
|
.map(|uid| sys.get_user_by_id(uid))
|
|
|
|
.flatten()
|
|
|
|
.map(|u| u.name().to_owned());
|
|
|
|
|
2024-07-03 06:33:58 -04:00
|
|
|
let exe = match proc.exe() {
|
2023-09-18 20:13:29 -07:00
|
|
|
p if p == Path::new("") => None,
|
|
|
|
p => Some(PathBuf::from(p)),
|
|
|
|
};
|
|
|
|
|
2024-11-25 11:22:27 -05:00
|
|
|
Ok(Client { pid: proc.pid().as_u32(), exe, username })
|
2022-12-03 21:47:09 -08:00
|
|
|
}
|