1use std::io;
2use std::path::{Path, PathBuf};
3
4fn unescape(s: &str) -> String {
5 s.replace("\\040", " ")
6 .replace("\\011", "\t")
7 .replace("\\012", "\n")
8 .replace("\\134", "\\")
9}
10
11pub fn mount_points_under(mountinfo: &str, dir: &Path) -> Vec<PathBuf> {
12 let mut v: Vec<PathBuf> = mountinfo
13 .lines()
14 .filter_map(|l| l.split(' ').nth(4))
15 .map(|p| PathBuf::from(unescape(p)))
16 .filter(|p| p.starts_with(dir) && p != dir)
17 .collect();
18 v.sort_by_key(|p| std::cmp::Reverse(p.as_os_str().len()));
19 v.dedup();
20 v
21}
22
23#[cfg(target_os = "linux")]
24mod imp {
25 use std::ffi::CString;
26 use std::fs;
27 use std::io;
28 use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
29 use std::os::unix::ffi::OsStrExt;
30 use std::path::Path;
31
32 fn cstr(s: &[u8]) -> io::Result<CString> {
33 CString::new(s).map_err(|_| io::Error::other("path contains NUL"))
34 }
35
36 fn openat2(dir: &OwnedFd, name: &str, dir_only: bool) -> io::Result<OwnedFd> {
37 let c = cstr(name.as_bytes())?;
38 let mut flags = libc::O_PATH | libc::O_CLOEXEC;
39 if dir_only {
40 flags |= libc::O_DIRECTORY;
41 }
42 let mut how: libc::open_how = unsafe { std::mem::zeroed() };
43 how.flags = flags as u64;
44 how.resolve =
45 libc::RESOLVE_BENEATH | libc::RESOLVE_NO_SYMLINKS | libc::RESOLVE_NO_MAGICLINKS;
46 let fd = unsafe {
47 libc::syscall(
48 libc::SYS_openat2,
49 dir.as_raw_fd(),
50 c.as_ptr(),
51 &how as *const libc::open_how,
52 std::mem::size_of::<libc::open_how>(),
53 )
54 };
55 if fd < 0 {
56 return Err(io::Error::last_os_error());
57 }
58 Ok(unsafe { OwnedFd::from_raw_fd(fd as i32) })
59 }
60
61 fn fstat(fd: &OwnedFd) -> io::Result<libc::stat> {
62 let mut st: libc::stat = unsafe { std::mem::zeroed() };
63 if unsafe { libc::fstat(fd.as_raw_fd(), &mut st) } != 0 {
64 return Err(io::Error::last_os_error());
65 }
66 Ok(st)
67 }
68
69 pub fn open_beneath(base: &Path, sub: &str) -> io::Result<OwnedFd> {
70 let b = cstr(base.as_os_str().as_bytes())?;
71 let fd = unsafe {
72 libc::open(
73 b.as_ptr(),
74 libc::O_PATH | libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC,
75 )
76 };
77 if fd < 0 {
78 return Err(io::Error::last_os_error());
79 }
80 let mut cur = unsafe { OwnedFd::from_raw_fd(fd) };
81 let parts: Vec<&str> = sub.split('/').collect();
82 for (i, p) in parts.iter().enumerate() {
83 if p.is_empty() || *p == "." || *p == ".." {
84 return Err(io::Error::new(
85 io::ErrorKind::InvalidInput,
86 "bad subPath component",
87 ));
88 }
89 let last = i + 1 == parts.len();
90 let next = match openat2(&cur, p, !last) {
91 Err(e) if e.raw_os_error() == Some(libc::ENOENT) => {
92 let c = cstr(p.as_bytes())?;
93 if unsafe { libc::mkdirat(cur.as_raw_fd(), c.as_ptr(), 0o755) } != 0 {
94 let e = io::Error::last_os_error();
95 if e.raw_os_error() != Some(libc::EEXIST) {
96 return Err(e);
97 }
98 }
99 openat2(&cur, p, !last)?
100 }
101 r => r?,
102 };
103 if fstat(&next)?.st_mode & libc::S_IFMT == libc::S_IFLNK {
104 return Err(io::Error::new(
105 io::ErrorKind::InvalidInput,
106 "symlink in subPath",
107 ));
108 }
109 cur = next;
110 }
111 Ok(cur)
112 }
113
114 pub fn pin(base: &Path, sub: &str, target: &Path) -> io::Result<()> {
115 let fd = open_beneath(base, sub)?;
116 let is_dir = fstat(&fd)?.st_mode & libc::S_IFMT == libc::S_IFDIR;
117 if let Some(p) = target.parent() {
118 fs::create_dir_all(p)?;
119 }
120 let t = cstr(target.as_os_str().as_bytes())?;
121 unsafe {
122 libc::umount2(t.as_ptr(), libc::MNT_DETACH);
123 }
124 match fs::symlink_metadata(target) {
125 Ok(m) if m.is_dir() == is_dir && !m.file_type().is_symlink() => {}
126 Ok(_) => return Err(io::Error::other("subPath mount target has the wrong type")),
127 Err(_) if is_dir => fs::create_dir(target)?,
128 Err(_) => {
129 fs::OpenOptions::new()
130 .write(true)
131 .create_new(true)
132 .open(target)?;
133 }
134 }
135 let src = cstr(format!("/proc/self/fd/{}", fd.as_raw_fd()).as_bytes())?;
136 if unsafe {
137 libc::mount(
138 src.as_ptr(),
139 t.as_ptr(),
140 std::ptr::null(),
141 libc::MS_BIND,
142 std::ptr::null(),
143 )
144 } != 0
145 {
146 return Err(io::Error::last_os_error());
147 }
148 Ok(())
149 }
150
151 pub fn umount(target: &Path) -> io::Result<()> {
152 let t = cstr(target.as_os_str().as_bytes())?;
153 if unsafe { libc::umount2(t.as_ptr(), libc::MNT_DETACH) } != 0 {
154 return Err(io::Error::last_os_error());
155 }
156 Ok(())
157 }
158}
159
160#[cfg(target_os = "linux")]
161pub use imp::{open_beneath, pin};
162
163#[cfg(not(target_os = "linux"))]
164pub fn pin(_base: &Path, _sub: &str, _target: &Path) -> io::Result<()> {
165 Err(io::Error::new(
166 io::ErrorKind::Unsupported,
167 "subPath requires Linux",
168 ))
169}
170
171pub fn unpin_under(dir: &Path) -> io::Result<()> {
172 let info = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();
173 for p in mount_points_under(&info, dir) {
174 #[cfg(target_os = "linux")]
175 imp::umount(&p)?;
176 #[cfg(not(target_os = "linux"))]
177 let _ = p;
178 }
179 Ok(())
180}
181
182pub fn remove_dir_safely(dir: &Path) -> io::Result<()> {
183 unpin_under(dir)?;
184 let info = std::fs::read_to_string("/proc/self/mountinfo").unwrap_or_default();
185 if !mount_points_under(&info, dir).is_empty() {
186 return Err(io::Error::other(format!(
187 "{} still has mounts",
188 dir.display()
189 )));
190 }
191 match std::fs::remove_dir_all(dir) {
192 Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
193 _ => Ok(()),
194 }
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn finds_nested_mounts_deepest_first() {
203 let info = "22 1 0:21 / /r/u1 rw - ext4 /dev/sda rw\n\
204 23 22 0:21 /x /r/u1/subpaths/c/0 rw - ext4 /dev/sda rw\n\
205 24 22 0:21 /y /r/u1/subpaths/c/0/deep\\040er rw - ext4 /dev/sda rw\n\
206 25 1 0:21 /z /r/u10/subpaths/c/0 rw - ext4 /dev/sda rw\n";
207 assert_eq!(
208 mount_points_under(info, Path::new("/r/u1")),
209 [
210 PathBuf::from("/r/u1/subpaths/c/0/deep er"),
211 PathBuf::from("/r/u1/subpaths/c/0")
212 ]
213 );
214 }
215
216 #[cfg(target_os = "linux")]
217 #[test]
218 fn open_beneath_rejects_symlinks_and_creates_dirs() {
219 use std::os::fd::AsRawFd;
220 let d = std::env::temp_dir().join(format!("krab-subpath-{}", std::process::id()));
221 let _ = std::fs::remove_dir_all(&d);
222 std::fs::create_dir_all(d.join("vol/real")).unwrap();
223 std::fs::create_dir_all(d.join("outside")).unwrap();
224 std::os::unix::fs::symlink(d.join("outside"), d.join("vol/link")).unwrap();
225 std::os::unix::fs::symlink("../outside", d.join("vol/real/up")).unwrap();
226 let vol = d.join("vol");
227 for bad in ["link", "link/x", "real/up", "real/up/x", "..", "real/../.."] {
228 assert!(open_beneath(&vol, bad).is_err(), "{bad}");
229 }
230 assert!(!d.join("outside/x").exists());
231 let fd = open_beneath(&vol, "real/a/b").unwrap();
232 let got = std::fs::read_link(format!("/proc/self/fd/{}", fd.as_raw_fd())).unwrap();
233 assert_eq!(got, vol.join("real/a/b"));
234 if crate::native::sys::is_root() {
235 let t = d.join("pins/c/0");
236 pin(&vol, "real/a", &t).unwrap();
237 std::fs::write(d.join("vol/real/a/f"), b"x").unwrap();
238 assert_eq!(std::fs::read(t.join("f")).unwrap(), b"x");
239 remove_dir_safely(&d.join("pins")).unwrap();
240 assert!(d.join("vol/real/a/f").exists());
241 }
242 std::fs::remove_dir_all(&d).unwrap();
243 }
244}