#[cfg(unix)]
use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
use std::path::Path;
use shep_core::paths::ShepPaths;
use super::BootError;
pub const DIR_MODE: u32 = 0o700;
#[cfg(windows)]
fn create_dir_at_dir_mode(dir: &Path) -> std::io::Result<()> {
std::fs::DirBuilder::new().recursive(true).create(dir)
}
#[cfg(unix)]
fn create_dir_at_dir_mode(dir: &Path) -> std::io::Result<()> {
std::fs::DirBuilder::new()
.mode(DIR_MODE)
.recursive(true)
.create(dir)
}
pub(crate) fn init_dirs(paths: &ShepPaths) -> Result<(), BootError> {
for dir in [&paths.home, &paths.logs, &paths.pids, &paths.run] {
create_dir_at_dir_mode(dir).map_err(|source| BootError::Io {
path: dir.clone(),
source,
})?;
#[cfg(unix)]
std::fs::set_permissions(dir, std::fs::Permissions::from_mode(DIR_MODE)).map_err(
|source| BootError::Io {
path: dir.clone(),
source,
},
)?;
}
Ok(())
}
#[cfg(all(test, windows))]
mod windows_tests {
use super::*;
use crate::boot::paths_in;
#[test]
fn init_dirs_creates_the_whole_layout() {
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
init_dirs(&paths).unwrap();
for expected in [&paths.home, &paths.logs, &paths.pids, &paths.run] {
assert!(expected.is_dir(), "{} was not created", expected.display());
}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use crate::testing::test_paths;
fn mode_of(path: &Path) -> u32 {
std::fs::metadata(path).unwrap().permissions().mode() & 0o777
}
#[test]
fn init_dirs_creates_the_whole_layout_owner_only() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
init_dirs(&paths).unwrap();
for path in [&paths.home, &paths.logs, &paths.pids, &paths.run] {
assert!(path.is_dir(), "{} was not created", path.display());
assert_eq!(mode_of(path), DIR_MODE, "{}", path.display());
}
init_dirs(&paths).unwrap(); }
#[test]
fn a_fresh_dir_lands_at_dir_mode_with_no_separate_chmod() {
let dir = tempfile::tempdir().unwrap();
let never_existed = dir.path().join("nested").join("run");
create_dir_at_dir_mode(&never_existed).unwrap();
assert_eq!(
mode_of(&never_existed),
DIR_MODE,
"a freshly created dir must be DIR_MODE at creation, not after a later chmod"
);
}
#[test]
fn init_dirs_tightens_a_world_readable_runtime_dir() {
let dir = tempfile::tempdir().unwrap();
let paths = test_paths(&dir);
std::fs::create_dir_all(&paths.run).unwrap();
std::fs::set_permissions(&paths.run, std::fs::Permissions::from_mode(0o755)).unwrap();
init_dirs(&paths).unwrap();
assert_eq!(
mode_of(&paths.run),
DIR_MODE,
"a loose run dir must be tightened, not accepted"
);
}
}