use std::collections::BTreeSet;
use std::io;
use netstat2::{AddressFamilyFlags, ProtocolFlags, ProtocolSocketInfo, TcpState, get_sockets_info};
use sysinfo::{Pid, ProcessesToUpdate, Signal, System};
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct PortScan {
pub pids: Vec<u32>,
pub sockets: usize,
}
impl PortScan {
#[must_use]
pub fn owner_is_hidden(&self) -> bool {
self.sockets > 0 && self.pids.is_empty()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Killed {
pub pid: u32,
pub name: String,
pub command: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum KillError {
Gone,
PermissionDenied,
Unsupported(String),
}
pub fn scan_port(port: u16) -> io::Result<PortScan> {
let sockets = get_sockets_info(
AddressFamilyFlags::IPV4 | AddressFamilyFlags::IPV6,
ProtocolFlags::TCP | ProtocolFlags::UDP,
)
.map_err(|error| io::Error::other(format!("failed to read the socket table: {error}")))?;
let mut pids = BTreeSet::new();
let mut bound = 0usize;
for socket in sockets {
let holds_port = match &socket.protocol_socket_info {
ProtocolSocketInfo::Tcp(tcp) => tcp.local_port == port && tcp.state == TcpState::Listen,
ProtocolSocketInfo::Udp(udp) => udp.local_port == port,
};
if !holds_port {
continue;
}
bound += 1;
pids.extend(socket.associated_pids);
}
Ok(PortScan {
pids: pids.into_iter().collect(),
sockets: bound,
})
}
pub fn kill(pid: u32) -> Result<Killed, KillError> {
let mut system = System::new().map_err(|error| {
KillError::Unsupported(format!("cannot read the process table: {error}"))
})?;
let pids = [Pid::from_u32(pid)];
system.refresh_processes(ProcessesToUpdate::Some(&pids), true);
let Some(process) = system.process(pids[0]) else {
return Err(KillError::Gone);
};
let killed = Killed {
pid,
name: process.name().to_string_lossy().into_owned(),
command: process
.cmd()
.iter()
.map(|arg| arg.to_string_lossy())
.collect::<Vec<_>>()
.join(" "),
};
if process.kill_with(Signal::Kill) == Some(true) {
return Ok(killed);
}
system.refresh_processes(ProcessesToUpdate::Some(&pids), true);
if system.process(pids[0]).is_some() {
Err(KillError::PermissionDenied)
} else {
Err(KillError::Gone)
}
}