common/emgauwa-lib/src/utils.rs

95 lines
2.4 KiB
Rust
Raw Normal View History

use std::ffi::CString;
use std::io::{Error, ErrorKind};
2023-11-29 13:27:46 +00:00
use std::str::FromStr;
2023-11-30 00:43:56 +00:00
use chrono::Datelike;
use log::LevelFilter;
use simple_logger::SimpleLogger;
2023-12-05 00:42:19 +00:00
use crate::errors::EmgauwaError;
use crate::settings::Permissions;
2023-11-30 00:43:56 +00:00
use crate::types::Weekday;
2023-12-05 00:42:19 +00:00
pub fn init_logging(level: &str) -> Result<(), EmgauwaError> {
let log_level: LevelFilter = LevelFilter::from_str(level)
2023-12-05 00:51:06 +00:00
.map_err(|_| EmgauwaError::Other(format!("Invalid log level: {}", level)))?;
log::trace!("Log level set to {:?}", log_level);
SimpleLogger::new()
.with_level(log_level)
.init()
2023-12-05 00:51:06 +00:00
.map_err(|err| EmgauwaError::Other(format!("Failed to initialize logger: {}", err)))?;
2023-12-05 00:42:19 +00:00
Ok(())
}
2023-11-30 00:43:56 +00:00
// https://blog.lxsang.me/post/id/28.0
pub fn drop_privileges(permissions: &Permissions) -> Result<(), Error> {
log::info!(
"Dropping privileges to {}:{}",
permissions.user,
permissions.group
);
// the group id need to be set first, because, when the user privileges drop,
// we are unable to drop the group privileges
if !permissions.group.is_empty() {
drop_privileges_group(&permissions.group)?;
}
if !permissions.user.is_empty() {
drop_privileges_user(&permissions.user)?;
}
Ok(())
}
fn drop_privileges_group(group: &str) -> Result<(), Error> {
// 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() {
log::error!("Unable to getgrnam of group: {}", group);
return Err(Error::last_os_error());
}
if unsafe { libc::setgid((*p).gr_gid) } != 0 {
log::error!("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)!",
));
}
Ok(())
}
fn drop_privileges_user(user: &str) -> Result<(), Error> {
// 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() {
log::error!("Unable to getpwnam of user: {}", user);
return Err(Error::last_os_error());
}
if unsafe { libc::setuid((*p).pw_uid) } != 0 {
log::error!("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(())
}
2023-11-30 00:43:56 +00:00
pub fn get_weekday() -> Weekday {
(chrono::offset::Local::now()
.date_naive()
.weekday()
.number_from_monday()
- 1) as Weekday
}