// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The 512-byte header block: where each field lives, and how the numbers in //! it are written. //! //! A tar archive is a sequence of 512-byte blocks. Each member starts with a //! header block, followed by its content rounded up to a whole number of //! blocks. Every field in the header is a fixed-width byte string; the //! numeric ones are octal text, except that GNU tar (and after it everyone //! else) marks a field whose high bit is set as a big-endian two's complement //! binary number instead, which is how a size of 8 GiB or more, or a date //! before 1970, gets written at all. const std = @import("std"); pub const block_len = 512; pub const Block = [block_len]u8; /// A field of the header: its offset and its width. pub const Field = struct { offset: usize, len: usize, pub fn get(f: Field, block: *const Block) []const u8 { return block[f.offset..][0..f.len]; } pub fn getMut(f: Field, block: *Block) []u8 { return block[f.offset..][0..f.len]; } }; pub const name: Field = .{ .offset = 0, .len = 100 }; pub const mode: Field = .{ .offset = 100, .len = 8 }; pub const uid: Field = .{ .offset = 108, .len = 8 }; pub const gid: Field = .{ .offset = 116, .len = 8 }; pub const size: Field = .{ .offset = 124, .len = 12 }; pub const mtime: Field = .{ .offset = 136, .len = 12 }; pub const chksum: Field = .{ .offset = 148, .len = 8 }; pub const typeflag_offset = 156; pub const linkname: Field = .{ .offset = 157, .len = 100 }; /// POSIX puts `"ustar\x00"` here and `"00"` in `version`; GNU tar writes the /// eight bytes `"ustar \x00"` across both. pub const magic: Field = .{ .offset = 257, .len = 6 }; pub const version: Field = .{ .offset = 263, .len = 2 }; pub const uname: Field = .{ .offset = 265, .len = 32 }; pub const gname: Field = .{ .offset = 297, .len = 32 }; pub const devmajor: Field = .{ .offset = 329, .len = 8 }; pub const devminor: Field = .{ .offset = 337, .len = 8 }; /// Only a POSIX header has a prefix. GNU tar keeps the access and change /// times in these bytes instead, so reading them as a prefix of a GNU /// header prepends a timestamp to the name. pub const prefix: Field = .{ .offset = 345, .len = 155 }; /// In a GNU sparse (`S`) header: nonzero when more sparse maps follow in /// blocks of their own. pub const gnu_sparse_is_extended_offset = 482; /// The same flag in each of those extension blocks. pub const gnu_sparse_ext_is_extended_offset = 504; pub const Typeflag = struct { pub const regular: u8 = '0'; /// What V7 tar wrote for a regular file, before there were other types. pub const regular_old: u8 = 0; pub const hard_link: u8 = '1'; pub const symbolic_link: u8 = '2'; pub const directory: u8 = '5'; /// Reserved by POSIX for high-performance files; everyone reads it as /// a regular one. pub const contiguous: u8 = '7'; pub const pax_extended: u8 = 'x'; pub const pax_global: u8 = 'g'; pub const gnu_long_name: u8 = 'L'; pub const gnu_long_link: u8 = 'K'; pub const gnu_sparse: u8 = 'S'; }; pub const Format = enum { /// No magic at all: the original seventh-edition layout. v7, /// `"ustar\x00"`, with a prefix field. posix, /// `"ustar \x00"`, without one. gnu, }; pub fn format(block: *const Block) Format { const m = block[magic.offset..][0..8]; if (std.mem.eql(u8, m[0..6], "ustar\x00")) return .posix; if (std.mem.eql(u8, m, "ustar \x00")) return .gnu; return .v7; } pub fn isZero(block: *const Block) bool { return std.mem.allEqual(u8, block, 0); } /// A string field, which ends at its first NUL or fills the field. pub fn string(field: []const u8) []const u8 { return field[0 .. std.mem.findScalar(u8, field, 0) orelse field.len]; } pub const NumberError = error{InvalidHeader}; /// Reads a numeric field as either octal text or GNU base-256. /// /// Octal text may be padded with leading spaces or zeros and ends at the /// first space or NUL; anything after that must also be a space or NUL. An /// entirely empty field reads as zero, which is what several old writers put /// in fields they had nothing for. pub fn parseNumber(comptime T: type, field: []const u8) NumberError!T { // Twelve bytes of base-256 is 96 bits; twelve octal digits is 36. // Either fits an i128 with room to spare, so the arithmetic below cannot // overflow and the range check is done once, at the end. std.debug.assert(field.len <= 12); var value: i128 = 0; if (field.len > 0 and field[0] & 0x80 != 0) { // The high bit marks base-256. What remains of the first byte is the // top of a two's complement number: 0x80 starts a positive one and // 0xff a negative one, whose sign bit is the byte's second bit. const first: u8 = field[0] & 0x7f; value = if (first & 0x40 != 0) @as(i128, first) - 0x80 else first; for (field[1..]) |b| value = value * 256 + b; } else { var i: usize = 0; while (i < field.len and field[i] == ' ') i += 1; while (i < field.len and field[i] >= '0' and field[i] <= '7') : (i += 1) { value = value * 8 + (field[i] - '0'); } for (field[i..]) |b| if (b != 0 and b != ' ') return error.InvalidHeader; } return std.math.cast(T, value) orelse error.InvalidHeader; } /// Writes `value` as zero-padded octal filling all but the last byte of /// the field, and a NUL in that last byte. Returns false if it does not fit. pub fn formatOctal(field: []u8, value: u64) bool { const digits = field.len - 1; if (digits < 22 and value >> @intCast(3 * digits) != 0) return false; var v = value; var i = digits; while (i > 0) { i -= 1; field[i] = '0' + @as(u8, @intCast(v & 7)); v >>= 3; } field[digits] = 0; return true; } /// Writes `value` as GNU base-256: big-endian two's complement across the /// whole field, with the high bit of the first byte set. The value must fit /// in one bit less than the field, which any `i64` or `u64` does in the /// twelve bytes of a size or time field. pub fn formatBase256(field: []u8, value: i128) void { std.debug.assert(field.len <= 16); std.debug.assert(std.math.log2_int_ceil(u128, @abs(value) + 1) < 8 * field.len - 1); var bytes: [16]u8 = undefined; std.mem.writeInt(i128, &bytes, value, .big); @memcpy(field, bytes[16 - field.len ..]); field[0] |= 0x80; } /// The largest value an octal field of `len` bytes holds. pub fn octalMax(len: usize) u64 { return (@as(u64, 1) << @intCast(3 * (len - 1))) - 1; } /// Computes the checksum both ways: as a sum of unsigned bytes, which is what /// POSIX specifies, and of signed ones, which is what some old writers on /// platforms with a signed `char` produced. The checksum field itself counts /// as eight spaces. pub fn checksums(block: *const Block) struct { unsigned: u64, signed: i64 } { var unsigned: u64 = 0; var signed: i64 = 0; for (block, 0..) |b, i| { const c = if (i >= chksum.offset and i < chksum.offset + chksum.len) ' ' else b; unsigned += c; signed += @as(i8, @bitCast(c)); } return .{ .unsigned = unsigned, .signed = signed }; } pub fn checksumMatches(block: *const Block) bool { const stored = parseNumber(i64, chksum.get(block)) catch return false; const sums = checksums(block); return stored == sums.unsigned or stored == sums.signed; } /// Fills in the checksum of an otherwise complete header: six octal digits, /// a NUL and a space, as every tar since V7 has written it. pub fn setChecksum(block: *Block) void { const field = chksum.getMut(block); const sum = checksums(block).unsigned; std.debug.assert(formatOctal(field[0..7], sum)); field[7] = ' '; } /// Splits a path that is too long for the name field into a prefix and a /// name at a `/`, the way a POSIX header allows. The `/` itself is in /// neither half. Returns null if there is no such split. pub fn splitName(path: []const u8) ?struct { prefix: []const u8, name: []const u8 } { if (path.len > prefix.len + 1 + name.len) return null; // The earliest slash that leaves a name short enough, then check the // prefix is too. Taking the earliest makes the prefix as short as it can // be, which is the only way it could fit. const start = path.len -| (name.len + 1); const slash = std.mem.findScalarPos(u8, path, start, '/') orelse return null; if (slash > prefix.len or slash == 0 or slash + 1 == path.len) return null; return .{ .prefix = path[0..slash], .name = path[slash + 1 ..] }; } const testing = std.testing; test parseNumber { try testing.expectEqual(0o644, try parseNumber(u32, "0000644\x00")); try testing.expectEqual(0o644, try parseNumber(u32, " 644 \x00")); try testing.expectEqual(0, try parseNumber(u32, "\x00\x00\x00\x00\x00\x00\x00\x00")); try testing.expectEqual(0, try parseNumber(u32, " ")); try testing.expectEqual(0o77777777777, try parseNumber(u64, "77777777777\x00")); try testing.expectEqual(0o777777777777, try parseNumber(u64, "777777777777")); try testing.expectError(error.InvalidHeader, parseNumber(u32, "0000648\x00")); try testing.expectError(error.InvalidHeader, parseNumber(u32, "12 34\x00\x00\x00")); // Too big for the type asked for is an error, not a truncation. try testing.expectError(error.InvalidHeader, parseNumber(u8, "0000400\x00")); } test "parseNumber base-256" { var field: [12]u8 = undefined; for ([_]i64{ 0, 1, 255, 1 << 33, std.math.maxInt(i64), -1, -86400, std.math.minInt(i64) }) |v| { formatBase256(&field, v); try testing.expectEqual(v, try parseNumber(i64, &field)); } formatBase256(&field, 1 << 40); try testing.expectEqual(1 << 40, try parseNumber(u64, &field)); formatBase256(&field, std.math.maxInt(u64)); try testing.expectEqual(std.math.maxInt(u64), try parseNumber(u64, &field)); formatBase256(&field, -1); try testing.expectError(error.InvalidHeader, parseNumber(u64, &field)); // Bigger than any i64: 0x80 followed by eleven 0xff bytes. @memset(&field, 0xff); field[0] = 0x80; try testing.expectError(error.InvalidHeader, parseNumber(i64, &field)); try testing.expectEqual((1 << 88) - 1, try parseNumber(u128, &field)); } test formatOctal { var field: [12]u8 = undefined; try testing.expect(formatOctal(&field, 0o17)); try testing.expectEqualStrings("00000000017\x00", &field); try testing.expect(formatOctal(&field, octalMax(12))); try testing.expectEqualStrings("77777777777\x00", &field); try testing.expect(!formatOctal(&field, octalMax(12) + 1)); var small: [8]u8 = undefined; try testing.expect(!formatOctal(&small, 0o10000000)); } test checksums { var block: Block = @splat(0); @memcpy(block[0..5], "hello"); setChecksum(&block); try testing.expect(checksumMatches(&block)); try testing.expectEqualStrings("\x20", block[chksum.offset + 7 ..][0..1]); // A header written by a tar that summed signed bytes. block[200] = 0xe9; const sums = checksums(&block); try testing.expect(sums.unsigned != @as(u64, @bitCast(sums.signed))); try testing.expect(formatOctal(chksum.getMut(&block)[0..7], @intCast(sums.signed))); try testing.expect(checksumMatches(&block)); block[300] = 1; try testing.expect(!checksumMatches(&block)); } test splitName { const a = "a" ** 100; try testing.expect(splitName(a) == null); try testing.expect(splitName("x/" ++ a ++ "b") == null); const s = splitName("dir/" ++ a).?; try testing.expectEqualStrings("dir", s.prefix); try testing.expectEqualStrings(a, s.name); const p = "p" ** 155; const t = splitName(p ++ "/" ++ a).?; try testing.expectEqualStrings(p, t.prefix); try testing.expect(splitName(p ++ "p/" ++ a) == null); // Several slashes: the prefix is kept as short as the name allows. const u = splitName("one/two/three/" ++ "n" ** 95).?; try testing.expectEqualStrings("one/two/three", u.prefix); try testing.expectEqualStrings("n" ** 95, u.name); const v = splitName("one/two/three/" ++ "n" ** 93).?; try testing.expectEqualStrings("one/two", v.prefix); try testing.expectEqualStrings("three/" ++ "n" ** 93, v.name); // A trailing slash would leave the name empty. try testing.expect(splitName("d" ** 101 ++ "/") == null); try testing.expect(splitName("/" ++ a) == null); } test format { var block: Block = @splat(0); try testing.expectEqual(Format.v7, format(&block)); @memcpy(block[magic.offset..][0..8], "ustar\x0000"); try testing.expectEqual(Format.posix, format(&block)); @memcpy(block[magic.offset..][0..8], "ustar \x00"); try testing.expectEqual(Format.gnu, format(&block)); }