tools: rustfmt

Signed-off-by: Thomas Lamprecht <t.lamprecht@proxmox.com>
This commit is contained in:
Thomas Lamprecht 2022-04-14 14:05:17 +02:00
parent 9531d2c570
commit 00ae34dfda
7 changed files with 69 additions and 52 deletions

View File

@ -7,8 +7,8 @@ use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};
use proxmox_async::broadcast_future::BroadcastFuture;
use crate::lru_cache::LruCache; use crate::lru_cache::LruCache;
use proxmox_async::broadcast_future::BroadcastFuture;
/// Interface for asynchronously getting values on cache misses. /// Interface for asynchronously getting values on cache misses.
pub trait AsyncCacher<K, V: Clone>: Sync + Send { pub trait AsyncCacher<K, V: Clone>: Sync + Send {

View File

@ -1,13 +1,13 @@
//! Deals with the server's current certificates (proxy.pem). //! Deals with the server's current certificates (proxy.pem).
use std::path::PathBuf;
use std::mem::MaybeUninit; use std::mem::MaybeUninit;
use std::path::PathBuf;
use anyhow::{bail, format_err, Error}; use anyhow::{bail, format_err, Error};
use foreign_types::ForeignTypeRef; use foreign_types::ForeignTypeRef;
use openssl::x509::{X509, GeneralName}; use openssl::pkey::{PKey, Public};
use openssl::stack::Stack; use openssl::stack::Stack;
use openssl::pkey::{Public, PKey}; use openssl::x509::{GeneralName, X509};
// C type: // C type:
#[allow(non_camel_case_types)] #[allow(non_camel_case_types)]
@ -34,7 +34,11 @@ pub struct CertInfo {
fn x509name_to_string(name: &openssl::x509::X509NameRef) -> Result<String, Error> { fn x509name_to_string(name: &openssl::x509::X509NameRef) -> Result<String, Error> {
let mut parts = Vec::new(); let mut parts = Vec::new();
for entry in name.entries() { for entry in name.entries() {
parts.push(format!("{} = {}", entry.object().nid().short_name()?, entry.data().as_utf8()?)); parts.push(format!(
"{} = {}",
entry.object().nid().short_name()?,
entry.data().as_utf8()?
));
} }
Ok(parts.join(", ")) Ok(parts.join(", "))
} }
@ -47,9 +51,7 @@ impl CertInfo {
pub fn from_pem(cert_pem: &[u8]) -> Result<Self, Error> { pub fn from_pem(cert_pem: &[u8]) -> Result<Self, Error> {
let x509 = openssl::x509::X509::from_pem(cert_pem)?; let x509 = openssl::x509::X509::from_pem(cert_pem)?;
Ok(Self{ Ok(Self { x509 })
x509
})
} }
pub fn subject_alt_names(&self) -> Option<Stack<GeneralName>> { pub fn subject_alt_names(&self) -> Option<Stack<GeneralName>> {
@ -70,7 +72,8 @@ impl CertInfo {
.as_bytes() .as_bytes()
.chunks(2) .chunks(2)
.map(|v| std::str::from_utf8(v).unwrap()) .map(|v| std::str::from_utf8(v).unwrap())
.collect::<Vec<&str>>().join(":")) .collect::<Vec<&str>>()
.join(":"))
} }
pub fn public_key(&self) -> Result<PKey<Public>, Error> { pub fn public_key(&self) -> Result<PKey<Public>, Error> {

View File

@ -7,7 +7,7 @@
//! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption) //! encryption](https://en.wikipedia.org/wiki/Authenticated_encryption)
//! for a short introduction. //! for a short introduction.
use anyhow::{Error}; use anyhow::Error;
use openssl::hash::MessageDigest; use openssl::hash::MessageDigest;
use openssl::pkcs5::pbkdf2_hmac; use openssl::pkcs5::pbkdf2_hmac;
use openssl::symm::{Cipher, Crypter, Mode}; use openssl::symm::{Cipher, Crypter, Mode};
@ -15,10 +15,8 @@ use openssl::symm::{Cipher, Crypter, Mode};
// openssl::sha::sha256(b"Proxmox Backup Encryption Key Fingerprint") // openssl::sha::sha256(b"Proxmox Backup Encryption Key Fingerprint")
/// This constant is used to compute fingerprints. /// This constant is used to compute fingerprints.
const FINGERPRINT_INPUT: [u8; 32] = [ const FINGERPRINT_INPUT: [u8; 32] = [
110, 208, 239, 119, 71, 31, 255, 77, 110, 208, 239, 119, 71, 31, 255, 77, 85, 199, 168, 254, 74, 157, 182, 33, 97, 64, 127, 19, 76,
85, 199, 168, 254, 74, 157, 182, 33, 114, 93, 223, 48, 153, 45, 37, 236, 69, 237, 38,
97, 64, 127, 19, 76, 114, 93, 223,
48, 153, 45, 37, 236, 69, 237, 38,
]; ];
/// Encryption Configuration with secret key /// Encryption Configuration with secret key
@ -37,13 +35,11 @@ pub struct CryptConfig {
} }
impl CryptConfig { impl CryptConfig {
/// Create a new instance. /// Create a new instance.
/// ///
/// We compute a derived 32 byte key using pbkdf2_hmac. This second /// We compute a derived 32 byte key using pbkdf2_hmac. This second
/// key is used in compute_digest. /// key is used in compute_digest.
pub fn new(enc_key: [u8; 32]) -> Result<Self, Error> { pub fn new(enc_key: [u8; 32]) -> Result<Self, Error> {
let mut id_key = [0u8; 32]; let mut id_key = [0u8; 32];
pbkdf2_hmac( pbkdf2_hmac(
@ -51,11 +47,17 @@ impl CryptConfig {
b"_id_key", b"_id_key",
10, 10,
MessageDigest::sha256(), MessageDigest::sha256(),
&mut id_key)?; &mut id_key,
)?;
let id_pkey = openssl::pkey::PKey::hmac(&id_key).unwrap(); let id_pkey = openssl::pkey::PKey::hmac(&id_key).unwrap();
Ok(Self { id_key, id_pkey, enc_key, cipher: Cipher::aes_256_gcm() }) Ok(Self {
id_key,
id_pkey,
enc_key,
cipher: Cipher::aes_256_gcm(),
})
} }
/// Expose Cipher (AES_256_GCM) /// Expose Cipher (AES_256_GCM)
@ -107,7 +109,7 @@ impl CryptConfig {
} }
/// Returns an openssl Crypter using AES_256_GCM, /// Returns an openssl Crypter using AES_256_GCM,
pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> { pub fn data_crypter(&self, iv: &[u8; 16], mode: Mode) -> Result<Crypter, Error> {
let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?; let mut crypter = openssl::symm::Crypter::new(self.cipher, mode, &self.enc_key, Some(iv))?;
crypter.aad_update(b"")?; //?? crypter.aad_update(b"")?; //??
Ok(crypter) Ok(crypter)

View File

@ -1,20 +1,21 @@
use std::borrow::Borrow; use std::borrow::Borrow;
use anyhow::{Error}; use anyhow::Error;
use serde_json::Value; use serde_json::Value;
use pbs_api_types::HumanByte; use pbs_api_types::HumanByte;
pub fn strip_server_file_extension(name: &str) -> &str { pub fn strip_server_file_extension(name: &str) -> &str {
if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") { if name.ends_with(".didx") || name.ends_with(".fidx") || name.ends_with(".blob") {
&name[..name.len()-5] &name[..name.len() - 5]
} else { } else {
name // should not happen name // should not happen
} }
} }
pub fn render_backup_file_list<S: Borrow<str>>(files: &[S]) -> String { pub fn render_backup_file_list<S: Borrow<str>>(files: &[S]) -> String {
let mut files: Vec<&str> = files.iter() let mut files: Vec<&str> = files
.iter()
.map(|v| strip_server_file_extension(v.borrow())) .map(|v| strip_server_file_extension(v.borrow()))
.collect(); .collect();
@ -24,7 +25,9 @@ pub fn render_backup_file_list<S: Borrow<str>>(files: &[S]) -> String {
} }
pub fn render_epoch(value: &Value, _record: &Value) -> Result<String, Error> { pub fn render_epoch(value: &Value, _record: &Value) -> Result<String, Error> {
if value.is_null() { return Ok(String::new()); } if value.is_null() {
return Ok(String::new());
}
let text = match value.as_i64() { let text = match value.as_i64() {
Some(epoch) => { Some(epoch) => {
if let Ok(epoch_string) = proxmox_time::strftime_local("%c", epoch as i64) { if let Ok(epoch_string) = proxmox_time::strftime_local("%c", epoch as i64) {
@ -32,10 +35,8 @@ pub fn render_epoch(value: &Value, _record: &Value) -> Result<String, Error> {
} else { } else {
epoch.to_string() epoch.to_string()
} }
},
None => {
value.to_string()
} }
None => value.to_string(),
}; };
Ok(text) Ok(text)
} }
@ -54,14 +55,12 @@ pub fn render_bool_with_default_true(value: &Value, _record: &Value) -> Result<S
} }
pub fn render_bytes_human_readable(value: &Value, _record: &Value) -> Result<String, Error> { pub fn render_bytes_human_readable(value: &Value, _record: &Value) -> Result<String, Error> {
if value.is_null() { return Ok(String::new()); } if value.is_null() {
return Ok(String::new());
}
let text = match value.as_u64() { let text = match value.as_u64() {
Some(bytes) => { Some(bytes) => HumanByte::from(bytes).to_string(),
HumanByte::from(bytes).to_string() None => value.to_string(),
}
None => {
value.to_string()
}
}; };
Ok(text) Ok(text)
} }

View File

@ -24,6 +24,6 @@ pub mod async_lru_cache;
/// less erratic behavior in the overall's runtime RSS size. /// less erratic behavior in the overall's runtime RSS size.
pub fn setup_libc_malloc_opts() { pub fn setup_libc_malloc_opts() {
unsafe { unsafe {
libc::mallopt(libc::M_MMAP_THRESHOLD, 4096*32); libc::mallopt(libc::M_MMAP_THRESHOLD, 4096 * 32);
} }
} }

View File

@ -4,7 +4,7 @@
//! A HashMap is used for fast access by a given key and a doubly linked list //! A HashMap is used for fast access by a given key and a doubly linked list
//! is used to keep track of the cache access order. //! is used to keep track of the cache access order.
use std::collections::{HashMap, hash_map::Entry}; use std::collections::{hash_map::Entry, HashMap};
use std::marker::PhantomData; use std::marker::PhantomData;
/// Interface for getting values on cache misses. /// Interface for getting values on cache misses.
@ -101,7 +101,7 @@ pub struct LruCache<K, V> {
} }
impl<K, V> Drop for LruCache<K, V> { impl<K, V> Drop for LruCache<K, V> {
fn drop (&mut self) { fn drop(&mut self) {
self.clear(); self.clear();
} }
} }
@ -204,7 +204,11 @@ impl<K: std::cmp::Eq + std::hash::Hash + Copy, V> LruCache<K, V> {
/// value. /// value.
/// If fetch returns a value, it is inserted as the most recently used entry /// If fetch returns a value, it is inserted as the most recently used entry
/// in the cache. /// in the cache.
pub fn access<'a>(&'a mut self, key: K, cacher: &mut dyn Cacher<K, V>) -> Result<Option<&'a mut V>, anyhow::Error> { pub fn access<'a>(
&'a mut self,
key: K,
cacher: &mut dyn Cacher<K, V>,
) -> Result<Option<&'a mut V>, anyhow::Error> {
match self.map.entry(key) { match self.map.entry(key) {
Entry::Occupied(mut o) => { Entry::Occupied(mut o) => {
// Cache hit, birng node to front of list // Cache hit, birng node to front of list

View File

@ -1,10 +1,10 @@
use anyhow::{bail, Error}; use anyhow::{bail, Error};
use nom::{ use nom::{
error::{ParseError, VerboseError},
bytes::complete::{take_while, take_while1}, bytes::complete::{take_while, take_while1},
combinator::{map_res, all_consuming, recognize}, character::complete::digit1,
character::complete::{digit1}, combinator::{all_consuming, map_res, recognize},
error::{ParseError, VerboseError},
}; };
pub type IResult<I, O, E = VerboseError<I>> = Result<(I, O), nom::Err<E>>; pub type IResult<I, O, E = VerboseError<I>> = Result<(I, O), nom::Err<E>>;
@ -22,17 +22,17 @@ pub fn parse_failure<'a>(i: &'a str, context: &'static str) -> nom::Err<VerboseE
} }
/// Recognizes zero or more spaces and tabs (but not carage returns or line feeds) /// Recognizes zero or more spaces and tabs (but not carage returns or line feeds)
pub fn multispace0(i: &str) -> IResult<&str, &str> { pub fn multispace0(i: &str) -> IResult<&str, &str> {
take_while(|c| c == ' ' || c == '\t')(i) take_while(|c| c == ' ' || c == '\t')(i)
} }
/// Recognizes one or more spaces and tabs (but not carage returns or line feeds) /// Recognizes one or more spaces and tabs (but not carage returns or line feeds)
pub fn multispace1(i: &str) -> IResult<&str, &str> { pub fn multispace1(i: &str) -> IResult<&str, &str> {
take_while1(|c| c == ' ' || c == '\t')(i) take_while1(|c| c == ' ' || c == '\t')(i)
} }
/// Recognizes one or more non-whitespace-characters /// Recognizes one or more non-whitespace-characters
pub fn notspace1(i: &str) -> IResult<&str, &str> { pub fn notspace1(i: &str) -> IResult<&str, &str> {
take_while1(|c| !(c == ' ' || c == '\t' || c == '\n'))(i) take_while1(|c| !(c == ' ' || c == '\t' || c == '\n'))(i)
} }
@ -43,32 +43,41 @@ pub fn parse_u64(i: &str) -> IResult<&str, u64> {
/// Parse complete input, generate verbose error message with line numbers /// Parse complete input, generate verbose error message with line numbers
pub fn parse_complete<'a, F, O>(what: &str, i: &'a str, parser: F) -> Result<O, Error> pub fn parse_complete<'a, F, O>(what: &str, i: &'a str, parser: F) -> Result<O, Error>
where F: Fn(&'a str) -> IResult<&'a str, O>, where
F: Fn(&'a str) -> IResult<&'a str, O>,
{ {
match all_consuming(parser)(i) { match all_consuming(parser)(i) {
Err(nom::Err::Error(err)) | Err(nom::Err::Error(err)) | Err(nom::Err::Failure(err)) => {
Err(nom::Err::Failure(err)) => { bail!(
bail!("unable to parse {} - {}", what, nom::error::convert_error(i, err)); "unable to parse {} - {}",
what,
nom::error::convert_error(i, err)
);
} }
Err(err) => { Err(err) => {
bail!("unable to parse {} - {}", what, err); bail!("unable to parse {} - {}", what, err);
} }
Ok((_, data)) => Ok(data), Ok((_, data)) => Ok(data),
} }
} }
/// Parse complete input, generate simple error message (use this for sinple line input). /// Parse complete input, generate simple error message (use this for sinple line input).
pub fn parse_complete_line<'a, F, O>(what: &str, i: &'a str, parser: F) -> Result<O, Error> pub fn parse_complete_line<'a, F, O>(what: &str, i: &'a str, parser: F) -> Result<O, Error>
where F: Fn(&'a str) -> IResult<&'a str, O>, where
F: Fn(&'a str) -> IResult<&'a str, O>,
{ {
match all_consuming(parser)(i) { match all_consuming(parser)(i) {
Err(nom::Err::Error(VerboseError { errors })) | Err(nom::Err::Error(VerboseError { errors }))
Err(nom::Err::Failure(VerboseError { errors })) => { | Err(nom::Err::Failure(VerboseError { errors })) => {
if errors.is_empty() { if errors.is_empty() {
bail!("unable to parse {}", what); bail!("unable to parse {}", what);
} else { } else {
bail!("unable to parse {} at '{}' - {:?}", what, errors[0].0, errors[0].1); bail!(
"unable to parse {} at '{}' - {:?}",
what,
errors[0].0,
errors[0].1
);
} }
} }
Err(err) => { Err(err) => {