use std::io::BufReader;
use std::io::Cursor;
use std::io::Read;
use std::io::Seek;
use std::io::SeekFrom;
use crate::ArchiveError;
use crate::ProgressCallback;
use crate::ReaderFormatError;
use crate::Result;
use crate::SecurityConfig;
use crate::VerificationOptions;
use crate::config::Validated;
use crate::formats::SevenZArchive;
use crate::formats::TarArchive;
use crate::formats::ZipArchive;
use crate::formats::compression::CompressionCodec;
use crate::formats::detect::ArchiveType;
use crate::formats::detect::FormatFamily;
use crate::formats::detect::match_signature;
use crate::formats::detect::peek_header;
use crate::inspection::ArchiveManifest;
use crate::inspection::VerificationReport;
use crate::inspection::list::ListPass;
use crate::inspection::list::list_tar_stream;
use crate::inspection::verify::verify_with;
pub(crate) trait ReadSeek: Read + Seek + Send {}
impl<T: Read + Seek + Send> ReadSeek for T {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeekableFormat {
Zip,
SevenZ,
}
impl SeekableFormat {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Zip => "zip",
Self::SevenZ => "7z",
}
}
}
pub(crate) enum Source<'a> {
Tar {
stream: Box<dyn Read + Send + 'a>,
codec: Option<CompressionCodec>,
},
Seekable {
reader: Box<dyn ReadSeek + 'a>,
format: SeekableFormat,
},
}
pub struct ArchiveReader<'a> {
source: Source<'a>,
}
impl std::fmt::Debug for ArchiveReader<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ArchiveReader")
.field("format", &self.format())
.finish_non_exhaustive()
}
}
impl<'a> ArchiveReader<'a> {
#[must_use]
pub fn tar<R: Read + Send + 'a>(reader: R, codec: Option<CompressionCodec>) -> Self {
Self {
source: Source::Tar {
stream: Box::new(reader),
codec,
},
}
}
#[must_use]
pub fn seekable<R: Read + Seek + Send + 'a>(reader: R, format: SeekableFormat) -> Self {
Self {
source: Source::Seekable {
reader: Box::new(reader),
format,
},
}
}
#[must_use]
pub fn of_type<R: Read + Seek + Send + 'a>(reader: R, format: ArchiveType) -> Self {
match format.family() {
FormatFamily::Tar(codec) => Self::tar(reader, codec),
FormatFamily::Seekable(container) => Self::seekable(reader, container),
}
}
pub fn from_bytes<B: AsRef<[u8]> + Send + 'a>(
bytes: B,
format: Option<ArchiveType>,
) -> Result<Self> {
let cursor = Cursor::new(bytes);
match format {
Some(format) => Ok(Self::of_type(cursor, format)),
None => Self::detect(cursor),
}
}
pub fn detect<R: Read + Seek + Send + 'a>(mut reader: R) -> Result<Self> {
let start = reader.stream_position().map_err(ArchiveError::Io)?;
let header = peek_header(&mut reader).map_err(ArchiveError::Io)?;
reader
.seek(SeekFrom::Start(start))
.map_err(ArchiveError::Io)?;
let format = match_signature(header.as_slice())
.ok_or(ArchiveError::ReaderFormat(ReaderFormatError::Unrecognized))?;
match format.family() {
FormatFamily::Seekable(container) if start != 0 => Err(ArchiveError::ReaderFormat(
ReaderFormatError::NotAtStart(container),
)),
_ => Ok(Self::of_type(reader, format)),
}
}
pub fn detect_stream<R: Read + Send + 'a>(mut reader: R) -> Result<Self> {
let header = peek_header(&mut reader).map_err(ArchiveError::Io)?;
let format = match_signature(header.as_slice())
.ok_or(ArchiveError::ReaderFormat(ReaderFormatError::Unrecognized))?;
match format.family() {
FormatFamily::Tar(codec) => {
let replay = Cursor::new(header.as_slice().to_vec());
Ok(Self::tar(replay.chain(reader), codec))
}
FormatFamily::Seekable(container) => Err(ArchiveError::ReaderFormat(
ReaderFormatError::NeedsSeek(container),
)),
}
}
#[must_use]
pub const fn format(&self) -> ArchiveType {
match self.source {
Source::Tar { codec, .. } => ArchiveType::tar_with(codec),
Source::Seekable {
format: SeekableFormat::Zip,
..
} => ArchiveType::Zip,
Source::Seekable {
format: SeekableFormat::SevenZ,
..
} => ArchiveType::SevenZ,
}
}
pub(crate) fn into_source(self) -> Source<'a> {
self.source
}
pub(crate) fn list(
self,
config: &SecurityConfig<Validated>,
listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
let format = self.format();
match self.source {
Source::Tar { stream, codec } => {
let decoded = decode_tar_stream(stream, codec, config.max_decoder_memory)?;
list_tar_stream(decoded, codec, format, config, listing)
}
Source::Seekable {
reader,
format: SeekableFormat::Zip,
} => ZipArchive::new(reader)?.list_with(config, listing),
Source::Seekable {
reader,
format: SeekableFormat::SevenZ,
} => crate::inspection::list::list_sevenz_reader(reader, config, listing),
}
}
pub(crate) fn verify(
self,
config: &SecurityConfig<Validated>,
options: VerificationOptions,
progress: &mut dyn ProgressCallback,
) -> Result<VerificationReport> {
let format = self.format();
match self.source {
Source::Tar { stream, codec } => {
let decoded = decode_tar_stream(stream, codec, config.max_decoder_memory)?;
verify_with(config, options, progress, |listing| {
list_tar_stream(decoded, codec, format, config, listing)
})
}
Source::Seekable {
reader,
format: SeekableFormat::Zip,
} => ZipArchive::new(reader)?.verify_with_progress(config, options, progress),
Source::Seekable {
reader,
format: SeekableFormat::SevenZ,
} => SevenZArchive::new(reader)?.verify_with_progress(config, options, progress),
}
}
}
pub(crate) fn decode_tar_stream<'r, R: Read + Send + 'r>(
reader: R,
codec: Option<CompressionCodec>,
max_decoder_memory: u64,
) -> Result<Box<dyn Read + Send + 'r>> {
let buffered = BufReader::new(reader);
match codec {
Some(codec) => codec.decoder(buffered, max_decoder_memory),
None => Ok(Box::new(buffered)),
}
}
pub(crate) fn tar_archive<'r, R: Read + Send + 'r>(
reader: R,
codec: Option<CompressionCodec>,
max_decoder_memory: u64,
) -> Result<TarArchive<Box<dyn Read + Send + 'r>>> {
decode_tar_stream(reader, codec, max_decoder_memory).map(TarArchive::new)
}