use std::fs::File;
use std::io;
use std::path::Path;
#[cfg(unix)]
const FILE_MODE: u32 = 0o600;
pub(crate) fn create_dir_secure(dir: &Path) -> io::Result<()> {
powdb_storage::create_data_dir_secure(dir)
}
fn open_file_secure(path: &Path, truncate: bool) -> io::Result<File> {
let mut options = std::fs::OpenOptions::new();
options.read(true).write(true).create(true);
if truncate {
options.truncate(true);
} else {
options.truncate(false);
}
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(FILE_MODE);
}
let file = options.open(path)?;
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
file.set_permissions(std::fs::Permissions::from_mode(FILE_MODE))?;
}
Ok(file)
}
pub(crate) fn write_file_secure(path: &Path, bytes: &[u8]) -> io::Result<()> {
use std::io::Write;
let mut file = open_file_secure(path, true)?;
file.write_all(bytes)?;
file.flush()
}
pub(crate) fn open_paged_file_secure(path: &Path) -> io::Result<File> {
open_file_secure(path, false)
}