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