Verify that the output and job directories exist and are writable

This commit is contained in:
Kienan Stewart 2022-09-24 11:08:45 -04:00
parent 053910c03f
commit 222d4c6c18
1 changed files with 69 additions and 0 deletions

View File

@ -43,6 +43,25 @@ impl ThreadJob<'_> {
}
}
fn verify_directory(dir: &String) -> bool {
let md = match std::fs::metadata(&dir) {
Err(why) => {
println!("Cannot stat directory '{}': {}", dir, why);
return false;
},
Ok(val) => val,
};
if !md.is_dir() {
println!("Output directory '{}' is not a directory", dir);
return false;
}
if md.permissions().readonly() {
println!("Output directory '{}' is read-only", dir);
return false;
}
return true;
}
fn main() {
let mut conf = Conf::get_default_conf();
conf.update_from_file("/etc/haunter/haunter.conf");
@ -57,6 +76,15 @@ fn main() {
}
}
if !verify_directory(&conf.output_dir) {
println!("Output directory unusable, aborting");
std::process::exit(1);
}
if !verify_directory(&conf.job_dir) {
println!("Output job unusable, aborting");
std::process::exit(1);
}
let mut jobs = Vec::new();
let some_job = Job {
url: "https://www.rust-lang.org",
@ -156,3 +184,44 @@ fn get_source(driver: &str, url: &str) -> Result<String, &'static str> {
driver.quit().expect("failed to close session");
return Ok(source);
}
#[cfg(test)]
mod tests {
use super::*;
use std::str::FromStr;
use tempfile;
#[test]
fn verify_directory_exists_but_is_file() {
let mut tf = tempfile::NamedTempFile::new().unwrap();
let dir = String::from_str(tf.path().to_str().unwrap()).unwrap();
assert!(!verify_directory(&dir));
}
#[test]
fn verify_directory_does_not_exist() {
assert!(!verify_directory(&String::from_str("/fake/path/that/does/not/exist").unwrap()));
}
#[test]
fn verify_directory_exists() {
let mut tf = tempfile::tempdir().unwrap();
assert!(verify_directory(&String::from_str(tf.path().to_str().unwrap()).unwrap()));
}
#[test]
fn verify_directory_exists_but_is_not_writable() {
let mut tf = tempfile::tempdir().unwrap();
let md = std::fs::metadata(&tf.path()).unwrap();
let mut perms = md.permissions();
perms.set_readonly(true);
std::fs::set_permissions(&tf.path(), perms);
let result = verify_directory(&String::from_str(tf.path().to_str().unwrap()).unwrap());
perms = md.permissions();
perms.set_readonly(false);
std::fs::set_permissions(&tf.path(), perms);
assert!(!result);
}
}