1use std::collections::HashSet;
9
10use archive_trait::{
11 Archive as ArchiveTrait, Member, MemberMetadata, MemberPayload as MemberPayloadTrait,
12 SpecialKind,
13};
14use tar_framing::{
15 ArchiveFormat, FrameError, PaxKeyword, PaxKind, PaxRecord, PaxValue, StreamPolicy, UstarKind,
16 logical::{MemberExtensions, MemberFrame, MemberPayload as FramingMemberPayload, TarReader},
17};
18use thiserror::Error;
19use tokio::io::AsyncRead;
20
21pub use tar_framing::{
22 DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE, DEFAULT_MAX_GNU_EXTENSION_SIZE,
23 DEFAULT_MAX_PAX_EXTENSION_SIZE,
24};
25
26pub struct TarArchive<R> {
35 reader: TarReader<R>,
36 policy: DecodePolicy,
37 fused: bool,
38}
39
40impl<R> TarArchive<R> {
41 pub fn new(reader: R) -> Self {
43 Self {
44 reader: TarReader::new(reader),
45 policy: DecodePolicy::default(),
46 fused: false,
47 }
48 }
49
50 pub fn with_policy(mut self, policy: DecodePolicy) -> Self {
54 let stream_policy = StreamPolicy::default()
55 .max_pax_extension_size(policy.pax_policy.max_extension_size)
56 .max_global_pax_extensions_size(policy.pax_policy.max_global_extensions_size)
57 .allow_pax_hardlink_linkdata(policy.pax_policy.allow_hardlink_linkdata)
58 .allow_all_nul_numeric_fields(policy.allow_all_nul_numeric_fields)
59 .allow_header_uname_and_gname_without_terminator(
60 policy.allow_header_uname_and_gname_without_terminator,
61 )
62 .max_gnu_extension_size(policy.max_gnu_extension_size);
63 self.reader = self.reader.with_policy(stream_policy);
64 self.policy = policy;
65 self
66 }
67}
68
69#[derive(Clone, Debug)]
73pub struct DecodePolicy {
74 allow_gnu: bool,
75 allow_all_nul_numeric_fields: bool,
76 allow_header_uname_and_gname_without_terminator: bool,
77 max_gnu_extension_size: u64,
78 pax_policy: PaxDecodePolicy,
79}
80
81#[derive(Clone, Debug, Eq, PartialEq)]
85pub struct PaxDecodePolicy {
86 max_extension_size: u64,
87 max_global_extensions_size: u64,
88 allow_non_utf8_pax_vendor_values: bool,
89 allow_global_pax_extensions: bool,
90 vendor_extension_policy: PaxVendorExtensionPolicy,
91 allow_duplicate_pax_records: bool,
92 allow_global_pax_member_metadata: bool,
93 allow_hardlink_linkdata: bool,
94}
95
96#[derive(Clone, Debug, Default, Eq, PartialEq)]
98pub enum PaxVendorExtensionPolicy {
99 #[default]
101 RejectUnknown,
102 Ignore(PaxVendorAllowlist),
106 AllowUnknown,
110}
111
112impl PaxVendorExtensionPolicy {
113 pub fn ignore(vendors: impl IntoIterator<Item = &'static str>) -> Self {
117 Self::Ignore(PaxVendorAllowlist {
118 vendors: vendors.into_iter().collect(),
119 })
120 }
121}
122
123#[derive(Clone, Debug, Eq, PartialEq)]
127pub struct PaxVendorAllowlist {
128 vendors: HashSet<&'static str>,
129}
130
131impl Default for PaxDecodePolicy {
132 fn default() -> Self {
133 Self {
134 max_extension_size: DEFAULT_MAX_PAX_EXTENSION_SIZE,
135 max_global_extensions_size: DEFAULT_MAX_GLOBAL_PAX_EXTENSIONS_SIZE,
136 allow_non_utf8_pax_vendor_values: true,
137 allow_global_pax_extensions: true,
138 vendor_extension_policy: PaxVendorExtensionPolicy::default(),
139 allow_duplicate_pax_records: false,
140 allow_global_pax_member_metadata: false,
141 allow_hardlink_linkdata: false,
142 }
143 }
144}
145
146impl Default for DecodePolicy {
147 fn default() -> Self {
148 Self {
149 allow_gnu: true,
150 allow_all_nul_numeric_fields: true,
151 allow_header_uname_and_gname_without_terminator: false,
152 max_gnu_extension_size: DEFAULT_MAX_GNU_EXTENSION_SIZE,
153 pax_policy: PaxDecodePolicy::default(),
154 }
155 }
156}
157
158impl DecodePolicy {
159 pub fn allow_gnu(mut self, allow: bool) -> Self {
166 self.allow_gnu = allow;
167 self
168 }
169
170 pub fn allow_all_nul_numeric_fields(mut self, allow: bool) -> Self {
178 self.allow_all_nul_numeric_fields = allow;
179 self
180 }
181
182 pub fn allow_header_uname_and_gname_without_terminator(mut self, allow: bool) -> Self {
188 self.allow_header_uname_and_gname_without_terminator = allow;
189 self
190 }
191
192 pub fn max_gnu_extension_size(mut self, max_gnu_extension_size: u64) -> Self {
200 self.max_gnu_extension_size = max_gnu_extension_size;
201 self
202 }
203
204 pub fn pax_policy(mut self, policy: PaxDecodePolicy) -> Self {
206 self.pax_policy = policy;
207 self
208 }
209
210 fn check_format(&self, position: u64, format: ArchiveFormat) -> Result<(), DecodeError> {
211 if format == ArchiveFormat::Gnu && !self.allow_gnu {
212 return Err(DecodeError::policy_violation(
213 position,
214 DecodePolicyViolation::GnuArchive,
215 ));
216 }
217 Ok(())
218 }
219
220 fn check_global_pax(&self, position: u64, records: &[PaxRecord]) -> Result<(), DecodeError> {
221 self.pax_policy.check_global_pax_extension(position)?;
222 self.pax_policy
223 .check_pax_records(position, PaxKind::Global, records)
224 }
225
226 fn check_member<R>(&self, frame: &MemberFrame<'_, R>) -> Result<(), DecodeError> {
227 if let MemberExtensions::Pax(state) = &frame.extensions {
228 for extension in state
229 .extensions()
230 .filter(|extension| extension.kind == PaxKind::Global)
231 {
232 self.check_global_pax(extension.position, extension.records())?;
233 }
234 }
235 let format_position = match &frame.extensions {
236 MemberExtensions::Pax(_) => frame.header.position,
237 MemberExtensions::Gnu {
238 long_name,
239 long_link,
240 } => long_name
241 .iter()
242 .chain(long_link.iter())
243 .map(|header| header.position)
244 .min()
245 .unwrap_or(frame.header.position),
246 };
247 self.check_format(format_position, frame.header.format)?;
248 if let MemberExtensions::Pax(state) = &frame.extensions {
249 for extension in state
250 .extensions()
251 .filter(|extension| extension.kind == PaxKind::Local)
252 {
253 self.pax_policy.check_pax_records(
254 extension.position,
255 PaxKind::Local,
256 extension.records(),
257 )?;
258 }
259 }
260 Ok(())
261 }
262}
263
264impl PaxDecodePolicy {
265 pub fn max_extension_size(mut self, max_extension_size: u64) -> Self {
276 self.max_extension_size = max_extension_size;
277 self
278 }
279
280 pub fn max_global_extensions_size(mut self, max_global_extensions_size: u64) -> Self {
289 self.max_global_extensions_size = max_global_extensions_size;
290 self
291 }
292
293 pub fn allow_non_utf8_pax_vendor_values(mut self, allow: bool) -> Self {
303 self.allow_non_utf8_pax_vendor_values = allow;
304 self
305 }
306
307 pub fn allow_global_pax_extensions(mut self, allow: bool) -> Self {
316 self.allow_global_pax_extensions = allow;
317 self
318 }
319
320 pub fn vendor_extension_policy(mut self, policy: PaxVendorExtensionPolicy) -> Self {
337 self.vendor_extension_policy = policy;
338 self
339 }
340
341 pub fn allow_duplicate_pax_records(mut self, allow: bool) -> Self {
348 self.allow_duplicate_pax_records = allow;
349 self
350 }
351
352 pub fn allow_global_pax_member_metadata(mut self, allow: bool) -> Self {
360 self.allow_global_pax_member_metadata = allow;
361 self
362 }
363
364 pub fn allow_hardlink_linkdata(mut self, allow: bool) -> Self {
372 self.allow_hardlink_linkdata = allow;
373 self
374 }
375
376 fn check_global_pax_extension(&self, position: u64) -> Result<(), DecodeError> {
377 if !self.allow_global_pax_extensions {
378 return Err(DecodeError::policy_violation(
379 position,
380 DecodePolicyViolation::GlobalPaxExtension,
381 ));
382 }
383 Ok(())
384 }
385
386 fn check_pax_records(
387 &self,
388 position: u64,
389 kind: PaxKind,
390 records: &[PaxRecord],
391 ) -> Result<(), DecodeError> {
392 for record in records {
393 if let PaxRecord::Vendor {
394 vendor,
395 name,
396 value,
397 } = record
398 {
399 let allowed = match &self.vendor_extension_policy {
400 PaxVendorExtensionPolicy::RejectUnknown => false,
401 PaxVendorExtensionPolicy::Ignore(allowed) => {
402 allowed.vendors.contains(vendor.as_ref())
403 }
404 PaxVendorExtensionPolicy::AllowUnknown => true,
405 };
406 if !allowed {
407 return Err(DecodeError::policy_violation(
408 position,
409 DecodePolicyViolation::PaxVendorExtension {
410 vendor: vendor.to_string(),
411 name: name.to_string(),
412 },
413 ));
414 }
415
416 if !self.allow_non_utf8_pax_vendor_values
417 && let PaxValue::Value(value) = value
418 && std::str::from_utf8(value).is_err()
419 {
420 return Err(DecodeError::policy_violation(
421 position,
422 DecodePolicyViolation::NonUtf8PaxVendorValue {
423 vendor: vendor.to_string(),
424 name: name.to_string(),
425 },
426 ));
427 }
428 }
429 }
430
431 if kind == PaxKind::Global && !self.allow_global_pax_member_metadata {
432 for record in records {
433 let keyword = match record.keyword() {
434 PaxKeyword::Path => Some("path"),
435 PaxKeyword::LinkPath => Some("linkpath"),
436 PaxKeyword::Size => Some("size"),
437 _ => None,
438 };
439 if let Some(keyword) = keyword {
440 return Err(DecodeError::policy_violation(
441 position,
442 DecodePolicyViolation::GlobalPaxMemberMetadata { keyword },
443 ));
444 }
445 }
446 }
447
448 if !self.allow_duplicate_pax_records {
449 let mut keywords = HashSet::new();
450 for record in records {
451 let keyword = record.keyword();
452 if !keywords.insert(keyword.clone()) {
453 return Err(DecodeError::policy_violation(
454 position,
455 DecodePolicyViolation::DuplicatePaxRecord {
456 keyword: keyword.to_string(),
457 },
458 ));
459 }
460 }
461 }
462
463 Ok(())
464 }
465}
466
467#[derive(Clone, Debug, Eq, PartialEq, Error)]
469pub enum DecodePolicyViolation {
470 #[error("GNU archives are not allowed")]
472 GnuArchive,
473 #[error("global pax extended headers are not allowed")]
475 GlobalPaxExtension,
476 #[error("pax vendor extension {vendor}.{name} is not allowed")]
478 PaxVendorExtension {
479 vendor: String,
481 name: String,
483 },
484 #[error("pax vendor extension {vendor}.{name} contains a non-UTF-8 value")]
486 NonUtf8PaxVendorValue {
487 vendor: String,
489 name: String,
491 },
492 #[error("pax extended header contains duplicate record {keyword}")]
494 DuplicatePaxRecord {
495 keyword: String,
497 },
498 #[error("global pax extended header contains restricted member metadata {keyword}")]
500 GlobalPaxMemberMetadata {
501 keyword: &'static str,
503 },
504}
505
506#[derive(Debug, Error)]
508pub enum DecodeError {
509 #[error(transparent)]
511 Framing(#[from] FrameError),
512 #[error("at byte {position}: {field} is not valid UTF-8")]
514 InvalidUtf8 {
515 position: u64,
517 field: &'static str,
519 },
520 #[error("at byte {position}: decode policy rejected input: {violation}")]
522 PolicyViolation {
523 position: u64,
525 violation: DecodePolicyViolation,
527 },
528}
529
530impl DecodeError {
531 fn policy_violation(position: u64, violation: DecodePolicyViolation) -> Self {
532 Self::PolicyViolation {
533 position,
534 violation,
535 }
536 }
537}
538
539pub struct TarMemberPayload<'a, R> {
541 payload: FramingMemberPayload<'a, R>,
542}
543
544impl<R: AsyncRead + Unpin> MemberPayloadTrait for TarMemberPayload<'_, R> {
545 type Error = DecodeError;
546
547 async fn next_chunk(
548 &mut self,
549 buffer: &mut Vec<u8>,
550 target_len: usize,
551 ) -> Result<bool, Self::Error> {
552 self.payload
553 .next_chunk(buffer, target_len)
554 .await
555 .map_err(Into::into)
556 }
557
558 async fn skip(self) -> Result<(), Self::Error> {
559 self.payload.skip().await.map_err(Into::into)
560 }
561}
562
563impl<R: AsyncRead + Unpin> ArchiveTrait for TarArchive<R> {
564 type Error = DecodeError;
565 type Payload<'a>
566 = TarMemberPayload<'a, R>
567 where
568 Self: 'a;
569
570 async fn next_member<'a>(
571 &'a mut self,
572 ) -> Result<Option<Member<Self::Payload<'a>>>, Self::Error> {
573 if self.fused {
574 return Ok(None);
575 }
576
577 let result = match self.reader.next_frame().await {
578 Ok(Some(frame)) => decode_member(frame, &self.policy).map(Some),
579 Ok(None) => Ok(None),
580 Err(error) => Err(error.into()),
581 };
582 self.fused = !matches!(result, Ok(Some(_)));
583 result
584 }
585}
586
587fn decode_member<'a, R>(
588 frame: MemberFrame<'a, R>,
589 policy: &DecodePolicy,
590) -> Result<Member<TarMemberPayload<'a, R>>, DecodeError> {
591 policy.check_member(&frame)?;
592 let position = frame.header.position;
593 let kind = frame.header.kind;
594 let size = frame.header.effective_size;
595 let executable = frame.header.mode.unwrap_or_default() & 0o111 != 0;
596 let path = std::str::from_utf8(frame.effective_path()?.as_ref())
597 .map(str::to_owned)
598 .map_err(|_| DecodeError::InvalidUtf8 {
599 position,
600 field: "path",
601 })?;
602 let target = if matches!(kind, UstarKind::HardLink | UstarKind::SymbolicLink) {
603 std::str::from_utf8(frame.effective_link_path()?.as_ref())
604 .map(str::to_owned)
605 .map_err(|_| DecodeError::InvalidUtf8 {
606 position,
607 field: "linkpath",
608 })?
609 } else {
610 String::new()
611 };
612 let metadata = MemberMetadata { path, position };
613
614 Ok(match kind {
615 UstarKind::Regular | UstarKind::Contiguous => Member::File {
616 metadata,
617 size,
618 executable,
619 payload: TarMemberPayload {
620 payload: frame.payload,
621 },
622 },
623 UstarKind::Directory => Member::Directory { metadata },
624 UstarKind::SymbolicLink => Member::SymbolicLink { metadata, target },
625 UstarKind::HardLink => Member::HardLink {
626 metadata,
627 target,
628 size,
629 payload: TarMemberPayload {
630 payload: frame.payload,
631 },
632 },
633 UstarKind::CharacterDevice => Member::Special {
634 metadata,
635 kind: SpecialKind::CharacterDevice,
636 },
637 UstarKind::BlockDevice => Member::Special {
638 metadata,
639 kind: SpecialKind::BlockDevice,
640 },
641 UstarKind::Fifo => Member::Special {
642 metadata,
643 kind: SpecialKind::Fifo,
644 },
645 })
646}