Skip to main content

archive_trait/
extract.rs

1//! Format-neutral archive extraction.
2//!
3//! [`ExtractPolicy`] configures common path, overwrite, and link behavior.
4//! Filesystem mutation is capability-relative and confined to the destination.
5
6mod path;
7mod root;
8
9use std::path::Path;
10
11use self::{path::decode_member, root::ExtractionRoot};
12use super::*;
13
14/// Controls behavior shared by [`Archive::extract_in`] implementations.
15///
16/// See each configuration API for its default.
17#[derive(Clone, Copy, Debug)]
18pub struct ExtractPolicy {
19    pub(crate) link_policy: LinkPolicy,
20    pub(crate) allow_overwrites: bool,
21    pub(crate) name_validation: crate::name::NameValidation,
22}
23
24/// Controls how symbolic- and hard-link members are extracted.
25///
26/// By default, symbolic links are preserved as native links, including links
27/// to pre-existing entries and missing targets. Resolving a preserved link
28/// must stay within the extraction root. Hard links require explicit opt-in.
29///
30/// Extraction limits preserved symbolic links to 8 MiB per archive across
31/// their records, paths, original targets, and normalized targets. Each link
32/// counts toward the limit even if a later member overwrites it.
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
34pub struct LinkPolicy {
35    pub(crate) symlink_policy: SymlinkPolicy,
36    pub(crate) allow_hard_links: bool,
37    pub(crate) allow_missing_targets: bool,
38}
39
40/// Controls how symbolic-link members are handled during extraction.
41#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
42pub enum SymlinkPolicy {
43    /// Preserve symbolic-link members as native filesystem links.
44    #[default]
45    Preserve,
46    /// Ignore symbolic-link members without changing the filesystem.
47    Skip,
48    /// Reject archives containing symbolic-link members.
49    Reject,
50}
51
52impl Default for ExtractPolicy {
53    fn default() -> Self {
54        Self {
55            link_policy: LinkPolicy::default(),
56            allow_overwrites: true,
57            name_validation: crate::name::NameValidation::Default,
58        }
59    }
60}
61
62impl Default for LinkPolicy {
63    fn default() -> Self {
64        Self {
65            symlink_policy: SymlinkPolicy::default(),
66            allow_hard_links: false,
67            allow_missing_targets: true,
68        }
69    }
70}
71
72impl ExtractPolicy {
73    /// Configures symbolic- and hard-link extraction behavior.
74    pub fn link_policy(mut self, policy: LinkPolicy) -> Self {
75        self.link_policy = policy;
76        self
77    }
78
79    /// Configures whether archive members may replace existing entries.
80    ///
81    /// Overwrites are **allowed by default**. Replacement never follows
82    /// symbolic links or recursively removes non-empty directories. Real
83    /// directories are always reused, including when overwrites are disabled.
84    pub fn allow_overwrites(mut self, allow: bool) -> Self {
85        self.allow_overwrites = allow;
86        self
87    }
88
89    /// Configures validation for member names and link targets.
90    ///
91    /// Passing [`None`] disables configurable name validation. UTF-8 and
92    /// extraction containment requirements still apply.
93    pub fn name_validator(mut self, validator: Option<NameValidator>) -> Self {
94        self.name_validation = crate::name::NameValidation::from_validator(validator);
95        self
96    }
97
98    fn check_name<E>(
99        self,
100        position: u64,
101        context: &'static str,
102        value: &str,
103    ) -> Result<(), ExtractError<E>> {
104        if !self.name_validation.accepts(value) {
105            return Err(ExtractError::policy_violation(
106                position,
107                ExtractPolicyViolation::NameRejected {
108                    context,
109                    value: value.to_owned(),
110                },
111            ));
112        }
113        Ok(())
114    }
115}
116
117impl LinkPolicy {
118    /// Configures how symbolic-link members are handled during extraction.
119    ///
120    /// Symbolic links are preserved by default. Platforms without native
121    /// symbolic-link creation require [`SymlinkPolicy::Skip`] or
122    /// [`SymlinkPolicy::Reject`].
123    pub fn symlink_policy(mut self, policy: SymlinkPolicy) -> Self {
124        self.symlink_policy = policy;
125        self
126    }
127
128    /// Configures whether hard-link members may be extracted.
129    ///
130    /// Hard links are **forbidden by default** because they are uncommon,
131    /// difficult to extract consistently, and prone to implementation
132    /// differentials. Enable them only for trusted archives.
133    pub fn allow_hard_links(mut self, allow: bool) -> Self {
134        self.allow_hard_links = allow;
135        self
136    }
137
138    /// Configures whether symbolic links to missing targets may be extracted.
139    ///
140    /// Missing symbolic-link targets are **allowed by default**. This does not
141    /// affect hard-link validation.
142    pub fn allow_missing_targets(mut self, allow: bool) -> Self {
143        self.allow_missing_targets = allow;
144        self
145    }
146}
147
148/// Extracts a member stream into `destination` under the shared extraction policy.
149pub(crate) async fn extract<A: Archive>(
150    mut members: Members<A>,
151    destination: &Path,
152    policy: ExtractPolicy,
153) -> Result<(), ExtractError<A::Error>> {
154    let mut root = ExtractionRoot::<A::Error>::open(destination, policy.allow_overwrites).await?;
155    // Scratch space reused for each payload read and streamed directly for large files.
156    let mut chunk_buffer = Vec::new();
157    // Complete small-file contents, buffered so payload validation precedes file creation.
158    let mut buffered_payload = Vec::new();
159    let result: Result<(), ExtractError<A::Error>> = async {
160        while let Some(member) = members.next().await.map_err(ExtractError::Archive)? {
161            check_member_policy(&member, policy)?;
162            let decoded = decode_member(&member, policy)?;
163            match member {
164                Member::File {
165                    size,
166                    executable,
167                    payload,
168                    ..
169                } => {
170                    root.extract_file(
171                        &decoded.path,
172                        size,
173                        executable,
174                        payload,
175                        &mut chunk_buffer,
176                        &mut buffered_payload,
177                    )
178                    .await?;
179                }
180                Member::Directory { .. } => root.extract_directory(&decoded.path).await?,
181                Member::SymbolicLink { .. } => {
182                    if policy.link_policy.symlink_policy == SymlinkPolicy::Preserve {
183                        root.reserve_symlink(decoded).await?;
184                    }
185                }
186                Member::HardLink { size, payload, .. } => {
187                    root.extract_hard_link(&decoded, size, payload, &mut chunk_buffer)
188                        .await?;
189                }
190                Member::Special { kind, .. } => {
191                    return Err(ExtractError::UnsupportedMember {
192                        position: decoded.position,
193                        path: decoded.path.to_path_buf(),
194                        kind,
195                    });
196                }
197            }
198        }
199        Ok(())
200    }
201    .await;
202    // Commit earlier validated files before reporting a later member error.
203    root.flush_buffered_files().await?;
204    result?;
205    root.finalize_symlinks(policy.link_policy).await
206}
207
208fn check_member_policy<E, P>(
209    member: &Member<P>,
210    policy: ExtractPolicy,
211) -> Result<(), ExtractError<E>> {
212    let position = member.metadata().position;
213    match member {
214        Member::SymbolicLink { .. } => {
215            let violation = match policy.link_policy.symlink_policy {
216                SymlinkPolicy::Reject => Some(ExtractPolicyViolation::SymbolicLink),
217                #[cfg(not(unix))]
218                SymlinkPolicy::Preserve => {
219                    Some(ExtractPolicyViolation::NativeSymlinkCreationUnsupported)
220                }
221                _ => None,
222            };
223            if let Some(violation) = violation {
224                return Err(ExtractError::policy_violation(position, violation));
225            }
226        }
227        Member::HardLink { .. } if !policy.link_policy.allow_hard_links => {
228            return Err(ExtractError::policy_violation(
229                position,
230                ExtractPolicyViolation::HardLink,
231            ));
232        }
233        _ => {}
234    }
235    Ok(())
236}