// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reads and writes tar archives over `std.Io.Reader` and `std.Io.Writer`. //! //! Nothing here opens a file, allocates, or chooses an `Io`: the archive //! comes from a reader and goes to a writer that the caller made, and the //! caller provides a scratch buffer for the little that has to be kept. //! Compression is out of scope; put a decompressor's reader in front of an //! iterator, or a compressor's writer behind a `Writer`. //! //! Reading: //! //! ```zig //! var scratch: [16 * 1024]u8 = undefined; //! var it = tar.iterator(reader, .ignore, &scratch); //! while (try it.next()) |entry| { //! switch (entry.kind) { //! .file => _ = try entry.reader.streamRemaining(out), //! .directory, .symbolic_link => {}, //! } //! } //! ``` //! //! Writing: //! //! ```zig //! var scratch: [4096]u8 = undefined; //! var w: tar.Writer = .init(writer, &scratch); //! try w.add("hello.txt", &content, .{ .size = content_len, .mtime = now }); //! try w.finish(); //! ``` //! //! Formats read: POSIX ustar, PAX extended headers, GNU tar's long names //! and base-256 numbers, and the seventh-edition layout before any of them. //! Format written: ustar, with a PAX extended header wherever ustar runs //! out of room. const std = @import("std"); const Io = std.Io; pub const Iterator = @import("Iterator.zig"); pub const Writer = @import("Writer.zig"); /// The kinds of member this library reads and writes. pub const Kind = enum { file, directory, symbolic_link, }; /// Something about the archive that did not stop it being read, and that /// the caller may want to know. Slices in it are valid only for the /// duration of the callback. pub const Diagnostic = union(enum) { /// A member of a type the iterator does not return — a hard link, a /// device, a FIFO, a GNU sparse file, or something unknown — was /// skipped along with its content. unsupported_entry: struct { name: []const u8, /// The header's typeflag byte, `'1'` for a hard link and so on. typeflag: u8, }, /// A PAX extended header held a record the iterator does not interpret: /// ownership, access times, extended attributes, vendor keys. ignored_pax_record: struct { key: []const u8, value_len: u64, }, /// A PAX global extended header was skipped. Its records would apply to /// every member after it; none of them are applied. ignored_global_header, /// The archive ended without the two zero blocks that should close it. /// Everything before that was read, so the archive may be complete, or /// may have been cut off at a member boundary. missing_end_of_archive, }; /// Where an iterator sends what it would otherwise have to either ignore /// silently or fail on. It is a context and a function, the usual Zig /// shape for a callback: /// /// ```zig /// const Counter = struct { /// unsupported: usize = 0, /// fn report(ctx: ?*anyopaque, d: tar.Diagnostic) void { /// const self: *@This() = @ptrCast(@alignCast(ctx.?)); /// if (d == .unsupported_entry) self.unsupported += 1; /// } /// }; /// var counter: Counter = .{}; /// var it = tar.iterator(reader, .{ .context = &counter, .report = Counter.report }, &scratch); /// ``` pub const Diagnostics = struct { context: ?*anyopaque = null, report: *const fn (context: ?*anyopaque, diagnostic: Diagnostic) void, /// Discards every diagnostic. pub const ignore: Diagnostics = .{ .report = ignoreReport }; fn ignoreReport(context: ?*anyopaque, diagnostic: Diagnostic) void { _ = context; _ = diagnostic; } }; /// Starts reading the archive in `reader`. /// /// `scratch` holds the names of the current entry when they are too long /// for its header, and whatever of it the names leave over becomes the /// buffer of the entry's reader. It must be at least /// `Iterator.min_scratch_len` bytes; a name longer than it can hold is /// `error.NameTooLong`. Twice `std.fs.max_path_bytes` plus a few kilobytes /// reads anything a file system could have produced. /// /// The returned iterator must not be moved once `next` has been called. pub fn iterator(reader: *Io.Reader, diagnostics: Diagnostics, scratch: []u8) Iterator { return .init(reader, diagnostics, scratch); } test { _ = @import("header.zig"); _ = @import("pax.zig"); _ = Iterator; _ = Writer; } const testing = std.testing; const header = @import("header.zig"); /// A member to write and then expect back. const Member = struct { name: []const u8, kind: Kind = .file, content: []const u8 = "", mode: ?u32 = null, mtime: i64 = 0, link_name: []const u8 = "", }; fn writeArchive(out: *Io.Writer, members: []const Member) !void { var scratch: [4096]u8 = undefined; var w: Writer = .init(out, &scratch); for (members) |m| { var r: Io.Reader = .fixed(m.content); try w.add(m.name, &r, .{ .kind = m.kind, .size = m.content.len, .mode = m.mode, .mtime = m.mtime, .link_name = m.link_name, }); } try w.finish(); } const Recorder = struct { count: usize = 0, last: ?std.meta.Tag(Diagnostic) = null, fn report(ctx: ?*anyopaque, d: Diagnostic) void { const self: *Recorder = @ptrCast(@alignCast(ctx.?)); self.count += 1; self.last = d; } fn diagnostics(self: *Recorder) Diagnostics { return .{ .context = self, .report = report }; } }; fn expectArchive(archive: []const u8, members: []const Member) !void { var scratch: [4096]u8 = undefined; var r: Io.Reader = .fixed(archive); var recorder: Recorder = .{}; var it = iterator(&r, recorder.diagnostics(), &scratch); for (members) |m| { const e = (try it.next()).?; try testing.expectEqualStrings(m.name, e.name); try testing.expectEqual(m.kind, e.kind); try testing.expectEqualStrings(m.link_name, e.link_name); try testing.expectEqual(m.mtime, e.mtime); try testing.expectEqual(m.content.len, e.size); if (m.mode) |mode| try testing.expectEqual(mode, e.mode); var got: [2048]u8 = undefined; var sink: Io.Writer = .fixed(&got); const n = try e.reader.streamRemaining(&sink); try testing.expectEqualStrings(m.content, got[0..n]); } try testing.expectEqual(null, try it.next()); try testing.expectEqual(null, try it.next()); try testing.expectEqual(0, recorder.count); try testing.expectEqual(0, r.bufferedLen()); } fn roundTrip(members: []const Member) !void { var buf: [64 * 1024]u8 = undefined; var out: Io.Writer = .fixed(&buf); try writeArchive(&out, members); try testing.expectEqual(0, out.end % header.block_len); try expectArchive(out.buffered(), members); } test "round trip: the ordinary things" { try roundTrip(&.{ .{ .name = "hello.txt", .content = "Hello, world!\n", .mtime = 1700000000 }, .{ .name = "empty", .mode = 0o600 }, .{ .name = "dir/", .kind = .directory, .mode = 0o755 }, .{ .name = "dir/link", .kind = .symbolic_link, .link_name = "../hello.txt", .mode = 0o777 }, .{ .name = "exactly-a-block", .content = "b" ** 512 }, .{ .name = "one-over", .content = "c" ** 513 }, }); } test "round trip: an empty archive" { try roundTrip(&.{}); } test "round trip: long names" { const long = "d" ** 150 ++ "/" ++ "f" ** 99; const unsplittable = "x" ** 300; const exactly_100 = "e" ** 100; try roundTrip(&.{ .{ .name = exactly_100, .content = "100" }, .{ .name = long, .content = "split into prefix and name" }, .{ .name = unsplittable, .content = "in a PAX header" }, .{ .name = "l", .kind = .symbolic_link, .link_name = "t" ** 101 }, .{ .name = unsplittable ++ "/", .kind = .directory }, }); } test "round trip: long names are in the places they should be" { var buf: [8192]u8 = undefined; var out: Io.Writer = .fixed(&buf); const long = "d" ** 150 ++ "/" ++ "f" ** 99; try writeArchive(&out, &.{.{ .name = long }}); // Split, not PAX: exactly one header and then the end. try testing.expectEqual(3 * header.block_len, out.end); const block = buf[0..header.block_len]; try testing.expectEqualStrings("d" ** 150, header.string(header.prefix.get(block))); try testing.expectEqualStrings("f" ** 99, header.string(header.name.get(block))); } test "round trip: times outside the octal field" { try roundTrip(&.{ .{ .name = "before-1970", .mtime = -86400 }, .{ .name = "far-future", .mtime = 1 << 40 }, .{ .name = "minimum", .mtime = std.math.minInt(i64) }, .{ .name = "maximum", .mtime = std.math.maxInt(i64) }, .{ .name = "last-octal", .mtime = @intCast(header.octalMax(12)) }, }); } test "a size too big for octal gets PAX and base-256" { var buf: [4096]u8 = undefined; var out: Io.Writer = .fixed(&buf); var scratch: [4096]u8 = undefined; var w: Writer = .init(&out, &scratch); // Only the headers: the content would be 8 GiB, so the test stops // before writing it by handing over an empty reader and catching the // short read. var empty: Io.Reader = .fixed(""); const size: u64 = header.octalMax(12) + 1; try testing.expectError(error.ShortRead, w.add("big", &empty, .{ .size = size })); const pax_block = buf[0..header.block_len]; try testing.expectEqual('x', pax_block[header.typeflag_offset]); try testing.expectEqualStrings("PaxHeaders/big", header.string(header.name.get(pax_block))); const records = buf[header.block_len..][0..19]; try testing.expectEqualStrings("19 size=8589934592\n", records); const block = buf[2 * header.block_len ..][0..header.block_len]; try testing.expect(header.checksumMatches(block)); try testing.expectEqual(size, try header.parseNumber(u64, header.size.get(block))); // And read back, the entry says so, then finds the archive truncated. var r: Io.Reader = .fixed(out.buffered()); var it = iterator(&r, .ignore, &scratch); const e = (try it.next()).?; try testing.expectEqual(size, e.size); try testing.expectError(error.TruncatedArchive, it.next()); } test "entries skipped or read partway" { var buf: [16 * 1024]u8 = undefined; var out: Io.Writer = .fixed(&buf); try writeArchive(&out, &.{ .{ .name = "a", .content = "A" ** 1000 }, .{ .name = "b", .content = "B" ** 700 }, .{ .name = "c", .content = "C" ** 3 }, }); var scratch: [1024]u8 = undefined; var r: Io.Reader = .fixed(out.buffered()); var it = iterator(&r, .ignore, &scratch); _ = (try it.next()).?; // not read at all const b = (try it.next()).?; try testing.expectEqual('B', try b.reader.takeByte()); try testing.expectEqualStrings("BBBB", try b.reader.take(4)); const c = (try it.next()).?; try testing.expectEqualStrings("c", c.name); try testing.expectEqualStrings("CCC", try c.reader.take(3)); try testing.expectError(error.EndOfStream, c.reader.takeByte()); try testing.expectEqual(null, try it.next()); } test "writer rejects what it cannot write" { var buf: [4096]u8 = undefined; var out: Io.Writer = .fixed(&buf); var scratch: [4096]u8 = undefined; var w: Writer = .init(&out, &scratch); try testing.expectError(error.InvalidName, w.add("", null, .{})); try testing.expectError(error.InvalidName, w.add("a\x00b", null, .{})); try testing.expectError(error.InvalidName, w.add("l", null, .{ .kind = .symbolic_link })); try testing.expectError(error.InvalidOptions, w.add("d", null, .{ .kind = .directory, .size = 1 })); try testing.expectError(error.InvalidOptions, w.add("f", null, .{ .size = 1 })); try testing.expectError(error.InvalidOptions, w.add("f", null, .{ .link_name = "x" })); try testing.expectError(error.InvalidOptions, w.add("f", null, .{ .mode = 0o10000000 })); var small: [64]u8 = undefined; var w2: Writer = .init(&out, &small); try testing.expectError(error.ScratchTooSmall, w2.add("x" ** 300, null, .{})); // Nothing was written for any of them. try testing.expectEqual(0, out.end); } test "a truncated archive is an error, never a short file" { var buf: [8192]u8 = undefined; var out: Io.Writer = .fixed(&buf); try writeArchive(&out, &.{ .{ .name = "x" ** 300, .content = "first" }, .{ .name = "second", .content = "S" ** 600 }, }); const archive = out.buffered(); // Between members, a cut archive looks exactly like a complete one // missing its end marker, and that is what it is reported as. Anywhere // else it is an error. const boundaries = [_]usize{ 4 * header.block_len, archive.len - 2 * header.block_len }; for (1..archive.len - 2 * header.block_len + 1) |cut| { var recorder: Recorder = .{}; const result = readAll(archive[0..cut], recorder.diagnostics()); if (std.mem.findScalar(usize, &boundaries, cut) != null) { try result; try testing.expectEqual(.missing_end_of_archive, recorder.last.?); } else if (result) { std.debug.print("cut at {d} of {d} read cleanly\n", .{ cut, archive.len }); return error.TestUnexpectedResult; } else |_| {} } } /// Reads every entry of an archive to the end. fn readAll(archive: []const u8, diagnostics: Diagnostics) !void { var scratch: [1024]u8 = undefined; var r: Io.Reader = .fixed(archive); var it = iterator(&r, diagnostics, &scratch); while (try it.next()) |e| { var sink: Io.Writer.Discarding = .init(&.{}); _ = e.reader.streamRemaining(&sink.writer) catch |err| { try testing.expectEqual(error.TruncatedArchive, it.err.?); return err; }; } } test "diagnostics" { // A hard link and a FIFO between two files, written by hand, then a // global header and an unknown PAX key. var buf: [8192]u8 = undefined; var out: Io.Writer = .fixed(&buf); var scratch: [4096]u8 = undefined; var w: Writer = .init(&out, &scratch); var r0: Io.Reader = .fixed("one"); try w.add("one", &r0, .{ .size = 3 }); try writeRaw(&out, "hard", '1', "linkdata", 0); try writeRaw(&out, "hard-ustar", '1', "", 0); // A FIFO's size field is ignored, and no content follows it. try writeRaw(&out, "fifo", '6', "", 99); try writeRaw(&out, "global", 'g', "17 comment=hello\n", 0); try writeRaw(&out, "pax", 'x', "15 uname=alice\n", 0); var r1: Io.Reader = .fixed("two"); try w.add("two", &r1, .{ .size = 3 }); // No end marker. const Log = struct { kinds: [8]std.meta.Tag(Diagnostic) = undefined, len: usize = 0, fn report(ctx: ?*anyopaque, d: Diagnostic) void { const self: *@This() = @ptrCast(@alignCast(ctx.?)); switch (d) { .unsupported_entry => |u| std.debug.assert(u.typeflag == '1' or u.typeflag == '6'), .ignored_pax_record => |p| std.debug.assert(std.mem.eql(u8, p.key, "uname") and p.value_len == 5), else => {}, } self.kinds[self.len] = d; self.len += 1; } }; var log: Log = .{}; var r: Io.Reader = .fixed(out.buffered()); var it = iterator(&r, .{ .context = &log, .report = Log.report }, &scratch); try testing.expectEqualStrings("one", (try it.next()).?.name); try testing.expectEqualStrings("two", (try it.next()).?.name); try testing.expectEqual(null, try it.next()); try testing.expectEqualSlices(std.meta.Tag(Diagnostic), &.{ .unsupported_entry, .unsupported_entry, .unsupported_entry, .ignored_global_header, .ignored_pax_record, .missing_end_of_archive, }, log.kinds[0..log.len]); } /// Writes a member with an arbitrary typeflag and content. fn writeRaw(out: *Io.Writer, name: []const u8, typeflag: u8, content: []const u8, size_field: u64) !void { var block: header.Block = @splat(0); @memcpy(header.name.getMut(&block)[0..name.len], name); _ = header.formatOctal(header.mode.getMut(&block), 0o644); _ = header.formatOctal(header.size.getMut(&block), if (content.len > 0) content.len else size_field); block[header.typeflag_offset] = typeflag; @memcpy(header.magic.getMut(&block), "ustar\x00"); @memcpy(header.version.getMut(&block), "00"); header.setChecksum(&block); try out.writeAll(&block); try out.writeAll(content); try out.splatByteAll(0, (header.block_len - content.len % header.block_len) % header.block_len); } test "bad checksum" { var buf: [4096]u8 = undefined; var out: Io.Writer = .fixed(&buf); try writeArchive(&out, &.{.{ .name = "a" }}); buf[0] = 'b'; var scratch: [1024]u8 = undefined; var r: Io.Reader = .fixed(out.buffered()); var it = iterator(&r, .ignore, &scratch); try testing.expectError(error.BadChecksum, it.next()); } test "a name longer than the scratch buffer" { var buf: [8192]u8 = undefined; var out: Io.Writer = .fixed(&buf); try writeArchive(&out, &.{.{ .name = "n" ** 600 }}); var scratch: [1024]u8 = undefined; var r: Io.Reader = .fixed(out.buffered()); var it = iterator(&r, .ignore, &scratch); try testing.expectError(error.NameTooLong, it.next()); }