use std::io::{self, Read};
use std::os::fd::OwnedFd;
use rustix::fs::{openat2, FsWord, Mode, OFlags, ResolveFlags, CWD, PROC_SUPER_MAGIC};
use rustix::io::Errno;
use super::kernel::Kernel;
use super::refusal::{FailedCall, Refusal};
#[derive(Debug)]
pub(crate) enum ReadFailure {
Open(io::Error),
Read(io::Error),
}
impl ReadFailure {
pub(crate) fn into_io(self) -> io::Error {
match self {
ReadFailure::Open(e) | ReadFailure::Read(e) => e,
}
}
pub(crate) fn refusal(&self) -> Option<Refusal> {
match self {
ReadFailure::Open(e) => FailedCall::openat2(Errno::from_io_error(e)?).refusal(),
ReadFailure::Read(_) => None,
}
}
}
#[derive(Debug)]
pub(crate) enum OwnUnreadable {
Refused(Refusal),
Failed(io::Error),
}
impl OwnUnreadable {
fn of(failure: ReadFailure) -> Self {
match failure.refusal() {
Some(refusal) => OwnUnreadable::Refused(refusal),
None => OwnUnreadable::Failed(failure.into_io()),
}
}
pub(crate) fn opening(errno: Errno) -> Self {
Self::of(ReadFailure::Open(errno.into()))
}
}
pub(crate) fn read_own(kernel: &dyn Kernel, dir: &ProcDir, path: &str) -> Result<Vec<u8>, OwnUnreadable> {
debug_assert_own(path);
kernel.read(dir, path).map_err(OwnUnreadable::of)
}
pub(crate) fn read_own_link(kernel: &dyn Kernel, dir: &ProcDir, path: &str) -> Result<Option<Vec<u8>>, OwnUnreadable> {
debug_assert_own(path);
match kernel.read_link(dir, path) {
Ok(target) => Ok(Some(target)),
Err(ReadFailure::Open(e)) if e.raw_os_error() == Some(libc::ENOENT) => Ok(None),
Err(failure) => Err(OwnUnreadable::of(failure)),
}
}
fn debug_assert_own(path: &str) {
debug_assert!(
path.starts_with("self/") || path.starts_with("thread-self/"),
"{path:?} is not one of this process's own files"
);
}
#[derive(Debug)]
pub(crate) enum ProcOpenFailure {
Open(OwnUnreadable),
Check(io::Error),
NotProcfs {
f_type: FsWord,
},
NotRoot {
ino: u64,
},
}
impl ProcOpenFailure {
pub(crate) fn opening(errno: Errno) -> Self {
ProcOpenFailure::Open(OwnUnreadable::opening(errno))
}
}
#[derive(Debug)]
pub(crate) struct ProcDir(OwnedFd);
impl ProcDir {
pub(crate) fn open() -> Result<ProcDir, ProcOpenFailure> {
let fd = open_proc_root().map_err(ProcOpenFailure::opening)?;
let fs = rustix::fs::fstatfs(&fd).map_err(|e| ProcOpenFailure::Check(e.into()))?;
if fs.f_type != PROC_SUPER_MAGIC {
return Err(ProcOpenFailure::NotProcfs { f_type: fs.f_type });
}
let ino = rustix::fs::fstat(&fd)
.map_err(|e| ProcOpenFailure::Check(e.into()))?
.st_ino;
if ino != PROC_ROOT_INO {
return Err(ProcOpenFailure::NotRoot { ino });
}
Ok(ProcDir(fd))
}
fn open_beneath(&self, path: &str, oflags: OFlags) -> io::Result<OwnedFd> {
openat2(
&self.0,
path,
oflags | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::BENEATH | ResolveFlags::NO_XDEV | ResolveFlags::NO_MAGICLINKS,
)
.map_err(io::Error::from)
}
pub(crate) fn open_own_fd_dir(&self) -> rustix::io::Result<OwnedFd> {
openat2(
&self.0,
c"self/fd",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::BENEATH | ResolveFlags::NO_XDEV | ResolveFlags::NO_MAGICLINKS,
)
}
pub(crate) fn read(&self, path: &str) -> Result<Vec<u8>, ReadFailure> {
let file = self.open_beneath(path, OFlags::RDONLY).map_err(ReadFailure::Open)?;
let mut bytes = Vec::new();
std::fs::File::from(file)
.read_to_end(&mut bytes)
.map_err(ReadFailure::Read)?;
Ok(bytes)
}
pub(super) fn read_link(&self, path: &str) -> Result<Vec<u8>, ReadFailure> {
let link = self
.open_beneath(path, OFlags::PATH | OFlags::NOFOLLOW)
.map_err(ReadFailure::Open)?;
let target = rustix::fs::readlinkat(&link, "", Vec::new()).map_err(|e| ReadFailure::Read(e.into()))?;
Ok(target.into_bytes())
}
pub(super) fn pids(&self) -> Result<Vec<u32>, ReadFailure> {
self.numeric_entries(".")
}
pub(super) fn tids(&self, pid: u32) -> Result<Vec<u32>, ReadFailure> {
self.numeric_entries(&format!("{pid}/task"))
}
fn numeric_entries(&self, path: &str) -> Result<Vec<u32>, ReadFailure> {
let fd = self
.open_beneath(path, OFlags::RDONLY | OFlags::DIRECTORY)
.map_err(ReadFailure::Open)?;
let dir = rustix::fs::Dir::new(fd).map_err(|e| ReadFailure::Read(e.into()))?;
collect_pids(dir.map(|entry| Ok(entry?.file_name().to_bytes().to_vec()))).map_err(ReadFailure::Read)
}
}
const PROC_ROOT_INO: u64 = 1;
fn open_proc_root() -> Result<OwnedFd, Errno> {
openat2(
CWD,
"/proc",
OFlags::DIRECTORY | OFlags::RDONLY | OFlags::CLOEXEC,
Mode::empty(),
ResolveFlags::NO_MAGICLINKS,
)
}
pub(crate) fn utf8(bytes: Vec<u8>) -> io::Result<String> {
String::from_utf8(bytes).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))
}
fn collect_pids(names: impl IntoIterator<Item = io::Result<Vec<u8>>>) -> io::Result<Vec<u32>> {
const PID_MAX_LIMIT: u32 = 1 << 22;
let mut pids = Vec::new();
for name in names {
let name = name?;
if name.is_empty() || !name.iter().all(u8::is_ascii_digit) {
continue;
}
let text = String::from_utf8_lossy(&name);
let pid = text.parse::<u32>().map_err(|e| {
crate::error::io_context(
format!("the /proc entry {text:?} is all digits but not a pid"),
io::Error::new(io::ErrorKind::InvalidData, e),
)
})?;
debug_assert!(
pid <= PID_MAX_LIMIT,
"/proc lists pid {pid} beyond the kernel's PID_MAX_LIMIT"
);
pids.push(pid);
}
Ok(pids)
}
#[cfg(test)]
#[path = "proc_read_tests.rs"]
mod proc_read_tests;