1use crate::closed_enum::closed_enum;
5use crate::formats::tar_extension_headers::MAX_PAX_RECORD_BYTES;
6
7closed_enum! {
8 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
18 #[non_exhaustive]
19 pub enum TarHeaderField {
20 Size => "size",
22 Checksum => "checksum",
24 }
25}
26
27closed_enum! {
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
38 #[non_exhaustive]
39 pub enum TarNonRegularKind {
40 Directory => "directory",
42 Symlink => "symlink",
44 Hardlink => "hardlink",
46 }
47}
48
49impl TarNonRegularKind {
50 pub(crate) const fn of(entry_type: tar::EntryType) -> Option<Self> {
52 match entry_type {
53 tar::EntryType::Directory => Some(Self::Directory),
54 tar::EntryType::Symlink => Some(Self::Symlink),
55 tar::EntryType::Link => Some(Self::Hardlink),
56 _ => None,
57 }
58 }
59}
60
61#[derive(Debug, Clone, Copy, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum TarExtensionKind {
74 Pax,
76 LongName,
78 LongLink,
80}
81
82impl TarExtensionKind {
83 #[must_use]
85 pub const fn typeflag(self) -> u8 {
86 match self {
87 Self::Pax => b'x',
88 Self::LongName => b'L',
89 Self::LongLink => b'K',
90 }
91 }
92
93 const fn name(self) -> &'static str {
94 match self {
95 Self::Pax => "PAX",
96 Self::LongName => "GNU long name",
97 Self::LongLink => "GNU long link",
98 }
99 }
100
101 const fn entry_type_name(self) -> &'static str {
102 match self {
103 Self::Pax => "XHeader",
104 Self::LongName => "GNULongName",
105 Self::LongLink => "GNULongLink",
106 }
107 }
108}
109
110impl std::fmt::Display for TarExtensionKind {
111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
112 f.write_str(self.name())
113 }
114}
115
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
126#[non_exhaustive]
127pub enum TarPathKey {
128 Path,
130 LinkPath,
132}
133
134impl TarPathKey {
135 #[must_use]
137 pub const fn as_str(self) -> &'static str {
138 match self {
139 Self::Path => "path",
140 Self::LinkPath => "linkpath",
141 }
142 }
143
144 const fn long_record(self) -> &'static str {
145 match self {
146 Self::Path => "name",
147 Self::LinkPath => "link",
148 }
149 }
150}
151
152impl std::fmt::Display for TarPathKey {
153 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
154 f.write_str(self.as_str())
155 }
156}
157
158#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub enum TarAmbiguity {
181 MalformedRecord,
183
184 EmptyKey,
186
187 OversizedRecord {
189 key: String,
191 },
192
193 DuplicateRecord {
195 key: String,
197 },
198
199 UnsupportedRecord {
202 key: String,
204 },
205
206 InvalidSize,
208
209 GlobalOverride {
212 key: String,
214 },
215
216 GlobalTooLarge {
218 size: u64,
220 limit: u64,
222 },
223
224 LocalBeforeGlobal,
226
227 LongRecordBeforeGlobal,
229
230 StackedLongRecord {
232 key: TarPathKey,
234 },
235
236 StackedSizeRecord,
239
240 UnrecognizedHeader {
242 kind: TarExtensionKind,
244 },
245
246 SparseEntry,
248
249 NonCanonicalNumber {
251 field: TarHeaderField,
253 },
254
255 PrefixWithoutUstar,
257
258 ChecksumMismatch,
260
261 DuplicateExtensionHeader {
263 kind: TarExtensionKind,
265 },
266
267 WindowMismatch,
270
271 NonZeroPadding,
274
275 MalformedLongRecord {
277 kind: TarExtensionKind,
279 },
280
281 NonRegularPayload {
284 kind: TarNonRegularKind,
286 size: u64,
288 path: String,
290 },
291
292 DirectoryNamedPayload {
295 size: u64,
297 path: String,
299 },
300}
301
302impl std::fmt::Display for TarAmbiguity {
303 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
304 match self {
305 Self::MalformedRecord => f.write_str("malformed PAX record"),
306 Self::EmptyKey => f.write_str("PAX record with an empty key"),
307 Self::OversizedRecord { key } => write!(
308 f,
309 "PAX record {key:?} is longer than {MAX_PAX_RECORD_BYTES} bytes"
310 ),
311 Self::DuplicateRecord { key } => write!(f, "duplicate PAX record {key:?}"),
312 Self::UnsupportedRecord { key } => write!(f, "PAX record {key:?} is not supported"),
313 Self::InvalidSize => f.write_str("PAX `size` record is not a decimal number"),
314 Self::GlobalOverride { key } => {
315 write!(f, "global PAX record {key:?} would apply to later entries")
316 }
317 Self::GlobalTooLarge { size, limit } => write!(
318 f,
319 "global PAX header ({size} bytes) exceeds the metadata limit of {limit} bytes"
320 ),
321 Self::LocalBeforeGlobal => f.write_str("global PAX header follows a local PAX header"),
322 Self::LongRecordBeforeGlobal => {
323 f.write_str("global PAX header follows a GNU long name or link record")
324 }
325 Self::StackedLongRecord { key } => write!(
326 f,
327 "PAX `{key}` record and a GNU long {} record both describe the same entry",
328 key.long_record()
329 ),
330 Self::StackedSizeRecord => f.write_str(
331 "PAX `size` record and a GNU long name or link record share one extension chain",
332 ),
333 Self::UnrecognizedHeader { kind } => write!(
334 f,
335 "extension header {} lacks a ustar or GNU magic",
336 kind.entry_type_name()
337 ),
338 Self::SparseEntry => f.write_str("GNU sparse entries are not supported"),
339 Self::NonCanonicalNumber { field } => write!(
340 f,
341 "header {field} field is not a plain octal or base-256 number"
342 ),
343 Self::PrefixWithoutUstar => {
344 f.write_str("header carries a prefix field without a ustar magic")
345 }
346 Self::ChecksumMismatch => {
347 f.write_str("header checksum does not match the header bytes")
348 }
349 Self::DuplicateExtensionHeader { kind } => {
350 write!(f, "duplicate {kind} extension header")
351 }
352 Self::NonZeroPadding => {
353 f.write_str("extension header body is followed by non-zero padding")
354 }
355 Self::MalformedLongRecord { kind } => {
356 write!(
357 f,
358 "{kind} extension header is not a single NUL-terminated string"
359 )
360 }
361 Self::WindowMismatch => {
362 f.write_str("bytes read before the entry do not match the position of its header")
363 }
364 Self::NonRegularPayload { kind, size, path } => {
365 write!(f, "{kind} entry declares a {size} byte payload: {path}")
366 }
367 Self::DirectoryNamedPayload { size, path } => {
368 write!(
369 f,
370 "file entry with a directory name carries {size} bytes: {path}"
371 )
372 }
373 }
374 }
375}
376
377#[cfg(test)]
378mod tests {
379 use super::*;
380
381 #[test]
382 fn payload_messages_are_pinned() {
383 let directory = TarAmbiguity::NonRegularPayload {
384 kind: TarNonRegularKind::Directory,
385 size: 1024,
386 path: "x/".into(),
387 };
388 assert_eq!(
389 directory.to_string(),
390 "directory entry declares a 1024 byte payload: x/"
391 );
392 let named = TarAmbiguity::DirectoryNamedPayload {
393 size: 3,
394 path: "d/".into(),
395 };
396 let hardlink = TarAmbiguity::NonRegularPayload {
397 kind: TarNonRegularKind::Hardlink,
398 size: 2,
399 path: "l".into(),
400 };
401 assert_eq!(
402 hardlink.to_string(),
403 "hardlink entry declares a 2 byte payload: l"
404 );
405 assert_eq!(
406 named.to_string(),
407 "file entry with a directory name carries 3 bytes: d/"
408 );
409 }
410
411 #[test]
412 fn non_regular_kinds_display_in_lower_case_like_their_siblings() {
413 use crate::error::zip_inconsistency::ZipNonRegularKind;
414
415 let spellings: Vec<_> = TarNonRegularKind::ALL
416 .iter()
417 .map(ToString::to_string)
418 .collect();
419 assert_eq!(spellings, ["directory", "symlink", "hardlink"]);
420 for kind in TarNonRegularKind::ALL {
421 assert_eq!(kind.as_str(), kind.to_string());
422 assert_eq!(kind.to_string(), kind.to_string().to_lowercase());
423 }
424 assert_eq!(
425 TarNonRegularKind::Directory.to_string(),
426 ZipNonRegularKind::Directory.to_string()
427 );
428 }
429
430 #[test]
431 fn a_symlink_payload_message_uses_the_lower_case_kind() {
432 let symlink = TarAmbiguity::NonRegularPayload {
433 kind: TarNonRegularKind::Symlink,
434 size: 9,
435 path: "s".into(),
436 };
437 assert_eq!(
438 symlink.to_string(),
439 "symlink entry declares a 9 byte payload: s"
440 );
441 }
442
443 #[test]
444 fn extension_kind_messages_are_pinned() {
445 let cases = [
446 (TarExtensionKind::Pax, "PAX", "XHeader"),
447 (TarExtensionKind::LongName, "GNU long name", "GNULongName"),
448 (TarExtensionKind::LongLink, "GNU long link", "GNULongLink"),
449 ];
450 for (kind, name, entry_type) in cases {
451 assert_eq!(kind.to_string(), name);
452 assert_eq!(
453 TarAmbiguity::DuplicateExtensionHeader { kind }.to_string(),
454 format!("duplicate {name} extension header")
455 );
456 assert_eq!(
457 TarAmbiguity::MalformedLongRecord { kind }.to_string(),
458 format!("{name} extension header is not a single NUL-terminated string")
459 );
460 assert_eq!(
461 TarAmbiguity::UnrecognizedHeader { kind }.to_string(),
462 format!("extension header {entry_type} lacks a ustar or GNU magic")
463 );
464 }
465 }
466}