use std::io;
use std::path::{Path, PathBuf};
fn unescape(s: &str) -> String {
s.replace("\\040", " ")
.replace("\\011", "\t")
.replace("\\012", "\n")
.replace("\\134", "\\")
}
pub fn mount_points_under(mountinfo: &str, dir: &Path) -> Vec<PathBuf> {
let mut v: Vec<PathBuf> = mountinfo
.lines()
.filter_map(|l| l.split(' ').nth(4))
.map(|p| PathBuf::from(unescape(p)))
.filter(|p| p.starts_with(dir) && p != dir)
.collect();
v.sort_by_key(|p| std::cmp::Reverse(p.as_os_str().len()));
v.dedup();
v
}
#[cfg(target_os = "linux")]
mod imp {
use std::ffi::CString;
use std::fs;
use std::io;
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::os::unix::ffi::OsStrExt;
use std::path::Path;
fn cstr(s: &[u8]) -> io::Result<CString> {
CString::new(s).map_err(|_| io::Error::other("path contains NUL"))
}
fn openat2(dir: &OwnedFd, name: &str, dir_only: bool) -> io::Result<OwnedFd> {
let c = cstr(name.as_bytes())?;
let mut flags = libc::O_PATH | libc::O_CLOEXEC;
if dir_only {
flags |= libc::O_DIRECTORY;
}
let mut how: libc::open_how = unsafe { std::mem::zeroed() };
how.flags = flags as u64;
how.resolve =
libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS;
let fd = unsafe {
libc::syscall(
libc::SYS_openat2,
dir.as_raw_fd(),
c.as_ptr(),
&how as *const libc::open_how,
std::mem::size_of::<libc::open_how>(),
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) })
}
fn fstat(fd: &OwnedFd) -> io::Result<libc::stat> {
let mut st: libc::stat = unsafe { std::mem::zeroed() };
if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(st)
}
pub fn open_beneath(base: &Path, sub: &str) -> io::Result<OwnedFd> {
let b = cstr(base.as_os_str().as_bytes())?;
let fd = unsafe {
libc::open(
b.as_ptr(),
libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
)
};
if fd < 0 {
return Err(io::Error::last_os_error());
}
let mut cur = unsafe { OwnedFd::from_raw_fd(fd) };
let parts: Vec<&str> = sub.split('/').collect();
for (i, p) in parts.iter().enumerate() {
if p.is_empty() || *p == "." || *p == ".." {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"bad subPath component",
));
}
let last = i + 1 == parts.len();
let next = match openat2(&cur, p, !last) {
Err(e) if e.raw_os_error() == Some(libc::ENOENT) => {
let c = cstr(p.as_bytes())?;
if unsafe { libc::mkdirat(cur.as_raw_fd(), c.as_ptr(), 0o755) } != 0 {
let e = io::Error::last_os_error();
if e.raw_os_error() != Some(libc::EEXIST) {
return Err(e);
}
}
openat2(&cur, p, !last)?
}
r => r?,
};
if fstat(&next)?.st_mode & libc::S_IFMT == libc::S_IFLNK {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
"symlink in subPath",
));
}
cur = next;
}
Ok(cur)
}
pub fn pin(base: &Path, sub: &str, target: &Path) -> io::Result<()> {
let fd = open_beneath(base, sub)?;
let is_dir = fstat(&fd)?.st_mode & libc::S_IFMT == libc::S_IFDIR;
if let Some(p) = target.parent() {
fs::create_dir_all(p)?;
}
let t = cstr(target.as_os_str().as_bytes())?;
unsafe {
libc::umount2(t.as_ptr(), libc::MNT_DETACH);
}
match fs::symlink_metadata(target) {
Ok(m) if m.is_dir() == is_dir && !m.file_type().is_symlink() => {}
Ok(_) => return Err(io::Error::other("subPath mount target has the wrong type")),
Err(_) if is_dir => fs::create_dir(target)?,
Err(_) => {
fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(target)?;
}
}
let src = cstr(format!("/proc/self/fd/{}", fd.as_raw_fd()).as_bytes())?;
if unsafe {
libc::mount(
src.as_ptr(),
t.as_ptr(),
std::ptr::null(),
libc::MS_BIND,
std::ptr::null(),
)
} != 0
{
return Err(io::Error::last_os_error());
}
Ok(())
}
pub fn umount(target: &Path) -> io::Result<()> {
let t = cstr(target.as_os_str().as_bytes())?;
if unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}
}
#[cfg(target_os = "linux")]
pub use imp::{open_beneath, pin};
#[cfg(not(target_os = "linux"))]
pub fn pin(_base: &Path, _sub: &str, _target: &Path) -> io::Result<()> {
Err(io::Error::new(
io::ErrorKind::Unsupported,
"subPath requires Linux",
))
}
pub fn unpin_under(dir: &Path) -> io::Result<()> {
let info = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();
for p in mount_points_under(&info, dir) {
#[cfg(target_os = "linux")]
imp::umount(&p)?;
#[cfg(not(target_os = "linux"))]
let _ = p;
}
Ok(())
}
pub fn remove_dir_safely(dir: &Path) -> io::Result<()> {
unpin_under(dir)?;
let info = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();
if !mount_points_under(&info, dir).is_empty() {
return Err(io::Error::other(format!(
"{} still has mounts",
dir.display()
)));
}
match std::fs::remove_dir_all(dir) {
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
_ => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_nested_mounts_deepest_first() {
let info = "22 1 0:21 / /r/u1 rw - ext4 /dev/sda rw\n\
23 22 0:21 /x /r/u1/subpaths/c/0 rw - ext4 /dev/sda rw\n\
24 22 0:21 /y /r/u1/subpaths/c/0/deep\\040er rw - ext4 /dev/sda rw\n\
25 1 0:21 /z /r/u10/subpaths/c/0 rw - ext4 /dev/sda rw\n";
assert_eq!(
mount_points_under(info, Path::new("/r/u1")),
[
PathBuf::from("/r/u1/subpaths/c/0/deep er"),
PathBuf::from("/r/u1/subpaths/c/0")
]
);
}
#[cfg(target_os = "linux")]
#[test]
fn open_beneath_rejects_symlinks_and_creates_dirs() {
use std::os::fd::AsRawFd;
let d = std::env::temp_dir().join(format!("krab-subpath-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(d.join("vol/real")).unwrap();
std::fs::create_dir_all(d.join("outside")).unwrap();
std::os::unix::fs::symlink(d.join("outside"), d.join("vol/link")).unwrap();
std::os::unix::fs::symlink("../outside", d.join("vol/real/up")).unwrap();
let vol = d.join("vol");
for bad in ["link", "link/x", "real/up", "real/up/x", "..", "real/../.."] {
assert!(open_beneath(&vol, bad).is_err(), "{bad}");
}
assert!(!d.join("outside/x").exists());
let fd = open_beneath(&vol, "real/a/b").unwrap();
let got = std::fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap();
assert_eq!(got, vol.join("real/a/b"));
if crate::native::sys::is_root() {
let t = d.join("pins/c/0");
pin(&vol, "real/a", &t).unwrap();
std::fs::write(d.join("vol/real/a/f"), b"x").unwrap();
assert_eq!(std::fs::read(t.join("f")).unwrap(), b"x");
remove_dir_safely(&d.join("pins")).unwrap();
assert!(d.join("vol/real/a/f").exists());
}
std::fs::remove_dir_all(&d).unwrap();
}
}