// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reads the members of a tar archive one at a time. //! //! ```zig //! var it = tar.iterator(reader, .ignore, &scratch); //! while (try it.next()) |entry| { //! // entry.name, entry.kind, and entry.reader, which produces exactly //! // entry.size bytes and then ends. //! } //! ``` //! //! 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, and never seen on their own. Members of a kind the iterator //! does not return — hard links, devices, FIFOs, sparse files — are passed //! over and reported to the diagnostics callback. //! //! The iterator holds the `Io.Reader` each entry hands out, so it must stay //! where it is while an entry is in use: keep it in a `var` and do not copy //! it. The same is true of `Io.File.Reader`, for the same reason. //! //! Names are returned exactly as the archive holds them. They are untrusted //! input: they may be absolute, may contain `..`, and may name the same path //! twice. Deciding what to do with that is the caller's job. const std = @import("std"); const Io = std.Io; const root = @import("root.zig"); const header = @import("header.zig"); const pax = @import("pax.zig"); const Iterator = @This(); /// The smallest scratch buffer `init` accepts. pub const min_scratch_len = 1024; /// How much of the scratch buffer is always left over for the entry /// reader's buffer, however long the names are. Names may use everything /// else. const reader_reserve = 512; reader: *Io.Reader, diagnostics: root.Diagnostics, scratch: []u8, /// The header block most recently read. Names that fit the header are /// returned as slices of it rather than copied. block: header.Block = undefined, /// Bytes of the current entry's content not yet taken from `reader`. Bytes /// in `entry_reader`'s buffer have already been taken and are not counted. remaining: u64 = 0, /// Zero bytes after the content, up to the end of its last block. padding: usize = 0, /// How much of the front of `scratch` the current entry's names occupy. used: usize = 0, /// Set once the end of the archive has been read. done: bool = false, /// Why an entry's reader returned `error.ReadFailed`, when the reason was /// the archive rather than `reader`. When this is null after a /// `ReadFailed`, the underlying reader failed and has its own diagnostics. err: ?Error = null, entry_reader: Io.Reader, pub const Error = error{ /// The underlying reader failed; see its implementation for why. ReadFailed, /// The archive ended in the middle of a header or a member's content. TruncatedArchive, /// A header's checksum does not match its contents. BadChecksum, /// A numeric header field is malformed or out of range. InvalidHeader, /// A PAX extended header is malformed. InvalidPaxRecord, /// A name, link target or PAX key does not fit the scratch buffer. NameTooLong, }; /// One file, directory or symbolic link in the archive. Everything in it, /// including the reader, is valid until the next call to `next`. pub const Entry = struct { kind: root.Kind, name: []const u8, /// The target of a symbolic link; empty for anything else. link_name: []const u8, /// The content length: zero for anything but a file. size: u64, /// Permission bits and whatever else the archive stored in the mode /// field, which is usually `0o7777` at most. mode: u32, /// Modification time in seconds since the Unix epoch. mtime: i64, /// Produces exactly `size` bytes and then `error.EndOfStream`. It need /// not be read to the end: `next` skips whatever is left. /// /// If the archive is cut short partway through the content, this /// returns `error.ReadFailed` and sets the iterator's `err` to /// `error.TruncatedArchive`, so that a truncated archive can never pass /// for a short file. reader: *Io.Reader, }; /// See `root.iterator`. pub fn init(reader: *Io.Reader, diagnostics: root.Diagnostics, scratch: []u8) Iterator { std.debug.assert(scratch.len >= min_scratch_len); return .{ .reader = reader, .diagnostics = diagnostics, .scratch = scratch, .entry_reader = .{ .vtable = &.{ .stream = stream, .discard = discard }, .buffer = &.{}, .seek = 0, .end = 0, }, }; } /// Overrides for the next member, collected from PAX and GNU headers. const Pending = struct { name: ?[]const u8 = null, link_name: ?[]const u8 = null, size: ?u64 = null, mtime: ?i64 = null, }; /// Returns the next file, directory or symbolic link, or null at the end /// of the archive. /// /// Anything not read from the previous entry's reader is skipped first. /// Once this has returned an error the iterator should not be used again. pub fn next(it: *Iterator) Error!?Entry { if (it.done) return null; try it.skip(it.remaining); try it.skip(it.padding); it.remaining = 0; it.padding = 0; it.used = 0; it.entry_reader.buffer = &.{}; it.entry_reader.seek = 0; it.entry_reader.end = 0; var pending: Pending = .{}; // Whether a PAX or GNU header has been read that describes a member not // yet seen. The archive cannot properly end until it has been. var describing = false; while (true) { const n = it.reader.readSliceShort(&it.block) catch return error.ReadFailed; if (n == 0) { if (describing) return error.TruncatedArchive; // A clean end at a block boundary, but without the end marker. it.done = true; it.report(.missing_end_of_archive); return null; } if (n < header.block_len) return error.TruncatedArchive; if (header.isZero(&it.block)) { if (describing) return error.TruncatedArchive; try it.endOfArchive(); return null; } if (!header.checksumMatches(&it.block)) return error.BadChecksum; const typeflag = it.block[header.typeflag_offset]; const header_size = try header.parseNumber(u64, header.size.get(&it.block)); describing = switch (typeflag) { header.Typeflag.pax_extended, header.Typeflag.gnu_long_name, header.Typeflag.gnu_long_link, => true, else => false, }; switch (typeflag) { header.Typeflag.pax_extended => { try it.readPax(header_size, &pending); }, header.Typeflag.gnu_long_name => { pending.name = try it.readLongName(header_size); }, header.Typeflag.gnu_long_link => { pending.link_name = try it.readLongName(header_size); }, header.Typeflag.pax_global => { it.report(.ignored_global_header); try it.skip(header_size); try it.skip(blockPadding(header_size)); }, header.Typeflag.regular, header.Typeflag.regular_old, header.Typeflag.contiguous, header.Typeflag.directory, header.Typeflag.symbolic_link, => return try it.entry(typeflag, header_size, pending), else => { const name = pending.name orelse try it.headerName(); it.report(.{ .unsupported_entry = .{ .name = name, .typeflag = typeflag } }); if (typeflag == header.Typeflag.gnu_sparse) try it.skipSparseMaps(); // Devices and FIFOs have no content whatever their size // field says; anything else is skipped by its size. const content = if (isHeaderOnly(typeflag)) 0 else pending.size orelse header_size; try it.skip(content); try it.skip(blockPadding(content)); pending = .{}; it.used = 0; }, } } } /// Builds the entry from the header in `block` and what came before it. fn entry(it: *Iterator, typeflag: u8, header_size: u64, pending: Pending) Error!Entry { const name = pending.name orelse try it.headerName(); const kind: root.Kind = switch (typeflag) { header.Typeflag.directory => .directory, header.Typeflag.symbolic_link => .symbolic_link, // Before there was a directory typeflag, a directory was a regular // file whose name ended in a slash. header.Typeflag.regular_old => if (std.mem.endsWith(u8, name, "/")) .directory else .file, else => .file, }; const link_name = if (kind == .symbolic_link) pending.link_name orelse header.string(header.linkname.get(&it.block)) else ""; const mode = try header.parseNumber(u32, header.mode.get(&it.block)); const mtime = pending.mtime orelse try header.parseNumber(i64, header.mtime.get(&it.block)); // A directory's size field may say how much space to set aside for it, // but POSIX stores no content after it, and a symbolic link's must be // zero; both are read as having none, as Go's archive/tar does too. const size: u64 = if (kind == .file) pending.size orelse header_size else 0; it.remaining = size; it.padding = blockPadding(size); it.entry_reader.buffer = it.scratch[it.used..]; return .{ .kind = kind, .name = name, .link_name = link_name, .size = size, .mode = mode, .mtime = mtime, .reader = &it.entry_reader, }; } /// The name held in the header itself: the name field, preceded by the /// prefix field and a slash when this is a POSIX header with a prefix. fn headerName(it: *Iterator) Error![]const u8 { const name = header.string(header.name.get(&it.block)); if (header.format(&it.block) != .posix) return name; const prefix = header.string(header.prefix.get(&it.block)); if (prefix.len == 0) return name; const buf = try it.alloc(prefix.len + 1 + name.len); @memcpy(buf[0..prefix.len], prefix); buf[prefix.len] = '/'; @memcpy(buf[prefix.len + 1 ..], name); return buf; } /// Reads the content of a GNU `L` or `K` member: a name, NUL terminated. fn readLongName(it: *Iterator, size: u64) Error![]const u8 { const len = std.math.cast(usize, size) orelse return error.NameTooLong; const buf = try it.alloc(len); try it.readAll(buf); try it.skip(blockPadding(size)); return header.string(buf); } /// Reads the records of a PAX extended header into `pending`. fn readPax(it: *Iterator, size: u64, pending: *Pending) Error!void { var left = size; while (left > 0) { // The length, which counts every byte of the record including // itself and the space after it. var len: u64 = 0; var digits: u64 = 0; while (true) { if (left == 0) return error.InvalidPaxRecord; const c = try it.readByte(); left -= 1; if (c == ' ') break; if (c == 0 and digits == 0) { // Some writers pad the records out with NULs. try it.skip(left); left = 0; break; } if (c < '0' or c > '9' or digits == 19) return error.InvalidPaxRecord; len = len * 10 + (c - '0'); digits += 1; } if (digits == 0) break; // What follows the space: at least a one-byte key, "=" and "\n". if (len < digits + 1 + 3) return error.InvalidPaxRecord; const body = len - digits - 1; if (body > left) return error.InvalidPaxRecord; left -= body; const key = try it.readKey(body); const value_len = body - key.len - 2; if (std.mem.eql(u8, key, pax.key_path)) { pending.name = try it.readValue(value_len); } else if (std.mem.eql(u8, key, pax.key_linkpath)) { pending.link_name = try it.readValue(value_len); } else if (std.mem.eql(u8, key, pax.key_size)) { var buf: [32]u8 = undefined; pending.size = if (value_len == 0) null else try pax.parseSize(try it.readSmall(&buf, value_len)); } else if (std.mem.eql(u8, key, pax.key_mtime)) { var buf: [64]u8 = undefined; pending.mtime = if (value_len == 0) null else try pax.parseTime(try it.readSmall(&buf, value_len)); } else { it.report(.{ .ignored_pax_record = .{ .key = key, .value_len = value_len } }); try it.skip(value_len); } if (try it.readByte() != '\n') return error.InvalidPaxRecord; } try it.skip(blockPadding(size)); } /// Reads a PAX key and its `=` into the free part of the scratch buffer, /// without claiming it: the value that follows may be stored over it. A /// record of `body` bytes holds a key of at most `body - 2`. fn readKey(it: *Iterator, body: u64) Error![]const u8 { const free = it.scratch[it.used .. it.scratch.len - reader_reserve]; var len: usize = 0; while (true) { if (len + 2 > body) return error.InvalidPaxRecord; const c = try it.readByte(); if (c == '=') break; if (len == free.len) return error.NameTooLong; free[len] = c; len += 1; } if (len == 0) return error.InvalidPaxRecord; return free[0..len]; } /// Reads a PAX string value into the scratch buffer and keeps it. An empty /// value deletes the override rather than setting it to nothing. fn readValue(it: *Iterator, len: u64) Error!?[]const u8 { if (len == 0) return null; const n = std.math.cast(usize, len) orelse return error.NameTooLong; const buf = try it.alloc(n); try it.readAll(buf); return buf; } fn readSmall(it: *Iterator, buf: []u8, len: u64) Error![]const u8 { if (len > buf.len) return error.InvalidPaxRecord; const out = buf[0..@intCast(len)]; try it.readAll(out); return out; } /// Reads the rest of the end-of-archive marker, which is two zero blocks, /// the first of which has just been read. fn endOfArchive(it: *Iterator) Error!void { it.done = true; const n = it.reader.readSliceShort(&it.block) catch return error.ReadFailed; if (n < header.block_len or !header.isZero(&it.block)) it.report(.missing_end_of_archive); } /// Skips the extension blocks of a GNU sparse header, each of which says /// whether another follows it. fn skipSparseMaps(it: *Iterator) Error!void { var extended = it.block[header.gnu_sparse_is_extended_offset] != 0; while (extended) { try it.readAll(&it.block); extended = it.block[header.gnu_sparse_ext_is_extended_offset] != 0; } } /// Claims `len` bytes of the scratch buffer for the current entry. fn alloc(it: *Iterator, len: usize) Error![]u8 { const limit = it.scratch.len - reader_reserve; if (len > limit - it.used) return error.NameTooLong; defer it.used += len; return it.scratch[it.used..][0..len]; } fn readAll(it: *Iterator, buf: []u8) Error!void { it.reader.readSliceAll(buf) catch |err| return switch (err) { error.EndOfStream => error.TruncatedArchive, error.ReadFailed => error.ReadFailed, }; } fn readByte(it: *Iterator) Error!u8 { var b: [1]u8 = undefined; try it.readAll(&b); return b[0]; } fn skip(it: *Iterator, n: u64) Error!void { it.reader.discardAll64(n) catch |err| return switch (err) { error.EndOfStream => error.TruncatedArchive, error.ReadFailed => error.ReadFailed, }; } fn report(it: *Iterator, diagnostic: root.Diagnostic) void { it.diagnostics.report(it.diagnostics.context, diagnostic); } /// The zero bytes that round `size` up to a whole number of blocks. fn blockPadding(size: u64) usize { return @intCast((header.block_len - size % header.block_len) % header.block_len); } /// Whether a member of this type has no content, whatever its size field /// says: POSIX stores none for a symbolic link, a device, a FIFO or a /// directory. A hard link is not on the list. A ustar one must have a size /// of zero, but a pax one may carry the file's content (`pax -o linkdata`), /// and then its size is the only way past it. fn isHeaderOnly(typeflag: u8) bool { return switch (typeflag) { '2', '3', '4', '5', '6' => true, else => false, }; } fn stream(r: *Io.Reader, w: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize { const it: *Iterator = @fieldParentPtr("entry_reader", r); if (it.remaining == 0) return error.EndOfStream; const n = it.reader.stream(w, limit.min(.limited64(it.remaining))) catch |err| switch (err) { error.EndOfStream => return it.truncated(), else => |e| return e, }; it.remaining -= n; return n; } fn discard(r: *Io.Reader, limit: Io.Limit) Io.Reader.Error!usize { const it: *Iterator = @fieldParentPtr("entry_reader", r); if (it.remaining == 0) return error.EndOfStream; const n = it.reader.discard(limit.min(.limited64(it.remaining))) catch |err| switch (err) { error.EndOfStream => return it.truncated(), error.ReadFailed => return error.ReadFailed, }; it.remaining -= n; return n; } fn truncated(it: *Iterator) error{ReadFailed} { it.err = error.TruncatedArchive; return error.ReadFailed; }