Skip to main content

exarch_core/
reader.rs

1//! Archives read from a caller-supplied reader instead of a path.
2//!
3//! [`ArchiveReader`] is the input of [`list_reader`](crate::list_reader),
4//! [`verify_reader`](crate::verify_reader) and
5//! [`extract_to_sink`](crate::extract_to_sink). The constructors encode what
6//! each format needs: a TAR stream is forward-only, so any `Read` will do,
7//! while ZIP and 7z read a directory at the end of the archive and need `Seek`.
8//! The caller states the format with [`ArchiveReader::tar`],
9//! [`ArchiveReader::seekable`] or [`ArchiveReader::of_type`], or has it
10//! sniffed from the leading bytes by [`ArchiveReader::detect`] and
11//! [`ArchiveReader::detect_stream`].
12
13use std::io::BufReader;
14use std::io::Cursor;
15use std::io::Read;
16use std::io::Seek;
17use std::io::SeekFrom;
18
19use crate::ArchiveError;
20use crate::ProgressCallback;
21use crate::ReaderFormatError;
22use crate::Result;
23use crate::SecurityConfig;
24use crate::VerificationOptions;
25use crate::config::Validated;
26use crate::formats::SevenZArchive;
27use crate::formats::TarArchive;
28use crate::formats::ZipArchive;
29use crate::formats::compression::CompressionCodec;
30use crate::formats::detect::ArchiveType;
31use crate::formats::detect::FormatFamily;
32use crate::formats::detect::match_signature;
33use crate::formats::detect::peek_header;
34use crate::inspection::ArchiveManifest;
35use crate::inspection::VerificationReport;
36use crate::inspection::list::ListPass;
37use crate::inspection::list::list_tar_stream;
38use crate::inspection::verify::verify_with;
39
40/// A seekable byte source.
41pub(crate) trait ReadSeek: Read + Seek + Send {}
42
43impl<T: Read + Seek + Send> ReadSeek for T {}
44
45/// A format that is read through a directory at the end of the archive, and
46/// so needs a seekable source.
47///
48/// # Examples
49///
50/// ```
51/// use exarch_core::SeekableFormat;
52///
53/// assert_eq!(SeekableFormat::Zip.as_str(), "zip");
54/// ```
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56#[non_exhaustive]
57pub enum SeekableFormat {
58    /// A ZIP archive.
59    Zip,
60    /// A 7z archive.
61    SevenZ,
62}
63
64impl SeekableFormat {
65    /// The format's lower-case name.
66    #[must_use]
67    pub const fn as_str(self) -> &'static str {
68        match self {
69            Self::Zip => "zip",
70            Self::SevenZ => "7z",
71        }
72    }
73}
74
75pub(crate) enum Source<'a> {
76    Tar {
77        stream: Box<dyn Read + Send + 'a>,
78        codec: Option<CompressionCodec>,
79    },
80    Seekable {
81        reader: Box<dyn ReadSeek + 'a>,
82        format: SeekableFormat,
83    },
84}
85
86/// An archive supplied as a reader.
87///
88/// # Examples
89///
90/// ```
91/// use exarch_core::ArchiveReader;
92/// use exarch_core::SeekableFormat;
93/// use exarch_core::formats::detect::ArchiveType;
94/// use std::io::Cursor;
95///
96/// let tar = ArchiveReader::tar(Cursor::new(Vec::<u8>::new()), None);
97/// assert_eq!(tar.format(), ArchiveType::Tar);
98///
99/// let zip = ArchiveReader::seekable(Cursor::new(Vec::<u8>::new()), SeekableFormat::Zip);
100/// assert_eq!(zip.format(), ArchiveType::Zip);
101/// ```
102pub struct ArchiveReader<'a> {
103    source: Source<'a>,
104}
105
106impl std::fmt::Debug for ArchiveReader<'_> {
107    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108        f.debug_struct("ArchiveReader")
109            .field("format", &self.format())
110            .finish_non_exhaustive()
111    }
112}
113
114impl<'a> ArchiveReader<'a> {
115    /// A TAR archive in `reader`, compressed with `codec` when given.
116    ///
117    /// The reader holds the raw bytes. The decoder is applied when the
118    /// operation runs, with the decoder memory limit of its config.
119    #[must_use]
120    pub fn tar<R: Read + Send + 'a>(reader: R, codec: Option<CompressionCodec>) -> Self {
121        Self {
122            source: Source::Tar {
123                stream: Box::new(reader),
124                codec,
125            },
126        }
127    }
128
129    /// A ZIP or 7z archive in `reader`.
130    ///
131    /// The archive must start at offset 0 of the reader: 7z addresses its
132    /// blocks by absolute offsets, so an archive embedded in a larger stream
133    /// needs a reader that maps offset 0 to the start of the archive.
134    #[must_use]
135    pub fn seekable<R: Read + Seek + Send + 'a>(reader: R, format: SeekableFormat) -> Self {
136        Self {
137            source: Source::Seekable {
138                reader: Box::new(reader),
139                format,
140            },
141        }
142    }
143
144    /// An archive of the stated `format` in `reader`, whichever way it is read.
145    ///
146    /// The reader must start at the archive, as for [`Self::tar`] and
147    /// [`Self::seekable`].
148    ///
149    /// # Examples
150    ///
151    /// ```
152    /// use exarch_core::ArchiveReader;
153    /// use exarch_core::formats::detect::ArchiveType;
154    /// use std::io::Cursor;
155    ///
156    /// let reader = ArchiveReader::of_type(Cursor::new(Vec::<u8>::new()), ArchiveType::TarGz);
157    /// assert_eq!(reader.format(), ArchiveType::TarGz);
158    /// ```
159    #[must_use]
160    pub fn of_type<R: Read + Seek + Send + 'a>(reader: R, format: ArchiveType) -> Self {
161        match format.family() {
162            FormatFamily::Tar(codec) => Self::tar(reader, codec),
163            FormatFamily::Seekable(container) => Self::seekable(reader, container),
164        }
165    }
166
167    /// An archive held in memory: of the stated `format`, or detected from its
168    /// leading bytes when `format` is `None`.
169    ///
170    /// # Errors
171    ///
172    /// With `format` of `None`, the errors of [`Self::detect`].
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use exarch_core::ArchiveReader;
178    /// use exarch_core::formats::detect::ArchiveType;
179    ///
180    /// let bytes = b"PK\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0".to_vec();
181    /// let detected = ArchiveReader::from_bytes(bytes.clone(), None)?;
182    /// assert_eq!(detected.format(), ArchiveType::Zip);
183    ///
184    /// let stated = ArchiveReader::from_bytes(bytes, Some(ArchiveType::Tar))?;
185    /// assert_eq!(stated.format(), ArchiveType::Tar);
186    /// # Ok::<(), exarch_core::ArchiveError>(())
187    /// ```
188    pub fn from_bytes<B: AsRef<[u8]> + Send + 'a>(
189        bytes: B,
190        format: Option<ArchiveType>,
191    ) -> Result<Self> {
192        let cursor = Cursor::new(bytes);
193        match format {
194            Some(format) => Ok(Self::of_type(cursor, format)),
195            None => Self::detect(cursor),
196        }
197    }
198
199    /// Detects the format of the archive at the current position of a
200    /// seekable `reader` from its leading bytes.
201    ///
202    /// The reader is left at the position it was in. A TAR archive may start
203    /// anywhere; a ZIP or 7z archive must start at offset 0, because both
204    /// address their records by absolute offsets. Where several signatures
205    /// match, the first in table order wins: a container magic at the start
206    /// beats the `ustar` marker at offset 257, and so do gzip, xz and zstd
207    /// magics. Only `BZh` can open a member name, so a checksum-valid ustar
208    /// header that does not start with a complete bzip2 stream header is read
209    /// as a plain TAR; input valid under both readings stays bzip2. A v7 TAR
210    /// (no `ustar` marker)
211    /// and a ZIP with data prepended are not recognized; use [`Self::tar`]
212    /// for the former.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`ArchiveError::ReaderFormat`] with `Unrecognized` if no
217    /// signature matches, or with `NotAtStart` if a ZIP or 7z signature is
218    /// found at a position other than 0. Returns [`ArchiveError::Io`] if the
219    /// reader cannot be read or repositioned.
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use exarch_core::ArchiveReader;
225    /// use exarch_core::formats::detect::ArchiveType;
226    /// use std::io::Cursor;
227    ///
228    /// let empty_zip = b"PK\x05\x06\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
229    /// let reader = ArchiveReader::detect(Cursor::new(empty_zip.to_vec()))?;
230    /// assert_eq!(reader.format(), ArchiveType::Zip);
231    /// # Ok::<(), exarch_core::ArchiveError>(())
232    /// ```
233    pub fn detect<R: Read + Seek + Send + 'a>(mut reader: R) -> Result<Self> {
234        let start = reader.stream_position().map_err(ArchiveError::Io)?;
235        let header = peek_header(&mut reader).map_err(ArchiveError::Io)?;
236        reader
237            .seek(SeekFrom::Start(start))
238            .map_err(ArchiveError::Io)?;
239        let format = match_signature(header.as_slice())
240            .ok_or(ArchiveError::ReaderFormat(ReaderFormatError::Unrecognized))?;
241        match format.family() {
242            FormatFamily::Seekable(container) if start != 0 => Err(ArchiveError::ReaderFormat(
243                ReaderFormatError::NotAtStart(container),
244            )),
245            _ => Ok(Self::of_type(reader, format)),
246        }
247    }
248
249    /// Detects the format of a forward-only `reader` from its leading bytes.
250    ///
251    /// Only TAR streams can be read without seeking. The bytes consumed for
252    /// detection are replayed in front of the rest of the stream, so nothing
253    /// is lost. The signature rules are those of [`Self::detect`]. Up to 512
254    /// bytes are peeked, or the stream is read to its end if it is shorter.
255    ///
256    /// # Errors
257    ///
258    /// Returns [`ArchiveError::ReaderFormat`] with `NeedsSeek` if the bytes
259    /// are a ZIP or 7z signature, or with `Unrecognized` if no signature
260    /// matches. Returns [`ArchiveError::Io`] if the reader cannot be read.
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use std::assert_matches;
266    ///
267    /// use exarch_core::ArchiveError;
268    /// use exarch_core::ArchiveReader;
269    /// use exarch_core::ReaderFormatError;
270    /// use exarch_core::SeekableFormat;
271    ///
272    /// let zip: &[u8] = b"PK\x03\x04 and the rest";
273    /// assert_matches!(
274    ///     ArchiveReader::detect_stream(zip),
275    ///     Err(ArchiveError::ReaderFormat(ReaderFormatError::NeedsSeek(
276    ///         SeekableFormat::Zip
277    ///     )))
278    /// );
279    /// ```
280    pub fn detect_stream<R: Read + Send + 'a>(mut reader: R) -> Result<Self> {
281        let header = peek_header(&mut reader).map_err(ArchiveError::Io)?;
282        let format = match_signature(header.as_slice())
283            .ok_or(ArchiveError::ReaderFormat(ReaderFormatError::Unrecognized))?;
284        match format.family() {
285            FormatFamily::Tar(codec) => {
286                let replay = Cursor::new(header.as_slice().to_vec());
287                Ok(Self::tar(replay.chain(reader), codec))
288            }
289            FormatFamily::Seekable(container) => Err(ArchiveError::ReaderFormat(
290                ReaderFormatError::NeedsSeek(container),
291            )),
292        }
293    }
294
295    /// The format the reader was declared to hold.
296    #[must_use]
297    pub const fn format(&self) -> ArchiveType {
298        match self.source {
299            Source::Tar { codec, .. } => ArchiveType::tar_with(codec),
300            Source::Seekable {
301                format: SeekableFormat::Zip,
302                ..
303            } => ArchiveType::Zip,
304            Source::Seekable {
305                format: SeekableFormat::SevenZ,
306                ..
307            } => ArchiveType::SevenZ,
308        }
309    }
310
311    pub(crate) fn into_source(self) -> Source<'a> {
312        self.source
313    }
314
315    pub(crate) fn list(
316        self,
317        config: &SecurityConfig<Validated>,
318        listing: &mut ListPass<'_, '_>,
319    ) -> Result<ArchiveManifest> {
320        let format = self.format();
321        match self.source {
322            Source::Tar { stream, codec } => {
323                let decoded = decode_tar_stream(stream, codec, config.max_decoder_memory)?;
324                list_tar_stream(decoded, codec, format, config, listing)
325            }
326            Source::Seekable {
327                reader,
328                format: SeekableFormat::Zip,
329            } => ZipArchive::new(reader)?.list_with(config, listing),
330            Source::Seekable {
331                reader,
332                format: SeekableFormat::SevenZ,
333            } => crate::inspection::list::list_sevenz_reader(reader, config, listing),
334        }
335    }
336
337    pub(crate) fn verify(
338        self,
339        config: &SecurityConfig<Validated>,
340        options: VerificationOptions,
341        progress: &mut dyn ProgressCallback,
342    ) -> Result<VerificationReport> {
343        let format = self.format();
344        match self.source {
345            Source::Tar { stream, codec } => {
346                let decoded = decode_tar_stream(stream, codec, config.max_decoder_memory)?;
347                verify_with(config, options, progress, |listing| {
348                    list_tar_stream(decoded, codec, format, config, listing)
349                })
350            }
351            Source::Seekable {
352                reader,
353                format: SeekableFormat::Zip,
354            } => ZipArchive::new(reader)?.verify_with_progress(config, options, progress),
355            Source::Seekable {
356                reader,
357                format: SeekableFormat::SevenZ,
358            } => SevenZArchive::new(reader)?.verify_with_progress(config, options, progress),
359        }
360    }
361}
362
363/// Wraps a TAR byte stream in its decoder.
364///
365/// # Errors
366///
367/// Returns an error if the decoder cannot be initialised.
368pub(crate) fn decode_tar_stream<'r, R: Read + Send + 'r>(
369    reader: R,
370    codec: Option<CompressionCodec>,
371    max_decoder_memory: u64,
372) -> Result<Box<dyn Read + Send + 'r>> {
373    let buffered = BufReader::new(reader);
374    match codec {
375        Some(codec) => codec.decoder(buffered, max_decoder_memory),
376        None => Ok(Box::new(buffered)),
377    }
378}
379
380/// Opens a TAR stream on `reader`; the owner of the stream reads archive
381/// entries from it.
382pub(crate) fn tar_archive<'r, R: Read + Send + 'r>(
383    reader: R,
384    codec: Option<CompressionCodec>,
385    max_decoder_memory: u64,
386) -> Result<TarArchive<Box<dyn Read + Send + 'r>>> {
387    decode_tar_stream(reader, codec, max_decoder_memory).map(TarArchive::new)
388}