exarch_core/sink.rs
1//! Extraction into caller-owned storage instead of a directory.
2//!
3//! [`extract_to_sink`](crate::extract_to_sink) 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::ArchiveReader;
82//! use exarch_core::EntrySink;
83//! use exarch_core::SafePath;
84//! use exarch_core::SanitizedMode;
85//! use exarch_core::SecurityConfig;
86//! use exarch_core::SinkOptions;
87//! use exarch_core::extract_to_sink;
88//!
89//! #[derive(Default)]
90//! struct MapSink(BTreeMap<PathBuf, Vec<u8>>);
91//!
92//! impl EntrySink for MapSink {
93//! type File = Vec<u8>;
94//!
95//! fn create_directory(&mut self, _: &SafePath) -> io::Result<()> {
96//! Ok(())
97//! }
98//!
99//! fn create_file(
100//! &mut self,
101//! _: &SafePath,
102//! _: Option<SanitizedMode>,
103//! size: u64,
104//! ) -> io::Result<Vec<u8>> {
105//! Ok(Vec::with_capacity(
106//! usize::try_from(size.min(1 << 16)).unwrap_or(0),
107//! ))
108//! }
109//!
110//! fn finish_file(&mut self, path: &SafePath, file: Vec<u8>) -> io::Result<()> {
111//! self.0.insert(path.as_path().to_path_buf(), file);
112//! Ok(())
113//! }
114//!
115//! fn create_symlink(&mut self, _: &SafePath, _: &Path) -> io::Result<()> {
116//! Ok(())
117//! }
118//!
119//! fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()> {
120//! let bytes = self.0.get(target.as_path()).cloned().unwrap_or_default();
121//! self.0.insert(link.as_path().to_path_buf(), bytes);
122//! Ok(())
123//! }
124//! }
125//!
126//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
127//! let mut builder = tar::Builder::new(Vec::new());
128//! let mut header = tar::Header::new_gnu();
129//! header.set_size(5);
130//! header.set_mode(0o644);
131//! builder.append_data(&mut header, "docs/hello.txt", &b"hello"[..])?;
132//! let archive = builder.into_inner()?;
133//!
134//! let mut sink = MapSink::default();
135//! let reader = ArchiveReader::tar(io::Cursor::new(archive), None);
136//! let report = extract_to_sink(
137//! reader,
138//! &mut sink,
139//! &SecurityConfig::default(),
140//! &SinkOptions::default(),
141//! )?;
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 memory;
149
150pub use memory::MemoryEntry;
151pub use memory::MemoryEntryKind;
152pub use memory::MemoryFile;
153pub use memory::MemoryLimit;
154pub use memory::MemorySink;
155pub use memory::extract_bytes_to_memory;
156pub use memory::utf8_entry_path;
157
158use std::collections::HashMap;
159use std::io;
160use std::io::Read;
161use std::io::Write;
162use std::path::Path;
163use std::path::PathBuf;
164
165use crate::ArchiveError;
166use crate::ExtractionOptions;
167use crate::QuotaResource;
168use crate::Result;
169use crate::SecurityConfig;
170use crate::config::Validated;
171use crate::copy::CopyBuffer;
172use crate::copy::copy_with_buffer;
173use crate::formats::common;
174use crate::formats::target::ExtractTarget;
175use crate::formats::target::FileAdmission;
176use crate::formats::target::FileRequest;
177use crate::formats::target::Tally;
178use crate::security::admitted::EntrySize;
179use crate::security::admitted::ValidatedFile;
180use crate::security::admitted::ValidatedHardlink;
181use crate::security::fs_view::CollisionRecording;
182use crate::security::fs_view::Containment;
183use crate::security::fs_view::FsView as _;
184use crate::security::fs_view::LinkKind;
185use crate::security::fs_view::ModelRoot as _;
186use crate::security::fs_view::Node;
187use crate::security::fs_view::NodeBudget;
188use crate::security::fs_view::Occupant;
189use crate::security::fs_view::PathModel;
190use crate::security::fs_view::PlaceError;
191use crate::security::fs_view::VirtualRoot;
192use crate::security::fs_view::VirtualTree;
193use crate::security::hardlink::HardlinkTracker;
194use crate::security::hardlink::hardlink_target_missing;
195use crate::security::permissions::SanitizedMode;
196use crate::security::quota::EntryCount;
197use crate::security::validator::ValidatorCore;
198use crate::types::SafePath;
199use crate::types::SafeSymlink;
200
201/// What a sink extraction honours of [`ExtractionOptions`].
202///
203/// Atomic extraction renames a directory, which a sink does not have, so the
204/// only setting that carries over is the duplicate policy.
205///
206/// # Examples
207///
208/// ```
209/// use exarch_core::ExtractionOptions;
210/// use exarch_core::SinkOptions;
211///
212/// let options = SinkOptions::default().with_skip_duplicates(false);
213/// assert!(!options.skip_duplicates);
214///
215/// let atomic = ExtractionOptions::default().with_atomic(true);
216/// assert!(SinkOptions::try_from(&atomic).is_err());
217/// ```
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219#[non_exhaustive]
220pub struct SinkOptions {
221 /// Skip an entry whose destination path an earlier entry already holds
222 /// (the default) instead of failing.
223 pub skip_duplicates: bool,
224}
225
226impl Default for SinkOptions {
227 fn default() -> Self {
228 Self {
229 skip_duplicates: true,
230 }
231 }
232}
233
234impl SinkOptions {
235 /// Sets whether a duplicate entry is skipped or fails the extraction.
236 #[must_use]
237 pub const fn with_skip_duplicates(mut self, skip: bool) -> Self {
238 self.skip_duplicates = skip;
239 self
240 }
241}
242
243impl SinkOptions {
244 /// The duplicate policy of path-based options, for extraction paths that
245 /// handle `atomic` themselves.
246 pub(crate) const fn duplicates_of(options: &ExtractionOptions) -> Self {
247 Self {
248 skip_duplicates: options.skip_duplicates,
249 }
250 }
251}
252
253impl TryFrom<&ExtractionOptions> for SinkOptions {
254 type Error = ArchiveError;
255
256 /// Carries the duplicate policy over from path-based options.
257 ///
258 /// # Errors
259 ///
260 /// Returns [`ArchiveError::InvalidConfiguration`] for `atomic`, which needs
261 /// a directory to rename.
262 fn try_from(options: &ExtractionOptions) -> Result<Self> {
263 if options.atomic {
264 return Err(ArchiveError::InvalidConfiguration {
265 reason: "atomic extraction renames a directory and cannot target a sink".into(),
266 });
267 }
268 Ok(Self {
269 skip_duplicates: options.skip_duplicates,
270 })
271 }
272}
273
274/// The payload of the [`io::ErrorKind::QuotaExceeded`] error a sink returns
275/// when it has no room for an entry.
276///
277/// Extraction maps it to
278/// [`QuotaResource::SinkCapacity`], so a
279/// custom sink reports running out of space the same way [`MemorySink`] does,
280/// and not as a plain [`ArchiveError::Io`].
281///
282/// # Examples
283///
284/// ```
285/// use std::io;
286///
287/// use exarch_core::SinkFull;
288///
289/// let error = io::Error::new(io::ErrorKind::QuotaExceeded, SinkFull::new(1024));
290/// assert_eq!(error.to_string(), "sink is full (1024 bytes)");
291/// ```
292#[derive(Debug, Clone, Copy, PartialEq, Eq)]
293pub struct SinkFull {
294 max: u64,
295}
296
297impl SinkFull {
298 /// A full sink whose capacity is `max` bytes.
299 #[must_use]
300 pub const fn new(max: u64) -> Self {
301 Self { max }
302 }
303
304 /// The capacity that was exceeded, in bytes.
305 #[must_use]
306 pub const fn max(&self) -> u64 {
307 self.max
308 }
309}
310
311impl std::fmt::Display for SinkFull {
312 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
313 write!(f, "sink is full ({} bytes)", self.max)
314 }
315}
316
317impl std::error::Error for SinkFull {}
318
319/// Receives the validated entries of an archive in extraction order.
320///
321/// See the [module documentation](self) for what every path and target
322/// guarantees. The pipeline calls a sink from a single thread, one entry at a
323/// time.
324///
325/// # Contract
326///
327/// - A file is delivered as `create_file`, a stream of writes to the returned
328/// [`File`](Self::File), then `finish_file`. A `File` that is dropped without
329/// `finish_file` is DISCARDED: the pipeline drops it when the entry fails (a
330/// forged size, a corrupt stream), so a sink must not publish data from
331/// `Drop` or from `write`.
332/// - The pipeline never flushes the `File`. `finish_file` must flush any
333/// buffering it holds and report a failed flush as an error.
334/// - Every `Err` a method returns ends the extraction with [`ArchiveError::Io`]
335/// if no entry was delivered yet, and with
336/// [`ArchiveError::PartialExtraction`] wrapping it afterwards.
337/// - Under overwrite (`skip_duplicates = false`) a later `create_file` for a
338/// path replaces the earlier one, and a hardlink reads the size of the most
339/// recent write at its target.
340/// - A hardlink is delivered after every other entry. The sink copies the bytes
341/// it holds for `target`; the pipeline has already charged the quota for
342/// them.
343pub trait EntrySink {
344 /// The writer a file's bytes stream into.
345 type File: Write;
346
347 /// The path semantics entries are validated against; the host's by
348 /// default.
349 ///
350 /// A sink whose storage is read on another platform returns
351 /// [`PathModel::Portable`].
352 fn path_model(&self) -> PathModel {
353 PathModel::Host
354 }
355
356 /// Creates a directory the archive names explicitly.
357 ///
358 /// # Errors
359 ///
360 /// Returns an error if the directory cannot be created.
361 fn create_directory(&mut self, path: &SafePath) -> io::Result<()>;
362
363 /// Starts a file of exactly `size` bytes, as the archive declares it.
364 ///
365 /// `mode` is the permission bits after setuid and setgid are stripped, if
366 /// the archive carries any.
367 ///
368 /// # Errors
369 ///
370 /// Returns an error if the file cannot be started.
371 fn create_file(
372 &mut self,
373 path: &SafePath,
374 mode: Option<SanitizedMode>,
375 size: u64,
376 ) -> io::Result<Self::File>;
377
378 /// Completes a file after all of its bytes were written and verified.
379 ///
380 /// # Errors
381 ///
382 /// Returns an error if the file cannot be stored, including a failed
383 /// flush.
384 fn finish_file(&mut self, path: &SafePath, file: Self::File) -> io::Result<()>;
385
386 /// Creates a symlink at `link` pointing at `target`, which is stored as
387 /// the archive spells it and is validated not to escape the root.
388 ///
389 /// Entries delivered later are already resolved through this link, so a
390 /// sink may store it as opaque data.
391 ///
392 /// # Errors
393 ///
394 /// Returns an error if the link cannot be created.
395 fn create_symlink(&mut self, link: &SafePath, target: &Path) -> io::Result<()>;
396
397 /// Creates `link` with the content of the file at `target`.
398 ///
399 /// # Errors
400 ///
401 /// Returns an error if the link cannot be created.
402 fn create_hardlink(&mut self, link: &SafePath, target: &SafePath) -> io::Result<()>;
403}
404
405/// An [`ExtractTarget`] that validates against an in-memory model of the
406/// destination and delivers to an [`EntrySink`].
407pub(crate) struct SinkTarget<'a, S: EntrySink> {
408 sink: &'a mut S,
409 config: &'a SecurityConfig<Validated>,
410 root: VirtualRoot,
411 model: PathModel,
412 tree: VirtualTree,
413 core: ValidatorCore<'a>,
414 /// Bytes of every file or materialized hardlink, by resolved path.
415 sizes: HashMap<PathBuf, u64>,
416 copy_buffer: CopyBuffer,
417}
418
419impl<'a, S: EntrySink> SinkTarget<'a, S> {
420 pub(crate) fn new(sink: &'a mut S, config: &'a SecurityConfig<Validated>) -> Self {
421 let root = VirtualRoot::new();
422 let model = sink.path_model();
423 let tree = VirtualTree::new(
424 &root,
425 model,
426 NodeBudget::from_config(config),
427 CollisionRecording::Discard,
428 );
429 Self {
430 sink,
431 config,
432 root,
433 model,
434 tree,
435 core: ValidatorCore::new(config),
436 sizes: HashMap::new(),
437 copy_buffer: CopyBuffer::new(),
438 }
439 }
440
441 /// Places `node` at `rel`, returning where it landed.
442 fn place(&mut self, rel: &Path, node: Node) -> Result<SafePath> {
443 let resolved = self.tree.place(rel, node).map_err(place_error)?;
444 self.landed_within_limits(resolved)
445 }
446
447 /// The path an entry landed at, checked against the model's name limits:
448 /// the entry's own name was checked before it was resolved through earlier
449 /// symlinks, and the path it lands at can be longer.
450 fn landed_within_limits(&self, resolved: PathBuf) -> Result<SafePath> {
451 self.model
452 .check_name_lengths(&resolved)
453 .map_err(ArchiveError::Io)?;
454 Ok(landed(resolved))
455 }
456
457 /// The path model entries are validated against.
458 pub(crate) const fn model(&self) -> PathModel {
459 self.model
460 }
461
462 /// Where a hardlink target ends up once every symlink on it is followed.
463 fn resolved_target(&self, link: &Path, target: &Path) -> Result<PathBuf> {
464 let canonical = self
465 .tree
466 .canonicalize(&self.root.as_path().join(target), &self.root)
467 .map_err(ArchiveError::Io)?;
468 match canonical {
469 Containment::Within(path) => path
470 .strip_prefix(self.root.as_path())
471 .map(Path::to_path_buf)
472 .map_err(|_| hardlink_target_missing(target)),
473 Containment::Escapes => Err(ArchiveError::HardlinkEscape {
474 path: link.to_path_buf(),
475 }),
476 }
477 }
478}
479
480fn place_error(error: PlaceError) -> ArchiveError {
481 match error {
482 PlaceError::Conflict(conflict) => ArchiveError::Io(conflict.error),
483 PlaceError::Budget(exceeded) => exceeded.into(),
484 }
485}
486
487/// Maps an error a sink returned, keeping a full sink typed.
488fn sink_error(error: io::Error) -> ArchiveError {
489 let full = error
490 .get_ref()
491 .and_then(|inner| inner.downcast_ref::<SinkFull>())
492 .map(SinkFull::max);
493 full.map_or_else(
494 || ArchiveError::Io(error),
495 |max| ArchiveError::QuotaExceeded {
496 resource: QuotaResource::SinkCapacity { max },
497 },
498 )
499}
500
501fn landed(resolved: PathBuf) -> SafePath {
502 // SAFETY: the tree builds the path from components of entries that passed
503 // `SafePath` validation and from nothing else, so it is relative and
504 // normalized.
505 SafePath::new_unchecked(resolved)
506}
507
508impl<S: EntrySink> SinkTarget<'_, S> {
509 /// Applies the host's name limits, which the host meets when it writes.
510 fn check_limits(&self, path: &Path, link: Option<(&Path, LinkKind)>) -> Result<()> {
511 self.model
512 .check_name_lengths(path)
513 .map_err(ArchiveError::Io)?;
514 if let Some((target, kind)) = link {
515 self.model
516 .check_link_target_length(target, kind)
517 .map_err(ArchiveError::Io)?;
518 }
519 Ok(())
520 }
521}
522
523impl<S: EntrySink> ExtractTarget for SinkTarget<'_, S> {
524 type AdmittedFile = ValidatedFile;
525
526 fn validate_file(
527 &mut self,
528 request: FileRequest<'_>,
529 _tally: &mut Tally<'_>,
530 ) -> Result<FileAdmission<ValidatedFile>> {
531 let ctx = self.core.context();
532 let file = self.core.validate_file_in(
533 request.path,
534 request.size,
535 request.mode,
536 &self.root,
537 &self.tree,
538 &ctx,
539 )?;
540 self.check_limits(request.path, None)?;
541 Ok(FileAdmission::Write(file))
542 }
543
544 fn validate_directory(&mut self, path: &Path, size: EntrySize) -> Result<SafePath> {
545 let ctx = self.core.context();
546 let safe_path = self
547 .core
548 .validate_directory_in(path, size, &self.root, &self.tree, &ctx)?;
549 self.check_limits(path, None)?;
550 Ok(safe_path)
551 }
552
553 fn validate_symlink(
554 &mut self,
555 path: &Path,
556 target: &Path,
557 size: EntrySize,
558 ) -> Result<SafeSymlink> {
559 let ctx = self.core.context();
560 let validated = self
561 .core
562 .validate_symlink_in(path, target, size, &self.root, &self.tree, &ctx)?;
563 self.check_limits(path, Some((target, LinkKind::Symlink)))?;
564 Ok(validated.symlink)
565 }
566
567 fn validate_hardlink(
568 &mut self,
569 path: &Path,
570 target: &Path,
571 size: EntrySize,
572 ) -> Result<ValidatedHardlink> {
573 let ctx = self.core.context();
574 let validated = self
575 .core
576 .validate_hardlink_in(path, target, size, &self.root, &self.tree, &ctx)?;
577 self.check_limits(path, Some((target, LinkKind::Hardlink)))?;
578 Ok(validated)
579 }
580
581 fn directory(&mut self, path: &SafePath, tally: &mut Tally<'_>) -> Result<()> {
582 let rel = path.as_path();
583 let occupied = self.tree.occupant(rel).is_some();
584 let resolved = self.place(rel, Node::Dir)?;
585 if !occupied && !rel.is_empty() {
586 self.sink.create_directory(&resolved).map_err(sink_error)?;
587 }
588 tally.report.directories_created += 1;
589 Ok(())
590 }
591
592 fn file<R: Read>(
593 &mut self,
594 reader: &mut R,
595 admitted: ValidatedFile,
596 size: u64,
597 tally: &mut Tally<'_>,
598 ) -> Result<()> {
599 // Overflow guard only, as on the host: the sum is not stored.
600 common::checked_add_bytes(tally.report.bytes_written, size)?;
601
602 let ValidatedFile { path, mode, .. } = admitted;
603 let rel = path.as_path();
604 match (self.tree.occupant(rel), tally.options.skip_duplicates) {
605 (Some(_), true) => return tally.record_duplicate_skip().map(drop),
606 (Some(occupant @ (Occupant::Directory | Occupant::Symlink)), false) => {
607 return Err(common::occupant_at_dest_error(rel, occupant).into());
608 }
609 (Some(Occupant::File) | None, _) => {}
610 }
611
612 let resolved = self.place(rel, Node::File)?;
613 let mut file = self
614 .sink
615 .create_file(&resolved, mode, size)
616 .map_err(sink_error)?;
617 let written = copy_with_buffer(reader, &mut file, &mut self.copy_buffer, Some(size))?;
618 self.sink.finish_file(&resolved, file).map_err(sink_error)?;
619 self.sizes.insert(resolved.into_path_buf(), written);
620
621 if written > 0 {
622 tally.progress.on_bytes_written(written);
623 }
624 tally.report.files_extracted += 1;
625 tally.report.bytes_written =
626 common::checked_add_bytes(tally.report.bytes_written, written)?;
627 Ok(())
628 }
629
630 fn symlink(&mut self, symlink: &SafeSymlink, tally: &mut Tally<'_>) -> Result<()> {
631 let rel = symlink.link_path();
632 let target = symlink.target_path();
633 let occupant = self.tree.occupant(rel);
634 match (occupant, tally.options.skip_duplicates) {
635 (Some(_), true) => return tally.record_duplicate_skip().map(drop),
636 (Some(Occupant::Directory), false) => {
637 return Err(common::occupant_at_dest_error(rel, Occupant::Directory).into());
638 }
639 (Some(Occupant::Symlink), false) => {
640 // An unchanged link re-points nothing; any other target is
641 // refused by the tree.
642 let unchanged = self.tree.place(rel, Node::Symlink(target.to_path_buf()));
643 return match unchanged {
644 Ok(_) => common::checked_increment_files_skipped(tally.report),
645 Err(PlaceError::Budget(exceeded)) => Err(exceeded.into()),
646 Err(PlaceError::Conflict(_)) => {
647 Err(common::occupant_at_dest_error(rel, Occupant::Symlink).into())
648 }
649 };
650 }
651 (Some(Occupant::File) | None, _) => {}
652 }
653
654 let node = Node::Symlink(target.to_path_buf());
655 let resolved = match self.tree.place(rel, node.clone()) {
656 Ok(resolved) => self.landed_within_limits(resolved)?,
657 // The tree reports a symlink replacing a file as a conflict but
658 // does replace it, as the host does; placing it again finds its
659 // own unchanged duplicate and returns the path.
660 Err(PlaceError::Conflict(conflict)) if conflict.occupant == Some(Occupant::File) => {
661 self.place(rel, node)?
662 }
663 Err(error) => return Err(place_error(error)),
664 };
665 self.sink
666 .create_symlink(&resolved, target)
667 .map_err(sink_error)?;
668 tally.report.symlinks_created += 1;
669 Ok(())
670 }
671
672 fn hardlink(
673 &mut self,
674 link: &SafePath,
675 target: &SafePath,
676 counted: EntryCount,
677 tally: &mut Tally<'_>,
678 hardlink_duplicate_skips: &mut u64,
679 ) -> Result<()> {
680 let config = self.config;
681 let link = SafePath::validate_in(link.as_path(), &self.root, config, &self.tree)?;
682 HardlinkTracker::new().validate_hardlink_in(
683 &link,
684 target.as_path(),
685 &self.root,
686 config,
687 &self.tree,
688 )?;
689
690 let full = self.root.as_path().join(target.as_path());
691 if !self.tree.exists(&full) {
692 return Err(hardlink_target_missing(target.as_path()));
693 }
694 if self.tree.resolves_to_dir(&full) {
695 return Err(ArchiveError::InvalidArchive(format!(
696 "hardlink target is a directory: {}",
697 target.as_path().display()
698 )));
699 }
700 if self.tree.occupant(link.as_path()).is_some() {
701 if tally.options.skip_duplicates {
702 common::checked_increment_files_skipped(tally.report)?;
703 *hardlink_duplicate_skips = hardlink_duplicate_skips.saturating_add(1);
704 return Ok(());
705 }
706 return Err(ArchiveError::InvalidArchive(format!(
707 "duplicate entry: {}",
708 link.as_path().display()
709 )));
710 }
711
712 let resolved_target = self.resolved_target(link.as_path(), target.as_path())?;
713 let size = self
714 .sizes
715 .get(&resolved_target)
716 .copied()
717 .ok_or_else(|| hardlink_target_missing(target.as_path()))?;
718 self.core.charge_hardlink(counted, size).map(drop)?;
719
720 let resolved = self.place(link.as_path(), Node::File)?;
721 self.sink
722 .create_hardlink(&resolved, &landed(resolved_target))
723 .map_err(sink_error)?;
724 self.sizes.insert(resolved.into_path_buf(), size);
725
726 tally.report.files_extracted = common::checked_add_count(tally.report.files_extracted, 1)?;
727 tally.report.bytes_written = common::checked_add_bytes(tally.report.bytes_written, size)?;
728 tally.progress.on_bytes_written(size);
729 Ok(())
730 }
731}