use super::common;
use super::occupant::OccupantPolicy;
use super::output_root::OutputRoot;
use super::traits::ArchiveFormat;
use super::traits::sealed;
use crate::ArchiveError;
use crate::EntryCompression;
use crate::ExtractionOptions;
use crate::ExtractionReport;
use crate::ExtractionWarning;
use crate::Malformation;
use crate::ProgressCallback;
use crate::Result;
use crate::SecurityConfig;
use crate::SinkOptions;
use crate::VerificationOptions;
use crate::Violation;
use crate::encryption::Credentials;
use crate::inspection::report::Finding;
use crate::inspection::report::Heuristic;
use crate::inspection::report::IssueSeverity;
use crate::inspection::report::VerificationIssue;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use std::sync::Arc;
#[derive(Debug, Clone)]
struct CachedEntry {
name: String,
size: u64,
class: SevenZClass,
compression: EntryCompression,
}
const SIGNATURE_HEADER_LEN: usize = 32;
const SIGNATURE_HEADER_SIZE: u64 = SIGNATURE_HEADER_LEN as u64;
#[derive(Debug)]
pub(crate) struct SevenZArchive<R: Read + Seek> {
source: R,
entries: Vec<CachedEntry>,
header: SevenZHeader,
config: Arc<SecurityConfig>,
}
impl<R: Read + Seek> SevenZArchive<R> {
#[cfg(test)]
pub(crate) fn new(source: R, config: &SecurityConfig) -> Result<Self> {
Self::open(source, config, &Credentials::default())
}
pub(crate) fn open(
mut source: R,
config: &SecurityConfig,
credentials: &Credentials,
) -> Result<Self> {
let header =
open_sevenz_header(&mut source, HeaderLimit::from_config(config), credentials)?;
let source_len = source.seek(SeekFrom::End(0)).map_err(ArchiveError::Io)?;
let compression = sevenz_entry_compression(&header, source_len)?;
let entries: Vec<CachedEntry> = header
.files()
.iter()
.zip(compression)
.map(|(e, compression)| CachedEntry {
name: e.name.clone(),
size: e.size,
class: SevenZClass::of(e),
compression,
})
.collect();
source.rewind().map_err(ArchiveError::Io)?;
Ok(Self {
source,
entries,
header,
config: Arc::new(config.clone()),
})
}
}
impl<R: Read + Seek> SevenZArchive<R> {
fn anti_item_count(&self) -> u64 {
let count = self
.entries
.iter()
.filter(|entry| entry.class == SevenZClass::AntiItem)
.count();
u64::try_from(count).unwrap_or(u64::MAX)
}
}
fn push_anti_item_warning(report: &mut ExtractionReport, count: u64) {
if count > 0 {
report.add_warning(ExtractionWarning::AntiItemsSkipped { count });
}
}
fn anti_item_issue(count: u64) -> Option<VerificationIssue> {
(count > 0).then(|| {
VerificationIssue::new(
IssueSeverity::Info,
Finding::Heuristic(Heuristic::AntiItemsSkipped { count }),
)
})
}
impl<R: Read + Seek> sealed::Sealed for SevenZArchive<R> {}
impl<R: Read + Seek> ArchiveFormat for SevenZArchive<R> {
fn extract<'o>(
mut self,
output: impl Into<OutputRoot<'o>>,
options: &ExtractionOptions,
progress: &mut dyn ProgressCallback,
) -> Result<ExtractionReport> {
let config = Arc::clone(&self.config);
let output = output.into().with_record_budget(
OccupantPolicy::new(options.existing_files, config.repeated_paths).record_budget(),
);
self.admit(&config)?.extract_with(
|config| SevenZHostTarget::create(output, config),
SinkOptions::existing_files_of(options),
progress,
)
}
#[cfg(test)]
fn list(mut self) -> Result<crate::inspection::ArchiveManifest> {
use crate::inspection::list::ListPass;
use crate::inspection::list::list_sevenz_parsed;
let config = Arc::clone(&self.config);
list_sevenz_parsed(
&self.header,
&mut self.source,
&config,
&mut ListPass::strict(),
)
}
#[cfg(test)]
fn verify(
mut self,
options: VerificationOptions,
) -> Result<crate::inspection::VerificationReport> {
let config = Arc::clone(&self.config);
self.verify_with_progress(&config, options, &mut crate::NoopProgress)
}
}
impl<R: Read + Seek> SevenZArchive<R> {
pub(crate) fn verify_with_progress(
&mut self,
config: &SecurityConfig,
options: VerificationOptions,
progress: &mut dyn ProgressCallback,
) -> Result<crate::inspection::VerificationReport> {
use crate::inspection::list::list_sevenz_parsed;
use crate::inspection::report::ArchiveStructure;
use crate::inspection::verify::list_for_verify;
use crate::inspection::verify::verify_manifest_with_structure;
let mut issues = refusal_issues(&sevenz_refusals(&self.header, config));
issues.extend(anti_item_issue(self.anti_item_count()));
let listed = list_for_verify(config, options, progress, |listing| {
list_sevenz_parsed(&self.header, &mut self.source, config, listing)
})?;
let structure = ArchiveStructure::of_manifest(&listed.manifest).with_refusals(&issues);
Ok(verify_manifest_with_structure(
&listed.manifest,
config,
&structure,
listed.integrity,
))
}
}
pub(crate) fn is_password_error(error: &sevenz_rust2::Error) -> bool {
matches!(
error,
sevenz_rust2::Error::PasswordRequired | sevenz_rust2::Error::MaybeBadPassword(_)
)
}
impl From<sevenz_rust2::Error> for ArchiveError {
fn from(err: sevenz_rust2::Error) -> Self {
match err {
sevenz_rust2::Error::PasswordRequired => return common::encrypted_archive_error(),
sevenz_rust2::Error::MaybeBadPassword(_) => {
return Violation::Encrypted {
reason: crate::EncryptionRefusal::WrongPasswordOrCorrupt,
name: None,
}
.into();
}
_ => {}
}
match err {
sevenz_rust2::Error::Io(io_err, _) => Self::Io(io_err),
sevenz_rust2::Error::FileOpen(io_err, path) => Self::Io(std::io::Error::new(
io_err.kind(),
crate::IoContext::new("failed to open a 7z file", format!("{path}: {io_err}")),
)),
other => Self::from(Malformation::SevenZLibraryError {
detail: other.to_string().into(),
}),
}
}
}
#[cfg(test)]
mod link_walk_tests;
#[cfg(test)]
mod parallel_tests;
#[cfg(test)]
mod sequential_crc_tests;
pub(crate) use admit::iter_sevenz_refusals;
pub(crate) use admit::refusal_issues;
pub(crate) use admit::sevenz_entry_compression;
pub(crate) use admit::sevenz_refusals;
pub(crate) use classify::SevenZClass;
pub(crate) use classify::SevenZKind;
pub(crate) use classify::file_permissions;
pub(crate) use header::FileIndex;
pub(crate) use header::HeaderLimit;
pub(crate) use header::SEVENZ_MAGIC;
pub(crate) use header::SevenZHeader;
pub(crate) use header::open_sevenz_header;
#[cfg(test)]
pub(crate) use header::read_sevenz_header;
use host::SevenZHostTarget;
pub(crate) use links::LinkCapture;
pub(crate) use links::LinkOutcome;
pub(crate) use links::LinkTable;
pub(crate) use links::StoredLinkTarget;
pub(crate) use links::deliver_undecoded_links;
pub(crate) use links::walk_sevenz_links;
pub(crate) use verify::is_decode_announced;
pub(crate) use verify::verify_sevenz_blocks;
mod admit;
mod classify;
mod decode;
mod extract;
mod header;
mod header_probe;
mod host;
mod links;
mod lzma2;
mod prefetched;
mod raw_key;
mod sink;
mod verify;
mod write;
#[cfg(test)]
mod tests;