use crate::{
error::{Error, Result},
proc::process::proc_path,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FdTarget {
File(std::path::PathBuf),
Socket(u64),
Pipe(u64),
AnonInode(Box<str>),
MemFD(Box<str>),
Other(Box<str>),
}
impl FdTarget {
pub fn parse(target: &str) -> Self {
if let Some(inode) = target.strip_prefix("socket:[") {
if let Some(inode) = inode.strip_suffix(']') {
return FdTarget::Socket(inode.parse().unwrap_or(0));
}
}
if let Some(inode) = target.strip_prefix("pipe:[") {
if let Some(inode) = inode.strip_suffix(']') {
return FdTarget::Pipe(inode.parse().unwrap_or(0));
}
}
if let Some(kind) = target.strip_prefix("anon_inode:") {
return FdTarget::AnonInode(kind.to_string().into_boxed_str());
}
if let Some(name) = target.strip_prefix("/memfd:") {
return FdTarget::MemFD(name.to_string().into_boxed_str());
}
if target.starts_with('/') {
return FdTarget::File(std::path::PathBuf::from(target));
}
FdTarget::Other(target.to_string().into_boxed_str())
}
}
#[derive(Debug)]
pub struct Fd {
pub number: i32,
pub target: FdTarget,
}
pub fn read_fds(pid: u32) -> Result<Vec<Fd>> {
let mut buf = [0u8; 32];
let path = proc_path(&mut buf, pid, "/fd");
let entries = std::fs::read_dir(path).map_err(|e| {
if e.kind() == std::io::ErrorKind::PermissionDenied {
Error::PermissionDenied(std::path::PathBuf::from(path))
} else {
Error::Io {
path: Some(std::path::PathBuf::from(path)),
error: e,
}
}
})?;
let mut fds = Vec::new();
for entry in entries {
let entry = entry.map_err(|e| Error::Io {
path: Some(std::path::PathBuf::from(path)),
error: e,
})?;
let fd_num = entry.file_name().to_string_lossy().parse::<i32>().ok();
if let Some(num) = fd_num {
let target = std::fs::read_link(entry.path()).map_err(|e| Error::Io {
path: Some(entry.path().to_path_buf()),
error: e,
})?;
let target_str = target.to_string_lossy();
let fd_target = FdTarget::parse(&target_str);
fds.push(Fd {
number: num,
target: fd_target,
});
}
}
Ok(fds)
}