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;
9use std::sync::Arc;
10use std::sync::atomic::AtomicU64;
11use std::sync::atomic::Ordering;
12
13use crate::ArchiveError;
14use crate::ArchiveReader;
15use crate::ExtractionReport;
16use crate::ProgressCallback;
17use crate::Result;
18use crate::SecurityConfig;
19use crate::closed_enum::closed_enum;
20use crate::security::fs_view::PathModel;
21use crate::security::permissions::SanitizedMode;
22use crate::security::quota::AdmittedSize;
23use crate::sink::EntrySink;
24use crate::sink::SinkFull;
25use crate::sink::SinkOptions;
26use crate::types::CheckedLinkTarget;
27use crate::types::SafePath;
28
29const DEFAULT_LIMIT_BYTES: u64 = 500 * 1024 * 1024;
30const INITIAL_CAPACITY_CAP: u64 = 64 * 1024;
31
32/// The most bytes a [`MemorySink`] accepts, counted as its payload (file data,
33/// hardlink copies, symlink targets) plus, for every entry, the bytes of its
34/// path and [`MemorySink::ENTRY_OVERHEAD`].
35///
36/// # Examples
37///
38/// ```
39/// use std::num::NonZeroU64;
40///
41/// use exarch_core::MemoryLimit;
42///
43/// assert_eq!(MemoryLimit::new(NonZeroU64::MIN).bytes().get(), 1);
44/// assert_eq!(MemoryLimit::DEFAULT.bytes().get(), 500 * 1024 * 1024);
45/// ```
46#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct MemoryLimit(NonZeroU64);
48
49impl MemoryLimit {
50 /// 500 MiB, the default `max_total_size`.
51 pub const DEFAULT: Self = Self(match NonZeroU64::new(DEFAULT_LIMIT_BYTES) {
52 Some(bytes) => bytes,
53 None => NonZeroU64::MIN,
54 });
55
56 /// A limit of `bytes`.
57 #[must_use]
58 pub const fn new(bytes: NonZeroU64) -> Self {
59 Self(bytes)
60 }
61
62 /// The limit in bytes.
63 #[must_use]
64 pub const fn bytes(self) -> NonZeroU64 {
65 self.0
66 }
67
68 /// The limit equal to the config's `max_total_size` (a zero quota becomes
69 /// one byte), so raising the extraction quota does not meet a second limit.
70 ///
71 /// # Examples
72 ///
73 /// ```
74 /// use exarch_core::MemoryLimit;
75 /// use exarch_core::SecurityConfig;
76 ///
77 /// let config = SecurityConfig::default().with_max_total_size(exarch_core::non_zero!(4096));
78 /// assert_eq!(MemoryLimit::from_config(&config).bytes().get(), 4096);
79 /// ```
80 #[must_use]
81 pub fn from_config(config: &SecurityConfig) -> Self {
82 Self(match config.max_total_size {
83 crate::Limit::Bounded(bytes) => bytes,
84 crate::Limit::Unbounded => NonZeroU64::MAX,
85 })
86 }
87}
88
89/// The bytes a [`MemorySink`] has charged, readable while the sink is borrowed
90/// by an extraction, so the ZIP decode store can share the sink's limit.
91#[derive(Debug, Clone, Default)]
92pub struct SinkUsage(Arc<AtomicU64>);
93
94impl SinkUsage {
95 pub(crate) fn get(&self) -> u64 {
96 self.0.load(Ordering::Relaxed)
97 }
98
99 pub(crate) fn set(&self, bytes: u64) {
100 self.0.store(bytes, Ordering::Relaxed);
101 }
102}
103
104/// What an extraction into a [`MemorySink`] shares with the ZIP decode store:
105/// the sink's charged bytes and its limit.
106#[derive(Debug)]
107pub struct SinkReuse {
108 pub(crate) usage: SinkUsage,
109 pub(crate) limit: MemoryLimit,
110}
111
112/// An entry held by a [`MemorySink`].
113///
114/// A [`MemorySink`] stores a hardlink as a copy of the file, so this type has
115/// no hardlink variant. A [`CallbackSink`](crate::CallbackSink) delivers a
116/// hardlink by reference as a [`CallbackEntry`](crate::CallbackEntry).
117#[derive(Debug, Clone, PartialEq, Eq)]
118#[non_exhaustive]
119pub enum MemoryEntry {
120 /// A regular file.
121 File {
122 /// The file's bytes.
123 data: Vec<u8>,
124 /// The permission bits after setuid and setgid were stripped, if the
125 /// archive carries any.
126 mode: Option<SanitizedMode>,
127 },
128 /// A directory the archive names explicitly.
129 Directory,
130 /// A symbolic link, stored as data.
131 Symlink {
132 /// The target as the archive spells it, relative to the link.
133 target: PathBuf,
134 },
135}
136
137closed_enum! {
138 /// What a [`MemoryEntry`] or a [`CallbackEntry`](crate::CallbackEntry) holds.
139 ///
140 /// The string form is the one every language binding reports. Only a
141 /// [`CallbackEntry`](crate::CallbackEntry) can be a [`Hardlink`](Self::Hardlink).
142 ///
143 /// # Examples
144 ///
145 /// ```
146 /// use exarch_core::MemoryEntry;
147 /// use exarch_core::MemoryEntryKind;
148 ///
149 /// assert_eq!(MemoryEntry::Directory.kind(), MemoryEntryKind::Directory);
150 /// assert_eq!(MemoryEntryKind::Symlink.as_str(), "symlink");
151 /// ```
152 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
153 #[non_exhaustive]
154 pub enum MemoryEntryKind {
155 /// A regular file.
156 File => "file",
157 /// A directory the archive names explicitly.
158 Directory => "directory",
159 /// A symbolic link, stored as data.
160 Symlink => "symlink",
161 /// A hard link to an already delivered file, by reference.
162 Hardlink => "hardlink",
163 }
164}
165
166impl MemoryEntry {
167 /// What the entry holds.
168 #[must_use]
169 pub const fn kind(&self) -> MemoryEntryKind {
170 match self {
171 Self::File { .. } => MemoryEntryKind::File,
172 Self::Directory => MemoryEntryKind::Directory,
173 Self::Symlink { .. } => MemoryEntryKind::Symlink,
174 }
175 }
176
177 /// The bytes the entry holds besides its path.
178 fn payload_bytes(&self) -> u64 {
179 match self {
180 Self::File { data, .. } => data.len() as u64,
181 Self::Symlink { target } => target.as_os_str().len() as u64,
182 Self::Directory => 0,
183 }
184 }
185}
186
187/// How [`extract_reader_to_memory`] validates and stores an archive.
188///
189/// Every field has a default: the default [`SecurityConfig`] and
190/// [`SinkOptions`], the host path model, and a limit equal to the config's
191/// `max_total_size` (see [`MemoryLimit::from_config`]).
192///
193/// # Examples
194///
195/// ```
196/// use std::num::NonZeroU64;
197///
198/// use exarch_core::MemoryExtractRequest;
199/// use exarch_core::MemoryLimit;
200/// use exarch_core::PathModel;
201///
202/// let request = MemoryExtractRequest::default()
203/// .with_limit(MemoryLimit::new(NonZeroU64::MIN))
204/// .with_path_model(PathModel::Portable);
205/// # let _ = request;
206/// ```
207#[derive(Debug, Clone, Default)]
208pub struct MemoryExtractRequest {
209 pub(super) config: SecurityConfig,
210 pub(super) options: SinkOptions,
211 limit: Option<MemoryLimit>,
212 pub(super) model: PathModel,
213}
214
215impl MemoryExtractRequest {
216 /// Validates against `config`.
217 #[must_use]
218 pub fn with_config(mut self, config: SecurityConfig) -> Self {
219 self.config = config;
220 self
221 }
222
223 /// Applies `options` to the extraction.
224 #[must_use]
225 pub const fn with_options(mut self, options: SinkOptions) -> Self {
226 self.options = options;
227 self
228 }
229
230 /// Caps the sink at `limit` instead of [`MemoryLimit::from_config`].
231 ///
232 /// Only [`extract_reader_to_memory`] has a sink to cap;
233 /// [`extract_reader_to_callback`](crate::extract_reader_to_callback) keeps
234 /// nothing and ignores it.
235 #[must_use]
236 pub const fn with_limit(mut self, limit: MemoryLimit) -> Self {
237 self.limit = Some(limit);
238 self
239 }
240
241 /// Validates against `model` instead of the host's path rules.
242 #[must_use]
243 pub const fn with_path_model(mut self, model: PathModel) -> Self {
244 self.model = model;
245 self
246 }
247}
248
249/// Extracts the archive in `reader` into a [`MemorySink`].
250///
251/// Build the reader with [`ArchiveReader::from_bytes`] for bytes in memory, or
252/// with [`ArchiveReader::detect`] and friends for a stream. A failure after
253/// entries were delivered reports
254/// [`PartialWrites::Discarded`](crate::PartialWrites): nothing is written to
255/// disk and the entries are dropped with the error.
256///
257/// # Decode reuse
258///
259/// A ZIP archive is decoded once: the structural check keeps the output of
260/// its compressed entries and extraction replays it. This path always uses
261/// in-memory reuse, whatever `config.decode_reuse` says, and the kept bytes
262/// together with what the sink holds stay within the smaller of the sink's
263/// memory limit and `max_decoder_memory`.
264///
265/// # Errors
266///
267/// Returns the errors of
268/// [`SinkExtractRequest::extract`](crate::SinkExtractRequest::extract).
269///
270/// # Examples
271///
272/// ```
273/// use std::assert_matches;
274///
275/// use exarch_core::ArchiveReader;
276/// use exarch_core::MemoryEntry;
277/// use exarch_core::MemoryExtractRequest;
278/// use exarch_core::NoopProgress;
279/// use exarch_core::extract_reader_to_memory;
280///
281/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
282/// let mut builder = tar::Builder::new(Vec::new());
283/// let mut header = tar::Header::new_gnu();
284/// header.set_size(2);
285/// header.set_mode(0o644);
286/// builder.append_data(&mut header, "a.txt", &b"hi"[..])?;
287///
288/// let reader = ArchiveReader::from_bytes(builder.into_inner()?, None)?;
289/// let (report, sink) =
290/// extract_reader_to_memory(reader, &MemoryExtractRequest::default(), &mut NoopProgress)?;
291/// assert_eq!(report.files_extracted, 1);
292/// let entries = sink.into_entries();
293/// assert_matches!(entries.values().next(), Some(MemoryEntry::File { .. }));
294/// # Ok(())
295/// # }
296/// ```
297pub fn extract_reader_to_memory(
298 reader: ArchiveReader<'_>,
299 request: &MemoryExtractRequest,
300 progress: &mut dyn ProgressCallback,
301) -> Result<(ExtractionReport, MemorySink)> {
302 let limit = request
303 .limit
304 .unwrap_or_else(|| MemoryLimit::from_config(&request.config));
305 let mut sink = MemorySink::new(limit).with_path_model(request.model);
306 let reuse = SinkReuse {
307 usage: sink.usage(),
308 limit,
309 };
310 let report = crate::api::extract_to_sink_reusing(
311 reader,
312 &mut sink,
313 &request.config,
314 request.options,
315 progress,
316 Some(reuse),
317 )
318 .map_err(ArchiveError::discarded)?;
319 Ok((report, sink))
320}
321
322/// The writer of a file being stored by a [`MemorySink`].
323///
324/// Nothing is published until `finish_file`; dropping it discards the bytes.
325#[derive(Debug)]
326pub struct MemoryFile {
327 data: Vec<u8>,
328 mode: Option<SanitizedMode>,
329}
330
331impl MemoryFile {
332 /// A writer that holds `data` already, for a file received whole.
333 pub(crate) const fn from_vec(data: Vec<u8>, mode: Option<SanitizedMode>) -> Self {
334 Self { data, mode }
335 }
336
337 /// A writer for a file of `size` bytes, pre-allocating at most 64 KiB so a
338 /// forged size cannot reserve memory before any byte arrives.
339 pub(crate) fn with_size(size: u64, mode: Option<SanitizedMode>) -> Self {
340 let capacity = usize::try_from(size.min(INITIAL_CAPACITY_CAP)).unwrap_or(0);
341 Self {
342 data: Vec::with_capacity(capacity),
343 mode,
344 }
345 }
346
347 /// The completed file, with its buffer shrunk to the bytes received.
348 pub(crate) fn into_entry(self) -> MemoryEntry {
349 let Self { mut data, mode } = self;
350 data.shrink_to_fit();
351 MemoryEntry::File { data, mode }
352 }
353}
354
355impl Write for MemoryFile {
356 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
357 self.data.write(buf)
358 }
359
360 fn flush(&mut self) -> io::Result<()> {
361 Ok(())
362 }
363}
364
365/// An [`EntrySink`] that keeps the extracted tree in memory.
366///
367/// The [`MemoryLimit`] counts, for every entry (directories included), the
368/// bytes of its path plus [`ENTRY_OVERHEAD`](Self::ENTRY_OVERHEAD), and for
369/// files, hardlink copies and symlinks their payload. A flood of directory
370/// entries with long names therefore fills the sink instead of growing it
371/// without bound. The overhead of the model that validates the archive is
372/// bounded separately by the node budget and is not counted. While a file is
373/// written its buffer may be up to twice the bytes received; it is shrunk when
374/// the file is stored.
375///
376/// # Examples
377///
378/// ```
379/// use std::assert_matches;
380/// use std::io;
381/// use std::path::Path;
382///
383/// use exarch_core::ArchiveReader;
384/// use exarch_core::SinkExtractRequest;
385/// use exarch_core::SinkOptions;
386/// use exarch_core::MemoryEntry;
387/// use exarch_core::MemorySink;
388/// use exarch_core::SecurityConfig;
389///
390/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
391/// let mut builder = tar::Builder::new(Vec::new());
392/// let mut header = tar::Header::new_gnu();
393/// header.set_size(5);
394/// header.set_mode(0o644);
395/// builder.append_data(&mut header, "docs/hello.txt", &b"hello"[..])?;
396/// let archive = builder.into_inner()?;
397///
398/// let mut sink = MemorySink::default();
399/// let reader = ArchiveReader::tar(io::Cursor::new(archive), None);
400/// let config = SecurityConfig::default();
401/// SinkExtractRequest::new(&config)
402/// .with_options(SinkOptions::default())
403/// .extract(reader, &mut sink)?;
404/// assert_matches!(
405/// sink.get(Path::new("docs/hello.txt")),
406/// Some(MemoryEntry::File { data, .. }) if data == b"hello"
407/// );
408/// assert_eq!(
409/// sink.stored_bytes(),
410/// MemorySink::ENTRY_OVERHEAD + "docs/hello.txt".len() as u64 + 5
411/// );
412/// # Ok(())
413/// # }
414/// ```
415#[derive(Debug)]
416pub struct MemorySink {
417 limit: MemoryLimit,
418 path_model: PathModel,
419 stored: u64,
420 usage: SinkUsage,
421 entries: BTreeMap<PathBuf, MemoryEntry>,
422}
423
424impl Default for MemorySink {
425 fn default() -> Self {
426 Self::new(MemoryLimit::DEFAULT)
427 }
428}
429
430impl MemorySink {
431 /// Bytes charged to the limit for every entry on top of its path and
432 /// payload, covering the map node and the entry itself.
433 pub const ENTRY_OVERHEAD: u64 = 256;
434
435 /// An empty sink that accepts at most `limit` bytes.
436 #[must_use]
437 pub fn new(limit: MemoryLimit) -> Self {
438 Self {
439 limit,
440 path_model: PathModel::Host,
441 stored: 0,
442 usage: SinkUsage(Arc::new(AtomicU64::new(0))),
443 entries: BTreeMap::new(),
444 }
445 }
446
447 /// Validates against `path_model` instead of the host's rules.
448 ///
449 /// # Examples
450 ///
451 /// ```
452 /// use exarch_core::EntrySink;
453 /// use exarch_core::MemorySink;
454 /// use exarch_core::PathModel;
455 ///
456 /// let sink = MemorySink::default().with_path_model(PathModel::Portable);
457 /// assert_eq!(sink.path_model(), PathModel::Portable);
458 /// ```
459 #[must_use]
460 pub const fn with_path_model(mut self, path_model: PathModel) -> Self {
461 self.path_model = path_model;
462 self
463 }
464
465 /// The limit on charged bytes.
466 #[must_use]
467 pub const fn limit(&self) -> MemoryLimit {
468 self.limit
469 }
470
471 /// The bytes charged to the limit now: payload, path bytes and
472 /// [`ENTRY_OVERHEAD`](Self::ENTRY_OVERHEAD) per entry.
473 #[must_use]
474 pub const fn stored_bytes(&self) -> u64 {
475 self.stored
476 }
477
478 /// The entry at `path`, spelled as it was delivered.
479 #[must_use]
480 pub fn get(&self, path: &Path) -> Option<&MemoryEntry> {
481 self.entries.get(path)
482 }
483
484 /// Every entry in path order.
485 pub fn iter(&self) -> impl Iterator<Item = (&Path, &MemoryEntry)> {
486 self.entries
487 .iter()
488 .map(|(path, entry)| (path.as_path(), entry))
489 }
490
491 /// Consumes the sink into its entries.
492 #[must_use]
493 pub fn into_entries(self) -> BTreeMap<PathBuf, MemoryEntry> {
494 self.entries
495 }
496
497 fn full(&self) -> io::Error {
498 io::Error::new(
499 io::ErrorKind::QuotaExceeded,
500 SinkFull::new(self.limit.bytes().get()),
501 )
502 }
503
504 pub(crate) fn usage(&self) -> SinkUsage {
505 self.usage.clone()
506 }
507
508 pub(crate) fn charge_of(path: &Path, payload: u64) -> u64 {
509 Self::ENTRY_OVERHEAD
510 .saturating_add(path.as_os_str().len() as u64)
511 .saturating_add(payload)
512 }
513
514 fn held_at(&self, path: &Path) -> u64 {
515 self.entries
516 .get(path)
517 .map_or(0, |entry| Self::charge_of(path, entry.payload_bytes()))
518 }
519
520 /// The total charge after replacing the entry at `path` by one with
521 /// `payload`, or the full error if that passes the limit.
522 fn charged_with(&self, path: &Path, payload: u64) -> io::Result<u64> {
523 self.stored
524 .saturating_sub(self.held_at(path))
525 .checked_add(Self::charge_of(path, payload))
526 .filter(|total| *total <= self.limit.bytes().get())
527 .ok_or_else(|| self.full())
528 }
529
530 /// Stores `entry` at `path`, replacing the entry there, unless the charge
531 /// would pass the limit.
532 fn store(&mut self, path: &SafePath, entry: MemoryEntry) -> io::Result<()> {
533 let key = path.as_path();
534 self.stored = self.charged_with(key, entry.payload_bytes())?;
535 self.usage.set(self.stored);
536 self.entries.insert(key.to_path_buf(), entry);
537 Ok(())
538 }
539
540 /// Drops the entry at `path` to make room for a file of `size` bytes, or
541 /// refuses a file that would pass the limit.
542 fn reserve_file(&mut self, path: &SafePath, size: u64) -> io::Result<()> {
543 self.charged_with(path.as_path(), size)?;
544 self.stored = self.stored.saturating_sub(self.held_at(path.as_path()));
545 self.usage.set(self.stored);
546 self.entries.remove(path.as_path());
547 Ok(())
548 }
549}
550
551impl EntrySink for MemorySink {
552 type File = MemoryFile;
553
554 fn path_model(&self) -> PathModel {
555 self.path_model
556 }
557
558 fn create_directory(&mut self, path: &SafePath) -> io::Result<()> {
559 self.store(path, MemoryEntry::Directory)
560 }
561
562 fn create_file(
563 &mut self,
564 path: &SafePath,
565 mode: Option<SanitizedMode>,
566 size: AdmittedSize,
567 ) -> io::Result<MemoryFile> {
568 self.reserve_file(path, size.get())?;
569 Ok(MemoryFile::with_size(size.get(), mode))
570 }
571
572 fn create_file_from(
573 &mut self,
574 path: &SafePath,
575 mode: Option<SanitizedMode>,
576 size: AdmittedSize,
577 bytes: Vec<u8>,
578 ) -> io::Result<MemoryFile> {
579 self.reserve_file(path, size.get())?;
580 Ok(MemoryFile::from_vec(bytes, mode))
581 }
582
583 fn finish_file(&mut self, path: &SafePath, file: MemoryFile) -> io::Result<()> {
584 self.store(path, file.into_entry())
585 }
586
587 fn create_symlink(&mut self, link: &SafePath, target: CheckedLinkTarget<'_>) -> io::Result<()> {
588 self.store(
589 link,
590 MemoryEntry::Symlink {
591 target: target.as_path().to_path_buf(),
592 },
593 )
594 }
595
596 fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
597 let Some(MemoryEntry::File { data, mode }) = self.entries.get(target.as_path()) else {
598 return Err(io::Error::new(
599 io::ErrorKind::NotFound,
600 "hardlink target is not a file",
601 ));
602 };
603 self.charged_with(link.as_path(), data.len() as u64)?;
604 let copy = MemoryEntry::File {
605 data: data.clone(),
606 mode: *mode,
607 };
608 self.store(link, copy)
609 }
610}