Skip to main content

exarch_core/sink/
memory.rs

1//! An [`EntrySink`] that keeps the extracted tree in memory.
2
3use std::collections::BTreeMap;
4use std::io;
5use std::io::Write;
6use std::num::NonZeroU64;
7use std::path::Path;
8use std::path::PathBuf;
9
10use crate::ArchiveError;
11use crate::ArchiveReader;
12use crate::ExtractionReport;
13use crate::ProgressCallback;
14use crate::Result;
15use crate::SecurityConfig;
16use crate::closed_enum::closed_enum;
17use crate::formats::detect::ArchiveType;
18use crate::security::fs_view::PathModel;
19use crate::security::permissions::SanitizedMode;
20use crate::sink::EntrySink;
21use crate::sink::SinkFull;
22use crate::sink::SinkOptions;
23use crate::types::SafePath;
24
25const DEFAULT_LIMIT_BYTES: u64 = 500 * 1024 * 1024;
26const INITIAL_CAPACITY_CAP: u64 = 64 * 1024;
27
28/// The most bytes a [`MemorySink`] accepts, counted as its payload (file data,
29/// hardlink copies, symlink targets) plus, for every entry, the bytes of its
30/// path and [`MemorySink::ENTRY_OVERHEAD`].
31///
32/// # Examples
33///
34/// ```
35/// use std::num::NonZeroU64;
36///
37/// use exarch_core::MemoryLimit;
38///
39/// assert_eq!(MemoryLimit::new(NonZeroU64::MIN).bytes().get(), 1);
40/// assert_eq!(MemoryLimit::DEFAULT.bytes().get(), 500 * 1024 * 1024);
41/// ```
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub struct MemoryLimit(NonZeroU64);
44
45impl MemoryLimit {
46    /// 500 MiB, the default `max_total_size`.
47    pub const DEFAULT: Self = Self(match NonZeroU64::new(DEFAULT_LIMIT_BYTES) {
48        Some(bytes) => bytes,
49        None => NonZeroU64::MIN,
50    });
51
52    /// A limit of `bytes`.
53    #[must_use]
54    pub const fn new(bytes: NonZeroU64) -> Self {
55        Self(bytes)
56    }
57
58    /// The limit in bytes.
59    #[must_use]
60    pub const fn bytes(self) -> NonZeroU64 {
61        self.0
62    }
63
64    /// The limit equal to the config's `max_total_size` (a zero quota becomes
65    /// one byte), so raising the extraction quota does not meet a second limit.
66    ///
67    /// # Examples
68    ///
69    /// ```
70    /// use exarch_core::MemoryLimit;
71    /// use exarch_core::SecurityConfig;
72    ///
73    /// let config = SecurityConfig::default().with_max_total_size(4096);
74    /// assert_eq!(MemoryLimit::from_config(&config).bytes().get(), 4096);
75    /// ```
76    #[must_use]
77    pub fn from_config<State>(config: &SecurityConfig<State>) -> Self {
78        Self(NonZeroU64::new(config.max_total_size).unwrap_or(NonZeroU64::MIN))
79    }
80}
81
82/// An entry held by a [`MemorySink`].
83#[derive(Debug, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum MemoryEntry {
86    /// A regular file.
87    File {
88        /// The file's bytes.
89        data: Vec<u8>,
90        /// The permission bits after setuid and setgid were stripped, if the
91        /// archive carries any.
92        mode: Option<SanitizedMode>,
93    },
94    /// A directory the archive names explicitly.
95    Directory,
96    /// A symbolic link, stored as data.
97    Symlink {
98        /// The target as the archive spells it.
99        target: PathBuf,
100    },
101}
102
103closed_enum! {
104    /// What a [`MemoryEntry`] holds.
105    ///
106    /// The string form is the one every language binding reports.
107    ///
108    /// # Examples
109    ///
110    /// ```
111    /// use exarch_core::MemoryEntry;
112    /// use exarch_core::MemoryEntryKind;
113    ///
114    /// assert_eq!(MemoryEntry::Directory.kind(), MemoryEntryKind::Directory);
115    /// assert_eq!(MemoryEntryKind::Symlink.as_str(), "symlink");
116    /// ```
117    #[derive(Debug, Clone, Copy, PartialEq, Eq)]
118    #[non_exhaustive]
119    pub enum MemoryEntryKind {
120        /// A regular file.
121        File => "file",
122        /// A directory the archive names explicitly.
123        Directory => "directory",
124        /// A symbolic link, stored as data.
125        Symlink => "symlink",
126    }
127}
128
129impl MemoryEntry {
130    /// What the entry holds.
131    #[must_use]
132    pub const fn kind(&self) -> MemoryEntryKind {
133        match self {
134            Self::File { .. } => MemoryEntryKind::File,
135            Self::Directory => MemoryEntryKind::Directory,
136            Self::Symlink { .. } => MemoryEntryKind::Symlink,
137        }
138    }
139
140    /// The bytes the entry holds besides its path.
141    fn payload_bytes(&self) -> u64 {
142        match self {
143            Self::File { data, .. } => data.len() as u64,
144            Self::Symlink { target } => target.as_os_str().len() as u64,
145            Self::Directory => 0,
146        }
147    }
148}
149
150/// The text of an entry path, or [`ArchiveError::InvalidArchive`] when it is
151/// not valid UTF-8: a lossy conversion could merge two distinct entries into
152/// one name.
153///
154/// # Errors
155///
156/// Returns [`ArchiveError::InvalidArchive`] for a path that is not UTF-8.
157///
158/// # Examples
159///
160/// ```
161/// use std::path::Path;
162///
163/// use exarch_core::utf8_entry_path;
164///
165/// assert_eq!(utf8_entry_path(Path::new("a/b.txt")).unwrap(), "a/b.txt");
166/// ```
167pub fn utf8_entry_path(path: &Path) -> Result<&str> {
168    path.to_str().ok_or_else(|| {
169        ArchiveError::InvalidArchive(format!("entry path is not valid UTF-8: {}", path.display()))
170    })
171}
172
173/// Extracts an archive held in memory into a [`MemorySink`].
174///
175/// The format is detected from the leading bytes unless `format` is given;
176/// `limit` defaults to [`MemoryLimit::from_config`]. A failure after entries
177/// were delivered reports [`PartialWrites::Discarded`](crate::PartialWrites):
178/// nothing is written to disk and the entries are dropped with the error.
179///
180/// # Errors
181///
182/// Returns the errors of
183/// [`extract_to_sink_with_progress`](crate::extract_to_sink_with_progress), and
184/// [`ArchiveError::UnknownFormat`] or a reader-format error when the
185/// format cannot be determined.
186///
187/// # Examples
188///
189/// ```
190/// use std::assert_matches;
191///
192/// use exarch_core::MemoryEntry;
193/// use exarch_core::NoopProgress;
194/// use exarch_core::PathModel;
195/// use exarch_core::SecurityConfig;
196/// use exarch_core::SinkOptions;
197/// use exarch_core::extract_bytes_to_memory;
198///
199/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
200/// let mut builder = tar::Builder::new(Vec::new());
201/// let mut header = tar::Header::new_gnu();
202/// header.set_size(2);
203/// header.set_mode(0o644);
204/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
205///
206/// let (report, sink) = extract_bytes_to_memory(
207///     builder.into_inner()?,
208///     None,
209///     &SecurityConfig::default(),
210///     &SinkOptions::default(),
211///     None,
212///     PathModel::Host,
213///     &mut NoopProgress,
214/// )?;
215/// assert_eq!(report.files_extracted, 1);
216/// let entries = sink.into_entries();
217/// assert_matches!(entries.values().next(), Some(MemoryEntry::File { .. }));
218/// # Ok(())
219/// # }
220/// ```
221pub fn extract_bytes_to_memory<B: AsRef<[u8]> + Send>(
222    bytes: B,
223    format: Option<ArchiveType>,
224    config: &SecurityConfig,
225    options: &SinkOptions,
226    limit: Option<MemoryLimit>,
227    model: PathModel,
228    progress: &mut dyn ProgressCallback,
229) -> Result<(ExtractionReport, MemorySink)> {
230    let reader = ArchiveReader::from_bytes(bytes, format)?;
231    let limit = limit.unwrap_or_else(|| MemoryLimit::from_config(config));
232    let mut sink = MemorySink::new(limit).with_path_model(model);
233    let report = crate::extract_to_sink_with_progress(reader, &mut sink, config, options, progress)
234        .map_err(ArchiveError::discarded)?;
235    Ok((report, sink))
236}
237
238/// The writer of a file being stored by a [`MemorySink`].
239///
240/// Nothing is published until `finish_file`; dropping it discards the bytes.
241#[derive(Debug)]
242pub struct MemoryFile {
243    data: Vec<u8>,
244    mode: Option<SanitizedMode>,
245}
246
247impl Write for MemoryFile {
248    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
249        self.data.write(buf)
250    }
251
252    fn flush(&mut self) -> io::Result<()> {
253        Ok(())
254    }
255}
256
257/// An [`EntrySink`] that keeps the extracted tree in memory.
258///
259/// The [`MemoryLimit`] counts, for every entry (directories included), the
260/// bytes of its path plus [`ENTRY_OVERHEAD`](Self::ENTRY_OVERHEAD), and for
261/// files, hardlink copies and symlinks their payload. A flood of directory
262/// entries with long names therefore fills the sink instead of growing it
263/// without bound. The overhead of the model that validates the archive is
264/// bounded separately by the node budget and is not counted. While a file is
265/// written its buffer may be up to twice the bytes received; it is shrunk when
266/// the file is stored.
267///
268/// # Examples
269///
270/// ```
271/// use std::assert_matches;
272/// use std::io;
273/// use std::path::Path;
274///
275/// use exarch_core::ArchiveReader;
276/// use exarch_core::SinkOptions;
277/// use exarch_core::MemoryEntry;
278/// use exarch_core::MemorySink;
279/// use exarch_core::SecurityConfig;
280/// use exarch_core::extract_to_sink;
281///
282/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
283/// let mut builder = tar::Builder::new(Vec::new());
284/// let mut header = tar::Header::new_gnu();
285/// header.set_size(5);
286/// header.set_mode(0o644);
287/// builder.append_data(&mut header, "docs/hello.txt", &b"hello"[..])?;
288/// let archive = builder.into_inner()?;
289///
290/// let mut sink = MemorySink::default();
291/// let reader = ArchiveReader::tar(io::Cursor::new(archive), None);
292/// extract_to_sink(
293///     reader,
294///     &mut sink,
295///     &SecurityConfig::default(),
296///     &SinkOptions::default(),
297/// )?;
298/// assert_matches!(
299///     sink.get(Path::new("docs/hello.txt")),
300///     Some(MemoryEntry::File { data, .. }) if data == b"hello"
301/// );
302/// assert_eq!(
303///     sink.stored_bytes(),
304///     MemorySink::ENTRY_OVERHEAD + "docs/hello.txt".len() as u64 + 5
305/// );
306/// # Ok(())
307/// # }
308/// ```
309#[derive(Debug)]
310pub struct MemorySink {
311    limit: MemoryLimit,
312    path_model: PathModel,
313    stored: u64,
314    entries: BTreeMap<PathBuf, MemoryEntry>,
315}
316
317impl Default for MemorySink {
318    fn default() -> Self {
319        Self::new(MemoryLimit::DEFAULT)
320    }
321}
322
323impl MemorySink {
324    /// Bytes charged to the limit for every entry on top of its path and
325    /// payload, covering the map node and the entry itself.
326    pub const ENTRY_OVERHEAD: u64 = 256;
327
328    /// An empty sink that accepts at most `limit` bytes.
329    #[must_use]
330    pub const fn new(limit: MemoryLimit) -> Self {
331        Self {
332            limit,
333            path_model: PathModel::Host,
334            stored: 0,
335            entries: BTreeMap::new(),
336        }
337    }
338
339    /// Validates against `path_model` instead of the host's rules.
340    ///
341    /// # Examples
342    ///
343    /// ```
344    /// use exarch_core::EntrySink;
345    /// use exarch_core::MemorySink;
346    /// use exarch_core::PathModel;
347    ///
348    /// let sink = MemorySink::default().with_path_model(PathModel::Portable);
349    /// assert_eq!(sink.path_model(), PathModel::Portable);
350    /// ```
351    #[must_use]
352    pub const fn with_path_model(mut self, path_model: PathModel) -> Self {
353        self.path_model = path_model;
354        self
355    }
356
357    /// The limit on charged bytes.
358    #[must_use]
359    pub const fn limit(&self) -> MemoryLimit {
360        self.limit
361    }
362
363    /// The bytes charged to the limit now: payload, path bytes and
364    /// [`ENTRY_OVERHEAD`](Self::ENTRY_OVERHEAD) per entry.
365    #[must_use]
366    pub const fn stored_bytes(&self) -> u64 {
367        self.stored
368    }
369
370    /// The entry at `path`, spelled as it was delivered.
371    #[must_use]
372    pub fn get(&self, path: &Path) -> Option<&MemoryEntry> {
373        self.entries.get(path)
374    }
375
376    /// Every entry in path order.
377    pub fn iter(&self) -> impl Iterator<Item = (&Path, &MemoryEntry)> {
378        self.entries
379            .iter()
380            .map(|(path, entry)| (path.as_path(), entry))
381    }
382
383    /// Consumes the sink into its entries.
384    #[must_use]
385    pub fn into_entries(self) -> BTreeMap<PathBuf, MemoryEntry> {
386        self.entries
387    }
388
389    fn full(&self) -> io::Error {
390        io::Error::new(
391            io::ErrorKind::QuotaExceeded,
392            SinkFull::new(self.limit.bytes().get()),
393        )
394    }
395
396    fn charge_of(path: &Path, payload: u64) -> u64 {
397        Self::ENTRY_OVERHEAD
398            .saturating_add(path.as_os_str().len() as u64)
399            .saturating_add(payload)
400    }
401
402    fn held_at(&self, path: &Path) -> u64 {
403        self.entries
404            .get(path)
405            .map_or(0, |entry| Self::charge_of(path, entry.payload_bytes()))
406    }
407
408    /// The total charge after replacing the entry at `path` by one with
409    /// `payload`, or the full error if that passes the limit.
410    fn charged_with(&self, path: &Path, payload: u64) -> io::Result<u64> {
411        self.stored
412            .saturating_sub(self.held_at(path))
413            .checked_add(Self::charge_of(path, payload))
414            .filter(|total| *total <= self.limit.bytes().get())
415            .ok_or_else(|| self.full())
416    }
417
418    /// Stores `entry` at `path`, replacing the entry there, unless the charge
419    /// would pass the limit.
420    fn store(&mut self, path: &SafePath, entry: MemoryEntry) -> io::Result<()> {
421        let key = path.as_path();
422        self.stored = self.charged_with(key, entry.payload_bytes())?;
423        self.entries.insert(key.to_path_buf(), entry);
424        Ok(())
425    }
426}
427
428impl EntrySink for MemorySink {
429    type File = MemoryFile;
430
431    fn path_model(&self) -> PathModel {
432        self.path_model
433    }
434
435    fn create_directory(&mut self, path: &SafePath) -> io::Result<()> {
436        self.store(path, MemoryEntry::Directory)
437    }
438
439    fn create_file(
440        &mut self,
441        path: &SafePath,
442        mode: Option<SanitizedMode>,
443        size: u64,
444    ) -> io::Result<MemoryFile> {
445        self.charged_with(path.as_path(), size)?;
446        self.stored = self.stored.saturating_sub(self.held_at(path.as_path()));
447        self.entries.remove(path.as_path());
448        let capacity = usize::try_from(size.min(INITIAL_CAPACITY_CAP)).unwrap_or(0);
449        Ok(MemoryFile {
450            data: Vec::with_capacity(capacity),
451            mode,
452        })
453    }
454
455    fn finish_file(&mut self, path: &SafePath, file: MemoryFile) -> io::Result<()> {
456        let MemoryFile { mut data, mode } = file;
457        data.shrink_to_fit();
458        self.store(path, MemoryEntry::File { data, mode })
459    }
460
461    fn create_symlink(&mut self, link: &SafePath, target: &Path) -> io::Result<()> {
462        self.store(
463            link,
464            MemoryEntry::Symlink {
465                target: target.to_path_buf(),
466            },
467        )
468    }
469
470    fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
471        let Some(MemoryEntry::File { data, mode }) = self.entries.get(target.as_path()) else {
472            return Err(io::Error::new(
473                io::ErrorKind::NotFound,
474                "hardlink target is not a file",
475            ));
476        };
477        self.charged_with(link.as_path(), data.len() as u64)?;
478        let copy = MemoryEntry::File {
479            data: data.clone(),
480            mode: *mode,
481        };
482        self.store(link, copy)
483    }
484}