Skip to main content

tar_codec/
decode.rs

1//! Member-oriented decoding of pax or GNU tar streams.
2//!
3//! The decoder applies format extensions to member paths and link targets.
4//! It does not normalize these values for extraction. Do not use them directly
5//! as file-system paths. [`ArchiveTrait::extract_in`] validates and normalizes
6//! them as specified by [`crate::extract::ExtractPolicy`].
7
8use std::collections::HashSet;
9
10use archive_trait::{
11    Archive as ArchiveTrait, Member, MemberMetadata, MemberPayload as MemberPayloadTrait,
12    SpecialKind,
13};
14use tar_framing::{
15    ArchiveFormat, FrameError, PaxKeyword, PaxKind, PaxRecord, PaxValue, StreamPolicy, UstarKind,
16    logical::{MemberExtensions, MemberFrame, MemberPayload as FramingMemberPayload, TarReader},
17};
18use thiserror::Error;
19use tokio::io::AsyncRead;
20
21pub use tar_framing::{
22    DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE, DEFAULT_MAX_GNU_EXTENSION_SIZE,
23    DEFAULT_MAX_PAX_EXTENSION_SIZE,
24};
25
26/// This type reads one structurally valid pax or GNU tar archive in one pass.
27///
28/// Member paths and link targets are not normalized for extraction. A direct
29/// consumer must validate them before it uses them as file-system paths.
30/// [`ArchiveTrait::extract_in`] does this validation.
31///
32/// Member iteration is fused. After reaching the end of the archive or
33/// returning a decoding error, every subsequent attempt returns end-of-archive.
34pub struct TarArchive<R> {
35    reader: TarReader<R>,
36    policy: DecodePolicy,
37    fused: bool,
38}
39
40impl<R> TarArchive<R> {
41    /// Creates an archive decoder from an uncompressed tar reader.
42    pub fn new(reader: R) -> Self {
43        Self {
44            reader: TarReader::new(reader),
45            policy: DecodePolicy::default(),
46            fused: false,
47        }
48    }
49
50    /// Configures the decoding policy used by this archive.
51    ///
52    /// Call before reading any members.
53    pub fn with_policy(mut self, policy: DecodePolicy) -> Self {
54        let stream_policy = StreamPolicy::default()
55            .max_pax_extension_size(policy.pax_policy.max_extension_size)
56            .max_global_pax_extensions_size(policy.pax_policy.max_global_extensions_size)
57            .allow_pax_hardlink_linkdata(policy.pax_policy.allow_hardlink_linkdata)
58            .allow_all_nul_numeric_fields(policy.allow_all_nul_numeric_fields)
59            .allow_header_uname_and_gname_without_terminator(
60                policy.allow_header_uname_and_gname_without_terminator,
61            )
62            .max_gnu_extension_size(policy.max_gnu_extension_size);
63        self.reader = self.reader.with_policy(stream_policy);
64        self.policy = policy;
65        self
66    }
67}
68
69/// Controls tar compatibility and the feature subset member decoding may accept.
70///
71/// See each configuration API for its default.
72#[derive(Clone, Debug)]
73pub struct DecodePolicy {
74    allow_gnu: bool,
75    allow_all_nul_numeric_fields: bool,
76    allow_header_uname_and_gname_without_terminator: bool,
77    max_gnu_extension_size: u64,
78    pax_policy: PaxDecodePolicy,
79}
80
81/// Controls pax compatibility and the feature subset member decoding may accept.
82///
83/// See each allow API for its default.
84#[derive(Clone, Debug, Eq, PartialEq)]
85pub struct PaxDecodePolicy {
86    max_extension_size: u64,
87    max_global_extensions_size: u64,
88    allow_non_utf8_pax_vendor_values: bool,
89    allow_global_pax_extensions: bool,
90    vendor_extension_policy: PaxVendorExtensionPolicy,
91    allow_duplicate_pax_records: bool,
92    allow_global_pax_member_metadata: bool,
93    allow_hardlink_linkdata: bool,
94}
95
96/// Controls which vendor-namespaced pax records may be ignored during decoding.
97#[derive(Clone, Debug, Default, Eq, PartialEq)]
98pub enum PaxVendorExtensionPolicy {
99    /// Reject every unknown vendor-namespaced pax record.
100    #[default]
101    RejectUnknown,
102    /// Ignore only records whose vendor namespaces appear in this allowlist.
103    ///
104    /// A vendor namespace such as `SCHILY` permits every `SCHILY.*` record.
105    Ignore(PaxVendorAllowlist),
106    /// Ignore every unknown vendor-namespaced pax record.
107    ///
108    /// Unknown vendor semantics can affect the archive's intended contents.
109    AllowUnknown,
110}
111
112impl PaxVendorExtensionPolicy {
113    /// Ignores vendor records whose vendor namespaces appear in `vendors`.
114    ///
115    /// A vendor namespace such as `SCHILY` permits every `SCHILY.*` record.
116    pub fn ignore(vendors: impl IntoIterator<Item = &'static str>) -> Self {
117        Self::Ignore(PaxVendorAllowlist {
118            vendors: vendors.into_iter().collect(),
119        })
120    }
121}
122
123/// An opaque allowlist of pax vendor namespaces.
124///
125/// Construct an allowlist with [`PaxVendorExtensionPolicy::ignore`].
126#[derive(Clone, Debug, Eq, PartialEq)]
127pub struct PaxVendorAllowlist {
128    vendors: HashSet<&'static str>,
129}
130
131impl Default for PaxDecodePolicy {
132    fn default() -> Self {
133        Self {
134            max_extension_size: DEFAULT_MAX_PAX_EXTENSION_SIZE,
135            max_global_extensions_size: DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE,
136            allow_non_utf8_pax_vendor_values: true,
137            allow_global_pax_extensions: true,
138            vendor_extension_policy: PaxVendorExtensionPolicy::default(),
139            allow_duplicate_pax_records: false,
140            allow_global_pax_member_metadata: false,
141            allow_hardlink_linkdata: false,
142        }
143    }
144}
145
146impl Default for DecodePolicy {
147    fn default() -> Self {
148        Self {
149            allow_gnu: true,
150            allow_all_nul_numeric_fields: true,
151            allow_header_uname_and_gname_without_terminator: false,
152            max_gnu_extension_size: DEFAULT_MAX_GNU_EXTENSION_SIZE,
153            pax_policy: PaxDecodePolicy::default(),
154        }
155    }
156}
157
158impl DecodePolicy {
159    /// Configures whether archives in the GNU framing family may be decoded.
160    ///
161    /// GNU tar archives are **allowed by default**.
162    ///
163    /// Users who wish to parse strictly pax-confirming tar archives may wish to
164    /// disable this setting.
165    pub fn allow_gnu(mut self, allow: bool) -> Self {
166        self.allow_gnu = allow;
167        self
168    }
169
170    /// Configures whether wholly NUL numeric metadata fields may be accepted.
171    ///
172    /// This compatibility option applies to the ordinary header's `mode`, `uid`,
173    /// `gid`, and `mtime` fields in both pax/ustar and GNU archives. It is
174    /// **enabled by default**. When enabled, a wholly NUL field is represented
175    /// as missing; every other value must be a valid numeric encoding for its
176    /// archive family.
177    pub fn allow_all_nul_numeric_fields(mut self, allow: bool) -> Self {
178        self.allow_all_nul_numeric_fields = allow;
179        self
180    }
181
182    /// Configures whether ordinary header `uname` and `gname` fields may omit their NUL terminators.
183    ///
184    /// This compatibility option applies to ordinary pax/ustar and GNU member
185    /// headers and is **disabled by default**. Enabling it accepts names that
186    /// occupy all 32 bytes of either field.
187    pub fn allow_header_uname_and_gname_without_terminator(mut self, allow: bool) -> Self {
188        self.allow_header_uname_and_gname_without_terminator = allow;
189        self
190    }
191
192    /// Configures the maximum payload size accepted for one GNU metadata extension.
193    ///
194    /// The limit applies independently to long-name and long-link extensions.
195    /// An extension that declares a larger payload is rejected before its
196    /// payload is consumed. The default is [`DEFAULT_MAX_GNU_EXTENSION_SIZE`].
197    /// Setting the limit to zero rejects every GNU extension. Setting it to
198    /// [`u64::MAX`] permits unbounded metadata buffering.
199    pub fn max_gnu_extension_size(mut self, max_gnu_extension_size: u64) -> Self {
200        self.max_gnu_extension_size = max_gnu_extension_size;
201        self
202    }
203
204    /// Configures the accepted pax feature subset.
205    pub fn pax_policy(mut self, policy: PaxDecodePolicy) -> Self {
206        self.pax_policy = policy;
207        self
208    }
209
210    fn check_format(&self, position: u64, format: ArchiveFormat) -> Result<(), DecodeError> {
211        if format == ArchiveFormat::Gnu && !self.allow_gnu {
212            return Err(DecodeError::policy_violation(
213                position,
214                DecodePolicyViolation::GnuArchive,
215            ));
216        }
217        Ok(())
218    }
219
220    fn check_global_pax(&self, position: u64, records: &[PaxRecord]) -> Result<(), DecodeError> {
221        self.pax_policy.check_global_pax_extension(position)?;
222        self.pax_policy
223            .check_pax_records(position, PaxKind::Global, records)
224    }
225
226    fn check_member<R>(&self, frame: &MemberFrame<'_, R>) -> Result<(), DecodeError> {
227        if let MemberExtensions::Pax(state) = &frame.extensions {
228            for extension in state
229                .extensions()
230                .filter(|extension| extension.kind == PaxKind::Global)
231            {
232                self.check_global_pax(extension.position, extension.records())?;
233            }
234        }
235        let format_position = match &frame.extensions {
236            MemberExtensions::Pax(_) => frame.header.position,
237            MemberExtensions::Gnu {
238                long_name,
239                long_link,
240            } => long_name
241                .iter()
242                .chain(long_link.iter())
243                .map(|header| header.position)
244                .min()
245                .unwrap_or(frame.header.position),
246        };
247        self.check_format(format_position, frame.header.format)?;
248        if let MemberExtensions::Pax(state) = &frame.extensions {
249            for extension in state
250                .extensions()
251                .filter(|extension| extension.kind == PaxKind::Local)
252            {
253                self.pax_policy.check_pax_records(
254                    extension.position,
255                    PaxKind::Local,
256                    extension.records(),
257                )?;
258            }
259        }
260        Ok(())
261    }
262}
263
264impl PaxDecodePolicy {
265    /// Configures the maximum payload size in bytes accepted for one pax extension.
266    ///
267    /// The limit applies independently to each local or global extension and
268    /// covers all records in that extension. An extension that declares a
269    /// larger payload is rejected before its payload is consumed.
270    ///
271    /// The default is [`DEFAULT_MAX_PAX_EXTENSION_SIZE`]. Setting the limit to
272    /// zero rejects every nonempty pax extension. Setting it to [`u64::MAX`]
273    /// removes the limit for each extension. Each global extension still counts
274    /// toward the limit for the full archive.
275    pub fn max_extension_size(mut self, max_extension_size: u64) -> Self {
276        self.max_extension_size = max_extension_size;
277        self
278    }
279
280    /// Sets the maximum total payload size of all global pax extensions.
281    ///
282    /// This limit applies to the full archive. It does not reset after an
283    /// ordinary member.
284    ///
285    /// The default is [`DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE`]. A value of zero
286    /// rejects each nonempty global extension. A value of [`u64::MAX`] removes
287    /// this limit. The separate limit for each extension still applies.
288    pub fn max_global_extensions_size(mut self, max_global_extensions_size: u64) -> Self {
289        self.max_global_extensions_size = max_global_extensions_size;
290        self
291    }
292
293    /// Configures whether vendor-namespaced pax record values may contain non-UTF-8 bytes.
294    ///
295    /// This compatibility option is enabled by default to accommodate raw extensions
296    /// incorrectly emitted by other real-world writers. Disabling it requires every vendor
297    /// record value to be valid UTF-8. Vendor values remain exposed as opaque
298    /// bytes in either mode.
299    ///
300    /// [`Self::vendor_extension_policy`] separately controls whether decoding
301    /// may ignore vendor records after they have been parsed.
302    pub fn allow_non_utf8_pax_vendor_values(mut self, allow: bool) -> Self {
303        self.allow_non_utf8_pax_vendor_values = allow;
304        self
305    }
306
307    /// Configures whether global pax extension headers may be accepted.
308    ///
309    /// When enabled, [`Self::allow_global_pax_member_metadata`] separately
310    /// controls whether global `path`, `linkpath`, and `size` records are
311    /// accepted. Trailing global headers without a following ordinary member
312    /// are consumed and ignored before policy checks.
313    ///
314    /// Global pax extension headers are **allowed by default**.
315    pub fn allow_global_pax_extensions(mut self, allow: bool) -> Self {
316        self.allow_global_pax_extensions = allow;
317        self
318    }
319
320    /// Configures which unknown vendor-namespaced pax records may be ignored.
321    ///
322    /// [`PaxVendorExtensionPolicy::Ignore`] accepts every record under its
323    /// explicitly listed vendor namespaces, while
324    /// [`PaxVendorExtensionPolicy::AllowUnknown`] accepts every
325    /// vendor-namespaced record. Accepted values are parsed structurally, but
326    /// their semantics are not interpreted.
327    ///
328    /// This can produce output that differs from the archive's intended
329    /// contents. For example, `GNU.sparse.*` records can change a member's
330    /// effective name, logical size, and mapping from stored payload bytes to
331    /// file contents; these semantics are ignored when this option is enabled.
332    ///
333    /// **IMPORTANT**: Only permit records whose ignored semantics are
334    /// acceptable. Unknown vendor-namespaced pax records are **forbidden by
335    /// default**.
336    pub fn vendor_extension_policy(mut self, policy: PaxVendorExtensionPolicy) -> Self {
337        self.vendor_extension_policy = policy;
338        self
339    }
340
341    /// Configures whether one pax extended header may repeat a keyword.
342    ///
343    /// When enabled, standard pax precedence applies and the last record for
344    /// a repeated keyword takes effect.
345    ///
346    /// Duplicated pax records within a single header are **forbidden by default**.
347    pub fn allow_duplicate_pax_records(mut self, allow: bool) -> Self {
348        self.allow_duplicate_pax_records = allow;
349        self
350    }
351
352    /// Configures whether global pax headers may set member path or size data.
353    ///
354    /// When enabled, standard pax semantics permit global `path`, `linkpath`,
355    /// and `size` records to apply to following members until overridden.
356    ///
357    /// Member metadata within global pax headers is **forbidden by default**,
358    /// as it is extremely differential-prone.
359    pub fn allow_global_pax_member_metadata(mut self, allow: bool) -> Self {
360        self.allow_global_pax_member_metadata = allow;
361        self
362    }
363
364    /// Allows pax hard links to carry file data, as written by `pax -o linkdata`.
365    ///
366    /// This is **disabled by default** because readers disagree on whether the
367    /// block after a hard link contains file data or the next member header.
368    /// When enabled, the effective pax size determines the payload length.
369    /// If [hard-link extraction](crate::extract::LinkPolicy::allow_hard_links)
370    /// is also enabled, a nonempty payload replaces the target file's contents.
371    pub fn allow_hardlink_linkdata(mut self, allow: bool) -> Self {
372        self.allow_hardlink_linkdata = allow;
373        self
374    }
375
376    fn check_global_pax_extension(&self, position: u64) -> Result<(), DecodeError> {
377        if !self.allow_global_pax_extensions {
378            return Err(DecodeError::policy_violation(
379                position,
380                DecodePolicyViolation::GlobalPaxExtension,
381            ));
382        }
383        Ok(())
384    }
385
386    fn check_pax_records(
387        &self,
388        position: u64,
389        kind: PaxKind,
390        records: &[PaxRecord],
391    ) -> Result<(), DecodeError> {
392        for record in records {
393            if let PaxRecord::Vendor {
394                vendor,
395                name,
396                value,
397            } = record
398            {
399                let allowed = match &self.vendor_extension_policy {
400                    PaxVendorExtensionPolicy::RejectUnknown => false,
401                    PaxVendorExtensionPolicy::Ignore(allowed) => {
402                        allowed.vendors.contains(vendor.as_ref())
403                    }
404                    PaxVendorExtensionPolicy::AllowUnknown => true,
405                };
406                if !allowed {
407                    return Err(DecodeError::policy_violation(
408                        position,
409                        DecodePolicyViolation::PaxVendorExtension {
410                            vendor: vendor.to_string(),
411                            name: name.to_string(),
412                        },
413                    ));
414                }
415
416                if !self.allow_non_utf8_pax_vendor_values
417                    && let PaxValue::Value(value) = value
418                    && std::str::from_utf8(value).is_err()
419                {
420                    return Err(DecodeError::policy_violation(
421                        position,
422                        DecodePolicyViolation::NonUtf8PaxVendorValue {
423                            vendor: vendor.to_string(),
424                            name: name.to_string(),
425                        },
426                    ));
427                }
428            }
429        }
430
431        if kind == PaxKind::Global && !self.allow_global_pax_member_metadata {
432            for record in records {
433                let keyword = match record.keyword() {
434                    PaxKeyword::Path => Some("path"),
435                    PaxKeyword::LinkPath => Some("linkpath"),
436                    PaxKeyword::Size => Some("size"),
437                    _ => None,
438                };
439                if let Some(keyword) = keyword {
440                    return Err(DecodeError::policy_violation(
441                        position,
442                        DecodePolicyViolation::GlobalPaxMemberMetadata { keyword },
443                    ));
444                }
445            }
446        }
447
448        if !self.allow_duplicate_pax_records {
449            let mut keywords = HashSet::new();
450            for record in records {
451                let keyword = record.keyword();
452                if !keywords.insert(keyword.clone()) {
453                    return Err(DecodeError::policy_violation(
454                        position,
455                        DecodePolicyViolation::DuplicatePaxRecord {
456                            keyword: keyword.to_string(),
457                        },
458                    ));
459                }
460            }
461        }
462
463        Ok(())
464    }
465}
466
467/// A tar feature accepted by framing but rejected by the selected [`DecodePolicy`].
468#[derive(Clone, Debug, Eq, PartialEq, Error)]
469pub enum DecodePolicyViolation {
470    /// A GNU-family frame appeared when only POSIX-pax decoding is allowed.
471    #[error("GNU archives are not allowed")]
472    GnuArchive,
473    /// A global POSIX pax extended header appeared when it is forbidden.
474    #[error("global pax extended headers are not allowed")]
475    GlobalPaxExtension,
476    /// A vendor-namespaced POSIX pax record appeared.
477    #[error("pax vendor extension {vendor}.{name} is not allowed")]
478    PaxVendorExtension {
479        /// Vendor namespace.
480        vendor: String,
481        /// Keyword suffix following the vendor namespace.
482        name: String,
483    },
484    /// A vendor-namespaced POSIX pax record contains a non-UTF-8 value.
485    #[error("pax vendor extension {vendor}.{name} contains a non-UTF-8 value")]
486    NonUtf8PaxVendorValue {
487        /// Vendor namespace.
488        vendor: String,
489        /// Keyword suffix following the vendor namespace.
490        name: String,
491    },
492    /// One POSIX pax extended header repeats the same logical keyword.
493    #[error("pax extended header contains duplicate record {keyword}")]
494    DuplicatePaxRecord {
495        /// The repeated POSIX pax record keyword.
496        keyword: String,
497    },
498    /// A global POSIX pax header supplies per-member identity or framing data.
499    #[error("global pax extended header contains restricted member metadata {keyword}")]
500    GlobalPaxMemberMetadata {
501        /// The restricted global record keyword.
502        keyword: &'static str,
503    },
504}
505
506/// An error produced while decoding tar members.
507#[derive(Debug, Error)]
508pub enum DecodeError {
509    /// The underlying tar stream is not structurally valid.
510    #[error(transparent)]
511    Framing(#[from] FrameError),
512    /// An effective member path or link target is not UTF-8 text.
513    #[error("at byte {position}: {field} is not valid UTF-8")]
514    InvalidUtf8 {
515        /// Source tar block position.
516        position: u64,
517        /// Metadata field being decoded.
518        field: &'static str,
519    },
520    /// A structurally valid tar feature was rejected by decode policy.
521    #[error("at byte {position}: decode policy rejected input: {violation}")]
522    PolicyViolation {
523        /// Source header position for the rejected feature.
524        position: u64,
525        /// The selected policy rule that rejected the feature.
526        violation: DecodePolicyViolation,
527    },
528}
529
530impl DecodeError {
531    fn policy_violation(position: u64, violation: DecodePolicyViolation) -> Self {
532        Self::PolicyViolation {
533            position,
534            violation,
535        }
536    }
537}
538
539/// A tar member payload adapted to [`MemberPayloadTrait`].
540pub struct TarMemberPayload<'a, R> {
541    payload: FramingMemberPayload<'a, R>,
542}
543
544impl<R: AsyncRead + Unpin> MemberPayloadTrait for TarMemberPayload<'_, R> {
545    type Error = DecodeError;
546
547    async fn next_chunk(
548        &mut self,
549        buffer: &mut Vec<u8>,
550        target_len: usize,
551    ) -> Result<bool, Self::Error> {
552        self.payload
553            .next_chunk(buffer, target_len)
554            .await
555            .map_err(Into::into)
556    }
557
558    async fn skip(self) -> Result<(), Self::Error> {
559        self.payload.skip().await.map_err(Into::into)
560    }
561}
562
563impl<R: AsyncRead + Unpin> ArchiveTrait for TarArchive<R> {
564    type Error = DecodeError;
565    type Payload<'a>
566        = TarMemberPayload<'a, R>
567    where
568        Self: 'a;
569
570    async fn next_member<'a>(
571        &'a mut self,
572    ) -> Result<Option<Member<Self::Payload<'a>>>, Self::Error> {
573        if self.fused {
574            return Ok(None);
575        }
576
577        let result = match self.reader.next_frame().await {
578            Ok(Some(frame)) => decode_member(frame, &self.policy).map(Some),
579            Ok(None) => Ok(None),
580            Err(error) => Err(error.into()),
581        };
582        self.fused = !matches!(result, Ok(Some(_)));
583        result
584    }
585}
586
587fn decode_member<'a, R>(
588    frame: MemberFrame<'a, R>,
589    policy: &DecodePolicy,
590) -> Result<Member<TarMemberPayload<'a, R>>, DecodeError> {
591    policy.check_member(&frame)?;
592    let position = frame.header.position;
593    let kind = frame.header.kind;
594    let size = frame.header.effective_size;
595    let executable = frame.header.mode.unwrap_or_default() & 0o111 != 0;
596    let path = std::str::from_utf8(frame.effective_path()?.as_ref())
597        .map(str::to_owned)
598        .map_err(|_| DecodeError::InvalidUtf8 {
599            position,
600            field: "path",
601        })?;
602    let target = if matches!(kind, UstarKind::HardLink | UstarKind::SymbolicLink) {
603        std::str::from_utf8(frame.effective_link_path()?.as_ref())
604            .map(str::to_owned)
605            .map_err(|_| DecodeError::InvalidUtf8 {
606                position,
607                field: "linkpath",
608            })?
609    } else {
610        String::new()
611    };
612    let metadata = MemberMetadata { path, position };
613
614    Ok(match kind {
615        UstarKind::Regular | UstarKind::Contiguous => Member::File {
616            metadata,
617            size,
618            executable,
619            payload: TarMemberPayload {
620                payload: frame.payload,
621            },
622        },
623        UstarKind::Directory => Member::Directory { metadata },
624        UstarKind::SymbolicLink => Member::SymbolicLink { metadata, target },
625        UstarKind::HardLink => Member::HardLink {
626            metadata,
627            target,
628            size,
629            payload: TarMemberPayload {
630                payload: frame.payload,
631            },
632        },
633        UstarKind::CharacterDevice => Member::Special {
634            metadata,
635            kind: SpecialKind::CharacterDevice,
636        },
637        UstarKind::BlockDevice => Member::Special {
638            metadata,
639            kind: SpecialKind::BlockDevice,
640        },
641        UstarKind::Fifo => Member::Special {
642            metadata,
643            kind: SpecialKind::Fifo,
644        },
645    })
646}