Browse Source

Reformat log messages

pull/39/head
Rodolphe Breard 4 years ago
parent
commit
4eb0423da3
  1. 4
      acme_common/src/crypto/key_type.rs
  2. 2
      acme_common/src/crypto/openssl_certificate.rs
  3. 14
      acme_common/src/crypto/openssl_keys.rs
  4. 4
      acme_common/src/error.rs
  5. 2
      acme_common/src/lib.rs
  6. 4
      acmed/src/account.rs
  7. 10
      acmed/src/acme_proto.rs
  8. 23
      acmed/src/acme_proto/account.rs
  9. 8
      acmed/src/acme_proto/http.rs
  10. 50
      acmed/src/acme_proto/structs/error.rs
  11. 14
      acmed/src/certificate.rs
  12. 12
      acmed/src/config.rs
  13. 29
      acmed/src/hooks.rs
  14. 4
      acmed/src/http.rs
  15. 2
      acmed/src/identifier.rs
  16. 10
      acmed/src/main_event_loop.rs
  17. 10
      acmed/src/storage.rs
  18. 4
      tacd/src/main.rs
  19. 8
      tacd/src/openssl_server.rs

4
acme_common/src/crypto/key_type.rs

@ -41,7 +41,7 @@ impl KeyType {
Ok(()) Ok(())
} else { } else {
let err_msg = format!( let err_msg = format!(
"Incompatible signature algorithm: {} cannot be used with an {} key.",
"incompatible signature algorithm: {} cannot be used with an {} key",
alg, self alg, self
); );
Err(err_msg.into()) Err(err_msg.into())
@ -75,7 +75,7 @@ impl FromStr for KeyType {
"ed25519" => Ok(KeyType::Ed25519), "ed25519" => Ok(KeyType::Ed25519),
#[cfg(ed448)] #[cfg(ed448)]
"ed448" => Ok(KeyType::Ed448), "ed448" => Ok(KeyType::Ed448),
_ => Err(format!("{}: unknown algorithm.", s).into()),
_ => Err(format!("{}: unknown algorithm", s).into()),
} }
} }
} }

2
acme_common/src/crypto/openssl_certificate.rs

@ -16,7 +16,7 @@ const APP_ORG: &str = "ACMEd";
const APP_NAME: &str = "ACMEd"; const APP_NAME: &str = "ACMEd";
const X509_VERSION: i32 = 0x02; const X509_VERSION: i32 = 0x02;
const CRT_SERIAL_NB_BITS: i32 = 32; const CRT_SERIAL_NB_BITS: i32 = 32;
const INVALID_EXT_MSG: &str = "Invalid acmeIdentifier extension.";
const INVALID_EXT_MSG: &str = "invalid acmeIdentifier extension";
fn get_digest(digest: HashFunction, key_pair: &KeyPair) -> MessageDigest { fn get_digest(digest: HashFunction, key_pair: &KeyPair) -> MessageDigest {
#[cfg(not(any(ed25519, ed448)))] #[cfg(not(any(ed25519, ed448)))]

14
acme_common/src/crypto/openssl_keys.rs

@ -19,17 +19,17 @@ macro_rules! get_key_type {
256 => KeyType::Rsa2048, 256 => KeyType::Rsa2048,
512 => KeyType::Rsa4096, 512 => KeyType::Rsa4096,
s => { s => {
return Err(format!("{}: unsupported RSA key size", s).into());
return Err(format!("{}: unsupported RSA key size", s * 8).into());
} }
}, },
Id::EC => match $key.ec_key()?.group().curve_name() { Id::EC => match $key.ec_key()?.group().curve_name() {
Some(Nid::X9_62_PRIME256V1) => KeyType::EcdsaP256, Some(Nid::X9_62_PRIME256V1) => KeyType::EcdsaP256,
Some(Nid::SECP384R1) => KeyType::EcdsaP384, Some(Nid::SECP384R1) => KeyType::EcdsaP384,
Some(nid) => { Some(nid) => {
return Err(format!("{:?}: Unsupported EC key.", nid).into());
return Err(format!("{:?}: unsupported EC key", nid).into());
} }
None => { None => {
return Err("None: Unsupported EC key".into());
return Err("unsupported EC key".into());
} }
}, },
#[cfg(ed25519)] #[cfg(ed25519)]
@ -37,7 +37,7 @@ macro_rules! get_key_type {
#[cfg(ed448)] #[cfg(ed448)]
Id::ED448 => KeyType::Ed448, Id::ED448 => KeyType::Ed448,
_ => { _ => {
return Err("Unsupported key type".into());
return Err("unsupported key type".into());
} }
} }
}; };
@ -167,7 +167,7 @@ impl KeyPair {
KeyType::EcdsaP256 => ("P-256", "ES256", Nid::X9_62_PRIME256V1), KeyType::EcdsaP256 => ("P-256", "ES256", Nid::X9_62_PRIME256V1),
KeyType::EcdsaP384 => ("P-384", "ES384", Nid::SECP384R1), KeyType::EcdsaP384 => ("P-384", "ES384", Nid::SECP384R1),
_ => { _ => {
return Err("Not an ECDSA elliptic curve.".into());
return Err("not an ECDSA elliptic curve".into());
} }
}; };
let group = EcGroup::from_curve_name(curve).unwrap(); let group = EcGroup::from_curve_name(curve).unwrap();
@ -209,7 +209,7 @@ impl KeyPair {
#[cfg(ed448)] #[cfg(ed448)]
KeyType::Ed448 => "Ed448", KeyType::Ed448 => "Ed448",
_ => { _ => {
return Err("Not an EdDSA elliptic curve.".into());
return Err("not an EdDSA elliptic curve".into());
} }
}; };
let x = ""; let x = "";
@ -273,7 +273,7 @@ pub fn gen_keypair(key_type: KeyType) -> Result<KeyPair, Error> {
#[cfg(ed448)] #[cfg(ed448)]
KeyType::Ed448 => gen_ed448_pair(), KeyType::Ed448 => gen_ed448_pair(),
} }
.map_err(|_| Error::from(format!("Unable to generate a {} key pair.", key_type)))?;
.map_err(|_| Error::from(format!("unable to generate a {} key pair", key_type)))?;
let key_pair = KeyPair { let key_pair = KeyPair {
key_type, key_type,
inner_key: priv_key, inner_key: priv_key,

4
acme_common/src/error.rs

@ -95,13 +95,13 @@ impl From<attohttpc::Error> for Error {
impl From<glob::PatternError> for Error { impl From<glob::PatternError> for Error {
fn from(error: glob::PatternError) -> Self { fn from(error: glob::PatternError) -> Self {
format!("Pattern error: {}", error).into()
format!("pattern error: {}", error).into()
} }
} }
impl From<handlebars::TemplateRenderError> for Error { impl From<handlebars::TemplateRenderError> for Error {
fn from(error: handlebars::TemplateRenderError) -> Self { fn from(error: handlebars::TemplateRenderError) -> Self {
format!("Template error: {}", error).into()
format!("template error: {}", error).into()
} }
} }

2
acme_common/src/lib.rs

@ -14,7 +14,7 @@ macro_rules! exit_match {
match $e { match $e {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
log::error!("Error: {}", e);
log::error!("error: {}", e);
std::process::exit(3); std::process::exit(3);
} }
} }

4
acmed/src/account.rs

@ -111,7 +111,7 @@ impl Account {
Some(ep) => Ok(ep), Some(ep) => Ok(ep),
None => { None => {
let msg = format!( let msg = format!(
"{}: unknown endpoint for account {}",
"\"{}\": unknown endpoint for account \"{}\"",
endpoint_name, self.name endpoint_name, self.name
); );
Err(msg.into()) Err(msg.into())
@ -124,7 +124,7 @@ impl Account {
Some(ep) => Ok(ep), Some(ep) => Ok(ep),
None => { None => {
let msg = format!( let msg = format!(
"{}: unknown endpoint for account {}",
"\"{}\": unknown endpoint for account \"{}\"",
endpoint_name, self.name endpoint_name, self.name
); );
Err(msg.into()) Err(msg.into())

10
acmed/src/acme_proto.rs

@ -114,7 +114,7 @@ pub fn request_certificate(
let auth = http::get_authorization(endpoint, root_certs, &data_builder, &auth_url) let auth = http::get_authorization(endpoint, root_certs, &data_builder, &auth_url)
.map_err(HttpError::in_err)?; .map_err(HttpError::in_err)?;
if let Some(e) = auth.get_error() { if let Some(e) = auth.get_error() {
cert.warn(&e.prefix("Error").message);
cert.warn(&e.prefix("error").message);
} }
if auth.status == AuthorizationStatus::Valid { if auth.status == AuthorizationStatus::Valid {
continue; continue;
@ -188,7 +188,7 @@ pub fn request_certificate(
domains.as_slice(), domains.as_slice(),
ips.as_slice(), ips.as_slice(),
)?; )?;
cert.trace(&format!("New CSR:\n{}", csr.to_pem()?));
cert.trace(&format!("new CSR:\n{}", csr.to_pem()?));
let csr = json!({ let csr = json!({
"csr": csr.to_der_base64()?, "csr": csr.to_der_base64()?,
}); });
@ -197,7 +197,7 @@ pub fn request_certificate(
let order = http::finalize_order(endpoint, root_certs, &data_builder, &order.finalize) let order = http::finalize_order(endpoint, root_certs, &data_builder, &order.finalize)
.map_err(HttpError::in_err)?; .map_err(HttpError::in_err)?;
if let Some(e) = order.get_error() { if let Some(e) = order.get_error() {
cert.warn(&e.prefix("Error").message);
cert.warn(&e.prefix("error").message);
} }
// Pool the order in order to see whether or not it is valid // Pool the order in order to see whether or not it is valid
@ -209,14 +209,14 @@ pub fn request_certificate(
// Download the certificate // Download the certificate
let crt_url = order let crt_url = order
.certificate .certificate
.ok_or_else(|| Error::from("No certificate available for download."))?;
.ok_or_else(|| Error::from("no certificate available for download"))?;
let data_builder = set_empty_data_builder!(account, endpoint_name); let data_builder = set_empty_data_builder!(account, endpoint_name);
let crt = http::get_certificate(endpoint, root_certs, &data_builder, &crt_url) let crt = http::get_certificate(endpoint, root_certs, &data_builder, &crt_url)
.map_err(HttpError::in_err)?; .map_err(HttpError::in_err)?;
storage::write_certificate(&cert.file_manager, &crt.as_bytes())?; storage::write_certificate(&cert.file_manager, &crt.as_bytes())?;
cert.info(&format!( cert.info(&format!(
"Certificate renewed (identifiers: {})",
"certificate renewed (identifiers: {})",
cert.identifier_list() cert.identifier_list()
)); ));
Ok(()) Ok(())

23
acmed/src/acme_proto/account.rs

@ -15,8 +15,10 @@ macro_rules! create_account_if_does_not_exist {
Err(he) => match he { Err(he) => match he {
HttpError::ApiError(ref e) => match e.get_acme_type() { HttpError::ApiError(ref e) => match e.get_acme_type() {
AcmeError::AccountDoesNotExist => { AcmeError::AccountDoesNotExist => {
let msg =
format!("account has been dropped by endpoint {}", $endpoint.name);
let msg = format!(
"account has been dropped by endpoint \"{}\"",
$endpoint.name
);
$account.debug(&msg); $account.debug(&msg);
return register_account($endpoint, $root_certs, $account); return register_account($endpoint, $root_certs, $account);
} }
@ -34,7 +36,7 @@ pub fn register_account(
account: &mut BaseAccount, account: &mut BaseAccount,
) -> Result<(), Error> { ) -> Result<(), Error> {
account.debug(&format!( account.debug(&format!(
"creating account on endpoint {}...",
"creating account on endpoint \"{}\"...",
&endpoint.name &endpoint.name
)); ));
let account_struct = Account::new(account, endpoint); let account_struct = Account::new(account, endpoint);
@ -48,7 +50,7 @@ pub fn register_account(
http::new_account(endpoint, root_certs, &data_builder).map_err(HttpError::in_err)?; http::new_account(endpoint, root_certs, &data_builder).map_err(HttpError::in_err)?;
account.set_account_url(&endpoint.name, &account_url)?; account.set_account_url(&endpoint.name, &account_url)?;
let msg = format!( let msg = format!(
"endpoint {}: account {}: the server has not provided an order URL upon account creation",
"endpoint \"{}\": account \"{}\": the server has not provided an order URL upon account creation",
&endpoint.name, &account.name &endpoint.name, &account.name
); );
let order_url = acc_rep.orders.ok_or_else(|| Error::from(&msg))?; let order_url = acc_rep.orders.ok_or_else(|| Error::from(&msg))?;
@ -56,7 +58,10 @@ pub fn register_account(
account.update_key_hash(&endpoint.name)?; account.update_key_hash(&endpoint.name)?;
account.update_contacts_hash(&endpoint.name)?; account.update_contacts_hash(&endpoint.name)?;
account.save()?; account.save()?;
account.info(&format!("account created on endpoint {}", &endpoint.name));
account.info(&format!(
"account created on endpoint \"{}\"",
&endpoint.name
));
Ok(()) Ok(())
} }
@ -67,7 +72,7 @@ pub fn update_account_contacts(
) -> Result<(), Error> { ) -> Result<(), Error> {
let endpoint_name = endpoint.name.clone(); let endpoint_name = endpoint.name.clone();
account.debug(&format!( account.debug(&format!(
"updating account contacts on endpoint {}...",
"updating account contacts on endpoint \"{}\"...",
&endpoint_name &endpoint_name
)); ));
let new_contacts: Vec<String> = account.contacts.iter().map(|c| c.to_string()).collect(); let new_contacts: Vec<String> = account.contacts.iter().map(|c| c.to_string()).collect();
@ -84,7 +89,7 @@ pub fn update_account_contacts(
account.update_contacts_hash(&endpoint_name)?; account.update_contacts_hash(&endpoint_name)?;
account.save()?; account.save()?;
account.info(&format!( account.info(&format!(
"account contacts updated on endpoint {}",
"account contacts updated on endpoint \"{}\"",
&endpoint_name &endpoint_name
)); ));
Ok(()) Ok(())
@ -97,7 +102,7 @@ pub fn update_account_key(
) -> Result<(), Error> { ) -> Result<(), Error> {
let endpoint_name = endpoint.name.clone(); let endpoint_name = endpoint.name.clone();
account.debug(&format!( account.debug(&format!(
"updating account key on endpoint {}...",
"updating account key on endpoint \"{}\"...",
&endpoint_name &endpoint_name
)); ));
let url = endpoint.dir.key_change.clone(); let url = endpoint.dir.key_change.clone();
@ -132,7 +137,7 @@ pub fn update_account_key(
account.update_key_hash(&endpoint_name)?; account.update_key_hash(&endpoint_name)?;
account.save()?; account.save()?;
account.info(&format!( account.info(&format!(
"account key updated on endpoint {}",
"account key updated on endpoint \"{}\"",
&endpoint_name &endpoint_name
)); ));
Ok(()) Ok(())

8
acmed/src/acme_proto/http.rs

@ -55,7 +55,7 @@ where
let acc_uri = response let acc_uri = response
.headers() .headers()
.get(http::HEADER_LOCATION) .get(http::HEADER_LOCATION)
.ok_or_else(|| Error::from("No account location found."))?;
.ok_or_else(|| Error::from("no account location found"))?;
let acc_uri = http::header_to_string(&acc_uri)?; let acc_uri = http::header_to_string(&acc_uri)?;
let acc_resp = response.json::<AccountResponse>()?; let acc_resp = response.json::<AccountResponse>()?;
Ok((acc_resp, acc_uri)) Ok((acc_resp, acc_uri))
@ -74,7 +74,7 @@ where
let order_uri = response let order_uri = response
.headers() .headers()
.get(http::HEADER_LOCATION) .get(http::HEADER_LOCATION)
.ok_or_else(|| Error::from("No order location found."))?;
.ok_or_else(|| Error::from("no order location found"))?;
let order_uri = http::header_to_string(&order_uri)?; let order_uri = http::header_to_string(&order_uri)?;
let order_resp = response.json::<Order>()?; let order_resp = response.json::<Order>()?;
Ok((order_resp, order_uri)) Ok((order_resp, order_uri))
@ -107,7 +107,7 @@ where
{ {
pool_object!( pool_object!(
Authorization, Authorization,
"Authorization",
"authorization",
endpoint, endpoint,
root_certs, root_certs,
url, url,
@ -129,7 +129,7 @@ where
{ {
pool_object!( pool_object!(
Order, Order,
"Order",
"order",
endpoint, endpoint,
root_certs, root_certs,
url, url,

50
acmed/src/acme_proto/structs/error.rs

@ -73,31 +73,31 @@ impl From<String> for AcmeError {
impl fmt::Display for AcmeError { impl fmt::Display for AcmeError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = match self { let msg = match self {
AcmeError::AccountDoesNotExist => "The request specified an account that does not exist",
AcmeError::AlreadyRevoked => "The request specified a certificate to be revoked that has already been revoked",
AcmeError::BadCSR => "The CSR is unacceptable (e.g., due to a short key)",
AcmeError::BadNonce => "The client sent an unacceptable anti-replay nonce",
AcmeError::BadPublicKey => "The JWS was signed by a public key the server does not support",
AcmeError::BadRevocationReason => "The revocation reason provided is not allowed by the server",
AcmeError::BadSignatureAlgorithm => "The JWS was signed with an algorithm the server does not support",
AcmeError::AccountDoesNotExist => "the request specified an account that does not exist",
AcmeError::AlreadyRevoked => "the request specified a certificate to be revoked that has already been revoked",
AcmeError::BadCSR => "the CSR is unacceptable (e.g., due to a short key)",
AcmeError::BadNonce => "the client sent an unacceptable anti-replay nonce",
AcmeError::BadPublicKey => "the JWS was signed by a public key the server does not support",
AcmeError::BadRevocationReason => "the revocation reason provided is not allowed by the server",
AcmeError::BadSignatureAlgorithm => "the JWS was signed with an algorithm the server does not support",
AcmeError::Caa => "Certification Authority Authorization (CAA) records forbid the CA from issuing a certificate", AcmeError::Caa => "Certification Authority Authorization (CAA) records forbid the CA from issuing a certificate",
AcmeError::Compound => "Specific error conditions are indicated in the \"subproblems\" array",
AcmeError::Connection => "The server could not connect to validation target",
AcmeError::Dns => "There was a problem with a DNS query during identifier validation",
AcmeError::ExternalAccountRequired => "The request must include a value for the \"externalAccountBinding\" field",
AcmeError::IncorrectResponse => "Response received didn't match the challenge's requirements",
AcmeError::InvalidContact => "A contact URL for an account was invalid",
AcmeError::Malformed => "The request message was malformed",
AcmeError::OrderNotReady => "The request attempted to finalize an order that is not ready to be finalized",
AcmeError::RateLimited => "The request exceeds a rate limit",
AcmeError::RejectedIdentifier => "The server will not issue certificates for the identifier",
AcmeError::ServerInternal => "The server experienced an internal error",
AcmeError::Tls => "The server received a TLS error during validation",
AcmeError::Unauthorized => "The client lacks sufficient authorization",
AcmeError::UnsupportedContact => "A contact URL for an account used an unsupported protocol scheme",
AcmeError::UnsupportedIdentifier => "An identifier is of an unsupported type",
AcmeError::UserActionRequired => "Visit the \"instance\" URL and take actions specified there",
AcmeError::Unknown => "Unknown error",
AcmeError::Compound => "specific error conditions are indicated in the \"subproblems\" array",
AcmeError::Connection => "the server could not connect to validation target",
AcmeError::Dns => "there was a problem with a DNS query during identifier validation",
AcmeError::ExternalAccountRequired => "the request must include a value for the \"externalAccountBinding\" field",
AcmeError::IncorrectResponse => "response received didn't match the challenge's requirements",
AcmeError::InvalidContact => "a contact URL for an account was invalid",
AcmeError::Malformed => "the request message was malformed",
AcmeError::OrderNotReady => "the request attempted to finalize an order that is not ready to be finalized",
AcmeError::RateLimited => "the request exceeds a rate limit",
AcmeError::RejectedIdentifier => "the server will not issue certificates for the identifier",
AcmeError::ServerInternal => "the server experienced an internal error",
AcmeError::Tls => "the server received a TLS error during validation",
AcmeError::Unauthorized => "the client lacks sufficient authorization",
AcmeError::UnsupportedContact => "a contact URL for an account used an unsupported protocol scheme",
AcmeError::UnsupportedIdentifier => "an identifier is of an unsupported type",
AcmeError::UserActionRequired => "visit the \"instance\" URL and take actions specified there",
AcmeError::Unknown => "unknown error",
}; };
write!(f, "{}", msg) write!(f, "{}", msg)
} }
@ -147,7 +147,7 @@ impl fmt::Display for HttpApiError {
.to_owned() .to_owned()
.unwrap_or_else(|| self.get_acme_type().to_string()); .unwrap_or_else(|| self.get_acme_type().to_string());
let msg = match self.status { let msg = match self.status {
Some(s) => format!("Status {}: {}", s, msg),
Some(s) => format!("status {}: {}", s, msg),
None => msg, None => msg,
}; };
write!(f, "{}", msg) write!(f, "{}", msg)

14
acmed/src/certificate.rs

@ -70,7 +70,7 @@ impl Certificate {
fn is_expiring(&self, cert: &X509Certificate) -> Result<bool, Error> { fn is_expiring(&self, cert: &X509Certificate) -> Result<bool, Error> {
let expires_in = cert.expires_in()?; let expires_in = cert.expires_in()?;
self.debug(&format!( self.debug(&format!(
"Certificate expires in {} days ({} days delay)",
"certificate expires in {} days ({} days delay)",
expires_in.as_secs() / 86400, expires_in.as_secs() / 86400,
self.renew_delay.as_secs() / 86400, self.renew_delay.as_secs() / 86400,
)); ));
@ -92,7 +92,7 @@ impl Certificate {
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(", "); .join(", ");
self.debug(&format!( self.debug(&format!(
"The certificate does not include the following domains: {}",
"the certificate does not include the following domains: {}",
domains domains
)); ));
} }
@ -110,7 +110,7 @@ impl Certificate {
pub fn should_renew(&self) -> Result<bool, Error> { pub fn should_renew(&self) -> Result<bool, Error> {
self.debug(&format!( self.debug(&format!(
"Checking for renewal (identifiers: {})",
"checking for renewal (identifiers: {})",
self.identifier_list() self.identifier_list()
)); ));
if !certificate_files_exists(&self.file_manager) { if !certificate_files_exists(&self.file_manager) {
@ -121,18 +121,18 @@ impl Certificate {
let renew_ident = self.has_missing_identifiers(&cert); let renew_ident = self.has_missing_identifiers(&cert);
if renew_ident { if renew_ident {
self.debug("The current certificate doesn't include all the required identifiers.");
self.debug("the current certificate doesn't include all the required identifiers");
} }
let renew_exp = self.is_expiring(&cert)?; let renew_exp = self.is_expiring(&cert)?;
if renew_exp { if renew_exp {
self.debug("The certificate is expiring.");
self.debug("the certificate is expiring");
} }
let renew = renew_ident || renew_exp; let renew = renew_ident || renew_exp;
if renew { if renew {
self.debug("The certificate will be renewed now");
self.debug("the certificate will be renewed now");
} else { } else {
self.debug("The certificate will not be renewed now");
self.debug("the certificate will not be renewed now");
} }
Ok(renew) Ok(renew)
} }

12
acmed/src/config.rs

@ -28,7 +28,7 @@ fn get_stdin(hook: &Hook) -> Result<hooks::HookStdin, Error> {
Some(file) => match &hook.stdin_str { Some(file) => match &hook.stdin_str {
Some(_) => { Some(_) => {
let msg = format!( let msg = format!(
"{}: A hook cannot have both stdin and stdin_str",
"{}: a hook cannot have both stdin and stdin_str",
&hook.name &hook.name
); );
Err(msg.into()) Err(msg.into())
@ -388,7 +388,7 @@ impl Certificate {
let id = self let id = self
.identifiers .identifiers
.first() .first()
.ok_or_else(|| Error::from("Certificate has no identifiers."))?;
.ok_or_else(|| Error::from("certificate has no identifiers"))?;
id.to_string() id.to_string()
} }
}; };
@ -423,7 +423,7 @@ impl Certificate {
return Ok(endpoint.clone()); return Ok(endpoint.clone());
} }
} }
Err(format!("{}: unknown endpoint.", self.endpoint).into())
Err(format!("{}: unknown endpoint", self.endpoint).into())
} }
pub fn get_endpoint(&self, cnf: &Config) -> Result<crate::endpoint::Endpoint, Error> { pub fn get_endpoint(&self, cnf: &Config) -> Result<crate::endpoint::Endpoint, Error> {
@ -497,7 +497,7 @@ impl Identifier {
None => match &self.ip { None => match &self.ip {
Some(ip) => (IdentifierType::Ip, ip), Some(ip) => (IdentifierType::Ip, ip),
None => { None => {
return Err("No identifier found.".into());
return Err("no identifier found".into());
} }
}, },
}; };
@ -533,7 +533,7 @@ fn get_cnf_path(from: &PathBuf, file: &str) -> Result<Vec<PathBuf>, Error> {
.collect::<Vec<PathBuf>>(); .collect::<Vec<PathBuf>>();
if g.is_empty() { if g.is_empty() {
log::warn!( log::warn!(
"Pattern `{}` (expanded as `{}`): no matching configuration file found.",
"pattern `{}` (expanded as `{}`): no matching configuration file found",
file, file,
raw_path raw_path
); );
@ -542,7 +542,7 @@ fn get_cnf_path(from: &PathBuf, file: &str) -> Result<Vec<PathBuf>, Error> {
} }
fn read_cnf(path: &PathBuf) -> Result<Config, Error> { fn read_cnf(path: &PathBuf) -> Result<Config, Error> {
info!("Loading configuration file: {}", path.display());
info!("loading configuration file: {}", path.display());
let mut file = let mut file =
File::open(path).map_err(|e| Error::from(e).prefix(&path.display().to_string()))?; File::open(path).map_err(|e| Error::from(e).prefix(&path.display().to_string()))?;
let mut contents = String::new(); let mut contents = String::new();

29
acmed/src/hooks.rs

@ -106,7 +106,10 @@ macro_rules! get_hook_output {
match $out { match $out {
Some(path) => { Some(path) => {
let path = $reg.render_template(path, $data)?; let path = $reg.render_template(path, $data)?;
$logger.trace(&format!("Hook {}: {}: {}", $hook_name, $out_name, &path));
$logger.trace(&format!(
"hook \"{}\": {}: {}",
$hook_name, $out_name, &path
));
let file = File::create(&path)?; let file = File::create(&path)?;
Stdio::from(file) Stdio::from(file)
} }
@ -120,7 +123,7 @@ where
L: HasLogger, L: HasLogger,
T: Clone + HookEnvData + Serialize, T: Clone + HookEnvData + Serialize,
{ {
logger.debug(&format!("Calling hook: {}", hook.name));
logger.debug(&format!("calling hook \"{}\"", hook.name));
let reg = Handlebars::new(); let reg = Handlebars::new();
let mut v = vec![]; let mut v = vec![];
let args = match &hook.args { let args = match &hook.args {
@ -133,8 +136,8 @@ where
} }
None => &[], None => &[],
}; };
logger.trace(&format!("Hook {}: cmd: {}", hook.name, hook.cmd));
logger.trace(&format!("Hook {}: args: {:?}", hook.name, args));
logger.trace(&format!("hook \"{}\": cmd: {}", hook.name, hook.cmd));
logger.trace(&format!("hook \"{}\": args: {:?}", hook.name, args));
let mut cmd = Command::new(&hook.cmd) let mut cmd = Command::new(&hook.cmd)
.envs(data.get_env()) .envs(data.get_env())
.args(args) .args(args)
@ -162,13 +165,19 @@ where
match &hook.stdin { match &hook.stdin {
HookStdin::Str(s) => { HookStdin::Str(s) => {
let data_in = reg.render_template(&s, &data)?; let data_in = reg.render_template(&s, &data)?;
logger.trace(&format!("Hook {}: string stdin: {}", hook.name, &data_in));
logger.trace(&format!(
"hook \"{}\": string stdin: {}",
hook.name, &data_in
));
let stdin = cmd.stdin.as_mut().ok_or("stdin not found")?; let stdin = cmd.stdin.as_mut().ok_or("stdin not found")?;
stdin.write_all(data_in.as_bytes())?; stdin.write_all(data_in.as_bytes())?;
} }
HookStdin::File(f) => { HookStdin::File(f) => {
let file_name = reg.render_template(&f, &data)?; let file_name = reg.render_template(&f, &data)?;
logger.trace(&format!("Hook {}: file stdin: {}", hook.name, &file_name));
logger.trace(&format!(
"hook \"{}\": file stdin: {}",
hook.name, &file_name
));
let stdin = cmd.stdin.as_mut().ok_or("stdin not found")?; let stdin = cmd.stdin.as_mut().ok_or("stdin not found")?;
let file = File::open(&file_name)?; let file = File::open(&file_name)?;
let buf_reader = BufReader::new(file); let buf_reader = BufReader::new(file);
@ -183,14 +192,14 @@ where
let status = cmd.wait()?; let status = cmd.wait()?;
if !status.success() && !hook.allow_failure { if !status.success() && !hook.allow_failure {
let msg = match status.code() { let msg = match status.code() {
Some(code) => format!("Unrecoverable failure: code {}", code).into(),
None => "Unrecoverable failure".into(),
Some(code) => format!("unrecoverable failure: code {}", code).into(),
None => "unrecoverable failure".into(),
}; };
return Err(msg); return Err(msg);
} }
match status.code() { match status.code() {
Some(code) => logger.debug(&format!("Hook {}: exited: code {}", hook.name, code)),
None => logger.debug(&format!("Hook {}: exited", hook.name)),
Some(code) => logger.debug(&format!("hook \"{}\": exited: code {}", hook.name, code)),
None => logger.debug(&format!("hook \"{}\": exited", hook.name)),
}; };
Ok(()) Ok(())
} }

4
acmed/src/http.rs

@ -100,7 +100,7 @@ fn rate_limit(endpoint: &mut Endpoint) {
pub fn header_to_string(header_value: &header::HeaderValue) -> Result<String, Error> { pub fn header_to_string(header_value: &header::HeaderValue) -> Result<String, Error> {
let s = header_value let s = header_value
.to_str() .to_str()
.map_err(|_| Error::from("Invalid nonce format."))?;
.map_err(|_| Error::from("invalid nonce format"))?;
Ok(s.to_string()) Ok(s.to_string())
} }
@ -177,7 +177,7 @@ where
} }
thread::sleep(time::Duration::from_secs(crate::DEFAULT_HTTP_FAIL_WAIT_SEC)); thread::sleep(time::Duration::from_secs(crate::DEFAULT_HTTP_FAIL_WAIT_SEC));
} }
Err("Too much errors, will not retry".into())
Err("too much errors, will not retry".into())
} }
pub fn post_jose<F>( pub fn post_jose<F>(

2
acmed/src/identifier.rs

@ -64,7 +64,7 @@ impl Identifier {
let challenge = Challenge::from_str(challenge)?; let challenge = Challenge::from_str(challenge)?;
if !id_type.supported_challenges().contains(&challenge) { if !id_type.supported_challenges().contains(&challenge) {
let msg = format!( let msg = format!(
"Challenge {} cannot be used with identifier of type {}",
"challenge {} cannot be used with identifier of type {}",
challenge, id_type challenge, id_type
); );
return Err(msg.into()); return Err(msg.into());

10
acmed/src/main_event_loop.rs

@ -22,9 +22,9 @@ fn renew_certificate(
account: &mut Account, account: &mut Account,
) { ) {
let (status, is_success) = match request_certificate(crt, root_certs, endpoint, account) { let (status, is_success) = match request_certificate(crt, root_certs, endpoint, account) {
Ok(_) => ("Success.".to_string(), true),
Ok(_) => ("success".to_string(), true),
Err(e) => { Err(e) => {
let e = e.prefix("Unable to renew the certificate");
let e = e.prefix("unable to renew the certificate");
crt.warn(&e.message); crt.warn(&e.message);
(e.message, false) (e.message, false)
} }
@ -32,7 +32,7 @@ fn renew_certificate(
match crt.call_post_operation_hooks(&status, is_success) { match crt.call_post_operation_hooks(&status, is_success) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
let e = e.prefix("Post-operation hook error");
let e = e.prefix("post-operation hook error");
crt.warn(&e.message); crt.warn(&e.message);
} }
}; };
@ -144,7 +144,7 @@ impl MainEventLoop {
match accounts.get_mut(&crt.account) { match accounts.get_mut(&crt.account) {
Some(acc) => acc.add_endpoint_name(&endpoint_name), Some(acc) => acc.add_endpoint_name(&endpoint_name),
None => { None => {
let msg = format!("{}: account not found.", &crt.account);
let msg = format!("{}: account not found", &crt.account);
return Err(msg.into()); return Err(msg.into());
} }
}; };
@ -152,8 +152,6 @@ impl MainEventLoop {
certs.push(cert); certs.push(cert);
} }
// TODO: call .synchronize() on every account
Ok(MainEventLoop { Ok(MainEventLoop {
certs, certs,
root_certs: root_certs.iter().map(|v| (*v).to_string()).collect(), root_certs: root_certs.iter().map(|v| (*v).to_string()).collect(),

10
acmed/src/storage.rs

@ -115,7 +115,7 @@ fn get_file_path(fm: &FileManager, file_type: FileType) -> Result<PathBuf, Error
} }
fn read_file(fm: &FileManager, path: &PathBuf) -> Result<Vec<u8>, Error> { fn read_file(fm: &FileManager, path: &PathBuf) -> Result<Vec<u8>, Error> {
fm.trace(&format!("Reading file {:?}", path));
fm.trace(&format!("reading file {:?}", path));
let mut file = File::open(path)?; let mut file = File::open(path)?;
let mut contents = vec![]; let mut contents = vec![];
file.read_to_end(&mut contents)?; file.read_to_end(&mut contents)?;
@ -137,7 +137,7 @@ fn set_owner(fm: &FileManager, path: &PathBuf, file_type: FileType) -> Result<()
if u.bytes().all(|b| b.is_ascii_digit()) { if u.bytes().all(|b| b.is_ascii_digit()) {
let raw_uid = u let raw_uid = u
.parse::<u32>() .parse::<u32>()
.map_err(|_| Error::from("Unable to parse the UID"))?;
.map_err(|_| Error::from("unable to parse the UID"))?;
let nix_uid = nix::unistd::Uid::from_raw(raw_uid); let nix_uid = nix::unistd::Uid::from_raw(raw_uid);
Some(nix_uid) Some(nix_uid)
} else { } else {
@ -152,7 +152,7 @@ fn set_owner(fm: &FileManager, path: &PathBuf, file_type: FileType) -> Result<()
if g.bytes().all(|b| b.is_ascii_digit()) { if g.bytes().all(|b| b.is_ascii_digit()) {
let raw_gid = g let raw_gid = g
.parse::<u32>() .parse::<u32>()
.map_err(|_| Error::from("Unable to parse the GID"))?;
.map_err(|_| Error::from("unable to parse the GID"))?;
let nix_gid = nix::unistd::Gid::from_raw(raw_gid); let nix_gid = nix::unistd::Gid::from_raw(raw_gid);
Some(nix_gid) Some(nix_gid)
} else { } else {
@ -193,7 +193,7 @@ fn write_file(fm: &FileManager, file_type: FileType, data: &[u8]) -> Result<(),
hooks::call(fm, &fm.hooks, &hook_data, HookType::FilePreEdit)?; hooks::call(fm, &fm.hooks, &hook_data, HookType::FilePreEdit)?;
} }
fm.trace(&format!("Writing file {:?}", path));
fm.trace(&format!("writing file {:?}", path));
let mut file = if cfg!(unix) { let mut file = if cfg!(unix) {
let mut options = OpenOptions::new(); let mut options = OpenOptions::new();
options.mode(match &file_type { options.mode(match &file_type {
@ -259,7 +259,7 @@ fn check_files(fm: &FileManager, file_types: &[FileType]) -> bool {
} }
}; };
fm.trace(&format!( fm.trace(&format!(
"Testing file path: {}",
"testing file path: {}",
path.to_str().unwrap_or_default() path.to_str().unwrap_or_default()
)); ));
if !path.is_file() { if !path.is_file() {

4
tacd/src/main.rs

@ -33,7 +33,7 @@ fn get_acme_value(cnf: &ArgMatches, opt: &str, opt_file: &str) -> Result<String,
Some(v) => Ok(v.to_string()), Some(v) => Ok(v.to_string()),
None => { None => {
debug!( debug!(
"Reading {} from {}",
"reading {} from {}",
opt, opt,
cnf.value_of(opt_file).unwrap_or("stdin") cnf.value_of(opt_file).unwrap_or("stdin")
); );
@ -61,7 +61,7 @@ fn init(cnf: &ArgMatches) -> Result<(), Error> {
None => DEFAULT_CRT_DIGEST, None => DEFAULT_CRT_DIGEST,
}; };
let (pk, cert) = X509Certificate::from_acme_ext(&domain, &ext, crt_signature_alg, crt_digest)?; let (pk, cert) = X509Certificate::from_acme_ext(&domain, &ext, crt_signature_alg, crt_digest)?;
info!("Starting {} on {} for {}", APP_NAME, listen_addr, domain);
info!("starting {} on {} for {}", APP_NAME, listen_addr, domain);
server_start(listen_addr, &cert, &pk)?; server_start(listen_addr, &cert, &pk)?;
Ok(()) Ok(())
} }

8
tacd/src/openssl_server.rs

@ -21,7 +21,7 @@ macro_rules! listen_and_accept {
if let Ok(stream) = stream { if let Ok(stream) = stream {
let acceptor = $acceptor.clone(); let acceptor = $acceptor.clone();
thread::spawn(move || { thread::spawn(move || {
debug!("New client");
debug!("new client");
let _ = acceptor.accept(stream).unwrap(); let _ = acceptor.accept(stream).unwrap();
}); });
}; };
@ -45,11 +45,11 @@ pub fn start(
let acceptor = Arc::new(acceptor.build()); let acceptor = Arc::new(acceptor.build());
if cfg!(unix) && listen_addr.starts_with("unix:") { if cfg!(unix) && listen_addr.starts_with("unix:") {
let listen_addr = &listen_addr[5..]; let listen_addr = &listen_addr[5..];
debug!("Listening on unix socket {}", listen_addr);
debug!("listening on unix socket {}", listen_addr);
listen_and_accept!(UnixListener, listen_addr, acceptor); listen_and_accept!(UnixListener, listen_addr, acceptor);
} else { } else {
debug!("Listening on {}", listen_addr);
debug!("listening on {}", listen_addr);
listen_and_accept!(TcpListener, listen_addr, acceptor); listen_and_accept!(TcpListener, listen_addr, acceptor);
} }
Err("Main thread loop unexpectedly exited".into())
Err("main thread loop unexpectedly exited".into())
} }
Loading…
Cancel
Save