use super::header_probe::DeclaredHeader;
use super::header_probe::HeaderEntries;
use super::header_probe::Refusal;
use super::header_probe::header_entries;
use super::header_probe::probe;
use crate::ArchiveError;
use crate::Malformation;
use crate::QuotaResource;
use crate::Result;
use crate::formats::common;
use crate::formats::source_fault::SourceRead;
use crate::formats::source_fault::SourceTap;
use sevenz_rust2::Archive;
use sevenz_rust2::Block;
use sevenz_rust2::Password;
use std::io::ErrorKind;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::num::NonZeroU64;
use std::sync::OnceLock;
pub(crate) const SEVENZ_MAGIC: [u8; 6] = [0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C];
const EMPTY_ARCHIVE_SIZE: u64 = 32;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct BlockIndex(usize);
impl BlockIndex {
#[cfg(test)]
pub(crate) const fn first() -> Self {
Self(0)
}
pub(crate) const fn get(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) struct FileIndex(usize);
impl FileIndex {
#[cfg(test)]
pub(crate) const fn at(position: usize) -> Self {
Self(position)
}
pub(crate) const fn get(self) -> usize {
self.0
}
}
#[derive(Debug, Clone)]
pub(crate) struct PerBlock<T>(Vec<T>);
impl<T> PerBlock<T> {
pub(crate) fn iter(&self) -> std::slice::Iter<'_, T> {
self.0.iter()
}
pub(crate) fn fill(&mut self, value: T)
where
T: Clone,
{
self.0.fill(value);
}
}
impl<T> std::ops::Index<BlockIndex> for PerBlock<T> {
type Output = T;
#[expect(
clippy::indexing_slicing,
reason = "the table is sized to the header whose blocks mint the index"
)]
fn index(&self, block: BlockIndex) -> &T {
&self.0[block.0]
}
}
impl<T> std::ops::IndexMut<BlockIndex> for PerBlock<T> {
#[expect(
clippy::indexing_slicing,
reason = "the table is sized to the header whose blocks mint the index"
)]
fn index_mut(&mut self, block: BlockIndex) -> &mut T {
&mut self.0[block.0]
}
}
#[derive(Debug, Clone)]
pub(crate) struct SevenZHeader {
archive: Archive,
unchecked_crc: OnceLock<Archive>,
}
impl SevenZHeader {
fn check(archive: Archive) -> Result<Self> {
let offsets = archive.stream_map.pack_stream_offsets().len();
let pack_streams = archive.pack_sizes().len();
if offsets != pack_streams {
return Err(ArchiveError::from(
Malformation::SevenZPackStreamOffsetMismatch {
offsets,
pack_streams,
},
));
}
Ok(Self::new(archive))
}
fn empty() -> Self {
Self::new(Archive::default())
}
fn new(archive: Archive) -> Self {
Self {
archive,
unchecked_crc: OnceLock::new(),
}
}
#[cfg(test)]
pub(crate) fn assume_checked(archive: Archive) -> Self {
Self::new(archive)
}
pub(crate) const fn archive(&self) -> &Archive {
&self.archive
}
pub(crate) fn unchecked_crc_archive(&self) -> &Archive {
self.unchecked_crc.get_or_init(|| {
let mut archive = self.archive.clone();
archive.files.iter_mut().for_each(|f| f.has_crc = false);
archive
})
}
pub(crate) fn files(&self) -> &[sevenz_rust2::ArchiveEntry] {
&self.archive.files
}
pub(crate) fn file_indices(&self) -> impl Iterator<Item = FileIndex> + use<> {
(0..self.archive.files.len()).map(FileIndex)
}
pub(crate) fn file_index(&self, position: usize) -> Option<FileIndex> {
(position < self.archive.files.len()).then_some(FileIndex(position))
}
#[expect(
clippy::indexing_slicing,
reason = "a FileIndex is minted only by this header from its own file list and never crosses headers"
)]
pub(crate) fn file(&self, index: FileIndex) -> &sevenz_rust2::ArchiveEntry {
&self.archive.files[index.0]
}
pub(crate) const fn is_solid(&self) -> bool {
self.archive.is_solid
}
pub(crate) fn block_count(&self) -> usize {
self.archive.blocks.len()
}
pub(crate) fn per_block<T: Clone>(&self, value: T) -> PerBlock<T> {
PerBlock(vec![value; self.block_count()])
}
pub(crate) fn block_indices(&self) -> impl Iterator<Item = BlockIndex> + use<> {
(0..self.archive.blocks.len()).map(BlockIndex)
}
#[expect(
clippy::indexing_slicing,
reason = "sevenz-rust2 >= 0.24.2 sizes its block tables to the blocks"
)]
pub(crate) fn block(&self, index: BlockIndex) -> &Block {
&self.archive.blocks[index.0]
}
pub(crate) fn file_block(&self, file: usize) -> Option<BlockIndex> {
self.archive
.stream_map
.file_block_index
.get(file)
.copied()
.flatten()
.map(BlockIndex)
}
#[expect(
clippy::indexing_slicing,
reason = "sevenz-rust2 >= 0.24.2 sizes its block tables to the blocks"
)]
pub(crate) fn block_first_file(&self, block: BlockIndex) -> usize {
self.archive.stream_map.block_first_file_index[block.0]
}
#[expect(
clippy::indexing_slicing,
reason = "sevenz-rust2 >= 0.24.2 sizes its block tables to the blocks"
)]
pub(crate) fn block_first_pack(&self, block: BlockIndex) -> usize {
self.archive.stream_map.block_first_pack_stream_index()[block.0]
}
pub(crate) fn next_block_first_pack(&self, block: BlockIndex) -> Option<usize> {
self.archive
.stream_map
.block_first_pack_stream_index()
.get(block.0.saturating_add(1))
.copied()
}
pub(crate) fn pack_stream_offsets(&self) -> &[u64] {
self.archive.stream_map.pack_stream_offsets()
}
}
const HEADER_BYTES_PER_ENTRY: u64 = 256;
const HEADER_BYTES_BASE: u64 = 64 * 1024;
pub(super) const HEADER_ENTRIES_BASE: u64 = 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct HeaderLimit {
memory: NonZeroU64,
entry_bytes: NonZeroU64,
entries: u64,
}
impl HeaderLimit {
#[cfg(test)]
pub(crate) const UNLIMITED: Self = Self {
memory: NonZeroU64::MAX,
entry_bytes: NonZeroU64::MAX,
entries: u64::MAX,
};
pub(crate) fn from_config(config: &crate::SecurityConfig) -> Self {
let files = u64::try_from(config.max_file_count.ceiling()).unwrap_or(u64::MAX);
Self::from_limits(config.max_decoder_memory, files)
}
fn from_limits(max_decoder_memory: NonZeroU64, max_file_count: u64) -> Self {
let entry_bytes = max_file_count
.saturating_mul(HEADER_BYTES_PER_ENTRY)
.saturating_add(HEADER_BYTES_BASE);
Self {
memory: max_decoder_memory,
entry_bytes: NonZeroU64::new(entry_bytes).unwrap_or(NonZeroU64::MAX),
entries: max_file_count.saturating_add(HEADER_ENTRIES_BASE),
}
}
fn header_cap(self) -> HeaderCap {
if self.entry_bytes < self.memory {
HeaderCap::EntryBudget(self.entry_bytes)
} else {
HeaderCap::Memory(self.memory)
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HeaderCap {
Memory(NonZeroU64),
EntryBudget(NonZeroU64),
}
impl HeaderCap {
const fn bytes(self) -> NonZeroU64 {
match self {
Self::Memory(bytes) | Self::EntryBudget(bytes) => bytes,
}
}
fn refusal(self) -> ArchiveError {
let resource = match self {
Self::Memory(bytes) => QuotaResource::DecoderMemory { max: bytes.get() },
Self::EntryBudget(bytes) => QuotaResource::HeaderSize { max: bytes.get() },
};
ArchiveError::QuotaExceeded { resource }
}
}
fn kib(limit: NonZeroU64) -> usize {
usize::try_from(limit.get() / 1024).unwrap_or(usize::MAX)
}
pub(crate) fn read_sevenz_header<R: Read + Seek>(
source: &mut R,
limit: HeaderLimit,
) -> Result<SevenZHeader> {
let cap = limit.header_cap();
let parse_limit = match probe(source, cap.bytes().get()) {
DeclaredHeader::Plain { bytes: size } | DeclaredHeader::Encoded { decoded: size } => {
if size > cap.bytes().get() {
return Err(cap.refusal());
}
HeaderCap::Memory(limit.memory)
}
DeclaredHeader::Unrecognized => cap,
};
match header_entries(source, cap.bytes().get(), kib(limit.memory)) {
HeaderEntries::Declared(tables) if tables.entries() > limit.entries => {
return Err(ArchiveError::QuotaExceeded {
resource: QuotaResource::HeaderEntryCount {
declared: tables.entries(),
max: limit.entries,
},
});
}
HeaderEntries::Declared(tables) => {
tables
.within_bounds(HEADER_ENTRIES_BASE)
.map_err(ArchiveError::from)?;
}
HeaderEntries::Unmodelled => {
return Err(ArchiveError::from(Malformation::SevenZHeaderUnreadable {
detail: "unsupported header layout: the number of entries cannot be read".into(),
}));
}
HeaderEntries::Refused(Refusal::Encrypted) => return Err(common::encrypted_archive_error()),
HeaderEntries::Refused(Refusal::Memory) => {
return Err(HeaderCap::Memory(limit.memory).refusal());
}
HeaderEntries::NotApplicable => {}
}
source.seek(SeekFrom::Start(0)).map_err(ArchiveError::Io)?;
let tap = SourceTap::default();
let parsed = Archive::read_with_memory_limit(
&mut SourceRead::new(&mut *source, tap.clone()),
&Password::empty(),
kib(parse_limit.bytes()),
);
match parsed {
Ok(archive) => SevenZHeader::check(archive),
Err(error) => header_failure(&error, &tap, source, parse_limit),
}
}
fn header_failure<R: Read + Seek>(
error: &sevenz_rust2::Error,
tap: &SourceTap,
source: &mut R,
limit: HeaderCap,
) -> Result<SevenZHeader> {
if let Some(fault) = tap.fault() {
return Err(ArchiveError::Io(fault));
}
if matches!(error, sevenz_rust2::Error::MaxMemLimited { .. }) {
return Err(limit.refusal());
}
if super::is_password_error(error) {
return Err(common::encrypted_archive_error());
}
if is_empty_sevenz_archive(error, source) {
return Ok(SevenZHeader::empty());
}
Err(ArchiveError::from(Malformation::SevenZHeaderUnreadable {
detail: error.to_string().into(),
}))
}
fn is_empty_sevenz_archive<R: Read + Seek>(err: &sevenz_rust2::Error, source: &mut R) -> bool {
let is_eof = matches!(err, sevenz_rust2::Error::Io(io_err, _) if io_err.kind() == ErrorKind::UnexpectedEof);
if !is_eof {
return false;
}
let Ok(size) = source.seek(SeekFrom::End(0)) else {
return false;
};
if size != EMPTY_ARCHIVE_SIZE {
return false;
}
if source.seek(SeekFrom::Start(0)).is_err() {
return false;
}
let mut magic = [0u8; 6];
source.read_exact(&mut magic).is_ok() && magic == SEVENZ_MAGIC
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
use std::assert_matches;
use std::io::Cursor;
const NO_FILES_INFO: &[u8] =
include_bytes!("../../../../../tests/fixtures/streams-without-files-info.7z");
const SIMPLE: &[u8] = include_bytes!("../../../../../tests/fixtures/simple.7z");
fn header_with_blocks(count: usize) -> SevenZHeader {
let mut archive = Archive::default();
archive.blocks = vec![Block::default(); count];
SevenZHeader::assume_checked(archive)
}
#[test]
fn per_block_is_sized_to_the_header_blocks() {
let header = header_with_blocks(3);
let table = header.per_block(0u8);
assert_eq!(table.iter().count(), header.block_count());
assert!(header.block_indices().all(|block| table[block] == 0));
}
#[test]
fn per_block_index_mut_writes_only_the_addressed_block() {
let header = header_with_blocks(3);
let mut table = header.per_block(0u8);
let second = header.block_indices().nth(1).unwrap();
table[second] = 1;
let expected: Vec<u8> = header
.block_indices()
.map(|block| u8::from(block == second))
.collect();
assert_eq!(table.iter().copied().collect::<Vec<_>>(), expected);
}
#[test]
fn per_block_fill_sets_every_entry() {
let header = header_with_blocks(3);
let mut table = header.per_block(false);
table.fill(true);
assert!(table.iter().all(|&set| set));
}
fn parsed(bytes: &[u8]) -> Archive {
Archive::read(&mut Cursor::new(bytes), &Password::empty()).unwrap()
}
fn crc32(data: &[u8]) -> u32 {
!data.iter().fold(!0u32, |mut crc, &byte| {
crc ^= u32::from(byte);
for _ in 0..8 {
crc = (crc >> 1) ^ (0xEDB8_8320 & 0u32.wrapping_sub(crc & 1));
}
crc
})
}
fn archive_with_pack_stream_and_no_blocks() -> Vec<u8> {
let header = [0x01, 0x04, 0x06, 0x00, 0x01, 0x09, 0x01, 0x00, 0x00, 0x00];
let mut start = Vec::new();
start.extend_from_slice(&0u64.to_le_bytes());
start.extend_from_slice(&(header.len() as u64).to_le_bytes());
start.extend_from_slice(&crc32(&header).to_le_bytes());
let mut bytes = SEVENZ_MAGIC.to_vec();
bytes.extend_from_slice(&[0, 4]);
bytes.extend_from_slice(&crc32(&start).to_le_bytes());
bytes.extend_from_slice(&start);
bytes.extend_from_slice(&header);
bytes
}
#[test]
fn the_entry_cap_follows_max_file_count_and_leaves_the_memory_limit() {
let memory = NonZeroU64::new(1 << 30).unwrap();
let limit = HeaderLimit::from_limits(memory, 1000);
assert_eq!(
limit.entry_bytes.get(),
1000 * HEADER_BYTES_PER_ENTRY + HEADER_BYTES_BASE
);
assert_eq!(limit.memory, memory);
assert_eq!(
limit.header_cap(),
HeaderCap::EntryBudget(limit.entry_bytes)
);
let zero = HeaderLimit::from_limits(memory, 0);
assert_eq!(zero.entry_bytes.get(), HEADER_BYTES_BASE);
}
#[test]
fn the_entry_limit_is_max_file_count_plus_the_allowance_and_saturates() {
let memory = NonZeroU64::new(1 << 30).unwrap();
assert_eq!(
HeaderLimit::from_limits(memory, 1000).entries,
1000 + HEADER_ENTRIES_BASE
);
assert_eq!(HeaderLimit::from_limits(memory, u64::MAX).entries, u64::MAX);
}
#[test]
fn the_header_cap_is_the_lower_of_memory_and_entry_bytes() {
let small = NonZeroU64::new(100 * 1024).unwrap();
let limit = HeaderLimit::from_limits(small, 1_000_000);
assert_eq!(limit.header_cap(), HeaderCap::Memory(small));
}
#[test]
fn an_unbounded_entry_count_saturates_instead_of_overflowing() {
let memory = NonZeroU64::new(256 << 20).unwrap();
let limit = HeaderLimit::from_limits(memory, u64::MAX);
assert_eq!(limit.entry_bytes, NonZeroU64::MAX);
assert_eq!(limit.header_cap(), HeaderCap::Memory(memory));
}
#[test]
fn header_limit_rounds_down_to_whole_kib_and_saturates() {
let kib = |bytes| kib(NonZeroU64::new(bytes).unwrap());
assert_eq!(kib(1), 0);
assert_eq!(kib(1023), 0);
assert_eq!(kib(1024), 1);
assert_eq!(kib(2047), 1);
assert_eq!(
kib(u64::MAX),
usize::try_from(u64::MAX / 1024).unwrap_or(usize::MAX)
);
}
#[test]
fn upstream_rejects_streams_without_files_info() {
let err = Archive::read(&mut Cursor::new(NO_FILES_INFO), &Password::empty()).unwrap_err();
assert!(err.to_string().contains("no files info"), "{err}");
}
#[test]
fn upstream_leaves_pack_offsets_empty_without_blocks() {
let bytes = archive_with_pack_stream_and_no_blocks();
let archive = parsed(&bytes);
assert!(archive.blocks.is_empty());
assert_eq!(archive.pack_sizes().len(), 1);
assert!(archive.stream_map.pack_stream_offsets().is_empty());
}
#[test]
fn check_rejects_pack_streams_without_blocks() {
let bytes = archive_with_pack_stream_and_no_blocks();
let err = read_sevenz_header(&mut Cursor::new(bytes), HeaderLimit::UNLIMITED).unwrap_err();
assert_matches!(&err, ArchiveError::InvalidArchive(m) if m.to_string().starts_with("failed to open 7z archive: "),
"{err:?}"
);
}
#[test]
fn check_accepts_a_valid_archive() {
let header = SevenZHeader::check(parsed(SIMPLE)).unwrap();
assert!(header.block_indices().count() > 0);
assert!(
header
.files()
.iter()
.enumerate()
.all(|(i, f)| { header.file_block(i).is_some() == f.has_stream })
);
}
#[test]
fn check_accepts_an_archive_without_blocks() {
assert!(SevenZHeader::check(Archive::default()).is_ok());
}
#[test]
fn file_block_ignores_an_index_past_the_files() {
let header = SevenZHeader::check(parsed(SIMPLE)).unwrap();
assert_eq!(header.file_block(usize::MAX), None);
}
#[test]
fn read_header_rejects_the_vector_as_invalid_archive() {
let err = read_sevenz_header(&mut Cursor::new(NO_FILES_INFO), HeaderLimit::UNLIMITED)
.unwrap_err();
assert_matches!(&err, ArchiveError::InvalidArchive(m) if m.to_string().starts_with("failed to open 7z archive: "),
"{err:?}"
);
}
#[test]
fn read_header_opens_the_empty_archive() {
let bytes = include_bytes!("../../../../../tests/fixtures/empty.7z");
let header =
read_sevenz_header(&mut Cursor::new(&bytes[..]), HeaderLimit::UNLIMITED).unwrap();
assert!(header.files().is_empty());
assert_eq!(header.block_count(), 0);
}
}