Something went wrong. Try again.
FTP for Zig 0.16: a client, a server, and the wire protocol as a layer you can use on its own, all built on std.Io.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the parsers must do with input nobody wrote.//!//! Everything here is a property rather than an example: not "this reply//! parses to that" — the unit tests have those — but "whatever arrives, the//! parser terminates, stays inside its buffers, and if it claims to have//! understood the input then writing it back out and reading it again gives//! the same answer". Round-tripping is what catches a parser and a writer that//! have drifted apart, which is the failure a test written against a fixed//! example cannot see.//!//! `path.resolve` gets the strongest property, because it is a security//! boundary rather than a convenience: no input may produce a path that leaves//! the root, and the answer must be a fixed point, or a backend that resolves//! twice gets a different tree the second time.//!//! 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 on input that has already been interesting once.//!//! With `--fuzz` they are Zig's coverage-guided fuzzer's targets://! `zig build fuzz --fuzz`. That needs the test binary compiled by LLVM,//! which `build.zig` arranges, because the self-hosted backend emits no//! coverage instrumentation.
const builtin = @import("builtin");const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const testing = std.testing;const Smith = std.testing.Smith;
const ftp = @import("ftp");const protocol = ftp.protocol;
/// The allocator the targets run against.////// Under `zig build test` that is the testing allocator, which reports a leak/// as a failure. `tools/fuzz.zig` cannot name it -- it is not a test build --/// so it sets this to a checked allocator of its own instead.pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined;
// -- replies ---------------------------------------------------------------
const reply_seeds = [_][]const u8{ "220 ready\r\n", "220\r\n", "211-Features:\r\n MDTM\r\n SIZE\r\n211 End\r\n", "211-Status:\r\n500 was the last error\r\n211 End\r\n", "211-a\r\n 211 padded\r\n211 End\r\n", "257 \"/pub\" is the current directory\r\n", "227 Entering Passive Mode (127,0,0,1,16,45).\r\n", "229 Entering Extended Passive Mode (|||6446|)\r\n", // Not replies at all. "", "\r\n", "<!DOCTYPE html>\r\n", "999-\r\n999 \r\n",};
/// Whatever arrives, `receive` either fails or produces a reply that survives/// being written back out and read again.fn replyProperty(input: []const u8) !void { var reader: Io.Reader = .fixed(input); var buffer: std.ArrayList(u8) = .empty; defer buffer.deinit(backing);
const reply = protocol.Reply.receive(&reader, backing, &buffer, .{}) catch return;
var written: std.ArrayList(u8) = .empty; defer written.deinit(backing); var w: Io.Writer.Allocating = .fromArrayList(backing, &written); defer written = w.toArrayList(); protocol.Reply.write(&w.writer, reply.code, reply.text) catch return error.OutOfMemory;
var again_reader: Io.Reader = .fixed(w.written()); var again_buffer: std.ArrayList(u8) = .empty; defer again_buffer.deinit(backing); const again = try protocol.Reply.receive(&again_reader, backing, &again_buffer, .{});
try testing.expectEqual(reply.code.value, again.code.value); try testing.expectEqualStrings(reply.text, again.text);}
test "fuzz replies" { for (reply_seeds) |seed| try replyProperty(seed); try testing.fuzz({}, fuzzReply, .{});}
fn fuzzReply(_: void, smith: *testing.Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try replyProperty(buffer[0..len]);}
// -- commands --------------------------------------------------------------
const command_seeds = [_][]const u8{ "USER anonymous", "PWD", "CWD ", "RETR two spaces ", "XYZZY plugh", "\xff\xf4\xff\xf2ABOR", "\xff\xfb\x01NOOP", "RETR a\xff\xffb", "", " RETR x", "RE-TR x", "TYPE A N", "EPRT |1|192.0.2.1|4141|",};
/// A command that parses must survive being written back out, except where/// the argument holds a byte that cannot be written at all.fn commandProperty(input: []const u8) !void { var line: [1024]u8 = undefined; if (input.len > line.len) return; @memcpy(line[0..input.len], input); const stripped = protocol.Command.stripTelnet(line[0..input.len]); // Stripping only ever removes bytes, and never invents one. try testing.expect(stripped.len <= input.len);
const cmd = protocol.Command.parse(stripped) catch return; try testing.expect(cmd.name.len > 0);
var out: [2048]u8 = undefined; var w: Io.Writer = .fixed(&out); protocol.Command.writeName(&w, cmd.name, cmd.arg) catch |err| switch (err) { // An argument holding CR, LF or NUL is refused rather than written, // which is the point: it could not be read back as one command. error.InvalidArgument => return, error.WriteFailed => return, };
var reader: Io.Reader = .fixed(w.buffered()); const again = try protocol.Command.receive(&reader); try testing.expectEqualStrings(cmd.name, again.name); try testing.expectEqual(cmd.verb, again.verb); if (cmd.arg) |arg| { try testing.expectEqualStrings(arg, again.arg.?); } else { try testing.expectEqual(@as(?[]const u8, null), again.arg); }}
test "fuzz commands" { for (command_seeds) |seed| try commandProperty(seed); try testing.fuzz({}, fuzzCommand, .{});}
fn fuzzCommand(_: void, smith: *testing.Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try commandProperty(buffer[0..len]);}
// -- pathnames -------------------------------------------------------------
const path_seeds = [_][]const u8{ "/pub", "..", "../../../../etc/shadow", "/../..", "./././.", "//////", "a/b/c/../../..", "", "/", ".", "...", "/a/../../b",};
/// The security property, and the only one in this library that a mistake/// would make dangerous rather than merely wrong.fn pathProperty(raw_cwd: []const u8, arg: []const u8) !void { const path = protocol.path; var cwd_buffer: [path.max_len]u8 = undefined; // A working directory is itself always the output of a resolve, so the // property is stated over the reachable ones rather than over any string. const cwd = path.resolve(&cwd_buffer, path.root, raw_cwd) catch return;
var buffer: [path.max_len]u8 = undefined; const resolved = path.resolve(&buffer, cwd, arg) catch return;
// Absolute, always. try testing.expect(resolved.len > 0); try testing.expect(resolved[0] == '/'); // Nothing that could climb out of the root survives. The root itself has // no components at all -- it is a bare separator -- so it is exempt. var components = std.mem.splitScalar(u8, resolved, '/'); _ = components.first(); while (if (path.isRoot(resolved)) null else components.next()) |component| { try testing.expect(component.len > 0); try testing.expect(!std.mem.eql(u8, component, ".")); try testing.expect(!std.mem.eql(u8, component, "..")); } // No trailing slash except on the root itself. if (!path.isRoot(resolved)) try testing.expect(resolved[resolved.len - 1] != '/');
// A fixed point: resolving the answer again must not move it, or a // backend that normalises a second time sees a different path. var again_buffer: [path.max_len]u8 = undefined; const again = try path.resolve(&again_buffer, path.root, resolved); try testing.expectEqualStrings(resolved, again);
// And the parent of anything is reachable from it, which is what `CDUP` // relies on. var parent_buffer: [path.max_len]u8 = undefined; const parent = try path.resolve(&parent_buffer, resolved, ".."); try testing.expectEqualStrings(path.parent(resolved), parent);}
test "fuzz pathnames" { for (path_seeds) |seed| { for (path_seeds) |cwd| try pathProperty(cwd, seed); } try testing.fuzz({}, fuzzPath, .{});}
fn fuzzPath(_: void, smith: *testing.Smith) !void { var cwd: [256]u8 = undefined; const cwd_len = smith.slice(&cwd); var arg: [512]u8 = undefined; const arg_len = smith.slice(&arg); try pathProperty(cwd[0..cwd_len], arg[0..arg_len]);}
/// The quoting of a 257 reply must be reversible for every possible name,/// since a name is an opaque sequence of bytes and the quote character is one/// of them.fn quoteProperty(name: []const u8) !void { const path = protocol.path; var out: [2048]u8 = undefined; var w: Io.Writer = .fixed(&out); path.writeQuoted(&w, name) catch return;
var back: [2048]u8 = undefined; try testing.expectEqualStrings(name, try path.unquote(&back, w.buffered()));}
const quote_seeds = [_][]const u8{ "", "/", "\"", "\"\"", "a\"b", "with space", "\x00\xff",};
test "fuzz pathname quoting" { for (quote_seeds) |seed| try quoteProperty(seed); try testing.fuzz({}, fuzzQuote, .{});}
fn fuzzQuote(_: void, smith: *testing.Smith) !void { var buffer: [512]u8 = undefined; const len = smith.slice(&buffer); try quoteProperty(buffer[0..len]);}
// -- listings --------------------------------------------------------------
const listing_seeds = [_][]const u8{ "-rw-r--r-- 1 0 0 2048 Jan 02 2024 welcome.msg", "drwxr-xr-x 2 ftp ftp 4096 Jun 15 16:32 pub", "lrwxrwxrwx 1 root root 11 Jan 02 2024 passwd -> /etc/passwd", "total 12", "02-11-25 03:05PM <DIR> folder", "02-11-25 03:05AM 1,234 file.txt", "type=file;size=1234;modify=20250615150640;perm=r; readme.txt", "type=cdir; .", "modify=20240102030405;perm=adfr;size=2048;type=file;UNIX.mode=0644; welcome.msg", "; x", "", "-", "----------",};
/// A listing line either fails to parse or yields a name; nothing in between,/// and nothing that reads past the line it was given.fn listingProperty(line: []const u8) !void { const listing = protocol.listing; if (listing.parseMachineEntry(line)) |entry| { try testing.expect(entry.name.len > 0); // The name is a slice of the line it came from. try testing.expect(@intFromPtr(entry.name.ptr) >= @intFromPtr(line.ptr)); try testing.expect(@intFromPtr(entry.name.ptr) + entry.name.len <= @intFromPtr(line.ptr) + line.len);
// Whatever was understood must survive being written back out. var out: [4096]u8 = undefined; var w: Io.Writer = .fixed(&out); if (listing.writeMachineEntry(&w, entry)) |_| { const again = try listing.parseMachineEntry(w.buffered()); try testing.expectEqualStrings(entry.name, again.name); try testing.expectEqual(entry.kind, again.kind); try testing.expectEqual(entry.size, again.size); try testing.expectEqual(entry.modified, again.modified); try testing.expectEqual(entry.permissions, again.permissions); } else |_| {} } else |_| {}
if (listing.parseEntry(line, .{ .now = 1750_000_000 })) |entry| { try testing.expect(entry.name.len > 0); } else |_| {}}
test "fuzz listings" { for (listing_seeds) |seed| try listingProperty(seed); try testing.fuzz({}, fuzzListing, .{});}
fn fuzzListing(_: void, smith: *testing.Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try listingProperty(buffer[0..len]);}
// -- data connection addresses ---------------------------------------------
const address_seeds = [_][]const u8{ "192,0,2,1,16,45", "1,2,3,4,5", "1,2,3,4,5,256", "|1|192.0.2.1|4141|", "|2|2001:db8::1|4141|", "!1!192.0.2.1!4141!", "|3|x|0|", "Entering Passive Mode (127,0,0,1,16,45).", "Entering Extended Passive Mode (|||6446|)", "", "|", "(",};
fn addressProperty(text: []const u8) !void { const address = protocol.address;
if (address.parseHostPort(text)) |parsed| { var out: [64]u8 = undefined; var w: Io.Writer = .fixed(&out); try address.writeHostPort(&w, parsed); const again = try address.parseHostPort(w.buffered()); try testing.expectEqual(parsed.bytes, again.bytes); try testing.expectEqual(parsed.port, again.port); } else |_| {}
if (address.parseExtendedHostPort(text)) |parsed| { var out: [128]u8 = undefined; var w: Io.Writer = .fixed(&out); try address.writeExtendedHostPort(&w, parsed); const again = try address.parseExtendedHostPort(w.buffered()); try testing.expect(again.eql(&parsed)); } else |_| {}
// These read a whole reply rather than a bare field, and must not run off // the end of one that holds no address at all. _ = address.parsePassiveReply(text) catch {}; _ = address.parseExtendedPassiveReply(text) catch {};}
test "fuzz addresses" { for (address_seeds) |seed| try addressProperty(seed); try testing.fuzz({}, fuzzAddress, .{});}
fn fuzzAddress(_: void, smith: *testing.Smith) !void { var buffer: [256]u8 = undefined; const len = smith.slice(&buffer); try addressProperty(buffer[0..len]);}
// -- timestamps ------------------------------------------------------------
/// A timestamp that parses must print back as itself, and a `DateTime` must/// survive the trip through seconds and back.fn timeProperty(text: []const u8, seconds: i64) !void { const time = protocol.time;
if (time.parseTimeval(text)) |parsed| { var out: [32]u8 = undefined; var w: Io.Writer = .fixed(&out); try time.writeTimeval(&w, parsed); try testing.expectEqual(parsed, try time.parseTimeval(w.buffered())); } else |_| {}
// Years outside four digits cannot be written, so the round trip is // stated over the range the format can hold. const dt: time.DateTime = .fromUnixSeconds(seconds); if (dt.year >= 1 and dt.year <= 9999) { try testing.expect(dt.isValid()); try testing.expectEqual(seconds, dt.toUnixSeconds()); var out: [32]u8 = undefined; var w: Io.Writer = .fixed(&out); try time.writeTimeval(&w, seconds); try testing.expectEqual(seconds, try time.parseTimeval(w.buffered())); }}
const time_seeds = [_][]const u8{ "20250615150640", "20250615150640.500", "19000229000000", "20000229000000", "2025061515064", "abcdefghijklmn", "",};
test "fuzz timestamps" { for (time_seeds) |seed| try timeProperty(seed, 0); for ([_]i64{ 0, -1, 1750_000_000, -2208988800, 253402300799, 1 << 40 }) |seconds| { try timeProperty("", seconds); } try testing.fuzz({}, fuzzTime, .{});}
fn fuzzTime(_: void, smith: *testing.Smith) !void { var buffer: [32]u8 = undefined; const len = smith.slice(&buffer); try timeProperty(buffer[0..len], smith.value(i64));}
// -- the ASCII representation type -----------------------------------------
/// Text with no CR in it survives the trip to the wire and back exactly.////// The other direction is not a round trip and must not be tested as one:/// decoding turns CRLF into LF, and encoding turns it back, so a file that/// already held CRLF comes back with the same bytes but one that held a lone/// CR before a LF does not — which is the conversion doing its job.fn asciiProperty(input: []const u8) !void { const transfer = protocol.transfer; for (input) |byte| if (byte == '\r') return;
var encoded: [8192]u8 = undefined; var ew: Io.Writer = .fixed(&encoded); var source: Io.Reader = .fixed(input); const written = transfer.encodeAscii(&source, &ew) catch return; try testing.expectEqual(written, ew.buffered().len);
// Every line ending on the wire is a full CRLF, and no LF stands alone. var i: usize = 0; while (std.mem.findScalarPos(u8, ew.buffered(), i, '\n')) |lf| : (i = lf + 1) { try testing.expect(lf > 0 and ew.buffered()[lf - 1] == '\r'); }
var decoded: [8192]u8 = undefined; var dw: Io.Writer = .fixed(&decoded); var wire: Io.Reader = .fixed(ew.buffered()); _ = transfer.decodeAscii(&wire, &dw) catch return; try testing.expectEqualStrings(input, dw.buffered());}
const ascii_seeds = [_][]const u8{ "", "\n", "\n\n\n", "one\ntwo\n", "no newline", "\x00\x01\x02",};
test "fuzz the ASCII conversion" { for (ascii_seeds) |seed| try asciiProperty(seed); try testing.fuzz({}, fuzzAscii, .{});}
fn fuzzAscii(_: void, smith: *testing.Smith) !void { var buffer: [2048]u8 = undefined; const len = smith.slice(&buffer); try asciiProperty(buffer[0..len]);}
// -- feature lists ---------------------------------------------------------
fn featureProperty(text: []const u8) !void { const parsed: protocol.Features = .parse(text); var out: [4096]u8 = undefined; var w: Io.Writer = .fixed(&out); parsed.write(&w) catch return;
const again: protocol.Features = .parse(w.buffered()); try testing.expectEqualStrings(parsed.mlst_facts, again.mlst_facts); var normalised = again; normalised.mlst_facts = parsed.mlst_facts; try testing.expectEqual(parsed, normalised);}
const feature_seeds = [_][]const u8{ "Features:\n MDTM\n SIZE\n MLST type*;size*;\n REST STREAM\nEnd", "Features:\n AUTH TLS\n PBSZ\n PROT\nEnd", "Features:\nEnd", "", " REST",};
test "fuzz feature lists" { for (feature_seeds) |seed| try featureProperty(seed); try testing.fuzz({}, fuzzFeatures, .{});}
fn fuzzFeatures(_: void, smith: *testing.Smith) !void { var buffer: [1024]u8 = undefined; const len = smith.slice(&buffer); try featureProperty(buffer[0..len]);}
// -- whole conversations ----------------------------------------------------
const session_seeds = [_][]const u8{ "USER anonymous\r\nPASS x@y.z\r\nSYST\r\nPWD\r\nFEAT\r\nQUIT\r\n", "USER a\r\nPASS b\r\nCWD /pub\r\nLIST\r\nMLSD\r\nNLST\r\n", "USER a\r\nPASS b\r\nEPSV\r\nRETR x\r\nPASV\r\nSTOR y\r\n", "USER a\r\nPASS b\r\nTYPE A\r\nTYPE I\r\nSTRU F\r\nMODE S\r\nREST 5\r\n", "USER a\r\nPASS b\r\nMKD d\r\nRNFR d\r\nRNTO e\r\nRMD e\r\nDELE f\r\n", "USER a\r\nPASS b\r\nSTAT /\r\nHELP\r\nMLST /\r\nSIZE f\r\nMDTM f\r\n", "USER a\r\nPASS b\r\nEPRT |1|127.0.0.1|9999|\r\nPORT 127,0,0,1,39,15\r\n", "USER a\r\nPASS b\r\nOPTS UTF8 ON\r\nOPTS MLST type;size;\r\nEPSV ALL\r\n", "\xff\xf4\xff\xf2ABOR\r\nNOOP\r\nXYZZY\r\n", "",};
/// A whole server session, driven by whatever bytes arrive.////// The parser targets above check one line at a time; this checks the state/// machine around them — that no sequence of commands, in any order, with any/// arguments, makes the session crash, leak, or say something that is not a/// reply.////// It runs on `std.Io.failing`, so nothing here opens a socket: `PASV` and/// `EPSV` get `error.NetworkDown` from it and answer 425, which is a path/// worth covering anyway. The file system is the empty one, so every path is/// refused at the storage layer and the interesting part — dispatch, argument/// handling, path resolution, reply framing — is what runs.fn sessionProperty(input: []const u8) !void { const Session = ftp.server.Session;
// A copy, because `Command.receive` strips TELNET sequences in place in // the reader's buffer. A socket's buffer is always writable; a seed is a // string literal, which LLVM puts in read-only memory. const writable = try backing.dupe(u8, input); defer backing.free(writable); var commands: Io.Reader = .fixed(writable); var out: Io.Writer.Allocating = .init(backing); defer out.deinit();
const config: Session.Config = .{ .filesystem = .empty, // Anyone may log in, so that the commands behind a login are reached // at all rather than every one of them answering 530. .auth = .open, .greeting = "fuzz", }; var session: Session = .init(std.Io.failing, backing, &config, &commands, &out.writer, .{ .peer = .{ .ip4 = .loopback(1234) }, .local = .{ .ip4 = .loopback(21) }, }); defer session.deinit();
// Any error is a legitimate way for a session to end. A panic is not, and // neither is a leak; the driver checks for both. session.run() catch {};
// Everything it said has to be a reply, and there must be nothing left // over at the end. This is the property that would catch a pathname // smuggling a CRLF into the control connection: a name that ended one // reply early would leave the rest of the line as a line that does not // parse. var written: Io.Reader = .fixed(out.written()); var text: std.ArrayList(u8) = .empty; defer text.deinit(backing); var replies: usize = 0; while (true) { const reply = protocol.Reply.receive(&written, backing, &text, .{}) catch |err| switch (err) { error.EndOfStream => break, else => return err, }; try testing.expect(reply.code.isValid()); replies += 1; } try testing.expectEqual(@as(usize, 0), written.bufferedLen()); // The greeting, at least, whatever the input was. try testing.expect(replies >= 1);}
fn fuzzSession(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try sessionProperty(buffer[0..len]);}
test "fuzz a whole session" { for (session_seeds) |seed| try sessionProperty(seed); try testing.fuzz({}, fuzzSession, .{});}
const client_seeds = [_][]const u8{ "220 ready\r\n230 in\r\n215 UNIX Type: L8\r\n257 \"/\" is it\r\n", "220 ready\r\n331 pw\r\n230 in\r\n211-Features:\r\n MLST a;b;\r\n SIZE\r\n211 End\r\n", "220 r\r\n230 i\r\n213 12345\r\n213 20250615150640\r\n", "220 r\r\n230 i\r\n250-Listing /x\r\n type=file;size=1; /x\r\n250 End\r\n", "220 r\r\n530 no\r\n", "421 go away\r\n", "",};
/// A whole client conversation, driven by whatever a server sends back.////// The mirror of `sessionProperty`: every call here reads a reply and parses/// something out of its text — a quoted path, an integer, a timestamp, a set/// of facts, a feature list — and none of them may crash or leak whatever/// arrives. Only the commands that answer on the control connection are used,/// since `std.Io.failing` cannot open a data connection.fn clientProperty(input: []const u8) !void { var replies: Io.Reader = .fixed(input); var sent: [4096]u8 = undefined; var out: Io.Writer = .fixed(&sent);
var client: ftp.Client = .init(std.Io.failing, backing, &replies, &out, .{ .server = .{ .ip4 = .loopback(21) }, .local = .{ .ip4 = .loopback(0) }, }, .{}); defer client.deinit();
var buffer: [1024]u8 = undefined; _ = client.readGreeting() catch {}; client.login("anonymous", "nobody@example.com", null) catch {}; _ = client.readFeatures() catch {}; _ = client.workingDirectory(&buffer) catch {}; _ = client.systemType(&buffer) catch {}; _ = client.makeDirectory("/d", &buffer) catch {}; _ = client.size("f") catch {}; _ = client.modificationTime("f") catch {}; _ = client.statPath("f", &buffer) catch {}; client.changeDirectory("/") catch {}; client.rename("a", "b") catch {}; client.quit() catch {};}
fn fuzzClient(_: void, smith: *Smith) !void { var buffer: [4096]u8 = undefined; const len = smith.slice(&buffer); try clientProperty(buffer[0..len]);}
test "fuzz a whole client conversation" { for (client_seeds) |seed| try clientProperty(seed); try testing.fuzz({}, fuzzClient, .{});}
// -- the same targets, for a driver that is not the test runner -------------
/// One fuzz target, addressable by name.////// `zig build test` reaches these through the `test` blocks above and Zig's/// own fuzzer reaches them through `std.testing.fuzz`. This is the third way/// in, for `tools/fuzz.zig`: a bounded, reproducible run with a watchdog and/// a leak check after every input, which is what CI wants and the/// coverage-guided fuzzer is not.pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating: the same seeds the tests above run, 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 most of the time. The /// timestamp target's buffer is 32 bytes, and until this field existed it /// was being fuzzed with the empty string. 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 = "replies", .run = Driven(fuzzReply).run, .corpus = &reply_seeds, .content_max = 1024 }, .{ .name = "commands", .run = Driven(fuzzCommand).run, .corpus = &command_seeds, .content_max = 512 }, // The smaller of this target's two buffers, so that both slices are fed. .{ .name = "paths", .run = Driven(fuzzPath).run, .corpus = &path_seeds, .content_max = 256 }, .{ .name = "quoting", .run = Driven(fuzzQuote).run, .corpus = "e_seeds, .content_max = 512 }, .{ .name = "listings", .run = Driven(fuzzListing).run, .corpus = &listing_seeds, .content_max = 1024 }, .{ .name = "addresses", .run = Driven(fuzzAddress).run, .corpus = &address_seeds, .content_max = 256 }, .{ .name = "timestamps", .run = Driven(fuzzTime).run, .corpus = &time_seeds, .content_max = 32 }, .{ .name = "ascii", .run = Driven(fuzzAscii).run, .corpus = &ascii_seeds, .content_max = 2048 }, .{ .name = "features", .run = Driven(fuzzFeatures).run, .corpus = &feature_seeds, .content_max = 1024 }, .{ .name = "session", .run = Driven(fuzzSession).run, .corpus = &session_seeds, .content_max = 4096 }, .{ .name = "client", .run = Driven(fuzzClient).run, .corpus = &client_seeds, .content_max = 4096 },};