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
334
335
336
337
338
339
340
341
342
343
344
|
#![forbid(unsafe_code)]
use std::{
collections::HashMap,
num::{NonZeroU64, NonZeroUsize},
path::PathBuf,
sync::{atomic::AtomicBool, Arc},
};
use anyhow::{anyhow, Context};
use clap::Parser;
use either::Either;
use flate2::{write::GzEncoder, Compression};
use itertools::Itertools;
use parseq::ParallelIterator;
mod core;
use core::*;
mod fs;
use fs::*;
// std::process::ExitCode::exit_process is unstable
// Exit codes should fit u8.
const EXIT_SUCCESS: i32 = 0;
const EXIT_FAILURE: i32 = 1;
const EXIT_INTERRUPT: i32 = 130;
/// A simple bit rot checker for legacy file systems.
///
/// On the first invocation, Brck records the modification time and a cryptographic hash sum of each regular file in the current working directory to a .brck file.
/// On subsequent invocations, Brck compares the recorded files against the current file system.
///
/// A file can be added, touched, changed, unchanged, removed, or corrupted.
/// A file is corrupted if it's content changed but it's modification did not.
///
/// Without any options, Brck denies corrupted files.
/// If Brck finds one or more denied differences, it prints them to standard output and exits >0.
/// Otherwise, Brck updates the .brck file.
#[derive(Debug, Parser)]
#[command(about, version, author)]
struct Args {
/// Increase verbosity.
///
/// Specify once to print all changed files.
/// Specify twice to print unchanged files, too.
/// By default, only denied differences are printed.
#[arg(short = 'v', long = "verbose", action = clap::ArgAction::Count)]
verbosity: u8,
/// Do not actually modify the database.
#[arg(short = 'n', long)]
dry_run: bool,
/// Specify the number of worker threads.
///
/// Defaults to the available parallelism, typically the number of CPUs.
#[arg(short, long)]
jobs: Option<NonZeroUsize>,
/// Deny select differences only.
///
/// This option accepts a comma-separated list of differences to deny.
/// Without this option, only corrupted files are denied.
/// With this option, only the specified differences are denied.
#[arg(value_enum, short, long, default_values_t = vec![DiffKind::Corrupted], value_delimiter = ',', action = clap::ArgAction::Append)]
deny: Vec<DiffKind>,
/// Enable structured output.
///
/// By default, Brck prints differences in a human readable format to standard output.
/// With this option, Brck prints differences as newline-delimited JSON objects to standard output.
#[arg(short = 'J', long)]
json: bool,
/// Print a summary to standard error.
#[arg(short, long)]
summary: bool,
/// Specify the maximum number of bytes a worker thread may read without checking for an interrupt signal.
///
/// Defaults to 1 GiB.
#[arg(long)]
chunk_size: Option<NonZeroU64>,
/// Specify the maximum number of files to read ahead.
///
/// This should be greater than the number of worker threads.
///
/// Defaults to 1024 files per worker thread.
#[arg(long)]
queue_size: Option<NonZeroUsize>,
}
fn main() {
std::process::exit(match run() {
Ok(_) => EXIT_SUCCESS,
Err(err) if err.is::<clap::Error>() => {
// Use clap's own error formatter
eprintln!("{err}");
EXIT_FAILURE
}
Err(err) => {
eprintln!("Error: {:?}", err);
match err.downcast_ref::<RecordError>() {
Some(RecordError::Interrupt) => EXIT_INTERRUPT,
_ => EXIT_FAILURE,
}
}
})
}
fn run() -> Result<(), anyhow::Error> {
let terminate = Arc::new(AtomicBool::new(false));
let args = Args::try_parse()?;
// Paths must begin with ./ for correct filtering.
let current_dir: PathBuf = std::path::Component::CurDir.as_os_str().into();
let db_path = current_dir.join(".brck");
let backup_path = current_dir.join(".brck.bak");
// Creating temporary files in the same directory instead of std::env_temp_dir() to enable atomic rename(2) on POSIX-conform systems.
// The drawback is that the operating system won't remove these files automatically.
let tmp_db_path = current_dir.join(".brck.tmp");
let tmp_backup_path = current_dir.join(".brck.bak.tmp");
#[cfg(target_os = "openbsd")]
{
use std::{os::unix::ffi::OsStrExt, path::Path};
pledge::pledge![Stdio Rpath Wpath Cpath Unveil, Stdio].context("Failed to pledge(2)")?;
fn unveil<P: AsRef<Path>>(path: P, permissions: &str) -> Result<(), anyhow::Error> {
unveil::unveil(path.as_ref().as_os_str().as_bytes(), permissions).with_context(|| {
format!(
"Failed to unveil(2) {} with permissions {}",
path.as_ref().display(),
permissions
)
})
}
unveil(".", "r")?;
unveil(&db_path, "rwc")?;
unveil(&tmp_db_path, "rwc")?;
unveil(&backup_path, "rwc")?;
unveil(&tmp_backup_path, "rwc")?;
unveil::unveil("", "").context("Failed to disable unveil(2)")?;
}
let t = terminate.clone();
ctrlc::try_set_handler(move || {
if t.load(std::sync::atomic::Ordering::SeqCst) {
eprintln!("Received second interrupt signal");
std::process::exit(EXIT_INTERRUPT);
}
eprintln!("Received interrupt signal");
t.store(true, std::sync::atomic::Ordering::SeqCst);
})
.context("Failed to register interrupt signal handler")?;
let (db, first_run) = match read_db(&db_path) {
Ok(db) => Ok((Either::Left(db), false)),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
Ok((Either::Right(std::iter::empty()), true))
}
Err(err) => Err(err),
}
.with_context(|| format!("Failed to read database {}", db_path.display()))?;
let db = db.map(|item| {
item.map_err(|err| {
anyhow::Error::new(err).context(format!(
"Failed to decode record from database {}",
&db_path.display()
))
})
});
let tmp = TmpFile::open(&tmp_db_path).with_context(|| {
format!(
"Failed to create temporary database {}",
tmp_db_path.display()
)
})?;
let mut tmp = GzEncoder::new(tmp.file(), Compression::default());
let jobs = args
.jobs
.or_else(|| std::thread::available_parallelism().ok())
.map(NonZeroUsize::get)
.unwrap_or(1);
let queue_size = args
.queue_size
.map(NonZeroUsize::get)
.unwrap_or_else(|| jobs.saturating_mul(1024));
let chunk_size = args
.chunk_size
.map(NonZeroU64::get)
.unwrap_or(1024 * 1024 * 1024);
let fs = find_files(¤t_dir)
.filter_ok(|path| path != &db_path && path != &tmp_db_path && path != &backup_path)
.map(|item| {
item.map_err(|err| anyhow::Error::new(err).context("Failed to walk filesystem"))
})
.map_parallel_limit(jobs, queue_size, move |item| {
item.and_then(|path| {
Record::from_path(&path, chunk_size, terminate.clone())
.with_context(|| format!("Failed to read file {}", path.display()))
})
});
let mut counter = HashMap::new();
let mut denied = 0;
let print = if args.json {
|diff: &Diff| println!("{}", serde_json::to_string(&diff).unwrap())
} else {
|diff: &Diff| println!("{diff}")
};
diff(db, fs).try_for_each(|item| match item {
Err(Either::Left(err)) => Err(err),
Err(Either::Right(err)) => Err(err),
Ok(diff) => {
*counter.entry(diff.kind()).or_insert(0) += 1;
record(&diff, &mut tmp).with_context(|| {
format!(
"Failed to write to temporary database {}",
tmp_db_path.display()
)
})?;
if args.deny.contains(&diff.kind()) {
denied += 1;
print(&diff);
} else if args.verbosity > 1
|| (diff.kind() != DiffKind::Unchanged && args.verbosity > 0)
{
print(&diff);
}
Ok(())
}
})?;
if args.summary {
let total: usize = counter.values().sum();
let width = usize::try_from(total.checked_ilog10().unwrap_or(0) + 1).unwrap_or(0);
eprintln!(
"Removed: {:>width$}",
counter.get(&DiffKind::Removed).unwrap_or(&0)
);
eprintln!(
"Added: {:>width$}",
counter.get(&DiffKind::Added).unwrap_or(&0)
);
eprintln!(
"Unchanged: {:>width$}",
counter.get(&DiffKind::Unchanged).unwrap_or(&0)
);
eprintln!(
"Corrupted: {:>width$}",
counter.get(&DiffKind::Corrupted).unwrap_or(&0)
);
eprintln!(
"Touched: {:>width$}",
counter.get(&DiffKind::Touched).unwrap_or(&0)
);
eprintln!(
"Changed: {:>width$}",
counter.get(&DiffKind::Changed).unwrap_or(&0)
);
eprintln!("Total: {:>width$}", total);
}
if denied > 0 {
return Err(anyhow!(
"Found {} denied {}",
denied,
if denied == 1 {
"difference"
} else {
"differences"
}
));
}
if args.dry_run {
eprintln!("Exiting due to dry run");
return Ok(());
}
tmp.finish().with_context(|| {
format!(
"Failed to synchronize temporary database {}",
tmp_db_path.display()
)
})?;
if !first_run {
copy_file(&db_path, tmp_backup_path, &backup_path).with_context(|| {
format!(
"Failed to backup database {} to {}",
db_path.display(),
backup_path.display()
)
})?;
}
rename_file(&tmp_db_path, &db_path).with_context(|| {
format!(
"Failed to persist temporary database {} to {}",
tmp_db_path.display(),
db_path.display()
)
})?;
Ok(())
}
fn record<T: std::io::Write>(diff: &Diff, mut writer: T) -> Result<(), std::io::Error> {
let file = match diff {
Diff::Removed { .. } => None,
Diff::Added { new, .. } => Some(new),
Diff::Unchanged { new, .. } => Some(new),
Diff::Corrupted { new, .. } => Some(new),
Diff::Touched { new, .. } => Some(new),
Diff::Changed { new, .. } => Some(new),
};
if let Some(file) = file {
let s = serde_json::to_string(file).unwrap();
writeln!(writer, "{}", s)
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn verify_clap_app() {
use clap::CommandFactory;
Args::command().debug_assert()
}
}
|