Skip to main content

archive_trait/
lib.rs

1//! Format-neutral, asynchronous archive construction and extraction.
2//!
3//! Archive formats implement [`ArchiveBuilder`] and call
4//! [`ArchiveBuilder::builder`] to reuse high-level entry addition, recursive
5//! filesystem traversal, validation, and source streaming.
6//! Archive formats implement [`Archive`] by projecting their entries into
7//! [`Member`] values.
8//!
9//! Extraction assumes unique access to the destination directory. Concurrent
10//! mutation of that directory is outside the threat model.
11#![cfg_attr(
12    feature = "fs",
13    doc = "",
14    doc = "The default [`Archive::extract_in`] implementation applies common",
15    doc = "extraction policy and filesystem behavior."
16)]
17
18pub mod builder;
19mod component_tree;
20#[cfg(feature = "fs")]
21pub mod extract;
22mod name;
23
24use std::marker::PhantomData;
25#[cfg(feature = "fs")]
26use std::{
27    io,
28    path::{Path, PathBuf},
29};
30
31#[cfg(feature = "fs")]
32use thiserror::Error;
33
34#[cfg(feature = "fs")]
35pub use builder::TraversalError;
36pub use builder::{ArchiveBuilder, BuildError, Builder, EntryMetadata, FilePayload};
37pub use name::{NameValidator, default_name_validator};
38
39/// Common metadata for one archive member.
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub struct MemberMetadata {
42    /// The archive-relative member path before extraction normalization.
43    pub path: String,
44    /// The member's byte position in the source archive.
45    pub position: u64,
46}
47
48/// A special-file kind that generic extraction deliberately rejects.
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50pub enum SpecialKind {
51    /// A character device.
52    CharacterDevice,
53    /// A block device.
54    BlockDevice,
55    /// A FIFO.
56    Fifo,
57}
58
59/// One format-neutral archive member.
60#[derive(Debug)]
61pub enum Member<P> {
62    /// A regular file with a streaming payload.
63    File {
64        /// Common member metadata.
65        metadata: MemberMetadata,
66        /// The logical, decoded payload size in bytes.
67        ///
68        /// `payload` must yield exactly this many bytes before completing
69        /// successfully. Format-level framing and compression are excluded.
70        size: u64,
71        /// Whether the archived mode carries executable intent.
72        executable: bool,
73        /// The streaming member payload.
74        payload: P,
75    },
76    /// A directory.
77    Directory {
78        /// Common member metadata.
79        metadata: MemberMetadata,
80    },
81    /// A symbolic link.
82    SymbolicLink {
83        /// Common member metadata.
84        metadata: MemberMetadata,
85        /// The archive-provided link target.
86        target: String,
87    },
88    /// A hard link, optionally followed by replacement payload bytes.
89    HardLink {
90        /// Common member metadata.
91        metadata: MemberMetadata,
92        /// The archive-provided link target.
93        target: String,
94        /// The logical, decoded replacement-payload size in bytes.
95        ///
96        /// `payload` must yield exactly this many bytes before completing
97        /// successfully. Format-level framing and compression are excluded.
98        size: u64,
99        /// The streaming member payload.
100        payload: P,
101    },
102    /// A parsed special file that cannot be extracted safely.
103    Special {
104        /// Common member metadata.
105        metadata: MemberMetadata,
106        /// The special-file kind.
107        kind: SpecialKind,
108    },
109}
110
111impl<P> Member<P> {
112    /// Returns this member's common metadata.
113    pub fn metadata(&self) -> &MemberMetadata {
114        match self {
115            Self::File { metadata, .. }
116            | Self::Directory { metadata }
117            | Self::SymbolicLink { metadata, .. }
118            | Self::HardLink { metadata, .. }
119            | Self::Special { metadata, .. } => metadata,
120        }
121    }
122
123    /// Transforms this member's payload, if it has one.
124    pub fn map_payload<Q>(self, map: impl FnOnce(P) -> Q) -> Member<Q> {
125        match self {
126            Self::File {
127                metadata,
128                size,
129                executable,
130                payload,
131            } => Member::File {
132                metadata,
133                size,
134                executable,
135                payload: map(payload),
136            },
137            Self::Directory { metadata } => Member::Directory { metadata },
138            Self::SymbolicLink { metadata, target } => Member::SymbolicLink { metadata, target },
139            Self::HardLink {
140                metadata,
141                target,
142                size,
143                payload,
144            } => Member::HardLink {
145                metadata,
146                target,
147                size,
148                payload: map(payload),
149            },
150            Self::Special { metadata, kind } => Member::Special { metadata, kind },
151        }
152    }
153}
154
155/// A streaming cursor over one archive member's payload.
156#[expect(
157    async_fn_in_trait,
158    reason = "payload readers may be !Send and run on a local executor"
159)]
160pub trait MemberPayload: Sized {
161    /// The archive-format error returned while reading the payload.
162    type Error;
163
164    /// Reads the next validated, logical payload chunk into a reusable buffer.
165    ///
166    /// Returns `true` after replacing `buffer` with a nonempty chunk. Returns
167    /// `false` only after the payload has been fully consumed and validated,
168    /// leaving `buffer` unchanged so its initialized storage can be reused.
169    /// Callers should not clear `buffer` between calls. Implementations may
170    /// return chunks shorter than `target_len`.
171    ///
172    /// Successful chunks contain decoded member contents rather than stored or
173    /// compressed bytes. Their total length must equal the `size` declared by
174    /// the enclosing [`Member`]; a mismatch must produce an error.
175    async fn next_chunk(
176        &mut self,
177        buffer: &mut Vec<u8>,
178        target_len: usize,
179    ) -> Result<bool, Self::Error>;
180
181    /// Discards and validates all remaining payload bytes.
182    async fn skip(self) -> Result<(), Self::Error>;
183}
184
185/// A member payload that keeps its lending [`Members`] cursor borrowed.
186///
187/// This wrapper is returned by [`Members::next`]. Its private fields prevent a
188/// payload whose concrete type does not itself borrow the archive from being
189/// detached from the cursor lifetime.
190#[derive(Debug)]
191pub struct LentPayload<'a, P> {
192    payload: P,
193    cursor: PhantomData<&'a mut ()>,
194}
195
196impl<P> LentPayload<'_, P> {
197    fn new(payload: P) -> Self {
198        Self {
199            payload,
200            cursor: PhantomData,
201        }
202    }
203}
204
205impl<P: MemberPayload> MemberPayload for LentPayload<'_, P> {
206    type Error = P::Error;
207
208    async fn next_chunk(
209        &mut self,
210        buffer: &mut Vec<u8>,
211        target_len: usize,
212    ) -> Result<bool, Self::Error> {
213        self.payload.next_chunk(buffer, target_len).await
214    }
215
216    async fn skip(self) -> Result<(), Self::Error> {
217        self.payload.skip().await
218    }
219}
220
221/// A consuming, lending member cursor.
222pub struct Members<A> {
223    archive: A,
224}
225
226impl<A: Archive> Members<A> {
227    /// Returns the next archive member.
228    ///
229    /// The returned payload borrows this cursor, so the cursor cannot advance
230    /// until that member is dropped or consumed.
231    /// See [`Archive::next_member`] for behavior after an error or cancellation.
232    pub async fn next<'a>(
233        &'a mut self,
234    ) -> Result<Option<Member<LentPayload<'a, A::Payload<'a>>>>, A::Error> {
235        Ok(self
236            .archive
237            .next_member()
238            .await?
239            .map(|member| member.map_payload(LentPayload::new)))
240    }
241}
242
243/// A one-pass archive that can enumerate and extract format-neutral members.
244#[expect(
245    async_fn_in_trait,
246    reason = "archive readers may be !Send and run on a local executor"
247)]
248pub trait Archive: Sized {
249    /// The archive-format error returned during member iteration.
250    type Error;
251    /// The streaming payload type lent by each file member.
252    type Payload<'a>: MemberPayload<Error = Self::Error>
253    where
254        Self: 'a;
255
256    /// Reads the next format-neutral member for [`Members::next`].
257    ///
258    /// Implementations must drain and validate an unfinished preceding payload
259    /// before returning another member. Archive consumers should use
260    /// [`Archive::members`] rather than call this hook directly: [`Members`]
261    /// wraps each payload in [`LentPayload`] to enforce the lending cursor
262    /// contract even when a concrete payload type does not retain its lifetime.
263    ///
264    /// Returns `Ok(None)` at the end of the archive. See the implementation's
265    /// documentation for whether reads can continue after a decoding error or
266    /// cancellation.
267    async fn next_member<'a>(
268        &'a mut self,
269    ) -> Result<Option<Member<Self::Payload<'a>>>, Self::Error>;
270
271    /// Consumes this archive and returns its lending member cursor.
272    ///
273    /// Member paths may repeat, and distinct paths may resolve to the same file
274    /// on disk. Callers that write members to disk themselves must decide how
275    /// to handle those collisions. Doing so is non-trivial.
276    #[cfg_attr(
277        feature = "fs",
278        doc = "Most users are **strongly** encouraged to use [`Self::extract_in`]."
279    )]
280    fn members(self) -> Members<Self> {
281        Members { archive: self }
282    }
283
284    /// Securely extracts this archive beneath `destination` under `policy`.
285    ///
286    /// This method requires the `fs` feature.
287    ///
288    /// `destination` is created if it does not already exist. Symbolic links
289    /// are preserved by default on platforms that support native creation;
290    /// hard links require explicit opt-in through [`extract::LinkPolicy`].
291    ///
292    /// Archived Unix permission modes are normalized rather than restored.
293    /// When creating a regular file on Unix, the extractor requests mode
294    /// `0o777` if the archive marks the file executable and `0o666` otherwise.
295    /// The host determines the file's effective permissions from that mode and
296    /// local settings such as the process umask or an access control list
297    /// inherited from the parent directory.
298    /// Directories use the platform's default creation mode, and special mode
299    /// bits are not restored. Ownership and timestamps are likewise determined
300    /// by extraction activity rather than archived metadata.
301    ///
302    /// **IMPORTANT**: `destination` must not be concurrently modified during
303    /// extraction. No correctness or isolation guarantees are made under
304    /// external mutation.
305    ///
306    /// Extraction is streamwise: a late error can leave a partially extracted
307    /// destination. Callers requiring all-or-nothing behavior should extract
308    /// into a new temporary directory and atomically rename it afterward.
309    #[cfg(feature = "fs")]
310    async fn extract_in<P: AsRef<Path>>(
311        self,
312        destination: P,
313        policy: extract::ExtractPolicy,
314    ) -> Result<(), ExtractError<Self::Error>> {
315        extract::extract(self.members(), destination.as_ref(), policy).await
316    }
317}
318
319/// A valid member feature rejected by the selected [`extract::ExtractPolicy`].
320#[cfg(feature = "fs")]
321#[derive(Clone, Debug, Eq, PartialEq, Error)]
322pub enum ExtractPolicyViolation {
323    /// An effective member name or link target was rejected.
324    #[error("archive {context} rejected by name policy: {value:?}")]
325    NameRejected {
326        /// The role of the rejected archive text.
327        context: &'static str,
328        /// The rejected UTF-8 value.
329        value: String,
330    },
331    /// A symbolic-link member appeared when links are forbidden.
332    #[error("symbolic-link members are not allowed")]
333    SymbolicLink,
334    /// A symbolic-link member requires native creation on an unsupported platform.
335    #[error("native symbolic-link creation is not supported on this platform")]
336    NativeSymlinkCreationUnsupported,
337    /// A hard-link member appeared when links are forbidden.
338    #[error("hard-link members are not allowed")]
339    HardLink,
340}
341
342/// An error produced while securely extracting an archive.
343#[cfg(feature = "fs")]
344#[derive(Debug, Error)]
345pub enum ExtractError<E> {
346    /// Reading or decoding the underlying archive failed.
347    #[error(transparent)]
348    Archive(E),
349    /// A destination filesystem operation failed.
350    #[error("failed to {operation} {path}: {source}")]
351    Filesystem {
352        /// The operation that failed.
353        operation: &'static str,
354        /// The path involved in the failed operation.
355        path: PathBuf,
356        /// The underlying I/O error.
357        #[source]
358        source: io::Error,
359    },
360    /// A blocking extraction operation failed to complete.
361    #[error("failed to complete blocking extraction operation: {0}")]
362    BlockingTask(#[from] tokio::task::JoinError),
363    /// An archive member path or link value is unsafe to extract.
364    #[error("at byte {position}: unsafe {context} {value:?}: {reason}")]
365    UnsafePath {
366        /// Source member position.
367        position: u64,
368        /// Whether this is a member path or link target.
369        context: &'static str,
370        /// Archive-provided value.
371        value: String,
372        /// Rejection reason.
373        reason: &'static str,
374    },
375    /// An archive entry collides with a path that cannot be replaced.
376    #[error("archive entry collides with existing path {path}")]
377    PathCollision {
378        /// Normalized extraction-relative path.
379        path: PathBuf,
380    },
381    /// A special member kind is deliberately excluded from extraction.
382    #[error("at byte {position}: cannot extract unsupported member type {kind:?} at {path}")]
383    UnsupportedMember {
384        /// Source member position.
385        position: u64,
386        /// Normalized extraction-relative path.
387        path: PathBuf,
388        /// Unsupported special-file kind.
389        kind: SpecialKind,
390    },
391    /// A symbolic or hard link cannot be safely resolved.
392    #[error("at byte {position}: invalid link {path} -> {target:?}: {reason}")]
393    InvalidLink {
394        /// Source member position.
395        position: u64,
396        /// Normalized link path.
397        path: PathBuf,
398        /// Archive-provided or normalized link target.
399        target: String,
400        /// Rejection reason.
401        reason: &'static str,
402    },
403    /// A structurally valid member was rejected by extraction policy.
404    #[error("at byte {position}: extraction policy rejected input: {violation}")]
405    PolicyViolation {
406        /// Source member position.
407        position: u64,
408        /// The selected policy rule that rejected the member.
409        violation: ExtractPolicyViolation,
410    },
411}
412
413#[cfg(feature = "fs")]
414impl<E> ExtractError<E> {
415    fn policy_violation(position: u64, violation: ExtractPolicyViolation) -> Self {
416        Self::PolicyViolation {
417            position,
418            violation,
419        }
420    }
421
422    fn invalid_link(position: u64, path: PathBuf, target: String, reason: &'static str) -> Self {
423        Self::InvalidLink {
424            position,
425            path,
426            target,
427            reason,
428        }
429    }
430
431    fn unsafe_path(
432        position: u64,
433        context: &'static str,
434        value: &str,
435        reason: &'static str,
436    ) -> Self {
437        Self::UnsafePath {
438            position,
439            context,
440            value: value.to_owned(),
441            reason,
442        }
443    }
444
445    fn filesystem(operation: &'static str, path: PathBuf, source: io::Error) -> Self {
446        Self::Filesystem {
447            operation,
448            path,
449            source,
450        }
451    }
452}