2022-04-14 11:27:53 +00:00
|
|
|
use anyhow::Error;
|
2019-08-14 11:05:11 +00:00
|
|
|
use std::io::Read;
|
2022-04-14 11:27:53 +00:00
|
|
|
use std::sync::Arc;
|
2019-08-14 11:05:11 +00:00
|
|
|
|
2021-10-13 08:40:50 +00:00
|
|
|
use proxmox_borrow::Tied;
|
|
|
|
|
2021-09-07 07:22:14 +00:00
|
|
|
use pbs_tools::crypt_config::CryptConfig;
|
2019-08-16 07:19:01 +00:00
|
|
|
|
|
|
|
pub struct ChecksumReader<R> {
|
2019-08-14 11:05:11 +00:00
|
|
|
reader: R,
|
|
|
|
hasher: crc32fast::Hasher,
|
2019-08-16 07:19:01 +00:00
|
|
|
signer: Option<Tied<Arc<CryptConfig>, openssl::sign::Signer<'static>>>,
|
2019-08-14 11:05:11 +00:00
|
|
|
}
|
|
|
|
|
2022-04-14 11:27:53 +00:00
|
|
|
impl<R: Read> ChecksumReader<R> {
|
2019-08-16 07:19:01 +00:00
|
|
|
pub fn new(reader: R, config: Option<Arc<CryptConfig>>) -> Self {
|
2019-08-14 11:05:11 +00:00
|
|
|
let hasher = crc32fast::Hasher::new();
|
2019-08-16 07:19:01 +00:00
|
|
|
let signer = match config {
|
|
|
|
Some(config) => {
|
|
|
|
let tied_signer = Tied::new(config, |config| {
|
|
|
|
Box::new(unsafe { (*config).data_signer() })
|
|
|
|
});
|
|
|
|
Some(tied_signer)
|
|
|
|
}
|
|
|
|
None => None,
|
|
|
|
};
|
|
|
|
|
2022-04-14 11:27:53 +00:00
|
|
|
Self {
|
|
|
|
reader,
|
|
|
|
hasher,
|
|
|
|
signer,
|
|
|
|
}
|
2019-08-14 11:05:11 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
pub fn finish(mut self) -> Result<(R, u32, Option<[u8; 32]>), Error> {
|
|
|
|
let crc = self.hasher.finalize();
|
|
|
|
|
|
|
|
if let Some(ref mut signer) = self.signer {
|
|
|
|
let mut tag = [0u8; 32];
|
|
|
|
signer.sign(&mut tag)?;
|
|
|
|
Ok((self.reader, crc, Some(tag)))
|
|
|
|
} else {
|
|
|
|
Ok((self.reader, crc, None))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-04-14 11:27:53 +00:00
|
|
|
impl<R: Read> Read for ChecksumReader<R> {
|
2019-08-14 11:05:11 +00:00
|
|
|
fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
|
|
|
|
let count = self.reader.read(buf)?;
|
|
|
|
if count > 0 {
|
|
|
|
self.hasher.update(&buf[..count]);
|
|
|
|
if let Some(ref mut signer) = self.signer {
|
2022-04-14 11:27:53 +00:00
|
|
|
signer.update(&buf[..count]).map_err(|err| {
|
|
|
|
std::io::Error::new(
|
|
|
|
std::io::ErrorKind::Other,
|
|
|
|
format!("hmac update failed - {}", err),
|
|
|
|
)
|
|
|
|
})?;
|
2019-08-14 11:05:11 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(count)
|
|
|
|
}
|
|
|
|
}
|