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