use std::ffi::OsStr;
use crate::error::{Error, Result};
#[derive(Debug)]
pub struct Namespaces {
pub cgroup: Option<u64>,
pub ipc: Option<u64>,
pub mnt: Option<u64>,
pub net: Option<u64>,
pub pid: Option<u64>,
pub time: Option<u64>,
pub time_for_children: Option<u64>,
pub user: Option<u64>,
pub uts: Option<u64>,
}
impl Namespaces {
pub fn from_dir(path: &OsStr) -> Result<Self> {
let mut cgroup = None;
let mut ipc = None;
let mut mnt = None;
let mut net = None;
let mut pid = None;
let mut time = None;
let mut time_for_children = None;
let mut user = None;
let mut uts = None;
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,
}
}
})?;
for entry in entries {
let entry = entry.map_err(|e| Error::Io {
path: Some(std::path::PathBuf::from(path)),
error: e,
})?;
let name = entry.file_name();
let name_str = name.to_string_lossy();
let target = std::fs::read_link(entry.path()).map_err(|e| Error::Io {
path: Some(entry.path()),
error: e,
})?;
let target_str = target.to_string_lossy();
if let Some(inode) = parse_ns_inode(&target_str) {
match name_str.as_ref() {
"cgroup" => cgroup = Some(inode),
"ipc" => ipc = Some(inode),
"mnt" => mnt = Some(inode),
"net" => net = Some(inode),
"pid" => pid = Some(inode),
"time" => time = Some(inode),
"time_for_children" => time_for_children = Some(inode),
"user" => user = Some(inode),
"uts" => uts = Some(inode),
_ => {}
}
}
}
Ok(Namespaces {
cgroup,
ipc,
mnt,
net,
pid,
time,
time_for_children,
user,
uts,
})
}
}
fn parse_ns_inode(target: &str) -> Option<u64> {
let start = target.find('[')?;
let s = target[start + 1..].strip_suffix(']')?;
s.parse::<u64>().ok()
}