exarch-core 0.9.0

Memory-safe archive extraction library with security validation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Archive creation into a caller-supplied writer instead of a path.
//!
//! [`ArchiveWriter`] is the destination of
//! [`CreateRequest::write`](crate::CreateRequest::write). The constructors
//! encode what each format needs: a TAR stream is forward-only, so any `Write`
//! will do, while ZIP patches earlier records and needs `Seek`. The
//! format is stated by the caller; nothing is derived from a file name.
//!
//! On error the writer may already hold a partial archive; the caller owns it
//! and decides whether to discard it.

use std::io::Seek;
use std::io::Write;
use std::path::Path;

use crate::CreationConfig;
use crate::CreationReport;
use crate::ProgressCallback;
use crate::Result;
use crate::creation::staged::ExcludedOutput;
use crate::creation::tar::write_tar;
use crate::creation::zip::write_zip;
use crate::formats::compression::CompressionCodec;
use crate::formats::detect::CreatableFormat;
use crate::formats::detect::CreationFamily;

/// A seekable byte destination.
pub(crate) trait WriteSeek: Write + Seek + Send {}

impl<T: Write + Seek + Send> WriteSeek for T {}

/// Counts the bytes that pass through to the inner writer.
#[derive(Debug)]
pub(crate) struct CountingWriter<W> {
    inner: W,
    bytes: u64,
}

impl<W> CountingWriter<W> {
    pub(crate) const fn new(inner: W) -> Self {
        Self { inner, bytes: 0 }
    }

    pub(crate) const fn bytes(&self) -> u64 {
        self.bytes
    }
}

impl<W: Write> Write for CountingWriter<W> {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        let written = self.inner.write(buf)?;
        self.bytes = self.bytes.saturating_add(written as u64);
        Ok(written)
    }

    fn flush(&mut self) -> std::io::Result<()> {
        self.inner.flush()
    }
}

enum Destination<'a> {
    Tar {
        stream: Box<dyn Write + Send + 'a>,
        codec: Option<CompressionCodec>,
    },
    Zip {
        stream: Box<dyn WriteSeek + 'a>,
    },
}

/// An archive destination supplied as a writer.
///
/// Pass `&mut writer` to keep the writer after the call.
///
/// # Examples
///
/// ```
/// use exarch_core::ArchiveWriter;
/// use exarch_core::formats::CompressionCodec;
/// use exarch_core::formats::detect::CreatableFormat;
/// use std::io::Cursor;
///
/// let tar = ArchiveWriter::tar(Vec::<u8>::new(), Some(CompressionCodec::Gzip));
/// assert_eq!(tar.format(), CreatableFormat::TarGz);
///
/// let zip = ArchiveWriter::zip(Cursor::new(Vec::<u8>::new()));
/// assert_eq!(zip.format(), CreatableFormat::Zip);
/// ```
pub struct ArchiveWriter<'a> {
    destination: Destination<'a>,
}

impl std::fmt::Debug for ArchiveWriter<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ArchiveWriter")
            .field("format", &self.format())
            .finish_non_exhaustive()
    }
}

impl<'a> ArchiveWriter<'a> {
    /// A TAR archive written to `writer`, compressed with `codec` when given.
    ///
    /// The compression level comes from `CreationConfig::compression_level`.
    #[must_use]
    pub fn tar<W: Write + Send + 'a>(writer: W, codec: Option<CompressionCodec>) -> Self {
        Self {
            destination: Destination::Tar {
                stream: Box::new(writer),
                codec,
            },
        }
    }

    /// A ZIP archive written to `writer`.
    ///
    /// The writer must be positioned at offset 0 when the archive is created,
    /// otherwise creation fails with
    /// [`InvalidConfiguration`](crate::ArchiveError::InvalidConfiguration).
    #[must_use]
    pub fn zip<W: Write + Seek + Send + 'a>(writer: W) -> Self {
        Self {
            destination: Destination::Zip {
                stream: Box::new(writer),
            },
        }
    }

    /// An archive of the given `format` written to `writer`.
    ///
    /// Picks [`tar`](Self::tar) or [`zip`](Self::zip) from `format`, for
    /// callers that hold the format as a value. `Seek` is required because
    /// the format is only known at run time.
    ///
    /// # Examples
    ///
    /// ```
    /// use exarch_core::ArchiveWriter;
    /// use exarch_core::formats::detect::CreatableFormat;
    /// use std::io::Cursor;
    ///
    /// let writer = ArchiveWriter::of_type(Cursor::new(Vec::<u8>::new()), CreatableFormat::TarZst);
    /// assert_eq!(writer.format(), CreatableFormat::TarZst);
    /// ```
    pub fn of_type<W: Write + Seek + Send + 'a>(writer: W, format: CreatableFormat) -> Self {
        match format.family() {
            CreationFamily::Tar(codec) => Self::tar(writer, codec),
            CreationFamily::Zip => Self::zip(writer),
        }
    }

    /// The format the writer was declared to receive.
    #[must_use]
    pub const fn format(&self) -> CreatableFormat {
        match self.destination {
            Destination::Tar { codec, .. } => CreatableFormat::tar_with(codec),
            Destination::Zip { .. } => CreatableFormat::Zip,
        }
    }

    /// Writes the archive of `sources` to the destination.
    pub(crate) fn write<P: AsRef<Path>>(
        self,
        sources: &[P],
        config: &CreationConfig,
        progress: &mut dyn ProgressCallback,
    ) -> Result<CreationReport> {
        let excluded = ExcludedOutput::none();
        match self.destination {
            Destination::Tar { stream, codec } => {
                write_tar(stream, codec, sources, config, &excluded, progress)
            }
            Destination::Zip { stream } => {
                write_zip(stream, sources, config, &excluded, progress).map(|(report, _)| report)
            }
        }
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use super::*;
    use crate::ArchiveError;
    use crate::CreateRequest;
    use crate::SecurityConfig;
    use crate::api::create_archive;
    use crate::api::extract_archive;
    use std::assert_matches;
    use std::fs;
    use std::io::Cursor;
    use tempfile::TempDir;

    fn source_tree() -> TempDir {
        let src = TempDir::new().unwrap();
        fs::write(src.path().join("a.txt"), "alpha").unwrap();
        fs::create_dir(src.path().join("sub")).unwrap();
        fs::write(src.path().join("sub/b.txt"), "bravo".repeat(500)).unwrap();
        src
    }

    fn config() -> CreationConfig {
        CreationConfig::default()
            .with_exclude_patterns(vec![])
            .with_include_hidden(true)
    }

    const TAR_FORMATS: [(Option<CompressionCodec>, &str); 5] = [
        (None, "tar"),
        (Some(CompressionCodec::Gzip), "tar.gz"),
        (Some(CompressionCodec::Bzip2), "tar.bz2"),
        (Some(CompressionCodec::Xz), "tar.xz"),
        (Some(CompressionCodec::Zstd), "tar.zst"),
    ];

    fn assert_extracts_equal(archive: &Path, src: &Path) {
        let dest = TempDir::new().unwrap();
        extract_archive(archive, dest.path(), &SecurityConfig::default()).unwrap();
        let root = dest.path();
        assert_eq!(fs::read_to_string(root.join("a.txt")).unwrap(), "alpha");
        assert_eq!(
            fs::read(root.join("sub/b.txt")).unwrap(),
            fs::read(src.join("sub/b.txt")).unwrap()
        );
    }

    #[test]
    fn test_tar_round_trip_every_codec() {
        let src = source_tree();
        for (codec, ext) in TAR_FORMATS {
            let mut buf = Vec::new();
            let report = CreateRequest::new(&config())
                .write(ArchiveWriter::tar(&mut buf, codec), &[src.path()])
                .unwrap();
            assert_eq!(report.bytes_compressed, buf.len() as u64, "{ext}");
            assert_eq!(report.files_added, 2, "{ext}");

            let out = TempDir::new().unwrap();
            let archive = out.path().join(format!("out.{ext}"));
            fs::write(&archive, &buf).unwrap();
            assert_extracts_equal(&archive, src.path());
        }
    }

    #[test]
    fn test_zip_round_trip() {
        let src = source_tree();
        let mut out = Cursor::new(Vec::new());
        let report = CreateRequest::new(&config())
            .write(ArchiveWriter::zip(&mut out), &[src.path()])
            .unwrap();
        let buf = out.into_inner();
        assert_eq!(report.bytes_compressed, buf.len() as u64);

        let dir = TempDir::new().unwrap();
        let archive = dir.path().join("out.zip");
        fs::write(&archive, &buf).unwrap();
        assert_extracts_equal(&archive, src.path());
    }

    #[test]
    fn test_writer_output_equals_path_output() {
        let src = source_tree();
        let dir = TempDir::new().unwrap();
        for (codec, ext) in TAR_FORMATS {
            let path = dir.path().join(format!("p.{ext}"));
            let path_report = create_archive(&path, &[src.path()], &config()).unwrap();
            let mut buf = Vec::new();
            let report = CreateRequest::new(&config())
                .write(ArchiveWriter::tar(&mut buf, codec), &[src.path()])
                .unwrap();
            assert_eq!(fs::read(&path).unwrap(), buf, "{ext}");
            assert_eq!(
                path_report.bytes_compressed,
                fs::metadata(&path).unwrap().len()
            );
            assert_eq!(
                report.bytes_compressed, path_report.bytes_compressed,
                "{ext}"
            );
        }
    }

    #[test]
    fn test_path_zip_bytes_compressed_equals_file_length() {
        let src = source_tree();
        let dir = TempDir::new().unwrap();
        let path = dir.path().join("p.zip");
        let report = create_archive(&path, &[src.path()], &config()).unwrap();
        assert_eq!(report.bytes_compressed, fs::metadata(&path).unwrap().len());
    }

    #[test]
    fn test_create_to_bytes_round_trips_every_creatable_format() {
        let src = source_tree();
        for &format in CreatableFormat::ALL {
            let (bytes, report) = CreateRequest::new(&config())
                .to_bytes(format, &[src.path()])
                .unwrap();
            assert_eq!(report.bytes_compressed, bytes.len() as u64, "{format}");
            let reader = crate::ArchiveReader::from_bytes(bytes, None).unwrap();
            assert_eq!(
                crate::formats::detect::ArchiveType::from(format),
                reader.format()
            );
        }
    }

    #[test]
    fn test_create_to_bytes_zip_warns_about_extraction_ratio() {
        let src = TempDir::new().unwrap();
        fs::write(src.path().join("zeros"), vec![0u8; 100_000]).unwrap();
        let (_, report) = CreateRequest::new(&config())
            .to_bytes(CreatableFormat::Zip, &[src.path()])
            .unwrap();
        assert!(
            report
                .warnings
                .iter()
                .any(|warning| warning.to_string().contains("extraction ratio limit")),
            "{:?}",
            report.warnings
        );
        let (_, report) = CreateRequest::new(&config())
            .to_bytes(CreatableFormat::TarGz, &[src.path()])
            .unwrap();
        assert!(report.warnings.is_empty(), "{:?}", report.warnings);
    }

    #[test]
    fn test_of_type_round_trips_every_creatable_format() {
        let src = source_tree();
        for &format in CreatableFormat::ALL {
            let mut out = Cursor::new(Vec::new());
            let writer = ArchiveWriter::of_type(&mut out, format);
            assert_eq!(writer.format(), format);
            CreateRequest::new(&config())
                .write(writer, &[src.path()])
                .unwrap();
            assert!(!out.get_ref().is_empty());
        }
    }

    #[test]
    fn test_zip_writer_not_at_start_is_rejected() {
        let src = source_tree();
        let mut out = Cursor::new(vec![0u8; 4]);
        out.set_position(4);
        let result = CreateRequest::new(&config()).write(ArchiveWriter::zip(out), &[src.path()]);
        assert_matches!(result, Err(ArchiveError::InvalidConfiguration { .. }));
    }

    #[test]
    fn test_missing_source_is_an_error() {
        let result = CreateRequest::new(&config()).write(
            ArchiveWriter::tar(Vec::new(), None),
            &[Path::new("/nonexistent/exarch-source")],
        );
        assert!(result.is_err());
    }

    #[test]
    fn test_progress_events_match_path_creation() {
        #[derive(Default)]
        struct Recorder {
            starts: Vec<std::path::PathBuf>,
            completes: usize,
            done: usize,
        }
        impl ProgressCallback for Recorder {
            fn on_entry_start(&mut self, path: &Path, _position: crate::EntryPosition) {
                self.starts.push(path.to_path_buf());
            }

            fn on_bytes_written(&mut self, _bytes: u64) {}

            fn on_entry_complete(&mut self, _path: &Path) {
                self.completes += 1;
            }

            fn on_complete(&mut self) {
                self.done += 1;
            }
        }

        let src = source_tree();
        let dir = TempDir::new().unwrap();
        let mut by_path = Recorder::default();
        crate::CreateRequest::new(&config())
            .with_progress(&mut by_path)
            .create(
                &crate::OutputFile::replace(dir.path().join("p.tar")),
                &[src.path()],
            )
            .unwrap();
        let mut by_writer = Recorder::default();
        CreateRequest::new(&config())
            .with_progress(&mut by_writer)
            .write(ArchiveWriter::tar(Vec::new(), None), &[src.path()])
            .unwrap();
        assert_eq!(by_path.starts, by_writer.starts);
        assert_eq!(by_path.completes, by_writer.completes);
        assert_eq!((by_path.done, by_writer.done), (1, 1));
    }

    #[test]
    fn test_created_archive_lists_through_reader() {
        let src = source_tree();
        let mut buf = Vec::new();
        CreateRequest::new(&config())
            .write(
                ArchiveWriter::tar(&mut buf, Some(CompressionCodec::Zstd)),
                &[src.path()],
            )
            .unwrap();
        let manifest = crate::ListRequest::new(&SecurityConfig::default())
            .with_options(crate::ListOptions::default())
            .list_reader(crate::ArchiveReader::tar(
                Cursor::new(buf),
                Some(CompressionCodec::Zstd),
            ))
            .unwrap();
        assert!(manifest.total_entries() >= 2);
    }
}