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
extern crate libc;
#[macro_use]
extern crate bitflags;
#[macro_use]
extern crate thiserror;
mod builder;
mod flags;
mod fstype;
mod mount;
mod supported;
mod umount;
pub use self::{builder::*, flags::*, fstype::*, mount::*, supported::*, umount::*};
use libc::swapoff as c_swapoff;
use std::{
ffi::CString,
io::{self, Error, ErrorKind},
os::unix::ffi::OsStrExt,
path::Path,
};
#[derive(Debug, Error)]
pub enum ScopedMountError {
#[error("cannot get list of supported file systems")]
Supported(#[source] io::Error),
#[error("could not mount partition")]
Mount(#[source] io::Error),
}
pub fn scoped_mount<T, S: FnOnce() -> T>(
source: &Path,
mount_at: &Path,
scope: S,
) -> Result<T, ScopedMountError> {
let supported = SupportedFilesystems::new().map_err(ScopedMountError::Supported)?;
Mount::builder()
.fstype(&supported)
.mount(source, mount_at)
.map_err(ScopedMountError::Mount)?;
let result = scope();
if let Err(why) = unmount(mount_at, UnmountFlags::empty()) {
tracing::warn!("{}: failed to unmount: {}", mount_at.display(), why);
}
Ok(result)
}
pub fn swapoff<P: AsRef<Path>>(dest: P) -> io::Result<()> {
let Ok(swap) = CString::new(dest.as_ref().as_os_str().as_bytes().to_owned()) else {
return Err(Error::new(
ErrorKind::Other,
format!(
"swap path is not a valid c string: '{}'",
dest.as_ref().display()
)
))
};
match unsafe { c_swapoff(swap.as_ptr()) } {
0 => Ok(()),
_err => Err(Error::new(
ErrorKind::Other,
format!(
"failed to swapoff {}: {}",
dest.as_ref().display(),
Error::last_os_error()
),
)),
}
}
#[inline]
fn to_cstring(data: &[u8]) -> io::Result<CString> {
CString::new(data).map_err(|why| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("failed to create `CString`: {}", why),
)
})
}