oxedyne/fe2o3/fe2o3_sys/src/notify/mounts.rs
9.7 KiB, 7 runs
created by r1870400018:76753, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | //! Mount tables and the host-path resolver. |
| 2 | //! |
| 3 | //! A file written inside a container or another mount namespace reaches a fanotify reader with a |
| 4 | //! descriptor whose link, read from the reader's `/proc/self/fd`, is a path in the writer's view. |
| 5 | //! [`resolve`] turns it into a path in the reader's own view, the host path. Where the descriptor's |
| 6 | //! mount (by `statx` `STATX_MNT_ID`) is one of the reader's, the link already is that path. Where it |
| 7 | //! is not, the mount must appear in the writer's `/proc/<pid>/mountinfo` (anything else, a pid |
| 8 | //! reused in another namespace for one, is unresolved, never guessed); the link is taken relative |
| 9 | //! to that mount's point, joined to the mount's root within its filesystem, and placed under the |
| 10 | //! reader's mount of the same superblock whose root holds it, the shortest such root first. |
| 11 | |
| 12 | use oxedyne_fe2o3_core::prelude::*; |
| 13 | |
| 14 | use std::{ |
| 15 | collections::BTreeMap, |
| 16 | fs, |
| 17 | os::fd::AsFd, |
| 18 | path::PathBuf, |
| 19 | }; |
| 20 | |
| 21 | /// One line of a mountinfo file. |
| 22 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 23 | pub struct Mount { |
| 24 | pub id: u64, |
| 25 | pub dev: String, // major:minor of the superblock. |
| 26 | pub root: String, // The mount's root within its filesystem. |
| 27 | pub point: String, // Where it is mounted, in the reading process's view. |
| 28 | pub fstype: String, |
| 29 | pub source: String, |
| 30 | pub rw: bool, // Writable both as mounted and as a superblock. |
| 31 | } |
| 32 | |
| 33 | /// What a mount's filesystem is, for a caller that must not hold a descriptor on a disk he may |
| 34 | /// pull, or a network or FUSE filesystem whose server may hang. |
| 35 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] |
| 36 | pub enum FsClass { |
| 37 | Local, // A fixed local disk, tmpfs, overlay, btrfs and the like. |
| 38 | Removable, // A block device whose disk sysfs marks `removable`. |
| 39 | Fuse, |
| 40 | Network, |
| 41 | Pseudo, // proc, sysfs, cgroup and the other kernel views: no files of anyone's. |
| 42 | } |
| 43 | |
| 44 | // fixed: kernel and mount(8) filesystem type names. |
| 45 | const PSEUDO: &[&str] = &["proc", "sysfs", "cgroup", "cgroup2", "devpts", "mqueue", "debugfs", "tracefs", |
| 46 | "securityfs", "pstore", "bpf", "configfs", "fusectl", "efivarfs", "binfmt_misc", "autofs", "hugetlbfs", |
| 47 | "nsfs", "rpc_pipefs", "selinuxfs", "ramfs"]; |
| 48 | const NETWORK: &[&str] = &["nfs", "nfs4", "cifs", "smb3", "smbfs", "9p", "ceph", "afs", "glusterfs", |
| 49 | "lustre", "ocfs2", "gfs2", "ncpfs", "coda", "virtiofs"]; |
| 50 | |
| 51 | impl Mount { |
| 52 | pub fn class(&self) -> FsClass { |
| 53 | let t = self.fstype.as_str(); |
| 54 | if t == "fuse" || t == "fuseblk" || t.starts_with("fuse.") { |
| 55 | return FsClass::Fuse; |
| 56 | } |
| 57 | if NETWORK.contains(&t) { |
| 58 | return FsClass::Network; |
| 59 | } |
| 60 | if PSEUDO.contains(&t) { |
| 61 | return FsClass::Pseudo; |
| 62 | } |
| 63 | // A partition's flag is its disk's, one directory up. |
| 64 | let dir = format!("/sys/dev/block/{}", self.dev); |
| 65 | let flag = |d: &str| fs::read_to_string(format!("{}/removable", d)).ok().map(|s| s.trim() == "1"); |
| 66 | match flag(&dir).or_else(|| flag(&format!("{}/..", dir))) { |
| 67 | Some(true) => FsClass::Removable, |
| 68 | _ => FsClass::Local, |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// The mounts one process sees, by mount id. |
| 74 | #[derive(Clone, Debug, Default, Eq, PartialEq)] |
| 75 | pub struct MountTable { |
| 76 | pub mounts: BTreeMap<u64, Mount>, |
| 77 | } |
| 78 | |
| 79 | impl MountTable { |
| 80 | /// Parses mountinfo text (proc(5)); a line that does not fit the format is an error. |
| 81 | pub fn parse(text: &str) -> Outcome<Self> { |
| 82 | let mut mounts = BTreeMap::new(); |
| 83 | for (n, line) in text.lines().enumerate() { |
| 84 | if line.is_empty() { continue; } |
| 85 | let f: Vec<&str> = line.split(' ').collect(); |
| 86 | let dash = match f.iter().position(|x| *x == "-") { |
| 87 | Some(d) if d >= 6 && f.len() >= d + 3 => d, |
| 88 | _ => return Err(err!("Mountinfo line {} is not in the proc(5) format: '{}'.", |
| 89 | n + 1, line; Invalid, Input)), |
| 90 | }; |
| 91 | let id = res!(f[0].parse::<u64>().map_err(|_| |
| 92 | err!("Mountinfo line {} has mount id '{}'.", n + 1, f[0]; Invalid, Input))); |
| 93 | mounts.insert(id, Mount { |
| 94 | id, |
| 95 | dev: f[2].to_string(), |
| 96 | root: unescape(f[3]), |
| 97 | point: unescape(f[4]), |
| 98 | fstype: f[dash + 1].to_string(), |
| 99 | source: unescape(f[dash + 2]), |
| 100 | rw: has_rw(f[5]) && f.get(dash + 3).map_or(true, |o| has_rw(o)), |
| 101 | }); |
| 102 | } |
| 103 | Ok(Self { mounts }) |
| 104 | } |
| 105 | |
| 106 | pub fn read(path: &str) -> Outcome<Self> { |
| 107 | let text = res!(fs::read_to_string(path).map_err(|e| |
| 108 | err!("Reading '{}': {}.", path, e; IO, File, Read))); |
| 109 | Self::parse(&text) |
| 110 | } |
| 111 | |
| 112 | pub fn of_self() -> Outcome<Self> { |
| 113 | Self::read("/proc/self/mountinfo") |
| 114 | } |
| 115 | |
| 116 | /// The mounts process `pid` sees, or `None` when it has gone or its table cannot be read. |
| 117 | pub fn of_pid(pid: i32) -> Option<Self> { |
| 118 | Self::read(&format!("/proc/{}/mountinfo", pid)).ok() |
| 119 | } |
| 120 | |
| 121 | pub fn get(&self, id: u64) -> Option<&Mount> { |
| 122 | self.mounts.get(&id) |
| 123 | } |
| 124 | |
| 125 | /// The mounts in `self` that `before` lacks. |
| 126 | pub fn added_since(&self, before: &MountTable) -> Vec<Mount> { |
| 127 | self.mounts.values().filter(|m| !before.mounts.contains_key(&m.id)).cloned().collect() |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | fn has_rw(opts: &str) -> bool { |
| 132 | opts.split(',').any(|o| o == "rw") |
| 133 | } |
| 134 | |
| 135 | /// Undoes the octal escapes mountinfo writes for space, tab, newline and backslash. |
| 136 | pub fn unescape(s: &str) -> String { |
| 137 | let b = s.as_bytes(); |
| 138 | let mut out = Vec::with_capacity(b.len()); |
| 139 | let mut i = 0; |
| 140 | while i < b.len() { |
| 141 | if b[i] == b'\\' && i + 3 < b.len() && b[i + 1..i + 4].iter().all(|c| (b'0'..=b'7').contains(c)) { |
| 142 | let v = (b[i + 1] - b'0') as u32 * 64 + (b[i + 2] - b'0') as u32 * 8 + (b[i + 3] - b'0') as u32; |
| 143 | if v <= 0xff { |
| 144 | out.push(v as u8); |
| 145 | i += 4; |
| 146 | continue; |
| 147 | } |
| 148 | } |
| 149 | out.push(b[i]); |
| 150 | i += 1; |
| 151 | } |
| 152 | String::from_utf8_lossy(&out).into_owned() |
| 153 | } |
| 154 | |
| 155 | /// The mount id of the file `fd` refers to, from `statx` `STATX_MNT_ID` (Linux 5.8). |
| 156 | pub fn mount_id<Fd: AsFd>(fd: Fd) -> Outcome<(u64, u64)> { |
| 157 | use rustix::fs::{AtFlags, StatxFlags}; |
| 158 | let x = res!(rustix::fs::statx(fd, "", AtFlags::EMPTY_PATH, StatxFlags::MNT_ID | StatxFlags::INO) |
| 159 | .map_err(|e| err!("statx for the mount id: {}.", e; IO, System))); |
| 160 | if x.stx_mask & StatxFlags::MNT_ID.bits() == 0 { |
| 161 | return Err(err!("The kernel did not report STATX_MNT_ID."; Missing, System)); |
| 162 | } |
| 163 | Ok((x.stx_mnt_id, x.stx_ino)) |
| 164 | } |
| 165 | |
| 166 | /// Where a written file is, in the reader's own view. |
| 167 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 168 | pub enum HostPath { |
| 169 | Own(PathBuf), // On one of the reader's mounts: the link is the path. |
| 170 | Mapped(PathBuf), // Through the writer's mountinfo onto a reader mount. |
| 171 | Unresolved(Unresolved), |
| 172 | } |
| 173 | |
| 174 | impl HostPath { |
| 175 | pub fn path(&self) -> Option<&PathBuf> { |
| 176 | match self { |
| 177 | Self::Own(p) | Self::Mapped(p) => Some(p), |
| 178 | Self::Unresolved(_) => None, |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | /// Why a written file has no host path. Every case is a loss the caller must make good, by a |
| 184 | /// rescan for one. |
| 185 | #[derive(Clone, Debug, Eq, PartialEq)] |
| 186 | pub enum Unresolved { |
| 187 | WriterGone, // Its mountinfo could not be read. |
| 188 | MountNotInWriter { mnt: u64 }, // N1: never map through a stranger's table. |
| 189 | NotUnderMount { link: String, point: String }, |
| 190 | NoHostMount { dev: String, fs_path: String }, |
| 191 | Deleted { link: String }, // Unlinked before it was read. |
| 192 | } |
| 193 | |
| 194 | // fixed: the suffix the kernel's d_path gives an unlinked file. |
| 195 | const DELETED: &str = " (deleted)"; |
| 196 | |
| 197 | /// Resolves `link`, a path read from `/proc/self/fd` for a descriptor on mount `mnt`, to a host |
| 198 | /// path, through `writer`'s mount table where the mount is not one of `own`. |
| 199 | pub fn resolve(link: &str, mnt: u64, own: &MountTable, writer: Option<&MountTable>) -> HostPath { |
| 200 | if link.ends_with(DELETED) { |
| 201 | return HostPath::Unresolved(Unresolved::Deleted { link: link.to_string() }); |
| 202 | } |
| 203 | if own.mounts.contains_key(&mnt) { |
| 204 | return HostPath::Own(PathBuf::from(link)); |
| 205 | } |
| 206 | let theirs = match writer { |
| 207 | Some(t) => t, |
| 208 | None => return HostPath::Unresolved(Unresolved::WriterGone), |
| 209 | }; |
| 210 | let m = match theirs.get(mnt) { |
| 211 | Some(m) => m, |
| 212 | None => return HostPath::Unresolved(Unresolved::MountNotInWriter { mnt }), |
| 213 | }; |
| 214 | let rel = match under(link, &m.point) { |
| 215 | Some(r) => r, |
| 216 | None => return HostPath::Unresolved(Unresolved::NotUnderMount { |
| 217 | link: link.to_string(), point: m.point.clone() }), |
| 218 | }; |
| 219 | let fs_path = join(&m.root, &rel); |
| 220 | let mut best: Option<(usize, String)> = None; |
| 221 | for h in own.mounts.values() { |
| 222 | if h.dev != m.dev { continue; } |
| 223 | if let Some(tail) = under(&fs_path, &h.root) { |
| 224 | if best.as_ref().map_or(true, |(l, _)| h.root.len() < *l) { |
| 225 | best = Some((h.root.len(), join(&h.point, &tail))); |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | match best { |
| 230 | Some((_, p)) => HostPath::Mapped(PathBuf::from(p)), |
| 231 | None => HostPath::Unresolved(Unresolved::NoHostMount { dev: m.dev.clone(), fs_path }), |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | /// `p` relative to `pre` as an absolute path ("/" for `pre` itself), or `None` when outside it. |
| 236 | fn under(p: &str, pre: &str) -> Option<String> { |
| 237 | if pre == "/" { return Some(p.to_string()); } |
| 238 | match p.strip_prefix(pre) { |
| 239 | Some("") => Some("/".to_string()), |
| 240 | Some(r) if r.starts_with('/') => Some(r.to_string()), |
| 241 | _ => None, |
| 242 | } |
| 243 | } |
| 244 | |
| 245 | fn join(a: &str, b: &str) -> String { |
| 246 | if b == "/" { a.to_string() } else if a == "/" { b.to_string() } else { format!("{}{}", a, b) } |
| 247 | } |