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::encryption::Credentials;
use crate::formats::SevenZArchive;
use crate::formats::TarArchive;
use crate::formats::ZipArchive;
use crate::formats::compression::CompressionCodec;
use crate::formats::compression::DecoderLimits;
use crate::formats::detect::ArchiveType;
use crate::formats::detect::FormatFamily;
use crate::formats::detect::match_signature;
use crate::formats::detect::peek_header;
use crate::formats::source_fault::SourceRead;
use crate::formats::source_fault::SourceTap;
use crate::formats::source_fault::TapSource;
use crate::inspection::ArchiveManifest;
use crate::inspection::VerificationReport;
use crate::inspection::integrity::TarTrailer;
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 of_stream<R: Read + Send + 'a>(reader: R, format: ArchiveType) -> Result<Self> {
match format.family() {
FormatFamily::Tar(codec) => Ok(Self::tar(reader, codec)),
FormatFamily::Seekable(container) => Err(ArchiveError::ReaderFormat(
ReaderFormatError::NeedsSeek(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,
listing: &mut ListPass<'_, '_>,
) -> Result<ArchiveManifest> {
let format = self.format();
match self.source {
Source::Tar { stream, codec } => {
let decoded = decode_tar_stream(stream, codec, DecoderLimits::of(config))?;
let source = decoded.source();
list_tar_stream(decoded.stream, source, codec, format, config, listing)
}
Source::Seekable {
reader,
format: SeekableFormat::Zip,
} => ZipArchive::open(reader, config, listing.credentials().clone())?
.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,
options: VerificationOptions,
progress: &mut dyn ProgressCallback,
credentials: Credentials,
) -> Result<VerificationReport> {
let format = self.format();
match self.source {
Source::Tar { stream, codec } => {
let decoded = decode_tar_stream(stream, codec, DecoderLimits::of(config))?;
let source = decoded.source();
verify_with(config, options, progress, |listing| {
list_tar_stream(decoded.stream, source, codec, format, config, listing)
})
}
Source::Seekable {
reader,
format: SeekableFormat::Zip,
} => ZipArchive::open(reader, config, credentials)?
.verify_with_progress(config, options, progress),
Source::Seekable {
reader,
format: SeekableFormat::SevenZ,
} => SevenZArchive::open(reader, config, &credentials)?
.verify_with_progress(config, options, progress),
}
}
}
pub(crate) struct TarStream<'r> {
pub(crate) stream: Box<dyn Read + Send + 'r>,
tap: SourceTap,
}
impl TarStream<'_> {
pub(crate) fn source(&self) -> TapSource {
TapSource::Tapped(self.tap.clone())
}
}
pub(crate) fn decode_tar_stream<'r, R: Read + Send + 'r>(
reader: R,
codec: Option<CompressionCodec>,
limits: DecoderLimits,
) -> Result<TarStream<'r>> {
let tap = SourceTap::default();
let buffered = BufReader::new(SourceRead::new(reader, tap.clone()));
let stream = match codec {
Some(codec) => codec.decoder(buffered, limits)?,
None => Box::new(buffered),
};
Ok(TarStream { stream, tap })
}
pub(crate) fn tar_archive<'r, R: Read + Send + 'r>(
reader: R,
codec: Option<CompressionCodec>,
config: &SecurityConfig,
) -> Result<TarArchive<Box<dyn Read + Send + 'r>>> {
let trailer = TarTrailer::for_codec(codec);
decode_tar_stream(reader, codec, DecoderLimits::of(config))
.map(|decoded| TarArchive::from_stream(decoded, trailer, config))
}
#[cfg(test)]
mod tests {
use std::assert_matches;
use super::*;
use crate::SeekableFormat;
#[test]
fn test_of_stream_keeps_every_tar_codec() -> Result<()> {
for format in [
ArchiveType::Tar,
ArchiveType::TarBz2,
ArchiveType::TarXz,
ArchiveType::TarZst,
] {
let reader = ArchiveReader::of_stream(&b""[..], format)?;
assert_eq!(reader.format(), format);
}
Ok(())
}
#[test]
fn test_of_stream_refuses_seekable_formats() {
for (format, container) in [
(ArchiveType::Zip, SeekableFormat::Zip),
(ArchiveType::SevenZ, SeekableFormat::SevenZ),
] {
assert_matches!(
ArchiveReader::of_stream(&b""[..], format),
Err(ArchiveError::ReaderFormat(ReaderFormatError::NeedsSeek(c))) if c == container
);
}
}
}