improved the errorhandling

Dieser Commit ist enthalten in:
Sebastian Tobie 2025-05-15 13:32:05 +02:00
Ursprung 5c3183f686
Commit 11f7df2116
4 geänderte Dateien mit 71 neuen und 30 gelöschten Zeilen

Datei anzeigen

@ -47,6 +47,7 @@ use std::{
Path,
PathBuf,
},
process::exit,
str::FromStr,
sync::Arc,
time::Duration,
@ -63,34 +64,55 @@ use tokio_stream::{
StreamExt,
wrappers::ReadDirStream,
};
use types::structs::Error;
fn default_client() -> reqwest::Client {
reqwest::Client::builder().min_tls_version(Version::TLS_1_2).https_only(true).pool_max_idle_per_host(POOL_SIZE).build().unwrap()
fn default_client() -> Result<reqwest::Client, Error> {
reqwest::Client::builder()
.min_tls_version(Version::TLS_1_2)
.https_only(true)
.pool_max_idle_per_host(POOL_SIZE)
.build()
.map_err(Error::from_display)
}
async fn load_privkey(path: PathBuf) -> Result<PKey<Private>, ()> {
let mut file = match_error!(FILE_MODE.open(path).await=>Err(error)-> "Failed to open Private Key: {error}", Err(()));
async fn load_privkey(path: PathBuf) -> Result<PKey<Private>, Error> {
let mut file = match FILE_MODE.open(path).await {
Ok(file) => file,
Err(error) => return Error::err(format!("Failed to open Private Key: {error}")),
};
let mut data = String::new();
if let Err(error) = file.read_to_string(&mut data).await {
error!("Failed to read data for the key: {error}");
return Err(());
return Error::err(format!("Failed to read data for the key: {error}"));
}
match PKey::private_key_from_pem(data.as_bytes()) {
Ok(key) => Ok(key),
Err(error) => {
error!("Failed to parse pem data: {error}");
Err(())
},
Err(error) => Error::err(format!("Failed to parse pem data: {error}")),
}
}
async fn racme(flags: Arguments) {
let client = default_client();
async fn racme(flags: Arguments) -> Result<(), Error> {
let client = default_client()?;
let systemd_access = daemon::booted();
let mainconfig = GeneralConfig::from_file(match_error!(FILE_MODE.open(flags.config).await=>Err(error)-> "error reading the config: {error}")).await;
let mainconfig = {
let file = match FILE_MODE.open(flags.config).await {
Ok(file) => file,
Err(error) => {
return Error::err(format!("error reading the config: {error}"));
},
};
GeneralConfig::from_file(file).await
};
trace!("Parsed Config: {mainconfig:?}");
let files = ReadDirStream::new(match_error!(read_dir(mainconfig.sites_path.clone()).await=>Err(error)-> "could not read files from sites dir: {error}"));
let files = {
let rd = match read_dir(mainconfig.sites_path.clone()).await {
Ok(rd) => rd,
Err(error) => {
return Error::err(format!("could not read files from sites dir: {error}"));
},
};
ReadDirStream::new(rd)
};
let mut siteconfigs = Vec::new();
for file in files.filter(Result::is_ok).map(|file| file.unwrap().path()).collect::<Vec<PathBuf>>().await {
let mut site = SiteConfig::from_file(FILE_MODE.open(file.clone()).await.unwrap()).await;
@ -105,22 +127,19 @@ async fn racme(flags: Arguments) {
let mut accounts = HashMap::new();
let accountpath = Path::new(&mainconfig.accounts_path).to_path_buf();
if let Err(error) = create_dir_all(accountpath.clone()).await {
error!("Failed to create the directory for the accounts: {error}");
return;
return Error::err(format!("Failed to create the directory for the accounts: {error}"));
}
for (name, ca) in mainconfig.ca.iter().filter(|(name, _)| used.contains(name.to_owned())) {
process::accounts(name, ca, &mut directories, &mut accounts, &client, accountpath.clone()).await;
}
let restart_services = Mutex::new(HashSet::<String>::new());
let reload_services = Mutex::new(HashSet::<String>::new());
let certs = Path::new(&mainconfig.certificates_path).to_path_buf();
if !certs.exists() {
if let Err(error) = create_dir_all(certs.clone()).await {
error!("Failed to create directory for all the certificates: {error}");
return;
return Error::err(format!("Failed to create directory for all the certificates: {error}"));
}
}
let challengepath = mainconfig.http_challenge_path.and_then(|path| PathBuf::from_str(path.as_str()).ok());
@ -150,11 +169,16 @@ async fn racme(flags: Arguments) {
if systemd_access {
process::services(restart_services.into_inner(), reload_services.into_inner()).await;
}
Ok(())
}
fn main() {
log_init();
let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap();
runtime.block_on(racme(Arguments::parse()));
let result = runtime.block_on(racme(Arguments::parse()));
runtime.shutdown_timeout(Duration::from_secs(1));
if let Err(error) = result {
error!("{error}");
exit(1)
}
}

Datei anzeigen

@ -218,30 +218,30 @@ pub async fn site(args: ProcessorArgs<'_>) {
if !private_key_file.exists() {
cert_renew = true;
write_pkey = true;
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)-> "Aborting processing the site due to problem with the certificate generation: {error}");
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)->"Aborting processing the site due to problem with the certificate generation: {error}");
} else if let Ok(key) = load_privkey(private_key_file.clone()).await {
private_key = key;
if !private_key.matches(args.algorithm(), args.strength()) {
info!("Algorithm for the private key has changed, updating the key");
cert_renew = true;
write_pkey = true;
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)-> "Aborting processing the site due to problem with the certificate generation: {error}");
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)->"Aborting processing the site due to problem with the certificate generation: {error}");
}
} else {
error!("Failed to parse the private key. Renewing the private key.");
write_pkey = true;
cert_renew = true;
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)-> "Aborting processing the site due to problem with the certificate generation: {error}");
private_key = match_error!(gen_key(args.algorithm(), args.strength())=>Err(error)->"Aborting processing the site due to problem with the certificate generation: {error}");
}
if write_pkey {
let pkey = private_key.private_key_to_pem_pkcs8().unwrap();
let mut file = match_error!(FILE_MODE_WRITE.open(private_key_file.clone()).await=>Err(error)-> "Failed to write new private key: {error}");
let mut file = match_error!(FILE_MODE_WRITE.open(private_key_file.clone()).await=>Err(error)->"Failed to write new private key: {error}");
match_error!(file.write_all(&pkey).await=>Err(error)->"Failed to write new private key: {error}");
}
}
let pubkey_filename = directory.join("pubkey.pem");
if pubkey_filename.exists() {
let mut file = match_error!(FILE_MODE.open(pubkey_filename.clone()).await=>Err(error)-> "Failed to open publickey. Aborting processing: {error}");
let mut file = match_error!(FILE_MODE.open(pubkey_filename.clone()).await=>Err(error)->"Failed to open publickey. Aborting processing: {error}");
let mut data = String::new();
if let Err(error) = file.read_to_string(&mut data).await {
cert_renew = true;

Datei anzeigen

@ -1,5 +1,9 @@
use std::{
collections::HashSet,
fmt::{
Debug,
Display,
},
net::IpAddr,
path::PathBuf,
sync::Arc,
@ -128,6 +132,16 @@ pub enum San {
pub struct Error(pub(super) String);
impl Error {
#[inline]
pub fn from_display<T: Display>(input: T) -> Error {
Error::new(format!("{input}"))
}
#[inline]
pub fn from_debug<T: Debug>(input: T) -> Error {
Error::new(format!("{input:?}"))
}
#[inline]
pub fn err<T>(message: String) -> Result<T, Self> {
Err(Self::new(message))

Datei anzeigen

@ -7,9 +7,12 @@ use crate::{
SECP_STRONG,
SECP_WEAK,
},
types::cryptography::{
Algorithm,
Strength,
types::{
cryptography::{
Algorithm,
Strength,
},
structs::Error,
},
};
use log::*;
@ -70,7 +73,7 @@ fn gen_ec_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>,
}
pub fn gen_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>, String> {
pub fn gen_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>, Error> {
let key = match algorithm {
Algorithm::Rsa => {
let key = Rsa::generate(strength.rsabits());
@ -85,7 +88,7 @@ pub fn gen_key(algorithm: Algorithm, strength: Strength) -> Result<PKey<Private>
};
match key {
Ok(key) => Ok(key),
Err(error) => Err(format!("Failed to generate an key to the parameters: {error}")),
Err(error) => Error::err(format!("Failed to generate an key to the parameters: {error}")),
}
}