use crate::ArchiveError;
use crate::Result;
use crate::formats::common;
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;
pub 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 struct BlockIndex(usize);
impl BlockIndex {
pub const fn get(self) -> usize {
self.0
}
}
#[derive(Debug, Clone)]
pub struct SevenZHeader {
archive: 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::InvalidArchive(format!(
"failed to open 7z archive: the pack stream offsets have {offsets} entries for \
{pack_streams} pack streams"
)));
}
Ok(Self { archive })
}
fn empty() -> Self {
Self {
archive: Archive::default(),
}
}
#[cfg(test)]
pub fn assume_checked(archive: Archive) -> Self {
Self { archive }
}
pub const fn archive(&self) -> &Archive {
&self.archive
}
pub fn files(&self) -> &[sevenz_rust2::ArchiveEntry] {
&self.archive.files
}
pub const fn is_solid(&self) -> bool {
self.archive.is_solid
}
pub fn block_count(&self) -> usize {
self.archive.blocks.len()
}
pub fn block_indices(&self) -> impl Iterator<Item = BlockIndex> + use<> {
(0..self.archive.blocks.len()).map(BlockIndex)
}
pub fn block(&self, index: BlockIndex) -> &Block {
&self.archive.blocks[index.0]
}
pub fn file_block(&self, file: usize) -> Option<BlockIndex> {
self.archive
.stream_map
.file_block_index
.get(file)
.copied()
.flatten()
.map(BlockIndex)
}
pub fn block_first_file(&self, block: BlockIndex) -> usize {
self.archive.stream_map.block_first_file_index[block.0]
}
pub fn block_first_pack(&self, block: BlockIndex) -> usize {
self.archive.stream_map.block_first_pack_stream_index()[block.0]
}
pub fn next_block_first_pack(&self, block: BlockIndex) -> Option<usize> {
self.archive
.stream_map
.block_first_pack_stream_index()
.get(block.0 + 1)
.copied()
}
pub fn pack_stream_offsets(&self) -> &[u64] {
self.archive.stream_map.pack_stream_offsets()
}
}
pub fn read_sevenz_header<R: Read + Seek>(source: &mut R) -> Result<SevenZHeader> {
match Archive::read(&mut *source, &Password::empty()) {
Ok(archive) => SevenZHeader::check(archive),
Err(e) if super::is_password_error(&e) => Err(common::encrypted_archive_error()),
Err(e) if is_empty_sevenz_archive(&e, source) => Ok(SevenZHeader::empty()),
Err(e) => Err(ArchiveError::InvalidArchive(format!(
"failed to open 7z archive: {e}"
))),
}
}
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 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 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)).unwrap_err();
assert_matches!(&err, ArchiveError::InvalidArchive(m) if m.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)).unwrap_err();
assert_matches!(&err, ArchiveError::InvalidArchive(m) if m.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[..])).unwrap();
assert!(header.files().is_empty());
assert_eq!(header.block_count(), 0);
}
}