// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the iterator and the writer must do with input nobody wrote. //! //! These are properties rather than examples: //! //! * `archives`: whatever bytes arrive, the iterator terminates, stays //! inside its buffers, and every entry's reader produces exactly the size //! the entry claims or fails with the iterator's `err` saying the archive //! was truncated. A short read that looks like a whole file is the bug //! this is looking for. //! * `resummed`: the same, but with the checksum of every block that looks //! like a header recomputed first. A mutated header nearly always fails //! its checksum, which is right, and stops the fuzzer getting any further; //! fixing the sums is what lets it reach the numeric fields, the PAX //! parser and the long names. //! * `round_trip`: members made up from the input are written and read //! back, and must come back exactly as they went in, or be refused by the //! writer with a reason. //! //! Each target is an ordinary test as well as a fuzz target: without //! `--fuzz` it runs the seeds beside it, so `zig build test` exercises the //! same properties. Zig 0.16.0 cannot usefully run its own fuzzer on them //! (the flake says why), so `tools/fuzz.zig` drives them instead. const std = @import("std"); const Io = std.Io; const testing = std.testing; const Smith = std.testing.Smith; const tar = @import("tar"); const block_len = 512; // -- archives ---------------------------------------------------------------- const archive_seeds = [_][]const u8{ @embedFile("data/gnu-gnu.tar"), @embedFile("data/gnu-posix.tar"), @embedFile("data/gnu-ustar.tar"), @embedFile("data/gnu-v7.tar"), @embedFile("data/bsd-pax.tar"), @embedFile("data/bsd-ustar.tar"), @embedFile("data/bsd-gnutar.tar"), "", &@as([1024]u8, @splat(0)), }; const archive_max = 24 * 1024; /// How an entry's content is read, chosen per entry, so that every way of /// leaving the entry reader behind gets exercised. const Strategy = enum { stream, bytes, partial, skip }; /// Reads the whole archive, checking what the entry readers produce against /// what the entries claim. fn archiveProperty(input: []const u8, smith: ?*Smith) !void { // The smallest scratch there is, which leaves the entry reader the // smallest buffer there is and makes long names hit the limit. var scratch: [tar.Iterator.min_scratch_len]u8 = undefined; var r: Io.Reader = .fixed(input); var it = tar.iterator(&r, .ignore, &scratch); var entries: usize = 0; while (true) { const e = (it.next() catch return) orelse break; entries += 1; // Every entry is at least a header, so there cannot be more of them // than there are blocks. try testing.expect(entries <= input.len / block_len); if (e.kind != .file) try testing.expectEqual(0, e.size); if (e.kind != .symbolic_link) try testing.expectEqual(0, e.link_name.len); const strategy: Strategy = if (smith) |s| @enumFromInt(s.value(u64) % 4) else .stream; const got: u64 = switch (strategy) { .stream => n: { var sink: Io.Writer.Discarding = .init(&.{}); break :n e.reader.streamRemaining(&sink.writer) catch { try testing.expectEqual(error.TruncatedArchive, it.err.?); return; }; }, .bytes => n: { var n: u64 = 0; while (true) : (n += 1) { _ = e.reader.takeByte() catch |err| switch (err) { error.EndOfStream => break, error.ReadFailed => { try testing.expectEqual(error.TruncatedArchive, it.err.?); return; }, }; } break :n n; }, .partial => { _ = e.reader.take(@min(e.size, 7)) catch {}; continue; }, .skip => continue, }; try testing.expectEqual(e.size, got); } // Once finished, finished. try testing.expectEqual(null, try it.next()); } test "fuzz archives" { for (archive_seeds) |seed| try archiveProperty(seed, null); try testing.fuzz({}, fuzzArchive, .{}); } fn fuzzArchive(_: void, smith: *Smith) !void { var buffer: [archive_max]u8 = undefined; const len = smith.slice(&buffer); try archiveProperty(buffer[0..len], smith); } // -- resummed ---------------------------------------------------------------- /// Recomputes the checksum of every block with a `ustar` magic in it, as if /// whoever made the damage had been careful to leave the sums right. fn resum(archive: []u8) void { var i: usize = 0; while (i + block_len <= archive.len) : (i += block_len) { const block = archive[i..][0..block_len]; if (!std.mem.eql(u8, block[257..262], "ustar")) continue; @memset(block[148..156], ' '); var sum: u64 = 0; for (block) |b| sum += b; _ = std.fmt.bufPrint(block[148..155], "{o:0>6}\x00", .{sum}) catch unreachable; } } test "fuzz resummed" { for (archive_seeds) |seed| { var buffer: [archive_max]u8 = undefined; @memcpy(buffer[0..seed.len], seed); resum(buffer[0..seed.len]); try archiveProperty(buffer[0..seed.len], null); } try testing.fuzz({}, fuzzResummed, .{}); } fn fuzzResummed(_: void, smith: *Smith) !void { var buffer: [archive_max]u8 = undefined; const len = smith.slice(&buffer); resum(buffer[0..len]); try archiveProperty(buffer[0..len], smith); } // -- round trip -------------------------------------------------------------- /// Members for the round trip, encoded as `decodeMembers` reads them. const member_seeds = [_][]const u8{ "\x00\x05\x00hello\x03\x00abc\x00\x00\x00\x00\x00\x00\x00\x00", "\x01\x04\x00dir/\x00\x00\xff\xff\xff\xff\xff\xff\xff\xff", "\x02\x04\x00link\x03\x00tgt\x00\x00\x00\x00\x00\x00\x00\x80", "\x00\x2c\x01" ++ "n" ** 300 ++ "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10", "\x00\xf0\x00" ++ "d" ** 130 ++ "/" ++ "f" ** 109 ++ "\x01\x00x\x00\x00\x00\x00\x00\x00\x00\x00", }; const Member = struct { kind: tar.Kind, name: []const u8, /// The content of a file, or the target of a symbolic link. data: []const u8, mtime: i64, }; /// Splits the input into members: a kind byte, a little-endian `u16` name /// length and the name, the same again for the data, and eight bytes of /// modification time. Whatever does not fit is ignored. fn decodeMembers(input: []const u8, out: []Member) []Member { var n: usize = 0; var rest = input; while (n < out.len) { if (rest.len < 3) break; const kind: tar.Kind = @enumFromInt(rest[0] % 3); const name_len = std.mem.readInt(u16, rest[1..3], .little); rest = rest[3..]; if (rest.len < name_len) break; const name = rest[0..name_len]; rest = rest[name_len..]; if (rest.len < 2) break; const data_len = std.mem.readInt(u16, rest[0..2], .little); rest = rest[2..]; if (rest.len < data_len) break; const data = rest[0..data_len]; rest = rest[data_len..]; if (rest.len < 8) break; const mtime = std.mem.readInt(i64, rest[0..8], .little); rest = rest[8..]; out[n] = .{ .kind = kind, .name = name, .data = if (kind == .directory) "" else data, .mtime = mtime }; n += 1; } return out[0..n]; } fn roundTripProperty(input: []const u8) !void { var members_buf: [16]Member = undefined; const members = decodeMembers(input, &members_buf); var archive: [64 * 1024]u8 = undefined; var out: Io.Writer = .fixed(&archive); var scratch: [2048]u8 = undefined; var w: tar.Writer = .init(&out, &scratch); var written: [16]Member = undefined; var count: usize = 0; for (members) |m| { var r: Io.Reader = .fixed(m.data); const before = out.end; w.add(m.name, &r, .{ .kind = m.kind, .size = if (m.kind == .file) m.data.len else 0, .link_name = if (m.kind == .symbolic_link) m.data else "", .mtime = m.mtime, }) catch |err| switch (err) { // Refused, for a reason the member itself gives. error.InvalidName, error.InvalidOptions, error.ScratchTooSmall => { // And nothing was written for it. try testing.expectEqual(before, out.end); continue; }, // The archive is bigger than the buffer; test what there is. error.WriteFailed => return, else => |e| return e, }; written[count] = m; count += 1; } w.finish() catch return; var read_scratch: [8192]u8 = undefined; var r: Io.Reader = .fixed(out.buffered()); var it = tar.iterator(&r, .ignore, &read_scratch); for (written[0..count]) |m| { const e = (try it.next()).?; try testing.expectEqual(m.kind, e.kind); try testing.expectEqualStrings(m.name, e.name); try testing.expectEqual(m.mtime, e.mtime); switch (m.kind) { .file => { try testing.expectEqual(m.data.len, e.size); var content: [65536]u8 = undefined; var sink: Io.Writer = .fixed(&content); const n = try e.reader.streamRemaining(&sink); try testing.expectEqualStrings(m.data, content[0..n]); }, .symbolic_link => try testing.expectEqualStrings(m.data, e.link_name), .directory => {}, } } try testing.expectEqual(null, try it.next()); } test "fuzz round trip" { for (member_seeds) |seed| try roundTripProperty(seed); try testing.fuzz({}, fuzzRoundTrip, .{}); } fn fuzzRoundTrip(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try roundTripProperty(buffer[0..len]); } // -- the table tools/fuzz.zig drives ----------------------------------------- pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating, which are what stands in for the coverage /// feedback a real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. /// /// `Smith.slice` yields an *empty* slice for a length larger than the /// buffer rather than a truncated one, so a generator that does not know /// this number hands the target nothing at all. content_max: usize, }; /// Wraps one of the `fuzz*` functions above so that it takes raw bytes. fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } }; } pub const all = [_]Target{ .{ .name = "archives", .run = Driven(fuzzArchive).run, .corpus = &archive_seeds, .content_max = archive_max }, .{ .name = "resummed", .run = Driven(fuzzResummed).run, .corpus = &archive_seeds, .content_max = archive_max }, .{ .name = "round_trip", .run = Driven(fuzzRoundTrip).run, .corpus = &member_seeds, .content_max = 4096 }, };