Skip to main content

tar_framing/
header.rs

1use crate::{ArchiveFormat, Block};
2
3/// The byte range that a member name appears at in a tar block,
4/// whether pax/ustar or GNU.
5pub const NAME_RANGE: std::ops::Range<usize> = 0..100;
6
7/// The byte range that a member's mode appears at in a tar block,
8/// whether pax/ustar or GNU.
9pub const MODE_RANGE: std::ops::Range<usize> = 100..108;
10
11/// The byte range that a member's user ID appears at in a tar block,
12/// whether pax/ustar or GNU.
13pub const UID_RANGE: std::ops::Range<usize> = 108..116;
14
15/// The byte range that a member's group ID appears at in a tar block,
16/// whether pax/ustar or GNU.
17pub const GID_RANGE: std::ops::Range<usize> = 116..124;
18
19/// The byte range that a member's size appears at in a tar block,
20/// whether pax/ustar or GNU.
21pub const SIZE_RANGE: std::ops::Range<usize> = 124..136;
22
23/// The byte range that a member's mtime appears at in a tar block,
24/// whether pax/ustar or GNU.
25pub const MTIME_RANGE: std::ops::Range<usize> = 136..148;
26
27/// The byte range that a member's checksum appears at in a tar block,
28/// whether pax/ustar or GNU.
29pub const CHECKSUM_RANGE: std::ops::Range<usize> = 148..156;
30
31/// The byte index that a member's typeflag appears at in a tar block,
32/// whether pax/ustar or GNU.
33pub const TYPEFLAG_OFFSET: usize = 156;
34
35/// The byte range that a member's link name (i.e. link target) appears
36/// at in a tar block, whether pax/ustar or GNU.
37pub const LINK_NAME_RANGE: std::ops::Range<usize> = 157..257;
38
39/// The byte range that a member's identity appears at in a tar block,
40/// whether pax/ustar or GNU.
41///
42/// This is both the tar magic and the tar version.
43pub const IDENTITY_RANGE: std::ops::Range<usize> = 257..265;
44
45/// The byte range that a member's user name appears at in a pax/ustar block.
46pub const UNAME_RANGE: std::ops::Range<usize> = 265..297;
47
48/// The byte range that a member's group name appears at in a pax/ustar block.
49pub const GNAME_RANGE: std::ops::Range<usize> = 297..329;
50
51/// The byte range that a member's device-major value appears at in a pax/ustar block.
52pub const DEVMAJOR_RANGE: std::ops::Range<usize> = 329..337;
53
54/// The byte range that a member's device-minor value appears at in a pax/ustar block.
55pub const DEVMINOR_RANGE: std::ops::Range<usize> = 337..345;
56
57/// The byte range that a member's checksum appears at in a tar block.
58///
59/// This is relevant only for pax/ustar; GNU blocks do not include a prefix.
60pub const PREFIX_RANGE: std::ops::Range<usize> = 345..500;
61
62/// The magic and version bytes for a ustar tar block.
63/// ustar blocks form the baseline for pax, since every pax block is
64/// a well-formed ustar block (and what makes it pax is whether
65/// it uses a pax typeflag).
66pub const USTAR_IDENTITY: &[u8; 8] = b"ustar\x0000";
67
68/// The magic and version bytes for a GNU tar block.
69/// Note that, despite not having the proper ustar identity, a GNU tar
70/// block uses a strict superset of the ustar typeflags.
71pub const GNU_IDENTITY: &[u8; 8] = b"ustar  \0";
72
73/// The signature in the final four bytes of an xstar header.
74pub(crate) const XSTAR_MAGIC: &[u8; 4] = b"tar\0";
75
76/// A tar header block (pax, ustar, or GNU) is exactly 512 bytes,
77/// so the logical maximum checksum is `255*512 = 130,560`. However,
78/// the checksum field *itself* is treated as 8 ASCII spaces when
79/// computing the checksum, so the actual maximum is
80/// `(504*255)+(8*32) = 128,776`.
81const MAX_CHECKSUM: u64 = (504 * 255) + (8 * 32);
82const _: () = assert!(MAX_CHECKSUM < 0o777777);
83
84// Pax framing constructs two headers per member. Keeping this fixed-size
85// reduction inline lets LLVM lower each call to a compact vectorized sum.
86#[inline(always)]
87pub(crate) fn checksum(block: &Block) -> u64 {
88    // A block's maximum byte sum fits in u32, which gives LLVM a compact
89    // vectorized reduction.
90    let block_sum = block.iter().map(|byte| u32::from(*byte)).sum::<u32>();
91    let checksum_sum = block[CHECKSUM_RANGE]
92        .iter()
93        .map(|byte| u32::from(*byte))
94        .sum::<u32>();
95    u64::from(block_sum - checksum_sum + CHECKSUM_RANGE.len() as u32 * u32::from(b' '))
96}
97
98#[inline(always)]
99pub(crate) fn encode_checksum(block: &mut Block) {
100    let value = checksum(block);
101
102    // Observe:
103    // 1. We know statically that our computed checksum is no more than MAX_CHECKSUM
104    // 2. We know that MAX_CHECKSUM is less than 0o777777 (262143)
105    //
106    // Therefore, we know that all possible checksums fit within 6 octal digits,
107    // and therefore we can always safely include two padding bytes.
108    //
109    // NOTE: the use of `\0 ` as the suffix is not specified by pax, but appears
110    // to be a convention across tar encoders.
111    debug_assert!(value <= MAX_CHECKSUM);
112    let _ = encode_octal_with_suffix(&mut block[CHECKSUM_RANGE], value, b"\0 ");
113}
114
115pub(crate) fn encode_octal(field: &mut [u8], value: u64) -> bool {
116    encode_octal_with_suffix(field, value, b"\0")
117}
118
119fn encode_octal_with_suffix(field: &mut [u8], value: u64, suffix: &[u8]) -> bool {
120    let Some(width) = field.len().checked_sub(suffix.len()) else {
121        return false;
122    };
123    if width == 0 {
124        return false;
125    }
126    field[width..].copy_from_slice(suffix);
127    encode_octal_digits(&mut field[..width], value)
128}
129
130fn encode_octal_digits(field: &mut [u8], mut value: u64) -> bool {
131    for byte in field.iter_mut().rev() {
132        *byte = b'0' + (value & 0o7) as u8;
133        value >>= 3;
134    }
135    value == 0
136}
137
138/// Parse an octal number from the given bytes.
139///
140/// Per pax, an octal number is a leading-zero filled sequence of octal characters
141/// (0-7), terminated by one or more NUL or space characters.
142pub(crate) fn parse_octal(bytes: &[u8]) -> Option<u64> {
143    let mut value = 0_u64;
144    let mut has_digits = false;
145    let mut terminated = false;
146    for byte in bytes {
147        match *byte {
148            b'0'..=b'7' if !terminated => {
149                value = value.checked_mul(8)?.checked_add(u64::from(*byte - b'0'))?;
150                has_digits = true;
151            }
152            0 | b' ' => terminated = true,
153            _ => return None,
154        }
155    }
156    (has_digits && terminated).then_some(value)
157}
158
159pub(crate) fn is_all_nul(bytes: &[u8]) -> bool {
160    bytes.iter().all(|byte| *byte == 0)
161}
162
163/// The encoding of a numeric header field.
164#[derive(Clone, Copy, Debug, Eq, PartialEq)]
165pub(crate) enum NumericFormat {
166    /// The pax octal encoding, as parsed by [`parse_octal`].
167    Octal,
168    /// The GNU octal or base-256 encoding, as parsed by [`parse_gnu_number`].
169    Gnu,
170}
171
172impl From<ArchiveFormat> for NumericFormat {
173    fn from(format: ArchiveFormat) -> Self {
174        match format {
175            ArchiveFormat::Pax => Self::Octal,
176            ArchiveFormat::Gnu => Self::Gnu,
177        }
178    }
179}
180
181impl NumericFormat {
182    /// Parses a numeric header field in this encoding.
183    pub(crate) fn parse(self, bytes: &[u8]) -> Option<u64> {
184        match self {
185            Self::Octal => parse_octal(bytes),
186            Self::Gnu => parse_gnu_number(bytes),
187        }
188    }
189}
190
191/// Parse a number according to the GNU tar rules.
192///
193/// This implements a subset of the GNU rules: negative numbers are rejected entirely,
194/// and we don't reject base256 encodings that *would* fit in the octal encoding.
195/// TODO: Consider rejecting these? The GNU spec describes base256 encodings that would
196/// fit in octal as "reserved for future use."
197fn parse_gnu_number(bytes: &[u8]) -> Option<u64> {
198    match bytes.first()? {
199        0x80 => bytes[1..].iter().try_fold(0_u64, |value, byte| {
200            value.checked_mul(256)?.checked_add(u64::from(*byte))
201        }),
202        // Negative encoding; reject for now. This would also be rejected by
203        // `parse_octal` but here is clearer.
204        0xff => None,
205        _ => parse_octal(bytes),
206    }
207}
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    #[test]
214    fn encodes_octal_values_that_fit_the_field() {
215        let mut field = [0xff; 4];
216        assert!(encode_octal(&mut field, 0o17));
217        assert_eq!(&field, b"017\0");
218        assert_eq!(parse_octal(&field), Some(0o17));
219
220        assert!(encode_octal(&mut field, 0o777));
221        assert_eq!(&field, b"777\0");
222        assert!(!encode_octal(&mut field, 0o1000));
223        assert!(!encode_octal(&mut [], 0));
224        assert!(!encode_octal(&mut [0], 0));
225    }
226
227    #[test]
228    fn parses_strict_octal_fields() {
229        for (field, expected) in [
230            // OK: leading zeroes.
231            (&b"000017 "[..], Some(0o17)),
232            (&b"0000000000000000000000000000017 "[..], Some(0o17)),
233            // OK: 0o17, null terminated.
234            (&b"17\0"[..], Some(0o17)),
235            // OK: 0o17, space terminated.
236            (&b"17 "[..], Some(0o17)),
237            // OK: 0o17, space terminated (trailing null ignored)
238            (&b"17 \0"[..], Some(0o17)),
239            // Invalid: empty
240            (&b""[..], None),
241            // Invalid: terminator only
242            (&b"\0"[..], None),
243            (&b" "[..], None),
244            // Invalid: no terminator
245            (&b"17"[..], None),
246            // Invalid: not in octal domain
247            (&b"18\0"[..], None),
248            // Invalid: not in octal domain, even after terminator
249            (&b"1\0\x32"[..], None),
250            // Invalid: octal after terminator.
251            (&b"1\0\x31"[..], None),
252            (&b"1 1"[..], None),
253            // Invalid: not in octal domain.
254            (&[0x80, 0][..], None),
255            // Invalid: overflows u64.
256            (&b"77777777777777777777777 "[..], None),
257            (&b"77777777777777777777777\0"[..], None),
258        ] {
259            assert_eq!(parse_octal(field), expected, "{field:?}");
260        }
261    }
262
263    #[test]
264    fn checksums_known_blocks() {
265        let zero_block = [0; crate::BLOCK_SIZE];
266        let mut x_typeflag_block = zero_block;
267        x_typeflag_block[TYPEFLAG_OFFSET] = b'x';
268        x_typeflag_block[CHECKSUM_RANGE].fill(0xff);
269        let maximum_block = [0xff; crate::BLOCK_SIZE];
270
271        for (name, mut block, expected) in [
272            ("zero block", zero_block, b"000400\0 "),
273            (
274                "x typeflag with junk checksum bytes",
275                x_typeflag_block,
276                b"000570\0 ",
277            ),
278            ("maximum block", maximum_block, b"373410\0 "),
279        ] {
280            assert_eq!(Some(checksum(&block)), parse_octal(expected), "{name}");
281            encode_checksum(&mut block);
282            assert_eq!(&block[CHECKSUM_RANGE], expected, "{name}");
283        }
284    }
285}