use std::path::PathBuf;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
use crate::error::{ServerError, ServerResult, TlsKind};
pub fn load_certs(file_path: &str) -> ServerResult<Vec<CertificateDer<'static>>> {
let path = PathBuf::from(file_path);
let iter = CertificateDer::pem_file_iter(file_path).map_err(|e| ServerError::TlsLoad {
kind: TlsKind::Certificate,
path: path.clone(),
reason: e.to_string(),
})?;
let mut certs = Vec::new();
for (idx, item) in iter.enumerate() {
let cert = item.map_err(|e| ServerError::TlsLoad {
kind: TlsKind::Certificate,
path: path.clone(),
reason: format!("failed to parse certificate #{}: {}", idx + 1, e),
})?;
certs.push(cert);
}
if certs.is_empty() {
return Err(ServerError::TlsLoad {
kind: TlsKind::Certificate,
path,
reason: "no certificates found in PEM file".to_owned(),
});
}
Ok(certs)
}
pub fn load_private_key(file_path: &str) -> ServerResult<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_file(file_path).map_err(|e| ServerError::TlsLoad {
kind: TlsKind::PrivateKey,
path: PathBuf::from(file_path),
reason: e.to_string(),
})
}