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