forked from GuillemCastro/mountinfo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
333 lines (308 loc) · 12.4 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
use regex::Regex;
use std::fmt;
use std::fs::File;
use std::io::{self, BufRead};
use std::path::{Path, PathBuf};
/**
* The MIT License
* Copyright (c) 2022 Guillem Castro
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
use std::str::FromStr;
/// Some common filesystems types
/// The String representation must be the same when creating using `from_str`
/// and when converting to `String` using `fmt::Display`
#[derive(Debug, PartialEq)]
pub enum FsType {
/// procfs filesystem. Pseudo filesystem that exposes the kernel's process table.
/// Usually mounted at /proc.
Proc,
/// overlayfs filesystem. A filesystem that combines multiple lower filesystems into a single directory.
Overlay,
/// tmpfs filesystem. A filesystem that provides a temporary file system stored in volatile memory.
Tmpfs,
/// sysfs filesystem. A filesystem that provides access to the kernel's internal device tree.
Sysfs,
/// btrfs filesystem. A filesystem that provides a hierarchical data structure for storing data in a compressed fashion.
Btrfs,
/// ext2 filesystem. A filesystem that provides a file system that is optimized for storing data on a local disk.
Ext2,
/// ext3 filesystem. A filesystem that provides a file system that is optimized for storing data on a local disk.
Ext3,
/// ext4 filesystem. A filesystem that provides a file system that is optimized for storing data on a local disk.
Ext4,
/// devtmpfs filesystem.
Devtmpfs,
/// Other filesystems.
Other(String),
}
impl FromStr for FsType {
type Err = ();
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"proc" => Ok(FsType::Proc),
"tmpfs" => Ok(FsType::Tmpfs),
"overlay" => Ok(FsType::Overlay),
"sysfs" => Ok(FsType::Sysfs),
"btrfs" => Ok(FsType::Btrfs),
"ext2" => Ok(FsType::Ext2),
"ext3" => Ok(FsType::Ext3),
"ext4" => Ok(FsType::Ext4),
"devtmpfs" => Ok(FsType::Devtmpfs),
_ => Ok(FsType::Other(s.to_string())),
}
}
}
impl fmt::Display for FsType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let fsname = match self {
FsType::Proc => "proc",
FsType::Overlay => "overlay",
FsType::Tmpfs => "tmpfs",
FsType::Sysfs => "sysfs",
FsType::Btrfs => "btrfs",
FsType::Ext2 => "ext2",
FsType::Ext3 => "ext3",
FsType::Ext4 => "ext4",
FsType::Devtmpfs => "devtmpfs",
FsType::Other(ref fsname) => fsname,
};
write!(f, "{}", fsname)
}
}
/// A struct representing a mount point.
#[derive(Debug)]
pub struct MountPoint {
/// The id of the mount point. It is unique for each mount point,
/// but can be resused afer a call to the umount syscall.
pub id: Option<u32>,
/// The id of the parent mount.
pub parent_id: Option<u32>,
/// The path to the directory that acts as the root for this mount point.
pub root: Option<PathBuf>,
// Filesystem-specific information
pub what: String,
/// The mount point directory relative to the root.
pub path: PathBuf,
/// The filesystem type.
pub fstype: FsType,
/// Some additional mount options
pub options: MountOptions,
}
impl MountPoint {
/// Creates a new mount point from a line of the `/proc/self/mountinfo` file.
fn parse_proc_mountinfo_line(line: &String, regex: &Regex) -> Result<Self, io::Error> {
if !regex.is_match(line) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "Invalid format"));
}
let caps = regex.captures(line).unwrap();
Ok(MountPoint {
id: Some(caps[1].parse::<u32>().unwrap()),
parent_id: Some(caps[2].parse::<u32>().unwrap()),
root: Some(PathBuf::from(caps[4].to_string())),
path: PathBuf::from(caps[5].to_string()),
options: MountOptions::new(&caps[6].to_string()),
fstype: FsType::from_str(&caps[8]).unwrap(),
what: caps[9].to_string(),
})
}
}
#[derive(Debug, PartialEq)]
pub enum ReadWrite {
ReadOnly,
ReadWrite,
}
/// A struct representing the mount options.
#[derive(Debug)]
pub struct MountOptions {
/// If it was mounted as read-only or read-write.
pub read_write: ReadWrite,
/// Additional options, not currently parsed by this library.
pub others: Vec<String>,
}
impl MountOptions {
/// Creates a new mount options from a string.
/// The string must be a comma-separated list of options.
pub fn new(options: &str) -> Self {
let mut read_write = ReadWrite::ReadOnly;
let mut others = Vec::new();
for option in options.split(',') {
match option {
"ro" => read_write = ReadWrite::ReadOnly,
"rw" => read_write = ReadWrite::ReadWrite,
&_ => others.push(option.to_owned()),
}
}
MountOptions { read_write, others }
}
}
/// A struct containing the mount information.
/// Note that it will only contain the mount points visible for the calling process.
/// If the calling process is inside a chroot, not all mount points will be visible.
#[derive(Debug)]
pub struct MountInfo {
/// The list of mount points visible for the current process.
pub mounting_points: Vec<MountPoint>,
}
impl MountInfo {
/// The most "modern" file with mount information. Introduced in Linux 2.6.26.
/// According to the docs, this should be the most reliable (and up-to-date) way to get the mount information.
const MOUNT_INFO_FILE: &'static str = "/proc/self/mountinfo";
/// This file should exists even in ancient versions of the Linux kernel.
/// We use it as a fallback, if for some reason /proc/self/mountinfo is not available.
/// Believe it or not, there are still devices running ancient versions of the Linux kernel.
const MTAB_FILE: &'static str = "/etc/mtab";
/// Creates a new instance of the MountInfo struct.
/// It will read the contents of the /proc/self/mountinfo file, if it exists.
/// If it does not exist, it will fall-back to read the contents of the /etc/mtab file.
pub fn new() -> Result<Self, io::Error> {
if Path::new(MountInfo::MOUNT_INFO_FILE).exists() {
let mut mtab = File::open("/proc/self/mountinfo")?;
return Ok(MountInfo {
mounting_points: MountInfo::parse_proc_mountinfo(&mut mtab)?,
});
} else if Path::new(MountInfo::MTAB_FILE).exists() {
let mut mtab = File::open(MountInfo::MTAB_FILE)?;
return Ok(MountInfo {
mounting_points: MountInfo::parse_mtab(&mut mtab)?,
});
} else {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"No mountinfo file found",
));
}
}
/// Check if a certain filesystem type is mounted at the given path.
pub fn contains<P: AsRef<Path>>(&self, mounting_point: P, fstype: FsType) -> bool {
let path = mounting_point.as_ref();
let filtered: Vec<&MountPoint> = self
.mounting_points
.iter()
.filter(|mts| mts.path == path.to_owned() && mts.fstype == fstype)
.collect();
filtered.len() > 0
}
/// Check if the given path is a mount point.
pub fn is_mounted<P: AsRef<Path>>(&self, path: P) -> bool {
let filtered: Vec<&MountPoint> = self
.mounting_points
.iter()
.filter(|mts| mts.path == path.as_ref().to_path_buf())
.collect();
filtered.len() > 0
}
fn parse_proc_mountinfo(
file: &mut dyn std::io::Read,
) -> Result<Vec<MountPoint>, std::io::Error> {
let mut result = Vec::new();
let reader = io::BufReader::new(file);
// The line format is:
// <id> <parent_id> <major>:<minor> <root> <mount_point> <mount_options> <optional tags> "-" <fstype> <mount souce> <super options>
// Ref: https://www.kernel.org/doc/Documentation/filesystems/proc.txt - /proc/<pid>/mountinfo - Information about mounts
let regex = Regex::new(
r"(\d*)\s(\d*)\s(\d*:\d*)\s([\S]*)\s([\S]*)\s([A-Za-z0-9,]*)\s([A-Za-z0-9:\s]*)\- ([\S]*)\s([\S]*)(.*)",
).unwrap();
for line in reader.lines() {
let mpoint = MountPoint::parse_proc_mountinfo_line(&line?, ®ex)?;
result.push(mpoint);
}
Ok(result)
}
fn parse_mtab(file: &mut dyn std::io::Read) -> Result<Vec<MountPoint>, std::io::Error> {
let mut results: Vec<MountPoint> = vec![];
let reader = io::BufReader::new(file);
for line in reader.lines() {
let l = line?;
let parts: Vec<&str> = l.split_whitespace().collect();
if !parts.is_empty() {
results.push(MountPoint {
what: parts[0].to_string(),
path: PathBuf::from(parts[1]),
fstype: FsType::from_str(parts[2]).unwrap(),
options: MountOptions::new(parts[3]),
id: None,
parent_id: None,
root: None,
})
}
}
Ok(results)
}
}
// unit tests
#[cfg(test)]
mod test {
use super::*;
struct FakeFile {
s: String,
read: bool,
}
impl io::Read for FakeFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if self.read {
return Ok(0);
}
let mut i = 0;
while i < self.s.len() {
buf[i] = self.s.as_bytes()[i];
i += 1;
}
self.read = true;
Ok(buf.len())
}
}
#[test]
fn test_load_mount_points() {
let mut file = FakeFile { s: "tmpfs /tmp tmpfs rw,seclabel,nosuid,nodev,size=8026512k,nr_inodes=1048576,inode64 0 0".to_owned(), read: false };
let munt_points = MountInfo::parse_mtab(&mut file).unwrap();
assert_eq!(munt_points.len(), 1);
assert_eq!(munt_points[0].what, "tmpfs".to_owned());
assert_eq!(munt_points[0].path, PathBuf::from("/tmp"));
assert_eq!(munt_points[0].fstype, FsType::Tmpfs);
}
#[test]
fn test_contains() {
let mut file = FakeFile { s: "tmpfs /tmp tmpfs rw,seclabel,nosuid,nodev,size=8026512k,nr_inodes=1048576,inode64 0 0".to_owned(), read: false };
let mtab = MountInfo {
mounting_points: MountInfo::parse_mtab(&mut file).unwrap(),
};
assert_eq!(mtab.contains("/tmp", FsType::Tmpfs), true);
}
#[test]
fn test_is_mounted() {
let mut file = FakeFile { s: "tmpfs /tmp tmpfs rw,seclabel,nosuid,nodev,size=8026512k,nr_inodes=1048576,inode64 0 0".to_owned(), read: false };
let mtab = MountInfo {
mounting_points: MountInfo::parse_mtab(&mut file).unwrap(),
};
assert_eq!(mtab.is_mounted("/tmp"), true);
}
#[test]
fn test_mount_options() {
let options =
MountOptions::new("rw,seclabel,nosuid,nodev,size=8026512k,nr_inodes=1048576,inode64");
assert_eq!(options.read_write, ReadWrite::ReadWrite);
assert_ne!(options.others.len(), 0);
let more_options =
MountOptions::new("ro,seclabel,nosuid,nodev,size=8026512k,nr_inodes=1048576,inode64");
assert_eq!(more_options.read_write, ReadWrite::ReadOnly);
assert_ne!(more_options.others.len(), 0);
}
}