2023-11-27 16:36:44 +00:00
|
|
|
use std::ffi::CString;
|
|
|
|
use std::io::{Error, ErrorKind};
|
|
|
|
|
2023-11-23 15:00:24 +00:00
|
|
|
pub fn load_settings<T>(config_name: &str, env_prefix: &str) -> T
|
|
|
|
where
|
2023-11-27 11:49:40 +00:00
|
|
|
for<'de> T: serde::Deserialize<'de>,
|
2023-11-23 15:00:24 +00:00
|
|
|
{
|
2023-11-27 11:49:40 +00:00
|
|
|
let default_file = config::File::with_name(&format!("emgauwa-{}", config_name)).required(false);
|
2023-11-23 15:00:24 +00:00
|
|
|
|
|
|
|
config::Config::builder()
|
|
|
|
.add_source(default_file)
|
|
|
|
.add_source(
|
|
|
|
config::Environment::with_prefix(&format!("EMGAUWA_{}", env_prefix))
|
|
|
|
.prefix_separator("__")
|
|
|
|
.separator("__"),
|
|
|
|
)
|
|
|
|
.build()
|
|
|
|
.expect("Error building settings")
|
|
|
|
.try_deserialize::<T>()
|
|
|
|
.expect("Error reading settings")
|
2023-11-27 11:49:40 +00:00
|
|
|
}
|
2023-11-27 16:36:44 +00:00
|
|
|
|
|
|
|
// https://blog.lxsang.me/post/id/28.0
|
|
|
|
pub fn drop_privileges(user: &str, group: &str) -> Result<(), Error> {
|
|
|
|
// the group id need to be set first, otherwise,
|
|
|
|
// when the user privileges drop, it is unable to
|
|
|
|
// drop the group privileges
|
|
|
|
// get the gid from username
|
|
|
|
if let Ok(cstr) = CString::new(group.as_bytes()) {
|
|
|
|
let p = unsafe { libc::getgrnam(cstr.as_ptr()) };
|
|
|
|
if p.is_null() {
|
|
|
|
eprintln!("Unable to getgrnam of group: {}", group);
|
|
|
|
return Err(Error::last_os_error());
|
|
|
|
}
|
|
|
|
if unsafe { libc::setgid((*p).gr_gid) } != 0 {
|
|
|
|
eprintln!("Unable to setgid of group: {}", group);
|
|
|
|
return Err(Error::last_os_error());
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(Error::new(
|
|
|
|
ErrorKind::Other,
|
|
|
|
"Cannot create CString from String (group)!",
|
|
|
|
));
|
|
|
|
}
|
|
|
|
// drop the user privileges
|
|
|
|
// get the uid from username
|
|
|
|
if let Ok(cstr) = CString::new(user.as_bytes()) {
|
|
|
|
let p = unsafe { libc::getpwnam(cstr.as_ptr()) };
|
|
|
|
if p.is_null() {
|
|
|
|
eprintln!("Unable to getpwnam of user: {}", user);
|
|
|
|
return Err(Error::last_os_error());
|
|
|
|
}
|
|
|
|
if unsafe { libc::setuid((*p).pw_uid) } != 0 {
|
|
|
|
eprintln!("Unable to setuid of user: {}", user);
|
|
|
|
return Err(Error::last_os_error());
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
return Err(Error::new(
|
|
|
|
ErrorKind::Other,
|
|
|
|
"Cannot create CString from String (user)!",
|
|
|
|
));
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|