use crate::{Error, Result};
pub const MAX_BLOCK_UNCOMPRESSED: usize = 16 * 1024 * 1024;
pub const MAX_BLOCK_COMPRESSED: usize = 16 * 1024 * 1024 + 64 * 1024;
pub const MAX_OFFSET: usize = 8 * 1024 * 1024;
pub const MAX_MATCH_LEN: usize = 1024 * 1024;
pub const MIN_MATCH: usize = 4;
pub const DEFAULT_MAX_OUTPUT: u64 = 4 * 1024 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct SecurityPolicy {
pub max_output: u64,
pub max_block_uncompressed: usize,
pub max_block_compressed: usize,
pub verify_checksum: bool,
}
impl Default for SecurityPolicy {
fn default() -> Self {
Self {
max_output: DEFAULT_MAX_OUTPUT,
max_block_uncompressed: MAX_BLOCK_UNCOMPRESSED,
max_block_compressed: MAX_BLOCK_COMPRESSED,
verify_checksum: true,
}
}
}
impl SecurityPolicy {
pub fn strict() -> Self {
Self {
max_output: 512 * 1024 * 1024,
max_block_uncompressed: 4 * 1024 * 1024,
max_block_compressed: 4 * 1024 * 1024 + 64 * 1024,
verify_checksum: true,
}
}
pub fn check_block(&self, compressed: usize, uncompressed: usize) -> Result<()> {
if uncompressed > self.max_block_uncompressed {
return Err(Error::InvalidParameter(format!(
"block uncompressed {uncompressed} exceeds cap {}",
self.max_block_uncompressed
)));
}
if compressed > self.max_block_compressed {
return Err(Error::InvalidParameter(format!(
"block compressed {compressed} exceeds cap {}",
self.max_block_compressed
)));
}
Ok(())
}
pub fn check_frame_size(&self, content_size: u64) -> Result<()> {
if content_size != u64::MAX && content_size > self.max_output {
return Err(Error::InvalidParameter(format!(
"content size {content_size} exceeds max_output {}",
self.max_output
)));
}
Ok(())
}
}
#[inline]
pub fn check_match(offset: usize, match_len: usize, decoded_len: usize) -> Result<()> {
check_match_with_history(offset, match_len, decoded_len, 0)
}
#[inline]
pub fn check_match_with_history(
offset: usize,
match_len: usize,
decoded_len: usize,
dict_len: usize,
) -> Result<()> {
if offset == 0 {
return Err(Error::Decompression("security: match offset 0".into()));
}
if offset > MAX_OFFSET {
return Err(Error::Decompression(format!(
"security: offset {offset} > MAX_OFFSET"
)));
}
let history = dict_len.saturating_add(decoded_len);
if offset > history {
return Err(Error::Decompression(format!(
"security: offset {offset} > history {history} (dict={dict_len} out={decoded_len})"
)));
}
if match_len == 0 || match_len > MAX_MATCH_LEN {
return Err(Error::Decompression(format!(
"security: bad match_len {match_len}"
)));
}
Ok(())
}
pub fn check_block_sizes(compressed: usize, uncompressed: usize) -> Result<()> {
SecurityPolicy::default().check_block(compressed, uncompressed)
}