1use 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#[derive(Debug, thiserror::Error)]
17pub enum PaxError {
18 #[error("invalid pax records: {reason}")]
20 InvalidRecords {
21 reason: &'static str,
23 },
24 #[error("pax records contain invalid UTF-8 text")]
26 InvalidUtf8,
27 #[error("invalid or unknown pax keyword {keyword:?}")]
29 InvalidKeyword {
30 keyword: String,
32 },
33 #[error("invalid pax {keyword} value: {value:?}")]
35 InvalidInteger {
36 keyword: &'static str,
38 value: String,
40 },
41 #[error("invalid pax {keyword} time value: {value:?}")]
43 InvalidTime {
44 keyword: &'static str,
46 value: String,
48 },
49 #[error("unsupported pax hdrcharset value {value:?}")]
51 UnsupportedCharset {
52 value: String,
54 },
55 #[error("arithmetic overflow while computing {context}")]
57 ArithmeticOverflow {
58 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#[derive(Clone, Debug, Eq, Hash, PartialEq)]
70pub enum PaxKeyword {
71 Atime,
73 Charset,
75 Comment,
77 Ctime,
79 Gid,
81 Gname,
83 HdrCharset,
85 LinkPath,
87 Mtime,
89 Path,
91 Realtime(Arc<str>),
93 Security(Arc<str>),
95 Size,
97 Uid,
99 Uname,
101 Vendor {
103 vendor: Arc<str>,
105 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#[derive(Debug, Default, Eq, PartialEq)]
149pub(crate) struct GlobalPaxRecords {
150 records: PaxRecords,
151 indices: HashMap<PaxKeyword, usize>,
152}
153
154impl GlobalPaxRecords {
155 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#[derive(Clone, Debug, Eq, PartialEq)]
189pub struct PaxExtension {
190 pub position: u64,
192 pub kind: PaxKind,
194 records: SharedPaxRecords,
195}
196
197impl PaxExtension {
198 pub(crate) fn new(position: u64, kind: PaxKind, records: SharedPaxRecords) -> Self {
199 Self {
200 position,
201 kind,
202 records,
203 }
204 }
205
206 pub fn records(&self) -> &[PaxRecord] {
208 self.records.as_slice()
209 }
210}
211
212#[derive(Clone, Debug, Eq, PartialEq)]
221pub struct PaxState<'global> {
222 global_records: Option<&'global GlobalPaxRecords>,
223 global_extensions: Vec<PaxExtension>,
224 local_extension: Option<PaxExtension>,
225}
226
227impl<'global> PaxState<'global> {
228 pub(crate) fn new(
229 global_records: Option<&'global GlobalPaxRecords>,
230 global_extensions: Vec<PaxExtension>,
231 local_extension: Option<PaxExtension>,
232 ) -> Self {
233 Self {
234 global_records,
235 global_extensions,
236 local_extension,
237 }
238 }
239
240 pub fn extensions(&self) -> impl Iterator<Item = &PaxExtension> {
245 self.global_extensions
246 .iter()
247 .chain(self.local_extension.iter())
248 }
249
250 pub fn effective_record(&self, keyword: &PaxKeyword) -> Option<&PaxRecord> {
252 let local_records = self
253 .local_extension
254 .as_ref()
255 .map(|extension| extension.records.as_ref());
256 Self::effective_record_from(local_records, self.global_records, keyword)
257 }
258
259 pub(super) fn effective_size<'records>(
260 local_records: Option<&'records PaxRecords>,
261 global_records: Option<&'records GlobalPaxRecords>,
262 ) -> Option<&'records PaxValue<u64>> {
263 Self::effective_record_from(local_records, global_records, &PaxKeyword::Size).and_then(
264 |record| match record {
265 PaxRecord::Size(value) => Some(value),
266 _ => None,
267 },
268 )
269 }
270
271 pub(super) fn effective_record_from<'records>(
272 local_records: Option<&'records PaxRecords>,
273 global_records: Option<&'records GlobalPaxRecords>,
274 keyword: &PaxKeyword,
275 ) -> Option<&'records PaxRecord> {
276 local_records
277 .and_then(|records| records.get(keyword))
278 .or_else(|| global_records.and_then(|records| records.get(keyword)))
279 }
280}
281
282#[derive(Clone, Copy, Debug, Eq, PartialEq)]
284pub enum HdrCharset {
285 Utf8,
287 Binary,
289}
290
291impl FromStr for HdrCharset {
292 type Err = String;
293
294 fn from_str(value: &str) -> Result<Self, Self::Err> {
295 match value {
296 UTF8_HDRCHARSET => Ok(Self::Utf8),
297 BINARY_HDRCHARSET => Ok(Self::Binary),
298 _ => Err(value.to_owned()),
299 }
300 }
301}
302
303#[derive(Clone, Debug, Eq, PartialEq)]
305pub enum PaxString {
306 Utf8(Arc<str>),
308 Binary(Arc<[u8]>),
310}
311
312#[derive(Clone, Debug, Eq, PartialEq)]
322pub enum PaxValue<T> {
323 Value(T),
325 Deleted,
327}
328
329impl<T: FromStr> FromStr for PaxValue<T> {
330 type Err = T::Err;
331
332 fn from_str(value: &str) -> Result<Self, Self::Err> {
333 if value.is_empty() {
334 Ok(Self::Deleted)
335 } else {
336 value.parse().map(Self::Value)
337 }
338 }
339}
340
341impl<T> PaxValue<T> {
342 fn parse_utf8(value: &[u8]) -> Result<&str, PaxError> {
343 std::str::from_utf8(value).map_err(|_| PaxError::InvalidUtf8)
344 }
345}
346
347#[derive(Clone, Debug, Eq, PartialEq)]
349pub enum PaxRecord {
350 Atime(PaxValue<u64>),
352 Charset(PaxValue<Arc<str>>),
355 Comment(PaxValue<Arc<str>>),
357 Ctime(PaxValue<u64>),
366 Gid(PaxValue<u64>),
368 Gname(PaxValue<PaxString>),
370 HdrCharset(PaxValue<HdrCharset>),
372 LinkPath(PaxValue<PaxString>),
374 Mtime(PaxValue<u64>),
376 Path(PaxValue<PaxString>),
378 Realtime {
380 name: Arc<str>,
382 value: PaxValue<Arc<str>>,
384 },
385 Security {
387 name: Arc<str>,
389 value: PaxValue<Arc<str>>,
391 },
392 Size(PaxValue<u64>),
394 Uid(PaxValue<u64>),
396 Uname(PaxValue<PaxString>),
398 Vendor {
400 vendor: Arc<str>,
402 name: Arc<str>,
404 value: PaxValue<Arc<[u8]>>,
406 },
407}
408
409impl PaxRecord {
410 pub fn keyword(&self) -> PaxKeyword {
412 match self {
413 Self::Atime(_) => PaxKeyword::Atime,
414 Self::Charset(_) => PaxKeyword::Charset,
415 Self::Comment(_) => PaxKeyword::Comment,
416 Self::Ctime(_) => PaxKeyword::Ctime,
417 Self::Gid(_) => PaxKeyword::Gid,
418 Self::Gname(_) => PaxKeyword::Gname,
419 Self::HdrCharset(_) => PaxKeyword::HdrCharset,
420 Self::LinkPath(_) => PaxKeyword::LinkPath,
421 Self::Mtime(_) => PaxKeyword::Mtime,
422 Self::Path(_) => PaxKeyword::Path,
423 Self::Realtime { name, .. } => PaxKeyword::Realtime(Arc::clone(name)),
424 Self::Security { name, .. } => PaxKeyword::Security(Arc::clone(name)),
425 Self::Size(_) => PaxKeyword::Size,
426 Self::Uid(_) => PaxKeyword::Uid,
427 Self::Uname(_) => PaxKeyword::Uname,
428 Self::Vendor { vendor, name, .. } => PaxKeyword::Vendor {
429 vendor: Arc::clone(vendor),
430 name: Arc::clone(name),
431 },
432 }
433 }
434
435 fn parse(keyword: &str, value: &[u8], hdrcharset: HdrCharset) -> Result<Self, PaxError> {
436 match keyword {
437 "atime" => PaxValue::parse_time("atime", value).map(Self::Atime),
438 "charset" => PaxValue::parse_text(value).map(Self::Charset),
439 "comment" => PaxValue::parse_text(value).map(Self::Comment),
440 "ctime" => PaxValue::parse_time("ctime", value).map(Self::Ctime),
441 "gid" => PaxValue::parse_integer("gid", value).map(Self::Gid),
442 "gname" => PaxValue::parse_string(value, hdrcharset).map(Self::Gname),
443 "hdrcharset" => PaxValue::parse_hdrcharset(value).map(Self::HdrCharset),
444 "linkpath" => PaxValue::parse_string(value, hdrcharset).map(Self::LinkPath),
445 "mtime" => PaxValue::parse_time("mtime", value).map(Self::Mtime),
446 "path" => PaxValue::parse_string(value, hdrcharset).map(Self::Path),
447 "size" => PaxValue::parse_integer("size", value).map(Self::Size),
448 "uid" => PaxValue::parse_integer("uid", value).map(Self::Uid),
449 "uname" => PaxValue::parse_string(value, hdrcharset).map(Self::Uname),
450 _ => Self::parse_namespaced(keyword, value),
451 }
452 }
453
454 fn parse_namespaced(keyword: &str, value: &[u8]) -> Result<Self, PaxError> {
455 let invalid = || PaxError::InvalidKeyword {
456 keyword: keyword.to_owned(),
457 };
458 let (namespace, name) = match keyword.split_once('.') {
459 Some((namespace, name)) if !name.is_empty() => (namespace, name),
460 _ => return Err(invalid()),
461 };
462 match namespace {
463 "realtime" => Ok(Self::Realtime {
464 name: Arc::from(name),
465 value: PaxValue::parse_text(value)?,
466 }),
467 "security" => Ok(Self::Security {
468 name: Arc::from(name),
469 value: PaxValue::parse_text(value)?,
470 }),
471 vendor if !vendor.is_empty() => Ok(Self::Vendor {
472 vendor: Arc::from(vendor),
473 name: Arc::from(name),
474 value: PaxValue::parse_opaque(value),
475 }),
476 _ => Err(invalid()),
477 }
478 }
479}
480
481impl PaxRecords {
482 pub(crate) fn as_slice(&self) -> &[PaxRecord] {
483 &self.0
484 }
485
486 pub(super) fn parse(
487 payload: &[u8],
488 inherited_hdrcharset: HdrCharset,
489 ) -> Result<Self, PaxError> {
490 if payload.is_empty() {
491 return Err(PaxError::InvalidRecords {
492 reason: "local extended header payload contains no records",
493 });
494 }
495
496 let mut records = Vec::new();
497 let mut cursor = 0;
498 while cursor < payload.len() {
499 let length_end = payload[cursor..]
500 .iter()
501 .position(|byte| *byte == b' ')
502 .ok_or(PaxError::InvalidRecords {
503 reason: "record is missing its length separator",
504 })?
505 + cursor;
506 if length_end == cursor {
507 return Err(PaxError::InvalidRecords {
508 reason: "record length is empty",
509 });
510 }
511 let record_len = std::str::from_utf8(&payload[cursor..length_end])
512 .ok()
513 .and_then(decimal_u64)
514 .ok_or(PaxError::InvalidRecords {
515 reason: "record length is not a valid decimal integer",
516 })?;
517 let record_len =
518 usize::try_from(record_len).map_err(|_| PaxError::ArithmeticOverflow {
519 context: "pax record length",
520 })?;
521 let record_end =
522 cursor
523 .checked_add(record_len)
524 .ok_or(PaxError::ArithmeticOverflow {
525 context: "pax record end",
526 })?;
527 if record_end > payload.len() {
528 return Err(PaxError::InvalidRecords {
529 reason: "record length exceeds extended header payload",
530 });
531 }
532 let record = &payload[cursor..record_end];
533 if record.last() != Some(&b'\n') {
534 return Err(PaxError::InvalidRecords {
535 reason: "record is not newline terminated",
536 });
537 }
538 let content_start = length_end - cursor + 1;
539 let equals = record[content_start..record.len() - 1]
540 .iter()
541 .position(|byte| *byte == b'=')
542 .ok_or(PaxError::InvalidRecords {
543 reason: "record is missing its keyword/value separator",
544 })?
545 + content_start;
546 if equals == content_start {
547 return Err(PaxError::InvalidRecords {
548 reason: "record keyword is empty",
549 });
550 }
551 let keyword = std::str::from_utf8(&record[content_start..equals])
552 .map_err(|_| PaxError::InvalidUtf8)?;
553 records.push((keyword, &record[equals + 1..record.len() - 1]));
554 cursor = record_end;
555 }
556
557 let hdrcharset = Self::resolve_hdrcharset(&records, inherited_hdrcharset)?;
564 records
565 .into_iter()
566 .map(|(keyword, value)| PaxRecord::parse(keyword, value, hdrcharset))
567 .collect::<Result<Vec<_>, _>>()
568 .map(Self)
569 }
570
571 fn resolve_hdrcharset(
572 records: &[(&str, &[u8])],
573 inherited: HdrCharset,
574 ) -> Result<HdrCharset, PaxError> {
575 let mut hdrcharset = inherited;
576 for (keyword, value) in records {
579 if *keyword == "hdrcharset" {
580 hdrcharset = match PaxValue::parse_hdrcharset(value)? {
581 PaxValue::Value(value) => value,
582 PaxValue::Deleted => HdrCharset::Utf8,
583 };
584 }
585 }
586 Ok(hdrcharset)
587 }
588
589 fn get(&self, keyword: &PaxKeyword) -> Option<&PaxRecord> {
590 self.0
591 .iter()
592 .rev()
593 .find(|record| record.keyword() == *keyword)
594 }
595
596 pub(super) fn apply_global(&self, active: &mut Option<GlobalPaxRecords>) {
597 active.get_or_insert_default().apply(self);
598 }
599}
600
601impl PaxValue<Arc<str>> {
602 fn parse_text(value: &[u8]) -> Result<Self, PaxError> {
603 Self::parse_utf8(value).map(|value| match value {
604 "" => Self::Deleted,
605 value => Self::Value(Arc::from(value)),
606 })
607 }
608}
609
610impl PaxValue<Arc<[u8]>> {
611 fn parse_opaque(value: &[u8]) -> Self {
612 if value.is_empty() {
613 Self::Deleted
614 } else {
615 Self::Value(Arc::from(value))
616 }
617 }
618}
619
620impl PaxValue<PaxString> {
621 fn parse_string(value: &[u8], hdrcharset: HdrCharset) -> Result<Self, PaxError> {
623 if value.is_empty() {
624 return Ok(Self::Deleted);
625 }
626 match hdrcharset {
627 HdrCharset::Utf8 => Self::parse_utf8(value)
628 .map(Arc::from)
629 .map(PaxString::Utf8)
630 .map(Self::Value),
631 HdrCharset::Binary => Ok(Self::Value(PaxString::Binary(Arc::from(value)))),
632 }
633 }
634}
635
636impl PaxValue<HdrCharset> {
637 fn parse_hdrcharset(value: &[u8]) -> Result<Self, PaxError> {
638 let value = Self::parse_utf8(value)?;
639 value
640 .parse()
641 .map_err(|value| PaxError::UnsupportedCharset { value })
642 }
643}
644
645impl PaxValue<u64> {
646 fn parse_integer(keyword: &'static str, value: &[u8]) -> Result<Self, PaxError> {
647 let value = Self::parse_utf8(value)?;
648 if value.is_empty() {
649 return Ok(Self::Deleted);
650 }
651
652 let invalid = || PaxError::InvalidInteger {
653 keyword,
654 value: value.to_owned(),
655 };
656 if keyword == "size" && matches!(value.as_bytes(), [b'0', _, ..]) {
659 return Err(invalid());
660 }
661 decimal_u64(value).map(Self::Value).ok_or_else(invalid)
662 }
663
664 fn parse_time(keyword: &'static str, value: &[u8]) -> Result<Self, PaxError> {
665 let value = Self::parse_utf8(value)?;
666 if value.is_empty() {
667 return Ok(Self::Deleted);
668 }
669
670 let invalid = || PaxError::InvalidTime {
671 keyword,
672 value: value.to_owned(),
673 };
674 let seconds = match value.split_once('.') {
675 Some((seconds, fractional_digits))
676 if !fractional_digits.is_empty()
677 && fractional_digits.bytes().all(|byte| byte.is_ascii_digit()) =>
678 {
679 seconds
680 }
681 Some(_) => return Err(invalid()),
682 None => value,
683 };
684 decimal_u64(seconds).map(Self::Value).ok_or_else(invalid)
685 }
686}
687
688fn decimal_u64(value: &str) -> Option<u64> {
689 if value.starts_with('+') {
690 return None;
691 }
692 value.parse().ok()
693}
694
695#[cfg(test)]
696mod tests {
697 use std::ptr;
698
699 use super::*;
700 use crate::test_support::{raw_record, record};
701
702 fn text(value: &str) -> Arc<str> {
703 Arc::from(value)
704 }
705
706 fn comment(value: &str) -> PaxRecord {
707 PaxRecord::Comment(PaxValue::Value(text(value)))
708 }
709
710 fn utf8(value: &str) -> PaxString {
711 PaxString::Utf8(text(value))
712 }
713
714 fn binary(value: &[u8]) -> PaxString {
715 PaxString::Binary(Arc::from(value))
716 }
717
718 fn opaque(value: &[u8]) -> Arc<[u8]> {
719 Arc::from(value)
720 }
721
722 fn vendor(name: &str, value: &str) -> PaxRecord {
723 PaxRecord::Vendor {
724 vendor: text("Acme"),
725 name: text(name),
726 value: PaxValue::Value(opaque(value.as_bytes())),
727 }
728 }
729
730 fn security(value: &str) -> PaxRecord {
731 PaxRecord::Security {
732 name: text("label"),
733 value: PaxValue::Value(text(value)),
734 }
735 }
736
737 fn global_state(records: Vec<PaxRecord>) -> Option<GlobalPaxRecords> {
738 let mut active = None;
739 PaxRecords(records).apply_global(&mut active);
740 active
741 }
742
743 fn extension(position: u64, kind: PaxKind, records: Vec<PaxRecord>) -> PaxExtension {
744 PaxExtension::new(position, kind, Arc::new(PaxRecords(records)))
745 }
746
747 #[test]
748 fn resolves_state_precedence_and_preserves_extension_order() {
749 struct Case {
750 name: &'static str,
751 global: Vec<PaxRecord>,
752 local: Option<Vec<PaxRecord>>,
753 expected: Option<PaxRecord>,
754 }
755
756 for case in [
757 Case {
758 name: "missing",
759 global: Vec::new(),
760 local: None,
761 expected: None,
762 },
763 Case {
764 name: "global",
765 global: vec![comment("global")],
766 local: None,
767 expected: Some(comment("global")),
768 },
769 Case {
770 name: "local overrides global",
771 global: vec![comment("global")],
772 local: Some(vec![comment("local")]),
773 expected: Some(comment("local")),
774 },
775 Case {
776 name: "last local duplicate wins",
777 global: Vec::new(),
778 local: Some(vec![comment("first"), comment("last")]),
779 expected: Some(comment("last")),
780 },
781 Case {
782 name: "local deletion suppresses global",
783 global: vec![comment("global")],
784 local: Some(vec![PaxRecord::Comment(PaxValue::Deleted)]),
785 expected: Some(PaxRecord::Comment(PaxValue::Deleted)),
786 },
787 ] {
788 let global = global_state(case.global);
789 let state = PaxState::new(
790 global.as_ref(),
791 Vec::new(),
792 case.local
793 .map(|records| extension(0, PaxKind::Local, records)),
794 );
795 assert_eq!(
796 state.effective_record(&PaxKeyword::Comment),
797 case.expected.as_ref(),
798 "{}",
799 case.name
800 );
801 }
802
803 let state = PaxState::new(
804 None,
805 vec![
806 extension(3, PaxKind::Global, vec![vendor("first", "value")]),
807 extension(7, PaxKind::Global, vec![vendor("second", "value")]),
808 ],
809 Some(extension(
810 11,
811 PaxKind::Local,
812 vec![vendor("local", "value")],
813 )),
814 );
815 assert_eq!(
816 state
817 .extensions()
818 .map(|extension| (extension.position, extension.kind))
819 .collect::<Vec<_>>(),
820 [
821 (3, PaxKind::Global),
822 (7, PaxKind::Global),
823 (11, PaxKind::Local),
824 ]
825 );
826 }
827
828 #[test]
829 fn updates_effective_global_state_in_place() {
830 let physical_records = Arc::new(PaxRecords(vec![comment("initial")]));
831 let mut active = None;
832 physical_records.apply_global(&mut active);
833 let initial_state = ptr::from_ref(active.as_ref().expect("global state should exist"));
834
835 PaxRecords(vec![vendor("attribute", "value")]).apply_global(&mut active);
836
837 assert_eq!(
838 ptr::from_ref(active.as_ref().expect("global state should exist")),
839 initial_state
840 );
841 assert_eq!(physical_records.as_slice(), [comment("initial")]);
842 }
843
844 #[test]
845 fn global_deletions_remain_effective_tombstones() {
846 let initial = Arc::new(PaxRecords(vec![
847 PaxRecord::Path(PaxValue::Value(utf8("global"))),
848 vendor("kept", "value"),
849 ]));
850 let deletion = Arc::new(PaxRecords(vec![PaxRecord::Path(PaxValue::Deleted)]));
851 let mut active = None;
852 initial.apply_global(&mut active);
853 deletion.apply_global(&mut active);
854
855 let active_records = active.as_ref().expect("global state should exist");
856 assert_eq!(active_records.records.as_slice().len(), 2);
857 let state = PaxState::new(active.as_ref(), Vec::new(), None);
858 assert_eq!(
859 state.effective_record(&PaxKeyword::Path),
860 Some(&PaxRecord::Path(PaxValue::Deleted))
861 );
862 }
863
864 #[test]
865 fn parses_values_and_deletions_through_from_str() {
866 assert!(matches!(
867 "".parse::<PaxValue<String>>(),
868 Ok(PaxValue::Deleted)
869 ));
870 assert!(matches!(
871 "value".parse::<PaxValue<String>>(),
872 Ok(PaxValue::Value(value)) if value == "value"
873 ));
874 assert!(matches!(
875 "12".parse::<PaxValue<u64>>(),
876 Ok(PaxValue::Value(12))
877 ));
878 }
879
880 #[test]
881 fn parses_strict_numeric_and_timestamp_values() {
882 assert!(matches!(
883 PaxValue::parse_integer("uid", b"12"),
884 Ok(PaxValue::Value(12))
885 ));
886 assert!(matches!(
887 PaxValue::parse_integer("uid", b""),
888 Ok(PaxValue::Deleted)
889 ));
890 assert!(matches!(
891 PaxValue::parse_time("mtime", b"12.034"),
892 Ok(PaxValue::Value(12))
893 ));
894 assert!(matches!(
895 PaxValue::parse_time("mtime", b""),
896 Ok(PaxValue::Deleted)
897 ));
898
899 for value in ["+1", "-1", "12x", "18446744073709551616"] {
900 assert!(matches!(
901 PaxValue::parse_integer("gid", value.as_bytes()),
902 Err(PaxError::InvalidInteger { .. })
903 ));
904 }
905 for value in ["+1", "-1", "1.", "1.nanosecond", "18446744073709551616"] {
906 assert!(matches!(
907 PaxValue::parse_time("atime", value.as_bytes()),
908 Err(PaxError::InvalidTime { .. })
909 ));
910 }
911 }
912
913 #[test]
914 fn parses_typed_standard_reserved_and_vendor_records() {
915 let fields = [
916 ("atime", "12.034"),
917 ("charset", "BINARY"),
918 ("comment", "a=b"),
919 ("ctime", "17.500"),
920 ("gid", "07"),
921 ("gname", "group"),
922 ("hdrcharset", UTF8_HDRCHARSET),
923 ("linkpath", "target"),
924 ("mtime", "42"),
925 ("path", "file"),
926 ("realtime.deadline", "soon"),
927 ("security.label", "secure"),
928 ("size", "0"),
929 ("uid", "08"),
930 ("uname", "user"),
931 ("Acme.attribute", "custom"),
932 ];
933 let mut payload = Vec::new();
934 for (keyword, value) in fields {
935 payload.extend_from_slice(&record(keyword, value));
936 }
937
938 let Ok(records) = PaxRecords::parse(&payload, HdrCharset::Utf8) else {
939 panic!("records should parse");
940 };
941 assert_eq!(
942 records.as_slice(),
943 [
944 PaxRecord::Atime(PaxValue::Value(12)),
945 PaxRecord::Charset(PaxValue::Value(text("BINARY"))),
946 comment("a=b"),
947 PaxRecord::Ctime(PaxValue::Value(17)),
948 PaxRecord::Gid(PaxValue::Value(7)),
949 PaxRecord::Gname(PaxValue::Value(utf8("group"))),
950 PaxRecord::HdrCharset(PaxValue::Value(HdrCharset::Utf8)),
951 PaxRecord::LinkPath(PaxValue::Value(utf8("target"))),
952 PaxRecord::Mtime(PaxValue::Value(42)),
953 PaxRecord::Path(PaxValue::Value(utf8("file"))),
954 PaxRecord::Realtime {
955 name: text("deadline"),
956 value: PaxValue::Value(text("soon")),
957 },
958 security("secure"),
959 PaxRecord::Size(PaxValue::Value(0)),
960 PaxRecord::Uid(PaxValue::Value(8)),
961 PaxRecord::Uname(PaxValue::Value(utf8("user"))),
962 vendor("attribute", "custom"),
963 ]
964 );
965 assert!(
966 records
967 .as_slice()
968 .iter()
969 .zip(fields)
970 .all(|(record, (keyword, _))| record.keyword().to_string() == keyword)
971 );
972 }
973
974 #[test]
975 fn parses_deleted_ctime_compatibility_extension() {
976 let Ok(records) = PaxRecords::parse(&record("ctime", ""), HdrCharset::Utf8) else {
977 panic!("ctime deletion should parse");
978 };
979 assert_eq!(records.as_slice(), [PaxRecord::Ctime(PaxValue::Deleted)]);
980 }
981
982 #[test]
983 fn rejects_invalid_records_and_keywords() {
984 for payload in [
985 b"11 path=name".as_slice(),
986 b"12 pathname\n".as_slice(),
987 b"99 path=name\n".as_slice(),
988 b"+12 path=name\n".as_slice(),
989 ] {
990 assert!(matches!(
991 PaxRecords::parse(payload, HdrCharset::Utf8),
992 Err(PaxError::InvalidRecords { .. })
993 ));
994 }
995
996 for keyword in ["unknown", "VENDOR", "VENDOR.", "realtime.", "security."] {
997 assert!(matches!(
998 PaxRecord::parse(keyword, b"value", HdrCharset::Utf8),
999 Err(PaxError::InvalidKeyword { .. })
1000 ));
1001 }
1002 }
1003
1004 #[test]
1005 fn accepts_opaque_vendor_values_but_rejects_invalid_utf8_text() {
1006 let invalid_utf8 = [0xd6, 0xfb, 0x00];
1007 let mut vendor_records = raw_record(b"SCHILY.xattr.user.data", &invalid_utf8);
1008 vendor_records.extend_from_slice(&raw_record(b"SCHILY.xattr.user.deleted", b""));
1009 let expected = PaxRecords(vec![
1010 PaxRecord::Vendor {
1011 vendor: text("SCHILY"),
1012 name: text("xattr.user.data"),
1013 value: PaxValue::Value(opaque(&invalid_utf8)),
1014 },
1015 PaxRecord::Vendor {
1016 vendor: text("SCHILY"),
1017 name: text("xattr.user.deleted"),
1018 value: PaxValue::Deleted,
1019 },
1020 ]);
1021 assert!(matches!(
1022 PaxRecords::parse(&vendor_records, HdrCharset::Utf8),
1023 Ok(records) if records == expected
1024 ));
1025
1026 for keyword in [
1027 b"path".as_slice(),
1028 b"comment",
1029 b"realtime.deadline",
1030 b"security.label",
1031 ] {
1032 assert!(matches!(
1033 PaxRecords::parse(&raw_record(keyword, &invalid_utf8), HdrCharset::Utf8),
1034 Err(PaxError::InvalidUtf8)
1035 ));
1036 }
1037 }
1038
1039 #[test]
1040 fn applies_namespaced_globals_and_accepts_supported_hdrcharset_records() {
1041 let mut active = global_state(vec![
1042 vendor("first", "old"),
1043 vendor("second", "kept"),
1044 security("old"),
1045 ]);
1046 let update = Arc::new(PaxRecords(vec![vendor("first", "new"), security("new")]));
1047 update.apply_global(&mut active);
1048 let active = active.as_ref().expect("global state should exist");
1049 assert_eq!(active.records.as_slice().len(), 3);
1050 assert_eq!(
1051 active.get(&PaxKeyword::Vendor {
1052 vendor: text("Acme"),
1053 name: text("first"),
1054 }),
1055 Some(&vendor("first", "new"))
1056 );
1057 assert_eq!(
1058 active.get(&PaxKeyword::Security(text("label"))),
1059 Some(&security("new"))
1060 );
1061
1062 for (case, payload) in [
1063 (
1064 "supported hdrcharset",
1065 record("hdrcharset", UTF8_HDRCHARSET),
1066 ),
1067 ("deleted hdrcharset", record("hdrcharset", "")),
1068 ("member data charset", record("charset", "BINARY")),
1069 ] {
1070 assert!(
1071 PaxRecords::parse(&payload, HdrCharset::Utf8).is_ok(),
1072 "{case}"
1073 );
1074 }
1075
1076 let mut binary_values = record("hdrcharset", BINARY_HDRCHARSET);
1077 for (keyword, value) in [
1078 (b"gname".as_slice(), [0xfc]),
1079 (b"linkpath".as_slice(), [0xfd]),
1080 (b"path".as_slice(), [0xfe]),
1081 (b"uname".as_slice(), [0xff]),
1082 ] {
1083 binary_values.extend_from_slice(&raw_record(keyword, &value));
1084 }
1085 let Ok(binary_records) = PaxRecords::parse(&binary_values, HdrCharset::Utf8) else {
1086 panic!("binary records should parse");
1087 };
1088 assert_eq!(
1089 binary_records.as_slice(),
1090 [
1091 PaxRecord::HdrCharset(PaxValue::Value(HdrCharset::Binary)),
1092 PaxRecord::Gname(PaxValue::Value(binary(&[0xfc]))),
1093 PaxRecord::LinkPath(PaxValue::Value(binary(&[0xfd]))),
1094 PaxRecord::Path(PaxValue::Value(binary(&[0xfe]))),
1095 PaxRecord::Uname(PaxValue::Value(binary(&[0xff]))),
1096 ]
1097 );
1098 let inherited_binary_path = raw_record(b"path", &[0xfe]);
1099 let Ok(inherited_records) = PaxRecords::parse(&inherited_binary_path, HdrCharset::Binary)
1100 else {
1101 panic!("inherited binary records should parse");
1102 };
1103 assert_eq!(
1104 inherited_records.as_slice(),
1105 [PaxRecord::Path(PaxValue::Value(binary(&[0xfe])))]
1106 );
1107 let mut reset_to_utf8 = record("hdrcharset", "");
1108 reset_to_utf8.extend_from_slice(&raw_record(b"path", &[0xfd]));
1109 assert!(matches!(
1110 PaxRecords::parse(&reset_to_utf8, HdrCharset::Binary),
1111 Err(PaxError::InvalidUtf8)
1112 ));
1113 let mut binary_comment = record("hdrcharset", BINARY_HDRCHARSET);
1114 binary_comment.extend_from_slice(&raw_record(b"comment", &[0xff]));
1115 assert!(matches!(
1116 PaxRecords::parse(&binary_comment, HdrCharset::Utf8),
1117 Err(PaxError::InvalidUtf8)
1118 ));
1119
1120 let unsupported_value = "ISO-IR 8859 1 1998";
1121 let mut overridden_unsupported = record("hdrcharset", unsupported_value);
1122 overridden_unsupported.extend_from_slice(&record("hdrcharset", UTF8_HDRCHARSET));
1123 for unsupported in [
1124 record("hdrcharset", unsupported_value),
1125 overridden_unsupported,
1126 ] {
1127 assert!(matches!(
1128 PaxRecords::parse(&unsupported, HdrCharset::Utf8),
1129 Err(PaxError::UnsupportedCharset { .. })
1130 ));
1131 }
1132 }
1133}