| 1 | //! Implementation based on [heim's](https://github.com/heim-rs/heim) |
| 2 | //! Unix disk usage. |
| 3 | |
| 4 | use std::{ |
| 5 | ffi::CString, |
| 6 | fs::File, |
| 7 | io::{self, BufRead, BufReader}, |
| 8 | mem, |
| 9 | path::{Path, PathBuf}, |
| 10 | str::FromStr, |
| 11 | }; |
| 12 | |
| 13 | use anyhow::bail; |
| 14 | |
| 15 | use crate::collection::disks::unix::{FileSystem, Usage}; |
| 16 | |
| 17 | /// Representation of partition details. Based on [`heim`](https://github.com/heim-rs/heim/tree/master). |
| 18 | pub(crate) struct Partition { |
| 19 | device: Option<String>, |
| 20 | mount_point: PathBuf, |
| 21 | fs_type: FileSystem, |
| 22 | } |
| 23 | |
| 24 | impl Partition { |
| 25 | /// Returns the device name, if there is one. |
| 26 | #[inline] |
| 27 | pub fn device(&self) -> Option<&str> { |
| 28 | self.device.as_deref() |
| 29 | } |
| 30 | |
| 31 | /// Returns the mount point for this partition. |
| 32 | #[inline] |
| 33 | pub fn mount_point(&self) -> &Path { |
| 34 | self.mount_point.as_path() |
| 35 | } |
| 36 | |
| 37 | /// Returns the [`FileSystem`] of this partition. |
| 38 | #[inline] |
| 39 | pub fn fs_type(&self) -> &FileSystem { |
| 40 | &self.fs_type |
| 41 | } |
| 42 | |
| 43 | /// Returns the device name for the partition. |
| 44 | pub fn get_device_name(&self) -> String { |
| 45 | if let Some(device) = self.device() { |
| 46 | // See if this disk is actually mounted elsewhere on Linux. This is a workaround |
| 47 | // properly map I/O in some cases (i.e. disk encryption, https://github.com/ClementTsang/bottom/issues/419). |
| 48 | if let Ok(path) = std::fs::read_link(device) { |
| 49 | if path.is_absolute() { |
| 50 | path.into_os_string() |
| 51 | .into_string() |
| 52 | .unwrap_or_else(|_| "Name Unavailable".to_string()) |
| 53 | } else { |
| 54 | let mut combined_path = PathBuf::new(); |
| 55 | combined_path.push(device); |
| 56 | combined_path.pop(); // Pop the current file... |
| 57 | combined_path.push(path); |
| 58 | |
| 59 | if let Ok(canon_path) = std::fs::canonicalize(combined_path) { |
| 60 | // Resolve the local path into an absolute one... |
| 61 | canon_path |
| 62 | .into_os_string() |
| 63 | .into_string() |
| 64 | .unwrap_or_else(|_| "Name Unavailable".to_string()) |
| 65 | } else { |
| 66 | device.to_owned() |
| 67 | } |
| 68 | } |
| 69 | } else { |
| 70 | device.to_owned() |
| 71 | } |
| 72 | } else { |
| 73 | "Name Unavailable".to_string() |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | /// Returns the usage stats for this partition. |
| 78 | pub fn usage(&self) -> anyhow::Result<Usage> { |
| 79 | // TODO: This might be unoptimal. |
| 80 | let path = self |
| 81 | .mount_point |
| 82 | .to_str() |
| 83 | .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) |
| 84 | .and_then(|string| { |
| 85 | CString::new(string).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput)) |
| 86 | }) |
| 87 | .map_err(|e| anyhow::anyhow!("invalid path: {e:?}"))?; |
| 88 | |
| 89 | let mut vfs = mem::MaybeUninit::<libc::statvfs>::uninit(); |
| 90 | |
| 91 | // SAFETY: libc call, `path` is a valid C string and buf is a valid pointer to |
| 92 | // write to. |
| 93 | let result = unsafe { libc::statvfs(path.as_ptr(), vfs.as_mut_ptr()) }; |
| 94 | |
| 95 | if result == 0 { |
| 96 | // SAFETY: If result is 0, it succeeded, and vfs should be non-null. |
| 97 | let vfs = unsafe { vfs.assume_init() }; |
| 98 | Ok(Usage::new(vfs)) |
| 99 | } else { |
| 100 | Err(anyhow::anyhow!( |
| 101 | "statvfs had an issue getting info from {path:?}" |
| 102 | )) |
| 103 | } |
| 104 | } |
| 105 | } |
| 106 | |
| 107 | fn fix_mount_point(s: &str) -> String { |
| 108 | const ESCAPED_BACKSLASH: &str = "\\134"; |
| 109 | const ESCAPED_SPACE: &str = "\\040"; |
| 110 | const ESCAPED_TAB: &str = "\\011"; |
| 111 | const ESCAPED_NEWLINE: &str = "\\012"; |
| 112 | |
| 113 | s.replace(ESCAPED_BACKSLASH, "\\") |
| 114 | .replace(ESCAPED_SPACE, " ") |
| 115 | .replace(ESCAPED_TAB, "\t") |
| 116 | .replace(ESCAPED_NEWLINE, "\n") |
| 117 | } |
| 118 | |
| 119 | impl FromStr for Partition { |
| 120 | type Err = anyhow::Error; |
| 121 | |
| 122 | fn from_str(line: &str) -> anyhow::Result<Partition> { |
| 123 | // Example: `/dev/sda3 /home ext4 rw,relatime,data=ordered 0 0` |
| 124 | let mut parts = line.trim_start().splitn(5, ' '); |
| 125 | |
| 126 | let device = match parts.next() { |
| 127 | Some("none") => None, |
| 128 | Some(device) => Some(device.to_string()), |
| 129 | None => { |
| 130 | bail!("missing device"); |
| 131 | } |
| 132 | }; |
| 133 | |
| 134 | let mount_point = match parts.next() { |
| 135 | Some(mount_point) => PathBuf::from(fix_mount_point(mount_point)), |
| 136 | None => { |
| 137 | bail!("missing mount point"); |
| 138 | } |
| 139 | }; |
| 140 | let fs_type = match parts.next() { |
| 141 | Some(fs) => FileSystem::from_str(fs)?, |
| 142 | _ => { |
| 143 | bail!("missing filesystem type"); |
| 144 | } |
| 145 | }; |
| 146 | |
| 147 | Ok(Partition { |
| 148 | device, |
| 149 | mount_point, |
| 150 | fs_type, |
| 151 | }) |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | #[expect(dead_code)] |
| 156 | /// Returns a [`Vec`] containing all partitions. |
| 157 | pub(crate) fn partitions() -> anyhow::Result<Vec<Partition>> { |
| 158 | const PROC_MOUNTS: &str = "/proc/mounts"; |
| 159 | |
| 160 | let mut results = vec![]; |
| 161 | let mut reader = BufReader::new(File::open(PROC_MOUNTS)?); |
| 162 | let mut line = String::new(); |
| 163 | |
| 164 | // This saves us from doing a string allocation on each iteration compared to |
| 165 | // `lines()`. |
| 166 | while let Ok(bytes) = reader.read_line(&mut line) { |
| 167 | if bytes > 0 { |
| 168 | if let Ok(partition) = Partition::from_str(&line) { |
| 169 | results.push(partition); |
| 170 | } |
| 171 | |
| 172 | line.clear(); |
| 173 | } else { |
| 174 | break; |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | Ok(results) |
| 179 | } |
| 180 | |
| 181 | /// Returns a [`Vec`] containing all *physical* partitions. This is defined by |
| 182 | /// [`FileSystem::is_physical()`]. |
| 183 | pub(crate) fn physical_partitions() -> anyhow::Result<Vec<Partition>> { |
| 184 | const PROC_MOUNTS: &str = "/proc/mounts"; |
| 185 | |
| 186 | let mut results = vec![]; |
| 187 | let mut reader = BufReader::new(File::open(PROC_MOUNTS)?); |
| 188 | let mut line = String::new(); |
| 189 | |
| 190 | // This saves us from doing a string allocation on each iteration compared to |
| 191 | // `lines()`. |
| 192 | while let Ok(bytes) = reader.read_line(&mut line) { |
| 193 | if bytes > 0 { |
| 194 | if let Ok(partition) = Partition::from_str(&line) |
| 195 | && partition.fs_type().is_physical() |
| 196 | { |
| 197 | results.push(partition); |
| 198 | } |
| 199 | |
| 200 | line.clear(); |
| 201 | } else { |
| 202 | break; |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | Ok(results) |
| 207 | } |
| 208 | |
| 209 | #[cfg(test)] |
| 210 | mod tests { |
| 211 | use super::*; |
| 212 | |
| 213 | #[test] |
| 214 | fn test_fix_mount_point() { |
| 215 | let line = "/run/media/test/Samsung\\040980"; |
| 216 | |
| 217 | assert_eq!(fix_mount_point(line), "/run/media/test/Samsung 980"); |
| 218 | } |
| 219 | } |