// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Writes a tar archive one member at a time. //! //! ```zig //! var w: tar.Writer = .init(writer, &scratch); //! try w.add("hello.txt", &content_reader, .{ .size = content_len }); //! try w.add("docs", null, .{ .kind = .directory }); //! try w.finish(); //! try writer.flush(); //! ``` //! //! What is written is a POSIX ustar archive. When something about a member //! does not fit a ustar header — a name that cannot be split into the //! header's prefix and name fields, a link target over 100 bytes, a size of //! 8 GiB or more, a date before 1970 or after 2242 — a PAX extended header is //! written ahead of it carrying the real value. Oversized numbers are also //! written into the header itself in GNU's base-256 form, so that a reader //! that knows GNU tar but not PAX still gets them right. //! //! Every member is owned by uid and gid 0 with no user or group name. const std = @import("std"); const Io = std.Io; const root = @import("root.zig"); const header = @import("header.zig"); const pax = @import("pax.zig"); const Writer = @This(); writer: *Io.Writer, /// Where PAX extended headers are assembled. It has to hold every record /// one member needs: a little over the length of the name and the link /// target, plus about eighty bytes. scratch: []u8, pub const Options = struct { kind: root.Kind = .file, /// The number of bytes the reader will supply. It must be zero for a /// directory or a symbolic link. size: u64 = 0, /// Defaults to `0o644` for a file, `0o755` for a directory and `0o777` /// for a symbolic link. At most `0o7777777`, which is what the field /// holds. mode: ?u32 = null, /// Seconds since the Unix epoch. mtime: i64 = 0, /// The target of a symbolic link. Required for one, and must be empty /// for anything else. link_name: []const u8 = "", }; pub const Error = error{ /// The underlying writer failed; see its implementation for why. WriteFailed, /// The content reader failed; see its implementation for why. ReadFailed, /// The content reader ended before `size` bytes. The archive now holds /// a partial member and cannot be finished. ShortRead, /// The name or link target is empty where it must not be, or contains /// a NUL. InvalidName, /// The PAX records this member needs do not fit the scratch buffer. ScratchTooSmall, /// The options contradict each other, or the mode is too large. InvalidOptions, }; pub fn init(writer: *Io.Writer, scratch: []u8) Writer { return .{ .writer = writer, .scratch = scratch }; } /// Adds one member to the archive. /// /// For a file, `reader` supplies its content: exactly `options.size` /// bytes are taken from it and nothing more, whatever may follow. For a /// directory or a symbolic link it is not used and may be null. /// /// A directory's name is written as given; tar implementations /// conventionally end one with a slash. pub fn add(w: *Writer, name: []const u8, reader: ?*Io.Reader, options: Options) Error!void { if (name.len == 0 or std.mem.findScalar(u8, name, 0) != null) return error.InvalidName; if (std.mem.findScalar(u8, options.link_name, 0) != null) return error.InvalidName; switch (options.kind) { .file => { if (options.link_name.len != 0) return error.InvalidOptions; if (options.size != 0 and reader == null) return error.InvalidOptions; }, .directory => { if (options.link_name.len != 0 or options.size != 0) return error.InvalidOptions; }, .symbolic_link => { if (options.link_name.len == 0) return error.InvalidName; if (options.size != 0) return error.InvalidOptions; }, } const mode: u32 = options.mode orelse switch (options.kind) { .file => 0o644, .directory => 0o755, .symbolic_link => 0o777, }; if (mode > header.octalMax(header.mode.len)) return error.InvalidOptions; var block: header.Block = @splat(0); var records_len: usize = 0; if (name.len <= header.name.len) { @memcpy(header.name.getMut(&block)[0..name.len], name); } else if (header.splitName(name)) |split| { @memcpy(header.prefix.getMut(&block)[0..split.prefix.len], split.prefix); @memcpy(header.name.getMut(&block)[0..split.name.len], split.name); } else { // Something for a reader that ignores the PAX header to go on. @memcpy(header.name.getMut(&block), name[0..header.name.len]); records_len += try w.record(records_len, pax.key_path, name); } const link_name = options.link_name; const link_len = @min(link_name.len, header.linkname.len); @memcpy(header.linkname.getMut(&block)[0..link_len], link_name[0..link_len]); if (link_name.len > header.linkname.len) { records_len += try w.record(records_len, pax.key_linkpath, link_name); } if (!header.formatOctal(header.size.getMut(&block), options.size)) { header.formatBase256(header.size.getMut(&block), options.size); var buf: [20]u8 = undefined; const value = std.fmt.bufPrint(&buf, "{d}", .{options.size}) catch unreachable; records_len += try w.record(records_len, pax.key_size, value); } if (options.mtime < 0 or !header.formatOctal(header.mtime.getMut(&block), @intCast(options.mtime))) { header.formatBase256(header.mtime.getMut(&block), options.mtime); var buf: [20]u8 = undefined; const value = std.fmt.bufPrint(&buf, "{d}", .{options.mtime}) catch unreachable; records_len += try w.record(records_len, pax.key_mtime, value); } std.debug.assert(header.formatOctal(header.mode.getMut(&block), mode)); block[header.typeflag_offset] = switch (options.kind) { .file => header.Typeflag.regular, .directory => header.Typeflag.directory, .symbolic_link => header.Typeflag.symbolic_link, }; fillCommon(&block); if (records_len > 0) try w.writePaxHeader(name, options.mtime, w.scratch[0..records_len]); try w.writer.writeAll(&block); if (options.kind == .file and options.size > 0) { reader.?.streamExact64(w.writer, options.size) catch |err| return switch (err) { error.EndOfStream => error.ShortRead, error.ReadFailed => error.ReadFailed, error.WriteFailed => error.WriteFailed, }; try w.pad(options.size); } } /// Writes the end-of-archive marker, two zero blocks. The writer is not /// flushed; that is left to whoever owns it. pub fn finish(w: *Writer) Io.Writer.Error!void { try w.writer.splatByteAll(0, 2 * header.block_len); } /// Appends a PAX record to those in the scratch buffer, which already /// holds `at` bytes of them. fn record(w: *Writer, at: usize, key: []const u8, value: []const u8) Error!usize { return pax.writeRecord(w.scratch[at..], key, value) orelse error.ScratchTooSmall; } /// Writes a PAX extended header carrying `records` for the member `name`. fn writePaxHeader(w: *Writer, name: []const u8, mtime: i64, records: []const u8) Error!void { var block: header.Block = @splat(0); // The header's own name is never used for anything, but it is what an // implementation that does not understand PAX extracts it as. This is // the shape GNU tar and bsdtar give it, minus the process ID. const dir_name = "PaxHeaders/"; const trimmed = std.mem.trimEnd(u8, name, "/"); const base = trimmed[if (std.mem.findScalarLast(u8, trimmed, '/')) |i| i + 1 else 0..]; const base_len = @min(base.len, header.name.len - dir_name.len); const name_field = header.name.getMut(&block); @memcpy(name_field[0..dir_name.len], dir_name); @memcpy(name_field[dir_name.len..][0..base_len], base[0..base_len]); std.debug.assert(header.formatOctal(header.mode.getMut(&block), 0o644)); std.debug.assert(header.formatOctal(header.size.getMut(&block), records.len)); const clamped = std.math.clamp(mtime, 0, header.octalMax(header.mtime.len)); std.debug.assert(header.formatOctal(header.mtime.getMut(&block), @intCast(clamped))); block[header.typeflag_offset] = header.Typeflag.pax_extended; fillCommon(&block); try w.writer.writeAll(&block); try w.writer.writeAll(records); try w.pad(records.len); } /// The fields every header written here has in common, and the checksum, /// which has to come last. fn fillCommon(block: *header.Block) void { std.debug.assert(header.formatOctal(header.uid.getMut(block), 0)); std.debug.assert(header.formatOctal(header.gid.getMut(block), 0)); std.debug.assert(header.formatOctal(header.devmajor.getMut(block), 0)); std.debug.assert(header.formatOctal(header.devminor.getMut(block), 0)); @memcpy(header.magic.getMut(block), "ustar\x00"); @memcpy(header.version.getMut(block), "00"); header.setChecksum(block); } fn pad(w: *Writer, len: u64) Io.Writer.Error!void { const rem: usize = @intCast(len % header.block_len); if (rem != 0) try w.writer.splatByteAll(0, header.block_len - rem); }