63 lines
2.0 KiB
Rust
63 lines
2.0 KiB
Rust
use std::path::PathBuf;
|
|
|
|
#[derive(Debug, Clone)]
|
|
pub struct Process {
|
|
pub pid: i32,
|
|
pub comm: String,
|
|
pub exec: Option<PathBuf>,
|
|
}
|
|
|
|
#[cfg(not(all(target_os = "linux", feature = "harden_process")))]
|
|
pub fn get_process(_port: u16) -> Option<Process> {
|
|
None
|
|
}
|
|
|
|
#[cfg(all(target_os = "linux", feature = "harden_process"))]
|
|
pub fn get_process(port: u16) -> Option<Process> {
|
|
let all_procs = match procfs::process::all_processes() {
|
|
Err(e) => {
|
|
rust_util::warning!("Get procfs all processes failed: {}", e);
|
|
return None;
|
|
}
|
|
Ok(all_procs) => all_procs,
|
|
};
|
|
let mut map = std::collections::HashMap::new();
|
|
for p in all_procs {
|
|
if let Ok(process) = p {
|
|
if let (Ok(stat), Ok(fds)) = (process.stat(), process.fd()) {
|
|
for fd in fds {
|
|
if let Ok(fd) = fd {
|
|
if let procfs::process::FDTarget::Socket(inode) = fd.target {
|
|
map.insert(inode, (stat.clone(), process.exe().ok()));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
let tcp = match procfs::net::tcp() {
|
|
Err(e) => {
|
|
rust_util::warning!("Get procfs net tcp failed: {}", e);
|
|
return None;
|
|
}
|
|
Ok(tcp) => tcp,
|
|
};
|
|
let local_ip = std::net::Ipv4Addr::LOCALHOST;
|
|
for entry in tcp.into_iter() {
|
|
if local_ip == entry.local_address.ip() && port == entry.local_address.port() {
|
|
if let Some((stat, exec)) = map.get(&entry.inode) {
|
|
return Some(Process {
|
|
pid: stat.pid,
|
|
comm: stat.comm.clone(),
|
|
exec: exec.clone(),
|
|
});
|
|
} else {
|
|
rust_util::warning!("Cannot get process by port: {}, inode: {}", port, entry.inode);
|
|
return None;
|
|
}
|
|
}
|
|
}
|
|
rust_util::warning!("Port not found: {}", port);
|
|
None
|
|
}
|