- Zig 95%
- Nix 3%
- Shell 2%
zig-tar #
Reading and writing tar archives in Zig 0.16, over nothing but a
std.Io.Reader and a std.Io.Writer.
Nothing in it opens a file, allocates, or chooses an Io implementation:
the archive comes from a reader and goes to a writer that the caller made,
and the caller hands over a scratch buffer for the little that has to be
kept. Compression is out of scope. Put a decompressor's reader in front of
the iterator, or a compressor's writer behind the writer.
The API documentation is generated from
the doc comments, and is built with zig build docs and read locally with
zig build docs-serve.
Reading #
const tar = @import("tar");
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 => std.debug.print("{s} -> {s}\n", .{ entry.name, entry.link_name }),
}
}
next returns null at the end of the archive. Each entry carries its name,
kind, size, mode, modification time, link target and its own
*std.Io.Reader, which produces exactly the entry's content and then ends.
Everything in an entry is valid until the next call to next. An entry need
not be read, or read to the end: next skips whatever was left.
What next returns is a file, not a header. PAX extended headers and GNU
long name and long link members are folded into the member they describe.
Anything else — hard links, devices, FIFOs, GNU sparse files, PAX global
headers, PAX records the iterator does not interpret — is passed over and
reported to the diagnostics callback, which is the second argument:
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);
.ignore discards them. An archive that ends at a member boundary without
its two zero blocks is read to that point and reported as
missing_end_of_archive, since it is indistinguishable from a complete one
that lacks the marker. An archive cut off anywhere else is an error: in a
header, next returns error.TruncatedArchive; in a member's content, the
entry's reader returns error.ReadFailed and the iterator's err field says
error.TruncatedArchive. A truncated archive never reads as a short file.
The scratch buffer holds names too long for their header — from a PAX
record, a GNU long name, or a ustar prefix — and whatever the names leave is
the entry reader's buffer. It must be at least tar.Iterator.min_scratch_len
(1 KiB); a name that does not fit is error.NameTooLong.
The iterator must not be moved after the first next, since the entries'
readers point into it. Names are returned exactly as stored and are
untrusted: they may be absolute, contain .., or repeat. What to do about
that when extracting is the caller's decision.
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.
Writing #
var scratch: [4096]u8 = undefined;
var w: tar.Writer = .init(writer, &scratch);
try w.add("hello.txt", &content_reader, .{ .size = content_len, .mtime = now });
try w.add("docs/", null, .{ .kind = .directory });
try w.add("docs/latest", null, .{ .kind = .symbolic_link, .link_name = "v2" });
try w.finish();
try writer.flush();
A tar header records the size before the content, and a reader cannot say
how long it is, so add is told: it takes exactly options.size bytes from
the reader, and a reader that runs out first is error.ShortRead. Mode
defaults to 0o644, 0o755 or 0o777 by kind; owner and group are 0 with
no names. finish writes the end-of-archive marker and does not flush.
What is written is POSIX ustar. When a member does not fit a ustar header —
a name that cannot be split between the prefix and name fields, a link
target over 100 bytes, a size of 8 GiB or more, a time before 1970 or after
2242 — a PAX extended header carrying the real value goes ahead of it, and
oversized numbers are also written in GNU base-256, so a reader that knows
GNU tar but not PAX still gets them right. The PAX records are assembled in
the scratch buffer, which therefore needs a little more than the name and
link target lengths; error.ScratchTooSmall says it did not.
Where this lives #
The repository lives in three places that carry the same history. The Forgejo instance at https://git.jcollie.dev/jeff/zig-tar is the web-visible one:
$ git clone https://git.jcollie.dev/jeff/zig-tar.git
it is mirrored on Tangled at https://tangled.org/jcollie.dev/zig-tar, and it is also on the Radicle network, where the repository's identifier is
rad:z2ARp77vvw5qEhszgR3QhCwKy63rg
and rad clone rad:z2ARp77vvw5qEhszgR3QhCwKy63rg fetches it from any node that
seeds it. Any of the three is the whole project.
Adding it to a project #
$ zig fetch --save git+https://git.jcollie.dev/jeff/zig-tar.git
const tar = b.dependency("zig_tar", .{ .target = target }).module("tar");
exe.root_module.addImport("tar", tar);
Tests #
$ nix develop
$ zig build test --summary all
$ zig build check # everything, compiled, nothing run
$ zig build fuzz-run -- --seconds 60 # a minute of each fuzz target
- Unit tests beside the code cover the header's octal and base-256 fields, both kinds of checksum, the prefix/name split, PAX record lengths (which count their own digits), and write-then-read round trips of long names, links, dates either side of the octal range, and entries skipped or read partway.
- Interoperability, in
tests/interop.zig: one small tree archived by GNU tar asgnu,posix,ustarandv7, and by bsdtar aspax,ustarandgnutar, read back entry by entry, including the hard link and FIFO that must be reported rather than returned; every one of those archives cut at every byte, which must give an error or a missing end marker and never a panic; and round trips throughstd.tarin both directions.tests/data/make-fixtures.shregenerates the archives, reproducibly, from the devshell. - Fuzzing, in
tests/fuzz.zig: arbitrary archives, whose entries must each produce exactly their size or report truncation; the same with every header's checksum put right first, which is what lets mutations reach the numeric fields and the PAX parser; and members made up from the input, which must round-trip exactly or be refused. Zig 0.16.0's own fuzzer cannot run them usefully, sotools/fuzz.zigdoes, mutating the fixtures above;flake.nixexplains the toolchain patch involved.
License #
MIT. The project follows REUSE; reuse lint checks
it.
References cited #
- IEEE and The Open Group. pax — portable archive interchange. IEEE Std 1003.1-2024, The Open Group Base Specifications Issue 8, 2024. https://pubs.opengroup.org/onlinepubs/9799919799/utilities/pax.html. The ustar and pax interchange formats, the PAX record syntax, and which member types store no content.
- Free Software Foundation. "Basic Tar Format." GNU tar: an archiver tool.
https://www.gnu.org/software/tar/manual/html_node/Standard.html. GNU's
header layout, the
LandKlong-name members, sparse headers and the base-256 numeric extension. - libarchive project. "tar(5): format of tape archive files." libarchive. https://github.com/libarchive/libarchive/blob/master/libarchive/tar.5. The history of the variants and how each is recognized.
- The Go Authors. archive/tar. Go standard library. https://github.com/golang/go/tree/master/src/archive/tar. Its reader likewise reads directories, symbolic links, devices and FIFOs as having no content; unlike this one, it reads hard links that way too.