Skip to main content

tar_framing/
pax.rs

1//! PAX record parsing, active-global updates, and per-member extension state.
2
3use std::{
4    collections::{HashMap, hash_map::Entry},
5    fmt,
6    str::FromStr,
7    sync::Arc,
8};
9
10use super::PaxKind;
11
12const UTF8_HDRCHARSET: &str = "ISO-IR 10646 2000 UTF-8";
13const BINARY_HDRCHARSET: &str = "BINARY";
14
15/// An error encountered while parsing pax extended-header records.
16#[derive(Debug, thiserror::Error)]
17pub enum PaxError {
18    /// A pax payload did not consist of valid extended-header records.
19    #[error("invalid pax records: {reason}")]
20    InvalidRecords {
21        /// A concise description of the grammar violation.
22        reason: &'static str,
23    },
24    /// A pax text component that must be UTF-8 is not valid UTF-8.
25    #[error("pax records contain invalid UTF-8 text")]
26    InvalidUtf8,
27    /// A pax record keyword is neither standard nor an accepted namespaced extension.
28    #[error("invalid or unknown pax keyword {keyword:?}")]
29    InvalidKeyword {
30        /// The rejected keyword.
31        keyword: String,
32    },
33    /// A pax decimal integer field is malformed or exceeds this API's integer range.
34    #[error("invalid pax {keyword} value: {value:?}")]
35    InvalidInteger {
36        /// The affected standard keyword.
37        keyword: &'static str,
38        /// The rejected textual value.
39        value: String,
40    },
41    /// A pax file-time value is malformed or exceeds this API's integer range.
42    #[error("invalid pax {keyword} time value: {value:?}")]
43    InvalidTime {
44        /// The affected standard keyword.
45        keyword: &'static str,
46        /// The rejected textual value.
47        value: String,
48    },
49    /// A pax `hdrcharset` record requests text encoding unsupported by this API.
50    #[error("unsupported pax hdrcharset value {value:?}")]
51    UnsupportedCharset {
52        /// The unsupported character-set identifier.
53        value: String,
54    },
55    /// A pax record length or offset overflowed.
56    #[error("arithmetic overflow while computing {context}")]
57    ArithmeticOverflow {
58        /// The computation that overflowed.
59        context: &'static str,
60    },
61}
62
63pub(crate) type SharedPaxRecords = Arc<PaxRecords>;
64
65#[derive(Clone, Debug, Default, Eq, PartialEq)]
66pub(crate) struct PaxRecords(Vec<PaxRecord>);
67
68/// An owned, hashable pax extended-header keyword.
69#[derive(Clone, Debug, Eq, Hash, PartialEq)]
70pub enum PaxKeyword {
71    /// File access time.
72    Atime,
73    /// Encoding of the following member's file data.
74    Charset,
75    /// Uninterpreted archive comment.
76    Comment,
77    /// File status-change time compatibility extension.
78    Ctime,
79    /// Numeric group identifier.
80    Gid,
81    /// Group name.
82    Gname,
83    /// Encoding of pathname and user/group-name values.
84    HdrCharset,
85    /// Link pathname.
86    LinkPath,
87    /// File modification time.
88    Mtime,
89    /// Member pathname.
90    Path,
91    /// Reserved `realtime.*` attribute.
92    Realtime(Arc<str>),
93    /// Reserved `security.*` attribute.
94    Security(Arc<str>),
95    /// Member payload size.
96    Size,
97    /// Numeric user identifier.
98    Uid,
99    /// User name.
100    Uname,
101    /// An implementation extension in a `vendor.keyword` namespace.
102    Vendor {
103        /// Vendor or organization identifier.
104        vendor: Arc<str>,
105        /// Keyword suffix after the vendor namespace.
106        name: Arc<str>,
107    },
108}
109
110impl PaxKeyword {
111    pub(crate) fn components(&self) -> (&str, Option<&str>) {
112        match self {
113            Self::Atime => ("atime", None),
114            Self::Charset => ("charset", None),
115            Self::Comment => ("comment", None),
116            Self::Ctime => ("ctime", None),
117            Self::Gid => ("gid", None),
118            Self::Gname => ("gname", None),
119            Self::HdrCharset => ("hdrcharset", None),
120            Self::LinkPath => ("linkpath", None),
121            Self::Mtime => ("mtime", None),
122            Self::Path => ("path", None),
123            Self::Realtime(name) => ("realtime", Some(name)),
124            Self::Security(name) => ("security", Some(name)),
125            Self::Size => ("size", None),
126            Self::Uid => ("uid", None),
127            Self::Uname => ("uname", None),
128            Self::Vendor { vendor, name } => (vendor, Some(name)),
129        }
130    }
131}
132
133impl fmt::Display for PaxKeyword {
134    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
135        let (namespace, name) = self.components();
136        formatter.write_str(namespace)?;
137        if let Some(name) = name {
138            formatter.write_str(".")?;
139            formatter.write_str(name)?;
140        }
141        Ok(())
142    }
143}
144
145/// Like [`PaxRecords`], but with an additional index of `keyword -> effective record index`
146/// to keep lookups cheap, even across pathological pax archives (e.g. multiple
147/// global extensions being merged together).
148#[derive(Debug, Default, Eq, PartialEq)]
149pub(crate) struct GlobalPaxRecords {
150    records: PaxRecords,
151    indices: HashMap<PaxKeyword, usize>,
152}
153
154impl GlobalPaxRecords {
155    pub(super) fn apply(&mut self, updates: &PaxRecords) {
156        for update in updates.as_slice() {
157            match self.indices.entry(update.keyword()) {
158                Entry::Occupied(entry) => self.records.0[*entry.get()] = update.clone(),
159                Entry::Vacant(entry) => {
160                    let index = self.records.0.len();
161                    self.records.0.push(update.clone());
162                    entry.insert(index);
163                }
164            }
165        }
166    }
167
168    fn get(&self, keyword: &PaxKeyword) -> Option<&PaxRecord> {
169        self.indices
170            .get(keyword)
171            .and_then(|index| self.records.as_slice().get(*index))
172    }
173
174    pub(super) fn hdrcharset(&self) -> HdrCharset {
175        self.get(&PaxKeyword::HdrCharset)
176            .and_then(|record| match record {
177                PaxRecord::HdrCharset(value) => Some(value),
178                _ => None,
179            })
180            .map_or(HdrCharset::Utf8, |value| match value {
181                PaxValue::Value(value) => *value,
182                PaxValue::Deleted => HdrCharset::Utf8,
183            })
184    }
185}
186
187/// One positioned parsed pax extended header.
188#[derive(Clone, Debug, Eq, PartialEq)]
189pub struct PaxExtension {
190    /// The absolute byte position of the pax extension header block.
191    pub position: u64,
192    /// Whether this extension has local or global scope.
193    pub kind: PaxKind,
194    pub(super) records: SharedPaxRecords,
195}
196
197impl PaxExtension {
198    /// Returns the parsed pax records in archive order.
199    pub fn records(&self) -> &[PaxRecord] {
200        self.records.as_slice()
201    }
202}
203
204/// Unified pax extension state applicable to one ordinary member.
205///
206/// Effective values apply local records over the active global state using
207/// standard last-record-wins and deletion semantics. [`Self::extensions`]
208/// retains the positioned extension headers newly encountered for this member.
209/// The effective global state is borrowed from the originating logical reader,
210/// so retaining this view also prevents that reader from advancing to another
211/// member whose global state could differ.
212#[derive(Clone, Debug, Eq, PartialEq)]
213pub struct PaxState<'global> {
214    global_records: &'global GlobalPaxRecords,
215    global_extensions: Vec<PaxExtension>,
216    local_extension: Option<PaxExtension>,
217}
218
219impl<'global> PaxState<'global> {
220    pub(crate) fn new(
221        global_records: &'global GlobalPaxRecords,
222        global_extensions: Vec<PaxExtension>,
223        local_extension: Option<PaxExtension>,
224    ) -> Self {
225        Self {
226            global_records,
227            global_extensions,
228            local_extension,
229        }
230    }
231
232    /// Returns positioned extensions newly encountered for this member.
233    ///
234    /// Global extensions are yielded in source order, followed by the optional
235    /// local extension.
236    pub fn extensions(&self) -> impl Iterator<Item = &PaxExtension> {
237        self.global_extensions
238            .iter()
239            .chain(self.local_extension.iter())
240    }
241
242    /// Returns the final applicable record for `keyword`, including deletions.
243    pub fn effective_record(&self, keyword: &PaxKeyword) -> Option<&PaxRecord> {
244        let local_records = self
245            .local_extension
246            .as_ref()
247            .map(|extension| extension.records.as_ref());
248        Self::effective_record_from(local_records, self.global_records, keyword)
249    }
250
251    /// Returns the effective pax `path` value, including an explicit deletion.
252    pub fn path(&self) -> Option<&PaxValue<PaxString>> {
253        match self.effective_record(&PaxKeyword::Path)? {
254            PaxRecord::Path(value) => Some(value),
255            _ => None,
256        }
257    }
258
259    /// Returns the effective pax `linkpath` value, including an explicit deletion.
260    pub fn link_path(&self) -> Option<&PaxValue<PaxString>> {
261        match self.effective_record(&PaxKeyword::LinkPath)? {
262            PaxRecord::LinkPath(value) => Some(value),
263            _ => None,
264        }
265    }
266
267    pub(super) fn effective_size<'records>(
268        local_records: Option<&'records PaxRecords>,
269        global_records: &'records GlobalPaxRecords,
270    ) -> Option<&'records PaxValue<u64>> {
271        Self::effective_record_from(local_records, global_records, &PaxKeyword::Size).and_then(
272            |record| match record {
273                PaxRecord::Size(value) => Some(value),
274                _ => None,
275            },
276        )
277    }
278
279    pub(super) fn effective_record_from<'records>(
280        local_records: Option<&'records PaxRecords>,
281        global_records: &'records GlobalPaxRecords,
282        keyword: &PaxKeyword,
283    ) -> Option<&'records PaxRecord> {
284        local_records
285            .and_then(|records| records.get(keyword))
286            .or_else(|| global_records.get(keyword))
287    }
288}
289
290/// A character encoding for PAX pathname and user/group-name values.
291#[derive(Clone, Copy, Debug, Eq, PartialEq)]
292pub enum HdrCharset {
293    /// UTF-8 extended-header text.
294    Utf8,
295    /// Unencoded bytes copied from the originating system.
296    Binary,
297}
298
299impl FromStr for HdrCharset {
300    type Err = String;
301
302    fn from_str(value: &str) -> Result<Self, Self::Err> {
303        match value {
304            UTF8_HDRCHARSET => Ok(Self::Utf8),
305            BINARY_HDRCHARSET => Ok(Self::Binary),
306            _ => Err(value.to_owned()),
307        }
308    }
309}
310
311/// A character value governed by the effective PAX [`HdrCharset`].
312#[derive(Clone, Debug, Eq, PartialEq)]
313pub enum PaxString {
314    /// A value declared or defaulted to UTF-8.
315    Utf8(Arc<str>),
316    /// A value declared as unencoded binary bytes.
317    Binary(Arc<[u8]>),
318}
319
320impl PaxString {
321    /// Returns the original bytes in either encoding.
322    pub fn as_bytes(&self) -> &[u8] {
323        match self {
324            Self::Utf8(value) => value.as_bytes(),
325            Self::Binary(value) => value,
326        }
327    }
328}
329
330/// A parsed pax value, including an explicit deletion tombstone.
331///
332/// Deletion tombstones are needed because pax has special semantics for
333/// empty (i.e. deleted) pax records: they're considered to delete
334/// "any header block field, previously entered extended header value, or global
335/// extended header value of the same name." (pax specification, "pax Extended Header")
336///
337/// This is a distinct state from "missing," which allows for fallbacks to
338/// e.g. global pax headers or the equivalent ustar field.
339#[derive(Clone, Debug, Eq, PartialEq)]
340pub enum PaxValue<T> {
341    /// This record sets or overrides the attribute.
342    Value(T),
343    /// This record deletes the attribute from its applicable scope.
344    Deleted,
345}
346
347impl<T: FromStr> FromStr for PaxValue<T> {
348    type Err = T::Err;
349
350    fn from_str(value: &str) -> Result<Self, Self::Err> {
351        if value.is_empty() {
352            Ok(Self::Deleted)
353        } else {
354            value.parse().map(Self::Value)
355        }
356    }
357}
358
359impl<T> PaxValue<T> {
360    fn parse_utf8(value: &[u8]) -> Result<&str, PaxError> {
361        std::str::from_utf8(value).map_err(|_| PaxError::InvalidUtf8)
362    }
363}
364
365/// A parsed pax extended-header record.
366#[derive(Clone, Debug, Eq, PartialEq)]
367pub enum PaxRecord {
368    /// File access time in integral seconds; fractional seconds are discarded.
369    Atime(PaxValue<u64>),
370    /// Encoding of the following member's file data.
371    // TODO: Consider enforcing known values here, similarly to what we do for `hdrcharset`.
372    Charset(PaxValue<Arc<str>>),
373    /// An uninterpreted archive comment.
374    Comment(PaxValue<Arc<str>>),
375    /// File status-change time compatibility extension in integral seconds.
376    ///
377    /// NOTE: newer versions of the pax spec don't include this record.
378    /// We support it for backwards compatibility.
379    ///
380    /// See: <https://www.opengroup.org/austin/aardvark/finaltext/xcubug.txt>
381    /// See: <https://www.opengroup.org/austin/docs/austin_166.txt>
382    /// See: <https://www.opengroup.org/austin/docs/austin_206.txt>
383    Ctime(PaxValue<u64>),
384    /// Numeric group identifier.
385    Gid(PaxValue<u64>),
386    /// Group name encoded according to the effective [`HdrCharset`].
387    Gname(PaxValue<PaxString>),
388    /// Encoding of pathname and user/group-name extended-header values.
389    HdrCharset(PaxValue<HdrCharset>),
390    /// Link pathname encoded according to the effective [`HdrCharset`].
391    LinkPath(PaxValue<PaxString>),
392    /// File modification time in integral seconds; fractional seconds are discarded.
393    Mtime(PaxValue<u64>),
394    /// Member pathname encoded according to the effective [`HdrCharset`].
395    Path(PaxValue<PaxString>),
396    /// A reserved `realtime.*` extended attribute.
397    Realtime {
398        /// Keyword suffix after `realtime.`.
399        name: Arc<str>,
400        /// Attribute value or deletion tombstone.
401        value: PaxValue<Arc<str>>,
402    },
403    /// A reserved `security.*` extended attribute.
404    Security {
405        /// Keyword suffix after `security.`.
406        name: Arc<str>,
407        /// Attribute value or deletion tombstone.
408        value: PaxValue<Arc<str>>,
409    },
410    /// Member payload size in octets.
411    Size(PaxValue<u64>),
412    /// Numeric user identifier.
413    Uid(PaxValue<u64>),
414    /// User name encoded according to the effective [`HdrCharset`].
415    Uname(PaxValue<PaxString>),
416    /// An implementation extension in a `vendor.keyword` namespace.
417    Vendor {
418        /// Vendor or organization identifier.
419        vendor: Arc<str>,
420        /// Keyword suffix after the vendor namespace.
421        name: Arc<str>,
422        /// Opaque attribute bytes or deletion tombstone.
423        value: PaxValue<Arc<[u8]>>,
424    },
425}
426
427impl PaxRecord {
428    /// Returns this record's typed pax keyword.
429    pub fn keyword(&self) -> PaxKeyword {
430        match self {
431            Self::Atime(_) => PaxKeyword::Atime,
432            Self::Charset(_) => PaxKeyword::Charset,
433            Self::Comment(_) => PaxKeyword::Comment,
434            Self::Ctime(_) => PaxKeyword::Ctime,
435            Self::Gid(_) => PaxKeyword::Gid,
436            Self::Gname(_) => PaxKeyword::Gname,
437            Self::HdrCharset(_) => PaxKeyword::HdrCharset,
438            Self::LinkPath(_) => PaxKeyword::LinkPath,
439            Self::Mtime(_) => PaxKeyword::Mtime,
440            Self::Path(_) => PaxKeyword::Path,
441            Self::Realtime { name, .. } => PaxKeyword::Realtime(Arc::clone(name)),
442            Self::Security { name, .. } => PaxKeyword::Security(Arc::clone(name)),
443            Self::Size(_) => PaxKeyword::Size,
444            Self::Uid(_) => PaxKeyword::Uid,
445            Self::Uname(_) => PaxKeyword::Uname,
446            Self::Vendor { vendor, name, .. } => PaxKeyword::Vendor {
447                vendor: Arc::clone(vendor),
448                name: Arc::clone(name),
449            },
450        }
451    }
452
453    fn parse(keyword: &str, value: &[u8], hdrcharset: HdrCharset) -> Result<Self, PaxError> {
454        match keyword {
455            "atime" => PaxValue::parse_time("atime", value).map(Self::Atime),
456            "charset" => PaxValue::parse_text(value).map(Self::Charset),
457            "comment" => PaxValue::parse_text(value).map(Self::Comment),
458            "ctime" => PaxValue::parse_time("ctime", value).map(Self::Ctime),
459            "gid" => PaxValue::parse_integer("gid", value).map(Self::Gid),
460            "gname" => PaxValue::parse_string(value, hdrcharset).map(Self::Gname),
461            "hdrcharset" => PaxValue::parse_hdrcharset(value).map(Self::HdrCharset),
462            "linkpath" => PaxValue::parse_string(value, hdrcharset).map(Self::LinkPath),
463            "mtime" => PaxValue::parse_time("mtime", value).map(Self::Mtime),
464            "path" => PaxValue::parse_string(value, hdrcharset).map(Self::Path),
465            "size" => PaxValue::parse_integer("size", value).map(Self::Size),
466            "uid" => PaxValue::parse_integer("uid", value).map(Self::Uid),
467            "uname" => PaxValue::parse_string(value, hdrcharset).map(Self::Uname),
468            _ => Self::parse_namespaced(keyword, value),
469        }
470    }
471
472    fn parse_namespaced(keyword: &str, value: &[u8]) -> Result<Self, PaxError> {
473        let invalid = || PaxError::InvalidKeyword {
474            keyword: keyword.to_owned(),
475        };
476        let (namespace, name) = match keyword.split_once('.') {
477            Some((namespace, name)) if !name.is_empty() => (namespace, name),
478            _ => return Err(invalid()),
479        };
480        match namespace {
481            "realtime" => Ok(Self::Realtime {
482                name: Arc::from(name),
483                value: PaxValue::parse_text(value)?,
484            }),
485            "security" => Ok(Self::Security {
486                name: Arc::from(name),
487                value: PaxValue::parse_text(value)?,
488            }),
489            vendor if !vendor.is_empty() => Ok(Self::Vendor {
490                vendor: Arc::from(vendor),
491                name: Arc::from(name),
492                value: PaxValue::parse_opaque(value),
493            }),
494            _ => Err(invalid()),
495        }
496    }
497}
498
499impl PaxRecords {
500    pub(crate) fn as_slice(&self) -> &[PaxRecord] {
501        &self.0
502    }
503
504    pub(super) fn parse(
505        payload: &[u8],
506        inherited_hdrcharset: HdrCharset,
507    ) -> Result<Self, PaxError> {
508        if payload.is_empty() {
509            return Err(PaxError::InvalidRecords {
510                reason: "local extended header payload contains no records",
511            });
512        }
513
514        let mut records = Vec::new();
515        let mut cursor = 0;
516        while cursor < payload.len() {
517            let length_end = payload[cursor..]
518                .iter()
519                .position(|byte| *byte == b' ')
520                .ok_or(PaxError::InvalidRecords {
521                    reason: "record is missing its length separator",
522                })?
523                + cursor;
524            if length_end == cursor {
525                return Err(PaxError::InvalidRecords {
526                    reason: "record length is empty",
527                });
528            }
529            let record_len = std::str::from_utf8(&payload[cursor..length_end])
530                .ok()
531                .and_then(decimal_u64)
532                .ok_or(PaxError::InvalidRecords {
533                    reason: "record length is not a valid decimal integer",
534                })?;
535            let record_len =
536                usize::try_from(record_len).map_err(|_| PaxError::ArithmeticOverflow {
537                    context: "pax record length",
538                })?;
539            let record_end =
540                cursor
541                    .checked_add(record_len)
542                    .ok_or(PaxError::ArithmeticOverflow {
543                        context: "pax record end",
544                    })?;
545            if record_end > payload.len() {
546                return Err(PaxError::InvalidRecords {
547                    reason: "record length exceeds extended header payload",
548                });
549            }
550            let record = &payload[cursor..record_end];
551            if record.last() != Some(&b'\n') {
552                return Err(PaxError::InvalidRecords {
553                    reason: "record is not newline terminated",
554                });
555            }
556            let content_start = length_end - cursor + 1;
557            let equals = record[content_start..record.len() - 1]
558                .iter()
559                .position(|byte| *byte == b'=')
560                .ok_or(PaxError::InvalidRecords {
561                    reason: "record is missing its keyword/value separator",
562                })?
563                + content_start;
564            if equals == content_start {
565                return Err(PaxError::InvalidRecords {
566                    reason: "record keyword is empty",
567                });
568            }
569            let keyword = std::str::from_utf8(&record[content_start..equals])
570                .map_err(|_| PaxError::InvalidUtf8)?;
571            records.push((keyword, &record[equals + 1..record.len() - 1]));
572            cursor = record_end;
573        }
574
575        // Per pax spec: the `gname`, `linkpath`, `path`, and `uname` records
576        // are encoded according to `hdrcharset`, so we need to first parse
577        // it (or take it from a parent global pax header) before we can parse
578        // the other pax records, regardless of order.
579        //
580        // See: pax spec, "pax Extended Header"
581        let hdrcharset = Self::resolve_hdrcharset(&records, inherited_hdrcharset)?;
582        records
583            .into_iter()
584            .map(|(keyword, value)| PaxRecord::parse(keyword, value, hdrcharset))
585            .collect::<Result<Vec<_>, _>>()
586            .map(Self)
587    }
588
589    fn resolve_hdrcharset(
590        records: &[(&str, &[u8])],
591        inherited: HdrCharset,
592    ) -> Result<HdrCharset, PaxError> {
593        let mut hdrcharset = inherited;
594        // TODO: Consider finding the last `hdrcharset` with a reverse search to avoid parsing
595        // shadowed values here. All records would still be validated during typed parsing.
596        for (keyword, value) in records {
597            if *keyword == "hdrcharset" {
598                hdrcharset = match PaxValue::parse_hdrcharset(value)? {
599                    PaxValue::Value(value) => value,
600                    PaxValue::Deleted => HdrCharset::Utf8,
601                };
602            }
603        }
604        Ok(hdrcharset)
605    }
606
607    fn get(&self, keyword: &PaxKeyword) -> Option<&PaxRecord> {
608        self.0
609            .iter()
610            .rev()
611            .find(|record| record.keyword() == *keyword)
612    }
613}
614
615impl PaxValue<Arc<str>> {
616    fn parse_text(value: &[u8]) -> Result<Self, PaxError> {
617        Self::parse_utf8(value).map(|value| match value {
618            "" => Self::Deleted,
619            value => Self::Value(Arc::from(value)),
620        })
621    }
622}
623
624impl PaxValue<Arc<[u8]>> {
625    fn parse_opaque(value: &[u8]) -> Self {
626        if value.is_empty() {
627            Self::Deleted
628        } else {
629            Self::Value(Arc::from(value))
630        }
631    }
632}
633
634impl PaxValue<PaxString> {
635    /// Parses a pax "string", taking the effective [`HdrCharset`] into account.
636    fn parse_string(value: &[u8], hdrcharset: HdrCharset) -> Result<Self, PaxError> {
637        if value.is_empty() {
638            return Ok(Self::Deleted);
639        }
640        match hdrcharset {
641            HdrCharset::Utf8 => Self::parse_utf8(value)
642                .map(Arc::from)
643                .map(PaxString::Utf8)
644                .map(Self::Value),
645            HdrCharset::Binary => Ok(Self::Value(PaxString::Binary(Arc::from(value)))),
646        }
647    }
648}
649
650impl PaxValue<HdrCharset> {
651    fn parse_hdrcharset(value: &[u8]) -> Result<Self, PaxError> {
652        let value = Self::parse_utf8(value)?;
653        value
654            .parse()
655            .map_err(|value| PaxError::UnsupportedCharset { value })
656    }
657}
658
659impl PaxValue<u64> {
660    fn parse_integer(keyword: &'static str, value: &[u8]) -> Result<Self, PaxError> {
661        let value = Self::parse_utf8(value)?;
662        if value.is_empty() {
663            return Ok(Self::Deleted);
664        }
665
666        let invalid = || PaxError::InvalidInteger {
667            keyword,
668            value: value.to_owned(),
669        };
670        // pax integers are decimal, but some readers interpret a leading zero as octal.
671        // For `size`, that can change which block they read as the next member header.
672        if keyword == "size" && matches!(value.as_bytes(), [b'0', _, ..]) {
673            return Err(invalid());
674        }
675        decimal_u64(value).map(Self::Value).ok_or_else(invalid)
676    }
677
678    fn parse_time(keyword: &'static str, value: &[u8]) -> Result<Self, PaxError> {
679        let value = Self::parse_utf8(value)?;
680        if value.is_empty() {
681            return Ok(Self::Deleted);
682        }
683
684        let invalid = || PaxError::InvalidTime {
685            keyword,
686            value: value.to_owned(),
687        };
688        let seconds = match value.split_once('.') {
689            Some((seconds, fractional_digits))
690                if !fractional_digits.is_empty()
691                    && fractional_digits.bytes().all(|byte| byte.is_ascii_digit()) =>
692            {
693                seconds
694            }
695            Some(_) => return Err(invalid()),
696            None => value,
697        };
698        decimal_u64(seconds).map(Self::Value).ok_or_else(invalid)
699    }
700}
701
702fn decimal_u64(value: &str) -> Option<u64> {
703    if value.starts_with('+') {
704        return None;
705    }
706    value.parse().ok()
707}
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use crate::test_support::{raw_record, record};
713
714    fn text(value: &str) -> Arc<str> {
715        Arc::from(value)
716    }
717
718    fn comment(value: &str) -> PaxRecord {
719        PaxRecord::Comment(PaxValue::Value(text(value)))
720    }
721
722    fn utf8(value: &str) -> PaxString {
723        PaxString::Utf8(text(value))
724    }
725
726    fn binary(value: &[u8]) -> PaxString {
727        PaxString::Binary(Arc::from(value))
728    }
729
730    fn opaque(value: &[u8]) -> Arc<[u8]> {
731        Arc::from(value)
732    }
733
734    fn vendor(name: &str, value: &str) -> PaxRecord {
735        PaxRecord::Vendor {
736            vendor: text("Acme"),
737            name: text(name),
738            value: PaxValue::Value(opaque(value.as_bytes())),
739        }
740    }
741
742    fn security(value: &str) -> PaxRecord {
743        PaxRecord::Security {
744            name: text("label"),
745            value: PaxValue::Value(text(value)),
746        }
747    }
748
749    fn global_state(records: Vec<PaxRecord>) -> GlobalPaxRecords {
750        let mut active = GlobalPaxRecords::default();
751        active.apply(&PaxRecords(records));
752        active
753    }
754
755    fn extension(position: u64, kind: PaxKind, records: Vec<PaxRecord>) -> PaxExtension {
756        PaxExtension {
757            position,
758            kind,
759            records: Arc::new(PaxRecords(records)),
760        }
761    }
762
763    #[test]
764    fn resolves_state_precedence_and_preserves_extension_order() {
765        struct Case {
766            name: &'static str,
767            global: Vec<PaxRecord>,
768            local: Option<Vec<PaxRecord>>,
769            expected: Option<PaxRecord>,
770        }
771
772        for case in [
773            Case {
774                name: "missing",
775                global: Vec::new(),
776                local: None,
777                expected: None,
778            },
779            Case {
780                name: "global",
781                global: vec![comment("global")],
782                local: None,
783                expected: Some(comment("global")),
784            },
785            Case {
786                name: "local overrides global",
787                global: vec![comment("global")],
788                local: Some(vec![comment("local")]),
789                expected: Some(comment("local")),
790            },
791            Case {
792                name: "last local duplicate wins",
793                global: Vec::new(),
794                local: Some(vec![comment("first"), comment("last")]),
795                expected: Some(comment("last")),
796            },
797            Case {
798                name: "local deletion suppresses global",
799                global: vec![comment("global")],
800                local: Some(vec![PaxRecord::Comment(PaxValue::Deleted)]),
801                expected: Some(PaxRecord::Comment(PaxValue::Deleted)),
802            },
803        ] {
804            let global = global_state(case.global);
805            let state = PaxState::new(
806                &global,
807                Vec::new(),
808                case.local
809                    .map(|records| extension(0, PaxKind::Local, records)),
810            );
811            assert_eq!(
812                state.effective_record(&PaxKeyword::Comment),
813                case.expected.as_ref(),
814                "{}",
815                case.name
816            );
817        }
818
819        let global = GlobalPaxRecords::default();
820        let state = PaxState::new(
821            &global,
822            vec![
823                extension(3, PaxKind::Global, vec![vendor("first", "value")]),
824                extension(7, PaxKind::Global, vec![vendor("second", "value")]),
825            ],
826            Some(extension(
827                11,
828                PaxKind::Local,
829                vec![vendor("local", "value")],
830            )),
831        );
832        assert_eq!(
833            state
834                .extensions()
835                .map(|extension| (extension.position, extension.kind))
836                .collect::<Vec<_>>(),
837            [
838                (3, PaxKind::Global),
839                (7, PaxKind::Global),
840                (11, PaxKind::Local),
841            ]
842        );
843    }
844
845    #[test]
846    fn global_deletions_remain_effective_tombstones() {
847        let mut active = global_state(vec![
848            PaxRecord::Path(PaxValue::Value(utf8("global"))),
849            vendor("kept", "value"),
850        ]);
851        active.apply(&PaxRecords(vec![PaxRecord::Path(PaxValue::Deleted)]));
852
853        assert_eq!(active.records.as_slice().len(), 2);
854        let state = PaxState::new(&active, Vec::new(), None);
855        assert_eq!(
856            state.effective_record(&PaxKeyword::Path),
857            Some(&PaxRecord::Path(PaxValue::Deleted))
858        );
859    }
860
861    #[test]
862    fn parses_values_and_deletions_through_from_str() {
863        assert!(matches!(
864            "".parse::<PaxValue<String>>(),
865            Ok(PaxValue::Deleted)
866        ));
867        assert!(matches!(
868            "value".parse::<PaxValue<String>>(),
869            Ok(PaxValue::Value(value)) if value == "value"
870        ));
871        assert!(matches!(
872            "12".parse::<PaxValue<u64>>(),
873            Ok(PaxValue::Value(12))
874        ));
875    }
876
877    #[test]
878    fn parses_strict_numeric_and_timestamp_values() {
879        assert!(matches!(
880            PaxValue::parse_integer("uid", b"12"),
881            Ok(PaxValue::Value(12))
882        ));
883        assert!(matches!(
884            PaxValue::parse_integer("uid", b""),
885            Ok(PaxValue::Deleted)
886        ));
887        assert!(matches!(
888            PaxValue::parse_time("mtime", b"12.034"),
889            Ok(PaxValue::Value(12))
890        ));
891        assert!(matches!(
892            PaxValue::parse_time("mtime", b""),
893            Ok(PaxValue::Deleted)
894        ));
895
896        for value in ["+1", "-1", "12x", "18446744073709551616"] {
897            assert!(matches!(
898                PaxValue::parse_integer("gid", value.as_bytes()),
899                Err(PaxError::InvalidInteger { .. })
900            ));
901        }
902        for value in ["+1", "-1", "1.", "1.nanosecond", "18446744073709551616"] {
903            assert!(matches!(
904                PaxValue::parse_time("atime", value.as_bytes()),
905                Err(PaxError::InvalidTime { .. })
906            ));
907        }
908    }
909
910    #[test]
911    fn parses_typed_standard_reserved_and_vendor_records() {
912        let fields = [
913            ("atime", "12.034"),
914            ("charset", "BINARY"),
915            ("comment", "a=b"),
916            ("ctime", "17.500"),
917            ("gid", "07"),
918            ("gname", "group"),
919            ("hdrcharset", UTF8_HDRCHARSET),
920            ("linkpath", "target"),
921            ("mtime", "42"),
922            ("path", "file"),
923            ("realtime.deadline", "soon"),
924            ("security.label", "secure"),
925            ("size", "0"),
926            ("uid", "08"),
927            ("uname", "user"),
928            ("Acme.attribute", "custom"),
929        ];
930        let mut payload = Vec::new();
931        for (keyword, value) in fields {
932            payload.extend_from_slice(&record(keyword, value));
933        }
934
935        let Ok(records) = PaxRecords::parse(&payload, HdrCharset::Utf8) else {
936            panic!("records should parse");
937        };
938        assert_eq!(
939            records.as_slice(),
940            [
941                PaxRecord::Atime(PaxValue::Value(12)),
942                PaxRecord::Charset(PaxValue::Value(text("BINARY"))),
943                comment("a=b"),
944                PaxRecord::Ctime(PaxValue::Value(17)),
945                PaxRecord::Gid(PaxValue::Value(7)),
946                PaxRecord::Gname(PaxValue::Value(utf8("group"))),
947                PaxRecord::HdrCharset(PaxValue::Value(HdrCharset::Utf8)),
948                PaxRecord::LinkPath(PaxValue::Value(utf8("target"))),
949                PaxRecord::Mtime(PaxValue::Value(42)),
950                PaxRecord::Path(PaxValue::Value(utf8("file"))),
951                PaxRecord::Realtime {
952                    name: text("deadline"),
953                    value: PaxValue::Value(text("soon")),
954                },
955                security("secure"),
956                PaxRecord::Size(PaxValue::Value(0)),
957                PaxRecord::Uid(PaxValue::Value(8)),
958                PaxRecord::Uname(PaxValue::Value(utf8("user"))),
959                vendor("attribute", "custom"),
960            ]
961        );
962        assert!(
963            records
964                .as_slice()
965                .iter()
966                .zip(fields)
967                .all(|(record, (keyword, _))| record.keyword().to_string() == keyword)
968        );
969    }
970
971    #[test]
972    fn parses_deleted_ctime_compatibility_extension() {
973        let Ok(records) = PaxRecords::parse(&record("ctime", ""), HdrCharset::Utf8) else {
974            panic!("ctime deletion should parse");
975        };
976        assert_eq!(records.as_slice(), [PaxRecord::Ctime(PaxValue::Deleted)]);
977    }
978
979    #[test]
980    fn rejects_invalid_records_and_keywords() {
981        for payload in [
982            b"11 path=name".as_slice(),
983            b"12 pathname\n".as_slice(),
984            b"99 path=name\n".as_slice(),
985            b"+12 path=name\n".as_slice(),
986        ] {
987            assert!(matches!(
988                PaxRecords::parse(payload, HdrCharset::Utf8),
989                Err(PaxError::InvalidRecords { .. })
990            ));
991        }
992
993        for keyword in ["unknown", "VENDOR", "VENDOR.", "realtime.", "security."] {
994            assert!(matches!(
995                PaxRecord::parse(keyword, b"value", HdrCharset::Utf8),
996                Err(PaxError::InvalidKeyword { .. })
997            ));
998        }
999    }
1000
1001    #[test]
1002    fn accepts_opaque_vendor_values_but_rejects_invalid_utf8_text() {
1003        let invalid_utf8 = [0xd6, 0xfb, 0x00];
1004        let mut vendor_records = raw_record(b"SCHILY.xattr.user.data", &invalid_utf8);
1005        vendor_records.extend_from_slice(&raw_record(b"SCHILY.xattr.user.deleted", b""));
1006        let expected = PaxRecords(vec![
1007            PaxRecord::Vendor {
1008                vendor: text("SCHILY"),
1009                name: text("xattr.user.data"),
1010                value: PaxValue::Value(opaque(&invalid_utf8)),
1011            },
1012            PaxRecord::Vendor {
1013                vendor: text("SCHILY"),
1014                name: text("xattr.user.deleted"),
1015                value: PaxValue::Deleted,
1016            },
1017        ]);
1018        assert!(matches!(
1019            PaxRecords::parse(&vendor_records, HdrCharset::Utf8),
1020            Ok(records) if records == expected
1021        ));
1022
1023        for keyword in [
1024            b"path".as_slice(),
1025            b"comment",
1026            b"realtime.deadline",
1027            b"security.label",
1028        ] {
1029            assert!(matches!(
1030                PaxRecords::parse(&raw_record(keyword, &invalid_utf8), HdrCharset::Utf8),
1031                Err(PaxError::InvalidUtf8)
1032            ));
1033        }
1034    }
1035
1036    #[test]
1037    fn applies_namespaced_globals_and_accepts_supported_hdrcharset_records() {
1038        let mut active = global_state(vec![
1039            vendor("first", "old"),
1040            vendor("second", "kept"),
1041            security("old"),
1042        ]);
1043        active.apply(&PaxRecords(vec![vendor("first", "new"), security("new")]));
1044        assert_eq!(active.records.as_slice().len(), 3);
1045        assert_eq!(
1046            active.get(&PaxKeyword::Vendor {
1047                vendor: text("Acme"),
1048                name: text("first"),
1049            }),
1050            Some(&vendor("first", "new"))
1051        );
1052        assert_eq!(
1053            active.get(&PaxKeyword::Security(text("label"))),
1054            Some(&security("new"))
1055        );
1056
1057        for (case, payload) in [
1058            (
1059                "supported hdrcharset",
1060                record("hdrcharset", UTF8_HDRCHARSET),
1061            ),
1062            ("deleted hdrcharset", record("hdrcharset", "")),
1063            ("member data charset", record("charset", "BINARY")),
1064        ] {
1065            assert!(
1066                PaxRecords::parse(&payload, HdrCharset::Utf8).is_ok(),
1067                "{case}"
1068            );
1069        }
1070
1071        let mut binary_values = record("hdrcharset", BINARY_HDRCHARSET);
1072        for (keyword, value) in [
1073            (b"gname".as_slice(), [0xfc]),
1074            (b"linkpath".as_slice(), [0xfd]),
1075            (b"path".as_slice(), [0xfe]),
1076            (b"uname".as_slice(), [0xff]),
1077        ] {
1078            binary_values.extend_from_slice(&raw_record(keyword, &value));
1079        }
1080        let Ok(binary_records) = PaxRecords::parse(&binary_values, HdrCharset::Utf8) else {
1081            panic!("binary records should parse");
1082        };
1083        assert_eq!(
1084            binary_records.as_slice(),
1085            [
1086                PaxRecord::HdrCharset(PaxValue::Value(HdrCharset::Binary)),
1087                PaxRecord::Gname(PaxValue::Value(binary(&[0xfc]))),
1088                PaxRecord::LinkPath(PaxValue::Value(binary(&[0xfd]))),
1089                PaxRecord::Path(PaxValue::Value(binary(&[0xfe]))),
1090                PaxRecord::Uname(PaxValue::Value(binary(&[0xff]))),
1091            ]
1092        );
1093        let inherited_binary_path = raw_record(b"path", &[0xfe]);
1094        let Ok(inherited_records) = PaxRecords::parse(&inherited_binary_path, HdrCharset::Binary)
1095        else {
1096            panic!("inherited binary records should parse");
1097        };
1098        assert_eq!(
1099            inherited_records.as_slice(),
1100            [PaxRecord::Path(PaxValue::Value(binary(&[0xfe])))]
1101        );
1102        let mut reset_to_utf8 = record("hdrcharset", "");
1103        reset_to_utf8.extend_from_slice(&raw_record(b"path", &[0xfd]));
1104        assert!(matches!(
1105            PaxRecords::parse(&reset_to_utf8, HdrCharset::Binary),
1106            Err(PaxError::InvalidUtf8)
1107        ));
1108        let mut binary_comment = record("hdrcharset", BINARY_HDRCHARSET);
1109        binary_comment.extend_from_slice(&raw_record(b"comment", &[0xff]));
1110        assert!(matches!(
1111            PaxRecords::parse(&binary_comment, HdrCharset::Utf8),
1112            Err(PaxError::InvalidUtf8)
1113        ));
1114
1115        let unsupported_value = "ISO-IR 8859 1 1998";
1116        let mut overridden_unsupported = record("hdrcharset", unsupported_value);
1117        overridden_unsupported.extend_from_slice(&record("hdrcharset", UTF8_HDRCHARSET));
1118        for unsupported in [
1119            record("hdrcharset", unsupported_value),
1120            overridden_unsupported,
1121        ] {
1122            assert!(matches!(
1123                PaxRecords::parse(&unsupported, HdrCharset::Utf8),
1124                Err(PaxError::UnsupportedCharset { .. })
1125            ));
1126        }
1127    }
1128}