exarch_core/sink.rs
1//! Extraction into caller-owned storage instead of a directory.
2//!
3//! [`SinkExtractRequest`](crate::SinkExtractRequest) runs the same validation
4//! pipeline as [`extract_archive`](crate::extract_archive) (quotas, ratio
5//! limits, path and link checks, the per-format gates) but hands each entry to
6//! an [`EntrySink`], so an archive can be unpacked into memory, an object
7//! store or a virtual filesystem without touching the host's.
8//!
9//! # What a sink may rely on
10//!
11//! - Every path is relative, normalized, free of `..`, a root or a prefix, and
12//! already resolved through the symlinks of earlier entries: no parent
13//! component is a symlink, and two spellings of one name (on hosts that fold
14//! case) arrive as one path.
15//! - Parent directories are not announced. A file under `a/b` arrives without a
16//! `create_directory` for `a` or `b`; create them on demand.
17//! - Link targets are validated not to escape the root. Validation uses the
18//! sink's [`PathModel`], [`EntrySink::path_model`]. The default, `Host`,
19//! follows the platform running the extraction: names fold case only on macOS
20//! and Windows, and the Windows component checks run only on Windows, so a
21//! sink that writes to a system with another model must not assume the checks
22//! hold there. `Portable` applies the strictest rules of every supported
23//! platform on every host and suits a sink whose storage is read elsewhere.
24//! - Validation assumes an EMPTY namespace: the sink must start empty. Entries
25//! the sink already holds are invisible to it.
26//! - Duplicates follow [`SinkOptions`] `skip_duplicates` exactly as the
27//! path-based API does: skipped entries are never delivered, and with
28//! overwrite a later file replaces an earlier one (a second `create_file` for
29//! the same path) and a later symlink replaces an earlier file.
30//! - Quotas, ratio limits and declared-size enforcement count the bytes the
31//! archive produces, not what the sink stores.
32//!
33//! # Differences from the path-based API
34//!
35//! - Symlinks are delivered on every platform, including hosts where the
36//! path-based API refuses to create them: a sink stores a link as data.
37//! - A sink failure ends the extraction. When an entry was already delivered,
38//! the error is a `PartialExtraction` wrapping [`ArchiveError::Io`].
39//! - The model is stricter than the host in a few shapes, and fails closed: a
40//! hardlink to a directory is `InvalidArchive` (the host fails in the copy),
41//! and that check runs before a duplicate hardlink is skipped; a directory or
42//! file entry through a dangling symlink, or over one, is refused.
43//! - Under case folding (macOS, Windows, and every host with `Portable`) two
44//! spellings of a name are one name, and the path delivered is the spelling
45//! stored first.
46//! - With `Host` the sink inherits the path-length limits of the platform
47//! running the extraction, not its own; `Portable` uses fixed limits. In both
48//! models symlink targets and other names are limited, but 8.3 short names
49//! and the legacy 260-unit `MAX_PATH` are not modelled.
50//! - A path that leaves the root and comes back (a symlink to `..` followed by
51//! the root's own name) is refused as an escape, though the host would
52//! resolve it inside.
53//!
54//! # Memory used by validation
55//!
56//! The model that validates paths holds every name the archive spells, charged
57//! to a budget of `max_file_count * max_path_depth + 1` names (a directory
58//! entry and each differently spelled alias of a name cost one name, whatever
59//! the entry type); an archive that passes it fails with
60//! [`QuotaResource::TreeNodes`]. With the
61//! default limits that is 320001 names. Measured on macOS in a release build,
62//! 320000 directory entries into a sink that stores nothing peaked at 176 MB
63//! resident with 7-byte names and 223 MB with 99-byte names (about 1.6 bytes
64//! per name byte on top of about 550 bytes per name), so names of 255 bytes
65//! reach roughly 300 MB. [`MemoryLimit`] counts the payload, the path bytes and
66//! a fixed 256 bytes per entry, but not this overhead.
67//!
68//! A sink that writes to a real filesystem loses the per-component symlink
69//! vetting, `O_NOFOLLOW` and `create_new` defences the path-based API relies
70//! on (the pre-existing destination symlink class). Use
71//! [`extract_archive`](crate::extract_archive) for that.
72//!
73//! # Examples
74//!
75//! ```
76//! use std::collections::BTreeMap;
77//! use std::io;
78//! use std::path::Path;
79//! use std::path::PathBuf;
80//!
81//! use exarch_core::AdmittedSize;
82//! use exarch_core::ArchiveReader;
83//! use exarch_core::CheckedLinkTarget;
84//! use exarch_core::EntrySink;
85//! use exarch_core::SafePath;
86//! use exarch_core::SanitizedMode;
87//! use exarch_core::SecurityConfig;
88//! use exarch_core::SinkExtractRequest;
89//! use exarch_core::SinkOptions;
90//!
91//! #[derive(Default)]
92//! struct MapSink(BTreeMap<PathBuf, Vec<u8>>);
93//!
94//! impl EntrySink for MapSink {
95//! type File = Vec<u8>;
96//!
97//! fn create_directory(&mut self, _: &SafePath) -> io::Result<()> {
98//! Ok(())
99//! }
100//!
101//! fn create_file(
102//! &mut self,
103//! _: &SafePath,
104//! _: Option<SanitizedMode>,
105//! size: AdmittedSize,
106//! ) -> io::Result<Vec<u8>> {
107//! Ok(Vec::with_capacity(
108//! usize::try_from(size.get().min(1 << 16)).unwrap_or(0),
109//! ))
110//! }
111//!
112//! fn finish_file(&mut self, path: &SafePath, file: Vec<u8>) -> io::Result<()> {
113//! self.0.insert(path.as_path().to_path_buf(), file);
114//! Ok(())
115//! }
116//!
117//! fn create_symlink(&mut self, _: &SafePath, _: CheckedLinkTarget<'_>) -> io::Result<()> {
118//! Ok(())
119//! }
120//!
121//! fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
122//! let bytes = self.0.get(target.as_path()).cloned().unwrap_or_default();
123//! self.0.insert(link.as_path().to_path_buf(), bytes);
124//! Ok(())
125//! }
126//! }
127//!
128//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
129//! let mut builder = tar::Builder::new(Vec::new());
130//! let mut header = tar::Header::new_gnu();
131//! header.set_size(5);
132//! header.set_mode(0o644);
133//! builder.append_data(&mut header, "docs/hello.txt", &b"hello"[..])?;
134//! let archive = builder.into_inner()?;
135//!
136//! let mut sink = MapSink::default();
137//! let reader = ArchiveReader::tar(io::Cursor::new(archive), None);
138//! let config = SecurityConfig::default();
139//! let report = SinkExtractRequest::new(&config)
140//! .with_options(SinkOptions::default())
141//! .extract(reader, &mut sink)?;
142//! assert_eq!(report.files_extracted, 1);
143//! assert_eq!(sink.0[Path::new("docs/hello.txt")], b"hello");
144//! # Ok(())
145//! # }
146//! ```
147
148mod callback;
149mod memory;
150
151pub use callback::CallbackEntry;
152pub use callback::CallbackError;
153pub use callback::CallbackSink;
154pub use callback::extract_reader_to_callback;
155pub use memory::MemoryEntry;
156pub use memory::MemoryEntryKind;
157pub use memory::MemoryExtractRequest;
158pub use memory::MemoryFile;
159pub use memory::MemoryLimit;
160pub use memory::MemorySink;
161pub(crate) use memory::SinkReuse;
162pub(crate) use memory::SinkUsage;
163pub use memory::extract_reader_to_memory;
164
165use std::collections::HashMap;
166use std::io;
167use std::io::Read;
168use std::io::Write;
169use std::path::Path;
170use std::path::PathBuf;
171
172use crate::ArchiveError;
173use crate::DecodeReuse;
174use crate::ExtractionOptions;
175use crate::Malformation;
176use crate::QuotaResource;
177use crate::Result;
178use crate::SecurityConfig;
179use crate::copy::CopyBuffer;
180use crate::copy::copy_with_buffer;
181use crate::formats::common;
182use crate::formats::target::ExtractTarget;
183use crate::formats::target::FileAdmission;
184use crate::formats::target::FileRequest;
185use crate::formats::target::Tally;
186use crate::formats::zip_reuse::Retained;
187use crate::security::admitted::EntrySize;
188use crate::security::admitted::ValidatedFile;
189use crate::security::admitted::ValidatedHardlink;
190use crate::security::fs_view::CollisionRecording;
191use crate::security::fs_view::Containment;
192use crate::security::fs_view::FsView as _;
193use crate::security::fs_view::LandingLimits;
194use crate::security::fs_view::LinkKind;
195use crate::security::fs_view::ModelRoot as _;
196use crate::security::fs_view::Node;
197use crate::security::fs_view::NodeBudget;
198use crate::security::fs_view::Occupant;
199use crate::security::fs_view::PathModel;
200use crate::security::fs_view::PlaceError;
201use crate::security::fs_view::VirtualRoot;
202use crate::security::fs_view::VirtualTree;
203use crate::security::fs_view::name_too_long;
204use crate::security::hardlink::HardlinkTarget;
205use crate::security::hardlink::HardlinkTracker;
206use crate::security::hardlink::hardlink_target_missing;
207use crate::security::permissions::SanitizedMode;
208use crate::security::quota::AdmittedSize;
209use crate::security::quota::EntryCount;
210use crate::security::validator::FileScreen;
211use crate::security::validator::ValidatorCore;
212use crate::types::CheckedLinkTarget;
213use crate::types::SafePath;
214use crate::types::SafeSymlink;
215use crate::types::safe_path::Resolved;
216
217/// What extraction does with an entry whose destination an earlier entry
218/// already holds.
219#[derive(Debug, Clone, Copy, PartialEq, Eq)]
220pub(crate) enum DuplicatePolicy {
221 /// Leave the earlier entry and count the skip.
222 Skip,
223 /// Replace the earlier entry where the kinds allow it, else fail.
224 Overwrite,
225}
226
227/// What a sink extraction honours of [`ExtractionOptions`].
228///
229/// Atomic extraction renames a directory, which a sink does not have, so the
230/// only setting that carries over from path-based options is the duplicate
231/// policy. [`decode_reuse`](Self::decode_reuse) is never carried over: a sink
232/// keeps nothing between the structural check and the write unless it is asked
233/// to here.
234///
235/// # Examples
236///
237/// ```
238/// use exarch_core::ExtractionOptions;
239/// use exarch_core::SinkOptions;
240///
241/// let options = SinkOptions::default().with_skip_duplicates(false);
242/// assert!(!options.skip_duplicates);
243///
244/// let atomic = ExtractionOptions::default().with_atomic(true);
245/// assert!(SinkOptions::try_from(&atomic).is_err());
246/// ```
247#[derive(Debug, Clone, Copy, PartialEq, Eq)]
248#[non_exhaustive]
249pub struct SinkOptions {
250 /// Skip an entry whose destination path an earlier entry already holds
251 /// (the default) instead of failing.
252 pub skip_duplicates: bool,
253
254 /// Where a ZIP extraction keeps the output its structural check already
255 /// decoded, so deflate entries are decoded once instead of twice.
256 ///
257 /// Defaults to [`DecodeReuse::Off`]: with a callback or a custom sink,
258 /// every deflate entry is decoded twice, once by the structural check and
259 /// once for the sink. Callback extraction runs in O(buffer) memory in that
260 /// default, and any reuse adds to it.
261 ///
262 /// Measured (2026-11, release build, wall time of
263 /// `extract_reader_to_callback`) on a 100 MiB deflate ZIP of ten 10 MiB
264 /// members: [`DecodeReuse::Memory`]
265 /// at [`ReuseLimit::DEFAULT`](crate::ReuseLimit::DEFAULT) (32 MiB, so three
266 /// members are kept) takes about 14% less time than `Off`, and at
267 /// [`ReuseLimit::MAX`](crate::ReuseLimit::MAX) (every member kept) about
268 /// 47% less. A member above the limit gains nothing: one 40 MiB member
269 /// took the same time at the default limit as with `Off`.
270 ///
271 /// Opting in has these costs:
272 ///
273 /// - [`DecodeReuse::Memory`] holds up to its
274 /// [`ReuseLimit`](crate::ReuseLimit) on the heap. The limit counts only
275 /// the store; at its peak the process holds the store, the entry being
276 /// delivered and the sink's own copy of it.
277 /// - [`DecodeReuse::TempFile`] writes the plaintext of the archive to the
278 /// platform's temporary directory until the extraction ends, which may be
279 /// RAM on a tmpfs.
280 /// - An entry above the [`ReuseLimit`](crate::ReuseLimit) is still decoded
281 /// twice.
282 ///
283 /// [`MemorySink`] extraction through
284 /// [`extract_reader_to_memory`] always
285 /// reuses in memory within its own limit and ignores this field.
286 pub decode_reuse: DecodeReuse,
287}
288
289impl Default for SinkOptions {
290 fn default() -> Self {
291 Self {
292 skip_duplicates: true,
293 decode_reuse: DecodeReuse::Off,
294 }
295 }
296}
297
298impl SinkOptions {
299 /// Sets whether a duplicate entry is skipped or fails the extraction.
300 #[must_use]
301 pub const fn with_skip_duplicates(mut self, skip: bool) -> Self {
302 self.skip_duplicates = skip;
303 self
304 }
305
306 /// Sets where a ZIP extraction keeps the output of its structural check.
307 ///
308 /// # Examples
309 ///
310 /// ```
311 /// use exarch_core::DecodeReuse;
312 /// use exarch_core::ReuseLimit;
313 /// use exarch_core::SinkOptions;
314 ///
315 /// let options =
316 /// SinkOptions::default().with_decode_reuse(DecodeReuse::Memory(ReuseLimit::DEFAULT));
317 /// assert_eq!(
318 /// options.decode_reuse,
319 /// DecodeReuse::Memory(ReuseLimit::DEFAULT)
320 /// );
321 /// assert_eq!(SinkOptions::default().decode_reuse, DecodeReuse::Off);
322 /// ```
323 #[must_use]
324 pub const fn with_decode_reuse(mut self, reuse: DecodeReuse) -> Self {
325 self.decode_reuse = reuse;
326 self
327 }
328}
329
330impl SinkOptions {
331 /// The duplicate policy these options select.
332 pub(crate) const fn duplicate_policy(self) -> DuplicatePolicy {
333 if self.skip_duplicates {
334 DuplicatePolicy::Skip
335 } else {
336 DuplicatePolicy::Overwrite
337 }
338 }
339
340 /// The duplicate policy of path-based options, for extraction paths that
341 /// handle `atomic` themselves.
342 pub(crate) const fn duplicates_of(options: &ExtractionOptions) -> Self {
343 Self {
344 skip_duplicates: options.skip_duplicates,
345 decode_reuse: DecodeReuse::Off,
346 }
347 }
348}
349
350impl TryFrom<&ExtractionOptions> for SinkOptions {
351 type Error = ArchiveError;
352
353 /// Carries the duplicate policy over from path-based options.
354 ///
355 /// # Errors
356 ///
357 /// Returns [`ArchiveError::InvalidConfiguration`] for `atomic`, which needs
358 /// a directory to rename.
359 fn try_from(options: &ExtractionOptions) -> Result<Self> {
360 if options.atomic {
361 return Err(ArchiveError::InvalidConfiguration {
362 setting: crate::ConfigSetting::AtomicExtraction,
363 problem: crate::ConfigProblem::CannotTargetSink,
364 });
365 }
366 Ok(Self {
367 skip_duplicates: options.skip_duplicates,
368 decode_reuse: DecodeReuse::Off,
369 })
370 }
371}
372
373/// The payload of the [`io::ErrorKind::QuotaExceeded`] error a sink returns
374/// when it has no room for an entry.
375///
376/// Extraction maps it to
377/// [`QuotaResource::SinkCapacity`], so a
378/// custom sink reports running out of space the same way [`MemorySink`] does,
379/// and not as a plain [`ArchiveError::Io`].
380///
381/// # Examples
382///
383/// ```
384/// use std::io;
385///
386/// use exarch_core::SinkFull;
387///
388/// let error = io::Error::new(io::ErrorKind::QuotaExceeded, SinkFull::new(1024));
389/// assert_eq!(error.to_string(), "sink is full (1024 bytes)");
390/// ```
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392pub struct SinkFull {
393 max: u64,
394}
395
396impl SinkFull {
397 /// A full sink whose capacity is `max` bytes.
398 #[must_use]
399 pub const fn new(max: u64) -> Self {
400 Self { max }
401 }
402
403 /// The capacity that was exceeded, in bytes.
404 #[must_use]
405 pub const fn max(&self) -> u64 {
406 self.max
407 }
408}
409
410impl std::fmt::Display for SinkFull {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 write!(f, "sink is full ({} bytes)", self.max)
413 }
414}
415
416impl std::error::Error for SinkFull {}
417
418/// Receives the validated entries of an archive in extraction order.
419///
420/// See the [module documentation](self) for what every path and target
421/// guarantees. The pipeline calls a sink from a single thread, one entry at a
422/// time.
423///
424/// # Contract
425///
426/// - A file is delivered as `create_file`, a stream of writes to the returned
427/// [`File`](Self::File), then `finish_file`. A `File` that is dropped without
428/// `finish_file` is DISCARDED: the pipeline drops it when the entry fails (a
429/// forged size, a corrupt stream), so a sink must not publish data from
430/// `Drop` or from `write`.
431/// - The pipeline never flushes the `File`. `finish_file` must flush any
432/// buffering it holds and report a failed flush as an error.
433/// - Every `Err` a method returns ends the extraction with [`ArchiveError::Io`]
434/// if no entry was delivered yet, and with
435/// [`ArchiveError::PartialExtraction`] wrapping it afterwards.
436/// - Under overwrite (`skip_duplicates = false`) a later `create_file` for a
437/// path replaces the earlier one, and a hardlink reads the size of the most
438/// recent write at its target.
439/// - A hardlink is delivered after every other entry. The sink copies the bytes
440/// it holds for `target`; the pipeline has already charged the quota for
441/// them.
442pub trait EntrySink {
443 /// The writer a file's bytes stream into.
444 type File: Write;
445
446 /// The path semantics entries are validated against; the host's by
447 /// default.
448 ///
449 /// A sink whose storage is read on another platform returns
450 /// [`PathModel::Portable`].
451 fn path_model(&self) -> PathModel {
452 PathModel::Host
453 }
454
455 /// Creates a directory the archive names explicitly.
456 ///
457 /// # Errors
458 ///
459 /// Returns an error if the directory cannot be created.
460 fn create_directory(&mut self, path: &SafePath) -> io::Result<()>;
461
462 /// Starts a file of exactly `size` bytes, the size the quota tracker
463 /// admitted for it.
464 ///
465 /// `mode` is the permission bits after setuid and setgid are stripped, if
466 /// the archive carries any.
467 ///
468 /// # Errors
469 ///
470 /// Returns an error if the file cannot be started.
471 fn create_file(
472 &mut self,
473 path: &SafePath,
474 mode: Option<SanitizedMode>,
475 size: AdmittedSize,
476 ) -> io::Result<Self::File>;
477
478 /// Starts a file whose `bytes` are already complete and verified.
479 ///
480 /// The result is then passed to [`finish_file`](Self::finish_file) like one
481 /// from [`create_file`](Self::create_file), and `bytes.len()` equals
482 /// `size`. The default writes `bytes` through
483 /// [`create_file`](Self::create_file); a sink that keeps its files in
484 /// memory can override it to take the buffer without copying it.
485 ///
486 /// # Errors
487 ///
488 /// Returns an error if the file cannot be started or written.
489 ///
490 /// # Examples
491 ///
492 /// ```
493 /// use std::io;
494 ///
495 /// use exarch_core::AdmittedSize;
496 /// use exarch_core::CheckedLinkTarget;
497 /// use exarch_core::EntrySink;
498 /// use exarch_core::SafePath;
499 /// use exarch_core::SanitizedMode;
500 ///
501 /// struct VecSink;
502 ///
503 /// impl EntrySink for VecSink {
504 /// type File = Vec<u8>;
505 ///
506 /// fn create_directory(&mut self, _: &SafePath) -> io::Result<()> {
507 /// Ok(())
508 /// }
509 ///
510 /// fn create_file(
511 /// &mut self,
512 /// _: &SafePath,
513 /// _: Option<SanitizedMode>,
514 /// size: AdmittedSize,
515 /// ) -> io::Result<Vec<u8>> {
516 /// Ok(Vec::with_capacity(
517 /// usize::try_from(size.get().min(1 << 16)).unwrap_or(0),
518 /// ))
519 /// }
520 ///
521 /// fn create_file_from(
522 /// &mut self,
523 /// _: &SafePath,
524 /// _: Option<SanitizedMode>,
525 /// _: AdmittedSize,
526 /// bytes: Vec<u8>,
527 /// ) -> io::Result<Vec<u8>> {
528 /// Ok(bytes)
529 /// }
530 ///
531 /// fn finish_file(&mut self, _: &SafePath, _: Vec<u8>) -> io::Result<()> {
532 /// Ok(())
533 /// }
534 ///
535 /// fn create_symlink(&mut self, _: &SafePath, _: CheckedLinkTarget<'_>) -> io::Result<()> {
536 /// Ok(())
537 /// }
538 ///
539 /// fn create_hardlink(&mut self, _: &SafePath, _: &SafePath) -> io::Result<()> {
540 /// Ok(())
541 /// }
542 /// }
543 /// ```
544 fn create_file_from(
545 &mut self,
546 path: &SafePath,
547 mode: Option<SanitizedMode>,
548 size: AdmittedSize,
549 bytes: Vec<u8>,
550 ) -> io::Result<Self::File> {
551 let mut file = self.create_file(path, mode, size)?;
552 file.write_all(&bytes)?;
553 Ok(file)
554 }
555
556 /// Completes a file after all of its bytes were written and verified.
557 ///
558 /// # Errors
559 ///
560 /// Returns an error if the file cannot be stored, including a failed
561 /// flush.
562 fn finish_file(&mut self, path: &SafePath, file: Self::File) -> io::Result<()>;
563
564 /// Creates a symlink at `link` pointing at `target`, which is stored as
565 /// the archive spells it and is validated not to escape the root.
566 ///
567 /// Entries delivered later are already resolved through this link, so a
568 /// sink may store it as opaque data; [`CheckedLinkTarget::as_path`] gives
569 /// the text to store.
570 ///
571 /// # Errors
572 ///
573 /// Returns an error if the link cannot be created.
574 fn create_symlink(&mut self, link: &SafePath, target: CheckedLinkTarget<'_>) -> io::Result<()>;
575
576 /// Creates `link` with the content of the file at `target`.
577 ///
578 /// # Errors
579 ///
580 /// Returns an error if the link cannot be created.
581 fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()>;
582}
583
584/// A file admitted and placed in the virtual tree, not yet written.
585struct StagedFile {
586 path: SafePath,
587 mode: Option<SanitizedMode>,
588 size: AdmittedSize,
589}
590
591/// An [`ExtractTarget`] that validates against an in-memory model of the
592/// destination and delivers to an [`EntrySink`].
593pub(crate) struct SinkTarget<'a, S: EntrySink> {
594 sink: &'a mut S,
595 config: &'a SecurityConfig,
596 root: VirtualRoot,
597 model: PathModel,
598 tree: VirtualTree,
599 core: ValidatorCore<'a>,
600 /// Bytes of every file or materialized hardlink, by resolved path.
601 sizes: HashMap<PathBuf, u64>,
602 copy_buffer: CopyBuffer,
603}
604
605impl<'a, S: EntrySink> SinkTarget<'a, S> {
606 pub(crate) fn new(sink: &'a mut S, config: &'a SecurityConfig) -> Self {
607 let root = VirtualRoot::new();
608 let model = sink.path_model();
609 let tree = VirtualTree::new(
610 &root,
611 model,
612 NodeBudget::from_config(config),
613 CollisionRecording::Discard,
614 );
615 Self {
616 sink,
617 config,
618 root,
619 model,
620 tree,
621 core: ValidatorCore::new(config),
622 sizes: HashMap::new(),
623 copy_buffer: CopyBuffer::new(),
624 }
625 }
626
627 /// Validates the placement of an admitted file, or records it as a skipped
628 /// duplicate and returns `None`.
629 fn stage_file(
630 &mut self,
631 admitted: ValidatedFile,
632 tally: &mut Tally<'_>,
633 ) -> Result<Option<StagedFile>> {
634 let (path, permit, mode) = admitted.into_parts();
635 let size = permit.into_admitted();
636 // Overflow guard only, as on the host: the sum is not stored.
637 common::checked_add_bytes(tally.report.bytes_written, size.get())?;
638
639 let rel = path.as_path();
640 match (self.tree.occupant(rel), tally.options.duplicate_policy()) {
641 (Some(_), DuplicatePolicy::Skip) => {
642 tally.record_duplicate_skip(rel)?;
643 return Ok(None);
644 }
645 (
646 Some(occupant @ (Occupant::Directory | Occupant::Symlink)),
647 DuplicatePolicy::Overwrite,
648 ) => {
649 return Err(common::occupant_at_dest_error(rel, occupant).into());
650 }
651 (Some(Occupant::File) | None, _) => {}
652 }
653
654 let path = self.place(&path, Node::File)?;
655 Ok(Some(StagedFile { path, mode, size }))
656 }
657
658 /// Streams `reader` into a new sink file for `staged`, capped at its size.
659 fn write_staged<R: Read>(
660 &mut self,
661 staged: StagedFile,
662 reader: &mut R,
663 tally: &mut Tally<'_>,
664 ) -> Result<()> {
665 let mut file = self
666 .sink
667 .create_file(&staged.path, staged.mode, staged.size)
668 .map_err(sink_error)?;
669 let written = copy_with_buffer(
670 reader,
671 &mut file,
672 &mut self.copy_buffer,
673 Some(staged.size.get()),
674 )?;
675 self.finish_staged(staged.path, file, written, tally)
676 }
677
678 fn finish_staged(
679 &mut self,
680 path: SafePath,
681 file: S::File,
682 written: u64,
683 tally: &mut Tally<'_>,
684 ) -> Result<()> {
685 self.sink.finish_file(&path, file).map_err(sink_error)?;
686 self.sizes.insert(path.into_path_buf(), written);
687 tally.record_file(written)
688 }
689
690 /// Places `node` at `rel`, returning where it landed.
691 fn place(&mut self, rel: &SafePath, node: Node) -> Result<SafePath> {
692 self.tree
693 .project_landing(rel, node, LandingLimits::Enforced)
694 .map_err(place_error)
695 }
696
697 /// The path model entries are validated against.
698 pub(crate) const fn model(&self) -> PathModel {
699 self.model
700 }
701
702 /// Where a hardlink target ends up once every symlink on it is followed.
703 fn resolved_target(&self, link: &Path, target: &Path) -> Result<PathBuf> {
704 let canonical = self
705 .tree
706 .canonicalize(&self.root.as_path().join(target), &self.root)
707 .map_err(ArchiveError::Io)?;
708 match canonical {
709 Containment::Within(path) => path
710 .strip_prefix(self.root.as_path())
711 .map(Path::to_path_buf)
712 .map_err(|_| hardlink_target_missing(target)),
713 Containment::Escapes => Err(ArchiveError::HardlinkEscape {
714 path: link.to_path_buf(),
715 }),
716 }
717 }
718}
719
720fn place_error(error: PlaceError) -> ArchiveError {
721 match error {
722 PlaceError::Conflict(conflict) => conflict.into_archive_error(),
723 PlaceError::Budget(exceeded) => exceeded.into(),
724 PlaceError::LandingTooLong => ArchiveError::Io(name_too_long()),
725 }
726}
727
728/// Maps an error a sink returned, keeping a full sink typed.
729fn sink_error(error: io::Error) -> ArchiveError {
730 let full = error
731 .get_ref()
732 .and_then(|inner| inner.downcast_ref::<SinkFull>())
733 .map(SinkFull::max);
734 full.map_or_else(
735 || ArchiveError::Io(error),
736 |max| ArchiveError::QuotaExceeded {
737 resource: QuotaResource::SinkCapacity { max },
738 },
739 )
740}
741
742impl<S: EntrySink> SinkTarget<'_, S> {
743 /// Applies the host's name limits, which the host meets when it writes.
744 fn check_limits(&self, path: &Path, link: Option<(&Path, LinkKind)>) -> Result<()> {
745 self.model
746 .check_name_lengths(path)
747 .map_err(ArchiveError::Io)?;
748 if let Some((target, kind)) = link {
749 self.model
750 .check_link_target_length(target, kind)
751 .map_err(ArchiveError::Io)?;
752 }
753 Ok(())
754 }
755}
756
757impl<S: EntrySink> ExtractTarget for SinkTarget<'_, S> {
758 type AdmittedFile = ValidatedFile;
759 type Parent = Resolved;
760
761 fn validate_file(
762 &mut self,
763 request: FileRequest<'_>,
764 tally: &mut Tally<'_>,
765 ) -> Result<FileAdmission<ValidatedFile>> {
766 let ctx = self.core.context();
767 let screen = self.core.screen_file_path_in(
768 request.path,
769 request.size,
770 request.mode,
771 &self.root,
772 &self.tree,
773 &ctx,
774 )?;
775 match screen {
776 FileScreen::DisallowedExtension => tally
777 .record_extension_skip(request.path)
778 .map(FileAdmission::Skipped),
779 FileScreen::Pending(pending) => {
780 let file = self.core.admit_file(pending)?;
781 self.check_limits(request.path, None)?;
782 Ok(FileAdmission::Write(file))
783 }
784 }
785 }
786
787 fn validate_directory(&mut self, path: &Path, size: EntrySize) -> Result<SafePath> {
788 let ctx = self.core.context();
789 let safe_path = self
790 .core
791 .validate_directory_in(path, size, &self.root, &self.tree, &ctx)?;
792 self.check_limits(path, None)?;
793 Ok(safe_path)
794 }
795
796 fn validate_symlink(
797 &mut self,
798 path: &Path,
799 target: &Path,
800 size: EntrySize,
801 ) -> Result<SafeSymlink> {
802 let ctx = self.core.context();
803 let validated = self
804 .core
805 .validate_symlink_in(path, target, size, &self.root, &self.tree, &ctx)?;
806 self.check_limits(path, Some((target, LinkKind::Symlink)))?;
807 Ok(validated.symlink)
808 }
809
810 fn validate_hardlink(
811 &mut self,
812 path: &Path,
813 target: &Path,
814 size: EntrySize,
815 ) -> Result<ValidatedHardlink> {
816 let ctx = self.core.context();
817 let validated = self
818 .core
819 .validate_hardlink_in(path, target, size, &self.root, &self.tree, &ctx)?;
820 self.check_limits(path, Some((target, LinkKind::Hardlink)))?;
821 Ok(validated)
822 }
823
824 fn directory(&mut self, path: &SafePath, tally: &mut Tally<'_>) -> Result<()> {
825 let rel = path.as_path();
826 let occupied = self.tree.occupant(rel).is_some();
827 let resolved = self.place(path, Node::Dir)?;
828 if !occupied && !rel.is_empty() {
829 self.sink.create_directory(&resolved).map_err(sink_error)?;
830 }
831 tally.report.directories_created += 1;
832 Ok(())
833 }
834
835 fn file<R: Read>(
836 &mut self,
837 reader: &mut R,
838 admitted: ValidatedFile,
839 tally: &mut Tally<'_>,
840 ) -> Result<()> {
841 let Some(staged) = self.stage_file(admitted, tally)? else {
842 return Ok(());
843 };
844 self.write_staged(staged, reader, tally)
845 }
846
847 fn file_retained(
848 &mut self,
849 retained: Retained<'_>,
850 admitted: ValidatedFile,
851 tally: &mut Tally<'_>,
852 ) -> Result<()> {
853 let Some(staged) = self.stage_file(admitted, tally)? else {
854 return Ok(());
855 };
856 match retained {
857 Retained::Bytes(bytes) if bytes.len() as u64 == staged.size.get() => {
858 let written = bytes.len() as u64;
859 let file = self
860 .sink
861 .create_file_from(&staged.path, staged.mode, staged.size, bytes)
862 .map_err(sink_error)?;
863 self.finish_staged(staged.path, file, written, tally)
864 }
865 Retained::Bytes(bytes) => self.write_staged(staged, &mut bytes.as_slice(), tally),
866 Retained::Spooled(mut reader) => self.write_staged(staged, &mut reader, tally),
867 }
868 }
869
870 fn symlink(&mut self, symlink: &SafeSymlink, tally: &mut Tally<'_>) -> Result<()> {
871 let link = symlink.link();
872 let rel = link.as_path();
873 let target = symlink.target_path();
874 let occupant = self.tree.occupant(rel);
875 match (occupant, tally.options.duplicate_policy()) {
876 (Some(_), DuplicatePolicy::Skip) => return tally.record_duplicate_skip(rel).map(drop),
877 (Some(Occupant::Directory), DuplicatePolicy::Overwrite) => {
878 return Err(common::occupant_at_dest_error(rel, Occupant::Directory).into());
879 }
880 (Some(Occupant::Symlink), DuplicatePolicy::Overwrite) => {
881 // An unchanged link re-points nothing; any other target is
882 // refused by the tree.
883 let unchanged = self.tree.project_landing(
884 link,
885 Node::Symlink(target.to_path_buf()),
886 LandingLimits::Enforced,
887 );
888 return match unchanged {
889 Ok(_) => common::record_duplicate_skip(tally.report, rel),
890 Err(PlaceError::Conflict(_)) => {
891 Err(common::occupant_at_dest_error(rel, Occupant::Symlink).into())
892 }
893 Err(error) => Err(place_error(error)),
894 };
895 }
896 (Some(Occupant::File) | None, _) => {}
897 }
898
899 let node = Node::Symlink(target.to_path_buf());
900 let resolved = match self
901 .tree
902 .project_landing(link, node.clone(), LandingLimits::Enforced)
903 {
904 Ok(resolved) => resolved,
905 // The tree reports a symlink replacing a file as a conflict but
906 // does replace it, as the host does; placing it again finds its
907 // own unchanged duplicate and returns the path.
908 Err(PlaceError::Conflict(conflict)) if conflict.occupant == Some(Occupant::File) => {
909 self.place(link, node)?
910 }
911 Err(error) => return Err(place_error(error)),
912 };
913 self.sink
914 .create_symlink(&resolved, symlink.checked_target())
915 .map_err(sink_error)?;
916 tally.report.symlinks_created += 1;
917 Ok(())
918 }
919
920 fn hardlink(
921 &mut self,
922 link: &SafePath,
923 target: &HardlinkTarget,
924 counted: EntryCount,
925 tally: &mut Tally<'_>,
926 ) -> Result<()> {
927 let config = self.config;
928 let link = SafePath::validate_in(link.as_path(), &self.root, config, &self.tree)?;
929 let target = &HardlinkTracker::new().validate_hardlink_in(
930 &link,
931 target.as_path(),
932 &self.root,
933 config,
934 &self.tree,
935 )?;
936
937 let full = self.root.as_path().join(target.as_path());
938 if !self.tree.exists(&full) {
939 return Err(hardlink_target_missing(target.as_path()));
940 }
941 if self.tree.resolves_to_dir(&full) {
942 return Err(ArchiveError::from(Malformation::HardlinkTargetDirectory {
943 target: target.as_path().to_path_buf(),
944 }));
945 }
946 if self.tree.occupant(link.as_path()).is_some() {
947 if tally.options.duplicate_policy() == DuplicatePolicy::Skip {
948 return common::record_duplicate_skip(tally.report, link.as_path());
949 }
950 return Err(ArchiveError::from(Malformation::DuplicateEntry {
951 path: link.as_path().to_path_buf(),
952 }));
953 }
954
955 let resolved_target = self.resolved_target(link.as_path(), target.as_path())?;
956 let size = self
957 .sizes
958 .get(&resolved_target)
959 .copied()
960 .ok_or_else(|| hardlink_target_missing(target.as_path()))?;
961 self.core.charge_hardlink(counted, size).map(drop)?;
962
963 let target_landing =
964 SafePath::from_normalized(resolved_target).map_err(ArchiveError::Io)?;
965 let resolved = self.place(&link, Node::File)?;
966 self.sink
967 .create_hardlink(&resolved, &target_landing)
968 .map_err(sink_error)?;
969 self.sizes.insert(resolved.into_path_buf(), size);
970
971 tally.record_file(size)
972 }
973}