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
#[macro_use]
extern crate log;
use std::fs::OpenOptions;
use std::io::{BufRead, BufReader, BufWriter, Error, ErrorKind, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::str::FromStr;
#[derive(Clone,Debug,Eq,PartialEq)]
pub struct FsEntry {
pub fs_spec: String,
pub mountpoint: PathBuf,
pub vfs_type: String,
pub mount_options: Vec<String>,
pub dump: bool,
pub fsck_order: u16,
}
#[cfg(test)]
mod tests {
use std::io::{BufReader, Cursor};
use std::path::{Path, PathBuf};
use super::FsEntry;
#[test]
fn test_parser() {
let expected_results =
vec![FsEntry {
fs_spec: "/dev/mapper/xubuntu--vg--ssd-root".to_string(),
mountpoint: PathBuf::from("/"),
vfs_type: "ext4".to_string(),
mount_options: vec!["noatime".to_string(), "errors=remount-ro".to_string()],
dump: false,
fsck_order: 1,
},
FsEntry {
fs_spec: "UUID=378f3c86-b21a-4172-832d-e2b3d4bc7511".to_string(),
mountpoint: PathBuf::from("/boot"),
vfs_type: "ext2".to_string(),
mount_options: vec!["defaults".to_string()],
dump: false,
fsck_order: 2,
},
FsEntry {
fs_spec: "/dev/mapper/xubuntu--vg--ssd-swap_1".to_string(),
mountpoint: PathBuf::from("none"),
vfs_type: "swap".to_string(),
mount_options: vec!["sw".to_string()],
dump: false,
fsck_order: 0,
},
FsEntry {
fs_spec: "UUID=be8a49b9-91a3-48df-b91b-20a0b409ba0f".to_string(),
mountpoint: PathBuf::from("/mnt/raid"),
vfs_type: "ext4".to_string(),
mount_options: vec!["errors=remount-ro".to_string(), "user".to_string()],
dump: false,
fsck_order: 1,
}];
let input = r#"
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point> <type> <options> <dump> <pass>
/dev/mapper/xubuntu--vg--ssd-root / ext4 noatime,errors=remount-ro 0 1
# /boot was on /dev/sda1 during installation
UUID=378f3c86-b21a-4172-832d-e2b3d4bc7511 /boot ext2 defaults 0 2
/dev/mapper/xubuntu--vg--ssd-swap_1 none swap sw 0 0
UUID=be8a49b9-91a3-48df-b91b-20a0b409ba0f /mnt/raid ext4 errors=remount-ro,user 0 1
# tmpfs /tmp tmpfs rw,nosuid,nodev
"#;
let bytes = input.as_bytes();
let buff = Cursor::new(bytes);
let reader = BufReader::new(buff);
let results = super::parse_fstab(reader).unwrap();
println!("Result: {:?}", results);
assert_eq!(results, expected_results);
let bytes_written = super::add_entry(expected_results[1].clone(), Path::new("/tmp/fstab"))
.unwrap();
println!("Wrote: {}", bytes_written);
}
}
pub fn parse_fstab<T: BufRead>(file: T) -> Result<Vec<FsEntry>, Error> {
let mut entries: Vec<FsEntry> = Vec::new();
for line in file.lines() {
let l = line?;
if l.starts_with("#") {
trace!("Skipping commented line: {}", l);
continue;
}
let parts: Vec<&str> = l.split(" ").filter(|s| !s.is_empty()).collect();
if parts.len() != 6 {
debug!("Unknown fstab entry: {}", l);
continue;
}
let fsck_order =
u16::from_str(parts[5]).map_err(|e| Error::new(ErrorKind::InvalidInput, e))?;
entries.push(FsEntry {
fs_spec: parts[0].to_string(),
mountpoint: PathBuf::from(parts[1]),
vfs_type: parts[2].to_string(),
mount_options: parts[3].split(",").map(|s| s.to_string()).collect(),
dump: if parts[4] == "0" { false } else { true },
fsck_order: fsck_order,
})
}
Ok(entries)
}
fn save_fstab<T: Write>(entries: &Vec<FsEntry>, file: &mut T) -> Result<usize, Error> {
let mut bytes_written: usize = 0;
for entry in entries {
bytes_written += file.write(&format!("{spec} {mount} {vfs} {options} {dump} {fsck}\n",
spec = entry.fs_spec,
mount = entry.mountpoint.display(),
vfs = entry.vfs_type,
options = entry.mount_options.join(","),
dump = if entry.dump { "1" } else { "0" },
fsck = entry.fsck_order)
.as_bytes())?;
}
file.flush()?;
debug!("Wrote {} bytes to fstab", bytes_written);
Ok(bytes_written)
}
pub fn add_entry(entry: FsEntry, file: &Path) -> Result<bool, Error> {
let mut f = OpenOptions::new().read(true)
.write(true)
.open(file)?;
let mut entries = {
parse_fstab(BufReader::new(&f))?
};
f.seek(SeekFrom::Start(0))?;
let mut writer = BufWriter::new(f);
let position = entries.iter().position(|e| e == &entry);
if let Some(pos) = position {
debug!("Removing {} from fstab entries", pos);
entries.remove(pos);
}
entries.push(entry);
match position {
Some(_) => {
save_fstab(&mut entries, &mut writer)?;
Ok(false)
}
None => {
save_fstab(&mut entries, &mut writer)?;
Ok(true)
}
}
}
pub fn remove_entry(spec: String, file: &Path) -> Result<bool, Error> {
let mut f = OpenOptions::new().read(true)
.write(true)
.open(file)?;
let mut entries = {
parse_fstab(BufReader::new(&f))?
};
f.seek(SeekFrom::Start(0))?;
let mut writer = BufWriter::new(f);
let position = entries.iter().position(|e| e.fs_spec == spec);
match position {
Some(pos) => {
debug!("Removing {} from fstab entries", pos);
entries.remove(pos);
save_fstab(&mut entries, &mut writer)?;
Ok(true)
}
None => Ok(false),
}
}