ptth/crates/ptth_server/src/load_toml.rs

72 lines
1.4 KiB
Rust

use std::{
fmt::Debug,
fs::File,
io::Read,
path::Path,
};
use serde::de::DeserializeOwned;
use crate::errors::LoadTomlError;
pub const CONFIG_PERMISSIONS_MODE: u32 = 33152;
fn load_inner <
T: DeserializeOwned
> (
mut f: File
) -> Result <T, LoadTomlError> {
let mut buffer = vec! [0_u8; 4096];
let bytes_read = f.read (&mut buffer)?;
buffer.truncate (bytes_read);
let config_s = String::from_utf8 (buffer)?;
Ok (toml::from_str (&config_s)?)
}
/// For files that contain public-viewable information
pub fn load_public <
T: DeserializeOwned,
P: AsRef <Path> + Debug
> (
config_file_path: P
) -> Result <T, LoadTomlError> {
let f = File::open (&config_file_path)?;
load_inner (f)
}
/// For files that may contain secrets and should have permissions or other
/// safeties checked
#[cfg (unix)]
pub fn load <
T: DeserializeOwned,
P: AsRef <Path> + Debug
> (
config_file_path: P
) -> Result <T, LoadTomlError> {
use std::os::unix::fs::PermissionsExt;
let f = File::open (&config_file_path)?;
let mode = f.metadata ()?.permissions ().mode ();
if mode != CONFIG_PERMISSIONS_MODE {
return Err (LoadTomlError::ConfigBadPermissions);
}
load_inner (f)
}
// The permission check doesn't work on Windows
#[cfg (not (unix))]
pub fn load <
T: DeserializeOwned,
P: AsRef <Path> + Debug
> (
config_file_path: P
) -> Result <T, LoadTomlError> {
load_public (config_file_path)
}