use crate::closed_enum::closed_enum;
use crate::formats::tar_extension_headers::MAX_PAX_RECORD_BYTES;
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarHeaderField {
Size => "size",
Checksum => "checksum",
SparseOffset => "sparse offset",
SparseLength => "sparse length",
RealSize => "real size",
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarNonRegularKind {
Directory => "directory",
Symlink => "symlink",
Hardlink => "hardlink",
VolumeLabel => "volume label",
}
}
impl TarNonRegularKind {
pub(crate) fn of(entry_type: tar::EntryType) -> Option<Self> {
match entry_type {
tar::EntryType::Directory => Some(Self::Directory),
tar::EntryType::Symlink => Some(Self::Symlink),
tar::EntryType::Link => Some(Self::Hardlink),
other if other.as_byte() == b'V' => Some(Self::VolumeLabel),
_ => None,
}
}
}
closed_enum! {
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SparseMapDefect {
PartialSlot => "partial slot",
SlotAfterEnd => "slot after the end of the map",
ExtendedFlag => "invalid extended flag",
ExtensionChain => "extension chain mismatch",
ZeroOffsetExtension => "zero offset in an extension block",
InteriorZeroLength => "zero-length slot before the end",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarExtensionKind {
Pax,
LongName,
LongLink,
}
impl TarExtensionKind {
#[must_use]
pub const fn typeflag(self) -> u8 {
match self {
Self::Pax => b'x',
Self::LongName => b'L',
Self::LongLink => b'K',
}
}
const fn name(self) -> &'static str {
match self {
Self::Pax => "PAX",
Self::LongName => "GNU long name",
Self::LongLink => "GNU long link",
}
}
const fn entry_type_name(self) -> &'static str {
match self {
Self::Pax => "XHeader",
Self::LongName => "GNULongName",
Self::LongLink => "GNULongLink",
}
}
}
impl std::fmt::Display for TarExtensionKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarPathKey {
Path,
LinkPath,
}
impl TarPathKey {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Path => "path",
Self::LinkPath => "linkpath",
}
}
const fn long_record(self) -> &'static str {
match self {
Self::Path => "name",
Self::LinkPath => "link",
}
}
}
impl std::fmt::Display for TarPathKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TarAmbiguity {
MalformedRecord,
EmptyKey,
OversizedRecord {
key: String,
},
DuplicateRecord {
key: String,
},
UnsupportedRecord {
key: String,
},
InvalidSize,
GlobalOverride {
key: String,
},
GlobalTooLarge {
size: u64,
limit: u64,
},
LocalBeforeGlobal,
LongRecordBeforeGlobal,
StackedLongRecord {
key: TarPathKey,
},
StackedSizeRecord,
UnrecognizedHeader {
kind: TarExtensionKind,
},
SparseEntry,
NonCanonicalNumber {
field: TarHeaderField,
},
PrefixWithoutUstar,
ChecksumMismatch,
DuplicateExtensionHeader {
kind: TarExtensionKind,
},
WindowMismatch,
NonZeroPadding,
MalformedLongRecord {
kind: TarExtensionKind,
},
NonRegularPayload {
kind: TarNonRegularKind,
size: u64,
path: String,
},
DirectoryNamedPayload {
size: u64,
path: String,
},
ExtensionBeforeLabel {
kind: TarExtensionKind,
},
SparseMap {
defect: SparseMapDefect,
},
}
impl std::fmt::Display for TarAmbiguity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::MalformedRecord => f.write_str("malformed PAX record"),
Self::EmptyKey => f.write_str("PAX record with an empty key"),
Self::OversizedRecord { key } => write!(
f,
"PAX record {key:?} is longer than {MAX_PAX_RECORD_BYTES} bytes"
),
Self::DuplicateRecord { key } => write!(f, "duplicate PAX record {key:?}"),
Self::UnsupportedRecord { key } => write!(f, "PAX record {key:?} is not supported"),
Self::InvalidSize => f.write_str("PAX `size` record is not a decimal number"),
Self::GlobalOverride { key } => {
write!(f, "global PAX record {key:?} would apply to later entries")
}
Self::GlobalTooLarge { size, limit } => write!(
f,
"global PAX header ({size} bytes) exceeds the metadata limit of {limit} bytes"
),
Self::LocalBeforeGlobal => f.write_str("global PAX header follows a local PAX header"),
Self::LongRecordBeforeGlobal => {
f.write_str("global PAX header follows a GNU long name or link record")
}
Self::StackedLongRecord { key } => write!(
f,
"PAX `{key}` record and a GNU long {} record both describe the same entry",
key.long_record()
),
Self::StackedSizeRecord => f.write_str(
"PAX `size` record and a GNU long name or link record share one extension chain",
),
Self::UnrecognizedHeader { kind } => write!(
f,
"extension header {} lacks a ustar or GNU magic",
kind.entry_type_name()
),
Self::SparseEntry => {
f.write_str("GNU sparse entries are refused unless tar_sparse is expand")
}
Self::NonCanonicalNumber { field } => write!(
f,
"header {field} field is not a plain octal or base-256 number"
),
Self::PrefixWithoutUstar => {
f.write_str("header carries a prefix field without a ustar magic")
}
Self::ChecksumMismatch => {
f.write_str("header checksum does not match the header bytes")
}
Self::DuplicateExtensionHeader { kind } => {
write!(f, "duplicate {kind} extension header")
}
Self::NonZeroPadding => {
f.write_str("extension header body is followed by non-zero padding")
}
Self::MalformedLongRecord { kind } => {
write!(
f,
"{kind} extension header is not a single NUL-terminated string"
)
}
Self::WindowMismatch => {
f.write_str("bytes read before the entry do not match the position of its header")
}
Self::NonRegularPayload { kind, size, path } => {
write!(f, "{kind} entry declares a {size} byte payload: {path}")
}
Self::DirectoryNamedPayload { size, path } => {
write!(
f,
"file entry with a directory name carries {size} bytes: {path}"
)
}
Self::ExtensionBeforeLabel { kind } => {
write!(f, "a {kind} header precedes a volume label")
}
Self::SparseMap { defect } => write!(f, "GNU sparse map: {defect}"),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn payload_messages_are_pinned() {
let directory = TarAmbiguity::NonRegularPayload {
kind: TarNonRegularKind::Directory,
size: 1024,
path: "x/".into(),
};
assert_eq!(
directory.to_string(),
"directory entry declares a 1024 byte payload: x/"
);
let named = TarAmbiguity::DirectoryNamedPayload {
size: 3,
path: "d/".into(),
};
let hardlink = TarAmbiguity::NonRegularPayload {
kind: TarNonRegularKind::Hardlink,
size: 2,
path: "l".into(),
};
assert_eq!(
hardlink.to_string(),
"hardlink entry declares a 2 byte payload: l"
);
assert_eq!(
named.to_string(),
"file entry with a directory name carries 3 bytes: d/"
);
}
#[test]
fn non_regular_kinds_display_in_lower_case_like_their_siblings() {
use crate::error::zip_inconsistency::ZipNonRegularKind;
let spellings: Vec<_> = TarNonRegularKind::ALL
.iter()
.map(ToString::to_string)
.collect();
assert_eq!(
spellings,
["directory", "symlink", "hardlink", "volume label"]
);
for kind in TarNonRegularKind::ALL {
assert_eq!(kind.as_str(), kind.to_string());
assert_eq!(kind.to_string(), kind.to_string().to_lowercase());
}
assert_eq!(
TarNonRegularKind::Directory.to_string(),
ZipNonRegularKind::Directory.to_string()
);
}
#[test]
fn volume_label_messages_are_pinned() {
let payload = TarAmbiguity::NonRegularPayload {
kind: TarNonRegularKind::VolumeLabel,
size: 1024,
path: "label".into(),
};
assert_eq!(
payload.to_string(),
"volume label entry declares a 1024 byte payload: label"
);
let cases = [
(
TarExtensionKind::Pax,
"a PAX header precedes a volume label",
),
(
TarExtensionKind::LongName,
"a GNU long name header precedes a volume label",
),
(
TarExtensionKind::LongLink,
"a GNU long link header precedes a volume label",
),
];
for (kind, text) in cases {
assert_eq!(
TarAmbiguity::ExtensionBeforeLabel { kind }.to_string(),
text
);
}
}
#[test]
fn only_the_label_typeflag_maps_to_the_volume_label_kind() {
assert_eq!(
TarNonRegularKind::of(tar::EntryType::new(b'V')),
Some(TarNonRegularKind::VolumeLabel)
);
assert_eq!(TarNonRegularKind::of(tar::EntryType::new(b'D')), None);
assert_eq!(TarNonRegularKind::of(tar::EntryType::Regular), None);
}
#[test]
fn a_symlink_payload_message_uses_the_lower_case_kind() {
let symlink = TarAmbiguity::NonRegularPayload {
kind: TarNonRegularKind::Symlink,
size: 9,
path: "s".into(),
};
assert_eq!(
symlink.to_string(),
"symlink entry declares a 9 byte payload: s"
);
}
#[test]
fn extension_kind_messages_are_pinned() {
let cases = [
(TarExtensionKind::Pax, "PAX", "XHeader"),
(TarExtensionKind::LongName, "GNU long name", "GNULongName"),
(TarExtensionKind::LongLink, "GNU long link", "GNULongLink"),
];
for (kind, name, entry_type) in cases {
assert_eq!(kind.to_string(), name);
assert_eq!(
TarAmbiguity::DuplicateExtensionHeader { kind }.to_string(),
format!("duplicate {name} extension header")
);
assert_eq!(
TarAmbiguity::MalformedLongRecord { kind }.to_string(),
format!("{name} extension header is not a single NUL-terminated string")
);
assert_eq!(
TarAmbiguity::UnrecognizedHeader { kind }.to_string(),
format!("extension header {entry_type} lacks a ustar or GNU magic")
);
}
}
}