Skip to main content

exarch_core/sink/
callback.rs

1//! An [`EntrySink`] that hands every verified entry to a closure.
2
3use std::error::Error;
4use std::fmt;
5use std::io;
6
7use crate::ArchiveError;
8use crate::ArchiveReader;
9use crate::ExtractionReport;
10use crate::ProgressCallback;
11use crate::security::fs_view::PathModel;
12use crate::security::permissions::SanitizedMode;
13use crate::security::quota::AdmittedSize;
14use crate::sink::EntrySink;
15use crate::sink::MemoryEntry;
16use crate::sink::MemoryEntryKind;
17use crate::sink::MemoryExtractRequest;
18use crate::sink::MemoryFile;
19use crate::types::CheckedLinkTarget;
20use crate::types::SafePath;
21
22/// An entry delivered by a [`CallbackSink`].
23///
24/// Everything a [`MemorySink`](crate::MemorySink) can hold is
25/// [`Stored`](Self::Stored); a hardlink is delivered by reference instead,
26/// because the sink keeps no bytes to copy.
27///
28/// # Examples
29///
30/// ```
31/// use exarch_core::CallbackEntry;
32/// use exarch_core::MemoryEntry;
33/// use exarch_core::MemoryEntryKind;
34///
35/// let entry = CallbackEntry::from(MemoryEntry::Directory);
36/// assert_eq!(entry.kind(), MemoryEntryKind::Directory);
37/// ```
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum CallbackEntry {
41    /// A file, directory or symlink, as a [`MemorySink`](crate::MemorySink)
42    /// would store it.
43    Stored(MemoryEntry),
44    /// A hard link to an entry that was already delivered, by reference.
45    Hardlink {
46        /// The validated, root-relative path of an already delivered entry: a
47        /// file, or an earlier hardlink (a chain is delivered link by link).
48        target: SafePath,
49    },
50}
51
52impl CallbackEntry {
53    /// What the entry holds.
54    #[must_use]
55    pub const fn kind(&self) -> MemoryEntryKind {
56        match self {
57            Self::Stored(entry) => entry.kind(),
58            Self::Hardlink { .. } => MemoryEntryKind::Hardlink,
59        }
60    }
61}
62
63impl From<MemoryEntry> for CallbackEntry {
64    fn from(entry: MemoryEntry) -> Self {
65        Self::Stored(entry)
66    }
67}
68
69/// An [`EntrySink`] that delivers each entry to a closure as it is verified.
70///
71/// The closure receives the entry's validated path and a [`CallbackEntry`]. A
72/// file is delivered whole, after all of its bytes were written and the stream
73/// delivered exactly the size the archive declares. The memory held at any
74/// moment is one file, bounded by the configuration's `max_file_size`; the sink
75/// keeps nothing after delivery.
76///
77/// # Entries are provisional
78///
79/// An entry is delivered as soon as it is verified, before the rest of the
80/// archive is read. A later failure (a corrupt or refused member further on)
81/// ends the extraction after earlier entries were delivered, so treat what the
82/// closure received as final only once the extraction returned `Ok`. A
83/// stream-level checksum is checked last: the gzip trailer CRC of a `.tar.gz`
84/// is verified after the end-of-archive marker, so a corrupt compressed stream
85/// ends the extraction with an error only after its entries were delivered.
86///
87/// An error from the closure ends the extraction like any other sink error
88/// (see [`EntrySink`]).
89///
90/// # What `target` means
91///
92/// - A [`MemoryEntry::Symlink`] target is spelled as the archive stores it and
93///   is relative to the directory of the link.
94/// - A [`CallbackEntry::Hardlink`] target is the validated, root-relative,
95///   resolved [`SafePath`] of an entry that was already delivered: a file, or
96///   an earlier hardlink, so a chain of links is delivered link by link. The
97///   sink holds no bytes, so the closure resolves the reference against what it
98///   kept.
99///
100/// # Delivery rules
101///
102/// - Under overwrite (`skip_duplicates = false`) one path can be delivered more
103///   than once, and a hardlink refers to the most recent delivery of its
104///   target.
105/// - Implicit parent directories are not delivered; only directories the
106///   archive names are.
107/// - A hardlink is delivered after every other entry. Its bytes stay charged to
108///   the extraction quota although they are not copied.
109///
110/// # Examples
111///
112/// ```
113/// use std::io;
114///
115/// use exarch_core::ArchiveReader;
116/// use exarch_core::CallbackEntry;
117/// use exarch_core::CallbackSink;
118/// use exarch_core::MemoryEntry;
119/// use exarch_core::SecurityConfig;
120/// use exarch_core::SinkExtractRequest;
121/// use exarch_core::SinkOptions;
122///
123/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
124/// let mut builder = tar::Builder::new(Vec::new());
125/// let mut header = tar::Header::new_gnu();
126/// header.set_size(5);
127/// header.set_mode(0o644);
128/// builder.append_data(&mut header, "docs/hello.txt", &b"hello"[..])?;
129/// let archive = builder.into_inner()?;
130///
131/// let mut seen = Vec::new();
132/// let mut sink = CallbackSink::new(|path, entry| {
133///     if let CallbackEntry::Stored(MemoryEntry::File { data, .. }) = entry {
134///         seen.push((path.as_path().to_path_buf(), data));
135///     }
136///     Ok(())
137/// });
138/// let reader = ArchiveReader::tar(io::Cursor::new(archive), None);
139/// let config = SecurityConfig::default();
140/// SinkExtractRequest::new(&config)
141///     .with_options(SinkOptions::default())
142///     .extract(reader, &mut sink)?;
143/// assert_eq!(seen.len(), 1);
144/// assert_eq!(seen[0].1, b"hello");
145/// # Ok(())
146/// # }
147/// ```
148#[derive(Debug)]
149pub struct CallbackSink<F> {
150    callback: F,
151    path_model: PathModel,
152}
153
154impl<F> CallbackSink<F>
155where
156    F: FnMut(&SafePath, CallbackEntry) -> io::Result<()>,
157{
158    /// A sink that calls `callback` for every entry, validating against the
159    /// host's path rules.
160    #[must_use]
161    pub const fn new(callback: F) -> Self {
162        Self {
163            callback,
164            path_model: PathModel::Host,
165        }
166    }
167
168    /// Validates against `path_model` instead of the host's rules.
169    ///
170    /// # Examples
171    ///
172    /// ```
173    /// use std::io;
174    ///
175    /// use exarch_core::CallbackSink;
176    /// use exarch_core::EntrySink as _;
177    /// use exarch_core::PathModel;
178    ///
179    /// let sink = CallbackSink::new(|_, _| Ok(())).with_path_model(PathModel::Portable);
180    /// assert_eq!(sink.path_model(), PathModel::Portable);
181    /// ```
182    #[must_use]
183    pub const fn with_path_model(mut self, path_model: PathModel) -> Self {
184        self.path_model = path_model;
185        self
186    }
187}
188
189impl<F> EntrySink for CallbackSink<F>
190where
191    F: FnMut(&SafePath, CallbackEntry) -> io::Result<()>,
192{
193    type File = MemoryFile;
194
195    fn path_model(&self) -> PathModel {
196        self.path_model
197    }
198
199    fn create_directory(&mut self, path: &SafePath) -> io::Result<()> {
200        (self.callback)(path, MemoryEntry::Directory.into())
201    }
202
203    fn create_file(
204        &mut self,
205        _path: &SafePath,
206        mode: Option<SanitizedMode>,
207        size: AdmittedSize,
208    ) -> io::Result<MemoryFile> {
209        Ok(MemoryFile::with_size(size.get(), mode))
210    }
211
212    fn finish_file(&mut self, path: &SafePath, file: MemoryFile) -> io::Result<()> {
213        (self.callback)(path, file.into_entry().into())
214    }
215
216    fn create_symlink(&mut self, link: &SafePath, target: CheckedLinkTarget<'_>) -> io::Result<()> {
217        (self.callback)(
218            link,
219            MemoryEntry::Symlink {
220                target: target.as_path().to_path_buf(),
221            }
222            .into(),
223        )
224    }
225
226    fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
227        (self.callback)(
228            link,
229            CallbackEntry::Hardlink {
230                target: target.clone(),
231            },
232        )
233    }
234}
235
236/// Why [`extract_reader_to_callback`] failed.
237///
238/// The first error the callback returned is kept as `E`, so the caller keeps
239/// its own error type instead of recovering it from a side slot.
240///
241/// Closed by design: a failure is either the caller's own or the archive's, so
242/// a `match` over both variants needs no wildcard arm and the compiler flags
243/// any variant a future change adds.
244///
245/// # Examples
246///
247/// ```
248/// use std::error::Error as _;
249///
250/// use exarch_core::CallbackError;
251///
252/// let err = CallbackError::Callback(std::io::Error::other("stop"));
253/// assert_eq!(err.to_string(), "entry callback failed");
254/// assert_eq!(
255///     err.source().map(ToString::to_string).as_deref(),
256///     Some("stop")
257/// );
258/// ```
259#[derive(Debug)]
260pub enum CallbackError<E> {
261    /// The callback returned this error for an entry, which ended the
262    /// extraction. It takes precedence over the archive error the aborted
263    /// extraction reports.
264    Callback(E),
265    /// The archive was refused or could not be read.
266    Archive(ArchiveError),
267}
268
269/// `Callback` names the failure and chains to the callback's error through
270/// `source()`; `Archive` is transparent, so an error chain shows each message
271/// once.
272impl<E> fmt::Display for CallbackError<E> {
273    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
274        match self {
275            Self::Callback(_) => f.write_str("entry callback failed"),
276            Self::Archive(err) => err.fmt(f),
277        }
278    }
279}
280
281impl<E: Error + 'static> Error for CallbackError<E> {
282    fn source(&self) -> Option<&(dyn Error + 'static)> {
283        match self {
284            Self::Callback(err) => Some(err),
285            Self::Archive(err) => err.source(),
286        }
287    }
288}
289
290impl<E> From<ArchiveError> for CallbackError<E> {
291    fn from(err: ArchiveError) -> Self {
292        Self::Archive(err)
293    }
294}
295
296/// Extracts the archive in `reader`, handing every verified entry to
297/// `on_entry`.
298///
299/// Validates with the config, options and path model of `request`; its memory
300/// limit is ignored, since nothing is kept. Entries are provisional and
301/// delivered as described at [`CallbackSink`]. The first error `on_entry`
302/// returns ends the extraction and is returned as
303/// [`CallbackError::Callback`], ahead of any archive error.
304///
305/// # Errors
306///
307/// [`CallbackError::Callback`] with the first error of `on_entry`, else
308/// [`CallbackError::Archive`] with the errors of
309/// [`SinkExtractRequest::extract`](crate::SinkExtractRequest::extract).
310///
311/// # Examples
312///
313/// ```
314/// use std::assert_matches;
315///
316/// use exarch_core::ArchiveReader;
317/// use exarch_core::CallbackError;
318/// use exarch_core::MemoryExtractRequest;
319/// use exarch_core::NoopProgress;
320/// use exarch_core::extract_reader_to_callback;
321///
322/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
323/// let mut builder = tar::Builder::new(Vec::new());
324/// let mut header = tar::Header::new_gnu();
325/// header.set_size(2);
326/// header.set_mode(0o644);
327/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
328/// let archive = builder.into_inner()?;
329///
330/// let mut paths = Vec::new();
331/// let reader = ArchiveReader::from_bytes(archive.clone(), None)?;
332/// extract_reader_to_callback(
333///     reader,
334///     &MemoryExtractRequest::default(),
335///     |path, _entry| {
336///         paths.push(path.as_path().to_path_buf());
337///         Ok::<(), std::io::Error>(())
338///     },
339///     &mut NoopProgress,
340/// )?;
341/// assert_eq!(paths.len(), 1);
342///
343/// let reader = ArchiveReader::from_bytes(archive, None)?;
344/// let failed = extract_reader_to_callback(
345///     reader,
346///     &MemoryExtractRequest::default(),
347///     |_, _| Err(std::io::Error::other("stop")),
348///     &mut NoopProgress,
349/// );
350/// assert_matches!(failed, Err(CallbackError::Callback(err)) if err.to_string() == "stop");
351/// # Ok(())
352/// # }
353/// ```
354pub fn extract_reader_to_callback<F, E>(
355    reader: ArchiveReader<'_>,
356    request: &MemoryExtractRequest,
357    mut on_entry: F,
358    progress: &mut dyn ProgressCallback,
359) -> Result<ExtractionReport, CallbackError<E>>
360where
361    F: FnMut(&SafePath, CallbackEntry) -> Result<(), E>,
362{
363    let mut failure = None;
364    let mut sink = CallbackSink::new(|path: &SafePath, entry| {
365        on_entry(path, entry).map_err(|err| {
366            failure.get_or_insert(err);
367            io::Error::other("entry callback failed")
368        })
369    })
370    .with_path_model(request.model);
371    let result = crate::SinkExtractRequest::new(&request.config)
372        .with_options(request.options)
373        .with_progress(progress)
374        .extract(reader, &mut sink);
375    match (failure, result) {
376        (Some(err), _) => Err(CallbackError::Callback(err)),
377        (None, Ok(report)) => Ok(report),
378        (None, Err(err)) => Err(CallbackError::Archive(err)),
379    }
380}
381
382#[cfg(test)]
383#[allow(clippy::unwrap_used)]
384mod tests {
385    use super::*;
386    use crate::SecurityConfig;
387
388    fn hardlink_target() -> SafePath {
389        SafePath::validate(
390            std::path::Path::new("target.txt"),
391            &crate::DestDir::new(std::env::temp_dir()).unwrap(),
392            &SecurityConfig::default(),
393        )
394        .unwrap()
395    }
396
397    #[test]
398    fn every_callback_entry_maps_to_a_memory_entry_kind() {
399        let entries = [
400            CallbackEntry::Stored(MemoryEntry::Directory),
401            CallbackEntry::Hardlink {
402                target: hardlink_target(),
403            },
404        ];
405        let mut seen = Vec::new();
406        for entry in &entries {
407            // A wildcard-free match: a new variant fails to compile here.
408            let expected = match entry {
409                CallbackEntry::Stored(stored) => stored.kind(),
410                CallbackEntry::Hardlink { .. } => MemoryEntryKind::Hardlink,
411            };
412            assert_eq!(entry.kind(), expected);
413            seen.push(entry.kind());
414        }
415        assert!(seen.contains(&MemoryEntryKind::Directory));
416        assert!(seen.contains(&MemoryEntryKind::Hardlink));
417    }
418}