1use std::{
4 fs,
5 mem::MaybeUninit,
6 os::fd::{AsFd, OwnedFd},
7 process::Command,
8};
9
10use anyhow::{Context, Result, anyhow};
11use bootc_utils::CommandRunExt;
12use camino::Utf8Path;
13use cap_std_ext::{cap_std::fs::Dir, cmdext::CapStdExtCommandExt};
14use fn_error_context::context;
15use rustix::{
16 mount::{MoveMountFlags, OpenTreeFlags},
17 net::{
18 AddressFamily, RecvFlags, SendAncillaryBuffer, SendAncillaryMessage, SendFlags,
19 SocketFlags, SocketType,
20 },
21 process::WaitOptions,
22 thread::Pid,
23};
24use serde::Deserialize;
25
26pub mod tempmount;
28
29pub const PID1: Pid = const {
31 match Pid::from_raw(1) {
32 Some(v) => v,
33 None => panic!("Expected to parse pid1"),
34 }
35};
36
37#[derive(Deserialize, Debug)]
39#[serde(rename_all = "kebab-case")]
40#[allow(dead_code)]
41pub struct Filesystem {
42 pub source: String,
45 pub target: String,
47 #[serde(rename = "maj:min")]
49 pub maj_min: String,
50 pub fstype: String,
52 pub options: String,
54 pub uuid: Option<String>,
56 pub children: Option<Vec<Filesystem>>,
58}
59
60#[derive(Deserialize, Debug, Default)]
62pub struct Findmnt {
63 pub filesystems: Vec<Filesystem>,
65}
66
67pub fn run_findmnt(args: &[&str], cwd: Option<&Dir>, path: Option<&str>) -> Result<Findmnt> {
69 let mut cmd = Command::new("findmnt");
70 if let Some(cwd) = cwd {
71 cmd.cwd_dir(cwd.try_clone()?);
72 }
73 cmd.args([
74 "-J",
75 "-v",
76 "--output=SOURCE,TARGET,MAJ:MIN,FSTYPE,OPTIONS,UUID",
78 ])
79 .args(args)
80 .args(path);
81 let o: Findmnt = cmd.log_debug().run_and_parse_json()?;
82 Ok(o)
83}
84
85fn findmnt_filesystem(args: &[&str], cwd: Option<&Dir>, path: &str) -> Result<Filesystem> {
87 let o = run_findmnt(args, cwd, Some(path))?;
88 o.filesystems
89 .into_iter()
90 .next()
91 .ok_or_else(|| anyhow!("findmnt returned no data for {path}"))
92}
93
94#[context("Inspecting filesystem {path}")]
95pub fn inspect_filesystem(path: &Utf8Path) -> Result<Filesystem> {
98 findmnt_filesystem(&["--mountpoint"], None, path.as_str())
99}
100
101#[context("Inspecting filesystem")]
102pub fn inspect_filesystem_of_dir(d: &Dir) -> Result<Filesystem> {
105 findmnt_filesystem(&["--mountpoint"], Some(d), ".")
106}
107
108#[context("Inspecting filesystem by UUID {uuid}")]
109pub fn inspect_filesystem_by_uuid(uuid: &str) -> Result<Filesystem> {
111 findmnt_filesystem(&["--source"], None, &(format!("UUID={uuid}")))
112}
113
114fn pid1_mounts() -> Result<Findmnt> {
116 run_findmnt(&["-N"], None, Some("1"))
117}
118
119pub fn is_mounted_in_pid1_mountns(path: &str) -> Result<bool> {
122 let o = pid1_mounts()?;
123
124 let mounted = o.filesystems.iter().any(|fs| is_source_mounted(path, fs));
125
126 Ok(mounted)
127}
128
129pub fn find_mount_target_by_source(dev: &str) -> Result<Option<camino::Utf8PathBuf>> {
143 let o = run_findmnt(&[], None, None)?;
144 let found = find_source_mount_target(dev, &o.filesystems);
145 if found.is_none() {
146 tracing::debug!(
147 "find_mount_target_by_source: no mount found for source {dev}; \
148 note that findmnt may report by-uuid or by-partuuid paths instead \
149 of the block device path in some environments"
150 );
151 }
152 Ok(found)
153}
154
155fn find_source_mount_target(dev: &str, mounts: &[Filesystem]) -> Option<camino::Utf8PathBuf> {
156 for m in mounts {
157 if m.source == dev {
158 return Some(camino::Utf8PathBuf::from(&m.target));
159 }
160 if let Some(children) = &m.children {
161 if let Some(t) = find_source_mount_target(dev, children) {
162 return Some(t);
163 }
164 }
165 }
166 None
167}
168
169pub fn is_source_mounted(path: &str, mounted_fs: &Filesystem) -> bool {
171 if mounted_fs.source.contains(path) {
172 return true;
173 }
174
175 if let Some(ref children) = mounted_fs.children {
176 for child in children {
177 if is_source_mounted(path, child) {
178 return true;
179 }
180 }
181 }
182
183 false
184}
185
186pub fn mount(dev: &str, target: &Utf8Path) -> Result<()> {
188 Command::new("mount")
189 .args([dev, target.as_str()])
190 .run_inherited_with_cmd_context()
191}
192
193pub fn mount_typed(dev: &str, fstype: &str, target: &Utf8Path) -> Result<()> {
201 Command::new("mount")
202 .args(["-t", fstype, dev, target.as_str()])
203 .run_inherited_with_cmd_context()
204}
205
206#[context("Comparing filesystems at {path} and /proc/1/root/{path}")]
211pub fn is_same_as_host(path: &Utf8Path) -> Result<bool> {
212 let path = Utf8Path::new("/").join(path);
214
215 let devstat = rustix::fs::statvfs(path.as_std_path())?;
218 let hostpath = Utf8Path::new("/proc/1/root").join(path.strip_prefix("/")?);
219 let hostdevstat = rustix::fs::statvfs(hostpath.as_std_path())?;
220 tracing::trace!(
221 "base mount id {:?}, host mount id {:?}",
222 devstat.f_fsid,
223 hostdevstat.f_fsid
224 );
225 Ok(devstat.f_fsid == hostdevstat.f_fsid)
226}
227
228#[allow(unsafe_code)]
231#[context("Opening mount tree from pid")]
232pub fn open_tree_from_pidns(
233 pid: rustix::process::Pid,
234 path: &Utf8Path,
235 recursive: bool,
236) -> Result<OwnedFd> {
237 let (sock_parent, sock_child) = rustix::net::socketpair(
239 AddressFamily::UNIX,
240 SocketType::STREAM,
241 SocketFlags::CLOEXEC,
242 None,
243 )
244 .context("socketpair")?;
245 const DUMMY_DATA: &[u8] = b"!";
246 match unsafe { libc::fork() } {
247 0 => {
248 drop(sock_parent);
252
253 let pidlink = fs::File::open(format!("/proc/{}/ns/mnt", pid.as_raw_nonzero()))?;
255 rustix::thread::move_into_link_name_space(
256 pidlink.as_fd(),
257 Some(rustix::thread::LinkNameSpaceType::Mount),
258 )
259 .context("setns")?;
260
261 let recursive = if recursive {
263 OpenTreeFlags::AT_RECURSIVE
264 } else {
265 OpenTreeFlags::empty()
266 };
267 let fd = rustix::mount::open_tree(
268 rustix::fs::CWD,
269 path.as_std_path(),
270 OpenTreeFlags::OPEN_TREE_CLOEXEC | OpenTreeFlags::OPEN_TREE_CLONE | recursive,
271 )
272 .context("open_tree")?;
273
274 let fd = fd.as_fd();
276 let fds = [fd];
277 let mut buffer = [MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
278 let mut control = SendAncillaryBuffer::new(&mut buffer);
279 let pushed = control.push(SendAncillaryMessage::ScmRights(&fds));
280 assert!(pushed);
281 let ios = std::io::IoSlice::new(DUMMY_DATA);
282 rustix::net::sendmsg(sock_child, &[ios], &mut control, SendFlags::empty())?;
283 std::process::exit(0)
285 }
286 -1 => {
287 let e = std::io::Error::last_os_error();
289 anyhow::bail!("failed to fork: {e}");
290 }
291 n => {
292 let pid = rustix::process::Pid::from_raw(n).unwrap();
294 drop(sock_child);
295 let mut cmsg_space = vec![MaybeUninit::uninit(); rustix::cmsg_space!(ScmRights(1))];
297 let mut cmsg_buffer = rustix::net::RecvAncillaryBuffer::new(&mut cmsg_space);
298 let mut buf = [0u8; DUMMY_DATA.len()];
299 let iov = std::io::IoSliceMut::new(buf.as_mut());
300 let mut iov = [iov];
301 let nread = rustix::net::recvmsg(
302 sock_parent,
303 &mut iov,
304 &mut cmsg_buffer,
305 RecvFlags::CMSG_CLOEXEC,
306 )
307 .context("recvmsg")?
308 .bytes;
309 anyhow::ensure!(nread == DUMMY_DATA.len());
310 assert_eq!(buf, DUMMY_DATA);
311 let r = cmsg_buffer
313 .drain()
314 .filter_map(|m| match m {
315 rustix::net::RecvAncillaryMessage::ScmRights(f) => Some(f),
316 _ => None,
317 })
318 .flatten()
319 .next()
320 .ok_or_else(|| anyhow::anyhow!("Did not receive a file descriptor"))?;
321 let st = rustix::process::waitpid(Some(pid), WaitOptions::empty())?
323 .expect("Wait status")
324 .1;
325 if let Some(0) = st.exit_status() {
326 Ok(r)
327 } else {
328 anyhow::bail!("forked helper failed: {st:?}");
329 }
330 }
331 }
332}
333
334pub fn bind_mount_from_pidns(
337 pid: Pid,
338 src: &Utf8Path,
339 target: &Utf8Path,
340 recursive: bool,
341) -> Result<()> {
342 let src = open_tree_from_pidns(pid, src, recursive)?;
343 rustix::mount::move_mount(
344 src.as_fd(),
345 "",
346 rustix::fs::CWD,
347 target.as_std_path(),
348 MoveMountFlags::MOVE_MOUNT_F_EMPTY_PATH,
349 )
350 .context("Moving mount")?;
351 Ok(())
352}
353
354pub fn ensure_mirrored_host_mount(path: impl AsRef<Utf8Path>) -> Result<()> {
357 let path = path.as_ref();
358 std::fs::create_dir_all(path)?;
361 if is_same_as_host(path)? {
362 tracing::debug!("Already mounted from host: {path}");
363 return Ok(());
364 }
365 tracing::debug!("Propagating host mount: {path}");
366 bind_mount_from_pidns(PID1, path, path, true)
367}
368
369#[cfg(test)]
370mod tests {
371 use super::*;
372 use camino::Utf8PathBuf;
373
374 fn mk_fs(source: &str, target: &str, children: Vec<Filesystem>) -> Filesystem {
375 Filesystem {
376 source: source.into(),
377 target: target.into(),
378 maj_min: "0:0".into(),
379 fstype: "ext4".into(),
380 options: "rw".into(),
381 uuid: None,
382 children: if children.is_empty() {
383 None
384 } else {
385 Some(children)
386 },
387 }
388 }
389
390 #[test]
391 fn find_source_mount_target_cases() {
392 let top_level = vec![
393 mk_fs("/dev/vda2", "/sysroot", vec![]),
394 mk_fs("/dev/vda1", "/boot", vec![]),
395 ];
396 let nested = vec![mk_fs(
399 "/dev/vda2",
400 "/sysroot",
401 vec![mk_fs("/dev/vda1", "/sysroot/boot", vec![])],
402 )];
403 let deep = vec![mk_fs(
408 "/dev/vda2",
409 "/sysroot",
410 vec![mk_fs(
411 "/dev/vda2",
412 "/var",
413 vec![mk_fs("/dev/mapper/var", "/var", vec![])],
414 )],
415 )];
416
417 let cases: &[(&str, &str, &[Filesystem], Option<&str>)] = &[
418 ("top-level match", "/dev/vda1", &top_level, Some("/boot")),
419 ("nested match", "/dev/vda1", &nested, Some("/sysroot/boot")),
420 ("not found", "/dev/vda1", &top_level[..1], None),
421 ("empty tree", "/dev/vda1", &[], None),
422 ("deep nesting", "/dev/mapper/var", &deep, Some("/var")),
423 ];
424
425 for (name, dev, tree, expected) in cases {
426 let got = find_source_mount_target(dev, tree);
427 let want = expected.map(Utf8PathBuf::from);
428 assert_eq!(got, want, "case: {name}");
429 }
430 }
431}