Browse Source

Inline the format args

pull/88/head
Rodolphe Bréard 2 years ago
parent
commit
e900138503
  1. 4
      acme_common/src/crypto.rs
  2. 4
      acme_common/src/crypto/jws_signature_algorithm.rs
  3. 7
      acme_common/src/crypto/key_type.rs
  4. 6
      acme_common/src/crypto/openssl_keys.rs
  5. 4
      acme_common/src/crypto/openssl_version.rs
  6. 30
      acme_common/src/error.rs
  7. 4
      acme_common/src/lib.rs
  8. 2
      acme_common/src/logs.rs
  9. 17
      acmed/src/account.rs
  10. 4
      acmed/src/account/contact.rs
  11. 8
      acmed/src/account/storage.rs
  12. 4
      acmed/src/acme_proto.rs
  13. 12
      acmed/src/acme_proto/account.rs
  14. 15
      acmed/src/acme_proto/structs/authorization.rs
  15. 6
      acmed/src/acme_proto/structs/error.rs
  16. 2
      acmed/src/acme_proto/structs/order.rs
  17. 13
      acmed/src/certificate.rs
  18. 18
      acmed/src/config.rs
  19. 4
      acmed/src/duration.rs
  20. 21
      acmed/src/hooks.rs
  21. 8
      acmed/src/http.rs
  22. 14
      acmed/src/identifier.rs
  23. 6
      acmed/src/jws.rs
  24. 7
      acmed/src/main.rs
  25. 2
      acmed/src/main_event_loop.rs
  26. 26
      acmed/src/storage.rs
  27. 2
      tacd/build.rs
  28. 12
      tacd/src/main.rs
  29. 4
      tacd/src/openssl_server.rs

4
acme_common/src/crypto.rs

@ -63,7 +63,7 @@ impl FromStr for BaseHashFunction {
"sha256" => Ok(BaseHashFunction::Sha256), "sha256" => Ok(BaseHashFunction::Sha256),
"sha384" => Ok(BaseHashFunction::Sha384), "sha384" => Ok(BaseHashFunction::Sha384),
"sha512" => Ok(BaseHashFunction::Sha512), "sha512" => Ok(BaseHashFunction::Sha512),
_ => Err(format!("{}: unknown hash function.", s).into()),
_ => Err(format!("{s}: unknown hash function.").into()),
} }
} }
} }
@ -75,7 +75,7 @@ impl fmt::Display for BaseHashFunction {
BaseHashFunction::Sha384 => "sha384", BaseHashFunction::Sha384 => "sha384",
BaseHashFunction::Sha512 => "sha512", BaseHashFunction::Sha512 => "sha512",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

4
acme_common/src/crypto/jws_signature_algorithm.rs

@ -33,7 +33,7 @@ impl FromStr for JwsSignatureAlgorithm {
"ed25519" => Ok(JwsSignatureAlgorithm::Ed25519), "ed25519" => Ok(JwsSignatureAlgorithm::Ed25519),
#[cfg(ed448)] #[cfg(ed448)]
"ed448" => Ok(JwsSignatureAlgorithm::Ed448), "ed448" => Ok(JwsSignatureAlgorithm::Ed448),
_ => Err(format!("{}: unknown algorithm.", s).into()),
_ => Err(format!("{s}: unknown algorithm.").into()),
} }
} }
} }
@ -53,7 +53,7 @@ impl fmt::Display for JwsSignatureAlgorithm {
#[cfg(ed448)] #[cfg(ed448)]
JwsSignatureAlgorithm::Ed448 => "Ed448", JwsSignatureAlgorithm::Ed448 => "Ed448",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

7
acme_common/src/crypto/key_type.rs

@ -45,8 +45,7 @@ impl KeyType {
Ok(()) Ok(())
} else { } else {
let err_msg = format!( let err_msg = format!(
"incompatible signature algorithm: {} cannot be used with an {} key",
alg, self
"incompatible signature algorithm: {alg} cannot be used with an {self} key"
); );
Err(err_msg.into()) Err(err_msg.into())
} }
@ -81,7 +80,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!("{s}: unknown algorithm").into()),
} }
} }
} }
@ -99,6 +98,6 @@ impl fmt::Display for KeyType {
#[cfg(ed448)] #[cfg(ed448)]
KeyType::Ed448 => "ed448", KeyType::Ed448 => "ed448",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

6
acme_common/src/crypto/openssl_keys.rs

@ -104,8 +104,8 @@ impl KeyPair {
JwsSignatureAlgorithm::Hs256 JwsSignatureAlgorithm::Hs256
| JwsSignatureAlgorithm::Hs384 | JwsSignatureAlgorithm::Hs384
| JwsSignatureAlgorithm::Hs512 => Err(format!( | JwsSignatureAlgorithm::Hs512 => Err(format!(
"{} key pair cannot be used for the {} signature algorithm",
self.key_type, alg
"{} key pair cannot be used for the {alg} signature algorithm",
self.key_type
) )
.into()), .into()),
JwsSignatureAlgorithm::Rs256 => self.sign_rsa(&MessageDigest::sha256(), data), JwsSignatureAlgorithm::Rs256 => self.sign_rsa(&MessageDigest::sha256(), data),
@ -336,7 +336,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_type} key pair")))?;
let key_pair = KeyPair { let key_pair = KeyPair {
key_type, key_type,
inner_key: priv_key, inner_key: priv_key,

4
acme_common/src/crypto/openssl_version.rs

@ -7,14 +7,14 @@ pub fn get_lib_version() -> String {
let mut version = vec![]; let mut version = vec![];
for i in 0..3 { for i in 0..3 {
let n = get_openssl_version_unit(v, i); let n = get_openssl_version_unit(v, i);
version.push(format!("{}", n));
version.push(format!("{n}"));
} }
let version = version.join("."); let version = version.join(".");
let p = get_openssl_version_unit(v, 3); let p = get_openssl_version_unit(v, 3);
if p != 0 { if p != 0 {
let p = p + 0x60; let p = p + 0x60;
let p = std::char::from_u32(p as u32).unwrap(); let p = std::char::from_u32(p as u32).unwrap();
format!("{}{}", version, p)
format!("{version}{p}")
} else { } else {
version version
} }

30
acme_common/src/error.rs

@ -8,7 +8,7 @@ pub struct Error {
impl Error { impl Error {
pub fn prefix(&self, prefix: &str) -> Self { pub fn prefix(&self, prefix: &str) -> Self {
Error { Error {
message: format!("{}: {}", prefix, &self.message),
message: format!("{prefix}: {}", &self.message),
} }
} }
} }
@ -41,25 +41,25 @@ impl From<&String> for Error {
impl From<std::io::Error> for Error { impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self { fn from(error: std::io::Error) -> Self {
format!("IO error: {}", error).into()
format!("IO error: {error}").into()
} }
} }
impl From<std::net::AddrParseError> for Error { impl From<std::net::AddrParseError> for Error {
fn from(error: std::net::AddrParseError) -> Self { fn from(error: std::net::AddrParseError) -> Self {
format!("{}", error).into()
format!("{error}").into()
} }
} }
impl From<std::string::FromUtf8Error> for Error { impl From<std::string::FromUtf8Error> for Error {
fn from(error: std::string::FromUtf8Error) -> Self { fn from(error: std::string::FromUtf8Error) -> Self {
format!("UTF-8 error: {}", error).into()
format!("UTF-8 error: {error}").into()
} }
} }
impl From<std::sync::mpsc::RecvError> for Error { impl From<std::sync::mpsc::RecvError> for Error {
fn from(error: std::sync::mpsc::RecvError) -> Self { fn from(error: std::sync::mpsc::RecvError) -> Self {
format!("MSPC receiver error: {}", error).into()
format!("MSPC receiver error: {error}").into()
} }
} }
@ -71,63 +71,63 @@ impl From<std::time::SystemTimeError> for Error {
impl From<base64::DecodeError> for Error { impl From<base64::DecodeError> for Error {
fn from(error: base64::DecodeError) -> Self { fn from(error: base64::DecodeError) -> Self {
format!("base 64 decode error: {}", error).into()
format!("base 64 decode error: {error}").into()
} }
} }
impl From<syslog::Error> for Error { impl From<syslog::Error> for Error {
fn from(error: syslog::Error) -> Self { fn from(error: syslog::Error) -> Self {
format!("syslog error: {}", error).into()
format!("syslog error: {error}").into()
} }
} }
impl From<toml::de::Error> for Error { impl From<toml::de::Error> for Error {
fn from(error: toml::de::Error) -> Self { fn from(error: toml::de::Error) -> Self {
format!("IO error: {}", error).into()
format!("IO error: {error}").into()
} }
} }
impl From<serde_json::error::Error> for Error { impl From<serde_json::error::Error> for Error {
fn from(error: serde_json::error::Error) -> Self { fn from(error: serde_json::error::Error) -> Self {
format!("IO error: {}", error).into()
format!("IO error: {error}").into()
} }
} }
impl From<attohttpc::Error> for Error { impl From<attohttpc::Error> for Error {
fn from(error: attohttpc::Error) -> Self { fn from(error: attohttpc::Error) -> Self {
format!("HTTP error: {}", error).into()
format!("HTTP error: {error}").into()
} }
} }
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<tinytemplate::error::Error> for Error { impl From<tinytemplate::error::Error> for Error {
fn from(error: tinytemplate::error::Error) -> Self { fn from(error: tinytemplate::error::Error) -> Self {
format!("template error: {}", error).into()
format!("template error: {error}").into()
} }
} }
#[cfg(feature = "crypto_openssl")] #[cfg(feature = "crypto_openssl")]
impl From<native_tls::Error> for Error { impl From<native_tls::Error> for Error {
fn from(error: native_tls::Error) -> Self { fn from(error: native_tls::Error) -> Self {
format!("{}", error).into()
format!("{error}").into()
} }
} }
#[cfg(feature = "crypto_openssl")] #[cfg(feature = "crypto_openssl")]
impl From<openssl::error::ErrorStack> for Error { impl From<openssl::error::ErrorStack> for Error {
fn from(error: openssl::error::ErrorStack) -> Self { fn from(error: openssl::error::ErrorStack) -> Self {
format!("{}", error).into()
format!("{error}").into()
} }
} }
#[cfg(unix)] #[cfg(unix)]
impl From<nix::Error> for Error { impl From<nix::Error> for Error {
fn from(error: nix::Error) -> Self { fn from(error: nix::Error) -> Self {
format!("{}", error).into()
format!("{error}").into()
} }
} }

4
acme_common/src/lib.rs

@ -15,7 +15,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);
} }
} }
@ -32,7 +32,7 @@ pub fn to_idna(domain_name: &str) -> Result<String, error::Error> {
} else { } else {
let idna_name = punycode::encode(&raw_name) let idna_name = punycode::encode(&raw_name)
.map_err(|_| error::Error::from("IDNA encoding failed."))?; .map_err(|_| error::Error::from("IDNA encoding failed."))?;
format!("xn--{}", idna_name)
format!("xn--{idna_name}")
}; };
idna_parts.push(idna_name); idna_parts.push(idna_name);
} }

2
acme_common/src/logs.rs

@ -21,7 +21,7 @@ fn get_loglevel(log_level: Option<&str>) -> Result<LevelFilter, Error> {
"debug" => LevelFilter::Debug, "debug" => LevelFilter::Debug,
"trace" => LevelFilter::Trace, "trace" => LevelFilter::Trace,
_ => { _ => {
return Err(format!("{}: invalid log level", v).into());
return Err(format!("{v}: invalid log level").into());
} }
}, },
None => DEFAULT_LOG_LEVEL, None => DEFAULT_LOG_LEVEL,

17
acmed/src/account.rs

@ -30,7 +30,7 @@ impl FromStr for AccountContactType {
fn from_str(s: &str) -> Result<Self, Error> { fn from_str(s: &str) -> Result<Self, Error> {
match s.to_lowercase().as_str() { match s.to_lowercase().as_str() {
"mailfrom" => Ok(AccountContactType::Mailfrom), "mailfrom" => Ok(AccountContactType::Mailfrom),
_ => Err(format!("{}: unknown contact type.", s).into()),
_ => Err(format!("{s}: unknown contact type.").into()),
} }
} }
} }
@ -40,7 +40,7 @@ impl fmt::Display for AccountContactType {
let s = match self { let s = match self {
AccountContactType::Mailfrom => "mailfrom", AccountContactType::Mailfrom => "mailfrom",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }
@ -97,19 +97,19 @@ pub struct Account {
impl HasLogger for Account { impl HasLogger for Account {
fn warn(&self, msg: &str) { fn warn(&self, msg: &str) {
log::warn!("account \"{}\": {}", &self.name, msg);
log::warn!("account \"{}\": {msg}", &self.name);
} }
fn info(&self, msg: &str) { fn info(&self, msg: &str) {
log::info!("account \"{}\": {}", &self.name, msg);
log::info!("account \"{}\": {msg}", &self.name);
} }
fn debug(&self, msg: &str) { fn debug(&self, msg: &str) {
log::debug!("account \"{}\": {}", &self.name, msg);
log::debug!("account \"{}\": {msg}", &self.name);
} }
fn trace(&self, msg: &str) { fn trace(&self, msg: &str) {
log::trace!("account \"{}\": {}", &self.name, msg);
log::trace!("account \"{}\": {msg}", &self.name);
} }
} }
@ -288,10 +288,7 @@ impl Account {
self.past_keys.push(self.current_key.to_owned()); self.past_keys.push(self.current_key.to_owned());
self.current_key = AccountKey::new(key_type, signature_algorithm)?; self.current_key = AccountKey::new(key_type, signature_algorithm)?;
self.save()?; self.save()?;
let msg = format!(
"new {} account key created, using {} as signing algorithm",
key_type, signature_algorithm
);
let msg = format!("new {key_type} account key created, using {signature_algorithm} as signing algorithm");
self.info(&msg); self.info(&msg);
} else { } else {
self.trace("account key is up to date"); self.trace("account key is up to date");

4
acmed/src/account/contact.rs

@ -36,7 +36,7 @@ impl FromStr for ContactType {
fn from_str(s: &str) -> Result<Self, Error> { fn from_str(s: &str) -> Result<Self, Error> {
match s.to_lowercase().as_str() { match s.to_lowercase().as_str() {
"mailto" => Ok(ContactType::Mailto), "mailto" => Ok(ContactType::Mailto),
_ => Err(format!("{}: unknown contact type.", s).into()),
_ => Err(format!("{s}: unknown contact type.").into()),
} }
} }
} }
@ -46,7 +46,7 @@ impl fmt::Display for ContactType {
let s = match self { let s = match self {
ContactType::Mailto => "mailto", ContactType::Mailto => "mailto",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

8
acmed/src/account/storage.rs

@ -175,14 +175,10 @@ fn do_save(file_manager: &FileManager, account: &Account) -> Result<(), Error> {
pub fn fetch(file_manager: &FileManager, name: &str) -> Result<Option<Account>, Error> { pub fn fetch(file_manager: &FileManager, name: &str) -> Result<Option<Account>, Error> {
do_fetch(file_manager, name).map_err(|_| { do_fetch(file_manager, name).map_err(|_| {
format!(
"account \"{}\": unable to load account file: file may be corrupted",
name
)
.into()
format!("account \"{name}\": unable to load account file: file may be corrupted").into()
}) })
} }
pub fn save(file_manager: &FileManager, account: &Account) -> Result<(), Error> { pub fn save(file_manager: &FileManager, account: &Account) -> Result<(), Error> {
do_save(file_manager, account).map_err(|e| format!("unable to save account file: {}", e).into())
do_save(file_manager, account).map_err(|e| format!("unable to save account file: {e}").into())
} }

4
acmed/src/acme_proto.rs

@ -32,7 +32,7 @@ impl Challenge {
"http-01" => Ok(Challenge::Http01), "http-01" => Ok(Challenge::Http01),
"dns-01" => Ok(Challenge::Dns01), "dns-01" => Ok(Challenge::Dns01),
"tls-alpn-01" => Ok(Challenge::TlsAlpn01), "tls-alpn-01" => Ok(Challenge::TlsAlpn01),
_ => Err(format!("{}: unknown challenge.", s).into()),
_ => Err(format!("{s}: unknown challenge.").into()),
} }
} }
} }
@ -44,7 +44,7 @@ impl fmt::Display for Challenge {
Challenge::Dns01 => "dns-01", Challenge::Dns01 => "dns-01",
Challenge::TlsAlpn01 => "tls-alpn-01", Challenge::TlsAlpn01 => "tls-alpn-01",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

12
acmed/src/acme_proto/account.rs

@ -82,8 +82,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 \"{}\"...",
&endpoint_name
"updating account contacts on endpoint \"{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();
let acc_up_struct = AccountUpdate::new(&new_contacts); let acc_up_struct = AccountUpdate::new(&new_contacts);
@ -98,8 +97,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 \"{}\"",
&endpoint_name
"account contacts updated on endpoint \"{endpoint_name}\""
)); ));
Ok(()) Ok(())
} }
@ -107,8 +105,7 @@ pub fn update_account_contacts(
pub fn update_account_key(endpoint: &mut Endpoint, account: &mut BaseAccount) -> Result<(), Error> { pub fn update_account_key(endpoint: &mut Endpoint, account: &mut BaseAccount) -> 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 \"{}\"...",
&endpoint_name
"updating account key on endpoint \"{endpoint_name}\"..."
)); ));
let url = endpoint.dir.key_change.clone(); let url = endpoint.dir.key_change.clone();
let ep = account.get_endpoint(&endpoint_name)?; let ep = account.get_endpoint(&endpoint_name)?;
@ -142,8 +139,7 @@ pub fn update_account_key(endpoint: &mut Endpoint, account: &mut BaseAccount) ->
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 \"{}\"",
&endpoint_name
"account key updated on endpoint \"{endpoint_name}\""
)); ));
Ok(()) Ok(())
} }

15
acmed/src/acme_proto/structs/authorization.rs

@ -63,7 +63,7 @@ impl fmt::Display for AuthorizationStatus {
AuthorizationStatus::Expired => "expired", AuthorizationStatus::Expired => "expired",
AuthorizationStatus::Revoked => "revoked", AuthorizationStatus::Revoked => "revoked",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }
@ -102,22 +102,19 @@ impl Challenge {
Ok(a) Ok(a)
} }
Challenge::TlsAlpn01(tc) => { Challenge::TlsAlpn01(tc) => {
let acme_ext_name = format!("{}.{}", ACME_OID, ID_PE_ACME_ID);
let acme_ext_name = format!("{ACME_OID}.{ID_PE_ACME_ID}");
let ka = tc.key_authorization(key_pair)?; let ka = tc.key_authorization(key_pair)?;
let proof = HashFunction::Sha256.hash(ka.as_bytes()); let proof = HashFunction::Sha256.hash(ka.as_bytes());
let proof_str = proof let proof_str = proof
.iter() .iter()
.map(|e| format!("{:02x}", e))
.map(|e| format!("{e:02x}"))
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join(":"); .join(":");
let value = format!( let value = format!(
"critical,{}:{:02x}:{:02x}:{}",
DER_STRUCT_NAME,
DER_OCTET_STRING_ID,
"critical,{DER_STRUCT_NAME}:{DER_OCTET_STRING_ID:02x}:{:02x}:{proof_str}",
proof.len(), proof.len(),
proof_str
); );
let acme_ext = format!("{}={}", acme_ext_name, value);
let acme_ext = format!("{acme_ext_name}={value}");
Ok(acme_ext) Ok(acme_ext)
} }
Challenge::Unknown => Ok(String::new()), Challenge::Unknown => Ok(String::new()),
@ -158,7 +155,7 @@ impl TokenChallenge {
let thumbprint = key_pair.jwk_public_key_thumbprint()?; let thumbprint = key_pair.jwk_public_key_thumbprint()?;
let thumbprint = HashFunction::Sha256.hash(thumbprint.to_string().as_bytes()); let thumbprint = HashFunction::Sha256.hash(thumbprint.to_string().as_bytes());
let thumbprint = b64_encode(&thumbprint); let thumbprint = b64_encode(&thumbprint);
let auth = format!("{}.{}", self.token, thumbprint);
let auth = format!("{}.{thumbprint}", self.token);
Ok(auth) Ok(auth)
} }
} }

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

@ -99,7 +99,7 @@ impl fmt::Display for AcmeError {
AcmeError::UserActionRequired => "visit the \"instance\" URL and take actions specified there", AcmeError::UserActionRequired => "visit the \"instance\" URL and take actions specified there",
AcmeError::Unknown => "unknown error", AcmeError::Unknown => "unknown error",
}; };
write!(f, "{}", msg)
write!(f, "{msg}")
} }
} }
@ -147,10 +147,10 @@ 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}")
} }
} }

2
acmed/src/acme_proto/structs/order.rs

@ -66,7 +66,7 @@ impl fmt::Display for OrderStatus {
OrderStatus::Valid => "valid", OrderStatus::Valid => "valid",
OrderStatus::Invalid => "invalid", OrderStatus::Invalid => "invalid",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }

13
acmed/src/certificate.rs

@ -34,19 +34,19 @@ impl fmt::Display for Certificate {
impl HasLogger for Certificate { impl HasLogger for Certificate {
fn warn(&self, msg: &str) { fn warn(&self, msg: &str) {
warn!("certificate \"{}\": {}", &self, msg);
warn!("certificate \"{self}\": {msg}");
} }
fn info(&self, msg: &str) { fn info(&self, msg: &str) {
info!("certificate \"{}\": {}", &self, msg);
info!("certificate \"{self}\": {msg}");
} }
fn debug(&self, msg: &str) { fn debug(&self, msg: &str) {
debug!("certificate \"{}\": {}", &self, msg);
debug!("certificate \"{self}\": {msg}");
} }
fn trace(&self, msg: &str) { fn trace(&self, msg: &str) {
trace!("certificate \"{}\": {}", &self, msg);
trace!("certificate \"{self}\": {msg}");
} }
} }
@ -67,7 +67,7 @@ impl Certificate {
return Ok(d.clone()); return Ok(d.clone());
} }
} }
Err(format!("{}: identifier not found", identifier).into())
Err(format!("{identifier}: identifier not found").into())
} }
fn is_expiring(&self, cert: &X509Certificate) -> Result<bool, Error> { fn is_expiring(&self, cert: &X509Certificate) -> Result<bool, Error> {
@ -95,8 +95,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: {}",
domains
"the certificate does not include the following domains: {domains}"
)); ));
} }
has_miss has_miss

18
acmed/src/config.rs

@ -78,7 +78,7 @@ impl Config {
return Ok((rl.number, rl.period.to_owned())); return Ok((rl.number, rl.period.to_owned()));
} }
} }
Err(format!("{}: rate limit not found", name).into())
Err(format!("{name}: rate limit not found").into())
} }
pub fn get_account_dir(&self) -> String { pub fn get_account_dir(&self) -> String {
@ -120,7 +120,7 @@ impl Config {
return Ok(ret); return Ok(ret);
} }
} }
Err(format!("{}: hook not found", name).into())
Err(format!("{name}: hook not found").into())
} }
pub fn get_cert_file_mode(&self) -> u32 { pub fn get_cert_file_mode(&self) -> u32 {
@ -341,11 +341,7 @@ impl ExternalAccount {
| JwsSignatureAlgorithm::Hs384 | JwsSignatureAlgorithm::Hs384
| JwsSignatureAlgorithm::Hs512 => {} | JwsSignatureAlgorithm::Hs512 => {}
_ => { _ => {
return Err(format!(
"{}: invalid signature algorithm for external account binding",
signature_algorithm
)
.into());
return Err(format!("{signature_algorithm}: invalid signature algorithm for external account binding").into());
} }
}; };
Ok(crate::account::ExternalAccount { Ok(crate::account::ExternalAccount {
@ -584,7 +580,7 @@ impl fmt::Display for Identifier {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let s = String::new(); let s = String::new();
let msg = self.dns.as_ref().or(self.ip.as_ref()).unwrap_or(&s); let msg = self.dns.as_ref().or(self.ip.as_ref()).unwrap_or(&s);
write!(f, "{}", msg)
write!(f, "{msg}")
} }
} }
@ -666,16 +662,14 @@ fn get_cnf_path(from: &Path, file: &str) -> Result<Vec<PathBuf>, Error> {
let mut path = from.to_path_buf().canonicalize()?; let mut path = from.to_path_buf().canonicalize()?;
path.pop(); path.pop();
path.push(file); path.push(file);
let err = format!("{:?}: invalid UTF-8 path", path);
let err = format!("{path:?}: invalid UTF-8 path");
let raw_path = path.to_str().ok_or(err)?; let raw_path = path.to_str().ok_or(err)?;
let g = glob(raw_path)? let g = glob(raw_path)?
.filter_map(Result::ok) .filter_map(Result::ok)
.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",
file,
raw_path
"pattern `{file}` (expanded as `{raw_path}`): no matching configuration file found"
); );
} }
Ok(g) Ok(g)

4
acmed/src/duration.rs

@ -44,8 +44,8 @@ pub fn parse_duration(input: &str) -> Result<Duration, Error> {
match get_duration(input) { match get_duration(input) {
Ok((r, d)) => match r.len() { Ok((r, d)) => match r.len() {
0 => Ok(d), 0 => Ok(d),
_ => Err(format!("{}: invalid duration", input).into()),
_ => Err(format!("{input}: invalid duration").into()),
}, },
Err(_) => Err(format!("{}: invalid duration", input).into()),
Err(_) => Err(format!("{input}: invalid duration").into()),
} }
} }

21
acmed/src/hooks.rs

@ -106,10 +106,7 @@ macro_rules! get_hook_output {
match $out { match $out {
Some(path) => { Some(path) => {
let path = render_template(path, $data)?; let path = render_template(path, $data)?;
$logger.trace(&format!(
"hook \"{}\": {}: {}",
$hook_name, $out_name, &path
));
$logger.trace(&format!("hook \"{}\": {}: {path}", $hook_name, $out_name));
let file = File::create(&path)?; let file = File::create(&path)?;
Stdio::from(file) Stdio::from(file)
} }
@ -136,7 +133,7 @@ where
None => &[], None => &[],
}; };
logger.trace(&format!("hook \"{}\": cmd: {}", hook.name, hook.cmd)); logger.trace(&format!("hook \"{}\": cmd: {}", hook.name, hook.cmd));
logger.trace(&format!("hook \"{}\": args: {:?}", hook.name, args));
logger.trace(&format!("hook \"{}\": args: {args:?}", hook.name));
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,19 +159,13 @@ where
match &hook.stdin { match &hook.stdin {
HookStdin::Str(s) => { HookStdin::Str(s) => {
let data_in = render_template(s, &data)?; let data_in = render_template(s, &data)?;
logger.trace(&format!(
"hook \"{}\": string stdin: {}",
hook.name, &data_in
));
logger.trace(&format!("hook \"{}\": string stdin: {data_in}", hook.name));
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 = render_template(f, &data)?; let file_name = render_template(f, &data)?;
logger.trace(&format!(
"hook \"{}\": file stdin: {}",
hook.name, &file_name
));
logger.trace(&format!("hook \"{}\": file stdin: {file_name}", hook.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).map_err(|e| Error::from(e).prefix(&file_name))?; let file = File::open(&file_name).map_err(|e| Error::from(e).prefix(&file_name))?;
let buf_reader = BufReader::new(file); let buf_reader = BufReader::new(file);
@ -189,13 +180,13 @@ 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(),
Some(code) => format!("unrecoverable failure: code {code}").into(),
None => "unrecoverable failure".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)),
Some(code) => logger.debug(&format!("hook \"{}\": exited: code {code}", hook.name)),
None => logger.debug(&format!("hook \"{}\": exited", hook.name)), None => logger.debug(&format!("hook \"{}\": exited", hook.name)),
}; };
Ok(()) Ok(())

8
acmed/src/http.rs

@ -41,8 +41,8 @@ impl ValidHttpResponse {
fn from_response(response: Response) -> Result<Self, Error> { fn from_response(response: Response) -> Result<Self, Error> {
let (_status, headers, body) = response.split(); let (_status, headers, body) = response.split();
let body = body.text()?; let body = body.text()?;
log::trace!("HTTP response headers: {:?}", headers);
log::trace!("HTTP response body: {}", body);
log::trace!("HTTP response headers: {headers:?}");
log::trace!("HTTP response body: {body}");
Ok(ValidHttpResponse { headers, body }) Ok(ValidHttpResponse { headers, body })
} }
} }
@ -117,7 +117,7 @@ fn update_nonce(endpoint: &mut Endpoint, response: &Response) -> Result<(), Erro
if let Some(nonce) = response.headers().get(HEADER_NONCE) { if let Some(nonce) = response.headers().get(HEADER_NONCE) {
let nonce = header_to_string(nonce)?; let nonce = header_to_string(nonce)?;
if !is_nonce(&nonce) { if !is_nonce(&nonce) {
let msg = format!("{}: invalid nonce.", &nonce);
let msg = format!("{nonce}: invalid nonce.");
return Err(msg.into()); return Err(msg.into());
} }
endpoint.nonce = Some(nonce); endpoint.nonce = Some(nonce);
@ -202,7 +202,7 @@ where
let nonce = &endpoint.nonce.clone().unwrap_or_default(); let nonce = &endpoint.nonce.clone().unwrap_or_default();
let body = data_builder(nonce, url)?; let body = data_builder(nonce, url)?;
rate_limit(endpoint); rate_limit(endpoint);
log::trace!("POST request body: {}", body);
log::trace!("POST request body: {body}");
let response = session.post(url).text(&body).send()?; let response = session.post(url).text(&body).send()?;
update_nonce(endpoint, &response)?; update_nonce(endpoint, &response)?;
match check_status(&response) { match check_status(&response) {

14
acmed/src/identifier.rs

@ -12,7 +12,7 @@ fn u8_to_nibbles_string(value: &u8) -> String {
let bytes = value.to_ne_bytes(); let bytes = value.to_ne_bytes();
let first = bytes[0] & 0x0f; let first = bytes[0] & 0x0f;
let second = (bytes[0] >> 4) & 0x0f; let second = (bytes[0] >> 4) & 0x0f;
format!("{:x}.{:x}", first, second)
format!("{first:x}.{second:x}")
} }
#[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)] #[derive(Clone, Debug, Deserialize, Serialize, Eq, PartialEq)]
@ -38,7 +38,7 @@ impl fmt::Display for IdentifierType {
IdentifierType::Dns => "dns", IdentifierType::Dns => "dns",
IdentifierType::Ip => "ip", IdentifierType::Ip => "ip",
}; };
write!(f, "{}", name)
write!(f, "{name}")
} }
} }
@ -63,10 +63,8 @@ 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!(
"challenge {} cannot be used with identifier of type {}",
challenge, id_type
);
let msg =
format!("challenge {challenge} cannot be used with identifier of type {id_type}");
return Err(msg.into()); return Err(msg.into());
} }
Ok(Identifier { Ok(Identifier {
@ -89,7 +87,7 @@ impl Identifier {
.map(|v| v.to_string()) .map(|v| v.to_string())
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join("."); .join(".");
let dn = format!("{}.in-addr.arpa", dn);
let dn = format!("{dn}.in-addr.arpa");
Ok(dn) Ok(dn)
} }
IpAddr::V6(ip) => { IpAddr::V6(ip) => {
@ -100,7 +98,7 @@ impl Identifier {
.map(u8_to_nibbles_string) .map(u8_to_nibbles_string)
.collect::<Vec<String>>() .collect::<Vec<String>>()
.join("."); .join(".");
let dn = format!("{}.ip6.arpa", dn);
let dn = format!("{dn}.ip6.arpa");
Ok(dn) Ok(dn)
} }
}, },

6
acmed/src/jws.rs

@ -31,7 +31,7 @@ fn get_jws_data(
) -> Result<String, Error> { ) -> Result<String, Error> {
let protected = b64_encode(protected); let protected = b64_encode(protected);
let payload = b64_encode(payload); let payload = b64_encode(payload);
let signing_input = format!("{}.{}", protected, payload);
let signing_input = format!("{protected}.{payload}");
let signature = key_pair.sign(sign_alg, signing_input.as_bytes())?; let signature = key_pair.sign(sign_alg, signing_input.as_bytes())?;
let signature = b64_encode(&signature); let signature = b64_encode(&signature);
let data = JwsData { let data = JwsData {
@ -97,13 +97,13 @@ pub fn encode_kid_mac(
let protected = serde_json::to_string(&protected)?; let protected = serde_json::to_string(&protected)?;
let protected = b64_encode(&protected); let protected = b64_encode(&protected);
let payload = b64_encode(payload); let payload = b64_encode(payload);
let signing_input = format!("{}.{}", protected, payload);
let signing_input = format!("{protected}.{payload}");
let hash_func = match sign_alg { let hash_func = match sign_alg {
JwsSignatureAlgorithm::Hs256 => HashFunction::Sha256, JwsSignatureAlgorithm::Hs256 => HashFunction::Sha256,
JwsSignatureAlgorithm::Hs384 => HashFunction::Sha384, JwsSignatureAlgorithm::Hs384 => HashFunction::Sha384,
JwsSignatureAlgorithm::Hs512 => HashFunction::Sha512, JwsSignatureAlgorithm::Hs512 => HashFunction::Sha512,
_ => { _ => {
return Err(format!("{}: not a HMAC-based signature algorithm", sign_alg).into());
return Err(format!("{sign_alg}: not a HMAC-based signature algorithm").into());
} }
}; };
let signature = hash_func.hmac(key, signing_input.as_bytes())?; let signature = hash_func.hmac(key, signing_input.as_bytes())?;

7
acmed/src/main.rs

@ -50,8 +50,7 @@ pub const MIN_RATE_LIMIT_SLEEP_MILISEC: u64 = 100;
fn main() { fn main() {
let full_version = format!( let full_version = format!(
"{} built for {}\n\nCryptographic library:\n - {} {}\nHTTP client library:\n - {} {}",
APP_VERSION,
"{APP_VERSION} built for {}\n\nCryptographic library:\n - {} {}\nHTTP client library:\n - {} {}",
env!("ACMED_TARGET"), env!("ACMED_TARGET"),
get_lib_name(), get_lib_name(),
get_lib_version(), get_lib_version(),
@ -135,7 +134,7 @@ fn main() {
) { ) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
eprintln!("Error: {}", e);
eprintln!("Error: {e}");
std::process::exit(2); std::process::exit(2);
} }
}; };
@ -156,7 +155,7 @@ fn main() {
let mut srv = match MainEventLoop::new(config_file, &root_certs) { let mut srv = match MainEventLoop::new(config_file, &root_certs) {
Ok(s) => s, Ok(s) => s,
Err(e) => { Err(e) => {
error!("{}", e);
error!("{e}");
let _ = clean_pid_file(pid_file); let _ = clean_pid_file(pid_file);
std::process::exit(1); std::process::exit(1);
} }

2
acmed/src/main_event_loop.rs

@ -137,7 +137,7 @@ impl MainEventLoop {
}; };
let crt_id = cert.get_id(); let crt_id = cert.get_id();
if certs.iter().any(|c| c.get_id() == crt_id) { if certs.iter().any(|c| c.get_id() == crt_id) {
let msg = format!("{}: duplicate certificate id", crt_id);
let msg = format!("{crt_id}: duplicate certificate id");
return Err(msg.into()); return Err(msg.into());
} }
match accounts.get_mut(&crt.account) { match accounts.get_mut(&crt.account) {

26
acmed/src/storage.rs

@ -34,19 +34,19 @@ pub struct FileManager {
impl HasLogger for FileManager { impl HasLogger for FileManager {
fn warn(&self, msg: &str) { fn warn(&self, msg: &str) {
log::warn!("{}: {}", self, msg);
log::warn!("{self}: {msg}");
} }
fn info(&self, msg: &str) { fn info(&self, msg: &str) {
log::info!("{}: {}", self, msg);
log::info!("{self}: {msg}");
} }
fn debug(&self, msg: &str) { fn debug(&self, msg: &str) {
log::debug!("{}: {}", self, msg);
log::debug!("{self}: {msg}");
} }
fn trace(&self, msg: &str) { fn trace(&self, msg: &str) {
log::trace!("{}: {}", self, msg);
log::trace!("{self}: {msg}");
} }
} }
@ -57,7 +57,7 @@ impl fmt::Display for FileManager {
} else { } else {
format!("account \"{}\"", self.account_name) format!("account \"{}\"", self.account_name)
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }
@ -75,7 +75,7 @@ impl fmt::Display for FileType {
FileType::PrivateKey => "pk", FileType::PrivateKey => "pk",
FileType::Certificate => "crt", FileType::Certificate => "crt",
}; };
write!(f, "{}", s)
write!(f, "{s}")
} }
} }
@ -124,7 +124,7 @@ fn get_file_path(fm: &FileManager, file_type: FileType) -> Result<PathBuf, Error
} }
fn read_file(fm: &FileManager, path: &Path) -> Result<Vec<u8>, Error> { fn read_file(fm: &FileManager, path: &Path) -> Result<Vec<u8>, Error> {
fm.trace(&format!("reading file {:?}", path));
fm.trace(&format!("reading file {path:?}"));
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 = vec![]; let mut contents = vec![];
@ -173,16 +173,16 @@ fn set_owner(fm: &FileManager, path: &Path, file_type: FileType) -> Result<(), E
None => None, None => None,
}; };
match uid { match uid {
Some(u) => fm.trace(&format!("{:?}: setting the uid to {}", path, u.as_raw())),
None => fm.trace(&format!("{:?}: uid unchanged", path)),
Some(u) => fm.trace(&format!("{path:?}: setting the uid to {}", u.as_raw())),
None => fm.trace(&format!("{path:?}: uid unchanged")),
}; };
match gid { match gid {
Some(g) => fm.trace(&format!("{:?}: setting the gid to {}", path, g.as_raw())),
None => fm.trace(&format!("{:?}: gid unchanged", path)),
Some(g) => fm.trace(&format!("{path:?}: setting the gid to {}", g.as_raw())),
None => fm.trace(&format!("{path:?}: gid unchanged")),
}; };
match nix::unistd::chown(path, uid, gid) { match nix::unistd::chown(path, uid, gid) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(format!("{}", e).into()),
Err(e) => Err(format!("{e}").into()),
} }
} }
@ -203,7 +203,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 {

2
tacd/build.rs

@ -33,7 +33,7 @@ macro_rules! set_runstate_path_if_absent {
fn main() { fn main() {
if let Ok(target) = env::var("TARGET") { if let Ok(target) = env::var("TARGET") {
println!("cargo:rustc-env=TACD_TARGET={}", target);
println!("cargo:rustc-env=TACD_TARGET={target}");
}; };
set_runstate_path_if_absent!("TACD_DEFAULT_PID_FILE", "tacd.pid"); set_runstate_path_if_absent!("TACD_DEFAULT_PID_FILE", "tacd.pid");

12
tacd/src/main.rs

@ -36,8 +36,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 {}",
opt,
"reading {opt} from {}",
cnf.get_one::<String>(opt_file) cnf.get_one::<String>(opt_file)
.map(|e| e.as_str()) .map(|e| e.as_str())
.unwrap_or("stdin") .unwrap_or("stdin")
@ -68,15 +67,14 @@ 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 {APP_NAME} on {listen_addr} for {domain}");
server_start(listen_addr, &cert, &pk)?; server_start(listen_addr, &cert, &pk)?;
Ok(()) Ok(())
} }
fn main() { fn main() {
let full_version = format!( let full_version = format!(
"{} built for {}\n\nCryptographic library:\n - {} {}",
APP_VERSION,
"{APP_VERSION} built for {}\n\nCryptographic library:\n - {} {}",
env!("TACD_TARGET"), env!("TACD_TARGET"),
get_lib_name(), get_lib_name(),
get_lib_version(), get_lib_version(),
@ -204,7 +202,7 @@ fn main() {
) { ) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
eprintln!("Error: {}", e);
eprintln!("Error: {e}");
std::process::exit(2); std::process::exit(2);
} }
}; };
@ -212,7 +210,7 @@ fn main() {
match init(&matches) { match init(&matches) {
Ok(_) => {} Ok(_) => {}
Err(e) => { Err(e) => {
error!("{}", e);
error!("{e}");
let pid_file = matches.get_one::<String>("pid-file").map(|e| e.as_str()); let pid_file = matches.get_one::<String>("pid-file").map(|e| e.as_str());
let _ = clean_pid_file(pid_file); let _ = clean_pid_file(pid_file);
std::process::exit(1); std::process::exit(1);

4
tacd/src/openssl_server.rs

@ -45,10 +45,10 @@ 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