Skip to main content

agentmux_srv_core/backend/widget/
beneath.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Reading a package out of a container agent's workspace without ever following a link.
5//!
6//! The workspace is the agent's to change while it is read. Checking a path and then opening it leaves a
7//! gap in which a folder on the way is swapped for a link to somewhere else, so every step here is made
8//! relative to a folder already open (`openat` with `O_NOFOLLOW`): what is open is what was named, and
9//! a link anywhere on the way is an error rather than a detour.
10
11use std::ffi::{CString, OsStr, OsString};
12use std::io;
13use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
14use std::os::unix::ffi::{OsStrExt, OsStringExt};
15use std::path::{Component, Path};
16
17/// What a folder entry is, without following it.
18#[derive(Debug, PartialEq, Eq)]
19pub(crate) enum Kind {
20    File,
21    Dir,
22    Link,
23    Other,
24}
25
26fn cstring(bytes: &[u8]) -> io::Result<CString> {
27    CString::new(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a path with a NUL byte"))
28}
29
30fn owned(fd: RawFd) -> io::Result<OwnedFd> {
31    // SAFETY: `fd` is a descriptor `open`/`openat` just returned and nothing else owns.
32    if fd < 0 { Err(io::Error::last_os_error()) } else { Ok(unsafe { OwnedFd::from_raw_fd(fd) }) }
33}
34
35/// `name` in `dir`, opened with `flags`; a link in its place is an error.
36fn open_in(dir: &OwnedFd, name: &OsStr, flags: i32) -> io::Result<OwnedFd> {
37    let name = cstring(name.as_bytes())?;
38    // SAFETY: `name` is a NUL-terminated string that outlives the call.
39    owned(unsafe { libc::openat(dir.as_raw_fd(), name.as_ptr(), flags | libc::O_RDONLY | libc::O_NOFOLLOW | libc::O_CLOEXEC) })
40}
41
42/// The folder `path`, which lies under `root` (a canonical path), opened one component at a time.
43pub(crate) fn dir_beneath(root: &Path, path: &Path) -> io::Result<OwnedFd> {
44    let outside = || io::Error::new(io::ErrorKind::PermissionDenied, "outside the workspace");
45    let rel = path.strip_prefix(root).map_err(|_| outside())?;
46    let root = cstring(root.as_os_str().as_bytes())?;
47    // SAFETY: `root` is a NUL-terminated string that outlives the call.
48    let mut dir = owned(unsafe { libc::open(root.as_ptr(), libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC) })?;
49    for part in rel.components() {
50        match part {
51            Component::Normal(name) => dir = open_in(&dir, name, libc::O_DIRECTORY)?,
52            Component::CurDir => {}
53            _ => return Err(outside()),
54        }
55    }
56    Ok(dir)
57}
58
59/// The sub-folder `name` of `dir`.
60pub(crate) fn subdir(dir: &OwnedFd, name: &OsStr) -> io::Result<OwnedFd> {
61    open_in(dir, name, libc::O_DIRECTORY)
62}
63
64/// The regular file `name` of `dir`, ready to read.
65pub(crate) fn file_in(dir: &OwnedFd, name: &OsStr) -> io::Result<std::fs::File> {
66    // `O_NONBLOCK` so a pipe put in the file's place is refused below, not waited on.
67    let file = std::fs::File::from(open_in(dir, name, libc::O_NONBLOCK)?);
68    if file.metadata()?.is_file() { Ok(file) } else { Err(io::Error::new(io::ErrorKind::InvalidInput, "not a regular file")) }
69}
70
71/// The regular file `path`, which lies under `root`.
72pub(crate) fn file_beneath(root: &Path, path: &Path) -> io::Result<std::fs::File> {
73    let name = path.file_name().ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "no file name"))?;
74    file_in(&dir_beneath(root, path.parent().unwrap_or(root))?, name)
75}
76
77/// What is in `dir`, each entry's kind taken without following it.
78pub(crate) fn entries(dir: &OwnedFd) -> io::Result<Vec<(OsString, Kind)>> {
79    // SAFETY: `dup` returns a new descriptor that `fdopendir` then owns; on failure it is closed here.
80    let copy = unsafe { libc::dup(dir.as_raw_fd()) };
81    if copy < 0 {
82        return Err(io::Error::last_os_error());
83    }
84    let stream = unsafe { libc::fdopendir(copy) };
85    if stream.is_null() {
86        let e = io::Error::last_os_error();
87        unsafe { libc::close(copy) };
88        return Err(e);
89    }
90    // The duplicate shares the folder's read position; start from the top.
91    unsafe { libc::rewinddir(stream) };
92    let mut found = Vec::new();
93    loop {
94        let entry = unsafe { libc::readdir(stream) };
95        if entry.is_null() {
96            break;
97        }
98        // SAFETY: `d_name` of a returned entry is a NUL-terminated string valid until the next `readdir`.
99        let name = unsafe { std::ffi::CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes().to_vec();
100        if name == b"." || name == b".." {
101            continue;
102        }
103        let c = cstring(&name)?;
104        let mut st: libc::stat = unsafe { std::mem::zeroed() };
105        if unsafe { libc::fstatat(dir.as_raw_fd(), c.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) } != 0 {
106            let e = io::Error::last_os_error();
107            unsafe { libc::closedir(stream) };
108            return Err(e);
109        }
110        let kind = match st.st_mode & libc::S_IFMT {
111            libc::S_IFREG => Kind::File,
112            libc::S_IFDIR => Kind::Dir,
113            libc::S_IFLNK => Kind::Link,
114            _ => Kind::Other,
115        };
116        found.push((OsString::from_vec(name), kind));
117    }
118    unsafe { libc::closedir(stream) };
119    Ok(found)
120}